[Python-checkins] r69450 - in python/branches/io-c: Demo/tkinter/README Demo/tkinter/ttk Doc/c-api/allocation.rst Doc/c-api/arg.rst Doc/c-api/bool.rst Doc/c-api/buffer.rst Doc/c-api/bytearray.rst Doc/c-api/bytes.rst Doc/c-api/cell.rst Doc/c-api/cobject.rst Doc/c-api/complex.rst Doc/c-api/conversion.rst Doc/c-api/datetime.rst Doc/c-api/descriptor.rst Doc/c-api/dict.rst Doc/c-api/exceptions.rst Doc/c-api/file.rst Doc/c-api/float.rst Doc/c-api/function.rst Doc/c-api/gcsupport.rst Doc/c-api/gen.rst Doc/c-api/import.rst Doc/c-api/init.rst Doc/c-api/iter.rst Doc/c-api/iterator.rst Doc/c-api/list.rst Doc/c-api/long.rst Doc/c-api/mapping.rst Doc/c-api/marshal.rst Doc/c-api/method.rst Doc/c-api/module.rst Doc/c-api/none.rst Doc/c-api/number.rst Doc/c-api/objbuffer.rst Doc/c-api/object.rst Doc/c-api/objimpl.rst Doc/c-api/reflection.rst Doc/c-api/sequence.rst Doc/c-api/set.rst Doc/c-api/slice.rst Doc/c-api/structures.rst Doc/c-api/sys.rst Doc/c-api/tuple.rst Doc/c-api/type.rst Doc/c-api/typeobj.rst Doc/c-api/unicode.rst Doc/c-api/weakref.rst Doc/documenting/markup.rst Doc/extending/newtypes.rst Doc/glossary.rst Doc/includes/noddy.c Doc/includes/noddy2.c Doc/includes/noddy3.c Doc/includes/noddy4.c Doc/includes/shoddy.c Doc/includes/sqlite3/collation_reverse.py Doc/includes/typestruct.h Doc/library/ast.rst Doc/library/binascii.rst Doc/library/collections.rst Doc/library/copyreg.rst Doc/library/ctypes.rst Doc/library/datetime.rst Doc/library/fractions.rst Doc/library/functions.rst Doc/library/html.entities.rst Doc/library/importlib.rst Doc/library/io.rst Doc/library/itertools.rst Doc/library/json.rst Doc/library/locale.rst Doc/library/multiprocessing.rst Doc/library/operator.rst Doc/library/optparse.rst Doc/library/plistlib.rst Doc/library/queue.rst Doc/library/reprlib.rst Doc/library/runpy.rst Doc/library/shelve.rst Doc/library/sys.rst Doc/library/threading.rst Doc/library/tk.rst Doc/library/tkinter.ttk.rst Doc/library/unittest.rst Doc/library/zipimport.rst Doc/library/zlib.rst Doc/reference/datamodel.rst Doc/reference/executionmodel.rst Doc/reference/expressions.rst Doc/reference/grammar.rst Doc/reference/simple_stmts.rst Doc/tools/sphinxext/download.html Doc/tools/sphinxext/pyspecific.py Doc/tutorial/floatingpoint.rst Doc/tutorial/modules.rst Doc/using/cmdline.rst Doc/whatsnew/2.7.rst Doc/whatsnew/3.0.rst Include/abstract.h Include/code.h Include/object.h Lib/_abcoll.py Lib/colorsys.py Lib/decimal.py Lib/distutils/README Lib/distutils/__init__.py Lib/distutils/cmd.py Lib/distutils/command/build_ext.py Lib/distutils/command/install_lib.py Lib/distutils/command/wininst-9.0-amd64.exe Lib/distutils/command/wininst-9.0.exe Lib/distutils/dir_util.py Lib/distutils/file_util.py Lib/distutils/sysconfig.py Lib/distutils/tests/test_build_ext.py Lib/distutils/tests/test_cmd.py Lib/distutils/tests/test_dir_util.py Lib/distutils/tests/test_file_util.py Lib/distutils/tests/test_sdist.py Lib/distutils/tests/test_sysconfig.py Lib/heapq.py Lib/http/client.py Lib/importlib/NOTES Lib/importlib/__init__.py Lib/importlib/_bootstrap.py Lib/importlib/machinery.py Lib/importlib/test/

antoine.pitrou python-checkins at python.org
Sun Feb 8 21:39:06 CET 2009


Author: antoine.pitrou
Date: Sun Feb  8 21:39:02 2009
New Revision: 69450

Log:
Merged revisions 69041,69051,69055,69064,69068,69072,69075,69081-69082,69086,69088-69089,69092,69096,69098,69101,69105,69108,69110-69111,69114,69116-69118,69120,69132-69133,69136,69138,69150-69151,69164-69168,69170-69174,69176-69179,69181,69184,69188,69190,69192,69197-69198,69202,69207,69209-69210,69213-69214,69218,69222,69224,69229,69233-69234,69239,69246-69247,69249,69251,69254,69259,69261,69274,69279-69284,69287,69290-69292,69294,69296,69306-69308,69313,69318,69320-69321,69323,69326,69335-69336,69344,69346,69349-69350,69352,69354,69358,69362,69368,69370,69372,69375,69379-69380,69387,69392,69395-69403,69406-69407,69411,69416,69418,69421,69426,69429,69431,69434,69438,69440,69444 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/branches/py3k

................
  r69041 | mark.hammond | 2009-01-28 00:46:57 +0100 (mer., 28 janv. 2009) | 10 lines
  
  Merged revisions 69038 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69038 | mark.hammond | 2009-01-28 10:12:23 +1100 (Wed, 28 Jan 2009) | 3 lines
    
    On Windows, use the Python 'Activation Context' when loading extensions
    to avoid problems loading the CRT from a private assembly.  Via bug 4566.
  ........
................
  r69051 | guilherme.polo | 2009-01-28 15:41:10 +0100 (mer., 28 janv. 2009) | 9 lines
  
  Merged revisions 69050 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69050 | guilherme.polo | 2009-01-28 11:09:03 -0200 (Wed, 28 Jan 2009) | 2 lines
    
    Added the ttk module. See issue #2983: Ttk support for Tkinter.
  ........
................
  r69055 | guilherme.polo | 2009-01-28 17:06:51 +0100 (mer., 28 janv. 2009) | 9 lines
  
  Merged revisions 69053 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69053 | guilherme.polo | 2009-01-28 13:56:01 -0200 (Wed, 28 Jan 2009) | 2 lines
    
    Demos for ttk added.
  ........
................
  r69064 | guilherme.polo | 2009-01-28 21:40:48 +0100 (mer., 28 janv. 2009) | 23 lines
  
  Merged revisions 69060-69063 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69060 | guilherme.polo | 2009-01-28 17:23:28 -0200 (Wed, 28 Jan 2009) | 2 lines
    
    Added support for collecting tests only from specific packages.
  ........
    r69061 | guilherme.polo | 2009-01-28 17:28:04 -0200 (Wed, 28 Jan 2009) | 4 lines
    
    * Renaming test_tk_* to test_ttk_* since that is what they are testing.
    * Added ttk tests to the expected skips mapping just like where test_tcl 
    was expected to be skipped too.
  ........
    r69062 | guilherme.polo | 2009-01-28 18:02:01 -0200 (Wed, 28 Jan 2009) | 1 line
    
    Make sure the root windows gets destroyed
  ........
    r69063 | guilherme.polo | 2009-01-28 18:03:26 -0200 (Wed, 28 Jan 2009) | 2 lines
    
    Issue #5083: New 'gui' resource for regrtest.
  ........
................
  r69068 | mark.dickinson | 2009-01-28 22:25:58 +0100 (mer., 28 janv. 2009) | 3 lines
  
  Issue #4707: round(x, n) now returns an integer when x is an integer.
  Previously it returned a float.
................
  r69072 | raymond.hettinger | 2009-01-29 00:33:59 +0100 (jeu., 29 janv. 2009) | 1 line
  
  Beef-up tests for collections ABCs.
................
  r69075 | raymond.hettinger | 2009-01-29 01:01:27 +0100 (jeu., 29 janv. 2009) | 1 line
  
  Correct docs for ABCs (MutableSequence was missing __setiem).  Simplify the table by taking out inherited requirements for abstract methods.
................
  r69081 | benjamin.peterson | 2009-01-29 02:59:38 +0100 (jeu., 29 janv. 2009) | 14 lines
  
  Blocked revisions 69070,69074 via svnmerge
  
  ........
    r69070 | raymond.hettinger | 2009-01-28 17:02:26 -0600 (Wed, 28 Jan 2009) | 6 lines
    
    Issue 4920:  Fixed next() vs __next__() issues in the ABCs
    for Iterator and MutableSet.  Also added thorough test for
    required abstractmethods.
  ........
    r69074 | raymond.hettinger | 2009-01-28 17:58:16 -0600 (Wed, 28 Jan 2009) | 1 line
    
    Correct docs for ABCs (MutableSequence was missing __setiem).  Simplify the table by taking out inherited requirements for abstract methods.
  ........
................
  r69082 | benjamin.peterson | 2009-01-29 03:14:30 +0100 (jeu., 29 janv. 2009) | 8 lines
  
  Blocked revisions 68521 via svnmerge
  
  ........
    r68521 | hirokazu.yamamoto | 2009-01-10 21:28:13 -0600 (Sat, 10 Jan 2009) | 1 line
    
    Fixed version number in build_ssl.bat.
  ........
................
  r69086 | raymond.hettinger | 2009-01-29 04:41:55 +0100 (jeu., 29 janv. 2009) | 1 line
  
  Update itertools.__doc__ to include all tools.
................
  r69088 | raymond.hettinger | 2009-01-29 04:48:02 +0100 (jeu., 29 janv. 2009) | 1 line
  
  Fix typo.
................
  r69089 | benjamin.peterson | 2009-01-29 04:52:26 +0100 (jeu., 29 janv. 2009) | 12 lines
  
  Blocked revisions 69085,69087 via svnmerge
  
  ........
    r69085 | raymond.hettinger | 2009-01-28 21:21:42 -0600 (Wed, 28 Jan 2009) | 1 line
    
    Update itertools.__doc__ to include all tools.
  ........
    r69087 | raymond.hettinger | 2009-01-28 21:43:44 -0600 (Wed, 28 Jan 2009) | 1 line
    
    Fix typo.
  ........
................
  r69092 | brett.cannon | 2009-01-29 05:10:21 +0100 (jeu., 29 janv. 2009) | 17 lines
  
  Merged revisions 69078-69080 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69078 | brett.cannon | 2009-01-28 16:54:11 -0800 (Wed, 28 Jan 2009) | 2 lines
    
    Clarify some __del__ stuff.
  ........
    r69079 | brett.cannon | 2009-01-28 16:54:32 -0800 (Wed, 28 Jan 2009) | 2 lines
    
    Minor spelling mistake in datetime docs.
  ........
    r69080 | brett.cannon | 2009-01-28 16:55:33 -0800 (Wed, 28 Jan 2009) | 2 lines
    
    Ignore .pyc and .pyo files.
  ........
................
  r69096 | mark.hammond | 2009-01-29 13:36:50 +0100 (jeu., 29 janv. 2009) | 9 lines
  
  Merged revisions 69094 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69094 | mark.hammond | 2009-01-29 23:13:31 +1100 (Thu, 29 Jan 2009) | 2 lines
    
    Fix issue5075: bdist_wininst should not depend on the vc runtime?
  ........
................
  r69098 | mark.hammond | 2009-01-29 14:08:01 +0100 (jeu., 29 janv. 2009) | 2 lines
  
  Fix issue5076: bdist_wininst fails on py3k
................
  r69101 | antoine.pitrou | 2009-01-29 21:26:59 +0100 (jeu., 29 janv. 2009) | 11 lines
  
  Merged revisions 69100 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69100 | antoine.pitrou | 2009-01-29 21:19:34 +0100 (jeu., 29 janv. 2009) | 5 lines
    
    Issue #2047: shutil.move() could believe that its destination path was
    inside its source path if it began with the same letters (e.g. "src" vs.
    "src.new").
  ........
................
  r69105 | raymond.hettinger | 2009-01-29 23:26:20 +0100 (jeu., 29 janv. 2009) | 1 line
  
  Fix error in docs.  The source says proto 2 is the default.
................
  r69108 | tarek.ziade | 2009-01-30 00:54:06 +0100 (ven., 30 janv. 2009) | 9 lines
  
  Merged revisions 69106 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69106 | tarek.ziade | 2009-01-30 00:49:17 +0100 (Fri, 30 Jan 2009) | 1 line
    
    fixed test_make_distribution so it runs on any platform, as long as tar an gzip are available
  ........
................
  r69110 | brett.cannon | 2009-01-30 01:22:35 +0100 (ven., 30 janv. 2009) | 2 lines
  
  Merge testing ABCs for importlib into importlib.test.abc.
................
  r69111 | brett.cannon | 2009-01-30 02:31:34 +0100 (ven., 30 janv. 2009) | 3 lines
  
  The trace module was trying to turn ints into ints since co_lnotab was changed
  to a bytes object.
................
  r69114 | benjamin.peterson | 2009-01-30 03:29:43 +0100 (ven., 30 janv. 2009) | 1 line
  
  fix a case of set_daemon #5087
................
  r69116 | benjamin.peterson | 2009-01-30 04:01:08 +0100 (ven., 30 janv. 2009) | 16 lines
  
  Blocked revisions 68772,68892,69039 via svnmerge
  
  ........
    r68772 | benjamin.peterson | 2009-01-19 09:42:23 -0600 (Mon, 19 Jan 2009) | 1 line
    
    add a note about the ftruncate change
  ........
    r68892 | martin.v.loewis | 2009-01-24 09:45:18 -0600 (Sat, 24 Jan 2009) | 2 lines
    
    Add heading for 2.7a0.
  ........
    r69039 | benjamin.peterson | 2009-01-27 17:15:48 -0600 (Tue, 27 Jan 2009) | 1 line
    
    use True and False
  ........
................
  r69117 | hirokazu.yamamoto | 2009-01-30 04:15:05 +0100 (ven., 30 janv. 2009) | 1 line
  
  Issue #5041: Fixed memory leak.
................
  r69118 | benjamin.peterson | 2009-01-30 04:39:35 +0100 (ven., 30 janv. 2009) | 34 lines
  
  Merged revisions 68884,68973,68978,69003,69083,69112-69113 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r68884 | kristjan.jonsson | 2009-01-24 04:52:26 -0600 (Sat, 24 Jan 2009) | 1 line
    
    Add a test for UNC import paths, see issue 3677
  ........
    r68973 | georg.brandl | 2009-01-26 15:29:38 -0600 (Mon, 26 Jan 2009) | 2 lines
    
    Copy over docs on advanced role features from Sphinx docs.
  ........
    r68978 | mark.dickinson | 2009-01-26 15:51:56 -0600 (Mon, 26 Jan 2009) | 3 lines
    
    Issue #5073: Fix occasional failure of bsddb/test/test_lock.py.  Thanks
    Hirokazu Yamamoto for the patch.
  ........
    r69003 | benjamin.peterson | 2009-01-26 21:07:53 -0600 (Mon, 26 Jan 2009) | 1 line
    
    excellent place to use a set() #5069
  ........
    r69083 | benjamin.peterson | 2009-01-28 21:03:00 -0600 (Wed, 28 Jan 2009) | 1 line
    
    fix download url
  ........
    r69112 | benjamin.peterson | 2009-01-29 20:02:25 -0600 (Thu, 29 Jan 2009) | 1 line
    
    pep8tify conditionals
  ........
    r69113 | benjamin.peterson | 2009-01-29 20:24:39 -0600 (Thu, 29 Jan 2009) | 1 line
    
    make _tkinter._flatten check the result of PySequence_Size for errors #3880
  ........
................
  r69120 | benjamin.peterson | 2009-01-30 05:00:29 +0100 (ven., 30 janv. 2009) | 21 lines
  
  Merged revisions 68840,68881,68943,68945 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r68840 | andrew.kuchling | 2009-01-20 20:15:43 -0600 (Tue, 20 Jan 2009) | 1 line
    
    Add some items
  ........
    r68881 | andrew.kuchling | 2009-01-23 21:28:18 -0600 (Fri, 23 Jan 2009) | 1 line
    
    Add various items
  ........
    r68943 | tarek.ziade | 2009-01-25 16:09:10 -0600 (Sun, 25 Jan 2009) | 1 line
    
    Issue #5052: removed backward compatibility information (out of date)
  ........
    r68945 | tarek.ziade | 2009-01-25 16:11:04 -0600 (Sun, 25 Jan 2009) | 1 line
    
    added missing module docstring
  ........
................
  r69132 | benjamin.peterson | 2009-01-31 04:57:19 +0100 (sam., 31 janv. 2009) | 1 line
  
  comprehrensions now have proper scoping #5106
................
  r69133 | mark.dickinson | 2009-01-31 13:12:41 +0100 (sam., 31 janv. 2009) | 3 lines
  
  Make Python/makeopcodetargets runnable with Python 2.3.  With any luck, this
  should solve the 'failed compile' on the x86 gentoo 3.x buildbot.
................
  r69136 | benjamin.peterson | 2009-01-31 17:36:08 +0100 (sam., 31 janv. 2009) | 1 line
  
  detabify Objects/unicodeobject.c
................
  r69138 | benjamin.peterson | 2009-01-31 17:41:58 +0100 (sam., 31 janv. 2009) | 8 lines
  
  Blocked revisions 69134 via svnmerge
  
  ........
    r69134 | benjamin.peterson | 2009-01-31 10:29:18 -0600 (Sat, 31 Jan 2009) | 1 line
    
    completely detabify unicodeobject.c
  ........
................
  r69150 | benjamin.peterson | 2009-01-31 23:14:21 +0100 (sam., 31 janv. 2009) | 1 line
  
  fix indentation again
................
  r69151 | benjamin.peterson | 2009-01-31 23:17:25 +0100 (sam., 31 janv. 2009) | 12 lines
  
  Blocked revisions 69146,69149 via svnmerge
  
  ........
    r69146 | benjamin.peterson | 2009-01-31 15:47:42 -0600 (Sat, 31 Jan 2009) | 1 line
    
    fix indentation
  ........
    r69149 | benjamin.peterson | 2009-01-31 16:03:19 -0600 (Sat, 31 Jan 2009) | 1 line
    
    fix indentation; looks like all I managed to do the first time is make things uglier
  ........
................
  r69164 | gregory.p.smith | 2009-02-01 01:30:50 +0100 (dim., 01 févr. 2009) | 2 lines
  
  documentation wording fix for issue4903
................
  r69165 | brett.cannon | 2009-02-01 01:37:13 +0100 (dim., 01 févr. 2009) | 1 line
  
  Move built-in loader tests to importlib.test.abc.LoaderTests.
................
  r69166 | brett.cannon | 2009-02-01 01:49:41 +0100 (dim., 01 févr. 2009) | 1 line
  
  Move extension module loader tests over to importlib.test.abc.LoaderTests.
................
  r69167 | brett.cannon | 2009-02-01 02:34:13 +0100 (dim., 01 févr. 2009) | 4 lines
  
  Fix importlib.machinery.FrozenImporter.load_module() to set __package__
  properly. Discovered by also moving the loader tests over to
  importlib.test.abc.LoaderTests.
................
  r69168 | brett.cannon | 2009-02-01 03:05:11 +0100 (dim., 01 févr. 2009) | 3 lines
  
  Move source loader tests (including reload tests) over to
  importlib.test.abc.LoaderTests.
................
  r69170 | brett.cannon | 2009-02-01 04:08:31 +0100 (dim., 01 févr. 2009) | 3 lines
  
  Split out support code that is specific to source tests out of
  importlib.test.support to importlib.test.source.util.
................
  r69171 | brett.cannon | 2009-02-01 04:51:54 +0100 (dim., 01 févr. 2009) | 2 lines
  
  Do not execute the .pyc/.pyo files as well as the .py files.
................
  r69172 | brett.cannon | 2009-02-01 05:00:05 +0100 (dim., 01 févr. 2009) | 2 lines
  
  Rename importlib.test.support to importlib.test.util.
................
  r69173 | brett.cannon | 2009-02-01 05:28:04 +0100 (dim., 01 févr. 2009) | 2 lines
  
  Move import semantic util code to importlib.test.import_.util.
................
  r69174 | brett.cannon | 2009-02-01 06:04:06 +0100 (dim., 01 févr. 2009) | 1 line
  
  Remove an outdated todo item from importlib.
................
  r69176 | brett.cannon | 2009-02-01 06:33:17 +0100 (dim., 01 févr. 2009) | 2 lines
  
  Expose source_path and bytecode_path on _PyFileLoader.
................
  r69177 | brett.cannon | 2009-02-01 06:43:31 +0100 (dim., 01 févr. 2009) | 3 lines
  
  Ditch read_source() and read_bytecode() and replace with *_path() and
  get_data().
................
  r69178 | brett.cannon | 2009-02-01 06:55:23 +0100 (dim., 01 févr. 2009) | 1 line
  
  Update importlib notes.
................
  r69179 | brett.cannon | 2009-02-01 07:07:57 +0100 (dim., 01 févr. 2009) | 1 line
  
  Simplify write_bytecode for importlib.
................
  r69181 | mark.dickinson | 2009-02-01 11:28:51 +0100 (dim., 01 févr. 2009) | 3 lines
  
  Issue #1717, stage 2: remove uses of tp_compare in Modules and most
  Objects.
................
  r69184 | mark.dickinson | 2009-02-01 13:13:56 +0100 (dim., 01 févr. 2009) | 3 lines
  
  Issue #1717:  remove the cmp builtin function, the C-API functions
  PyObject_Cmp, PyObject_Compare, and various support functions.
................
  r69188 | mark.dickinson | 2009-02-01 14:59:22 +0100 (dim., 01 févr. 2009) | 6 lines
  
  Issue #1717, continued:  remove PyObject_Compare and Py_CmpToRich declarations
  from object.h; don't inherit tp_compare slot on subclasses; and raise TypeError
  when initializing a type that has a nonzero tp_compare slot.  Fix up
  comparison-related comments in object.c and code.h.
................
  r69190 | mark.dickinson | 2009-02-01 15:18:10 +0100 (dim., 01 févr. 2009) | 2 lines
  
  Issue #1717: documentation fixes related to the cmp removal.
................
  r69192 | mark.dickinson | 2009-02-01 21:36:08 +0100 (dim., 01 févr. 2009) | 2 lines
  
  Remove exception for non-NULL tp_compare that was introduced in r69188.
................
  r69197 | guilherme.polo | 2009-02-02 02:02:20 +0100 (lun., 02 févr. 2009) | 10 lines
  
  Recorded merge of revisions 69195 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69195 | guilherme.polo | 2009-02-01 22:38:54 -0200 (Sun, 01 Feb 2009) | 3 lines
    
    Use a single Tcl interpreter through all these tests, this may help some 
    failing buildbots.
  ........
................
  r69198 | brett.cannon | 2009-02-02 06:58:30 +0100 (lun., 02 févr. 2009) | 3 lines
  
  Note to move __package__ stuff over to rpartition to make Nick happy. Also make
  sure that accepting the empty string for top-level modules is okay.
................
  r69202 | hirokazu.yamamoto | 2009-02-02 10:15:41 +0100 (lun., 02 févr. 2009) | 9 lines
  
  Merged revisions 69200 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69200 | hirokazu.yamamoto | 2009-02-02 17:01:17 +0900 | 1 line
    
    Set native svn:eol-style property for text files.
  ........
................
  r69207 | martin.v.loewis | 2009-02-02 16:32:22 +0100 (lun., 02 févr. 2009) | 9 lines
  
  Merged revisions 69205 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69205 | martin.v.loewis | 2009-02-02 15:23:16 +0100 (Mo, 02 Feb 2009) | 1 line
    
    Issue #4494: Fix build with Py_NO_ENABLE_SHARED on Windows.
  ........
................
  r69209 | kristjan.jonsson | 2009-02-02 17:04:04 +0100 (lun., 02 févr. 2009) | 4 lines
  
  merging / reimplementing r68532 from the trunk to Py3k
  
  Enable buffering for HTTPResponse's fp.  read() behaves identically for buffered and non-buffered IO.  read(n) also won't block if n bytes are availble on the socket.  There is therefore no reason not to use buffering.  The reason 2.x disables buffering by default, that some clients may be accessing the underlying socket directly and so bypass the buffering buffer, doesn't apply in 3.x with its redesigned IO library.
  See issue 4448 and issue 4879
................
  r69210 | brett.cannon | 2009-02-02 20:19:36 +0100 (lun., 02 févr. 2009) | 5 lines
  
  To prevent another screw-up on my part where my prototype gets lost thanks to
  an ``svn revert`` (gee, maybe more atomic commits by use of something like a
  DVCS would help with this? Wish someone would get on that ...), I am checking
  in an untested, work-in-progress meta path finder to handle sys.path.
................
  r69213 | brett.cannon | 2009-02-02 21:32:29 +0100 (lun., 02 févr. 2009) | 1 line
  
  Add some notes for importlib to package up what is in Python 2.7 as well as modules that can probably get replaced by importlib at some point.
................
  r69214 | mark.dickinson | 2009-02-02 21:36:42 +0100 (lun., 02 févr. 2009) | 4 lines
  
  Issue #1717: rename tp_compare to tp_reserved.  I'll change the
  type of tp_compare in a separate commit, for ease of reversion
  should things go wrong.
................
  r69218 | mark.dickinson | 2009-02-02 22:11:16 +0100 (lun., 02 févr. 2009) | 3 lines
  
  Change type of tp_reserved from cmpfunc to (void *);  remove definition
  of cmpfunc.
................
  r69222 | guilherme.polo | 2009-02-02 22:17:09 +0100 (lun., 02 févr. 2009) | 13 lines
  
  Merged revisions 69217,69219 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69217 | guilherme.polo | 2009-02-02 19:08:32 -0200 (Mon, 02 Feb 2009) | 1 line
    
    Fix for issue #1581476
  ........
    r69219 | guilherme.polo | 2009-02-02 19:14:14 -0200 (Mon, 02 Feb 2009) | 1 line
    
    NEWS entry for issue #1581476
  ........
................
  r69224 | mark.dickinson | 2009-02-02 22:29:40 +0100 (lun., 02 févr. 2009) | 3 lines
  
  Issue #1717, continued: Doc fixes and other cleanup related
  to renaming of tp_compare.
................
  r69229 | raymond.hettinger | 2009-02-02 23:55:09 +0100 (lun., 02 févr. 2009) | 1 line
  
  Issue 1242657: list(obj) can swallow KeyboardInterrupt.
................
  r69233 | benjamin.peterson | 2009-02-03 02:47:16 +0100 (mar., 03 févr. 2009) | 16 lines
  
  Blocked revisions 68532,69161,69227 via svnmerge
  
  ........
    r68532 | kristjan.jonsson | 2009-01-11 10:23:37 -0600 (Sun, 11 Jan 2009) | 1 line
    
    Issue 4879: Allow buffering for HTTPResponse
  ........
    r69161 | gregory.p.smith | 2009-01-31 18:24:21 -0600 (Sat, 31 Jan 2009) | 2 lines
    
    wording for for issue4903.
  ........
    r69227 | raymond.hettinger | 2009-02-02 15:50:13 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Issue 1242657: list(obj) can swallow KeyboardInterrupt.
  ........
................
  r69234 | raymond.hettinger | 2009-02-03 03:12:10 +0100 (mar., 03 févr. 2009) | 1 line
  
  Validate that __length_hint__ returns a usable result.
................
  r69239 | benjamin.peterson | 2009-02-03 03:30:19 +0100 (mar., 03 févr. 2009) | 8 lines
  
  Blocked revisions 69237 via svnmerge
  
  ........
    r69237 | raymond.hettinger | 2009-02-02 20:23:19 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Validate that __length_hint__ returns a usable result.
  ........
................
  r69246 | raymond.hettinger | 2009-02-03 04:54:28 +0100 (mar., 03 févr. 2009) | 1 line
  
  Register decimals as numbers.Number
................
  r69247 | benjamin.peterson | 2009-02-03 05:08:48 +0100 (mar., 03 févr. 2009) | 8 lines
  
  Blocked revisions 69242 via svnmerge
  
  ........
    r69242 | raymond.hettinger | 2009-02-02 21:37:03 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Register decimals as numbers.Number
  ........
................
  r69249 | raymond.hettinger | 2009-02-03 05:19:10 +0100 (mar., 03 févr. 2009) | 1 line
  
  The default shelve pickle protocol should have been 3.
................
  r69251 | brett.cannon | 2009-02-03 05:57:48 +0100 (mar., 03 févr. 2009) | 1 line
  
  Add importlib to the Makefile.
................
  r69254 | brett.cannon | 2009-02-03 06:00:53 +0100 (mar., 03 févr. 2009) | 9 lines
  
  Blocked revisions 69252 via svnmerge
  
  ........
    r69252 | brett.cannon | 2009-02-02 20:58:29 -0800 (Mon, 02 Feb 2009) | 3 lines
    
    Make importlib a package. This allows using svn:externals in the sandbox to
    package up the code for separate distribution.
  ........
................
  r69259 | kristjan.jonsson | 2009-02-03 11:57:52 +0100 (mar., 03 févr. 2009) | 1 line
  
  r69209 caused the fp of HTTPResponse objects to be a io.BufferedReader instead of a socket.SocketIO.  This moves the underlying socket.socket object from r.fp._sock to r.fp.raw._sock.  Since _sock is an internal object, this should be ok. The change is for the testsuite only, to assert socket state.
................
  r69261 | thomas.heller | 2009-02-03 20:34:18 +0100 (mar., 03 févr. 2009) | 16 lines
  
  Merged revisions 69260 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69260 | thomas.heller | 2009-02-03 18:07:40 +0100 (Di, 03 Feb 2009) | 9 lines
    
    This refactoring should make it easier to add new calling conventions.
    
    Replace ffi_call_STDCALL and ffi_call_SYSV by a ffi_call_x86 function
    that cleans up the stack when FFI_SYSV is used, and does nothing for
    FFI_STDCALL.
    
    Remove libffi_msvc\win32.S, which is out of date and also unused; it
    was only used for building ctypes with the MingW compiler.
  ........
................
  r69274 | raymond.hettinger | 2009-02-04 12:41:45 +0100 (mer., 04 févr. 2009) | 1 line
  
  Tweak the docs for Counter() objects.
................
  r69279 | raymond.hettinger | 2009-02-04 20:45:13 +0100 (mer., 04 févr. 2009) | 1 line
  
  Minor doc fixes.
................
  r69280 | benjamin.peterson | 2009-02-05 01:05:45 +0100 (jeu., 05 févr. 2009) | 8 lines
  
  Blocked revisions 69276 via svnmerge
  
  ........
    r69276 | raymond.hettinger | 2009-02-04 13:25:17 -0600 (Wed, 04 Feb 2009) | 1 line
    
    Clarify that named tuples do not have to subclass tuple.
  ........
................
  r69281 | brett.cannon | 2009-02-05 03:52:18 +0100 (jeu., 05 févr. 2009) | 3 lines
  
  Rename importlib._bootstrap.SysPathFinder to PathFinder and expose off of
  importlib.machinery. Also make the methods either class or staticmethods.
................
  r69282 | brett.cannon | 2009-02-05 03:52:57 +0100 (jeu., 05 févr. 2009) | 2 lines
  
  Check in the fact that importlib.machinery.PathFinder now exists.
................
  r69283 | brett.cannon | 2009-02-05 03:53:23 +0100 (jeu., 05 févr. 2009) | 2 lines
  
  Begin writing tests for importlib.machinery.PathFinder.
................
  r69284 | brett.cannon | 2009-02-05 03:53:47 +0100 (jeu., 05 févr. 2009) | 2 lines
  
  Update NOTES for importlib about PathFinder.
................
  r69287 | tarek.ziade | 2009-02-05 10:08:59 +0100 (jeu., 05 févr. 2009) | 9 lines
  
  Merged revisions 69285 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69285 | tarek.ziade | 2009-02-05 10:06:23 +0100 (Thu, 05 Feb 2009) | 1 line
    
    Fix comment for #1835
  ........
................
  r69290 | georg.brandl | 2009-02-05 11:40:48 +0100 (jeu., 05 févr. 2009) | 1 line
  
  #5130: replace "unicode" by "bytes" in examples for sequence types.
................
  r69291 | georg.brandl | 2009-02-05 11:47:16 +0100 (jeu., 05 févr. 2009) | 1 line
  
  #5107: document that default encoding is the same as locale.getpreferredencoding().
................
  r69292 | georg.brandl | 2009-02-05 11:56:37 +0100 (jeu., 05 févr. 2009) | 1 line
  
  #5096: document PyErr_PrintEx().
................
  r69294 | georg.brandl | 2009-02-05 12:01:54 +0100 (jeu., 05 févr. 2009) | 1 line
  
  #4992: next() method -> next() function.
................
  r69296 | georg.brandl | 2009-02-05 12:24:04 +0100 (jeu., 05 févr. 2009) | 8 lines
  
  Blocked revisions 69295 via svnmerge
  
  ........
    r69295 | georg.brandl | 2009-02-05 12:23:47 +0100 (Do, 05 Feb 2009) | 1 line
    
    PyErr_PrintEx is also in 2.x...
  ........
................
  r69306 | neil.schemenauer | 2009-02-05 17:33:41 +0100 (jeu., 05 févr. 2009) | 3 lines
  
  Fix get_python_inc() to work when building in a directory separate from
  the source.  Also, define 'srcdir' on non-posix platforms.
................
  r69307 | neil.schemenauer | 2009-02-05 17:35:04 +0100 (jeu., 05 févr. 2009) | 4 lines
  
  Since sysconfig.get_python_inc() now works when building in a
  directory other than the source directory, simplify the test code in
  test_sysconfig.py.
................
  r69308 | neil.schemenauer | 2009-02-05 17:35:45 +0100 (jeu., 05 févr. 2009) | 4 lines
  
  Make setup.py work when building in a directory other than the
  source directory.  Mainly, use 'srcdir' rather than os.getcwd() or
  '.'.
................
  r69313 | brett.cannon | 2009-02-05 23:02:03 +0100 (jeu., 05 févr. 2009) | 3 lines
  
  Implement test for sys.path_importer_cache having None for
  importlib.machinery.PathFinder.
................
  r69318 | tarek.ziade | 2009-02-05 23:56:14 +0100 (jeu., 05 févr. 2009) | 9 lines
  
  Merged revisions 69316 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69316 | tarek.ziade | 2009-02-05 23:52:52 +0100 (Thu, 05 Feb 2009) | 1 line
    
    Fixed #5132: enable extensions to link on Solaris
  ........
................
  r69320 | brett.cannon | 2009-02-06 00:36:02 +0100 (ven., 06 févr. 2009) | 2 lines
  
  Add tests for using sys.path_hooks by importlib.machinery.PathFinder.
................
  r69321 | brett.cannon | 2009-02-06 01:07:49 +0100 (ven., 06 févr. 2009) | 3 lines
  
  Finish implementing tests for importlib.machinery.PathFinder by testing that
  implicit hooks are handled properly.
................
  r69323 | neil.schemenauer | 2009-02-06 01:27:50 +0100 (ven., 06 févr. 2009) | 2 lines
  
  Distutils apparently requires an absolute path so provide one.
................
  r69326 | tarek.ziade | 2009-02-06 01:38:35 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69324 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69324 | tarek.ziade | 2009-02-06 01:31:59 +0100 (Fri, 06 Feb 2009) | 1 line
    
    Fixed #1276768: verbose option was not used in the code.
  ........
................
  r69335 | tarek.ziade | 2009-02-06 01:52:52 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69330 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69330 | tarek.ziade | 2009-02-06 01:46:57 +0100 (Fri, 06 Feb 2009) | 1 line
    
    README now reflects the current state
  ........
................
  r69336 | tarek.ziade | 2009-02-06 01:53:43 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69332 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69332 | tarek.ziade | 2009-02-06 01:49:45 +0100 (Fri, 06 Feb 2009) | 1 line
    
    using >= so setting verbose to 2 will work as well
  ........
................
  r69344 | tarek.ziade | 2009-02-06 02:18:36 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69342 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69342 | tarek.ziade | 2009-02-06 02:15:51 +0100 (Fri, 06 Feb 2009) | 1 line
    
    fixed #1520877: now distutils reads Read  from the environment/Makefile
  ........
................
  r69346 | eric.smith | 2009-02-06 02:32:42 +0100 (ven., 06 févr. 2009) | 10 lines
  
  Merged revisions 69331 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69331 | eric.smith | 2009-02-05 19:48:26 -0500 (Thu, 05 Feb 2009) | 2 lines
    
    Implement issue #4285, convert sys.version_info to a named
    tuple. Patch by Ross Light.
  ........
................
  r69349 | benjamin.peterson | 2009-02-06 03:02:07 +0100 (ven., 06 févr. 2009) | 75 lines
  
  Blocked revisions 69240,69242,69252-69253,69257,69262,69271-69273,69302-69305,69315,69322 via svnmerge
  
  ........
    r69240 | raymond.hettinger | 2009-02-02 21:18:14 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Record operator deprecations in docs.
  ........
    r69242 | raymond.hettinger | 2009-02-02 21:37:03 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Register decimals as numbers.Number
  ........
    r69252 | brett.cannon | 2009-02-02 22:58:29 -0600 (Mon, 02 Feb 2009) | 3 lines
    
    Make importlib a package. This allows using svn:externals in the sandbox to
    package up the code for separate distribution.
  ........
    r69253 | brett.cannon | 2009-02-02 22:59:58 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Ignore bytecode files in importlib.
  ........
    r69257 | brett.cannon | 2009-02-02 23:08:22 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Backport importlib to at least Python 2.5 by getting rid of use of str.format.
  ........
    r69262 | brett.cannon | 2009-02-03 15:13:05 -0600 (Tue, 03 Feb 2009) | 5 lines
    
    Make importlib backwards-compatible to Python 2.2 (but this is not promised to
    last; just doing it to be nice).
    
    Also fix a message for an exception.
  ........
    r69271 | raymond.hettinger | 2009-02-04 04:52:32 -0600 (Wed, 04 Feb 2009) | 1 line
    
    Minor doc fixups.
  ........
    r69272 | raymond.hettinger | 2009-02-04 05:14:18 -0600 (Wed, 04 Feb 2009) | 1 line
    
    Doc fixes. Remove overbroad, redundant warnings.  Fixup example code.
  ........
    r69273 | raymond.hettinger | 2009-02-04 05:31:30 -0600 (Wed, 04 Feb 2009) | 1 line
    
    Tweak the docs for Counter() objects.
  ........
    r69302 | neil.schemenauer | 2009-02-05 10:14:39 -0600 (Thu, 05 Feb 2009) | 3 lines
    
    Fix get_python_inc() to work when building in a directory separate from
    the source.  Also, define 'srcdir' on non-posix platforms.
  ........
    r69303 | neil.schemenauer | 2009-02-05 10:19:05 -0600 (Thu, 05 Feb 2009) | 4 lines
    
    Since sysconfig.get_python_inc() now works when building in a
    directory other than the source directory, simplify the test code in
    test_sysconfig.py.
  ........
    r69304 | neil.schemenauer | 2009-02-05 10:25:16 -0600 (Thu, 05 Feb 2009) | 4 lines
    
    Fix test_build_ext.py to work when building in a separate directory.
    Since "srcdir" should now be defined on all platforms, use it to
    find the module source.
  ........
    r69305 | neil.schemenauer | 2009-02-05 10:32:29 -0600 (Thu, 05 Feb 2009) | 4 lines
    
    Make setup.py work when building in a directory other than the
    source directory.  Mainly use 'srcdir' rather than os.getcwd() or
    '.'.
  ........
    r69315 | neil.schemenauer | 2009-02-05 16:14:04 -0600 (Thu, 05 Feb 2009) | 2 lines
    
    Oops, Mac build needs the 'incdirlist' variable so restore it.
  ........
    r69322 | neil.schemenauer | 2009-02-05 18:21:55 -0600 (Thu, 05 Feb 2009) | 2 lines
    
    Distutils apparently requires an absolute path so provide one.
  ........
................
  r69350 | benjamin.peterson | 2009-02-06 03:40:07 +0100 (ven., 06 févr. 2009) | 96 lines
  
  Merged revisions 69129-69131,69139-69140,69143,69154-69159,69169,69288-69289,69293,69297-69301,69348 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69129 | benjamin.peterson | 2009-01-30 19:42:55 -0600 (Fri, 30 Jan 2009) | 1 line
    
    check the errno in bad fd cases
  ........
    r69130 | andrew.kuchling | 2009-01-30 20:50:09 -0600 (Fri, 30 Jan 2009) | 1 line
    
    Add a section
  ........
    r69131 | andrew.kuchling | 2009-01-30 21:26:02 -0600 (Fri, 30 Jan 2009) | 1 line
    
    Text edits and markup fixes
  ........
    r69139 | mark.dickinson | 2009-01-31 10:44:04 -0600 (Sat, 31 Jan 2009) | 2 lines
    
    Add an extra test for long <-> float hash equivalence.
  ........
    r69140 | benjamin.peterson | 2009-01-31 10:52:03 -0600 (Sat, 31 Jan 2009) | 1 line
    
    PyErr_BadInternalCall() raises a SystemError, not TypeError #5112
  ........
    r69143 | benjamin.peterson | 2009-01-31 15:00:10 -0600 (Sat, 31 Jan 2009) | 1 line
    
    I believe the intention here was to avoid a global lookup
  ........
    r69154 | benjamin.peterson | 2009-01-31 16:33:02 -0600 (Sat, 31 Jan 2009) | 1 line
    
    fix indentation in comment
  ........
    r69155 | david.goodger | 2009-01-31 16:53:46 -0600 (Sat, 31 Jan 2009) | 1 line
    
    markup fix
  ........
    r69156 | gregory.p.smith | 2009-01-31 16:57:30 -0600 (Sat, 31 Jan 2009) | 4 lines
    
    - Issue #5104: The socket module now raises OverflowError when 16-bit port and
      protocol numbers are supplied outside the allowed 0-65536 range on bind()
      and getservbyport().
  ........
    r69157 | benjamin.peterson | 2009-01-31 17:43:25 -0600 (Sat, 31 Jan 2009) | 1 line
    
    add explanatory comment
  ........
    r69158 | benjamin.peterson | 2009-01-31 17:54:38 -0600 (Sat, 31 Jan 2009) | 1 line
    
    more flags which only work for function blocks
  ........
    r69159 | gregory.p.smith | 2009-01-31 18:16:01 -0600 (Sat, 31 Jan 2009) | 2 lines
    
    Update doc wording as suggested in issue4903.
  ........
    r69169 | guilherme.polo | 2009-01-31 20:56:16 -0600 (Sat, 31 Jan 2009) | 3 lines
    
    Restore Tkinter.Tk._loadtk so this test doesn't fail for problems 
    related to ttk.
  ........
    r69288 | georg.brandl | 2009-02-05 04:30:57 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #5153: fix typo in example.
  ........
    r69289 | georg.brandl | 2009-02-05 04:37:07 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #5144: document that PySys_SetArgv prepends the script directory (or the empty string) to sys.path.
  ........
    r69293 | georg.brandl | 2009-02-05 04:59:28 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #5059: fix example.
  ........
    r69297 | georg.brandl | 2009-02-05 05:32:18 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #5015: document PythonHome API functions.
  ........
    r69298 | georg.brandl | 2009-02-05 05:33:21 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #4827: fix callback example.
  ........
    r69299 | georg.brandl | 2009-02-05 05:35:28 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #4820: use correct module for ctypes.util.
  ........
    r69300 | georg.brandl | 2009-02-05 05:38:23 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #4563: disable alpha and roman lists, fixes wrong formatting of contributor list.
  ........
    r69301 | georg.brandl | 2009-02-05 05:40:35 -0600 (Thu, 05 Feb 2009) | 1 line
    
    #5031: fix Thread.daemon property docs.
  ........
    r69348 | benjamin.peterson | 2009-02-05 19:47:31 -0600 (Thu, 05 Feb 2009) | 1 line
    
    fix download link
  ........
................
  r69352 | brett.cannon | 2009-02-06 03:47:33 +0100 (ven., 06 févr. 2009) | 3 lines
  
  Initial, untested stab at writing a common denominator function for __import__
  and import_module.
................
  r69354 | benjamin.peterson | 2009-02-06 04:01:24 +0100 (ven., 06 févr. 2009) | 17 lines
  
  Merged revisions 69141,69211-69212 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69141 | benjamin.peterson | 2009-01-31 14:01:48 -0600 (Sat, 31 Jan 2009) | 1 line
    
    fix indentation
  ........
    r69211 | guilherme.polo | 2009-02-02 14:23:29 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Restore the previous geometry before leaving the test
  ........
    r69212 | guilherme.polo | 2009-02-02 14:28:59 -0600 (Mon, 02 Feb 2009) | 1 line
    
    Moving to importlib
  ........
................
  r69358 | tarek.ziade | 2009-02-06 09:22:21 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69356 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69356 | tarek.ziade | 2009-02-06 09:20:15 +0100 (Fri, 06 Feb 2009) | 1 line
    
    Fixed #3987 : removed unused import
  ........
................
  r69362 | tarek.ziade | 2009-02-06 10:03:10 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69360 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69360 | tarek.ziade | 2009-02-06 09:55:23 +0100 (Fri, 06 Feb 2009) | 1 line
    
    removed types usage and added test coverage (work for #3986)
  ........
................
  r69368 | tarek.ziade | 2009-02-06 14:33:47 +0100 (ven., 06 févr. 2009) | 9 lines
  
  Merged revisions 69366 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69366 | tarek.ziade | 2009-02-06 14:27:38 +0100 (Fri, 06 Feb 2009) | 1 line
    
    Fixed #5167: test_customize_compiler does not apply under non unix compilers
  ........
................
  r69370 | mark.dickinson | 2009-02-06 17:39:11 +0100 (ven., 06 févr. 2009) | 3 lines
  
  Replace references to python-3000 mailing list with python-dev in
  README.
................
  r69372 | georg.brandl | 2009-02-06 19:11:01 +0100 (ven., 06 févr. 2009) | 1 line
  
  #5173: StandardError wasn't removed in 2.6.
................
  r69375 | neil.schemenauer | 2009-02-06 22:42:05 +0100 (ven., 06 févr. 2009) | 4 lines
  
  Make test_build_ext.py use sysconfig "srcdir" to find the source for
  xxmodule.c.  Have sysconfig make the srcdir path absolute if that seems
  necessary (running non-installed Python outside the build directory).
................
  r69379 | guilherme.polo | 2009-02-07 00:04:44 +0100 (sam., 07 févr. 2009) | 2 lines
  
  Fixing changes from the last merge.
................
  r69380 | guilherme.polo | 2009-02-07 00:16:11 +0100 (sam., 07 févr. 2009) | 17 lines
  
  Merged revisions 69376-69377 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69376 | guilherme.polo | 2009-02-06 20:26:22 -0200 (Fri, 06 Feb 2009) | 3 lines
    
    Partial fix to issue #1731706: memory leak in Tkapp_Call when calling
    from a thread different than the one that created the Tcl interpreter.
  ........
    r69377 | guilherme.polo | 2009-02-06 20:48:07 -0200 (Fri, 06 Feb 2009) | 5 lines
    
    Issue #1731706: Call Tcl_ConditionFinalize for Tcl_Conditions that will
    not be used again (this requires Tcl/Tk 8.3.1), also fix a memory 
    leak in Tkapp_Call when calling from a thread different than the one that 
    created the Tcl interpreter.
  ........
................
  r69387 | tarek.ziade | 2009-02-07 01:10:48 +0100 (sam., 07 févr. 2009) | 9 lines
  
  Merged revisions 69385 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69385 | tarek.ziade | 2009-02-07 01:05:39 +0100 (Sat, 07 Feb 2009) | 1 line
    
    #3986 replacing string and types call (like in the Py3k branch), and put exec_msg call at the right place
  ........
................
  r69392 | guilherme.polo | 2009-02-07 01:45:10 +0100 (sam., 07 févr. 2009) | 1 line
  
  long -> int
................
  r69395 | brett.cannon | 2009-02-07 02:15:27 +0100 (sam., 07 févr. 2009) | 8 lines
  
  Rewrite the code implementing __import__ for importlib. Now it is much simpler
  and relies much more on meta path finders to abstract out various parts of
  import.
  
  As part of this the semantics for import_module tightened up and now follow
  __import__ much more closely (biggest thing is that the 'package' argument must
  now already be imported, else a SystemError is raised).
................
  r69396 | benjamin.peterson | 2009-02-07 02:35:08 +0100 (sam., 07 févr. 2009) | 29 lines
  
  Blocked revisions 69373-69374,69389,69394 via svnmerge
  
  ........
    r69373 | neil.schemenauer | 2009-02-06 15:08:52 -0600 (Fri, 06 Feb 2009) | 5 lines
    
    Overhaul Lib/compiler block ordering.  The previous code was filled with
    hacks.  The new code is based on issue #2472 posted by Antoine Pitrou.  I
    did some further cleanups of the pyassem code and optimized the block
    ordering pass.
  ........
    r69374 | neil.schemenauer | 2009-02-06 15:33:45 -0600 (Fri, 06 Feb 2009) | 6 lines
    
    Convert "srcdir" into an absolute path if that seems prudent.  Currrently
    the only user of this is Lib/distutils/tests/test_build_ext.py (in order
    to find the source for xxmodule.c).  I'm not sure if other platforms
    need similar tweaks, I'm not brave enough to attempt it without being
    able to test.
  ........
    r69389 | neil.schemenauer | 2009-02-06 18:13:39 -0600 (Fri, 06 Feb 2009) | 2 lines
    
    Make names generated for 'with' variables match the built-in compiler.
  ........
    r69394 | neil.schemenauer | 2009-02-06 18:54:41 -0600 (Fri, 06 Feb 2009) | 4 lines
    
    Issue #999042: The Python compiler now handles explict global statements
    correctly (should be assigned using STORE_GLOBAL opcode).  This was done by
    having the system table differentiate between explict and implicit globals.
  ........
................
  r69397 | brett.cannon | 2009-02-07 02:38:38 +0100 (sam., 07 févr. 2009) | 2 lines
  
  Move importlib's frozen importer over to rpartition for setting __package__.
................
  r69398 | brett.cannon | 2009-02-07 02:40:19 +0100 (sam., 07 févr. 2009) | 2 lines
  
  Move importlib's built-in importer to use rpartition for __package__.
................
  r69399 | brett.cannon | 2009-02-07 02:52:25 +0100 (sam., 07 févr. 2009) | 3 lines
  
  Move importlib completely over to using rpartition and accepting the empty
  string for top-level modules.
................
  r69400 | brett.cannon | 2009-02-07 02:57:14 +0100 (sam., 07 févr. 2009) | 1 line
  
  Add a note for importlib about backporting some of functools.wraps functionality.
................
  r69401 | brett.cannon | 2009-02-07 03:06:43 +0100 (sam., 07 févr. 2009) | 2 lines
  
  Factor out helper code from importlib.test.extension.test_path_hook.
................
  r69402 | brett.cannon | 2009-02-07 03:13:28 +0100 (sam., 07 févr. 2009) | 2 lines
  
  Create a simple substitute for functools.wraps to use in importlib._bootstrap.
................
  r69403 | brett.cannon | 2009-02-07 03:14:07 +0100 (sam., 07 févr. 2009) | 3 lines
  
  Update NOTES for importlib now that a replacement for functools.wraps is
  available.
................
  r69406 | guilherme.polo | 2009-02-07 03:33:47 +0100 (sam., 07 févr. 2009) | 9 lines
  
  Merged revisions 69404 via svnmerge from 
  svn+ssh://pythondev/python/trunk
  
  ........
    r69404 | guilherme.polo | 2009-02-07 00:20:29 -0200 (Sat, 07 Feb 2009) | 2 lines
    
    Eliminated the need to use ttk.__loadtk__ and the problems related it.
  ........
................
  r69407 | brett.cannon | 2009-02-07 03:33:52 +0100 (sam., 07 févr. 2009) | 2 lines
  
  Add the missing importlib.test.extension.util.
................
  r69411 | antoine.pitrou | 2009-02-07 18:13:31 +0100 (sam., 07 févr. 2009) | 4 lines
  
  Issue #4704: remove use of cmp() in pybench, bump its version number to 2.1,
  and make it 2.6-compatible.
................
  r69416 | benjamin.peterson | 2009-02-07 23:55:24 +0100 (sam., 07 févr. 2009) | 1 line
  
  fix typo and test_urllib failures
................
  r69418 | benjamin.peterson | 2009-02-08 01:29:20 +0100 (dim., 08 févr. 2009) | 1 line
  
  revert 69416; it didn't help much
................
  r69421 | nick.coghlan | 2009-02-08 02:58:26 +0100 (dim., 08 févr. 2009) | 13 lines
  
  Merged revisions 69419-69420 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69419 | nick.coghlan | 2009-02-08 11:26:34 +1000 (Sun, 08 Feb 2009) | 1 line
    
    Issue 4195: Restore the ability to execute packages with the -m switch (but this time in a way that leaves the import machinery in a valid state). (Original patch by Andi Vajda)
  ........
    r69420 | nick.coghlan | 2009-02-08 11:46:01 +1000 (Sun, 08 Feb 2009) | 1 line
    
    Mention patch submitter in NEWS entry for r69419
  ........
................
  r69426 | nick.coghlan | 2009-02-08 04:37:27 +0100 (dim., 08 févr. 2009) | 9 lines
  
  Merged revisions 69425 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69425 | nick.coghlan | 2009-02-08 13:17:00 +1000 (Sun, 08 Feb 2009) | 1 line
    
    Issue #4512 closeout: Make ZipImport.get_filename() a public method
  ........
................
  r69429 | nick.coghlan | 2009-02-08 05:01:00 +0100 (dim., 08 févr. 2009) | 1 line
  
  Fix broken socket.makefile emulation in test_urllib
................
  r69431 | mark.dickinson | 2009-02-08 12:02:10 +0100 (dim., 08 févr. 2009) | 4 lines
  
  Issue #1717: add a DeprecationWarning in 3.x on type initialization
  for types that implement tp_reserved (formerly tp_compare) but
  not tp_richcompare.
................
  r69434 | mark.dickinson | 2009-02-08 15:00:21 +0100 (dim., 08 févr. 2009) | 8 lines
  
  Blocked revisions 69433 via svnmerge
  
  ........
    r69433 | mark.dickinson | 2009-02-08 13:58:10 +0000 (Sun, 08 Feb 2009) | 2 lines
    
    Remove redundant assignment in _PyObject_LengthHint
  ........
................
  r69438 | benjamin.peterson | 2009-02-08 16:00:52 +0100 (dim., 08 févr. 2009) | 1 line
  
  remove memoryview.__str__ #5182
................
  r69440 | mark.dickinson | 2009-02-08 16:09:21 +0100 (dim., 08 févr. 2009) | 17 lines
  
  Merged revisions 69436 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/python/trunk
  
  ........
    r69436 | mark.dickinson | 2009-02-08 14:42:28 +0000 (Sun, 08 Feb 2009) | 10 lines
    
    Issue #789290: make sure that hash(2**63) == hash(2.**63) on 64-bit
    platforms.  The previous code was fragile, depending on the twin
    accidents that:
    
      (1) in C, casting the double value 2.**63 to long returns the integer
          value -2**63, and
      (2) in Python, hash(-2**63) == hash(2**63).
    
    There's already a test for this in test_hash.
  ........
................
  r69444 | mark.dickinson | 2009-02-08 18:39:43 +0100 (dim., 08 févr. 2009) | 8 lines
  
  Blocked revisions 69443 via svnmerge
  
  ........
    r69443 | mark.dickinson | 2009-02-08 17:33:11 +0000 (Sun, 08 Feb 2009) | 2 lines
    
    Silence 'arg may be used uninitialized in this function' warning from gcc.
  ........
................


Added:
   python/branches/io-c/Demo/tkinter/ttk/
      - copied from r69444, /python/branches/py3k/Demo/tkinter/ttk/
   python/branches/io-c/Doc/library/tkinter.ttk.rst
      - copied unchanged from r69444, /python/branches/py3k/Doc/library/tkinter.ttk.rst
   python/branches/io-c/Lib/distutils/tests/test_cmd.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/distutils/tests/test_cmd.py
   python/branches/io-c/Lib/distutils/tests/test_dir_util.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/distutils/tests/test_dir_util.py
   python/branches/io-c/Lib/distutils/tests/test_file_util.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/distutils/tests/test_file_util.py
   python/branches/io-c/Lib/importlib/test/abc.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/importlib/test/abc.py
   python/branches/io-c/Lib/importlib/test/extension/util.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/importlib/test/extension/util.py
   python/branches/io-c/Lib/importlib/test/import_/util.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/importlib/test/import_/util.py
   python/branches/io-c/Lib/importlib/test/source/util.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/importlib/test/source/util.py
   python/branches/io-c/Lib/importlib/test/util.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/importlib/test/util.py
   python/branches/io-c/Lib/test/test_ttk_guionly.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/test/test_ttk_guionly.py
   python/branches/io-c/Lib/test/test_ttk_textonly.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/test/test_ttk_textonly.py
   python/branches/io-c/Lib/tkinter/test/
      - copied from r69444, /python/branches/py3k/Lib/tkinter/test/
   python/branches/io-c/Lib/tkinter/ttk.py
      - copied unchanged from r69444, /python/branches/py3k/Lib/tkinter/ttk.py
Removed:
   python/branches/io-c/Lib/importlib/test/finder_tests.py
   python/branches/io-c/Lib/importlib/test/frozen/support.py
   python/branches/io-c/Lib/importlib/test/loader_tests.py
   python/branches/io-c/Lib/importlib/test/source/test_reload.py
   python/branches/io-c/Lib/importlib/test/support.py
   python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.S
Modified:
   python/branches/io-c/   (props changed)
   python/branches/io-c/Demo/tkinter/README
   python/branches/io-c/Doc/c-api/allocation.rst   (props changed)
   python/branches/io-c/Doc/c-api/arg.rst   (props changed)
   python/branches/io-c/Doc/c-api/bool.rst   (props changed)
   python/branches/io-c/Doc/c-api/buffer.rst   (props changed)
   python/branches/io-c/Doc/c-api/bytearray.rst   (props changed)
   python/branches/io-c/Doc/c-api/bytes.rst   (props changed)
   python/branches/io-c/Doc/c-api/cell.rst   (props changed)
   python/branches/io-c/Doc/c-api/cobject.rst   (props changed)
   python/branches/io-c/Doc/c-api/complex.rst   (props changed)
   python/branches/io-c/Doc/c-api/conversion.rst   (props changed)
   python/branches/io-c/Doc/c-api/datetime.rst   (props changed)
   python/branches/io-c/Doc/c-api/descriptor.rst   (props changed)
   python/branches/io-c/Doc/c-api/dict.rst   (props changed)
   python/branches/io-c/Doc/c-api/exceptions.rst
   python/branches/io-c/Doc/c-api/file.rst   (props changed)
   python/branches/io-c/Doc/c-api/float.rst   (props changed)
   python/branches/io-c/Doc/c-api/function.rst   (props changed)
   python/branches/io-c/Doc/c-api/gcsupport.rst   (props changed)
   python/branches/io-c/Doc/c-api/gen.rst   (props changed)
   python/branches/io-c/Doc/c-api/import.rst   (props changed)
   python/branches/io-c/Doc/c-api/init.rst
   python/branches/io-c/Doc/c-api/iter.rst   (props changed)
   python/branches/io-c/Doc/c-api/iterator.rst   (props changed)
   python/branches/io-c/Doc/c-api/list.rst   (props changed)
   python/branches/io-c/Doc/c-api/long.rst   (props changed)
   python/branches/io-c/Doc/c-api/mapping.rst   (props changed)
   python/branches/io-c/Doc/c-api/marshal.rst   (props changed)
   python/branches/io-c/Doc/c-api/method.rst   (props changed)
   python/branches/io-c/Doc/c-api/module.rst   (props changed)
   python/branches/io-c/Doc/c-api/none.rst   (props changed)
   python/branches/io-c/Doc/c-api/number.rst   (props changed)
   python/branches/io-c/Doc/c-api/objbuffer.rst   (props changed)
   python/branches/io-c/Doc/c-api/object.rst   (contents, props changed)
   python/branches/io-c/Doc/c-api/objimpl.rst   (props changed)
   python/branches/io-c/Doc/c-api/reflection.rst   (props changed)
   python/branches/io-c/Doc/c-api/sequence.rst   (props changed)
   python/branches/io-c/Doc/c-api/set.rst   (props changed)
   python/branches/io-c/Doc/c-api/slice.rst   (props changed)
   python/branches/io-c/Doc/c-api/structures.rst   (props changed)
   python/branches/io-c/Doc/c-api/sys.rst   (props changed)
   python/branches/io-c/Doc/c-api/tuple.rst   (props changed)
   python/branches/io-c/Doc/c-api/type.rst   (props changed)
   python/branches/io-c/Doc/c-api/typeobj.rst   (contents, props changed)
   python/branches/io-c/Doc/c-api/unicode.rst   (props changed)
   python/branches/io-c/Doc/c-api/weakref.rst   (props changed)
   python/branches/io-c/Doc/documenting/markup.rst
   python/branches/io-c/Doc/extending/newtypes.rst
   python/branches/io-c/Doc/glossary.rst
   python/branches/io-c/Doc/includes/noddy.c
   python/branches/io-c/Doc/includes/noddy2.c
   python/branches/io-c/Doc/includes/noddy3.c
   python/branches/io-c/Doc/includes/noddy4.c
   python/branches/io-c/Doc/includes/shoddy.c
   python/branches/io-c/Doc/includes/sqlite3/collation_reverse.py
   python/branches/io-c/Doc/includes/typestruct.h
   python/branches/io-c/Doc/library/ast.rst   (props changed)
   python/branches/io-c/Doc/library/binascii.rst
   python/branches/io-c/Doc/library/collections.rst
   python/branches/io-c/Doc/library/copyreg.rst   (props changed)
   python/branches/io-c/Doc/library/ctypes.rst
   python/branches/io-c/Doc/library/datetime.rst
   python/branches/io-c/Doc/library/fractions.rst   (props changed)
   python/branches/io-c/Doc/library/functions.rst
   python/branches/io-c/Doc/library/html.entities.rst   (props changed)
   python/branches/io-c/Doc/library/importlib.rst   (contents, props changed)
   python/branches/io-c/Doc/library/io.rst   (props changed)
   python/branches/io-c/Doc/library/itertools.rst
   python/branches/io-c/Doc/library/json.rst   (props changed)
   python/branches/io-c/Doc/library/locale.rst
   python/branches/io-c/Doc/library/multiprocessing.rst   (props changed)
   python/branches/io-c/Doc/library/operator.rst
   python/branches/io-c/Doc/library/optparse.rst
   python/branches/io-c/Doc/library/plistlib.rst   (props changed)
   python/branches/io-c/Doc/library/queue.rst
   python/branches/io-c/Doc/library/reprlib.rst   (props changed)
   python/branches/io-c/Doc/library/runpy.rst
   python/branches/io-c/Doc/library/shelve.rst
   python/branches/io-c/Doc/library/sys.rst
   python/branches/io-c/Doc/library/threading.rst
   python/branches/io-c/Doc/library/tk.rst
   python/branches/io-c/Doc/library/unittest.rst
   python/branches/io-c/Doc/library/zipimport.rst
   python/branches/io-c/Doc/library/zlib.rst
   python/branches/io-c/Doc/reference/datamodel.rst
   python/branches/io-c/Doc/reference/executionmodel.rst
   python/branches/io-c/Doc/reference/expressions.rst
   python/branches/io-c/Doc/reference/grammar.rst   (props changed)
   python/branches/io-c/Doc/reference/simple_stmts.rst
   python/branches/io-c/Doc/tools/sphinxext/download.html
   python/branches/io-c/Doc/tools/sphinxext/pyspecific.py
   python/branches/io-c/Doc/tutorial/floatingpoint.rst
   python/branches/io-c/Doc/tutorial/modules.rst
   python/branches/io-c/Doc/using/cmdline.rst
   python/branches/io-c/Doc/whatsnew/2.7.rst   (contents, props changed)
   python/branches/io-c/Doc/whatsnew/3.0.rst
   python/branches/io-c/Include/abstract.h
   python/branches/io-c/Include/code.h
   python/branches/io-c/Include/object.h
   python/branches/io-c/Lib/_abcoll.py
   python/branches/io-c/Lib/colorsys.py
   python/branches/io-c/Lib/decimal.py
   python/branches/io-c/Lib/distutils/README
   python/branches/io-c/Lib/distutils/__init__.py
   python/branches/io-c/Lib/distutils/cmd.py
   python/branches/io-c/Lib/distutils/command/build_ext.py
   python/branches/io-c/Lib/distutils/command/install_lib.py
   python/branches/io-c/Lib/distutils/command/wininst-9.0-amd64.exe
   python/branches/io-c/Lib/distutils/command/wininst-9.0.exe
   python/branches/io-c/Lib/distutils/dir_util.py
   python/branches/io-c/Lib/distutils/file_util.py
   python/branches/io-c/Lib/distutils/sysconfig.py
   python/branches/io-c/Lib/distutils/tests/test_build_ext.py
   python/branches/io-c/Lib/distutils/tests/test_sdist.py
   python/branches/io-c/Lib/distutils/tests/test_sysconfig.py
   python/branches/io-c/Lib/heapq.py
   python/branches/io-c/Lib/http/client.py
   python/branches/io-c/Lib/importlib/NOTES
   python/branches/io-c/Lib/importlib/__init__.py
   python/branches/io-c/Lib/importlib/_bootstrap.py
   python/branches/io-c/Lib/importlib/machinery.py
   python/branches/io-c/Lib/importlib/test/__init__.py
   python/branches/io-c/Lib/importlib/test/builtin/test_finder.py
   python/branches/io-c/Lib/importlib/test/builtin/test_loader.py
   python/branches/io-c/Lib/importlib/test/extension/test_case_sensitivity.py
   python/branches/io-c/Lib/importlib/test/extension/test_finder.py
   python/branches/io-c/Lib/importlib/test/extension/test_loader.py
   python/branches/io-c/Lib/importlib/test/extension/test_path_hook.py
   python/branches/io-c/Lib/importlib/test/frozen/test_finder.py
   python/branches/io-c/Lib/importlib/test/frozen/test_loader.py
   python/branches/io-c/Lib/importlib/test/import_/test___package__.py
   python/branches/io-c/Lib/importlib/test/import_/test_caching.py
   python/branches/io-c/Lib/importlib/test/import_/test_fromlist.py
   python/branches/io-c/Lib/importlib/test/import_/test_meta_path.py
   python/branches/io-c/Lib/importlib/test/import_/test_packages.py
   python/branches/io-c/Lib/importlib/test/import_/test_path.py
   python/branches/io-c/Lib/importlib/test/import_/test_relative_imports.py
   python/branches/io-c/Lib/importlib/test/source/test_case_sensitivity.py
   python/branches/io-c/Lib/importlib/test/source/test_finder.py
   python/branches/io-c/Lib/importlib/test/source/test_loader.py
   python/branches/io-c/Lib/importlib/test/source/test_path_hook.py
   python/branches/io-c/Lib/importlib/test/source/test_source_encoding.py
   python/branches/io-c/Lib/importlib/test/test_api.py
   python/branches/io-c/Lib/posixpath.py
   python/branches/io-c/Lib/runpy.py
   python/branches/io-c/Lib/shelve.py
   python/branches/io-c/Lib/shutil.py
   python/branches/io-c/Lib/test/regrtest.py
   python/branches/io-c/Lib/test/test_builtin.py
   python/branches/io-c/Lib/test/test_cmd_line_script.py
   python/branches/io-c/Lib/test/test_collections.py
   python/branches/io-c/Lib/test/test_decimal.py
   python/branches/io-c/Lib/test/test_descr.py
   python/branches/io-c/Lib/test/test_funcattrs.py
   python/branches/io-c/Lib/test/test_hash.py
   python/branches/io-c/Lib/test/test_iterlen.py
   python/branches/io-c/Lib/test/test_itertools.py
   python/branches/io-c/Lib/test/test_long.py
   python/branches/io-c/Lib/test/test_os.py
   python/branches/io-c/Lib/test/test_parser.py
   python/branches/io-c/Lib/test/test_shutil.py
   python/branches/io-c/Lib/test/test_socket.py
   python/branches/io-c/Lib/test/test_sys.py
   python/branches/io-c/Lib/test/test_tcl.py
   python/branches/io-c/Lib/test/test_urllib.py
   python/branches/io-c/Lib/test/test_urllib2net.py
   python/branches/io-c/Lib/test/test_zipimport.py
   python/branches/io-c/Lib/trace.py
   python/branches/io-c/Lib/xmlrpc/client.py
   python/branches/io-c/Makefile.pre.in
   python/branches/io-c/Misc/ACKS
   python/branches/io-c/Misc/NEWS
   python/branches/io-c/Modules/_bytesio.c
   python/branches/io-c/Modules/_collectionsmodule.c
   python/branches/io-c/Modules/_csv.c
   python/branches/io-c/Modules/_ctypes/_ctypes.c
   python/branches/io-c/Modules/_ctypes/callbacks.c
   python/branches/io-c/Modules/_ctypes/callproc.c
   python/branches/io-c/Modules/_ctypes/cfield.c
   python/branches/io-c/Modules/_ctypes/libffi_msvc/ffi.c
   python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.c
   python/branches/io-c/Modules/_ctypes/stgdict.c
   python/branches/io-c/Modules/_curses_panel.c
   python/branches/io-c/Modules/_cursesmodule.c
   python/branches/io-c/Modules/_dbmmodule.c
   python/branches/io-c/Modules/_elementtree.c
   python/branches/io-c/Modules/_fileio.c
   python/branches/io-c/Modules/_functoolsmodule.c
   python/branches/io-c/Modules/_gdbmmodule.c
   python/branches/io-c/Modules/_hashopenssl.c
   python/branches/io-c/Modules/_localemodule.c
   python/branches/io-c/Modules/_lsprof.c
   python/branches/io-c/Modules/_multiprocessing/connection.h
   python/branches/io-c/Modules/_multiprocessing/semaphore.c
   python/branches/io-c/Modules/_pickle.c
   python/branches/io-c/Modules/_randommodule.c
   python/branches/io-c/Modules/_sqlite/cache.c
   python/branches/io-c/Modules/_sqlite/connection.c
   python/branches/io-c/Modules/_sqlite/cursor.c
   python/branches/io-c/Modules/_sqlite/prepare_protocol.c
   python/branches/io-c/Modules/_sqlite/row.c
   python/branches/io-c/Modules/_sqlite/statement.c
   python/branches/io-c/Modules/_sre.c
   python/branches/io-c/Modules/_ssl.c
   python/branches/io-c/Modules/_stringio.c
   python/branches/io-c/Modules/_struct.c
   python/branches/io-c/Modules/_testcapimodule.c
   python/branches/io-c/Modules/_threadmodule.c
   python/branches/io-c/Modules/_tkinter.c
   python/branches/io-c/Modules/arraymodule.c
   python/branches/io-c/Modules/bz2module.c
   python/branches/io-c/Modules/cjkcodecs/multibytecodec.c
   python/branches/io-c/Modules/datetimemodule.c
   python/branches/io-c/Modules/itertoolsmodule.c
   python/branches/io-c/Modules/md5module.c
   python/branches/io-c/Modules/mmapmodule.c
   python/branches/io-c/Modules/operator.c
   python/branches/io-c/Modules/ossaudiodev.c
   python/branches/io-c/Modules/parsermodule.c
   python/branches/io-c/Modules/pyexpat.c
   python/branches/io-c/Modules/selectmodule.c
   python/branches/io-c/Modules/sha1module.c
   python/branches/io-c/Modules/sha256module.c
   python/branches/io-c/Modules/sha512module.c
   python/branches/io-c/Modules/socketmodule.c
   python/branches/io-c/Modules/unicodedata.c
   python/branches/io-c/Modules/xxmodule.c
   python/branches/io-c/Modules/xxsubtype.c
   python/branches/io-c/Modules/zipimport.c
   python/branches/io-c/Modules/zlibmodule.c
   python/branches/io-c/Objects/abstract.c
   python/branches/io-c/Objects/boolobject.c
   python/branches/io-c/Objects/bytearrayobject.c
   python/branches/io-c/Objects/bytesobject.c
   python/branches/io-c/Objects/cellobject.c
   python/branches/io-c/Objects/classobject.c
   python/branches/io-c/Objects/cobject.c
   python/branches/io-c/Objects/codeobject.c
   python/branches/io-c/Objects/complexobject.c
   python/branches/io-c/Objects/descrobject.c
   python/branches/io-c/Objects/dictobject.c
   python/branches/io-c/Objects/enumobject.c
   python/branches/io-c/Objects/exceptions.c
   python/branches/io-c/Objects/fileobject.c
   python/branches/io-c/Objects/floatobject.c
   python/branches/io-c/Objects/frameobject.c
   python/branches/io-c/Objects/funcobject.c
   python/branches/io-c/Objects/genobject.c
   python/branches/io-c/Objects/iterobject.c
   python/branches/io-c/Objects/listobject.c
   python/branches/io-c/Objects/longobject.c
   python/branches/io-c/Objects/memoryobject.c
   python/branches/io-c/Objects/methodobject.c
   python/branches/io-c/Objects/moduleobject.c
   python/branches/io-c/Objects/object.c
   python/branches/io-c/Objects/rangeobject.c
   python/branches/io-c/Objects/setobject.c
   python/branches/io-c/Objects/sliceobject.c
   python/branches/io-c/Objects/stringlib/string_format.h
   python/branches/io-c/Objects/structseq.c
   python/branches/io-c/Objects/tupleobject.c
   python/branches/io-c/Objects/typeobject.c
   python/branches/io-c/Objects/unicodeobject.c
   python/branches/io-c/Objects/weakrefobject.c
   python/branches/io-c/PC/_msi.c
   python/branches/io-c/PC/_subprocess.c
   python/branches/io-c/PC/bdist_wininst/install.c
   python/branches/io-c/PC/dl_nt.c
   python/branches/io-c/PC/getpathp.c
   python/branches/io-c/PC/winreg.c
   python/branches/io-c/PCbuild/bdist_wininst.vcproj
   python/branches/io-c/Parser/asdl_c.py
   python/branches/io-c/Python/Python-ast.c
   python/branches/io-c/Python/bltinmodule.c
   python/branches/io-c/Python/compile.c
   python/branches/io-c/Python/dynload_win.c
   python/branches/io-c/Python/import.c
   python/branches/io-c/Python/makeopcodetargets.py
   python/branches/io-c/Python/symtable.c
   python/branches/io-c/Python/sysmodule.c
   python/branches/io-c/Python/traceback.c
   python/branches/io-c/README
   python/branches/io-c/Tools/framer/framer/slots.py
   python/branches/io-c/Tools/pybench/Calls.py
   python/branches/io-c/Tools/pybench/CommandLine.py
   python/branches/io-c/Tools/pybench/README
   python/branches/io-c/Tools/pybench/Strings.py
   python/branches/io-c/Tools/pybench/pybench.py
   python/branches/io-c/Tools/pybench/systimes.py
   python/branches/io-c/setup.py

Modified: python/branches/io-c/Demo/tkinter/README
==============================================================================
--- python/branches/io-c/Demo/tkinter/README	(original)
+++ python/branches/io-c/Demo/tkinter/README	Sun Feb  8 21:39:02 2009
@@ -8,3 +8,4 @@
 
 guido		my original example set (fairly random collection)
 matt		Matt Conway's examples, to go with his lifesaver document
+ttk         Examples using the ttk module

Modified: python/branches/io-c/Doc/c-api/exceptions.rst
==============================================================================
--- python/branches/io-c/Doc/c-api/exceptions.rst	(original)
+++ python/branches/io-c/Doc/c-api/exceptions.rst	Sun Feb  8 21:39:02 2009
@@ -35,12 +35,21 @@
    Either alphabetical or some kind of structure.
 
 
-.. cfunction:: void PyErr_Print()
+.. cfunction:: void PyErr_PrintEx(int set_sys_last_vars)
 
    Print a standard traceback to ``sys.stderr`` and clear the error indicator.
    Call this function only when the error indicator is set.  (Otherwise it will
    cause a fatal error!)
 
+   If *set_sys_last_vars* is nonzero, the variables :data:`sys.last_type`,
+   :data:`sys.last_value` and :data:`sys.last_traceback` will be set to the
+   type, value and traceback of the printed exception, respectively.
+
+
+.. cfunction:: void PyErr_Print()
+
+   Alias for ``PyErr_PrintEx(1)``.
+
 
 .. cfunction:: PyObject* PyErr_Occurred()
 
@@ -271,9 +280,10 @@
 
 .. cfunction:: void PyErr_BadInternalCall()
 
-   This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
-   *message* indicates that an internal operation (e.g. a Python/C API function)
-   was invoked with an illegal argument.  It is mostly for internal use.
+   This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
+   where *message* indicates that an internal operation (e.g. a Python/C API
+   function) was invoked with an illegal argument.  It is mostly for internal
+   use.
 
 
 .. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel)

Modified: python/branches/io-c/Doc/c-api/init.rst
==============================================================================
--- python/branches/io-c/Doc/c-api/init.rst	(original)
+++ python/branches/io-c/Doc/c-api/init.rst	Sun Feb  8 21:39:02 2009
@@ -350,18 +350,36 @@
       single: Py_FatalError()
       single: argv (in module sys)
 
-   Set ``sys.argv`` based on *argc* and *argv*.  These parameters are similar to
-   those passed to the program's :cfunc:`main` function with the difference that
-   the first entry should refer to the script file to be executed rather than the
-   executable hosting the Python interpreter.  If there isn't a script that will be
-   run, the first entry in *argv* can be an empty string.  If this function fails
-   to initialize ``sys.argv``, a fatal condition is signalled using
-   :cfunc:`Py_FatalError`.
+   Set :data:`sys.argv` based on *argc* and *argv*.  These parameters are
+   similar to those passed to the program's :cfunc:`main` function with the
+   difference that the first entry should refer to the script file to be
+   executed rather than the executable hosting the Python interpreter.  If there
+   isn't a script that will be run, the first entry in *argv* can be an empty
+   string.  If this function fails to initialize :data:`sys.argv`, a fatal
+   condition is signalled using :cfunc:`Py_FatalError`.
+
+   This function also prepends the executed script's path to :data:`sys.path`.
+   If no script is executed (in the case of calling ``python -c`` or just the
+   interactive interpreter), the empty string is used instead.
 
    .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
       check w/ Guido.
 
 
+.. cfunction:: void Py_SetPythonHome(char *home)
+
+   Set the default "home" directory, that is, the location of the standard
+   Python libraries.  The libraries are searched in
+   :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`.
+
+
+.. cfunction:: char* Py_GetPythonHome()
+
+   Return the default "home", that is, the value set by a previous call to
+   :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
+   environment variable if it is set.
+
+
 .. _threads:
 
 Thread State and the Global Interpreter Lock

Modified: python/branches/io-c/Doc/c-api/object.rst
==============================================================================
--- python/branches/io-c/Doc/c-api/object.rst	(original)
+++ python/branches/io-c/Doc/c-api/object.rst	Sun Feb  8 21:39:02 2009
@@ -89,27 +89,6 @@
    *opid*.
 
 
-.. cfunction:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
-
-   .. index:: builtin: cmp
-
-   Compare the values of *o1* and *o2* using a routine provided by *o1*, if one
-   exists, otherwise with a routine provided by *o2*.  The result of the comparison
-   is returned in *result*.  Returns ``-1`` on failure.  This is the equivalent of
-   the Python statement ``result = cmp(o1, o2)``.
-
-
-.. cfunction:: int PyObject_Compare(PyObject *o1, PyObject *o2)
-
-   .. index:: builtin: cmp
-
-   Compare the values of *o1* and *o2* using a routine provided by *o1*, if one
-   exists, otherwise with a routine provided by *o2*.  Returns the result of the
-   comparison on success.  On error, the value returned is undefined; use
-   :cfunc:`PyErr_Occurred` to detect an error.  This is equivalent to the Python
-   expression ``cmp(o1, o2)``.
-
-
 .. cfunction:: PyObject* PyObject_Repr(PyObject *o)
 
    .. index:: builtin: repr

Modified: python/branches/io-c/Doc/c-api/typeobj.rst
==============================================================================
--- python/branches/io-c/Doc/c-api/typeobj.rst	(original)
+++ python/branches/io-c/Doc/c-api/typeobj.rst	Sun Feb  8 21:39:02 2009
@@ -23,7 +23,7 @@
 Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, intargfunc,
 intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor,
 freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc,
-cmpfunc, reprfunc, hashfunc
+reprfunc, hashfunc
 
 The structure definition for :ctype:`PyTypeObject` can be found in
 :file:`Include/object.h`.  For convenience of reference, this repeats the
@@ -244,19 +244,9 @@
    the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*.
 
 
-.. cmember:: cmpfunc PyTypeObject.tp_compare
+.. cmember:: void* PyTypeObject.tp_reserved
 
-   An optional pointer to the three-way comparison function.
-
-   The signature is the same as for :cfunc:`PyObject_Compare`. The function should
-   return ``1`` if *self* greater than *other*, ``0`` if *self* is equal to
-   *other*, and ``-1`` if *self* less than *other*.  It should return ``-1`` and
-   set an exception condition when an error occurred during the comparison.
-
-   This field is inherited by subtypes together with :attr:`tp_richcompare` and
-   :attr:`tp_hash`: a subtypes inherits all three of :attr:`tp_compare`,
-   :attr:`tp_richcompare`, and :attr:`tp_hash` when the subtype's
-   :attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*.
+   Reserved slot, formerly known as tp_compare.
 
 
 .. cmember:: reprfunc PyTypeObject.tp_repr
@@ -329,14 +319,13 @@
    the Python level will result in the ``tp_hash`` slot being set to
    :cfunc:`PyObject_HashNotImplemented`.
 
-   When this field is not set, two possibilities exist: if the :attr:`tp_compare`
-   and :attr:`tp_richcompare` fields are both *NULL*, a default hash value based on
-   the object's address is returned; otherwise, a :exc:`TypeError` is raised.
-
-   This field is inherited by subtypes together with :attr:`tp_richcompare` and
-   :attr:`tp_compare`: a subtypes inherits all three of :attr:`tp_compare`,
-   :attr:`tp_richcompare`, and :attr:`tp_hash`, when the subtype's
-   :attr:`tp_compare`, :attr:`tp_richcompare` and :attr:`tp_hash` are all *NULL*.
+   When this field is not set, an attempt to take the hash of the
+   object raises :exc:`TypeError`.
+
+   This field is inherited by subtypes together with
+   :attr:`tp_richcompare`: a subtype inherits both of
+   :attr:`tp_richcompare` and :attr:`tp_hash`, when the subtype's
+   :attr:`tp_richcompare` and :attr:`tp_hash` are both *NULL*.
 
 
 .. cmember:: ternaryfunc PyTypeObject.tp_call
@@ -596,10 +585,10 @@
       comparisons makes sense (e.g. ``==`` and ``!=``, but not ``<`` and
       friends), directly raise :exc:`TypeError` in the rich comparison function.
 
-   This field is inherited by subtypes together with :attr:`tp_compare` and
-   :attr:`tp_hash`: a subtype inherits all three of :attr:`tp_compare`,
-   :attr:`tp_richcompare`, and :attr:`tp_hash`, when the subtype's
-   :attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*.
+   This field is inherited by subtypes together with :attr:`tp_hash`:
+   a subtype inherits :attr:`tp_richcompare` and :attr:`tp_hash` when
+   the subtype's :attr:`tp_richcompare` and :attr:`tp_hash` are both
+   *NULL*.
 
    The following constants are defined to be used as the third argument for
    :attr:`tp_richcompare` and for :cfunc:`PyObject_RichCompare`:

Modified: python/branches/io-c/Doc/documenting/markup.rst
==============================================================================
--- python/branches/io-c/Doc/documenting/markup.rst	(original)
+++ python/branches/io-c/Doc/documenting/markup.rst	Sun Feb  8 21:39:02 2009
@@ -290,10 +290,22 @@
 
 For all other roles, you have to write ``:rolename:`content```.
 
-.. note::
+There are some additional facilities that make cross-referencing roles more
+versatile:
 
-   For all cross-referencing roles, if you prefix the content with ``!``, no
-   reference/hyperlink will be created.
+* You may supply an explicit title and reference target, like in reST direct
+  hyperlinks: ``:role:`title <target>``` will refer to *target*, but the link
+  text will be *title*.
+
+* If you prefix the content with ``!``, no reference/hyperlink will be created.
+
+* For the Python object roles, if you prefix the content with ``~``, the link
+  text will only be the last component of the target.  For example,
+  ``:meth:`~Queue.Queue.get``` will refer to ``Queue.Queue.get`` but only
+  display ``get`` as the link text.
+
+  In HTML output, the link's ``title`` attribute (that is e.g. shown as a
+  tool-tip on mouse-hover) will always be the full target name.
 
 The following roles refer to objects in modules and are possibly hyperlinked if
 a matching identifier is found:

Modified: python/branches/io-c/Doc/extending/newtypes.rst
==============================================================================
--- python/branches/io-c/Doc/extending/newtypes.rst	(original)
+++ python/branches/io-c/Doc/extending/newtypes.rst	Sun Feb  8 21:39:02 2009
@@ -80,7 +80,7 @@
        0,                         /* tp_print */
        0,                         /* tp_getattr */
        0,                         /* tp_setattr */
-       0,                         /* tp_compare */
+       0,                         /* tp_reserved */
        0,                         /* tp_repr */
        0,                         /* tp_as_number */
        0,                         /* tp_as_sequence */
@@ -1484,10 +1484,10 @@
 comes with the source distribution of Python.
 
 In order to learn how to implement any specific method for your new data type,
-do the following: Download and unpack the Python source distribution.  Go the
-:file:`Objects` directory, then search the C source files for ``tp_`` plus the
-function you want (for example, ``tp_compare``).  You will find examples of the
-function you want to implement.
+do the following: Download and unpack the Python source distribution.  Go to
+the :file:`Objects` directory, then search the C source files for ``tp_`` plus
+the function you want (for example, ``tp_richcompare``).  You will find examples
+of the function you want to implement.
 
 When you need to verify that an object is an instance of the type you are
 implementing, use the :cfunc:`PyObject_TypeCheck` function. A sample of its use

Modified: python/branches/io-c/Doc/glossary.rst
==============================================================================
--- python/branches/io-c/Doc/glossary.rst	(original)
+++ python/branches/io-c/Doc/glossary.rst	Sun Feb  8 21:39:02 2009
@@ -393,7 +393,7 @@
       also :term:`immutable`.
 
    named tuple
-      Any tuple subclass whose indexable elements are also accessible using
+      Any tuple-like class whose indexable elements are also accessible using
       named attributes (for example, :func:`time.localtime` returns a
       tuple-like object where the *year* is accessible either with an
       index such as ``t[0]`` or with a named attribute like ``t.tm_year``).
@@ -484,7 +484,7 @@
       indices via the :meth:`__getitem__` special method and defines a
       :meth:`len` method that returns the length of the sequence.
       Some built-in sequence types are :class:`list`, :class:`str`,
-      :class:`tuple`, and :class:`unicode`. Note that :class:`dict` also
+      :class:`tuple`, and :class:`bytes`. Note that :class:`dict` also
       supports :meth:`__getitem__` and :meth:`__len__`, but is considered a
       mapping rather than a sequence because the lookups use arbitrary
       :term:`immutable` keys rather than integers.

Modified: python/branches/io-c/Doc/includes/noddy.c
==============================================================================
--- python/branches/io-c/Doc/includes/noddy.c	(original)
+++ python/branches/io-c/Doc/includes/noddy.c	Sun Feb  8 21:39:02 2009
@@ -14,7 +14,7 @@
     0,                         /* tp_print */
     0,                         /* tp_getattr */
     0,                         /* tp_setattr */
-    0,                         /* tp_compare */
+    0,                         /* tp_reserved */
     0,                         /* tp_repr */
     0,                         /* tp_as_number */
     0,                         /* tp_as_sequence */

Modified: python/branches/io-c/Doc/includes/noddy2.c
==============================================================================
--- python/branches/io-c/Doc/includes/noddy2.c	(original)
+++ python/branches/io-c/Doc/includes/noddy2.c	Sun Feb  8 21:39:02 2009
@@ -131,7 +131,7 @@
     0,                         /* tp_print */
     0,                         /* tp_getattr */
     0,                         /* tp_setattr */
-    0,                         /* tp_compare */
+    0,                         /* tp_reserved */
     0,                         /* tp_repr */
     0,                         /* tp_as_number */
     0,                         /* tp_as_sequence */

Modified: python/branches/io-c/Doc/includes/noddy3.c
==============================================================================
--- python/branches/io-c/Doc/includes/noddy3.c	(original)
+++ python/branches/io-c/Doc/includes/noddy3.c	Sun Feb  8 21:39:02 2009
@@ -184,7 +184,7 @@
     0,                         /* tp_print */
     0,                         /* tp_getattr */
     0,                         /* tp_setattr */
-    0,                         /* tp_compare */
+    0,                         /* tp_reserved */
     0,                         /* tp_repr */
     0,                         /* tp_as_number */
     0,                         /* tp_as_sequence */

Modified: python/branches/io-c/Doc/includes/noddy4.c
==============================================================================
--- python/branches/io-c/Doc/includes/noddy4.c	(original)
+++ python/branches/io-c/Doc/includes/noddy4.c	Sun Feb  8 21:39:02 2009
@@ -165,7 +165,7 @@
     0,                         /* tp_print */
     0,                         /* tp_getattr */
     0,                         /* tp_setattr */
-    0,                         /* tp_compare */
+    0,                         /* tp_reserved */
     0,                         /* tp_repr */
     0,                         /* tp_as_number */
     0,                         /* tp_as_sequence */

Modified: python/branches/io-c/Doc/includes/shoddy.c
==============================================================================
--- python/branches/io-c/Doc/includes/shoddy.c	(original)
+++ python/branches/io-c/Doc/includes/shoddy.c	Sun Feb  8 21:39:02 2009
@@ -39,7 +39,7 @@
     0,                       /* tp_print */
     0,                       /* tp_getattr */
     0,                       /* tp_setattr */
-    0,                       /* tp_compare */
+    0,                       /* tp_reserved */
     0,                       /* tp_repr */
     0,                       /* tp_as_number */
     0,                       /* tp_as_sequence */

Modified: python/branches/io-c/Doc/includes/sqlite3/collation_reverse.py
==============================================================================
--- python/branches/io-c/Doc/includes/sqlite3/collation_reverse.py	(original)
+++ python/branches/io-c/Doc/includes/sqlite3/collation_reverse.py	Sun Feb  8 21:39:02 2009
@@ -1,7 +1,12 @@
 import sqlite3
 
 def collate_reverse(string1, string2):
-    return -cmp(string1, string2)
+    if string1 == string2:
+        return 0
+    elif string1 < string2:
+        return 1
+    else:
+        return -1
 
 con = sqlite3.connect(":memory:")
 con.create_collation("reverse", collate_reverse)

Modified: python/branches/io-c/Doc/includes/typestruct.h
==============================================================================
--- python/branches/io-c/Doc/includes/typestruct.h	(original)
+++ python/branches/io-c/Doc/includes/typestruct.h	Sun Feb  8 21:39:02 2009
@@ -9,7 +9,7 @@
     printfunc tp_print;
     getattrfunc tp_getattr;
     setattrfunc tp_setattr;
-    cmpfunc tp_compare;
+    void *tp_reserved;
     reprfunc tp_repr;
 
     /* Method suites for standard classes */

Modified: python/branches/io-c/Doc/library/binascii.rst
==============================================================================
--- python/branches/io-c/Doc/library/binascii.rst	(original)
+++ python/branches/io-c/Doc/library/binascii.rst	Sun Feb  8 21:39:02 2009
@@ -120,11 +120,11 @@
    To generate the same numeric value across all Python versions and
    platforms use crc32(data) & 0xffffffff.  If you are only using
    the checksum in packed binary format this is not necessary as the
-   return value will have the correct 32bit binary representation
+   return value is the correct 32bit binary representation
    regardless of sign.
 
 .. versionchanged:: 3.0
-   The return value will always be unsigned and in the range [0, 2**32-1]
+   The return value is unsigned and in the range [0, 2**32-1]
    regardless of platform.
 
 

Modified: python/branches/io-c/Doc/library/collections.rst
==============================================================================
--- python/branches/io-c/Doc/library/collections.rst	(original)
+++ python/branches/io-c/Doc/library/collections.rst	Sun Feb  8 21:39:02 2009
@@ -45,31 +45,29 @@
 :class:`Callable`                                 ``__call__``
 
 :class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
-                           :class:`Iterable`,     and ``__len__``         ``index``, and ``count``
+                           :class:`Iterable`,                             ``index``, and ``count``
                            :class:`Container`
 
-:class:`MutableSequence`   :class:`Sequence`      ``__getitem__``         Inherited Sequence methods and
+:class:`MutableSequence`   :class:`Sequence`      ``__setitem__``         Inherited Sequence methods and
                                                   ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
-                                                  ``insert``,             ``remove``, and ``__iadd__``
-                                                  and ``__len__``
+                                                  and ``insert``          ``remove``, and ``__iadd__``
 
-:class:`Set`               :class:`Sized`,        ``__len__``,            ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
-                           :class:`Iterable`,     ``__iter__``, and       ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
-                           :class:`Container`     ``__contains__``        ``__sub__``, ``__xor__``, and ``isdisjoint``
+:class:`Set`               :class:`Sized`,                                ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
+                           :class:`Iterable`,                             ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
+                           :class:`Container`                             ``__sub__``, ``__xor__``, and ``isdisjoint``
 
 :class:`MutableSet`        :class:`Set`           ``add`` and             Inherited Set methods and
                                                   ``discard``             ``clear``, ``pop``, ``remove``, ``__ior__``,
                                                                           ``__iand__``, ``__ixor__``, and ``__isub__``
 
-:class:`Mapping`           :class:`Sized`,        ``__getitem__``,        ``__contains__``, ``keys``, ``items``, ``values``,
-                           :class:`Iterable`,     ``__len__``. and        ``get``, ``__eq__``, and ``__ne__``
-                           :class:`Container`     ``__iter__``
-
-:class:`MutableMapping`    :class:`Mapping`       ``__getitem__``         Inherited Mapping methods and
-                                                  ``__setitem__``,        ``pop``, ``popitem``, ``clear``, ``update``,
-                                                  ``__delitem__``,        and ``setdefault``
-                                                  ``__iter__``, and
-                                                  ``__len__``
+:class:`Mapping`           :class:`Sized`,        ``__getitem__``         ``__contains__``, ``keys``, ``items``, ``values``,
+                           :class:`Iterable`,                             ``get``, ``__eq__``, and ``__ne__``
+                           :class:`Container`
+
+:class:`MutableMapping`    :class:`Mapping`       ``__setitem__`` and     Inherited Mapping methods and
+                                                  ``__delitem__``         ``pop``, ``popitem``, ``clear``, ``update``,
+                                                                          and ``setdefault``
+
 
 :class:`MappingView`       :class:`Sized`                                 ``__len__``
 :class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
@@ -146,14 +144,14 @@
 A counter tool is provided to support convenient and rapid tallies.
 For example::
 
-    # Tally occurrences of words in a list
+    >>> # Tally occurrences of words in a list
     >>> cnt = Counter()
     >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
     ...     cnt[word] += 1
     >>> cnt
     Counter({'blue': 3, 'red': 2, 'green': 1})
 
-    # Find the ten most common words in Hamlet
+    >>> # Find the ten most common words in Hamlet
     >>> import re
     >>> words = re.findall('\w+', open('hamlet.txt').read().lower())
     >>> Counter(words).most_common(10)
@@ -208,7 +206,7 @@
    .. method:: most_common([n])
 
       Return a list of the *n* most common elements and their counts from the
-      most common to the least.  If *n* not specified, :func:`most_common`
+      most common to the least.  If *n* is not specified, :func:`most_common`
       returns *all* elements in the counter.  Elements with equal counts are
       ordered arbitrarily::
 
@@ -246,8 +244,8 @@
 contain repeated elements (with counts of one or more).  Addition and
 subtraction combine counters by adding or subtracting the counts of
 corresponding elements.  Intersection and union return the minimum and maximum
-of corresponding counts.  All four multiset operations exclude results with
-counts less than one::
+of corresponding counts.  Each operation can accept inputs with signed counts,
+but the output excludes results with counts less than one.
 
     >>> c = Counter(a=3, b=1)
     >>> d = Counter(a=1, b=2)

Modified: python/branches/io-c/Doc/library/ctypes.rst
==============================================================================
--- python/branches/io-c/Doc/library/ctypes.rst	(original)
+++ python/branches/io-c/Doc/library/ctypes.rst	Sun Feb  8 21:39:02 2009
@@ -1272,6 +1272,7 @@
 
 
 .. data:: find_library(name)
+   :module: ctypes.util
    :noindex:
 
    Try to find a library and return a pathname.  *name* is the library name without

Modified: python/branches/io-c/Doc/library/datetime.rst
==============================================================================
--- python/branches/io-c/Doc/library/datetime.rst	(original)
+++ python/branches/io-c/Doc/library/datetime.rst	Sun Feb  8 21:39:02 2009
@@ -1266,7 +1266,7 @@
 :class:`tzinfo` Objects
 -----------------------
 
-:class:`tzinfo` is an abstract base clase, meaning that this class should not be
+: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

Modified: python/branches/io-c/Doc/library/functions.rst
==============================================================================
--- python/branches/io-c/Doc/library/functions.rst	(original)
+++ python/branches/io-c/Doc/library/functions.rst	Sun Feb  8 21:39:02 2009
@@ -666,9 +666,14 @@
    Other common values are ``'w'`` for writing (truncating the file if it
    already exists), and ``'a'`` for appending (which on *some* Unix systems,
    means that *all* writes append to the end of the file regardless of the
-   current seek position).  In text mode, if *encoding* is not specified the
-   encoding used is platform dependent. (For reading and writing raw bytes use
-   binary mode and leave *encoding* unspecified.)  The available modes are:
+   current seek position).
+
+   In text mode, if *encoding* is not specified the encoding used is the same as
+   returned by :func:`locale.getpreferredencoding`, if the :mod:`locale` module
+   is available, else ASCII.  For reading and writing raw bytes, use binary mode
+   and leave *encoding* unspecified.
+
+   The available modes are:
 
    ========= ===============================================================
    Character Meaning

Modified: python/branches/io-c/Doc/library/importlib.rst
==============================================================================
--- python/branches/io-c/Doc/library/importlib.rst	(original)
+++ python/branches/io-c/Doc/library/importlib.rst	Sun Feb  8 21:39:02 2009
@@ -72,11 +72,15 @@
     import in absolute or relative terms
     (e.g. either ``pkg.mod`` or ``..mod``). If the name is
     specified in relative terms, then the *package* argument must be
-    specified to the package which is to act as the anchor for resolving the
+    set to the package which is to act as the anchor for resolving the
     package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
-    ``pkg.mod``). The specified module will be inserted into
-    :data:`sys.modules` and returned.
+    ``pkg.mod``).
 
+    The :func:`import_module` function acts as a simplifying wrapper around
+    :func:`__import__`. This means all semantics of the function are derived
+    from :func:`__import__`, including requiring the package where an import is
+    occuring from to already be imported (i.e., *package* must already be
+    imported).
 
 :mod:`importlib.machinery` -- Importers and path hooks
 ------------------------------------------------------

Modified: python/branches/io-c/Doc/library/itertools.rst
==============================================================================
--- python/branches/io-c/Doc/library/itertools.rst	(original)
+++ python/branches/io-c/Doc/library/itertools.rst	Sun Feb  8 21:39:02 2009
@@ -290,7 +290,7 @@
 
       class groupby(object):
           # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
-          # [(list(g)) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
+          # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
           def __init__(self, iterable, key=None):
               if key is None:
                   key = lambda x: x
@@ -591,8 +591,8 @@
        return map(function, count(start))
 
    def nth(iterable, n):
-       "Returns the nth item or empty list"
-       return list(islice(iterable, n, n+1))
+       "Returns the nth item or None"
+       return next(islice(iterable, n, None), None)
 
    def quantify(iterable, pred=bool):
        "Count how many times the predicate is true"
@@ -654,26 +654,26 @@
        s = list(iterable)
        return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
 
-    def unique_everseen(iterable, key=None):
-        "List unique elements, preserving order. Remember all elements ever seen."
-        # unique_everseen('AAAABBBCCDAABBB') --> A B C D
-        # unique_everseen('ABBCcAD', str.lower) --> A B C D
-        seen = set()
-        seen_add = seen.add
-        if key is None:
-            for element in iterable:
-                if element not in seen:
-                    seen_add(element)
-                    yield element
-        else:
-            for element in iterable:
-                k = key(element)
-                if k not in seen:
-                    seen_add(k)
-                    yield element
-
-    def unique_justseen(iterable, key=None):
-        "List unique elements, preserving order. Remember only the element just seen."
-        # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
-        # unique_justseen('ABBCcAD', str.lower) --> A B C A D
-        return map(next, map(itemgetter(1), groupby(iterable, key)))
+   def unique_everseen(iterable, key=None):
+       "List unique elements, preserving order. Remember all elements ever seen."
+       # unique_everseen('AAAABBBCCDAABBB') --> A B C D
+       # unique_everseen('ABBCcAD', str.lower) --> A B C D
+       seen = set()
+       seen_add = seen.add
+       if key is None:
+           for element in iterable:
+               if element not in seen:
+                   seen_add(element)
+                   yield element
+       else:
+           for element in iterable:
+               k = key(element)
+               if k not in seen:
+                   seen_add(k)
+                   yield element
+
+   def unique_justseen(iterable, key=None):
+       "List unique elements, preserving order. Remember only the element just seen."
+       # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
+       # unique_justseen('ABBCcAD', str.lower) --> A B C A D
+       return map(next, imap(itemgetter(1), groupby(iterable, key)))

Modified: python/branches/io-c/Doc/library/locale.rst
==============================================================================
--- python/branches/io-c/Doc/library/locale.rst	(original)
+++ python/branches/io-c/Doc/library/locale.rst	Sun Feb  8 21:39:02 2009
@@ -225,12 +225,11 @@
 
 .. function:: strxfrm(string)
 
-   .. index:: builtin: cmp
-
-   Transforms a string to one that can be used for the built-in function
-   :func:`cmp`, and still returns locale-aware results.  This function can be used
-   when the same string is compared repeatedly, e.g. when collating a sequence of
-   strings.
+   Transforms a string to one that can be used in locale-aware
+   comparisons.  For example, ``strxfrm(s1) < strxfrm(s2)`` is
+   equivalent to ``strcoll(s1, s2) < 0``.  This function can be used
+   when the same string is compared repeatedly, e.g. when collating a
+   sequence of strings.
 
 
 .. function:: format(format, val[, grouping[, monetary]])

Modified: python/branches/io-c/Doc/library/operator.rst
==============================================================================
--- python/branches/io-c/Doc/library/operator.rst	(original)
+++ python/branches/io-c/Doc/library/operator.rst	Sun Feb  8 21:39:02 2009
@@ -43,9 +43,9 @@
    equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
    b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
    ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
-   >= b``.  Note that unlike the built-in :func:`cmp`, these functions can
-   return any value, which may or may not be interpretable as a Boolean value.
-   See :ref:`comparisons` for more information about rich comparisons.
+   >= b``.  Note that these functions can return any value, which may
+   or may not be interpretable as a Boolean value.  See
+   :ref:`comparisons` for more information about rich comparisons.
 
 
 The logical operations are also generally applicable to all objects, and support

Modified: python/branches/io-c/Doc/library/optparse.rst
==============================================================================
--- python/branches/io-c/Doc/library/optparse.rst	(original)
+++ python/branches/io-c/Doc/library/optparse.rst	Sun Feb  8 21:39:02 2009
@@ -1506,7 +1506,7 @@
 records that the option was seen::
 
    def record_foo_seen(option, opt_str, value, parser):
-       parser.saw_foo = True
+       parser.values.saw_foo = True
 
    parser.add_option("--foo", action="callback", callback=record_foo_seen)
 
@@ -1646,7 +1646,7 @@
             value.append(arg)
 
         del parser.rargs[:len(value)]
-        setattr(parser.values, option.dest, value))
+        setattr(parser.values, option.dest, value)
 
    [...]
    parser.add_option("-c", "--callback", dest="vararg_attr",

Modified: python/branches/io-c/Doc/library/queue.rst
==============================================================================
--- python/branches/io-c/Doc/library/queue.rst	(original)
+++ python/branches/io-c/Doc/library/queue.rst	Sun Feb  8 21:39:02 2009
@@ -147,7 +147,7 @@
    q = Queue()
    for i in range(num_worker_threads):
         t = Thread(target=worker)
-        t.set_daemon(True)
+        t.daemon = True
         t.start()
 
    for item in source():

Modified: python/branches/io-c/Doc/library/runpy.rst
==============================================================================
--- python/branches/io-c/Doc/library/runpy.rst	(original)
+++ python/branches/io-c/Doc/library/runpy.rst	Sun Feb  8 21:39:02 2009
@@ -26,17 +26,22 @@
    mechanism (refer to PEP 302 for details) and then executed in a fresh module
    namespace.
 
+   If the supplied module name refers to a package rather than a normal module,
+   then that package is imported and the ``__main__`` submodule within that
+   package is then executed and the resulting module globals dictionary returned.
+
    The optional dictionary argument *init_globals* may be used to pre-populate the
    globals dictionary before the code is executed. The supplied dictionary will not
    be modified. If any of the special global variables below are defined in the
    supplied dictionary, those definitions are overridden by the ``run_module``
    function.
 
-   The special global variables ``__name__``, ``__file__``, ``__loader__`` and
-   ``__builtins__`` are set in the globals dictionary before the module code is
-   executed.
+   The special global variables ``__name__``, ``__file__``, ``__loader__``,
+   ``__builtins__`` and ``__package__`` are set in the globals dictionary before
+   the module code is executed.
 
-   ``__name__`` is set to *run_name* if this optional argument is supplied, and the
+   ``__name__`` is set to *run_name* if this optional argument is supplied, to
+   ``mod_name + '.__main__'`` if the named module is a package and to the
    *mod_name* argument otherwise.
 
    ``__loader__`` is set to the PEP 302 module loader used to retrieve the code for
@@ -48,6 +53,9 @@
    ``__builtins__`` is automatically initialised with a reference to the top level
    namespace of the :mod:`builtins` module.
 
+   ``__package__`` is set to *mod_name* if the named module is a package and to
+   ``mod_name.rpartition('.')[0]`` otherwise.
+
    If the argument *alter_sys* is supplied and evaluates to ``True``, then
    ``sys.argv[0]`` is updated with the value of ``__file__`` and
    ``sys.modules[__name__]`` is updated with a temporary module object for the
@@ -60,8 +68,15 @@
    function from threaded code.
 
 
+   .. versionchanged:: 3.1
+         Added ability to execute packages by looking for a ``__main__`` submodule
+
+
 .. seealso::
 
    :pep:`338` - Executing modules as scripts
-      PEP written and  implemented by Nick Coghlan.
+      PEP written and implemented by Nick Coghlan.
+
+   :pep:`366` - Main module explicit relative imports
+      PEP written and implemented by Nick Coghlan.
 

Modified: python/branches/io-c/Doc/library/shelve.rst
==============================================================================
--- python/branches/io-c/Doc/library/shelve.rst	(original)
+++ python/branches/io-c/Doc/library/shelve.rst	Sun Feb  8 21:39:02 2009
@@ -23,7 +23,7 @@
    database file is opened for reading and writing.  The optional *flag* parameter
    has the same interpretation as the *flag* parameter of :func:`dbm.open`.
 
-   By default, version 0 pickles are used to serialize values.  The version of the
+   By default, version 3 pickles are used to serialize values.  The version of the
    pickle protocol can be specified with the *protocol* parameter.
 
    By default, mutations to persistent-dictionary mutable entries are not

Modified: python/branches/io-c/Doc/library/sys.rst
==============================================================================
--- python/branches/io-c/Doc/library/sys.rst	(original)
+++ python/branches/io-c/Doc/library/sys.rst	Sun Feb  8 21:39:02 2009
@@ -769,8 +769,12 @@
    *micro*, *releaselevel*, and *serial*.  All values except *releaselevel* are
    integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
    ``'final'``.  The ``version_info`` value corresponding to the Python version 2.0
-   is ``(2, 0, 0, 'final', 0)``.
+   is ``(2, 0, 0, 'final', 0)``.  The components can also be accessed by name,
+   so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major``
+   and so on.
 
+   .. versionchanged:: 2.7
+      Added named component attributes
 
 .. data:: warnoptions
 

Modified: python/branches/io-c/Doc/library/threading.rst
==============================================================================
--- python/branches/io-c/Doc/library/threading.rst	(original)
+++ python/branches/io-c/Doc/library/threading.rst	Sun Feb  8 21:39:02 2009
@@ -198,7 +198,7 @@
 A thread can be flagged as a "daemon thread".  The significance of this flag is
 that the entire Python program exits when only daemon threads are left.  The
 initial value is inherited from the creating thread.  The flag can be set
-through the :attr:`daemon` attribute.
+through the :attr:`daemon` property.
 
 There is a "main thread" object; this corresponds to the initial thread of
 control in the Python program.  It is not a daemon thread.
@@ -312,10 +312,11 @@
 
 .. attribute:: Thread.daemon
 
-   The thread's daemon flag. This must be set before :meth:`start` is called,
-   otherwise :exc:`RuntimeError` is raised.
-
-   The initial value is inherited from the creating thread.
+   A boolean value indicating whether this thread is a daemon thread (True) or
+   not (False).  This must be set before :meth:`start` is called, otherwise
+   :exc:`RuntimeError` is raised.  Its initial value is inherited from the
+   creating thread; the main thread is not a daemon thread and therefore all
+   threads created in the main thread default to :attr:`daemon` = ``False``.
 
    The entire Python program exits when no alive non-daemon threads are left.
 

Modified: python/branches/io-c/Doc/library/tk.rst
==============================================================================
--- python/branches/io-c/Doc/library/tk.rst	(original)
+++ python/branches/io-c/Doc/library/tk.rst	Sun Feb  8 21:39:02 2009
@@ -12,8 +12,8 @@
 
 Tk/Tcl has long been an integral part of Python.  It provides a robust and
 platform independent windowing toolkit, that is available to Python programmers
-using the :mod:`tkinter` package, and its extension, the :mod:`tkinter.tix`
-module.
+using the :mod:`tkinter` package, and its extension, the :mod:`tkinter.tix` and
+the :mod:`tkinter.ttk` modules.
 
 The :mod:`tkinter` package is a thin object-oriented layer on top of Tcl/Tk. To
 use :mod:`tkinter`, you don't need to write Tcl code, but you will need to
@@ -33,6 +33,7 @@
 .. toctree::
 
    tkinter.rst
+   tkinter.ttk.rst
    tkinter.tix.rst
    tkinter.scrolledtext.rst
    turtle.rst

Modified: python/branches/io-c/Doc/library/unittest.rst
==============================================================================
--- python/branches/io-c/Doc/library/unittest.rst	(original)
+++ python/branches/io-c/Doc/library/unittest.rst	Sun Feb  8 21:39:02 2009
@@ -327,8 +327,9 @@
 ``WidgetTestCase.testResize``. :class:`TestLoader` uses the ``'test'`` method
 name prefix to identify test methods automatically.
 
-Note that the order in which the various test cases will be run is determined by
-sorting the test function names with the built-in :func:`cmp` function.
+Note that the order in which the various test cases will be run is
+determined by sorting the test function names with respect to the
+built-in ordering for strings.
 
 Often it is desirable to group suites of test cases together, so as to run tests
 for the whole system at once.  This is easy, since :class:`TestSuite` instances
@@ -921,9 +922,13 @@
 .. attribute:: TestLoader.sortTestMethodsUsing
 
    Function to be used to compare method names when sorting them in
-   :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
-   default value is the built-in :func:`cmp` function; the attribute can also be
-   set to :const:`None` to disable the sort.
+   :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
+   methods.  This should be a function that takes two arguments
+   ``self`` and ``other``, and returns ``-1`` if ``self`` precedes
+   ``other`` in the desired ordering, ``1`` if ``other`` precedes
+   ``self``, and ``0`` if ``self`` and ``other`` are equal.  The
+   default ordering is the built-in ordering for strings.  This
+   attribute can also be set to :const:`None` to disable the sort.
 
 
 .. attribute:: TestLoader.suiteClass

Modified: python/branches/io-c/Doc/library/zipimport.rst
==============================================================================
--- python/branches/io-c/Doc/library/zipimport.rst	(original)
+++ python/branches/io-c/Doc/library/zipimport.rst	Sun Feb  8 21:39:02 2009
@@ -88,6 +88,15 @@
       file wasn't found.
 
 
+   .. method:: get_filename(fullname)
+
+      Return the value ``__file__`` would be set to if the specified module
+      was imported. Raise :exc:`ZipImportError` if the module couldn't be
+      found.
+
+   .. versionadded:: 3.1
+
+
    .. method:: get_source(fullname)
 
       Return the source code for the specified module. Raise

Modified: python/branches/io-c/Doc/library/zlib.rst
==============================================================================
--- python/branches/io-c/Doc/library/zlib.rst	(original)
+++ python/branches/io-c/Doc/library/zlib.rst	Sun Feb  8 21:39:02 2009
@@ -48,11 +48,11 @@
    To generate the same numeric value across all Python versions and
    platforms use adler32(data) & 0xffffffff.  If you are only using
    the checksum in packed binary format this is not necessary as the
-   return value will have the correct 32bit binary representation
+   return value is the correct 32bit binary representation
    regardless of sign.
 
 .. versionchanged:: 3.0
-   The return value will always be unsigned and in the range [0, 2**32-1]
+   The return value is unsigned and in the range [0, 2**32-1]
    regardless of platform.
 
 
@@ -93,11 +93,11 @@
    To generate the same numeric value across all Python versions and
    platforms use crc32(data) & 0xffffffff.  If you are only using
    the checksum in packed binary format this is not necessary as the
-   return value will have the correct 32bit binary representation
+   return value is the correct 32bit binary representation
    regardless of sign.
 
 .. versionchanged:: 3.0
-   The return value will always be unsigned and in the range [0, 2**32-1]
+   The return value is unsigned and in the range [0, 2**32-1]
    regardless of platform.
 
 

Modified: python/branches/io-c/Doc/reference/datamodel.rst
==============================================================================
--- python/branches/io-c/Doc/reference/datamodel.rst	(original)
+++ python/branches/io-c/Doc/reference/datamodel.rst	Sun Feb  8 21:39:02 2009
@@ -1096,7 +1096,9 @@
       is printed to ``sys.stderr`` instead.  Also, when :meth:`__del__` is invoked in
       response to a module being deleted (e.g., when execution of the program is
       done), other globals referenced by the :meth:`__del__` method may already have
-      been deleted.  For this reason, :meth:`__del__` methods should do the absolute
+      been deleted or in the process of being torn down (e.g. the import
+      machinery shutting down).  For this reason, :meth:`__del__` methods
+      should do the absolute
       minimum needed to maintain external invariants.  Starting with version 1.5,
       Python guarantees that globals whose name begins with a single underscore are
       deleted from their module before other globals are deleted; if no other

Modified: python/branches/io-c/Doc/reference/executionmodel.rst
==============================================================================
--- python/branches/io-c/Doc/reference/executionmodel.rst	(original)
+++ python/branches/io-c/Doc/reference/executionmodel.rst	Sun Feb  8 21:39:02 2009
@@ -51,8 +51,8 @@
 within the defining one, unless a contained block introduces a different binding
 for the name.  The scope of names defined in a class block is limited to the
 class block; it does not extend to the code blocks of methods -- this includes
-generator expressions since they are implemented using a function scope.  This
-means that the following will fail::
+comprehensions and generator expressions since they are implemented using a
+function scope.  This means that the following will fail::
 
    class A:
        a = 42

Modified: python/branches/io-c/Doc/reference/expressions.rst
==============================================================================
--- python/branches/io-c/Doc/reference/expressions.rst	(original)
+++ python/branches/io-c/Doc/reference/expressions.rst	Sun Feb  8 21:39:02 2009
@@ -1022,8 +1022,8 @@
   length.
 
   If not equal, the sequences are ordered the same as their first differing
-  elements.  For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
-  ``cmp(x,y)``.  If the corresponding element does not exist, the shorter
+  elements.  For example, ``[1,2,x] <= [1,2,y]`` has the same value as
+  ``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,

Modified: python/branches/io-c/Doc/reference/simple_stmts.rst
==============================================================================
--- python/branches/io-c/Doc/reference/simple_stmts.rst	(original)
+++ python/branches/io-c/Doc/reference/simple_stmts.rst	Sun Feb  8 21:39:02 2009
@@ -441,14 +441,14 @@
 create a generator function instead of a normal function.
 When a generator function is called, it returns an iterator known as a generator
 iterator, or more commonly, a generator.  The body of the generator function is
-executed by calling the generator's :meth:`next` method repeatedly until it
-raises an exception.
+executed by calling the :func:`next` function on the generator repeatedly until
+it raises an exception.
 
 When a :keyword:`yield` statement is executed, the state of the generator is
 frozen and the value of :token:`expression_list` is returned to :meth:`next`'s
 caller.  By "frozen" we mean that all local state is retained, including the
 current bindings of local variables, the instruction pointer, and the internal
-evaluation stack: enough information is saved so that the next time :meth:`next`
+evaluation stack: enough information is saved so that the next time :func:`next`
 is invoked, the function can proceed exactly as if the :keyword:`yield`
 statement were just another external call.
 

Modified: python/branches/io-c/Doc/tools/sphinxext/download.html
==============================================================================
--- python/branches/io-c/Doc/tools/sphinxext/download.html	(original)
+++ python/branches/io-c/Doc/tools/sphinxext/download.html	Sun Feb  8 21:39:02 2009
@@ -31,7 +31,7 @@
     <td><a href="{{ dlbase }}/python-{{ release }}-docs-html.tar.bz2">Download</a> (ca. 4 MB)</td>
   </tr>
   <tr><td>Plain Text</td>
-    <td><a href="{{ dlbase }}/python-docs-text.zip">Download</a> (ca. 2 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.zip">Download</a> (ca. 2 MB)</td>
     <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.tar.bz2">Download</a> (ca. 1.5 MB)</td>
   </tr>
 </table>

Modified: python/branches/io-c/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/io-c/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/io-c/Doc/tools/sphinxext/pyspecific.py	Sun Feb  8 21:39:02 2009
@@ -13,6 +13,14 @@
 
 from docutils import nodes, utils
 
+# monkey-patch reST parser to disable alphabetic and roman enumerated lists
+from docutils.parsers.rst.states import Body
+Body.enum.converters['loweralpha'] = \
+    Body.enum.converters['upperalpha'] = \
+    Body.enum.converters['lowerroman'] = \
+    Body.enum.converters['upperroman'] = lambda x: None
+
+
 def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
     issue = utils.unescape(text)
     text = 'issue ' + issue

Modified: python/branches/io-c/Doc/tutorial/floatingpoint.rst
==============================================================================
--- python/branches/io-c/Doc/tutorial/floatingpoint.rst	(original)
+++ python/branches/io-c/Doc/tutorial/floatingpoint.rst	Sun Feb  8 21:39:02 2009
@@ -200,7 +200,7 @@
 machines today (November 2000) use IEEE-754 floating point arithmetic, and
 almost all platforms map Python floats to IEEE-754 "double precision".  754
 doubles contain 53 bits of precision, so on input the computer strives to
-convert 0.1 to the closest fraction it can of the form *J*/2\*\**N* where *J* is
+convert 0.1 to the closest fraction it can of the form *J*/2**\ *N* where *J* is
 an integer containing exactly 53 bits.  Rewriting ::
 
    1 / 10 ~= J / (2**N)

Modified: python/branches/io-c/Doc/tutorial/modules.rst
==============================================================================
--- python/branches/io-c/Doc/tutorial/modules.rst	(original)
+++ python/branches/io-c/Doc/tutorial/modules.rst	Sun Feb  8 21:39:02 2009
@@ -317,25 +317,25 @@
    >>> dir(builtins)
 
    ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Buffer
-   Error', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Excep
-   tion', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError
-   ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
-    'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImp
-   lemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecatio
-   nWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration',
-   'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
-    'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', '
-   UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueE
-   rror', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__'
-   , '__import__', '__name__', 'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'b
-   uffer', 'bytes', 'chr', 'chr8', 'classmethod', 'cmp', 'compile', 'complex', 'cop
-   yright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'ex
-   ec', 'exit', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'h
-   ash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', '
-   len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'o
-   bject', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr
-   ', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'st
-   r', 'str8', 'sum', 'super', 'trunc', 'tuple', 'type', 'vars', 'zip']
+   Error', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'Environme
+   ntError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'Generato
+   rExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexErr
+   or', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',
+    'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'P
+   endingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', '
+   StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'Ta
+   bError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'Unicod
+   eEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserW
+   arning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__deb
+   ug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any',
+   'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'chr', 'classmethod', 'compile', '
+   complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate
+   ', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr',
+   'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance',
+    'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memory
+   view', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property'
+   , 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sort
+   ed', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
 
 .. _tut-packages:
 

Modified: python/branches/io-c/Doc/using/cmdline.rst
==============================================================================
--- python/branches/io-c/Doc/using/cmdline.rst	(original)
+++ python/branches/io-c/Doc/using/cmdline.rst	Sun Feb  8 21:39:02 2009
@@ -78,6 +78,12 @@
    the implementation may not always enforce this (e.g. it may allow you to
    use a name that includes a hyphen).
 
+   Package names are also permitted. When a package name is supplied instead
+   of a normal module, the interpreter will execute ``<pkg>.__main__`` as
+   the main module. This behaviour is deliberately similar to the handling
+   of directories and zipfiles that are passed to the interpreter as the
+   script argument.
+
    .. note::
 
       This option cannot be used with builtin modules and extension modules
@@ -97,11 +103,14 @@
 
    .. seealso::
       :func:`runpy.run_module`
-         The actual implementation of this feature.
+         Equivalent functionality directly available to Python code
 
       :pep:`338` -- Executing modules as scripts
 
 
+   .. versionchanged:: 3.1
+      Supply the package name to run a ``__main__`` submodule.
+
 .. describe:: -
 
    Read commands from standard input (:data:`sys.stdin`).  If standard input is

Modified: python/branches/io-c/Doc/whatsnew/2.7.rst
==============================================================================
--- python/branches/io-c/Doc/whatsnew/2.7.rst	(original)
+++ python/branches/io-c/Doc/whatsnew/2.7.rst	Sun Feb  8 21:39:02 2009
@@ -6,6 +6,8 @@
 :Release: |release|
 :Date: |today|
 
+.. Fix accents on Kristjan Valur Jonsson, Fuerstenau.
+
 .. $Id$
    Rules for maintenance:
 
@@ -60,11 +62,6 @@
 .. ========================================================================
 
 
-Kristján Valur Jónsson, issue 4293
-Py_AddPendingCall is now thread safe.  This allows any worker thread
-to submit notifications to the python main thread.  This is particularly
-useful for asynchronous IO operations.
-
 
 Other Language Changes
 ======================
@@ -95,7 +92,19 @@
 Optimizations
 -------------
 
-To be written.
+A few performance enhancements have been added:
+
+* The garbage collector now performs better when many objects are
+  being allocated without deallocating any.  A full garbage collection
+  pass is only performed 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.  The second condition was added to reduce the number
+  of full garbage collections as the number of objects on the heap grows,
+  avoiding quadratic performance when allocating very many objects.
+  (Suggested by Martin von Loewis and implemented by Antoine Pitrou;
+  :issue:`4074`.)
+
 
 .. ======================================================================
 
@@ -108,6 +117,62 @@
 :file:`Misc/NEWS` file in the source tree for a more complete list of
 changes, or look through the Subversion logs for all the details.
 
+* It is not mandatory anymore to store clear text passwords in the
+  :file:`.pypirc` file when registering and uploading packages to PyPI. As long
+  as the username is present in that file, the :mod:`distutils` package will
+  prompt for the password if not present.  (Added by tarek, with the initial
+  contribution of Nathan Van Gheem; :issue:`4394`.)
+
+* The :mod:`bz2` module's :class:`BZ2File` now supports the context
+  management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
+  (Contributed by Hagen Fuerstenau; :issue:`3860`.)
+
+* A new :class:`Counter` class in the :mod:`collections` module is
+  useful for tallying data.  :class:`Counter` instances behave mostly
+  like dictionaries but return zero for missing keys instead of
+  raising a :exc:`KeyError`::
+
+    >>> from collections import Counter
+    >>> c=Counter()
+    >>> for letter in 'here is a sample of english text':
+    ...   c[letter] += 1
+    ...
+    >>> c
+    Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
+    'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
+    'p': 1, 'r': 1, 'x': 1})
+    >>> c['e']
+    5
+    >>> c['z']
+    0
+
+  There are two additional :class:`Counter` methods: :meth:`most_common`
+  returns the N most common elements and their counts, and :meth:`elements`
+  returns an iterator over the contained element, repeating each element
+  as many times as its count::
+
+    >>> c.most_common(5)
+    [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
+    >>> c.elements() ->
+       'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
+       'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
+       'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
+       's', 's', 'r', 't', 't', 'x']
+
+  Contributed by Raymond Hettinger; :issue:`1696199`.
+
+* The :mod:`gzip` module's :class:`GzipFile` now supports the context
+  management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``.
+  (Contributed by Hagen Fuerstenau; :issue:`3860`.)
+
+* The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
+  an invalid file descriptor.  (Implemented by Benjamin Peterson;
+  :issue:`4991`.)
+
+* The :mod:`pydoc` module now has help for the various symbols that Python
+  uses.  You can now do ``help('<<')`` or ``help('@')``, for example.
+  (Contributed by David Laban; :issue:`4739`.)
+
 * A new function in the :mod:`subprocess` module,
   :func:`check_output`, runs a command with a specified set of arguments
   and returns the command's output as a string if the command runs without
@@ -125,15 +190,30 @@
 
   (Contributed by Gregory P. Smith.)
 
-* It is not mandatory anymore to store clear text passwords in the
-  :file:`.pypirc` file when registering and uploading packages to PyPI. As long
-  as the username is present in that file, the :mod:`distutils` package will
-  prompt for the password if not present.  (Added by tarek, with the initial
-  contribution of Nathan Van Gheem; :issue:`4394`.)
+* The :func:`is_zipfile` function in the :mod:`zipfile` module will now
+  accept a file object, in addition to the path names accepted in earlier
+  versions.  (Contributed by Gabriel Genellina; :issue:`4756`.)
 
 .. ======================================================================
 .. whole new modules get described in subsections here
 
+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 a brief discussion and an example 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.
+
 .. ======================================================================
 
 
@@ -145,7 +225,13 @@
 * If you use the :file:`.gdbinit` file provided with Python,
   the "pyo" macro in the 2.7 version will now work when the thread being
   debugged doesn't hold the GIL; the macro will now acquire it before printing.
-  (Contributed by haypo XXX; :issue:`3632`.)
+  (Contributed by Victor Stinner; :issue:`3632`.)
+
+* :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`.)
+
 
 .. ======================================================================
 
@@ -157,7 +243,11 @@
   :data:`CRT_ASSEMBLY_VERSION`,
   :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
   and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
-  (Added by Martin von Loewis (XXX check); :issue:`4365`.)
+  (Contributed by David Cournapeau; :issue:`4365`.)
+
+* 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`.)
 
 .. ======================================================================
 

Modified: python/branches/io-c/Doc/whatsnew/3.0.rst
==============================================================================
--- python/branches/io-c/Doc/whatsnew/3.0.rst	(original)
+++ python/branches/io-c/Doc/whatsnew/3.0.rst	Sun Feb  8 21:39:02 2009
@@ -691,7 +691,7 @@
   idiom for handling all exceptions except for this latter category is
   to use :keyword:`except` :exc:`Exception`.
 
-* :exc:`StandardError` was removed (in 2.6 already).
+* :exc:`StandardError` was removed.
 
 * Exceptions no longer behave as sequences.  Use the :attr:`args`
   attribute instead.

Modified: python/branches/io-c/Include/abstract.h
==============================================================================
--- python/branches/io-c/Include/abstract.h	(original)
+++ python/branches/io-c/Include/abstract.h	Sun Feb  8 21:39:02 2009
@@ -228,29 +228,6 @@
        */
 #define  PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A),NULL)
 
-     PyAPI_FUNC(int) PyObject_Cmp(PyObject *o1, PyObject *o2, int *result);
-
-       /*
-	 Compare the values of o1 and o2 using a routine provided by
-	 o1, if one exists, otherwise with a routine provided by o2.
-	 The result of the comparison is returned in result.  Returns
-	 -1 on failure.  This is the equivalent of the Python
-	 statement: result=cmp(o1,o2).
-
-       */
-
-     /* Implemented elsewhere:
-
-     int PyObject_Compare(PyObject *o1, PyObject *o2);
-
-	 Compare the values of o1 and o2 using a routine provided by
-	 o1, if one exists, otherwise with a routine provided by o2.
-	 Returns the result of the comparison on success.  On error,
-	 the value returned is undefined. This is equivalent to the
-	 Python expression: cmp(o1,o2).
-
-       */
-
      /* Implemented elsewhere:
 
      PyObject *PyObject_Repr(PyObject *o);
@@ -415,7 +392,7 @@
        /*
          Guess the size of object o using len(o) or o.__length_hint__().
          If neither of those return a non-negative value, then return the
-         default value.  This function never fails. All exceptions are cleared.
+         default value.  If one of the calls fails, this function returns -1.
        */
 
      PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key);

Modified: python/branches/io-c/Include/code.h
==============================================================================
--- python/branches/io-c/Include/code.h	(original)
+++ python/branches/io-c/Include/code.h	Sun Feb  8 21:39:02 2009
@@ -20,7 +20,7 @@
     PyObject *co_varnames;	/* tuple of strings (local variable names) */
     PyObject *co_freevars;	/* tuple of strings (free variable names) */
     PyObject *co_cellvars;      /* tuple of strings (cell variable names) */
-    /* The rest doesn't count for hash/cmp */
+    /* The rest doesn't count for hash or comparisons */
     PyObject *co_filename;	/* unicode (where it was loaded from) */
     PyObject *co_name;		/* unicode (name, for reference) */
     int co_firstlineno;		/* first source line number */

Modified: python/branches/io-c/Include/object.h
==============================================================================
--- python/branches/io-c/Include/object.h	(original)
+++ python/branches/io-c/Include/object.h	Sun Feb  8 21:39:02 2009
@@ -274,7 +274,6 @@
 typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
 typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
 typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
-typedef int (*cmpfunc)(PyObject *, PyObject *);
 typedef PyObject *(*reprfunc)(PyObject *);
 typedef long (*hashfunc)(PyObject *);
 typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
@@ -297,7 +296,7 @@
 	printfunc tp_print;
 	getattrfunc tp_getattr;
 	setattrfunc tp_setattr;
-	cmpfunc tp_compare;
+	void *tp_reserved; /* formerly known as tp_compare */
 	reprfunc tp_repr;
 
 	/* Method suites for standard classes */
@@ -426,10 +425,8 @@
 PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
-PyAPI_FUNC(int) PyObject_Compare(PyObject *, PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
 PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
-PyAPI_FUNC(PyObject *) Py_CmpToRich(int op, int cmp);
 PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
 PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
 PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);

Modified: python/branches/io-c/Lib/_abcoll.py
==============================================================================
--- python/branches/io-c/Lib/_abcoll.py	(original)
+++ python/branches/io-c/Lib/_abcoll.py	Sun Feb  8 21:39:02 2009
@@ -301,7 +301,7 @@
         """Return the popped value.  Raise KeyError if empty."""
         it = iter(self)
         try:
-            value = it.__next__()
+            value = next(it)
         except StopIteration:
             raise KeyError
         self.discard(value)

Modified: python/branches/io-c/Lib/colorsys.py
==============================================================================
--- python/branches/io-c/Lib/colorsys.py	(original)
+++ python/branches/io-c/Lib/colorsys.py	Sun Feb  8 21:39:02 2009
@@ -44,12 +44,18 @@
     r = y + 0.948262*i + 0.624013*q
     g = y - 0.276066*i - 0.639810*q
     b = y - 1.105450*i + 1.729860*q
-    if r < 0.0: r = 0.0
-    if g < 0.0: g = 0.0
-    if b < 0.0: b = 0.0
-    if r > 1.0: r = 1.0
-    if g > 1.0: g = 1.0
-    if b > 1.0: b = 1.0
+    if r < 0.0:
+        r = 0.0
+    if g < 0.0:
+        g = 0.0
+    if b < 0.0:
+        b = 0.0
+    if r > 1.0:
+        r = 1.0
+    if g > 1.0:
+        g = 1.0
+    if b > 1.0:
+        b = 1.0
     return (r, g, b)
 
 
@@ -63,30 +69,42 @@
     minc = min(r, g, b)
     # XXX Can optimize (maxc+minc) and (maxc-minc)
     l = (minc+maxc)/2.0
-    if minc == maxc: return 0.0, l, 0.0
-    if l <= 0.5: s = (maxc-minc) / (maxc+minc)
-    else: s = (maxc-minc) / (2.0-maxc-minc)
+    if minc == maxc:
+        return 0.0, l, 0.0
+    if l <= 0.5:
+        s = (maxc-minc) / (maxc+minc)
+    else:
+        s = (maxc-minc) / (2.0-maxc-minc)
     rc = (maxc-r) / (maxc-minc)
     gc = (maxc-g) / (maxc-minc)
     bc = (maxc-b) / (maxc-minc)
-    if r == maxc: h = bc-gc
-    elif g == maxc: h = 2.0+rc-bc
-    else: h = 4.0+gc-rc
+    if r == maxc:
+        h = bc-gc
+    elif g == maxc:
+        h = 2.0+rc-bc
+    else:
+        h = 4.0+gc-rc
     h = (h/6.0) % 1.0
     return h, l, s
 
 def hls_to_rgb(h, l, s):
-    if s == 0.0: return l, l, l
-    if l <= 0.5: m2 = l * (1.0+s)
-    else: m2 = l+s-(l*s)
+    if s == 0.0:
+        return l, l, l
+    if l <= 0.5:
+        m2 = l * (1.0+s)
+    else:
+        m2 = l+s-(l*s)
     m1 = 2.0*l - m2
     return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD))
 
 def _v(m1, m2, hue):
     hue = hue % 1.0
-    if hue < ONE_SIXTH: return m1 + (m2-m1)*hue*6.0
-    if hue < 0.5: return m2
-    if hue < TWO_THIRD: return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0
+    if hue < ONE_SIXTH:
+        return m1 + (m2-m1)*hue*6.0
+    if hue < 0.5:
+        return m2
+    if hue < TWO_THIRD:
+        return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0
     return m1
 
 
@@ -99,29 +117,40 @@
     maxc = max(r, g, b)
     minc = min(r, g, b)
     v = maxc
-    if minc == maxc: return 0.0, 0.0, v
+    if minc == maxc:
+        return 0.0, 0.0, v
     s = (maxc-minc) / maxc
     rc = (maxc-r) / (maxc-minc)
     gc = (maxc-g) / (maxc-minc)
     bc = (maxc-b) / (maxc-minc)
-    if r == maxc: h = bc-gc
-    elif g == maxc: h = 2.0+rc-bc
-    else: h = 4.0+gc-rc
+    if r == maxc:
+        h = bc-gc
+    elif g == maxc:
+        h = 2.0+rc-bc
+    else:
+        h = 4.0+gc-rc
     h = (h/6.0) % 1.0
     return h, s, v
 
 def hsv_to_rgb(h, s, v):
-    if s == 0.0: return v, v, v
+    if s == 0.0:
+        return v, v, v
     i = int(h*6.0) # XXX assume int() truncates!
     f = (h*6.0) - i
     p = v*(1.0 - s)
     q = v*(1.0 - s*f)
     t = v*(1.0 - s*(1.0-f))
     i = i%6
-    if i == 0: return v, t, p
-    if i == 1: return q, v, p
-    if i == 2: return p, v, t
-    if i == 3: return p, q, v
-    if i == 4: return t, p, v
-    if i == 5: return v, p, q
+    if i == 0:
+        return v, t, p
+    if i == 1:
+        return q, v, p
+    if i == 2:
+        return p, v, t
+    if i == 3:
+        return p, q, v
+    if i == 4:
+        return t, p, v
+    if i == 5:
+        return v, p, q
     # Cannot get here

Modified: python/branches/io-c/Lib/decimal.py
==============================================================================
--- python/branches/io-c/Lib/decimal.py	(original)
+++ python/branches/io-c/Lib/decimal.py	Sun Feb  8 21:39:02 2009
@@ -136,6 +136,7 @@
 
 import copy as _copy
 import math as _math
+import numbers as _numbers
 
 try:
     from collections import namedtuple as _namedtuple
@@ -3695,6 +3696,12 @@
 
     return self
 
+# Register Decimal as a kind of Number (an abstract base class).
+# However, do not register it as Real (because Decimals are not
+# interoperable with floats).
+_numbers.Number.register(Decimal)
+
+
 ##### Context class #######################################################
 
 

Modified: python/branches/io-c/Lib/distutils/README
==============================================================================
--- python/branches/io-c/Lib/distutils/README	(original)
+++ python/branches/io-c/Lib/distutils/README	Sun Feb  8 21:39:02 2009
@@ -1,22 +1,11 @@
-This directory contains only a subset of the Distutils, specifically
-the Python modules in the 'distutils' and 'distutils.command'
-packages.  This is all you need to distribute and install Python
-modules using the Distutils.  There is also a separately packaged
-standalone version of the Distutils available for people who want to
-upgrade the Distutils without upgrading Python, available from the
-Distutils web page:
+This directory contains the Distutils package.
 
-    http://www.python.org/sigs/distutils-sig/
+There's a full documentation available at:
 
-The standalone version includes all of the code in this directory,
-plus documentation, test scripts, examples, etc.
+    http://docs.python.org/distutils/
 
-The Distutils documentation is divided into two documents, "Installing
-Python Modules", which explains how to install Python packages, and
-"Distributing Python Modules", which explains how to write setup.py
-files.  Both documents are part of the standard Python documentation
-set, and are available from http://www.python.org/doc/current/ .
+The Distutils-SIG web page is also a good starting point:
 
-        Greg Ward (gward at python.net)
+    http://www.python.org/sigs/distutils-sig/
 
 $Id$

Modified: python/branches/io-c/Lib/distutils/__init__.py
==============================================================================
--- python/branches/io-c/Lib/distutils/__init__.py	(original)
+++ python/branches/io-c/Lib/distutils/__init__.py	Sun Feb  8 21:39:02 2009
@@ -12,13 +12,8 @@
 
 # Distutils version
 #
-# Please coordinate with Marc-Andre Lemburg <mal at egenix.com> when adding
-# new features to distutils that would warrant bumping the version number.
+# Updated automatically by the Python release process.
 #
-# In general, major and minor version should loosely follow the Python
-# version number the distutils code was shipped with.
-#
-
 #--start constants--
 __version__ = "3.1a0"
 #--end constants--

Modified: python/branches/io-c/Lib/distutils/cmd.py
==============================================================================
--- python/branches/io-c/Lib/distutils/cmd.py	(original)
+++ python/branches/io-c/Lib/distutils/cmd.py	Sun Feb  8 21:39:02 2009
@@ -7,7 +7,7 @@
 __revision__ = "$Id$"
 
 import sys, os, re
-from distutils.errors import *
+from distutils.errors import DistutilsOptionError
 from distutils import util, dir_util, file_util, archive_util, dep_util
 from distutils import log
 
@@ -155,15 +155,15 @@
         from distutils.fancy_getopt import longopt_xlate
         if header is None:
             header = "command options for '%s':" % self.get_command_name()
-        print(indent + header)
+        self.announce(indent + header, level=log.INFO)
         indent = indent + "  "
         for (option, _, _) in self.user_options:
             option = longopt_xlate(option)
             if option[-1] == "=":
                 option = option[:-1]
             value = getattr(self, option)
-            print(indent + "%s = %s" % (option, value))
-
+            self.announce(indent + "%s = %s" % (option, value),
+                          level=log.INFO)
 
     def run(self):
         """A command's raison d'etre: carry out the action it exists to
@@ -383,12 +383,9 @@
         and it is true, then the command is unconditionally run -- does no
         timestamp checks.
         """
-        if exec_msg is None:
-            exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles))
         if skip_msg is None:
             skip_msg = "skipping %s (inputs unchanged)" % outfile
 
-
         # Allow 'infiles' to be a single string
         if isinstance(infiles, str):
             infiles = (infiles,)
@@ -396,10 +393,13 @@
             raise TypeError(
                   "'infiles' must be a string, or a list or tuple of strings")
 
+        if exec_msg is None:
+            exec_msg = "generating %s from %s" % (outfile, ', '.join(infiles))
+
         # If 'outfile' must be regenerated (either because it doesn't
         # exist, is out-of-date, or the 'force' flag is true) then
         # perform the action that presumably regenerates it
-        if self.force or dep_util.newer_group (infiles, outfile):
+        if self.force or dep_util.newer_group(infiles, outfile):
             self.execute(func, args, exec_msg, level)
         # Otherwise, print the "skip" message
         else:

Modified: python/branches/io-c/Lib/distutils/command/build_ext.py
==============================================================================
--- python/branches/io-c/Lib/distutils/command/build_ext.py	(original)
+++ python/branches/io-c/Lib/distutils/command/build_ext.py	Sun Feb  8 21:39:02 2009
@@ -229,10 +229,12 @@
                 # building python standard extensions
                 self.library_dirs.append('.')
 
-        # for extensions under Linux with a shared Python library,
+        # for extensions under Linux or Solaris with a shared Python library,
         # Python's library directory must be appended to library_dirs
-        if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \
-                and sysconfig.get_config_var('Py_ENABLE_SHARED'):
+        sysconfig.get_config_var('Py_ENABLE_SHARED')
+        if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')
+             or sys.platform.startswith('sunos'))
+            and sysconfig.get_config_var('Py_ENABLE_SHARED')):
             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
                 # building third party extensions
                 self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))

Modified: python/branches/io-c/Lib/distutils/command/install_lib.py
==============================================================================
--- python/branches/io-c/Lib/distutils/command/install_lib.py	(original)
+++ python/branches/io-c/Lib/distutils/command/install_lib.py	Sun Feb  8 21:39:02 2009
@@ -1,3 +1,8 @@
+"""distutils.command.install_lib
+
+Implements the Distutils 'install_lib' command
+(install all Python modules)."""
+
 __revision__ = "$Id$"
 
 import sys, os

Modified: python/branches/io-c/Lib/distutils/command/wininst-9.0-amd64.exe
==============================================================================
Binary files. No diff available.

Modified: python/branches/io-c/Lib/distutils/command/wininst-9.0.exe
==============================================================================
Binary files. No diff available.

Modified: python/branches/io-c/Lib/distutils/dir_util.py
==============================================================================
--- python/branches/io-c/Lib/distutils/dir_util.py	(original)
+++ python/branches/io-c/Lib/distutils/dir_util.py	Sun Feb  8 21:39:02 2009
@@ -15,7 +15,7 @@
 # I don't use os.makedirs because a) it's new to Python 1.5.2, and
 # b) it blows up if the directory already exists (I want to silently
 # succeed in that case).
-def mkpath (name, mode=0o777, verbose=0, dry_run=0):
+def mkpath (name, mode=0o777, verbose=1, dry_run=0):
     """Create a directory and any missing ancestor directories.  If the
        directory already exists (or if 'name' is the empty string, which
        means the current directory, which of course exists), then do
@@ -48,13 +48,9 @@
     tails = [tail]                      # stack of lone dirs to create
 
     while head and tail and not os.path.isdir(head):
-        #print "splitting '%s': " % head,
         (head, tail) = os.path.split(head)
-        #print "to ('%s','%s')" % (head, tail)
         tails.insert(0, tail)          # push next higher dir onto stack
 
-    #print "stack of tails:", tails
-
     # now 'head' contains the deepest directory that already exists
     # (that is, the child of 'head' in 'name' is the highest directory
     # that does *not* exist)
@@ -66,7 +62,8 @@
         if _path_created.get(abs_head):
             continue
 
-        log.info("creating %s", head)
+        if verbose >= 1:
+            log.info("creating %s", head)
 
         if not dry_run:
             try:
@@ -82,7 +79,7 @@
 # mkpath ()
 
 
-def create_tree (base_dir, files, mode=0o777, verbose=0, dry_run=0):
+def create_tree (base_dir, files, mode=0o777, verbose=1, dry_run=0):
 
     """Create all the empty directories under 'base_dir' needed to
        put 'files' there.  'base_dir' is just the a name of a directory
@@ -99,7 +96,7 @@
 
     # Now create them
     for dir in sorted(need_dir):
-        mkpath(dir, mode, dry_run=dry_run)
+        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
 
 # create_tree ()
 
@@ -109,7 +106,7 @@
                preserve_times=1,
                preserve_symlinks=0,
                update=0,
-               verbose=0,
+               verbose=1,
                dry_run=0):
 
     """Copy an entire directory tree 'src' to a new location 'dst'.  Both
@@ -146,7 +143,7 @@
                   "error listing files in '%s': %s" % (src, errstr))
 
     if not dry_run:
-        mkpath(dst)
+        mkpath(dst, verbose=verbose)
 
     outputs = []
 
@@ -156,7 +153,8 @@
 
         if preserve_symlinks and os.path.islink(src_name):
             link_dest = os.readlink(src_name)
-            log.info("linking %s -> %s", dst_name, link_dest)
+            if verbose >= 1:
+                log.info("linking %s -> %s", dst_name, link_dest)
             if not dry_run:
                 os.symlink(link_dest, dst_name)
             outputs.append(dst_name)
@@ -165,10 +163,11 @@
             outputs.extend(
                 copy_tree(src_name, dst_name, preserve_mode,
                           preserve_times, preserve_symlinks, update,
-                          dry_run=dry_run))
+                          verbose=verbose, dry_run=dry_run))
         else:
             copy_file(src_name, dst_name, preserve_mode,
-                      preserve_times, update, dry_run=dry_run)
+                      preserve_times, update, verbose=verbose,
+                      dry_run=dry_run)
             outputs.append(dst_name)
 
     return outputs
@@ -184,14 +183,15 @@
     cmdtuples.append((os.rmdir, path))
 
 
-def remove_tree (directory, verbose=0, dry_run=0):
+def remove_tree (directory, verbose=1, dry_run=0):
     """Recursively remove an entire directory tree.  Any errors are ignored
     (apart from being reported to stdout if 'verbose' is true).
     """
     from distutils.util import grok_environment_error
     global _path_created
 
-    log.info("removing '%s' (and everything under it)", directory)
+    if verbose >= 1:
+        log.info("removing '%s' (and everything under it)", directory)
     if dry_run:
         return
     cmdtuples = []

Modified: python/branches/io-c/Lib/distutils/file_util.py
==============================================================================
--- python/branches/io-c/Lib/distutils/file_util.py	(original)
+++ python/branches/io-c/Lib/distutils/file_util.py	Sun Feb  8 21:39:02 2009
@@ -67,7 +67,7 @@
             fsrc.close()
 
 def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
-              link=None, verbose=0, dry_run=0):
+              link=None, verbose=1, dry_run=0):
     """Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is
     copied there with the same name; otherwise, it must be a filename.  (If
     the file exists, it will be ruthlessly clobbered.)  If 'preserve_mode'
@@ -112,17 +112,20 @@
         dir = os.path.dirname(dst)
 
     if update and not newer(src, dst):
-        log.debug("not copying %s (output up-to-date)", src)
+        if verbose >= 1:
+            log.debug("not copying %s (output up-to-date)", src)
         return (dst, 0)
 
     try:
         action = _copy_action[link]
     except KeyError:
         raise ValueError("invalid value '%s' for 'link' argument" % link)
-    if os.path.basename(dst) == os.path.basename(src):
-        log.info("%s %s -> %s", action, src, dir)
-    else:
-        log.info("%s %s -> %s", action, src, dst)
+
+    if verbose >= 1:
+        if os.path.basename(dst) == os.path.basename(src):
+            log.info("%s %s -> %s", action, src, dir)
+        else:
+            log.info("%s %s -> %s", action, src, dst)
 
     if dry_run:
         return (dst, 1)
@@ -164,7 +167,7 @@
 
 # XXX I suspect this is Unix-specific -- need porting help!
 def move_file (src, dst,
-               verbose=0,
+               verbose=1,
                dry_run=0):
 
     """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
@@ -177,7 +180,8 @@
     from os.path import exists, isfile, isdir, basename, dirname
     import errno
 
-    log.info("moving %s -> %s", src, dst)
+    if verbose >= 1:
+        log.info("moving %s -> %s", src, dst)
 
     if dry_run:
         return dst
@@ -209,7 +213,7 @@
                   "couldn't move '%s' to '%s': %s" % (src, dst, msg))
 
     if copy_it:
-        copy_file(src, dst)
+        copy_file(src, dst, verbose=verbose)
         try:
             os.unlink(src)
         except os.error as e:

Modified: python/branches/io-c/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/io-c/Lib/distutils/sysconfig.py	(original)
+++ python/branches/io-c/Lib/distutils/sysconfig.py	Sun Feb  8 21:39:02 2009
@@ -72,14 +72,17 @@
         prefix = plat_specific and EXEC_PREFIX or PREFIX
     if os.name == "posix":
         if python_build:
+            # Assume the executable is in the build directory.  The
+            # pyconfig.h file should be in the same directory.  Since
+            # the build directory may not be the source directory, we
+            # must use "srcdir" from the makefile to find the "Include"
+            # directory.
             base = os.path.dirname(os.path.abspath(sys.executable))
             if plat_specific:
-                inc_dir = base
+                return base
             else:
-                inc_dir = os.path.join(base, "Include")
-                if not os.path.exists(inc_dir):
-                    inc_dir = os.path.join(os.path.dirname(base), "Include")
-            return inc_dir
+                incdir = os.path.join(get_config_var('srcdir'), 'Include')
+                return os.path.normpath(incdir)
         return os.path.join(prefix, "include", "python" + get_python_version())
     elif os.name == "nt":
         return os.path.join(prefix, "include")
@@ -157,9 +160,9 @@
     varies across Unices and is stored in Python's Makefile.
     """
     if compiler.compiler_type == "unix":
-        (cc, cxx, opt, cflags, ccshared, ldshared, so_ext) = \
+        (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar) = \
             get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
-                            'CCSHARED', 'LDSHARED', 'SO')
+                            'CCSHARED', 'LDSHARED', 'SO', 'AR')
 
         if 'CC' in os.environ:
             cc = os.environ['CC']
@@ -180,6 +183,8 @@
             cpp = cpp + ' ' + os.environ['CPPFLAGS']
             cflags = cflags + ' ' + os.environ['CPPFLAGS']
             ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
+        if 'AR' in os.environ:
+            ar = os.environ['AR']
 
         cc_cmd = cc + ' ' + cflags
         compiler.set_executables(
@@ -188,7 +193,8 @@
             compiler_so=cc_cmd + ' ' + ccshared,
             compiler_cxx=cxx,
             linker_so=ldshared,
-            linker_exe=cc)
+            linker_exe=cc,
+            archiver=ar)
 
         compiler.shared_lib_extension = so_ext
 
@@ -498,6 +504,20 @@
         _config_vars['prefix'] = PREFIX
         _config_vars['exec_prefix'] = EXEC_PREFIX
 
+        # Convert srcdir into an absolute path if it appears necessary.
+        # Normally it is relative to the build directory.  However, during
+        # testing, for example, we might be running a non-installed python
+        # from a different directory.
+        if python_build and os.name == "posix":
+            base = os.path.dirname(os.path.abspath(sys.executable))
+            if (not os.path.isabs(_config_vars['srcdir']) and
+                base != os.getcwd()):
+                # srcdir is relative and we are not in the same directory
+                # as the executable. Assume executable is in the build
+                # directory and make srcdir absolute.
+                srcdir = os.path.join(base, _config_vars['srcdir'])
+                _config_vars['srcdir'] = os.path.normpath(srcdir)
+
         if sys.platform == 'darwin':
             kernel_version = os.uname()[2] # Kernel version (8.4.3)
             major_version = int(kernel_version.split('.')[0])

Modified: python/branches/io-c/Lib/distutils/tests/test_build_ext.py
==============================================================================
--- python/branches/io-c/Lib/distutils/tests/test_build_ext.py	(original)
+++ python/branches/io-c/Lib/distutils/tests/test_build_ext.py	Sun Feb  8 21:39:02 2009
@@ -15,6 +15,10 @@
 # Don't load the xx module more than once.
 ALREADY_TESTED = False
 
+def _get_source_filename():
+    srcdir = sysconfig.get_config_var('srcdir')
+    return os.path.join(srcdir, 'Modules', 'xxmodule.c')
+
 class BuildExtTestCase(unittest.TestCase):
     def setUp(self):
         # Create a simple test environment
@@ -22,9 +26,7 @@
         self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_")
         self.sys_path = sys.path[:]
         sys.path.append(self.tmp_dir)
-
-        xx_c = os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')
-        shutil.copy(xx_c, self.tmp_dir)
+        shutil.copy(_get_source_filename(), self.tmp_dir)
 
     def test_build_ext(self):
         global ALREADY_TESTED
@@ -75,10 +77,33 @@
         # XXX on Windows the test leaves a directory with xx module in TEMP
         shutil.rmtree(self.tmp_dir, os.name == 'nt' or sys.platform == 'cygwin')
 
+    def test_solaris_enable_shared(self):
+        dist = Distribution({'name': 'xx'})
+        cmd = build_ext(dist)
+        old = sys.platform
+
+        sys.platform = 'sunos' # fooling finalize_options
+        from distutils.sysconfig import  _config_vars
+        old_var = _config_vars.get('Py_ENABLE_SHARED')
+        _config_vars['Py_ENABLE_SHARED'] = 1
+        try:
+            cmd.ensure_finalized()
+        finally:
+            sys.platform = old
+            if old_var is None:
+                del _config_vars['Py_ENABLE_SHARED']
+            else:
+                _config_vars['Py_ENABLE_SHARED'] = old_var
+
+        # make sur we get some lobrary dirs under solaris
+        self.assert_(len(cmd.library_dirs) > 0)
+
 def test_suite():
-    if not sysconfig.python_build:
+    src = _get_source_filename()
+    if not os.path.exists(src):
         if support.verbose:
-            print('test_build_ext: The test must be run in a python build dir')
+            print('test_build_ext: Cannot find source code (test'
+                  ' must run in python build dir)')
         return unittest.TestSuite()
     else: return unittest.makeSuite(BuildExtTestCase)
 

Modified: python/branches/io-c/Lib/distutils/tests/test_sdist.py
==============================================================================
--- python/branches/io-c/Lib/distutils/tests/test_sdist.py	(original)
+++ python/branches/io-c/Lib/distutils/tests/test_sdist.py	Sun Feb  8 21:39:02 2009
@@ -10,7 +10,7 @@
 from distutils.core import Distribution
 from distutils.tests.test_config import PyPIRCCommandTestCase
 from distutils.errors import DistutilsExecError
-from distutils.spawn import spawn
+from distutils.spawn import find_executable
 
 CURDIR = os.path.dirname(__file__)
 TEMP_PKG = join(CURDIR, 'temppkg')
@@ -111,15 +111,12 @@
 
     def test_make_distribution(self):
 
-        self._init_tmp_pkg()
+        # check if tar and gzip are installed
+        if (find_executable('tar') is None or
+            find_executable('gzip') is None):
+            return
 
-        # check if tar is installed under win32
-        if sys.platform == 'win32':
-            try:
-                spawn('tar --help')
-            except DistutilsExecError:
-                # let's return, no need to go further
-                return
+        self._init_tmp_pkg()
 
         # now building a sdist
         dist = Distribution()

Modified: python/branches/io-c/Lib/distutils/tests/test_sysconfig.py
==============================================================================
--- python/branches/io-c/Lib/distutils/tests/test_sysconfig.py	(original)
+++ python/branches/io-c/Lib/distutils/tests/test_sysconfig.py	Sun Feb  8 21:39:02 2009
@@ -1,6 +1,8 @@
 """Tests for distutils.dist."""
 
 from distutils import sysconfig
+from distutils.ccompiler import get_default_compiler
+
 import os
 import unittest
 
@@ -8,6 +10,13 @@
 
 class SysconfigTestCase(unittest.TestCase):
 
+    def setUp(self):
+        self.old_AR = os.environ.get('AR')
+
+    def tearDown(self):
+        if self.old_AR is not None:
+            os.environ['AR'] = self.old_AR
+
     def test_get_config_h_filename(self):
         config_h = sysconfig.get_config_h_filename()
         self.assert_(os.path.isfile(config_h), config_h)
@@ -19,27 +28,10 @@
         # test for pythonxx.lib?
 
     def test_get_python_inc(self):
-        # The check for srcdir is copied from Python's setup.py,
-        # and is necessary to make this test pass when building
-        # Python in a directory other than the source directory.
-        (srcdir,) = sysconfig.get_config_vars('srcdir')
-        if not srcdir:
-            inc_dir = sysconfig.get_python_inc()
-        else:
-            # This test is not really a proper test: when building
-            # Python from source, even in the same directory,
-            # we won't be testing the same thing as when running
-            # distutils' tests on an installed Python. Nevertheless,
-            # let's try to do our best: if we are running Python's
-            # unittests from a build directory that is not the source
-            # directory, the normal inc_dir will exist, it will just not
-            # contain anything of interest.
-            inc_dir = sysconfig.get_python_inc()
-            self.assert_(os.path.isdir(inc_dir))
-            # Now test the source location, to make sure Python.h does
-            # exist.
-            inc_dir = os.path.join(os.getcwd(), srcdir, 'Include')
-            inc_dir = os.path.normpath(inc_dir)
+        inc_dir = sysconfig.get_python_inc()
+        # This is not much of a test.  We make sure Python.h exists
+        # in the directory returned by get_python_inc() but we don't know
+        # it is the correct file.
         self.assert_(os.path.isdir(inc_dir), inc_dir)
         python_h = os.path.join(inc_dir, "Python.h")
         self.assert_(os.path.isfile(python_h), python_h)
@@ -49,6 +41,25 @@
         self.assert_(isinstance(cvars, dict))
         self.assert_(cvars)
 
+    def test_customize_compiler(self):
+
+        # not testing if default compiler is not unix
+        if get_default_compiler() != 'unix':
+            return
+
+        os.environ['AR'] = 'xxx'
+
+        # make sure AR gets caught
+        class compiler:
+            compiler_type = 'unix'
+
+            def set_executables(self, **kw):
+                self.exes = kw
+
+        comp = compiler()
+        sysconfig.customize_compiler(comp)
+        self.assertEquals(comp.exes['archiver'], 'xxx')
+
 
 def test_suite():
     suite = unittest.TestSuite()

Modified: python/branches/io-c/Lib/heapq.py
==============================================================================
--- python/branches/io-c/Lib/heapq.py	(original)
+++ python/branches/io-c/Lib/heapq.py	Sun Feb  8 21:39:02 2009
@@ -195,7 +195,7 @@
     heapify(result)
     _heappushpop = heappushpop
     for elem in it:
-        heappushpop(result, elem)
+        _heappushpop(result, elem)
     result.sort(reverse=True)
     return result
 

Modified: python/branches/io-c/Lib/http/client.py
==============================================================================
--- python/branches/io-c/Lib/http/client.py	(original)
+++ python/branches/io-c/Lib/http/client.py	Sun Feb  8 21:39:02 2009
@@ -265,14 +265,14 @@
     # accepts iso-8859-1.
 
     def __init__(self, sock, debuglevel=0, strict=0, method=None):
-        # XXX If the response includes a content-length header, we
+        # If the response includes a content-length header, we
         # need to make sure that the client doesn't read more than the
         # specified number of bytes.  If it does, it will block until
         # the server times out and closes the connection.  (The only
-        # applies to HTTP/1.1 connections.)  Since some clients access
-        # self.fp directly rather than calling read(), this is a little
-        # tricky.
-        self.fp = sock.makefile("rb", 0)
+        # applies to HTTP/1.1 connections.)  This will happen if a self.fp.read()
+        # is done (without a size) whether self.fp is buffered or not.
+        # So, no self.fp.read() by clients unless they know what they are doing.
+        self.fp = sock.makefile("rb")
         self.debuglevel = debuglevel
         self.strict = strict
         self._method = method

Modified: python/branches/io-c/Lib/importlib/NOTES
==============================================================================
--- python/branches/io-c/Lib/importlib/NOTES	(original)
+++ python/branches/io-c/Lib/importlib/NOTES	Sun Feb  8 21:39:02 2009
@@ -1,39 +1,6 @@
 to do
 /////
 
-* Use test.loader_tests
-
-    + builtin
-    + frozen
-    + extension
-    + source
-
-* Reorganize support code.
-
-    + Separate general support code and importer-specific (e.g. source) support
-      code.
-        - Create support modules for each subdirectory (as needed).
-    + Add a file loader mock that returns monotonically increasing mtime.
-        - Use in source/test_reload.
-        - Use in source/test_load_module_mixed.
-
-* API simplification?
-
-    + read_source -> get_data/source_path
-    + read_bytecode -> get_data/bytecode_path
-    + write_bytecode -> complete set of bytes for bytecode instead of
-      individual arguments.
-
-* Create meta_path importer for sys.path.
-
-* OPTIMIZE!
-
-  + Write benchmark suite.
-  + Fast path common cases.
-
-    - Absolute name from sys.path.
-    - Relative name from sys.path.
-
 * Implement PEP 302 protocol for loaders (should just be a matter of testing).
 
     + Built-in.
@@ -41,7 +8,7 @@
     + Extension.
     + Source/bytecode.
 
-* Public API to expose (w/ docs!)
+* Public API left to expose (w/ docs!)
 
   + abc
 
@@ -53,6 +20,8 @@
 
         * load_module
 
+      - (?) Importer(Finder, Loader)
+
       - ResourceLoader(Loader)
 
         * get_data
@@ -67,19 +36,16 @@
 
         * source_path
         * bytecode_path
-        * write_bytecode
+        * write_bytecode (not abstract)
 
   + util
 
-      - get_module decorator (new name)
-      - check_name decorator (new name)
-      - resolve_name
+      - get_module decorator (rename: module_for_loader)
+      - set___package__ decorator
 
   + machinery
 
       - (?) Chained path hook/finder
-      - BuiltinImporter
-      - FrozenImporter
       - (?) FileFinder
       - Extensions importers
 
@@ -91,4 +57,19 @@
           * SourceFinder
           * (?) Loader
 
+      - PathFinder
+
+* Write benchmark suite.
+
+* OPTIMIZE!
+
+  + Fast path absolute name.
+  + Fast path pulling from sys.modules.
+
 * Bootstrap importlib as implementation of builtins.__import__
+
+* Replace standard library modules.
+
+  + imp
+  + py_compile
+  + compileall

Modified: python/branches/io-c/Lib/importlib/__init__.py
==============================================================================
--- python/branches/io-c/Lib/importlib/__init__.py	(original)
+++ python/branches/io-c/Lib/importlib/__init__.py	Sun Feb  8 21:39:02 2009
@@ -29,7 +29,7 @@
     """Set __import__ to an instance of Import."""
     global original__import__
     original__import__ = __import__
-    __builtins__['__import__'] = Import()
+    __builtins__['__import__'] = _bootstrap._import
 
 
 def _reset__import__():
@@ -114,7 +114,7 @@
 
 # Public API #########################################################
 
-__import__ = _bootstrap.Import().__call__
+__import__ = _bootstrap._import
 
 
 def import_module(name, package=None):
@@ -125,17 +125,15 @@
     relative import to an absolute import.
 
     """
+    level = 0
     if name.startswith('.'):
         if not package:
             raise TypeError("relative imports require the 'package' argument")
-        level = 0
         for character in name:
             if character != '.':
                 break
             level += 1
-        name = Import._resolve_name(name[level:], package, level)
-    __import__(name)
-    return sys.modules[name]
+    return _bootstrap._gcd_import(name[level:], package, level)
 
 
 # XXX This should go away once the public API is done.

Modified: python/branches/io-c/Lib/importlib/_bootstrap.py
==============================================================================
--- python/branches/io-c/Lib/importlib/_bootstrap.py	(original)
+++ python/branches/io-c/Lib/importlib/_bootstrap.py	Sun Feb  8 21:39:02 2009
@@ -90,6 +90,26 @@
         self.obj.close()
 
 
+def wrap(new, old):
+    """Simple substitute for functools.wraps."""
+    for replace in ['__module__', '__name__', '__doc__']:
+        setattr(new, replace, getattr(old, replace))
+    new.__dict__.update(old.__dict__)
+
+
+def set___package__(fxn):
+    """Set __package__ on the returned module."""
+    def wrapper(*args, **kwargs):
+        module = fxn(*args, **kwargs)
+        if not hasattr(module, '__package__') or module.__package__ is None:
+            module.__package__ = module.__name__
+            if not hasattr(module, '__path__'):
+                module.__package__ = module.__package__.rpartition('.')[0]
+        return module
+    wrap(wrapper, fxn)
+    return wrapper
+
+
 class BuiltinImporter:
 
     """Meta path loader for built-in modules.
@@ -111,11 +131,13 @@
         return cls if imp.is_builtin(fullname) else None
 
     @classmethod
+    @set___package__
     def load_module(cls, fullname):
         """Load a built-in module."""
         if fullname not in sys.builtin_module_names:
             raise ImportError("{0} is not a built-in module".format(fullname))
-        return imp.init_builtin(fullname)
+        module = imp.init_builtin(fullname)
+        return module
 
 
 class FrozenImporter:
@@ -133,11 +155,13 @@
         return cls if imp.is_frozen(fullname) else None
 
     @classmethod
+    @set___package__
     def load_module(cls, fullname):
         """Load a frozen module."""
         if cls.find_module(fullname) is None:
             raise ImportError("{0} is not a frozen module".format(fullname))
-        return imp.init_frozen(fullname)
+        module = imp.init_frozen(fullname)
+        return module
 
 
 class ChainedImporter(object):
@@ -197,9 +221,7 @@
         if self._name != name:
             raise ImportError("loader cannot handle %s" % name)
         return method(self, name, *args, **kwargs)
-    inner.__name__ = method.__name__
-    inner.__doc__ = method.__doc__
-    inner.__dict__.update(method.__dict__)
+    wrap(inner, method)
     return inner
 
 
@@ -224,6 +246,7 @@
             raise ValueError("extension modules cannot be packages")
 
     @check_name
+    @set___package__
     def load_module(self, fullname):
         """Load an extension module."""
         assert self._name == fullname
@@ -301,6 +324,7 @@
                     elif hasattr(module, attr):
                         delattr(module, attr)
             raise
+    wrap(decorated, fxn)
     return decorated
 
 
@@ -336,13 +360,15 @@
         else:
             return None
 
-    def _source_path(self):
+    @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 _bytecode_path(self):
+    @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.
@@ -352,18 +378,17 @@
     @get_module
     def load_module(self, module):
         """Load a Python source or bytecode module."""
-        source_path = self._source_path()
-        bytecode_path = self._bytecode_path()
+        name = module.__name__
+        source_path = self.source_path(name)
+        bytecode_path = self.bytecode_path(name)
         code_object = self.get_code(module.__name__)
         module.__file__ = source_path if source_path else bytecode_path
         module.__loader__ = self
         if self._is_pkg:
             module.__path__  = [module.__file__.rsplit(path_sep, 1)[0]]
-            module.__package__ = module.__name__
-        elif '.' in module.__name__:
-            module.__package__ = module.__name__.rsplit('.', 1)[0]
-        else:
-            module.__package__ = None
+        module.__package__ = module.__name__
+        if not hasattr(module, '__path__'):
+            module.__package__ = module.__package__.rpartition('.')[0]
         exec(code_object, module.__dict__)
         return module
 
@@ -371,7 +396,7 @@
     def source_mtime(self, name):
         """Return the modification time of the source for the specified
         module."""
-        source_path = self._source_path()
+        source_path = self.source_path(name)
         if not source_path:
             return None
         return int(_os.stat(source_path).st_mtime)
@@ -384,7 +409,7 @@
         laoder cannot handle the specified module.
 
         """
-        source_path = self._source_path()
+        source_path = self._source_path(name)
         if source_path is None:
             return None
         import tokenize
@@ -395,57 +420,20 @@
         return open(source_path, encoding=encoding).read()
 
     @check_name
-    def read_source(self, fullname):
-        """Return the source for the specified module as bytes along with the
-        path where the source came from.
-
-        The returned path is used by 'compile' for error messages.
-
-        """
-        source_path = self._source_path()
-        if source_path is None:
-            return None
-        with closing(_io.FileIO(source_path, 'r')) as bytes_file:
-            return bytes_file.read(), source_path
-
-    @check_name
-    def read_bytecode(self, name):
-        """Return the magic number, timestamp, and the module bytecode for the
-        module.
-
-        Raises ImportError (just like get_source) if the laoder cannot handle
-        the module. Returns None if there is no bytecode.
-
-        """
-        path = self._bytecode_path()
-        if path is None:
-            return None
-        file = _io.FileIO(path, 'r')
-        try:
-            with closing(file) as bytecode_file:
-                data = bytecode_file.read()
-            return data[:4], marshal._r_long(data[4:8]), data[8:]
-        except AttributeError:
-            return None
-
-    @check_name
-    def write_bytecode(self, name, magic, timestamp, data):
-        """Write out 'data' for the specified module using the specific
-        timestamp, returning a boolean
+    def write_bytecode(self, name, data):
+        """Write out 'data' for the specified module, returning a boolean
         signifying if the write-out actually occurred.
 
         Raises ImportError (just like get_source) if the specified module
         cannot be handled by the loader.
 
         """
-        bytecode_path = self._bytecode_path()
+        bytecode_path = self.bytecode_path(name)
         if not bytecode_path:
             bytecode_path = self._base_path + suffix_list(imp.PY_COMPILED)[0]
         file = _io.FileIO(bytecode_path, 'w')
         try:
             with closing(file) as bytecode_file:
-                bytecode_file.write(magic)
-                bytecode_file.write(marshal._w_long(timestamp))
                 bytecode_file.write(data)
                 return True
         except IOError as exc:
@@ -454,39 +442,19 @@
             else:
                 raise
 
-    # XXX Take an optional argument to flag whether to write bytecode?
     @check_name
     def get_code(self, name):
-        """Return the code object for the module.
-
-            'self' must implement:
-
-            * read_bytecode(name:str) -> (int, int, bytes) or None
-                Return the magic number, timestamp, and bytecode for the
-                module. None is returned if not bytecode is available.
-
-            * source_mtime(name:str) -> int
-                Return the last modification time for the source of the module.
-                Returns None if their is no source.
-
-            * read_source(name:str) -> (bytes, str)
-                Return the source code for the module and the path to use in
-                the call to 'compile'. Not called if source_mtime returned
-                None.
-
-            * write_bytecode(name:str, magic:bytes, timestamp:int, data:str)
-                Write out bytecode for the module with the specified magic
-                number and timestamp. Not called if sys.dont_write_bytecode is
-                True.
-
-        """
+        """Return the code object for the module."""
         # XXX Care enough to make sure this call does not happen if the magic
         #     number is bad?
         source_timestamp = self.source_mtime(name)
         # Try to use bytecode if it is available.
-        bytecode_tuple = self.read_bytecode(name)
-        if bytecode_tuple:
-            magic, pyc_timestamp, bytecode = bytecode_tuple
+        bytecode_path = self.bytecode_path(name)
+        if bytecode_path:
+            data = self.get_data(bytecode_path)
+            magic = data[:4]
+            pyc_timestamp = marshal._r_long(data[4:8])
+            bytecode = data[8:]
             try:
                 # Verify that the magic number is valid.
                 if imp.get_magic() != magic:
@@ -511,7 +479,8 @@
             raise ImportError("no source or bytecode available to create code "
                                 "object for {0!r}".format(name))
         # Use the source.
-        source, source_path = self.read_source(name)
+        source_path = self.source_path(name)
+        source = self.get_data(source_path)
         # Convert to universal newlines.
         line_endings = b'\n'
         for index, c in enumerate(source):
@@ -530,8 +499,10 @@
         code_object = compile(source, source_path, 'exec', dont_inherit=True)
         # Generate bytecode and write it out.
         if not sys.dont_write_bytecode:
-            data = marshal.dumps(code_object)
-            self.write_bytecode(name, imp.get_magic(), source_timestamp, data)
+            data = bytearray(imp.get_magic())
+            data.extend(marshal._w_long(source_timestamp))
+            data.extend(marshal.dumps(code_object))
+            self.write_bytecode(name, data)
         return code_object
 
     def get_data(self, path):
@@ -635,319 +606,209 @@
         super(PyFileImporter, self).__init__(path_entry)
 
 
-class ImportLockContext(object):
-
-    """Context manager for the import lock."""
-
-    def __enter__(self):
-        """Acquire the import lock."""
-        imp.acquire_lock()
-
-    def __exit__(self, exc_type, exc_value, exc_traceback):
-        """Release the import lock regardless of any raised exceptions."""
-        imp.release_lock()
-
+class PathFinder:
 
-class Import(object):
+    """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
 
-    """Class that implements the __import__ interface.
+    _default_hook = staticmethod(chaining_fs_path_hook(ExtensionFileImporter,
+                                                        PyFileImporter))
 
-    Backwards compatibility is maintained  by extending sys.meta_path
-    interally (for handling built-in and frozen modules) and providing a
-    default path hooks entry for extension modules, .py, and .pyc
-    files.  Both are controlled during instance initialization.
-
-    """
+    # The list of implicit hooks cannot be a class attribute because of
+    # bootstrapping issues for accessing imp.
+    @classmethod
+    def _implicit_hooks(cls):
+        """Return a list of the implicit path hooks."""
+        return [cls._default_hook, imp.NullImporter]
 
-    def __init__(self, default_path_hook=None,
-                 extended_meta_path=None):
-        """Store a default path hook entry and a sequence to internally extend
-        sys.meta_path by (passing in None uses default importers)."""
-        if extended_meta_path is None:
-            self.extended_meta_path = BuiltinImporter, FrozenImporter
-        else:
-            self.extended_meta_path = extended_meta_path
-        self.default_path_hook = default_path_hook
-        if self.default_path_hook is None:
-            # Create a handler to deal with extension modules, .py, and .pyc
-            # files.  Built-in and frozen modules are handled by sys.meta_path
-            # entries.
-            importers = [ExtensionFileImporter, PyFileImporter]
-            self.default_path_hook = chaining_fs_path_hook(*importers)
-
-    def _search_meta_path(self, name, path=None):
-        """Check the importers on sys.meta_path for a loader along with the
-        extended meta path sequence stored within this instance.
+    @classmethod
+    def _path_hooks(cls, path):
+        """Search sys.path_hooks for a finder for 'path'.
 
-        The extended sys.meta_path entries are searched after the entries on
-        sys.meta_path.
+        Guaranteed to return a finder for the path as NullImporter is the
+        default importer for any path that does not have an explicit finder.
 
         """
-        for entry in (tuple(sys.meta_path) + self.extended_meta_path):
-            loader = entry.find_module(name, path)
-            if loader:
-                return loader
+        for hook in sys.path_hooks + cls._implicit_hooks():
+            try:
+                return hook(path)
+            except ImportError:
+                continue
         else:
-            raise ImportError("No module named %s" % name)
+            # This point should never be reached thanks to NullImporter.
+            raise SystemError("no hook could find an importer for "
+                              "{0}".format(path))
 
-    def _sys_path_importer(self, path_entry):
-        """Return the importer for the specified path, from
-        sys.path_importer_cache if possible.
+    @classmethod
+    def _path_importer_cache(cls, path):
+        """Get the finder for the path from sys.path_importer_cache.
 
-        If None is stored in sys.path_importer_cache then use the default path
-        hook.
+        If the path is not in the cache, find the appropriate finder and cache
+        it. If None is cached, get the default finder and cache that
+        (if applicable).
+
+        Because of NullImporter, some finder should be returned. The only
+        explicit fail case is if None is cached but the path cannot be used for
+        the default hook, for which ImportError is raised.
 
         """
         try:
-            # See if an importer is cached.
-            importer = sys.path_importer_cache[path_entry]
-            # If None was returned, use default importer factory.
-            if importer is None:
-                return self.default_path_hook(path_entry)
-            else:
-                return importer
+            finder = sys.path_importer_cache[path]
         except KeyError:
-            # No cached importer found; try to get a new one from
-            # sys.path_hooks or imp.NullImporter.
-            for importer_factory in (sys.path_hooks + [imp.NullImporter]):
-                try:
-                    importer = importer_factory(path_entry)
-                    sys.path_importer_cache[path_entry] = importer
-                    return importer
-                except ImportError:
-                    continue
-            else:
-                # No importer factory on sys.path_hooks works; use the default
-                # importer factory and store None in sys.path_importer_cache.
-                try:
-                    importer = self.default_path_hook(path_entry)
-                    sys.path_importer_cache[path_entry] = None
-                    return importer
-                except ImportError:
-                    raise ImportError("no importer found for %s" % path_entry)
-
-    def _search_std_path(self, name, path=None):
-        """Check sys.path or 'path' (depending if 'path' is set) for the
-        named module and return its loader."""
-        if path:
-            search_paths = path
+            finder = cls._path_hooks(path)
+            sys.path_importer_cache[path] = finder
         else:
-            search_paths = sys.path
-        for entry in search_paths:
+            if finder is None:
+                # Raises ImportError on failure.
+                finder = cls._default_hook(path)
+                sys.path_importer_cache[path] = finder
+        return finder
+
+    @classmethod
+    def find_module(cls, fullname, path=None):
+        """Find the module on sys.path or 'path'."""
+        if not path:
+            path = sys.path
+        for entry in path:
             try:
-                importer = self._sys_path_importer(entry)
+                finder = cls._path_importer_cache(entry)
             except ImportError:
                 continue
-            loader = importer.find_module(name)
+            loader = finder.find_module(fullname)
             if loader:
                 return loader
         else:
-            raise ImportError("No module named %s" % name)
+            return None
 
-    def module_from_cache(self, name):
-        """Try to return the named module from sys.modules.
 
-        Return False if the module is not in the cache.
-        """
-        if name in sys.modules:
-            return sys.modules[name]
-        else:
-            return False
+class ImportLockContext(object):
 
-    def post_import(self, module):
-        """Perform any desired post-import processing on the module."""
-        return module
+    """Context manager for the import lock."""
 
-    def _import_module(self, name, path=None):
-        """Import the specified module with no handling of parent modules.
+    def __enter__(self):
+        """Acquire the import lock."""
+        imp.acquire_lock()
 
-        If None is set for a value in sys.modules (to signify that a relative
-        import was attempted and failed) then ImportError is raised.
+    def __exit__(self, exc_type, exc_value, exc_traceback):
+        """Release the import lock regardless of any raised exceptions."""
+        imp.release_lock()
 
-        """
-        cached_module = self.module_from_cache(name)
-        if cached_module is not False:
-            if cached_module is None:
-                raise ImportError("relative import redirect")
-            else:
-                return cached_module
-        try:
-            # Attempt to find a loader on sys.meta_path.
-            loader = self._search_meta_path(name, path)
-        except ImportError:
-            # sys.meta_path search failed.  Attempt to find a loader on
-            # sys.path.  If this fails then module cannot be found.
-            loader = self._search_std_path(name, path)
-        # A loader was found.  It is the loader's responsibility to have put an
-        # entry in sys.modules.
-        module = self.post_import(loader.load_module(name))
-        # 'module' could be something like None.
-        if not hasattr(module, '__name__'):
-            return module
-        # Set __package__.
-        if not hasattr(module, '__package__') or module.__package__ is None:
-            if hasattr(module, '__path__'):
-                module.__package__ = module.__name__
-            elif '.' in module.__name__:
-                pkg_name = module.__name__.rsplit('.', 1)[0]
-                module.__package__ = pkg_name
-            else:
-                module.__package__ = None
-        return module
 
+def _gcd_import(name, package=None, level=0):
+    """Import and return the module based on its name, the package the call is
+    being made from, and the level adjustment.
+
+    This function represents the greatest common denominator of functionality
+    between import_module and __import__. This includes settting __package__ if
+    the loader did not.
 
-    def _import_full_module(self, name):
-        """Import a module and set it on its parent if needed."""
-        path_list = None
-        parent_name = name.rsplit('.', 1)[0]
-        parent = None
-        if parent_name != name:
-            parent = sys.modules[parent_name]
+    """
+    if package:
+        if not hasattr(package, 'rindex'):
+            raise ValueError("__package__ not set to a string")
+        elif package not in sys.modules:
+            msg = ("Parent module {0!r} not loaded, cannot perform relative "
+                   "import")
+            raise SystemError(msg.format(package))
+    if not name and level == 0:
+        raise ValueError("Empty module name")
+    if level > 0:
+        dot = len(package)
+        for x in range(level, 1, -1):
             try:
-                path_list = parent.__path__
-            except AttributeError:
-                pass
-        self._import_module(name, path_list)
-        module = sys.modules[name]
-        if parent:
-            tail = name.rsplit('.', 1)[-1]
-            setattr(parent, tail, module)
-
-    def _find_package(self, name, has_path):
-        """Return the package that the caller is in or None."""
-        if has_path:
-            return name
-        elif '.' in name:
-            return name.rsplit('.', 1)[0]
+                dot = package.rindex('.', 0, dot)
+            except ValueError:
+                raise ValueError("attempted relative import beyond "
+                                 "top-level package")
+        if name:
+            name = "{0}.{1}".format(package[:dot], name)
         else:
-            return None
-
-    @staticmethod
-    def _resolve_name(name, package, level):
-        """Return the absolute name of the module to be imported."""
-        level -= 1
+            name = package[:dot]
+    with ImportLockContext():
         try:
-            if package.count('.') < level:
-                raise ValueError("attempted relative import beyond top-level "
-                                  "package")
-        except AttributeError:
-            raise ValueError("__package__ not set to a string")
-        base = package.rsplit('.', level)[0]
-        if name:
-            return "{0}.{1}".format(base, name)
+            return sys.modules[name]
+        except KeyError:
+            pass
+        parent = name.rpartition('.')[0]
+        path = None
+        if parent:
+            if parent not in sys.modules:
+                _gcd_import(parent)
+            # Backwards-compatibility; be nicer to skip the dict lookup.
+            parent_module = sys.modules[parent]
+            path = parent_module.__path__
+        meta_path = (sys.meta_path +
+                     [BuiltinImporter, FrozenImporter, PathFinder])
+        for finder in meta_path:
+            loader = finder.find_module(name, path)
+            if loader is not None:
+                loader.load_module(name)
+                break
         else:
-            return base
-
-    def _return_module(self, absolute_name, relative_name, fromlist):
-        """Return the proper module based on what module was requested (and its
-        absolute module name), who is requesting it, and whether any specific
-        attributes were specified.
-
-        The semantics of this method revolve around 'fromlist'.  When it is
-        empty, the module up to the first dot is to be returned.  When the
-        module being requested is an absolute name this is simple (and
-        relative_name is an empty string).  But if the requested module was
-        a relative import (as signaled by relative_name having a non-false
-        value), then the name up to the first dot in the relative name resolved
-        to an absolute name is to be returned.
-
-        When fromlist is not empty and the module being imported is a package,
-        then the values
-        in fromlist need to be checked for.  If a value is not a pre-existing
-        attribute a relative import is attempted.  If it fails then suppressed
-        the failure silently.
+            raise ImportError("No module named {0}".format(name))
+        # Backwards-compatibility; be nicer to skip the dict lookup.
+        module = sys.modules[name]
+        if parent:
+            # Set the module as an attribute on its parent.
+            setattr(parent_module, name.rpartition('.')[2], module)
+        # Set __package__ if the loader did not.
+        if not hasattr(module, '__package__') or module.__package__ is None:
+            # Watch out for what comes out of sys.modules to not be a module,
+            # e.g. an int.
+            try:
+                module.__package__ = module.__name__
+                if not hasattr(module, '__path__'):
+                    module.__package__ = module.__package__.rpartition('.')[0]
+            except AttributeError:
+                pass
+        return module
 
-        """
-        if not fromlist:
-            if relative_name:
-                absolute_base = absolute_name.rpartition(relative_name)[0]
-                relative_head = relative_name.split('.', 1)[0]
-                to_return = absolute_base + relative_head
-            else:
-                to_return = absolute_name.split('.', 1)[0]
-            return sys.modules[to_return]
-        # When fromlist is not empty, return the actual module specified in
-        # the import.
-        else:
-            module = sys.modules[absolute_name]
-            if hasattr(module, '__path__') and hasattr(module, '__name__'):
-                # When fromlist has a value and the imported module is a
-                # package, then if a name in fromlist is not found as an
-                # attribute on module, try a relative import to find it.
-                # Failure is fine and the exception is suppressed.
-                check_for = list(fromlist)
-                if '*' in check_for and hasattr(module, '__all__'):
-                    check_for.extend(module.__all__)
-                for item in check_for:
-                    if item == '*':
-                        continue
-                    if not hasattr(module, item):
-                        resolved_name = self._resolve_name(item,
-                                                            module.__name__, 1)
-                        try:
-                            self._import_full_module(resolved_name)
-                        except ImportError:
-                            pass
-            return module
 
-    def __call__(self, name, globals={}, locals={}, fromlist=[], level=0):
-        """Import a module.
+def _import(name, globals={}, locals={}, fromlist=[], level=0):
+    """Import a module.
 
-        The 'name' argument is the name of the module to be imported (e.g.,
-        'foo' in ``import foo`` or ``from foo import ...``).
+    The 'globals' argument is used to infer where the import is occuring from
+    to handle relative imports. The 'locals' argument is ignored. The
+    'fromlist' argument specifies what should exist as attributes on the module
+    being imported (e.g. ``from module import <fromlist>``).  The 'level'
+    argument represents the package location to import from in a relative
+    import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
 
-        'globals' and 'locals' are the global and local namespace dictionaries
-        of the module where the import statement appears.  'globals' is used to
-        introspect the __path__ and __name__ attributes of the module making
-        the call.  'local's is ignored.
-
-        'fromlist' lists any specific objects that are to eventually be put
-        into the namespace (e.g., ``from for.bar import baz`` would have 'baz'
-        in the fromlist, and this includes '*').  An entry of '*' will lead to
-        a check for __all__ being defined on the module.  If it is defined then
-        the values in __all__ will be checked to make sure that all values are
-        attributes on the module, attempting a module import relative to 'name'
-        to set that attribute.
-
-        When 'name' is a dotted name, there are two different situations to
-        consider for the return value.  One is when the fromlist is empty.
-        In this situation the import statement imports and returns the name up
-        to the first dot.  All subsequent names are imported but set as
-        attributes as needed on parent modules.  When fromlist is not empty
-        then the module represented by the full dotted name is returned.
-
-        'level' represents possible relative imports.
-        A value of 0 is for absolute module names. Any positive value
-        represents the number of dots listed in the relative import statement
-        (e.g. has a value of 2 for ``from .. import foo``).
+    """
+    if level == 0:
+        module = _gcd_import(name)
+    else:
+        # __package__ is not guaranteed to be defined.
+        try:
+            package = globals['__package__']
+        except KeyError:
+            package = globals['__name__']
+            if '__path__' not in globals:
+                package = package.rpartition('.')[0]
+        module = _gcd_import(name, package, level)
+    # The hell that is fromlist ...
+    if not fromlist:
+        # Return up to the first dot in 'name'. This is complicated by the fact
+        # that 'name' may be relative.
+        if level == 0:
+            return sys.modules[name.partition('.')[0]]
+        elif not name:
+            return module
+        else:
+            cut_off = len(name) - len(name.partition('.')[0])
+            return sys.modules[module.__name__[:-cut_off]]
+    else:
+        # If a package was imported, try to import stuff from fromlist.
+        if hasattr(module, '__path__'):
+            if '*' in fromlist and hasattr(module, '__all__'):
+                fromlist.remove('*')
+                fromlist.extend(module.__all__)
+            for x in (y for y in fromlist if not hasattr(module,y)):
+                try:
+                    _gcd_import('{0}.{1}'.format(module.__name__, x))
+                except ImportError:
+                    pass
+        return module
 
-        """
-        if not name and level < 1:
-            raise ValueError("Empty module name")
-        is_pkg = True if '__path__' in globals else False
-        caller_name = globals.get('__name__')
-        package = globals.get('__package__')
-        if caller_name and not package:
-            package = self._find_package(caller_name, '__path__' in globals)
-        if package and package not in sys.modules:
-            if not hasattr(package, 'rsplit'):
-                raise ValueError("__package__ not set to a string")
-            msg = ("Parent module {0!r} not loaded, "
-                    "cannot perform relative import")
-            raise SystemError(msg.format(package))
-        with ImportLockContext():
-            if level:
-                imported_name = self._resolve_name(name, package, level)
-            else:
-                imported_name = name
-            parent_name = imported_name.rsplit('.', 1)[0]
-            if parent_name != imported_name and parent_name not in sys.modules:
-                self.__call__(parent_name, level=0)
-            # This call will also handle setting the attribute on the
-            # package.
-            self._import_full_module(imported_name)
-            relative_name = '' if imported_name == name else name
-            return self._return_module(imported_name, relative_name, fromlist)
 
 # XXX Eventually replace with a proper __all__ value (i.e., don't expose os
 # replacements but do expose _ExtensionFileLoader, etc. for testing).

Modified: python/branches/io-c/Lib/importlib/machinery.py
==============================================================================
--- python/branches/io-c/Lib/importlib/machinery.py	(original)
+++ python/branches/io-c/Lib/importlib/machinery.py	Sun Feb  8 21:39:02 2009
@@ -2,3 +2,4 @@
 
 from ._bootstrap import BuiltinImporter
 from ._bootstrap import FrozenImporter
+from ._bootstrap import PathFinder

Modified: python/branches/io-c/Lib/importlib/test/__init__.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/__init__.py	(original)
+++ python/branches/io-c/Lib/importlib/test/__init__.py	Sun Feb  8 21:39:02 2009
@@ -9,7 +9,8 @@
         if name.startswith('.'):
             continue
         path = os.path.join(directory, name)
-        if os.path.isfile(path) and name.startswith('test_'):
+        if (os.path.isfile(path) and name.startswith('test_') and
+                name.endswith('.py')):
             submodule_name = os.path.splitext(name)[0]
             module_name = "{0}.{1}".format(package, submodule_name)
             __import__(module_name, level=0)
@@ -20,6 +21,8 @@
             __import__(package_name, level=0)
             package_tests = getattr(sys.modules[package_name], 'test_suite')()
             suite.addTest(package_tests)
+        else:
+            continue
     return suite
 
 

Modified: python/branches/io-c/Lib/importlib/test/builtin/test_finder.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/builtin/test_finder.py	(original)
+++ python/branches/io-c/Lib/importlib/test/builtin/test_finder.py	Sun Feb  8 21:39:02 2009
@@ -1,11 +1,11 @@
 from importlib import machinery
-from .. import finder_tests
-from .. import support
+from .. import abc
+from .. import util
 
 import sys
 import unittest
 
-class FinderTests(finder_tests.FinderTests):
+class FinderTests(abc.FinderTests):
 
     """Test find_module() for built-in modules."""
 
@@ -14,7 +14,7 @@
 
     def test_module(self):
         # Common case.
-        with support.uncache(self.name):
+        with util.uncache(self.name):
             self.assert_(machinery.BuiltinImporter.find_module(self.name))
 
     def test_package(self):
@@ -40,7 +40,7 @@
 
     def test_ignore_path(self):
         # The value for 'path' should always trigger a failed import.
-        with support.uncache(self.name):
+        with util.uncache(self.name):
             loader = machinery.BuiltinImporter.find_module(self.name, ['pkg'])
             self.assert_(loader is None)
 

Modified: python/branches/io-c/Lib/importlib/test/builtin/test_loader.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/builtin/test_loader.py	(original)
+++ python/branches/io-c/Lib/importlib/test/builtin/test_loader.py	Sun Feb  8 21:39:02 2009
@@ -1,20 +1,21 @@
 import importlib
 from importlib import machinery
-from .. import support
+from .. import abc
+from .. import util
 
 import sys
 import types
 import unittest
 
 
-class LoaderTests(unittest.TestCase):
+class LoaderTests(abc.LoaderTests):
 
     """Test load_module() for built-in modules."""
 
     assert 'errno' in sys.builtin_module_names
     name = 'errno'
 
-    verification = {'__name__': 'errno', '__package__': None}
+    verification = {'__name__': 'errno', '__package__': ''}
 
     def verify(self, module):
         """Verify that the module matches against what it should have."""
@@ -26,13 +27,32 @@
     load_module = staticmethod(lambda name:
                                 machinery.BuiltinImporter.load_module(name))
 
-    def test_load_module(self):
+    def test_module(self):
         # Common case.
-        with support.uncache(self.name):
+        with util.uncache(self.name):
             module = self.load_module(self.name)
             self.verify(module)
 
-    def test_nonexistent(self):
+    def test_package(self):
+        # Built-in modules cannot be a package.
+        pass
+
+    def test_lacking_parent(self):
+        # Built-in modules cannot be a package.
+        pass
+
+    def test_state_after_failure(self):
+        # Not way to force an imoprt failure.
+        pass
+
+    def test_module_reuse(self):
+        # Test that the same module is used in a reload.
+        with util.uncache(self.name):
+            module1 = self.load_module(self.name)
+            module2 = self.load_module(self.name)
+            self.assert_(module1 is module2)
+
+    def test_unloadable(self):
         name = 'dssdsdfff'
         assert name not in sys.builtin_module_names
         self.assertRaises(ImportError, self.load_module, name)

Modified: python/branches/io-c/Lib/importlib/test/extension/test_case_sensitivity.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/extension/test_case_sensitivity.py	(original)
+++ python/branches/io-c/Lib/importlib/test/extension/test_case_sensitivity.py	Sun Feb  8 21:39:02 2009
@@ -1,29 +1,29 @@
 import sys
-from test import support as test_support
+from test import support
 import unittest
 import importlib
-from .. import support
-from . import test_path_hook
+from .. import util
+from . import util as ext_util
 
 
- at support.case_insensitive_tests
+ at util.case_insensitive_tests
 class ExtensionModuleCaseSensitivityTest(unittest.TestCase):
 
     def find_module(self):
-        good_name = test_path_hook.NAME
+        good_name = ext_util.NAME
         bad_name = good_name.upper()
         assert good_name != bad_name
-        finder = importlib.ExtensionFileImporter(test_path_hook.PATH)
+        finder = importlib.ExtensionFileImporter(ext_util.PATH)
         return finder.find_module(bad_name)
 
     def test_case_sensitive(self):
-        with test_support.EnvironmentVarGuard() as env:
+        with support.EnvironmentVarGuard() as env:
             env.unset('PYTHONCASEOK')
             loader = self.find_module()
             self.assert_(loader is None)
 
     def test_case_insensitivity(self):
-        with test_support.EnvironmentVarGuard() as env:
+        with support.EnvironmentVarGuard() as env:
             env.set('PYTHONCASEOK', '1')
             loader = self.find_module()
             self.assert_(hasattr(loader, 'load_module'))
@@ -32,7 +32,7 @@
 
 
 def test_main():
-    test_support.run_unittest(ExtensionModuleCaseSensitivityTest)
+    support.run_unittest(ExtensionModuleCaseSensitivityTest)
 
 
 if __name__ == '__main__':

Modified: python/branches/io-c/Lib/importlib/test/extension/test_finder.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/extension/test_finder.py	(original)
+++ python/branches/io-c/Lib/importlib/test/extension/test_finder.py	Sun Feb  8 21:39:02 2009
@@ -1,19 +1,19 @@
 import importlib
-from .. import finder_tests
-from . import test_path_hook
+from .. import abc
+from . import util
 
 import unittest
 
-class FinderTests(finder_tests.FinderTests):
+class FinderTests(abc.FinderTests):
 
     """Test the finder for extension modules."""
 
     def find_module(self, fullname):
-        importer = importlib.ExtensionFileImporter(test_path_hook.PATH)
+        importer = importlib.ExtensionFileImporter(util.PATH)
         return importer.find_module(fullname)
 
     def test_module(self):
-        self.assert_(self.find_module(test_path_hook.NAME))
+        self.assert_(self.find_module(util.NAME))
 
     def test_package(self):
         # Extension modules cannot be an __init__ for a package.

Modified: python/branches/io-c/Lib/importlib/test/extension/test_loader.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/extension/test_loader.py	(original)
+++ python/branches/io-c/Lib/importlib/test/extension/test_loader.py	Sun Feb  8 21:39:02 2009
@@ -1,30 +1,49 @@
 import importlib
-from . import test_path_hook
-from .. import support
+from . import util as ext_util
+from .. import abc
+from .. import util
 
 import sys
 import unittest
 
 
-class LoaderTests(unittest.TestCase):
+class LoaderTests(abc.LoaderTests):
 
     """Test load_module() for extension modules."""
 
     def load_module(self, fullname):
-        loader = importlib._ExtensionFileLoader(test_path_hook.NAME,
-                                                test_path_hook.FILEPATH,
-                                                False)
+        loader = importlib._ExtensionFileLoader(ext_util.NAME,
+                                                ext_util.FILEPATH, False)
         return loader.load_module(fullname)
 
-    def test_success(self):
-        with support.uncache(test_path_hook.NAME):
-            module = self.load_module(test_path_hook.NAME)
-            for attr, value in [('__name__', test_path_hook.NAME),
-                                ('__file__', test_path_hook.FILEPATH)]:
+    def test_module(self):
+        with util.uncache(ext_util.NAME):
+            module = self.load_module(ext_util.NAME)
+            for attr, value in [('__name__', ext_util.NAME),
+                                ('__file__', ext_util.FILEPATH),
+                                ('__package__', '')]:
                 self.assertEqual(getattr(module, attr), value)
-            self.assert_(test_path_hook.NAME in sys.modules)
+            self.assert_(ext_util.NAME in sys.modules)
 
-    def test_failure(self):
+    def test_package(self):
+        # Extensions are not found in packages.
+        pass
+
+    def test_lacking_parent(self):
+        # Extensions are not found in packages.
+        pass
+
+    def test_module_reuse(self):
+        with util.uncache(ext_util.NAME):
+            module1 = self.load_module(ext_util.NAME)
+            module2 = self.load_module(ext_util.NAME)
+            self.assert_(module1 is module2)
+
+    def test_state_after_failure(self):
+        # No easy way to trigger a failure after a successful import.
+        pass
+
+    def test_unloadable(self):
         self.assertRaises(ImportError, self.load_module, 'asdfjkl;')
 
 

Modified: python/branches/io-c/Lib/importlib/test/extension/test_path_hook.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/extension/test_path_hook.py	(original)
+++ python/branches/io-c/Lib/importlib/test/extension/test_path_hook.py	Sun Feb  8 21:39:02 2009
@@ -1,31 +1,12 @@
 import importlib
+from . import util
 
 import collections
 import imp
-from os import path
 import sys
 import unittest
 
 
-PATH = None
-EXT = None
-FILENAME = None
-NAME = '_testcapi'
-_file_exts = [x[0] for x in imp.get_suffixes() if x[2] == imp.C_EXTENSION]
-try:
-    for PATH in sys.path:
-        for EXT in _file_exts:
-            FILENAME = NAME + EXT
-            FILEPATH = path.join(PATH, FILENAME)
-            if path.exists(path.join(PATH, FILENAME)):
-                raise StopIteration
-    else:
-        PATH = EXT = FILENAME = FILEPATH = None
-except StopIteration:
-    pass
-del _file_exts
-
-
 class PathHookTests(unittest.TestCase):
 
     """Test the path hook for extension modules."""
@@ -38,7 +19,7 @@
     def test_success(self):
         # Path hook should handle a directory where a known extension module
         # exists.
-        self.assert_(hasattr(self.hook(PATH), 'find_module'))
+        self.assert_(hasattr(self.hook(util.PATH), 'find_module'))
 
 
 def test_main():

Deleted: python/branches/io-c/Lib/importlib/test/finder_tests.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/finder_tests.py	Sun Feb  8 21:39:02 2009
+++ (empty file)
@@ -1,39 +0,0 @@
-import abc
-import unittest
-
-
-class FinderTests(unittest.TestCase, metaclass=abc.ABCMeta):
-
-    """Basic tests for a finder to pass."""
-
-    @abc.abstractmethod
-    def test_module(self):
-        # Test importing a top-level module.
-        pass
-
-    @abc.abstractmethod
-    def test_package(self):
-        # Test importing a package.
-        pass
-
-    @abc.abstractmethod
-    def test_module_in_package(self):
-        # Test importing a module contained within a package.
-        # A value for 'path' should be used if for a meta_path finder.
-        pass
-
-    @abc.abstractmethod
-    def test_package_in_package(self):
-        # Test importing a subpackage.
-        # A value for 'path' should be used if for a meta_path finder.
-        pass
-
-    @abc.abstractmethod
-    def test_package_over_module(self):
-        # Test that packages are chosen over modules.
-        pass
-
-    @abc.abstractmethod
-    def test_failure(self):
-        # Test trying to find a module that cannot be handled.
-        pass

Deleted: python/branches/io-c/Lib/importlib/test/frozen/support.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/frozen/support.py	Sun Feb  8 21:39:02 2009
+++ (empty file)
@@ -1,24 +0,0 @@
-import sys
-
-
-class Null:
-
-    """Just absorb what is given."""
-
-    def __getattr__(self):
-        return lambda *args, **kwargs: None
-
-
-class SilenceStdout:
-
-    """Silence sys.stdout."""
-
-    def setUp(self):
-        """Substitute sys.stdout with something that does not print to the
-        screen thanks to what bytecode is frozen."""
-        sys.stdout = Null()
-        super().setUp()
-
-    def tearDown(self):
-        sys.stdout = sys.__stdout__
-        super().tearDown()

Modified: python/branches/io-c/Lib/importlib/test/frozen/test_finder.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/frozen/test_finder.py	(original)
+++ python/branches/io-c/Lib/importlib/test/frozen/test_finder.py	Sun Feb  8 21:39:02 2009
@@ -1,10 +1,10 @@
 from ... import machinery
-from .. import finder_tests
+from .. import abc
 
 import unittest
 
 
-class FinderTests(finder_tests.FinderTests):
+class FinderTests(abc.FinderTests):
 
     """Test finding frozen modules."""
 

Modified: python/branches/io-c/Lib/importlib/test/frozen/test_loader.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/frozen/test_loader.py	(original)
+++ python/branches/io-c/Lib/importlib/test/frozen/test_loader.py	Sun Feb  8 21:39:02 2009
@@ -1,26 +1,59 @@
 from importlib import machinery
-from ..builtin import test_loader
+from .. import abc
+from .. import util
 
 
-class LoaderTests(test_loader.LoaderTests):
+class LoaderTests(abc.LoaderTests):
 
-    name = '__phello__'
-    load_module = staticmethod(lambda name:
-                                machinery.FrozenImporter.load_module(name))
-    verification = {'__name__': '__phello__', '__file__': '<frozen>',
-                    '__package__': None, '__path__': ['__phello__']}
-
-
-class SubmoduleLoaderTests(LoaderTests):
-
-    name = '__phello__.spam'
-    verification = {'__name__': '__phello__.spam', '__file__': '<frozen>',
-                    '__package__': None}
+    def test_module(self):
+        with util.uncache('__hello__'):
+            module = machinery.FrozenImporter.load_module('__hello__')
+            check = {'__name__': '__hello__', '__file__': '<frozen>',
+                        '__package__': ''}
+            for attr, value in check.items():
+                self.assertEqual(getattr(module, attr), value)
+
+    def test_package(self):
+        with util.uncache('__phello__'):
+            module = machinery.FrozenImporter.load_module('__phello__')
+            check = {'__name__': '__phello__', '__file__': '<frozen>',
+                     '__package__': '__phello__', '__path__': ['__phello__']}
+            for attr, value in check.items():
+                attr_value = getattr(module, attr)
+                self.assertEqual(attr_value, value,
+                                 "for __phello__.%s, %r != %r" %
+                                 (attr, attr_value, value))
+
+    def test_lacking_parent(self):
+        with util.uncache('__phello__', '__phello__.spam'):
+            module = machinery.FrozenImporter.load_module('__phello__.spam')
+            check = {'__name__': '__phello__.spam', '__file__': '<frozen>',
+                     '__package__': '__phello__'}
+            for attr, value in check.items():
+                attr_value = getattr(module, attr)
+                self.assertEqual(attr_value, value,
+                                 "for __phello__.spam.%s, %r != %r" %
+                                 (attr, attr_value, value))
+
+    def test_module_reuse(self):
+        with util.uncache('__hello__'):
+            module1 = machinery.FrozenImporter.load_module('__hello__')
+            module2 = machinery.FrozenImporter.load_module('__hello__')
+            self.assert_(module1 is module2)
+
+    def test_state_after_failure(self):
+        # No way to trigger an error in a frozen module.
+        pass
+
+    def test_unloadable(self):
+        assert machinery.FrozenImporter.find_module('_not_real') is None
+        self.assertRaises(ImportError, machinery.FrozenImporter.load_module,
+                            '_not_real')
 
 
 def test_main():
     from test.support import run_unittest
-    run_unittest(LoaderTests, SubmoduleLoaderTests)
+    run_unittest(LoaderTests)
 
 
 if __name__ == '__main__':

Modified: python/branches/io-c/Lib/importlib/test/import_/test___package__.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test___package__.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test___package__.py	Sun Feb  8 21:39:02 2009
@@ -5,7 +5,8 @@
 
 """
 import unittest
-from .. import support
+from .. import util
+from . import util as import_util
 
 
 class Using__package__(unittest.TestCase):
@@ -34,19 +35,20 @@
 
     def test_using___package__(self):
         # [__package__]
-        with support.mock_modules('pkg.__init__', 'pkg.fake') as importer:
-            with support.import_state(meta_path=[importer]):
-                support.import_('pkg.fake')
-                module = support.import_('', globals={'__package__': 'pkg.fake'},
-                                 fromlist=['attr'], level=2)
+        with util.mock_modules('pkg.__init__', 'pkg.fake') as importer:
+            with util.import_state(meta_path=[importer]):
+                import_util.import_('pkg.fake')
+                module = import_util.import_('',
+                                            globals={'__package__': 'pkg.fake'},
+                                            fromlist=['attr'], level=2)
         self.assertEquals(module.__name__, 'pkg')
 
     def test_using___name__(self):
         # [__name__]
-        with support.mock_modules('pkg.__init__', 'pkg.fake') as importer:
-            with support.import_state(meta_path=[importer]):
-                support.import_('pkg.fake')
-                module = support.import_('',
+        with util.mock_modules('pkg.__init__', 'pkg.fake') as importer:
+            with util.import_state(meta_path=[importer]):
+                import_util.import_('pkg.fake')
+                module = import_util.import_('',
                                  globals={'__name__': 'pkg.fake',
                                           '__path__': []},
                                  fromlist=['attr'], level=2)
@@ -54,12 +56,12 @@
 
     def test_bad__package__(self):
         globals = {'__package__': '<not real>'}
-        self.assertRaises(SystemError, support.import_,'', globals, {},
+        self.assertRaises(SystemError, import_util.import_,'', globals, {},
                             ['relimport'], 1)
 
     def test_bunk__package__(self):
         globals = {'__package__': 42}
-        self.assertRaises(ValueError, support.import_, '', globals, {},
+        self.assertRaises(ValueError, import_util.import_, '', globals, {},
                             ['relimport'], 1)
 
 
@@ -77,26 +79,26 @@
 
     # [top-level]
     def test_top_level(self):
-        with support.mock_modules('top_level') as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules('top_level') as mock:
+            with util.import_state(meta_path=[mock]):
                 del mock['top_level'].__package__
-                module = support.import_('top_level')
-                self.assert_(module.__package__ is None)
+                module = import_util.import_('top_level')
+                self.assertEqual(module.__package__, '')
 
     # [package]
     def test_package(self):
-        with support.mock_modules('pkg.__init__') as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules('pkg.__init__') as mock:
+            with util.import_state(meta_path=[mock]):
                 del mock['pkg'].__package__
-                module = support.import_('pkg')
+                module = import_util.import_('pkg')
                 self.assertEqual(module.__package__, 'pkg')
 
     # [submodule]
     def test_submodule(self):
-        with support.mock_modules('pkg.__init__', 'pkg.mod') as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules('pkg.__init__', 'pkg.mod') as mock:
+            with util.import_state(meta_path=[mock]):
                 del mock['pkg.mod'].__package__
-                pkg = support.import_('pkg.mod')
+                pkg = import_util.import_('pkg.mod')
                 module = getattr(pkg, 'mod')
                 self.assertEqual(module.__package__, 'pkg')
 

Modified: python/branches/io-c/Lib/importlib/test/import_/test_caching.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test_caching.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test_caching.py	Sun Feb  8 21:39:02 2009
@@ -1,6 +1,6 @@
 """Test that sys.modules is used properly by import."""
-from ..support import import_, mock_modules, importlib_only, import_state
-
+from .. import util
+from . import util as import_util
 import sys
 from types import MethodType
 import unittest
@@ -24,11 +24,11 @@
         # [use cache]
         module_to_use = "some module found!"
         sys.modules['some_module'] = module_to_use
-        module = import_('some_module')
+        module = import_util.import_('some_module')
         self.assertEqual(id(module_to_use), id(module))
 
     def create_mock(self, *names, return_=None):
-        mock = mock_modules(*names)
+        mock = util.mock_modules(*names)
         original_load = mock.load_module
         def load_module(self, fullname):
             original_load(fullname)
@@ -38,33 +38,34 @@
 
     # __import__ inconsistent between loaders and built-in import when it comes
     #   to when to use the module in sys.modules and when not to.
-    @importlib_only
+    @import_util.importlib_only
     def test_using_cache_after_loader(self):
         # [from cache on return]
         with self.create_mock('module') as mock:
-            with import_state(meta_path=[mock]):
-                module = import_('module')
+            with util.import_state(meta_path=[mock]):
+                module = import_util.import_('module')
                 self.assertEquals(id(module), id(sys.modules['module']))
 
     # See test_using_cache_after_loader() for reasoning.
-    @importlib_only
+    @import_util.importlib_only
     def test_using_cache_for_assigning_to_attribute(self):
         # [from cache to attribute]
         with self.create_mock('pkg.__init__', 'pkg.module') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg.module')
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg.module')
                 self.assert_(hasattr(module, 'module'))
                 self.assert_(id(module.module), id(sys.modules['pkg.module']))
 
     # See test_using_cache_after_loader() for reasoning.
-    @importlib_only
+    @import_util.importlib_only
     def test_using_cache_for_fromlist(self):
         # [from cache for fromlist]
         with self.create_mock('pkg.__init__', 'pkg.module') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg', fromlist=['module'])
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg', fromlist=['module'])
                 self.assert_(hasattr(module, 'module'))
-                self.assertEquals(id(module.module), id(sys.modules['pkg.module']))
+                self.assertEquals(id(module.module),
+                                  id(sys.modules['pkg.module']))
 
 
 def test_main():

Modified: python/branches/io-c/Lib/importlib/test/import_/test_fromlist.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test_fromlist.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test_fromlist.py	Sun Feb  8 21:39:02 2009
@@ -1,6 +1,6 @@
 """Test that the semantics relating to the 'fromlist' argument are correct."""
-from ..support import import_, mock_modules, import_state
-
+from .. import util
+from . import util as import_util
 import unittest
 
 class ReturnValue(unittest.TestCase):
@@ -16,16 +16,16 @@
 
     def test_return_from_import(self):
         # [import return]
-        with mock_modules('pkg.__init__', 'pkg.module') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg.module')
+        with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg.module')
                 self.assertEquals(module.__name__, 'pkg')
 
     def test_return_from_from_import(self):
         # [from return]
-        with mock_modules('pkg.__init__', 'pkg.module')as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg.module', fromlist=['attr'])
+        with util.mock_modules('pkg.__init__', 'pkg.module')as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg.module', fromlist=['attr'])
                 self.assertEquals(module.__name__, 'pkg.module')
 
 
@@ -48,59 +48,59 @@
 
     def test_object(self):
         # [object case]
-        with mock_modules('module') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('module', fromlist=['attr'])
+        with util.mock_modules('module') as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('module', fromlist=['attr'])
                 self.assertEquals(module.__name__, 'module')
 
     def test_unexistent_object(self):
         # [bad object]
-        with mock_modules('module') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('module', fromlist=['non_existent'])
+        with util.mock_modules('module') as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('module', fromlist=['non_existent'])
                 self.assertEquals(module.__name__, 'module')
                 self.assert_(not hasattr(module, 'non_existent'))
 
     def test_module_from_package(self):
         # [module]
-        with mock_modules('pkg.__init__', 'pkg.module') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg', fromlist=['module'])
+        with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg', fromlist=['module'])
                 self.assertEquals(module.__name__, 'pkg')
                 self.assert_(hasattr(module, 'module'))
                 self.assertEquals(module.module.__name__, 'pkg.module')
 
     def test_no_module_from_package(self):
         # [no module]
-        with mock_modules('pkg.__init__') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg', fromlist='non_existent')
+        with util.mock_modules('pkg.__init__') as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg', fromlist='non_existent')
                 self.assertEquals(module.__name__, 'pkg')
                 self.assert_(not hasattr(module, 'non_existent'))
 
     def test_empty_string(self):
-        with mock_modules('pkg.__init__', 'pkg.mod') as importer:
-            with import_state(meta_path=[importer]):
-                module = import_('pkg.mod', fromlist=[''])
+        with util.mock_modules('pkg.__init__', 'pkg.mod') as importer:
+            with util.import_state(meta_path=[importer]):
+                module = import_util.import_('pkg.mod', fromlist=[''])
                 self.assertEquals(module.__name__, 'pkg.mod')
 
     def test_using_star(self):
         # [using *]
-        with mock_modules('pkg.__init__', 'pkg.module') as mock:
-            with import_state(meta_path=[mock]):
+        with util.mock_modules('pkg.__init__', 'pkg.module') as mock:
+            with util.import_state(meta_path=[mock]):
                 mock['pkg'].__all__ = ['module']
-                module = import_('pkg', fromlist=['*'])
+                module = import_util.import_('pkg', fromlist=['*'])
                 self.assertEquals(module.__name__, 'pkg')
                 self.assert_(hasattr(module, 'module'))
                 self.assertEqual(module.module.__name__, 'pkg.module')
 
     def test_star_with_others(self):
         # [using * with others]
-        context = mock_modules('pkg.__init__', 'pkg.module1', 'pkg.module2')
+        context = util.mock_modules('pkg.__init__', 'pkg.module1', 'pkg.module2')
         with context as mock:
-            with import_state(meta_path=[mock]):
+            with util.import_state(meta_path=[mock]):
                 mock['pkg'].__all__ = ['module1']
-                module = import_('pkg', fromlist=['module2', '*'])
+                module = import_util.import_('pkg', fromlist=['module2', '*'])
                 self.assertEquals(module.__name__, 'pkg')
                 self.assert_(hasattr(module, 'module1'))
                 self.assert_(hasattr(module, 'module2'))

Modified: python/branches/io-c/Lib/importlib/test/import_/test_meta_path.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test_meta_path.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test_meta_path.py	Sun Feb  8 21:39:02 2009
@@ -1,5 +1,5 @@
-from ..support import import_state, mock_modules, import_
-
+from .. import util
+from . import util as import_util
 from contextlib import nested
 from types import MethodType
 import unittest
@@ -16,24 +16,25 @@
     def test_first_called(self):
         # [first called]
         mod = 'top_level'
-        first = mock_modules(mod)
-        second = mock_modules(mod)
-        with nested(mock_modules(mod), mock_modules(mod)) as (first, second):
+        first = util.mock_modules(mod)
+        second = util.mock_modules(mod)
+        context = nested(util.mock_modules(mod), util.mock_modules(mod))
+        with  context as (first, second):
             first.modules[mod] = 42
             second.modules[mod] = -13
-            with import_state(meta_path=[first, second]):
-                self.assertEquals(import_(mod), 42)
+            with util.import_state(meta_path=[first, second]):
+                self.assertEquals(import_util.import_(mod), 42)
 
     def test_continuing(self):
         # [continuing]
         mod_name = 'for_real'
-        first = mock_modules('nonexistent')
-        second = mock_modules(mod_name)
+        first = util.mock_modules('nonexistent')
+        second = util.mock_modules(mod_name)
         with nested(first, second):
             first.find_module = lambda self, fullname, path=None: None
             second.modules[mod_name] = 42
-            with import_state(meta_path=[first, second]):
-                self.assertEquals(import_(mod_name), 42)
+            with util.import_state(meta_path=[first, second]):
+                self.assertEquals(import_util.import_(mod_name), 42)
 
 
 class CallSignature(unittest.TestCase):
@@ -54,11 +55,11 @@
         # [no path]
         mod_name = 'top_level'
         assert '.' not in mod_name
-        with mock_modules(mod_name) as importer:
+        with util.mock_modules(mod_name) as importer:
             log, wrapped_call = self.log(importer.find_module)
             importer.find_module = MethodType(wrapped_call, importer)
-            with import_state(meta_path=[importer]):
-                import_(mod_name)
+            with util.import_state(meta_path=[importer]):
+                import_util.import_(mod_name)
                 assert len(log) == 1
                 args = log[0][0]
                 kwargs = log[0][1]
@@ -74,12 +75,12 @@
         mod_name = pkg_name + '.module'
         path = [42]
         assert '.' in mod_name
-        with mock_modules(pkg_name+'.__init__', mod_name) as importer:
+        with util.mock_modules(pkg_name+'.__init__', mod_name) as importer:
             importer.modules[pkg_name].__path__ = path
             log, wrapped_call = self.log(importer.find_module)
             importer.find_module = MethodType(wrapped_call, importer)
-            with import_state(meta_path=[importer]):
-                import_(mod_name)
+            with util.import_state(meta_path=[importer]):
+                import_util.import_(mod_name)
                 assert len(log) == 2
                 args = log[1][0]
                 kwargs = log[1][1]

Modified: python/branches/io-c/Lib/importlib/test/import_/test_packages.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test_packages.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test_packages.py	Sun Feb  8 21:39:02 2009
@@ -1,7 +1,8 @@
+from .. import util
+from . import util as import_util
 import sys
 import unittest
 import importlib
-from .. import support
 
 
 class ParentModuleTests(unittest.TestCase):
@@ -9,15 +10,16 @@
     """Importing a submodule should import the parent modules."""
 
     def test_import_parent(self):
-        with support.mock_modules('pkg.__init__', 'pkg.module') as mock:
-            with support.import_state(meta_path=[mock]):
-                module = support.import_('pkg.module')
+        with util.mock_modules('pkg.__init__', 'pkg.module') as mock:
+            with util.import_state(meta_path=[mock]):
+                module = import_util.import_('pkg.module')
                 self.assert_('pkg' in sys.modules)
 
     def test_bad_parent(self):
-        with support.mock_modules('pkg.module') as mock:
-            with support.import_state(meta_path=[mock]):
-                self.assertRaises(ImportError, support.import_, 'pkg.module')
+        with util.mock_modules('pkg.module') as mock:
+            with util.import_state(meta_path=[mock]):
+                self.assertRaises(ImportError,
+                                    import_util.import_, 'pkg.module')
 
 
 def test_main():

Modified: python/branches/io-c/Lib/importlib/test/import_/test_path.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test_path.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test_path.py	Sun Feb  8 21:39:02 2009
@@ -1,158 +1,106 @@
-from ..support import (mock_modules, import_state, import_, mock_path_hook,
-                        importlib_only, uncache)
-
+from importlib import machinery
+from .. import util
+from . import util as import_util
 from contextlib import nested
-from imp import new_module
+import imp
+import os
 import sys
+from test import support
 from types import MethodType
 import unittest
 
 
-class BaseTests(unittest.TestCase):
+class FinderTests(unittest.TestCase):
 
-    """When sys.meta_path cannot find the desired module, sys.path is
-    consulted. For each entry on the sequence [order], sys.path_importer_cache
-    is checked to see if it contains a key for the entry [cache check]. If an
-    importer is found then it is consulted before trying the next entry in
-    sys.path [cache use]. The 'path' argument to find_module() is never used
-    when trying to find a module [path not used].
-
-    If an entry from sys.path is not in sys.path_importer_cache, sys.path_hooks
-    is called in turn [hooks order]. If a path hook cannot handle an entry,
-    ImportError is raised [hook failure]. Otherwise the resulting object is
-    cached in sys.path_importer_cache and then consulted [hook success]. If no
-    hook is found, None is set in sys.path_importer_cache and the default
-    importer is tried [no hook].
-
-    For use of __path__ in a package, the above is all true, just substitute
-    "sys.path" for "__path__".
-
-    """
-
-    def order_test(self, to_import, entry, search_path, path=[]):
-        # [order]
-        log = []
-        class LogFindModule(mock_modules):
-            def find_module(self, fullname):
-                log.append(self)
-                return super().find_module(fullname)
-
-        assert len(search_path) == 2
-        misser = LogFindModule(search_path[0])
-        hitter = LogFindModule(to_import)
-        with nested(misser, hitter):
-            cache = dict(zip(search_path, (misser, hitter)))
-            with import_state(path=path, path_importer_cache=cache):
-                import_(to_import)
-        self.assertEquals(log[0], misser)
-        self.assertEquals(log[1], hitter)
-
-    @importlib_only  # __import__ uses PyDict_GetItem(), bypassing log.
-    def cache_use_test(self, to_import, entry, path=[]):
-        # [cache check], [cache use]
-        log = []
-        class LoggingDict(dict):
-            def __getitem__(self, item):
-                log.append(item)
-                return super(LoggingDict, self).__getitem__(item)
-
-        with mock_modules(to_import) as importer:
-            cache = LoggingDict()
-            cache[entry] = importer
-            with import_state(path=[entry], path_importer_cache=cache):
-                module = import_(to_import, fromlist=['a'])
-            self.assert_(module is importer[to_import])
-        self.assertEquals(len(cache), 1)
-        self.assertEquals([entry], log)
-
-    def hooks_order_test(self, to_import, entry, path=[]):
-        # [hooks order], [hooks failure], [hook success]
-        log = []
-        def logging_hook(entry):
-            log.append(entry)
-            raise ImportError
-        with mock_modules(to_import) as importer:
-            hitter = mock_path_hook(entry, importer=importer)
-            path_hooks = [logging_hook, logging_hook, hitter]
-            with import_state(path_hooks=path_hooks, path=path):
-                import_(to_import)
-                self.assertEquals(sys.path_importer_cache[entry], importer)
-        self.assertEquals(len(log), 2)
-
-    # [no hook] XXX Worry about after deciding how to handle the default hook.
-
-    def path_argument_test(self, to_import):
-        # [path not used]
-        class BadImporter:
-            """Class to help detect TypeError from calling find_module() with
-            an improper number of arguments."""
-            def find_module(name):
-                raise ImportError
+    """Tests for SysPathImporter."""
 
+    def test_failure(self):
+        # Test None returned upon not finding a suitable finder.
+        def mock_implicit_hooks():
+            return []
+        # XXX Not blackbox.
+        original_hooks = machinery.PathFinder._implicit_hooks
+        machinery.PathFinder._implicit_hooks = staticmethod(mock_implicit_hooks)
         try:
-            import_(to_import)
-        except ImportError:
-            pass
-
-
-class PathTests(BaseTests):
-
-    """Tests for sys.path."""
-
-    def test_order(self):
-        self.order_test('hit', 'second', ['first', 'second'],
-                        ['first', 'second'])
-
-    def test_cache_use(self):
-        entry = "found!"
-        self.cache_use_test('hit', entry, [entry])
-
-    def test_hooks_order(self):
-        entry = "found!"
-        self.hooks_order_test('hit', entry, [entry])
-
-    def test_path_argument(self):
-        name = 'total junk'
-        with uncache(name):
-            self.path_argument_test(name)
-
-
-class __path__Tests(BaseTests):
-
-    """Tests for __path__."""
-
-    def run_test(self, test, entry, path, *args):
-        with mock_modules('pkg.__init__') as importer:
-            importer['pkg'].__path__ = path
-            importer.load_module('pkg')
-            test('pkg.hit', entry, *args)
-
-
-    @importlib_only  # XXX Unknown reason why this fails.
-    def test_order(self):
-        self.run_test(self.order_test, 'second', ('first', 'second'), ['first',
-            'second'])
-
-    def test_cache_use(self):
-        location = "I'm here!"
-        self.run_test(self.cache_use_test, location, [location])
-
-    def test_hooks_order(self):
-        location = "I'm here!"
-        self.run_test(self.hooks_order_test, location, [location])
-
-    def test_path_argument(self):
-        module = new_module('pkg')
-        module.__path__ = ['random __path__']
-        name = 'pkg.whatever'
-        sys.modules['pkg'] = module
-        with uncache('pkg', name):
-            self.path_argument_test(name)
+            with util.import_state():
+                self.assert_(machinery.PathFinder.find_module('XXX') is None)
+        finally:
+            machinery.PathFinder._implicit_hooks = original_hooks
+
+    def test_sys_path(self):
+        # Test that sys.path is used when 'path' is None.
+        # Implicitly tests that sys.path_importer_cache is used.
+        module = '<test module>'
+        path = '<test path>'
+        importer = util.mock_modules(module)
+        with util.import_state(path_importer_cache={path: importer},
+                               path=[path]):
+            loader = machinery.PathFinder.find_module(module)
+            self.assert_(loader is importer)
+
+    def test_path(self):
+        # Test that 'path' is used when set.
+        # Implicitly tests that sys.path_importer_cache is used.
+        module = '<test module>'
+        path = '<test path>'
+        importer = util.mock_modules(module)
+        with util.import_state(path_importer_cache={path: importer}):
+            loader = machinery.PathFinder.find_module(module, [path])
+            self.assert_(loader is importer)
+
+    def test_path_importer_cache_has_None(self):
+        # Test that the default hook is used when sys.path_importer_cache
+        # contains None for a path.
+        module = '<test module>'
+        importer = util.mock_modules(module)
+        path = '<test path>'
+        # XXX Not blackbox.
+        original_hook = machinery.PathFinder._default_hook
+        mock_hook = import_util.mock_path_hook(path, importer=importer)
+        machinery.PathFinder._default_hook = staticmethod(mock_hook)
+        try:
+            with util.import_state(path_importer_cache={path: None}):
+                loader = machinery.PathFinder.find_module(module, path=[path])
+                self.assert_(loader is importer)
+        finally:
+            machinery.PathFinder._default_hook = original_hook
+
+    def test_path_hooks(self):
+        # Test that sys.path_hooks is used.
+        # Test that sys.path_importer_cache is set.
+        module = '<test module>'
+        path = '<test path>'
+        importer = util.mock_modules(module)
+        hook = import_util.mock_path_hook(path, importer=importer)
+        with util.import_state(path_hooks=[hook]):
+            loader = machinery.PathFinder.find_module(module, [path])
+            self.assert_(loader is importer)
+            self.assert_(path in sys.path_importer_cache)
+            self.assert_(sys.path_importer_cache[path] is importer)
+
+    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 = machinery.PathFinder.find_module(module,
+                                                       path=[existing_path])
+            self.assert_(nothing is None)
+            self.assert_(existing_path in sys.path_importer_cache)
+            self.assert_(not isinstance(sys.path_importer_cache[existing_path],
+                                        imp.NullImporter))
+            nothing = machinery.PathFinder.find_module(module, path=[bad_path])
+            self.assert_(nothing is None)
+            self.assert_(bad_path in sys.path_importer_cache)
+            self.assert_(isinstance(sys.path_importer_cache[bad_path],
+                                    imp.NullImporter))
 
 
 def test_main():
     from test.support import run_unittest
-    run_unittest(PathTests, __path__Tests)
+    run_unittest(PathTests, __path__Tests, FinderTests)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/io-c/Lib/importlib/test/import_/test_relative_imports.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/import_/test_relative_imports.py	(original)
+++ python/branches/io-c/Lib/importlib/test/import_/test_relative_imports.py	Sun Feb  8 21:39:02 2009
@@ -1,7 +1,6 @@
 """Test relative imports (PEP 328)."""
-
-from ..support import uncache, import_, mock_modules, import_state
-
+from .. import util
+from . import util as import_util
 import sys
 import unittest
 
@@ -65,10 +64,10 @@
                 uncache_names.append(name)
             else:
                 uncache_names.append(name[:-len('.__init__')])
-        with mock_modules(*create) as importer:
-            with import_state(meta_path=[importer]):
+        with util.mock_modules(*create) as importer:
+            with util.import_state(meta_path=[importer]):
                 for global_ in globals_:
-                    with uncache(*uncache_names):
+                    with util.uncache(*uncache_names):
                         callback(global_)
 
 
@@ -77,8 +76,8 @@
         create = 'pkg.__init__', 'pkg.mod2'
         globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
         def callback(global_):
-            import_('pkg')  # For __import__().
-            module = import_('', global_, fromlist=['mod2'], level=1)
+            import_util.import_('pkg')  # For __import__().
+            module = import_util.import_('', global_, fromlist=['mod2'], level=1)
             self.assertEqual(module.__name__, 'pkg')
             self.assert_(hasattr(module, 'mod2'))
             self.assertEqual(module.mod2.attr, 'pkg.mod2')
@@ -89,8 +88,9 @@
         create = 'pkg.__init__', 'pkg.mod2'
         globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
         def callback(global_):
-            import_('pkg')  # For __import__().
-            module = import_('mod2', global_, fromlist=['attr'], level=1)
+            import_util.import_('pkg')  # For __import__().
+            module = import_util.import_('mod2', global_, fromlist=['attr'],
+                                            level=1)
             self.assertEqual(module.__name__, 'pkg.mod2')
             self.assertEqual(module.attr, 'pkg.mod2')
         self.relative_import_test(create, globals_, callback)
@@ -101,8 +101,8 @@
         globals_ = ({'__package__': 'pkg'},
                     {'__name__': 'pkg', '__path__': ['blah']})
         def callback(global_):
-            import_('pkg')  # For __import__().
-            module = import_('', global_, fromlist=['module'],
+            import_util.import_('pkg')  # For __import__().
+            module = import_util.import_('', global_, fromlist=['module'],
                              level=1)
             self.assertEqual(module.__name__, 'pkg')
             self.assert_(hasattr(module, 'module'))
@@ -114,8 +114,8 @@
         create = 'pkg.__init__', 'pkg.module'
         globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
         def callback(global_):
-            import_('pkg')  # For __import__().
-            module = import_('', global_, fromlist=['attr'], level=1)
+            import_util.import_('pkg')  # For __import__().
+            module = import_util.import_('', global_, fromlist=['attr'], level=1)
             self.assertEqual(module.__name__, 'pkg')
         self.relative_import_test(create, globals_, callback)
 
@@ -126,7 +126,8 @@
         globals_ =  ({'__package__': 'pkg.subpkg1'},
                      {'__name__': 'pkg.subpkg1', '__path__': ['blah']})
         def callback(global_):
-            module = import_('', global_, fromlist=['subpkg2'], level=2)
+            module = import_util.import_('', global_, fromlist=['subpkg2'],
+                                            level=2)
             self.assertEqual(module.__name__, 'pkg')
             self.assert_(hasattr(module, 'subpkg2'))
             self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__')
@@ -141,8 +142,8 @@
                     {'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5',
                         '__path__': ['blah']})
         def callback(global_):
-            import_(globals_[0]['__package__'])
-            module = import_('', global_, fromlist=['attr'], level=6)
+            import_util.import_(globals_[0]['__package__'])
+            module = import_util.import_('', global_, fromlist=['attr'], level=6)
             self.assertEqual(module.__name__, 'pkg')
         self.relative_import_test(create, globals_, callback)
 
@@ -152,8 +153,8 @@
         globals_ = ({'__package__': 'pkg'},
                     {'__name__': 'pkg', '__path__': ['blah']})
         def callback(global_):
-            import_('pkg')
-            self.assertRaises(ValueError, import_, '', global_,
+            import_util.import_('pkg')
+            self.assertRaises(ValueError, import_util.import_, '', global_,
                                 fromlist=['top_level'], level=2)
         self.relative_import_test(create, globals_, callback)
 
@@ -162,14 +163,14 @@
         create = ['top_level', 'pkg.__init__', 'pkg.module']
         globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
         def callback(global_):
-            import_('pkg')
-            self.assertRaises(ValueError, import_, '', global_,
+            import_util.import_('pkg')
+            self.assertRaises(ValueError, import_util.import_, '', global_,
                                 fromlist=['top_level'], level=2)
         self.relative_import_test(create, globals_, callback)
 
     def test_empty_name_w_level_0(self):
         # [empty name]
-        self.assertRaises(ValueError, import_, '')
+        self.assertRaises(ValueError, import_util.import_, '')
 
     def test_import_from_different_package(self):
         # Test importing from a different package than the caller.
@@ -183,8 +184,9 @@
                     '__runpy_pkg__.uncle.cousin.nephew']
         globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'}
         def callback(global_):
-            import_('__runpy_pkg__.__runpy_pkg__')
-            module = import_('uncle.cousin', globals_, {}, fromlist=['nephew'],
+            import_util.import_('__runpy_pkg__.__runpy_pkg__')
+            module = import_util.import_('uncle.cousin', globals_, {},
+                                    fromlist=['nephew'],
                                 level=2)
             self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin')
         self.relative_import_test(create, globals_, callback)

Deleted: python/branches/io-c/Lib/importlib/test/loader_tests.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/loader_tests.py	Sun Feb  8 21:39:02 2009
+++ (empty file)
@@ -1,61 +0,0 @@
-import abc
-import unittest
-
-
-class LoaderTests(unittest.TestCase, metaclass=abc.ABCMeta):
-
-    @abc.abstractmethod
-    def test_module(self):
-        """A module should load without issue.
-
-        After the loader returns the module should be in sys.modules.
-
-        Attributes to verify:
-
-            * __file__
-            * __loader__
-            * __name__
-            * No __path__
-
-        """
-        pass
-
-    @abc.abstractmethod
-    def test_package(self):
-        """Loading a package should work.
-
-        After the loader returns the module should be in sys.modules.
-
-        Attributes to verify:
-
-            * __file__
-            * __loader__
-            * __name__
-            * __path__
-
-        """
-        pass
-
-    @abc.abstractmethod
-    def test_lacking_parent(self):
-        """A loader should not be dependent on it's parent package being
-        imported."""
-        pass
-
-    @abc.abstractmethod
-    def test_module_reuse(self):
-        """If a module is already in sys.modules, it should be reused."""
-        pass
-
-    @abc.abstractmethod
-    def test_state_after_failure(self):
-        """If a module is already in sys.modules and a reload fails
-        (e.g. a SyntaxError), the module should be in the state it was before
-        the reload began."""
-        pass
-
-    @abc.abstractmethod
-    def test_unloadable(self):
-        """Test ImportError is raised when the loader is asked to load a module
-        it can't."""
-        pass

Modified: python/branches/io-c/Lib/importlib/test/source/test_case_sensitivity.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/source/test_case_sensitivity.py	(original)
+++ python/branches/io-c/Lib/importlib/test/source/test_case_sensitivity.py	Sun Feb  8 21:39:02 2009
@@ -1,13 +1,14 @@
 """Test case-sensitivity (PEP 235)."""
 import importlib
-from .. import support
+from .. import util
+from . import util as source_util
 import os
 import sys
 from test import support as test_support
 import unittest
 
 
- at support.case_insensitive_tests
+ at util.case_insensitive_tests
 class CaseSensitivityTest(unittest.TestCase):
 
     """PEP 235 dictates that on case-preserving, case-insensitive file systems
@@ -25,7 +26,8 @@
         """Look for a module with matching and non-matching sensitivity."""
         sensitive_pkg = 'sensitive.{0}'.format(self.name)
         insensitive_pkg = 'insensitive.{0}'.format(self.name.lower())
-        with support.create_modules(insensitive_pkg, sensitive_pkg) as mapping:
+        context = source_util.create_modules(insensitive_pkg, sensitive_pkg)
+        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)

Modified: python/branches/io-c/Lib/importlib/test/source/test_finder.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/source/test_finder.py	(original)
+++ python/branches/io-c/Lib/importlib/test/source/test_finder.py	Sun Feb  8 21:39:02 2009
@@ -1,13 +1,13 @@
 import importlib
-from .. import finder_tests
-from .. import support
+from .. import abc
+from . import util as source_util
 import os
 import py_compile
 import unittest
 import warnings
 
 
-class FinderTests(finder_tests.FinderTests):
+class FinderTests(abc.FinderTests):
 
     """For a top-level module, it should just be found directly in the
     directory being searched. This is true for a directory with source
@@ -45,7 +45,7 @@
         """
         if create is None:
             create = {test}
-        with support.create_modules(*create) as mapping:
+        with source_util.create_modules(*create) as mapping:
             if compile_:
                 for name in compile_:
                     py_compile.compile(mapping[name])
@@ -76,14 +76,14 @@
 
     # [sub module]
     def test_module_in_package(self):
-        with support.create_modules('pkg.__init__', 'pkg.sub') as mapping:
+        with source_util.create_modules('pkg.__init__', 'pkg.sub') as mapping:
             pkg_dir = os.path.dirname(mapping['pkg.__init__'])
             loader = self.import_(pkg_dir, 'pkg.sub')
             self.assert_(hasattr(loader, 'load_module'))
 
     # [sub package]
     def test_package_in_package(self):
-        context = support.create_modules('pkg.__init__', 'pkg.sub.__init__')
+        context = source_util.create_modules('pkg.__init__', 'pkg.sub.__init__')
         with context as mapping:
             pkg_dir = os.path.dirname(mapping['pkg.__init__'])
             loader = self.import_(pkg_dir, 'pkg.sub')
@@ -91,7 +91,7 @@
 
     # [sub empty]
     def test_empty_sub_directory(self):
-        context = support.create_modules('pkg.__init__', 'pkg.sub.__init__')
+        context = source_util.create_modules('pkg.__init__', 'pkg.sub.__init__')
         with warnings.catch_warnings():
             warnings.simplefilter("error", ImportWarning)
             with context as mapping:
@@ -109,7 +109,7 @@
 
 
     def test_failure(self):
-        with support.create_modules('blah') as mapping:
+        with source_util.create_modules('blah') as mapping:
             nothing = self.import_(mapping['.root'], 'sdfsadsadf')
             self.assert_(nothing is None)
 

Modified: python/branches/io-c/Lib/importlib/test/source/test_loader.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/source/test_loader.py	(original)
+++ python/branches/io-c/Lib/importlib/test/source/test_loader.py	Sun Feb  8 21:39:02 2009
@@ -1,5 +1,6 @@
 import importlib
-from .. import support
+from .. import abc
+from . import util as source_util
 
 import imp
 import os
@@ -16,15 +17,84 @@
     """
 
     # [basic]
-    def test_basic(self):
-        with support.create_modules('_temp') as mapping:
+    def test_module(self):
+        with source_util.create_modules('_temp') as mapping:
             loader = importlib._PyFileLoader('_temp', mapping['_temp'], False)
-            loader.load_module('_temp')
+            module = loader.load_module('_temp')
             self.assert_('_temp' in sys.modules)
+            check = {'__name__': '_temp', '__file__': mapping['_temp'],
+                     '__package__': ''}
+            for attr, value in check.items():
+                self.assertEqual(getattr(module, attr), value)
+
+    def test_package(self):
+        with source_util.create_modules('_pkg.__init__') as mapping:
+            loader = importlib._PyFileLoader('_pkg', mapping['_pkg.__init__'],
+                                             True)
+            module = loader.load_module('_pkg')
+            self.assert_('_pkg' in sys.modules)
+            check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'],
+                     '__path__': [os.path.dirname(mapping['_pkg.__init__'])],
+                     '__package__': '_pkg'}
+            for attr, value in check.items():
+                self.assertEqual(getattr(module, attr), value)
+
+
+    def test_lacking_parent(self):
+        with source_util.create_modules('_pkg.__init__', '_pkg.mod')as mapping:
+            loader = importlib._PyFileLoader('_pkg.mod', mapping['_pkg.mod'],
+                                             False)
+            module = loader.load_module('_pkg.mod')
+            self.assert_('_pkg.mod' in sys.modules)
+            check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'],
+                     '__package__': '_pkg'}
+            for attr, value in check.items():
+                self.assertEqual(getattr(module, attr), value)
+
+    def fake_mtime(self, fxn):
+        """Fake mtime to always be higher than expected."""
+        return lambda name: fxn(name) + 1
+
+    def test_module_reuse(self):
+        with source_util.create_modules('_temp') as mapping:
+            loader = importlib._PyFileLoader('_temp', mapping['_temp'], False)
+            module = loader.load_module('_temp')
+            module_id = id(module)
+            module_dict_id = id(module.__dict__)
+            with open(mapping['_temp'], 'w') as file:
+                file.write("testing_var = 42\n")
+            # For filesystems where the mtime is only to a second granularity,
+            # 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)
+            module = loader.load_module('_temp')
+            self.assert_('testing_var' in module.__dict__,
+                         "'testing_var' not in "
+                            "{0}".format(list(module.__dict__.keys())))
+            self.assertEqual(module, sys.modules['_temp'])
+            self.assertEqual(id(module), module_id)
+            self.assertEqual(id(module.__dict__), module_dict_id)
+
+    def test_state_after_failure(self):
+        # A failed reload should leave the original module intact.
+        attributes = ('__file__', '__path__', '__package__')
+        value = '<test>'
+        name = '_temp'
+        with source_util.create_modules(name) as mapping:
+            orig_module = imp.new_module(name)
+            for attr in attributes:
+                setattr(orig_module, attr, value)
+            with open(mapping[name], 'w') as file:
+                file.write('+++ bad syntax +++')
+            loader = importlib._PyFileLoader('_temp', mapping['_temp'], False)
+            self.assertRaises(SyntaxError, loader.load_module, name)
+            for attr in attributes:
+                self.assertEqual(getattr(orig_module, attr), value)
 
     # [syntax error]
     def test_bad_syntax(self):
-        with support.create_modules('_temp') as mapping:
+        with source_util.create_modules('_temp') as mapping:
             with open(mapping['_temp'], 'w') as file:
                 file.write('=')
             loader = importlib._PyFileLoader('_temp', mapping['_temp'], False)
@@ -39,12 +109,12 @@
     def tearDown(self):
         sys.dont_write_bytecode = False
 
-    @support.writes_bytecode
+    @source_util.writes_bytecode
     def run_test(self, assertion):
-        with support.create_modules('_temp') as mapping:
+        with source_util.create_modules('_temp') as mapping:
             loader = importlib._PyFileLoader('_temp', mapping['_temp'], False)
             loader.load_module('_temp')
-            bytecode_path = support.bytecode_path(mapping['_temp'])
+            bytecode_path = source_util.bytecode_path(mapping['_temp'])
             assertion(bytecode_path)
 
     def test_bytecode_written(self):
@@ -67,10 +137,10 @@
 
     # [bad magic]
     def test_bad_magic(self):
-        with support.create_modules('_temp') as mapping:
+        with source_util.create_modules('_temp') as mapping:
             py_compile.compile(mapping['_temp'])
             os.unlink(mapping['_temp'])
-            bytecode_path = support.bytecode_path(mapping['_temp'])
+            bytecode_path = source_util.bytecode_path(mapping['_temp'])
             with open(bytecode_path, 'r+b') as file:
                 file.seek(0)
                 file.write(b'\x00\x00\x00\x00')
@@ -94,7 +164,7 @@
 
     def run_test(self, test, *create, pkg=False):
         create += (test,)
-        with support.create_modules(*create) as mapping:
+        with source_util.create_modules(*create) as mapping:
             for name in create:
                 py_compile.compile(mapping[name])
             if pkg:
@@ -147,11 +217,11 @@
         self.assert_(module_name in sys.modules)
 
     # [bad magic]
-    @support.writes_bytecode
+    @source_util.writes_bytecode
     def test_bad_magic(self):
-        with support.create_modules('_temp') as mapping:
+        with source_util.create_modules('_temp') as mapping:
             py_compile.compile(mapping['_temp'])
-            bytecode_path = support.bytecode_path(mapping['_temp'])
+            bytecode_path = source_util.bytecode_path(mapping['_temp'])
             with open(bytecode_path, 'r+b') as bytecode_file:
                 bytecode_file.seek(0)
                 bytecode_file.write(b'\x00\x00\x00\x00')
@@ -160,12 +230,12 @@
                 self.assertEqual(bytecode_file.read(4), imp.get_magic())
 
     # [bad timestamp]
-    @support.writes_bytecode
+    @source_util.writes_bytecode
     def test_bad_bytecode(self):
         zeros = b'\x00\x00\x00\x00'
-        with support.create_modules('_temp') as mapping:
+        with source_util.create_modules('_temp') as mapping:
             py_compile.compile(mapping['_temp'])
-            bytecode_path = support.bytecode_path(mapping['_temp'])
+            bytecode_path = source_util.bytecode_path(mapping['_temp'])
             with open(bytecode_path, 'r+b') as bytecode_file:
                 bytecode_file.seek(4)
                 bytecode_file.write(zeros)
@@ -178,8 +248,8 @@
 
     # [bad marshal]
     def test_bad_marshal(self):
-        with support.create_modules('_temp') as mapping:
-            bytecode_path = support.bytecode_path(mapping['_temp'])
+        with source_util.create_modules('_temp') as mapping:
+            bytecode_path = source_util.bytecode_path(mapping['_temp'])
             source_mtime = os.path.getmtime(mapping['_temp'])
             source_timestamp = importlib._w_long(source_mtime)
             with open(bytecode_path, 'wb') as bytecode_file:

Modified: python/branches/io-c/Lib/importlib/test/source/test_path_hook.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/source/test_path_hook.py	(original)
+++ python/branches/io-c/Lib/importlib/test/source/test_path_hook.py	Sun Feb  8 21:39:02 2009
@@ -1,5 +1,5 @@
 import importlib
-from .. import support
+from . import util as source_util
 import unittest
 
 
@@ -9,7 +9,7 @@
 
     def test_success(self):
         # XXX Only work on existing directories?
-        with support.create_modules('dummy') as mapping:
+        with source_util.create_modules('dummy') as mapping:
             self.assert_(hasattr(importlib.FileImporter(mapping['.root']),
                                  'find_module'))
 

Deleted: python/branches/io-c/Lib/importlib/test/source/test_reload.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/source/test_reload.py	Sun Feb  8 21:39:02 2009
+++ (empty file)
@@ -1,71 +0,0 @@
-"""Test reload support.
-
-Reload support requires two things. One is that if module is loaded that
-already exists in sys.modules then it is reused. And two, if a reload fails the
-pre-existing module is left in a sane state.
-
-"""
-import imp
-import sys
-import types
-import unittest
-import importlib
-from .. import support
-
-
-class ReloadTests(unittest.TestCase):
-
-    name = '_temp'
-
-    def load_module(self, mapping):
-        return importlib._PyFileLoader(self.name, mapping[self.name], False)
-
-    def fake_mtime(self, fxn):
-        """Fake mtime to always be higher than expected."""
-        return lambda name: fxn(name) + 1
-
-    def test_module_reuse(self):
-        with support.create_modules(self.name) as mapping:
-            loader = self.load_module(mapping)
-            module = loader.load_module(self.name)
-            module_id = id(module)
-            module_dict_id = id(module.__dict__)
-            with open(mapping[self.name], 'w') as file:
-                file.write("testing_var = 42\n")
-            # For filesystems where the mtime is only to a second granularity,
-            # 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)
-            module = loader.load_module(self.name)
-            self.assert_('testing_var' in module.__dict__,
-                         "'testing_var' not in "
-                            "{0}".format(list(module.__dict__.keys())))
-            self.assertEqual(module, sys.modules[self.name])
-            self.assertEqual(id(module), module_id)
-            self.assertEqual(id(module.__dict__), module_dict_id)
-
-    def test_bad_reload(self):
-        # A failed reload should leave the original module intact.
-        attributes = ('__file__', '__path__', '__package__')
-        value = '<test>'
-        with support.create_modules(self.name) as mapping:
-            orig_module = imp.new_module(self.name)
-            for attr in attributes:
-                setattr(orig_module, attr, value)
-            with open(mapping[self.name], 'w') as file:
-                file.write('+++ bad syntax +++')
-            loader = self.load_module(mapping)
-            self.assertRaises(SyntaxError, loader.load_module, self.name)
-            for attr in attributes:
-                self.assertEqual(getattr(orig_module, attr), value)
-
-
-
-def test_main():
-    from test.support import run_unittest
-    run_unittest(ReloadTests)
-
-
-if __name__ == '__main__':
-    test_main()

Modified: python/branches/io-c/Lib/importlib/test/source/test_source_encoding.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/source/test_source_encoding.py	(original)
+++ python/branches/io-c/Lib/importlib/test/source/test_source_encoding.py	Sun Feb  8 21:39:02 2009
@@ -1,5 +1,5 @@
 import importlib
-from .. import support
+from . import util as source_util
 
 import codecs
 import re
@@ -32,7 +32,7 @@
     module_name = '_temp'
 
     def run_test(self, source):
-        with support.create_modules(self.module_name) as mapping:
+        with source_util.create_modules(self.module_name) as mapping:
             with open(mapping[self.module_name], 'wb')as file:
                 file.write(source)
             loader = importlib._PyFileLoader(self.module_name,
@@ -93,7 +93,7 @@
         module_name = '_temp'
         source_lines = [b"a = 42", b"b = -13", b'']
         source = line_ending.join(source_lines)
-        with support.create_modules(module_name) as mapping:
+        with source_util.create_modules(module_name) as mapping:
             with open(mapping[module_name], 'wb') as file:
                 file.write(source)
             loader = importlib._PyFileLoader(module_name, mapping[module_name],

Deleted: python/branches/io-c/Lib/importlib/test/support.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/support.py	Sun Feb  8 21:39:02 2009
+++ (empty file)
@@ -1,233 +0,0 @@
-from importlib import Import
-
-from contextlib import contextmanager
-from functools import update_wrapper
-import imp
-import os.path
-from test.support import unlink
-import sys
-from tempfile import gettempdir
-
-
-using___import__ = False
-
-def import_(*args, **kwargs):
-    """Delegate to allow for injecting different implementations of import."""
-    if using___import__:
-        return __import__(*args, **kwargs)
-    return Import()(*args, **kwargs)
-
-def importlib_only(fxn):
-    """Decorator to mark which tests are not supported by the current
-    implementation of __import__()."""
-    def inner(*args, **kwargs):
-        if using___import__:
-            return
-        else:
-            return fxn(*args, **kwargs)
-    update_wrapper(inner, fxn)
-    return inner
-
-def writes_bytecode(fxn):
-    """Decorator that returns the function if writing bytecode is enabled, else
-    a stub function that accepts anything and simply returns None."""
-    if sys.dont_write_bytecode:
-        return lambda *args, **kwargs: None
-    else:
-        return fxn
-
-
-def case_insensitive_tests(class_):
-    """Class decorator that nullifies tests that require a case-insensitive
-    file system."""
-    if sys.platform not in ('win32', 'darwin', 'cygwin'):
-        return object()
-    else:
-        return class_
-
-
- at contextmanager
-def uncache(*names):
-    """Uncache a module from sys.modules.
-
-    A basic sanity check is performed to prevent uncaching modules that either
-    cannot/shouldn't be uncached.
-
-    """
-    for name in names:
-        if name in ('sys', 'marshal', 'imp'):
-            raise ValueError(
-                "cannot uncache {0} as it will break _importlib".format(name))
-        try:
-            del sys.modules[name]
-        except KeyError:
-            pass
-    try:
-        yield
-    finally:
-        for name in names:
-            try:
-                del sys.modules[name]
-            except KeyError:
-                pass
-
- at contextmanager
-def import_state(**kwargs):
-    """Context manager to manage the various importers and stored state in the
-    sys module.
-
-    The 'modules' attribute is not supported as the interpreter state stores a
-    pointer to the dict that the interpreter uses internally;
-    reassigning to sys.modules does not have the desired effect.
-
-    """
-    originals = {}
-    try:
-        for attr, default in (('meta_path', []), ('path', []),
-                              ('path_hooks', []),
-                              ('path_importer_cache', {})):
-            originals[attr] = getattr(sys, attr)
-            if attr in kwargs:
-                new_value = kwargs[attr]
-                del kwargs[attr]
-            else:
-                new_value = default
-            setattr(sys, attr, new_value)
-        if len(kwargs):
-            raise ValueError(
-                    'unrecognized arguments: {0}'.format(kwargs.keys()))
-        yield
-    finally:
-        for attr, value in originals.items():
-            setattr(sys, attr, value)
-
-
- at contextmanager
-def create_modules(*names):
-    """Temporarily create each named module with an attribute (named 'attr')
-    that contains the name passed into the context manager that caused the
-    creation of the module.
-
-    All files are created in a temporary directory specified by
-    tempfile.gettempdir(). This directory is inserted at the beginning of
-    sys.path. When the context manager exits all created files (source and
-    bytecode) are explicitly deleted.
-
-    No magic is performed when creating packages! This means that if you create
-    a module within a package you must also create the package's __init__ as
-    well.
-
-    """
-    source = 'attr = {0!r}'
-    created_paths = []
-    mapping = {}
-    try:
-        temp_dir = gettempdir()
-        mapping['.root'] = temp_dir
-        import_names = set()
-        for name in names:
-            if not name.endswith('__init__'):
-                import_name = name
-            else:
-                import_name = name[:-len('.__init__')]
-            import_names.add(import_name)
-            if import_name in sys.modules:
-                del sys.modules[import_name]
-            name_parts = name.split('.')
-            file_path = temp_dir
-            for directory in name_parts[:-1]:
-                file_path = os.path.join(file_path, directory)
-                if not os.path.exists(file_path):
-                    os.mkdir(file_path)
-                    created_paths.append(file_path)
-            file_path = os.path.join(file_path, name_parts[-1] + '.py')
-            with open(file_path, 'w') as file:
-                file.write(source.format(name))
-            created_paths.append(file_path)
-            mapping[name] = file_path
-        uncache_manager = uncache(*import_names)
-        uncache_manager.__enter__()
-        state_manager = import_state(path=[temp_dir])
-        state_manager.__enter__()
-        yield mapping
-    finally:
-        state_manager.__exit__(None, None, None)
-        uncache_manager.__exit__(None, None, None)
-        # Reverse the order for path removal to unroll directory creation.
-        for path in reversed(created_paths):
-            if file_path.endswith('.py'):
-                unlink(path)
-                unlink(path + 'c')
-                unlink(path + 'o')
-            else:
-                os.rmdir(path)
-
-
-class mock_modules:
-
-    """A mock importer/loader."""
-
-    def __init__(self, *names):
-        self.modules = {}
-        for name in names:
-            if not name.endswith('.__init__'):
-                import_name = name
-            else:
-                import_name = name[:-len('.__init__')]
-            if '.' not in name:
-                package = None
-            elif import_name == name:
-                package = name.rsplit('.', 1)[0]
-            else:
-                package = import_name
-            module = imp.new_module(import_name)
-            module.__loader__ = self
-            module.__file__ = '<mock __file__>'
-            module.__package__ = package
-            module.attr = name
-            if import_name != name:
-                module.__path__ = ['<mock __path__>']
-            self.modules[import_name] = module
-
-    def __getitem__(self, name):
-        return self.modules[name]
-
-    def find_module(self, fullname, path=None):
-        if fullname not in self.modules:
-            return None
-        else:
-            return self
-
-    def load_module(self, fullname):
-        if fullname not in self.modules:
-            raise ImportError
-        else:
-            sys.modules[fullname] = self.modules[fullname]
-            return self.modules[fullname]
-
-    def __enter__(self):
-        self._uncache = uncache(*self.modules.keys())
-        self._uncache.__enter__()
-        return self
-
-    def __exit__(self, *exc_info):
-        self._uncache.__exit__(None, None, None)
-
-
-def mock_path_hook(*entries, importer):
-    """A mock sys.path_hooks entry."""
-    def hook(entry):
-        if entry not in entries:
-            raise ImportError
-        return importer
-    return hook
-
-
-def bytecode_path(source_path):
-    for suffix, _, type_ in imp.get_suffixes():
-        if type_ == imp.PY_COMPILED:
-            bc_suffix = suffix
-            break
-    else:
-        raise ValueError("no bytecode suffix is defined")
-    return os.path.splitext(source_path)[0] + bc_suffix

Modified: python/branches/io-c/Lib/importlib/test/test_api.py
==============================================================================
--- python/branches/io-c/Lib/importlib/test/test_api.py	(original)
+++ python/branches/io-c/Lib/importlib/test/test_api.py	Sun Feb  8 21:39:02 2009
@@ -1,6 +1,8 @@
-import unittest
+from . import util
+import imp
 import importlib
-from . import support
+import sys
+import unittest
 
 
 class ImportModuleTests(unittest.TestCase):
@@ -9,8 +11,8 @@
 
     def test_module_import(self):
         # Test importing a top-level module.
-        with support.mock_modules('top_level') as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules('top_level') as mock:
+            with util.import_state(meta_path=[mock]):
                 module = importlib.import_module('top_level')
                 self.assertEqual(module.__name__, 'top_level')
 
@@ -19,8 +21,8 @@
         pkg_name = 'pkg'
         pkg_long_name = '{0}.__init__'.format(pkg_name)
         name = '{0}.mod'.format(pkg_name)
-        with support.mock_modules(pkg_long_name, name) as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules(pkg_long_name, name) as mock:
+            with util.import_state(meta_path=[mock]):
                 module = importlib.import_module(name)
                 self.assertEqual(module.__name__, name)
 
@@ -31,8 +33,9 @@
         module_name = 'mod'
         absolute_name = '{0}.{1}'.format(pkg_name, module_name)
         relative_name = '.{0}'.format(module_name)
-        with support.mock_modules(pkg_long_name, absolute_name) as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules(pkg_long_name, absolute_name) as mock:
+            with util.import_state(meta_path=[mock]):
+                importlib.import_module(pkg_name)
                 module = importlib.import_module(relative_name, pkg_name)
                 self.assertEqual(module.__name__, absolute_name)
 
@@ -42,8 +45,9 @@
         pkg_name = 'pkg'
         pkg_long_name = '{0}.__init__'.format(pkg_name)
         name = '{0}.mod'.format(pkg_name)
-        with support.mock_modules(pkg_long_name, name) as mock:
-            with support.import_state(meta_path=[mock]):
+        with util.mock_modules(pkg_long_name, name) as mock:
+            with util.import_state(meta_path=[mock]):
+                importlib.import_module(pkg_name)
                 module = importlib.import_module(name, pkg_name)
                 self.assertEqual(module.__name__, name)
 

Modified: python/branches/io-c/Lib/posixpath.py
==============================================================================
--- python/branches/io-c/Lib/posixpath.py	(original)
+++ python/branches/io-c/Lib/posixpath.py	Sun Feb  8 21:39:02 2009
@@ -403,12 +403,12 @@
     until we either arrive at something that isn't a symlink, or
     encounter a path we've seen before (meaning that there's a loop).
     """
-    paths_seen = []
+    paths_seen = set()
     while islink(path):
         if path in paths_seen:
             # Already seen this path, so we must have a symlink loop
             return None
-        paths_seen.append(path)
+        paths_seen.add(path)
         # Resolve where the link points to
         resolved = os.readlink(path)
         if not isabs(resolved):

Modified: python/branches/io-c/Lib/runpy.py
==============================================================================
--- python/branches/io-c/Lib/runpy.py	(original)
+++ python/branches/io-c/Lib/runpy.py	Sun Feb  8 21:39:02 2009
@@ -80,13 +80,19 @@
     if loader is None:
         raise ImportError("No module named %s" % mod_name)
     if loader.is_package(mod_name):
-        raise ImportError(("%s is a package and cannot " +
-                          "be directly executed") % mod_name)
+        if mod_name == "__main__" or mod_name.endswith(".__main__"):
+            raise ImportError(("Cannot use package as __main__ module"))
+        try:
+            pkg_main_name = mod_name + ".__main__"
+            return _get_module_details(pkg_main_name)
+        except ImportError as e:
+            raise ImportError(("%s; %r is a package and cannot " +
+                               "be directly executed") %(e, mod_name))
     code = loader.get_code(mod_name)
     if code is None:
         raise ImportError("No code object available for %s" % mod_name)
     filename = _get_filename(loader, mod_name)
-    return loader, code, filename
+    return mod_name, loader, code, filename
 
 
 # XXX ncoghlan: Should this be documented and made public?
@@ -101,12 +107,12 @@
            __loader__
     """
     try:
-        loader, code, fname = _get_module_details(mod_name)
+        mod_name, loader, code, fname = _get_module_details(mod_name)
     except ImportError as exc:
         # Try to provide a good error message
         # for directories, zip files and the -m switch
         if set_argv0:
-            # For -m switch, just disply the exception
+            # For -m switch, just display the exception
             info = str(exc)
         else:
             # For directories/zipfiles, let the user
@@ -127,7 +133,7 @@
 
        Returns the resulting top level namespace dictionary
     """
-    loader, code, fname = _get_module_details(mod_name)
+    mod_name, loader, code, fname = _get_module_details(mod_name)
     if run_name is None:
         run_name = mod_name
     pkg_name = mod_name.rpartition('.')[0]

Modified: python/branches/io-c/Lib/shelve.py
==============================================================================
--- python/branches/io-c/Lib/shelve.py	(original)
+++ python/branches/io-c/Lib/shelve.py	Sun Feb  8 21:39:02 2009
@@ -84,7 +84,7 @@
                  keyencoding="utf-8"):
         self.dict = dict
         if protocol is None:
-            protocol = 2
+            protocol = 3
         self._protocol = protocol
         self.writeback = writeback
         self.cache = {}

Modified: python/branches/io-c/Lib/shutil.py
==============================================================================
--- python/branches/io-c/Lib/shutil.py	(original)
+++ python/branches/io-c/Lib/shutil.py	Sun Feb  8 21:39:02 2009
@@ -265,4 +265,10 @@
             os.unlink(src)
 
 def destinsrc(src, dst):
-    return abspath(dst).startswith(abspath(src))
+    src = abspath(src)
+    dst = abspath(dst)
+    if not src.endswith(os.path.sep):
+        src += os.path.sep
+    if not dst.endswith(os.path.sep):
+        dst += os.path.sep
+    return dst.startswith(src)

Modified: python/branches/io-c/Lib/test/regrtest.py
==============================================================================
--- python/branches/io-c/Lib/test/regrtest.py	(original)
+++ python/branches/io-c/Lib/test/regrtest.py	Sun Feb  8 21:39:02 2009
@@ -123,6 +123,8 @@
 
     urlfetch -  It is okay to download files required on testing.
 
+    gui -       Run tests that require a running GUI.
+
 To enable all resources except one, use '-uall,-<resource>'.  For
 example, to run all the tests except for the bsddb tests, give the
 option '-uall,-bsddb'.
@@ -176,7 +178,7 @@
 from test import support
 
 RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
-                  'decimal', 'compiler', 'subprocess', 'urlfetch')
+                  'decimal', 'compiler', 'subprocess', 'urlfetch', 'gui')
 
 
 def usage(msg):
@@ -1073,6 +1075,8 @@
         test_pty
         test_socketserver
         test_tcl
+        test_ttk_guionly
+        test_ttk_textonly
         test_timeout
         test_urllibnet
         test_multiprocessing
@@ -1088,6 +1092,8 @@
         test_kqueue
         test_ossaudiodev
         test_tcl
+        test_ttk_guionly
+        test_ttk_textonly
         test_zipimport
         test_zlib
         """,
@@ -1103,6 +1109,8 @@
         test_ossaudiodev
         test_pep277
         test_tcl
+        test_ttk_guionly
+        test_ttk_textonly
         test_multiprocessing
         """,
     'netbsd3':
@@ -1117,6 +1125,8 @@
         test_ossaudiodev
         test_pep277
         test_tcl
+        test_ttk_guionly
+        test_ttk_textonly
         test_multiprocessing
         """,
 }

Modified: python/branches/io-c/Lib/test/test_builtin.py
==============================================================================
--- python/branches/io-c/Lib/test/test_builtin.py	(original)
+++ python/branches/io-c/Lib/test/test_builtin.py	Sun Feb  8 21:39:02 2009
@@ -220,9 +220,7 @@
         self.assertRaises((OverflowError, ValueError), chr, 2**32)
 
     def test_cmp(self):
-        # uncomment the following line once cmp has been removed
-        #self.assert_(not hasattr(builtins, "cmp"))
-        pass
+        self.assert_(not hasattr(builtins, "cmp"))
 
     def test_compile(self):
         compile('print(1)\n', '', 'exec')
@@ -1068,9 +1066,9 @@
         self.assertEqual(round(8), 8)
         self.assertEqual(round(-8), -8)
         self.assertEqual(type(round(0)), int)
-        self.assertEqual(type(round(-8, -1)), float)
-        self.assertEqual(type(round(-8, 0)), float)
-        self.assertEqual(type(round(-8, 1)), float)
+        self.assertEqual(type(round(-8, -1)), int)
+        self.assertEqual(type(round(-8, 0)), int)
+        self.assertEqual(type(round(-8, 1)), int)
 
         # test new kwargs
         self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)

Modified: python/branches/io-c/Lib/test/test_cmd_line_script.py
==============================================================================
--- python/branches/io-c/Lib/test/test_cmd_line_script.py	(original)
+++ python/branches/io-c/Lib/test/test_cmd_line_script.py	Sun Feb  8 21:39:02 2009
@@ -113,7 +113,7 @@
     os.unlink(script_name)
     #if verbose:
     #    zip_file = zipfile.ZipFile(zip_name, 'r')
-    #    print 'Contents of %r:' % zip_name
+    #    print('Contents of %r:' % zip_name)
     #    zip_file.printdir()
     #    zip_file.close()
     return zip_name, os.path.join(zip_name, script_name_in_zip)
@@ -158,6 +158,16 @@
         self.assert_(printed_package in data)
         self.assert_(printed_argv0 in data)
 
+    def _check_import_error(self, script_name, expected_msg,
+                            *cmd_line_switches):
+        run_args = cmd_line_switches + (script_name,)
+        exit_code, data = _run_python(*run_args)
+        if verbose:
+            print('Output from test script %r:' % script_name)
+            print(data)
+            print('Expected output: %r' % expected_msg)
+        self.assert_(expected_msg in data)
+
     def test_basic_script(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, 'script')
@@ -182,6 +192,11 @@
             os.remove(script_name)
             self._check_script(script_dir, compiled_name, script_dir, '')
 
+    def test_directory_error(self):
+        with temp_dir() as script_dir:
+            msg = "can't find '__main__.py' in %r" % script_dir
+            self._check_import_error(script_dir, msg)
+
     def test_zipfile(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
@@ -195,6 +210,13 @@
             zip_name, run_name = _make_test_zip(script_dir, 'test_zip', compiled_name)
             self._check_script(zip_name, run_name, zip_name, '')
 
+    def test_zipfile_error(self):
+        with temp_dir() as script_dir:
+            script_name = _make_test_script(script_dir, 'not_main')
+            zip_name, run_name = _make_test_zip(script_dir, 'test_zip', script_name)
+            msg = "can't find '__main__.py' in %r" % zip_name
+            self._check_import_error(zip_name, msg)
+
     def test_module_in_package(self):
         with temp_dir() as script_dir:
             pkg_dir = os.path.join(script_dir, 'test_pkg')
@@ -215,6 +237,47 @@
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
             self._check_script(launch_name, run_name, run_name, 'test_pkg.test_pkg')
 
+    def test_package(self):
+        with temp_dir() as script_dir:
+            pkg_dir = os.path.join(script_dir, 'test_pkg')
+            _make_test_pkg(pkg_dir)
+            script_name = _make_test_script(pkg_dir, '__main__')
+            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
+            self._check_script(launch_name, script_name,
+                               script_name, 'test_pkg')
+
+    def test_package_compiled(self):
+        with temp_dir() as script_dir:
+            pkg_dir = os.path.join(script_dir, 'test_pkg')
+            _make_test_pkg(pkg_dir)
+            script_name = _make_test_script(pkg_dir, '__main__')
+            compiled_name = _compile_test_script(script_name)
+            os.remove(script_name)
+            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
+            self._check_script(launch_name, compiled_name,
+                               compiled_name, 'test_pkg')
+
+    def test_package_error(self):
+        with temp_dir() as script_dir:
+            pkg_dir = os.path.join(script_dir, 'test_pkg')
+            _make_test_pkg(pkg_dir)
+            msg = ("'test_pkg' is a package and cannot "
+                   "be directly executed")
+            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
+            self._check_import_error(launch_name, msg)
+
+    def test_package_recursion(self):
+        with temp_dir() as script_dir:
+            pkg_dir = os.path.join(script_dir, 'test_pkg')
+            _make_test_pkg(pkg_dir)
+            main_dir = os.path.join(pkg_dir, '__main__')
+            _make_test_pkg(main_dir)
+            msg = ("Cannot use package as __main__ module; "
+                   "'test_pkg' is a package and cannot "
+                   "be directly executed")
+            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg')
+            self._check_import_error(launch_name, msg)
+
 
 def test_main():
     test.support.run_unittest(CmdLineTest)

Modified: python/branches/io-c/Lib/test/test_collections.py
==============================================================================
--- python/branches/io-c/Lib/test/test_collections.py	(original)
+++ python/branches/io-c/Lib/test/test_collections.py	Sun Feb  8 21:39:02 2009
@@ -160,7 +160,24 @@
             self.assertEqual(p, q)
             self.assertEqual(p._fields, q._fields)
 
-class TestOneTrickPonyABCs(unittest.TestCase):
+class ABCTestCase(unittest.TestCase):
+
+    def validate_abstract_methods(self, abc, *names):
+        methodstubs = dict.fromkeys(names, lambda s, *args: 0)
+
+        # everything should work will all required methods are present
+        C = type('C', (abc,), methodstubs)
+        C()
+
+        # instantiation should fail if a required method is missing
+        for name in names:
+            stubs = methodstubs.copy()
+            del stubs[name]
+            C = type('C', (abc,), stubs)
+            self.assertRaises(TypeError, C, name)
+
+
+class TestOneTrickPonyABCs(ABCTestCase):
 
     def test_Hashable(self):
         # Check some non-hashables
@@ -185,6 +202,7 @@
                 return super().__hash__()
         self.assertEqual(hash(H()), 0)
         self.failIf(issubclass(int, H))
+        self.validate_abstract_methods(Hashable, '__hash__')
 
     def test_Iterable(self):
         # Check some non-iterables
@@ -208,6 +226,7 @@
                 return super().__iter__()
         self.assertEqual(list(I()), [])
         self.failIf(issubclass(str, I))
+        self.validate_abstract_methods(Iterable, '__iter__')
 
     def test_Iterator(self):
         non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()]
@@ -225,6 +244,7 @@
         for x in samples:
             self.failUnless(isinstance(x, Iterator), repr(x))
             self.failUnless(issubclass(type(x), Iterator), repr(type(x)))
+        self.validate_abstract_methods(Iterator, '__next__')
 
     def test_Sized(self):
         non_samples = [None, 42, 3.14, 1j,
@@ -241,6 +261,7 @@
         for x in samples:
             self.failUnless(isinstance(x, Sized), repr(x))
             self.failUnless(issubclass(type(x), Sized), repr(type(x)))
+        self.validate_abstract_methods(Sized, '__len__')
 
     def test_Container(self):
         non_samples = [None, 42, 3.14, 1j,
@@ -257,6 +278,7 @@
         for x in samples:
             self.failUnless(isinstance(x, Container), repr(x))
             self.failUnless(issubclass(type(x), Container), repr(type(x)))
+        self.validate_abstract_methods(Container, '__contains__')
 
     def test_Callable(self):
         non_samples = [None, 42, 3.14, 1j,
@@ -275,6 +297,7 @@
         for x in samples:
             self.failUnless(isinstance(x, Callable), repr(x))
             self.failUnless(issubclass(type(x), Callable), repr(type(x)))
+        self.validate_abstract_methods(Callable, '__call__')
 
     def test_direct_subclassing(self):
         for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
@@ -292,7 +315,7 @@
             self.failUnless(issubclass(C, B))
 
 
-class TestCollectionABCs(unittest.TestCase):
+class TestCollectionABCs(ABCTestCase):
 
     # XXX For now, we only test some virtual inheritance properties.
     # We should also test the proper behavior of the collection ABCs
@@ -302,6 +325,7 @@
         for sample in [set, frozenset]:
             self.failUnless(isinstance(sample(), Set))
             self.failUnless(issubclass(sample, Set))
+        self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__')
 
     def test_hash_Set(self):
         class OneTwoThreeSet(Set):
@@ -323,22 +347,57 @@
         self.failUnless(issubclass(set, MutableSet))
         self.failIf(isinstance(frozenset(), MutableSet))
         self.failIf(issubclass(frozenset, MutableSet))
+        self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__',
+            'add', 'discard')
+
+    def test_issue_4920(self):
+        # MutableSet.pop() method did not work
+        class MySet(collections.MutableSet):
+            __slots__=['__s']
+            def __init__(self,items=None):
+                if items is None:
+                    items=[]
+                self.__s=set(items)
+            def __contains__(self,v):
+                return v in self.__s
+            def __iter__(self):
+                return iter(self.__s)
+            def __len__(self):
+                return len(self.__s)
+            def add(self,v):
+                result=v not in self.__s
+                self.__s.add(v)
+                return result
+            def discard(self,v):
+                result=v in self.__s
+                self.__s.discard(v)
+                return result
+            def __repr__(self):
+                return "MySet(%s)" % repr(list(self))
+        s = MySet([5,43,2,1])
+        self.assertEqual(s.pop(), 1)
 
     def test_Mapping(self):
         for sample in [dict]:
             self.failUnless(isinstance(sample(), Mapping))
             self.failUnless(issubclass(sample, Mapping))
+        self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__',
+            '__getitem__')
 
     def test_MutableMapping(self):
         for sample in [dict]:
             self.failUnless(isinstance(sample(), MutableMapping))
             self.failUnless(issubclass(sample, MutableMapping))
+        self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
+            '__getitem__', '__setitem__', '__delitem__')
 
     def test_Sequence(self):
         for sample in [tuple, list, bytes, str]:
             self.failUnless(isinstance(sample(), Sequence))
             self.failUnless(issubclass(sample, Sequence))
         self.failUnless(issubclass(str, Sequence))
+        self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__',
+            '__getitem__')
 
     def test_ByteString(self):
         for sample in [bytes, bytearray]:
@@ -358,6 +417,8 @@
             self.failUnless(isinstance(sample(), MutableSequence))
             self.failUnless(issubclass(sample, MutableSequence))
         self.failIf(issubclass(str, MutableSequence))
+        self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
+            '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
 
 class TestCounter(unittest.TestCase):
 

Modified: python/branches/io-c/Lib/test/test_decimal.py
==============================================================================
--- python/branches/io-c/Lib/test/test_decimal.py	(original)
+++ python/branches/io-c/Lib/test/test_decimal.py	Sun Feb  8 21:39:02 2009
@@ -30,6 +30,7 @@
 import pickle, copy
 import unittest
 from decimal import *
+import numbers
 from test.support import (TestSkipped, run_unittest, run_doctest,
                                is_resource_enabled)
 import random
@@ -1388,6 +1389,12 @@
 
 class DecimalPythonAPItests(unittest.TestCase):
 
+    def test_abc(self):
+        self.assert_(issubclass(Decimal, numbers.Number))
+        self.assert_(not issubclass(Decimal, numbers.Real))
+        self.assert_(isinstance(Decimal(0), numbers.Number))
+        self.assert_(not isinstance(Decimal(0), numbers.Real))
+
     def test_pickle(self):
         d = Decimal('-3.141590000')
         p = pickle.dumps(d)

Modified: python/branches/io-c/Lib/test/test_descr.py
==============================================================================
--- python/branches/io-c/Lib/test/test_descr.py	(original)
+++ python/branches/io-c/Lib/test/test_descr.py	Sun Feb  8 21:39:02 2009
@@ -3885,7 +3885,7 @@
         # Testing method-wrapper objects...
         # <type 'method-wrapper'> did not support any reflection before 2.5
 
-        return # XXX should methods really support __eq__?
+        # XXX should methods really support __eq__?
 
         l = []
         self.assertEqual(l.__add__, l.__add__)

Modified: python/branches/io-c/Lib/test/test_funcattrs.py
==============================================================================
--- python/branches/io-c/Lib/test/test_funcattrs.py	(original)
+++ python/branches/io-c/Lib/test/test_funcattrs.py	Sun Feb  8 21:39:02 2009
@@ -224,10 +224,41 @@
         del self.b.__doc__
         self.assertEqual(self.b.__doc__, None)
 
+def cell(value):
+    """Create a cell containing the given value."""
+    def f():
+        print(a)
+    a = value
+    return f.__closure__[0]
+
+def empty_cell(empty=True):
+    """Create an empty cell."""
+    def f():
+        print(a)
+    # the intent of the following line is simply "if False:";  it's
+    # spelt this way to avoid the danger that a future optimization
+    # might simply remove an "if False:" code block.
+    if not empty:
+        a = 1729
+    return f.__closure__[0]
+
+class CellTest(unittest.TestCase):
+    def test_comparison(self):
+        # These tests are here simply to exercise the comparison code;
+        # their presence should not be interpreted as providing any
+        # guarantees about the semantics (or even existence) of cell
+        # comparisons in future versions of CPython.
+        self.assert_(cell(2) < cell(3))
+        self.assert_(empty_cell() < cell('saturday'))
+        self.assert_(empty_cell() == empty_cell())
+        self.assert_(cell(-36) == cell(-36.0))
+        self.assert_(cell(True) > empty_cell())
+
+
 def test_main():
     support.run_unittest(FunctionPropertiesTest, ImplicitReferencesTest,
                               ArbitraryFunctionAttrTest, FunctionDictsTest,
-                              FunctionDocstringTest)
+                              FunctionDocstringTest, CellTest)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/io-c/Lib/test/test_hash.py
==============================================================================
--- python/branches/io-c/Lib/test/test_hash.py	(original)
+++ python/branches/io-c/Lib/test/test_hash.py	Sun Feb  8 21:39:02 2009
@@ -33,6 +33,7 @@
         # for 64-bit platforms
         self.same_hash(int(2**31), float(2**31))
         self.same_hash(int(-2**63), float(-2**63))
+        self.same_hash(int(2**63), float(2**63))
 
     def test_coerced_floats(self):
         self.same_hash(int(1.23e300), float(1.23e300))

Modified: python/branches/io-c/Lib/test/test_iterlen.py
==============================================================================
--- python/branches/io-c/Lib/test/test_iterlen.py	(original)
+++ python/branches/io-c/Lib/test/test_iterlen.py	Sun Feb  8 21:39:02 2009
@@ -195,6 +195,39 @@
         d.extend(range(20))
         self.assertEqual(len(it), 0)
 
+## -- Check to make sure exceptions are not suppressed by __length_hint__()
+
+
+class BadLen(object):
+    def __iter__(self): return iter(range(10))
+    def __len__(self):
+        raise RuntimeError('hello')
+
+class BadLengthHint(object):
+    def __iter__(self): return iter(range(10))
+    def __length_hint__(self):
+        raise RuntimeError('hello')
+
+class NoneLengthHint(object):
+    def __iter__(self): return iter(range(10))
+    def __length_hint__(self):
+        return None
+
+class TestLengthHintExceptions(unittest.TestCase):
+
+    def test_issue1242657(self):
+        self.assertRaises(RuntimeError, list, BadLen())
+        self.assertRaises(RuntimeError, list, BadLengthHint())
+        self.assertRaises(RuntimeError, [].extend, BadLen())
+        self.assertRaises(RuntimeError, [].extend, BadLengthHint())
+        b = bytearray(range(10))
+        self.assertRaises(RuntimeError, b.extend, BadLen())
+        self.assertRaises(RuntimeError, b.extend, BadLengthHint())
+
+    def test_invalid_hint(self):
+        # Make sure an invalid result doesn't muck-up the works
+        self.assertEqual(list(NoneLengthHint()), list(range(10)))
+
 
 def test_main():
     unittests = [
@@ -210,6 +243,7 @@
         TestSet,
         TestList,
         TestListReversed,
+        TestLengthHintExceptions,
     ]
     support.run_unittest(*unittests)
 

Modified: python/branches/io-c/Lib/test/test_itertools.py
==============================================================================
--- python/branches/io-c/Lib/test/test_itertools.py	(original)
+++ python/branches/io-c/Lib/test/test_itertools.py	Sun Feb  8 21:39:02 2009
@@ -1371,8 +1371,8 @@
 ...     return map(function, count(start))
 
 >>> def nth(iterable, n):
-...     "Returns the nth item or empty list"
-...     return list(islice(iterable, n, n+1))
+...     "Returns the nth item or None"
+...     return next(islice(iterable, n, None), None)
 
 >>> def quantify(iterable, pred=bool):
 ...     "Count how many times the predicate is true"
@@ -1469,7 +1469,10 @@
 [0, 2, 4, 6]
 
 >>> nth('abcde', 3)
-['d']
+'d'
+
+>>> nth('abcde', 9) is None
+True
 
 >>> quantify(range(99), lambda x: x%2==0)
 50

Modified: python/branches/io-c/Lib/test/test_long.py
==============================================================================
--- python/branches/io-c/Lib/test/test_long.py	(original)
+++ python/branches/io-c/Lib/test/test_long.py	Sun Feb  8 21:39:02 2009
@@ -896,6 +896,81 @@
             self.assertEqual((a+1).bit_length(), i+1)
             self.assertEqual((-a-1).bit_length(), i+1)
 
+    def test_round(self):
+        # check round-half-even algorithm. For round to nearest ten;
+        # rounding map is invariant under adding multiples of 20
+        test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
+                     6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
+                     15:20, 16:20, 17:20, 18:20, 19:20}
+        for offset in range(-520, 520, 20):
+            for k, v in test_dict.items():
+                got = round(k+offset, -1)
+                expected = v+offset
+                self.assertEqual(got, expected)
+                self.assert_(type(got) is int)
+
+        # larger second argument
+        self.assertEqual(round(-150, -2), -200)
+        self.assertEqual(round(-149, -2), -100)
+        self.assertEqual(round(-51, -2), -100)
+        self.assertEqual(round(-50, -2), 0)
+        self.assertEqual(round(-49, -2), 0)
+        self.assertEqual(round(-1, -2), 0)
+        self.assertEqual(round(0, -2), 0)
+        self.assertEqual(round(1, -2), 0)
+        self.assertEqual(round(49, -2), 0)
+        self.assertEqual(round(50, -2), 0)
+        self.assertEqual(round(51, -2), 100)
+        self.assertEqual(round(149, -2), 100)
+        self.assertEqual(round(150, -2), 200)
+        self.assertEqual(round(250, -2), 200)
+        self.assertEqual(round(251, -2), 300)
+        self.assertEqual(round(172500, -3), 172000)
+        self.assertEqual(round(173500, -3), 174000)
+        self.assertEqual(round(31415926535, -1), 31415926540)
+        self.assertEqual(round(31415926535, -2), 31415926500)
+        self.assertEqual(round(31415926535, -3), 31415927000)
+        self.assertEqual(round(31415926535, -4), 31415930000)
+        self.assertEqual(round(31415926535, -5), 31415900000)
+        self.assertEqual(round(31415926535, -6), 31416000000)
+        self.assertEqual(round(31415926535, -7), 31420000000)
+        self.assertEqual(round(31415926535, -8), 31400000000)
+        self.assertEqual(round(31415926535, -9), 31000000000)
+        self.assertEqual(round(31415926535, -10), 30000000000)
+        self.assertEqual(round(31415926535, -11), 0)
+        self.assertEqual(round(31415926535, -12), 0)
+        self.assertEqual(round(31415926535, -999), 0)
+
+        # should get correct results even for huge inputs
+        for k in range(10, 100):
+            got = round(10**k + 324678, -3)
+            expect = 10**k + 325000
+            self.assertEqual(got, expect)
+            self.assert_(type(got) is int)
+
+        # nonnegative second argument: round(x, n) should just return x
+        for n in range(5):
+            for i in range(100):
+                x = random.randrange(-10000, 10000)
+                got = round(x, n)
+                self.assertEqual(got, x)
+                self.assert_(type(got) is int)
+        for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
+            self.assertEqual(round(8979323, huge_n), 8979323)
+
+        # omitted second argument
+        for i in range(100):
+            x = random.randrange(-10000, 10000)
+            got = round(x)
+            self.assertEqual(got, x)
+            self.assert_(type(got) is int)
+
+        # bad second argument
+        bad_exponents = ('brian', 2.0, 0j, None)
+        for e in bad_exponents:
+            self.assertRaises(TypeError, round, 3, e)
+
+
 
 def test_main():
     support.run_unittest(LongTest)

Modified: python/branches/io-c/Lib/test/test_os.py
==============================================================================
--- python/branches/io-c/Lib/test/test_os.py	(original)
+++ python/branches/io-c/Lib/test/test_os.py	Sun Feb  8 21:39:02 2009
@@ -3,6 +3,7 @@
 # portable than they had been thought to be.
 
 import os
+import errno
 import unittest
 import warnings
 import sys
@@ -277,7 +278,6 @@
             result = os.statvfs(self.fname)
         except OSError as e:
             # On AtheOS, glibc always returns ENOSYS
-            import errno
             if e.errno == errno.ENOSYS:
                 return
 
@@ -601,7 +601,13 @@
         locals()["test_"+f] = get_single(f)
 
     def check(self, f, *args):
-        self.assertRaises(OSError, f, support.make_bad_fd(), *args)
+        try:
+            f(support.make_bad_fd(), *args)
+        except OSError as e:
+            self.assertEqual(e.errno, errno.EBADF)
+        else:
+            self.fail("%r didn't raise a OSError with a bad file descriptor"
+                      % f)
 
     def test_isatty(self):
         if hasattr(os, "isatty"):

Modified: python/branches/io-c/Lib/test/test_parser.py
==============================================================================
--- python/branches/io-c/Lib/test/test_parser.py	(original)
+++ python/branches/io-c/Lib/test/test_parser.py	Sun Feb  8 21:39:02 2009
@@ -2,6 +2,7 @@
 import os
 import unittest
 import sys
+import operator
 from test import support
 
 #
@@ -496,12 +497,81 @@
               file=sys.stderr)
         self.assertRaises(MemoryError, parser.expr, e)
 
+class STObjectTestCase(unittest.TestCase):
+    """Test operations on ST objects themselves"""
+
+    def test_comparisons(self):
+        # ST objects should support order and equality comparisons
+        st1 = parser.expr('2 + 3')
+        st2 = parser.suite('x = 2; y = x + 3')
+        st3 = parser.expr('list(x**3 for x in range(20))')
+        st1_copy = parser.expr('2 + 3')
+        st2_copy = parser.suite('x = 2; y = x + 3')
+        st3_copy = parser.expr('list(x**3 for x in range(20))')
+
+        # exercise fast path for object identity
+        self.assertEquals(st1 == st1, True)
+        self.assertEquals(st2 == st2, True)
+        self.assertEquals(st3 == st3, True)
+        # slow path equality
+        self.assertEqual(st1, st1_copy)
+        self.assertEqual(st2, st2_copy)
+        self.assertEqual(st3, st3_copy)
+        self.assertEquals(st1 == st2, False)
+        self.assertEquals(st1 == st3, False)
+        self.assertEquals(st2 == st3, False)
+        self.assertEquals(st1 != st1, False)
+        self.assertEquals(st2 != st2, False)
+        self.assertEquals(st3 != st3, False)
+        self.assertEquals(st1 != st1_copy, False)
+        self.assertEquals(st2 != st2_copy, False)
+        self.assertEquals(st3 != st3_copy, False)
+        self.assertEquals(st2 != st1, True)
+        self.assertEquals(st1 != st3, True)
+        self.assertEquals(st3 != st2, True)
+        # we don't particularly care what the ordering is;  just that
+        # it's usable and self-consistent
+        self.assertEquals(st1 < st2, not (st2 <= st1))
+        self.assertEquals(st1 < st3, not (st3 <= st1))
+        self.assertEquals(st2 < st3, not (st3 <= st2))
+        self.assertEquals(st1 < st2, st2 > st1)
+        self.assertEquals(st1 < st3, st3 > st1)
+        self.assertEquals(st2 < st3, st3 > st2)
+        self.assertEquals(st1 <= st2, st2 >= st1)
+        self.assertEquals(st3 <= st1, st1 >= st3)
+        self.assertEquals(st2 <= st3, st3 >= st2)
+        # transitivity
+        bottom = min(st1, st2, st3)
+        top = max(st1, st2, st3)
+        mid = sorted([st1, st2, st3])[1]
+        self.assert_(bottom < mid)
+        self.assert_(bottom < top)
+        self.assert_(mid < top)
+        self.assert_(bottom <= mid)
+        self.assert_(bottom <= top)
+        self.assert_(mid <= top)
+        self.assert_(bottom <= bottom)
+        self.assert_(mid <= mid)
+        self.assert_(top <= top)
+        # interaction with other types
+        self.assertEquals(st1 == 1588.602459, False)
+        self.assertEquals('spanish armada' != st2, True)
+        self.assertRaises(TypeError, operator.ge, st3, None)
+        self.assertRaises(TypeError, operator.le, False, st1)
+        self.assertRaises(TypeError, operator.lt, st1, 1815)
+        self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
+
+
+    # XXX tests for pickling and unpickling of ST objects should go here
+
+
 def test_main():
     support.run_unittest(
         RoundtripLegalSyntaxTestCase,
         IllegalSyntaxTestCase,
         CompileTestCase,
         ParserStackLimitTestCase,
+        STObjectTestCase,
     )
 
 

Modified: python/branches/io-c/Lib/test/test_shutil.py
==============================================================================
--- python/branches/io-c/Lib/test/test_shutil.py	(original)
+++ python/branches/io-c/Lib/test/test_shutil.py	Sun Feb  8 21:39:02 2009
@@ -340,7 +340,29 @@
         dst = os.path.join(self.src_dir, "bar")
         self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
 
+    def test_destinsrc_false_negative(self):
+        os.mkdir(TESTFN)
+        try:
+            for src, dst in [('srcdir', 'srcdir/dest')]:
+                src = os.path.join(TESTFN, src)
+                dst = os.path.join(TESTFN, dst)
+                self.assert_(shutil.destinsrc(src, dst),
+                             msg='destinsrc() wrongly concluded that '
+                             'dst (%s) is not in src (%s)' % (dst, src))
+        finally:
+            shutil.rmtree(TESTFN, ignore_errors=True)
 
+    def test_destinsrc_false_positive(self):
+        os.mkdir(TESTFN)
+        try:
+            for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
+                src = os.path.join(TESTFN, src)
+                dst = os.path.join(TESTFN, dst)
+                self.failIf(shutil.destinsrc(src, dst),
+                            msg='destinsrc() wrongly concluded that '
+                            'dst (%s) is in src (%s)' % (dst, src))
+        finally:
+            shutil.rmtree(TESTFN, ignore_errors=True)
 
 def test_main():
     support.run_unittest(TestShutil, TestMove)

Modified: python/branches/io-c/Lib/test/test_socket.py
==============================================================================
--- python/branches/io-c/Lib/test/test_socket.py	(original)
+++ python/branches/io-c/Lib/test/test_socket.py	Sun Feb  8 21:39:02 2009
@@ -366,6 +366,9 @@
         eq(socket.getservbyport(port, 'tcp'), service)
         if udpport is not None:
             eq(socket.getservbyport(udpport, 'udp'), service)
+        # Make sure getservbyport does not accept out of range ports.
+        self.assertRaises(OverflowError, socket.getservbyport, -1)
+        self.assertRaises(OverflowError, socket.getservbyport, 65536)
 
     def testDefaultTimeout(self):
         # Testing default timeout
@@ -466,15 +469,23 @@
 
     # XXX The following don't test module-level functionality...
 
-    def testSockName(self):
-        # Testing getsockname().  Use a temporary socket to elicit an unused
-        # ephemeral port that we can use later in the test.
+    def _get_unused_port(self, bind_address='0.0.0.0'):
+        """Use a temporary socket to elicit an unused ephemeral port.
+
+        Args:
+            bind_address: Hostname or IP address to search for a port on.
+
+        Returns: A most likely to be unused port.
+        """
         tempsock = socket.socket()
-        tempsock.bind(("0.0.0.0", 0))
-        (host, port) = tempsock.getsockname()
+        tempsock.bind((bind_address, 0))
+        host, port = tempsock.getsockname()
         tempsock.close()
-        del tempsock
+        return port
 
+    def testSockName(self):
+        # Testing getsockname()
+        port = self._get_unused_port()
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.bind(("0.0.0.0", port))
         name = sock.getsockname()
@@ -514,6 +525,19 @@
         self.assertEqual(sock.proto, 0)
         sock.close()
 
+    def test_getsockaddrarg(self):
+        host = '0.0.0.0'
+        port = self._get_unused_port(bind_address=host)
+        big_port = port + 65536
+        neg_port = port - 65536
+        sock = socket.socket()
+        try:
+            self.assertRaises(OverflowError, sock.bind, (host, big_port))
+            self.assertRaises(OverflowError, sock.bind, (host, neg_port))
+            sock.bind((host, port))
+        finally:
+            sock.close()
+
     def test_sock_ioctl(self):
         if os.name != "nt":
             return

Modified: python/branches/io-c/Lib/test/test_sys.py
==============================================================================
--- python/branches/io-c/Lib/test/test_sys.py	(original)
+++ python/branches/io-c/Lib/test/test_sys.py	Sun Feb  8 21:39:02 2009
@@ -298,13 +298,25 @@
         self.assert_(isinstance(sys.prefix, str))
         self.assert_(isinstance(sys.version, str))
         vi = sys.version_info
-        self.assert_(isinstance(vi, tuple))
+        self.assert_(isinstance(vi[:], tuple))
         self.assertEqual(len(vi), 5)
         self.assert_(isinstance(vi[0], int))
         self.assert_(isinstance(vi[1], int))
         self.assert_(isinstance(vi[2], int))
         self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
         self.assert_(isinstance(vi[4], int))
+        self.assert_(isinstance(vi.major, int))
+        self.assert_(isinstance(vi.minor, int))
+        self.assert_(isinstance(vi.micro, int))
+        self.assert_(vi.releaselevel in
+                     ("alpha", "beta", "candidate", "final"))
+        self.assert_(isinstance(vi.serial, int))
+        self.assertEqual(vi[0], vi.major)
+        self.assertEqual(vi[1], vi.minor)
+        self.assertEqual(vi[2], vi.micro)
+        self.assertEqual(vi[3], vi.releaselevel)
+        self.assertEqual(vi[4], vi.serial)
+        self.assert_(vi > (1,0,0))
 
     def test_43581(self):
         # Can't use sys.stdout, as this is a StringIO object when

Modified: python/branches/io-c/Lib/test/test_tcl.py
==============================================================================
--- python/branches/io-c/Lib/test/test_tcl.py	(original)
+++ python/branches/io-c/Lib/test/test_tcl.py	Sun Feb  8 21:39:02 2009
@@ -2,10 +2,19 @@
 
 import unittest
 import os
+import _tkinter
 from test import support
 from tkinter import Tcl
 from _tkinter import TclError
 
+
+class TkinterTest(unittest.TestCase):
+
+    def testFlattenLen(self):
+        # flatten(<object with no length>)
+        self.assertRaises(TypeError, _tkinter._flatten, True)
+
+
 class TclTest(unittest.TestCase):
 
     def setUp(self):
@@ -151,7 +160,7 @@
                 os.environ['DISPLAY'] = old_display
 
 def test_main():
-    support.run_unittest(TclTest)
+    support.run_unittest(TclTest, TkinterTest)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/io-c/Lib/test/test_urllib.py
==============================================================================
--- python/branches/io-c/Lib/test/test_urllib.py	(original)
+++ python/branches/io-c/Lib/test/test_urllib.py	Sun Feb  8 21:39:02 2009
@@ -146,7 +146,8 @@
     def fakehttp(self, fakedata):
         class FakeSocket(io.BytesIO):
             def sendall(self, str): pass
-            def makefile(self, mode, name): return self
+            def makefile(self, *args, **kwds):
+                return self
             def read(self, amt=None):
                 if self.closed: return b""
                 return io.BytesIO.read(self, amt)

Modified: python/branches/io-c/Lib/test/test_urllib2net.py
==============================================================================
--- python/branches/io-c/Lib/test/test_urllib2net.py	(original)
+++ python/branches/io-c/Lib/test/test_urllib2net.py	Sun Feb  8 21:39:02 2009
@@ -195,7 +195,7 @@
     def test_http_basic(self):
         self.assertTrue(socket.getdefaulttimeout() is None)
         u = _urlopen_with_retry("http://www.python.org")
-        self.assertTrue(u.fp._sock.gettimeout() is None)
+        self.assertTrue(u.fp.raw._sock.gettimeout() is None)
 
     def test_http_default_timeout(self):
         self.assertTrue(socket.getdefaulttimeout() is None)
@@ -204,7 +204,7 @@
             u = _urlopen_with_retry("http://www.python.org")
         finally:
             socket.setdefaulttimeout(None)
-        self.assertEqual(u.fp._sock.gettimeout(), 60)
+        self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
 
     def test_http_no_timeout(self):
         self.assertTrue(socket.getdefaulttimeout() is None)
@@ -213,11 +213,11 @@
             u = _urlopen_with_retry("http://www.python.org", timeout=None)
         finally:
             socket.setdefaulttimeout(None)
-        self.assertTrue(u.fp._sock.gettimeout() is None)
+        self.assertTrue(u.fp.raw._sock.gettimeout() is None)
 
     def test_http_timeout(self):
         u = _urlopen_with_retry("http://www.python.org", timeout=120)
-        self.assertEqual(u.fp._sock.gettimeout(), 120)
+        self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
 
     FTP_HOST = "ftp://ftp.mirror.nl/pub/mirror/gnu/"
 

Modified: python/branches/io-c/Lib/test/test_zipimport.py
==============================================================================
--- python/branches/io-c/Lib/test/test_zipimport.py	(original)
+++ python/branches/io-c/Lib/test/test_zipimport.py	Sun Feb  8 21:39:02 2009
@@ -212,7 +212,7 @@
             self.assertEquals(zi.archive, TEMP_ZIP)
             self.assertEquals(zi.is_package(TESTPACK), True)
             mod = zi.load_module(TESTPACK)
-            self.assertEquals(zi._get_filename(TESTPACK), mod.__file__)
+            self.assertEquals(zi.get_filename(TESTPACK), mod.__file__)
 
             self.assertEquals(zi.is_package(packdir + '__init__'), False)
             self.assertEquals(zi.is_package(packdir + TESTPACK2), True)
@@ -224,11 +224,11 @@
             mod = sys.modules[mod_name]
             self.assertEquals(zi.get_source(TESTPACK), None)
             self.assertEquals(zi.get_source(mod_path), None)
-            self.assertEquals(zi._get_filename(mod_path), mod.__file__)
+            self.assertEquals(zi.get_filename(mod_path), mod.__file__)
             # To pass in the module name instead of the path, we must use the right importer
             loader = mod.__loader__
             self.assertEquals(loader.get_source(mod_name), None)
-            self.assertEquals(loader._get_filename(mod_name), mod.__file__)
+            self.assertEquals(loader.get_filename(mod_name), mod.__file__)
 
             # test prefix and archivepath members
             zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
@@ -257,7 +257,7 @@
             self.assertEquals(zi.prefix, packdir)
             self.assertEquals(zi.is_package(TESTPACK2), True)
             mod = zi.load_module(TESTPACK2)
-            self.assertEquals(zi._get_filename(TESTPACK2), mod.__file__)
+            self.assertEquals(zi.get_filename(TESTPACK2), mod.__file__)
 
             self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
             self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
@@ -268,11 +268,11 @@
             mod = sys.modules[mod_name]
             self.assertEquals(zi.get_source(TESTPACK2), None)
             self.assertEquals(zi.get_source(mod_path), None)
-            self.assertEquals(zi._get_filename(mod_path), mod.__file__)
+            self.assertEquals(zi.get_filename(mod_path), mod.__file__)
             # To pass in the module name instead of the path, we must use the right importer
             loader = mod.__loader__
             self.assertEquals(loader.get_source(mod_name), None)
-            self.assertEquals(loader._get_filename(mod_name), mod.__file__)
+            self.assertEquals(loader.get_filename(mod_name), mod.__file__)
         finally:
             z.close()
             os.remove(TEMP_ZIP)

Modified: python/branches/io-c/Lib/trace.py
==============================================================================
--- python/branches/io-c/Lib/trace.py	(original)
+++ python/branches/io-c/Lib/trace.py	Sun Feb  8 21:39:02 2009
@@ -367,7 +367,7 @@
     """Return dict where keys are lines in the line number table."""
     linenos = {}
 
-    line_increments = [ord(c) for c in code.co_lnotab[1::2]]
+    line_increments = code.co_lnotab[1::2]
     table_length = len(line_increments)
     docstring = False
 

Modified: python/branches/io-c/Lib/xmlrpc/client.py
==============================================================================
--- python/branches/io-c/Lib/xmlrpc/client.py	(original)
+++ python/branches/io-c/Lib/xmlrpc/client.py	Sun Feb  8 21:39:02 2009
@@ -1129,7 +1129,7 @@
 
         self.verbose = verbose
 
-        return self._parse_response(resp, None)
+        return self.parse_response(resp)
 
     ##
     # Create parser.
@@ -1212,29 +1212,12 @@
     # @return Response tuple and target method.
 
     def parse_response(self, file):
-        # compatibility interface
-        return self._parse_response(file, None)
-
-    ##
-    # Parse response (alternate interface).  This is similar to the
-    # parse_response method, but also provides direct access to the
-    # underlying socket object (where available).
-    #
-    # @param file Stream.
-    # @param sock Socket handle (or None, if the socket object
-    #    could not be accessed).
-    # @return Response tuple and target method.
-
-    def _parse_response(self, file, sock):
         # read response from input file/socket, and parse it
 
         p, u = self.getparser()
 
         while 1:
-            if sock:
-                response = sock.recv(1024)
-            else:
-                response = file.read(1024)
+            response = file.read(1024)
             if not response:
                 break
             if self.verbose:

Modified: python/branches/io-c/Makefile.pre.in
==============================================================================
--- python/branches/io-c/Makefile.pre.in	(original)
+++ python/branches/io-c/Makefile.pre.in	Sun Feb  8 21:39:02 2009
@@ -841,6 +841,9 @@
 		lib2to3 lib2to3/fixes lib2to3/pgen2 lib2to3/tests \
 		ctypes ctypes/test ctypes/macholib idlelib idlelib/Icons \
 		distutils distutils/command distutils/tests $(XMLLIBSUBDIRS) \
+		importlib importlib/test importlib/test/builtin \
+		importlib/test/extension importlib/test/frozen \
+		importlib/test/import_ importlib/test/source \
 		setuptools setuptools/command setuptools/tests setuptools.egg-info \
 		multiprocessing multiprocessing/dummy \
 		curses $(MACHDEPS)

Modified: python/branches/io-c/Misc/ACKS
==============================================================================
--- python/branches/io-c/Misc/ACKS	(original)
+++ python/branches/io-c/Misc/ACKS	Sun Feb  8 21:39:02 2009
@@ -714,6 +714,7 @@
 Roger Upole
 Michael Urman
 Hector Urtubia
+Andi Vajda
 Atul Varma
 Dmitry Vasiliev
 Alexandre Vassalotti

Modified: python/branches/io-c/Misc/NEWS
==============================================================================
--- python/branches/io-c/Misc/NEWS	(original)
+++ python/branches/io-c/Misc/NEWS	Sun Feb  8 21:39:02 2009
@@ -12,6 +12,19 @@
 Core and Builtins
 -----------------
 
+- Issue #5182: Removed memoryview.__str__.
+
+- Issue #1717: Removed builtin cmp() function, dropped tp_compare
+  slot, the C API functions PyObject_Compare and PyUnicode_Compare and
+  the type definition cmpfunc.  The tp_compare slot has been renamed
+  to tp_reserved, and is reserved for future usage.
+
+- Issue 1242657: the __len__() and __length_hint__() calls in several tools
+  were suppressing all exceptions.  These include list() and bytearray().
+
+- Issue #4707: round(x, n) now returns an integer if x is an integer.
+  Previously it returned a float.
+
 - Issue #4753: By enabling a configure option named '--with-computed-gotos'
   on compilers that support it (notably: gcc, SunPro, icc), the bytecode
   evaluation loop is compiled with a new dispatch mechanism which gives
@@ -144,6 +157,44 @@
 Library
 -------
 
+- Issue #4512 (part 2): Promote ``ZipImporter._get_filename()`` to be a
+  public documented method ``ZipImporter.get_filename()``.
+
+- Issue #4195: The ``runpy`` module (and the ``-m`` switch) now support
+  the execution of packages by looking for and executing a ``__main__``
+  submodule when a package name is supplied. Initial patch by Andi
+  Vajda.
+
+- Issue #1731706: Call Tcl_ConditionFinalize for Tcl_Conditions that will
+  not be used again (this requires Tcl/Tk 8.3.1), also fix a memory leak in
+  Tkapp_Call when calling from a thread different than the one that created
+  the Tcl interpreter. Patch by Robert Hancock.
+
+- Issue #4285: Change sys.version_info to be a named tuple. Patch by
+  Ross Light.
+
+- Issue #1520877: Now distutils.sysconfig reads $AR from the 
+  environment/Makefile. Patch by Douglas Greiman.
+
+- Issue #1276768: The verbose option was not used in the code of
+  distutils.file_util and distutils.dir_util.
+
+- Issue #5132: Fixed trouble building extensions under Solaris with 
+  --enabled-shared activated. Initial patch by Dave Peterson.
+
+- Issue #1581476: Always use the Tcl global namespace when calling into Tcl.
+
+- The shelve module now defaults to pickle protocol 3.
+
+- Fix a bug in the trace module where a bytes object from co_lnotab had its
+  items being passed through ord().
+
+- Issue #2047: shutil.move() could believe that its destination path was
+  inside its source path if it began with the same letters (e.g. "src" vs.
+  "src.new").
+
+- Added the ttk module. See issue #2983: Ttk support for Tkinter.
+
 - Removed isSequenceType(), isMappingType, and isNumberType() from the
   operator module; use the abstract base classes instead.  Also removed
   the repeat() function; use mul() instead.
@@ -346,15 +397,26 @@
 - Issue #4861: ctypes.util.find_library(): Robustify. Fix library detection on
   biarch systems. Try to rely on ldconfig only, without using objdump and gcc.
 
+- Issue #5104: The socket module now raises OverflowError when 16-bit port and
+  protocol numbers are supplied outside the allowed 0-65536 range on bind()
+  and getservbyport().
+
 Tools/Demos
 -----------
 
+- Issue #4704: remove use of cmp() in pybench, bump its version number to 2.1,
+  and make it 2.6-compatible.
+
+- Ttk demos added in Demo/tkinter/ttk/
+
 - Issue #4677: add two list comprehension tests to pybench.
 
 
 Build
 -----
 
+- Issue #4494: Fix build with Py_NO_ENABLE_SHARED on Windows.
+
 - Issue #4895: Use _strdup on Windows CE.
 
 - Issue #4472: "configure --enable-shared" now works on OSX
@@ -419,6 +481,12 @@
   buffer.
 
 
+Tests
+-----
+
+- Issue #5083: New 'gui' resource for regrtest.
+
+
 Docs
 ----
 

Modified: python/branches/io-c/Modules/_bytesio.c
==============================================================================
--- python/branches/io-c/Modules/_bytesio.c	(original)
+++ python/branches/io-c/Modules/_bytesio.c	Sun Feb  8 21:39:02 2009
@@ -702,7 +702,7 @@
     0,                                         /*tp_print*/
     0,                                         /*tp_getattr*/
     0,                                         /*tp_setattr*/
-    0,                                         /*tp_compare*/
+    0,                                         /*tp_reserved*/
     0,                                         /*tp_repr*/
     0,                                         /*tp_as_number*/
     0,                                         /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_collectionsmodule.c
==============================================================================
--- python/branches/io-c/Modules/_collectionsmodule.c	(original)
+++ python/branches/io-c/Modules/_collectionsmodule.c	Sun Feb  8 21:39:02 2009
@@ -848,7 +848,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	deque_repr,			/* tp_repr */
 	0,				/* tp_as_number */
 	&deque_as_sequence,		/* tp_as_sequence */
@@ -978,7 +978,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -1061,7 +1061,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -1318,7 +1318,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	(reprfunc)defdict_repr,		/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_csv.c
==============================================================================
--- python/branches/io-c/Modules/_csv.c	(original)
+++ python/branches/io-c/Modules/_csv.c	Sun Feb  8 21:39:02 2009
@@ -443,7 +443,7 @@
 	(printfunc)0,                           /* tp_print */
 	(getattrfunc)0,                         /* tp_getattr */
 	(setattrfunc)0,                         /* tp_setattr */
-	(cmpfunc)0,                             /* tp_compare */
+	0,                                      /* tp_reserved */
 	(reprfunc)0,                            /* tp_repr */
 	0,                                      /* tp_as_number */
 	0,                                      /* tp_as_sequence */
@@ -864,7 +864,7 @@
 	(printfunc)0,                           /*tp_print*/
 	(getattrfunc)0,                         /*tp_getattr*/
 	(setattrfunc)0,                         /*tp_setattr*/
-	(cmpfunc)0,                             /*tp_compare*/
+	0,                                     /*tp_reserved*/
 	(reprfunc)0,                            /*tp_repr*/
 	0,                                      /*tp_as_number*/
 	0,                                      /*tp_as_sequence*/
@@ -1286,7 +1286,7 @@
 	(printfunc)0,                           /*tp_print*/
 	(getattrfunc)0,                         /*tp_getattr*/
 	(setattrfunc)0,                         /*tp_setattr*/
-	(cmpfunc)0,                             /*tp_compare*/
+	0,                                      /*tp_reserved*/
 	(reprfunc)0,                            /*tp_repr*/
 	0,                                      /*tp_as_number*/
 	0,                                      /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/_ctypes.c	(original)
+++ python/branches/io-c/Modules/_ctypes/_ctypes.c	Sun Feb  8 21:39:02 2009
@@ -179,7 +179,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -713,7 +713,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	&CDataType_as_sequence,			/* tp_as_sequence */
@@ -755,7 +755,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	&CDataType_as_sequence,		/* tp_as_sequence */
@@ -988,7 +988,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	&CDataType_as_sequence,		/* tp_as_sequence */
@@ -1390,7 +1390,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	&CDataType_as_sequence,			/* tp_as_sequence */
@@ -2059,7 +2059,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	&CDataType_as_sequence,		/* tp_as_sequence */
@@ -2277,7 +2277,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,			       		/* tp_repr */
 	0,					/* tp_as_number */
 	&CDataType_as_sequence,			/* tp_as_sequence */
@@ -2560,7 +2560,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -3889,7 +3889,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)CFuncPtr_repr,		/* tp_repr */
 	&CFuncPtr_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -4032,7 +4032,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -4074,7 +4074,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -4383,7 +4383,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	&Array_as_sequence,			/* tp_as_sequence */
@@ -4615,7 +4615,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)&Simple_repr,			/* tp_repr */
 	&Simple_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -4992,7 +4992,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	&Pointer_as_number,			/* tp_as_number */
 	&Pointer_as_sequence,			/* tp_as_sequence */
@@ -5086,7 +5086,7 @@
     0,                          /* tp_print */
     0,                          /* tp_getattr */
     0,                          /* tp_setattr */
-    0,                          /* tp_compare */
+    0,                          /* tp_reserved */
     0,                          /* tp_repr */
     0,                          /* tp_as_number */
     0,                          /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_ctypes/callbacks.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/callbacks.c	(original)
+++ python/branches/io-c/Modules/_ctypes/callbacks.c	Sun Feb  8 21:39:02 2009
@@ -50,7 +50,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/callproc.c	(original)
+++ python/branches/io-c/Modules/_ctypes/callproc.c	Sun Feb  8 21:39:02 2009
@@ -512,7 +512,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)PyCArg_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/cfield.c	(original)
+++ python/branches/io-c/Modules/_ctypes/cfield.c	Sun Feb  8 21:39:02 2009
@@ -289,7 +289,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)CField_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_ctypes/libffi_msvc/ffi.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/libffi_msvc/ffi.c	(original)
+++ python/branches/io-c/Modules/_ctypes/libffi_msvc/ffi.c	Sun Feb  8 21:39:02 2009
@@ -148,27 +148,12 @@
 }
 
 #ifdef _WIN32
-/*@-declundef@*/
-/*@-exportheader@*/
-extern int
-ffi_call_SYSV(void (*)(char *, extended_cif *), 
-	      /*@out@*/ extended_cif *, 
-	      unsigned, unsigned, 
-	      /*@out@*/ unsigned *, 
-	      void (*fn)());
-/*@=declundef@*/
-/*@=exportheader@*/
-
-/*@-declundef@*/
-/*@-exportheader@*/
 extern int
-ffi_call_STDCALL(void (*)(char *, extended_cif *),
-		 /*@out@*/ extended_cif *,
-		 unsigned, unsigned,
-		 /*@out@*/ unsigned *,
-		 void (*fn)());
-/*@=declundef@*/
-/*@=exportheader@*/
+ffi_call_x86(void (*)(char *, extended_cif *), 
+	     /*@out@*/ extended_cif *, 
+	     unsigned, unsigned, 
+	     /*@out@*/ unsigned *, 
+	     void (*fn)());
 #endif
 
 #ifdef _WIN64
@@ -209,17 +194,9 @@
     {
 #if !defined(_WIN64)
     case FFI_SYSV:
-      /*@-usedef@*/
-      return ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, 
-			   cif->flags, ecif.rvalue, fn);
-      /*@=usedef@*/
-      break;
-
     case FFI_STDCALL:
-      /*@-usedef@*/
-      return ffi_call_STDCALL(ffi_prep_args, &ecif, cif->bytes,
-			      cif->flags, ecif.rvalue, fn);
-      /*@=usedef@*/
+      return ffi_call_x86(ffi_prep_args, &ecif, cif->bytes, 
+			  cif->flags, ecif.rvalue, fn);
       break;
 #else
     case FFI_SYSV:

Deleted: python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.S
==============================================================================
--- python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.S	Sun Feb  8 21:39:02 2009
+++ (empty file)
@@ -1,243 +0,0 @@
-/* -----------------------------------------------------------------------
-   win32.S - Copyright (c) 1996, 1998, 2001, 2002  Red Hat, Inc.
-	     Copyright (c) 2001  John Beniton
-	     Copyright (c) 2002  Ranjit Mathew
-			
- 
-   X86 Foreign Function Interface
- 
-   Permission is hereby granted, free of charge, to any person obtaining
-   a copy of this software and associated documentation files (the
-   ``Software''), to deal in the Software without restriction, including
-   without limitation the rights to use, copy, modify, merge, publish,
-   distribute, sublicense, and/or sell copies of the Software, and to
-   permit persons to whom the Software is furnished to do so, subject to
-   the following conditions:
- 
-   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 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.
-   ----------------------------------------------------------------------- */
- 
-#define LIBFFI_ASM
-#include <fficonfig.h>
-#include <ffi.h>
- 
-.text
- 
-.globl ffi_prep_args
- 
-        # This assumes we are using gas.
-        .balign 16
-.globl _ffi_call_SYSV
- 
-_ffi_call_SYSV:
-        pushl %ebp
-        movl  %esp,%ebp
-
-	#THe: save previous %esi, and store the current stack pointer in %esi
-	pushl %esi
-	movl %esp,%esi
-
-        # Make room for all of the new args.
-        movl  16(%ebp),%ecx                                                     
-        subl  %ecx,%esp
- 
-        movl  %esp,%eax
- 
-        # Place all of the ffi_prep_args in position
-        pushl 12(%ebp)
-        pushl %eax
-        call  *8(%ebp)
- 
-        # Return stack to previous state and call the function
-        addl  $8,%esp
- 
-        # FIXME: Align the stack to a 128-bit boundary to avoid
-        # potential performance hits.
-
-	call  *28(%ebp)
- 
-        # Remove the space we pushed for the args
-        movl  16(%ebp),%ecx
-        addl  %ecx,%esp
-
-	sub %esp,%esi # calculate stack pointer difference
-
-        # Load %ecx with the return type code
-        movl  20(%ebp),%ecx
- 
-        # If the return value pointer is NULL, assume no return value.
-        cmpl  $0,24(%ebp)
-        jne   retint
- 
-        # Even if there is no space for the return value, we are
-        # obliged to handle floating-point values.
-        cmpl  $FFI_TYPE_FLOAT,%ecx
-        jne   noretval
-        fstp  %st(0)
- 
-        jmp   epilogue
- 
-retint:
-        cmpl  $FFI_TYPE_INT,%ecx
-        jne   retfloat
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        movl  %eax,0(%ecx)
-        jmp   epilogue
- 
-retfloat:
-        cmpl  $FFI_TYPE_FLOAT,%ecx
-        jne   retdouble   
-         # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        fstps (%ecx)
-        jmp   epilogue
- 
-retdouble:
-        cmpl  $FFI_TYPE_DOUBLE,%ecx
-        jne   retlongdouble
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        fstpl (%ecx)
-        jmp   epilogue
- 
-retlongdouble:
-        cmpl  $FFI_TYPE_LONGDOUBLE,%ecx
-        jne   retint64
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        fstpt (%ecx)
-        jmp   epilogue
- 
-retint64:
-        cmpl  $FFI_TYPE_SINT64,%ecx
-        jne   retstruct
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        movl  %eax,0(%ecx)
-        movl  %edx,4(%ecx)
- 
-retstruct:
-        # Nothing to do!
- 
-noretval:
-epilogue:
-	movl %esi,%eax # return the stack pointer detlta in %eax
-	popl %esi # restore previous %esi
-        movl %ebp,%esp
-        popl %ebp
-        ret
- 
-.ffi_call_SYSV_end:
-
-        # This assumes we are using gas.
-        .balign 16
-.globl _ffi_call_STDCALL
-
-_ffi_call_STDCALL:
-        pushl %ebp
-        movl  %esp,%ebp
-
-	#THe: save previous %esi, and store the current stack pointer in %esi
-	pushl %esi
-	movl %esp,%esi
-	
-        # Make room for all of the new args.
-        movl  16(%ebp),%ecx 
-        subl  %ecx,%esp
-
-        movl  %esp,%eax
-
-        # Place all of the ffi_prep_args in position
-        pushl 12(%ebp)
-        pushl %eax
-        call  *8(%ebp)
-
-        # Return stack to previous state and call the function
-        addl  $8,%esp
-
-        # FIXME: Align the stack to a 128-bit boundary to avoid
-        # potential performance hits.
-
-        call  *28(%ebp)
-
-	sub %esp,%esi # difference in stack
-
-        # stdcall functions pop arguments off the stack themselves
-
-        # Load %ecx with the return type code
-        movl  20(%ebp),%ecx
-
-        # If the return value pointer is NULL, assume no return value.
-        cmpl  $0,24(%ebp)
-        jne   sc_retint
-
-        # Even if there is no space for the return value, we are
-        # obliged to handle floating-point values.
-        cmpl  $FFI_TYPE_FLOAT,%ecx
-        jne   sc_noretval
-        fstp  %st(0)
-
-        jmp   sc_epilogue
-
-sc_retint:
-        cmpl  $FFI_TYPE_INT,%ecx
-        jne   sc_retfloat
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        movl  %eax,0(%ecx)
-        jmp   sc_epilogue
-
-sc_retfloat:
-        cmpl  $FFI_TYPE_FLOAT,%ecx
-        jne   sc_retdouble
-         # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        fstps (%ecx)
-        jmp   sc_epilogue
-
-sc_retdouble:
-        cmpl  $FFI_TYPE_DOUBLE,%ecx
-        jne   sc_retlongdouble
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        fstpl (%ecx)
-        jmp   sc_epilogue
-
-sc_retlongdouble:
-        cmpl  $FFI_TYPE_LONGDOUBLE,%ecx
-        jne   sc_retint64
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        fstpt (%ecx)
-        jmp   sc_epilogue
-
-sc_retint64:
-        cmpl  $FFI_TYPE_SINT64,%ecx
-        jne   sc_retstruct
-        # Load %ecx with the pointer to storage for the return value
-        movl  24(%ebp),%ecx
-        movl  %eax,0(%ecx)
-        movl  %edx,4(%ecx)
-
-sc_retstruct:
-        # Nothing to do!
-
-sc_noretval:
-sc_epilogue:
-        movl %esi,%eax # return the stack difference
-	popl %esi # restore previous %esi value
-        movl %ebp,%esp
-        popl %ebp
-        ret
-
-.ffi_call_STDCALL_end:

Modified: python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.c	(original)
+++ python/branches/io-c/Modules/_ctypes/libffi_msvc/win32.c	Sun Feb  8 21:39:02 2009
@@ -29,21 +29,21 @@
 /* theller: almost verbatim translation from gas syntax to MSVC inline
    assembler code. */
 
-/* theller: ffi_call_SYSV and ffi_call_STDCALL now return an integer - the
-   difference of the stack pointer before and after the function call.  If
-   everything is ok, zero is returned.  If stdcall functions are passed the
-   wrong number of arguments, the difference will be nonzero. */
+/* theller: ffi_call_x86 now returns an integer - the difference of the stack
+   pointer before and after the function call.  If everything is ok, zero is
+   returned.  If stdcall functions are passed the wrong number of arguments,
+   the difference will be nonzero. */
 
 #include <ffi.h>
 #include <ffi_common.h>
 
 __declspec(naked) int
-ffi_call_SYSV(void (* prepfunc)(char *, extended_cif *), /* 8 */
-		 extended_cif *ecif, /* 12 */
-		 unsigned bytes, /* 16 */
-		 unsigned flags, /* 20 */
-		 unsigned *rvalue, /* 24 */
-		 void (*fn)()) /* 28 */
+ffi_call_x86(void (* prepfunc)(char *, extended_cif *), /* 8 */
+	     extended_cif *ecif, /* 12 */
+	     unsigned bytes, /* 16 */
+	     unsigned flags, /* 20 */
+	     unsigned *rvalue, /* 24 */
+	     void (*fn)()) /* 28 */
 {
 	_asm {
 		push ebp
@@ -69,125 +69,20 @@
 // FIXME: Align the stack to a 128-bit boundary to avoid
 // potential performance hits.
 		call [ebp + 28]
-// Remove the space we pushed for the args
-		mov ecx, [ebp + 16]
-		add esp, ecx
-
-// XXX ASSERT THAT ESP IS THE SAME NOW THAN BEFORE!
-		sub esi, esp
-
-// Load %ecx with the return type code
-		mov ecx, [ebp + 20]
-
-// If the return value pointer is NULL, assume no return value.
-/*
-  Intel asm is weird. We have to explicitely specify 'DWORD PTR' in the nexr instruction,
-  otherwise only one BYTE will be compared (instead of a DWORD)!
- */
-		cmp DWORD PTR [ebp + 24], 0
-		jne sc_retint
-
-// Even if there is no space for the return value, we are
-// obliged to handle floating-point values.
-		cmp ecx, FFI_TYPE_FLOAT
-		jne sc_noretval
-//        fstp  %st(0)
-		fstp st(0)
-
-		jmp sc_epilogue
-
-sc_retint:
-		cmp ecx, FFI_TYPE_INT
-		jne sc_retfloat
-//        # Load %ecx with the pointer to storage for the return value
-		mov ecx, [ebp + 24]
-		mov [ecx + 0], eax
-		jmp sc_epilogue
-
-sc_retfloat:
-		cmp ecx, FFI_TYPE_FLOAT
-		jne sc_retdouble
-// Load %ecx with the pointer to storage for the return value
-		mov ecx, [ebp+24]
-//        fstps (%ecx)
-		fstp DWORD PTR [ecx]
-		jmp sc_epilogue
 
-sc_retdouble:
-		cmp ecx, FFI_TYPE_DOUBLE
-		jne sc_retlongdouble
-//        movl  24(%ebp),%ecx
-		mov ecx, [ebp+24]
-		fstp QWORD PTR [ecx]
-		jmp sc_epilogue
-
-		jmp sc_retlongdouble // avoid warning about unused label
-sc_retlongdouble:
-		cmp ecx, FFI_TYPE_LONGDOUBLE
-		jne sc_retint64
-// Load %ecx with the pointer to storage for the return value
-		mov ecx, [ebp+24]
-//        fstpt (%ecx)
-		fstp QWORD PTR [ecx] /* XXX ??? */
-		jmp sc_epilogue
-
-sc_retint64:
-		cmp ecx, FFI_TYPE_SINT64
-		jne sc_retstruct
-// Load %ecx with the pointer to storage for the return value
-		mov ecx, [ebp+24]
-		mov [ecx+0], eax
-		mov [ecx+4], edx
-
-sc_retstruct:
-// Nothing to do!
-
-sc_noretval:
-sc_epilogue:
-		mov eax, esi
-		pop esi // NEW restore: must be preserved across function calls
-		mov esp, ebp
-		pop ebp
-		ret
-	}
-}
-
-__declspec(naked) int
-ffi_call_STDCALL(void (* prepfunc)(char *, extended_cif *), /* 8 */
-		 extended_cif *ecif, /* 12 */
-		 unsigned bytes, /* 16 */
-		 unsigned flags, /* 20 */
-		 unsigned *rvalue, /* 24 */
-		 void (*fn)()) /* 28 */
-{
-	_asm {
-		push ebp
-		mov ebp, esp
-
-		push esi // NEW: this register must be preserved across function calls
-
-// XXX SAVE ESP NOW!
-		mov esi, esp
-
-// Make room for all of the new args.
-		mov ecx, [ebp+16]
-		sub esp, ecx
+// Load ecif->cif->abi
+		mov ecx, [ebp + 12]
+		mov ecx, [ecx]ecif.cif
+		mov ecx, [ecx]ecif.cif.abi
 		
-		mov eax, esp
-
-// Place all of the ffi_prep_args in position
-		push [ebp + 12] // ecif
-		push eax
-		call [ebp + 8] // prepfunc
-
-// Return stack to previous state and call the function
-		add esp, 8
-// FIXME: Align the stack to a 128-bit boundary to avoid
-// potential performance hits.
-		call [ebp + 28]
-// stdcall functions pop arguments off the stack themselves
-
-// XXX IS ESP NOW THE SAME AS BEFORE?
+		cmp ecx, FFI_STDCALL
+		je noclean
+// STDCALL: Remove the space we pushed for the args
+		mov ecx, [ebp + 16]
+		add esp, ecx
+// CDECL: Caller has already cleaned the stack
+noclean:
+// Check that esp has the same value as before!
 		sub esi, esp
 
 // Load %ecx with the return type code

Modified: python/branches/io-c/Modules/_ctypes/stgdict.c
==============================================================================
--- python/branches/io-c/Modules/_ctypes/stgdict.c	(original)
+++ python/branches/io-c/Modules/_ctypes/stgdict.c	Sun Feb  8 21:39:02 2009
@@ -111,7 +111,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_curses_panel.c
==============================================================================
--- python/branches/io-c/Modules/_curses_panel.c	(original)
+++ python/branches/io-c/Modules/_curses_panel.c	Sun Feb  8 21:39:02 2009
@@ -341,7 +341,7 @@
     0,			/*tp_print*/
     0,			/*tp_getattr*/
     0,			/*tp_setattr*/
-    0,			/*tp_compare*/
+    0,			/*tp_reserved*/
     0,			/*tp_repr*/
     0,			/*tp_as_number*/
     0,			/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_cursesmodule.c
==============================================================================
--- python/branches/io-c/Modules/_cursesmodule.c	(original)
+++ python/branches/io-c/Modules/_cursesmodule.c	Sun Feb  8 21:39:02 2009
@@ -1662,7 +1662,7 @@
 	0,			/*tp_print*/
 	(getattrfunc)0,		/*tp_getattr*/
 	(setattrfunc)0,		/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_dbmmodule.c
==============================================================================
--- python/branches/io-c/Modules/_dbmmodule.c	(original)
+++ python/branches/io-c/Modules/_dbmmodule.c	Sun Feb  8 21:39:02 2009
@@ -337,7 +337,7 @@
 	0,			  /*tp_print*/
 	0,                        /*tp_getattr*/
 	0,			  /*tp_setattr*/
-	0,			  /*tp_compare*/
+	0,			  /*tp_reserved*/
 	0,			  /*tp_repr*/
 	0,			  /*tp_as_number*/
 	&dbm_as_sequence,	  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_elementtree.c
==============================================================================
--- python/branches/io-c/Modules/_elementtree.c	(original)
+++ python/branches/io-c/Modules/_elementtree.c	Sun Feb  8 21:39:02 2009
@@ -761,7 +761,7 @@
     for (i = 0; i < self->extra->length; i++) {
         PyObject* item = self->extra->children[i];
         if (Element_CheckExact(item) &&
-            PyObject_Compare(((ElementObject*)item)->tag, tag) == 0) {
+            PyObject_RichCompareBool(((ElementObject*)item)->tag, tag, Py_EQ) == 1) {
             Py_INCREF(item);
             return item;
         }
@@ -792,7 +792,8 @@
 
     for (i = 0; i < self->extra->length; i++) {
         ElementObject* item = (ElementObject*) self->extra->children[i];
-        if (Element_CheckExact(item) && !PyObject_Compare(item->tag, tag)) {
+        if (Element_CheckExact(item) && (PyObject_RichCompareBool(item->tag, tag, Py_EQ) == 1)) {
+
             PyObject* text = element_get_text(item);
             if (text == Py_None)
                 return PyBytes_FromString("");
@@ -830,7 +831,7 @@
     for (i = 0; i < self->extra->length; i++) {
         PyObject* item = self->extra->children[i];
         if (Element_CheckExact(item) &&
-            PyObject_Compare(((ElementObject*)item)->tag, tag) == 0) {
+            PyObject_RichCompareBool(((ElementObject*)item)->tag, tag, Py_EQ) == 1) {
             if (PyList_Append(out, item) < 0) {
                 Py_DECREF(out);
                 return NULL;
@@ -1102,7 +1103,7 @@
     for (i = 0; i < self->extra->length; i++) {
         if (self->extra->children[i] == element)
             break;
-        if (PyObject_Compare(self->extra->children[i], element) == 0)
+        if (PyObject_RichCompareBool(self->extra->children[i], element, Py_EQ) == 1)
             break;
     }
 
@@ -1378,7 +1379,7 @@
     0, /* tp_print */
     0, /* tp_getattr */
     (setattrfunc)element_setattr, /* tp_setattr */
-    0, /* tp_compare */
+    0, /* tp_reserved */
     (reprfunc)element_repr, /* tp_repr */
     0, /* tp_as_number */
     &element_as_sequence, /* tp_as_sequence */
@@ -1802,7 +1803,7 @@
     0, /* tp_print */
     0, /* tp_getattr */
     0, /* tp_setattr */
-    0, /* tp_compare */
+    0, /* tp_reserved */
     0, /* tp_repr */
     0, /* tp_as_number */
     0, /* tp_as_sequence */
@@ -2558,7 +2559,7 @@
     0, /* tp_print */
     0, /* tp_getattr */
     0, /* tp_setattr */
-    0, /* tp_compare */
+    0, /* tp_reserved */
     0, /* tp_repr */
     0, /* tp_as_number */
     0, /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_fileio.c
==============================================================================
--- python/branches/io-c/Modules/_fileio.c	(original)
+++ python/branches/io-c/Modules/_fileio.c	Sun Feb  8 21:39:02 2009
@@ -961,7 +961,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)fileio_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_functoolsmodule.c
==============================================================================
--- python/branches/io-c/Modules/_functoolsmodule.c	(original)
+++ python/branches/io-c/Modules/_functoolsmodule.c	Sun Feb  8 21:39:02 2009
@@ -206,7 +206,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_gdbmmodule.c
==============================================================================
--- python/branches/io-c/Modules/_gdbmmodule.c	(original)
+++ python/branches/io-c/Modules/_gdbmmodule.c	Sun Feb  8 21:39:02 2009
@@ -390,7 +390,7 @@
     0,                                  /*tp_print*/
     0,                                  /*tp_getattr*/
     0,                                  /*tp_setattr*/
-    0,                                  /*tp_compare*/
+    0,                                  /*tp_reserved*/
     0,                                  /*tp_repr*/
     0,                                  /*tp_as_number*/
     &dbm_as_sequence,                   /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_hashopenssl.c
==============================================================================
--- python/branches/io-c/Modules/_hashopenssl.c	(original)
+++ python/branches/io-c/Modules/_hashopenssl.c	Sun Feb  8 21:39:02 2009
@@ -407,7 +407,7 @@
     0,                  /*tp_print*/
     0,                  /*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     (reprfunc)EVP_repr, /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_localemodule.c
==============================================================================
--- python/branches/io-c/Modules/_localemodule.c	(original)
+++ python/branches/io-c/Modules/_localemodule.c	Sun Feb  8 21:39:02 2009
@@ -272,7 +272,9 @@
 
 #ifdef HAVE_WCSXFRM
 PyDoc_STRVAR(strxfrm__doc__,
-"string -> string. Returns a string that behaves for cmp locale-aware.");
+"strxfrm(string) -> string.\n\
+\n\
+Return a string that can be used as a key for locale-aware comparisons.");
 
 static PyObject*
 PyLocale_strxfrm(PyObject* self, PyObject* args)

Modified: python/branches/io-c/Modules/_lsprof.c
==============================================================================
--- python/branches/io-c/Modules/_lsprof.c	(original)
+++ python/branches/io-c/Modules/_lsprof.c	Sun Feb  8 21:39:02 2009
@@ -820,7 +820,7 @@
 	0,                                      /* tp_print */
 	0,                                      /* tp_getattr */
 	0,                                      /* tp_setattr */
-	0,                                      /* tp_compare */
+	0,                                      /* tp_reserved */
 	0,                                      /* tp_repr */
 	0,                                      /* tp_as_number */
 	0,                                      /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_multiprocessing/connection.h
==============================================================================
--- python/branches/io-c/Modules/_multiprocessing/connection.h	(original)
+++ python/branches/io-c/Modules/_multiprocessing/connection.h	Sun Feb  8 21:39:02 2009
@@ -487,7 +487,7 @@
 	/* tp_print          */ 0,
 	/* tp_getattr        */ 0,
 	/* tp_setattr        */ 0,
-	/* tp_compare        */ 0,
+	/* tp_reserved       */ 0,
 	/* tp_repr           */ (reprfunc)connection_repr,
 	/* tp_as_number      */ 0,
 	/* tp_as_sequence    */ 0,

Modified: python/branches/io-c/Modules/_multiprocessing/semaphore.c
==============================================================================
--- python/branches/io-c/Modules/_multiprocessing/semaphore.c	(original)
+++ python/branches/io-c/Modules/_multiprocessing/semaphore.c	Sun Feb  8 21:39:02 2009
@@ -592,7 +592,7 @@
 	/* tp_print          */ 0,
 	/* tp_getattr        */ 0,
 	/* tp_setattr        */ 0,
-	/* tp_compare        */ 0,
+	/* tp_reserved       */ 0,
 	/* tp_repr           */ 0,
 	/* tp_as_number      */ 0,
 	/* tp_as_sequence    */ 0,

Modified: python/branches/io-c/Modules/_pickle.c
==============================================================================
--- python/branches/io-c/Modules/_pickle.c	(original)
+++ python/branches/io-c/Modules/_pickle.c	Sun Feb  8 21:39:02 2009
@@ -715,7 +715,7 @@
     i = 0;
     module_name = NULL;
     while ((j = PyDict_Next(modules_dict, &i, &module_name, &module))) {
-        if (PyObject_Compare(module_name, main_str) == 0)
+        if (PyObject_RichCompareBool(module_name, main_str, Py_EQ) == 1)
             continue;
 
         obj = PyObject_GetAttr(module, global_name);
@@ -2677,7 +2677,7 @@
     0,                                  /*tp_print*/
     0,                                  /*tp_getattr*/
     0,                                  /*tp_setattr*/
-    0,                                  /*tp_compare*/
+    0,                                  /*tp_reserved*/
     0,                                  /*tp_repr*/
     0,                                  /*tp_as_number*/
     0,                                  /*tp_as_sequence*/
@@ -4534,7 +4534,7 @@
     0,                                  /*tp_print*/
     0,                                  /*tp_getattr*/
     0,	                                /*tp_setattr*/
-    0,                                  /*tp_compare*/
+    0,                                  /*tp_reserved*/
     0,                                  /*tp_repr*/
     0,                                  /*tp_as_number*/
     0,                                  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_randommodule.c
==============================================================================
--- python/branches/io-c/Modules/_randommodule.c	(original)
+++ python/branches/io-c/Modules/_randommodule.c	Sun Feb  8 21:39:02 2009
@@ -459,7 +459,7 @@
 	0,				/*tp_print*/
 	0,				/*tp_getattr*/
 	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
+	0,				/*tp_reserved*/
 	0,				/*tp_repr*/
 	0,				/*tp_as_number*/
 	0,				/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_sqlite/cache.c
==============================================================================
--- python/branches/io-c/Modules/_sqlite/cache.c	(original)
+++ python/branches/io-c/Modules/_sqlite/cache.c	Sun Feb  8 21:39:02 2009
@@ -282,7 +282,7 @@
         0,                                              /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */
@@ -324,7 +324,7 @@
         0,                                              /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_sqlite/connection.c
==============================================================================
--- python/branches/io-c/Modules/_sqlite/connection.c	(original)
+++ python/branches/io-c/Modules/_sqlite/connection.c	Sun Feb  8 21:39:02 2009
@@ -1350,7 +1350,7 @@
         0,                                              /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_sqlite/cursor.c
==============================================================================
--- python/branches/io-c/Modules/_sqlite/cursor.c	(original)
+++ python/branches/io-c/Modules/_sqlite/cursor.c	Sun Feb  8 21:39:02 2009
@@ -1066,7 +1066,7 @@
         0,                                              /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_sqlite/prepare_protocol.c
==============================================================================
--- python/branches/io-c/Modules/_sqlite/prepare_protocol.c	(original)
+++ python/branches/io-c/Modules/_sqlite/prepare_protocol.c	Sun Feb  8 21:39:02 2009
@@ -42,7 +42,7 @@
         0,                                              /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_sqlite/row.c
==============================================================================
--- python/branches/io-c/Modules/_sqlite/row.c	(original)
+++ python/branches/io-c/Modules/_sqlite/row.c	Sun Feb  8 21:39:02 2009
@@ -210,7 +210,7 @@
         (printfunc)pysqlite_row_print,                  /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_sqlite/statement.c
==============================================================================
--- python/branches/io-c/Modules/_sqlite/statement.c	(original)
+++ python/branches/io-c/Modules/_sqlite/statement.c	Sun Feb  8 21:39:02 2009
@@ -464,7 +464,7 @@
         0,                                              /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
-        0,                                              /* tp_compare */
+        0,                                              /* tp_reserved */
         0,                                              /* tp_repr */
         0,                                              /* tp_as_number */
         0,                                              /* tp_as_sequence */

Modified: python/branches/io-c/Modules/_sre.c
==============================================================================
--- python/branches/io-c/Modules/_sre.c	(original)
+++ python/branches/io-c/Modules/_sre.c	Sun Feb  8 21:39:02 2009
@@ -2625,7 +2625,7 @@
     0,					/* tp_print */
     0,					/* tp_getattr */
     0,					/* tp_setattr */
-    0,					/* tp_compare */
+    0,					/* tp_reserved */
     0,					/* tp_repr */
     0,					/* tp_as_number */
     0,					/* tp_as_sequence */
@@ -3635,7 +3635,7 @@
     0,				/* tp_print */
     0,				/* tp_getattr */
     0,				/* tp_setattr */
-    0,				/* tp_compare */
+    0,				/* tp_reserved */
     0,				/* tp_repr */
     0,				/* tp_as_number */
     0,				/* tp_as_sequence */
@@ -3819,7 +3819,7 @@
     0,				/* tp_print */
     0,				/* tp_getattr */
     0,				/* tp_setattr */
-    0,				/* tp_compare */
+    0,				/* tp_reserved */
     0,				/* tp_repr */
     0,				/* tp_as_number */
     0,				/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_ssl.c
==============================================================================
--- python/branches/io-c/Modules/_ssl.c	(original)
+++ python/branches/io-c/Modules/_ssl.c	Sun Feb  8 21:39:02 2009
@@ -1432,7 +1432,7 @@
 	0,				/*tp_print*/
 	0,				/*tp_getattr*/
 	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
+	0,				/*tp_reserved*/
 	0,				/*tp_repr*/
 	0,				/*tp_as_number*/
 	0,				/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_stringio.c
==============================================================================
--- python/branches/io-c/Modules/_stringio.c	(original)
+++ python/branches/io-c/Modules/_stringio.c	Sun Feb  8 21:39:02 2009
@@ -322,7 +322,7 @@
     0,                                         /*tp_print*/
     0,                                         /*tp_getattr*/
     0,                                         /*tp_setattr*/
-    0,                                         /*tp_compare*/
+    0,                                         /*tp_reserved*/
     0,                                         /*tp_repr*/
     0,                                         /*tp_as_number*/
     0,                                         /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/_struct.c
==============================================================================
--- python/branches/io-c/Modules/_struct.c	(original)
+++ python/branches/io-c/Modules/_struct.c	Sun Feb  8 21:39:02 2009
@@ -1853,7 +1853,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_testcapimodule.c
==============================================================================
--- python/branches/io-c/Modules/_testcapimodule.c	(original)
+++ python/branches/io-c/Modules/_testcapimodule.c	Sun Feb  8 21:39:02 2009
@@ -187,7 +187,7 @@
 	0,			/* tp_print */
 	0,			/* tp_getattr */
 	0,			/* tp_setattr */
-	0,			/* tp_compare */
+	0,			/* tp_reserved */
 	0,			/* tp_repr */
 	0,			/* tp_as_number */
 	0,			/* tp_as_sequence */
@@ -1322,7 +1322,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Modules/_threadmodule.c
==============================================================================
--- python/branches/io-c/Modules/_threadmodule.c	(original)
+++ python/branches/io-c/Modules/_threadmodule.c	Sun Feb  8 21:39:02 2009
@@ -129,7 +129,7 @@
 	0,				/*tp_print*/
 	0,				/*tp_getattr*/
 	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
+	0,				/*tp_reserved*/
 	0,				/*tp_repr*/
 	0,				/*tp_as_number*/
 	0,				/*tp_as_sequence*/
@@ -358,7 +358,7 @@
 	/* tp_print          */ 0,
 	/* tp_getattr        */ 0,
 	/* tp_setattr        */ 0,
-	/* tp_compare        */ 0,
+	/* tp_reserved       */ 0,
 	/* tp_repr           */ 0,
 	/* tp_as_number      */ 0,
 	/* tp_as_sequence    */ 0,

Modified: python/branches/io-c/Modules/_tkinter.c
==============================================================================
--- python/branches/io-c/Modules/_tkinter.c	(original)
+++ python/branches/io-c/Modules/_tkinter.c	Sun Feb  8 21:39:02 2009
@@ -9,9 +9,9 @@
 
 /* TCL/TK VERSION INFO:
 
-	Only Tcl/Tk 8.2 and later are supported.  Older versions are not
-	supported.  (Use Python 2.2 if you cannot upgrade your Tcl/Tk
-	libraries.)
+	Only Tcl/Tk 8.3.1 and later are supported.  Older versions are not
+	supported. Use Python 2.6 or older if you cannot upgrade your
+	Tcl/Tk libraries.
 */
 
 /* XXX Further speed-up ideas, involving Tcl 8.0 features:
@@ -788,15 +788,59 @@
 	                            self->value->typePtr->name, self->value);
 }
 
-static int
-PyTclObject_cmp(PyTclObject *self, PyTclObject *other)
+#define TEST_COND(cond) ((cond) ? Py_True : Py_False)
+
+static PyObject *
+PyTclObject_richcompare(PyObject *self, PyObject *other, int op)
 {
-	int res;
-	res = strcmp(Tcl_GetString(self->value),
-		     Tcl_GetString(other->value));
-	if (res < 0) return -1;
-	if (res > 0) return 1;
-	return 0;
+	int result;
+	PyObject *v;
+
+	/* neither argument should be NULL, unless something's gone wrong */
+	if (self == NULL || other == NULL) {
+		PyErr_BadInternalCall();
+		return NULL;
+	}
+
+	/* both arguments should be instances of PyTclObject */
+	if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) {
+		v = Py_NotImplemented;
+		goto finished;
+	}
+
+	if (self == other)
+		/* fast path when self and other are identical */
+		result = 0;
+	else
+		result = strcmp(Tcl_GetString(((PyTclObject *)self)->value),
+				Tcl_GetString(((PyTclObject *)other)->value));
+	/* Convert return value to a Boolean */
+	switch (op) {
+	case Py_EQ:
+		v = TEST_COND(result == 0);
+		break;
+	case Py_NE:
+		v = TEST_COND(result != 0);
+		break;
+	case Py_LE:
+		v = TEST_COND(result <= 0);
+		break;
+	case Py_GE:
+		v = TEST_COND(result >= 0);
+		break;
+	case Py_LT:
+		v = TEST_COND(result < 0);
+		break;
+	case Py_GT:
+		v = TEST_COND(result > 0);
+		break;
+	default:
+		PyErr_BadArgument();
+		return NULL;
+	}
+  finished:
+	Py_INCREF(v);
+	return v;
 }
 
 PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
@@ -818,45 +862,45 @@
 static PyTypeObject PyTclObject_Type = {
 	PyVarObject_HEAD_INIT(NULL, 0)
 	"_tkinter.Tcl_Obj",		/*tp_name*/
-	sizeof(PyTclObject),	/*tp_basicsize*/
-	0,			/*tp_itemsize*/
+	sizeof(PyTclObject),		/*tp_basicsize*/
+	0,				/*tp_itemsize*/
 	/* methods */
-	(destructor)PyTclObject_dealloc, /*tp_dealloc*/
-	0,			/*tp_print*/
-	0,			/*tp_getattr*/
-	0,			/*tp_setattr*/
-	(cmpfunc)PyTclObject_cmp,	/*tp_compare*/
+	(destructor)PyTclObject_dealloc,/*tp_dealloc*/
+	0,				/*tp_print*/
+	0,				/*tp_getattr*/
+	0,				/*tp_setattr*/
+	0,				/*tp_reserved*/
 	(reprfunc)PyTclObject_repr,	/*tp_repr*/
-	0,			/*tp_as_number*/
-	0,			/*tp_as_sequence*/
-	0,			/*tp_as_mapping*/
-	0,			/*tp_hash*/
-        0,                      /*tp_call*/
-        (reprfunc)PyTclObject_str,        /*tp_str*/
-        PyObject_GenericGetAttr,/*tp_getattro*/
-        0,                      /*tp_setattro*/
-        0,                      /*tp_as_buffer*/
-        Py_TPFLAGS_DEFAULT,     /*tp_flags*/
-        0,                      /*tp_doc*/
-        0,                      /*tp_traverse*/
-        0,                      /*tp_clear*/
-        0,                      /*tp_richcompare*/
-        0,                      /*tp_weaklistoffset*/
-        0,                      /*tp_iter*/
-        0,                      /*tp_iternext*/
-        0,    /*tp_methods*/
-        0,			/*tp_members*/
-        PyTclObject_getsetlist, /*tp_getset*/
-        0,                      /*tp_base*/
-        0,                      /*tp_dict*/
-        0,                      /*tp_descr_get*/
-        0,                      /*tp_descr_set*/
-        0,                      /*tp_dictoffset*/
-        0,                      /*tp_init*/
-        0,                      /*tp_alloc*/
-        0,                      /*tp_new*/
-        0,                      /*tp_free*/
-        0,                      /*tp_is_gc*/
+	0,				/*tp_as_number*/
+	0,				/*tp_as_sequence*/
+	0,				/*tp_as_mapping*/
+	0,				/*tp_hash*/
+	0,				/*tp_call*/
+	(reprfunc)PyTclObject_str,	/*tp_str*/
+	PyObject_GenericGetAttr,	/*tp_getattro*/
+	0,				/*tp_setattro*/
+	0,				/*tp_as_buffer*/
+	Py_TPFLAGS_DEFAULT,		/*tp_flags*/
+	0,				/*tp_doc*/
+	0,				/*tp_traverse*/
+	0,				/*tp_clear*/
+	PyTclObject_richcompare,	/*tp_richcompare*/
+	0,				/*tp_weaklistoffset*/
+	0,				/*tp_iter*/
+	0,				/*tp_iternext*/
+	0,				/*tp_methods*/
+	0,				/*tp_members*/
+	PyTclObject_getsetlist,		/*tp_getset*/
+	0,				/*tp_base*/
+	0,				/*tp_dict*/
+	0,				/*tp_descr_get*/
+	0,				/*tp_descr_set*/
+	0,				/*tp_dictoffset*/
+	0,				/*tp_init*/
+	0,				/*tp_alloc*/
+	0,				/*tp_new*/
+	0,				/*tp_free*/
+	0,				/*tp_is_gc*/
 };
 
 static Tcl_Obj*
@@ -1041,7 +1085,7 @@
 	int flags;
 	PyObject **res;
 	PyObject **exc_type, **exc_value, **exc_tb;
-	Tcl_Condition done;
+	Tcl_Condition *done;
 } Tkapp_CallEvent;
 
 void
@@ -1164,10 +1208,12 @@
 		*(e->res) = Tkapp_CallResult(e->self);
 	}
 	LEAVE_PYTHON
-  done:
+
+	Tkapp_CallDeallocArgs(objv, objStore, objc);
+done:
 	/* Wake up calling thread. */
 	Tcl_MutexLock(&call_mutex);
-	Tcl_ConditionNotify(&e->done);
+	Tcl_ConditionNotify(e->done);
 	Tcl_MutexUnlock(&call_mutex);
 	return 1;
 }
@@ -1192,8 +1238,7 @@
 	int objc, i;
 	PyObject *res = NULL;
 	TkappObject *self = (TkappObject*)selfptr;
-	/* Could add TCL_EVAL_GLOBAL if wrapped by GlobalCall... */
-	int flags = TCL_EVAL_DIRECT;
+	int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL;
 
 	/* If args is a single tuple, replace with contents of tuple */
 	if (1 == PyTuple_Size(args)){
@@ -1206,6 +1251,7 @@
 		/* We cannot call the command directly. Instead, we must
 		   marshal the parameters to the interpreter thread. */
 		Tkapp_CallEvent *ev;
+		Tcl_Condition cond = NULL;
 		PyObject *exc_type, *exc_value, *exc_tb;
 		if (!WaitForMainloop(self))
 			return NULL;
@@ -1217,9 +1263,9 @@
 		ev->exc_type = &exc_type;
 		ev->exc_value = &exc_value;
 		ev->exc_tb = &exc_tb;
-		ev->done = (Tcl_Condition)0;
+		ev->done = &cond;
 
-		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done, &call_mutex);
+		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex);
 
 		if (res == NULL) {
 			if (exc_type)
@@ -1227,6 +1273,7 @@
 			else
 				PyErr_SetObject(Tkinter_TclError, exc_value);
 		}
+		Tcl_ConditionFinalize(&cond);
 	}
 	else
 #endif
@@ -1412,7 +1459,7 @@
 	PyObject **res;
 	PyObject **exc_type;
 	PyObject **exc_val;
-	Tcl_Condition cond;
+	Tcl_Condition *cond;
 } VarEvent;
 
 static int
@@ -1456,7 +1503,7 @@
 	ENTER_PYTHON
         var_perform(ev);
 	Tcl_MutexLock(&var_mutex);
-	Tcl_ConditionNotify(&ev->cond);
+	Tcl_ConditionNotify(ev->cond);
 	Tcl_MutexUnlock(&var_mutex);
 	LEAVE_PYTHON
 	return 1;
@@ -1471,6 +1518,7 @@
 		TkappObject *self = (TkappObject*)selfptr;
 		VarEvent *ev;
 		PyObject *res, *exc_type, *exc_val;
+		Tcl_Condition cond = NULL;
 
 		/* The current thread is not the interpreter thread.  Marshal
 		   the call to the interpreter thread, then wait for
@@ -1487,9 +1535,10 @@
 		ev->res = &res;
 		ev->exc_type = &exc_type;
 		ev->exc_val = &exc_val;
-		ev->cond = NULL;
+		ev->cond = &cond;
 		ev->ev.proc = (Tcl_EventProc*)var_proc;
-		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->cond, &var_mutex);
+		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex);
+		Tcl_ConditionFinalize(&cond);
 		if (!res) {
 			PyErr_SetObject(exc_type, exc_val);
 			Py_DECREF(exc_type);
@@ -1976,7 +2025,7 @@
 	int create;
 	int *status;
 	ClientData *data;
-	Tcl_Condition done;
+	Tcl_Condition *done;
 } CommandEvent;
 
 static int
@@ -1989,7 +2038,7 @@
 	else
 		*ev->status = Tcl_DeleteCommand(ev->interp, ev->name);
 	Tcl_MutexLock(&command_mutex);
-	Tcl_ConditionNotify(&ev->done);
+	Tcl_ConditionNotify(ev->done);
 	Tcl_MutexUnlock(&command_mutex);
 	return 1;
 }
@@ -2025,6 +2074,7 @@
 	data->func = func;
 
 	if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+		Tcl_Condition cond = NULL;
 		CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
 		ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
 		ev->interp = self->interp;
@@ -2032,8 +2082,9 @@
 		ev->name = cmdName;
 		ev->data = (ClientData)data;
 		ev->status = &err;
-		ev->done = NULL;
-		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done, &command_mutex);
+		ev->done = &cond;
+		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex);
+		Tcl_ConditionFinalize(&cond);
 	}
 	else {
 		ENTER_TCL
@@ -2064,6 +2115,7 @@
 	if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
 		return NULL;
 	if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+		Tcl_Condition cond = NULL;
 		CommandEvent *ev;
 		ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
 		ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
@@ -2071,9 +2123,10 @@
 		ev->create = 0;
 		ev->name = cmdName;
 		ev->status = &err;
-		ev->done = NULL;
-		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &ev->done,
+		ev->done = &cond;
+		Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond,
 				 &command_mutex);
+		Tcl_ConditionFinalize(&cond);
 	}
 	else {
 		ENTER_TCL
@@ -2307,7 +2360,7 @@
 	0,				     /*tp_print */
 	0,				     /*tp_getattr */
 	0,				     /*tp_setattr */
-	0,				     /*tp_compare */
+	0,				     /*tp_reserved */
 	Tktt_Repr,			     /*tp_repr */
 	0,				     /*tp_as_number */
 	0,				     /*tp_as_sequence */
@@ -2633,7 +2686,7 @@
 	0,				     /*tp_print */
 	0,				     /*tp_getattr */
 	0,				     /*tp_setattr */
-	0,				     /*tp_compare */
+	0,				     /*tp_reserved */
 	0,				     /*tp_repr */
 	0,				     /*tp_as_number */
 	0,				     /*tp_as_sequence */
@@ -2750,7 +2803,9 @@
 		return NULL;
 
 	context.maxsize = PySequence_Size(item);
-	if (context.maxsize <= 0)
+	if (context.maxsize < 0)
+		return NULL;
+	if (context.maxsize == 0)
 		return PyTuple_New(0);
 
 	context.tuple = PyTuple_New(context.maxsize);

Modified: python/branches/io-c/Modules/arraymodule.c
==============================================================================
--- python/branches/io-c/Modules/arraymodule.c	(original)
+++ python/branches/io-c/Modules/arraymodule.c	Sun Feb  8 21:39:02 2009
@@ -2013,7 +2013,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)array_repr,			/* tp_repr */
 	0,					/* tp_as_number*/
 	&array_as_sequence,			/* tp_as_sequence*/
@@ -2116,7 +2116,7 @@
 	0,                                      /* tp_print */
 	0,                                      /* tp_getattr */
 	0,                                      /* tp_setattr */
-	0,                                      /* tp_compare */
+	0,                                      /* tp_reserved */
 	0,                                      /* tp_repr */
 	0,                                      /* tp_as_number */
 	0,                                      /* tp_as_sequence */

Modified: python/branches/io-c/Modules/bz2module.c
==============================================================================
--- python/branches/io-c/Modules/bz2module.c	(original)
+++ python/branches/io-c/Modules/bz2module.c	Sun Feb  8 21:39:02 2009
@@ -1339,7 +1339,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -1622,7 +1622,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -1851,7 +1851,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/cjkcodecs/multibytecodec.c
==============================================================================
--- python/branches/io-c/Modules/cjkcodecs/multibytecodec.c	(original)
+++ python/branches/io-c/Modules/cjkcodecs/multibytecodec.c	Sun Feb  8 21:39:02 2009
@@ -705,7 +705,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -990,7 +990,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1199,7 +1199,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1529,7 +1529,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1749,7 +1749,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Modules/datetimemodule.c
==============================================================================
--- python/branches/io-c/Modules/datetimemodule.c	(original)
+++ python/branches/io-c/Modules/datetimemodule.c	Sun Feb  8 21:39:02 2009
@@ -1427,7 +1427,7 @@
  * Miscellaneous helpers.
  */
 
-/* For various reasons, we need to use tp_richcompare instead of tp_compare.
+/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
  * The comparisons here all most naturally compute a cmp()-like result.
  * This little helper turns that into a bool result for rich comparisons.
  */
@@ -2138,7 +2138,7 @@
 	0,						/* tp_print */
 	0,						/* tp_getattr */
 	0,						/* tp_setattr */
-	0,						/* tp_compare */
+	0,						/* tp_reserved */
 	(reprfunc)delta_repr,				/* tp_repr */
 	&delta_as_number,				/* tp_as_number */
 	0,						/* tp_as_sequence */
@@ -2709,7 +2709,7 @@
 	0,						/* tp_print */
 	0,						/* tp_getattr */
 	0,						/* tp_setattr */
-	0,						/* tp_compare */
+	0,						/* tp_reserved */
 	(reprfunc)date_repr,				/* tp_repr */
 	&date_as_number,				/* tp_as_number */
 	0,						/* tp_as_sequence */
@@ -2963,7 +2963,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -3478,7 +3478,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)time_repr,			/* tp_repr */
 	&time_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -4606,7 +4606,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)datetime_repr,		/* tp_repr */
 	&datetime_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/itertoolsmodule.c
==============================================================================
--- python/branches/io-c/Modules/itertoolsmodule.c	(original)
+++ python/branches/io-c/Modules/itertoolsmodule.c	Sun Feb  8 21:39:02 2009
@@ -148,7 +148,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -279,7 +279,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -432,7 +432,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -588,7 +588,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -783,7 +783,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -925,7 +925,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1064,7 +1064,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1257,7 +1257,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1388,7 +1388,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1556,7 +1556,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1804,7 +1804,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -2027,7 +2027,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -2273,7 +2273,7 @@
 	0,						/* tp_print */
 	0,						/* tp_getattr */
 	0,						/* tp_setattr */
-	0,						/* tp_compare */
+	0,						/* tp_reserved */
 	0,						/* tp_repr */
 	0,						/* tp_as_number */
 	0,						/* tp_as_sequence */
@@ -2544,7 +2544,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -2700,7 +2700,7 @@
 	0,								/* tp_print */
 	0,								/* tp_getattr */
 	0,								/* tp_setattr */
-	0,								/* tp_compare */
+	0,								/* tp_reserved */
 	0,								/* tp_repr */
 	0,								/* tp_as_number */
 	0,								/* tp_as_sequence */
@@ -2843,7 +2843,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -2994,7 +2994,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	(reprfunc)count_repr,		/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -3129,7 +3129,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	(reprfunc)repeat_repr,		/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -3355,7 +3355,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -3400,16 +3400,23 @@
 repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times\n\
 \n\
 Iterators terminating on the shortest input sequence:\n\
-zip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\
+chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... \n\
+compress(data, selectors) --> (d[0] if s[0]), (d[1] if s[1]), ...\n\
+dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails\n\
+groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v)\n\
 filterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\
 islice(seq, [start,] stop [, step]) --> elements from\n\
        seq[start:stop:step]\n\
 starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...\n\
 tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n\n\
-chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... \n\
 takewhile(pred, seq) --> seq[0], seq[1], until pred fails\n\
-dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails\n\
-groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v)\n\
+zip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\
+\n\
+Combinatoric generators:\n\
+product(p, q, ... [repeat=1]) --> cartesian product\n\
+permutations(p[, r])\n\
+combinations(p[, r])\n\
+combinations_with_replacement(p[, r])\n\
 ");
 
 

Modified: python/branches/io-c/Modules/md5module.c
==============================================================================
--- python/branches/io-c/Modules/md5module.c	(original)
+++ python/branches/io-c/Modules/md5module.c	Sun Feb  8 21:39:02 2009
@@ -476,7 +476,7 @@
     0,			/*tp_print*/
     0,          	/*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     0,                  /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/mmapmodule.c
==============================================================================
--- python/branches/io-c/Modules/mmapmodule.c	(original)
+++ python/branches/io-c/Modules/mmapmodule.c	Sun Feb  8 21:39:02 2009
@@ -930,7 +930,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	&mmap_as_sequence,			/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/operator.c
==============================================================================
--- python/branches/io-c/Modules/operator.c	(original)
+++ python/branches/io-c/Modules/operator.c	Sun Feb  8 21:39:02 2009
@@ -334,7 +334,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -508,7 +508,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -639,7 +639,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Modules/ossaudiodev.c
==============================================================================
--- python/branches/io-c/Modules/ossaudiodev.c	(original)
+++ python/branches/io-c/Modules/ossaudiodev.c	Sun Feb  8 21:39:02 2009
@@ -849,7 +849,7 @@
     0,                          /*tp_print*/
     0,                          /*tp_getattr*/
     0,                          /*tp_setattr*/
-    0,                          /*tp_compare*/
+    0,                          /*tp_reserved*/
     0,                          /*tp_repr*/
     0,                          /*tp_as_number*/
     0,                          /*tp_as_sequence*/
@@ -881,7 +881,7 @@
     0,                              /*tp_print*/
     0,                              /*tp_getattr*/
     0,                              /*tp_setattr*/
-    0,                              /*tp_compare*/
+    0,                              /*tp_reserved*/
     0,                              /*tp_repr*/
     0,                              /*tp_as_number*/
     0,                              /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/parsermodule.c
==============================================================================
--- python/branches/io-c/Modules/parsermodule.c	(original)
+++ python/branches/io-c/Modules/parsermodule.c	Sun Feb  8 21:39:02 2009
@@ -169,7 +169,7 @@
 
 
 static void parser_free(PyST_Object *st);
-static int parser_compare(PyST_Object *left, PyST_Object *right);
+static PyObject* parser_richcompare(PyObject *left, PyObject *right, int op);
 static PyObject* parser_compilest(PyST_Object *, PyObject *, PyObject *);
 static PyObject* parser_isexpr(PyST_Object *, PyObject *, PyObject *);
 static PyObject* parser_issuite(PyST_Object *, PyObject *, PyObject *);
@@ -203,7 +203,7 @@
     0,                                  /* tp_print             */
     0,                                  /* tp_getattr           */
     0,                                  /* tp_setattr           */
-    (cmpfunc)parser_compare,            /* tp_compare           */
+    0,                                  /* tp_reserved          */
     0,                                  /* tp_repr              */
     0,                                  /* tp_as_number         */
     0,                                  /* tp_as_sequence       */
@@ -223,7 +223,7 @@
     "Intermediate representation of a Python parse tree.",
     0,                                  /* tp_traverse */
     0,                                  /* tp_clear */
-    0,                                  /* tp_richcompare */
+    parser_richcompare,                 /* tp_richcompare */
     0,                                  /* tp_weaklistoffset */
     0,                                  /* tp_iter */
     0,                                  /* tp_iternext */
@@ -231,6 +231,9 @@
 };  /* PyST_Type */
 
 
+/* PyST_Type isn't subclassable, so just check ob_type */
+#define PyST_Object_Check(v) ((v)->ob_type == &PyST_Type)
+
 static int
 parser_compare_nodes(node *left, node *right)
 {
@@ -260,26 +263,69 @@
     return (0);
 }
 
-
-/*  int parser_compare(PyST_Object* left, PyST_Object* right)
+/*  parser_richcompare(PyObject* left, PyObject* right, int op)
  *
  *  Comparison function used by the Python operators ==, !=, <, >, <=, >=
  *  This really just wraps a call to parser_compare_nodes() with some easy
  *  checks and protection code.
  *
  */
-static int
-parser_compare(PyST_Object *left, PyST_Object *right)
+
+#define TEST_COND(cond) ((cond) ? Py_True : Py_False)
+
+static PyObject *
+parser_richcompare(PyObject *left, PyObject *right, int op)
 {
-    if (left == right)
-        return (0);
+    int result;
+    PyObject *v;
 
-    if ((left == 0) || (right == 0))
-        return (-1);
+    /* neither argument should be NULL, unless something's gone wrong */
+    if (left == NULL || right == NULL) {
+        PyErr_BadInternalCall();
+        return NULL;
+    }
 
-    return (parser_compare_nodes(left->st_node, right->st_node));
-}
+    /* both arguments should be instances of PyST_Object */
+    if (!PyST_Object_Check(left) || !PyST_Object_Check(right)) {
+        v = Py_NotImplemented;
+        goto finished;
+    }
 
+    if (left == right)
+        /* if arguments are identical, they're equal */
+        result = 0;
+    else
+        result = parser_compare_nodes(((PyST_Object *)left)->st_node,
+                                      ((PyST_Object *)right)->st_node);
+
+    /* Convert return value to a Boolean */
+    switch (op) {
+    case Py_EQ:
+        v = TEST_COND(result == 0);
+        break;
+    case Py_NE:
+        v = TEST_COND(result != 0);
+        break;
+    case Py_LE:
+        v = TEST_COND(result <= 0);
+        break;
+    case Py_GE:
+        v = TEST_COND(result >= 0);
+        break;
+    case Py_LT:
+        v = TEST_COND(result < 0);
+        break;
+    case Py_GT:
+        v = TEST_COND(result > 0);
+        break;
+    default:
+        PyErr_BadArgument();
+        return NULL;
+    }
+  finished:
+    Py_INCREF(v);
+    return v;
+}
 
 /*  parser_newstobject(node* st)
  *

Modified: python/branches/io-c/Modules/pyexpat.c
==============================================================================
--- python/branches/io-c/Modules/pyexpat.c	(original)
+++ python/branches/io-c/Modules/pyexpat.c	Sun Feb  8 21:39:02 2009
@@ -1622,7 +1622,7 @@
 	(printfunc)0,		/*tp_print*/
 	0,			/*tp_getattr*/
 	(setattrfunc)xmlparse_setattr,	/*tp_setattr*/
-	(cmpfunc)0,		/*tp_compare*/
+	0,			/*tp_reserved*/
 	(reprfunc)0,		/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,		/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/selectmodule.c
==============================================================================
--- python/branches/io-c/Modules/selectmodule.c	(original)
+++ python/branches/io-c/Modules/selectmodule.c	Sun Feb  8 21:39:02 2009
@@ -639,7 +639,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,                      /*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -1097,7 +1097,7 @@
 	0,						/* tp_print */
 	0,						/* tp_getattr */
 	0,						/* tp_setattr */
-	0,						/* tp_compare */
+	0,						/* tp_reserved */
 	0,						/* tp_repr */
 	0,						/* tp_as_number */
 	0,						/* tp_as_sequence */
@@ -1310,7 +1310,7 @@
 	0,						/* tp_print */
 	0,						/* tp_getattr */
 	0,						/* tp_setattr */
-	0,						/* tp_compare */
+	0,						/* tp_reserved */
 	(reprfunc)kqueue_event_repr,			/* tp_repr */
 	0,						/* tp_as_number */
 	0,						/* tp_as_sequence */
@@ -1665,7 +1665,7 @@
 	0,						/* tp_print */
 	0,						/* tp_getattr */
 	0,						/* tp_setattr */
-	0,						/* tp_compare */
+	0,						/* tp_reserved */
 	0,						/* tp_repr */
 	0,						/* tp_as_number */
 	0,						/* tp_as_sequence */

Modified: python/branches/io-c/Modules/sha1module.c
==============================================================================
--- python/branches/io-c/Modules/sha1module.c	(original)
+++ python/branches/io-c/Modules/sha1module.c	Sun Feb  8 21:39:02 2009
@@ -452,7 +452,7 @@
     0,			/*tp_print*/
     0,          	/*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     0,                  /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/sha256module.c
==============================================================================
--- python/branches/io-c/Modules/sha256module.c	(original)
+++ python/branches/io-c/Modules/sha256module.c	Sun Feb  8 21:39:02 2009
@@ -545,7 +545,7 @@
     0,			/*tp_print*/
     0,          	/*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     0,                  /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/
@@ -579,7 +579,7 @@
     0,			/*tp_print*/
     0,          	/*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     0,                  /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/sha512module.c
==============================================================================
--- python/branches/io-c/Modules/sha512module.c	(original)
+++ python/branches/io-c/Modules/sha512module.c	Sun Feb  8 21:39:02 2009
@@ -611,7 +611,7 @@
     0,			/*tp_print*/
     0,          	/*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     0,                  /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/
@@ -645,7 +645,7 @@
     0,			/*tp_print*/
     0,          	/*tp_getattr*/
     0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
+    0,                  /*tp_reserved*/
     0,                  /*tp_repr*/
     0,                  /*tp_as_number*/
     0,                  /*tp_as_sequence*/

Modified: python/branches/io-c/Modules/socketmodule.c
==============================================================================
--- python/branches/io-c/Modules/socketmodule.c	(original)
+++ python/branches/io-c/Modules/socketmodule.c	Sun Feb  8 21:39:02 2009
@@ -1223,6 +1223,12 @@
                 PyMem_Free(host);
                 if (result < 0)
 			return 0;
+		if (port < 0 || port > 0xffff) {
+			PyErr_SetString(
+				PyExc_OverflowError,
+				"getsockaddrarg: port must be 0-65535.");
+			return 0;
+		}
 		addr->sin_family = AF_INET;
 		addr->sin_port = htons((short)port);
 		*len_ret = sizeof *addr;
@@ -1255,6 +1261,12 @@
                 PyMem_Free(host);
                 if (result < 0)
 			return 0;
+		if (port < 0 || port > 0xffff) {
+			PyErr_SetString(
+				PyExc_OverflowError,
+				"getsockaddrarg: port must be 0-65535.");
+			return 0;
+		}
 		addr->sin6_family = s->sock_family;
 		addr->sin6_port = htons((short)port);
 		addr->sin6_flowinfo = flowinfo;
@@ -1381,6 +1393,12 @@
 				  "Hardware address must be 8 bytes or less");
 		  return 0;
 		}
+		if (protoNumber < 0 || protoNumber > 0xffff) {
+			PyErr_SetString(
+				PyExc_OverflowError,
+				"getsockaddrarg: protoNumber must be 0-65535.");
+			return 0;
+		}
 		addr = (struct sockaddr_ll*)addr_ret;
 		addr->sll_family = AF_PACKET;
 		addr->sll_protocol = htons((short)protoNumber);
@@ -2860,7 +2878,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)sock_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -3271,13 +3289,19 @@
 static PyObject *
 socket_getservbyport(PyObject *self, PyObject *args)
 {
-	unsigned short port;
+	int port;
 	char *proto=NULL;
 	struct servent *sp;
-	if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
+	if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
+		return NULL;
+	if (port < 0 || port > 0xffff) {
+		PyErr_SetString(
+			PyExc_OverflowError,
+			"getservbyport: port must be 0-65535.");
 		return NULL;
+	}
 	Py_BEGIN_ALLOW_THREADS
-	sp = getservbyport(htons(port), proto);
+	sp = getservbyport(htons((short)port), proto);
 	Py_END_ALLOW_THREADS
 	if (sp == NULL) {
 		PyErr_SetString(socket_error, "port/proto not found");

Modified: python/branches/io-c/Modules/unicodedata.c
==============================================================================
--- python/branches/io-c/Modules/unicodedata.c	(original)
+++ python/branches/io-c/Modules/unicodedata.c	Sun Feb  8 21:39:02 2009
@@ -1144,7 +1144,7 @@
 	0,			/*tp_print*/
 	0,                      /*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/xxmodule.c
==============================================================================
--- python/branches/io-c/Modules/xxmodule.c	(original)
+++ python/branches/io-c/Modules/xxmodule.c	Sun Feb  8 21:39:02 2009
@@ -106,7 +106,7 @@
 	0,			/*tp_print*/
 	(getattrfunc)0,         /*tp_getattr*/
 	(setattrfunc)Xxo_setattr, /*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -224,7 +224,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -279,7 +279,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/

Modified: python/branches/io-c/Modules/xxsubtype.c
==============================================================================
--- python/branches/io-c/Modules/xxsubtype.c	(original)
+++ python/branches/io-c/Modules/xxsubtype.c	Sun Feb  8 21:39:02 2009
@@ -109,7 +109,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -200,7 +200,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/zipimport.c
==============================================================================
--- python/branches/io-c/Modules/zipimport.c	(original)
+++ python/branches/io-c/Modules/zipimport.c	Sun Feb  8 21:39:02 2009
@@ -363,7 +363,7 @@
     char *fullname, *modpath;
     int ispackage;
 
-    if (!PyArg_ParseTuple(args, "s:zipimporter._get_filename",
+    if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename",
                          &fullname))
         return NULL;
 
@@ -543,7 +543,7 @@
 
 
 PyDoc_STRVAR(doc_get_filename,
-"_get_filename(fullname) -> filename string.\n\
+"get_filename(fullname) -> filename string.\n\
 \n\
 Return the filename for the specified module.");
 
@@ -558,7 +558,7 @@
 	 doc_get_code},
 	{"get_source", zipimporter_get_source, METH_VARARGS,
 	 doc_get_source},
-	{"_get_filename", zipimporter_get_filename, METH_VARARGS,
+	{"get_filename", zipimporter_get_filename, METH_VARARGS,
 	 doc_get_filename},
 	{"is_package", zipimporter_is_package, METH_VARARGS,
 	 doc_is_package},
@@ -597,7 +597,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)zipimporter_repr,		/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Modules/zlibmodule.c
==============================================================================
--- python/branches/io-c/Modules/zlibmodule.c	(original)
+++ python/branches/io-c/Modules/zlibmodule.c	Sun Feb  8 21:39:02 2009
@@ -982,7 +982,7 @@
     0,                              /*tp_print*/
     0,                              /*tp_getattr*/
     0,                              /*tp_setattr*/
-    0,                              /*tp_compare*/
+    0,                              /*tp_reserved*/
     0,                              /*tp_repr*/
     0,                              /*tp_as_number*/
     0,                              /*tp_as_sequence*/
@@ -1013,7 +1013,7 @@
     0,                              /*tp_print*/
     0,                              /*tp_getattr*/
     0,                              /*tp_setattr*/
-    0,                              /*tp_compare*/
+    0,                              /*tp_reserved*/
     0,                              /*tp_repr*/
     0,                              /*tp_as_number*/
     0,                              /*tp_as_sequence*/

Modified: python/branches/io-c/Objects/abstract.c
==============================================================================
--- python/branches/io-c/Objects/abstract.c	(original)
+++ python/branches/io-c/Objects/abstract.c	Sun Feb  8 21:39:02 2009
@@ -27,22 +27,6 @@
 
 /* Operations on any object */
 
-int
-PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
-{
-	int r;
-
-	if (o1 == NULL || o2 == NULL) {
-		null_error();
-		return -1;
-	}
-	r = PyObject_Compare(o1, o2);
-	if (PyErr_Occurred())
-		return -1;
-	*result = r;
-	return 0;
-}
-
 PyObject *
 PyObject_Type(PyObject *o)
 {
@@ -83,8 +67,8 @@
 
 /* The length hint function returns a non-negative value from o.__len__()
    or o.__length_hint__().  If those methods aren't found or return a negative
-   value, then the defaultvalue is returned.  This function never fails. 
-   Accordingly, it will mask exceptions raised in either method.
+   value, then the defaultvalue is returned.  If one of the calls fails,
+   this function returns -1.
 */
 
 Py_ssize_t
@@ -98,29 +82,32 @@
 	rv = PyObject_Size(o);
 	if (rv >= 0)
 		return rv;
-	if (PyErr_Occurred())
+	if (PyErr_Occurred()) {
+		if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
+			!PyErr_ExceptionMatches(PyExc_AttributeError))
+				return -1;
 		PyErr_Clear();
+	}
 
 	/* cache a hashed version of the attribute string */
 	if (hintstrobj == NULL) {
 		hintstrobj = PyUnicode_InternFromString("__length_hint__");
 		if (hintstrobj == NULL)
-			goto defaultcase;
+			return -1;
 	}
 
 	/* try o.__length_hint__() */
 	ro = PyObject_CallMethodObjArgs(o, hintstrobj, NULL);
-	if (ro == NULL)
-		goto defaultcase;
-	rv = PyLong_AsSsize_t(ro);
-	Py_DECREF(ro);
-	if (rv >= 0)
-		return rv;
-
-defaultcase:
-	if (PyErr_Occurred())
+	if (ro == NULL) {
+		if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
+			!PyErr_ExceptionMatches(PyExc_AttributeError))
+				return -1;
 		PyErr_Clear();
-	return defaultvalue;
+		return defaultvalue;
+	}
+	rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
+	Py_DECREF(ro);
+	return rv;
 }
 
 PyObject *
@@ -1758,7 +1745,7 @@
 {
 	PyObject *it;  /* iter(v) */
 	Py_ssize_t n;	      /* guess for result tuple size */
-	PyObject *result;
+	PyObject *result = NULL;
 	Py_ssize_t j;
 
 	if (v == NULL)
@@ -1783,6 +1770,8 @@
 
 	/* Guess result size and allocate space. */
 	n = _PyObject_LengthHint(v, 10);
+	if (n == -1)
+		goto Fail;
 	result = PyTuple_New(n);
 	if (result == NULL)
 		goto Fail;

Modified: python/branches/io-c/Objects/boolobject.c
==============================================================================
--- python/branches/io-c/Objects/boolobject.c	(original)
+++ python/branches/io-c/Objects/boolobject.c	Sun Feb  8 21:39:02 2009
@@ -139,7 +139,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	bool_repr,				/* tp_repr */
 	&bool_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/bytearrayobject.c
==============================================================================
--- python/branches/io-c/Objects/bytearrayobject.c	(original)
+++ python/branches/io-c/Objects/bytearrayobject.c	Sun Feb  8 21:39:02 2009
@@ -2616,6 +2616,10 @@
 
     /* Try to determine the length of the argument. 32 is abitrary. */
     buf_size = _PyObject_LengthHint(arg, 32);
+	if (buf_size == -1) {
+		Py_DECREF(it);
+		return NULL;
+	}
 
     bytes_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
     if (bytes_obj == NULL)
@@ -3182,7 +3186,7 @@
     0,                                  /* tp_print */
     0,                                  /* tp_getattr */
     0,                                  /* tp_setattr */
-    0,                                  /* tp_compare */
+    0,                                  /* tp_reserved */
     (reprfunc)bytes_repr,               /* tp_repr */
     0,                                  /* tp_as_number */
     &bytes_as_sequence,                 /* tp_as_sequence */
@@ -3291,7 +3295,7 @@
     0,                                 /* tp_print */
     0,                                 /* tp_getattr */
     0,                                 /* tp_setattr */
-    0,                                 /* tp_compare */
+    0,                                 /* tp_reserved */
     0,                                 /* tp_repr */
     0,                                 /* tp_as_number */
     0,                                 /* tp_as_sequence */

Modified: python/branches/io-c/Objects/bytesobject.c
==============================================================================
--- python/branches/io-c/Objects/bytesobject.c	(original)
+++ python/branches/io-c/Objects/bytesobject.c	Sun Feb  8 21:39:02 2009
@@ -3089,7 +3089,7 @@
 	0,			 		/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)string_repr, 			/* tp_repr */
 	0,					/* tp_as_number */
 	&string_as_sequence,			/* tp_as_sequence */
@@ -3423,7 +3423,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/cellobject.c
==============================================================================
--- python/branches/io-c/Objects/cellobject.c	(original)
+++ python/branches/io-c/Objects/cellobject.c	Sun Feb  8 21:39:02 2009
@@ -51,16 +51,56 @@
 	PyObject_GC_Del(op);
 }
 
-static int
-cell_compare(PyCellObject *a, PyCellObject *b)
+#define TEST_COND(cond) ((cond) ? Py_True : Py_False)
+
+static PyObject *
+cell_richcompare(PyObject *a, PyObject *b, int op)
 {
-	if (a->ob_ref == NULL) {
-		if (b->ob_ref == NULL)
-			return 0;
-		return -1;
-	} else if (b->ob_ref == NULL)
-		return 1;
-	return PyObject_Compare(a->ob_ref, b->ob_ref);
+	int result;
+	PyObject *v;
+
+	/* neither argument should be NULL, unless something's gone wrong */
+	assert(a != NULL && b != NULL);
+
+	/* both arguments should be instances of PyCellObject */
+	if (!PyCell_Check(a) || !PyCell_Check(b)) {
+		v = Py_NotImplemented;
+		Py_INCREF(v);
+		return v;
+	}
+
+	/* compare cells by contents; empty cells come before anything else */
+	a = ((PyCellObject *)a)->ob_ref;
+	b = ((PyCellObject *)b)->ob_ref;
+	if (a != NULL && b != NULL)
+		return PyObject_RichCompare(a, b, op);
+
+	result = (b == NULL) - (a == NULL);
+	switch (op) {
+	case Py_EQ:
+		v = TEST_COND(result == 0);
+		break;
+	case Py_NE:
+		v = TEST_COND(result != 0);
+		break;
+	case Py_LE:
+		v = TEST_COND(result <= 0);
+		break;
+	case Py_GE:
+		v = TEST_COND(result >= 0);
+		break;
+	case Py_LT:
+		v = TEST_COND(result < 0);
+		break;
+	case Py_GT:
+		v = TEST_COND(result > 0);
+		break;
+	default:
+		PyErr_BadArgument();
+		return NULL;
+	}
+	Py_INCREF(v);
+	return v;
 }
 
 static PyObject *
@@ -114,7 +154,7 @@
 	0,                                      /* tp_print */
 	0,	                                /* tp_getattr */
 	0,					/* tp_setattr */
-	(cmpfunc)cell_compare,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)cell_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,			                /* tp_as_sequence */
@@ -129,7 +169,7 @@
  	0,					/* tp_doc */
  	(traverseproc)cell_traverse,		/* tp_traverse */
  	(inquiry)cell_clear,			/* tp_clear */
-	0,					/* tp_richcompare */
+	cell_richcompare,			/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
 	0, 					/* tp_iter */
 	0,					/* tp_iternext */

Modified: python/branches/io-c/Objects/classobject.c
==============================================================================
--- python/branches/io-c/Objects/classobject.c	(original)
+++ python/branches/io-c/Objects/classobject.c	Sun Feb  8 21:39:02 2009
@@ -348,7 +348,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)method_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -614,7 +614,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)instancemethod_repr,		/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/cobject.c
==============================================================================
--- python/branches/io-c/Objects/cobject.c	(original)
+++ python/branches/io-c/Objects/cobject.c	Sun Feb  8 21:39:02 2009
@@ -137,7 +137,7 @@
     0,				/*tp_print*/
     0,				/*tp_getattr*/
     0,				/*tp_setattr*/
-    0,				/*tp_compare*/
+    0,				/*tp_reserved*/
     0,				/*tp_repr*/
     0,				/*tp_as_number*/
     0,				/*tp_as_sequence*/

Modified: python/branches/io-c/Objects/codeobject.c
==============================================================================
--- python/branches/io-c/Objects/codeobject.c	(original)
+++ python/branches/io-c/Objects/codeobject.c	Sun Feb  8 21:39:02 2009
@@ -399,7 +399,7 @@
 	0,				/* tp_print */
 	0, 				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,		 		/* tp_compare */
+	0,		 		/* tp_reserved */
 	(reprfunc)code_repr,		/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Objects/complexobject.c
==============================================================================
--- python/branches/io-c/Objects/complexobject.c	(original)
+++ python/branches/io-c/Objects/complexobject.c	Sun Feb  8 21:39:02 2009
@@ -1087,7 +1087,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)complex_repr,			/* tp_repr */
 	&complex_as_number,    			/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/descrobject.c
==============================================================================
--- python/branches/io-c/Objects/descrobject.c	(original)
+++ python/branches/io-c/Objects/descrobject.c	Sun Feb  8 21:39:02 2009
@@ -392,7 +392,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)method_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -430,7 +430,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)method_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -467,7 +467,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)member_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -504,7 +504,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)getset_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -541,7 +541,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)wrapperdescr_repr,		/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -774,12 +774,6 @@
 	return 0;
 }
 
-static int
-proxy_compare(proxyobject *v, PyObject *w)
-{
-	return PyObject_Compare(v->dict, w);
-}
-
 static PyObject *
 proxy_richcompare(proxyobject *v, PyObject *w, int op)
 {
@@ -796,7 +790,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	(cmpfunc)proxy_compare,			/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	&proxy_as_sequence,			/* tp_as_sequence */
@@ -844,12 +838,17 @@
 /* This has no reason to be in this file except that adding new files is a
    bit of a pain */
 
+/* forward */
+static PyTypeObject wrappertype;
+
 typedef struct {
 	PyObject_HEAD
 	PyWrapperDescrObject *descr;
 	PyObject *self;
 } wrapperobject;
 
+#define Wrapper_Check(v) (Py_TYPE(v) == &wrappertype)
+
 static void
 wrapper_dealloc(wrapperobject *wp)
 {
@@ -861,13 +860,60 @@
 	Py_TRASHCAN_SAFE_END(wp)
 }
 
-static int
-wrapper_compare(wrapperobject *a, wrapperobject *b)
+#define TEST_COND(cond) ((cond) ? Py_True : Py_False)
+
+static PyObject *
+wrapper_richcompare(PyObject *a, PyObject *b, int op)
 {
-	if (a->descr == b->descr)
-		return PyObject_Compare(a->self, b->self);
-	else
-		return (a->descr < b->descr) ? -1 : 1;
+	int result;
+	PyObject *v;
+	PyWrapperDescrObject *a_descr, *b_descr;
+
+	assert(a != NULL && b != NULL);
+
+	/* both arguments should be wrapperobjects */
+	if (!Wrapper_Check(a) || !Wrapper_Check(b)) {
+		v = Py_NotImplemented;
+		Py_INCREF(v);
+		return v;
+	}
+
+	/* compare by descriptor address; if the descriptors are the same,
+	   compare by the objects they're bound to */
+	a_descr = ((wrapperobject *)a)->descr;
+	b_descr = ((wrapperobject *)b)->descr;
+	if (a_descr == b_descr) {
+		a = ((wrapperobject *)a)->self;
+		b = ((wrapperobject *)b)->self;
+		return PyObject_RichCompare(a, b, op);
+	}
+
+	result = a_descr - b_descr;
+	switch (op) {
+	case Py_EQ:
+		v = TEST_COND(result == 0);
+		break;
+	case Py_NE:
+		v = TEST_COND(result != 0);
+		break;
+	case Py_LE:
+		v = TEST_COND(result <= 0);
+		break;
+	case Py_GE:
+		v = TEST_COND(result >= 0);
+		break;
+	case Py_LT:
+		v = TEST_COND(result < 0);
+		break;
+	case Py_GT:
+		v = TEST_COND(result > 0);
+		break;
+	default:
+		PyErr_BadArgument();
+		return NULL;
+	}
+	Py_INCREF(v);
+	return v;
 }
 
 static long
@@ -977,7 +1023,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	(cmpfunc)wrapper_compare,		/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)wrapper_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -992,7 +1038,7 @@
  	0,					/* tp_doc */
 	wrapper_traverse,			/* tp_traverse */
  	0,					/* tp_clear */
-	0,					/* tp_richcompare */
+	wrapper_richcompare,			/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
 	0,					/* tp_iter */
 	0,					/* tp_iternext */
@@ -1309,7 +1355,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/dictobject.c
==============================================================================
--- python/branches/io-c/Objects/dictobject.c	(original)
+++ python/branches/io-c/Objects/dictobject.c	Sun Feb  8 21:39:02 2009
@@ -2032,7 +2032,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)dict_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	&dict_as_sequence,			/* tp_as_sequence */
@@ -2226,7 +2226,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -2298,7 +2298,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -2384,7 +2384,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -2699,7 +2699,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	&dictviews_as_number,			/* tp_as_number */
 	&dictkeys_as_sequence,			/* tp_as_sequence */
@@ -2783,7 +2783,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	&dictviews_as_number,			/* tp_as_number */
 	&dictitems_as_sequence,			/* tp_as_sequence */
@@ -2848,7 +2848,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	&dictvalues_as_sequence,		/* tp_as_sequence */

Modified: python/branches/io-c/Objects/enumobject.c
==============================================================================
--- python/branches/io-c/Objects/enumobject.c	(original)
+++ python/branches/io-c/Objects/enumobject.c	Sun Feb  8 21:39:02 2009
@@ -176,7 +176,7 @@
 	0,                              /* tp_print */
 	0,                              /* tp_getattr */
 	0,                              /* tp_setattr */
-	0,                              /* tp_compare */
+	0,                              /* tp_reserved */
 	0,                              /* tp_repr */
 	0,                              /* tp_as_number */
 	0,                              /* tp_as_sequence */
@@ -326,7 +326,7 @@
 	0,                              /* tp_print */
 	0,                              /* tp_getattr */
 	0,                              /* tp_setattr */
-	0,                              /* tp_compare */
+	0,                              /* tp_reserved */
 	0,                              /* tp_repr */
 	0,                              /* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/Objects/exceptions.c
==============================================================================
--- python/branches/io-c/Objects/exceptions.c	(original)
+++ python/branches/io-c/Objects/exceptions.c	Sun Feb  8 21:39:02 2009
@@ -320,7 +320,7 @@
     0,                          /*tp_print*/
     0,                          /*tp_getattr*/
     0,                          /*tp_setattr*/
-    0,                          /* tp_compare; */
+    0,                          /* tp_reserved; */
     (reprfunc)BaseException_repr, /*tp_repr*/
     0,                          /*tp_as_number*/
     0,                          /*tp_as_sequence*/

Modified: python/branches/io-c/Objects/fileobject.c
==============================================================================
--- python/branches/io-c/Objects/fileobject.c	(original)
+++ python/branches/io-c/Objects/fileobject.c	Sun Feb  8 21:39:02 2009
@@ -490,7 +490,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)stdprinter_repr,		/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/floatobject.c
==============================================================================
--- python/branches/io-c/Objects/floatobject.c	(original)
+++ python/branches/io-c/Objects/floatobject.c	Sun Feb  8 21:39:02 2009
@@ -1819,7 +1819,7 @@
 	0,			 		/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,			 		/* tp_compare */
+	0,			 		/* tp_reserved */
 	(reprfunc)float_repr,			/* tp_repr */
 	&float_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/frameobject.c
==============================================================================
--- python/branches/io-c/Objects/frameobject.c	(original)
+++ python/branches/io-c/Objects/frameobject.c	Sun Feb  8 21:39:02 2009
@@ -546,7 +546,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/funcobject.c
==============================================================================
--- python/branches/io-c/Objects/funcobject.c	(original)
+++ python/branches/io-c/Objects/funcobject.c	Sun Feb  8 21:39:02 2009
@@ -659,7 +659,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)func_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -805,7 +805,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -952,7 +952,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/genobject.c
==============================================================================
--- python/branches/io-c/Objects/genobject.c	(original)
+++ python/branches/io-c/Objects/genobject.c	Sun Feb  8 21:39:02 2009
@@ -333,7 +333,7 @@
 	0,					/* tp_print */
 	0, 					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)gen_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/iterobject.c
==============================================================================
--- python/branches/io-c/Objects/iterobject.c	(original)
+++ python/branches/io-c/Objects/iterobject.c	Sun Feb  8 21:39:02 2009
@@ -103,7 +103,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -207,7 +207,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/listobject.c
==============================================================================
--- python/branches/io-c/Objects/listobject.c	(original)
+++ python/branches/io-c/Objects/listobject.c	Sun Feb  8 21:39:02 2009
@@ -802,6 +802,10 @@
 
 	/* Guess a result list size. */
 	n = _PyObject_LengthHint(b, 8);
+	if (n == -1) {
+		Py_DECREF(it);
+		return NULL;
+	}
 	m = Py_SIZE(self);
 	mn = m + n;
 	if (mn >= m) {
@@ -1784,7 +1788,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -2565,7 +2569,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)list_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	&list_as_sequence,			/* tp_as_sequence */
@@ -2631,7 +2635,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -2753,7 +2757,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/longobject.c
==============================================================================
--- python/branches/io-c/Objects/longobject.c	(original)
+++ python/branches/io-c/Objects/longobject.c	Sun Feb  8 21:39:02 2009
@@ -3643,32 +3643,140 @@
 				      PyUnicode_GET_SIZE(format_spec));
 }
 
-
 static PyObject *
 long_round(PyObject *self, PyObject *args)
 {
-#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
-	int ndigits = UNDEF_NDIGITS;
-	double x;
-	PyObject *res;
-	
-	if (!PyArg_ParseTuple(args, "|i", &ndigits))
-		return NULL;
+	PyObject *o_ndigits=NULL, *temp;
+	PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
+	int errcode;
+	digit q_mod_4;
+
+	/* Notes on the algorithm: to round to the nearest 10**n (n positive),
+	   the straightforward method is:
+
+	      (1) divide by 10**n
+	      (2) round to nearest integer (round to even in case of tie)
+	      (3) multiply result by 10**n.
+
+	   But the rounding step involves examining the fractional part of the
+	   quotient to see whether it's greater than 0.5 or not.  Since we
+	   want to do the whole calculation in integer arithmetic, it's
+	   simpler to do:
+
+	      (1) divide by (10**n)/2
+	      (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
+	      (3) multiply result by (10**n)/2.
+
+	   Then all we need to know about the fractional part of the quotient
+	   arising in step (2) is whether it's zero or not.
+
+	   Doing both a multiplication and division is wasteful, and is easily
+	   avoided if we just figure out how much to adjust the original input
+	   by to do the rounding.
+
+	   Here's the whole algorithm expressed in Python.
+
+	    def round(self, ndigits = None):
+	        """round(int, int) -> int"""
+	        if ndigits is None or ndigits >= 0:
+	            return self
+	        pow = 10**-ndigits >> 1
+	        q, r = divmod(self, pow)
+	        self -= r
+	        if (q & 1 != 0):
+	            if (q & 2 == r == 0):
+	                self -= pow
+	            else:
+	                self += pow
+	        return self
 
-	if (ndigits == UNDEF_NDIGITS)
+	*/
+	if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
+		return NULL;
+	if (o_ndigits == NULL)
 		return long_long(self);
 
-	/* If called with two args, defer to float.__round__(). */
-	x = PyLong_AsDouble(self);
-	if (x == -1.0 && PyErr_Occurred())
+	ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
+	if (ndigits == NULL)
 		return NULL;
-	self = PyFloat_FromDouble(x);
-	if (self == NULL)
-		return NULL;
-	res = PyObject_CallMethod(self, "__round__", "i", ndigits);
+
+	if (Py_SIZE(ndigits) >= 0) {
+		Py_DECREF(ndigits);
+		return long_long(self);
+	}
+
+	Py_INCREF(self); /* to keep refcounting simple */
+	/* we now own references to self, ndigits */
+
+	/* pow = 10 ** -ndigits >> 1 */
+	pow = (PyLongObject *)PyLong_FromLong(10L);
+	if (pow == NULL)
+		goto error;
+	temp = long_neg(ndigits);
+	Py_DECREF(ndigits);
+	ndigits = (PyLongObject *)temp;
+	if (ndigits == NULL)
+		goto error;
+	temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
+	Py_DECREF(pow);
+	pow = (PyLongObject *)temp;
+	if (pow == NULL)
+		goto error;
+	assert(PyLong_Check(pow)); /* check long_pow returned a long */
+	one = (PyLongObject *)PyLong_FromLong(1L);
+	if (one == NULL)
+		goto error;
+	temp = long_rshift(pow, one);
+	Py_DECREF(one);
+	Py_DECREF(pow);
+	pow = (PyLongObject *)temp;
+	if (pow == NULL)
+		goto error;
+
+	/* q, r = divmod(self, pow) */
+	errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
+	if (errcode == -1)
+		goto error;
+
+	/* self -= r */
+	temp = long_sub((PyLongObject *)self, r);
 	Py_DECREF(self);
-	return res;
-#undef UNDEF_NDIGITS
+	self = temp;
+	if (self == NULL)
+		goto error;
+
+	/* get value of quotient modulo 4 */
+	if (Py_SIZE(q) == 0)
+		q_mod_4 = 0;
+	else if (Py_SIZE(q) > 0)
+		q_mod_4 = q->ob_digit[0] & 3;
+	else
+		q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
+
+	if ((q_mod_4 & 1) == 1) {
+		/* q is odd; round self up or down by adding or subtracting pow */
+		if (q_mod_4 == 1 && Py_SIZE(r) == 0)
+			temp = (PyObject *)long_sub((PyLongObject *)self, pow);
+		else
+			temp = (PyObject *)long_add((PyLongObject *)self, pow);
+		Py_DECREF(self);
+		self = temp;
+		if (self == NULL)
+			goto error;
+	}
+	Py_DECREF(q);
+	Py_DECREF(r);
+	Py_DECREF(pow);
+	Py_DECREF(ndigits);
+	return self;
+
+  error:
+	Py_XDECREF(q);
+	Py_XDECREF(r);
+	Py_XDECREF(pow);
+	Py_XDECREF(self);
+	Py_XDECREF(ndigits);
+	return NULL;
 }
 
 static PyObject *
@@ -3773,8 +3881,8 @@
 	{"__ceil__",	(PyCFunction)long_long,	METH_NOARGS,
          "Ceiling of an Integral returns itself."},
 	{"__round__",	(PyCFunction)long_round, METH_VARARGS,
-         "Rounding an Integral returns itself.\n"
-	 "Rounding with an ndigits arguments defers to float.__round__."},
+	 "Rounding an Integral returns itself.\n"
+	 "Rounding with an ndigits argument also returns an integer."},
 	{"__getnewargs__",	(PyCFunction)long_getnewargs,	METH_NOARGS},
         {"__format__", (PyCFunction)long__format__, METH_VARARGS},
 	{"__sizeof__",	(PyCFunction)long_sizeof, METH_NOARGS,
@@ -3859,7 +3967,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	long_repr,				/* tp_repr */
 	&long_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/memoryobject.c
==============================================================================
--- python/branches/io-c/Objects/memoryobject.c	(original)
+++ python/branches/io-c/Objects/memoryobject.c	Sun Feb  8 21:39:02 2009
@@ -498,22 +498,6 @@
     return PyUnicode_FromFormat("<memory at %p>", self);
 }
 
-
-static PyObject *
-memory_str(PyMemoryViewObject *self)
-{
-    Py_buffer view;
-    PyObject *res;
-
-    if (PyObject_GetBuffer((PyObject *)self, &view, PyBUF_FULL) < 0)
-        return NULL;
-
-    res = PyBytes_FromStringAndSize(NULL, view.len);
-    PyBuffer_ToContiguous(PyBytes_AS_STRING(res), &view, view.len, 'C');
-    PyBuffer_Release(&view);
-    return res;
-}
-
 /* Sequence methods */
 static Py_ssize_t
 memory_length(PyMemoryViewObject *self)
@@ -805,14 +789,14 @@
     0,                                        /* tp_print */
     0,                                        /* tp_getattr */
     0,                                        /* tp_setattr */
-    0,                                        /* tp_compare */
+    0,                                        /* tp_reserved */
     (reprfunc)memory_repr,                    /* tp_repr */
     0,                                        /* tp_as_number */
     0,                                        /* tp_as_sequence */
     &memory_as_mapping,                       /* tp_as_mapping */
     0,                                        /* tp_hash */
     0,                                        /* tp_call */
-    (reprfunc)memory_str,                     /* tp_str */
+    0,                                        /* tp_str */
     PyObject_GenericGetAttr,                  /* tp_getattro */
     0,                                        /* tp_setattro */
     &memory_as_buffer,                        /* tp_as_buffer */

Modified: python/branches/io-c/Objects/methodobject.c
==============================================================================
--- python/branches/io-c/Objects/methodobject.c	(original)
+++ python/branches/io-c/Objects/methodobject.c	Sun Feb  8 21:39:02 2009
@@ -254,7 +254,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)meth_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/moduleobject.c
==============================================================================
--- python/branches/io-c/Objects/moduleobject.c	(original)
+++ python/branches/io-c/Objects/moduleobject.c	Sun Feb  8 21:39:02 2009
@@ -379,7 +379,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)module_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/object.c
==============================================================================
--- python/branches/io-c/Objects/object.c	(original)
+++ python/branches/io-c/Objects/object.c	Sun Feb  8 21:39:02 2009
@@ -500,35 +500,19 @@
 	return PyBytes_FromObject(v);
 }
 
-/* The new comparison philosophy is: we completely separate three-way
-   comparison from rich comparison.  That is, PyObject_Compare() and
-   PyObject_Cmp() *just* use the tp_compare slot.  And PyObject_RichCompare()
-   and PyObject_RichCompareBool() *just* use the tp_richcompare slot.
+/* For Python 3.0.1 and later, the old three-way comparison has been
+   completely removed in favour of rich comparisons.  PyObject_Compare() and
+   PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
+   The old tp_compare slot has been renamed to tp_reserved, and should no
+   longer be used.  Use tp_richcompare instead.
 
    See (*) below for practical amendments.
 
-   IOW, only cmp() uses tp_compare; the comparison operators (==, !=, <=, <,
-   >=, >) only use tp_richcompare.  Note that list.sort() only uses <.
+   tp_richcompare gets called with a first argument of the appropriate type
+   and a second object of an arbitrary type.  We never do any kind of
+   coercion.
 
-   (And yes, eventually we'll rip out cmp() and tp_compare.)
-
-   The calling conventions are different: tp_compare only gets called with two
-   objects of the appropriate type; tp_richcompare gets called with a first
-   argument of the appropriate type and a second object of an arbitrary type.
-   We never do any kind of coercion.
-
-   The return conventions are also different.
-
-   The tp_compare slot should return a C int, as follows:
-
-     -1 if a < b or if an exception occurred
-      0 if a == b
-     +1 if a > b
-
-   No other return values are allowed.  PyObject_Compare() has the same
-   calling convention.
-
-  The tp_richcompare slot should return an object, as follows:
+   The tp_richcompare slot should return an object, as follows:
 
     NULL if an exception occurred
     NotImplemented if the requested comparison is not implemented
@@ -544,73 +528,8 @@
     comparing the object pointer (i.e. falling back to the base object
     implementation).
 
-  - If three-way comparison is not implemented, it falls back on rich
-    comparison (but not the other way around!).
-
 */
 
-/* Forward */
-static PyObject *do_richcompare(PyObject *v, PyObject *w, int op);
-
-/* Perform a three-way comparison, raising TypeError if three-way comparison
-   is not supported.  */
-static int
-do_compare(PyObject *v, PyObject *w)
-{
-	cmpfunc f;
-	int ok;
-
-	if (v->ob_type == w->ob_type &&
-	    (f = v->ob_type->tp_compare) != NULL) {
-		return (*f)(v, w);
-	}
-
-	/* Now try three-way compare before giving up.  This is intentionally
-	   elaborate; if you have a it will raise TypeError if it detects two
-	   objects that aren't ordered with respect to each other. */
-	ok = PyObject_RichCompareBool(v, w, Py_LT);
-	if (ok < 0)
-		return -1; /* Error */
-	if (ok)
-		return -1; /* Less than */
-	ok = PyObject_RichCompareBool(v, w, Py_GT);
-	if (ok < 0)
-		return -1; /* Error */
-	if (ok)
-		return 1; /* Greater than */
-	ok = PyObject_RichCompareBool(v, w, Py_EQ);
-	if (ok < 0)
-		return -1; /* Error */
-	if (ok)
-		return 0; /* Equal */
-
-	/* Give up */
-	PyErr_Format(PyExc_TypeError,
-		     "unorderable types: '%.100s' != '%.100s'",
-		     v->ob_type->tp_name,
-		     w->ob_type->tp_name);
-	return -1;
-}
-
-/* Perform a three-way comparison.  This wraps do_compare() with a check for
-   NULL arguments and a recursion check. */
-int
-PyObject_Compare(PyObject *v, PyObject *w)
-{
-	int res;
-
-	if (v == NULL || w == NULL) {
-		if (!PyErr_Occurred())
-			PyErr_BadInternalCall();
-		return -1;
-	}
-	if (Py_EnterRecursiveCall(" in cmp"))
-		return -1;
-	res = do_compare(v, w);
-	Py_LeaveRecursiveCall();
-	return res < 0 ? -1 : res;
-}
-
 /* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
 int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
 
@@ -715,44 +634,6 @@
 	return ok;
 }
 
-/* Turn the result of a three-way comparison into the result expected by a
-   rich comparison. */
-PyObject *
-Py_CmpToRich(int op, int cmp)
-{
-	PyObject *res;
-	int ok;
-
-	if (PyErr_Occurred())
-		return NULL;
-	switch (op) {
-	case Py_LT:
-		ok = cmp <  0;
-		break;
-	case Py_LE:
-		ok = cmp <= 0;
-		break;
-	case Py_EQ:
-		ok = cmp == 0;
-		break;
-	case Py_NE:
-		ok = cmp != 0;
-		break;
-	case Py_GT:
-		ok = cmp >  0;
-		break;
-	case Py_GE:
-		ok = cmp >= 0;
-		break;
-	default:
-		PyErr_BadArgument();
-		return NULL;
-	}
-	res = ok ? Py_True : Py_False;
-	Py_INCREF(res);
-	return res;
-}
-
 /* Set of hash utility functions to help maintaining the invariant that
 	if a==b then hash(a)==hash(b)
 
@@ -774,7 +655,7 @@
 	fractpart = modf(v, &intpart);
 	if (fractpart == 0.0) {
 		/* This must return the same hash as an equal int or long. */
-		if (intpart > LONG_MAX || -intpart > LONG_MAX) {
+		if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
 			/* Convert to long and use its hash. */
 			PyObject *plong;	/* converted to Python long */
 			if (Py_IS_INFINITY(intpart))
@@ -1552,7 +1433,7 @@
 	0,		/*tp_print*/
 	0,		/*tp_getattr*/
 	0,		/*tp_setattr*/
-	0,		/*tp_compare*/
+	0,		/*tp_reserved*/
 	none_repr,	/*tp_repr*/
 	0,		/*tp_as_number*/
 	0,		/*tp_as_sequence*/
@@ -1583,7 +1464,7 @@
 	0,		/*tp_print*/
 	0,		/*tp_getattr*/
 	0,		/*tp_setattr*/
-	0,		/*tp_compare*/
+	0,		/*tp_reserved*/
 	NotImplemented_repr, /*tp_repr*/
 	0,		/*tp_as_number*/
 	0,		/*tp_as_sequence*/

Modified: python/branches/io-c/Objects/rangeobject.c
==============================================================================
--- python/branches/io-c/Objects/rangeobject.c	(original)
+++ python/branches/io-c/Objects/rangeobject.c	Sun Feb  8 21:39:02 2009
@@ -123,7 +123,7 @@
     Algorithm is equal to that of get_len_of_range(), but it operates
     on PyObjects (which are assumed to be PyLong or PyInt objects).
     ---------------------------------------------------------------*/
-    int cmp_result, cmp_call;
+    int cmp_result;
     PyObject *lo, *hi;
     PyObject *step = NULL;
     PyObject *diff = NULL;
@@ -134,13 +134,12 @@
     PyObject *zero = PyLong_FromLong(0);
     if (zero == NULL)
         return NULL;
-    cmp_call = PyObject_Cmp(r->step, zero, &cmp_result);
+    cmp_result = PyObject_RichCompareBool(r->step, zero, Py_GT);
     Py_DECREF(zero);
-    if (cmp_call == -1)
+    if (cmp_result == -1)
         return NULL;
 
-    assert(cmp_result != 0);
-    if (cmp_result > 0) {
+    if (cmp_result == 1) {
         lo = r->start;
         hi = r->stop;
         step = r->step;
@@ -154,7 +153,7 @@
     }
 
     /* if (lo >= hi), return length of 0. */
-    if (PyObject_Compare(lo, hi) >= 0) {
+    if (PyObject_RichCompareBool(lo, hi, Py_GE) == 1) {
         Py_XDECREF(step);
         return PyLong_FromLong(0);
     }
@@ -290,7 +289,7 @@
 	0,			/* tp_print */
 	0,			/* tp_getattr */
 	0,			/* tp_setattr */
-	0,			/* tp_compare */
+	0,			/* tp_reserved */
 	(reprfunc)range_repr,	/* tp_repr */
 	0,			/* tp_as_number */
 	&range_as_sequence,	/* tp_as_sequence */
@@ -386,7 +385,7 @@
 	0,                                      /* tp_print */
 	0,                                      /* tp_getattr */
 	0,                                      /* tp_setattr */
-	0,                                      /* tp_compare */
+	0,                                      /* tp_reserved */
 	0,                                      /* tp_repr */
 	0,                                      /* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -538,7 +537,7 @@
 	0,                                      /* tp_print */
 	0,                                      /* tp_getattr */
 	0,                                      /* tp_setattr */
-	0,                                      /* tp_compare */
+	0,                                      /* tp_reserved */
 	0,                                      /* tp_repr */
 	0,                                      /* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/setobject.c
==============================================================================
--- python/branches/io-c/Objects/setobject.c	(original)
+++ python/branches/io-c/Objects/setobject.c	Sun Feb  8 21:39:02 2009
@@ -876,7 +876,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -1824,13 +1824,6 @@
 	return Py_NotImplemented;
 }
 
-static int
-set_nocmp(PyObject *self, PyObject *other)
-{
-	PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
-	return -1;
-}
-
 static PyObject *
 set_add(PySetObject *so, PyObject *key)
 {
@@ -2111,7 +2104,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	set_nocmp,			/* tp_compare */
+	0,				/* tp_reserved */
 	(reprfunc)set_repr,		/* tp_repr */
 	&set_as_number,			/* tp_as_number */
 	&set_as_sequence,		/* tp_as_sequence */
@@ -2208,7 +2201,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	set_nocmp,			/* tp_compare */
+	0,				/* tp_reserved */
 	(reprfunc)set_repr,		/* tp_repr */
 	&frozenset_as_number,		/* tp_as_number */
 	&set_as_sequence,		/* tp_as_sequence */

Modified: python/branches/io-c/Objects/sliceobject.c
==============================================================================
--- python/branches/io-c/Objects/sliceobject.c	(original)
+++ python/branches/io-c/Objects/sliceobject.c	Sun Feb  8 21:39:02 2009
@@ -31,7 +31,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	ellipsis_repr,			/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -352,7 +352,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,			 		/* tp_compare */
+	0,			 		/* tp_reserved */
 	(reprfunc)slice_repr,   		/* tp_repr */
 	0,					/* tp_as_number */
 	0,	    				/* tp_as_sequence */

Modified: python/branches/io-c/Objects/stringlib/string_format.h
==============================================================================
--- python/branches/io-c/Objects/stringlib/string_format.h	(original)
+++ python/branches/io-c/Objects/stringlib/string_format.h	Sun Feb  8 21:39:02 2009
@@ -1064,7 +1064,7 @@
     0,					/* tp_print */
     0,					/* tp_getattr */
     0,					/* tp_setattr */
-    0,					/* tp_compare */
+    0,					/* tp_reserved */
     0,					/* tp_repr */
     0,					/* tp_as_number */
     0,					/* tp_as_sequence */
@@ -1197,7 +1197,7 @@
     0,					/* tp_print */
     0,					/* tp_getattr */
     0,					/* tp_setattr */
-    0,					/* tp_compare */
+    0,					/* tp_reserved */
     0,					/* tp_repr */
     0,					/* tp_as_number */
     0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/structseq.c
==============================================================================
--- python/branches/io-c/Objects/structseq.c	(original)
+++ python/branches/io-c/Objects/structseq.c	Sun Feb  8 21:39:02 2009
@@ -440,7 +440,7 @@
 	0,                        	        /* tp_print */
 	0,			 		/* tp_getattr */
 	0,					/* tp_setattr */
-	0,               			/* tp_compare */
+	0,               			/* tp_reserved */
 	(reprfunc)structseq_repr,             	/* tp_repr */
 	0,					/* tp_as_number */
 	&structseq_as_sequence,			/* tp_as_sequence */

Modified: python/branches/io-c/Objects/tupleobject.c
==============================================================================
--- python/branches/io-c/Objects/tupleobject.c	(original)
+++ python/branches/io-c/Objects/tupleobject.c	Sun Feb  8 21:39:02 2009
@@ -727,7 +727,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)tuplerepr,			/* tp_repr */
 	0,					/* tp_as_number */
 	&tuple_as_sequence,			/* tp_as_sequence */
@@ -930,7 +930,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/typeobject.c
==============================================================================
--- python/branches/io-c/Objects/typeobject.c	(original)
+++ python/branches/io-c/Objects/typeobject.c	Sun Feb  8 21:39:02 2009
@@ -2584,7 +2584,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	(reprfunc)type_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -2897,7 +2897,7 @@
 	slots_a = ((PyHeapTypeObject *)a)->ht_slots;
 	slots_b = ((PyHeapTypeObject *)b)->ht_slots;
 	if (slots_a && slots_b) {
-		if (PyObject_Compare(slots_a, slots_b) != 0)
+		if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1)
 			return 0;
 		size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
 	}
@@ -3357,7 +3357,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	object_repr,				/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
@@ -3662,7 +3662,7 @@
 		type->tp_setattr = base->tp_setattr;
 		type->tp_setattro = base->tp_setattro;
 	}
-	/* tp_compare see tp_richcompare */
+	/* tp_reserved is ignored */
 	COPYSLOT(tp_repr);
 	/* tp_hash see tp_richcompare */
 	COPYSLOT(tp_call);
@@ -3670,12 +3670,10 @@
 	{
 		/* Copy comparison-related slots only when
 		   not overriding them anywhere */
-		if (type->tp_compare == NULL &&
-		    type->tp_richcompare == NULL &&
+		if (type->tp_richcompare == NULL &&
 		    type->tp_hash == NULL &&
 		    !overrides_hash(type))
 		{
-			type->tp_compare = base->tp_compare;
 			type->tp_richcompare = base->tp_richcompare;
 			type->tp_hash = base->tp_hash;
 		}
@@ -3888,6 +3886,21 @@
 			goto error;
 	}
 
+	/* Warn for a type that implements tp_compare (now known as
+	   tp_reserved) but not tp_richcompare. */
+	if (type->tp_reserved && !type->tp_richcompare) {
+		int error;
+		char msg[240];
+		PyOS_snprintf(msg, sizeof(msg),
+			      "Type %.100s defines tp_reserved (formerly "
+			      "tp_compare) but not tp_richcompare. "
+			      "Comparisons may not behave as intended.",
+			      type->tp_name);
+		error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1);
+		if (error == -1)
+			goto error;
+	}
+
 	/* All done -- set the ready flag */
 	assert(type->tp_dict != NULL);
 	type->tp_flags =
@@ -6252,7 +6265,7 @@
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
-	0,					/* tp_compare */
+	0,					/* tp_reserved */
 	super_repr,				/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */

Modified: python/branches/io-c/Objects/unicodeobject.c
==============================================================================
--- python/branches/io-c/Objects/unicodeobject.c	(original)
+++ python/branches/io-c/Objects/unicodeobject.c	Sun Feb  8 21:39:02 2009
@@ -12,8 +12,8 @@
 --------------------------------------------------------------------
 The original string type implementation is:
 
-    Copyright (c) 1999 by Secret Labs AB
-    Copyright (c) 1999 by Fredrik Lundh
+  Copyright (c) 1999 by Secret Labs AB
+  Copyright (c) 1999 by Fredrik Lundh
 
 By obtaining, using, and/or copying this software and/or its
 associated documentation, you agree that you have read, understood,
@@ -125,59 +125,59 @@
 
 /* Fast detection of the most frequent whitespace characters */
 const unsigned char _Py_ascii_whitespace[] = {
-	0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0,
 /*     case 0x0009: * HORIZONTAL TABULATION */
 /*     case 0x000A: * LINE FEED */
 /*     case 0x000B: * VERTICAL TABULATION */
 /*     case 0x000C: * FORM FEED */
 /*     case 0x000D: * CARRIAGE RETURN */
-	0, 1, 1, 1, 1, 1, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,
+    0, 1, 1, 1, 1, 1, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0,
 /*     case 0x001C: * FILE SEPARATOR */
 /*     case 0x001D: * GROUP SEPARATOR */
 /*     case 0x001E: * RECORD SEPARATOR */
 /*     case 0x001F: * UNIT SEPARATOR */
-	0, 0, 0, 0, 1, 1, 1, 1,
+    0, 0, 0, 0, 1, 1, 1, 1,
 /*     case 0x0020: * SPACE */
-	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, 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, 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, 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, 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, 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
 };
 
 /* Same for linebreaks */
 static unsigned char ascii_linebreak[] = {
-	0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0,
 /*         0x000A, * LINE FEED */
 /*         0x000D, * CARRIAGE RETURN */
-	0, 0, 1, 0, 0, 1, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 1, 0, 0, 1, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0,
 /*         0x001C, * FILE SEPARATOR */
 /*         0x001D, * GROUP SEPARATOR */
 /*         0x001E, * RECORD SEPARATOR */
-	0, 0, 0, 0, 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, 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, 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, 0
+    0, 0, 0, 0, 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, 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, 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, 0
 };
 
 
@@ -185,11 +185,11 @@
 PyUnicode_GetMax(void)
 {
 #ifdef Py_UNICODE_WIDE
-	return 0x10FFFF;
+    return 0x10FFFF;
 #else
-	/* This is actually an illegal character, so it should
-	   not be passed to unichr. */
-	return 0xFFFF;
+    /* This is actually an illegal character, so it should
+       not be passed to unichr. */
+    return 0xFFFF;
 #endif
 }
 
@@ -207,9 +207,9 @@
 
 #define BLOOM(mask, ch) ((mask & (1 << ((ch) & 0x1F))))
 
-#define BLOOM_LINEBREAK(ch) \
-    ((ch) < 128U ? ascii_linebreak[(ch)] : \
-    (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
+#define BLOOM_LINEBREAK(ch)                                             \
+    ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
+     (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
 
 Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
 {
@@ -236,29 +236,29 @@
     return 0;
 }
 
-#define BLOOM_MEMBER(mask, chr, set, setlen)\
+#define BLOOM_MEMBER(mask, chr, set, setlen)                    \
     BLOOM(mask, chr) && unicode_member(chr, set, setlen)
 
 /* --- Unicode Object ----------------------------------------------------- */
 
 static
 int unicode_resize(register PyUnicodeObject *unicode,
-                      Py_ssize_t length)
+                   Py_ssize_t length)
 {
     void *oldstr;
 
     /* Shortcut if there's nothing much to do. */
     if (unicode->length == length)
-	goto reset;
+        goto reset;
 
     /* Resizing shared object (unicode_empty or single character
        objects) in-place is not allowed. Use PyUnicode_Resize()
        instead ! */
 
-    if (unicode == unicode_empty || 
-	(unicode->length == 1 && 
-	 unicode->str[0] < 256U &&
-	 unicode_latin1[unicode->str[0]] == unicode)) {
+    if (unicode == unicode_empty ||
+        (unicode->length == 1 &&
+         unicode->str[0] < 256U &&
+         unicode_latin1[unicode->str[0]] == unicode)) {
         PyErr_SetString(PyExc_SystemError,
                         "can't resize shared str objects");
         return -1;
@@ -271,16 +271,16 @@
 
     oldstr = unicode->str;
     unicode->str = PyObject_REALLOC(unicode->str,
-				    sizeof(Py_UNICODE) * (length + 1));
+                                    sizeof(Py_UNICODE) * (length + 1));
     if (!unicode->str) {
-	unicode->str = (Py_UNICODE *)oldstr;
+        unicode->str = (Py_UNICODE *)oldstr;
         PyErr_NoMemory();
         return -1;
     }
     unicode->str[length] = 0;
     unicode->length = length;
 
- reset:
+  reset:
     /* Reset the object caches */
     if (unicode->defenc) {
         Py_DECREF(unicode->defenc);
@@ -296,7 +296,7 @@
    relies on that.
 
    XXX This allocator could further be enhanced by assuring that the
-       free list never reduces its size below 1.
+   free list never reduces its size below 1.
 
 */
 
@@ -321,33 +321,33 @@
         unicode = free_list;
         free_list = *(PyUnicodeObject **)unicode;
         numfree--;
-	if (unicode->str) {
-	    /* Keep-Alive optimization: we only upsize the buffer,
-	       never downsize it. */
-	    if ((unicode->length < length) &&
+        if (unicode->str) {
+            /* Keep-Alive optimization: we only upsize the buffer,
+               never downsize it. */
+            if ((unicode->length < length) &&
                 unicode_resize(unicode, length) < 0) {
-		PyObject_DEL(unicode->str);
-		unicode->str = NULL;
-	    }
-	}
+                PyObject_DEL(unicode->str);
+                unicode->str = NULL;
+            }
+        }
         else {
-	    size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
-	    unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
+            size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
+            unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
         }
         PyObject_INIT(unicode, &PyUnicode_Type);
     }
     else {
-	size_t new_size;
+        size_t new_size;
         unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
         if (unicode == NULL)
             return NULL;
-	new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
-	unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
+        new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
+        unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
     }
 
     if (!unicode->str) {
-	PyErr_NoMemory();
-	goto onError;
+        PyErr_NoMemory();
+        goto onError;
     }
     /* Initialize the first element to guard against cases where
      * the caller fails before initializing str -- unicode_resize()
@@ -364,7 +364,7 @@
     unicode->defenc = NULL;
     return unicode;
 
- onError:
+  onError:
     /* XXX UNREF/NEWREF interface should be more symmetrical */
     _Py_DEC_REFTOTAL;
     _Py_ForgetReference((PyObject *)unicode);
@@ -376,45 +376,45 @@
 void unicode_dealloc(register PyUnicodeObject *unicode)
 {
     switch (PyUnicode_CHECK_INTERNED(unicode)) {
-        case SSTATE_NOT_INTERNED:
-            break;
+    case SSTATE_NOT_INTERNED:
+        break;
 
-        case SSTATE_INTERNED_MORTAL:
-            /* revive dead object temporarily for DelItem */
-            Py_REFCNT(unicode) = 3;
-            if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
-                Py_FatalError(
-                    "deletion of interned string failed");
-            break;
+    case SSTATE_INTERNED_MORTAL:
+        /* revive dead object temporarily for DelItem */
+        Py_REFCNT(unicode) = 3;
+        if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
+            Py_FatalError(
+                "deletion of interned string failed");
+        break;
 
-        case SSTATE_INTERNED_IMMORTAL:
-            Py_FatalError("Immortal interned string died.");
+    case SSTATE_INTERNED_IMMORTAL:
+        Py_FatalError("Immortal interned string died.");
 
-        default:
-            Py_FatalError("Inconsistent interned string state.");
+    default:
+        Py_FatalError("Inconsistent interned string state.");
     }
 
     if (PyUnicode_CheckExact(unicode) &&
-	numfree < PyUnicode_MAXFREELIST) {
+        numfree < PyUnicode_MAXFREELIST) {
         /* Keep-Alive optimization */
-	if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
-	    PyObject_DEL(unicode->str);
-	    unicode->str = NULL;
-	    unicode->length = 0;
-	}
-	if (unicode->defenc) {
-	    Py_DECREF(unicode->defenc);
-	    unicode->defenc = NULL;
-	}
-	/* Add to free list */
+        if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
+            PyObject_DEL(unicode->str);
+            unicode->str = NULL;
+            unicode->length = 0;
+        }
+        if (unicode->defenc) {
+            Py_DECREF(unicode->defenc);
+            unicode->defenc = NULL;
+        }
+        /* Add to free list */
         *(PyUnicodeObject **)unicode = free_list;
         free_list = unicode;
         numfree++;
     }
     else {
-	PyObject_DEL(unicode->str);
-	Py_XDECREF(unicode->defenc);
-	Py_TYPE(unicode)->tp_free((PyObject *)unicode);
+        PyObject_DEL(unicode->str);
+        Py_XDECREF(unicode->defenc);
+        Py_TYPE(unicode)->tp_free((PyObject *)unicode);
     }
 }
 
@@ -425,28 +425,28 @@
 
     /* Argument checks */
     if (unicode == NULL) {
-	PyErr_BadInternalCall();
-	return -1;
+        PyErr_BadInternalCall();
+        return -1;
     }
     v = *unicode;
     if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
-	PyErr_BadInternalCall();
-	return -1;
+        PyErr_BadInternalCall();
+        return -1;
     }
 
     /* Resizing unicode_empty and single character objects is not
        possible since these are being shared. We simply return a fresh
        copy with the same Unicode content. */
     if (v->length != length &&
-	(v == unicode_empty || v->length == 1)) {
-	PyUnicodeObject *w = _PyUnicode_New(length);
-	if (w == NULL)
-	    return -1;
-	Py_UNICODE_COPY(w->str, v->str,
-			length < v->length ? length : v->length);
-	Py_DECREF(*unicode);
-	*unicode = w;
-	return 0;
+        (v == unicode_empty || v->length == 1)) {
+        PyUnicodeObject *w = _PyUnicode_New(length);
+        if (w == NULL)
+            return -1;
+        Py_UNICODE_COPY(w->str, v->str,
+                        length < v->length ? length : v->length);
+        Py_DECREF(*unicode);
+        *unicode = w;
+        return 0;
     }
 
     /* Note that we don't have to modify *unicode for unshared Unicode
@@ -460,7 +460,7 @@
 }
 
 PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
-				Py_ssize_t size)
+                                Py_ssize_t size)
 {
     PyUnicodeObject *unicode;
 
@@ -468,26 +468,26 @@
        some optimizations which share commonly used objects. */
     if (u != NULL) {
 
-	/* Optimization for empty strings */
-	if (size == 0 && unicode_empty != NULL) {
-	    Py_INCREF(unicode_empty);
-	    return (PyObject *)unicode_empty;
-	}
-
-	/* Single character Unicode objects in the Latin-1 range are
-	   shared when using this constructor */
-	if (size == 1 && *u < 256) {
-	    unicode = unicode_latin1[*u];
-	    if (!unicode) {
-		unicode = _PyUnicode_New(1);
-		if (!unicode)
-		    return NULL;
-		unicode->str[0] = *u;
-		unicode_latin1[*u] = unicode;
-	    }
-	    Py_INCREF(unicode);
-	    return (PyObject *)unicode;
-	}
+        /* Optimization for empty strings */
+        if (size == 0 && unicode_empty != NULL) {
+            Py_INCREF(unicode_empty);
+            return (PyObject *)unicode_empty;
+        }
+
+        /* Single character Unicode objects in the Latin-1 range are
+           shared when using this constructor */
+        if (size == 1 && *u < 256) {
+            unicode = unicode_latin1[*u];
+            if (!unicode) {
+                unicode = _PyUnicode_New(1);
+                if (!unicode)
+                    return NULL;
+                unicode->str[0] = *u;
+                unicode_latin1[*u] = unicode;
+            }
+            Py_INCREF(unicode);
+            return (PyObject *)unicode;
+        }
     }
 
     unicode = _PyUnicode_New(size);
@@ -496,7 +496,7 @@
 
     /* Copy the Unicode data into the new object */
     if (u != NULL)
-	Py_UNICODE_COPY(unicode->str, u, size);
+        Py_UNICODE_COPY(unicode->str, u, size);
 
     return (PyObject *)unicode;
 }
@@ -505,11 +505,11 @@
 {
     PyUnicodeObject *unicode;
 
-	if (size < 0) {
-		PyErr_SetString(PyExc_SystemError,
-		    "Negative size passed to PyUnicode_FromStringAndSize");
-		return NULL;
-	}
+    if (size < 0) {
+        PyErr_SetString(PyExc_SystemError,
+                        "Negative size passed to PyUnicode_FromStringAndSize");
+        return NULL;
+    }
 
     /* If the Unicode data is known at construction time, we can apply
        some optimizations which share commonly used objects.
@@ -517,26 +517,26 @@
        UTF-8 decoder at the end. */
     if (u != NULL) {
 
-	/* Optimization for empty strings */
-	if (size == 0 && unicode_empty != NULL) {
-	    Py_INCREF(unicode_empty);
-	    return (PyObject *)unicode_empty;
-	}
+        /* Optimization for empty strings */
+        if (size == 0 && unicode_empty != NULL) {
+            Py_INCREF(unicode_empty);
+            return (PyObject *)unicode_empty;
+        }
 
-	/* Single characters are shared when using this constructor.
+        /* Single characters are shared when using this constructor.
            Restrict to ASCII, since the input must be UTF-8. */
-	if (size == 1 && Py_CHARMASK(*u) < 128) {
-	    unicode = unicode_latin1[Py_CHARMASK(*u)];
-	    if (!unicode) {
-		unicode = _PyUnicode_New(1);
-		if (!unicode)
-		    return NULL;
-		unicode->str[0] = Py_CHARMASK(*u);
-		unicode_latin1[Py_CHARMASK(*u)] = unicode;
-	    }
-	    Py_INCREF(unicode);
-	    return (PyObject *)unicode;
-	}
+        if (size == 1 && Py_CHARMASK(*u) < 128) {
+            unicode = unicode_latin1[Py_CHARMASK(*u)];
+            if (!unicode) {
+                unicode = _PyUnicode_New(1);
+                if (!unicode)
+                    return NULL;
+                unicode->str[0] = Py_CHARMASK(*u);
+                unicode_latin1[Py_CHARMASK(*u)] = unicode;
+            }
+            Py_INCREF(unicode);
+            return (PyObject *)unicode;
+        }
 
         return PyUnicode_DecodeUTF8(u, size, NULL);
     }
@@ -562,15 +562,15 @@
 #ifdef HAVE_WCHAR_H
 
 PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
-				 Py_ssize_t size)
+                                 Py_ssize_t size)
 {
     PyUnicodeObject *unicode;
 
     if (w == NULL) {
         if (size == 0)
             return PyUnicode_FromStringAndSize(NULL, 0);
-	PyErr_BadInternalCall();
-	return NULL;
+        PyErr_BadInternalCall();
+        return NULL;
     }
 
     if (size == -1) {
@@ -586,11 +586,11 @@
     memcpy(unicode->str, w, size * sizeof(wchar_t));
 #else
     {
-	register Py_UNICODE *u;
-	register Py_ssize_t i;
-	u = PyUnicode_AS_UNICODE(unicode);
-	for (i = size; i > 0; i--)
-	    *u++ = *w++;
+        register Py_UNICODE *u;
+        register Py_ssize_t i;
+        u = PyUnicode_AS_UNICODE(unicode);
+        for (i = size; i > 0; i--)
+            *u++ = *w++;
     }
 #endif
 
@@ -600,23 +600,23 @@
 static void
 makefmt(char *fmt, int longflag, int size_tflag, int zeropad, int width, int precision, char c)
 {
-	*fmt++ = '%';
-	if (width) {
-		if (zeropad)
-			*fmt++ = '0';
-		fmt += sprintf(fmt, "%d", width);
-	}
-	if (precision)
-		fmt += sprintf(fmt, ".%d", precision);
-	if (longflag)
-		*fmt++ = 'l';
-	else if (size_tflag) {
-		char *f = PY_FORMAT_SIZE_T;
-		while (*f)
-			*fmt++ = *f++;
-	}
-	*fmt++ = c;
-	*fmt = '\0';
+    *fmt++ = '%';
+    if (width) {
+        if (zeropad)
+            *fmt++ = '0';
+        fmt += sprintf(fmt, "%d", width);
+    }
+    if (precision)
+        fmt += sprintf(fmt, ".%d", precision);
+    if (longflag)
+        *fmt++ = 'l';
+    else if (size_tflag) {
+        char *f = PY_FORMAT_SIZE_T;
+        while (*f)
+            *fmt++ = *f++;
+    }
+    *fmt++ = c;
+    *fmt = '\0';
 }
 
 #define appendstring(string) {for (copy = string;*copy;) *s++ = *copy++;}
@@ -624,387 +624,387 @@
 PyObject *
 PyUnicode_FromFormatV(const char *format, va_list vargs)
 {
-	va_list count;
-	Py_ssize_t callcount = 0;
-	PyObject **callresults = NULL;
-	PyObject **callresult = NULL;
-	Py_ssize_t n = 0;
-	int width = 0;
-	int precision = 0;
-	int zeropad;
-	const char* f;
-	Py_UNICODE *s;
-	PyObject *string;
-	/* used by sprintf */
-	char buffer[21];
-	/* use abuffer instead of buffer, if we need more space
-	 * (which can happen if there's a format specifier with width). */
-	char *abuffer = NULL;
-	char *realbuffer;
-	Py_ssize_t abuffersize = 0;
-	char fmt[60]; /* should be enough for %0width.precisionld */
-	const char *copy;
+    va_list count;
+    Py_ssize_t callcount = 0;
+    PyObject **callresults = NULL;
+    PyObject **callresult = NULL;
+    Py_ssize_t n = 0;
+    int width = 0;
+    int precision = 0;
+    int zeropad;
+    const char* f;
+    Py_UNICODE *s;
+    PyObject *string;
+    /* used by sprintf */
+    char buffer[21];
+    /* use abuffer instead of buffer, if we need more space
+     * (which can happen if there's a format specifier with width). */
+    char *abuffer = NULL;
+    char *realbuffer;
+    Py_ssize_t abuffersize = 0;
+    char fmt[60]; /* should be enough for %0width.precisionld */
+    const char *copy;
 
 #ifdef VA_LIST_IS_ARRAY
-	Py_MEMCPY(count, vargs, sizeof(va_list));
+    Py_MEMCPY(count, vargs, sizeof(va_list));
 #else
 #ifdef  __va_copy
-	__va_copy(count, vargs);
+    __va_copy(count, vargs);
 #else
-	count = vargs;
+    count = vargs;
 #endif
 #endif
-	/* step 1: count the number of %S/%R/%A format specifications
-	 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII() for 
-	 * these objects once during step 3 and put the result in 
-	   an array) */
-	for (f = format; *f; f++) {
-		if (*f == '%' && (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A'))
-			++callcount;
-	}
-	/* step 2: allocate memory for the results of
-	 * PyObject_Str()/PyObject_Repr() calls */
-	if (callcount) {
-		callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
-		if (!callresults) {
-			PyErr_NoMemory();
-			return NULL;
-		}
-		callresult = callresults;
-	}
-	/* step 3: figure out how large a buffer we need */
-	for (f = format; *f; f++) {
-		if (*f == '%') {
-			const char* p = f;
-			width = 0;
-			while (ISDIGIT((unsigned)*f))
-				width = (width*10) + *f++ - '0';
-			while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
-				;
-
-			/* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
-			 * they don't affect the amount of space we reserve.
-			 */
-			if ((*f == 'l' || *f == 'z') &&
-					(f[1] == 'd' || f[1] == 'u'))
-                                ++f;
-
-			switch (*f) {
-			case 'c':
-				(void)va_arg(count, int);
-				/* fall through... */
-			case '%':
-				n++;
-				break;
-			case 'd': case 'u': case 'i': case 'x':
-				(void) va_arg(count, int);
-				/* 20 bytes is enough to hold a 64-bit
-				   integer.  Decimal takes the most space.
-				   This isn't enough for octal.
-				   If a width is specified we need more
-				   (which we allocate later). */
-				if (width < 20)
-					width = 20;
-				n += width;
-				if (abuffersize < width)
-					abuffersize = width;
-				break;
-			case 's':
-			{
-				/* UTF-8 */
-				unsigned char*s;
-				s = va_arg(count, unsigned char*);
-				while (*s) {
-					if (*s < 128) {
-						n++; s++;
-					} else if (*s < 0xc0) {
-						/* invalid UTF-8 */
-						n++; s++;
-					} else if (*s < 0xc0) {
-						n++;
-						s++; if(!*s)break;
-						s++;
-					} else if (*s < 0xe0) {
-						n++;
-						s++; if(!*s)break;
-						s++; if(!*s)break;
-						s++;
-					} else {
-						#ifdef Py_UNICODE_WIDE
-						n++;
-						#else
-						n+=2;
-						#endif
-						s++; if(!*s)break;
-						s++; if(!*s)break;
-						s++; if(!*s)break;
-						s++;
-					}
-				}
-				break;
-			}
-			case 'U':
-			{
-				PyObject *obj = va_arg(count, PyObject *);
-				assert(obj && PyUnicode_Check(obj));
-				n += PyUnicode_GET_SIZE(obj);
-				break;
-			}
-			case 'V':
-			{
-				PyObject *obj = va_arg(count, PyObject *);
-				const char *str = va_arg(count, const char *);
-				assert(obj || str);
-				assert(!obj || PyUnicode_Check(obj));
-				if (obj)
-					n += PyUnicode_GET_SIZE(obj);
-				else
-					n += strlen(str);
-				break;
-			}
-			case 'S':
-			{
-				PyObject *obj = va_arg(count, PyObject *);
-				PyObject *str;
-				assert(obj);
-				str = PyObject_Str(obj);
-				if (!str)
-					goto fail;
-				n += PyUnicode_GET_SIZE(str);
-				/* Remember the str and switch to the next slot */
-				*callresult++ = str;
-				break;
-			}
-			case 'R':
-			{
-				PyObject *obj = va_arg(count, PyObject *);
-				PyObject *repr;
-				assert(obj);
-				repr = PyObject_Repr(obj);
-				if (!repr)
-					goto fail;
-				n += PyUnicode_GET_SIZE(repr);
-				/* Remember the repr and switch to the next slot */
-				*callresult++ = repr;
-				break;
-			}
-			case 'A':
-			{
-				PyObject *obj = va_arg(count, PyObject *);
-				PyObject *ascii;
-				assert(obj);
-				ascii = PyObject_ASCII(obj);
-				if (!ascii)
-					goto fail;
-				n += PyUnicode_GET_SIZE(ascii);
-				/* Remember the repr and switch to the next slot */
-				*callresult++ = ascii;
-				break;
-			}
-			case 'p':
-				(void) va_arg(count, int);
-				/* maximum 64-bit pointer representation:
-				 * 0xffffffffffffffff
-				 * so 19 characters is enough.
-				 * XXX I count 18 -- what's the extra for?
-				 */
-				n += 19;
-				break;
-			default:
-				/* if we stumble upon an unknown
-				   formatting code, copy the rest of
-				   the format string to the output
-				   string. (we cannot just skip the
-				   code, since there's no way to know
-				   what's in the argument list) */
-				n += strlen(p);
-				goto expand;
-			}
-		} else
-			n++;
-	}
- expand:
-	if (abuffersize > 20) {
-		abuffer = PyObject_Malloc(abuffersize);
-		if (!abuffer) {
-			PyErr_NoMemory();
-			goto fail;
-		}
-		realbuffer = abuffer;
-	}
-	else
-		realbuffer = buffer;
-	/* step 4: fill the buffer */
-	/* Since we've analyzed how much space we need for the worst case,
-	   we don't have to resize the string.
-	   There can be no errors beyond this point. */
-	string = PyUnicode_FromUnicode(NULL, n);
-	if (!string)
-		goto fail;
-
-	s = PyUnicode_AS_UNICODE(string);
-	callresult = callresults;
-
-	for (f = format; *f; f++) {
-		if (*f == '%') {
-			const char* p = f++;
-			int longflag = 0;
-			int size_tflag = 0;
-			zeropad = (*f == '0');
-			/* parse the width.precision part */
-			width = 0;
-			while (ISDIGIT((unsigned)*f))
-				width = (width*10) + *f++ - '0';
-			precision = 0;
-			if (*f == '.') {
-				f++;
-				while (ISDIGIT((unsigned)*f))
-					precision = (precision*10) + *f++ - '0';
-			}
-			/* handle the long flag, but only for %ld and %lu.
-			   others can be added when necessary. */
-			if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
-				longflag = 1;
-				++f;
-			}
-			/* handle the size_t flag. */
-			if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
-				size_tflag = 1;
-				++f;
-			}
-
-			switch (*f) {
-			case 'c':
-				*s++ = va_arg(vargs, int);
-				break;
-			case 'd':
-				makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd');
-				if (longflag)
-					sprintf(realbuffer, fmt, va_arg(vargs, long));
-				else if (size_tflag)
-					sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
-				else
-					sprintf(realbuffer, fmt, va_arg(vargs, int));
-				appendstring(realbuffer);
-				break;
-			case 'u':
-				makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u');
-				if (longflag)
-					sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
-				else if (size_tflag)
-					sprintf(realbuffer, fmt, va_arg(vargs, size_t));
-				else
-					sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
-				appendstring(realbuffer);
-				break;
-			case 'i':
-				makefmt(fmt, 0, 0, zeropad, width, precision, 'i');
-				sprintf(realbuffer, fmt, va_arg(vargs, int));
-				appendstring(realbuffer);
-				break;
-			case 'x':
-				makefmt(fmt, 0, 0, zeropad, width, precision, 'x');
-				sprintf(realbuffer, fmt, va_arg(vargs, int));
-				appendstring(realbuffer);
-				break;
-			case 's':
-			{
-				/* Parameter must be UTF-8 encoded.
-				   In case of encoding errors, use
-				   the replacement character. */
-				PyObject *u;
-				p = va_arg(vargs, char*);
-				u = PyUnicode_DecodeUTF8(p, strlen(p), 
-							 "replace");
-				if (!u)
-					goto fail;
-				Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(u),
-						PyUnicode_GET_SIZE(u));
-				s += PyUnicode_GET_SIZE(u);
-				Py_DECREF(u);
-				break;
-			}
-			case 'U':
-			{
-				PyObject *obj = va_arg(vargs, PyObject *);
-				Py_ssize_t size = PyUnicode_GET_SIZE(obj);
-				Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
-				s += size;
-				break;
-			}
-			case 'V':
-			{
-				PyObject *obj = va_arg(vargs, PyObject *);
-				const char *str = va_arg(vargs, const char *);
-				if (obj) {
-					Py_ssize_t size = PyUnicode_GET_SIZE(obj);
-					Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
-					s += size;
-				} else {
-					appendstring(str);
-				}
-				break;
-			}
-			case 'S':
-			case 'R':
-			{
-				Py_UNICODE *ucopy;
-				Py_ssize_t usize;
-				Py_ssize_t upos;
-				/* unused, since we already have the result */
-				(void) va_arg(vargs, PyObject *);
-				ucopy = PyUnicode_AS_UNICODE(*callresult);
-				usize = PyUnicode_GET_SIZE(*callresult);
-				for (upos = 0; upos<usize;)
-					*s++ = ucopy[upos++];
-				/* We're done with the unicode()/repr() => forget it */
-				Py_DECREF(*callresult);
-				/* switch to next unicode()/repr() result */
-				++callresult;
-				break;
-			}
-			case 'p':
-				sprintf(buffer, "%p", va_arg(vargs, void*));
-				/* %p is ill-defined:  ensure leading 0x. */
-				if (buffer[1] == 'X')
-					buffer[1] = 'x';
-				else if (buffer[1] != 'x') {
-					memmove(buffer+2, buffer, strlen(buffer)+1);
-					buffer[0] = '0';
-					buffer[1] = 'x';
-				}
-				appendstring(buffer);
-				break;
-			case '%':
-				*s++ = '%';
-				break;
-			default:
-				appendstring(p);
-				goto end;
-			}
-		} else
-			*s++ = *f;
-	}
-
- end:
-	if (callresults)
-		PyObject_Free(callresults);
-	if (abuffer)
-		PyObject_Free(abuffer);
-	PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
-	return string;
- fail:
-	if (callresults) {
-		PyObject **callresult2 = callresults;
-		while (callresult2 < callresult) {
-			Py_DECREF(*callresult2);
-			++callresult2;
-		}
-		PyObject_Free(callresults);
-	}
-	if (abuffer)
-		PyObject_Free(abuffer);
-	return NULL;
+    /* step 1: count the number of %S/%R/%A format specifications
+     * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII() for
+     * these objects once during step 3 and put the result in
+     an array) */
+    for (f = format; *f; f++) {
+        if (*f == '%' && (*(f+1)=='S' || *(f+1)=='R' || *(f+1)=='A'))
+            ++callcount;
+    }
+    /* step 2: allocate memory for the results of
+     * PyObject_Str()/PyObject_Repr() calls */
+    if (callcount) {
+        callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
+        if (!callresults) {
+            PyErr_NoMemory();
+            return NULL;
+        }
+        callresult = callresults;
+    }
+    /* step 3: figure out how large a buffer we need */
+    for (f = format; *f; f++) {
+        if (*f == '%') {
+            const char* p = f;
+            width = 0;
+            while (ISDIGIT((unsigned)*f))
+                width = (width*10) + *f++ - '0';
+            while (*++f && *f != '%' && !ISALPHA((unsigned)*f))
+                ;
+
+            /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
+             * they don't affect the amount of space we reserve.
+             */
+            if ((*f == 'l' || *f == 'z') &&
+                (f[1] == 'd' || f[1] == 'u'))
+                ++f;
+
+            switch (*f) {
+            case 'c':
+                (void)va_arg(count, int);
+                /* fall through... */
+            case '%':
+                n++;
+                break;
+            case 'd': case 'u': case 'i': case 'x':
+                (void) va_arg(count, int);
+                /* 20 bytes is enough to hold a 64-bit
+                   integer.  Decimal takes the most space.
+                   This isn't enough for octal.
+                   If a width is specified we need more
+                   (which we allocate later). */
+                if (width < 20)
+                    width = 20;
+                n += width;
+                if (abuffersize < width)
+                    abuffersize = width;
+                break;
+            case 's':
+            {
+                /* UTF-8 */
+                unsigned char*s;
+                s = va_arg(count, unsigned char*);
+                while (*s) {
+                    if (*s < 128) {
+                        n++; s++;
+                    } else if (*s < 0xc0) {
+                        /* invalid UTF-8 */
+                        n++; s++;
+                    } else if (*s < 0xc0) {
+                        n++;
+                        s++; if(!*s)break;
+                        s++;
+                    } else if (*s < 0xe0) {
+                        n++;
+                        s++; if(!*s)break;
+                        s++; if(!*s)break;
+                        s++;
+                    } else {
+#ifdef Py_UNICODE_WIDE
+                        n++;
+#else
+                        n+=2;
+#endif
+                        s++; if(!*s)break;
+                        s++; if(!*s)break;
+                        s++; if(!*s)break;
+                        s++;
+                    }
+                }
+                break;
+            }
+            case 'U':
+            {
+                PyObject *obj = va_arg(count, PyObject *);
+                assert(obj && PyUnicode_Check(obj));
+                n += PyUnicode_GET_SIZE(obj);
+                break;
+            }
+            case 'V':
+            {
+                PyObject *obj = va_arg(count, PyObject *);
+                const char *str = va_arg(count, const char *);
+                assert(obj || str);
+                assert(!obj || PyUnicode_Check(obj));
+                if (obj)
+                    n += PyUnicode_GET_SIZE(obj);
+                else
+                    n += strlen(str);
+                break;
+            }
+            case 'S':
+            {
+                PyObject *obj = va_arg(count, PyObject *);
+                PyObject *str;
+                assert(obj);
+                str = PyObject_Str(obj);
+                if (!str)
+                    goto fail;
+                n += PyUnicode_GET_SIZE(str);
+                /* Remember the str and switch to the next slot */
+                *callresult++ = str;
+                break;
+            }
+            case 'R':
+            {
+                PyObject *obj = va_arg(count, PyObject *);
+                PyObject *repr;
+                assert(obj);
+                repr = PyObject_Repr(obj);
+                if (!repr)
+                    goto fail;
+                n += PyUnicode_GET_SIZE(repr);
+                /* Remember the repr and switch to the next slot */
+                *callresult++ = repr;
+                break;
+            }
+            case 'A':
+            {
+                PyObject *obj = va_arg(count, PyObject *);
+                PyObject *ascii;
+                assert(obj);
+                ascii = PyObject_ASCII(obj);
+                if (!ascii)
+                    goto fail;
+                n += PyUnicode_GET_SIZE(ascii);
+                /* Remember the repr and switch to the next slot */
+                *callresult++ = ascii;
+                break;
+            }
+            case 'p':
+                (void) va_arg(count, int);
+                /* maximum 64-bit pointer representation:
+                 * 0xffffffffffffffff
+                 * so 19 characters is enough.
+                 * XXX I count 18 -- what's the extra for?
+                 */
+                n += 19;
+                break;
+            default:
+                /* if we stumble upon an unknown
+                   formatting code, copy the rest of
+                   the format string to the output
+                   string. (we cannot just skip the
+                   code, since there's no way to know
+                   what's in the argument list) */
+                n += strlen(p);
+                goto expand;
+            }
+        } else
+            n++;
+    }
+  expand:
+    if (abuffersize > 20) {
+        abuffer = PyObject_Malloc(abuffersize);
+        if (!abuffer) {
+            PyErr_NoMemory();
+            goto fail;
+        }
+        realbuffer = abuffer;
+    }
+    else
+        realbuffer = buffer;
+    /* step 4: fill the buffer */
+    /* Since we've analyzed how much space we need for the worst case,
+       we don't have to resize the string.
+       There can be no errors beyond this point. */
+    string = PyUnicode_FromUnicode(NULL, n);
+    if (!string)
+        goto fail;
+
+    s = PyUnicode_AS_UNICODE(string);
+    callresult = callresults;
+
+    for (f = format; *f; f++) {
+        if (*f == '%') {
+            const char* p = f++;
+            int longflag = 0;
+            int size_tflag = 0;
+            zeropad = (*f == '0');
+            /* parse the width.precision part */
+            width = 0;
+            while (ISDIGIT((unsigned)*f))
+                width = (width*10) + *f++ - '0';
+            precision = 0;
+            if (*f == '.') {
+                f++;
+                while (ISDIGIT((unsigned)*f))
+                    precision = (precision*10) + *f++ - '0';
+            }
+            /* handle the long flag, but only for %ld and %lu.
+               others can be added when necessary. */
+            if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
+                longflag = 1;
+                ++f;
+            }
+            /* handle the size_t flag. */
+            if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
+                size_tflag = 1;
+                ++f;
+            }
+
+            switch (*f) {
+            case 'c':
+                *s++ = va_arg(vargs, int);
+                break;
+            case 'd':
+                makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'd');
+                if (longflag)
+                    sprintf(realbuffer, fmt, va_arg(vargs, long));
+                else if (size_tflag)
+                    sprintf(realbuffer, fmt, va_arg(vargs, Py_ssize_t));
+                else
+                    sprintf(realbuffer, fmt, va_arg(vargs, int));
+                appendstring(realbuffer);
+                break;
+            case 'u':
+                makefmt(fmt, longflag, size_tflag, zeropad, width, precision, 'u');
+                if (longflag)
+                    sprintf(realbuffer, fmt, va_arg(vargs, unsigned long));
+                else if (size_tflag)
+                    sprintf(realbuffer, fmt, va_arg(vargs, size_t));
+                else
+                    sprintf(realbuffer, fmt, va_arg(vargs, unsigned int));
+                appendstring(realbuffer);
+                break;
+            case 'i':
+                makefmt(fmt, 0, 0, zeropad, width, precision, 'i');
+                sprintf(realbuffer, fmt, va_arg(vargs, int));
+                appendstring(realbuffer);
+                break;
+            case 'x':
+                makefmt(fmt, 0, 0, zeropad, width, precision, 'x');
+                sprintf(realbuffer, fmt, va_arg(vargs, int));
+                appendstring(realbuffer);
+                break;
+            case 's':
+            {
+                /* Parameter must be UTF-8 encoded.
+                   In case of encoding errors, use
+                   the replacement character. */
+                PyObject *u;
+                p = va_arg(vargs, char*);
+                u = PyUnicode_DecodeUTF8(p, strlen(p),
+                                         "replace");
+                if (!u)
+                    goto fail;
+                Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(u),
+                                PyUnicode_GET_SIZE(u));
+                s += PyUnicode_GET_SIZE(u);
+                Py_DECREF(u);
+                break;
+            }
+            case 'U':
+            {
+                PyObject *obj = va_arg(vargs, PyObject *);
+                Py_ssize_t size = PyUnicode_GET_SIZE(obj);
+                Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
+                s += size;
+                break;
+            }
+            case 'V':
+            {
+                PyObject *obj = va_arg(vargs, PyObject *);
+                const char *str = va_arg(vargs, const char *);
+                if (obj) {
+                    Py_ssize_t size = PyUnicode_GET_SIZE(obj);
+                    Py_UNICODE_COPY(s, PyUnicode_AS_UNICODE(obj), size);
+                    s += size;
+                } else {
+                    appendstring(str);
+                }
+                break;
+            }
+            case 'S':
+            case 'R':
+            {
+                Py_UNICODE *ucopy;
+                Py_ssize_t usize;
+                Py_ssize_t upos;
+                /* unused, since we already have the result */
+                (void) va_arg(vargs, PyObject *);
+                ucopy = PyUnicode_AS_UNICODE(*callresult);
+                usize = PyUnicode_GET_SIZE(*callresult);
+                for (upos = 0; upos<usize;)
+                    *s++ = ucopy[upos++];
+                /* We're done with the unicode()/repr() => forget it */
+                Py_DECREF(*callresult);
+                /* switch to next unicode()/repr() result */
+                ++callresult;
+                break;
+            }
+            case 'p':
+                sprintf(buffer, "%p", va_arg(vargs, void*));
+                /* %p is ill-defined:  ensure leading 0x. */
+                if (buffer[1] == 'X')
+                    buffer[1] = 'x';
+                else if (buffer[1] != 'x') {
+                    memmove(buffer+2, buffer, strlen(buffer)+1);
+                    buffer[0] = '0';
+                    buffer[1] = 'x';
+                }
+                appendstring(buffer);
+                break;
+            case '%':
+                *s++ = '%';
+                break;
+            default:
+                appendstring(p);
+                goto end;
+            }
+        } else
+            *s++ = *f;
+    }
+
+  end:
+    if (callresults)
+        PyObject_Free(callresults);
+    if (abuffer)
+        PyObject_Free(abuffer);
+    PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
+    return string;
+  fail:
+    if (callresults) {
+        PyObject **callresult2 = callresults;
+        while (callresult2 < callresult) {
+            Py_DECREF(*callresult2);
+            ++callresult2;
+        }
+        PyObject_Free(callresults);
+    }
+    if (abuffer)
+        PyObject_Free(abuffer);
+    return NULL;
 }
 
 #undef appendstring
@@ -1012,48 +1012,48 @@
 PyObject *
 PyUnicode_FromFormat(const char *format, ...)
 {
-	PyObject* ret;
-	va_list vargs;
+    PyObject* ret;
+    va_list vargs;
 
 #ifdef HAVE_STDARG_PROTOTYPES
-	va_start(vargs, format);
+    va_start(vargs, format);
 #else
-	va_start(vargs);
+    va_start(vargs);
 #endif
-	ret = PyUnicode_FromFormatV(format, vargs);
-	va_end(vargs);
-	return ret;
+    ret = PyUnicode_FromFormatV(format, vargs);
+    va_end(vargs);
+    return ret;
 }
 
 Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode,
-				wchar_t *w,
-				Py_ssize_t size)
+                                wchar_t *w,
+                                Py_ssize_t size)
 {
     if (unicode == NULL) {
-	PyErr_BadInternalCall();
-	return -1;
+        PyErr_BadInternalCall();
+        return -1;
     }
 
     /* If possible, try to copy the 0-termination as well */
     if (size > PyUnicode_GET_SIZE(unicode))
-	size = PyUnicode_GET_SIZE(unicode) + 1;
+        size = PyUnicode_GET_SIZE(unicode) + 1;
 
 #ifdef HAVE_USABLE_WCHAR_T
     memcpy(w, unicode->str, size * sizeof(wchar_t));
 #else
     {
-	register Py_UNICODE *u;
-	register Py_ssize_t i;
-	u = PyUnicode_AS_UNICODE(unicode);
-	for (i = size; i > 0; i--)
-	    *w++ = *u++;
+        register Py_UNICODE *u;
+        register Py_ssize_t i;
+        u = PyUnicode_AS_UNICODE(unicode);
+        for (i = size; i > 0; i--)
+            *w++ = *u++;
     }
 #endif
 
     if (size > PyUnicode_GET_SIZE(unicode))
         return PyUnicode_GET_SIZE(unicode);
     else
-    return size;
+        return size;
 }
 
 #endif
@@ -1063,9 +1063,9 @@
     Py_UNICODE s[2];
 
     if (ordinal < 0 || ordinal > 0x10ffff) {
-	PyErr_SetString(PyExc_ValueError,
-			"chr() arg not in range(0x110000)");
-	return NULL;
+        PyErr_SetString(PyExc_ValueError,
+                        "chr() arg not in range(0x110000)");
+        return NULL;
     }
 
 #ifndef Py_UNICODE_WIDE
@@ -1084,16 +1084,16 @@
 PyObject *PyUnicode_FromObject(register PyObject *obj)
 {
     /* XXX Perhaps we should make this API an alias of
-           PyObject_Str() instead ?! */
+       PyObject_Str() instead ?! */
     if (PyUnicode_CheckExact(obj)) {
-	Py_INCREF(obj);
-	return obj;
+        Py_INCREF(obj);
+        return obj;
     }
     if (PyUnicode_Check(obj)) {
-	/* For a Unicode subtype that's not a Unicode object,
-	   return a true Unicode object with the same data. */
-	return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
-				     PyUnicode_GET_SIZE(obj));
+        /* For a Unicode subtype that's not a Unicode object,
+           return a true Unicode object with the same data. */
+        return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
+                                     PyUnicode_GET_SIZE(obj));
     }
     PyErr_Format(PyExc_TypeError,
                  "Can't convert '%.100s' object to str implicitly",
@@ -1102,23 +1102,23 @@
 }
 
 PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
-				      const char *encoding,
-				      const char *errors)
+                                      const char *encoding,
+                                      const char *errors)
 {
     const char *s = NULL;
     Py_ssize_t len;
     PyObject *v;
 
     if (obj == NULL) {
-	PyErr_BadInternalCall();
-	return NULL;
+        PyErr_BadInternalCall();
+        return NULL;
     }
 
     if (PyUnicode_Check(obj)) {
-	PyErr_SetString(PyExc_TypeError,
-			"decoding str is not supported");
-	return NULL;
-	}
+        PyErr_SetString(PyExc_TypeError,
+                        "decoding str is not supported");
+        return NULL;
+    }
 
     /* Coerce object */
     if (PyBytes_Check(obj)) {
@@ -1130,34 +1130,34 @@
         len = PyByteArray_GET_SIZE(obj);
     }
     else if (PyObject_AsCharBuffer(obj, &s, &len)) {
-	/* Overwrite the error message with something more useful in
-	   case of a TypeError. */
-	if (PyErr_ExceptionMatches(PyExc_TypeError))
+        /* Overwrite the error message with something more useful in
+           case of a TypeError. */
+        if (PyErr_ExceptionMatches(PyExc_TypeError))
             PyErr_Format(PyExc_TypeError,
-			 "coercing to str: need string or buffer, "
-			 "%.80s found",
-		     Py_TYPE(obj)->tp_name);
-	goto onError;
+                         "coercing to str: need string or buffer, "
+                         "%.80s found",
+                         Py_TYPE(obj)->tp_name);
+        goto onError;
     }
 
     /* Convert to Unicode */
     if (len == 0) {
-	Py_INCREF(unicode_empty);
-	v = (PyObject *)unicode_empty;
+        Py_INCREF(unicode_empty);
+        v = (PyObject *)unicode_empty;
     }
     else
-	v = PyUnicode_Decode(s, len, encoding, errors);
+        v = PyUnicode_Decode(s, len, encoding, errors);
 
     return v;
 
- onError:
+  onError:
     return NULL;
 }
 
 PyObject *PyUnicode_Decode(const char *s,
-			   Py_ssize_t size,
-			   const char *encoding,
-			   const char *errors)
+                           Py_ssize_t size,
+                           const char *encoding,
+                           const char *errors)
 {
     PyObject *buffer = NULL, *unicode;
     Py_buffer info;
@@ -1223,7 +1223,7 @@
     Py_DECREF(buffer);
     return unicode;
 
- onError:
+  onError:
     Py_XDECREF(buffer);
     return NULL;
 }
@@ -1240,7 +1240,7 @@
     }
 
     if (encoding == NULL)
-	encoding = PyUnicode_GetDefaultEncoding();
+        encoding = PyUnicode_GetDefaultEncoding();
 
     /* Decode via the codec registry */
     v = PyCodec_Decode(unicode, encoding, errors);
@@ -1248,7 +1248,7 @@
         goto onError;
     return v;
 
- onError:
+  onError:
     return NULL;
 }
 
@@ -1264,7 +1264,7 @@
     }
 
     if (encoding == NULL)
-	encoding = PyUnicode_GetDefaultEncoding();
+        encoding = PyUnicode_GetDefaultEncoding();
 
     /* Decode via the codec registry */
     v = PyCodec_Decode(unicode, encoding, errors);
@@ -1279,20 +1279,20 @@
     }
     return v;
 
- onError:
+  onError:
     return NULL;
 }
 
 PyObject *PyUnicode_Encode(const Py_UNICODE *s,
-			   Py_ssize_t size,
-			   const char *encoding,
-			   const char *errors)
+                           Py_ssize_t size,
+                           const char *encoding,
+                           const char *errors)
 {
     PyObject *v, *unicode;
 
     unicode = PyUnicode_FromUnicode(s, size);
     if (unicode == NULL)
-	return NULL;
+        return NULL;
     v = PyUnicode_AsEncodedString(unicode, encoding, errors);
     Py_DECREF(unicode);
     return v;
@@ -1310,7 +1310,7 @@
     }
 
     if (encoding == NULL)
-	encoding = PyUnicode_GetDefaultEncoding();
+        encoding = PyUnicode_GetDefaultEncoding();
 
     /* Encode via the codec registry */
     v = PyCodec_Encode(unicode, encoding, errors);
@@ -1318,7 +1318,7 @@
         goto onError;
     return v;
 
- onError:
+  onError:
     return NULL;
 }
 
@@ -1334,20 +1334,20 @@
     }
 
     if (encoding == NULL)
-	encoding = PyUnicode_GetDefaultEncoding();
+        encoding = PyUnicode_GetDefaultEncoding();
 
     /* Shortcuts for common default encodings */
     if (errors == NULL) {
-	if (strcmp(encoding, "utf-8") == 0)
-	    return PyUnicode_AsUTF8String(unicode);
-	else if (strcmp(encoding, "latin-1") == 0)
-	    return PyUnicode_AsLatin1String(unicode);
+        if (strcmp(encoding, "utf-8") == 0)
+            return PyUnicode_AsUTF8String(unicode);
+        else if (strcmp(encoding, "latin-1") == 0)
+            return PyUnicode_AsLatin1String(unicode);
 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
-	else if (strcmp(encoding, "mbcs") == 0)
-	    return PyUnicode_AsMBCSString(unicode);
+        else if (strcmp(encoding, "mbcs") == 0)
+            return PyUnicode_AsMBCSString(unicode);
 #endif
-	else if (strcmp(encoding, "ascii") == 0)
-	    return PyUnicode_AsASCIIString(unicode);
+        else if (strcmp(encoding, "ascii") == 0)
+            return PyUnicode_AsASCIIString(unicode);
         /* During bootstrap, we may need to find the encodings
            package, to load the file system encoding, and require the
            file system encoding in order to load the encodings
@@ -1360,7 +1360,7 @@
         else if (Py_FileSystemDefaultEncoding &&
                  strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
                  !PyThreadState_GET()->interp->codecs_initialized)
-	    return PyUnicode_AsASCIIString(unicode);            
+            return PyUnicode_AsASCIIString(unicode);
     }
 
     /* Encode via the codec registry */
@@ -1408,7 +1408,7 @@
     }
 
     if (encoding == NULL)
-	encoding = PyUnicode_GetDefaultEncoding();
+        encoding = PyUnicode_GetDefaultEncoding();
 
     /* Encode via the codec registry */
     v = PyCodec_Encode(unicode, encoding, errors);
@@ -1423,12 +1423,12 @@
     }
     return v;
 
- onError:
+  onError:
     return NULL;
 }
 
 PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
-					    const char *errors)
+                                            const char *errors)
 {
     PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
     if (v)
@@ -1507,7 +1507,7 @@
     }
     return PyUnicode_AS_UNICODE(unicode);
 
- onError:
+  onError:
     return NULL;
 }
 
@@ -1519,7 +1519,7 @@
     }
     return PyUnicode_GET_SIZE(unicode);
 
- onError:
+  onError:
     return -1;
 }
 
@@ -1548,10 +1548,10 @@
 
 static
 int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
-                 const char *encoding, const char *reason,
-                 const char **input, const char **inend, Py_ssize_t *startinpos,
-                 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
-                 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
+                                     const char *encoding, const char *reason,
+                                     const char **input, const char **inend, Py_ssize_t *startinpos,
+                                     Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
+                                     PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
 {
     static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
 
@@ -1567,35 +1567,35 @@
     int res = -1;
 
     if (*errorHandler == NULL) {
-	*errorHandler = PyCodec_LookupError(errors);
-	if (*errorHandler == NULL)
-	   goto onError;
+        *errorHandler = PyCodec_LookupError(errors);
+        if (*errorHandler == NULL)
+            goto onError;
     }
 
     if (*exceptionObject == NULL) {
-    	*exceptionObject = PyUnicodeDecodeError_Create(
-	    encoding, *input, *inend-*input, *startinpos, *endinpos, reason);
-	if (*exceptionObject == NULL)
-	   goto onError;
+        *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;
+        if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos))
+            goto onError;
+        if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos))
+            goto onError;
+        if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
+            goto onError;
     }
 
     restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
     if (restuple == NULL)
-	goto onError;
+        goto onError;
     if (!PyTuple_Check(restuple)) {
-	PyErr_Format(PyExc_TypeError, &argparse[4]);
-	goto onError;
+        PyErr_Format(PyExc_TypeError, &argparse[4]);
+        goto onError;
     }
     if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
-	goto onError;
+        goto onError;
 
     /* Copy back the bytes variables, which might have been modified by the
        callback */
@@ -1603,7 +1603,7 @@
     if (!inputobj)
         goto onError;
     if (!PyBytes_Check(inputobj)) {
-	PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
+        PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
     }
     *input = PyBytes_AS_STRING(inputobj);
     insize = PyBytes_GET_SIZE(inputobj);
@@ -1613,10 +1613,10 @@
     Py_DECREF(inputobj);
 
     if (newpos<0)
-	newpos = insize+newpos;
+        newpos = insize+newpos;
     if (newpos<0 || newpos>insize) {
-	PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
-	goto onError;
+        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
+        goto onError;
     }
 
     /* need more space? (at least enough for what we
@@ -1627,11 +1627,11 @@
     repsize = PyUnicode_GET_SIZE(repunicode);
     requiredsize = *outpos + repsize + insize-newpos;
     if (requiredsize > outsize) {
-	if (requiredsize<2*outsize)
-	    requiredsize = 2*outsize;
-	if (_PyUnicode_Resize(output, requiredsize) < 0)
-	    goto onError;
-	*outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
+        if (requiredsize<2*outsize)
+            requiredsize = 2*outsize;
+        if (_PyUnicode_Resize(output, requiredsize) < 0)
+            goto onError;
+        *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
     }
     *endinpos = newpos;
     *inptr = *input + newpos;
@@ -1642,7 +1642,7 @@
     /* we made it! */
     res = 0;
 
-    onError:
+  onError:
     Py_XDECREF(restuple);
     return res;
 }
@@ -1655,10 +1655,10 @@
 char utf7_special[128] = {
     /* indicate whether a UTF-7 character is special i.e. cannot be directly
        encoded:
-	   0 - not special
-	   1 - special
-	   2 - whitespace (optional)
-	   3 - RFC2152 Set O (optional) */
+       0 - not special
+       1 - special
+       2 - whitespace (optional)
+       3 - RFC2152 Set O (optional) */
     1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1,
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
     2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 1, 0, 0, 0, 1,
@@ -1675,17 +1675,17 @@
    utf7_special[0] is 1, we can safely make that one comparison
    true  */
 
-#define SPECIAL(c, encodeO, encodeWS) \
+#define SPECIAL(c, encodeO, encodeWS)                   \
     ((c) > 127 || (c) <= 0 || utf7_special[(c)] == 1 || \
-     (encodeWS && (utf7_special[(c)] == 2)) || \
+     (encodeWS && (utf7_special[(c)] == 2)) ||          \
      (encodeO && (utf7_special[(c)] == 3)))
 
-#define B64(n)  \
+#define B64(n)                                                          \
     ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
-#define B64CHAR(c) \
+#define B64CHAR(c)                              \
     (ISALNUM(c) || (c) == '+' || (c) == '/')
-#define UB64(c) \
-    ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ?                   \
+#define UB64(c)                                         \
+    ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ?   \
      (c) - 71 : (c) >= 'A' ? (c) - 65 : (c) + 4 )
 
 #define ENCODE(out, ch, bits)                   \
@@ -1714,16 +1714,16 @@
     }
 
 PyObject *PyUnicode_DecodeUTF7(const char *s,
-			       Py_ssize_t size,
-			       const char *errors)
+                               Py_ssize_t size,
+                               const char *errors)
 {
     return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
 }
 
 PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
-			       Py_ssize_t size,
-			       const char *errors,
-			       Py_ssize_t *consumed)
+                                       Py_ssize_t size,
+                                       const char *errors,
+                                       Py_ssize_t *consumed)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -1754,7 +1754,7 @@
 
     while (s < e) {
         Py_UNICODE ch;
-        restart:
+      restart:
         ch = (unsigned char) *s;
 
         if (inShift) {
@@ -1788,7 +1788,7 @@
                     }
                 } else if (SPECIAL(ch,0,0)) {
                     errmsg = "unexpected special character";
-	                goto utf7Error;
+                    goto utf7Error;
                 } else  {
                     *p++ = ch;
                 }
@@ -1822,28 +1822,28 @@
             s++;
         }
         continue;
-    utf7Error:
+      utf7Error:
         outpos = p-PyUnicode_AS_UNICODE(unicode);
         endinpos = s-starts;
         if (unicode_decode_call_errorhandler(
-             errors, &errorHandler,
-             "utf7", errmsg,
-             &starts, &e, &startinpos, &endinpos, &exc, &s,
-             &unicode, &outpos, &p))
-        goto onError;
+                errors, &errorHandler,
+                "utf7", errmsg,
+                &starts, &e, &startinpos, &endinpos, &exc, &s,
+                &unicode, &outpos, &p))
+            goto onError;
     }
 
     if (inShift && !consumed) {
         outpos = p-PyUnicode_AS_UNICODE(unicode);
         endinpos = size;
         if (unicode_decode_call_errorhandler(
-             errors, &errorHandler,
-             "utf7", "unterminated shift sequence",
-             &starts, &e, &startinpos, &endinpos, &exc, &s,
-             &unicode, &outpos, &p))
+                errors, &errorHandler,
+                "utf7", "unterminated shift sequence",
+                &starts, &e, &startinpos, &endinpos, &exc, &s,
+                &unicode, &outpos, &p))
             goto onError;
         if (s < e)
-           goto restart;
+            goto restart;
     }
     if (consumed) {
         if(inShift)
@@ -1859,7 +1859,7 @@
     Py_XDECREF(exc);
     return (PyObject *)unicode;
 
-onError:
+  onError:
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     Py_DECREF(unicode);
@@ -1868,10 +1868,10 @@
 
 
 PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
-                   Py_ssize_t size,
-                   int encodeSetO,
-                   int encodeWhiteSpace,
-                   const char *errors)
+                               Py_ssize_t size,
+                               int encodeSetO,
+                               int encodeWhiteSpace,
+                               const char *errors)
 {
     PyObject *v;
     /* It might be possible to tighten this worst case */
@@ -1884,7 +1884,7 @@
     char * start;
 
     if (size == 0)
-       return PyBytes_FromStringAndSize(NULL, 0);
+        return PyBytes_FromStringAndSize(NULL, 0);
 
     if (cbAllocated / 5 != size)
         return PyErr_NoMemory();
@@ -1995,8 +1995,8 @@
 };
 
 PyObject *PyUnicode_DecodeUTF8(const char *s,
-			       Py_ssize_t size,
-			       const char *errors)
+                               Py_ssize_t size,
+                               const char *errors)
 {
     return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
 }
@@ -2015,9 +2015,9 @@
 #endif
 
 PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
-			                Py_ssize_t size,
-			                const char *errors,
-			                Py_ssize_t *consumed)
+                                       Py_ssize_t size,
+                                       const char *errors,
+                                       Py_ssize_t *consumed)
 {
     const char *starts = s;
     int n;
@@ -2099,72 +2099,72 @@
         n = utf8_code_length[ch];
 
         if (s + n > e) {
-	    if (consumed)
-		break;
-	    else {
-		errmsg = "unexpected end of data";
-		startinpos = s-starts;
-		endinpos = size;
-		goto utf8Error;
-	    }
-	}
+            if (consumed)
+                break;
+            else {
+                errmsg = "unexpected end of data";
+                startinpos = s-starts;
+                endinpos = size;
+                goto utf8Error;
+            }
+        }
 
         switch (n) {
 
         case 0:
             errmsg = "unexpected code byte";
-	    startinpos = s-starts;
-	    endinpos = startinpos+1;
-	    goto utf8Error;
+            startinpos = s-starts;
+            endinpos = startinpos+1;
+            goto utf8Error;
 
         case 1:
             errmsg = "internal error";
-	    startinpos = s-starts;
-	    endinpos = startinpos+1;
-	    goto utf8Error;
+            startinpos = s-starts;
+            endinpos = startinpos+1;
+            goto utf8Error;
 
         case 2:
             if ((s[1] & 0xc0) != 0x80) {
                 errmsg = "invalid data";
-		startinpos = s-starts;
-		endinpos = startinpos+2;
-		goto utf8Error;
-	    }
+                startinpos = s-starts;
+                endinpos = startinpos+2;
+                goto utf8Error;
+            }
             ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
             if (ch < 0x80) {
-		startinpos = s-starts;
-		endinpos = startinpos+2;
+                startinpos = s-starts;
+                endinpos = startinpos+2;
                 errmsg = "illegal encoding";
-		goto utf8Error;
-	    }
-	    else
-		*p++ = (Py_UNICODE)ch;
+                goto utf8Error;
+            }
+            else
+                *p++ = (Py_UNICODE)ch;
             break;
 
         case 3:
             if ((s[1] & 0xc0) != 0x80 ||
                 (s[2] & 0xc0) != 0x80) {
                 errmsg = "invalid data";
-		startinpos = s-starts;
-		endinpos = startinpos+3;
-		goto utf8Error;
-	    }
+                startinpos = s-starts;
+                endinpos = startinpos+3;
+                goto utf8Error;
+            }
             ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
             if (ch < 0x0800) {
-		/* Note: UTF-8 encodings of surrogates are considered
-		   legal UTF-8 sequences;
+                /* Note: UTF-8 encodings of surrogates are considered
+                   legal UTF-8 sequences;
 
-		   XXX For wide builds (UCS-4) we should probably try
-		       to recombine the surrogates into a single code
-		       unit.
-		*/
+                   XXX For wide builds (UCS-4) we should probably try
+                   to recombine the surrogates into a single code
+                   unit.
+                */
                 errmsg = "illegal encoding";
-		startinpos = s-starts;
-		endinpos = startinpos+3;
-		goto utf8Error;
-	    }
-	    else
-		*p++ = (Py_UNICODE)ch;
+                startinpos = s-starts;
+                endinpos = startinpos+3;
+                goto utf8Error;
+            }
+            else
+                *p++ = (Py_UNICODE)ch;
             break;
 
         case 4:
@@ -2172,25 +2172,25 @@
                 (s[2] & 0xc0) != 0x80 ||
                 (s[3] & 0xc0) != 0x80) {
                 errmsg = "invalid data";
-		startinpos = s-starts;
-		endinpos = startinpos+4;
-		goto utf8Error;
-	    }
+                startinpos = s-starts;
+                endinpos = startinpos+4;
+                goto utf8Error;
+            }
             ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
-                 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
+                ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
             /* validate and convert to UTF-16 */
             if ((ch < 0x10000)        /* minimum value allowed for 4
-					 byte encoding */
+                                         byte encoding */
                 || (ch > 0x10ffff))   /* maximum value allowed for
-					 UTF-16 */
-	    {
+                                         UTF-16 */
+            {
                 errmsg = "illegal encoding";
-		startinpos = s-starts;
-		endinpos = startinpos+4;
-		goto utf8Error;
-	    }
+                startinpos = s-starts;
+                endinpos = startinpos+4;
+                goto utf8Error;
+            }
 #ifdef Py_UNICODE_WIDE
-	    *p++ = (Py_UNICODE)ch;
+            *p++ = (Py_UNICODE)ch;
 #else
             /*  compute and append the two surrogates: */
 
@@ -2208,25 +2208,25 @@
         default:
             /* Other sizes are only needed for UCS-4 */
             errmsg = "unsupported Unicode code range";
-	    startinpos = s-starts;
-	    endinpos = startinpos+n;
-	    goto utf8Error;
+            startinpos = s-starts;
+            endinpos = startinpos+n;
+            goto utf8Error;
         }
         s += n;
-	continue;
+        continue;
 
-    utf8Error:
-    outpos = p-PyUnicode_AS_UNICODE(unicode);
-    if (unicode_decode_call_errorhandler(
-	     errors, &errorHandler,
-	     "utf8", errmsg,
-	     &starts, &e, &startinpos, &endinpos, &exc, &s,
-	     &unicode, &outpos, &p))
-	goto onError;
-	aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
+      utf8Error:
+        outpos = p-PyUnicode_AS_UNICODE(unicode);
+        if (unicode_decode_call_errorhandler(
+                errors, &errorHandler,
+                "utf8", errmsg,
+                &starts, &e, &startinpos, &endinpos, &exc, &s,
+                &unicode, &outpos, &p))
+            goto onError;
+        aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
     }
     if (consumed)
-	*consumed = s-starts;
+        *consumed = s-starts;
 
     /* Adjust length */
     if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
@@ -2236,7 +2236,7 @@
     Py_XDECREF(exc);
     return (PyObject *)unicode;
 
-onError:
+  onError:
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     Py_DECREF(unicode);
@@ -2253,8 +2253,8 @@
 */
 PyObject *
 PyUnicode_EncodeUTF8(const Py_UNICODE *s,
-		     Py_ssize_t size,
-		     const char *errors)
+                     Py_ssize_t size,
+                     const char *errors)
 {
 #define MAX_SHORT_UNICHARS 300  /* largest size we'll do on the stack */
 
@@ -2319,8 +2319,8 @@
                 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
                 *p++ = (char)(0x80 | (ch & 0x3f));
                 continue;
-    	    }
-encodeUCS4:
+            }
+          encodeUCS4:
             /* Encode UCS4 Unicode ordinals */
             *p++ = (char)(0xf0 | (ch >> 18));
             *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
@@ -2353,27 +2353,27 @@
         return NULL;
     }
     return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
-				PyUnicode_GET_SIZE(unicode),
-				NULL);
+                                PyUnicode_GET_SIZE(unicode),
+                                NULL);
 }
 
 /* --- UTF-32 Codec ------------------------------------------------------- */
 
 PyObject *
 PyUnicode_DecodeUTF32(const char *s,
-		      Py_ssize_t size,
-		      const char *errors,
-		      int *byteorder)
+                      Py_ssize_t size,
+                      const char *errors,
+                      int *byteorder)
 {
     return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
 }
 
 PyObject *
 PyUnicode_DecodeUTF32Stateful(const char *s,
-			      Py_ssize_t size,
-			      const char *errors,
-			      int *byteorder,
-			      Py_ssize_t *consumed)
+                              Py_ssize_t size,
+                              const char *errors,
+                              int *byteorder,
+                              Py_ssize_t *consumed)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -2401,8 +2401,8 @@
        codepoints => count how much extra space we need. */
 #ifndef Py_UNICODE_WIDE
     for (i = pairs = 0; i < size/4; i++)
-	if (((Py_UCS4 *)s)[i] >= 0x10000)
-	    pairs++;
+        if (((Py_UCS4 *)s)[i] >= 0x10000)
+            pairs++;
 #endif
 
     /* This might be one to much, because of a BOM */
@@ -2427,27 +2427,27 @@
     if (bo == 0) {
         if (size >= 4) {
             const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
-                                (q[iorder[1]] << 8) | q[iorder[0]];
+                (q[iorder[1]] << 8) | q[iorder[0]];
 #ifdef BYTEORDER_IS_LITTLE_ENDIAN
-	    if (bom == 0x0000FEFF) {
-		q += 4;
-		bo = -1;
-	    }
-	    else if (bom == 0xFFFE0000) {
-		q += 4;
-		bo = 1;
-	    }
+            if (bom == 0x0000FEFF) {
+                q += 4;
+                bo = -1;
+            }
+            else if (bom == 0xFFFE0000) {
+                q += 4;
+                bo = 1;
+            }
 #else
-	    if (bom == 0x0000FEFF) {
-		q += 4;
-		bo = 1;
-	    }
-	    else if (bom == 0xFFFE0000) {
-		q += 4;
-		bo = -1;
-	    }
+            if (bom == 0x0000FEFF) {
+                q += 4;
+                bo = 1;
+            }
+            else if (bom == 0xFFFE0000) {
+                q += 4;
+                bo = -1;
+            }
 #endif
-	}
+        }
     }
 
     if (bo == -1) {
@@ -2466,54 +2466,54 @@
     }
 
     while (q < e) {
-	Py_UCS4 ch;
-	/* remaining bytes at the end? (size should be divisible by 4) */
-	if (e-q<4) {
-	    if (consumed)
-		break;
-	    errmsg = "truncated data";
-	    startinpos = ((const char *)q)-starts;
-	    endinpos = ((const char *)e)-starts;
-	    goto utf32Error;
-	    /* The remaining input chars are ignored if the callback
-	       chooses to skip the input */
-	}
-	ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
-	     (q[iorder[1]] << 8) | q[iorder[0]];
-
-	if (ch >= 0x110000)
-	{
-	    errmsg = "codepoint not in range(0x110000)";
-	    startinpos = ((const char *)q)-starts;
-	    endinpos = startinpos+4;
-	    goto utf32Error;
-	}
+        Py_UCS4 ch;
+        /* remaining bytes at the end? (size should be divisible by 4) */
+        if (e-q<4) {
+            if (consumed)
+                break;
+            errmsg = "truncated data";
+            startinpos = ((const char *)q)-starts;
+            endinpos = ((const char *)e)-starts;
+            goto utf32Error;
+            /* The remaining input chars are ignored if the callback
+               chooses to skip the input */
+        }
+        ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
+            (q[iorder[1]] << 8) | q[iorder[0]];
+
+        if (ch >= 0x110000)
+        {
+            errmsg = "codepoint not in range(0x110000)";
+            startinpos = ((const char *)q)-starts;
+            endinpos = startinpos+4;
+            goto utf32Error;
+        }
 #ifndef Py_UNICODE_WIDE
-	if (ch >= 0x10000)
-	{
-	    *p++ = 0xD800 | ((ch-0x10000) >> 10);
-	    *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
-	}
-	else
-#endif
-	    *p++ = ch;
-	q += 4;
-	continue;
-    utf32Error:
-	outpos = p-PyUnicode_AS_UNICODE(unicode);
-	if (unicode_decode_call_errorhandler(
-	         errors, &errorHandler,
-	         "utf32", errmsg,
-	         &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
-	         &unicode, &outpos, &p))
-	    goto onError;
+        if (ch >= 0x10000)
+        {
+            *p++ = 0xD800 | ((ch-0x10000) >> 10);
+            *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
+        }
+        else
+#endif
+            *p++ = ch;
+        q += 4;
+        continue;
+      utf32Error:
+        outpos = p-PyUnicode_AS_UNICODE(unicode);
+        if (unicode_decode_call_errorhandler(
+                errors, &errorHandler,
+                "utf32", errmsg,
+                &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
+                &unicode, &outpos, &p))
+            goto onError;
     }
 
     if (byteorder)
         *byteorder = bo;
 
     if (consumed)
-	*consumed = (const char *)q-starts;
+        *consumed = (const char *)q-starts;
 
     /* Adjust length */
     if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
@@ -2523,7 +2523,7 @@
     Py_XDECREF(exc);
     return (PyObject *)unicode;
 
-onError:
+  onError:
     Py_DECREF(unicode);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
@@ -2532,9 +2532,9 @@
 
 PyObject *
 PyUnicode_EncodeUTF32(const Py_UNICODE *s,
-		      Py_ssize_t size,
-		      const char *errors,
-		      int byteorder)
+                      Py_ssize_t size,
+                      const char *errors,
+                      int byteorder)
 {
     PyObject *v;
     unsigned char *p;
@@ -2551,34 +2551,34 @@
     int iorder[] = {3, 2, 1, 0};
 #endif
 
-#define STORECHAR(CH)                       \
-    do {                                    \
-        p[iorder[3]] = ((CH) >> 24) & 0xff; \
-        p[iorder[2]] = ((CH) >> 16) & 0xff; \
-        p[iorder[1]] = ((CH) >> 8) & 0xff;  \
-        p[iorder[0]] = (CH) & 0xff;         \
-        p += 4;                             \
+#define STORECHAR(CH)                           \
+    do {                                        \
+        p[iorder[3]] = ((CH) >> 24) & 0xff;     \
+        p[iorder[2]] = ((CH) >> 16) & 0xff;     \
+        p[iorder[1]] = ((CH) >> 8) & 0xff;      \
+        p[iorder[0]] = (CH) & 0xff;             \
+        p += 4;                                 \
     } while(0)
 
     /* In narrow builds we can output surrogate pairs as one codepoint,
        so we need less space. */
 #ifndef Py_UNICODE_WIDE
     for (i = pairs = 0; i < size-1; i++)
-	if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
-	    0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
-	    pairs++;
+        if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
+            0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
+            pairs++;
 #endif
     nsize = (size - pairs + (byteorder == 0));
     bytesize = nsize * 4;
     if (bytesize / 4 != nsize)
-	return PyErr_NoMemory();
+        return PyErr_NoMemory();
     v = PyBytes_FromStringAndSize(NULL, bytesize);
     if (v == NULL)
         return NULL;
 
     p = (unsigned char *)PyBytes_AS_STRING(v);
     if (byteorder == 0)
-	STORECHAR(0xFEFF);
+        STORECHAR(0xFEFF);
     if (size == 0)
         goto done;
 
@@ -2598,16 +2598,16 @@
     }
 
     while (size-- > 0) {
-	Py_UCS4 ch = *s++;
+        Py_UCS4 ch = *s++;
 #ifndef Py_UNICODE_WIDE
-	if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
-	    Py_UCS4 ch2 = *s;
-	    if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
-		ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
-		s++;
-		size--;
-	    }
-	}
+        if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
+            Py_UCS4 ch2 = *s;
+            if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
+                ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
+                s++;
+                size--;
+            }
+        }
 #endif
         STORECHAR(ch);
     }
@@ -2624,18 +2624,18 @@
         return NULL;
     }
     return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
-				 PyUnicode_GET_SIZE(unicode),
-				 NULL,
-				 0);
+                                 PyUnicode_GET_SIZE(unicode),
+                                 NULL,
+                                 0);
 }
 
 /* --- UTF-16 Codec ------------------------------------------------------- */
 
 PyObject *
 PyUnicode_DecodeUTF16(const char *s,
-		      Py_ssize_t size,
-		      const char *errors,
-		      int *byteorder)
+                      Py_ssize_t size,
+                      const char *errors,
+                      int *byteorder)
 {
     return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
 }
@@ -2646,7 +2646,7 @@
    rare in most input.
    FAST_CHAR_MASK is used when the input is in native byte ordering,
    SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
-   */
+*/
 #if (SIZEOF_LONG == 8)
 # define FAST_CHAR_MASK         0x8000800080008000L
 # define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
@@ -2659,10 +2659,10 @@
 
 PyObject *
 PyUnicode_DecodeUTF16Stateful(const char *s,
-			      Py_ssize_t size,
-			      const char *errors,
-			      int *byteorder,
-			      Py_ssize_t *consumed)
+                              Py_ssize_t size,
+                              const char *errors,
+                              int *byteorder,
+                              Py_ssize_t *consumed)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -2707,25 +2707,25 @@
         if (size >= 2) {
             const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
 #ifdef BYTEORDER_IS_LITTLE_ENDIAN
-	    if (bom == 0xFEFF) {
-		q += 2;
-		bo = -1;
-	    }
-	    else if (bom == 0xFFFE) {
-		q += 2;
-		bo = 1;
-	    }
+            if (bom == 0xFEFF) {
+                q += 2;
+                bo = -1;
+            }
+            else if (bom == 0xFFFE) {
+                q += 2;
+                bo = 1;
+            }
 #else
-	    if (bom == 0xFEFF) {
-		q += 2;
-		bo = 1;
-	    }
-	    else if (bom == 0xFFFE) {
-		q += 2;
-		bo = -1;
-	    }
+            if (bom == 0xFEFF) {
+                q += 2;
+                bo = 1;
+            }
+            else if (bom == 0xFFFE) {
+                q += 2;
+                bo = -1;
+            }
 #endif
-	}
+        }
     }
 
     if (bo == -1) {
@@ -2746,7 +2746,7 @@
 
     aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
     while (q < e) {
-	Py_UNICODE ch;
+        Py_UNICODE ch;
         /* First check for possible aligned read of a C 'long'. Unaligned
            reads are more expensive, better to defer to another iteration. */
         if (!((size_t) q & LONG_PTR_MASK)) {
@@ -2818,50 +2818,50 @@
             if (q >= e)
                 break;
         }
-	ch = (q[ihi] << 8) | q[ilo];
+        ch = (q[ihi] << 8) | q[ilo];
+
+        q += 2;
 
-	q += 2;
+        if (ch < 0xD800 || ch > 0xDFFF) {
+            *p++ = ch;
+            continue;
+        }
 
-	if (ch < 0xD800 || ch > 0xDFFF) {
-	    *p++ = ch;
-	    continue;
-	}
-
-	/* UTF-16 code pair: */
-	if (q > e) {
-	    errmsg = "unexpected end of data";
-	    startinpos = (((const char *)q) - 2) - starts;
-	    endinpos = ((const char *)e) + 1 - starts;
-	    goto utf16Error;
-	}
-	if (0xD800 <= ch && ch <= 0xDBFF) {
-	    Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
-	    q += 2;
-	    if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
+        /* UTF-16 code pair: */
+        if (q > e) {
+            errmsg = "unexpected end of data";
+            startinpos = (((const char *)q) - 2) - starts;
+            endinpos = ((const char *)e) + 1 - starts;
+            goto utf16Error;
+        }
+        if (0xD800 <= ch && ch <= 0xDBFF) {
+            Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
+            q += 2;
+            if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
 #ifndef Py_UNICODE_WIDE
-		*p++ = ch;
-		*p++ = ch2;
+                *p++ = ch;
+                *p++ = ch2;
 #else
-		*p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
+                *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
 #endif
-		continue;
-	    }
-	    else {
+                continue;
+            }
+            else {
                 errmsg = "illegal UTF-16 surrogate";
-		startinpos = (((const char *)q)-4)-starts;
-		endinpos = startinpos+2;
-		goto utf16Error;
-	    }
-
-	}
-	errmsg = "illegal encoding";
-	startinpos = (((const char *)q)-2)-starts;
-	endinpos = startinpos+2;
-	/* Fall through to report the error */
-
-    utf16Error:
-	outpos = p - PyUnicode_AS_UNICODE(unicode);
-	if (unicode_decode_call_errorhandler(
+                startinpos = (((const char *)q)-4)-starts;
+                endinpos = startinpos+2;
+                goto utf16Error;
+            }
+
+        }
+        errmsg = "illegal encoding";
+        startinpos = (((const char *)q)-2)-starts;
+        endinpos = startinpos+2;
+        /* Fall through to report the error */
+
+      utf16Error:
+        outpos = p - PyUnicode_AS_UNICODE(unicode);
+        if (unicode_decode_call_errorhandler(
                 errors,
                 &errorHandler,
                 "utf16", errmsg,
@@ -2874,7 +2874,7 @@
                 &unicode,
                 &outpos,
                 &p))
-	    goto onError;
+            goto onError;
     }
     /* remaining byte at the end? (size should be even) */
     if (e == q) {
@@ -2906,7 +2906,7 @@
         *byteorder = bo;
 
     if (consumed)
-	*consumed = (const char *)q-starts;
+        *consumed = (const char *)q-starts;
 
     /* Adjust length */
     if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
@@ -2916,7 +2916,7 @@
     Py_XDECREF(exc);
     return (PyObject *)unicode;
 
-onError:
+  onError:
     Py_DECREF(unicode);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
@@ -2928,9 +2928,9 @@
 
 PyObject *
 PyUnicode_EncodeUTF16(const Py_UNICODE *s,
-		      Py_ssize_t size,
-		      const char *errors,
-		      int byteorder)
+                      Py_ssize_t size,
+                      const char *errors,
+                      int byteorder)
 {
     PyObject *v;
     unsigned char *p;
@@ -2947,33 +2947,33 @@
     int ihi = 0, ilo = 1;
 #endif
 
-#define STORECHAR(CH)                   \
-    do {                                \
-        p[ihi] = ((CH) >> 8) & 0xff;    \
-        p[ilo] = (CH) & 0xff;           \
-        p += 2;                         \
+#define STORECHAR(CH)                           \
+    do {                                        \
+        p[ihi] = ((CH) >> 8) & 0xff;            \
+        p[ilo] = (CH) & 0xff;                   \
+        p += 2;                                 \
     } while(0)
 
 #ifdef Py_UNICODE_WIDE
     for (i = pairs = 0; i < size; i++)
-	if (s[i] >= 0x10000)
-	    pairs++;
+        if (s[i] >= 0x10000)
+            pairs++;
 #endif
     /* 2 * (size + pairs + (byteorder == 0)) */
     if (size > PY_SSIZE_T_MAX ||
         size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
-	return PyErr_NoMemory();
+        return PyErr_NoMemory();
     nsize = size + pairs + (byteorder == 0);
     bytesize = nsize * 2;
     if (bytesize / 2 != nsize)
-	return PyErr_NoMemory();
+        return PyErr_NoMemory();
     v = PyBytes_FromStringAndSize(NULL, bytesize);
     if (v == NULL)
         return NULL;
 
     p = (unsigned char *)PyBytes_AS_STRING(v);
     if (byteorder == 0)
-	STORECHAR(0xFEFF);
+        STORECHAR(0xFEFF);
     if (size == 0)
         goto done;
 
@@ -2989,13 +2989,13 @@
     }
 
     while (size-- > 0) {
-	Py_UNICODE ch = *s++;
-	Py_UNICODE ch2 = 0;
+        Py_UNICODE ch = *s++;
+        Py_UNICODE ch2 = 0;
 #ifdef Py_UNICODE_WIDE
-	if (ch >= 0x10000) {
-	    ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
-	    ch  = 0xD800 | ((ch-0x10000) >> 10);
-	}
+        if (ch >= 0x10000) {
+            ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
+            ch  = 0xD800 | ((ch-0x10000) >> 10);
+        }
 #endif
         STORECHAR(ch);
         if (ch2)
@@ -3014,9 +3014,9 @@
         return NULL;
     }
     return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
-				 PyUnicode_GET_SIZE(unicode),
-				 NULL,
-				 0);
+                                 PyUnicode_GET_SIZE(unicode),
+                                 NULL,
+                                 0);
 }
 
 /* --- Unicode Escape Codec ----------------------------------------------- */
@@ -3024,8 +3024,8 @@
 static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
 
 PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
-					Py_ssize_t size,
-					const char *errors)
+                                        Py_ssize_t size,
+                                        const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -3073,7 +3073,7 @@
             c = '\0'; /* Invalid after \ */
         switch (c) {
 
-        /* \x escapes */
+            /* \x escapes */
         case '\n': break;
         case '\\': *p++ = '\\'; break;
         case '\'': *p++ = '\''; break;
@@ -3086,7 +3086,7 @@
         case 'v': *p++ = '\013'; break; /* VT */
         case 'a': *p++ = '\007'; break; /* BEL, not classic C */
 
-        /* \OOO (octal) escapes */
+            /* \OOO (octal) escapes */
         case '0': case '1': case '2': case '3':
         case '4': case '5': case '6': case '7':
             x = s[-1] - '0';
@@ -3098,20 +3098,20 @@
             *p++ = x;
             break;
 
-        /* hex escapes */
-        /* \xXX */
+            /* hex escapes */
+            /* \xXX */
         case 'x':
             digits = 2;
             message = "truncated \\xXX escape";
             goto hexescape;
 
-        /* \uXXXX */
+            /* \uXXXX */
         case 'u':
             digits = 4;
             message = "truncated \\uXXXX escape";
             goto hexescape;
 
-        /* \UXXXXXXXX */
+            /* \UXXXXXXXX */
         case 'U':
             digits = 8;
             message = "truncated \\UXXXXXXXX escape";
@@ -3121,10 +3121,10 @@
             if (s+digits>end) {
                 endinpos = size;
                 if (unicode_decode_call_errorhandler(
-                    errors, &errorHandler,
-                    "unicodeescape", "end of string in escape sequence",
-                    &starts, &end, &startinpos, &endinpos, &exc, &s,
-                    &v, &outpos, &p))
+                        errors, &errorHandler,
+                        "unicodeescape", "end of string in escape sequence",
+                        &starts, &end, &startinpos, &endinpos, &exc, &s,
+                        &v, &outpos, &p))
                     goto onError;
                 goto nextByte;
             }
@@ -3133,10 +3133,10 @@
                 if (!ISXDIGIT(c)) {
                     endinpos = (s+i+1)-starts;
                     if (unicode_decode_call_errorhandler(
-                        errors, &errorHandler,
-                        "unicodeescape", message,
-                        &starts, &end, &startinpos, &endinpos, &exc, &s,
-                        &v, &outpos, &p))
+                            errors, &errorHandler,
+                            "unicodeescape", message,
+                            &starts, &end, &startinpos, &endinpos, &exc, &s,
+                            &v, &outpos, &p))
                         goto onError;
                     goto nextByte;
                 }
@@ -3172,15 +3172,15 @@
                 endinpos = s-starts;
                 outpos = p-PyUnicode_AS_UNICODE(v);
                 if (unicode_decode_call_errorhandler(
-                    errors, &errorHandler,
-                    "unicodeescape", "illegal Unicode character",
-                    &starts, &end, &startinpos, &endinpos, &exc, &s,
-                    &v, &outpos, &p))
+                        errors, &errorHandler,
+                        "unicodeescape", "illegal Unicode character",
+                        &starts, &end, &startinpos, &endinpos, &exc, &s,
+                        &v, &outpos, &p))
                     goto onError;
             }
             break;
 
-        /* \N{name} */
+            /* \N{name} */
         case 'N':
             message = "malformed \\N character escape";
             if (ucnhash_CAPI == NULL) {
@@ -3214,10 +3214,10 @@
             endinpos = s-starts;
             outpos = p-PyUnicode_AS_UNICODE(v);
             if (unicode_decode_call_errorhandler(
-                errors, &errorHandler,
-                "unicodeescape", message,
-                &starts, &end, &startinpos, &endinpos, &exc, &s,
-                &v, &outpos, &p))
+                    errors, &errorHandler,
+                    "unicodeescape", message,
+                    &starts, &end, &startinpos, &endinpos, &exc, &s,
+                    &v, &outpos, &p))
                 goto onError;
             break;
 
@@ -3228,10 +3228,10 @@
                 endinpos = s-starts;
                 outpos = p-PyUnicode_AS_UNICODE(v);
                 if (unicode_decode_call_errorhandler(
-                    errors, &errorHandler,
-                    "unicodeescape", message,
-                    &starts, &end, &startinpos, &endinpos, &exc, &s,
-                    &v, &outpos, &p))
+                        errors, &errorHandler,
+                        "unicodeescape", message,
+                        &starts, &end, &startinpos, &endinpos, &exc, &s,
+                        &v, &outpos, &p))
                     goto onError;
             }
             else {
@@ -3240,7 +3240,7 @@
             }
             break;
         }
-        nextByte:
+      nextByte:
         ;
     }
     if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
@@ -3249,7 +3249,7 @@
     Py_XDECREF(exc);
     return (PyObject *)v;
 
-ucnhashError:
+  ucnhashError:
     PyErr_SetString(
         PyExc_UnicodeError,
         "\\N escapes not supported (can't load unicodedata module)"
@@ -3259,7 +3259,7 @@
     Py_XDECREF(exc);
     return NULL;
 
-onError:
+  onError:
     Py_XDECREF(v);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
@@ -3274,8 +3274,8 @@
 */
 
 Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s,
-                                      Py_ssize_t size,
-                                      Py_UNICODE ch)
+                                             Py_ssize_t size,
+                                             Py_UNICODE ch)
 {
     /* like wcschr, but doesn't stop at NULL characters */
 
@@ -3291,7 +3291,7 @@
 static const char *hexdigits = "0123456789abcdef";
 
 PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
-					Py_ssize_t size)
+                                        Py_ssize_t size)
 {
     PyObject *repr;
     char *p;
@@ -3324,12 +3324,12 @@
         return PyBytes_FromStringAndSize(NULL, 0);
 
     if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
-	return PyErr_NoMemory();
+        return PyErr_NoMemory();
 
     repr = PyBytes_FromStringAndSize(NULL,
-        2
-        + expandsize*size
-        + 1);
+                                     2
+                                     + expandsize*size
+                                     + 1);
     if (repr == NULL)
         return NULL;
 
@@ -3358,34 +3358,34 @@
             *p++ = hexdigits[(ch >> 8) & 0x0000000F];
             *p++ = hexdigits[(ch >> 4) & 0x0000000F];
             *p++ = hexdigits[ch & 0x0000000F];
-	    continue;
+            continue;
         }
 #else
-	/* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
-	else if (ch >= 0xD800 && ch < 0xDC00) {
-	    Py_UNICODE ch2;
-	    Py_UCS4 ucs;
-
-	    ch2 = *s++;
-	    size--;
-	    if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
-		ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
-		*p++ = '\\';
-		*p++ = 'U';
-		*p++ = hexdigits[(ucs >> 28) & 0x0000000F];
-		*p++ = hexdigits[(ucs >> 24) & 0x0000000F];
-		*p++ = hexdigits[(ucs >> 20) & 0x0000000F];
-		*p++ = hexdigits[(ucs >> 16) & 0x0000000F];
-		*p++ = hexdigits[(ucs >> 12) & 0x0000000F];
-		*p++ = hexdigits[(ucs >> 8) & 0x0000000F];
-		*p++ = hexdigits[(ucs >> 4) & 0x0000000F];
-		*p++ = hexdigits[ucs & 0x0000000F];
-		continue;
-	    }
-	    /* Fall through: isolated surrogates are copied as-is */
-	    s--;
-	    size++;
-	}
+        /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
+        else if (ch >= 0xD800 && ch < 0xDC00) {
+            Py_UNICODE ch2;
+            Py_UCS4 ucs;
+
+            ch2 = *s++;
+            size--;
+            if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
+                ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
+                *p++ = '\\';
+                *p++ = 'U';
+                *p++ = hexdigits[(ucs >> 28) & 0x0000000F];
+                *p++ = hexdigits[(ucs >> 24) & 0x0000000F];
+                *p++ = hexdigits[(ucs >> 20) & 0x0000000F];
+                *p++ = hexdigits[(ucs >> 16) & 0x0000000F];
+                *p++ = hexdigits[(ucs >> 12) & 0x0000000F];
+                *p++ = hexdigits[(ucs >> 8) & 0x0000000F];
+                *p++ = hexdigits[(ucs >> 4) & 0x0000000F];
+                *p++ = hexdigits[ucs & 0x0000000F];
+                continue;
+            }
+            /* Fall through: isolated surrogates are copied as-is */
+            s--;
+            size++;
+        }
 #endif
 
         /* Map 16-bit characters to '\uxxxx' */
@@ -3446,8 +3446,8 @@
 /* --- Raw Unicode Escape Codec ------------------------------------------- */
 
 PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
-					   Py_ssize_t size,
-					   const char *errors)
+                                           Py_ssize_t size,
+                                           const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -3466,75 +3466,75 @@
        handler might have to resize the string) */
     v = _PyUnicode_New(size);
     if (v == NULL)
-	goto onError;
+        goto onError;
     if (size == 0)
-	return (PyObject *)v;
+        return (PyObject *)v;
     p = PyUnicode_AS_UNICODE(v);
     end = s + size;
     while (s < end) {
-	unsigned char c;
-	Py_UCS4 x;
-	int i;
+        unsigned char c;
+        Py_UCS4 x;
+        int i;
         int count;
 
-	/* Non-escape characters are interpreted as Unicode ordinals */
-	if (*s != '\\') {
-	    *p++ = (unsigned char)*s++;
-	    continue;
-	}
-	startinpos = s-starts;
-
-	/* \u-escapes are only interpreted iff the number of leading
-	   backslashes if odd */
-	bs = s;
-	for (;s < end;) {
-	    if (*s != '\\')
-		break;
-	    *p++ = (unsigned char)*s++;
-	}
-	if (((s - bs) & 1) == 0 ||
-	    s >= end ||
-	    (*s != 'u' && *s != 'U')) {
-	    continue;
-	}
-	p--;
+        /* Non-escape characters are interpreted as Unicode ordinals */
+        if (*s != '\\') {
+            *p++ = (unsigned char)*s++;
+            continue;
+        }
+        startinpos = s-starts;
+
+        /* \u-escapes are only interpreted iff the number of leading
+           backslashes if odd */
+        bs = s;
+        for (;s < end;) {
+            if (*s != '\\')
+                break;
+            *p++ = (unsigned char)*s++;
+        }
+        if (((s - bs) & 1) == 0 ||
+            s >= end ||
+            (*s != 'u' && *s != 'U')) {
+            continue;
+        }
+        p--;
         count = *s=='u' ? 4 : 8;
-	s++;
+        s++;
 
-	/* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
-	outpos = p-PyUnicode_AS_UNICODE(v);
-	for (x = 0, i = 0; i < count; ++i, ++s) {
-	    c = (unsigned char)*s;
-	    if (!ISXDIGIT(c)) {
-		endinpos = s-starts;
-		if (unicode_decode_call_errorhandler(
-		    errors, &errorHandler,
-		    "rawunicodeescape", "truncated \\uXXXX",
-		    &starts, &end, &startinpos, &endinpos, &exc, &s,
-		    &v, &outpos, &p))
-		    goto onError;
-		goto nextByte;
-	    }
-	    x = (x<<4) & ~0xF;
-	    if (c >= '0' && c <= '9')
-		x += c - '0';
-	    else if (c >= 'a' && c <= 'f')
-		x += 10 + c - 'a';
-	    else
-		x += 10 + c - 'A';
-	}
+        /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
+        outpos = p-PyUnicode_AS_UNICODE(v);
+        for (x = 0, i = 0; i < count; ++i, ++s) {
+            c = (unsigned char)*s;
+            if (!ISXDIGIT(c)) {
+                endinpos = s-starts;
+                if (unicode_decode_call_errorhandler(
+                        errors, &errorHandler,
+                        "rawunicodeescape", "truncated \\uXXXX",
+                        &starts, &end, &startinpos, &endinpos, &exc, &s,
+                        &v, &outpos, &p))
+                    goto onError;
+                goto nextByte;
+            }
+            x = (x<<4) & ~0xF;
+            if (c >= '0' && c <= '9')
+                x += c - '0';
+            else if (c >= 'a' && c <= 'f')
+                x += 10 + c - 'a';
+            else
+                x += 10 + c - 'A';
+        }
         if (x <= 0xffff)
-                /* UCS-2 character */
-                *p++ = (Py_UNICODE) x;
+            /* UCS-2 character */
+            *p++ = (Py_UNICODE) x;
         else if (x <= 0x10ffff) {
-                /* UCS-4 character. Either store directly, or as
-                   surrogate pair. */
+            /* UCS-4 character. Either store directly, or as
+               surrogate pair. */
 #ifdef Py_UNICODE_WIDE
-                *p++ = (Py_UNICODE) x;
+            *p++ = (Py_UNICODE) x;
 #else
-                x -= 0x10000L;
-                *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
-                *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
+            x -= 0x10000L;
+            *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
+            *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
 #endif
         } else {
             endinpos = s-starts;
@@ -3542,20 +3542,20 @@
             if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "rawunicodeescape", "\\Uxxxxxxxx out of range",
-		    &starts, &end, &startinpos, &endinpos, &exc, &s,
-		    &v, &outpos, &p))
-		    goto onError;
+                    &starts, &end, &startinpos, &endinpos, &exc, &s,
+                    &v, &outpos, &p))
+                goto onError;
         }
-	nextByte:
-	;
+      nextByte:
+        ;
     }
     if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
-	goto onError;
+        goto onError;
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     return (PyObject *)v;
 
- onError:
+  onError:
     Py_XDECREF(v);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
@@ -3563,7 +3563,7 @@
 }
 
 PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
-					   Py_ssize_t size)
+                                           Py_ssize_t size)
 {
     PyObject *repr;
     char *p;
@@ -3574,10 +3574,10 @@
 #else
     const Py_ssize_t expandsize = 6;
 #endif
-    
+
     if (size > PY_SSIZE_T_MAX / expandsize)
-	return PyErr_NoMemory();
-    
+        return PyErr_NoMemory();
+
     repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
     if (repr == NULL)
         return NULL;
@@ -3588,8 +3588,8 @@
     while (size-- > 0) {
         Py_UNICODE ch = *s++;
 #ifdef Py_UNICODE_WIDE
-	/* Map 32-bit characters to '\Uxxxxxxxx' */
-	if (ch >= 0x10000) {
+        /* Map 32-bit characters to '\Uxxxxxxxx' */
+        if (ch >= 0x10000) {
             *p++ = '\\';
             *p++ = 'U';
             *p++ = hexdigits[(ch >> 28) & 0xf];
@@ -3603,34 +3603,34 @@
         }
         else
 #else
-	/* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
-	if (ch >= 0xD800 && ch < 0xDC00) {
-	    Py_UNICODE ch2;
-	    Py_UCS4 ucs;
-
-	    ch2 = *s++;
-	    size--;
-	    if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
-		ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
-		*p++ = '\\';
-		*p++ = 'U';
-		*p++ = hexdigits[(ucs >> 28) & 0xf];
-		*p++ = hexdigits[(ucs >> 24) & 0xf];
-		*p++ = hexdigits[(ucs >> 20) & 0xf];
-		*p++ = hexdigits[(ucs >> 16) & 0xf];
-		*p++ = hexdigits[(ucs >> 12) & 0xf];
-		*p++ = hexdigits[(ucs >> 8) & 0xf];
-		*p++ = hexdigits[(ucs >> 4) & 0xf];
-		*p++ = hexdigits[ucs & 0xf];
-		continue;
-	    }
-	    /* Fall through: isolated surrogates are copied as-is */
-	    s--;
-	    size++;
-	}
+            /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
+            if (ch >= 0xD800 && ch < 0xDC00) {
+                Py_UNICODE ch2;
+                Py_UCS4 ucs;
+
+                ch2 = *s++;
+                size--;
+                if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
+                    ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
+                    *p++ = '\\';
+                    *p++ = 'U';
+                    *p++ = hexdigits[(ucs >> 28) & 0xf];
+                    *p++ = hexdigits[(ucs >> 24) & 0xf];
+                    *p++ = hexdigits[(ucs >> 20) & 0xf];
+                    *p++ = hexdigits[(ucs >> 16) & 0xf];
+                    *p++ = hexdigits[(ucs >> 12) & 0xf];
+                    *p++ = hexdigits[(ucs >> 8) & 0xf];
+                    *p++ = hexdigits[(ucs >> 4) & 0xf];
+                    *p++ = hexdigits[ucs & 0xf];
+                    continue;
+                }
+                /* Fall through: isolated surrogates are copied as-is */
+                s--;
+                size++;
+            }
 #endif
-	/* Map 16-bit characters to '\uxxxx' */
-	if (ch >= 256) {
+        /* Map 16-bit characters to '\uxxxx' */
+        if (ch >= 256) {
             *p++ = '\\';
             *p++ = 'u';
             *p++ = hexdigits[(ch >> 12) & 0xf];
@@ -3638,8 +3638,8 @@
             *p++ = hexdigits[(ch >> 4) & 0xf];
             *p++ = hexdigits[ch & 15];
         }
-	/* Copy everything else as-is */
-	else
+        /* Copy everything else as-is */
+        else
             *p++ = (char) ch;
     }
     size = p - q;
@@ -3666,8 +3666,8 @@
 /* --- Unicode Internal Codec ------------------------------------------- */
 
 PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
-					   Py_ssize_t size,
-					   const char *errors)
+                                           Py_ssize_t size,
+                                           const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -3687,9 +3687,9 @@
     /* XXX overflow detection missing */
     v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
     if (v == NULL)
-	goto onError;
+        goto onError;
     if (PyUnicode_GetSize((PyObject *)v) == 0)
-	return (PyObject *)v;
+        return (PyObject *)v;
     p = PyUnicode_AS_UNICODE(v);
     end = s + size;
 
@@ -3698,12 +3698,12 @@
         /* We have to sanity check the raw data, otherwise doom looms for
            some malformed UCS-4 data. */
         if (
-            #ifdef Py_UNICODE_WIDE
+#ifdef Py_UNICODE_WIDE
             *p > unimax || *p < 0 ||
-            #endif
+#endif
             end-s < Py_UNICODE_SIZE
             )
-            {
+        {
             startinpos = s - starts;
             if (end-s < Py_UNICODE_SIZE) {
                 endinpos = end-starts;
@@ -3734,7 +3734,7 @@
     Py_XDECREF(exc);
     return (PyObject *)v;
 
- onError:
+  onError:
     Py_XDECREF(v);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
@@ -3744,8 +3744,8 @@
 /* --- Latin-1 Codec ------------------------------------------------------ */
 
 PyObject *PyUnicode_DecodeLatin1(const char *s,
-				 Py_ssize_t size,
-				 const char *errors)
+                                 Py_ssize_t size,
+                                 const char *errors)
 {
     PyUnicodeObject *v;
     Py_UNICODE *p;
@@ -3753,15 +3753,15 @@
 
     /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
     if (size == 1) {
-	Py_UNICODE r = *(unsigned char*)s;
-	return PyUnicode_FromUnicode(&r, 1);
+        Py_UNICODE r = *(unsigned char*)s;
+        return PyUnicode_FromUnicode(&r, 1);
     }
 
     v = _PyUnicode_New(size);
     if (v == NULL)
-	goto onError;
+        goto onError;
     if (size == 0)
-	return (PyObject *)v;
+        return (PyObject *)v;
     p = PyUnicode_AS_UNICODE(v);
     e = s + size;
     /* Unrolling the copy makes it much faster by reducing the looping
@@ -3779,47 +3779,47 @@
         *p++ = (unsigned char) *s++;
     return (PyObject *)v;
 
- onError:
+  onError:
     Py_XDECREF(v);
     return NULL;
 }
 
 /* create or adjust a UnicodeEncodeError */
 static void make_encode_exception(PyObject **exceptionObject,
-    const char *encoding,
-    const Py_UNICODE *unicode, Py_ssize_t size,
-    Py_ssize_t startpos, Py_ssize_t endpos,
-    const char *reason)
+                                  const char *encoding,
+                                  const Py_UNICODE *unicode, Py_ssize_t size,
+                                  Py_ssize_t startpos, Py_ssize_t endpos,
+                                  const char *reason)
 {
     if (*exceptionObject == NULL) {
-	*exceptionObject = PyUnicodeEncodeError_Create(
-	    encoding, unicode, size, startpos, endpos, reason);
+        *exceptionObject = PyUnicodeEncodeError_Create(
+            encoding, unicode, size, startpos, endpos, reason);
     }
     else {
-	if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
-	    goto onError;
-	if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
-	    goto onError;
-	if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
-	    goto onError;
-	return;
-	onError:
-	Py_DECREF(*exceptionObject);
-	*exceptionObject = NULL;
+        if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
+            goto onError;
+        if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
+            goto onError;
+        if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
+            goto onError;
+        return;
+      onError:
+        Py_DECREF(*exceptionObject);
+        *exceptionObject = NULL;
     }
 }
 
 /* raises a UnicodeEncodeError */
 static void raise_encode_exception(PyObject **exceptionObject,
-    const char *encoding,
-    const Py_UNICODE *unicode, Py_ssize_t size,
-    Py_ssize_t startpos, Py_ssize_t endpos,
-    const char *reason)
+                                   const char *encoding,
+                                   const Py_UNICODE *unicode, Py_ssize_t size,
+                                   Py_ssize_t startpos, Py_ssize_t endpos,
+                                   const char *reason)
 {
     make_encode_exception(exceptionObject,
-	encoding, unicode, size, startpos, endpos, reason);
+                          encoding, unicode, size, startpos, endpos, reason);
     if (*exceptionObject != NULL)
-	PyCodec_StrictErrors(*exceptionObject);
+        PyCodec_StrictErrors(*exceptionObject);
 }
 
 /* error handling callback helper:
@@ -3827,11 +3827,11 @@
    put the result into newpos and return the replacement string, which
    has to be freed by the caller */
 static PyObject *unicode_encode_call_errorhandler(const char *errors,
-    PyObject **errorHandler,
-    const char *encoding, const char *reason,
-    const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
-    Py_ssize_t startpos, Py_ssize_t endpos,
-    Py_ssize_t *newpos)
+                                                  PyObject **errorHandler,
+                                                  const char *encoding, const char *reason,
+                                                  const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
+                                                  Py_ssize_t startpos, Py_ssize_t endpos,
+                                                  Py_ssize_t *newpos)
 {
     static char *argparse = "O!n;encoding error handler must return (str, int) tuple";
 
@@ -3839,36 +3839,36 @@
     PyObject *resunicode;
 
     if (*errorHandler == NULL) {
-	*errorHandler = PyCodec_LookupError(errors);
+        *errorHandler = PyCodec_LookupError(errors);
         if (*errorHandler == NULL)
-	    return NULL;
+            return NULL;
     }
 
     make_encode_exception(exceptionObject,
-	encoding, unicode, size, startpos, endpos, reason);
+                          encoding, unicode, size, startpos, endpos, reason);
     if (*exceptionObject == NULL)
-	return NULL;
+        return NULL;
 
     restuple = PyObject_CallFunctionObjArgs(
-	*errorHandler, *exceptionObject, NULL);
+        *errorHandler, *exceptionObject, NULL);
     if (restuple == NULL)
-	return NULL;
+        return NULL;
     if (!PyTuple_Check(restuple)) {
-	PyErr_Format(PyExc_TypeError, &argparse[4]);
-	Py_DECREF(restuple);
-	return NULL;
+        PyErr_Format(PyExc_TypeError, &argparse[4]);
+        Py_DECREF(restuple);
+        return NULL;
     }
     if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
-	&resunicode, newpos)) {
-	Py_DECREF(restuple);
-	return NULL;
+                          &resunicode, newpos)) {
+        Py_DECREF(restuple);
+        return NULL;
     }
     if (*newpos<0)
-	*newpos = size+*newpos;
+        *newpos = size+*newpos;
     if (*newpos<0 || *newpos>size) {
-	PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
-	Py_DECREF(restuple);
-	return NULL;
+        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
+        Py_DECREF(restuple);
+        return NULL;
     }
     Py_INCREF(resunicode);
     Py_DECREF(restuple);
@@ -3876,9 +3876,9 @@
 }
 
 static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
-				 Py_ssize_t size,
-				 const char *errors,
-				 int limit)
+                                     Py_ssize_t size,
+                                     const char *errors,
+                                     int limit)
 {
     /* output object */
     PyObject *res;
@@ -3910,128 +3910,128 @@
     ressize = size;
 
     while (p<endp) {
-	Py_UNICODE c = *p;
+        Py_UNICODE c = *p;
 
-	/* can we encode this? */
-	if (c<limit) {
-	    /* no overflow check, because we know that the space is enough */
-	    *str++ = (char)c;
-	    ++p;
-	}
-	else {
-	    Py_ssize_t unicodepos = p-startp;
-	    Py_ssize_t requiredsize;
-	    PyObject *repunicode;
-	    Py_ssize_t repsize;
-	    Py_ssize_t newpos;
-	    Py_ssize_t respos;
-	    Py_UNICODE *uni2;
-	    /* startpos for collecting unencodable chars */
-	    const Py_UNICODE *collstart = p;
-	    const Py_UNICODE *collend = p;
-	    /* find all unecodable characters */
-	    while ((collend < endp) && ((*collend)>=limit))
-		++collend;
-	    /* cache callback name lookup (if not done yet, i.e. it's the first error) */
-	    if (known_errorHandler==-1) {
-		if ((errors==NULL) || (!strcmp(errors, "strict")))
-		    known_errorHandler = 1;
-		else if (!strcmp(errors, "replace"))
-		    known_errorHandler = 2;
-		else if (!strcmp(errors, "ignore"))
-		    known_errorHandler = 3;
-		else if (!strcmp(errors, "xmlcharrefreplace"))
-		    known_errorHandler = 4;
-		else
-		    known_errorHandler = 0;
-	    }
-	    switch (known_errorHandler) {
-		case 1: /* strict */
-		    raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
-		    goto onError;
-		case 2: /* replace */
-		    while (collstart++<collend)
-			*str++ = '?'; /* fall through */
-		case 3: /* ignore */
-		    p = collend;
-		    break;
-		case 4: /* xmlcharrefreplace */
-		    respos = str - PyBytes_AS_STRING(res);
-		    /* determine replacement size (temporarily (mis)uses p) */
-		    for (p = collstart, repsize = 0; p < collend; ++p) {
-			if (*p<10)
-			    repsize += 2+1+1;
-			else if (*p<100)
-			    repsize += 2+2+1;
-			else if (*p<1000)
-			    repsize += 2+3+1;
-			else if (*p<10000)
-			    repsize += 2+4+1;
+        /* can we encode this? */
+        if (c<limit) {
+            /* no overflow check, because we know that the space is enough */
+            *str++ = (char)c;
+            ++p;
+        }
+        else {
+            Py_ssize_t unicodepos = p-startp;
+            Py_ssize_t requiredsize;
+            PyObject *repunicode;
+            Py_ssize_t repsize;
+            Py_ssize_t newpos;
+            Py_ssize_t respos;
+            Py_UNICODE *uni2;
+            /* startpos for collecting unencodable chars */
+            const Py_UNICODE *collstart = p;
+            const Py_UNICODE *collend = p;
+            /* find all unecodable characters */
+            while ((collend < endp) && ((*collend)>=limit))
+                ++collend;
+            /* cache callback name lookup (if not done yet, i.e. it's the first error) */
+            if (known_errorHandler==-1) {
+                if ((errors==NULL) || (!strcmp(errors, "strict")))
+                    known_errorHandler = 1;
+                else if (!strcmp(errors, "replace"))
+                    known_errorHandler = 2;
+                else if (!strcmp(errors, "ignore"))
+                    known_errorHandler = 3;
+                else if (!strcmp(errors, "xmlcharrefreplace"))
+                    known_errorHandler = 4;
+                else
+                    known_errorHandler = 0;
+            }
+            switch (known_errorHandler) {
+            case 1: /* strict */
+                raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
+                goto onError;
+            case 2: /* replace */
+                while (collstart++<collend)
+                    *str++ = '?'; /* fall through */
+            case 3: /* ignore */
+                p = collend;
+                break;
+            case 4: /* xmlcharrefreplace */
+                respos = str - PyBytes_AS_STRING(res);
+                /* determine replacement size (temporarily (mis)uses p) */
+                for (p = collstart, repsize = 0; p < collend; ++p) {
+                    if (*p<10)
+                        repsize += 2+1+1;
+                    else if (*p<100)
+                        repsize += 2+2+1;
+                    else if (*p<1000)
+                        repsize += 2+3+1;
+                    else if (*p<10000)
+                        repsize += 2+4+1;
 #ifndef Py_UNICODE_WIDE
-			else
-			    repsize += 2+5+1;
+                    else
+                        repsize += 2+5+1;
 #else
-			else if (*p<100000)
-			    repsize += 2+5+1;
-			else if (*p<1000000)
-			    repsize += 2+6+1;
-			else
-			    repsize += 2+7+1;
-#endif
-		    }
-		    requiredsize = respos+repsize+(endp-collend);
-		    if (requiredsize > ressize) {
-			if (requiredsize<2*ressize)
-			    requiredsize = 2*ressize;
-			if (_PyBytes_Resize(&res, requiredsize))
-			    goto onError;
-			str = PyBytes_AS_STRING(res) + respos;
-			ressize = requiredsize;
-		    }
-		    /* generate replacement (temporarily (mis)uses p) */
-		    for (p = collstart; p < collend; ++p) {
-			str += sprintf(str, "&#%d;", (int)*p);
-		    }
-		    p = collend;
-		    break;
-		default:
-		    repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
-			encoding, reason, startp, size, &exc,
-			collstart-startp, collend-startp, &newpos);
-		    if (repunicode == NULL)
-			goto onError;
-		    /* need more space? (at least enough for what we
-		       have+the replacement+the rest of the string, so
-		       we won't have to check space for encodable characters) */
-		    respos = str - PyBytes_AS_STRING(res);
-		    repsize = PyUnicode_GET_SIZE(repunicode);
-		    requiredsize = respos+repsize+(endp-collend);
-		    if (requiredsize > ressize) {
-			if (requiredsize<2*ressize)
-			    requiredsize = 2*ressize;
-			if (_PyBytes_Resize(&res, requiredsize)) {
-			    Py_DECREF(repunicode);
-			    goto onError;
-			}
-			str = PyBytes_AS_STRING(res) + respos;
-			ressize = requiredsize;
-		    }
-		    /* check if there is anything unencodable in the replacement
-		       and copy it to the output */
-		    for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
-			c = *uni2;
-			if (c >= limit) {
-			    raise_encode_exception(&exc, encoding, startp, size,
-				unicodepos, unicodepos+1, reason);
-			    Py_DECREF(repunicode);
-			    goto onError;
-			}
-			*str = (char)c;
-		    }
-		    p = startp + newpos;
-		    Py_DECREF(repunicode);
-	    }
-	}
+                    else if (*p<100000)
+                        repsize += 2+5+1;
+                    else if (*p<1000000)
+                        repsize += 2+6+1;
+                    else
+                        repsize += 2+7+1;
+#endif
+                }
+                requiredsize = respos+repsize+(endp-collend);
+                if (requiredsize > ressize) {
+                    if (requiredsize<2*ressize)
+                        requiredsize = 2*ressize;
+                    if (_PyBytes_Resize(&res, requiredsize))
+                        goto onError;
+                    str = PyBytes_AS_STRING(res) + respos;
+                    ressize = requiredsize;
+                }
+                /* generate replacement (temporarily (mis)uses p) */
+                for (p = collstart; p < collend; ++p) {
+                    str += sprintf(str, "&#%d;", (int)*p);
+                }
+                p = collend;
+                break;
+            default:
+                repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
+                                                              encoding, reason, startp, size, &exc,
+                                                              collstart-startp, collend-startp, &newpos);
+                if (repunicode == NULL)
+                    goto onError;
+                /* need more space? (at least enough for what we
+                   have+the replacement+the rest of the string, so
+                   we won't have to check space for encodable characters) */
+                respos = str - PyBytes_AS_STRING(res);
+                repsize = PyUnicode_GET_SIZE(repunicode);
+                requiredsize = respos+repsize+(endp-collend);
+                if (requiredsize > ressize) {
+                    if (requiredsize<2*ressize)
+                        requiredsize = 2*ressize;
+                    if (_PyBytes_Resize(&res, requiredsize)) {
+                        Py_DECREF(repunicode);
+                        goto onError;
+                    }
+                    str = PyBytes_AS_STRING(res) + respos;
+                    ressize = requiredsize;
+                }
+                /* check if there is anything unencodable in the replacement
+                   and copy it to the output */
+                for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
+                    c = *uni2;
+                    if (c >= limit) {
+                        raise_encode_exception(&exc, encoding, startp, size,
+                                               unicodepos, unicodepos+1, reason);
+                        Py_DECREF(repunicode);
+                        goto onError;
+                    }
+                    *str = (char)c;
+                }
+                p = startp + newpos;
+                Py_DECREF(repunicode);
+            }
+        }
     }
     /* Resize if we allocated to much */
     size = str - PyBytes_AS_STRING(res);
@@ -4053,8 +4053,8 @@
 }
 
 PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
-				 Py_ssize_t size,
-				 const char *errors)
+                                 Py_ssize_t size,
+                                 const char *errors)
 {
     return unicode_encode_ucs1(p, size, errors, 256);
 }
@@ -4062,19 +4062,19 @@
 PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
-	PyErr_BadArgument();
-	return NULL;
+        PyErr_BadArgument();
+        return NULL;
     }
     return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
-				  PyUnicode_GET_SIZE(unicode),
-				  NULL);
+                                  PyUnicode_GET_SIZE(unicode),
+                                  NULL);
 }
 
 /* --- 7-bit ASCII Codec -------------------------------------------------- */
 
 PyObject *PyUnicode_DecodeASCII(const char *s,
-				Py_ssize_t size,
-				const char *errors)
+                                Py_ssize_t size,
+                                const char *errors)
 {
     const char *starts = s;
     PyUnicodeObject *v;
@@ -4088,43 +4088,43 @@
 
     /* ASCII is equivalent to the first 128 ordinals in Unicode. */
     if (size == 1 && *(unsigned char*)s < 128) {
-	Py_UNICODE r = *(unsigned char*)s;
-	return PyUnicode_FromUnicode(&r, 1);
+        Py_UNICODE r = *(unsigned char*)s;
+        return PyUnicode_FromUnicode(&r, 1);
     }
 
     v = _PyUnicode_New(size);
     if (v == NULL)
-	goto onError;
+        goto onError;
     if (size == 0)
-	return (PyObject *)v;
+        return (PyObject *)v;
     p = PyUnicode_AS_UNICODE(v);
     e = s + size;
     while (s < e) {
-	register unsigned char c = (unsigned char)*s;
-	if (c < 128) {
-	    *p++ = c;
-	    ++s;
-	}
-	else {
-	    startinpos = s-starts;
-	    endinpos = startinpos + 1;
-	    outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
-	    if (unicode_decode_call_errorhandler(
-		 errors, &errorHandler,
-		 "ascii", "ordinal not in range(128)",
-		 &starts, &e, &startinpos, &endinpos, &exc, &s,
-		 &v, &outpos, &p))
-		goto onError;
-	}
+        register unsigned char c = (unsigned char)*s;
+        if (c < 128) {
+            *p++ = c;
+            ++s;
+        }
+        else {
+            startinpos = s-starts;
+            endinpos = startinpos + 1;
+            outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
+            if (unicode_decode_call_errorhandler(
+                    errors, &errorHandler,
+                    "ascii", "ordinal not in range(128)",
+                    &starts, &e, &startinpos, &endinpos, &exc, &s,
+                    &v, &outpos, &p))
+                goto onError;
+        }
     }
     if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
-	if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
-	    goto onError;
+        if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
+            goto onError;
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     return (PyObject *)v;
 
- onError:
+  onError:
     Py_XDECREF(v);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
@@ -4132,8 +4132,8 @@
 }
 
 PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
-				Py_ssize_t size,
-				const char *errors)
+                                Py_ssize_t size,
+                                const char *errors)
 {
     return unicode_encode_ucs1(p, size, errors, 128);
 }
@@ -4141,12 +4141,12 @@
 PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
-	PyErr_BadArgument();
-	return NULL;
+        PyErr_BadArgument();
+        return NULL;
     }
     return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
-				 PyUnicode_GET_SIZE(unicode),
-				 NULL);
+                                 PyUnicode_GET_SIZE(unicode),
+                                 NULL);
 }
 
 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
@@ -4160,15 +4160,15 @@
 /* XXX This code is limited to "true" double-byte encodings, as
    a) it assumes an incomplete character consists of a single byte, and
    b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
-      encodings, see IsDBCSLeadByteEx documentation. */
+   encodings, see IsDBCSLeadByteEx documentation. */
 
 static int is_dbcs_lead_byte(const char *s, int offset)
 {
     const char *curr = s + offset;
 
     if (IsDBCSLeadByte(*curr)) {
-	const char *prev = CharPrev(s, curr);
-	return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
+        const char *prev = CharPrev(s, curr);
+        return (prev == curr) || !IsDBCSLeadByte(*prev) || (curr - prev == 2);
     }
     return 0;
 }
@@ -4178,9 +4178,9 @@
  * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
  */
 static int decode_mbcs(PyUnicodeObject **v,
-			const char *s, /* MBCS string */
-			int size, /* sizeof MBCS string */
-			int final)
+                       const char *s, /* MBCS string */
+                       int size, /* sizeof MBCS string */
+                       int final)
 {
     Py_UNICODE *p;
     Py_ssize_t n = 0;
@@ -4190,74 +4190,74 @@
 
     /* Skip trailing lead-byte unless 'final' is set */
     if (!final && size >= 1 && is_dbcs_lead_byte(s, size - 1))
-	--size;
+        --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, 0, s, size, NULL, 0);
+        if (usize == 0) {
+            PyErr_SetFromWindowsErrWithFilename(0, NULL);
+            return -1;
+        }
     }
 
     if (*v == NULL) {
-	/* Create unicode object */
-	*v = _PyUnicode_New(usize);
-	if (*v == NULL)
-	    return -1;
+        /* Create unicode object */
+        *v = _PyUnicode_New(usize);
+        if (*v == NULL)
+            return -1;
     }
     else {
-	/* Extend unicode object */
-	n = PyUnicode_GET_SIZE(*v);
-	if (_PyUnicode_Resize(v, n + usize) < 0)
-	    return -1;
+        /* Extend unicode object */
+        n = PyUnicode_GET_SIZE(*v);
+        if (_PyUnicode_Resize(v, n + usize) < 0)
+            return -1;
     }
 
     /* Do the conversion */
     if (size > 0) {
-	p = PyUnicode_AS_UNICODE(*v) + n;
-	if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
-	    PyErr_SetFromWindowsErrWithFilename(0, NULL);
-	    return -1;
-	}
+        p = PyUnicode_AS_UNICODE(*v) + n;
+        if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
+            PyErr_SetFromWindowsErrWithFilename(0, NULL);
+            return -1;
+        }
     }
 
     return size;
 }
 
 PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
-					Py_ssize_t size,
-					const char *errors,
-					Py_ssize_t *consumed)
+                                       Py_ssize_t size,
+                                       const char *errors,
+                                       Py_ssize_t *consumed)
 {
     PyUnicodeObject *v = NULL;
     int done;
 
     if (consumed)
-	*consumed = 0;
+        *consumed = 0;
 
 #ifdef NEED_RETRY
   retry:
     if (size > INT_MAX)
-	done = decode_mbcs(&v, s, INT_MAX, 0);
+        done = decode_mbcs(&v, s, INT_MAX, 0);
     else
 #endif
-	done = decode_mbcs(&v, s, (int)size, !consumed);
+        done = decode_mbcs(&v, s, (int)size, !consumed);
 
     if (done < 0) {
         Py_XDECREF(v);
-	return NULL;
+        return NULL;
     }
 
     if (consumed)
-	*consumed += done;
+        *consumed += done;
 
 #ifdef NEED_RETRY
     if (size > INT_MAX) {
-	s += done;
-	size -= done;
-	goto retry;
+        s += done;
+        size -= done;
+        goto retry;
     }
 #endif
 
@@ -4265,8 +4265,8 @@
 }
 
 PyObject *PyUnicode_DecodeMBCS(const char *s,
-				Py_ssize_t size,
-				const char *errors)
+                               Py_ssize_t size,
+                               const char *errors)
 {
     return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
 }
@@ -4276,8 +4276,8 @@
  * Returns 0 if succeed, -1 otherwise.
  */
 static int encode_mbcs(PyObject **repr,
-			const Py_UNICODE *p, /* unicode */
-			int size) /* size of unicode */
+                       const Py_UNICODE *p, /* unicode */
+                       int size) /* size of unicode */
 {
     int mbcssize = 0;
     Py_ssize_t n = 0;
@@ -4286,63 +4286,63 @@
 
     /* First get the size of the result */
     if (size > 0) {
-	mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
-	if (mbcssize == 0) {
-	    PyErr_SetFromWindowsErrWithFilename(0, NULL);
-	    return -1;
-	}
+        mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
+        if (mbcssize == 0) {
+            PyErr_SetFromWindowsErrWithFilename(0, NULL);
+            return -1;
+        }
     }
 
     if (*repr == NULL) {
-	/* Create string object */
-	*repr = PyBytes_FromStringAndSize(NULL, mbcssize);
-	if (*repr == NULL)
-	    return -1;
+        /* Create string object */
+        *repr = PyBytes_FromStringAndSize(NULL, mbcssize);
+        if (*repr == NULL)
+            return -1;
     }
     else {
-	/* Extend string object */
-	n = PyBytes_Size(*repr);
-	if (_PyBytes_Resize(repr, n + mbcssize) < 0)
-	    return -1;
+        /* Extend string object */
+        n = PyBytes_Size(*repr);
+        if (_PyBytes_Resize(repr, n + mbcssize) < 0)
+            return -1;
     }
 
     /* 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)) {
-	    PyErr_SetFromWindowsErrWithFilename(0, NULL);
-	    return -1;
-	}
+        char *s = PyBytes_AS_STRING(*repr) + n;
+        if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
+            PyErr_SetFromWindowsErrWithFilename(0, NULL);
+            return -1;
+        }
     }
 
     return 0;
 }
 
 PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
-				Py_ssize_t size,
-				const char *errors)
+                               Py_ssize_t size,
+                               const char *errors)
 {
     PyObject *repr = NULL;
     int ret;
 
 #ifdef NEED_RETRY
- retry:
+  retry:
     if (size > INT_MAX)
-	ret = encode_mbcs(&repr, p, INT_MAX);
+        ret = encode_mbcs(&repr, p, INT_MAX);
     else
 #endif
-	ret = encode_mbcs(&repr, p, (int)size);
+        ret = encode_mbcs(&repr, p, (int)size);
 
     if (ret < 0) {
-	Py_XDECREF(repr);
-	return NULL;
+        Py_XDECREF(repr);
+        return NULL;
     }
 
 #ifdef NEED_RETRY
     if (size > INT_MAX) {
-	p += INT_MAX;
-	size -= INT_MAX;
-	goto retry;
+        p += INT_MAX;
+        size -= INT_MAX;
+        goto retry;
     }
 #endif
 
@@ -4356,8 +4356,8 @@
         return NULL;
     }
     return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
-				PyUnicode_GET_SIZE(unicode),
-				NULL);
+                                PyUnicode_GET_SIZE(unicode),
+                                NULL);
 }
 
 #undef NEED_RETRY
@@ -4367,9 +4367,9 @@
 /* --- Character Mapping Codec -------------------------------------------- */
 
 PyObject *PyUnicode_DecodeCharmap(const char *s,
-				  Py_ssize_t size,
-				  PyObject *mapping,
-				  const char *errors)
+                                  Py_ssize_t size,
+                                  PyObject *mapping,
+                                  const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -4386,141 +4386,141 @@
 
     /* Default to Latin-1 */
     if (mapping == NULL)
-	return PyUnicode_DecodeLatin1(s, size, errors);
+        return PyUnicode_DecodeLatin1(s, size, errors);
 
     v = _PyUnicode_New(size);
     if (v == NULL)
-	goto onError;
+        goto onError;
     if (size == 0)
-	return (PyObject *)v;
+        return (PyObject *)v;
     p = PyUnicode_AS_UNICODE(v);
     e = s + size;
     if (PyUnicode_CheckExact(mapping)) {
-	mapstring = PyUnicode_AS_UNICODE(mapping);
-	maplen = PyUnicode_GET_SIZE(mapping);
-	while (s < e) {
-	    unsigned char ch = *s;
-	    Py_UNICODE x = 0xfffe; /* illegal value */
-
-	    if (ch < maplen)
-		x = mapstring[ch];
-
-	    if (x == 0xfffe) {
-		/* undefined mapping */
-		outpos = p-PyUnicode_AS_UNICODE(v);
-		startinpos = s-starts;
-		endinpos = startinpos+1;
-		if (unicode_decode_call_errorhandler(
-		     errors, &errorHandler,
-		     "charmap", "character maps to <undefined>",
-		     &starts, &e, &startinpos, &endinpos, &exc, &s,
-		     &v, &outpos, &p)) {
-		    goto onError;
-		}
-		continue;
-	    }
-	    *p++ = x;
-	    ++s;
-	}
+        mapstring = PyUnicode_AS_UNICODE(mapping);
+        maplen = PyUnicode_GET_SIZE(mapping);
+        while (s < e) {
+            unsigned char ch = *s;
+            Py_UNICODE x = 0xfffe; /* illegal value */
+
+            if (ch < maplen)
+                x = mapstring[ch];
+
+            if (x == 0xfffe) {
+                /* undefined mapping */
+                outpos = p-PyUnicode_AS_UNICODE(v);
+                startinpos = s-starts;
+                endinpos = startinpos+1;
+                if (unicode_decode_call_errorhandler(
+                        errors, &errorHandler,
+                        "charmap", "character maps to <undefined>",
+                        &starts, &e, &startinpos, &endinpos, &exc, &s,
+                        &v, &outpos, &p)) {
+                    goto onError;
+                }
+                continue;
+            }
+            *p++ = x;
+            ++s;
+        }
     }
     else {
-	while (s < e) {
-	    unsigned char ch = *s;
-	    PyObject *w, *x;
-
-	    /* Get mapping (char ordinal -> integer, Unicode char or None) */
-	    w = PyLong_FromLong((long)ch);
-	    if (w == NULL)
-		goto onError;
-	    x = PyObject_GetItem(mapping, w);
-	    Py_DECREF(w);
-	    if (x == NULL) {
-		if (PyErr_ExceptionMatches(PyExc_LookupError)) {
-		    /* No mapping found means: mapping is undefined. */
-		    PyErr_Clear();
-		    x = Py_None;
-		    Py_INCREF(x);
-		} else
-		    goto onError;
-	    }
-    
-	    /* Apply mapping */
-	    if (PyLong_Check(x)) {
-		long value = PyLong_AS_LONG(x);
-		if (value < 0 || value > 65535) {
-		    PyErr_SetString(PyExc_TypeError,
-				    "character mapping must be in range(65536)");
-		    Py_DECREF(x);
-		    goto onError;
-		}
-		*p++ = (Py_UNICODE)value;
-	    }
-	    else if (x == Py_None) {
-		/* undefined mapping */
-		outpos = p-PyUnicode_AS_UNICODE(v);
-		startinpos = s-starts;
-		endinpos = startinpos+1;
-		if (unicode_decode_call_errorhandler(
-		     errors, &errorHandler,
-		     "charmap", "character maps to <undefined>",
-		     &starts, &e, &startinpos, &endinpos, &exc, &s,
-		     &v, &outpos, &p)) {
-		    Py_DECREF(x);
-		    goto onError;
-		}
-		Py_DECREF(x);
-		continue;
-	    }
-	    else if (PyUnicode_Check(x)) {
-		Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
-    
-		if (targetsize == 1)
-		    /* 1-1 mapping */
-		    *p++ = *PyUnicode_AS_UNICODE(x);
-    
-		else if (targetsize > 1) {
-		    /* 1-n mapping */
-		    if (targetsize > extrachars) {
-			/* resize first */
-			Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
-			Py_ssize_t needed = (targetsize - extrachars) + \
-				     (targetsize << 2);
-			extrachars += needed;
-			/* XXX overflow detection missing */
-			if (_PyUnicode_Resize(&v,
-					     PyUnicode_GET_SIZE(v) + needed) < 0) {
-			    Py_DECREF(x);
-			    goto onError;
-			}
-			p = PyUnicode_AS_UNICODE(v) + oldpos;
-		    }
-		    Py_UNICODE_COPY(p,
-				    PyUnicode_AS_UNICODE(x),
-				    targetsize);
-		    p += targetsize;
-		    extrachars -= targetsize;
-		}
-		/* 1-0 mapping: skip the character */
-	    }
-	    else {
-		/* wrong return value */
-		PyErr_SetString(PyExc_TypeError,
-		      "character mapping must return integer, None or str");
-		Py_DECREF(x);
-		goto onError;
-	    }
-	    Py_DECREF(x);
-	    ++s;
-	}
+        while (s < e) {
+            unsigned char ch = *s;
+            PyObject *w, *x;
+
+            /* Get mapping (char ordinal -> integer, Unicode char or None) */
+            w = PyLong_FromLong((long)ch);
+            if (w == NULL)
+                goto onError;
+            x = PyObject_GetItem(mapping, w);
+            Py_DECREF(w);
+            if (x == NULL) {
+                if (PyErr_ExceptionMatches(PyExc_LookupError)) {
+                    /* No mapping found means: mapping is undefined. */
+                    PyErr_Clear();
+                    x = Py_None;
+                    Py_INCREF(x);
+                } else
+                    goto onError;
+            }
+
+            /* Apply mapping */
+            if (PyLong_Check(x)) {
+                long value = PyLong_AS_LONG(x);
+                if (value < 0 || value > 65535) {
+                    PyErr_SetString(PyExc_TypeError,
+                                    "character mapping must be in range(65536)");
+                    Py_DECREF(x);
+                    goto onError;
+                }
+                *p++ = (Py_UNICODE)value;
+            }
+            else if (x == Py_None) {
+                /* undefined mapping */
+                outpos = p-PyUnicode_AS_UNICODE(v);
+                startinpos = s-starts;
+                endinpos = startinpos+1;
+                if (unicode_decode_call_errorhandler(
+                        errors, &errorHandler,
+                        "charmap", "character maps to <undefined>",
+                        &starts, &e, &startinpos, &endinpos, &exc, &s,
+                        &v, &outpos, &p)) {
+                    Py_DECREF(x);
+                    goto onError;
+                }
+                Py_DECREF(x);
+                continue;
+            }
+            else if (PyUnicode_Check(x)) {
+                Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
+
+                if (targetsize == 1)
+                    /* 1-1 mapping */
+                    *p++ = *PyUnicode_AS_UNICODE(x);
+
+                else if (targetsize > 1) {
+                    /* 1-n mapping */
+                    if (targetsize > extrachars) {
+                        /* resize first */
+                        Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
+                        Py_ssize_t needed = (targetsize - extrachars) + \
+                            (targetsize << 2);
+                        extrachars += needed;
+                        /* XXX overflow detection missing */
+                        if (_PyUnicode_Resize(&v,
+                                              PyUnicode_GET_SIZE(v) + needed) < 0) {
+                            Py_DECREF(x);
+                            goto onError;
+                        }
+                        p = PyUnicode_AS_UNICODE(v) + oldpos;
+                    }
+                    Py_UNICODE_COPY(p,
+                                    PyUnicode_AS_UNICODE(x),
+                                    targetsize);
+                    p += targetsize;
+                    extrachars -= targetsize;
+                }
+                /* 1-0 mapping: skip the character */
+            }
+            else {
+                /* wrong return value */
+                PyErr_SetString(PyExc_TypeError,
+                                "character mapping must return integer, None or str");
+                Py_DECREF(x);
+                goto onError;
+            }
+            Py_DECREF(x);
+            ++s;
+        }
     }
     if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
-	if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
-	    goto onError;
+        if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
+            goto onError;
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     return (PyObject *)v;
 
- onError:
+  onError:
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     Py_XDECREF(v);
@@ -4530,74 +4530,74 @@
 /* Charmap encoding: the lookup table */
 
 struct encoding_map{
-  PyObject_HEAD
-  unsigned char level1[32];
-  int count2, count3;
-  unsigned char level23[1];
+    PyObject_HEAD
+    unsigned char level1[32];
+    int count2, count3;
+    unsigned char level23[1];
 };
 
 static PyObject*
 encoding_map_size(PyObject *obj, PyObject* args)
 {
     struct encoding_map *map = (struct encoding_map*)obj;
-    return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 + 
-                          128*map->count3);
+    return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
+                           128*map->count3);
 }
 
 static PyMethodDef encoding_map_methods[] = {
-	{"size", encoding_map_size, METH_NOARGS, 
-         PyDoc_STR("Return the size (in bytes) of this object") },
-        { 0 }
+    {"size", encoding_map_size, METH_NOARGS,
+     PyDoc_STR("Return the size (in bytes) of this object") },
+    { 0 }
 };
 
 static void
 encoding_map_dealloc(PyObject* o)
 {
-	PyObject_FREE(o);
+    PyObject_FREE(o);
 }
 
 static PyTypeObject EncodingMapType = {
-	PyVarObject_HEAD_INIT(NULL, 0)
-        "EncodingMap",          /*tp_name*/
-        sizeof(struct encoding_map),   /*tp_basicsize*/
-        0,                      /*tp_itemsize*/
-        /* methods */
-        encoding_map_dealloc,   /*tp_dealloc*/
-        0,                      /*tp_print*/
-        0,                      /*tp_getattr*/
-        0,                      /*tp_setattr*/
-        0,                      /*tp_compare*/
-        0,                      /*tp_repr*/
-        0,                      /*tp_as_number*/
-        0,                      /*tp_as_sequence*/
-        0,                      /*tp_as_mapping*/
-        0,                      /*tp_hash*/
-        0,                      /*tp_call*/
-        0,                      /*tp_str*/
-        0,                      /*tp_getattro*/
-        0,                      /*tp_setattro*/
-        0,                      /*tp_as_buffer*/
-        Py_TPFLAGS_DEFAULT,     /*tp_flags*/
-        0,                      /*tp_doc*/
-        0,                      /*tp_traverse*/
-        0,                      /*tp_clear*/
-        0,                      /*tp_richcompare*/
-        0,                      /*tp_weaklistoffset*/
-        0,                      /*tp_iter*/
-        0,                      /*tp_iternext*/
-        encoding_map_methods,   /*tp_methods*/
-        0,                      /*tp_members*/
-        0,                      /*tp_getset*/
-        0,                      /*tp_base*/
-        0,                      /*tp_dict*/
-        0,                      /*tp_descr_get*/
-        0,                      /*tp_descr_set*/
-        0,                      /*tp_dictoffset*/
-        0,                      /*tp_init*/
-        0,                      /*tp_alloc*/
-        0,                      /*tp_new*/
-        0,                      /*tp_free*/
-        0,                      /*tp_is_gc*/
+    PyVarObject_HEAD_INIT(NULL, 0)
+    "EncodingMap",          /*tp_name*/
+    sizeof(struct encoding_map),   /*tp_basicsize*/
+    0,                      /*tp_itemsize*/
+    /* methods */
+    encoding_map_dealloc,   /*tp_dealloc*/
+    0,                      /*tp_print*/
+    0,                      /*tp_getattr*/
+    0,                      /*tp_setattr*/
+    0,                      /*tp_reserved*/
+    0,                      /*tp_repr*/
+    0,                      /*tp_as_number*/
+    0,                      /*tp_as_sequence*/
+    0,                      /*tp_as_mapping*/
+    0,                      /*tp_hash*/
+    0,                      /*tp_call*/
+    0,                      /*tp_str*/
+    0,                      /*tp_getattro*/
+    0,                      /*tp_setattro*/
+    0,                      /*tp_as_buffer*/
+    Py_TPFLAGS_DEFAULT,     /*tp_flags*/
+    0,                      /*tp_doc*/
+    0,                      /*tp_traverse*/
+    0,                      /*tp_clear*/
+    0,                      /*tp_richcompare*/
+    0,                      /*tp_weaklistoffset*/
+    0,                      /*tp_iter*/
+    0,                      /*tp_iternext*/
+    encoding_map_methods,   /*tp_methods*/
+    0,                      /*tp_members*/
+    0,                      /*tp_getset*/
+    0,                      /*tp_base*/
+    0,                      /*tp_dict*/
+    0,                      /*tp_descr_get*/
+    0,                      /*tp_descr_set*/
+    0,                      /*tp_dictoffset*/
+    0,                      /*tp_init*/
+    0,                      /*tp_alloc*/
+    0,                      /*tp_new*/
+    0,                      /*tp_free*/
+    0,                      /*tp_is_gc*/
 };
 
 PyObject*
@@ -4629,10 +4629,10 @@
     for (i = 1; i < 256; i++) {
         int l1, l2;
         if (decode[i] == 0
-            #ifdef Py_UNICODE_WIDE
+#ifdef Py_UNICODE_WIDE
             || decode[i] > 0xFFFF
-            #endif
-        ) {
+#endif
+            ) {
             need_dict = 1;
             break;
         }
@@ -4644,7 +4644,7 @@
         if (level1[l1] == 0xFF)
             level1[l1] = count2++;
         if (level2[l2] == 0xFF)
-            level2[l2] = count3++; 
+            level2[l2] = count3++;
     }
 
     if (count2 >= 0xFF || count3 >= 0xFF)
@@ -4718,7 +4718,7 @@
 
 #ifdef Py_UNICODE_WIDE
     if (c > 0xFFFF) {
-	return -1;
+        return -1;
     }
 #endif
     if (c == 0)
@@ -4750,57 +4750,57 @@
     PyObject *x;
 
     if (w == NULL)
-	 return NULL;
+        return NULL;
     x = PyObject_GetItem(mapping, w);
     Py_DECREF(w);
     if (x == NULL) {
-	if (PyErr_ExceptionMatches(PyExc_LookupError)) {
-	    /* No mapping found means: mapping is undefined. */
-	    PyErr_Clear();
-	    x = Py_None;
-	    Py_INCREF(x);
-	    return x;
-	} else
-	    return NULL;
+        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
+            /* No mapping found means: mapping is undefined. */
+            PyErr_Clear();
+            x = Py_None;
+            Py_INCREF(x);
+            return x;
+        } else
+            return NULL;
     }
     else if (x == Py_None)
-	return x;
+        return x;
     else if (PyLong_Check(x)) {
-	long value = PyLong_AS_LONG(x);
-	if (value < 0 || value > 255) {
-	    PyErr_SetString(PyExc_TypeError,
-			     "character mapping must be in range(256)");
-	    Py_DECREF(x);
-	    return NULL;
-	}
-	return x;
+        long value = PyLong_AS_LONG(x);
+        if (value < 0 || value > 255) {
+            PyErr_SetString(PyExc_TypeError,
+                            "character mapping must be in range(256)");
+            Py_DECREF(x);
+            return NULL;
+        }
+        return x;
     }
     else if (PyBytes_Check(x))
-	return x;
+        return x;
     else {
-	/* wrong return value */
-	PyErr_Format(PyExc_TypeError,
-                "character mapping must return integer, bytes or None, not %.400s",
-                x->ob_type->tp_name);
-	Py_DECREF(x);
-	return NULL;
+        /* wrong return value */
+        PyErr_Format(PyExc_TypeError,
+                     "character mapping must return integer, bytes or None, not %.400s",
+                     x->ob_type->tp_name);
+        Py_DECREF(x);
+        return NULL;
     }
 }
 
 static int
 charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
 {
-	Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
-	/* exponentially overallocate to minimize reallocations */
-	if (requiredsize < 2*outsize)
-	    requiredsize = 2*outsize;
-	if (_PyBytes_Resize(outobj, requiredsize))
-	    return -1;
-	return 0;
+    Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
+    /* exponentially overallocate to minimize reallocations */
+    if (requiredsize < 2*outsize)
+        requiredsize = 2*outsize;
+    if (_PyBytes_Resize(outobj, requiredsize))
+        return -1;
+    return 0;
 }
 
-typedef enum charmapencode_result { 
-  enc_SUCCESS, enc_FAILED, enc_EXCEPTION 
+typedef enum charmapencode_result {
+    enc_SUCCESS, enc_FAILED, enc_EXCEPTION
 }charmapencode_result;
 /* lookup the character, put the result in the output string and adjust
    various state variables. Resize the output bytes object if not enough
@@ -4810,7 +4810,7 @@
    reallocation error occurred. The caller must decref the result */
 static
 charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
-    PyObject **outobj, Py_ssize_t *outpos)
+                                          PyObject **outobj, Py_ssize_t *outpos)
 {
     PyObject *rep;
     char *outstart;
@@ -4818,47 +4818,47 @@
 
     if (Py_TYPE(mapping) == &EncodingMapType) {
         int res = encoding_map_lookup(c, mapping);
-	Py_ssize_t requiredsize = *outpos+1;
+        Py_ssize_t requiredsize = *outpos+1;
         if (res == -1)
             return enc_FAILED;
-	if (outsize<requiredsize)
-	    if (charmapencode_resize(outobj, outpos, requiredsize))
-		return enc_EXCEPTION;
+        if (outsize<requiredsize)
+            if (charmapencode_resize(outobj, outpos, requiredsize))
+                return enc_EXCEPTION;
         outstart = PyBytes_AS_STRING(*outobj);
-	outstart[(*outpos)++] = (char)res;
-	return enc_SUCCESS;
+        outstart[(*outpos)++] = (char)res;
+        return enc_SUCCESS;
     }
 
     rep = charmapencode_lookup(c, mapping);
     if (rep==NULL)
-	return enc_EXCEPTION;
+        return enc_EXCEPTION;
     else if (rep==Py_None) {
-	Py_DECREF(rep);
-	return enc_FAILED;
+        Py_DECREF(rep);
+        return enc_FAILED;
     } else {
-	if (PyLong_Check(rep)) {
-	    Py_ssize_t requiredsize = *outpos+1;
-	    if (outsize<requiredsize)
-		if (charmapencode_resize(outobj, outpos, requiredsize)) {
-		    Py_DECREF(rep);
-		    return enc_EXCEPTION;
-		}
+        if (PyLong_Check(rep)) {
+            Py_ssize_t requiredsize = *outpos+1;
+            if (outsize<requiredsize)
+                if (charmapencode_resize(outobj, outpos, requiredsize)) {
+                    Py_DECREF(rep);
+                    return enc_EXCEPTION;
+                }
             outstart = PyBytes_AS_STRING(*outobj);
-	    outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
-	}
-	else {
-	    const char *repchars = PyBytes_AS_STRING(rep);
-	    Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
-	    Py_ssize_t requiredsize = *outpos+repsize;
-	    if (outsize<requiredsize)
-		if (charmapencode_resize(outobj, outpos, requiredsize)) {
-		    Py_DECREF(rep);
-		    return enc_EXCEPTION;
-		}
+            outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
+        }
+        else {
+            const char *repchars = PyBytes_AS_STRING(rep);
+            Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
+            Py_ssize_t requiredsize = *outpos+repsize;
+            if (outsize<requiredsize)
+                if (charmapencode_resize(outobj, outpos, requiredsize)) {
+                    Py_DECREF(rep);
+                    return enc_EXCEPTION;
+                }
             outstart = PyBytes_AS_STRING(*outobj);
-	    memcpy(outstart + *outpos, repchars, repsize);
-	    *outpos += repsize;
-	}
+            memcpy(outstart + *outpos, repchars, repsize);
+            *outpos += repsize;
+        }
     }
     Py_DECREF(rep);
     return enc_SUCCESS;
@@ -4889,103 +4889,103 @@
     while (collendpos < size) {
         PyObject *rep;
         if (Py_TYPE(mapping) == &EncodingMapType) {
-	    int res = encoding_map_lookup(p[collendpos], mapping);
-	    if (res != -1)
-		break;
-	    ++collendpos;
-	    continue;
-	}
-            
-	rep = charmapencode_lookup(p[collendpos], mapping);
-	if (rep==NULL)
-	    return -1;
-	else if (rep!=Py_None) {
-	    Py_DECREF(rep);
-	    break;
-	}
-	Py_DECREF(rep);
-	++collendpos;
+            int res = encoding_map_lookup(p[collendpos], mapping);
+            if (res != -1)
+                break;
+            ++collendpos;
+            continue;
+        }
+
+        rep = charmapencode_lookup(p[collendpos], mapping);
+        if (rep==NULL)
+            return -1;
+        else if (rep!=Py_None) {
+            Py_DECREF(rep);
+            break;
+        }
+        Py_DECREF(rep);
+        ++collendpos;
     }
     /* cache callback name lookup
      * (if not done yet, i.e. it's the first error) */
     if (*known_errorHandler==-1) {
-	if ((errors==NULL) || (!strcmp(errors, "strict")))
-	    *known_errorHandler = 1;
-	else if (!strcmp(errors, "replace"))
-	    *known_errorHandler = 2;
-	else if (!strcmp(errors, "ignore"))
-	    *known_errorHandler = 3;
-	else if (!strcmp(errors, "xmlcharrefreplace"))
-	    *known_errorHandler = 4;
-	else
-	    *known_errorHandler = 0;
+        if ((errors==NULL) || (!strcmp(errors, "strict")))
+            *known_errorHandler = 1;
+        else if (!strcmp(errors, "replace"))
+            *known_errorHandler = 2;
+        else if (!strcmp(errors, "ignore"))
+            *known_errorHandler = 3;
+        else if (!strcmp(errors, "xmlcharrefreplace"))
+            *known_errorHandler = 4;
+        else
+            *known_errorHandler = 0;
     }
     switch (*known_errorHandler) {
-	case 1: /* strict */
-	    raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
-	    return -1;
-	case 2: /* replace */
-	    for (collpos = collstartpos; collpos<collendpos; ++collpos) {
-		x = charmapencode_output('?', mapping, res, respos);
-		if (x==enc_EXCEPTION) {
-		    return -1;
-		}
-		else if (x==enc_FAILED) {
-		    raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
-		    return -1;
-		}
-	    }
-	    /* fall through */
-	case 3: /* ignore */
-	    *inpos = collendpos;
-	    break;
-	case 4: /* xmlcharrefreplace */
-	    /* generate replacement (temporarily (mis)uses p) */
-	    for (collpos = collstartpos; collpos < collendpos; ++collpos) {
-		char buffer[2+29+1+1];
-		char *cp;
-		sprintf(buffer, "&#%d;", (int)p[collpos]);
-		for (cp = buffer; *cp; ++cp) {
-		    x = charmapencode_output(*cp, mapping, res, respos);
-		    if (x==enc_EXCEPTION)
-			return -1;
-		    else if (x==enc_FAILED) {
-			raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
-			return -1;
-		    }
-		}
-	    }
-	    *inpos = collendpos;
-	    break;
-	default:
-	    repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
-		encoding, reason, p, size, exceptionObject,
-		collstartpos, collendpos, &newpos);
-	    if (repunicode == NULL)
-		return -1;
-	    /* generate replacement  */
-	    repsize = PyUnicode_GET_SIZE(repunicode);
-	    for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
-		x = charmapencode_output(*uni2, mapping, res, respos);
-		if (x==enc_EXCEPTION) {
-		    return -1;
-		}
-		else if (x==enc_FAILED) {
-		    Py_DECREF(repunicode);
-		    raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
-		    return -1;
-		}
-	    }
-	    *inpos = newpos;
-	    Py_DECREF(repunicode);
+    case 1: /* strict */
+        raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
+        return -1;
+    case 2: /* replace */
+        for (collpos = collstartpos; collpos<collendpos; ++collpos) {
+            x = charmapencode_output('?', mapping, res, respos);
+            if (x==enc_EXCEPTION) {
+                return -1;
+            }
+            else if (x==enc_FAILED) {
+                raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
+                return -1;
+            }
+        }
+        /* fall through */
+    case 3: /* ignore */
+        *inpos = collendpos;
+        break;
+    case 4: /* xmlcharrefreplace */
+        /* generate replacement (temporarily (mis)uses p) */
+        for (collpos = collstartpos; collpos < collendpos; ++collpos) {
+            char buffer[2+29+1+1];
+            char *cp;
+            sprintf(buffer, "&#%d;", (int)p[collpos]);
+            for (cp = buffer; *cp; ++cp) {
+                x = charmapencode_output(*cp, mapping, res, respos);
+                if (x==enc_EXCEPTION)
+                    return -1;
+                else if (x==enc_FAILED) {
+                    raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
+                    return -1;
+                }
+            }
+        }
+        *inpos = collendpos;
+        break;
+    default:
+        repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
+                                                      encoding, reason, p, size, exceptionObject,
+                                                      collstartpos, collendpos, &newpos);
+        if (repunicode == NULL)
+            return -1;
+        /* generate replacement  */
+        repsize = PyUnicode_GET_SIZE(repunicode);
+        for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
+            x = charmapencode_output(*uni2, mapping, res, respos);
+            if (x==enc_EXCEPTION) {
+                return -1;
+            }
+            else if (x==enc_FAILED) {
+                Py_DECREF(repunicode);
+                raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
+                return -1;
+            }
+        }
+        *inpos = newpos;
+        Py_DECREF(repunicode);
     }
     return 0;
 }
 
 PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
-				  Py_ssize_t size,
-				  PyObject *mapping,
-				  const char *errors)
+                                  Py_ssize_t size,
+                                  PyObject *mapping,
+                                  const char *errors)
 {
     /* output object */
     PyObject *res = NULL;
@@ -5002,7 +5002,7 @@
 
     /* Default to Latin-1 */
     if (mapping == NULL)
-	return PyUnicode_EncodeLatin1(p, size, errors);
+        return PyUnicode_EncodeLatin1(p, size, errors);
 
     /* allocate enough for a simple encoding without
        replacements, if we need more, we'll resize */
@@ -5010,24 +5010,24 @@
     if (res == NULL)
         goto onError;
     if (size == 0)
-	return res;
+        return res;
 
     while (inpos<size) {
-	/* try to encode it */
-	charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
-	if (x==enc_EXCEPTION) /* error */
-	    goto onError;
-	if (x==enc_FAILED) { /* unencodable character */
-	    if (charmap_encoding_error(p, size, &inpos, mapping,
-		&exc,
-		&known_errorHandler, &errorHandler, errors,
-		&res, &respos)) {
-		goto onError;
-	    }
-	}
-	else
-	    /* done with this character => adjust input position */
-	    ++inpos;
+        /* try to encode it */
+        charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
+        if (x==enc_EXCEPTION) /* error */
+            goto onError;
+        if (x==enc_FAILED) { /* unencodable character */
+            if (charmap_encoding_error(p, size, &inpos, mapping,
+                                       &exc,
+                                       &known_errorHandler, &errorHandler, errors,
+                                       &res, &respos)) {
+                goto onError;
+            }
+        }
+        else
+            /* done with this character => adjust input position */
+            ++inpos;
     }
 
     /* Resize if we allocated to much */
@@ -5039,7 +5039,7 @@
     Py_XDECREF(errorHandler);
     return res;
 
-    onError:
+  onError:
     Py_XDECREF(res);
     Py_XDECREF(exc);
     Py_XDECREF(errorHandler);
@@ -5047,52 +5047,52 @@
 }
 
 PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
-				    PyObject *mapping)
+                                    PyObject *mapping)
 {
     if (!PyUnicode_Check(unicode) || mapping == NULL) {
-	PyErr_BadArgument();
-	return NULL;
+        PyErr_BadArgument();
+        return NULL;
     }
     return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
-				   PyUnicode_GET_SIZE(unicode),
-				   mapping,
-				   NULL);
+                                   PyUnicode_GET_SIZE(unicode),
+                                   mapping,
+                                   NULL);
 }
 
 /* create or adjust a UnicodeTranslateError */
 static void make_translate_exception(PyObject **exceptionObject,
-    const Py_UNICODE *unicode, Py_ssize_t size,
-    Py_ssize_t startpos, Py_ssize_t endpos,
-    const char *reason)
+                                     const Py_UNICODE *unicode, Py_ssize_t size,
+                                     Py_ssize_t startpos, Py_ssize_t endpos,
+                                     const char *reason)
 {
     if (*exceptionObject == NULL) {
-    	*exceptionObject = PyUnicodeTranslateError_Create(
-	    unicode, size, startpos, endpos, reason);
+        *exceptionObject = PyUnicodeTranslateError_Create(
+            unicode, size, startpos, endpos, reason);
     }
     else {
-	if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
-	    goto onError;
-	if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
-	    goto onError;
-	if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
-	    goto onError;
-	return;
-	onError:
-	Py_DECREF(*exceptionObject);
-	*exceptionObject = NULL;
+        if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
+            goto onError;
+        if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
+            goto onError;
+        if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
+            goto onError;
+        return;
+      onError:
+        Py_DECREF(*exceptionObject);
+        *exceptionObject = NULL;
     }
 }
 
 /* raises a UnicodeTranslateError */
 static void raise_translate_exception(PyObject **exceptionObject,
-    const Py_UNICODE *unicode, Py_ssize_t size,
-    Py_ssize_t startpos, Py_ssize_t endpos,
-    const char *reason)
+                                      const Py_UNICODE *unicode, Py_ssize_t size,
+                                      Py_ssize_t startpos, Py_ssize_t endpos,
+                                      const char *reason)
 {
     make_translate_exception(exceptionObject,
-	unicode, size, startpos, endpos, reason);
+                             unicode, size, startpos, endpos, reason);
     if (*exceptionObject != NULL)
-	PyCodec_StrictErrors(*exceptionObject);
+        PyCodec_StrictErrors(*exceptionObject);
 }
 
 /* error handling callback helper:
@@ -5100,11 +5100,11 @@
    put the result into newpos and return the replacement string, which
    has to be freed by the caller */
 static PyObject *unicode_translate_call_errorhandler(const char *errors,
-    PyObject **errorHandler,
-    const char *reason,
-    const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
-    Py_ssize_t startpos, Py_ssize_t endpos,
-    Py_ssize_t *newpos)
+                                                     PyObject **errorHandler,
+                                                     const char *reason,
+                                                     const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
+                                                     Py_ssize_t startpos, Py_ssize_t endpos,
+                                                     Py_ssize_t *newpos)
 {
     static char *argparse = "O!n;translating error handler must return (str, int) tuple";
 
@@ -5113,38 +5113,38 @@
     PyObject *resunicode;
 
     if (*errorHandler == NULL) {
-	*errorHandler = PyCodec_LookupError(errors);
+        *errorHandler = PyCodec_LookupError(errors);
         if (*errorHandler == NULL)
-	    return NULL;
+            return NULL;
     }
 
     make_translate_exception(exceptionObject,
-	unicode, size, startpos, endpos, reason);
+                             unicode, size, startpos, endpos, reason);
     if (*exceptionObject == NULL)
-	return NULL;
+        return NULL;
 
     restuple = PyObject_CallFunctionObjArgs(
-	*errorHandler, *exceptionObject, NULL);
+        *errorHandler, *exceptionObject, NULL);
     if (restuple == NULL)
-	return NULL;
+        return NULL;
     if (!PyTuple_Check(restuple)) {
-	PyErr_Format(PyExc_TypeError, &argparse[4]);
-	Py_DECREF(restuple);
-	return NULL;
+        PyErr_Format(PyExc_TypeError, &argparse[4]);
+        Py_DECREF(restuple);
+        return NULL;
     }
     if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
-	&resunicode, &i_newpos)) {
-	Py_DECREF(restuple);
-	return NULL;
+                          &resunicode, &i_newpos)) {
+        Py_DECREF(restuple);
+        return NULL;
     }
     if (i_newpos<0)
-	*newpos = size+i_newpos;
+        *newpos = size+i_newpos;
     else
         *newpos = i_newpos;
     if (*newpos<0 || *newpos>size) {
-	PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
-	Py_DECREF(restuple);
-	return NULL;
+        PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
+        Py_DECREF(restuple);
+        return NULL;
     }
     Py_INCREF(resunicode);
     Py_DECREF(restuple);
@@ -5161,63 +5161,63 @@
     PyObject *x;
 
     if (w == NULL)
-	 return -1;
+        return -1;
     x = PyObject_GetItem(mapping, w);
     Py_DECREF(w);
     if (x == NULL) {
-	if (PyErr_ExceptionMatches(PyExc_LookupError)) {
-	    /* No mapping found means: use 1:1 mapping. */
-	    PyErr_Clear();
-	    *result = NULL;
-	    return 0;
-	} else
-	    return -1;
+        if (PyErr_ExceptionMatches(PyExc_LookupError)) {
+            /* No mapping found means: use 1:1 mapping. */
+            PyErr_Clear();
+            *result = NULL;
+            return 0;
+        } else
+            return -1;
     }
     else if (x == Py_None) {
-	*result = x;
-	return 0;
+        *result = x;
+        return 0;
     }
     else if (PyLong_Check(x)) {
-	long value = PyLong_AS_LONG(x);
-	long max = PyUnicode_GetMax();
-	if (value < 0 || value > max) {
-	    PyErr_Format(PyExc_TypeError,
+        long value = PyLong_AS_LONG(x);
+        long max = PyUnicode_GetMax();
+        if (value < 0 || value > max) {
+            PyErr_Format(PyExc_TypeError,
                          "character mapping must be in range(0x%x)", max+1);
-	    Py_DECREF(x);
-	    return -1;
-	}
-	*result = x;
-	return 0;
+            Py_DECREF(x);
+            return -1;
+        }
+        *result = x;
+        return 0;
     }
     else if (PyUnicode_Check(x)) {
-	*result = x;
-	return 0;
+        *result = x;
+        return 0;
     }
     else {
-	/* wrong return value */
-	PyErr_SetString(PyExc_TypeError,
-	      "character mapping must return integer, None or str");
-	Py_DECREF(x);
-	return -1;
+        /* wrong return value */
+        PyErr_SetString(PyExc_TypeError,
+                        "character mapping must return integer, None or str");
+        Py_DECREF(x);
+        return -1;
     }
 }
 /* ensure that *outobj is at least requiredsize characters long,
-if not reallocate and adjust various state variables.
-Return 0 on success, -1 on error */
+   if not reallocate and adjust various state variables.
+   Return 0 on success, -1 on error */
 static
 int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
-    Py_ssize_t requiredsize)
+                               Py_ssize_t requiredsize)
 {
     Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
     if (requiredsize > oldsize) {
-	/* remember old output position */
-	Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
-	/* exponentially overallocate to minimize reallocations */
-	if (requiredsize < 2 * oldsize)
-	    requiredsize = 2 * oldsize;
-	if (PyUnicode_Resize(outobj, requiredsize) < 0)
-	    return -1;
-	*outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
+        /* remember old output position */
+        Py_ssize_t outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
+        /* exponentially overallocate to minimize reallocations */
+        if (requiredsize < 2 * oldsize)
+            requiredsize = 2 * oldsize;
+        if (PyUnicode_Resize(outobj, requiredsize) < 0)
+            return -1;
+        *outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
     }
     return 0;
 }
@@ -5229,47 +5229,47 @@
    Return 0 on success, -1 on error. */
 static
 int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
-    Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
-    PyObject **res)
+                            Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
+                            PyObject **res)
 {
     if (charmaptranslate_lookup(*curinp, mapping, res))
-	return -1;
+        return -1;
     if (*res==NULL) {
-	/* not found => default to 1:1 mapping */
-	*(*outp)++ = *curinp;
+        /* not found => default to 1:1 mapping */
+        *(*outp)++ = *curinp;
     }
     else if (*res==Py_None)
-	;
+        ;
     else if (PyLong_Check(*res)) {
-	/* no overflow check, because we know that the space is enough */
-	*(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
+        /* no overflow check, because we know that the space is enough */
+        *(*outp)++ = (Py_UNICODE)PyLong_AS_LONG(*res);
     }
     else if (PyUnicode_Check(*res)) {
-	Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
-	if (repsize==1) {
-	    /* no overflow check, because we know that the space is enough */
-	    *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
-	}
-	else if (repsize!=0) {
-	    /* more than one character */
-	    Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
-		(insize - (curinp-startinp)) +
-		repsize - 1;
-	    if (charmaptranslate_makespace(outobj, outp, requiredsize))
-		return -1;
-	    memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
-	    *outp += repsize;
-	}
+        Py_ssize_t repsize = PyUnicode_GET_SIZE(*res);
+        if (repsize==1) {
+            /* no overflow check, because we know that the space is enough */
+            *(*outp)++ = *PyUnicode_AS_UNICODE(*res);
+        }
+        else if (repsize!=0) {
+            /* more than one character */
+            Py_ssize_t requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
+                (insize - (curinp-startinp)) +
+                repsize - 1;
+            if (charmaptranslate_makespace(outobj, outp, requiredsize))
+                return -1;
+            memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
+            *outp += repsize;
+        }
     }
     else
-	return -1;
+        return -1;
     return 0;
 }
 
 PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
-				     Py_ssize_t size,
-				     PyObject *mapping,
-				     const char *errors)
+                                     Py_ssize_t size,
+                                     PyObject *mapping,
+                                     const char *errors)
 {
     /* output object */
     PyObject *res = NULL;
@@ -5289,119 +5289,119 @@
     int known_errorHandler = -1;
 
     if (mapping == NULL) {
-	PyErr_BadArgument();
-	return NULL;
+        PyErr_BadArgument();
+        return NULL;
     }
 
     /* allocate enough for a simple 1:1 translation without
        replacements, if we need more, we'll resize */
     res = PyUnicode_FromUnicode(NULL, size);
     if (res == NULL)
-	goto onError;
+        goto onError;
     if (size == 0)
-	return res;
+        return res;
     str = PyUnicode_AS_UNICODE(res);
 
     while (p<endp) {
-	/* try to encode it */
-	PyObject *x = NULL;
-	if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
-	    Py_XDECREF(x);
-	    goto onError;
-	}
-	Py_XDECREF(x);
-	if (x!=Py_None) /* it worked => adjust input pointer */
-	    ++p;
-	else { /* untranslatable character */
-	    PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
-	    Py_ssize_t repsize;
-	    Py_ssize_t newpos;
-	    Py_UNICODE *uni2;
-	    /* startpos for collecting untranslatable chars */
-	    const Py_UNICODE *collstart = p;
-	    const Py_UNICODE *collend = p+1;
-	    const Py_UNICODE *coll;
-
-	    /* find all untranslatable characters */
-	    while (collend < endp) {
-		if (charmaptranslate_lookup(*collend, mapping, &x))
-		    goto onError;
-		Py_XDECREF(x);
-		if (x!=Py_None)
-		    break;
-		++collend;
-	    }
-	    /* cache callback name lookup
-	     * (if not done yet, i.e. it's the first error) */
-	    if (known_errorHandler==-1) {
-		if ((errors==NULL) || (!strcmp(errors, "strict")))
-		    known_errorHandler = 1;
-		else if (!strcmp(errors, "replace"))
-		    known_errorHandler = 2;
-		else if (!strcmp(errors, "ignore"))
-		    known_errorHandler = 3;
-		else if (!strcmp(errors, "xmlcharrefreplace"))
-		    known_errorHandler = 4;
-		else
-		    known_errorHandler = 0;
-	    }
-	    switch (known_errorHandler) {
-		case 1: /* strict */
-		    raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
-		    goto onError;
-		case 2: /* replace */
-		    /* No need to check for space, this is a 1:1 replacement */
-		    for (coll = collstart; coll<collend; ++coll)
-			*str++ = '?';
-		    /* fall through */
-		case 3: /* ignore */
-		    p = collend;
-		    break;
-		case 4: /* xmlcharrefreplace */
-		    /* generate replacement (temporarily (mis)uses p) */
-		    for (p = collstart; p < collend; ++p) {
-			char buffer[2+29+1+1];
-			char *cp;
-			sprintf(buffer, "&#%d;", (int)*p);
-			if (charmaptranslate_makespace(&res, &str,
-			    (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
-			    goto onError;
-			for (cp = buffer; *cp; ++cp)
-			    *str++ = *cp;
-		    }
-		    p = collend;
-		    break;
-		default:
-		    repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
-			reason, startp, size, &exc,
-			collstart-startp, collend-startp, &newpos);
-		    if (repunicode == NULL)
-			goto onError;
-		    /* generate replacement  */
-		    repsize = PyUnicode_GET_SIZE(repunicode);
-		    if (charmaptranslate_makespace(&res, &str,
-			(str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
-			Py_DECREF(repunicode);
-			goto onError;
-		    }
-		    for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
-			*str++ = *uni2;
-		    p = startp + newpos;
-		    Py_DECREF(repunicode);
-	    }
-	}
+        /* try to encode it */
+        PyObject *x = NULL;
+        if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
+            Py_XDECREF(x);
+            goto onError;
+        }
+        Py_XDECREF(x);
+        if (x!=Py_None) /* it worked => adjust input pointer */
+            ++p;
+        else { /* untranslatable character */
+            PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
+            Py_ssize_t repsize;
+            Py_ssize_t newpos;
+            Py_UNICODE *uni2;
+            /* startpos for collecting untranslatable chars */
+            const Py_UNICODE *collstart = p;
+            const Py_UNICODE *collend = p+1;
+            const Py_UNICODE *coll;
+
+            /* find all untranslatable characters */
+            while (collend < endp) {
+                if (charmaptranslate_lookup(*collend, mapping, &x))
+                    goto onError;
+                Py_XDECREF(x);
+                if (x!=Py_None)
+                    break;
+                ++collend;
+            }
+            /* cache callback name lookup
+             * (if not done yet, i.e. it's the first error) */
+            if (known_errorHandler==-1) {
+                if ((errors==NULL) || (!strcmp(errors, "strict")))
+                    known_errorHandler = 1;
+                else if (!strcmp(errors, "replace"))
+                    known_errorHandler = 2;
+                else if (!strcmp(errors, "ignore"))
+                    known_errorHandler = 3;
+                else if (!strcmp(errors, "xmlcharrefreplace"))
+                    known_errorHandler = 4;
+                else
+                    known_errorHandler = 0;
+            }
+            switch (known_errorHandler) {
+            case 1: /* strict */
+                raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
+                goto onError;
+            case 2: /* replace */
+                /* No need to check for space, this is a 1:1 replacement */
+                for (coll = collstart; coll<collend; ++coll)
+                    *str++ = '?';
+                /* fall through */
+            case 3: /* ignore */
+                p = collend;
+                break;
+            case 4: /* xmlcharrefreplace */
+                /* generate replacement (temporarily (mis)uses p) */
+                for (p = collstart; p < collend; ++p) {
+                    char buffer[2+29+1+1];
+                    char *cp;
+                    sprintf(buffer, "&#%d;", (int)*p);
+                    if (charmaptranslate_makespace(&res, &str,
+                                                   (str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
+                        goto onError;
+                    for (cp = buffer; *cp; ++cp)
+                        *str++ = *cp;
+                }
+                p = collend;
+                break;
+            default:
+                repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
+                                                                 reason, startp, size, &exc,
+                                                                 collstart-startp, collend-startp, &newpos);
+                if (repunicode == NULL)
+                    goto onError;
+                /* generate replacement  */
+                repsize = PyUnicode_GET_SIZE(repunicode);
+                if (charmaptranslate_makespace(&res, &str,
+                                               (str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
+                    Py_DECREF(repunicode);
+                    goto onError;
+                }
+                for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
+                    *str++ = *uni2;
+                p = startp + newpos;
+                Py_DECREF(repunicode);
+            }
+        }
     }
     /* Resize if we allocated to much */
     respos = str-PyUnicode_AS_UNICODE(res);
     if (respos<PyUnicode_GET_SIZE(res)) {
-	if (PyUnicode_Resize(&res, respos) < 0)
-	    goto onError;
+        if (PyUnicode_Resize(&res, respos) < 0)
+            goto onError;
     }
     Py_XDECREF(exc);
     Py_XDECREF(errorHandler);
     return res;
 
-    onError:
+  onError:
     Py_XDECREF(res);
     Py_XDECREF(exc);
     Py_XDECREF(errorHandler);
@@ -5409,22 +5409,22 @@
 }
 
 PyObject *PyUnicode_Translate(PyObject *str,
-			      PyObject *mapping,
-			      const char *errors)
+                              PyObject *mapping,
+                              const char *errors)
 {
     PyObject *result;
 
     str = PyUnicode_FromObject(str);
     if (str == NULL)
-	goto onError;
+        goto onError;
     result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
-					PyUnicode_GET_SIZE(str),
-					mapping,
-					errors);
+                                        PyUnicode_GET_SIZE(str),
+                                        mapping,
+                                        errors);
     Py_DECREF(str);
     return result;
 
- onError:
+  onError:
     Py_XDECREF(str);
     return NULL;
 }
@@ -5432,9 +5432,9 @@
 /* --- Decimal Encoder ---------------------------------------------------- */
 
 int PyUnicode_EncodeDecimal(Py_UNICODE *s,
-			    Py_ssize_t length,
-			    char *output,
-			    const char *errors)
+                            Py_ssize_t length,
+                            char *output,
+                            const char *errors)
 {
     Py_UNICODE *p, *end;
     PyObject *errorHandler = NULL;
@@ -5446,107 +5446,107 @@
     int known_errorHandler = -1;
 
     if (output == NULL) {
-	PyErr_BadArgument();
-	return -1;
+        PyErr_BadArgument();
+        return -1;
     }
 
     p = s;
     end = s + length;
     while (p < end) {
-	register Py_UNICODE ch = *p;
-	int decimal;
-	PyObject *repunicode;
-	Py_ssize_t repsize;
-	Py_ssize_t newpos;
-	Py_UNICODE *uni2;
-	Py_UNICODE *collstart;
-	Py_UNICODE *collend;
-
-	if (Py_UNICODE_ISSPACE(ch)) {
-	    *output++ = ' ';
-	    ++p;
-	    continue;
-	}
-	decimal = Py_UNICODE_TODECIMAL(ch);
-	if (decimal >= 0) {
-	    *output++ = '0' + decimal;
-	    ++p;
-	    continue;
-	}
-	if (0 < ch && ch < 256) {
-	    *output++ = (char)ch;
-	    ++p;
-	    continue;
-	}
-	/* All other characters are considered unencodable */
-	collstart = p;
-	collend = p+1;
-	while (collend < end) {
-	    if ((0 < *collend && *collend < 256) ||
-	        !Py_UNICODE_ISSPACE(*collend) ||
-	        Py_UNICODE_TODECIMAL(*collend))
-		break;
-	}
-	/* cache callback name lookup
-	 * (if not done yet, i.e. it's the first error) */
-	if (known_errorHandler==-1) {
-	    if ((errors==NULL) || (!strcmp(errors, "strict")))
-		known_errorHandler = 1;
-	    else if (!strcmp(errors, "replace"))
-		known_errorHandler = 2;
-	    else if (!strcmp(errors, "ignore"))
-		known_errorHandler = 3;
-	    else if (!strcmp(errors, "xmlcharrefreplace"))
-		known_errorHandler = 4;
-	    else
-		known_errorHandler = 0;
-	}
-	switch (known_errorHandler) {
-	    case 1: /* strict */
-		raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
-		goto onError;
-	    case 2: /* replace */
-		for (p = collstart; p < collend; ++p)
-		    *output++ = '?';
-		/* fall through */
-	    case 3: /* ignore */
-		p = collend;
-		break;
-	    case 4: /* xmlcharrefreplace */
-		/* generate replacement (temporarily (mis)uses p) */
-		for (p = collstart; p < collend; ++p)
-		    output += sprintf(output, "&#%d;", (int)*p);
-		p = collend;
-		break;
-	    default:
-		repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
-		    encoding, reason, s, length, &exc,
-		    collstart-s, collend-s, &newpos);
-		if (repunicode == NULL)
-		    goto onError;
-		/* generate replacement  */
-		repsize = PyUnicode_GET_SIZE(repunicode);
-		for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
-		    Py_UNICODE ch = *uni2;
-		    if (Py_UNICODE_ISSPACE(ch))
-			*output++ = ' ';
-		    else {
-			decimal = Py_UNICODE_TODECIMAL(ch);
-			if (decimal >= 0)
-			    *output++ = '0' + decimal;
-			else if (0 < ch && ch < 256)
-			    *output++ = (char)ch;
-			else {
-			    Py_DECREF(repunicode);
-			    raise_encode_exception(&exc, encoding,
-				s, length, collstart-s, collend-s, reason);
-			    goto onError;
-			}
-		    }
-		}
-		p = s + newpos;
-		Py_DECREF(repunicode);
-	}
+        register Py_UNICODE ch = *p;
+        int decimal;
+        PyObject *repunicode;
+        Py_ssize_t repsize;
+        Py_ssize_t newpos;
+        Py_UNICODE *uni2;
+        Py_UNICODE *collstart;
+        Py_UNICODE *collend;
+
+        if (Py_UNICODE_ISSPACE(ch)) {
+            *output++ = ' ';
+            ++p;
+            continue;
+        }
+        decimal = Py_UNICODE_TODECIMAL(ch);
+        if (decimal >= 0) {
+            *output++ = '0' + decimal;
+            ++p;
+            continue;
+        }
+        if (0 < ch && ch < 256) {
+            *output++ = (char)ch;
+            ++p;
+            continue;
+        }
+        /* All other characters are considered unencodable */
+        collstart = p;
+        collend = p+1;
+        while (collend < end) {
+            if ((0 < *collend && *collend < 256) ||
+                !Py_UNICODE_ISSPACE(*collend) ||
+                Py_UNICODE_TODECIMAL(*collend))
+                break;
+        }
+        /* cache callback name lookup
+         * (if not done yet, i.e. it's the first error) */
+        if (known_errorHandler==-1) {
+            if ((errors==NULL) || (!strcmp(errors, "strict")))
+                known_errorHandler = 1;
+            else if (!strcmp(errors, "replace"))
+                known_errorHandler = 2;
+            else if (!strcmp(errors, "ignore"))
+                known_errorHandler = 3;
+            else if (!strcmp(errors, "xmlcharrefreplace"))
+                known_errorHandler = 4;
+            else
+                known_errorHandler = 0;
+        }
+        switch (known_errorHandler) {
+        case 1: /* strict */
+            raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
+            goto onError;
+        case 2: /* replace */
+            for (p = collstart; p < collend; ++p)
+                *output++ = '?';
+            /* fall through */
+        case 3: /* ignore */
+            p = collend;
+            break;
+        case 4: /* xmlcharrefreplace */
+            /* generate replacement (temporarily (mis)uses p) */
+            for (p = collstart; p < collend; ++p)
+                output += sprintf(output, "&#%d;", (int)*p);
+            p = collend;
+            break;
+        default:
+            repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
+                                                          encoding, reason, s, length, &exc,
+                                                          collstart-s, collend-s, &newpos);
+            if (repunicode == NULL)
+                goto onError;
+            /* generate replacement  */
+            repsize = PyUnicode_GET_SIZE(repunicode);
+            for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
+                Py_UNICODE ch = *uni2;
+                if (Py_UNICODE_ISSPACE(ch))
+                    *output++ = ' ';
+                else {
+                    decimal = Py_UNICODE_TODECIMAL(ch);
+                    if (decimal >= 0)
+                        *output++ = '0' + decimal;
+                    else if (0 < ch && ch < 256)
+                        *output++ = (char)ch;
+                    else {
+                        Py_DECREF(repunicode);
+                        raise_encode_exception(&exc, encoding,
+                                               s, length, collstart-s, collend-s, reason);
+                        goto onError;
+                    }
+                }
+            }
+            p = s + newpos;
+            Py_DECREF(repunicode);
+        }
     }
     /* 0-terminate the output string */
     *output++ = '\0';
@@ -5554,7 +5554,7 @@
     Py_XDECREF(errorHandler);
     return 0;
 
- onError:
+  onError:
     Py_XDECREF(exc);
     Py_XDECREF(errorHandler);
     return -1;
@@ -5597,11 +5597,11 @@
 
     str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
     if (!str_obj)
-	return -1;
+        return -1;
     sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
     if (!sub_obj) {
-	Py_DECREF(str_obj);
-	return -1;
+        Py_DECREF(str_obj);
+        return -1;
     }
 
     FIX_START_END(str_obj);
@@ -5626,11 +5626,11 @@
 
     str = PyUnicode_FromObject(str);
     if (!str)
-	return -2;
+        return -2;
     sub = PyUnicode_FromObject(sub);
     if (!sub) {
-	Py_DECREF(str);
-	return -2;
+        Py_DECREF(str);
+        return -2;
     }
 
     if (direction > 0)
@@ -5654,10 +5654,10 @@
 
 static
 int tailmatch(PyUnicodeObject *self,
-	      PyUnicodeObject *substring,
-	      Py_ssize_t start,
-	      Py_ssize_t end,
-	      int direction)
+              PyUnicodeObject *substring,
+              Py_ssize_t start,
+              Py_ssize_t end,
+              int direction)
 {
     if (substring->length == 0)
         return 1;
@@ -5666,39 +5666,39 @@
 
     end -= substring->length;
     if (end < start)
-	return 0;
+        return 0;
 
     if (direction > 0) {
-	if (Py_UNICODE_MATCH(self, end, substring))
-	    return 1;
+        if (Py_UNICODE_MATCH(self, end, substring))
+            return 1;
     } else {
         if (Py_UNICODE_MATCH(self, start, substring))
-	    return 1;
+            return 1;
     }
 
     return 0;
 }
 
 Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
-			PyObject *substr,
-			Py_ssize_t start,
-			Py_ssize_t end,
-			int direction)
+                               PyObject *substr,
+                               Py_ssize_t start,
+                               Py_ssize_t end,
+                               int direction)
 {
     Py_ssize_t result;
 
     str = PyUnicode_FromObject(str);
     if (str == NULL)
-	return -1;
+        return -1;
     substr = PyUnicode_FromObject(substr);
     if (substr == NULL) {
-	Py_DECREF(str);
-	return -1;
+        Py_DECREF(str);
+        return -1;
     }
 
     result = tailmatch((PyUnicodeObject *)str,
-		       (PyUnicodeObject *)substr,
-		       start, end, direction);
+                       (PyUnicodeObject *)substr,
+                       start, end, direction);
     Py_DECREF(str);
     Py_DECREF(substr);
     return result;
@@ -5709,24 +5709,24 @@
 
 static
 PyObject *fixup(PyUnicodeObject *self,
-		int (*fixfct)(PyUnicodeObject *s))
+                int (*fixfct)(PyUnicodeObject *s))
 {
 
     PyUnicodeObject *u;
 
     u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
     if (u == NULL)
-	return NULL;
+        return NULL;
 
     Py_UNICODE_COPY(u->str, self->str, self->length);
 
     if (!fixfct(u) && PyUnicode_CheckExact(self)) {
-	/* fixfct should return TRUE if it modified the buffer. If
-	   FALSE, return a reference to the original buffer instead
-	   (to save space, not time) */
-	Py_INCREF(self);
-	Py_DECREF(u);
-	return (PyObject*) self;
+        /* fixfct should return TRUE if it modified the buffer. If
+           FALSE, return a reference to the original buffer instead
+           (to save space, not time) */
+        Py_INCREF(self);
+        Py_DECREF(u);
+        return (PyObject*) self;
     }
     return (PyObject*) u;
 }
@@ -5739,13 +5739,13 @@
     int status = 0;
 
     while (len-- > 0) {
-	register Py_UNICODE ch;
+        register Py_UNICODE ch;
 
-	ch = Py_UNICODE_TOUPPER(*s);
-	if (ch != *s) {
+        ch = Py_UNICODE_TOUPPER(*s);
+        if (ch != *s) {
             status = 1;
-	    *s = ch;
-	}
+            *s = ch;
+        }
         s++;
     }
 
@@ -5760,13 +5760,13 @@
     int status = 0;
 
     while (len-- > 0) {
-	register Py_UNICODE ch;
+        register Py_UNICODE ch;
 
-	ch = Py_UNICODE_TOLOWER(*s);
-	if (ch != *s) {
+        ch = Py_UNICODE_TOLOWER(*s);
+        if (ch != *s) {
             status = 1;
-	    *s = ch;
-	}
+            *s = ch;
+        }
         s++;
     }
 
@@ -5802,10 +5802,10 @@
     int status = 0;
 
     if (len == 0)
-	return 0;
+        return 0;
     if (Py_UNICODE_ISLOWER(*s)) {
-	*s = Py_UNICODE_TOUPPER(*s);
-	status = 1;
+        *s = Py_UNICODE_TOUPPER(*s);
+        status = 1;
     }
     s++;
     while (--len > 0) {
@@ -5827,31 +5827,31 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1) {
-	Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
-	if (*p != ch) {
-	    *p = ch;
-	    return 1;
-	}
-	else
-	    return 0;
+        Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
+        if (*p != ch) {
+            *p = ch;
+            return 1;
+        }
+        else
+            return 0;
     }
 
     e = p + PyUnicode_GET_SIZE(self);
     previous_is_cased = 0;
     for (; p < e; p++) {
-	register const Py_UNICODE ch = *p;
+        register const Py_UNICODE ch = *p;
 
-	if (previous_is_cased)
-	    *p = Py_UNICODE_TOLOWER(ch);
-	else
-	    *p = Py_UNICODE_TOTITLE(ch);
-
-	if (Py_UNICODE_ISLOWER(ch) ||
-	    Py_UNICODE_ISUPPER(ch) ||
-	    Py_UNICODE_ISTITLE(ch))
-	    previous_is_cased = 1;
-	else
-	    previous_is_cased = 0;
+        if (previous_is_cased)
+            *p = Py_UNICODE_TOLOWER(ch);
+        else
+            *p = Py_UNICODE_TOTITLE(ch);
+
+        if (Py_UNICODE_ISLOWER(ch) ||
+            Py_UNICODE_ISUPPER(ch) ||
+            Py_UNICODE_ISTITLE(ch))
+            previous_is_cased = 1;
+        else
+            previous_is_cased = 0;
     }
     return 1;
 }
@@ -5872,7 +5872,7 @@
 
     fseq = PySequence_Fast(seq, "");
     if (fseq == NULL) {
-    	return NULL;
+        return NULL;
     }
 
     /* NOTE: the following code can't call back into Python code,
@@ -5882,18 +5882,18 @@
     seqlen = PySequence_Fast_GET_SIZE(fseq);
     /* If empty sequence, return u"". */
     if (seqlen == 0) {
-    	res = _PyUnicode_New(0);  /* empty sequence; return u"" */
-    	goto Done;
+        res = _PyUnicode_New(0);  /* empty sequence; return u"" */
+        goto Done;
     }
     items = PySequence_Fast_ITEMS(fseq);
     /* If singleton sequence with an exact Unicode, return that. */
     if (seqlen == 1) {
-	item = items[0];
-	if (PyUnicode_CheckExact(item)) {
-	    Py_INCREF(item);
-	    res = (PyUnicodeObject *)item;
-	    goto Done;
-	}
+        item = items[0];
+        if (PyUnicode_CheckExact(item)) {
+            Py_INCREF(item);
+            res = (PyUnicodeObject *)item;
+            goto Done;
+        }
     }
     else {
         /* Set up sep and seplen */
@@ -5923,19 +5923,19 @@
     for (i = 0; i < seqlen; i++) {
         const Py_ssize_t old_sz = sz;
         item = items[i];
-	if (!PyUnicode_Check(item)) {
-	    PyErr_Format(PyExc_TypeError,
-			 "sequence item %zd: expected str instance,"
-			 " %.80s found",
-			 i, Py_TYPE(item)->tp_name);
-	    goto onError;
-	}
+        if (!PyUnicode_Check(item)) {
+            PyErr_Format(PyExc_TypeError,
+                         "sequence item %zd: expected str instance,"
+                         " %.80s found",
+                         i, Py_TYPE(item)->tp_name);
+            goto onError;
+        }
         sz += PyUnicode_GET_SIZE(item);
         if (i != 0)
             sz += seplen;
         if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
             PyErr_SetString(PyExc_OverflowError,
-                "join() result is too long for a Python string");
+                            "join() result is too long for a Python string");
             goto onError;
         }
     }
@@ -5950,20 +5950,20 @@
         Py_ssize_t itemlen;
         item = items[i];
         itemlen = PyUnicode_GET_SIZE(item);
-	/* Copy item, and maybe the separator. */
-	if (i) {
-	    Py_UNICODE_COPY(res_p, sep, seplen);
-	    res_p += seplen;
-	}
-	Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
-	res_p += itemlen;
+        /* Copy item, and maybe the separator. */
+        if (i) {
+            Py_UNICODE_COPY(res_p, sep, seplen);
+            res_p += seplen;
+        }
+        Py_UNICODE_COPY(res_p, PyUnicode_AS_UNICODE(item), itemlen);
+        res_p += itemlen;
     }
 
- Done:
+  Done:
     Py_DECREF(fseq);
     return (PyObject *)res;
 
- onError:
+  onError:
     Py_DECREF(fseq);
     Py_XDECREF(res);
     return NULL;
@@ -5971,9 +5971,9 @@
 
 static
 PyUnicodeObject *pad(PyUnicodeObject *self,
-		     Py_ssize_t left,
-		     Py_ssize_t right,
-		     Py_UNICODE fill)
+                     Py_ssize_t left,
+                     Py_ssize_t right,
+                     Py_UNICODE fill)
 {
     PyUnicodeObject *u;
 
@@ -6004,21 +6004,21 @@
     return u;
 }
 
-#define SPLIT_APPEND(data, left, right)					\
-	str = PyUnicode_FromUnicode((data) + (left), (right) - (left));	\
-	if (!str)							\
-	    goto onError;						\
-	if (PyList_Append(list, str)) {					\
-	    Py_DECREF(str);						\
-	    goto onError;						\
-	}								\
-        else								\
-            Py_DECREF(str);
+#define SPLIT_APPEND(data, left, right)                                 \
+    str = PyUnicode_FromUnicode((data) + (left), (right) - (left));     \
+    if (!str)                                                           \
+        goto onError;                                                   \
+    if (PyList_Append(list, str)) {                                     \
+        Py_DECREF(str);                                                 \
+        goto onError;                                                   \
+    }                                                                   \
+    else                                                                \
+        Py_DECREF(str);
 
 static
 PyObject *split_whitespace(PyUnicodeObject *self,
-			   PyObject *list,
-			   Py_ssize_t maxcount)
+                           PyObject *list,
+                           Py_ssize_t maxcount)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6027,33 +6027,33 @@
     register const Py_UNICODE *buf = self->str;
 
     for (i = j = 0; i < len; ) {
-	/* find a token */
-	while (i < len && Py_UNICODE_ISSPACE(buf[i]))
-	    i++;
-	j = i;
-	while (i < len && !Py_UNICODE_ISSPACE(buf[i]))
-	    i++;
-	if (j < i) {
-	    if (maxcount-- <= 0)
-		break;
-	    SPLIT_APPEND(buf, j, i);
-	    while (i < len && Py_UNICODE_ISSPACE(buf[i]))
-		i++;
-	    j = i;
-	}
+        /* find a token */
+        while (i < len && Py_UNICODE_ISSPACE(buf[i]))
+            i++;
+        j = i;
+        while (i < len && !Py_UNICODE_ISSPACE(buf[i]))
+            i++;
+        if (j < i) {
+            if (maxcount-- <= 0)
+                break;
+            SPLIT_APPEND(buf, j, i);
+            while (i < len && Py_UNICODE_ISSPACE(buf[i]))
+                i++;
+            j = i;
+        }
     }
     if (j < len) {
-	SPLIT_APPEND(buf, j, len);
+        SPLIT_APPEND(buf, j, len);
     }
     return list;
 
- onError:
+  onError:
     Py_DECREF(list);
     return NULL;
 }
 
 PyObject *PyUnicode_Splitlines(PyObject *string,
-			       int keepends)
+                               int keepends)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6064,7 +6064,7 @@
 
     string = PyUnicode_FromObject(string);
     if (string == NULL)
-	return NULL;
+        return NULL;
     data = PyUnicode_AS_UNICODE(string);
     len = PyUnicode_GET_SIZE(string);
 
@@ -6073,34 +6073,34 @@
         goto onError;
 
     for (i = j = 0; i < len; ) {
-	Py_ssize_t eol;
+        Py_ssize_t eol;
 
-	/* Find a line and append it */
-	while (i < len && !BLOOM_LINEBREAK(data[i]))
-	    i++;
-
-	/* Skip the line break reading CRLF as one line break */
-	eol = i;
-	if (i < len) {
-	    if (data[i] == '\r' && i + 1 < len &&
-		data[i+1] == '\n')
-		i += 2;
-	    else
-		i++;
-	    if (keepends)
-		eol = i;
-	}
-	SPLIT_APPEND(data, j, eol);
-	j = i;
+        /* Find a line and append it */
+        while (i < len && !BLOOM_LINEBREAK(data[i]))
+            i++;
+
+        /* Skip the line break reading CRLF as one line break */
+        eol = i;
+        if (i < len) {
+            if (data[i] == '\r' && i + 1 < len &&
+                data[i+1] == '\n')
+                i += 2;
+            else
+                i++;
+            if (keepends)
+                eol = i;
+        }
+        SPLIT_APPEND(data, j, eol);
+        j = i;
     }
     if (j < len) {
-	SPLIT_APPEND(data, j, len);
+        SPLIT_APPEND(data, j, len);
     }
 
     Py_DECREF(string);
     return list;
 
- onError:
+  onError:
     Py_XDECREF(list);
     Py_DECREF(string);
     return NULL;
@@ -6108,9 +6108,9 @@
 
 static
 PyObject *split_char(PyUnicodeObject *self,
-		     PyObject *list,
-		     Py_UNICODE ch,
-		     Py_ssize_t maxcount)
+                     PyObject *list,
+                     Py_UNICODE ch,
+                     Py_ssize_t maxcount)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6119,29 +6119,29 @@
     register const Py_UNICODE *buf = self->str;
 
     for (i = j = 0; i < len; ) {
-	if (buf[i] == ch) {
-	    if (maxcount-- <= 0)
-		break;
-	    SPLIT_APPEND(buf, j, i);
-	    i = j = i + 1;
-	} else
-	    i++;
+        if (buf[i] == ch) {
+            if (maxcount-- <= 0)
+                break;
+            SPLIT_APPEND(buf, j, i);
+            i = j = i + 1;
+        } else
+            i++;
     }
     if (j <= len) {
-	SPLIT_APPEND(buf, j, len);
+        SPLIT_APPEND(buf, j, len);
     }
     return list;
 
- onError:
+  onError:
     Py_DECREF(list);
     return NULL;
 }
 
 static
 PyObject *split_substring(PyUnicodeObject *self,
-			  PyObject *list,
-			  PyUnicodeObject *substring,
-			  Py_ssize_t maxcount)
+                          PyObject *list,
+                          PyUnicodeObject *substring,
+                          Py_ssize_t maxcount)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6150,28 +6150,28 @@
     PyObject *str;
 
     for (i = j = 0; i <= len - sublen; ) {
-	if (Py_UNICODE_MATCH(self, i, substring)) {
-	    if (maxcount-- <= 0)
-		break;
-	    SPLIT_APPEND(self->str, j, i);
-	    i = j = i + sublen;
-	} else
-	    i++;
+        if (Py_UNICODE_MATCH(self, i, substring)) {
+            if (maxcount-- <= 0)
+                break;
+            SPLIT_APPEND(self->str, j, i);
+            i = j = i + sublen;
+        } else
+            i++;
     }
     if (j <= len) {
-	SPLIT_APPEND(self->str, j, len);
+        SPLIT_APPEND(self->str, j, len);
     }
     return list;
 
- onError:
+  onError:
     Py_DECREF(list);
     return NULL;
 }
 
 static
 PyObject *rsplit_whitespace(PyUnicodeObject *self,
-			    PyObject *list,
-			    Py_ssize_t maxcount)
+                            PyObject *list,
+                            Py_ssize_t maxcount)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6180,38 +6180,38 @@
     register const Py_UNICODE *buf = self->str;
 
     for (i = j = len - 1; i >= 0; ) {
-	/* find a token */
-	while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
-	    i--;
-	j = i;
-	while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i]))
-	    i--;
-	if (j > i) {
-	    if (maxcount-- <= 0)
-		break;
-	    SPLIT_APPEND(buf, i + 1, j + 1);
-	    while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
-		i--;
-	    j = i;
-	}
+        /* find a token */
+        while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
+            i--;
+        j = i;
+        while (i >= 0 && !Py_UNICODE_ISSPACE(buf[i]))
+            i--;
+        if (j > i) {
+            if (maxcount-- <= 0)
+                break;
+            SPLIT_APPEND(buf, i + 1, j + 1);
+            while (i >= 0 && Py_UNICODE_ISSPACE(buf[i]))
+                i--;
+            j = i;
+        }
     }
     if (j >= 0) {
-	SPLIT_APPEND(buf, 0, j + 1);
+        SPLIT_APPEND(buf, 0, j + 1);
     }
     if (PyList_Reverse(list) < 0)
         goto onError;
     return list;
 
- onError:
+  onError:
     Py_DECREF(list);
     return NULL;
 }
 
-static 
+static
 PyObject *rsplit_char(PyUnicodeObject *self,
-		      PyObject *list,
-		      Py_UNICODE ch,
-		      Py_ssize_t maxcount)
+                      PyObject *list,
+                      Py_UNICODE ch,
+                      Py_ssize_t maxcount)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6220,31 +6220,31 @@
     register const Py_UNICODE *buf = self->str;
 
     for (i = j = len - 1; i >= 0; ) {
-	if (buf[i] == ch) {
-	    if (maxcount-- <= 0)
-		break;
-	    SPLIT_APPEND(buf, i + 1, j + 1);
-	    j = i = i - 1;
-	} else
-	    i--;
+        if (buf[i] == ch) {
+            if (maxcount-- <= 0)
+                break;
+            SPLIT_APPEND(buf, i + 1, j + 1);
+            j = i = i - 1;
+        } else
+            i--;
     }
     if (j >= -1) {
-	SPLIT_APPEND(buf, 0, j + 1);
+        SPLIT_APPEND(buf, 0, j + 1);
     }
     if (PyList_Reverse(list) < 0)
         goto onError;
     return list;
 
- onError:
+  onError:
     Py_DECREF(list);
     return NULL;
 }
 
-static 
+static
 PyObject *rsplit_substring(PyUnicodeObject *self,
-			   PyObject *list,
-			   PyUnicodeObject *substring,
-			   Py_ssize_t maxcount)
+                           PyObject *list,
+                           PyUnicodeObject *substring,
+                           Py_ssize_t maxcount)
 {
     register Py_ssize_t i;
     register Py_ssize_t j;
@@ -6253,23 +6253,23 @@
     PyObject *str;
 
     for (i = len - sublen, j = len; i >= 0; ) {
-	if (Py_UNICODE_MATCH(self, i, substring)) {
-	    if (maxcount-- <= 0)
-		break;
-	    SPLIT_APPEND(self->str, i + sublen, j);
-	    j = i;
-	    i -= sublen;
-	} else
-	    i--;
+        if (Py_UNICODE_MATCH(self, i, substring)) {
+            if (maxcount-- <= 0)
+                break;
+            SPLIT_APPEND(self->str, i + sublen, j);
+            j = i;
+            i -= sublen;
+        } else
+            i--;
     }
     if (j >= 0) {
-	SPLIT_APPEND(self->str, 0, j);
+        SPLIT_APPEND(self->str, 0, j);
     }
     if (PyList_Reverse(list) < 0)
         goto onError;
     return list;
 
- onError:
+  onError:
     Py_DECREF(list);
     return NULL;
 }
@@ -6278,8 +6278,8 @@
 
 static
 PyObject *split(PyUnicodeObject *self,
-		PyUnicodeObject *substring,
-		Py_ssize_t maxcount)
+                PyUnicodeObject *substring,
+                Py_ssize_t maxcount)
 {
     PyObject *list;
 
@@ -6291,24 +6291,24 @@
         return NULL;
 
     if (substring == NULL)
-	return split_whitespace(self,list,maxcount);
+        return split_whitespace(self,list,maxcount);
 
     else if (substring->length == 1)
-	return split_char(self,list,substring->str[0],maxcount);
+        return split_char(self,list,substring->str[0],maxcount);
 
     else if (substring->length == 0) {
-	Py_DECREF(list);
-	PyErr_SetString(PyExc_ValueError, "empty separator");
-	return NULL;
+        Py_DECREF(list);
+        PyErr_SetString(PyExc_ValueError, "empty separator");
+        return NULL;
     }
     else
-	return split_substring(self,list,substring,maxcount);
+        return split_substring(self,list,substring,maxcount);
 }
 
 static
 PyObject *rsplit(PyUnicodeObject *self,
-		 PyUnicodeObject *substring,
-		 Py_ssize_t maxcount)
+                 PyUnicodeObject *substring,
+                 Py_ssize_t maxcount)
 {
     PyObject *list;
 
@@ -6320,30 +6320,30 @@
         return NULL;
 
     if (substring == NULL)
-	return rsplit_whitespace(self,list,maxcount);
+        return rsplit_whitespace(self,list,maxcount);
 
     else if (substring->length == 1)
-	return rsplit_char(self,list,substring->str[0],maxcount);
+        return rsplit_char(self,list,substring->str[0],maxcount);
 
     else if (substring->length == 0) {
-	Py_DECREF(list);
-	PyErr_SetString(PyExc_ValueError, "empty separator");
-	return NULL;
+        Py_DECREF(list);
+        PyErr_SetString(PyExc_ValueError, "empty separator");
+        return NULL;
     }
     else
-	return rsplit_substring(self,list,substring,maxcount);
+        return rsplit_substring(self,list,substring,maxcount);
 }
 
 static
 PyObject *replace(PyUnicodeObject *self,
-		  PyUnicodeObject *str1,
-		  PyUnicodeObject *str2,
-		  Py_ssize_t maxcount)
+                  PyUnicodeObject *str1,
+                  PyUnicodeObject *str2,
+                  Py_ssize_t maxcount)
 {
     PyUnicodeObject *u;
 
     if (maxcount < 0)
-	maxcount = PY_SSIZE_T_MAX;
+        maxcount = PY_SSIZE_T_MAX;
 
     if (str1->length == str2->length) {
         /* same length */
@@ -6429,7 +6429,7 @@
                         break;
                     j++;
                 }
-		if (j > i) {
+                if (j > i) {
                     if (j > e)
                         break;
                     /* copy unchanged part [i:j] */
@@ -6460,7 +6460,7 @@
     }
     return (PyObject *) u;
 
-nothing:
+  nothing:
     /* nothing to replace; return original string (when possible) */
     if (PyUnicode_CheckExact(self)) {
         Py_INCREF(self);
@@ -6472,7 +6472,7 @@
 /* --- Unicode Object Methods --------------------------------------------- */
 
 PyDoc_STRVAR(title__doc__,
-"S.title() -> str\n\
+             "S.title() -> str\n\
 \n\
 Return a titlecased version of S, i.e. words start with title case\n\
 characters, all remaining cased characters have lower case.");
@@ -6484,7 +6484,7 @@
 }
 
 PyDoc_STRVAR(capitalize__doc__,
-"S.capitalize() -> str\n\
+             "S.capitalize() -> str\n\
 \n\
 Return a capitalized version of S, i.e. make the first character\n\
 have upper case.");
@@ -6497,7 +6497,7 @@
 
 #if 0
 PyDoc_STRVAR(capwords__doc__,
-"S.capwords() -> str\n\
+             "S.capwords() -> str\n\
 \n\
 Apply .capitalize() to all words in S and return the result with\n\
 normalized whitespace (all whitespace strings are replaced by ' ').");
@@ -6517,7 +6517,7 @@
     /* Capitalize each word */
     for (i = 0; i < PyList_GET_SIZE(list); i++) {
         item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
-		     fixcapitalize);
+                     fixcapitalize);
         if (item == NULL)
             goto onError;
         Py_DECREF(PyList_GET_ITEM(list, i));
@@ -6527,7 +6527,7 @@
     /* Join the words to form a new string */
     item = PyUnicode_Join(NULL, list);
 
-onError:
+  onError:
     Py_DECREF(list);
     return (PyObject *)item;
 }
@@ -6538,30 +6538,30 @@
 static int
 convert_uc(PyObject *obj, void *addr)
 {
-	Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
-	PyObject *uniobj;
-	Py_UNICODE *unistr;
-
-	uniobj = PyUnicode_FromObject(obj);
-	if (uniobj == NULL) {
-		PyErr_SetString(PyExc_TypeError,
-			"The fill character cannot be converted to Unicode");
-		return 0;
-	}
-	if (PyUnicode_GET_SIZE(uniobj) != 1) {
-		PyErr_SetString(PyExc_TypeError,
-			"The fill character must be exactly one character long");
-		Py_DECREF(uniobj);
-		return 0;
-	}
-	unistr = PyUnicode_AS_UNICODE(uniobj);
-	*fillcharloc = unistr[0];
-	Py_DECREF(uniobj);
-	return 1;
+    Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
+    PyObject *uniobj;
+    Py_UNICODE *unistr;
+
+    uniobj = PyUnicode_FromObject(obj);
+    if (uniobj == NULL) {
+        PyErr_SetString(PyExc_TypeError,
+                        "The fill character cannot be converted to Unicode");
+        return 0;
+    }
+    if (PyUnicode_GET_SIZE(uniobj) != 1) {
+        PyErr_SetString(PyExc_TypeError,
+                        "The fill character must be exactly one character long");
+        Py_DECREF(uniobj);
+        return 0;
+    }
+    unistr = PyUnicode_AS_UNICODE(uniobj);
+    *fillcharloc = unistr[0];
+    Py_DECREF(uniobj);
+    return 1;
 }
 
 PyDoc_STRVAR(center__doc__,
-"S.center(width[, fillchar]) -> str\n\
+             "S.center(width[, fillchar]) -> str\n\
 \n\
 Return S centered in a string of length width. Padding is\n\
 done using the specified fill character (default is a space)");
@@ -6622,9 +6622,9 @@
         c1 = *s1++;
         c2 = *s2++;
 
-	if (c1 > (1<<11) * 26)
-	    c1 += utf16Fixup[c1>>11];
-	if (c2 > (1<<11) * 26)
+        if (c1 > (1<<11) * 26)
+            c1 += utf16Fixup[c1>>11];
+        if (c2 > (1<<11) * 26)
             c2 += utf16Fixup[c2>>11];
         /* now c1 and c2 are in UTF-32-compatible order */
 
@@ -6668,7 +6668,7 @@
 #endif
 
 int PyUnicode_Compare(PyObject *left,
-		      PyObject *right)
+                      PyObject *right)
 {
     if (PyUnicode_Check(left) && PyUnicode_Check(right))
         return unicode_compare((PyUnicodeObject *)left,
@@ -6689,25 +6689,25 @@
     id = PyUnicode_AS_UNICODE(uni);
     /* Compare Unicode string and source character set string */
     for (i = 0; id[i] && str[i]; i++)
-	if (id[i] != str[i])
-	    return ((int)id[i] < (int)str[i]) ? -1 : 1;
+        if (id[i] != str[i])
+            return ((int)id[i] < (int)str[i]) ? -1 : 1;
     if (id[i])
-	return 1; /* uni is longer */
+        return 1; /* uni is longer */
     if (str[i])
-	return -1; /* str is longer */
+        return -1; /* str is longer */
     return 0;
 }
 
 
-#define TEST_COND(cond) \
-	((cond) ? Py_True : Py_False)
+#define TEST_COND(cond)                         \
+    ((cond) ? Py_True : Py_False)
 
 PyObject *PyUnicode_RichCompare(PyObject *left,
                                 PyObject *right,
                                 int op)
 {
     int result;
-    
+
     if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
         PyObject *v;
         if (((PyUnicodeObject *) left)->length !=
@@ -6726,7 +6726,7 @@
         else
             result = unicode_compare((PyUnicodeObject *)left,
                                      (PyUnicodeObject *)right);
-    
+
         /* Convert the return value to a Boolean */
         switch (op) {
         case Py_EQ:
@@ -6754,13 +6754,13 @@
         Py_INCREF(v);
         return v;
     }
-    
+
     Py_INCREF(Py_NotImplemented);
     return Py_NotImplemented;
 }
 
 int PyUnicode_Contains(PyObject *container,
-		       PyObject *element)
+                       PyObject *element)
 {
     PyObject *str, *sub;
     int result;
@@ -6768,9 +6768,9 @@
     /* Coerce the two arguments */
     sub = PyUnicode_FromObject(element);
     if (!sub) {
-	PyErr_Format(PyExc_TypeError,
-	    "'in <string>' requires string as left operand, not %s",
-	    element->ob_type->tp_name);
+        PyErr_Format(PyExc_TypeError,
+                     "'in <string>' requires string as left operand, not %s",
+                     element->ob_type->tp_name);
         return -1;
     }
 
@@ -6791,32 +6791,32 @@
 /* Concat to string or Unicode object giving a new Unicode object. */
 
 PyObject *PyUnicode_Concat(PyObject *left,
-			   PyObject *right)
+                           PyObject *right)
 {
     PyUnicodeObject *u = NULL, *v = NULL, *w;
 
     /* Coerce the two arguments */
     u = (PyUnicodeObject *)PyUnicode_FromObject(left);
     if (u == NULL)
-	goto onError;
+        goto onError;
     v = (PyUnicodeObject *)PyUnicode_FromObject(right);
     if (v == NULL)
-	goto onError;
+        goto onError;
 
     /* Shortcuts */
     if (v == unicode_empty) {
-	Py_DECREF(v);
-	return (PyObject *)u;
+        Py_DECREF(v);
+        return (PyObject *)u;
     }
     if (u == unicode_empty) {
-	Py_DECREF(u);
-	return (PyObject *)v;
+        Py_DECREF(u);
+        return (PyObject *)v;
     }
 
     /* Concat the two Unicode strings */
     w = _PyUnicode_New(u->length + v->length);
     if (w == NULL)
-	goto onError;
+        goto onError;
     Py_UNICODE_COPY(w->str, u->str, u->length);
     Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
 
@@ -6824,7 +6824,7 @@
     Py_DECREF(v);
     return (PyObject *)w;
 
-onError:
+  onError:
     Py_XDECREF(u);
     Py_XDECREF(v);
     return NULL;
@@ -6833,28 +6833,28 @@
 void
 PyUnicode_Append(PyObject **pleft, PyObject *right)
 {
-	PyObject *new;
-	if (*pleft == NULL)
-		return;
-	if (right == NULL || !PyUnicode_Check(*pleft)) {
-		Py_DECREF(*pleft);
-		*pleft = NULL;
-		return;
-	}
-	new = PyUnicode_Concat(*pleft, right);
-	Py_DECREF(*pleft);
-	*pleft = new;
+    PyObject *new;
+    if (*pleft == NULL)
+        return;
+    if (right == NULL || !PyUnicode_Check(*pleft)) {
+        Py_DECREF(*pleft);
+        *pleft = NULL;
+        return;
+    }
+    new = PyUnicode_Concat(*pleft, right);
+    Py_DECREF(*pleft);
+    *pleft = new;
 }
 
 void
 PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
 {
-	PyUnicode_Append(pleft, right);
-	Py_XDECREF(right);
+    PyUnicode_Append(pleft, right);
+    Py_XDECREF(right);
 }
 
 PyDoc_STRVAR(count__doc__,
-"S.count(sub[, start[, end]]) -> int\n\
+             "S.count(sub[, start[, end]]) -> int\n\
 \n\
 Return the number of non-overlapping occurrences of substring sub in\n\
 string S[start:end].  Optional arguments start and end are\n\
@@ -6869,13 +6869,13 @@
     PyObject *result;
 
     if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
-		_PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+                          _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
         return NULL;
 
     substring = (PyUnicodeObject *)PyUnicode_FromObject(
         (PyObject *)substring);
     if (substring == NULL)
-	return NULL;
+        return NULL;
 
     FIX_START_END(self);
 
@@ -6890,7 +6890,7 @@
 }
 
 PyDoc_STRVAR(encode__doc__,
-"S.encode([encoding[, errors]]) -> bytes\n\
+             "S.encode([encoding[, errors]]) -> bytes\n\
 \n\
 Encode S using the codec registered for encoding. encoding defaults\n\
 to the default encoding. errors may be given to set a different error\n\
@@ -6921,12 +6921,12 @@
     }
     return v;
 
- onError:
+  onError:
     return NULL;
 }
 
 PyDoc_STRVAR(expandtabs__doc__,
-"S.expandtabs([tabsize]) -> str\n\
+             "S.expandtabs([tabsize]) -> str\n\
 \n\
 Return a copy of S where all tab characters are expanded using spaces.\n\
 If tabsize is not given, a tab size of 8 characters is assumed.");
@@ -6943,7 +6943,7 @@
     int tabsize = 8;
 
     if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
-	return NULL;
+        return NULL;
 
     /* First pass: determine size of output string */
     i = 0; /* chars up to and including most recent \n or \r */
@@ -6951,27 +6951,27 @@
     e = self->str + self->length; /* end of input */
     for (p = self->str; p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0) {
-		incr = tabsize - (j % tabsize); /* cannot overflow */
-		if (j > PY_SSIZE_T_MAX - incr)
-		    goto overflow1;
-		j += incr;
+            if (tabsize > 0) {
+                incr = tabsize - (j % tabsize); /* cannot overflow */
+                if (j > PY_SSIZE_T_MAX - incr)
+                    goto overflow1;
+                j += incr;
             }
-	}
+        }
         else {
-	    if (j > PY_SSIZE_T_MAX - 1)
-		goto overflow1;
+            if (j > PY_SSIZE_T_MAX - 1)
+                goto overflow1;
             j++;
             if (*p == '\n' || *p == '\r') {
-		if (i > PY_SSIZE_T_MAX - j)
-		    goto overflow1;
+                if (i > PY_SSIZE_T_MAX - j)
+                    goto overflow1;
                 i += j;
                 j = 0;
             }
         }
 
     if (i > PY_SSIZE_T_MAX - j)
-	goto overflow1;
+        goto overflow1;
 
     /* Second pass: create output string and fill it */
     u = _PyUnicode_New(i + j);
@@ -6984,20 +6984,20 @@
 
     for (p = self->str; p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0) {
-		i = tabsize - (j % tabsize);
-		j += i;
-		while (i--) {
-		    if (q >= qe)
-			goto overflow2;
-		    *q++ = ' ';
-                }
-	    }
-	}
-	else {
-	    if (q >= qe)
-		goto overflow2;
-	    *q++ = *p;
+            if (tabsize > 0) {
+                i = tabsize - (j % tabsize);
+                j += i;
+                while (i--) {
+                    if (q >= qe)
+                        goto overflow2;
+                    *q++ = ' ';
+                }
+            }
+        }
+        else {
+            if (q >= qe)
+                goto overflow2;
+            *q++ = *p;
             j++;
             if (*p == '\n' || *p == '\r')
                 j = 0;
@@ -7013,7 +7013,7 @@
 }
 
 PyDoc_STRVAR(find__doc__,
-"S.find(sub[, start[, end]]) -> int\n\
+             "S.find(sub[, start[, end]]) -> int\n\
 \n\
 Return the lowest index in S where substring sub is found,\n\
 such that sub is contained within s[start:end].  Optional\n\
@@ -7078,7 +7078,7 @@
 }
 
 PyDoc_STRVAR(index__doc__,
-"S.index(sub[, start[, end]]) -> int\n\
+             "S.index(sub[, start[, end]]) -> int\n\
 \n\
 Like S.find() but raise ValueError when the substring is not found.");
 
@@ -7110,7 +7110,7 @@
 }
 
 PyDoc_STRVAR(islower__doc__,
-"S.islower() -> bool\n\
+             "S.islower() -> bool\n\
 \n\
 Return True if all cased characters in S are lowercase and there is\n\
 at least one cased character in S, False otherwise.");
@@ -7124,27 +7124,27 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1)
-	return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
+        return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     cased = 0;
     for (; p < e; p++) {
-	register const Py_UNICODE ch = *p;
+        register const Py_UNICODE ch = *p;
 
-	if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
-	    return PyBool_FromLong(0);
-	else if (!cased && Py_UNICODE_ISLOWER(ch))
-	    cased = 1;
+        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
+            return PyBool_FromLong(0);
+        else if (!cased && Py_UNICODE_ISLOWER(ch))
+            cased = 1;
     }
     return PyBool_FromLong(cased);
 }
 
 PyDoc_STRVAR(isupper__doc__,
-"S.isupper() -> bool\n\
+             "S.isupper() -> bool\n\
 \n\
 Return True if all cased characters in S are uppercase and there is\n\
 at least one cased character in S, False otherwise.");
@@ -7158,27 +7158,27 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1)
-	return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
+        return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     cased = 0;
     for (; p < e; p++) {
-	register const Py_UNICODE ch = *p;
+        register const Py_UNICODE ch = *p;
 
-	if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
-	    return PyBool_FromLong(0);
-	else if (!cased && Py_UNICODE_ISUPPER(ch))
-	    cased = 1;
+        if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
+            return PyBool_FromLong(0);
+        else if (!cased && Py_UNICODE_ISUPPER(ch))
+            cased = 1;
     }
     return PyBool_FromLong(cased);
 }
 
 PyDoc_STRVAR(istitle__doc__,
-"S.istitle() -> bool\n\
+             "S.istitle() -> bool\n\
 \n\
 Return True if S is a titlecased string and there is at least one\n\
 character in S, i.e. upper- and titlecase characters may only\n\
@@ -7194,39 +7194,39 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1)
-	return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
-			       (Py_UNICODE_ISUPPER(*p) != 0));
+        return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
+                               (Py_UNICODE_ISUPPER(*p) != 0));
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     cased = 0;
     previous_is_cased = 0;
     for (; p < e; p++) {
-	register const Py_UNICODE ch = *p;
+        register const Py_UNICODE ch = *p;
 
-	if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
-	    if (previous_is_cased)
-		return PyBool_FromLong(0);
-	    previous_is_cased = 1;
-	    cased = 1;
-	}
-	else if (Py_UNICODE_ISLOWER(ch)) {
-	    if (!previous_is_cased)
-		return PyBool_FromLong(0);
-	    previous_is_cased = 1;
-	    cased = 1;
-	}
-	else
-	    previous_is_cased = 0;
+        if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
+            if (previous_is_cased)
+                return PyBool_FromLong(0);
+            previous_is_cased = 1;
+            cased = 1;
+        }
+        else if (Py_UNICODE_ISLOWER(ch)) {
+            if (!previous_is_cased)
+                return PyBool_FromLong(0);
+            previous_is_cased = 1;
+            cased = 1;
+        }
+        else
+            previous_is_cased = 0;
     }
     return PyBool_FromLong(cased);
 }
 
 PyDoc_STRVAR(isspace__doc__,
-"S.isspace() -> bool\n\
+             "S.isspace() -> bool\n\
 \n\
 Return True if all characters in S are whitespace\n\
 and there is at least one character in S, False otherwise.");
@@ -7239,23 +7239,23 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1 &&
-	Py_UNICODE_ISSPACE(*p))
-	return PyBool_FromLong(1);
+        Py_UNICODE_ISSPACE(*p))
+        return PyBool_FromLong(1);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     for (; p < e; p++) {
-	if (!Py_UNICODE_ISSPACE(*p))
-	    return PyBool_FromLong(0);
+        if (!Py_UNICODE_ISSPACE(*p))
+            return PyBool_FromLong(0);
     }
     return PyBool_FromLong(1);
 }
 
 PyDoc_STRVAR(isalpha__doc__,
-"S.isalpha() -> bool\n\
+             "S.isalpha() -> bool\n\
 \n\
 Return True if all characters in S are alphabetic\n\
 and there is at least one character in S, False otherwise.");
@@ -7268,23 +7268,23 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1 &&
-	Py_UNICODE_ISALPHA(*p))
-	return PyBool_FromLong(1);
+        Py_UNICODE_ISALPHA(*p))
+        return PyBool_FromLong(1);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     for (; p < e; p++) {
-	if (!Py_UNICODE_ISALPHA(*p))
-	    return PyBool_FromLong(0);
+        if (!Py_UNICODE_ISALPHA(*p))
+            return PyBool_FromLong(0);
     }
     return PyBool_FromLong(1);
 }
 
 PyDoc_STRVAR(isalnum__doc__,
-"S.isalnum() -> bool\n\
+             "S.isalnum() -> bool\n\
 \n\
 Return True if all characters in S are alphanumeric\n\
 and there is at least one character in S, False otherwise.");
@@ -7297,23 +7297,23 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1 &&
-	Py_UNICODE_ISALNUM(*p))
-	return PyBool_FromLong(1);
+        Py_UNICODE_ISALNUM(*p))
+        return PyBool_FromLong(1);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     for (; p < e; p++) {
-	if (!Py_UNICODE_ISALNUM(*p))
-	    return PyBool_FromLong(0);
+        if (!Py_UNICODE_ISALNUM(*p))
+            return PyBool_FromLong(0);
     }
     return PyBool_FromLong(1);
 }
 
 PyDoc_STRVAR(isdecimal__doc__,
-"S.isdecimal() -> bool\n\
+             "S.isdecimal() -> bool\n\
 \n\
 Return True if there are only decimal characters in S,\n\
 False otherwise.");
@@ -7326,23 +7326,23 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1 &&
-	Py_UNICODE_ISDECIMAL(*p))
-	return PyBool_FromLong(1);
+        Py_UNICODE_ISDECIMAL(*p))
+        return PyBool_FromLong(1);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     for (; p < e; p++) {
-	if (!Py_UNICODE_ISDECIMAL(*p))
-	    return PyBool_FromLong(0);
+        if (!Py_UNICODE_ISDECIMAL(*p))
+            return PyBool_FromLong(0);
     }
     return PyBool_FromLong(1);
 }
 
 PyDoc_STRVAR(isdigit__doc__,
-"S.isdigit() -> bool\n\
+             "S.isdigit() -> bool\n\
 \n\
 Return True if all characters in S are digits\n\
 and there is at least one character in S, False otherwise.");
@@ -7355,23 +7355,23 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1 &&
-	Py_UNICODE_ISDIGIT(*p))
-	return PyBool_FromLong(1);
+        Py_UNICODE_ISDIGIT(*p))
+        return PyBool_FromLong(1);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     for (; p < e; p++) {
-	if (!Py_UNICODE_ISDIGIT(*p))
-	    return PyBool_FromLong(0);
+        if (!Py_UNICODE_ISDIGIT(*p))
+            return PyBool_FromLong(0);
     }
     return PyBool_FromLong(1);
 }
 
 PyDoc_STRVAR(isnumeric__doc__,
-"S.isnumeric() -> bool\n\
+             "S.isnumeric() -> bool\n\
 \n\
 Return True if there are only numeric characters in S,\n\
 False otherwise.");
@@ -7384,17 +7384,17 @@
 
     /* Shortcut for single character strings */
     if (PyUnicode_GET_SIZE(self) == 1 &&
-	Py_UNICODE_ISNUMERIC(*p))
-	return PyBool_FromLong(1);
+        Py_UNICODE_ISNUMERIC(*p))
+        return PyBool_FromLong(1);
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
+        return PyBool_FromLong(0);
 
     e = p + PyUnicode_GET_SIZE(self);
     for (; p < e; p++) {
-	if (!Py_UNICODE_ISNUMERIC(*p))
-	    return PyBool_FromLong(0);
+        if (!Py_UNICODE_ISNUMERIC(*p))
+            return PyBool_FromLong(0);
     }
     return PyBool_FromLong(1);
 }
@@ -7407,12 +7407,12 @@
 
     /* Special case for empty strings */
     if (PyUnicode_GET_SIZE(self) == 0)
-	return 0;
+        return 0;
 
     /* PEP 3131 says that the first character must be in
        XID_Start and subsequent characters in XID_Continue,
        and for the ASCII range, the 2.x rules apply (i.e
-       start with letters and underscore, continue with 
+       start with letters and underscore, continue with
        letters, digits, underscore). However, given the current
        definition of XID_Start and XID_Continue, it is sufficient
        to check just for these, except that _ must be allowed
@@ -7422,14 +7422,14 @@
 
     e = p + PyUnicode_GET_SIZE(self);
     for (p++; p < e; p++) {
-	if (!_PyUnicode_IsXidContinue(*p))
-	    return 0;
+        if (!_PyUnicode_IsXidContinue(*p))
+            return 0;
     }
     return 1;
 }
 
 PyDoc_STRVAR(isidentifier__doc__,
-"S.isidentifier() -> bool\n\
+             "S.isidentifier() -> bool\n\
 \n\
 Return True if S is a valid identifier according\n\
 to the language definition.");
@@ -7441,7 +7441,7 @@
 }
 
 PyDoc_STRVAR(isprintable__doc__,
-"S.isprintable() -> bool\n\
+             "S.isprintable() -> bool\n\
 \n\
 Return True if all characters in S are considered\n\
 printable in repr() or S is empty, False otherwise.");
@@ -7467,7 +7467,7 @@
 }
 
 PyDoc_STRVAR(join__doc__,
-"S.join(sequence) -> str\n\
+             "S.join(sequence) -> str\n\
 \n\
 Return a string which is the concatenation of the strings in the\n\
 sequence.  The separator between elements is S.");
@@ -7485,7 +7485,7 @@
 }
 
 PyDoc_STRVAR(ljust__doc__,
-"S.ljust(width[, fillchar]) -> str\n\
+             "S.ljust(width[, fillchar]) -> str\n\
 \n\
 Return S left-justified in a Unicode string of length width. Padding is\n\
 done using the specified fill character (default is a space).");
@@ -7508,7 +7508,7 @@
 }
 
 PyDoc_STRVAR(lower__doc__,
-"S.lower() -> str\n\
+             "S.lower() -> str\n\
 \n\
 Return a copy of the string S converted to lowercase.");
 
@@ -7531,93 +7531,93 @@
 PyObject *
 _PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
 {
-	Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
-	Py_ssize_t len = PyUnicode_GET_SIZE(self);
-	Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
-	Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
-	Py_ssize_t i, j;
-
-        BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
-
-	i = 0;
-	if (striptype != RIGHTSTRIP) {
-            while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
-                i++;
-            }
-	}
+    Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
+    Py_ssize_t len = PyUnicode_GET_SIZE(self);
+    Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
+    Py_ssize_t seplen = PyUnicode_GET_SIZE(sepobj);
+    Py_ssize_t i, j;
 
-	j = len;
-	if (striptype != LEFTSTRIP) {
-            do {
-                j--;
-            } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
-            j++;
-	}
+    BLOOM_MASK sepmask = make_bloom_mask(sep, seplen);
 
-	if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
-            Py_INCREF(self);
-            return (PyObject*)self;
-	}
-	else
-            return PyUnicode_FromUnicode(s+i, j-i);
+    i = 0;
+    if (striptype != RIGHTSTRIP) {
+        while (i < len && BLOOM_MEMBER(sepmask, s[i], sep, seplen)) {
+            i++;
+        }
+    }
+
+    j = len;
+    if (striptype != LEFTSTRIP) {
+        do {
+            j--;
+        } while (j >= i && BLOOM_MEMBER(sepmask, s[j], sep, seplen));
+        j++;
+    }
+
+    if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
+        Py_INCREF(self);
+        return (PyObject*)self;
+    }
+    else
+        return PyUnicode_FromUnicode(s+i, j-i);
 }
 
 
 static PyObject *
 do_strip(PyUnicodeObject *self, int striptype)
 {
-	Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
-	Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
+    Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
+    Py_ssize_t len = PyUnicode_GET_SIZE(self), i, j;
+
+    i = 0;
+    if (striptype != RIGHTSTRIP) {
+        while (i < len && Py_UNICODE_ISSPACE(s[i])) {
+            i++;
+        }
+    }
+
+    j = len;
+    if (striptype != LEFTSTRIP) {
+        do {
+            j--;
+        } while (j >= i && Py_UNICODE_ISSPACE(s[j]));
+        j++;
+    }
 
-	i = 0;
-	if (striptype != RIGHTSTRIP) {
-		while (i < len && Py_UNICODE_ISSPACE(s[i])) {
-			i++;
-		}
-	}
-
-	j = len;
-	if (striptype != LEFTSTRIP) {
-		do {
-			j--;
-		} while (j >= i && Py_UNICODE_ISSPACE(s[j]));
-		j++;
-	}
-
-	if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
-		Py_INCREF(self);
-		return (PyObject*)self;
-	}
-	else
-		return PyUnicode_FromUnicode(s+i, j-i);
+    if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
+        Py_INCREF(self);
+        return (PyObject*)self;
+    }
+    else
+        return PyUnicode_FromUnicode(s+i, j-i);
 }
 
 
 static PyObject *
 do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
 {
-	PyObject *sep = NULL;
+    PyObject *sep = NULL;
 
-	if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
-		return NULL;
+    if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
+        return NULL;
 
-	if (sep != NULL && sep != Py_None) {
-		if (PyUnicode_Check(sep))
-			return _PyUnicode_XStrip(self, striptype, sep);
-		else {
-			PyErr_Format(PyExc_TypeError,
-				     "%s arg must be None or str",
-				     STRIPNAME(striptype));
-			return NULL;
-		}
-	}
+    if (sep != NULL && sep != Py_None) {
+        if (PyUnicode_Check(sep))
+            return _PyUnicode_XStrip(self, striptype, sep);
+        else {
+            PyErr_Format(PyExc_TypeError,
+                         "%s arg must be None or str",
+                         STRIPNAME(striptype));
+            return NULL;
+        }
+    }
 
-	return do_strip(self, striptype);
+    return do_strip(self, striptype);
 }
 
 
 PyDoc_STRVAR(strip__doc__,
-"S.strip([chars]) -> str\n\
+             "S.strip([chars]) -> str\n\
 \n\
 Return a copy of the string S with leading and trailing\n\
 whitespace removed.\n\
@@ -7626,15 +7626,15 @@
 static PyObject *
 unicode_strip(PyUnicodeObject *self, PyObject *args)
 {
-	if (PyTuple_GET_SIZE(args) == 0)
-		return do_strip(self, BOTHSTRIP); /* Common case */
-	else
-		return do_argstrip(self, BOTHSTRIP, args);
+    if (PyTuple_GET_SIZE(args) == 0)
+        return do_strip(self, BOTHSTRIP); /* Common case */
+    else
+        return do_argstrip(self, BOTHSTRIP, args);
 }
 
 
 PyDoc_STRVAR(lstrip__doc__,
-"S.lstrip([chars]) -> str\n\
+             "S.lstrip([chars]) -> str\n\
 \n\
 Return a copy of the string S with leading whitespace removed.\n\
 If chars is given and not None, remove characters in chars instead.");
@@ -7642,15 +7642,15 @@
 static PyObject *
 unicode_lstrip(PyUnicodeObject *self, PyObject *args)
 {
-	if (PyTuple_GET_SIZE(args) == 0)
-		return do_strip(self, LEFTSTRIP); /* Common case */
-	else
-		return do_argstrip(self, LEFTSTRIP, args);
+    if (PyTuple_GET_SIZE(args) == 0)
+        return do_strip(self, LEFTSTRIP); /* Common case */
+    else
+        return do_argstrip(self, LEFTSTRIP, args);
 }
 
 
 PyDoc_STRVAR(rstrip__doc__,
-"S.rstrip([chars]) -> str\n\
+             "S.rstrip([chars]) -> str\n\
 \n\
 Return a copy of the string S with trailing whitespace removed.\n\
 If chars is given and not None, remove characters in chars instead.");
@@ -7658,10 +7658,10 @@
 static PyObject *
 unicode_rstrip(PyUnicodeObject *self, PyObject *args)
 {
-	if (PyTuple_GET_SIZE(args) == 0)
-		return do_strip(self, RIGHTSTRIP); /* Common case */
-	else
-		return do_argstrip(self, RIGHTSTRIP, args);
+    if (PyTuple_GET_SIZE(args) == 0)
+        return do_strip(self, RIGHTSTRIP); /* Common case */
+    else
+        return do_argstrip(self, RIGHTSTRIP, args);
 }
 
 
@@ -7706,25 +7706,25 @@
     if (str->length == 1 && len > 0) {
         Py_UNICODE_FILL(p, str->str[0], len);
     } else {
-	Py_ssize_t done = 0; /* number of characters copied this far */
-	if (done < nchars) {
+        Py_ssize_t done = 0; /* number of characters copied this far */
+        if (done < nchars) {
             Py_UNICODE_COPY(p, str->str, str->length);
             done = str->length;
-	}
-	while (done < nchars) {
+        }
+        while (done < nchars) {
             Py_ssize_t n = (done <= nchars-done) ? done : nchars-done;
             Py_UNICODE_COPY(p+done, p, n);
             done += n;
-	}
+        }
     }
 
     return (PyObject*) u;
 }
 
 PyObject *PyUnicode_Replace(PyObject *obj,
-			    PyObject *subobj,
-			    PyObject *replobj,
-			    Py_ssize_t maxcount)
+                            PyObject *subobj,
+                            PyObject *replobj,
+                            Py_ssize_t maxcount)
 {
     PyObject *self;
     PyObject *str1;
@@ -7733,22 +7733,22 @@
 
     self = PyUnicode_FromObject(obj);
     if (self == NULL)
-	return NULL;
+        return NULL;
     str1 = PyUnicode_FromObject(subobj);
     if (str1 == NULL) {
-	Py_DECREF(self);
-	return NULL;
+        Py_DECREF(self);
+        return NULL;
     }
     str2 = PyUnicode_FromObject(replobj);
     if (str2 == NULL) {
-	Py_DECREF(self);
-	Py_DECREF(str1);
-	return NULL;
+        Py_DECREF(self);
+        Py_DECREF(str1);
+        return NULL;
     }
     result = replace((PyUnicodeObject *)self,
-		     (PyUnicodeObject *)str1,
-		     (PyUnicodeObject *)str2,
-		     maxcount);
+                     (PyUnicodeObject *)str1,
+                     (PyUnicodeObject *)str2,
+                     maxcount);
     Py_DECREF(self);
     Py_DECREF(str1);
     Py_DECREF(str2);
@@ -7756,7 +7756,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\
@@ -7774,11 +7774,11 @@
         return NULL;
     str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
     if (str1 == NULL)
-	return NULL;
+        return NULL;
     str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
     if (str2 == NULL) {
-	Py_DECREF(str1);
-	return NULL;
+        Py_DECREF(str1);
+        return NULL;
     }
 
     result = replace(self, str1, str2, maxcount);
@@ -7815,13 +7815,13 @@
     */
 
     repr = PyUnicode_FromUnicode(NULL,
-        2 /* quotes */
+                                 2 /* quotes */
 #ifdef Py_UNICODE_WIDE
-        + 10*size
+                                 + 10*size
 #else
-        + 6*size
+                                 + 6*size
 #endif
-        + 1);
+                                 + 1);
     if (repr == NULL)
         return NULL;
 
@@ -7840,7 +7840,7 @@
             continue;
         }
 
-	/* Map special whitespace to '\t', \n', '\r' */
+        /* Map special whitespace to '\t', \n', '\r' */
         if (ch == '\t') {
             *p++ = '\\';
             *p++ = 't';
@@ -7867,7 +7867,7 @@
             *p++ = ch;
         }
 
-	/* Non-ASCII characters */
+        /* Non-ASCII characters */
         else {
             Py_UCS4 ucs = ch;
 
@@ -7877,15 +7877,15 @@
             if (size > 0) {
                 ch2 = *s;
                 if (ch >= 0xD800 && ch < 0xDC00 && ch2 >= 0xDC00
-                            && ch2 <= 0xDFFF) {
-                    ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) 
-                            + 0x00010000;
-                    s++; 
+                    && ch2 <= 0xDFFF) {
+                    ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF))
+                        + 0x00010000;
+                    s++;
                     size--;
                 }
             }
 #endif
-            /* Map Unicode whitespace and control characters 
+            /* Map Unicode whitespace and control characters
                (categories Z* and C* except ASCII space)
             */
             if (!Py_UNICODE_ISPRINTABLE(ucs)) {
@@ -7938,7 +7938,7 @@
 }
 
 PyDoc_STRVAR(rfind__doc__,
-"S.rfind(sub[, start[, end]]) -> int\n\
+             "S.rfind(sub[, start[, end]]) -> int\n\
 \n\
 Return the highest index in S where substring sub is found,\n\
 such that sub is contained within s[start:end].  Optional\n\
@@ -7955,7 +7955,7 @@
     Py_ssize_t result;
 
     if (!_ParseTupleFinds(args, &substring, &start, &end))
-	    return NULL;
+        return NULL;
 
     result = stringlib_rfind_slice(
         PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
@@ -7969,7 +7969,7 @@
 }
 
 PyDoc_STRVAR(rindex__doc__,
-"S.rindex(sub[, start[, end]]) -> int\n\
+             "S.rindex(sub[, start[, end]]) -> int\n\
 \n\
 Like S.rfind() but raise ValueError when the substring is not found.");
 
@@ -7982,7 +7982,7 @@
     Py_ssize_t result;
 
     if (!_ParseTupleFinds(args, &substring, &start, &end))
-	    return NULL;
+        return NULL;
 
     result = stringlib_rfind_slice(
         PyUnicode_AS_UNICODE(self), PyUnicode_GET_SIZE(self),
@@ -8000,7 +8000,7 @@
 }
 
 PyDoc_STRVAR(rjust__doc__,
-"S.rjust(width[, fillchar]) -> str\n\
+             "S.rjust(width[, fillchar]) -> str\n\
 \n\
 Return S right-justified in a string of length width. Padding is\n\
 done using the specified fill character (default is a space).");
@@ -8023,20 +8023,20 @@
 }
 
 PyObject *PyUnicode_Split(PyObject *s,
-			  PyObject *sep,
-			  Py_ssize_t maxsplit)
+                          PyObject *sep,
+                          Py_ssize_t maxsplit)
 {
     PyObject *result;
 
     s = PyUnicode_FromObject(s);
     if (s == NULL)
-	return NULL;
+        return NULL;
     if (sep != NULL) {
-	sep = PyUnicode_FromObject(sep);
-	if (sep == NULL) {
-	    Py_DECREF(s);
-	    return NULL;
-	}
+        sep = PyUnicode_FromObject(sep);
+        if (sep == NULL) {
+            Py_DECREF(s);
+            return NULL;
+        }
     }
 
     result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
@@ -8047,7 +8047,7 @@
 }
 
 PyDoc_STRVAR(split__doc__,
-"S.split([sep[, maxsplit]]) -> list of strings\n\
+             "S.split([sep[, maxsplit]]) -> list of strings\n\
 \n\
 Return a list of the words in S, using sep as the\n\
 delimiter string.  If maxsplit is given, at most maxsplit\n\
@@ -8065,11 +8065,11 @@
         return NULL;
 
     if (substring == Py_None)
-	return split(self, NULL, maxcount);
+        return split(self, NULL, maxcount);
     else if (PyUnicode_Check(substring))
-	return split(self, (PyUnicodeObject *)substring, maxcount);
+        return split(self, (PyUnicodeObject *)substring, maxcount);
     else
-	return PyUnicode_Split((PyObject *)self, substring, maxcount);
+        return PyUnicode_Split((PyObject *)self, substring, maxcount);
 }
 
 PyObject *
@@ -8081,7 +8081,7 @@
 
     str_obj = PyUnicode_FromObject(str_in);
     if (!str_obj)
-	return NULL;
+        return NULL;
     sep_obj = PyUnicode_FromObject(sep_in);
     if (!sep_obj) {
         Py_DECREF(str_obj);
@@ -8109,7 +8109,7 @@
 
     str_obj = PyUnicode_FromObject(str_in);
     if (!str_obj)
-	return NULL;
+        return NULL;
     sep_obj = PyUnicode_FromObject(sep_in);
     if (!sep_obj) {
         Py_DECREF(str_obj);
@@ -8128,7 +8128,7 @@
 }
 
 PyDoc_STRVAR(partition__doc__,
-"S.partition(sep) -> (head, sep, tail)\n\
+             "S.partition(sep) -> (head, sep, tail)\n\
 \n\
 Search for the separator sep in S, and return the part before it,\n\
 the separator itself, and the part after it.  If the separator is not\n\
@@ -8141,7 +8141,7 @@
 }
 
 PyDoc_STRVAR(rpartition__doc__,
-"S.rpartition(sep) -> (tail, sep, head)\n\
+             "S.rpartition(sep) -> (tail, sep, head)\n\
 \n\
 Search for the separator sep in S, starting at the end of S, and return\n\
 the part before it, the separator itself, and the part after it.  If the\n\
@@ -8154,20 +8154,20 @@
 }
 
 PyObject *PyUnicode_RSplit(PyObject *s,
-			   PyObject *sep,
-			   Py_ssize_t maxsplit)
+                           PyObject *sep,
+                           Py_ssize_t maxsplit)
 {
     PyObject *result;
-    
+
     s = PyUnicode_FromObject(s);
     if (s == NULL)
-	return NULL;
+        return NULL;
     if (sep != NULL) {
-	sep = PyUnicode_FromObject(sep);
-	if (sep == NULL) {
-	    Py_DECREF(s);
-	    return NULL;
-	}
+        sep = PyUnicode_FromObject(sep);
+        if (sep == NULL) {
+            Py_DECREF(s);
+            return NULL;
+        }
     }
 
     result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
@@ -8178,7 +8178,7 @@
 }
 
 PyDoc_STRVAR(rsplit__doc__,
-"S.rsplit([sep[, maxsplit]]) -> list of strings\n\
+             "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
 \n\
 Return a list of the words in S, using sep as the\n\
 delimiter string, starting at the end of the string and\n\
@@ -8196,15 +8196,15 @@
         return NULL;
 
     if (substring == Py_None)
-	return rsplit(self, NULL, maxcount);
+        return rsplit(self, NULL, maxcount);
     else if (PyUnicode_Check(substring))
-	return rsplit(self, (PyUnicodeObject *)substring, maxcount);
+        return rsplit(self, (PyUnicodeObject *)substring, maxcount);
     else
-	return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
+        return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
 }
 
 PyDoc_STRVAR(splitlines__doc__,
-"S.splitlines([keepends]) -> list of strings\n\
+             "S.splitlines([keepends]) -> list of strings\n\
 \n\
 Return a list of the lines in S, breaking at line boundaries.\n\
 Line breaks are not included in the resulting list unless keepends\n\
@@ -8234,7 +8234,7 @@
 }
 
 PyDoc_STRVAR(swapcase__doc__,
-"S.swapcase() -> str\n\
+             "S.swapcase() -> str\n\
 \n\
 Return a copy of S with uppercase characters converted to lowercase\n\
 and vice versa.");
@@ -8246,7 +8246,7 @@
 }
 
 PyDoc_STRVAR(maketrans__doc__,
-"str.maketrans(x[, y[, z]]) -> dict (static method)\n\
+             "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
 \n\
 Return a translation table usable for str.translate().\n\
 If there is only one argument, it must be a dictionary mapping Unicode\n\
@@ -8264,7 +8264,7 @@
     PyObject *new = NULL, *key, *value;
     Py_ssize_t i = 0;
     int res;
-    
+
     if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
         return NULL;
     new = PyDict_New();
@@ -8349,7 +8349,7 @@
 }
 
 PyDoc_STRVAR(translate__doc__,
-"S.translate(table) -> str\n\
+             "S.translate(table) -> str\n\
 \n\
 Return a copy of the string S, where all characters have been mapped\n\
 through the given translation table, which must be a mapping of\n\
@@ -8364,7 +8364,7 @@
 }
 
 PyDoc_STRVAR(upper__doc__,
-"S.upper() -> str\n\
+             "S.upper() -> str\n\
 \n\
 Return a copy of S converted to uppercase.");
 
@@ -8375,7 +8375,7 @@
 }
 
 PyDoc_STRVAR(zfill__doc__,
-"S.zfill(width) -> str\n\
+             "S.zfill(width) -> str\n\
 \n\
 Pad a numeric string S with zeros on the left, to fill a field\n\
 of the specified width. The string S is never truncated.");
@@ -8399,7 +8399,7 @@
             return PyUnicode_FromUnicode(
                 PyUnicode_AS_UNICODE(self),
                 PyUnicode_GET_SIZE(self)
-            );
+                );
     }
 
     fill = width - self->length;
@@ -8427,7 +8427,7 @@
 #endif
 
 PyDoc_STRVAR(startswith__doc__,
-"S.startswith(prefix[, start[, end]]) -> bool\n\
+             "S.startswith(prefix[, start[, end]]) -> bool\n\
 \n\
 Return True if S starts with the specified prefix, False otherwise.\n\
 With optional start, test S beginning at that position.\n\
@@ -8436,7 +8436,7 @@
 
 static PyObject *
 unicode_startswith(PyUnicodeObject *self,
-		   PyObject *args)
+                   PyObject *args)
 {
     PyObject *subobj;
     PyUnicodeObject *substring;
@@ -8445,13 +8445,13 @@
     int result;
 
     if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
-		_PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
-	return NULL;
+                          _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+        return NULL;
     if (PyTuple_Check(subobj)) {
         Py_ssize_t i;
         for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
             substring = (PyUnicodeObject *)PyUnicode_FromObject(
-                            PyTuple_GET_ITEM(subobj, i));
+                PyTuple_GET_ITEM(subobj, i));
             if (substring == NULL)
                 return NULL;
             result = tailmatch(self, substring, start, end, -1);
@@ -8465,7 +8465,7 @@
     }
     substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
     if (substring == NULL)
-         return NULL;
+        return NULL;
     result = tailmatch(self, substring, start, end, -1);
     Py_DECREF(substring);
     return PyBool_FromLong(result);
@@ -8473,7 +8473,7 @@
 
 
 PyDoc_STRVAR(endswith__doc__,
-"S.endswith(suffix[, start[, end]]) -> bool\n\
+             "S.endswith(suffix[, start[, end]]) -> bool\n\
 \n\
 Return True if S ends with the specified suffix, False otherwise.\n\
 With optional start, test S beginning at that position.\n\
@@ -8482,7 +8482,7 @@
 
 static PyObject *
 unicode_endswith(PyUnicodeObject *self,
-		 PyObject *args)
+                 PyObject *args)
 {
     PyObject *subobj;
     PyUnicodeObject *substring;
@@ -8491,15 +8491,15 @@
     int result;
 
     if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
-        _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
-	return NULL;
+                          _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+        return NULL;
     if (PyTuple_Check(subobj)) {
         Py_ssize_t i;
         for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
             substring = (PyUnicodeObject *)PyUnicode_FromObject(
-                            PyTuple_GET_ITEM(subobj, i));
+                PyTuple_GET_ITEM(subobj, i));
             if (substring == NULL)
-            return NULL;
+                return NULL;
             result = tailmatch(self, substring, start, end, +1);
             Py_DECREF(substring);
             if (result) {
@@ -8510,7 +8510,7 @@
     }
     substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
     if (substring == NULL)
-    return NULL;
+        return NULL;
 
     result = tailmatch(self, substring, start, end, +1);
     Py_DECREF(substring);
@@ -8520,7 +8520,7 @@
 #include "stringlib/string_format.h"
 
 PyDoc_STRVAR(format__doc__,
-"S.format(*args, **kwargs) -> str\n\
+             "S.format(*args, **kwargs) -> str\n\
 \n\
 ");
 
@@ -8538,7 +8538,7 @@
 }
 
 PyDoc_STRVAR(p_format__doc__,
-"S.__format__(format_spec) -> str\n\
+             "S.__format__(format_spec) -> str\n\
 \n\
 ");
 
@@ -8550,12 +8550,12 @@
 }
 
 PyDoc_STRVAR(sizeof__doc__,
-"S.__sizeof__() -> size of S in memory, in bytes");
+             "S.__sizeof__() -> size of S in memory, in bytes");
 
 static PyObject *
 unicode_getnewargs(PyUnicodeObject *v)
 {
-	return Py_BuildValue("(u#)", v->str, v->length);
+    return Py_BuildValue("(u#)", v->str, v->length);
 }
 
 
@@ -8620,36 +8620,36 @@
     {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
 #endif
 
-    {"__getnewargs__",	(PyCFunction)unicode_getnewargs, METH_NOARGS},
+    {"__getnewargs__",  (PyCFunction)unicode_getnewargs, METH_NOARGS},
     {NULL, NULL}
 };
 
 static PyObject *
 unicode_mod(PyObject *v, PyObject *w)
 {
-       if (!PyUnicode_Check(v)) {
-               Py_INCREF(Py_NotImplemented);
-               return Py_NotImplemented;
-       }
-       return PyUnicode_Format(v, w);
+    if (!PyUnicode_Check(v)) {
+        Py_INCREF(Py_NotImplemented);
+        return Py_NotImplemented;
+    }
+    return PyUnicode_Format(v, w);
 }
 
 static PyNumberMethods unicode_as_number = {
-	0,				/*nb_add*/
-	0,				/*nb_subtract*/
-	0,				/*nb_multiply*/
-	unicode_mod,			/*nb_remainder*/
+    0,              /*nb_add*/
+    0,              /*nb_subtract*/
+    0,              /*nb_multiply*/
+    unicode_mod,            /*nb_remainder*/
 };
 
 static PySequenceMethods unicode_as_sequence = {
-    (lenfunc) unicode_length, 		/* sq_length */
-    PyUnicode_Concat,		 	/* sq_concat */
-    (ssizeargfunc) unicode_repeat, 	/* sq_repeat */
-    (ssizeargfunc) unicode_getitem, 	/* sq_item */
-    0,				 	/* sq_slice */
-    0, 					/* sq_ass_item */
-    0, 					/* sq_ass_slice */
-    PyUnicode_Contains, 		/* sq_contains */
+    (lenfunc) unicode_length,       /* sq_length */
+    PyUnicode_Concat,           /* sq_concat */
+    (ssizeargfunc) unicode_repeat,  /* sq_repeat */
+    (ssizeargfunc) unicode_getitem,     /* sq_item */
+    0,                  /* sq_slice */
+    0,                  /* sq_ass_item */
+    0,                  /* sq_ass_slice */
+    PyUnicode_Contains,         /* sq_contains */
 };
 
 static PyObject*
@@ -8669,7 +8669,7 @@
         PyObject* result;
 
         if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
-				 &start, &stop, &step, &slicelength) < 0) {
+                                 &start, &stop, &step, &slicelength) < 0) {
             return NULL;
         }
 
@@ -8685,9 +8685,9 @@
             source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
             result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
                                                        sizeof(Py_UNICODE));
-	    
-	    if (result_buf == NULL)
-		    return PyErr_NoMemory();
+
+            if (result_buf == NULL)
+                return PyErr_NoMemory();
 
             for (cur = start, i = 0; i < slicelength; cur += step, i++) {
                 result_buf[i] = source_buf[cur];
@@ -8704,9 +8704,9 @@
 }
 
 static PyMappingMethods unicode_as_mapping = {
-    (lenfunc)unicode_length,		/* mp_length */
-    (binaryfunc)unicode_subscript,	/* mp_subscript */
-    (objobjargproc)0,			/* mp_ass_subscript */
+    (lenfunc)unicode_length,        /* mp_length */
+    (binaryfunc)unicode_subscript,  /* mp_subscript */
+    (objobjargproc)0,           /* mp_ass_subscript */
 };
 
 
@@ -8717,14 +8717,14 @@
 {
     Py_ssize_t argidx = *p_argidx;
     if (argidx < arglen) {
-	(*p_argidx)++;
-	if (arglen < 0)
-	    return args;
-	else
-	    return PyTuple_GetItem(args, argidx);
+        (*p_argidx)++;
+        if (arglen < 0)
+            return args;
+        else
+            return PyTuple_GetItem(args, argidx);
     }
     PyErr_SetString(PyExc_TypeError,
-		    "not enough arguments for format string");
+                    "not enough arguments for format string");
     return NULL;
 }
 
@@ -8734,7 +8734,7 @@
     register Py_ssize_t i;
     Py_ssize_t len = strlen(charbuffer);
     for (i = len - 1; i >= 0; i--)
-	buffer[i] = (Py_UNICODE) charbuffer[i];
+        buffer[i] = (Py_UNICODE) charbuffer[i];
 
     return len;
 }
@@ -8749,7 +8749,7 @@
     return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
 }
 
-#if 0 
+#if 0
 static int
 longtounicode(Py_UNICODE *buffer, size_t len, const char *format, long x)
 {
@@ -8767,11 +8767,11 @@
 
 static int
 formatfloat(Py_UNICODE *buf,
-	    size_t buflen,
-	    int flags,
-	    int prec,
-	    int type,
-	    PyObject *v)
+            size_t buflen,
+            int flags,
+            int prec,
+            int type,
+            PyObject *v)
 {
     /* fmt = '%#.' + `prec` + `type`
        worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
@@ -8780,64 +8780,64 @@
 
     x = PyFloat_AsDouble(v);
     if (x == -1.0 && PyErr_Occurred())
-	return -1;
+        return -1;
     if (prec < 0)
-	prec = 6;
+        prec = 6;
     if (type == 'f' && (fabs(x) / 1e25) >= 1e25)
-	type = 'g';
+        type = 'g';
     /* Worst case length calc to ensure no buffer overrun:
 
        'g' formats:
-	 fmt = %#.<prec>g
-	 buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
-	    for any double rep.)
-	 len = 1 + prec + 1 + 2 + 5 = 9 + prec
+       fmt = %#.<prec>g
+       buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
+       for any double rep.)
+       len = 1 + prec + 1 + 2 + 5 = 9 + prec
 
        'f' formats:
-	 buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
-	 len = 1 + 50 + 1 + prec = 52 + prec
+       buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
+       len = 1 + 50 + 1 + prec = 52 + prec
 
        If prec=0 the effective precision is 1 (the leading digit is
        always given), therefore increase the length by one.
 
     */
-    if (((type == 'g' || type == 'G') && 
-          buflen <= (size_t)10 + (size_t)prec) ||
-	(type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
-	PyErr_SetString(PyExc_OverflowError,
-			"formatted float is too long (precision too large?)");
-	return -1;
+    if (((type == 'g' || type == 'G') &&
+         buflen <= (size_t)10 + (size_t)prec) ||
+        (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
+        PyErr_SetString(PyExc_OverflowError,
+                        "formatted float is too long (precision too large?)");
+        return -1;
     }
     PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
-		  (flags&F_ALT) ? "#" : "",
-		  prec, type);
+                  (flags&F_ALT) ? "#" : "",
+                  prec, type);
     return doubletounicode(buf, buflen, fmt, x);
 }
 
 static PyObject*
 formatlong(PyObject *val, int flags, int prec, int type)
 {
-	char *buf;
-	int len;
-	PyObject *str; /* temporary string object. */
-	PyObject *result;
-
-	str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
-	if (!str)
-		return NULL;
-	result = PyUnicode_FromStringAndSize(buf, len);
-	Py_DECREF(str);
-	return result;
+    char *buf;
+    int len;
+    PyObject *str; /* temporary string object. */
+    PyObject *result;
+
+    str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
+    if (!str)
+        return NULL;
+    result = PyUnicode_FromStringAndSize(buf, len);
+    Py_DECREF(str);
+    return result;
 }
 
 #if 0
 static int
 formatint(Py_UNICODE *buf,
-	  size_t buflen,
-	  int flags,
-	  int prec,
-	  int type,
-	  PyObject *v)
+          size_t buflen,
+          int flags,
+          int prec,
+          int type,
+          PyObject *v)
 {
     /* fmt = '%#.' + `prec` + 'l' + `type`
      * worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
@@ -8866,7 +8866,7 @@
      */
     if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
         PyErr_SetString(PyExc_OverflowError,
-    	        "formatted integer is too long (precision too large?)");
+                        "formatted integer is too long (precision too large?)");
         return -1;
     }
 
@@ -8874,7 +8874,7 @@
         (type == 'x' || type == 'X' || type == 'o')) {
         /* When converting under %#o, %#x or %#X, there are a number
          * of issues that cause pain:
-	 * - for %#o, we want a different base marker than C
+         * - for %#o, we want a different base marker than C
          * - when 0 is being converted, the C standard leaves off
          *   the '0x' or '0X', which is inconsistent with other
          *   %#x/%#X conversions and inconsistent with Python's
@@ -8915,56 +8915,56 @@
 {
     /* presume that the buffer is at least 3 characters long */
     if (PyUnicode_Check(v)) {
-	if (PyUnicode_GET_SIZE(v) == 1) {
-	    buf[0] = PyUnicode_AS_UNICODE(v)[0];
-	    buf[1] = '\0';
-	    return 1;
-	}
+        if (PyUnicode_GET_SIZE(v) == 1) {
+            buf[0] = PyUnicode_AS_UNICODE(v)[0];
+            buf[1] = '\0';
+            return 1;
+        }
 #ifndef Py_UNICODE_WIDE
-	if (PyUnicode_GET_SIZE(v) == 2) {
-	    /* Decode a valid surrogate pair */
-	    int c0 = PyUnicode_AS_UNICODE(v)[0];
-	    int c1 = PyUnicode_AS_UNICODE(v)[1];
-	    if (0xD800 <= c0 && c0 <= 0xDBFF &&
-		0xDC00 <= c1 && c1 <= 0xDFFF) {
-		buf[0] = c0;
-		buf[1] = c1;
-		buf[2] = '\0';
-		return 2;
-	    }
-	}
+        if (PyUnicode_GET_SIZE(v) == 2) {
+            /* Decode a valid surrogate pair */
+            int c0 = PyUnicode_AS_UNICODE(v)[0];
+            int c1 = PyUnicode_AS_UNICODE(v)[1];
+            if (0xD800 <= c0 && c0 <= 0xDBFF &&
+                0xDC00 <= c1 && c1 <= 0xDFFF) {
+                buf[0] = c0;
+                buf[1] = c1;
+                buf[2] = '\0';
+                return 2;
+            }
+        }
 #endif
-	goto onError;
+        goto onError;
     }
     else {
-	/* Integer input truncated to a character */
+        /* Integer input truncated to a character */
         long x;
-	x = PyLong_AsLong(v);
-	if (x == -1 && PyErr_Occurred())
-	    goto onError;
-
-	if (x < 0 || x > 0x10ffff) {
-	    PyErr_SetString(PyExc_OverflowError,
-			    "%c arg not in range(0x110000)");
-	    return -1;
-	}
+        x = PyLong_AsLong(v);
+        if (x == -1 && PyErr_Occurred())
+            goto onError;
+
+        if (x < 0 || x > 0x10ffff) {
+            PyErr_SetString(PyExc_OverflowError,
+                            "%c arg not in range(0x110000)");
+            return -1;
+        }
 
 #ifndef Py_UNICODE_WIDE
-	if (x > 0xffff) {
-	    x -= 0x10000;
-	    buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
-	    buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
-	    return 2;
-	}
-#endif
-	buf[0] = (Py_UNICODE) x;
-	buf[1] = '\0';
-	return 1;
+        if (x > 0xffff) {
+            x -= 0x10000;
+            buf[0] = (Py_UNICODE)(0xD800 | (x >> 10));
+            buf[1] = (Py_UNICODE)(0xDC00 | (x & 0x3FF));
+            return 2;
+        }
+#endif
+        buf[0] = (Py_UNICODE) x;
+        buf[1] = '\0';
+        return 1;
     }
 
- onError:
+  onError:
     PyErr_SetString(PyExc_TypeError,
-		    "%c requires int or char");
+                    "%c requires int or char");
     return -1;
 }
 
@@ -8979,7 +8979,7 @@
 #define FORMATBUFLEN (size_t)120
 
 PyObject *PyUnicode_Format(PyObject *format,
-			   PyObject *args)
+                           PyObject *args)
 {
     Py_UNICODE *fmt, *res;
     Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
@@ -8989,433 +8989,433 @@
     PyObject *uformat;
 
     if (format == NULL || args == NULL) {
-	PyErr_BadInternalCall();
-	return NULL;
+        PyErr_BadInternalCall();
+        return NULL;
     }
     uformat = PyUnicode_FromObject(format);
     if (uformat == NULL)
-	return NULL;
+        return NULL;
     fmt = PyUnicode_AS_UNICODE(uformat);
     fmtcnt = PyUnicode_GET_SIZE(uformat);
 
     reslen = rescnt = fmtcnt + 100;
     result = _PyUnicode_New(reslen);
     if (result == NULL)
-	goto onError;
+        goto onError;
     res = PyUnicode_AS_UNICODE(result);
 
     if (PyTuple_Check(args)) {
-	arglen = PyTuple_Size(args);
-	argidx = 0;
+        arglen = PyTuple_Size(args);
+        argidx = 0;
     }
     else {
-	arglen = -1;
-	argidx = -2;
+        arglen = -1;
+        argidx = -2;
     }
     if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
         !PyUnicode_Check(args))
-	dict = args;
+        dict = args;
 
     while (--fmtcnt >= 0) {
-	if (*fmt != '%') {
-	    if (--rescnt < 0) {
-		rescnt = fmtcnt + 100;
-		reslen += rescnt;
-		if (_PyUnicode_Resize(&result, reslen) < 0)
-		    goto onError;
-		res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
-		--rescnt;
-	    }
-	    *res++ = *fmt++;
-	}
-	else {
-	    /* Got a format specifier */
-	    int flags = 0;
-	    Py_ssize_t width = -1;
-	    int prec = -1;
-	    Py_UNICODE c = '\0';
-	    Py_UNICODE fill;
-	    int isnumok;
-	    PyObject *v = NULL;
-	    PyObject *temp = NULL;
-	    Py_UNICODE *pbuf;
-	    Py_UNICODE sign;
-	    Py_ssize_t len;
-	    Py_UNICODE formatbuf[FORMATBUFLEN]; /* For format{float,int,char}() */
-
-	    fmt++;
-	    if (*fmt == '(') {
-		Py_UNICODE *keystart;
-		Py_ssize_t keylen;
-		PyObject *key;
-		int pcount = 1;
-
-		if (dict == NULL) {
-		    PyErr_SetString(PyExc_TypeError,
-				    "format requires a mapping");
-		    goto onError;
-		}
-		++fmt;
-		--fmtcnt;
-		keystart = fmt;
-		/* Skip over balanced parentheses */
-		while (pcount > 0 && --fmtcnt >= 0) {
-		    if (*fmt == ')')
-			--pcount;
-		    else if (*fmt == '(')
-			++pcount;
-		    fmt++;
-		}
-		keylen = fmt - keystart - 1;
-		if (fmtcnt < 0 || pcount > 0) {
-		    PyErr_SetString(PyExc_ValueError,
-				    "incomplete format key");
-		    goto onError;
-		}
+        if (*fmt != '%') {
+            if (--rescnt < 0) {
+                rescnt = fmtcnt + 100;
+                reslen += rescnt;
+                if (_PyUnicode_Resize(&result, reslen) < 0)
+                    goto onError;
+                res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
+                --rescnt;
+            }
+            *res++ = *fmt++;
+        }
+        else {
+            /* Got a format specifier */
+            int flags = 0;
+            Py_ssize_t width = -1;
+            int prec = -1;
+            Py_UNICODE c = '\0';
+            Py_UNICODE fill;
+            int isnumok;
+            PyObject *v = NULL;
+            PyObject *temp = NULL;
+            Py_UNICODE *pbuf;
+            Py_UNICODE sign;
+            Py_ssize_t len;
+            Py_UNICODE formatbuf[FORMATBUFLEN]; /* For format{float,int,char}() */
+
+            fmt++;
+            if (*fmt == '(') {
+                Py_UNICODE *keystart;
+                Py_ssize_t keylen;
+                PyObject *key;
+                int pcount = 1;
+
+                if (dict == NULL) {
+                    PyErr_SetString(PyExc_TypeError,
+                                    "format requires a mapping");
+                    goto onError;
+                }
+                ++fmt;
+                --fmtcnt;
+                keystart = fmt;
+                /* Skip over balanced parentheses */
+                while (pcount > 0 && --fmtcnt >= 0) {
+                    if (*fmt == ')')
+                        --pcount;
+                    else if (*fmt == '(')
+                        ++pcount;
+                    fmt++;
+                }
+                keylen = fmt - keystart - 1;
+                if (fmtcnt < 0 || pcount > 0) {
+                    PyErr_SetString(PyExc_ValueError,
+                                    "incomplete format key");
+                    goto onError;
+                }
 #if 0
-		/* keys are converted to strings using UTF-8 and
-		   then looked up since Python uses strings to hold
-		   variables names etc. in its namespaces and we
-		   wouldn't want to break common idioms. */
-		key = PyUnicode_EncodeUTF8(keystart,
-					   keylen,
-					   NULL);
+                /* keys are converted to strings using UTF-8 and
+                   then looked up since Python uses strings to hold
+                   variables names etc. in its namespaces and we
+                   wouldn't want to break common idioms. */
+                key = PyUnicode_EncodeUTF8(keystart,
+                                           keylen,
+                                           NULL);
 #else
-		key = PyUnicode_FromUnicode(keystart, keylen);
+                key = PyUnicode_FromUnicode(keystart, keylen);
 #endif
-		if (key == NULL)
-		    goto onError;
-		if (args_owned) {
-		    Py_DECREF(args);
-		    args_owned = 0;
-		}
-		args = PyObject_GetItem(dict, key);
-		Py_DECREF(key);
-		if (args == NULL) {
-		    goto onError;
-		}
-		args_owned = 1;
-		arglen = -1;
-		argidx = -2;
-	    }
-	    while (--fmtcnt >= 0) {
-		switch (c = *fmt++) {
-		case '-': flags |= F_LJUST; continue;
-		case '+': flags |= F_SIGN; continue;
-		case ' ': flags |= F_BLANK; continue;
-		case '#': flags |= F_ALT; continue;
-		case '0': flags |= F_ZERO; continue;
-		}
-		break;
-	    }
-	    if (c == '*') {
-		v = getnextarg(args, arglen, &argidx);
-		if (v == NULL)
-		    goto onError;
-		if (!PyLong_Check(v)) {
-		    PyErr_SetString(PyExc_TypeError,
-				    "* wants int");
-		    goto onError;
-		}
-		width = PyLong_AsLong(v);
-		if (width == -1 && PyErr_Occurred())
-			goto onError;
-		if (width < 0) {
-		    flags |= F_LJUST;
-		    width = -width;
-		}
-		if (--fmtcnt >= 0)
-		    c = *fmt++;
-	    }
-	    else if (c >= '0' && c <= '9') {
-		width = c - '0';
-		while (--fmtcnt >= 0) {
-		    c = *fmt++;
-		    if (c < '0' || c > '9')
-			break;
-		    if ((width*10) / 10 != width) {
-			PyErr_SetString(PyExc_ValueError,
-					"width too big");
-			goto onError;
-		    }
-		    width = width*10 + (c - '0');
-		}
-	    }
-	    if (c == '.') {
-		prec = 0;
-		if (--fmtcnt >= 0)
-		    c = *fmt++;
-		if (c == '*') {
-		    v = getnextarg(args, arglen, &argidx);
-		    if (v == NULL)
-			goto onError;
-		    if (!PyLong_Check(v)) {
-			PyErr_SetString(PyExc_TypeError,
-					"* wants int");
-			goto onError;
-		    }
-		    prec = PyLong_AsLong(v);
-		    if (prec == -1 && PyErr_Occurred())
-			goto onError;
-		    if (prec < 0)
-			prec = 0;
-		    if (--fmtcnt >= 0)
-			c = *fmt++;
-		}
-		else if (c >= '0' && c <= '9') {
-		    prec = c - '0';
-		    while (--fmtcnt >= 0) {
-			c = Py_CHARMASK(*fmt++);
-			if (c < '0' || c > '9')
-			    break;
-			if ((prec*10) / 10 != prec) {
-			    PyErr_SetString(PyExc_ValueError,
-					    "prec too big");
-			    goto onError;
-			}
-			prec = prec*10 + (c - '0');
-		    }
-		}
-	    } /* prec */
-	    if (fmtcnt >= 0) {
-		if (c == 'h' || c == 'l' || c == 'L') {
-		    if (--fmtcnt >= 0)
-			c = *fmt++;
-		}
-	    }
-	    if (fmtcnt < 0) {
-		PyErr_SetString(PyExc_ValueError,
-				"incomplete format");
-		goto onError;
-	    }
-	    if (c != '%') {
-		v = getnextarg(args, arglen, &argidx);
-		if (v == NULL)
-		    goto onError;
-	    }
-	    sign = 0;
-	    fill = ' ';
-	    switch (c) {
-
-	    case '%':
-		pbuf = formatbuf;
-		/* presume that buffer length is at least 1 */
-		pbuf[0] = '%';
-		len = 1;
-		break;
-
-	    case 's':
-	    case 'r':
-	    case 'a':
-		if (PyUnicode_Check(v) && c == 's') {
-		    temp = v;
-		    Py_INCREF(temp);
-		}
-		else {
-		    if (c == 's')
-			temp = PyObject_Str(v);
-		    else if (c == 'r')
-			temp = PyObject_Repr(v);
-		    else
-			temp = PyObject_ASCII(v);
-		    if (temp == NULL)
-			goto onError;
+                if (key == NULL)
+                    goto onError;
+                if (args_owned) {
+                    Py_DECREF(args);
+                    args_owned = 0;
+                }
+                args = PyObject_GetItem(dict, key);
+                Py_DECREF(key);
+                if (args == NULL) {
+                    goto onError;
+                }
+                args_owned = 1;
+                arglen = -1;
+                argidx = -2;
+            }
+            while (--fmtcnt >= 0) {
+                switch (c = *fmt++) {
+                case '-': flags |= F_LJUST; continue;
+                case '+': flags |= F_SIGN; continue;
+                case ' ': flags |= F_BLANK; continue;
+                case '#': flags |= F_ALT; continue;
+                case '0': flags |= F_ZERO; continue;
+                }
+                break;
+            }
+            if (c == '*') {
+                v = getnextarg(args, arglen, &argidx);
+                if (v == NULL)
+                    goto onError;
+                if (!PyLong_Check(v)) {
+                    PyErr_SetString(PyExc_TypeError,
+                                    "* wants int");
+                    goto onError;
+                }
+                width = PyLong_AsLong(v);
+                if (width == -1 && PyErr_Occurred())
+                    goto onError;
+                if (width < 0) {
+                    flags |= F_LJUST;
+                    width = -width;
+                }
+                if (--fmtcnt >= 0)
+                    c = *fmt++;
+            }
+            else if (c >= '0' && c <= '9') {
+                width = c - '0';
+                while (--fmtcnt >= 0) {
+                    c = *fmt++;
+                    if (c < '0' || c > '9')
+                        break;
+                    if ((width*10) / 10 != width) {
+                        PyErr_SetString(PyExc_ValueError,
+                                        "width too big");
+                        goto onError;
+                    }
+                    width = width*10 + (c - '0');
+                }
+            }
+            if (c == '.') {
+                prec = 0;
+                if (--fmtcnt >= 0)
+                    c = *fmt++;
+                if (c == '*') {
+                    v = getnextarg(args, arglen, &argidx);
+                    if (v == NULL)
+                        goto onError;
+                    if (!PyLong_Check(v)) {
+                        PyErr_SetString(PyExc_TypeError,
+                                        "* wants int");
+                        goto onError;
+                    }
+                    prec = PyLong_AsLong(v);
+                    if (prec == -1 && PyErr_Occurred())
+                        goto onError;
+                    if (prec < 0)
+                        prec = 0;
+                    if (--fmtcnt >= 0)
+                        c = *fmt++;
+                }
+                else if (c >= '0' && c <= '9') {
+                    prec = c - '0';
+                    while (--fmtcnt >= 0) {
+                        c = Py_CHARMASK(*fmt++);
+                        if (c < '0' || c > '9')
+                            break;
+                        if ((prec*10) / 10 != prec) {
+                            PyErr_SetString(PyExc_ValueError,
+                                            "prec too big");
+                            goto onError;
+                        }
+                        prec = prec*10 + (c - '0');
+                    }
+                }
+            } /* prec */
+            if (fmtcnt >= 0) {
+                if (c == 'h' || c == 'l' || c == 'L') {
+                    if (--fmtcnt >= 0)
+                        c = *fmt++;
+                }
+            }
+            if (fmtcnt < 0) {
+                PyErr_SetString(PyExc_ValueError,
+                                "incomplete format");
+                goto onError;
+            }
+            if (c != '%') {
+                v = getnextarg(args, arglen, &argidx);
+                if (v == NULL)
+                    goto onError;
+            }
+            sign = 0;
+            fill = ' ';
+            switch (c) {
+
+            case '%':
+                pbuf = formatbuf;
+                /* presume that buffer length is at least 1 */
+                pbuf[0] = '%';
+                len = 1;
+                break;
+
+            case 's':
+            case 'r':
+            case 'a':
+                if (PyUnicode_Check(v) && c == 's') {
+                    temp = v;
+                    Py_INCREF(temp);
+                }
+                else {
+                    if (c == 's')
+                        temp = PyObject_Str(v);
+                    else if (c == 'r')
+                        temp = PyObject_Repr(v);
+                    else
+                        temp = PyObject_ASCII(v);
+                    if (temp == NULL)
+                        goto onError;
                     if (PyUnicode_Check(temp))
                         /* nothing to do */;
-		    else {
-			Py_DECREF(temp);
-			PyErr_SetString(PyExc_TypeError,
-					"%s argument has non-string str()");
-			goto onError;
-		    }
-		}
-		pbuf = PyUnicode_AS_UNICODE(temp);
-		len = PyUnicode_GET_SIZE(temp);
-		if (prec >= 0 && len > prec)
-		    len = prec;
-		break;
-
-	    case 'i':
-	    case 'd':
-	    case 'u':
-	    case 'o':
-	    case 'x':
-	    case 'X':
-		if (c == 'i')
-		    c = 'd';
-		isnumok = 0;
-		if (PyNumber_Check(v)) {
-			PyObject *iobj=NULL;
-
-			if (PyLong_Check(v)) {
-				iobj = v;
-				Py_INCREF(iobj);
-			}
-			else {
-				iobj = PyNumber_Long(v);
-			}
-			if (iobj!=NULL) {
-				if (PyLong_Check(iobj)) {
-					isnumok = 1;
-					temp = formatlong(iobj, flags, prec, c);
-					Py_DECREF(iobj);
-					if (!temp)
-					    goto onError;
-					pbuf = PyUnicode_AS_UNICODE(temp);
-					len = PyUnicode_GET_SIZE(temp);
-					sign = 1;
-				}
-				else {
-					Py_DECREF(iobj);
-				}
-			}
-		}
-		if (!isnumok) {
-			PyErr_Format(PyExc_TypeError, 
-			    "%%%c format: a number is required, "
-                                     "not %.200s", (char)c, Py_TYPE(v)->tp_name);
-			goto onError;
-		}
-		if (flags & F_ZERO)
-		    fill = '0';
-		break;
-
-	    case 'e':
-	    case 'E':
-	    case 'f':
-	    case 'F':
-	    case 'g':
-	    case 'G':
-		if (c == 'F')
-			c = 'f';
-		pbuf = formatbuf;
-		len = formatfloat(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE),
-			flags, prec, c, v);
-		if (len < 0)
-		    goto onError;
-		sign = 1;
-		if (flags & F_ZERO)
-		    fill = '0';
-		break;
-
-	    case 'c':
-		pbuf = formatbuf;
-		len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
-		if (len < 0)
-		    goto onError;
-		break;
-
-	    default:
-		PyErr_Format(PyExc_ValueError,
-			     "unsupported format character '%c' (0x%x) "
-			     "at index %zd",
-			     (31<=c && c<=126) ? (char)c : '?',
+                    else {
+                        Py_DECREF(temp);
+                        PyErr_SetString(PyExc_TypeError,
+                                        "%s argument has non-string str()");
+                        goto onError;
+                    }
+                }
+                pbuf = PyUnicode_AS_UNICODE(temp);
+                len = PyUnicode_GET_SIZE(temp);
+                if (prec >= 0 && len > prec)
+                    len = prec;
+                break;
+
+            case 'i':
+            case 'd':
+            case 'u':
+            case 'o':
+            case 'x':
+            case 'X':
+                if (c == 'i')
+                    c = 'd';
+                isnumok = 0;
+                if (PyNumber_Check(v)) {
+                    PyObject *iobj=NULL;
+
+                    if (PyLong_Check(v)) {
+                        iobj = v;
+                        Py_INCREF(iobj);
+                    }
+                    else {
+                        iobj = PyNumber_Long(v);
+                    }
+                    if (iobj!=NULL) {
+                        if (PyLong_Check(iobj)) {
+                            isnumok = 1;
+                            temp = formatlong(iobj, flags, prec, c);
+                            Py_DECREF(iobj);
+                            if (!temp)
+                                goto onError;
+                            pbuf = PyUnicode_AS_UNICODE(temp);
+                            len = PyUnicode_GET_SIZE(temp);
+                            sign = 1;
+                        }
+                        else {
+                            Py_DECREF(iobj);
+                        }
+                    }
+                }
+                if (!isnumok) {
+                    PyErr_Format(PyExc_TypeError,
+                                 "%%%c format: a number is required, "
+                                 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
+                    goto onError;
+                }
+                if (flags & F_ZERO)
+                    fill = '0';
+                break;
+
+            case 'e':
+            case 'E':
+            case 'f':
+            case 'F':
+            case 'g':
+            case 'G':
+                if (c == 'F')
+                    c = 'f';
+                pbuf = formatbuf;
+                len = formatfloat(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE),
+                                  flags, prec, c, v);
+                if (len < 0)
+                    goto onError;
+                sign = 1;
+                if (flags & F_ZERO)
+                    fill = '0';
+                break;
+
+            case 'c':
+                pbuf = formatbuf;
+                len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
+                if (len < 0)
+                    goto onError;
+                break;
+
+            default:
+                PyErr_Format(PyExc_ValueError,
+                             "unsupported format character '%c' (0x%x) "
+                             "at index %zd",
+                             (31<=c && c<=126) ? (char)c : '?',
                              (int)c,
-			     (Py_ssize_t)(fmt - 1 -
-					  PyUnicode_AS_UNICODE(uformat)));
-		goto onError;
-	    }
-	    if (sign) {
-		if (*pbuf == '-' || *pbuf == '+') {
-		    sign = *pbuf++;
-		    len--;
-		}
-		else if (flags & F_SIGN)
-		    sign = '+';
-		else if (flags & F_BLANK)
-		    sign = ' ';
-		else
-		    sign = 0;
-	    }
-	    if (width < len)
-		width = len;
-	    if (rescnt - (sign != 0) < width) {
-		reslen -= rescnt;
-		rescnt = width + fmtcnt + 100;
-		reslen += rescnt;
-		if (reslen < 0) {
-		    Py_XDECREF(temp);
-		    PyErr_NoMemory();
-		    goto onError;
-		}
-		if (_PyUnicode_Resize(&result, reslen) < 0) {
-		    Py_XDECREF(temp);
-		    goto onError;
-		}
-		res = PyUnicode_AS_UNICODE(result)
-		    + reslen - rescnt;
-	    }
-	    if (sign) {
-		if (fill != ' ')
-		    *res++ = sign;
-		rescnt--;
-		if (width > len)
-		    width--;
-	    }
-	    if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
-		assert(pbuf[0] == '0');
-		assert(pbuf[1] == c);
-		if (fill != ' ') {
-		    *res++ = *pbuf++;
-		    *res++ = *pbuf++;
-		}
-		rescnt -= 2;
-		width -= 2;
-		if (width < 0)
-		    width = 0;
-		len -= 2;
-	    }
-	    if (width > len && !(flags & F_LJUST)) {
-		do {
-		    --rescnt;
-		    *res++ = fill;
-		} while (--width > len);
-	    }
-	    if (fill == ' ') {
-		if (sign)
-		    *res++ = sign;
-		if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
-		    assert(pbuf[0] == '0');
-		    assert(pbuf[1] == c);
-		    *res++ = *pbuf++;
-		    *res++ = *pbuf++;
-		}
-	    }
-	    Py_UNICODE_COPY(res, pbuf, len);
-	    res += len;
-	    rescnt -= len;
-	    while (--width >= len) {
-		--rescnt;
-		*res++ = ' ';
-	    }
-	    if (dict && (argidx < arglen) && c != '%') {
-		PyErr_SetString(PyExc_TypeError,
-				"not all arguments converted during string formatting");
+                             (Py_ssize_t)(fmt - 1 -
+                                          PyUnicode_AS_UNICODE(uformat)));
+                goto onError;
+            }
+            if (sign) {
+                if (*pbuf == '-' || *pbuf == '+') {
+                    sign = *pbuf++;
+                    len--;
+                }
+                else if (flags & F_SIGN)
+                    sign = '+';
+                else if (flags & F_BLANK)
+                    sign = ' ';
+                else
+                    sign = 0;
+            }
+            if (width < len)
+                width = len;
+            if (rescnt - (sign != 0) < width) {
+                reslen -= rescnt;
+                rescnt = width + fmtcnt + 100;
+                reslen += rescnt;
+                if (reslen < 0) {
+                    Py_XDECREF(temp);
+                    PyErr_NoMemory();
+                    goto onError;
+                }
+                if (_PyUnicode_Resize(&result, reslen) < 0) {
+                    Py_XDECREF(temp);
+                    goto onError;
+                }
+                res = PyUnicode_AS_UNICODE(result)
+                    + reslen - rescnt;
+            }
+            if (sign) {
+                if (fill != ' ')
+                    *res++ = sign;
+                rescnt--;
+                if (width > len)
+                    width--;
+            }
+            if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
+                assert(pbuf[0] == '0');
+                assert(pbuf[1] == c);
+                if (fill != ' ') {
+                    *res++ = *pbuf++;
+                    *res++ = *pbuf++;
+                }
+                rescnt -= 2;
+                width -= 2;
+                if (width < 0)
+                    width = 0;
+                len -= 2;
+            }
+            if (width > len && !(flags & F_LJUST)) {
+                do {
+                    --rescnt;
+                    *res++ = fill;
+                } while (--width > len);
+            }
+            if (fill == ' ') {
+                if (sign)
+                    *res++ = sign;
+                if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
+                    assert(pbuf[0] == '0');
+                    assert(pbuf[1] == c);
+                    *res++ = *pbuf++;
+                    *res++ = *pbuf++;
+                }
+            }
+            Py_UNICODE_COPY(res, pbuf, len);
+            res += len;
+            rescnt -= len;
+            while (--width >= len) {
+                --rescnt;
+                *res++ = ' ';
+            }
+            if (dict && (argidx < arglen) && c != '%') {
+                PyErr_SetString(PyExc_TypeError,
+                                "not all arguments converted during string formatting");
                 Py_XDECREF(temp);
-		goto onError;
-	    }
-	    Py_XDECREF(temp);
-	} /* '%' */
+                goto onError;
+            }
+            Py_XDECREF(temp);
+        } /* '%' */
     } /* until end */
     if (argidx < arglen && !dict) {
-	PyErr_SetString(PyExc_TypeError,
-			"not all arguments converted during string formatting");
-	goto onError;
+        PyErr_SetString(PyExc_TypeError,
+                        "not all arguments converted during string formatting");
+        goto onError;
     }
 
     if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
-	goto onError;
+        goto onError;
     if (args_owned) {
-	Py_DECREF(args);
+        Py_DECREF(args);
     }
     Py_DECREF(uformat);
     return (PyObject *)result;
 
- onError:
+  onError:
     Py_XDECREF(result);
     Py_DECREF(uformat);
     if (args_owned) {
-	Py_DECREF(args);
+        Py_DECREF(args);
     }
     return NULL;
 }
@@ -9426,56 +9426,56 @@
 static PyObject *
 unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
-        PyObject *x = NULL;
-	static char *kwlist[] = {"object", "encoding", "errors", 0};
-	char *encoding = NULL;
-	char *errors = NULL;
-
-	if (type != &PyUnicode_Type)
-		return unicode_subtype_new(type, args, kwds);
-	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
-					  kwlist, &x, &encoding, &errors))
-	    return NULL;
-	if (x == NULL)
-		return (PyObject *)_PyUnicode_New(0);
-	if (encoding == NULL && errors == NULL)
-	    return PyObject_Str(x);
-	else
-	return PyUnicode_FromEncodedObject(x, encoding, errors);
+    PyObject *x = NULL;
+    static char *kwlist[] = {"object", "encoding", "errors", 0};
+    char *encoding = NULL;
+    char *errors = NULL;
+
+    if (type != &PyUnicode_Type)
+        return unicode_subtype_new(type, args, kwds);
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
+                                     kwlist, &x, &encoding, &errors))
+        return NULL;
+    if (x == NULL)
+        return (PyObject *)_PyUnicode_New(0);
+    if (encoding == NULL && errors == NULL)
+        return PyObject_Str(x);
+    else
+        return PyUnicode_FromEncodedObject(x, encoding, errors);
 }
 
 static PyObject *
 unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
-	PyUnicodeObject *tmp, *pnew;
-	Py_ssize_t n;
+    PyUnicodeObject *tmp, *pnew;
+    Py_ssize_t n;
 
-	assert(PyType_IsSubtype(type, &PyUnicode_Type));
-	tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
-	if (tmp == NULL)
-		return NULL;
-	assert(PyUnicode_Check(tmp));
-	pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
-	if (pnew == NULL) {
-		Py_DECREF(tmp);
-		return NULL;
-	}
-	pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
-	if (pnew->str == NULL) {
-		_Py_ForgetReference((PyObject *)pnew);
-		PyObject_Del(pnew);
-		Py_DECREF(tmp);
-		return PyErr_NoMemory();
-	}
-	Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
-	pnew->length = n;
-	pnew->hash = tmp->hash;
-	Py_DECREF(tmp);
-	return (PyObject *)pnew;
+    assert(PyType_IsSubtype(type, &PyUnicode_Type));
+    tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
+    if (tmp == NULL)
+        return NULL;
+    assert(PyUnicode_Check(tmp));
+    pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
+    if (pnew == NULL) {
+        Py_DECREF(tmp);
+        return NULL;
+    }
+    pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
+    if (pnew->str == NULL) {
+        _Py_ForgetReference((PyObject *)pnew);
+        PyObject_Del(pnew);
+        Py_DECREF(tmp);
+        return PyErr_NoMemory();
+    }
+    Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
+    pnew->length = n;
+    pnew->hash = tmp->hash;
+    Py_DECREF(tmp);
+    return (PyObject *)pnew;
 }
 
 PyDoc_STRVAR(unicode_doc,
-"str(string[, encoding[, errors]]) -> str\n\
+             "str(string[, encoding[, errors]]) -> str\n\
 \n\
 Create a new string object from the given encoded string.\n\
 encoding defaults to the current default string encoding.\n\
@@ -9485,46 +9485,46 @@
 
 PyTypeObject PyUnicode_Type = {
     PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "str", 				/* tp_name */
-    sizeof(PyUnicodeObject), 		/* tp_size */
-    0, 					/* tp_itemsize */
+    "str",              /* tp_name */
+    sizeof(PyUnicodeObject),        /* tp_size */
+    0,                  /* tp_itemsize */
     /* Slots */
-    (destructor)unicode_dealloc, 	/* tp_dealloc */
-    0, 					/* tp_print */
-    0,				 	/* tp_getattr */
-    0, 					/* tp_setattr */
-    0, 					/* tp_compare */
-    unicode_repr, 			/* tp_repr */
-    &unicode_as_number, 		/* tp_as_number */
-    &unicode_as_sequence, 		/* tp_as_sequence */
-    &unicode_as_mapping, 		/* tp_as_mapping */
-    (hashfunc) unicode_hash, 		/* tp_hash*/
-    0, 					/* tp_call*/
-    (reprfunc) unicode_str,	 	/* tp_str */
-    PyObject_GenericGetAttr, 		/* tp_getattro */
-    0,			 		/* tp_setattro */
-    0, 					/* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | 
-        Py_TPFLAGS_UNICODE_SUBCLASS,	/* tp_flags */
-    unicode_doc,			/* tp_doc */
-    0,					/* tp_traverse */
-    0,					/* tp_clear */
-    PyUnicode_RichCompare,		/* tp_richcompare */
-    0,					/* tp_weaklistoffset */
-    unicode_iter,			/* tp_iter */
-    0,					/* tp_iternext */
-    unicode_methods,			/* tp_methods */
-    0,					/* tp_members */
-    0,					/* tp_getset */
-    &PyBaseObject_Type,			/* tp_base */
-    0,					/* tp_dict */
-    0,					/* tp_descr_get */
-    0,					/* tp_descr_set */
-    0,					/* tp_dictoffset */
-    0,					/* tp_init */
-    0,					/* tp_alloc */
-    unicode_new,			/* tp_new */
-    PyObject_Del,      		/* tp_free */
+    (destructor)unicode_dealloc,    /* tp_dealloc */
+    0,                  /* tp_print */
+    0,                  /* tp_getattr */
+    0,                  /* tp_setattr */
+    0,                  /* tp_reserved */
+    unicode_repr,           /* tp_repr */
+    &unicode_as_number,         /* tp_as_number */
+    &unicode_as_sequence,       /* tp_as_sequence */
+    &unicode_as_mapping,        /* tp_as_mapping */
+    (hashfunc) unicode_hash,        /* tp_hash*/
+    0,                  /* tp_call*/
+    (reprfunc) unicode_str,     /* tp_str */
+    PyObject_GenericGetAttr,        /* tp_getattro */
+    0,                  /* tp_setattro */
+    0,                  /* tp_as_buffer */
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+    Py_TPFLAGS_UNICODE_SUBCLASS,    /* tp_flags */
+    unicode_doc,            /* tp_doc */
+    0,                  /* tp_traverse */
+    0,                  /* tp_clear */
+    PyUnicode_RichCompare,      /* tp_richcompare */
+    0,                  /* tp_weaklistoffset */
+    unicode_iter,           /* tp_iter */
+    0,                  /* tp_iternext */
+    unicode_methods,            /* tp_methods */
+    0,                  /* tp_members */
+    0,                  /* tp_getset */
+    &PyBaseObject_Type,         /* tp_base */
+    0,                  /* tp_dict */
+    0,                  /* tp_descr_get */
+    0,                  /* tp_descr_set */
+    0,                  /* tp_dictoffset */
+    0,                  /* tp_init */
+    0,                  /* tp_alloc */
+    unicode_new,            /* tp_new */
+    PyObject_Del,           /* tp_free */
 };
 
 /* Initialize the Unicode implementation */
@@ -9550,12 +9550,12 @@
     numfree = 0;
     unicode_empty = _PyUnicode_New(0);
     if (!unicode_empty)
-	return;
+        return;
 
     for (i = 0; i < 256; i++)
-	unicode_latin1[i] = NULL;
+        unicode_latin1[i] = NULL;
     if (PyType_Ready(&PyUnicode_Type) < 0)
-	Py_FatalError("Can't initialize 'unicode'");
+        Py_FatalError("Can't initialize 'unicode'");
 
     /* initialize the linebreak bloom filter */
     bloom_linebreak = make_bloom_mask(
@@ -9574,13 +9574,13 @@
     PyUnicodeObject *u;
 
     for (u = free_list; u != NULL;) {
-	PyUnicodeObject *v = u;
-	u = *(PyUnicodeObject **)u;
-	if (v->str)
-	    PyObject_DEL(v->str);
-	Py_XDECREF(v->defenc);
-	PyObject_Del(v);
-	numfree--;
+        PyUnicodeObject *v = u;
+        u = *(PyUnicodeObject **)u;
+        if (v->str)
+            PyObject_DEL(v->str);
+        Py_XDECREF(v->defenc);
+        PyObject_Del(v);
+        numfree--;
     }
     free_list = NULL;
     assert(numfree == 0);
@@ -9596,10 +9596,10 @@
     unicode_empty = NULL;
 
     for (i = 0; i < 256; i++) {
-	if (unicode_latin1[i]) {
-	    Py_DECREF(unicode_latin1[i]);
-	    unicode_latin1[i] = NULL;
-	}
+        if (unicode_latin1[i]) {
+            Py_DECREF(unicode_latin1[i]);
+            unicode_latin1[i] = NULL;
+        }
     }
     (void)PyUnicode_ClearFreeList();
 }
@@ -9607,238 +9607,238 @@
 void
 PyUnicode_InternInPlace(PyObject **p)
 {
-	register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
-	PyObject *t;
-	if (s == NULL || !PyUnicode_Check(s))
-		Py_FatalError(
-		    "PyUnicode_InternInPlace: unicode strings only please!");
-	/* If it's a subclass, we don't really know what putting
-	   it in the interned dict might do. */
-	if (!PyUnicode_CheckExact(s))
-		return;
-	if (PyUnicode_CHECK_INTERNED(s))
-		return;
-	if (interned == NULL) {
-		interned = PyDict_New();
-		if (interned == NULL) {
-			PyErr_Clear(); /* Don't leave an exception */
-			return;
-		}
-	}
-	/* It might be that the GetItem call fails even
-	   though the key is present in the dictionary,
-	   namely when this happens during a stack overflow. */
-	Py_ALLOW_RECURSION
-	t = PyDict_GetItem(interned, (PyObject *)s);
-	Py_END_ALLOW_RECURSION
-
-	if (t) {
-		Py_INCREF(t);
-		Py_DECREF(*p);
-		*p = t;
-		return;
-	}
-
-	PyThreadState_GET()->recursion_critical = 1;
-	if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
-		PyErr_Clear();
-		PyThreadState_GET()->recursion_critical = 0;
-		return;
-	}
-	PyThreadState_GET()->recursion_critical = 0;
-	/* The two references in interned are not counted by refcnt.
-	   The deallocator will take care of this */
-	Py_REFCNT(s) -= 2;
-	PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
+    register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
+    PyObject *t;
+    if (s == NULL || !PyUnicode_Check(s))
+        Py_FatalError(
+            "PyUnicode_InternInPlace: unicode strings only please!");
+    /* If it's a subclass, we don't really know what putting
+       it in the interned dict might do. */
+    if (!PyUnicode_CheckExact(s))
+        return;
+    if (PyUnicode_CHECK_INTERNED(s))
+        return;
+    if (interned == NULL) {
+        interned = PyDict_New();
+        if (interned == NULL) {
+            PyErr_Clear(); /* Don't leave an exception */
+            return;
+        }
+    }
+    /* It might be that the GetItem call fails even
+       though the key is present in the dictionary,
+       namely when this happens during a stack overflow. */
+    Py_ALLOW_RECURSION
+        t = PyDict_GetItem(interned, (PyObject *)s);
+    Py_END_ALLOW_RECURSION
+
+        if (t) {
+            Py_INCREF(t);
+            Py_DECREF(*p);
+            *p = t;
+            return;
+        }
+
+    PyThreadState_GET()->recursion_critical = 1;
+    if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
+        PyErr_Clear();
+        PyThreadState_GET()->recursion_critical = 0;
+        return;
+    }
+    PyThreadState_GET()->recursion_critical = 0;
+    /* The two references in interned are not counted by refcnt.
+       The deallocator will take care of this */
+    Py_REFCNT(s) -= 2;
+    PyUnicode_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
 }
 
 void
 PyUnicode_InternImmortal(PyObject **p)
 {
-	PyUnicode_InternInPlace(p);
-	if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
-		PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
-		Py_INCREF(*p);
-	}
+    PyUnicode_InternInPlace(p);
+    if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
+        PyUnicode_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
+        Py_INCREF(*p);
+    }
 }
 
 PyObject *
 PyUnicode_InternFromString(const char *cp)
 {
-	PyObject *s = PyUnicode_FromString(cp);
-	if (s == NULL)
-		return NULL;
-	PyUnicode_InternInPlace(&s);
-	return s;
+    PyObject *s = PyUnicode_FromString(cp);
+    if (s == NULL)
+        return NULL;
+    PyUnicode_InternInPlace(&s);
+    return s;
 }
 
 void _Py_ReleaseInternedUnicodeStrings(void)
 {
-	PyObject *keys;
-	PyUnicodeObject *s;
-	Py_ssize_t i, n;
-	Py_ssize_t immortal_size = 0, mortal_size = 0;
-
-	if (interned == NULL || !PyDict_Check(interned))
-		return;
-	keys = PyDict_Keys(interned);
-	if (keys == NULL || !PyList_Check(keys)) {
-		PyErr_Clear();
-		return;
-	}
-
-	/* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
-	   detector, interned unicode strings are not forcibly deallocated;
-	   rather, we give them their stolen references back, and then clear
-	   and DECREF the interned dict. */
-
-	n = PyList_GET_SIZE(keys);
-	fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
-		n);
-	for (i = 0; i < n; i++) {
-		s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
-		switch (s->state) {
-		case SSTATE_NOT_INTERNED:
-			/* XXX Shouldn't happen */
-			break;
-		case SSTATE_INTERNED_IMMORTAL:
-			Py_REFCNT(s) += 1;
-			immortal_size += s->length;
-			break;
-		case SSTATE_INTERNED_MORTAL:
-			Py_REFCNT(s) += 2;
-			mortal_size += s->length;
-			break;
-		default:
-			Py_FatalError("Inconsistent interned string state.");
-		}
-		s->state = SSTATE_NOT_INTERNED;
-	}
-	fprintf(stderr, "total size of all interned strings: "
-			"%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
-			"mortal/immortal\n", mortal_size, immortal_size);
-	Py_DECREF(keys);
-	PyDict_Clear(interned);
-	Py_DECREF(interned);
-	interned = NULL;
+    PyObject *keys;
+    PyUnicodeObject *s;
+    Py_ssize_t i, n;
+    Py_ssize_t immortal_size = 0, mortal_size = 0;
+
+    if (interned == NULL || !PyDict_Check(interned))
+        return;
+    keys = PyDict_Keys(interned);
+    if (keys == NULL || !PyList_Check(keys)) {
+        PyErr_Clear();
+        return;
+    }
+
+    /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
+       detector, interned unicode strings are not forcibly deallocated;
+       rather, we give them their stolen references back, and then clear
+       and DECREF the interned dict. */
+
+    n = PyList_GET_SIZE(keys);
+    fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
+            n);
+    for (i = 0; i < n; i++) {
+        s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
+        switch (s->state) {
+        case SSTATE_NOT_INTERNED:
+            /* XXX Shouldn't happen */
+            break;
+        case SSTATE_INTERNED_IMMORTAL:
+            Py_REFCNT(s) += 1;
+            immortal_size += s->length;
+            break;
+        case SSTATE_INTERNED_MORTAL:
+            Py_REFCNT(s) += 2;
+            mortal_size += s->length;
+            break;
+        default:
+            Py_FatalError("Inconsistent interned string state.");
+        }
+        s->state = SSTATE_NOT_INTERNED;
+    }
+    fprintf(stderr, "total size of all interned strings: "
+            "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
+            "mortal/immortal\n", mortal_size, immortal_size);
+    Py_DECREF(keys);
+    PyDict_Clear(interned);
+    Py_DECREF(interned);
+    interned = NULL;
 }
 
 
 /********************* Unicode Iterator **************************/
 
 typedef struct {
-	PyObject_HEAD
-	Py_ssize_t it_index;
-	PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
+    PyObject_HEAD
+    Py_ssize_t it_index;
+    PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
 } unicodeiterobject;
 
 static void
 unicodeiter_dealloc(unicodeiterobject *it)
 {
-	_PyObject_GC_UNTRACK(it);
-	Py_XDECREF(it->it_seq);
-	PyObject_GC_Del(it);
+    _PyObject_GC_UNTRACK(it);
+    Py_XDECREF(it->it_seq);
+    PyObject_GC_Del(it);
 }
 
 static int
 unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
 {
-	Py_VISIT(it->it_seq);
-	return 0;
+    Py_VISIT(it->it_seq);
+    return 0;
 }
 
 static PyObject *
 unicodeiter_next(unicodeiterobject *it)
 {
-	PyUnicodeObject *seq;
-	PyObject *item;
+    PyUnicodeObject *seq;
+    PyObject *item;
+
+    assert(it != NULL);
+    seq = it->it_seq;
+    if (seq == NULL)
+        return NULL;
+    assert(PyUnicode_Check(seq));
+
+    if (it->it_index < PyUnicode_GET_SIZE(seq)) {
+        item = PyUnicode_FromUnicode(
+            PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
+        if (item != NULL)
+            ++it->it_index;
+        return item;
+    }
 
-	assert(it != NULL);
-	seq = it->it_seq;
-	if (seq == NULL)
-		return NULL;
-	assert(PyUnicode_Check(seq));
-
-	if (it->it_index < PyUnicode_GET_SIZE(seq)) {
-		item = PyUnicode_FromUnicode(
-                    PyUnicode_AS_UNICODE(seq)+it->it_index, 1);
-		if (item != NULL)
-			++it->it_index;
-		return item;
-	}
-
-	Py_DECREF(seq);
-	it->it_seq = NULL;
-	return NULL;
+    Py_DECREF(seq);
+    it->it_seq = NULL;
+    return NULL;
 }
 
 static PyObject *
 unicodeiter_len(unicodeiterobject *it)
 {
-	Py_ssize_t len = 0;
-	if (it->it_seq)
-		len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
-	return PyLong_FromSsize_t(len);
+    Py_ssize_t len = 0;
+    if (it->it_seq)
+        len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index;
+    return PyLong_FromSsize_t(len);
 }
 
 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
 
 static PyMethodDef unicodeiter_methods[] = {
-	{"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
-         length_hint_doc},
- 	{NULL,		NULL}		/* sentinel */
+    {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
+     length_hint_doc},
+    {NULL,      NULL}       /* sentinel */
 };
 
 PyTypeObject PyUnicodeIter_Type = {
-	PyVarObject_HEAD_INIT(&PyType_Type, 0)
-	"str_iterator",			/* tp_name */
-	sizeof(unicodeiterobject),		/* tp_basicsize */
-	0,					/* tp_itemsize */
-	/* methods */
-	(destructor)unicodeiter_dealloc,	/* tp_dealloc */
-	0,					/* tp_print */
-	0,					/* tp_getattr */
-	0,					/* tp_setattr */
-	0,					/* tp_compare */
-	0,					/* tp_repr */
-	0,					/* tp_as_number */
-	0,					/* tp_as_sequence */
-	0,					/* tp_as_mapping */
-	0,					/* tp_hash */
-	0,					/* tp_call */
-	0,					/* tp_str */
-	PyObject_GenericGetAttr,		/* tp_getattro */
-	0,					/* tp_setattro */
-	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-	0,					/* tp_doc */
-	(traverseproc)unicodeiter_traverse,	/* tp_traverse */
-	0,					/* tp_clear */
-	0,					/* tp_richcompare */
-	0,					/* tp_weaklistoffset */
-	PyObject_SelfIter,			/* tp_iter */
-	(iternextfunc)unicodeiter_next,		/* tp_iternext */
-	unicodeiter_methods,			/* tp_methods */
-	0,
+    PyVarObject_HEAD_INIT(&PyType_Type, 0)
+    "str_iterator",         /* tp_name */
+    sizeof(unicodeiterobject),      /* tp_basicsize */
+    0,                  /* tp_itemsize */
+    /* methods */
+    (destructor)unicodeiter_dealloc,    /* tp_dealloc */
+    0,                  /* tp_print */
+    0,                  /* tp_getattr */
+    0,                  /* tp_setattr */
+    0,                  /* tp_reserved */
+    0,                  /* tp_repr */
+    0,                  /* tp_as_number */
+    0,                  /* tp_as_sequence */
+    0,                  /* tp_as_mapping */
+    0,                  /* tp_hash */
+    0,                  /* tp_call */
+    0,                  /* tp_str */
+    PyObject_GenericGetAttr,        /* tp_getattro */
+    0,                  /* tp_setattro */
+    0,                  /* tp_as_buffer */
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+    0,                  /* tp_doc */
+    (traverseproc)unicodeiter_traverse, /* tp_traverse */
+    0,                  /* tp_clear */
+    0,                  /* tp_richcompare */
+    0,                  /* tp_weaklistoffset */
+    PyObject_SelfIter,          /* tp_iter */
+    (iternextfunc)unicodeiter_next,     /* tp_iternext */
+    unicodeiter_methods,            /* tp_methods */
+    0,
 };
 
 static PyObject *
 unicode_iter(PyObject *seq)
 {
-	unicodeiterobject *it;
+    unicodeiterobject *it;
 
-	if (!PyUnicode_Check(seq)) {
-		PyErr_BadInternalCall();
-		return NULL;
-	}
-	it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
-	if (it == NULL)
-		return NULL;
-	it->it_index = 0;
-	Py_INCREF(seq);
-	it->it_seq = (PyUnicodeObject *)seq;
-	_PyObject_GC_TRACK(it);
-	return (PyObject *)it;
+    if (!PyUnicode_Check(seq)) {
+        PyErr_BadInternalCall();
+        return NULL;
+    }
+    it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
+    if (it == NULL)
+        return NULL;
+    it->it_index = 0;
+    Py_INCREF(seq);
+    it->it_seq = (PyUnicodeObject *)seq;
+    _PyObject_GC_TRACK(it);
+    return (PyObject *)it;
 }
 
 size_t
@@ -9899,8 +9899,8 @@
 
 
 /*
-Local variables:
-c-basic-offset: 4
-indent-tabs-mode: nil
-End:
+  Local variables:
+  c-basic-offset: 4
+  indent-tabs-mode: nil
+  End:
 */

Modified: python/branches/io-c/Objects/weakrefobject.c
==============================================================================
--- python/branches/io-c/Objects/weakrefobject.c	(original)
+++ python/branches/io-c/Objects/weakrefobject.c	Sun Feb  8 21:39:02 2009
@@ -342,7 +342,7 @@
     0,	                        /*tp_print*/
     0,                          /*tp_getattr*/
     0,                          /*tp_setattr*/
-    0,	                        /*tp_compare*/
+    0,	                        /*tp_reserved*/
     (reprfunc)weakref_repr,     /*tp_repr*/
     0,                          /*tp_as_number*/
     0,                          /*tp_as_sequence*/
@@ -642,7 +642,7 @@
     0,				        /* tp_print */
     0,				        /* tp_getattr */
     0, 				        /* tp_setattr */
-    0,				        /* tp_compare */
+    0,				        /* tp_reserved */
     (reprfunc)proxy_repr,	        /* tp_repr */
     &proxy_as_number,		        /* tp_as_number */
     &proxy_as_sequence,		        /* tp_as_sequence */
@@ -675,7 +675,7 @@
     0,				        /* tp_print */
     0,				        /* tp_getattr */
     0, 				        /* tp_setattr */
-    0,				        /* tp_compare */
+    0,				        /* tp_reserved */
     (unaryfunc)proxy_repr,	        /* tp_repr */
     &proxy_as_number,		        /* tp_as_number */
     &proxy_as_sequence,		        /* tp_as_sequence */

Modified: python/branches/io-c/PC/_msi.c
==============================================================================
--- python/branches/io-c/PC/_msi.c	(original)
+++ python/branches/io-c/PC/_msi.c	Sun Feb  8 21:39:02 2009
@@ -473,7 +473,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -643,7 +643,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -791,7 +791,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/
@@ -908,7 +908,7 @@
 	0,			/*tp_print*/
 	0,			/*tp_getattr*/
 	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
+	0,			/*tp_reserved*/
 	0,			/*tp_repr*/
 	0,			/*tp_as_number*/
 	0,			/*tp_as_sequence*/

Modified: python/branches/io-c/PC/_subprocess.c
==============================================================================
--- python/branches/io-c/PC/_subprocess.c	(original)
+++ python/branches/io-c/PC/_subprocess.c	Sun Feb  8 21:39:02 2009
@@ -133,7 +133,7 @@
 	0, /*tp_print*/
 	0,				/*tp_getattr*/
 	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
+	0,				/*tp_reserved*/
 	0,				/*tp_repr*/
 	&sp_handle_as_number,		/*tp_as_number */
 	0,				/*tp_as_sequence */

Modified: python/branches/io-c/PC/bdist_wininst/install.c
==============================================================================
--- python/branches/io-c/PC/bdist_wininst/install.c	(original)
+++ python/branches/io-c/PC/bdist_wininst/install.c	Sun Feb  8 21:39:02 2009
@@ -114,6 +114,7 @@
 FILE *logfile;
 
 char modulename[MAX_PATH];
+wchar_t wmodulename[MAX_PATH];
 
 HWND hwndMain;
 HWND hDialog;
@@ -299,6 +300,27 @@
 
 typedef void PyObject;
 
+// Convert a "char *" string to "whcar_t *", or NULL on error.
+// Result string must be free'd
+wchar_t *widen_string(char *src)
+{
+	wchar_t *result;
+	DWORD dest_cch;
+	int src_len = strlen(src) + 1; // include NULL term in all ops
+	/* use MultiByteToWideChar() to see how much we need. */
+	/* NOTE: this will include the null-term in the length */
+	dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0);
+	// alloc the buffer
+	result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t));
+	if (result==NULL)
+		return NULL;
+	/* do the conversion */
+	if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) {
+		free(result);
+		return NULL;
+	}
+	return result;
+}
 
 /*
  * Returns number of files which failed to compile,
@@ -307,7 +329,7 @@
 static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag)
 {
 	DECLPROC(hPython, void, Py_Initialize, (void));
-	DECLPROC(hPython, void, Py_SetProgramName, (char *));
+	DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *));
 	DECLPROC(hPython, void, Py_Finalize, (void));
 	DECLPROC(hPython, int, PyRun_SimpleString, (char *));
 	DECLPROC(hPython, PyObject *, PySys_GetObject, (char *));
@@ -326,7 +348,7 @@
 		return -1;
 
 	*Py_OptimizeFlag = optimize_flag ? 1 : 0;
-	Py_SetProgramName(modulename);
+	Py_SetProgramName(wmodulename);
 	Py_Initialize();
 
 	errors += do_compile_files(PyRun_SimpleString, optimize_flag);
@@ -694,10 +716,12 @@
  */
 
 static int
-run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv)
+do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv)
 {
+	int fh, result, i;
+	static wchar_t *wargv[256];
 	DECLPROC(hPython, void, Py_Initialize, (void));
-	DECLPROC(hPython, int, PySys_SetArgv, (int, char **));
+	DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **));
 	DECLPROC(hPython, int, PyRun_SimpleString, (char *));
 	DECLPROC(hPython, void, Py_Finalize, (void));
 	DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
@@ -706,9 +730,6 @@
 	DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
 	DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
 
-	int result = 0;
-	int fh;
-
 	if (!Py_Initialize || !PySys_SetArgv
 	    || !PyRun_SimpleString || !Py_Finalize)
 		return 1;
@@ -730,11 +751,20 @@
 	}
 
 	SetDlgItemText(hDialog, IDC_INFO, "Running Script...");
-		
+
 	Py_Initialize();
 
 	prepare_script_environment(hPython);
-	PySys_SetArgv(argc, argv);
+	// widen the argv array for py3k.
+	memset(wargv, 0, sizeof(wargv));
+	for (i=0;i<argc;i++)
+		wargv[i] = argv[i] ? widen_string(argv[i]) : NULL;
+	PySys_SetArgv(argc, wargv);
+	// free the strings we just widened.
+	for (i=0;i<argc;i++)
+		if (wargv[i])
+			free(wargv[i]);
+
 	result = 3;
 	{
 		struct _stat statbuf;
@@ -751,7 +781,57 @@
 	Py_Finalize();
 
 	close(fh);
+	return result;
+}
+
+static int
+run_installscript(char *pathname, int argc, char **argv, char **pOutput)
+{
+	HINSTANCE hPython;
+	int result = 1;
+	int out_buf_size;
+	HANDLE redirected, old_stderr, old_stdout;
+	char *tempname;
+
+	*pOutput = NULL;
 
+	tempname = tempnam(NULL, NULL);
+	// We use a static CRT while the Python version we load uses
+	// the CRT from one of various possibile DLLs.  As a result we
+	// need to redirect the standard handles using the API rather
+	// than the CRT.
+	redirected = CreateFile(
+					tempname,
+					GENERIC_WRITE | GENERIC_READ,
+					FILE_SHARE_READ,
+					NULL,
+					CREATE_ALWAYS,
+					FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
+					NULL);
+	old_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
+	old_stderr = GetStdHandle(STD_ERROR_HANDLE);
+	SetStdHandle(STD_OUTPUT_HANDLE, redirected);
+	SetStdHandle(STD_ERROR_HANDLE, redirected);
+
+	hPython = LoadPythonDll(pythondll);
+	if (hPython) {
+		result = do_run_installscript(hPython, pathname, argc, argv);
+		FreeLibrary(hPython);
+	} else {
+		fprintf(stderr, "*** Could not load Python ***");
+	}
+	SetStdHandle(STD_OUTPUT_HANDLE, old_stdout);
+	SetStdHandle(STD_ERROR_HANDLE, old_stderr);
+	out_buf_size = min(GetFileSize(redirected, NULL), 4096);
+	*pOutput = malloc(out_buf_size+1);
+	if (*pOutput) {
+		DWORD nread = 0;
+		SetFilePointer(redirected, 0, 0, FILE_BEGIN);
+		ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL);
+		(*pOutput)[nread] = '\0';
+	}
+	CloseHandle(redirected);
+	DeleteFile(tempname);
 	return result;
 }
 
@@ -759,7 +839,7 @@
 {
 	int rc;
 	DECLPROC(hPython, void, Py_Initialize, (void));
-	DECLPROC(hPython, void, Py_SetProgramName, (char *));
+	DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *));
 	DECLPROC(hPython, void, Py_Finalize, (void));
 	DECLPROC(hPython, int, PyRun_SimpleString, (char *));
 	DECLPROC(hPython, void, PyErr_Print, (void));
@@ -768,7 +848,7 @@
 	    !PyRun_SimpleString || !PyErr_Print)
 		return -1;
 
-	Py_SetProgramName(modulename);
+	Py_SetProgramName(wmodulename);
 	Py_Initialize();
 	prepare_script_environment(hPython);
 	rc = PyRun_SimpleString(script);
@@ -781,11 +861,21 @@
 static int run_simple_script(char *script)
 {
 	int rc;
-	char *tempname;
 	HINSTANCE hPython;
-	tempname = tempnam(NULL, NULL);
-	freopen(tempname, "a", stderr);
-	freopen(tempname, "a", stdout);
+	char *tempname = tempnam(NULL, NULL);
+	// Redirect output using win32 API - see comments above...
+	HANDLE redirected = CreateFile(
+					tempname,
+					GENERIC_WRITE | GENERIC_READ,
+					FILE_SHARE_READ,
+					NULL,
+					CREATE_ALWAYS,
+					FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
+					NULL);
+	HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
+	HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE);
+	SetStdHandle(STD_OUTPUT_HANDLE, redirected);
+	SetStdHandle(STD_ERROR_HANDLE, redirected);
 
 	hPython = LoadPythonDll(pythondll);
 	if (!hPython) {
@@ -796,10 +886,8 @@
 	}
 	rc = do_run_simple_script(hPython, script);
 	FreeLibrary(hPython);
-	fflush(stderr);
-	fclose(stderr);
-	fflush(stdout);
-	fclose(stdout);
+	SetStdHandle(STD_OUTPUT_HANDLE, old_stdout);
+	SetStdHandle(STD_ERROR_HANDLE, old_stderr);
 	/* We only care about the output when we fail.  If the script works
 	   OK, then we discard it
 	*/
@@ -808,24 +896,24 @@
 		char *err_buf;
 		const char *prefix = "Running the pre-installation script failed\r\n";
 		int prefix_len = strlen(prefix);
-		FILE *fp = fopen(tempname, "rb");
-		fseek(fp, 0, SEEK_END);
-		err_buf_size = ftell(fp);
-		fseek(fp, 0, SEEK_SET);
+		err_buf_size = GetFileSize(redirected, NULL);
+		if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway...
+			err_buf_size = 4096;
 		err_buf = malloc(prefix_len + err_buf_size + 1);
 		if (err_buf) {
-			int n;
+			DWORD n = 0;
 			strcpy(err_buf, prefix);
-			n = fread(err_buf+prefix_len, 1, err_buf_size, fp);
+			SetFilePointer(redirected, 0, 0, FILE_BEGIN);
+			ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL);
 			err_buf[prefix_len+n] = '\0';
-			fclose(fp);
 			set_failure_reason(err_buf);
 			free(err_buf);
 		} else {
 			set_failure_reason("Out of memory!");
 		}
 	}
-	remove(tempname);
+	CloseHandle(redirected);
+	DeleteFile(tempname);
 	return rc;
 }
 
@@ -1946,12 +2034,9 @@
 
 		if (success && install_script && install_script[0]) {
 			char fname[MAX_PATH];
-			char *tempname;
-			FILE *fp;
-			char buffer[4096];
-			int n;
+			char *buffer;
 			HCURSOR hCursor;
-			HINSTANCE hPython;
+			int result;
 
 			char *argv[3] = {NULL, "-install", NULL};
 
@@ -1964,48 +2049,21 @@
 			if (logfile)
 				fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname);
 
-			tempname = tempnam(NULL, NULL);
-
-			if (!freopen(tempname, "a", stderr))
-				MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
-			if (!freopen(tempname, "a", stdout))
-				MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
-/*
-  if (0 != setvbuf(stdout, NULL, _IONBF, 0))
-  MessageBox(GetFocus(), "setvbuf stdout", NULL, MB_OK);
-*/
 			hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
 
 			argv[0] = fname;
 
-			hPython = LoadPythonDll(pythondll);
-			if (hPython) {
-				int result;
-				result = run_installscript(hPython, fname, 2, argv);
-				if (-1 == result) {
-					fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
-				}
-				FreeLibrary(hPython);
-			} else {
-				fprintf(stderr, "*** Could not load Python ***");
+			result = run_installscript(fname, 2, argv, &buffer);
+			if (0 != result) {
+				fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
 			}
-			fflush(stderr);
-			fclose(stderr);
-			fflush(stdout);
-			fclose(stdout);
-	    
-			fp = fopen(tempname, "rb");
-			n = fread(buffer, 1, sizeof(buffer), fp);
-			fclose(fp);
-			remove(tempname);
-	    
-			buffer[n] = '\0';
-	    
-			SetDlgItemText(hwnd, IDC_INFO, buffer);
+			if (buffer)
+				SetDlgItemText(hwnd, IDC_INFO, buffer);
 			SetDlgItemText(hwnd, IDC_TITLE,
 					"Postinstall script finished.\n"
 					"Click the Finish button to exit the Setup wizard.");
 
+			free(buffer);
 			SetCursor(hCursor);
 			CloseLogfile();
 		}
@@ -2418,42 +2476,17 @@
 	/* this function may be called more than one time with the same
 	   script, only run it one time */
 	if (strcmp(lastscript, scriptname)) {
-		HINSTANCE hPython;
 		char *argv[3] = {NULL, "-remove", NULL};
-		char buffer[4096];
-		FILE *fp;
-		char *tempname;
-		int n;
+		char *buffer = NULL;
 
 		argv[0] = scriptname;
 
-		tempname = tempnam(NULL, NULL);
+		if (0 != run_installscript(scriptname, 2, argv, &buffer))
+			fprintf(stderr, "*** Could not run installation script ***");
 
-		if (!freopen(tempname, "a", stderr))
-			MessageBox(GetFocus(), "freopen stderr", NULL, MB_OK);
-		if (!freopen(tempname, "a", stdout))
-			MessageBox(GetFocus(), "freopen stdout", NULL, MB_OK);
-	
-		hPython = LoadLibrary(dllname);
-		if (hPython) {
-			if (0x80000000 == run_installscript(hPython, scriptname, 2, argv))
-				fprintf(stderr, "*** Could not load Python ***");
-			FreeLibrary(hPython);
-		}
-	
-		fflush(stderr);
-		fclose(stderr);
-		fflush(stdout);
-		fclose(stdout);
-	
-		fp = fopen(tempname, "rb");
-		n = fread(buffer, 1, sizeof(buffer), fp);
-		fclose(fp);
-		remove(tempname);
-	
-		buffer[n] = '\0';
-		if (buffer[0])
+		if (buffer && buffer[0])
 			MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK);
+		free(buffer);
 
 		strcpy(lastscript, scriptname);
 	}
@@ -2617,6 +2650,7 @@
 	char *basename;
 
 	GetModuleFileName(NULL, modulename, sizeof(modulename));
+	GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0]));
 
 	/* Map the executable file to memory */
 	arc_data = MapExistingFile(modulename, &arc_size);

Modified: python/branches/io-c/PC/dl_nt.c
==============================================================================
--- python/branches/io-c/PC/dl_nt.c	(original)
+++ python/branches/io-c/PC/dl_nt.c	Sun Feb  8 21:39:02 2009
@@ -18,6 +18,63 @@
 HMODULE PyWin_DLLhModule = NULL;
 const char *PyWin_DLLVersionString = dllVersionBuffer;
 
+// Windows "Activation Context" work:
+// Our .pyd extension modules are generally built without a manifest (ie,
+// those included with Python and those built with a default distutils.
+// This requires we perform some "activation context" magic when loading our
+// extensions.  In summary:
+// * As our DLL loads we save the context being used.
+// * Before loading our extensions we re-activate our saved context.
+// * After extension load is complete we restore the old context.
+// As an added complication, this magic only works on XP or later - we simply
+// use the existence (or not) of the relevant function pointers from kernel32.
+// See bug 4566 (http://python.org/sf/4566) for more details.
+
+typedef BOOL (WINAPI * PFN_GETCURRENTACTCTX)(HANDLE *);
+typedef BOOL (WINAPI * PFN_ACTIVATEACTCTX)(HANDLE, ULONG_PTR *);
+typedef BOOL (WINAPI * PFN_DEACTIVATEACTCTX)(DWORD, ULONG_PTR);
+typedef BOOL (WINAPI * PFN_ADDREFACTCTX)(HANDLE);
+typedef BOOL (WINAPI * PFN_RELEASEACTCTX)(HANDLE);
+
+// locals and function pointers for this activation context magic.
+static HANDLE PyWin_DLLhActivationContext = NULL; // one day it might be public
+static PFN_GETCURRENTACTCTX pfnGetCurrentActCtx = NULL;
+static PFN_ACTIVATEACTCTX pfnActivateActCtx = NULL;
+static PFN_DEACTIVATEACTCTX pfnDeactivateActCtx = NULL;
+static PFN_ADDREFACTCTX pfnAddRefActCtx = NULL;
+static PFN_RELEASEACTCTX pfnReleaseActCtx = NULL;
+
+void _LoadActCtxPointers()
+{
+	HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll");
+	if (hKernel32)
+		pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx");
+	// If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest.
+	if (pfnGetCurrentActCtx) {
+		pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx");
+		pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx");
+		pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx");
+		pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx");
+	}
+}
+
+ULONG_PTR _Py_ActivateActCtx()
+{
+	ULONG_PTR ret = 0;
+	if (PyWin_DLLhActivationContext && pfnActivateActCtx)
+		if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) {
+			OutputDebugString("Python failed to activate the activation context before loading a DLL\n");
+			ret = 0; // no promise the failing function didn't change it!
+		}
+	return ret;
+}
+
+void _Py_DeactivateActCtx(ULONG_PTR cookie)
+{
+	if (cookie && pfnDeactivateActCtx)
+		if (!(*pfnDeactivateActCtx)(0, cookie))
+			OutputDebugString("Python failed to de-activate the activation context\n");
+}
 
 BOOL	WINAPI	DllMain (HANDLE hInst, 
 						ULONG ul_reason_for_call,
@@ -29,9 +86,18 @@
 			PyWin_DLLhModule = hInst;
 			// 1000 is a magic number I picked out of the air.  Could do with a #define, I spose...
 			LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer));
-			//initall();
+
+			// and capture our activation context for use when loading extensions.
+			_LoadActCtxPointers();
+			if (pfnGetCurrentActCtx && pfnAddRefActCtx)
+				if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext))
+					if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext))
+						OutputDebugString("Python failed to load the default activation context\n");
 			break;
+
 		case DLL_PROCESS_DETACH:
+			if (pfnReleaseActCtx)
+				(*pfnReleaseActCtx)(PyWin_DLLhActivationContext);
 			break;
 	}
 	return TRUE;

Modified: python/branches/io-c/PC/getpathp.c
==============================================================================
--- python/branches/io-c/PC/getpathp.c	(original)
+++ python/branches/io-c/PC/getpathp.c	Sun Feb  8 21:39:02 2009
@@ -200,6 +200,7 @@
 }
 
 #ifdef MS_WINDOWS
+#ifdef Py_ENABLE_SHARED
 
 /* a string loaded from the DLL at startup.*/
 extern const char *PyWin_DLLVersionString;
@@ -349,6 +350,7 @@
 		free(keyBuf);
 	return retval;
 }
+#endif /* Py_ENABLE_SHARED */
 #endif /* MS_WINDOWS */
 
 static void
@@ -359,11 +361,15 @@
 	wchar_t *prog = Py_GetProgramName();
 
 #ifdef MS_WINDOWS
+#ifdef Py_ENABLE_SHARED
 	extern HANDLE PyWin_DLLhModule;
 	/* static init of progpath ensures final char remains \0 */
 	if (PyWin_DLLhModule)
 		if (!GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN))
 			dllpath[0] = 0;
+#else
+	dllpath[0] = 0;
+#endif
 	if (GetModuleFileNameW(NULL, progpath, MAXPATHLEN))
 		return;
 #endif
@@ -471,8 +477,10 @@
 	}
  
 	skiphome = pythonhome==NULL ? 0 : 1;
+#ifdef Py_ENABLE_SHARED
 	machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
 	userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
+#endif
 	/* We only use the default relative PYTHONPATH if we havent
 	   anything better to use! */
 	skipdefault = envpath!=NULL || pythonhome!=NULL || \

Modified: python/branches/io-c/PC/winreg.c
==============================================================================
--- python/branches/io-c/PC/winreg.c	(original)
+++ python/branches/io-c/PC/winreg.c	Sun Feb  8 21:39:02 2009
@@ -326,7 +326,7 @@
 "Operations:\n"
 "__bool__ - Handles with an open object return true, otherwise false.\n"
 "__int__ - Converting a handle to an integer returns the Win32 handle.\n"
-"__cmp__ - Handle objects are compared using the handle value.");
+"rich comparison - Handle objects are compared using the handle value.");
 
 
 PyDoc_STRVAR(PyHKEY_Close_doc,
@@ -485,7 +485,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	PyHKEY_compareFunc,		/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	&PyHKEY_NumberMethods,		/* tp_as_number */
 	0,				/* tp_as_sequence */

Modified: python/branches/io-c/PCbuild/bdist_wininst.vcproj
==============================================================================
--- python/branches/io-c/PCbuild/bdist_wininst.vcproj	(original)
+++ python/branches/io-c/PCbuild/bdist_wininst.vcproj	Sun Feb  8 21:39:02 2009
@@ -55,7 +55,7 @@
 				AdditionalIncludeDirectories="..\PC\bdist_wininst;..\Include;..\Modules\zlib"
 				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE"
 				StringPooling="true"
-				RuntimeLibrary="2"
+				RuntimeLibrary="0"
 				EnableFunctionLevelLinking="true"
 				WarningLevel="3"
 				SuppressStartupBanner="true"
@@ -145,7 +145,7 @@
 				AdditionalIncludeDirectories="..\PC\bdist_wininst;..\Include;..\Modules\zlib"
 				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE"
 				StringPooling="true"
-				RuntimeLibrary="2"
+				RuntimeLibrary="0"
 				EnableFunctionLevelLinking="true"
 				WarningLevel="3"
 				SuppressStartupBanner="true"

Modified: python/branches/io-c/Parser/asdl_c.py
==============================================================================
--- python/branches/io-c/Parser/asdl_c.py	(original)
+++ python/branches/io-c/Parser/asdl_c.py	Sun Feb  8 21:39:02 2009
@@ -662,7 +662,7 @@
     0,                       /* tp_print */
     0,                       /* tp_getattr */
     0,                       /* tp_setattr */
-    0,                       /* tp_compare */
+    0,                       /* tp_reserved */
     0,                       /* tp_repr */
     0,                       /* tp_as_number */
     0,                       /* tp_as_sequence */

Modified: python/branches/io-c/Python/Python-ast.c
==============================================================================
--- python/branches/io-c/Python/Python-ast.c	(original)
+++ python/branches/io-c/Python/Python-ast.c	Sun Feb  8 21:39:02 2009
@@ -479,7 +479,7 @@
     0,                       /* tp_print */
     0,                       /* tp_getattr */
     0,                       /* tp_setattr */
-    0,                       /* tp_compare */
+    0,                       /* tp_reserved */
     0,                       /* tp_repr */
     0,                       /* tp_as_number */
     0,                       /* tp_as_sequence */

Modified: python/branches/io-c/Python/bltinmodule.c
==============================================================================
--- python/branches/io-c/Python/bltinmodule.c	(original)
+++ python/branches/io-c/Python/bltinmodule.c	Sun Feb  8 21:39:02 2009
@@ -416,7 +416,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -493,25 +493,6 @@
 ;
 
 
-static PyObject *
-builtin_cmp(PyObject *self, PyObject *args)
-{
-	PyObject *a, *b;
-	int c;
-
-	if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
-		return NULL;
-	if (PyObject_Cmp(a, b, &c) < 0)
-		return NULL;
-	return PyLong_FromLong((long)c);
-}
-
-PyDoc_STRVAR(cmp_doc,
-"cmp(x, y) -> integer\n\
-\n\
-Return negative if x<y, zero if x==y, positive if x>y.");
-
-
 static char *
 source_as_string(PyObject *cmd, char *funcname, char *what)
 {
@@ -1036,7 +1017,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -1717,15 +1698,14 @@
 static PyObject *
 builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
 {
-#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
 	static PyObject *round_str = NULL;
-	int ndigits = UNDEF_NDIGITS;
+	PyObject *ndigits = NULL;
 	static char *kwlist[] = {"number", "ndigits", 0};
 	PyObject *number, *round;
 
-	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:round",
-                kwlist, &number, &ndigits))
-                return NULL;
+	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round",
+					 kwlist, &number, &ndigits))
+		return NULL;
 
 	if (Py_TYPE(number)->tp_dict == NULL) {
 		if (PyType_Ready(Py_TYPE(number)) < 0)
@@ -1746,15 +1726,14 @@
 		return NULL;
 	}
 
-	if (ndigits == UNDEF_NDIGITS)
-                return PyObject_CallFunction(round, "O", number);
+	if (ndigits == NULL)
+		return PyObject_CallFunction(round, "O", number);
 	else
-                return PyObject_CallFunction(round, "Oi", number, ndigits);
-#undef UNDEF_NDIGITS
+		return PyObject_CallFunction(round, "OO", number, ndigits);
 }
 
 PyDoc_STRVAR(round_doc,
-"round(number[, ndigits]) -> floating point number\n\
+"round(number[, ndigits]) -> number\n\
 \n\
 Round a number to a given precision in decimal digits (default 0 digits).\n\
 This returns an int when called with one argument, otherwise the\n\
@@ -2187,7 +2166,7 @@
 	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
-	0,				/* tp_compare */
+	0,				/* tp_reserved */
 	0,				/* tp_repr */
 	0,				/* tp_as_number */
 	0,				/* tp_as_sequence */
@@ -2232,7 +2211,6 @@
  	{"ascii",	builtin_ascii,      METH_O, ascii_doc},
 	{"bin",		builtin_bin,	    METH_O, bin_doc},
  	{"chr",		builtin_chr,        METH_VARARGS, chr_doc},
- 	{"cmp",		builtin_cmp,        METH_VARARGS, cmp_doc},
  	{"compile",	(PyCFunction)builtin_compile,    METH_VARARGS | METH_KEYWORDS, compile_doc},
  	{"delattr",	builtin_delattr,    METH_VARARGS, delattr_doc},
  	{"dir",		builtin_dir,        METH_VARARGS, dir_doc},

Modified: python/branches/io-c/Python/compile.c
==============================================================================
--- python/branches/io-c/Python/compile.c	(original)
+++ python/branches/io-c/Python/compile.c	Sun Feb  8 21:39:02 2009
@@ -4006,6 +4006,8 @@
 		return NULL;
 	while (PyDict_Next(dict, &pos, &k, &v)) {
 		i = PyLong_AS_LONG(v);
+		/* The keys of the dictionary are tuples. (see compiler_add_o)
+		   The object we want is always first, though. */
 		k = PyTuple_GET_ITEM(k, 0);
 		Py_INCREF(k);
 		assert((i - offset) < size);
@@ -4029,13 +4031,11 @@
 			flags |= CO_NESTED;
 		if (ste->ste_generator)
 			flags |= CO_GENERATOR;
+		if (ste->ste_varargs)
+			flags |= CO_VARARGS;
+		if (ste->ste_varkeywords)
+			flags |= CO_VARKEYWORDS;
 	}
-	if (ste->ste_varargs)
-		flags |= CO_VARARGS;
-	if (ste->ste_varkeywords)
-		flags |= CO_VARKEYWORDS;
-	if (ste->ste_generator)
-		flags |= CO_GENERATOR;
 
 	/* (Only) inherit compilerflags in PyCF_MASK */
 	flags |= (c->c_flags->cf_flags & PyCF_MASK);

Modified: python/branches/io-c/Python/dynload_win.c
==============================================================================
--- python/branches/io-c/Python/dynload_win.c	(original)
+++ python/branches/io-c/Python/dynload_win.c	Sun Feb  8 21:39:02 2009
@@ -11,6 +11,10 @@
 #include "importdl.h"
 #include <windows.h>
 
+// "activation context" magic - see dl_nt.c...
+extern ULONG_PTR _Py_ActivateActCtx();
+void _Py_DeactivateActCtx(ULONG_PTR cookie);
+
 const struct filedescr _PyImport_DynLoadFiletab[] = {
 #ifdef _DEBUG
 	{"_d.pyd", "rb", C_EXTENSION},
@@ -172,6 +176,7 @@
 		char pathbuf[260];
 		LPTSTR dummy;
 		unsigned int old_mode;
+		ULONG_PTR cookie = 0;
 		/* We use LoadLibraryEx so Windows looks for dependent DLLs 
 		    in directory of pathname first.  However, Windows95
 		    can sometimes not work correctly unless the absolute
@@ -184,10 +189,13 @@
 		if (GetFullPathName(pathname,
 				    sizeof(pathbuf),
 				    pathbuf,
-				    &dummy))
+				    &dummy)) {
+			ULONG_PTR cookie = _Py_ActivateActCtx();
 			/* XXX This call doesn't exist in Windows CE */
 			hDLL = LoadLibraryEx(pathname, NULL,
 					     LOAD_WITH_ALTERED_SEARCH_PATH);
+			_Py_DeactivateActCtx(cookie);
+		}
 
 		/* restore old error mode settings */
 		SetErrorMode(old_mode);

Modified: python/branches/io-c/Python/import.c
==============================================================================
--- python/branches/io-c/Python/import.c	(original)
+++ python/branches/io-c/Python/import.c	Sun Feb  8 21:39:02 2009
@@ -2894,12 +2894,14 @@
 imp_find_module(PyObject *self, PyObject *args)
 {
 	char *name;
-	PyObject *path = NULL;
+	PyObject *ret, *path = NULL;
 	if (!PyArg_ParseTuple(args, "es|O:find_module",
 	                      Py_FileSystemDefaultEncoding, &name,
 	                      &path))
 		return NULL;
-	return call_find_module(name, path);
+	ret = call_find_module(name, path);
+	PyMem_Free(name);
+	return ret;
 }
 
 static PyObject *
@@ -3293,7 +3295,7 @@
 	0,                         /*tp_print*/
 	0,                         /*tp_getattr*/
 	0,                         /*tp_setattr*/
-	0,                         /*tp_compare*/
+	0,                         /*tp_reserved*/
 	0,                         /*tp_repr*/
 	0,                         /*tp_as_number*/
 	0,                         /*tp_as_sequence*/

Modified: python/branches/io-c/Python/makeopcodetargets.py
==============================================================================
--- python/branches/io-c/Python/makeopcodetargets.py	(original)
+++ python/branches/io-c/Python/makeopcodetargets.py	Sun Feb  8 21:39:02 2009
@@ -3,6 +3,9 @@
 (for compilers supporting computed gotos or "labels-as-values", such as gcc).
 """
 
+# This code should stay compatible with Python 2.3, at least while
+# some of the buildbots have Python 2.3 as their system Python.
+
 import imp
 import os
 
@@ -25,7 +28,7 @@
             continue
         targets[op] = "TARGET_%s" % opname
     f.write("static void *opcode_targets[256] = {\n")
-    f.write(",\n".join("\t&&%s" % s for s in targets))
+    f.write(",\n".join(["\t&&%s" % s for s in targets]))
     f.write("\n};\n")
 
 

Modified: python/branches/io-c/Python/symtable.c
==============================================================================
--- python/branches/io-c/Python/symtable.c	(original)
+++ python/branches/io-c/Python/symtable.c	Sun Feb  8 21:39:02 2009
@@ -130,7 +130,7 @@
 	0,                                      /* tp_print */
 	0,			               /* tp_getattr */
 	0,					/* tp_setattr */
-	0,			                /* tp_compare */
+	0,			                /* tp_reserved */
 	(reprfunc)ste_repr,			/* tp_repr */
 	0,					/* tp_as_number */
 	0,			                /* tp_as_sequence */

Modified: python/branches/io-c/Python/sysmodule.c
==============================================================================
--- python/branches/io-c/Python/sysmodule.c	(original)
+++ python/branches/io-c/Python/sysmodule.c	Sun Feb  8 21:39:02 2009
@@ -1017,7 +1017,7 @@
 builtin_module_names -- tuple of module names built into this interpreter\n\
 subversion -- subversion information of the build as tuple\n\
 version -- the version of this interpreter as a string\n\
-version_info -- version information as a tuple\n\
+version_info -- version information as a named tuple\n\
 hexversion -- version information encoded as a single integer\n\
 copyright -- copyright notice pertaining to this interpreter\n\
 platform -- platform identifier\n\
@@ -1227,6 +1227,75 @@
 	return seq;
 }
 
+PyDoc_STRVAR(version_info__doc__,
+"sys.version_info\n\
+\n\
+Version information as a named tuple.");
+
+static PyTypeObject VersionInfoType;
+
+static PyStructSequence_Field version_info_fields[] = {
+	{"major", "Major release number"},
+	{"minor", "Minor release number"},
+	{"micro", "Patch release number"},
+	{"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
+	{"serial", "Serial release number"},
+	{0}
+};
+
+static PyStructSequence_Desc version_info_desc = {
+	"sys.version_info",     /* name */
+	version_info__doc__,    /* doc */
+	version_info_fields,    /* fields */
+	5
+};
+
+static PyObject *
+make_version_info(void)
+{
+	PyObject *version_info;
+	char *s;
+	int pos = 0;
+
+	version_info = PyStructSequence_New(&VersionInfoType);
+	if (version_info == NULL) {
+		return NULL;
+	}
+
+	/*
+	 * These release level checks are mutually exclusive and cover
+	 * the field, so don't get too fancy with the pre-processor!
+	 */
+#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
+	s = "alpha";
+#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
+	s = "beta";
+#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
+	s = "candidate";
+#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
+	s = "final";
+#endif
+
+#define SetIntItem(flag) \
+	PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
+#define SetStrItem(flag) \
+	PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
+
+	SetIntItem(PY_MAJOR_VERSION);
+	SetIntItem(PY_MINOR_VERSION);
+	SetIntItem(PY_MICRO_VERSION);
+	SetStrItem(s);
+	SetIntItem(PY_RELEASE_SERIAL);
+#undef SetIntItem
+#undef SetStrItem
+
+	if (PyErr_Occurred()) {
+		Py_CLEAR(version_info);
+		return NULL;
+	}
+	return version_info;
+}
+
 static struct PyModuleDef sysmodule = {
 	PyModuleDef_HEAD_INIT,
 	"sys",
@@ -1239,8 +1308,6 @@
 	NULL
 };
 
-
-
 PyObject *
 _PySys_Init(void)
 {
@@ -1291,25 +1358,6 @@
 					  svn_revision));
 	SET_SYS_FROM_STRING("dont_write_bytecode",
 			     PyBool_FromLong(Py_DontWriteBytecodeFlag));
-	/*
-	 * These release level checks are mutually exclusive and cover
-	 * the field, so don't get too fancy with the pre-processor!
-	 */
-#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
-	s = "alpha";
-#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
-	s = "beta";
-#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
-	s = "candidate";
-#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
-	s = "final";
-#endif
-
-	SET_SYS_FROM_STRING("version_info",
-			    Py_BuildValue("iiiUi", PY_MAJOR_VERSION,
-					       PY_MINOR_VERSION,
-					       PY_MICRO_VERSION, s,
-					       PY_RELEASE_SERIAL));
 	SET_SYS_FROM_STRING("api_version",
 			    PyLong_FromLong(PYTHON_API_VERSION));
 	SET_SYS_FROM_STRING("copyright",
@@ -1361,6 +1409,15 @@
 		PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
 	}
 
+	/* version_info */
+	if (VersionInfoType.tp_name == 0)
+		PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
+	SET_SYS_FROM_STRING("version_info", make_version_info());
+	/* prevent user from creating new instances */
+	VersionInfoType.tp_init = NULL;
+	VersionInfoType.tp_new = NULL;
+
+	/* flags */
 	if (FlagsType.tp_name == 0)
 		PyStructSequence_InitType(&FlagsType, &flags_desc);
 	SET_SYS_FROM_STRING("flags", make_flags());

Modified: python/branches/io-c/Python/traceback.c
==============================================================================
--- python/branches/io-c/Python/traceback.c	(original)
+++ python/branches/io-c/Python/traceback.c	Sun Feb  8 21:39:02 2009
@@ -72,7 +72,7 @@
 	0,		/*tp_print*/
 	0,    /*tp_getattr*/
 	0,		/*tp_setattr*/
-	0,		/*tp_compare*/
+	0,		/*tp_reserved*/
 	0,		/*tp_repr*/
 	0,		/*tp_as_number*/
 	0,		/*tp_as_sequence*/

Modified: python/branches/io-c/README
==============================================================================
--- python/branches/io-c/README	(original)
+++ python/branches/io-c/README	Sun Feb  8 21:39:02 2009
@@ -130,11 +130,11 @@
 If you're not sure whether you're dealing with a bug or a feature, use
 the mailing list:
 
-    python-3000 at python.org
+    python-dev at python.org
 
 To subscribe to the list, use the mailman form:
 
-    http://mail.python.org/mailman/listinfo/python-3000/
+    http://mail.python.org/mailman/listinfo/python-dev/
 
 
 Build Instructions

Modified: python/branches/io-c/Tools/framer/framer/slots.py
==============================================================================
--- python/branches/io-c/Tools/framer/framer/slots.py	(original)
+++ python/branches/io-c/Tools/framer/framer/slots.py	Sun Feb  8 21:39:02 2009
@@ -15,7 +15,7 @@
          Slot("tp_print", "printfunc"),
          Slot("tp_getattr", "getattrfunc"),
          Slot("tp_setattr", "setattrfunc"),
-         Slot("tp_compare", "cmpfunc", "__cmp__"),
+         Slot("tp_reserved", "void*"),
          Slot("tp_repr", "reprfunc", "__repr__"),
          Slot("tp_as_number"),
          Slot("tp_as_sequence"),

Modified: python/branches/io-c/Tools/pybench/Calls.py
==============================================================================
--- python/branches/io-c/Tools/pybench/Calls.py	(original)
+++ python/branches/io-c/Tools/pybench/Calls.py	Sun Feb  8 21:39:02 2009
@@ -2,7 +2,7 @@
 
 class PythonFunctionCalls(Test):
 
-    version = 2.0
+    version = 2.1
     operations = 5*(1+4+4+2)
     rounds = 60000
 
@@ -178,8 +178,8 @@
         # localize functions
         f0 = globals
         f1 = hash
-        f2 = cmp
-        f3 = range
+        f2 = divmod
+        f3 = max
 
         # do calls
         for i in range(self.rounds):
@@ -279,8 +279,8 @@
         # localize functions
         f0 = dir
         f1 = hash
-        f2 = range
-        f3 = range
+        f2 = divmod
+        f3 = max
 
         # do calls
         for i in range(self.rounds):

Modified: python/branches/io-c/Tools/pybench/CommandLine.py
==============================================================================
--- python/branches/io-c/Tools/pybench/CommandLine.py	(original)
+++ python/branches/io-c/Tools/pybench/CommandLine.py	Sun Feb  8 21:39:02 2009
@@ -11,6 +11,8 @@
 
 """
 
+from __future__ import print_function
+
 __copyright__ = """\
 Copyright (c), 1997-2006, Marc-Andre Lemburg (mal at lemburg.com)
 Copyright (c), 2000-2006, eGenix.com Software GmbH (info at egenix.com)

Modified: python/branches/io-c/Tools/pybench/README
==============================================================================
--- python/branches/io-c/Tools/pybench/README	(original)
+++ python/branches/io-c/Tools/pybench/README	Sun Feb  8 21:39:02 2009
@@ -82,7 +82,7 @@
   --examples       show examples of usage
 
 Version:
- 2.0
+ 2.1
 
 The normal operation is to run the suite and display the
 results. Use -f to save them for later reuse or comparisons.
@@ -95,9 +95,9 @@
 
 Examples:
 
-python2.1 pybench.py -f p21.pybench
-python2.5 pybench.py -f p25.pybench
-python pybench.py -s p25.pybench -c p21.pybench
+python3.0 pybench.py -f p30.pybench
+python3.1 pybench.py -f p31.pybench
+python pybench.py -s p31.pybench -c p30.pybench
 """
 
 License
@@ -111,9 +111,9 @@
 
 """
 -------------------------------------------------------------------------------
-PYBENCH 2.0
+PYBENCH 2.1
 -------------------------------------------------------------------------------
-* using Python 2.4.2
+* using CPython 3.0
 * disabled garbage collection
 * system check interval set to maximum: 2147483647
 * using timer: time.time
@@ -141,8 +141,9 @@
        Processor:    x86_64
 
     Python:
+       Implementation: CPython
        Executable:   /usr/local/bin/python
-       Version:      2.4.2
+       Version:      3.0
        Compiler:     GCC 3.3.4 (pre 3.3.5 20040809)
        Bits:         64bit
        Build:        Oct  1 2005 15:24:35 (#1)
@@ -331,6 +332,11 @@
 Version History
 ---------------
 
+  2.1: made some minor changes for compatibility with Python 3.0:
+        - replaced cmp with divmod and range with max in Calls.py
+          (cmp no longer exists in 3.0, and range is a list in
+          Python 2.x and an iterator in Python 3.x)
+
   2.0: rewrote parts of pybench which resulted in more repeatable
        timings:
         - made timer a parameter

Modified: python/branches/io-c/Tools/pybench/Strings.py
==============================================================================
--- python/branches/io-c/Tools/pybench/Strings.py	(original)
+++ python/branches/io-c/Tools/pybench/Strings.py	Sun Feb  8 21:39:02 2009
@@ -1,6 +1,12 @@
 from pybench import Test
 import sys
 
+try:
+    intern
+except NameError:
+    intern = sys.intern
+
+
 class ConcatStrings(Test):
 
     version = 2.0
@@ -174,7 +180,7 @@
     def test(self):
 
         # Make sure the strings *are* interned
-        s = sys.intern(''.join(map(str,range(10))))
+        s = intern(''.join(map(str,range(10))))
         t = s
 
         for i in range(self.rounds):
@@ -240,7 +246,7 @@
 
     def calibrate(self):
 
-        s = sys.intern(''.join(map(str,range(10))))
+        s = intern(''.join(map(str,range(10))))
         t = s
 
         for i in range(self.rounds):

Modified: python/branches/io-c/Tools/pybench/pybench.py
==============================================================================
--- python/branches/io-c/Tools/pybench/pybench.py	(original)
+++ python/branches/io-c/Tools/pybench/pybench.py	Sun Feb  8 21:39:02 2009
@@ -3,14 +3,15 @@
 """ A Python Benchmark Suite
 
 """
-#
-# Note: Please keep this module compatible to Python 1.5.2.
+# Note: Please keep this module compatible to Python 2.6.
 #
 # Tests may include features in later Python versions, but these
 # should then be embedded in try-except clauses in the configuration
 # module Setup.py.
 #
 
+from __future__ import print_function
+
 # pybench Copyright
 __copyright__ = """\
 Copyright (c), 1997-2006, Marc-Andre Lemburg (mal at lemburg.com)
@@ -44,7 +45,7 @@
     import pickle
 
 # Version number; version history: see README file !
-__version__ = '2.0'
+__version__ = '2.1'
 
 ### Constants
 
@@ -174,7 +175,7 @@
     # Version number of the test as float (x.yy); this is important
     # for comparisons of benchmark runs - tests with unequal version
     # number will not get compared.
-    version = 2.0
+    version = 2.1
 
     # The number of abstract operations done in each round of the
     # test. An operation is the basic unit of what you want to
@@ -403,7 +404,7 @@
     roundtime = 0
 
     # Benchmark version number as float x.yy
-    version = 2.0
+    version = 2.1
 
     # Produce verbose output ?
     verbose = 0

Modified: python/branches/io-c/Tools/pybench/systimes.py
==============================================================================
--- python/branches/io-c/Tools/pybench/systimes.py	(original)
+++ python/branches/io-c/Tools/pybench/systimes.py	Sun Feb  8 21:39:02 2009
@@ -31,6 +31,9 @@
     the author. All Rights Reserved.
 
 """
+
+from __future__ import print_function
+
 import time, sys
 
 #

Modified: python/branches/io-c/setup.py
==============================================================================
--- python/branches/io-c/setup.py	(original)
+++ python/branches/io-c/setup.py	Sun Feb  8 21:39:02 2009
@@ -112,51 +112,36 @@
         self.extensions = extensions
 
         # Fix up the autodetected modules, prefixing all the source files
-        # with Modules/ and adding Python's include directory to the path.
-        (srcdir,) = sysconfig.get_config_vars('srcdir')
+        # with Modules/.
+        srcdir = sysconfig.get_config_var('srcdir')
         if not srcdir:
             # Maybe running on Windows but not using CYGWIN?
             raise ValueError("No source directory; cannot proceed.")
-
-        # Figure out the location of the source code for extension modules
-        # (This logic is copied in distutils.test.test_sysconfig,
-        # so building in a separate directory does not break test_distutils.)
-        moddir = os.path.join(os.getcwd(), srcdir, 'Modules')
-        moddir = os.path.normpath(moddir)
-        srcdir, tail = os.path.split(moddir)
-        srcdir = os.path.normpath(srcdir)
-        moddir = os.path.normpath(moddir)
-
-        moddirlist = [moddir]
-        incdirlist = ['./Include']
+        srcdir = os.path.abspath(srcdir)
+        moddirlist = [os.path.join(srcdir, 'Modules')]
 
         # Platform-dependent module source and include directories
         platform = self.get_platform()
 
-        alldirlist = moddirlist + incdirlist
-
         # Fix up the paths for scripts, too
         self.distribution.scripts = [os.path.join(srcdir, filename)
                                      for filename in self.distribution.scripts]
 
         # Python header files
-        headers = glob("Include/*.h") + ["pyconfig.h"]
+        headers = [sysconfig.get_config_h_filename()]
+        headers += glob(os.path.join(sysconfig.get_python_inc(), "*.h"))
 
         for ext in self.extensions[:]:
             ext.sources = [ find_module_file(filename, moddirlist)
                             for filename in ext.sources ]
             if ext.depends is not None:
-                ext.depends = [find_module_file(filename, alldirlist)
+                ext.depends = [find_module_file(filename, moddirlist)
                                for filename in ext.depends]
             else:
                 ext.depends = []
             # re-compile extensions if a header file has been changed
             ext.depends.extend(headers)
 
-            ext.include_dirs.append( '.' ) # to get config.h
-            for incdir in incdirlist:
-                ext.include_dirs.append( os.path.join(srcdir, incdir) )
-
             # If a module has already been built statically,
             # don't build it here
             if ext.name in sys.builtin_module_names:
@@ -368,7 +353,7 @@
         config_h_vars = sysconfig.parse_config_h(open(config_h))
 
         platform = self.get_platform()
-        (srcdir,) = sysconfig.get_config_vars('srcdir')
+        srcdir = sysconfig.get_config_var('srcdir')
 
         # Check for AtheOS which has libraries in non-standard locations
         if platform == 'atheos':
@@ -1283,7 +1268,7 @@
     def configure_ctypes_darwin(self, ext):
         # Darwin (OS X) uses preconfigured files, in
         # the Modules/_ctypes/libffi_osx directory.
-        (srcdir,) = sysconfig.get_config_vars('srcdir')
+        srcdir = sysconfig.get_config_var('srcdir')
         ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
                                                   '_ctypes', 'libffi_osx'))
         sources = [os.path.join(ffi_srcdir, p)
@@ -1312,7 +1297,7 @@
             if sys.platform == 'darwin':
                 return self.configure_ctypes_darwin(ext)
 
-            (srcdir,) = sysconfig.get_config_vars('srcdir')
+            srcdir = sysconfig.get_config_var('srcdir')
             ffi_builddir = os.path.join(self.build_temp, 'libffi')
             ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
                                          '_ctypes', 'libffi'))


More information about the Python-checkins mailing list