[Python-checkins] r64887 - in python/branches/tlee-ast-optimize: Doc/c-api/float.rst Doc/c-api/int.rst Doc/c-api/sequence.rst Doc/library/collections.rst Doc/library/gc.rst Doc/library/robotparser.rst Doc/library/shutil.rst Doc/library/sys.rst Doc/library/urllib2.rst Doc/library/urlparse.rst Doc/tools/sphinxext/opensearch.xml Doc/whatsnew/2.6.rst Include/floatobject.h Include/intobject.h Include/traceback.h Lib/SimpleHTTPServer.py Lib/asynchat.py Lib/asyncore.py Lib/bisect.py Lib/curses/textpad.py Lib/fractions.py Lib/httplib.py Lib/lib2to3 Lib/lib2to3/fixes/fix_imports.py Lib/lib2to3/tests/test_fixers.py Lib/optparse.py Lib/subprocess.py Lib/test/regrtest.py Lib/test/test_asyncore.py Lib/test/test_audioop.py Lib/test/test_bisect.py Lib/test/test_bz2.py Lib/test/test_exceptions.py Lib/test/test_float.py Lib/test/test_fractions.py Lib/test/test_lib2to3.py Lib/test/test_sys.py Lib/test/test_traceback.py Lib/unittest.py Lib/zipfile.py Misc/ACKS Misc/NEWS Modules/Setup.dist Modules/_bisectmodule.c Modules/_fileio.c Modules/_testcapimodule.c Modules/audioop.c Modules/bz2module.c Modules/cmathmodule.c Modules/gcmodule.c Modules/timemodule.c Objects/abstract.c Objects/bytearrayobject.c Objects/exceptions.c Objects/floatobject.c Objects/frameobject.c Objects/intobject.c Objects/longobject.c Objects/object.c Objects/setobject.c Objects/unicodeobject.c Python/_warnings.c Python/sysmodule.c Python/traceback.c

thomas.lee python-checkins at python.org
Sat Jul 12 06:22:38 CEST 2008


Author: thomas.lee
Date: Sat Jul 12 06:22:35 2008
New Revision: 64887

Log:
Merged revisions 64727-64886 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/trunk

................
  r64729 | mark.dickinson | 2008-07-05 21:33:52 +1000 (Sat, 05 Jul 2008) | 5 lines
  
  Issue 3188: accept float('infinity') as well as float('inf').  This
  makes the float constructor behave in the same way as specified
  by various other language standards, including C99, IEEE 754r,
  and the IBM Decimal standard.
................
  r64735 | mark.dickinson | 2008-07-06 01:25:48 +1000 (Sun, 06 Jul 2008) | 3 lines
  
  Minor rewrite of cmath_log to work around a Sun compiler bug.  See issue 
  #3168.
................
  r64736 | martin.v.loewis | 2008-07-06 01:45:45 +1000 (Sun, 06 Jul 2008) | 20 lines
  
  Merged revisions 64285-64735 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r64493 | benjamin.peterson | 2008-06-24 04:14:14 +0200 (Di, 24 Jun 2008) | 1 line
    
    add a fix_import mapping for cPickle -> pickle
  ........
    r64651 | brett.cannon | 2008-07-02 04:00:11 +0200 (Mi, 02 Jul 2008) | 3 lines
    
    Update fix_imports for urllib. Had to change the fixer itself to handle modules
    that are split across several renames in 3.0.
  ........
    r64669 | brett.cannon | 2008-07-02 21:43:48 +0200 (Mi, 02 Jul 2008) | 4 lines
    
    Backing out last change until fix_imports is working again. Also re-enable the
    testing for fix_imports; if it is deemed that it takes too long to run then a
    random sample should be taken and used to test it.
  ........
................
  r64737 | martin.v.loewis | 2008-07-06 01:48:20 +1000 (Sun, 06 Jul 2008) | 2 lines
  
  Disable lib2to3 by default, unless run explicitly.
................
  r64742 | benjamin.peterson | 2008-07-06 02:29:38 +1000 (Sun, 06 Jul 2008) | 1 line
  
  make regrtest aware of the lib2to3 resource
................
  r64744 | georg.brandl | 2008-07-06 02:43:45 +1000 (Sun, 06 Jul 2008) | 2 lines
  
  Keep below 80 chars.
................
  r64745 | facundo.batista | 2008-07-06 05:19:50 +1000 (Sun, 06 Jul 2008) | 3 lines
  
  
  Issue 3289.  Removed two lines that ended doing nothing.
................
  r64746 | facundo.batista | 2008-07-06 06:39:59 +1000 (Sun, 06 Jul 2008) | 4 lines
  
  
  Issue #3239. Differentiate the ascii call from the curses one and 
  the builtin one.
................
  r64753 | gregory.p.smith | 2008-07-06 13:35:58 +1000 (Sun, 06 Jul 2008) | 4 lines
  
  - Issue #2862: Make int and float freelist management consistent with other
    freelists.  Changes their CompactFreeList apis into ClearFreeList apis and
    calls them via gc.collect().
................
  r64756 | gregory.p.smith | 2008-07-06 17:16:40 +1000 (Sun, 06 Jul 2008) | 3 lines
  
  - Issue #2113: Fix error in subprocess.Popen if the select system call is
    interrupted by a signal.
................
  r64757 | benjamin.peterson | 2008-07-06 22:39:09 +1000 (Sun, 06 Jul 2008) | 1 line
  
  remove test_compact_freelists from test_sys
................
  r64758 | gregory.p.smith | 2008-07-07 03:06:29 +1000 (Mon, 07 Jul 2008) | 2 lines
  
  fix issue3304 - remove an incorrect PyMem_Free in fileio_init
................
  r64759 | georg.brandl | 2008-07-07 03:36:20 +1000 (Mon, 07 Jul 2008) | 2 lines
  
  Fix opensearch template.
................
  r64760 | andrew.kuchling | 2008-07-07 03:43:16 +1000 (Mon, 07 Jul 2008) | 1 line
  
  Wording fix
................
  r64761 | andrew.kuchling | 2008-07-07 03:44:17 +1000 (Mon, 07 Jul 2008) | 1 line
  
  Add two items; rewrap paragraph
................
  r64762 | amaury.forgeotdarc | 2008-07-07 07:34:39 +1000 (Mon, 07 Jul 2008) | 8 lines
  
  Issue839496: SimpleHTTPServer should open all files in binary mode.
  
  Forward-port of 38255 (2005/01/15!)
  This was already fixed in 2.4, but never merged into trunk...
  py3k is already right, thanks to the bytes/str distinction!
  
  Should be backported to 2.5.
................
  r64767 | gregory.p.smith | 2008-07-07 14:31:58 +1000 (Mon, 07 Jul 2008) | 4 lines
  
  - Issue #3309: Fix bz2.BZFile itererator to release its internal lock
    properly when raising an exception due to the bz2file being closed.
    Prevents a deadlock.
................
  r64768 | josiah.carlson | 2008-07-07 14:51:46 +1000 (Mon, 07 Jul 2008) | 2 lines
  
  Fixed bugs 760475, 953599, and 1519.
................
  r64769 | gregory.p.smith | 2008-07-07 14:54:31 +1000 (Mon, 07 Jul 2008) | 2 lines
  
  Add commented out #_sha256 and #_sha512 lines per issue 3183.
................
  r64771 | gregory.p.smith | 2008-07-07 15:09:12 +1000 (Mon, 07 Jul 2008) | 4 lines
  
  - Issue #3094: httplib.HTTPSConnection Host: headers no longer include the
    redundant ":443" port number designation when the connection is using the
    default https port (443).
................
  r64772 | skip.montanaro | 2008-07-07 21:16:14 +1000 (Mon, 07 Jul 2008) | 2 lines
  
  Correct grammar.
................
  r64774 | andrew.kuchling | 2008-07-08 02:51:09 +1000 (Tue, 08 Jul 2008) | 1 line
  
  Fix example to match text
................
  r64775 | facundo.batista | 2008-07-08 03:02:59 +1000 (Tue, 08 Jul 2008) | 3 lines
  
  
  Issue 3306. Better control for a lenght in findmax() function.
................
  r64788 | georg.brandl | 2008-07-08 17:05:23 +1000 (Tue, 08 Jul 2008) | 2 lines
  
  Add missing ABCs to list.
................
  r64791 | nick.coghlan | 2008-07-09 00:08:04 +1000 (Wed, 09 Jul 2008) | 1 line
  
  Issue 2517: Allow unicode messages in Exceptions again by correctly bypassing the instance dictionary when looking up __unicode__ on new-style classes
................
  r64793 | nick.coghlan | 2008-07-09 00:21:42 +1000 (Wed, 09 Jul 2008) | 1 line
  
  Add missing NEWS and ACK entries for r64791
................
  r64835 | raymond.hettinger | 2008-07-10 19:31:08 +1000 (Thu, 10 Jul 2008) | 1 line
  
  Issue 3287: Raise correct exception for float inputs.
................
  r64836 | raymond.hettinger | 2008-07-10 20:28:41 +1000 (Thu, 10 Jul 2008) | 1 line
  
  Use operator.index() instead of n.__index__().
................
  r64842 | robert.schuppenies | 2008-07-10 23:43:26 +1000 (Thu, 10 Jul 2008) | 2 lines
  
  Fixed Issue3122 and extended sys.getsizeof tests for built-in types.
................
  r64845 | raymond.hettinger | 2008-07-11 00:03:19 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Issue 3301:  Bisect functions behaved badly when lo was negative.
................
  r64846 | raymond.hettinger | 2008-07-11 00:34:57 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Issue 3285: Fractions from_float() and from_decimal() accept Integral arguments.
................
  r64849 | andrew.kuchling | 2008-07-11 00:43:31 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Wording changes
................
  r64853 | robert.schuppenies | 2008-07-11 01:24:04 +1000 (Fri, 11 Jul 2008) | 3 lines
  
  Added additional __sizeof__ implementations and addressed comments made in
  Issue3122.
................
  r64854 | raymond.hettinger | 2008-07-11 01:37:08 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Clear the -3 warnings in optparse.py
................
  r64855 | raymond.hettinger | 2008-07-11 02:06:41 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Suppress -3 warnings in unittest.py
................
  r64856 | robert.schuppenies | 2008-07-11 03:13:55 +1000 (Fri, 11 Jul 2008) | 3 lines
  
  Added garbage collector overhead and optional default return value to
  sys.getsizeof.
................
  r64858 | brett.cannon | 2008-07-11 10:10:49 +1000 (Fri, 11 Jul 2008) | 2 lines
  
  Removal an invalid entry as the fixer for urllib is under active development.
................
  r64859 | brett.cannon | 2008-07-11 10:12:52 +1000 (Fri, 11 Jul 2008) | 3 lines
  
  Document the fact that urllib2 spans multiple modules with new names in Python
  3.0.
................
  r64861 | brett.cannon | 2008-07-11 10:16:30 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Doc that urlparse is named urllib.parse in Python 3.0.
................
  r64865 | brett.cannon | 2008-07-11 10:48:57 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Doc that robotparse has been renamed urllib.robotparser in Python 3.0.
................
  r64866 | brett.cannon | 2008-07-11 10:50:01 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Fix a minor typo in the last entry made.
................
  r64871 | raymond.hettinger | 2008-07-11 22:00:21 +1000 (Fri, 11 Jul 2008) | 1 line
  
  Add cautionary note on the use of PySequence_Fast_ITEMS.
................
  r64880 | amaury.forgeotdarc | 2008-07-12 07:28:25 +1000 (Sat, 12 Jul 2008) | 5 lines
  
  #3317 in zipfile module, restore the previous names of global variables:
  some applications relied on them.
  
  Also remove duplicated lines.
................
  r64881 | amaury.forgeotdarc | 2008-07-12 07:45:06 +1000 (Sat, 12 Jul 2008) | 3 lines
  
  #3342: In tracebacks, printed source lines were not indented since r62555.
  #3343: Py_DisplaySourceLine should be a private function. Rename it to _Py_DisplaySourceLine.
................
  r64882 | josiah.carlson | 2008-07-12 08:17:14 +1000 (Sat, 12 Jul 2008) | 2 lines
  
  Fix for the AttributeError in test_asynchat.
................
  r64885 | josiah.carlson | 2008-07-12 09:26:59 +1000 (Sat, 12 Jul 2008) | 2 lines
  
  Fixed test for asyncore.
................


Modified:
   python/branches/tlee-ast-optimize/   (props changed)
   python/branches/tlee-ast-optimize/Doc/c-api/float.rst
   python/branches/tlee-ast-optimize/Doc/c-api/int.rst
   python/branches/tlee-ast-optimize/Doc/c-api/sequence.rst
   python/branches/tlee-ast-optimize/Doc/library/collections.rst
   python/branches/tlee-ast-optimize/Doc/library/gc.rst
   python/branches/tlee-ast-optimize/Doc/library/robotparser.rst
   python/branches/tlee-ast-optimize/Doc/library/shutil.rst
   python/branches/tlee-ast-optimize/Doc/library/sys.rst
   python/branches/tlee-ast-optimize/Doc/library/urllib2.rst
   python/branches/tlee-ast-optimize/Doc/library/urlparse.rst
   python/branches/tlee-ast-optimize/Doc/tools/sphinxext/opensearch.xml
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.6.rst
   python/branches/tlee-ast-optimize/Include/floatobject.h
   python/branches/tlee-ast-optimize/Include/intobject.h
   python/branches/tlee-ast-optimize/Include/traceback.h
   python/branches/tlee-ast-optimize/Lib/SimpleHTTPServer.py
   python/branches/tlee-ast-optimize/Lib/asynchat.py
   python/branches/tlee-ast-optimize/Lib/asyncore.py
   python/branches/tlee-ast-optimize/Lib/bisect.py
   python/branches/tlee-ast-optimize/Lib/curses/textpad.py
   python/branches/tlee-ast-optimize/Lib/fractions.py
   python/branches/tlee-ast-optimize/Lib/httplib.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/   (props changed)
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_fixers.py
   python/branches/tlee-ast-optimize/Lib/optparse.py
   python/branches/tlee-ast-optimize/Lib/subprocess.py
   python/branches/tlee-ast-optimize/Lib/test/regrtest.py
   python/branches/tlee-ast-optimize/Lib/test/test_asyncore.py
   python/branches/tlee-ast-optimize/Lib/test/test_audioop.py
   python/branches/tlee-ast-optimize/Lib/test/test_bisect.py
   python/branches/tlee-ast-optimize/Lib/test/test_bz2.py
   python/branches/tlee-ast-optimize/Lib/test/test_exceptions.py
   python/branches/tlee-ast-optimize/Lib/test/test_float.py
   python/branches/tlee-ast-optimize/Lib/test/test_fractions.py
   python/branches/tlee-ast-optimize/Lib/test/test_lib2to3.py
   python/branches/tlee-ast-optimize/Lib/test/test_sys.py
   python/branches/tlee-ast-optimize/Lib/test/test_traceback.py
   python/branches/tlee-ast-optimize/Lib/unittest.py
   python/branches/tlee-ast-optimize/Lib/zipfile.py
   python/branches/tlee-ast-optimize/Misc/ACKS
   python/branches/tlee-ast-optimize/Misc/NEWS
   python/branches/tlee-ast-optimize/Modules/Setup.dist
   python/branches/tlee-ast-optimize/Modules/_bisectmodule.c
   python/branches/tlee-ast-optimize/Modules/_fileio.c
   python/branches/tlee-ast-optimize/Modules/_testcapimodule.c
   python/branches/tlee-ast-optimize/Modules/audioop.c
   python/branches/tlee-ast-optimize/Modules/bz2module.c
   python/branches/tlee-ast-optimize/Modules/cmathmodule.c
   python/branches/tlee-ast-optimize/Modules/gcmodule.c
   python/branches/tlee-ast-optimize/Modules/timemodule.c
   python/branches/tlee-ast-optimize/Objects/abstract.c
   python/branches/tlee-ast-optimize/Objects/bytearrayobject.c
   python/branches/tlee-ast-optimize/Objects/exceptions.c
   python/branches/tlee-ast-optimize/Objects/floatobject.c
   python/branches/tlee-ast-optimize/Objects/frameobject.c
   python/branches/tlee-ast-optimize/Objects/intobject.c
   python/branches/tlee-ast-optimize/Objects/longobject.c
   python/branches/tlee-ast-optimize/Objects/object.c
   python/branches/tlee-ast-optimize/Objects/setobject.c
   python/branches/tlee-ast-optimize/Objects/unicodeobject.c
   python/branches/tlee-ast-optimize/Python/_warnings.c
   python/branches/tlee-ast-optimize/Python/sysmodule.c
   python/branches/tlee-ast-optimize/Python/traceback.c

Modified: python/branches/tlee-ast-optimize/Doc/c-api/float.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/float.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/float.rst	Sat Jul 12 06:22:35 2008
@@ -86,10 +86,9 @@
    .. versionadded:: 2.6
 
 
-.. cfunction:: void PyFloat_CompactFreeList(size_t *bc, size_t *bf, size_t *sum)
+.. cfunction:: int PyFloat_ClearFreeList(void)
 
-   Compact the float free list. *bc* is the number of allocated blocks before
-   blocks are freed, *bf* is the number of freed blocks and *sum* is the number
-   of remaining objects in the blocks.
+   Clear the float free list. Return the number of items that could not
+   be freed.
 
    .. versionadded:: 2.6

Modified: python/branches/tlee-ast-optimize/Doc/c-api/int.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/int.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/int.rst	Sat Jul 12 06:22:35 2008
@@ -122,10 +122,9 @@
    (:const:`LONG_MAX`, as defined in the system header files).
 
 
-.. cfunction:: void PyInt_CompactFreeList(size_t *bc, size_t *bf, size_t *sum)
+.. cfunction:: int PyInt_ClearFreeList(void)
 
-   Compact the integer free list. *bc* is the number of allocated blocks before
-   blocks are freed, *bf* is the number of freed blocks and *sum* is the number
-   of remaining objects in the blocks.
+   Clear the integer free list. Return the number of items that could not
+   be freed.
 
    .. versionadded:: 2.6

Modified: python/branches/tlee-ast-optimize/Doc/c-api/sequence.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/sequence.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/sequence.rst	Sat Jul 12 06:22:35 2008
@@ -143,6 +143,10 @@
 
    Return the underlying array of PyObject pointers.  Assumes that *o* was returned
    by :cfunc:`PySequence_Fast` and *o* is not *NULL*.
+   
+   Note, if a list gets resized, the reallocation may relocate the items array.
+   So, only use the underlying array pointer in contexts where the sequence 
+   cannot change.
 
    .. versionadded:: 2.4
 

Modified: python/branches/tlee-ast-optimize/Doc/library/collections.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/collections.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/collections.rst	Sat Jul 12 06:22:35 2008
@@ -46,42 +46,50 @@
 
 The collections module offers the following ABCs:
 
-=========================  ====================  ======================  ====================================================
-ABC                        Inherits              Abstract Methods        Mixin Methods
-=========================  ====================  ======================  ====================================================
-:class:`Container`                               ``__contains__``
-:class:`Hashable`                                ``__hash__``
-:class:`Iterable`                                ``__iter__``
-:class:`Iterator`          :class:`Iterable`     ``__next__``            ``__iter__``
-:class:`Sized`          			 ``__len__``
-
-:class:`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:`Sequence`          :class:`Sized`,       ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
-                           :class:`Iterable`,    and ``__len__``         ``index``, and ``count``
-                           :class:`Container`
-
-:class:`MutableSequnce`    :class:`Sequence`     ``__getitem__``         Inherited Sequence methods and
-                                                 ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
-                                                 ``insert``,             ``remove``, and ``__iadd__``
-                                                 and ``__len__``
-
-: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:`MutableSet`        :class:`Set`          ``add`` and             Inherited Set methods and
-                                                 ``discard``             ``clear``, ``pop``, ``remove``, ``__ior__``,
-                                                                         ``__iand__``, ``__ixor__``, and ``__isub__``
-=========================  ====================  ======================  ====================================================
+=========================  =====================  ======================  ====================================================
+ABC                        Inherits               Abstract Methods        Mixin Methods
+=========================  =====================  ======================  ====================================================
+:class:`Container`                                ``__contains__``
+:class:`Hashable`                                 ``__hash__``
+:class:`Iterable`                                 ``__iter__``
+:class:`Iterator`          :class:`Iterable`      ``__next__``            ``__iter__``
+:class:`Sized`          			  ``__len__``
+:class:`Callable`                                 ``__call__``
+                                                  
+:class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
+                           :class:`Iterable`,     and ``__len__``         ``index``, and ``count``
+                           :class:`Container`     
+                                                  
+:class:`MutableSequnce`    :class:`Sequence`      ``__getitem__``         Inherited Sequence methods and
+                                                  ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
+                                                  ``insert``,             ``remove``, and ``__iadd__``
+                                                  and ``__len__``
+                                                  
+: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:`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:`MappingView`       :class:`Sized`                                 ``__len__``
+:class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
+                           :class:`Set`                                   ``__iter__``
+:class:`ItemsView`         :class:`MappingView`,                          ``__contains__``,
+                           :class:`Set`                                   ``__iter__``
+:class:`ValuesView`        :class:`MappingView`                           ``__contains__``, ``__iter__``
+=========================  =====================  ======================  ====================================================
 
 These ABCs allow us to ask classes or instances if they provide
 particular functionality, for example::

Modified: python/branches/tlee-ast-optimize/Doc/library/gc.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/gc.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/gc.rst	Sat Jul 12 06:22:35 2008
@@ -47,6 +47,12 @@
    .. versionchanged:: 2.5
       The optional *generation* argument was added.
 
+   .. versionchanged:: 2.6
+      The free lists maintained for a number of builtin types are cleared
+      whenever a full collection or collection of the highest generation (2)
+      is run.  Not all items in some free lists may be freed due to the
+      particular implementation, in particular :class:`int` and :class:`float`.
+
 
 .. function:: set_debug(flags)
 

Modified: python/branches/tlee-ast-optimize/Doc/library/robotparser.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/robotparser.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/robotparser.rst	Sat Jul 12 06:22:35 2008
@@ -13,6 +13,12 @@
    single: World Wide Web
    single: URL
    single: robots.txt
+   
+.. note::
+   The :mod:`robotparser` module has been renamed :mod:`urllib.robotparser` in
+   Python 3.0.
+   The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
 
 This module provides a single class, :class:`RobotFileParser`, which answers
 questions about whether or not a particular user agent can fetch a URL on the

Modified: python/branches/tlee-ast-optimize/Doc/library/shutil.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/shutil.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/shutil.rst	Sat Jul 12 06:22:35 2008
@@ -82,7 +82,7 @@
 
    This factory function creates a function that can be used as a callable for
    :func:`copytree`\'s *ignore* argument, ignoring files and directories that
-   match one the glob-style *patterns* provided.  See the example below.
+   match one of the glob-style *patterns* provided.  See the example below.
 
    .. versionadded:: 2.6
 

Modified: python/branches/tlee-ast-optimize/Doc/library/sys.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/sys.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/sys.rst	Sat Jul 12 06:22:35 2008
@@ -58,22 +58,6 @@
    A string containing the copyright pertaining to the Python interpreter.
 
 
-.. function:: _compact_freelists()
-
-   Compact the free lists of integers and floats by deallocating unused blocks.
-   It can reduce the memory usage of the Python process several tenth of
-   thousands of integers or floats have been allocated at once.
-
-   The return value is a tuple of tuples each containing three elements,
-   amount of used objects, total block count before the blocks are deallocated
-   and amount of freed blocks. The first tuple refers to ints, the second to
-   floats.
-
-   This function should be used for specialized purposes only.
-
-   .. versionadded:: 2.6
-
-
 .. function:: _clear_type_cache()
 
    Clear the internal type cache. The type cache is used to speed up attribute
@@ -409,13 +393,20 @@
    :func:`setrecursionlimit`.
 
 
-.. function:: getsizeof(object)
+.. function:: getsizeof(object[, default])
 
    Return the size of an object in bytes. The object can be any type of
    object. All built-in objects will return correct results, but this
-   does not have to hold true for third-party extensions as it is implementation 
+   does not have to hold true for third-party extensions as it is implementation
    specific.
 
+   The *default* argument allows to define a value which will be returned
+   if the object type does not provide means to retrieve the size and would
+   cause a `TypeError`. 
+
+   func:`getsizeof` calls the object's __sizeof__ method and adds an additional
+   garbage collector overhead if the object is managed by the garbage collector.
+
    .. versionadded:: 2.6
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/urllib2.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/urllib2.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/urllib2.rst	Sat Jul 12 06:22:35 2008
@@ -7,6 +7,13 @@
 .. sectionauthor:: Moshe Zadka <moshez at users.sourceforge.net>
 
 
+.. note::
+   The :mod:`urllib2` module has been split across several modules in
+   Python 3.0 named :mod:`urllib.request` and :mod:`urllib.error`.
+   The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
+
+
 The :mod:`urllib2` module defines functions and classes which help in opening
 URLs (mostly HTTP) in a complex world --- basic and digest authentication,
 redirections, cookies and more.

Modified: python/branches/tlee-ast-optimize/Doc/library/urlparse.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/urlparse.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/urlparse.rst	Sat Jul 12 06:22:35 2008
@@ -12,6 +12,12 @@
    pair: URL; parsing
    pair: relative; URL
 
+.. note::
+   The :mod:`urlparse` module is renamed to :mod:`urllib.parse` in Python 3.0.
+   The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
+
+
 This module defines a standard interface to break Uniform Resource Locator (URL)
 strings up in components (addressing scheme, network location, path etc.), to
 combine the components back into a URL string, and to convert a "relative URL"

Modified: python/branches/tlee-ast-optimize/Doc/tools/sphinxext/opensearch.xml
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tools/sphinxext/opensearch.xml	(original)
+++ python/branches/tlee-ast-optimize/Doc/tools/sphinxext/opensearch.xml	Sat Jul 12 06:22:35 2008
@@ -1,14 +1,4 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
-  <ShortName>Python Docs</ShortName>
-  <LongName>Python Documentation</LongName>
-  <Description>Search the Python documentation</Description>
-  <InputEncoding>utf-8</InputEncoding>
-  <Url type="text/html" method="get" template="{{ pathto('search') }}?">
-    <Param name="q" value="{searchTerms}" />
-    <Param name="check_keywords" value="yes" />
-    <Param name="area" value="default" />
-  </Url>
-  <Image height="16" width="16" type="image/x-icon">http://www.python.org/images/favicon16x16.ico</Image>
-</OpenSearchDescription>
-
+{% extends "!opensearch.xml" %}
+{% block extra -%}
+<Image height="16" width="16" type="image/x-icon">http://www.python.org/images/favicon16x16.ico</Image>
+{%- endblock %}

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.6.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.6.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.6.rst	Sat Jul 12 06:22:35 2008
@@ -1681,6 +1681,11 @@
   available, instead of restricting itself to protocol 1.
   (Contributed by W. Barnes; :issue:`1551443`.)
 
+* The :mod:`cgi` module will now read variables from the query string of an 
+  HTTP POST request.  This makes it possible to use form actions with 
+  URLs such as "/cgi-bin/add.py?category=1".  (Contributed by 
+  Alexandre Fiori and Nubis; :issue:`1817`.)
+
 * The :mod:`cmath` module underwent an extensive set of revisions,
   thanks to Mark Dickinson and Christian Heimes, that added some new
   features and greatly improved the accuracy of the computations.
@@ -2137,6 +2142,24 @@
 * The :mod:`sets` module has been deprecated; it's better to
   use the built-in :class:`set` and :class:`frozenset` types.
 
+* The :func:`shutil.copytree` function now has an optional **ignore** argument
+  that takes a callable object.  This callable will receive each directory path
+  and a list of the directory's contents, and returns a list of names that
+  will be ignored, not copied.  
+
+  The :mod:`shutil` module also provides an :func:`ignore_patterns`
+  function for use with this new parameter.
+  :func:`ignore_patterns` takes an arbitrary number of glob-style patterns
+  and will ignore any files and directories that match this pattern.
+  The following example copies a directory tree, but skip both SVN's internal
+  :file:`.svn` directories and Emacs backup 
+  files, which have names ending with '~'::
+
+      shutil.copytree('Doc/library', '/tmp/library', 
+                      ignore=shutil.ignore_patterns('*~', '.svn'))
+
+  (Contributed by Tarek Ziadé; :issue:`2663`.)
+
 * Integrating signal handling with GUI handling event loops
   like those used by Tkinter or GTk+ has long been a problem; most
   software ends up polling, waking up every fraction of a second.
@@ -2500,9 +2523,10 @@
       ...
     ValueError: malformed string
 
-The module also includes 
-:class:`NodeVisitor` and :class:`NodeTransformer` classes 
-for traversing and modifying an AST, and functions for common transformations such as changing line numbers.
+The module also includes :class:`NodeVisitor` and
+:class:`NodeTransformer` classes for traversing and modifying an AST,
+and functions for common transformations such as changing line
+numbers.
 
 .. ======================================================================
 

Modified: python/branches/tlee-ast-optimize/Include/floatobject.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/floatobject.h	(original)
+++ python/branches/tlee-ast-optimize/Include/floatobject.h	Sat Jul 12 06:22:35 2008
@@ -113,7 +113,7 @@
 PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le);
 
 /* free list api */
-PyAPI_FUNC(void) PyFloat_CompactFreeList(size_t *, size_t *, size_t *);
+PyAPI_FUNC(int) PyFloat_ClearFreeList(void);
 
 /* Format the object based on the format_spec, as defined in PEP 3101
    (Advanced String Formatting). */

Modified: python/branches/tlee-ast-optimize/Include/intobject.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/intobject.h	(original)
+++ python/branches/tlee-ast-optimize/Include/intobject.h	Sat Jul 12 06:22:35 2008
@@ -60,7 +60,7 @@
 PyAPI_FUNC(long) PyOS_strtol(char *, char **, int);
 
 /* free list api */
-PyAPI_FUNC(void) PyInt_CompactFreeList(size_t *, size_t *, size_t *);
+PyAPI_FUNC(int) PyInt_ClearFreeList(void);
 
 /* Convert an integer to the given base.  Returns a string.
    If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'.

Modified: python/branches/tlee-ast-optimize/Include/traceback.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/traceback.h	(original)
+++ python/branches/tlee-ast-optimize/Include/traceback.h	Sat Jul 12 06:22:35 2008
@@ -19,7 +19,7 @@
 
 PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *);
 PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *);
-PyAPI_FUNC(int) Py_DisplaySourceLine(PyObject *, const char *, int);
+PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, const char *, int, int);
 
 /* Reveal traceback type so we can typecheck traceback objects */
 PyAPI_DATA(PyTypeObject) PyTraceBack_Type;

Modified: python/branches/tlee-ast-optimize/Lib/SimpleHTTPServer.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/SimpleHTTPServer.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/SimpleHTTPServer.py	Sat Jul 12 06:22:35 2008
@@ -79,12 +79,11 @@
             else:
                 return self.list_directory(path)
         ctype = self.guess_type(path)
-        if ctype.startswith('text/'):
-            mode = 'r'
-        else:
-            mode = 'rb'
         try:
-            f = open(path, mode)
+            # Always read in binary mode. Opening files in text mode may cause
+            # newline translations, making the actual size of the content
+            # transmitted *less* than the content-length!
+            f = open(path, 'rb')
         except IOError:
             self.send_error(404, "File not found")
             return None

Modified: python/branches/tlee-ast-optimize/Lib/asynchat.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/asynchat.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/asynchat.py	Sat Jul 12 06:22:35 2008
@@ -59,7 +59,7 @@
     ac_in_buffer_size       = 4096
     ac_out_buffer_size      = 4096
 
-    def __init__ (self, conn=None):
+    def __init__ (self, sock=None, map=None):
         # for string terminator matching
         self.ac_in_buffer = ''
 
@@ -74,7 +74,7 @@
         # we toss the use of the "simple producer" and replace it with
         # a pure deque, which the original fifo was a wrapping of
         self.producer_fifo = deque()
-        asyncore.dispatcher.__init__ (self, conn)
+        asyncore.dispatcher.__init__ (self, sock, map)
 
     def collect_incoming_data(self, data):
         raise NotImplementedError("must be implemented in subclass")

Modified: python/branches/tlee-ast-optimize/Lib/asyncore.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/asyncore.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/asyncore.py	Sat Jul 12 06:22:35 2008
@@ -99,8 +99,10 @@
             obj.handle_read_event()
         if flags & select.POLLOUT:
             obj.handle_write_event()
-        if flags & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
+        if flags & (select.POLLERR | select.POLLNVAL):
             obj.handle_expt_event()
+        if flags & select.POLLHUP:
+            obj.handle_close()
     except (ExitNow, KeyboardInterrupt, SystemExit):
         raise
     except:
@@ -467,7 +469,7 @@
                 ),
             'error'
             )
-        self.close()
+        self.handle_close()
 
     def handle_expt(self):
         self.log_info('unhandled exception', 'warning')

Modified: python/branches/tlee-ast-optimize/Lib/bisect.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/bisect.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/bisect.py	Sat Jul 12 06:22:35 2008
@@ -9,6 +9,8 @@
     slice of a to be searched.
     """
 
+    if lo < 0:
+        raise ValueError('lo must be non-negative')
     if hi is None:
         hi = len(a)
     while lo < hi:
@@ -30,6 +32,8 @@
     slice of a to be searched.
     """
 
+    if lo < 0:
+        raise ValueError('lo must be non-negative')
     if hi is None:
         hi = len(a)
     while lo < hi:
@@ -49,6 +53,8 @@
     slice of a to be searched.
     """
 
+    if lo < 0:
+        raise ValueError('lo must be non-negative')
     if hi is None:
         hi = len(a)
     while lo < hi:
@@ -69,6 +75,8 @@
     slice of a to be searched.
     """
 
+    if lo < 0:
+        raise ValueError('lo must be non-negative')
     if hi is None:
         hi = len(a)
     while lo < hi:

Modified: python/branches/tlee-ast-optimize/Lib/curses/textpad.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/curses/textpad.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/curses/textpad.py	Sat Jul 12 06:22:35 2008
@@ -1,6 +1,7 @@
 """Simple textbox editing widget with Emacs-like keybindings."""
 
-import curses, ascii
+import curses
+import curses.ascii
 
 def rectangle(win, uly, ulx, lry, lrx):
     """Draw a rectangle with corners at the provided upper-left
@@ -54,7 +55,7 @@
         returning the index of the last non-blank character."""
         last = self.maxx
         while True:
-            if ascii.ascii(self.win.inch(y, last)) != ascii.SP:
+            if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
                 last = min(self.maxx, last+1)
                 break
             elif last == 0:
@@ -76,7 +77,7 @@
                 pass
             if self.insert_mode:
                 (backy, backx) = self.win.getyx()
-                if ascii.isprint(oldch):
+                if curses.ascii.isprint(oldch):
                     self._insert_printable_char(oldch)
                     self.win.move(backy, backx)
 
@@ -84,12 +85,12 @@
         "Process a single editing command."
         (y, x) = self.win.getyx()
         self.lastcmd = ch
-        if ascii.isprint(ch):
+        if curses.ascii.isprint(ch):
             if y < self.maxy or x < self.maxx:
                 self._insert_printable_char(ch)
-        elif ch == ascii.SOH:                           # ^a
+        elif ch == curses.ascii.SOH:                           # ^a
             self.win.move(y, 0)
-        elif ch in (ascii.STX,curses.KEY_LEFT, ascii.BS,curses.KEY_BACKSPACE):
+        elif ch in (curses.ascii.STX,curses.KEY_LEFT, curses.ascii.BS,curses.KEY_BACKSPACE):
             if x > 0:
                 self.win.move(y, x-1)
             elif y == 0:
@@ -98,46 +99,46 @@
                 self.win.move(y-1, self._end_of_line(y-1))
             else:
                 self.win.move(y-1, self.maxx)
-            if ch in (ascii.BS, curses.KEY_BACKSPACE):
+            if ch in (curses.ascii.BS, curses.KEY_BACKSPACE):
                 self.win.delch()
-        elif ch == ascii.EOT:                           # ^d
+        elif ch == curses.ascii.EOT:                           # ^d
             self.win.delch()
-        elif ch == ascii.ENQ:                           # ^e
+        elif ch == curses.ascii.ENQ:                           # ^e
             if self.stripspaces:
                 self.win.move(y, self._end_of_line(y))
             else:
                 self.win.move(y, self.maxx)
-        elif ch in (ascii.ACK, curses.KEY_RIGHT):       # ^f
+        elif ch in (curses.ascii.ACK, curses.KEY_RIGHT):       # ^f
             if x < self.maxx:
                 self.win.move(y, x+1)
             elif y == self.maxy:
                 pass
             else:
                 self.win.move(y+1, 0)
-        elif ch == ascii.BEL:                           # ^g
+        elif ch == curses.ascii.BEL:                           # ^g
             return 0
-        elif ch == ascii.NL:                            # ^j
+        elif ch == curses.ascii.NL:                            # ^j
             if self.maxy == 0:
                 return 0
             elif y < self.maxy:
                 self.win.move(y+1, 0)
-        elif ch == ascii.VT:                            # ^k
+        elif ch == curses.ascii.VT:                            # ^k
             if x == 0 and self._end_of_line(y) == 0:
                 self.win.deleteln()
             else:
                 # first undo the effect of self._end_of_line
                 self.win.move(y, x)
                 self.win.clrtoeol()
-        elif ch == ascii.FF:                            # ^l
+        elif ch == curses.ascii.FF:                            # ^l
             self.win.refresh()
-        elif ch in (ascii.SO, curses.KEY_DOWN):         # ^n
+        elif ch in (curses.ascii.SO, curses.KEY_DOWN):         # ^n
             if y < self.maxy:
                 self.win.move(y+1, x)
                 if x > self._end_of_line(y+1):
                     self.win.move(y+1, self._end_of_line(y+1))
-        elif ch == ascii.SI:                            # ^o
+        elif ch == curses.ascii.SI:                            # ^o
             self.win.insertln()
-        elif ch in (ascii.DLE, curses.KEY_UP):          # ^p
+        elif ch in (curses.ascii.DLE, curses.KEY_UP):          # ^p
             if y > 0:
                 self.win.move(y-1, x)
                 if x > self._end_of_line(y-1):
@@ -155,7 +156,7 @@
             for x in range(self.maxx+1):
                 if self.stripspaces and x > stop:
                     break
-                result = result + chr(ascii.ascii(self.win.inch(y, x)))
+                result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
             if self.maxy > 0:
                 result = result + "\n"
         return result

Modified: python/branches/tlee-ast-optimize/Lib/fractions.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/fractions.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/fractions.py	Sat Jul 12 06:22:35 2008
@@ -96,9 +96,8 @@
 
         if denominator == 0:
             raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
-
-        numerator = numerator.__index__()
-        denominator = denominator.__index__()
+        numerator = operator.index(numerator)
+        denominator = operator.index(denominator)
         g = gcd(numerator, denominator)
         self._numerator = numerator // g
         self._denominator = denominator // g
@@ -111,7 +110,9 @@
         Beware that Fraction.from_float(0.3) != Fraction(3, 10).
 
         """
-        if not isinstance(f, float):
+        if isinstance(f, numbers.Integral):
+            f = float(f)
+        elif not isinstance(f, float):
             raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                             (cls.__name__, f, type(f).__name__))
         if math.isnan(f) or math.isinf(f):
@@ -122,7 +123,9 @@
     def from_decimal(cls, dec):
         """Converts a finite Decimal instance to a rational number, exactly."""
         from decimal import Decimal
-        if not isinstance(dec, Decimal):
+        if isinstance(dec, numbers.Integral):
+            dec = Decimal(int(dec))
+        elif not isinstance(dec, Decimal):
             raise TypeError(
                 "%s.from_decimal() only takes Decimals, not %r (%s)" %
                 (cls.__name__, dec, type(dec).__name__))

Modified: python/branches/tlee-ast-optimize/Lib/httplib.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/httplib.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/httplib.py	Sat Jul 12 06:22:35 2008
@@ -813,7 +813,7 @@
                         host_enc = self.host.encode("ascii")
                     except UnicodeEncodeError:
                         host_enc = self.host.encode("idna")
-                    if self.port == HTTP_PORT:
+                    if self.port == self.default_port:
                         self.putheader('Host', host_enc)
                     else:
                         self.putheader('Host', "%s:%s" % (host_enc, self.port))

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports.py	Sat Jul 12 06:22:35 2008
@@ -19,6 +19,11 @@
 # XXX: overhead to the fixer.
 MAPPING = {"StringIO":  ("io", ["StringIO"]),
            "cStringIO": ("io", ["StringIO"]),
+           "cPickle": ("pickle", ['BadPickleGet', 'HIGHEST_PROTOCOL',
+                                  'PickleError', 'Pickler', 'PicklingError',
+                                  'UnpickleableError', 'Unpickler', 'UnpicklingError',
+                                  'compatible_formats', 'dump', 'dumps', 'format_version',
+                                  'load', 'loads']),
            "__builtin__" : ("builtins", builtin_names),
            'copy_reg': ('copyreg', ['pickle',
                                     'constructor',

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_fixers.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_fixers.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_fixers.py	Sat Jul 12 06:22:35 2008
@@ -1405,10 +1405,7 @@
         s = "foo(xreadlines)"
         self.unchanged(s)
 
-# Disable test, as it takes a too long time to run, and also
-# fails in 2.6.
-#class Test_imports(FixerTestCase):
-class Test_imports:
+class Test_imports(FixerTestCase):
     fixer = "imports"
     from ..fixes.fix_imports import MAPPING as modules
 

Modified: python/branches/tlee-ast-optimize/Lib/optparse.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/optparse.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/optparse.py	Sat Jul 12 06:22:35 2008
@@ -602,7 +602,7 @@
 
     def _set_attrs(self, attrs):
         for attr in self.ATTRS:
-            if attrs.has_key(attr):
+            if attr in attrs:
                 setattr(self, attr, attrs[attr])
                 del attrs[attr]
             else:
@@ -701,7 +701,7 @@
 
     def _check_callback(self):
         if self.action == "callback":
-            if not callable(self.callback):
+            if not hasattr(self.callback, '__call__'):
                 raise OptionError(
                     "callback not callable: %r" % self.callback, self)
             if (self.callback_args is not None and
@@ -817,12 +817,6 @@
 SUPPRESS_HELP = "SUPPRESS"+"HELP"
 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
 
-# For compatibility with Python 2.2
-try:
-    True, False
-except NameError:
-    (True, False) = (1, 0)
-
 try:
     basestring
 except NameError:
@@ -860,7 +854,7 @@
         are silently ignored.
         """
         for attr in dir(self):
-            if dict.has_key(attr):
+            if attr in dict:
                 dval = dict[attr]
                 if dval is not None:
                     setattr(self, attr, dval)
@@ -980,10 +974,10 @@
     def _check_conflict(self, option):
         conflict_opts = []
         for opt in option._short_opts:
-            if self._short_opt.has_key(opt):
+            if opt in self._short_opt:
                 conflict_opts.append((opt, self._short_opt[opt]))
         for opt in option._long_opts:
-            if self._long_opt.has_key(opt):
+            if opt in self._long_opt:
                 conflict_opts.append((opt, self._long_opt[opt]))
 
         if conflict_opts:
@@ -1029,7 +1023,7 @@
         if option.dest is not None:     # option has a dest, we need a default
             if option.default is not NO_DEFAULT:
                 self.defaults[option.dest] = option.default
-            elif not self.defaults.has_key(option.dest):
+            elif option.dest not in self.defaults:
                 self.defaults[option.dest] = None
 
         return option
@@ -1045,8 +1039,8 @@
                 self._long_opt.get(opt_str))
 
     def has_option(self, opt_str):
-        return (self._short_opt.has_key(opt_str) or
-                self._long_opt.has_key(opt_str))
+        return (opt_str in self._short_opt or
+                opt_str in self._long_opt)
 
     def remove_option(self, opt_str):
         option = self._short_opt.get(opt_str)
@@ -1664,7 +1658,7 @@
     'words', raise BadOptionError.
     """
     # Is there an exact match?
-    if wordmap.has_key(s):
+    if s in wordmap:
         return s
     else:
         # Isolate all words with s as a prefix.

Modified: python/branches/tlee-ast-optimize/Lib/subprocess.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/subprocess.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/subprocess.py	Sat Jul 12 06:22:35 2008
@@ -1158,7 +1158,12 @@
 
             input_offset = 0
             while read_set or write_set:
-                rlist, wlist, xlist = select.select(read_set, write_set, [])
+                try:
+                    rlist, wlist, xlist = select.select(read_set, write_set, [])
+                except select.error, e:
+                    if e.args[0] == errno.EINTR:
+                        continue
+                    raise
 
                 if self.stdin in wlist:
                     # When select has indicated that the file is writable,

Modified: python/branches/tlee-ast-optimize/Lib/test/regrtest.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/regrtest.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/regrtest.py	Sat Jul 12 06:22:35 2008
@@ -91,6 +91,8 @@
     curses -    Tests that use curses and will modify the terminal's
                 state and output modes.
 
+    lib2to3 -   Run the tests for 2to3 (They take a while.)
+
     largefile - It is okay to run some test that may create huge
                 files.  These tests can take a long time and may
                 consume >2GB of disk space temporarily.
@@ -165,8 +167,8 @@
 
 from test import test_support
 
-RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
-                  'decimal', 'compiler', 'subprocess', 'urlfetch')
+RESOURCE_NAMES = ('audio', 'curses', 'lib2to3', 'largefile', 'network',
+                  'bsddb', 'decimal', 'compiler', 'subprocess', 'urlfetch')
 
 
 def usage(code, msg=''):

Modified: python/branches/tlee-ast-optimize/Lib/test/test_asyncore.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_asyncore.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_asyncore.py	Sat Jul 12 06:22:35 2008
@@ -38,6 +38,7 @@
         raise asyncore.ExitNow()
 
     handle_write_event = handle_read_event
+    handle_close = handle_read_event
     handle_expt_event = handle_read_event
 
 class crashingdummy:
@@ -48,6 +49,7 @@
         raise Exception()
 
     handle_write_event = handle_read_event
+    handle_close = handle_read_event
     handle_expt_event = handle_read_event
 
     def handle_error(self):
@@ -117,6 +119,7 @@
                 def __init__(self):
                     self.read = False
                     self.write = False
+                    self.closed = False
                     self.expt = False
 
                 def handle_read_event(self):
@@ -125,6 +128,9 @@
                 def handle_write_event(self):
                     self.write = True
 
+                def handle_close(self):
+                    self.closed = True
+
                 def handle_expt_event(self):
                     self.expt = True
 
@@ -167,9 +173,9 @@
 
             for flag in (select.POLLERR, select.POLLHUP, select.POLLNVAL):
                 tobj = testobj()
-                self.assertEqual(tobj.expt, False)
+                self.assertEqual((tobj.expt, tobj.closed)[flag == select.POLLHUP], False)
                 asyncore.readwrite(tobj, flag)
-                self.assertEqual(tobj.expt, True)
+                self.assertEqual((tobj.expt, tobj.closed)[flag == select.POLLHUP], True)
 
                 # check that ExitNow exceptions in the object handler method
                 # bubbles all the way up through asyncore readwrite calls

Modified: python/branches/tlee-ast-optimize/Lib/test/test_audioop.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_audioop.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_audioop.py	Sat Jul 12 06:22:35 2008
@@ -161,6 +161,10 @@
             self.assertEqual(audioop.getsample(data[1], 2, i), i)
             self.assertEqual(audioop.getsample(data[2], 4, i), i)
 
+    def test_negavitelen(self):
+        # from issue 3306, previously it segfaulted
+        self.assertRaises(audioop.error,
+            audioop.findmax, ''.join( chr(x) for x in xrange(256)), -2392392)
 
 def test_main():
     run_unittest(TestAudioop)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_bisect.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_bisect.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_bisect.py	Sat Jul 12 06:22:35 2008
@@ -114,6 +114,14 @@
             self.assertEqual(func(data, elem), expected)
             self.assertEqual(func(UserList(data), elem), expected)
 
+    def test_negative_lo(self):
+        # Issue 3301
+        mod = self.module
+        self.assertRaises(ValueError, mod.bisect_left, [1, 2, 3], 5, -1, 3),
+        self.assertRaises(ValueError, mod.bisect_right, [1, 2, 3], 5, -1, 3),
+        self.assertRaises(ValueError, mod.insort_left, [1, 2, 3], 5, -1, 3),
+        self.assertRaises(ValueError, mod.insort_right, [1, 2, 3], 5, -1, 3),
+
     def test_random(self, n=25):
         from random import randrange
         for i in xrange(n):

Modified: python/branches/tlee-ast-optimize/Lib/test/test_bz2.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_bz2.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_bz2.py	Sat Jul 12 06:22:35 2008
@@ -112,6 +112,17 @@
         self.assertEqual(list(iter(bz2f)), sio.readlines())
         bz2f.close()
 
+    def testClosedIteratorDeadlock(self):
+        # "Test that iteration on a closed bz2file releases the lock."
+        # http://bugs.python.org/issue3309
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        bz2f.close()
+        self.assertRaises(ValueError, bz2f.next)
+        # This call will deadlock of the above .next call failed to
+        # release the lock.
+        self.assertRaises(ValueError, bz2f.readlines)
+
     def testXReadLines(self):
         # "Test BZ2File.xreadlines()"
         self.createTempFile()

Modified: python/branches/tlee-ast-optimize/Lib/test/test_exceptions.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_exceptions.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_exceptions.py	Sat Jul 12 06:22:35 2008
@@ -342,6 +342,7 @@
         self.failUnless(unicode(Exception))
         self.failUnless(str(Exception('a')))
         self.failUnless(unicode(Exception(u'a')))
+        self.failUnless(unicode(Exception(u'\xe1')))
 
 
 def test_main():

Modified: python/branches/tlee-ast-optimize/Lib/test/test_float.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_float.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_float.py	Sat Jul 12 06:22:35 2008
@@ -253,24 +253,36 @@
         floats_file.close()
 
 # Beginning with Python 2.6 float has cross platform compatible
-# ways to create and representate inf and nan
+# ways to create and represent inf and nan
 class InfNanTest(unittest.TestCase):
     def test_inf_from_str(self):
         self.assert_(isinf(float("inf")))
         self.assert_(isinf(float("+inf")))
         self.assert_(isinf(float("-inf")))
+        self.assert_(isinf(float("infinity")))
+        self.assert_(isinf(float("+infinity")))
+        self.assert_(isinf(float("-infinity")))
 
         self.assertEqual(repr(float("inf")), "inf")
         self.assertEqual(repr(float("+inf")), "inf")
         self.assertEqual(repr(float("-inf")), "-inf")
+        self.assertEqual(repr(float("infinity")), "inf")
+        self.assertEqual(repr(float("+infinity")), "inf")
+        self.assertEqual(repr(float("-infinity")), "-inf")
 
         self.assertEqual(repr(float("INF")), "inf")
         self.assertEqual(repr(float("+Inf")), "inf")
         self.assertEqual(repr(float("-iNF")), "-inf")
+        self.assertEqual(repr(float("Infinity")), "inf")
+        self.assertEqual(repr(float("+iNfInItY")), "inf")
+        self.assertEqual(repr(float("-INFINITY")), "-inf")
 
         self.assertEqual(str(float("inf")), "inf")
         self.assertEqual(str(float("+inf")), "inf")
         self.assertEqual(str(float("-inf")), "-inf")
+        self.assertEqual(str(float("infinity")), "inf")
+        self.assertEqual(str(float("+infinity")), "inf")
+        self.assertEqual(str(float("-infinity")), "-inf")
 
         self.assertRaises(ValueError, float, "info")
         self.assertRaises(ValueError, float, "+info")
@@ -278,6 +290,10 @@
         self.assertRaises(ValueError, float, "in")
         self.assertRaises(ValueError, float, "+in")
         self.assertRaises(ValueError, float, "-in")
+        self.assertRaises(ValueError, float, "infinit")
+        self.assertRaises(ValueError, float, "+Infin")
+        self.assertRaises(ValueError, float, "-INFI")
+        self.assertRaises(ValueError, float, "infinitys")
 
     def test_inf_as_str(self):
         self.assertEqual(repr(1e300 * 1e300), "inf")

Modified: python/branches/tlee-ast-optimize/Lib/test/test_fractions.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_fractions.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_fractions.py	Sat Jul 12 06:22:35 2008
@@ -62,11 +62,11 @@
 
         self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
                                  F, 12, 0)
-        self.assertRaises(AttributeError, F, 1.5)
-        self.assertRaises(AttributeError, F, 1.5 + 3j)
+        self.assertRaises(TypeError, F, 1.5)
+        self.assertRaises(TypeError, F, 1.5 + 3j)
 
-        self.assertRaises(AttributeError, F, F(1, 2), 3)
-        self.assertRaises(AttributeError, F, "3/2", 3)
+        self.assertRaises(TypeError, F, F(1, 2), 3)
+        self.assertRaises(TypeError, F, "3/2", 3)
 
     def testFromString(self):
         self.assertEquals((5, 1), _components(F("5")))
@@ -137,10 +137,8 @@
         self.assertNotEquals(F(4, 2), r)
 
     def testFromFloat(self):
-        self.assertRaisesMessage(
-            TypeError, "Fraction.from_float() only takes floats, not 3 (int)",
-            F.from_float, 3)
-
+        self.assertRaises(TypeError, F.from_float, 3+4j)
+        self.assertEquals((10, 1), _components(F.from_float(10)))
         self.assertEquals((0, 1), _components(F.from_float(-0.0)))
         self.assertEquals((10, 1), _components(F.from_float(10.0)))
         self.assertEquals((-5, 2), _components(F.from_float(-2.5)))
@@ -164,10 +162,8 @@
             F.from_float, nan)
 
     def testFromDecimal(self):
-        self.assertRaisesMessage(
-            TypeError,
-            "Fraction.from_decimal() only takes Decimals, not 3 (int)",
-            F.from_decimal, 3)
+        self.assertRaises(TypeError, F.from_decimal, 3+4j)
+        self.assertEquals(F(10, 1), F.from_decimal(10))
         self.assertEquals(F(0), F.from_decimal(Decimal("-0")))
         self.assertEquals(F(5, 10), F.from_decimal(Decimal("0.5")))
         self.assertEquals(F(5, 1000), F.from_decimal(Decimal("5e-3")))

Modified: python/branches/tlee-ast-optimize/Lib/test/test_lib2to3.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_lib2to3.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_lib2to3.py	Sat Jul 12 06:22:35 2008
@@ -2,7 +2,11 @@
 # because of running
 from lib2to3.tests import test_fixers, test_pytree, test_util
 import unittest
-from test.test_support import run_unittest
+from test.test_support import run_unittest, requires
+
+# Don't run lib2to3 tests by default since they take too long
+if __name__ != '__main__':
+    requires('lib2to3')
 
 def suite():
     tests = unittest.TestSuite()

Modified: python/branches/tlee-ast-optimize/Lib/test/test_sys.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_sys.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_sys.py	Sat Jul 12 06:22:35 2008
@@ -367,25 +367,6 @@
     def test_clear_type_cache(self):
         sys._clear_type_cache()
 
-    def test_compact_freelists(self):
-        sys._compact_freelists()
-        r = sys._compact_freelists()
-##        # freed blocks shouldn't change
-##        self.assertEqual(r[0][2], 0)
-##        self.assertEqual(r[1][2], 0)
-##        # fill freelists
-##        ints = list(range(10000))
-##        floats = [float(i) for i in ints]
-##        del ints
-##        del floats
-##        # should free more than 200 blocks each
-##        r = sys._compact_freelists()
-##        self.assert_(r[0][1] > 100, r[0][1])
-##        self.assert_(r[1][2] > 100, r[1][1])
-##
-##        self.assert_(r[0][2] > 100, r[0][2])
-##        self.assert_(r[1][2] > 100, r[1][2])
-
     def test_ioencoding(self):
         import subprocess,os
         env = dict(os.environ)
@@ -408,6 +389,9 @@
 
 class SizeofTest(unittest.TestCase):
 
+    TPFLAGS_HAVE_GC = 1<<14
+    TPFLAGS_HEAPTYPE = 1L<<9
+
     def setUp(self):
         self.c = len(struct.pack('c', ' '))
         self.H = len(struct.pack('H', 0))
@@ -417,22 +401,26 @@
         # due to missing size_t information from struct, it is assumed that
         # sizeof(Py_ssize_t) = sizeof(void*)
         self.header = 'PP'
+        self.vheader = self.header + 'P'
         if hasattr(sys, "gettotalrefcount"):
             self.header += '2P'
+            self.vheader += '2P'
+        import _testcapi
+        self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD
         self.file = open(test.test_support.TESTFN, 'wb')
 
     def tearDown(self):
         self.file.close()
         test.test_support.unlink(test.test_support.TESTFN)
 
-    def check_sizeof(self, o, size, size2=None):
-        """Check size of o. Possible are size and optionally size2)."""
+    def check_sizeof(self, o, size):
         result = sys.getsizeof(o)
-        msg = 'wrong size for %s: got %d, expected ' % (type(o), result)
-        if (size2 != None) and (result != size):
-            self.assertEqual(result, size2, msg + str(size2))
-        else:
-            self.assertEqual(result, size, msg + str(size))
+        if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
+           ((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
+            size += self.gc_headsize
+        msg = 'wrong size for %s: got %d, expected %d' \
+                % (type(o), result, size)
+        self.assertEqual(result, size, msg)
 
     def calcsize(self, fmt):
         """Wrapper around struct.calcsize which enforces the alignment of the
@@ -443,44 +431,123 @@
         """
         return struct.calcsize(fmt + '0P')
 
-    def test_standardtypes(self):
+    def test_gc_head_size(self):
+        # Check that the gc header size is added to objects tracked by the gc.
+        h = self.header
+        size = self.calcsize
+        gc_header_size = self.gc_headsize
+        # bool objects are not gc tracked
+        self.assertEqual(sys.getsizeof(True), size(h + 'l'))
+        # but lists are
+        self.assertEqual(sys.getsizeof([]), size(h + 'P PP') + gc_header_size)
+
+    def test_default(self):
         h = self.header
         size = self.calcsize
+        self.assertEqual(sys.getsizeof(True, -1), size(h + 'l'))
+
+    def test_objecttypes(self):
+        # check all types defined in Objects/
+        h = self.header
+        vh = self.vheader
+        size = self.calcsize
+        check = self.check_sizeof
         # bool
-        self.check_sizeof(True, size(h + 'l'))
+        check(True, size(h + 'l'))
         # buffer
-        self.check_sizeof(buffer(''), size(h + '2P2Pil'))
+        check(buffer(''), size(h + '2P2Pil'))
+        # builtin_function_or_method
+        check(len, size(h + '3P'))
+        # bytearray
+        samples = ['', 'u'*100000]
+        for sample in samples:
+            x = bytearray(sample)
+            check(x, size(vh + 'iPP') + x.__alloc__() * self.c)
+        # bytearray_iterator
+        check(iter(bytearray()), size(h + 'PP'))
         # cell
         def get_cell():
             x = 42
             def inner():
                 return x
             return inner
-        self.check_sizeof(get_cell().func_closure[0], size(h + 'P'))
-        # old-style class
+        check(get_cell().func_closure[0], size(h + 'P'))
+        # classobj (old-style class)
         class class_oldstyle():
             def method():
                 pass
-        self.check_sizeof(class_oldstyle, size(h + '6P'))
-        # instance
-        self.check_sizeof(class_oldstyle(), size(h + '3P'))
-        # method
-        self.check_sizeof(class_oldstyle().method, size(h + '4P'))
-        # code
-        self.check_sizeof(get_cell().func_code, size(h + '4i8Pi2P'))
+        check(class_oldstyle, size(h + '6P'))
+        # instance (old-style class)
+        check(class_oldstyle(), size(h + '3P'))
+        # instancemethod (old-style class)
+        check(class_oldstyle().method, size(h + '4P'))
         # complex
-        self.check_sizeof(complex(0,1), size(h + '2d'))
+        check(complex(0,1), size(h + '2d'))
+        # code
+        check(get_cell().func_code, size(h + '4i8Pi2P'))
+        # BaseException
+        check(BaseException(), size(h + '3P'))
+        # UnicodeEncodeError
+        check(UnicodeEncodeError("", u"", 0, 0, ""), size(h + '5P2PP'))
+        # UnicodeDecodeError
+        check(UnicodeDecodeError("", "", 0, 0, ""), size(h + '5P2PP'))
+        # UnicodeTranslateError
+        check(UnicodeTranslateError(u"", 0, 1, ""), size(h + '5P2PP'))
+        # method_descriptor (descriptor object)
+        check(str.lower, size(h + '2PP'))
+        # classmethod_descriptor (descriptor object)
+        # XXX
+        # member_descriptor (descriptor object)
+        import datetime
+        check(datetime.timedelta.days, size(h + '2PP'))
+        # getset_descriptor (descriptor object)
+        import __builtin__
+        check(__builtin__.file.closed, size(h + '2PP'))
+        # wrapper_descriptor (descriptor object)
+        check(int.__add__, size(h + '2P2P'))
+        # dictproxy
+        class C(object): pass
+        check(C.__dict__, size(h + 'P'))
+        # method-wrapper (descriptor object)
+        check({}.__iter__, size(h + '2P'))
+        # dict
+        check({}, size(h + '3P2P') + 8*size('P2P'))
+        x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
+        check(x, size(h + '3P2P') + (8+16)*size('P2P'))
+        # dictionary-keyiterator
+        check({}.iterkeys(), size(h + 'P2PPP'))
+        # dictionary-valueiterator
+        check({}.itervalues(), size(h + 'P2PPP'))
+        # dictionary-itemiterator
+        check({}.iteritems(), size(h + 'P2PPP'))
+        # ellipses
+        check(Ellipsis, size(h + ''))
+        # EncodingMap
+        import codecs, encodings.iso8859_3
+        x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
+        check(x, size(h + '32B2iB'))
         # enumerate
-        self.check_sizeof(enumerate([]), size(h + 'l3P'))
-        # reverse
-        self.check_sizeof(reversed(''), size(h + 'PP'))
+        check(enumerate([]), size(h + 'l3P'))
         # file
-        self.check_sizeof(self.file, size(h + '4P2i4P3i3Pi'))
+        check(self.file, size(h + '4P2i4P3i3Pi'))
         # float
-        self.check_sizeof(float(0), size(h + 'd'))
+        check(float(0), size(h + 'd'))
+        # sys.floatinfo
+        check(sys.float_info, size(vh) + self.P * len(sys.float_info))
+        # frame
+        import inspect
+        CO_MAXBLOCKS = 20
+        x = inspect.currentframe()
+        ncells = len(x.f_code.co_cellvars)
+        nfrees = len(x.f_code.co_freevars)
+        extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
+                 ncells + nfrees - 1
+        check(x, size(vh + '12P3i') +\
+                              CO_MAXBLOCKS*struct.calcsize('3i') +\
+                              self.P + extras*self.P)
         # function
         def func(): pass
-        self.check_sizeof(func, size(h + '9P'))
+        check(func, size(h + '9P'))
         class c():
             @staticmethod
             def foo():
@@ -489,75 +556,146 @@
             def bar(cls):
                 pass
             # staticmethod
-            self.check_sizeof(foo, size(h + 'P'))
+            check(foo, size(h + 'P'))
             # classmethod
-            self.check_sizeof(bar, size(h + 'P'))
+            check(bar, size(h + 'P'))
         # generator
         def get_gen(): yield 1
-        self.check_sizeof(get_gen(), size(h + 'Pi2P'))
+        check(get_gen(), size(h + 'Pi2P'))
         # integer
-        self.check_sizeof(1, size(h + 'l'))
-        # builtin_function_or_method
-        self.check_sizeof(abs, size(h + '3P'))
+        check(1, size(h + 'l'))
+        check(100, size(h + 'l'))
+        # iterator
+        check(iter('abc'), size(h + 'lP'))
+        # callable-iterator
+        import re
+        check(re.finditer('',''), size(h + '2P'))
+        # list
+        samples = [[], [1,2,3], ['1', '2', '3']]
+        for sample in samples:
+            check(sample, size(vh + 'PP') + len(sample)*self.P)
+        # sortwrapper (list)
+        # XXX
+        # cmpwrapper (list)
+        # XXX
+        # listiterator (list)
+        check(iter([]), size(h + 'lP'))
+        # listreverseiterator (list)
+        check(reversed([]), size(h + 'lP'))
+        # long
+        check(0L, size(vh + 'H') - self.H)
+        check(1L, size(vh + 'H'))
+        check(-1L, size(vh + 'H'))
+        check(32768L, size(vh + 'H') + self.H)
+        check(32768L*32768L-1, size(vh + 'H') + self.H)
+        check(32768L*32768L, size(vh + 'H') + 2*self.H)
         # module
-        self.check_sizeof(unittest, size(h + 'P'))
-        # xrange
-        self.check_sizeof(xrange(1), size(h + '3l'))
+        check(unittest, size(h + 'P'))
+        # None
+        check(None, size(h + ''))
+        # object
+        check(object(), size(h + ''))
+        # property (descriptor object)
+        class C(object):
+            def getx(self): return self.__x
+            def setx(self, value): self.__x = value
+            def delx(self): del self.__x
+            x = property(getx, setx, delx, "")
+            check(x, size(h + '4Pi'))
+        # PyCObject
+        # XXX
+        # rangeiterator
+        check(iter(xrange(1)), size(h + '4l'))
+        # reverse
+        check(reversed(''), size(h + 'PP'))
+        # set
+        # frozenset
+        PySet_MINSIZE = 8
+        samples = [[], range(10), range(50)]
+        s = size(h + '3P2P') +\
+            PySet_MINSIZE*struct.calcsize('lP') + self.l + self.P
+        for sample in samples:
+            minused = len(sample)
+            if minused == 0: tmp = 1
+            # the computation of minused is actually a bit more complicated
+            # but this suffices for the sizeof test
+            minused = minused*2
+            newsize = PySet_MINSIZE
+            while newsize <= minused:
+                newsize = newsize << 1
+            if newsize <= 8:
+                check(set(sample), s)
+                check(frozenset(sample), s)
+            else:
+                check(set(sample), s + newsize*struct.calcsize('lP'))
+                check(frozenset(sample), s + newsize*struct.calcsize('lP'))
+        # setiterator
+        check(iter(set()), size(h + 'P3P'))
         # slice
-        self.check_sizeof(slice(0), size(h + '3P'))
-
-        h += 'P'
-        # new-style class
-        class class_newstyle(object):
-            def method():
-                pass
-        # type (PyTypeObject + PyNumberMethods +  PyMappingMethods +
-        #       PySequenceMethods + PyBufferProcs)
-        self.check_sizeof(class_newstyle, size('P2P15Pl4PP9PP11PI') +\
-                                          size(h + '41P 10P 3P 6P'))
-
-    def test_specialtypes(self):
-        h = self.header
-        size = self.calcsize
-        # dict
-        self.check_sizeof({}, size(h + '3P2P') + 8*size('P2P'))
-        longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
-        self.check_sizeof(longdict, size(h + '3P2P') + (8+16)*size('P2P'))
+        check(slice(1), size(h + '3P'))
+        # str
+        check('', size(vh + 'lic'))
+        check('abc', size(vh + 'lic') + 3*self.c)
+        # super
+        check(super(int), size(h + '3P'))
+        # tuple
+        check((), size(vh))
+        check((1,2,3), size(vh) + 3*self.P)
+        # tupleiterator
+        check(iter(()), size(h + 'lP'))
+        # type
+        # (PyTypeObject + PyNumberMethods +  PyMappingMethods +
+        #  PySequenceMethods + PyBufferProcs)
+        s = size('P2P15Pl4PP9PP11PI') + size(vh + '41P 10P 3P 6P')
+        class newstyleclass(object):
+            pass
+        check(newstyleclass, s)
+        # builtin type
+        check(int, s)
+        # NotImplementedType
+        import types
+        check(types.NotImplementedType, s)
         # unicode
         usize = len(u'\0'.encode('unicode-internal'))
         samples = [u'', u'1'*100]
         # we need to test for both sizes, because we don't know if the string
         # has been cached
         for s in samples:
-            basicsize =  size(h + 'PPlP') + usize * (len(s) + 1)
-            self.check_sizeof(s, basicsize,\
-                                  size2=basicsize + sys.getsizeof(str(s)))
-        # XXX trigger caching encoded version as Python string
-        s = samples[1]
-        try:
-            getattr(sys, s)
-        except AttributeError:
-            pass
-        finally:
-            self.check_sizeof(s, basicsize + sys.getsizeof(str(s)))
+            check(s, size(h + 'PPlP') + usize * (len(s) + 1))
+        # weakref
+        import weakref
+        check(weakref.ref(int), size(h + '2Pl2P'))
+        # weakproxy
+        # XXX
+        # weakcallableproxy
+        check(weakref.proxy(int), size(h + '2Pl2P'))
+        # xrange
+        check(xrange(1), size(h + '3l'))
+        check(xrange(66000), size(h + '3l'))
 
-        h += 'P'
-        # list
-        self.check_sizeof([], size(h + 'PP'))
-        self.check_sizeof([1, 2, 3], size(h + 'PP') + 3*self.P)
-        # long
-        self.check_sizeof(0L, size(h + 'H'))
-        self.check_sizeof(1L, size(h + 'H'))
-        self.check_sizeof(-1L, size(h + 'H'))
-        self.check_sizeof(32768L, size(h + 'H') + self.H)
-        self.check_sizeof(32768L*32768L-1, size(h + 'H') + self.H)
-        self.check_sizeof(32768L*32768L, size(h + 'H') + 2*self.H)
-        # string
-        self.check_sizeof('', size(h + 'lic'))
-        self.check_sizeof('abc', size(h + 'lic') + 3*self.c)
-        # tuple
-        self.check_sizeof((), size(h))
-        self.check_sizeof((1,2,3), size(h) + 3*self.P)
+    def test_pythontypes(self):
+        # check all types defined in Python/
+        h = self.header
+        vh = self.vheader
+        size = self.calcsize
+        check = self.check_sizeof
+        # _ast.AST
+        import _ast
+        check(_ast.AST(), size(h + ''))
+        # imp.NullImporter
+        import imp
+        check(imp.NullImporter(self.file.name), size(h + ''))
+        try:
+            raise TypeError
+        except TypeError:
+            tb = sys.exc_info()[2]
+            # traceback
+            if tb != None:
+                check(tb, size(h + '2P2i'))
+        # symtable entry
+        # XXX
+        # sys.flags
+        check(sys.flags, size(vh) + self.P * len(sys.flags))
 
 
 def test_main():

Modified: python/branches/tlee-ast-optimize/Lib/test/test_traceback.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_traceback.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_traceback.py	Sat Jul 12 06:22:35 2008
@@ -177,7 +177,7 @@
         banner, location, source_line = tb_lines
         self.assert_(banner.startswith('Traceback'))
         self.assert_(location.startswith('  File'))
-        self.assert_(source_line.startswith('raise'))
+        self.assert_(source_line.startswith('    raise'))
 
 
 def test_main():

Modified: python/branches/tlee-ast-optimize/Lib/unittest.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/unittest.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/unittest.py	Sat Jul 12 06:22:35 2008
@@ -68,7 +68,6 @@
 # Backward compatibility
 ##############################################################################
 if sys.version_info[:2] < (2, 2):
-    False, True = 0, 1
     def isinstance(obj, clsinfo):
         import __builtin__
         if type(clsinfo) in (tuple, list):
@@ -79,6 +78,14 @@
             return 0
         else: return __builtin__.isinstance(obj, clsinfo)
 
+def _CmpToKey(mycmp):
+    'Convert a cmp= function into a key= function'
+    class K(object):
+        def __init__(self, obj):
+            self.obj = obj
+        def __lt__(self, other):
+            return mycmp(self.obj, other.obj) == -1
+    return K
 
 ##############################################################################
 # Test framework core
@@ -429,7 +436,7 @@
 
     def addTest(self, test):
         # sanity checks
-        if not callable(test):
+        if not hasattr(test, '__call__'):
             raise TypeError("the test to add must be callable")
         if (isinstance(test, (type, types.ClassType)) and
             issubclass(test, (TestCase, TestSuite))):
@@ -584,7 +591,7 @@
             return TestSuite([parent(obj.__name__)])
         elif isinstance(obj, TestSuite):
             return obj
-        elif callable(obj):
+        elif hasattr(obj, '__call__'):
             test = obj()
             if isinstance(test, TestSuite):
                 return test
@@ -607,10 +614,10 @@
         """Return a sorted sequence of method names found within testCaseClass
         """
         def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
-            return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
+            return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
         testFnNames = filter(isTestMethod, dir(testCaseClass))
         if self.sortTestMethodsUsing:
-            testFnNames.sort(self.sortTestMethodsUsing)
+            testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
         return testFnNames
 
 

Modified: python/branches/tlee-ast-optimize/Lib/zipfile.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/zipfile.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/zipfile.py	Sat Jul 12 06:22:35 2008
@@ -43,9 +43,9 @@
 
 # The "end of central directory" structure, magic number, size, and indices
 # (section V.I in the format document)
-structEndCentDir = "<4s4H2LH"
-magicEndCentDir = "PK\005\006"
-sizeEndCentDir = struct.calcsize(structEndCentDir)
+structEndArchive = "<4s4H2LH"
+stringEndArchive = "PK\005\006"
+sizeEndCentDir = struct.calcsize(structEndArchive)
 
 _ECD_SIGNATURE = 0
 _ECD_DISK_NUMBER = 1
@@ -63,37 +63,9 @@
 # The "central directory" structure, magic number, size, and indices
 # of entries in the structure (section V.F in the format document)
 structCentralDir = "<4s4B4HL2L5H2L"
-magicCentralDir = "PK\001\002"
+stringCentralDir = "PK\001\002"
 sizeCentralDir = struct.calcsize(structCentralDir)
 
-# The "local file header" structure, magic number, size, and indices
-# (section V.A in the format document)
-structFileHeader = "<4s2B4HL2L2H"
-magicFileHeader = "PK\003\004"
-sizeFileHeader = struct.calcsize(structFileHeader)
-
-# The "Zip64 end of central directory locator" structure, magic number, and size
-structEndCentDir64Locator = "<4sLQL"
-magicEndCentDir64Locator = "PK\x06\x07"
-sizeEndCentDir64Locator = struct.calcsize(structEndCentDir64Locator)
-
-# The "Zip64 end of central directory" record, magic number, size, and indices
-# (section V.G in the format document)
-structEndCentDir64 = "<4sQ2H2L4Q"
-magicEndCentDir64 = "PK\x06\x06"
-sizeEndCentDir64 = struct.calcsize(structEndCentDir64)
-
-_CD64_SIGNATURE = 0
-_CD64_DIRECTORY_RECSIZE = 1
-_CD64_CREATE_VERSION = 2
-_CD64_EXTRACT_VERSION = 3
-_CD64_DISK_NUMBER = 4
-_CD64_DISK_NUMBER_START = 5
-_CD64_NUMBER_ENTRIES_THIS_DISK = 6
-_CD64_NUMBER_ENTRIES_TOTAL = 7
-_CD64_DIRECTORY_SIZE = 8
-_CD64_OFFSET_START_CENTDIR = 9
-
 # indexes of entries in the central directory structure
 _CD_SIGNATURE = 0
 _CD_CREATE_VERSION = 1
@@ -118,7 +90,7 @@
 # The "local file header" structure, magic number, size, and indices
 # (section V.A in the format document)
 structFileHeader = "<4s2B4HL2L2H"
-magicFileHeader = "PK\003\004"
+stringFileHeader = "PK\003\004"
 sizeFileHeader = struct.calcsize(structFileHeader)
 
 _FH_SIGNATURE = 0
@@ -135,15 +107,15 @@
 _FH_EXTRA_FIELD_LENGTH = 11
 
 # The "Zip64 end of central directory locator" structure, magic number, and size
-structEndCentDir64Locator = "<4sLQL"
-magicEndCentDir64Locator = "PK\x06\x07"
-sizeEndCentDir64Locator = struct.calcsize(structEndCentDir64Locator)
+structEndArchive64Locator = "<4sLQL"
+stringEndArchive64Locator = "PK\x06\x07"
+sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
 
 # The "Zip64 end of central directory" record, magic number, size, and indices
 # (section V.G in the format document)
-structEndCentDir64 = "<4sQ2H2L4Q"
-magicEndCentDir64 = "PK\x06\x06"
-sizeEndCentDir64 = struct.calcsize(structEndCentDir64)
+structEndArchive64 = "<4sQ2H2L4Q"
+stringEndArchive64 = "PK\x06\x06"
+sizeEndCentDir64 = struct.calcsize(structEndArchive64)
 
 _CD64_SIGNATURE = 0
 _CD64_DIRECTORY_RECSIZE = 1
@@ -174,8 +146,8 @@
     """
     fpin.seek(offset - sizeEndCentDir64Locator, 2)
     data = fpin.read(sizeEndCentDir64Locator)
-    sig, diskno, reloff, disks = struct.unpack(structEndCentDir64Locator, data)
-    if sig != magicEndCentDir64Locator:
+    sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
+    if sig != stringEndArchive64Locator:
         return endrec
 
     if diskno != 0 or disks != 1:
@@ -186,8 +158,8 @@
     data = fpin.read(sizeEndCentDir64)
     sig, sz, create_version, read_version, disk_num, disk_dir, \
             dircount, dircount2, dirsize, diroffset = \
-            struct.unpack(structEndCentDir64, data)
-    if sig != magicEndCentDir64:
+            struct.unpack(structEndArchive64, data)
+    if sig != stringEndArchive64:
         return endrec
 
     # Update the original endrec using data from the ZIP64 record
@@ -215,9 +187,9 @@
     # file if this is the case).
     fpin.seek(-sizeEndCentDir, 2)
     data = fpin.read()
-    if data[0:4] == magicEndCentDir and data[-2:] == "\000\000":
+    if data[0:4] == stringEndArchive and data[-2:] == "\000\000":
         # the signature is correct and there's no comment, unpack structure
-        endrec = struct.unpack(structEndCentDir, data)
+        endrec = struct.unpack(structEndArchive, data)
         endrec=list(endrec)
 
         # Append a blank comment and record start offset
@@ -239,11 +211,11 @@
     maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
     fpin.seek(maxCommentStart, 0)
     data = fpin.read()
-    start = data.rfind(magicEndCentDir)
+    start = data.rfind(stringEndArchive)
     if start >= 0:
         # found the magic number; attempt to unpack and interpret
         recData = data[start:start+sizeEndCentDir]
-        endrec = list(struct.unpack(structEndCentDir, recData))
+        endrec = list(struct.unpack(structEndArchive, recData))
         comment = data[start+sizeEndCentDir:]
         # check that comment length is correct
         if endrec[_ECD_COMMENT_SIZE] == len(comment):
@@ -350,7 +322,7 @@
             self.create_version = max(45, self.extract_version)
 
         filename, flag_bits = self._encodeFilenameFlags()
-        header = struct.pack(structFileHeader, magicFileHeader,
+        header = struct.pack(structFileHeader, stringFileHeader,
                  self.extract_version, self.reserved, flag_bits,
                  self.compress_type, dostime, dosdate, CRC,
                  compress_size, file_size,
@@ -779,7 +751,7 @@
         total = 0
         while total < size_cd:
             centdir = fp.read(sizeCentralDir)
-            if centdir[0:4] != magicCentralDir:
+            if centdir[0:4] != stringCentralDir:
                 raise BadZipfile, "Bad magic number for central directory"
             centdir = struct.unpack(structCentralDir, centdir)
             if self.debug > 2:
@@ -885,7 +857,7 @@
 
         # Skip the file header:
         fheader = zef_file.read(sizeFileHeader)
-        if fheader[0:4] != magicFileHeader:
+        if fheader[0:4] != stringFileHeader:
             raise BadZipfile, "Bad magic number for file header"
 
         fheader = struct.unpack(structFileHeader, fheader)
@@ -1173,7 +1145,7 @@
                 try:
                     filename, flag_bits = zinfo._encodeFilenameFlags()
                     centdir = struct.pack(structCentralDir,
-                     magicCentralDir, create_version,
+                     stringCentralDir, create_version,
                      zinfo.create_system, extract_version, zinfo.reserved,
                      flag_bits, zinfo.compress_type, dostime, dosdate,
                      zinfo.CRC, compress_size, file_size,
@@ -1201,13 +1173,13 @@
             if pos1 > ZIP64_LIMIT:
                 # Need to write the ZIP64 end-of-archive records
                 zip64endrec = struct.pack(
-                        structEndCentDir64, magicEndCentDir64,
+                        structEndArchive64, stringEndArchive64,
                         44, 45, 45, 0, 0, count, count, pos2 - pos1, pos1)
                 self.fp.write(zip64endrec)
 
                 zip64locrec = struct.pack(
-                        structEndCentDir64Locator,
-                        magicEndCentDir64Locator, 0, pos2, 1)
+                        structEndArchive64Locator,
+                        stringEndArchive64Locator, 0, pos2, 1)
                 self.fp.write(zip64locrec)
                 centDirOffset = 0xFFFFFFFF
 
@@ -1218,7 +1190,7 @@
                           % ZIP_MAX_COMMENT
                 self.comment = self.comment[:ZIP_MAX_COMMENT]
 
-            endrec = struct.pack(structEndCentDir, magicEndCentDir,
+            endrec = struct.pack(structEndArchive, stringEndArchive,
                                  0, 0, count % ZIP_FILECOUNT_LIMIT,
                                  count % ZIP_FILECOUNT_LIMIT, pos2 - pos1,
                                  centDirOffset, len(self.comment))

Modified: python/branches/tlee-ast-optimize/Misc/ACKS
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/ACKS	(original)
+++ python/branches/tlee-ast-optimize/Misc/ACKS	Sat Jul 12 06:22:35 2008
@@ -146,6 +146,7 @@
 Matthew Dixon Cowles
 Christopher A. Craig
 Laura Creighton
+Simon Cross
 Drew Csillag
 John Cugini
 Tom Culliton

Modified: python/branches/tlee-ast-optimize/Misc/NEWS
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/NEWS	(original)
+++ python/branches/tlee-ast-optimize/Misc/NEWS	Sat Jul 12 06:22:35 2008
@@ -10,6 +10,11 @@
 Core and Builtins
 -----------------
 
+
+- Issue #2517: Allow unicode messages in Exceptions again by correctly
+  bypassing the instance dictionary when looking up __unicode__ on
+  new-style classes.
+
 - Issue #3242: Fix a crash inside the print statement, if sys.stdout is
   set to a custom object whose write() method happens to install
   another file in sys.stdout.
@@ -26,12 +31,26 @@
   10, -1).
 
 - Issue #3219: Calling a function with repeated keyword arguments, f(a=2, a=23),
-  would not cause a syntax error.  This was regression from 2.4 caused by the
+  would not cause a syntax error.  This was a regression from 2.4 caused by the
   switch to the new compiler.
 
+- Issue #2862: Make int and float freelist management consistent with other
+  freelists.  Changes their CompactFreeList apis into ClearFreeList apis and
+  calls them via gc.collect().
+
 Library
 -------
 
+- Issue #3285: Fractions from_float() and from_decimal() accept Integral arguments.
+
+- Issue #3301: Bisect module behaved badly when lo was negative.
+
+- Issue #839496: SimpleHTTPServer used to open text files in text mode. This is
+  both unnecessary (HTTP allows text content to be sent in several forms) and
+  wrong because the actual transmitted size could differ from the
+  content-length.  The problem had been corrected in the 2.4 branch, but never
+  merged into trunk.
+
 - Issue #2663: add filtering capability to shutil.copytree().
 
 - Issue #1622: Correct interpretation of various ZIP header fields.
@@ -42,8 +61,8 @@
   archives with comments over 4k were flagged as invalid). Allow writing
   Zip files with archives by setting the 'comment' attribute of a ZipFile.  
 
-- Issue #449227: Now with the rlcompleter module, callable objects are added
-  "(" when completed.
+- Issue #449227: The rlcompleter module now adds "(" to callable objects 
+  when completed.
 
 - Issue #3190: Pydoc now hides the automatic module attribute __package__ (the
   handling is now the same as that of other special attributes like __name__).
@@ -51,9 +70,16 @@
 - Issue #2885 (partial): The urllib.urlopen() function has been deprecated for
   removal in Python 3.0 in favor of urllib2.urlopen().
 
-- Issue #2885 (partial): lib2to3 has been updated to handle the renaming of the
-  urllib module in Python 3.0 to urllib.request, urllib.parse, and
-  urllib.error.
+- Issue #2113: Fix error in subprocess.Popen if the select system call is
+  interrupted by a signal.
+
+- Issue #3309: Fix bz2.BZFile iterator to release its internal lock
+  properly when raising an exception due to the bz2file being closed.
+  Prevents a deadlock.
+
+- Issue #3094: httplib.HTTPSConnection Host: headers no longer include the
+  redundant ":443" port number designation when the connection is using the
+  default https port (443).
 
 Build
 -----
@@ -61,6 +87,21 @@
 - Issue #3215: Build sqlite3 as sqlite3.dll, not sqlite3.pyd.
 
 
+Documentation
+-------------
+
+- Document that robotparser has been renamed to urllib.robotparser in
+  Python 3.0.
+
+- Document that urlparse has been renamed to urllib.parse in Python 3.0.
+
+- Document that urllib2 is split across multiple modules and renamed in
+  Python 3.0.
+
+- Document that urllib is split across multiple modules and renamed in
+  Python 3.0.
+
+
 What's New in Python 2.6 beta 1?
 ================================
 

Modified: python/branches/tlee-ast-optimize/Modules/Setup.dist
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/Setup.dist	(original)
+++ python/branches/tlee-ast-optimize/Modules/Setup.dist	Sat Jul 12 06:22:35 2008
@@ -246,9 +246,11 @@
 #_md5 md5module.c md5.c
 
 
-# The _sha module implements the SHA checksum algorithm.
-# (NIST's Secure Hash Algorithm.)
+# The _sha module implements the SHA checksum algorithms.
+# (NIST's Secure Hash Algorithms.)
 #_sha shamodule.c
+#_sha256 sha256module.c
+#_sha512 sha512module.c
 
 
 # SGI IRIX specific modules -- off by default.

Modified: python/branches/tlee-ast-optimize/Modules/_bisectmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_bisectmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_bisectmodule.c	Sat Jul 12 06:22:35 2008
@@ -11,6 +11,10 @@
 	PyObject *litem;
 	Py_ssize_t mid, res;
 
+	if (lo < 0) {
+		PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
+		return -1;
+	}
 	if (hi == -1) {
 		hi = PySequence_Size(list);
 		if (hi < 0)
@@ -108,6 +112,10 @@
 	PyObject *litem;
 	int mid, res;
 
+	if (lo < 0) {
+		PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
+		return -1;
+	}
 	if (hi == -1) {
 		hi = PySequence_Size(list);
 		if (hi < 0)

Modified: python/branches/tlee-ast-optimize/Modules/_fileio.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_fileio.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_fileio.c	Sat Jul 12 06:22:35 2008
@@ -278,7 +278,6 @@
 	ret = -1;
 
  done:
-	PyMem_Free(name);
 	return ret;
 }
 

Modified: python/branches/tlee-ast-optimize/Modules/_testcapimodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_testcapimodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_testcapimodule.c	Sat Jul 12 06:22:35 2008
@@ -967,6 +967,7 @@
 	PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
 	PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
 	PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
+	PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
 
 	TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
 	Py_INCREF(TestError);

Modified: python/branches/tlee-ast-optimize/Modules/audioop.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/audioop.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/audioop.c	Sat Jul 12 06:22:35 2008
@@ -575,7 +575,7 @@
         }
         len1 >>= 1;
     
-        if ( len1 < len2 ) {
+        if ( len2 < 0 || len1 < len2 ) {
                 PyErr_SetString(AudioopError, "Input sample should be longer");
                 return 0;
         }

Modified: python/branches/tlee-ast-optimize/Modules/bz2module.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/bz2module.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/bz2module.c	Sat Jul 12 06:22:35 2008
@@ -1451,6 +1451,7 @@
 	PyStringObject* ret;
 	ACQUIRE_LOCK(self);
 	if (self->mode == MODE_CLOSED) {
+                RELEASE_LOCK(self);
 		PyErr_SetString(PyExc_ValueError,
 				"I/O operation on closed file");
 		return NULL;

Modified: python/branches/tlee-ast-optimize/Modules/cmathmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/cmathmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/cmathmodule.c	Sat Jul 12 06:22:35 2008
@@ -839,8 +839,10 @@
 	errno = 0;
 	PyFPE_START_PROTECT("complex function", return 0)
 	x = c_log(x);
-	if (PyTuple_GET_SIZE(args) == 2)
-		x = c_quot(x, c_log(y));
+	if (PyTuple_GET_SIZE(args) == 2) {
+		y = c_log(y);
+		x = c_quot(x, y);
+	}
 	PyFPE_END_PROTECT(x)
 	if (errno != 0)
 		return math_error();

Modified: python/branches/tlee-ast-optimize/Modules/gcmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/gcmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/gcmodule.c	Sat Jul 12 06:22:35 2008
@@ -736,6 +736,8 @@
 	(void)PyCFunction_ClearFreeList();
 	(void)PyTuple_ClearFreeList();
 	(void)PyUnicode_ClearFreeList();
+	(void)PyInt_ClearFreeList();
+	(void)PyFloat_ClearFreeList();
 }
 
 /* This is the main function.  Read this to understand how the

Modified: python/branches/tlee-ast-optimize/Modules/timemodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/timemodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/timemodule.c	Sat Jul 12 06:22:35 2008
@@ -600,8 +600,6 @@
 {
 	struct tm buf;
 	time_t tt;
-	tt = time(&tt);
-	buf = *localtime(&tt);
 	if (!gettmarg(tup, &buf))
 		return NULL;
 	tt = mktime(&buf);

Modified: python/branches/tlee-ast-optimize/Objects/abstract.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/abstract.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/abstract.c	Sat Jul 12 06:22:35 2008
@@ -1946,7 +1946,7 @@
 		return m->sq_item(s, i);
 	}
 
-	return type_error("'%.200s' object is unindexable", s);
+	return type_error("'%.200s' object does not support indexing", s);
 }
 
 PyObject *

Modified: python/branches/tlee-ast-optimize/Objects/bytearrayobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/bytearrayobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/bytearrayobject.c	Sat Jul 12 06:22:35 2008
@@ -3106,6 +3106,19 @@
     return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict);
 }
 
+PyDoc_STRVAR(sizeof_doc,
+"B.__sizeof__() -> int\n\
+ \n\
+Returns the size of B in memory, in bytes");
+static PyObject *
+bytes_sizeof(PyByteArrayObject *self)
+{
+	Py_ssize_t res;
+
+	res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char);
+	return PyInt_FromSsize_t(res);
+}
+
 static PySequenceMethods bytes_as_sequence = {
     (lenfunc)bytes_length,              /* sq_length */
     (binaryfunc)PyByteArray_Concat,         /* sq_concat */
@@ -3138,6 +3151,7 @@
 bytes_methods[] = {
     {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc},
     {"__reduce__", (PyCFunction)bytes_reduce, METH_NOARGS, reduce_doc},
+    {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, sizeof_doc},
     {"append", (PyCFunction)bytes_append, METH_O, append__doc__},
     {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS,
      _Py_capitalize__doc__},

Modified: python/branches/tlee-ast-optimize/Objects/exceptions.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/exceptions.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/exceptions.c	Sat Jul 12 06:22:35 2008
@@ -117,6 +117,28 @@
     return out;
 }
 
+#ifdef Py_USING_UNICODE
+static PyObject *
+BaseException_unicode(PyBaseExceptionObject *self)
+{
+    PyObject *out;
+
+    switch (PyTuple_GET_SIZE(self->args)) {
+    case 0:
+        out = PyUnicode_FromString("");
+        break;
+    case 1:
+        out = PyObject_Unicode(PyTuple_GET_ITEM(self->args, 0));
+        break;
+    default:
+        out = PyObject_Unicode(self->args);
+        break;
+    }
+
+    return out;
+}
+#endif
+
 static PyObject *
 BaseException_repr(PyBaseExceptionObject *self)
 {
@@ -181,6 +203,9 @@
 static PyMethodDef BaseException_methods[] = {
    {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
    {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
+#ifdef Py_USING_UNICODE   
+   {"__unicode__", (PyCFunction)BaseException_unicode, METH_NOARGS },
+#endif
    {NULL, NULL, 0, NULL},
 };
 

Modified: python/branches/tlee-ast-optimize/Objects/floatobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/floatobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/floatobject.c	Sat Jul 12 06:22:35 2008
@@ -246,6 +246,9 @@
 		if (PyOS_strnicmp(p, "inf", 4) == 0) {
 			Py_RETURN_INF(sign);
 		}
+		if (PyOS_strnicmp(p, "infinity", 9) == 0) {
+			Py_RETURN_INF(sign);
+		}
 #ifdef Py_NAN
 		if(PyOS_strnicmp(p, "nan", 4) == 0) {
 			Py_RETURN_NAN;
@@ -1605,30 +1608,28 @@
 		PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
 }
 
-void
-PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
+int
+PyFloat_ClearFreeList(void)
 {
 	PyFloatObject *p;
 	PyFloatBlock *list, *next;
-	unsigned i;
-	size_t bc = 0, bf = 0;	/* block count, number of freed blocks */
-	size_t fsum = 0;	/* total unfreed ints */
-	int frem;		/* remaining unfreed ints per block */
+	int i;
+	int u;			/* remaining unfreed ints per block */
+	int freelist_size = 0;
 
 	list = block_list;
 	block_list = NULL;
 	free_list = NULL;
 	while (list != NULL) {
-		bc++;
-		frem = 0;
+		u = 0;
 		for (i = 0, p = &list->objects[0];
 		     i < N_FLOATOBJECTS;
 		     i++, p++) {
 			if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
-				frem++;
+				u++;
 		}
 		next = list->next;
-		if (frem) {
+		if (u) {
 			list->next = block_list;
 			block_list = list;
 			for (i = 0, p = &list->objects[0];
@@ -1643,15 +1644,12 @@
 			}
 		}
 		else {
-			PyMem_FREE(list); /* XXX PyObject_FREE ??? */
-			bf++;
+			PyMem_FREE(list);
 		}
-		fsum += frem;
+		freelist_size += u;
 		list = next;
 	}
-	*pbc = bc;
-	*pbf = bf;
-	*bsum = fsum;
+	return freelist_size;
 }
 
 void
@@ -1659,25 +1657,21 @@
 {
 	PyFloatObject *p;
 	PyFloatBlock *list;
-	unsigned i;
-	size_t bc, bf;	/* block count, number of freed blocks */
-	size_t fsum;	/* total unfreed floats per block */
+	int i;
+	int u;			/* total unfreed floats per block */
 
-	PyFloat_CompactFreeList(&bc, &bf, &fsum);
+	u = PyFloat_ClearFreeList();
 
 	if (!Py_VerboseFlag)
 		return;
 	fprintf(stderr, "# cleanup floats");
-	if (!fsum) {
+	if (!u) {
 		fprintf(stderr, "\n");
 	}
 	else {
 		fprintf(stderr,
-			": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
-			PY_FORMAT_SIZE_T "d out of %"
-			PY_FORMAT_SIZE_T "d block%s\n",
-			fsum, fsum == 1 ? "" : "s",
-			bc - bf, bc, bc == 1 ? "" : "s");
+			": %d unfreed float%s\n",
+			u, u == 1 ? "" : "s");
 	}
 	if (Py_VerboseFlag > 1) {
 		list = block_list;

Modified: python/branches/tlee-ast-optimize/Objects/frameobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/frameobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/frameobject.c	Sat Jul 12 06:22:35 2008
@@ -508,6 +508,29 @@
 	}
 }
 
+static PyObject *
+frame_sizeof(PyFrameObject *f)
+{
+	Py_ssize_t res, extras, ncells, nfrees;
+
+	ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
+	nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
+	extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
+		 ncells + nfrees;
+	// subtract one as it is already included in PyFrameObject
+	res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
+
+	return PyInt_FromSsize_t(res);
+}
+
+PyDoc_STRVAR(sizeof__doc__,
+"F.__sizeof__() -> size of F in memory, in bytes");
+
+static PyMethodDef frame_methods[] = {
+	{"__sizeof__",	(PyCFunction)frame_sizeof,	METH_NOARGS,
+	 sizeof__doc__},
+	{NULL,		NULL}	/* sentinel */
+};
 
 PyTypeObject PyFrame_Type = {
 	PyVarObject_HEAD_INIT(&PyType_Type, 0)
@@ -537,7 +560,7 @@
 	0,					/* tp_weaklistoffset */
 	0,					/* tp_iter */
 	0,					/* tp_iternext */
-	0,					/* tp_methods */
+	frame_methods,				/* tp_methods */
 	frame_memberlist,			/* tp_members */
 	frame_getsetlist,			/* tp_getset */
 	0,					/* tp_base */

Modified: python/branches/tlee-ast-optimize/Objects/intobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/intobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/intobject.c	Sat Jul 12 06:22:35 2008
@@ -1296,35 +1296,33 @@
 	return 1;
 }
 
-void
-PyInt_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
+int
+PyInt_ClearFreeList(void)
 {
 	PyIntObject *p;
 	PyIntBlock *list, *next;
-	unsigned int ctr;
-	size_t bc = 0, bf = 0;	/* block count, number of freed blocks */
-	size_t isum = 0;	/* total unfreed ints */
-	int irem;		/* remaining unfreed ints per block */
+	int i;
+	int u;			/* remaining unfreed ints per block */
+	int freelist_size = 0;
 
 	list = block_list;
 	block_list = NULL;
 	free_list = NULL;
 	while (list != NULL) {
-		bc++;
-		irem = 0;
-		for (ctr = 0, p = &list->objects[0];
-		     ctr < N_INTOBJECTS;
-		     ctr++, p++) {
+		u = 0;
+		for (i = 0, p = &list->objects[0];
+		     i < N_INTOBJECTS;
+		     i++, p++) {
 			if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
-				irem++;
+				u++;
 		}
 		next = list->next;
-		if (irem) {
+		if (u) {
 			list->next = block_list;
 			block_list = list;
-			for (ctr = 0, p = &list->objects[0];
-			     ctr < N_INTOBJECTS;
-			     ctr++, p++) {
+			for (i = 0, p = &list->objects[0];
+			     i < N_INTOBJECTS;
+			     i++, p++) {
 				if (!PyInt_CheckExact(p) ||
 				    p->ob_refcnt == 0) {
 					Py_TYPE(p) = (struct _typeobject *)
@@ -1345,15 +1343,12 @@
 		}
 		else {
 			PyMem_FREE(list);
-			bf++;
 		}
-		isum += irem;
+		freelist_size += u;
 		list = next;
 	}
 
-	*pbc = bc;
-	*pbf = bf;
-	*bsum = isum;
+	return freelist_size;
 }
 
 void
@@ -1361,12 +1356,10 @@
 {
 	PyIntObject *p;
 	PyIntBlock *list;
-	unsigned int ctr;
-	size_t bc, bf;	/* block count, number of freed blocks */
-	size_t isum;	/* total unfreed ints per block */
+	int i;
+	int u;			/* total unfreed ints per block */
 
 #if NSMALLNEGINTS + NSMALLPOSINTS > 0
-	int i;
 	PyIntObject **q;
 
 	i = NSMALLNEGINTS + NSMALLPOSINTS;
@@ -1376,27 +1369,24 @@
 		*q++ = NULL;
 	}
 #endif
-	PyInt_CompactFreeList(&bc, &bf, &isum);
+	u = PyInt_ClearFreeList();
 	if (!Py_VerboseFlag)
 		return;
 	fprintf(stderr, "# cleanup ints");
-	if (!isum) {
+	if (!u) {
 		fprintf(stderr, "\n");
 	}
 	else {
 		fprintf(stderr,
-			": %" PY_FORMAT_SIZE_T "d unfreed int%s in %"
-			PY_FORMAT_SIZE_T "d out of %"
-			PY_FORMAT_SIZE_T "d block%s\n",
-			isum, isum == 1 ? "" : "s",
-			bc - bf, bc, bc == 1 ? "" : "s");
+			": %d unfreed int%s\n",
+			u, u == 1 ? "" : "s");
 	}
 	if (Py_VerboseFlag > 1) {
 		list = block_list;
 		while (list != NULL) {
-			for (ctr = 0, p = &list->objects[0];
-			     ctr < N_INTOBJECTS;
-			     ctr++, p++) {
+			for (i = 0, p = &list->objects[0];
+			     i < N_INTOBJECTS;
+			     i++, p++) {
 				if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
 					/* XXX(twouters) cast refcount to
 					   long until %zd is universally

Modified: python/branches/tlee-ast-optimize/Objects/longobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/longobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/longobject.c	Sat Jul 12 06:22:35 2008
@@ -3441,9 +3441,9 @@
 {
 	Py_ssize_t res;
 
-	res = sizeof(PyLongObject) + abs(v->ob_size) * sizeof(digit);
+	res = v->ob_type->tp_basicsize;
         if (v->ob_size != 0)
-		res -=  sizeof(digit);
+		res += abs(v->ob_size) * sizeof(digit);
 	return PyInt_FromSsize_t(res);
 }
 

Modified: python/branches/tlee-ast-optimize/Objects/object.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/object.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/object.c	Sat Jul 12 06:22:35 2008
@@ -458,6 +458,7 @@
 	PyObject *res;
 	PyObject *func;
 	PyObject *str;
+	int unicode_method_found = 0;
 	static PyObject *unicodestr;
 
 	if (v == NULL) {
@@ -471,26 +472,46 @@
 		Py_INCREF(v);
 		return v;
 	}
-	/* XXX As soon as we have a tp_unicode slot, we should
-	   check this before trying the __unicode__
-	   method. */
+
+	/* Try the __unicode__ method */
 	if (unicodestr == NULL) {
 		unicodestr= PyString_InternFromString("__unicode__");
 		if (unicodestr == NULL)
 			return NULL;
 	}
-	func = PyObject_GetAttr(v, unicodestr);
-	if (func != NULL) {
-		res = PyEval_CallObject(func, (PyObject *)NULL);
-		Py_DECREF(func);
+	if (PyInstance_Check(v)) {
+		/* We're an instance of a classic class */
+		/* Try __unicode__ from the instance -- alas we have no type */
+		func = PyObject_GetAttr(v, unicodestr);
+		if (func != NULL) {
+			unicode_method_found = 1;
+			res = PyObject_CallFunctionObjArgs(func, NULL);
+			Py_DECREF(func);
+		}
+		else {
+			PyErr_Clear(); 
+		}
 	}
 	else {
-		PyErr_Clear();
+		/* Not a classic class instance, try __unicode__ from type */
+		/* _PyType_Lookup doesn't create a reference */
+		func = _PyType_Lookup(Py_TYPE(v), unicodestr);
+		if (func != NULL) {
+			unicode_method_found = 1;
+			res = PyObject_CallFunctionObjArgs(func, v, NULL);
+		}
+		else {
+			PyErr_Clear();
+		}
+	}
+
+	/* Didn't find __unicode__ */
+	if (!unicode_method_found) {
 		if (PyUnicode_Check(v)) {
 			/* For a Unicode subtype that's didn't overwrite __unicode__,
 			   return a true Unicode object with the same data. */
 			return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
-			                             PyUnicode_GET_SIZE(v));
+						     PyUnicode_GET_SIZE(v));
 		}
 		if (PyString_CheckExact(v)) {
 			Py_INCREF(v);
@@ -503,6 +524,7 @@
 				res = PyObject_Repr(v);
 		}
 	}
+
 	if (res == NULL)
 		return NULL;
 	if (!PyUnicode_Check(res)) {

Modified: python/branches/tlee-ast-optimize/Objects/setobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/setobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/setobject.c	Sat Jul 12 06:22:35 2008
@@ -1956,6 +1956,18 @@
 
 PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
 
+static PyObject *
+set_sizeof(PySetObject *so)
+{
+	Py_ssize_t res;
+
+	res = sizeof(PySetObject);
+	if (so->table != so->smalltable)
+		res = res + (so->mask + 1) * sizeof(setentry);
+	return PyInt_FromSsize_t(res);
+}
+
+PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes");
 static int
 set_init(PySetObject *self, PyObject *args, PyObject *kwds)
 {
@@ -2023,6 +2035,8 @@
 	 reduce_doc},
 	{"remove",	(PyCFunction)set_remove,	METH_O,
 	 remove_doc},
+	{"__sizeof__",	(PyCFunction)set_sizeof,	METH_NOARGS,
+	 sizeof_doc},
 	{"symmetric_difference",(PyCFunction)set_symmetric_difference,	METH_O,
 	 symmetric_difference_doc},
 	{"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update,	METH_O,
@@ -2144,6 +2158,8 @@
 	 issuperset_doc},
 	{"__reduce__",	(PyCFunction)set_reduce,	METH_NOARGS,
 	 reduce_doc},
+	{"__sizeof__",	(PyCFunction)set_sizeof,	METH_NOARGS,
+	 sizeof_doc},
 	{"symmetric_difference",(PyCFunction)set_symmetric_difference,	METH_O,
 	 symmetric_difference_doc},
 	{"union",	(PyCFunction)set_union,		METH_VARARGS,

Modified: python/branches/tlee-ast-optimize/Objects/unicodeobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/unicodeobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/unicodeobject.c	Sat Jul 12 06:22:35 2008
@@ -7898,20 +7898,8 @@
 static PyObject *
 unicode__sizeof__(PyUnicodeObject *v)
 {
-    PyObject *res = NULL, *defsize = NULL;
-
-    res = PyInt_FromSsize_t(sizeof(PyUnicodeObject) +
-                            sizeof(Py_UNICODE) * (v->length + 1));
-    if (v->defenc) {
-        defsize = PyObject_CallMethod(v->defenc, "__sizeof__", NULL);
-        if (defsize == NULL) {
-            Py_DECREF(res);
-            return NULL;
-        }
-        res = PyNumber_Add(res, defsize);
-        Py_DECREF(defsize);
-    }
-    return res;
+    return PyInt_FromSsize_t(sizeof(PyUnicodeObject) +
+                             sizeof(Py_UNICODE) * (v->length + 1));
 }
 
 PyDoc_STRVAR(sizeof__doc__,

Modified: python/branches/tlee-ast-optimize/Python/_warnings.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/_warnings.c	(original)
+++ python/branches/tlee-ast-optimize/Python/_warnings.c	Sat Jul 12 06:22:35 2008
@@ -256,7 +256,6 @@
     Py_XDECREF(name);
 
     /* Print "  source_line\n" */
-    PyFile_WriteString("  ", f_stderr);
     if (sourceline) {
         char *source_line_str = PyString_AS_STRING(sourceline);
         while (*source_line_str == ' ' || *source_line_str == '\t' ||
@@ -267,7 +266,8 @@
         PyFile_WriteString("\n", f_stderr);
     }
     else
-        Py_DisplaySourceLine(f_stderr, PyString_AS_STRING(filename), lineno);
+        _Py_DisplaySourceLine(f_stderr, PyString_AS_STRING(filename), 
+                              lineno, 2);
     PyErr_Clear();
 }
 

Modified: python/branches/tlee-ast-optimize/Python/sysmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/sysmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Python/sysmodule.c	Sat Jul 12 06:22:35 2008
@@ -640,9 +640,16 @@
 #endif /* USE_MALLOPT */
 
 static PyObject *
-sys_getsizeof(PyObject *self, PyObject *args)
+sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
 {
-	static PyObject * str__sizeof__ = NULL;
+	PyObject *res = NULL;
+	static PyObject *str__sizeof__, *gc_head_size = NULL;
+	static char *kwlist[] = {"object", "default", 0};
+	PyObject *o, *dflt = NULL;
+
+	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
+					 kwlist, &o, &dflt))
+		return NULL;
 
 	/* Initialize static variable needed by _PyType_Lookup */
 	if (str__sizeof__ == NULL) {
@@ -651,30 +658,54 @@
 			return NULL;
 	}
 
-	/* Type objects */
-	if (PyType_Check(args)){
-		PyObject *method = _PyType_Lookup(Py_TYPE(args),
+        /* Initialize static variable for GC head size */
+	if (gc_head_size == NULL) {
+		gc_head_size = PyInt_FromSsize_t(sizeof(PyGC_Head));
+		if (gc_head_size == NULL)
+			return NULL;
+	}
+
+	/* Make sure the type is initialized. float gets initialized late */
+	if (PyType_Ready(Py_TYPE(o)) < 0)
+		return NULL;
+
+	/* Instance of old-style class */
+	if (PyInstance_Check(o))
+		res = PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);
+	/* all other objects */
+	else {
+		PyObject *method = _PyType_Lookup(Py_TYPE(o),
 						  str__sizeof__);
-		if (method == NULL) {
+		if (method == NULL)
 			PyErr_Format(PyExc_TypeError,
 				     "Type %.100s doesn't define __sizeof__",
-				     Py_TYPE(args)->tp_name);
-			return NULL;
-		}
-		return PyObject_CallFunctionObjArgs(method, args, NULL);
-	} 
-	/* Instance of old-style classes */
-	else if (PyInstance_Check(args))
-		return PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);
-	/* Old-style classes */
-	else if (PyClass_Check(args))
-		return PyInt_FromSsize_t(PyClass_Type.tp_basicsize);
-	else
-		return PyObject_CallMethod(args, "__sizeof__", NULL);
+				     Py_TYPE(o)->tp_name);
+		else
+			res = PyObject_CallFunctionObjArgs(method, o, NULL);
+	}
+	
+	/* Has a default value been given? */
+	if ((res == NULL) && (dflt != NULL) &&
+	    PyErr_ExceptionMatches(PyExc_TypeError))
+	{
+		PyErr_Clear();
+		Py_INCREF(dflt);
+		return dflt;
+	}
+	else if (res == NULL)
+		return res;
+
+	/* add gc_head size */
+	if (PyObject_IS_GC(o)) {
+		PyObject *tmp = res;
+		res = PyNumber_Add(tmp, gc_head_size);
+		Py_DECREF(tmp);
+	}
+	return res;
 }
 
 PyDoc_STRVAR(getsizeof_doc,
-"getsizeof(object) -> int\n\
+"getsizeof(object, default) -> int\n\
 \n\
 Return the size of object in bytes.");
 
@@ -829,32 +860,12 @@
 Clear the internal type lookup cache.");
 
 
-static PyObject *
-sys_compact_freelists(PyObject* self, PyObject* args)
-{
-	size_t isum, ibc, ibf;
-	size_t fsum, fbc, fbf;
-
-	PyInt_CompactFreeList(&ibc, &ibf, &isum);
-	PyFloat_CompactFreeList(&fbc, &fbf, &fsum);
-
-	return Py_BuildValue("(kkk)(kkk)", isum, ibc, ibf,
-					   fsum, fbc, fbf);
-
-}
-
-PyDoc_STRVAR(sys_compact_freelists__doc__,
-"_compact_freelists() -> ((remaing_objects, total_blocks, freed_blocks), ...)\n\
-Compact the free lists of ints and floats.");
-
 static PyMethodDef sys_methods[] = {
 	/* Might as well keep this in alphabetic order */
 	{"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
 	 callstats_doc},
 	{"_clear_type_cache",	sys_clear_type_cache,	  METH_NOARGS,
 	 sys_clear_type_cache__doc__},
-	{"_compact_freelists",	sys_compact_freelists,	  METH_NOARGS,
-	 sys_compact_freelists__doc__},
 	{"_current_frames", sys_current_frames, METH_NOARGS,
 	 current_frames_doc},
 	{"displayhook",	sys_displayhook, METH_O, displayhook_doc},
@@ -889,7 +900,8 @@
 	{"getrefcount",	(PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
 	{"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
 	 getrecursionlimit_doc},
- 	{"getsizeof",	sys_getsizeof,  METH_O, getsizeof_doc},
+	{"getsizeof",   (PyCFunction)sys_getsizeof,
+	 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
 	{"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
 #ifdef MS_WINDOWS
 	{"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,

Modified: python/branches/tlee-ast-optimize/Python/traceback.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/traceback.c	(original)
+++ python/branches/tlee-ast-optimize/Python/traceback.c	Sat Jul 12 06:22:35 2008
@@ -123,7 +123,7 @@
 }
 
 int
-Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno)
+_Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent)
 {
 	int err = 0;
 	FILE *xfp = NULL;
@@ -197,12 +197,27 @@
 		} while (*pLastChar != '\0' && *pLastChar != '\n');
 	}
 	if (i == lineno) {
+		char buf[11];
 		char *p = linebuf;
 		while (*p == ' ' || *p == '\t' || *p == '\014')
 			p++;
-                    err = PyFile_WriteString(p, f);
-                    if (err == 0 && strchr(p, '\n') == NULL)
-                            err = PyFile_WriteString("\n", f);
+
+		/* Write some spaces before the line */
+		strcpy(buf, "          ");
+		assert (strlen(buf) == 10);
+		while (indent > 0) {
+			if(indent < 10)
+				buf[indent] = '\0';
+			err = PyFile_WriteString(buf, f);
+			if (err != 0)
+				break;
+			indent -= 10;
+		}
+
+		if (err == 0)
+			err = PyFile_WriteString(p, f);
+		if (err == 0 && strchr(p, '\n') == NULL)
+			err = PyFile_WriteString("\n", f);
 	}
 	fclose(xfp);
 	return err;
@@ -222,7 +237,7 @@
 	err = PyFile_WriteString(linebuf, f);
 	if (err != 0)
 		return err;
-        return Py_DisplaySourceLine(f, filename, lineno);
+        return _Py_DisplaySourceLine(f, filename, lineno, 4);
 }
 
 static int


More information about the Python-checkins mailing list