[Python-checkins] r68609 - in python/branches/tlee-ast-optimize: Doc/ACKS.txt Doc/Makefile Doc/README.txt Doc/c-api/arg.rst Doc/c-api/buffer.rst Doc/c-api/conversion.rst Doc/c-api/exceptions.rst Doc/c-api/file.rst Doc/c-api/init.rst Doc/c-api/long.rst Doc/c-api/module.rst Doc/c-api/reflection.rst Doc/c-api/sequence.rst Doc/c-api/set.rst Doc/c-api/structures.rst Doc/c-api/sys.rst Doc/c-api/typeobj.rst Doc/data/refcounts.dat Doc/distutils/apiref.rst Doc/distutils/builtdist.rst Doc/distutils/configfile.rst Doc/distutils/packageindex.rst Doc/distutils/setupscript.rst Doc/distutils/uploading.rst Doc/documenting/markup.rst Doc/documenting/rest.rst Doc/extending/building.rst Doc/extending/extending.rst Doc/extending/newtypes.rst Doc/extending/windows.rst Doc/glossary.rst Doc/howto/curses.rst Doc/howto/doanddont.rst Doc/howto/functional.rst Doc/howto/regex.rst Doc/howto/sockets.rst Doc/howto/unicode.rst Doc/howto/urllib2.rst Doc/howto/webservers.rst Doc/includes/mp_distributing.py Doc/install/index.rst Doc/library/2to3.rst Doc/library/abc.rst Doc/library/aifc.rst Doc/library/al.rst Doc/library/ast.rst Doc/library/audioop.rst Doc/library/bastion.rst Doc/library/bdb.rst Doc/library/binascii.rst Doc/library/bsddb.rst Doc/library/bz2.rst Doc/library/cd.rst Doc/library/cmath.rst Doc/library/codeop.rst Doc/library/collections.rst Doc/library/compiler.rst Doc/library/configparser.rst Doc/library/cookielib.rst Doc/library/crypt.rst Doc/library/csv.rst Doc/library/ctypes.rst Doc/library/datetime.rst Doc/library/decimal.rst Doc/library/difflib.rst Doc/library/dircache.rst Doc/library/dis.rst Doc/library/dl.rst Doc/library/email.mime.rst Doc/library/fileinput.rst Doc/library/fl.rst Doc/library/fm.rst Doc/library/fpformat.rst Doc/library/fractions.rst Doc/library/ftplib.rst Doc/library/functions.rst Doc/library/getopt.rst Doc/library/gettext.rst Doc/library/gl.rst Doc/library/gzip.rst Doc/library/hashlib.rst Doc/library/heapq.rst Doc/library/htmllib.rst Doc/library/idle.rst Doc/library/imageop.rst Doc/library/imgfile.rst Doc/library/io.rst Doc/library/itertools.rst Doc/library/jpeg.rst Doc/library/json.rst Doc/library/locale.rst Doc/library/logging.rst Doc/library/macos.rst Doc/library/mailbox.rst Doc/library/marshal.rst Doc/library/math.rst Doc/library/mhlib.rst Doc/library/mmap.rst Doc/library/msvcrt.rst Doc/library/multiprocessing.rst Doc/library/mutex.rst Doc/library/new.rst Doc/library/nntplib.rst Doc/library/numbers.rst Doc/library/operator.rst Doc/library/optparse.rst Doc/library/os.rst Doc/library/ossaudiodev.rst Doc/library/othergui.rst Doc/library/parser.rst Doc/library/pdb.rst Doc/library/pickle.rst Doc/library/popen2.rst Doc/library/profile.rst Doc/library/pydoc.rst Doc/library/pyexpat.rst Doc/library/random.rst Doc/library/re.rst Doc/library/repr.rst Doc/library/rexec.rst Doc/library/rlcompleter.rst Doc/library/robotparser.rst Doc/library/sched.rst Doc/library/sgmllib.rst Doc/library/shutil.rst Doc/library/signal.rst Doc/library/simplexmlrpcserver.rst Doc/library/smtplib.rst Doc/library/socket.rst Doc/library/socketserver.rst Doc/library/sqlite3.rst Doc/library/ssl.rst Doc/library/statvfs.rst Doc/library/stdtypes.rst Doc/library/string.rst Doc/library/stringio.rst Doc/library/subprocess.rst Doc/library/sunaudio.rst Doc/library/sys.rst Doc/library/tempfile.rst Doc/library/tk.rst Doc/library/tkinter.rst Doc/library/trace.rst Doc/library/traceback.rst Doc/library/turtle.rst Doc/library/undoc.rst Doc/library/unicodedata.rst Doc/library/unittest.rst Doc/library/urllib.rst Doc/library/urllib2.rst Doc/library/urlparse.rst Doc/library/warnings.rst Doc/library/webbrowser.rst Doc/library/winsound.rst Doc/library/wsgiref.rst Doc/library/xml.etree.elementtree.rst Doc/library/xmlrpclib.rst Doc/library/zipfile.rst Doc/library/zipimport.rst Doc/library/zlib.rst Doc/license.rst Doc/make.bat Doc/reference/datamodel.rst Doc/reference/expressions.rst Doc/reference/lexical_analysis.rst Doc/reference/simple_stmts.rst Doc/tools Doc/tools/rstlint.py Doc/tools/sphinx-web.py Doc/tools/sphinxext/download.html Doc/tools/sphinxext/layout.html Doc/tools/sphinxext/pyspecific.py Doc/tools/sphinxext/susp-ignored.csv Doc/tools/sphinxext/suspicious.py Doc/tutorial/classes.rst Doc/tutorial/controlflow.rst Doc/tutorial/datastructures.rst Doc/tutorial/errors.rst Doc/tutorial/index.rst Doc/tutorial/inputoutput.rst Doc/tutorial/interpreter.rst Doc/tutorial/introduction.rst Doc/tutorial/modules.rst Doc/tutorial/stdlib.rst Doc/tutorial/stdlib2.rst Doc/tutorial/whatnow.rst Doc/using/cmdline.rst Doc/using/unix.rst Doc/using/windows.rst Doc/whatsnew/2.0.rst Doc/whatsnew/2.1.rst Doc/whatsnew/2.2.rst Doc/whatsnew/2.3.rst Doc/whatsnew/2.4.rst Doc/whatsnew/2.5.rst Doc/whatsnew/2.6.rst Doc/whatsnew/2.7.rst Include/abstract.h Include/object.h Include/opcode.h Include/pymacconfig.h Include/pymath.h Include/pyport.h Include/unicodeobject.h LICENSE Lib/_abcoll.py Lib/ast.py Lib/bdb.py Lib/cgi.py Lib/collections.py Lib/compiler/misc.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/symbols.py Lib/compiler/transformer.py Lib/compiler/visitor.py Lib/ctypes/test/__init__.py Lib/ctypes/util.py Lib/decimal.py Lib/dis.py Lib/distutils/ccompiler.py Lib/distutils/command/register.py Lib/distutils/command/sdist.py Lib/distutils/command/upload.py Lib/distutils/config.py Lib/distutils/dist.py Lib/distutils/msvc9compiler.py Lib/distutils/tests/test_config.py Lib/distutils/tests/test_dist.py Lib/distutils/tests/test_msvc9compiler.py Lib/distutils/tests/test_register.py Lib/distutils/tests/test_sdist.py Lib/distutils/tests/test_upload.py Lib/distutils/util.py Lib/doctest.py Lib/fractions.py Lib/getopt.py Lib/gzip.py Lib/heapq.py Lib/httplib.py Lib/idlelib/NEWS.txt Lib/idlelib/help.txt Lib/idlelib/macosxSupport.py Lib/inspect.py Lib/io.py Lib/lib-tk/ScrolledText.py Lib/lib-tk/tkColorChooser.py Lib/lib2to3 Lib/lib2to3/fixer_base.py Lib/lib2to3/fixer_util.py Lib/lib2to3/fixes/fix_apply.py Lib/lib2to3/fixes/fix_execfile.py Lib/lib2to3/fixes/fix_has_key.py Lib/lib2to3/fixes/fix_import.py Lib/lib2to3/fixes/fix_imports.py Lib/lib2to3/fixes/fix_imports2.py Lib/lib2to3/fixes/fix_intern.py Lib/lib2to3/fixes/fix_isinstance.py Lib/lib2to3/fixes/fix_long.py Lib/lib2to3/fixes/fix_reduce.py Lib/lib2to3/fixes/fix_repr.py Lib/lib2to3/fixes/fix_urllib.py Lib/lib2to3/fixes/fix_xrange.py Lib/lib2to3/main.py Lib/lib2to3/pgen2/driver.py Lib/lib2to3/pygram.py Lib/lib2to3/pytree.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/benchmark.py Lib/lib2to3/tests/data/infinite_recursion.py Lib/lib2to3/tests/data/py3_test_grammar.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_util.py Lib/linecache.py Lib/logging/__init__.py Lib/logging/handlers.py Lib/opcode.py Lib/pdb.py Lib/plat-mac/EasyDialogs.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/macostools.py Lib/plat-mac/videoreader.py Lib/pydoc.py Lib/random.py Lib/re.py Lib/runpy.py Lib/ssl.py Lib/subprocess.py Lib/tarfile.py Lib/test/crashers/iter.py Lib/test/decimaltestdata/extra.decTest Lib/test/list_tests.py Lib/test/pickletester.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_bytes.py Lib/test/test_bz2.py Lib/test/test_capi.py Lib/test/test_cgi.py Lib/test/test_cmd_line_script.py Lib/test/test_collections.py Lib/test/test_datetime.py Lib/test/test_decimal.py Lib/test/test_deque.py Lib/test/test_dict.py Lib/test/test_dis.py Lib/test/test_doctest.py Lib/test/test_file.py Lib/test/test_fileio.py Lib/test/test_fractions.py Lib/test/test_generators.py Lib/test/test_getopt.py Lib/test/test_gzip.py Lib/test/test_hash.py Lib/test/test_hotshot.py Lib/test/test_import.py Lib/test/test_inspect.py Lib/test/test_int.py Lib/test/test_io.py Lib/test/test_iter.py Lib/test/test_itertools.py Lib/test/test_logging.py Lib/test/test_long.py Lib/test/test_macos.py Lib/test/test_os.py Lib/test/test_parser.py Lib/test/test_py3kwarn.py Lib/test/test_set.py Lib/test/test_struct.py Lib/test/test_subprocess.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_textwrap.py Lib/test/test_unittest.py Lib/test/test_urllib2.py Lib/test/test_urllib2_localnet.py Lib/test/test_urllibnet.py Lib/test/test_with.py Lib/test/test_xmlrpc.py Lib/test/test_zipfile.py Lib/test/test_zipimport.py Lib/test/test_zipimport_support.py Lib/textwrap.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/xmlrpclib.py Lib/zipfile.py Mac/IDLE/Makefile.in Mac/Modules/MacOS.c Mac/PythonLauncher/Makefile.in Makefile.pre.in Misc/ACKS Misc/NEWS Misc/build.sh Misc/developers.txt Misc/python.man Modules/_collectionsmodule.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_fileio.c Modules/_hotshot.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/bz2module.c Modules/cPickle.c Modules/dbmmodule.c Modules/gcmodule.c Modules/itertoolsmodule.c Modules/main.c Modules/mathmodule.c Modules/parsermodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/zipimport.c Objects/abstract.c Objects/bytearrayobject.c Objects/dictobject.c Objects/fileobject.c Objects/frameobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/object.c Objects/setobject.c Objects/stringlib/transmogrify.h Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c PC/VC6/_bsddb.dsp PC/VC6/_tkinter.dsp PC/VC6/build_tkinter.py PC/VC6/bz2.dsp PC/VC6/pythoncore.dsp PC/VC6/readme.txt PC/VC6/tcl852.patch PC/VS7.1/pythoncore.vcproj PC/VS7.1/readme.txt PC/VS8.0/build_ssl.bat PC/VS8.0/pyproject.vsprops PC/VS8.0/pythoncore.vcproj PC/_winreg.c PC/example_nt/example.vcproj PC/msvcrtmodule.c PC/os2emx/Makefile PC/os2emx/README.os2emx PC/os2emx/python26.def PC/os2emx/python27.def PC/os2vacpp/makefile PC/os2vacpp/makefile.omk PC/os2vacpp/python.def PC/pyconfig.h PCbuild/build_ssl.bat PCbuild/pythoncore.vcproj Parser/asdl.py Parser/printgrammar.c Python/ast.c Python/ceval.c Python/compile.c Python/getargs.c Python/getcopyright.c Python/getmtime.c Python/graminit.c Python/import.c Python/pythonrun.c Python/sysmodule.c Python/thread.c Python/thread_nt.h README RISCOS/Makefile RISCOS/Python/getmtime_riscos.c Tools/msi/crtlicense.txt Tools/msi/msi.py Tools/msi/uuids.py Tools/pybench/Lists.py Tools/scripts/patchcheck.py configure configure.in pyconfig.h.in setup.py

thomas.lee python-checkins at python.org
Wed Jan 14 13:24:25 CET 2009


Author: thomas.lee
Date: Wed Jan 14 13:24:17 2009
New Revision: 68609

Log:
Merged revisions 67449,67454-67455,67457-67458,67463,67467,67484,67494,67498,67511,67521,67528,67531-67532,67536-67538,67543,67553-67554,67556-67557,67571-67572,67574-67576,67579-67581,67583-67584,67587,67590-67591,67597,67601,67608,67614,67619,67628,67631,67654,67658-67659,67666,67676-67677,67681,67685,67688,67692,67694,67707,67717,67725,67746,67748,67750-67751,67761-67762,67777,67779,67784-67785,67787-67788,67790,67797,67802,67806,67818,67822,67832,67844,67848-67850,67857,67859,67862-67864,67880,67882,67885,67889-67892,67895,67898,67902,67904-67908,67912,67918,67920-67921,67923-67924,67926-67927,67930,67932,67934-67935,67943,67946,67952-67955,67957-67958,67960-67961,67963,67965,67967,67970-67971,67973,67976,67978-67980,67982,67985,67988,67990,67995,68006,68010,68014,68016,68018,68030,68033,68051,68057,68061,68081,68089,68092,68097,68099,68112,68115-68121,68123-68128,68133-68134,68141-68142,68145-68146,68148-68150,68153,68156,68158-68163,68166-68167,68171-68174,68176,68179,68182,68191,68195-68197,68203,68208-68210,68214-68215,68217-68222,68231-68232,68238,68240,68243,68276,68288-68293,68296,68299,68302,68304,68311-68312,68314,68317-68319,68325-68326,68338,68344,68360-68361,68373,68378,68381,68388,68393,68395,68415,68423-68426,68429-68430,68432,68435,68439,68450,68455,68457-68462,68468-68470,68476,68480-68481,68484-68485,68487,68493,68495-68496,68498-68499,68501,68512,68514-68515,68521,68523,68527,68532,68534-68536,68540,68542,68544-68547,68552,68559-68560,68562-68563,68565-68572,68575,68579-68580,68582,68584,68589,68592,68596-68597,68603-68605 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/trunk

................
  r67449 | martin.v.loewis | 2008-11-30 22:08:26 +1100 (Sun, 30 Nov 2008) | 3 lines
  
  Issue #4389: Add icon to the uninstall entry in
  "add-and-remove-programs".
................
  r67454 | benjamin.peterson | 2008-12-01 01:43:23 +1100 (Mon, 01 Dec 2008) | 1 line
  
  note the version that works
................
  r67455 | martin.v.loewis | 2008-12-01 06:28:27 +1100 (Mon, 01 Dec 2008) | 1 line
  
  Issue #4365: Add crtassem.h constants to the msvcrt module.
................
  r67457 | christian.heimes | 2008-12-01 08:16:28 +1100 (Mon, 01 Dec 2008) | 1 line
  
  w# requires Py_ssize_t
................
  r67458 | benjamin.peterson | 2008-12-01 08:46:16 +1100 (Mon, 01 Dec 2008) | 1 line
  
  fix pyspecific extensions that were broken by Sphinx's grand renaming
................
  r67463 | skip.montanaro | 2008-12-01 12:55:22 +1100 (Mon, 01 Dec 2008) | 1 line
  
  typo in comment
................
  r67467 | benjamin.peterson | 2008-12-01 23:52:51 +1100 (Mon, 01 Dec 2008) | 1 line
  
  let people using SVN Sphinx still build the docs
................
  r67484 | christian.heimes | 2008-12-03 11:53:18 +1100 (Wed, 03 Dec 2008) | 2 lines
  
  Issue #4025 again
  Converted a C99 style comment to a C89 style comment (found by MAL).
................
  r67494 | jeffrey.yasskin | 2008-12-03 17:46:45 +1100 (Wed, 03 Dec 2008) | 5 lines
  
  Speed up Python (according to pybench and 2to3-on-itself) by 1-2% by caching
  whether any thread has tracing turned on, which saves one load instruction in
  the fast_next_opcode path in PyEval_EvalFrameEx().  See issue 4477.
................
  r67498 | raymond.hettinger | 2008-12-04 02:42:10 +1100 (Thu, 04 Dec 2008) | 1 line
  
  Backport r67478
................
  r67511 | vinay.sajip | 2008-12-04 10:22:58 +1100 (Thu, 04 Dec 2008) | 1 line
  
  Issue #4384: Added logging integration with warnings module using captureWarnings(). This change includes a NullHandler which does nothing; it will be of use to library developers who want to avoid the "No handlers could be found for logger XXX" message which can appear if the library user doesn't configure logging.
................
  r67521 | christian.heimes | 2008-12-05 01:34:40 +1100 (Fri, 05 Dec 2008) | 1 line
  
  Bumped up 2.6 to 2.7
................
  r67528 | fred.drake | 2008-12-05 05:25:17 +1100 (Fri, 05 Dec 2008) | 4 lines
  
  Issue #1055234: cgi.parse_header(): Fixed parsing of header parameters to
  support unusual filenames (such as those containing semi-colons) in
  Content-Disposition headers.
................
  r67531 | georg.brandl | 2008-12-05 05:54:05 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  Add reference to enumerate() to indices example.
................
  r67532 | georg.brandl | 2008-12-05 05:59:16 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  Add another heapq example.
................
  r67536 | gregory.p.smith | 2008-12-05 07:21:09 +1100 (Fri, 05 Dec 2008) | 3 lines
  
  Adds a subprocess.check_call_output() function to return the output from a
  process on success or raise an exception on error.
................
  r67537 | vinay.sajip | 2008-12-05 07:32:18 +1100 (Fri, 05 Dec 2008) | 1 line
  
  Took Nick Coghlan's advice about importing warnings globally in logging, to avoid the possibility of race conditions: "This could deadlock if a thread spawned as a side effect of importing a module happens to trigger a warning. warnings is pulled into sys.modules as part of the interpreter startup - having a global 'import warnings' shouldn't have any real effect on logging's import time."
................
  r67538 | georg.brandl | 2008-12-05 08:28:16 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  Clarification to avoid confusing output with file descriptors.
................
  r67543 | gregory.p.smith | 2008-12-05 13:27:01 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  rename the new check_call_output to check_output.  its less ugly.
................
  r67553 | georg.brandl | 2008-12-05 18:49:49 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4408: document regex.groups.
................
  r67554 | georg.brandl | 2008-12-05 18:52:26 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4409: fix asterisks looking like footnotes.
................
  r67556 | georg.brandl | 2008-12-05 19:02:17 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4441: improve doc for os.open() flags.
................
  r67557 | georg.brandl | 2008-12-05 19:06:57 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  Add an index entry for "subclassing immutable types".
................
  r67571 | georg.brandl | 2008-12-05 20:13:45 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  Use markup.
................
  r67572 | georg.brandl | 2008-12-05 20:23:14 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4458: recognize "-" as an argument, not a malformed option in gnu_getopt().
................
  r67574 | georg.brandl | 2008-12-05 20:25:32 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4441 followup: Add link to open() docs for Windows.
................
  r67575 | georg.brandl | 2008-12-05 22:34:51 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4544: add `dedent` to textwrap.__all__.
................
  r67576 | georg.brandl | 2008-12-05 23:09:41 +1100 (Fri, 05 Dec 2008) | 2 lines
  
  #4529: fix parser's validation for try-except-finally statements.
................
  r67579 | georg.brandl | 2008-12-06 02:29:39 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  #4517: add "special method" glossary entry and clarify when __getattribute__ is bypassed.
................
  r67580 | georg.brandl | 2008-12-06 02:32:29 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  #4478: document that copyfile() can raise Error.
................
  r67581 | georg.brandl | 2008-12-06 02:42:03 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  #3171: document that *slice are removed in 3k.
................
  r67583 | georg.brandl | 2008-12-06 02:52:20 +1100 (Sat, 06 Dec 2008) | 4 lines
  
  Move __import__ to the bottom of the functions list.
  It doesn't make sense for such a fundamental document to have
  the most obscure function listed at the top.
................
  r67584 | fred.drake | 2008-12-06 02:52:25 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  bump version number
................
  r67587 | fred.drake | 2008-12-06 03:14:18 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  be more specific, and parallel to the py3k branch
................
  r67590 | mark.dickinson | 2008-12-06 04:59:46 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  Issue #4461: Safety check in parsenumber (ast.c)
................
  r67591 | georg.brandl | 2008-12-06 05:00:06 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  Followup to #4511: add link from decorator glossary entry to definition.
................
  r67597 | georg.brandl | 2008-12-06 06:03:19 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  Remove confusing sentence part.
................
  r67601 | mark.dickinson | 2008-12-06 08:55:28 +1100 (Sat, 06 Dec 2008) | 3 lines
  
  Issue #4445: save 3 bytes (on average, on a typical machine) per
  string allocation.
................
  r67608 | georg.brandl | 2008-12-06 22:57:12 +1100 (Sat, 06 Dec 2008) | 2 lines
  
  Follow-up to #4488: document PIPE and STDOUT properly.
................
  r67614 | skip.montanaro | 2008-12-07 04:43:30 +1100 (Sun, 07 Dec 2008) | 2 lines
  
  issue 4483 - dbm build failures on systems with gdbm_compat lib.
................
  r67619 | antoine.pitrou | 2008-12-07 08:29:24 +1100 (Sun, 07 Dec 2008) | 1 line
  
  Issue #4509: bugs in bytearray with exports (buffer protocol)
................
  r67628 | skip.montanaro | 2008-12-07 13:16:00 +1100 (Sun, 07 Dec 2008) | 1 line
  
  muffed the default case
................
  r67631 | georg.brandl | 2008-12-07 22:54:07 +1100 (Sun, 07 Dec 2008) | 2 lines
  
  Add link to the favicon to the docs.
................
  r67654 | georg.brandl | 2008-12-08 09:42:09 +1100 (Mon, 08 Dec 2008) | 2 lines
  
  #4457: rewrite __import__() documentation.
................
  r67658 | martin.v.loewis | 2008-12-08 22:14:57 +1100 (Mon, 08 Dec 2008) | 1 line
  
  Add UUIDs for 2.6.1 and 2.6.2.
................
  r67659 | martin.v.loewis | 2008-12-08 22:15:35 +1100 (Mon, 08 Dec 2008) | 1 line
  
  Consider micro version for name of CHM file.
................
  r67666 | jeffrey.yasskin | 2008-12-09 05:55:24 +1100 (Tue, 09 Dec 2008) | 3 lines
  
  Issue 4597: Fix several cases in EvalFrameEx where an exception could be
  "raised" without setting x, err, or why to let the eval loop know.
................
  r67676 | benjamin.peterson | 2008-12-09 13:03:03 +1100 (Tue, 09 Dec 2008) | 1 line
  
  specify how things are copied
................
  r67677 | benjamin.peterson | 2008-12-09 13:05:11 +1100 (Tue, 09 Dec 2008) | 1 line
  
  revert unrelated change to installer script
................
  r67681 | jeremy.hylton | 2008-12-10 08:03:10 +1100 (Wed, 10 Dec 2008) | 2 lines
  
  Add simple unittests for Request
................
  r67685 | jeffrey.yasskin | 2008-12-10 18:35:02 +1100 (Wed, 10 Dec 2008) | 2 lines
  
  Update Misc/NEWS for r67666.
................
  r67688 | amaury.forgeotdarc | 2008-12-11 10:22:49 +1100 (Thu, 11 Dec 2008) | 6 lines
  
  #4559: When a context manager's __exit__() method returns an object whose
  conversion to bool raises an exception, 'with' loses that exception. 
  
  Reviewed by Jeffrey Yasskin.
  Already ported to 2.5, will port to 2.6 and 3.0
................
  r67692 | amaury.forgeotdarc | 2008-12-11 11:03:42 +1100 (Thu, 11 Dec 2008) | 2 lines
  
  #1030250: correctly pass the dry_run option to the mkpath() function.
................
  r67694 | facundo.batista | 2008-12-11 15:19:46 +1100 (Thu, 11 Dec 2008) | 6 lines
  
  
  Issue #4084: Fix max, min, max_mag and min_mag Decimal methods to
  give correct results in the case where one argument is a quiet NaN
  and the other is a finite number that requires rounding.
  Thanks Mark Dickinson.
................
  r67707 | mark.dickinson | 2008-12-12 06:28:08 +1100 (Fri, 12 Dec 2008) | 5 lines
  
  Issues #3167, #3682: tests for math.log and math.log10 were failing on
  Solaris and OpenBSD.  Fix this by handling special values and domain
  errors directly in mathmodule.c, passing only positive nonspecial floats
  to the system log/log10.
................
  r67717 | lars.gustaebel | 2008-12-13 00:58:03 +1100 (Sat, 13 Dec 2008) | 2 lines
  
  Issue #4616: TarFile.utime(): Restore directory times on Windows.
................
  r67725 | benjamin.peterson | 2008-12-13 15:02:20 +1100 (Sat, 13 Dec 2008) | 1 line
  
  fix incorrect example
................
  r67746 | antoine.pitrou | 2008-12-14 10:12:30 +1100 (Sun, 14 Dec 2008) | 3 lines
  
  Issue #4163: Use unicode-friendly word splitting in the textwrap functions when given an unicode string.
................
  r67748 | benjamin.peterson | 2008-12-14 12:46:11 +1100 (Sun, 14 Dec 2008) | 1 line
  
  remove has_key usage
................
  r67750 | nick.coghlan | 2008-12-14 21:54:50 +1100 (Sun, 14 Dec 2008) | 1 line
  
  Fix several issues relating to access to source code inside zipfiles. Initial work by Alexander Belopolsky. See Misc/NEWS in this checkin for details.
................
  r67751 | nick.coghlan | 2008-12-14 22:09:40 +1100 (Sun, 14 Dec 2008) | 1 line
  
  Add file that was missed from r67750
................
  r67761 | benjamin.peterson | 2008-12-15 04:26:04 +1100 (Mon, 15 Dec 2008) | 1 line
  
  fix missing bracket
................
  r67762 | antoine.pitrou | 2008-12-15 04:40:51 +1100 (Mon, 15 Dec 2008) | 3 lines
  
  Backport r67759 (fix io.IncrementalNewlineDecoder for UTF-16 et al.).
................
  r67777 | antoine.pitrou | 2008-12-15 09:33:55 +1100 (Mon, 15 Dec 2008) | 3 lines
  
  try to fix failure in test_bad_address on some buildbots
................
  r67779 | antoine.pitrou | 2008-12-15 11:39:51 +1100 (Mon, 15 Dec 2008) | 1 line
  
  modify other occurrence of test_bad_address
................
  r67784 | georg.brandl | 2008-12-15 19:33:58 +1100 (Mon, 15 Dec 2008) | 2 lines
  
  #4446: document "platforms" argument for setup().
................
  r67785 | georg.brandl | 2008-12-15 19:36:11 +1100 (Mon, 15 Dec 2008) | 2 lines
  
  #4611: fix typo.
................
  r67787 | georg.brandl | 2008-12-15 19:58:59 +1100 (Mon, 15 Dec 2008) | 2 lines
  
  #4578: fix has_key() usage in compiler package.
................
  r67788 | georg.brandl | 2008-12-15 20:07:39 +1100 (Mon, 15 Dec 2008) | 2 lines
  
  #4568: remove limitation in varargs callback example.
................
  r67790 | nick.coghlan | 2008-12-15 22:41:05 +1100 (Mon, 15 Dec 2008) | 1 line
  
  Issue #4197: Fix the remaining part of the doctest-in-zipfile problem by giving linecache access to the module globals when available
................
  r67797 | amaury.forgeotdarc | 2008-12-16 08:47:57 +1100 (Tue, 16 Dec 2008) | 4 lines
  
  #3954: Fix error handling code in _hotshot.logreader
  
  Will port to 2.6. hotshot was deleted from python 3.
................
  r67802 | amaury.forgeotdarc | 2008-12-16 09:29:14 +1100 (Tue, 16 Dec 2008) | 4 lines
  
  #3632: the "pyo" macro from gdbinit can now run when the GIL is released.
  
  Patch by haypo.
................
  r67806 | benjamin.peterson | 2008-12-16 14:35:28 +1100 (Tue, 16 Dec 2008) | 111 lines
  
  Merged revisions 67427,67431,67433,67435,67630,67652,67656-67657,67674-67675,67678-67679,67705-67706,67716,67723,67765-67771,67774,67776,67778 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r67427 | benjamin.peterson | 2008-11-28 16:07:41 -0600 (Fri, 28 Nov 2008) | 1 line
    
    fix spelling in comment
  ........
    r67431 | benjamin.peterson | 2008-11-28 17:14:08 -0600 (Fri, 28 Nov 2008) | 1 line
    
    add a scripts directory; move things to it
  ........
    r67433 | benjamin.peterson | 2008-11-28 17:18:48 -0600 (Fri, 28 Nov 2008) | 1 line
    
    run svneol.py
  ........
    r67435 | benjamin.peterson | 2008-11-28 17:25:03 -0600 (Fri, 28 Nov 2008) | 1 line
    
    rename pre/post_order_mapping to pre/post_order_heads
  ........
    r67630 | alexandre.vassalotti | 2008-12-06 21:51:56 -0600 (Sat, 06 Dec 2008) | 2 lines
    
    Fix typo in the urllib2.HTTPDigestAuthHandler fixer.
  ........
    r67652 | armin.ronacher | 2008-12-07 15:39:43 -0600 (Sun, 07 Dec 2008) | 5 lines
    
    Added a fixer that cleans up a tuple argument to isinstance after the tokens
    in it were fixed.  This is mainly used to remove double occurrences of
    tokens as a leftover of the long -> int / unicode -> str conversion.
  ........
    r67656 | armin.ronacher | 2008-12-07 16:54:16 -0600 (Sun, 07 Dec 2008) | 3 lines
    
    Added missing copyright fo 2to3 fix_isinstance.
  ........
    r67657 | armin.ronacher | 2008-12-07 18:29:35 -0600 (Sun, 07 Dec 2008) | 3 lines
    
    2to3: intern and reduce fixes now add the imports if missing.  Because that is a common task the fixer_util module now has a function "touch_import" that adds imports if missing.
  ........
    r67674 | benjamin.peterson | 2008-12-08 19:58:11 -0600 (Mon, 08 Dec 2008) | 1 line
    
    copy permission bits when making backup files #4602
  ........
    r67675 | benjamin.peterson | 2008-12-08 19:59:11 -0600 (Mon, 08 Dec 2008) | 1 line
    
    add forgotten import
  ........
    r67678 | benjamin.peterson | 2008-12-08 20:08:30 -0600 (Mon, 08 Dec 2008) | 1 line
    
    fix #4602 for real
  ........
    r67679 | armin.ronacher | 2008-12-09 00:54:03 -0600 (Tue, 09 Dec 2008) | 3 lines
    
    Removed redudant code from the 2to3 long fixer.  This fixes #4590.
  ........
    r67705 | benjamin.peterson | 2008-12-11 13:04:08 -0600 (Thu, 11 Dec 2008) | 1 line
    
    put trailers after a range call after the list()
  ........
    r67706 | benjamin.peterson | 2008-12-11 13:17:57 -0600 (Thu, 11 Dec 2008) | 1 line
    
    add html related modules to the fix_imports mapping
  ........
    r67716 | benjamin.peterson | 2008-12-11 22:16:47 -0600 (Thu, 11 Dec 2008) | 1 line
    
    consolidate tests
  ........
    r67723 | benjamin.peterson | 2008-12-12 19:49:31 -0600 (Fri, 12 Dec 2008) | 1 line
    
    fix name
  ........
    r67765 | benjamin.peterson | 2008-12-14 14:05:05 -0600 (Sun, 14 Dec 2008) | 1 line
    
    run fix_isinstance after fix_long and fix_unicode
  ........
    r67766 | benjamin.peterson | 2008-12-14 14:13:05 -0600 (Sun, 14 Dec 2008) | 1 line
    
    use run_order instead of order
  ........
    r67767 | benjamin.peterson | 2008-12-14 14:28:12 -0600 (Sun, 14 Dec 2008) | 1 line
    
    don't retain parenthesis if there is only one item left
  ........
    r67768 | benjamin.peterson | 2008-12-14 14:32:30 -0600 (Sun, 14 Dec 2008) | 1 line
    
    use insert_child()
  ........
    r67769 | benjamin.peterson | 2008-12-14 14:59:10 -0600 (Sun, 14 Dec 2008) | 1 line
    
    parenthesize doesn't belong in pygram or FixerBase
  ........
    r67770 | alexandre.vassalotti | 2008-12-14 15:15:36 -0600 (Sun, 14 Dec 2008) | 2 lines
    
    Fix typo: html.paser -> html.parser.
  ........
    r67771 | benjamin.peterson | 2008-12-14 15:22:09 -0600 (Sun, 14 Dec 2008) | 1 line
    
    altering .children needs to call changed()
  ........
    r67774 | benjamin.peterson | 2008-12-14 15:55:38 -0600 (Sun, 14 Dec 2008) | 1 line
    
    employ an evil hack to fix multiple names in the same import statement
  ........
    r67776 | benjamin.peterson | 2008-12-14 16:22:38 -0600 (Sun, 14 Dec 2008) | 1 line
    
    make a common mixin class for Test_imports and friends
  ........
    r67778 | alexandre.vassalotti | 2008-12-14 17:48:20 -0600 (Sun, 14 Dec 2008) | 2 lines
    
    Make fix_imports refactor multiple imports as.
  ........
................
  r67818 | antoine.pitrou | 2008-12-17 11:38:28 +1100 (Wed, 17 Dec 2008) | 3 lines
  
  Issue #2183: Simplify and optimize bytecode for list comprehensions.
................
  r67822 | mark.dickinson | 2008-12-18 03:14:37 +1100 (Thu, 18 Dec 2008) | 4 lines
  
  Issue #3439: add bit_length method to int and long.
  Thanks Fredrik Johansson and Victor Stinner for code,
  Raymond Hettinger for review.
................
  r67832 | antoine.pitrou | 2008-12-18 09:46:54 +1100 (Thu, 18 Dec 2008) | 4 lines
  
  Issue #2467: gc.DEBUG_STATS reports invalid elapsed times.
  Patch by Neil Schemenauer, very slightly modified.
................
  r67844 | mark.dickinson | 2008-12-19 06:46:21 +1100 (Fri, 19 Dec 2008) | 3 lines
  
  Issue 4692: bogus 'Make' in Makefile.pre.in; replace with '$MAKE'.
  Thanks Ned Deily.
................
  r67848 | benjamin.peterson | 2008-12-19 13:28:56 +1100 (Fri, 19 Dec 2008) | 1 line
  
  fix typo
................
  r67849 | benjamin.peterson | 2008-12-19 13:31:35 +1100 (Fri, 19 Dec 2008) | 1 line
  
  _call_method -> _callmethod and _get_value to _getvalue
................
  r67850 | raymond.hettinger | 2008-12-19 20:06:07 +1100 (Fri, 19 Dec 2008) | 9 lines
  
  Fix-up and clean-up docs for int.bit_length().
  
  * Replace dramatic footnote with in-line comment about possible round-off errors in logarithms of large numbers.
  * Add comments to the pure python code equivalent.
  * replace floor() with int() in the mathematical equivalent so the type is correct (should be an int, not a float).
  * add abs() to the mathematical equivalent so that it matches the previous line that it is supposed to be equivalent to.
  * make one combined example with a negative input.
................
  r67857 | mark.dickinson | 2008-12-20 04:46:51 +1100 (Sat, 20 Dec 2008) | 2 lines
  
  Fix typo in Python equivalent for bit_length.
................
  r67859 | amaury.forgeotdarc | 2008-12-20 09:56:48 +1100 (Sat, 20 Dec 2008) | 4 lines
  
  #4700: crtlicense.txt is displayed by the license() command and should be kept ascii-only.
  
  Will port to 3.0
................
  r67862 | benjamin.peterson | 2008-12-20 13:48:02 +1100 (Sat, 20 Dec 2008) | 1 line
  
  copy sentence from docstring
................
  r67863 | benjamin.peterson | 2008-12-20 13:51:26 +1100 (Sat, 20 Dec 2008) | 1 line
  
  add headings
................
  r67864 | benjamin.peterson | 2008-12-20 13:57:19 +1100 (Sat, 20 Dec 2008) | 1 line
  
  beef up docstring
................
  r67880 | benjamin.peterson | 2008-12-21 09:49:24 +1100 (Sun, 21 Dec 2008) | 1 line
  
  remove redundant sentence
................
  r67882 | benjamin.peterson | 2008-12-21 09:59:49 +1100 (Sun, 21 Dec 2008) | 1 line
  
  add some recent releases to the list
................
  r67885 | benjamin.peterson | 2008-12-21 10:48:54 +1100 (Sun, 21 Dec 2008) | 1 line
  
  silence annoying DeprecationWarning
................
  r67889 | benjamin.peterson | 2008-12-21 12:04:32 +1100 (Sun, 21 Dec 2008) | 1 line
  
  sphinx.web is long gone
................
  r67890 | benjamin.peterson | 2008-12-21 12:12:26 +1100 (Sun, 21 Dec 2008) | 1 line
  
  update readme
................
  r67891 | benjamin.peterson | 2008-12-21 12:14:47 +1100 (Sun, 21 Dec 2008) | 1 line
  
  there are way too many places which need to have the current version added
................
  r67892 | benjamin.peterson | 2008-12-21 12:29:32 +1100 (Sun, 21 Dec 2008) | 9 lines
  
  Merged revisions 67809 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r67809 | benjamin.peterson | 2008-12-15 21:54:45 -0600 (Mon, 15 Dec 2008) | 1 line
    
    fix logic error
  ........
................
  r67895 | neal.norwitz | 2008-12-22 01:28:32 +1100 (Mon, 22 Dec 2008) | 2 lines
  
  Add Tarek for work on distutils.
................
  r67898 | benjamin.peterson | 2008-12-22 08:00:53 +1100 (Mon, 22 Dec 2008) | 1 line
  
  compute DISTVERSION with patchlevel.py
................
  r67902 | benjamin.peterson | 2008-12-23 07:16:25 +1100 (Tue, 23 Dec 2008) | 1 line
  
  add py3k warnings to frame.f_exc_*
................
  r67904 | benjamin.peterson | 2008-12-23 07:44:58 +1100 (Tue, 23 Dec 2008) | 1 line
  
  less attitude
................
  r67905 | benjamin.peterson | 2008-12-23 07:51:15 +1100 (Tue, 23 Dec 2008) | 1 line
  
  fix #4720: the format to PyArg_ParseTupleAndKeywords can now start with '|'
................
  r67906 | benjamin.peterson | 2008-12-23 07:52:53 +1100 (Tue, 23 Dec 2008) | 1 line
  
  add NEWS note
................
  r67907 | benjamin.peterson | 2008-12-23 09:12:19 +1100 (Tue, 23 Dec 2008) | 1 line
  
  silence compiler warning
................
  r67908 | skip.montanaro | 2008-12-23 14:30:15 +1100 (Tue, 23 Dec 2008) | 4 lines
  
  As a result of a regression that snuck into 2.5.3 add a test case that
  ensures that when you try to read from a file opened for writing an IOError
  is raised.
................
  r67912 | georg.brandl | 2008-12-23 23:37:21 +1100 (Tue, 23 Dec 2008) | 2 lines
  
  Fix missing "svn" command.
................
  r67918 | georg.brandl | 2008-12-24 02:44:25 +1100 (Wed, 24 Dec 2008) | 2 lines
  
  Markup fix.
................
  r67920 | benjamin.peterson | 2008-12-24 07:09:28 +1100 (Wed, 24 Dec 2008) | 1 line
  
  use a global variable, so the compiler doesn't optimize the assignment out
................
  r67921 | benjamin.peterson | 2008-12-24 07:12:33 +1100 (Wed, 24 Dec 2008) | 1 line
  
  make global static
................
  r67923 | benjamin.peterson | 2008-12-25 02:10:27 +1100 (Thu, 25 Dec 2008) | 1 line
  
  #4736 BufferRWPair.closed shouldn't try to call another property as a function
................
  r67924 | benjamin.peterson | 2008-12-25 03:10:05 +1100 (Thu, 25 Dec 2008) | 1 line
  
  pretend exceptions don't exist a while longer
................
  r67926 | tarek.ziade | 2008-12-25 06:10:05 +1100 (Thu, 25 Dec 2008) | 1 line
  
  fixed #4400 : distutils .pypirc default generated file was broken.
................
  r67927 | benjamin.peterson | 2008-12-27 10:26:30 +1100 (Sat, 27 Dec 2008) | 1 line
  
  python version is included in file name now
................
  r67930 | hirokazu.yamamoto | 2008-12-27 15:19:48 +1100 (Sat, 27 Dec 2008) | 2 lines
  
  Issue #4740: Use HIGHEST_PROTOCOL in pickle test.
  (There is no behavior difference in 2.x because HIGHEST_PROTOCOL == 2)
................
  r67932 | alexandre.vassalotti | 2008-12-27 17:36:10 +1100 (Sat, 27 Dec 2008) | 5 lines
  
  Remove unnecessary casts related to unicode_decode_call_errorhandler.
  Make the _PyUnicode_Resize macro a static function.
  
  These changes are needed to avoid breaking strict aliasing rules. 
................
  r67934 | alexandre.vassalotti | 2008-12-27 18:08:47 +1100 (Sat, 27 Dec 2008) | 4 lines
  
  Fix issue #4730: cPickle corrupts high-unicode strings.
  Update outdated copy of PyUnicode_EncodeRawUnicodeEscape.
  Add a test case.
................
  r67935 | alexandre.vassalotti | 2008-12-27 18:13:01 +1100 (Sat, 27 Dec 2008) | 2 lines
  
  Add Misc/NEWS entry for r67934.
................
  r67943 | alexandre.vassalotti | 2008-12-27 21:02:59 +1100 (Sat, 27 Dec 2008) | 2 lines
  
  Fix bogus unicode tests in pickletester.
................
  r67946 | antoine.pitrou | 2008-12-28 02:43:12 +1100 (Sun, 28 Dec 2008) | 4 lines
  
  Issue #4756: zipfile.is_zipfile() now supports file-like objects.
  Patch by Gabriel Genellina.
................
  r67952 | georg.brandl | 2008-12-28 04:42:40 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  #4752: actually use custom handler in example.
................
  r67953 | georg.brandl | 2008-12-28 05:20:04 +1100 (Sun, 28 Dec 2008) | 3 lines
  
  Patch #4739 by David Laban: add symbols to pydoc help topics,
  so that ``help('@')`` works as expected.
................
  r67954 | benjamin.peterson | 2008-12-28 05:24:11 +1100 (Sun, 28 Dec 2008) | 1 line
  
  #4748 lambda generators shouldn't return values
................
  r67955 | georg.brandl | 2008-12-28 05:27:53 +1100 (Sun, 28 Dec 2008) | 3 lines
  
  Follow-up to r67746 in order to restore backwards-compatibility for
  those who (monkey-)patch TextWrapper.wordsep_re with a custom RE.
................
  r67957 | georg.brandl | 2008-12-28 05:49:19 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  #4754: improve winsound documentation.
................
  r67958 | georg.brandl | 2008-12-28 06:02:59 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  #4682: 'b' is actually unsigned char.
................
  r67960 | georg.brandl | 2008-12-28 06:04:44 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  #4695: fix backslashery.
................
  r67961 | georg.brandl | 2008-12-28 06:06:04 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  Use :samp: role.
................
  r67963 | georg.brandl | 2008-12-28 06:11:15 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  #4671: document that pydoc imports modules.
................
  r67965 | antoine.pitrou | 2008-12-28 07:34:52 +1100 (Sun, 28 Dec 2008) | 3 lines
  
  Issue #4677: add two list comprehension tests to pybench.
................
  r67967 | benjamin.peterson | 2008-12-28 09:18:58 +1100 (Sun, 28 Dec 2008) | 1 line
  
  fix markup
................
  r67970 | alexandre.vassalotti | 2008-12-28 12:52:58 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  Fix name mangling of PyUnicode_ClearFreeList.
................
  r67971 | alexandre.vassalotti | 2008-12-28 13:10:35 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  Sort UCS-2/UCS-4 name mangling list.
................
  r67973 | alexandre.vassalotti | 2008-12-28 13:58:22 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  Document Py_VaBuildValue.
................
  r67976 | georg.brandl | 2008-12-28 22:54:53 +1100 (Sun, 28 Dec 2008) | 7 lines
  
  Backport r67974: 
  
  #4759: allow None as first argument of bytearray.translate(), for consistency with bytes.translate().
  
  Also fix segfault for bytearray.translate(x, None) -- will backport this part to 3.0 and 2.6.
................
  r67978 | georg.brandl | 2008-12-28 22:58:49 +1100 (Sun, 28 Dec 2008) | 2 lines
  
  #4731: clarify message about missing module prerequisites.
................
  r67979 | antoine.pitrou | 2008-12-29 01:09:36 +1100 (Mon, 29 Dec 2008) | 3 lines
  
  Issue #4444: Allow assertRaises() to be used as a context handler.
................
  r67980 | antoine.pitrou | 2008-12-29 01:24:29 +1100 (Mon, 29 Dec 2008) | 1 line
  
  wrong version number in doc changes committed in r67979
................
  r67982 | benjamin.peterson | 2008-12-29 02:37:31 +1100 (Mon, 29 Dec 2008) | 1 line
  
  fix WORD_BIGEDIAN declaration in Universal builds; fixes #4060 and #4728
................
  r67985 | antoine.pitrou | 2008-12-29 03:01:11 +1100 (Mon, 29 Dec 2008) | 4 lines
  
  Issue #2153: modernize coding style of unittest.py, remove obsolete compatibility stuff.
  Patch by Virgil Dupras.
................
  r67988 | ronald.oussoren | 2008-12-29 06:40:56 +1100 (Mon, 29 Dec 2008) | 1 line
  
  Issue4064: architecture string for universal builds on OSX
................
  r67990 | ronald.oussoren | 2008-12-29 06:50:40 +1100 (Mon, 29 Dec 2008) | 3 lines
  
  Update the fix for issue4064 to deal correctly with all three variants of
  universal builds that are presented by the configure script.
................
  r67995 | benjamin.peterson | 2008-12-29 08:16:07 +1100 (Mon, 29 Dec 2008) | 1 line
  
  #4763 PyErr_ExceptionMatches won't blow up with NULL arguments
................
  r68006 | martin.v.loewis | 2008-12-30 02:51:01 +1100 (Tue, 30 Dec 2008) | 2 lines
  
  Issue #3248: Allow placing ScrolledText in a PanedWindow.
................
  r68010 | martin.v.loewis | 2008-12-30 03:22:25 +1100 (Tue, 30 Dec 2008) | 2 lines
  
  Issue #3767: Convert Tk object to string in tkColorChooser.
................
  r68014 | benjamin.peterson | 2008-12-30 04:47:42 +1100 (Tue, 30 Dec 2008) | 1 line
  
  #4764 set IOError.filename when trying to open a directory on POSIX platforms
................
  r68016 | benjamin.peterson | 2008-12-30 04:56:58 +1100 (Tue, 30 Dec 2008) | 1 line
  
  #4764 in io.open, set IOError.filename when trying to open a directory on POSIX platforms
................
  r68018 | martin.v.loewis | 2008-12-30 05:17:34 +1100 (Tue, 30 Dec 2008) | 2 lines
  
  Issue #1040026: Fix os.times result on systems where HZ is incorrect.
................
  r68030 | benjamin.peterson | 2008-12-30 08:38:14 +1100 (Tue, 30 Dec 2008) | 1 line
  
  fix French
................
  r68033 | tarek.ziade | 2008-12-30 09:23:53 +1100 (Tue, 30 Dec 2008) | 1 line
  
  fixed #4646 : distutils was choking on empty options arg in the setup function.
................
  r68051 | nick.coghlan | 2008-12-30 12:18:48 +1100 (Tue, 30 Dec 2008) | 1 line
  
  Issue #4701: implicitly call PyType_Ready from PyObject_Hash
................
  r68057 | vinay.sajip | 2008-12-30 18:01:25 +1100 (Tue, 30 Dec 2008) | 1 line
  
  Minor documentation change relating to NullHandler.
................
  r68061 | georg.brandl | 2008-12-30 21:15:49 +1100 (Tue, 30 Dec 2008) | 2 lines
  
  #4778: attributes can't be called.
................
  r68081 | tarek.ziade | 2008-12-31 10:03:41 +1100 (Wed, 31 Dec 2008) | 1 line
  
  Fixed #4702: Throwing DistutilsPlatformError instead of IOError under win32 if MSVC is not found
................
  r68089 | benjamin.peterson | 2008-12-31 14:37:51 +1100 (Wed, 31 Dec 2008) | 1 line
  
  #4788 qualify some bare except clauses
................
  r68092 | benjamin.peterson | 2008-12-31 15:08:55 +1100 (Wed, 31 Dec 2008) | 1 line
  
  fix name collision issues
................
  r68097 | hirokazu.yamamoto | 2008-12-31 16:24:37 +1100 (Wed, 31 Dec 2008) | 1 line
  
  Fixed compile error on windows.
................
  r68099 | hirokazu.yamamoto | 2008-12-31 16:47:19 +1100 (Wed, 31 Dec 2008) | 1 line
  
  Just inserted blank line.
................
  r68112 | benjamin.peterson | 2009-01-01 10:48:39 +1100 (Thu, 01 Jan 2009) | 1 line
  
  #4795 inspect.isgeneratorfunction() should return False instead of None
................
  r68115 | benjamin.peterson | 2009-01-01 15:04:41 +1100 (Thu, 01 Jan 2009) | 1 line
  
  simplfy code
................
  r68116 | georg.brandl | 2009-01-01 22:46:51 +1100 (Thu, 01 Jan 2009) | 2 lines
  
  #4100: note that element children are not necessarily present on "start" events.
................
  r68117 | georg.brandl | 2009-01-01 22:53:55 +1100 (Thu, 01 Jan 2009) | 2 lines
  
  #4156: make clear that "protocol" is to be replaced with the protocol name.
................
  r68118 | georg.brandl | 2009-01-01 23:00:19 +1100 (Thu, 01 Jan 2009) | 2 lines
  
  #4185: clarify escape behavior of replacement strings.
................
  r68119 | georg.brandl | 2009-01-01 23:09:40 +1100 (Thu, 01 Jan 2009) | 3 lines
  
  #4222: document dis.findlabels() and dis.findlinestarts() and
  put them into dis.__all__.
................
  r68120 | georg.brandl | 2009-01-01 23:15:31 +1100 (Thu, 01 Jan 2009) | 4 lines
  
  #4228: Pack negative values the same way as 2.4 
  in struct's L format.
................
  r68121 | georg.brandl | 2009-01-01 23:43:33 +1100 (Thu, 01 Jan 2009) | 2 lines
  
  Point to types module in new module deprecation notice.
................
  r68123 | georg.brandl | 2009-01-01 23:52:29 +1100 (Thu, 01 Jan 2009) | 2 lines
  
  #4784: ... on three counts ...
................
  r68124 | georg.brandl | 2009-01-01 23:53:19 +1100 (Thu, 01 Jan 2009) | 2 lines
  
  #4782: Fix markup error that hid load() and loads().
................
  r68125 | georg.brandl | 2009-01-02 00:02:09 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  #4776: add data_files and package_dir arguments.
................
  r68126 | georg.brandl | 2009-01-02 00:05:13 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  Handlers are in the `logging.handlers` module.
................
  r68127 | georg.brandl | 2009-01-02 00:14:49 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  #4767: Use correct submodules for all MIME classes.
................
  r68128 | antoine.pitrou | 2009-01-02 01:11:22 +1100 (Fri, 02 Jan 2009) | 3 lines
  
  Issue #3680: Reference cycles created through a dict, set or deque iterator did not get collected.
................
  r68133 | antoine.pitrou | 2009-01-02 02:38:03 +1100 (Fri, 02 Jan 2009) | 1 line
  
  fill in actual issue number in tests
................
  r68134 | hirokazu.yamamoto | 2009-01-02 02:45:39 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  Issue #4797: IOError.filename was not set when _fileio.FileIO failed to open
  file with `str' filename on Windows.
................
  r68141 | benjamin.peterson | 2009-01-02 03:43:12 +1100 (Fri, 02 Jan 2009) | 1 line
  
  fix highlighting
................
  r68142 | benjamin.peterson | 2009-01-02 04:29:49 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  welcome to 2009, Python!
................
  r68145 | amaury.forgeotdarc | 2009-01-02 11:03:54 +1100 (Fri, 02 Jan 2009) | 5 lines
  
  #4801 _collections module fails to build on cygwin.
  
  _PyObject_GC_TRACK is the macro version of PyObject_GC_Track, 
  and according to documentation it should not be used for extension modules.
................
  r68146 | ronald.oussoren | 2009-01-02 21:44:46 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  Fix for issue4472: "configure --enable-shared doesn't work on OSX"
................
  r68148 | ronald.oussoren | 2009-01-02 21:48:31 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  Forgot to add a NEWS item in my previous checkin
................
  r68149 | ronald.oussoren | 2009-01-02 21:50:48 +1100 (Fri, 02 Jan 2009) | 2 lines
  
  Fix for issue4780
................
  r68150 | ronald.oussoren | 2009-01-02 22:46:05 +1100 (Fri, 02 Jan 2009) | 1 line
  
  Fix for issue 3433
................
  r68153 | ronald.oussoren | 2009-01-02 23:59:32 +1100 (Fri, 02 Jan 2009) | 10 lines
  
  Fix for issue3559: No preferences menu in IDLE on OSX
  
  1) Add a comment to the help file to that points to the 
     preferences menu.
  
  2) An earlier checkin tried to detect Tk >= 8.10.14,
     but did this in the wrong way. The end result of this
     was that the IDLE->Preferences... menu got surpressed
     when using the system version of Tcl/Tk
................
  r68156 | ronald.oussoren | 2009-01-03 01:10:20 +1100 (Sat, 03 Jan 2009) | 1 line
  
  Fix for issue1594
................
  r68158 | ronald.oussoren | 2009-01-03 01:46:19 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Fix for issue 900949
................
  r68159 | ronald.oussoren | 2009-01-03 01:48:17 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Fix for issue 1627952
................
  r68160 | ronald.oussoren | 2009-01-03 01:52:09 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Fix for issue r1737832
................
  r68161 | ronald.oussoren | 2009-01-03 02:00:05 +1100 (Sat, 03 Jan 2009) | 3 lines
  
  Fix for issue 1149804
................
  r68162 | ronald.oussoren | 2009-01-03 02:06:00 +1100 (Sat, 03 Jan 2009) | 3 lines
  
  Fix for issue 4472 is incompatible with Cygwin, this patch
  should fix that.
................
  r68163 | ronald.oussoren | 2009-01-03 02:25:36 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Fix for issues #841800 and #900506
................
  r68166 | benjamin.peterson | 2009-01-03 05:26:23 +1100 (Sat, 03 Jan 2009) | 1 line
  
  document PyMemberDef
................
  r68167 | vinay.sajip | 2009-01-03 05:53:04 +1100 (Sat, 03 Jan 2009) | 1 line
  
  Minor documentation changes relating to NullHandler, the module used for handlers and references to ConfigParser.
................
  r68171 | georg.brandl | 2009-01-03 07:25:14 +1100 (Sat, 03 Jan 2009) | 3 lines
  
  #4811: fix markup glitches (mostly remains of the conversion),
  found by Gabriel Genellina.
................
  r68172 | martin.v.loewis | 2009-01-03 07:32:55 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Issue #4075: Use OutputDebugStringW in Py_FatalError.
................
  r68173 | martin.v.loewis | 2009-01-03 07:40:14 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Issue #4051: Prevent conflict of UNICODE macros in cPickle.
................
  r68174 | benjamin.peterson | 2009-01-03 07:47:27 +1100 (Sat, 03 Jan 2009) | 1 line
  
  fix compilation on non-Windows platforms
................
  r68176 | andrew.kuchling | 2009-01-03 08:00:35 +1100 (Sat, 03 Jan 2009) | 1 line
  
  Add various items
................
  r68179 | raymond.hettinger | 2009-01-03 08:26:45 +1100 (Sat, 03 Jan 2009) | 1 line
  
  Issue #4615.  Document how to use itertools for de-duping.
................
  r68182 | mark.dickinson | 2009-01-03 10:07:08 +1100 (Sat, 03 Jan 2009) | 4 lines
  
  Issue #4812: add missing underscore prefix to some internal-use-only
  constants in the decimal module.  (Dec_0 becomes _Dec_0, etc.)
................
  r68191 | mark.dickinson | 2009-01-03 23:07:20 +1100 (Sat, 03 Jan 2009) | 2 lines
  
  Issue #4812:  further renaming of internal Decimal constants, for clarity.
................
  r68195 | georg.brandl | 2009-01-04 00:45:15 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Remove useless string literal.
................
  r68196 | georg.brandl | 2009-01-04 01:29:53 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Fix indentation.
................
  r68197 | benjamin.peterson | 2009-01-04 03:34:02 +1100 (Sun, 04 Jan 2009) | 55 lines
  
  Merged revisions 67900-67901,67919,67928,67984,67991-67993,68106-68108,68110 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r67900 | benjamin.peterson | 2008-12-22 14:02:45 -0600 (Mon, 22 Dec 2008) | 4 lines
    
    fix_execfile: wrap the open(fn).read() call in compile(), so the filename is preserved
    
    also add unittests for the fixer
  ........
    r67901 | benjamin.peterson | 2008-12-22 14:09:55 -0600 (Mon, 22 Dec 2008) | 1 line
    
    remove unused import
  ........
    r67919 | benjamin.peterson | 2008-12-23 13:12:22 -0600 (Tue, 23 Dec 2008) | 1 line
    
    copy permission bits from the backup to the original
  ........
    r67928 | benjamin.peterson | 2008-12-26 20:49:30 -0600 (Fri, 26 Dec 2008) | 1 line
    
    don't be so idiot about multiple local imports in fix_import; still won't handle absolute and local imports on the same line
  ........
    r67984 | benjamin.peterson | 2008-12-28 09:55:16 -0600 (Sun, 28 Dec 2008) | 1 line
    
    don't need loop
  ........
    r67991 | benjamin.peterson | 2008-12-28 14:30:26 -0600 (Sun, 28 Dec 2008) | 1 line
    
    actually call finish_tree()
  ........
    r67992 | benjamin.peterson | 2008-12-28 14:34:47 -0600 (Sun, 28 Dec 2008) | 1 line
    
    remove useless test
  ........
    r67993 | benjamin.peterson | 2008-12-28 15:04:32 -0600 (Sun, 28 Dec 2008) | 1 line
    
    update pyk3's test grammar
  ........
    r68106 | benjamin.peterson | 2008-12-31 11:53:58 -0600 (Wed, 31 Dec 2008) | 1 line
    
    #2734 don't convert every instance of long (eg if it's an attribute)
  ........
    r68107 | benjamin.peterson | 2008-12-31 11:55:10 -0600 (Wed, 31 Dec 2008) | 1 line
    
    add another test
  ........
    r68108 | benjamin.peterson | 2008-12-31 12:00:12 -0600 (Wed, 31 Dec 2008) | 1 line
    
    don't change long even if it's the only argument name
  ........
    r68110 | benjamin.peterson | 2008-12-31 14:13:26 -0600 (Wed, 31 Dec 2008) | 1 line
    
    remove unused import
  ........
................
  r68203 | martin.v.loewis | 2009-01-04 04:19:26 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Issue #4817: Remove unused function PyOS_GetLastModificationTime.
................
  r68208 | raymond.hettinger | 2009-01-04 06:02:23 +1100 (Sun, 04 Jan 2009) | 1 line
  
  Issue 4796: Add from_float methods to the decimal module.
................
  r68209 | raymond.hettinger | 2009-01-04 06:08:10 +1100 (Sun, 04 Jan 2009) | 1 line
  
  Reapply r68191.
................
  r68210 | georg.brandl | 2009-01-04 06:10:12 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Set eol-style correctly for mp_distributing.py.
................
  r68214 | georg.brandl | 2009-01-04 06:44:48 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Make indentation consistent.
................
  r68215 | georg.brandl | 2009-01-04 07:15:14 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Fix role name.
................
  r68217 | georg.brandl | 2009-01-04 07:30:15 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Add rstlint, a little tool to find subtle markup problems and inconsistencies in the Doc sources.
................
  r68218 | georg.brandl | 2009-01-04 07:38:59 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Recognize usage of the default role.
................
  r68219 | georg.brandl | 2009-01-04 07:47:01 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Fix uses of the default role.
................
  r68220 | georg.brandl | 2009-01-04 07:55:06 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Remove trailing whitespace.
................
  r68221 | georg.brandl | 2009-01-04 08:04:55 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Remove tabs from the documentation.
................
  r68222 | georg.brandl | 2009-01-04 08:11:58 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Disable the line length checker by default.
................
  r68231 | guilherme.polo | 2009-01-04 08:51:09 +1100 (Sun, 04 Jan 2009) | 4 lines
  
  The _tkinter module functions "createfilehandler", "deletefilehandler",
  "createtimerhandler", "mainloop", "dooneevent" and "quit" have been
  deprecated for removal in 3.x (part of issue #3638).
................
  r68232 | georg.brandl | 2009-01-04 08:52:16 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Grammar fix.
................
  r68238 | georg.brandl | 2009-01-04 09:03:11 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Manually merge r68095,68186,68187,68188,68190 from 2.6 branch.
................
  r68240 | georg.brandl | 2009-01-04 09:05:22 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Manually merge r67868 from 2.6 branch.
................
  r68243 | georg.brandl | 2009-01-04 09:15:42 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Add temporary code to fix the automatic doc build failure.
................
  r68276 | tarek.ziade | 2009-01-04 11:04:49 +1100 (Sun, 04 Jan 2009) | 1 line
  
  fixed #1702551: distutils sdist was not pruning VCS directories under win32
................
  r68288 | benjamin.peterson | 2009-01-04 11:39:07 +1100 (Sun, 04 Jan 2009) | 1 line
  
  only check the actual compile() call for a SyntaxError
................
  r68289 | georg.brandl | 2009-01-04 19:26:10 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Test commit.
................
  r68290 | georg.brandl | 2009-01-04 21:23:49 +1100 (Sun, 04 Jan 2009) | 4 lines
  
  Add "suspicious" builder which finds leftover markup in the HTML files.
  
  Patch by Gabriel Genellina.
................
  r68291 | georg.brandl | 2009-01-04 21:24:09 +1100 (Sun, 04 Jan 2009) | 2 lines
  
  Fix two issues found by the suspicious builder.
................
  r68292 | skip.montanaro | 2009-01-04 21:36:58 +1100 (Sun, 04 Jan 2009) | 3 lines
  
  If user configures --without-gcc give preference to $CC instead of blindly
  assuming the compiler will be "cc".
................
  r68293 | tarek.ziade | 2009-01-04 21:37:52 +1100 (Sun, 04 Jan 2009) | 1 line
  
  using clearer syntax
................
  r68296 | mark.dickinson | 2009-01-04 23:29:36 +1100 (Sun, 04 Jan 2009) | 6 lines
  
  Add autoconf test to detect x87-style double rounding, as described in
  issue #2937.  This information can be helpful for diagnosing platform-
  specific problems in math and cmath.  The result of the test also
  serves as a fairly reliable indicator of whether the x87 floating-point
  instructions (as opposed to SSE2) are in use on Intel x86/x86_64 systems.
................
  r68299 | mark.dickinson | 2009-01-05 00:57:26 +1100 (Mon, 05 Jan 2009) | 4 lines
  
  isinf and isnan are macros, not functions; fix configure script
  to use AC_CHECK_DECLS instead of AC_CHECK_FUNCS for these.
  (See discussion in issue #4506)
................
  r68302 | mark.dickinson | 2009-01-05 03:06:40 +1100 (Mon, 05 Jan 2009) | 4 lines
  
  Oops.  Need to check not only that HAVE_DECL_ISINF is defined, but also
  that it's equal to 1.  (If isinf isn't defined, HAVE_DECL_ISINF is
  defined to be 0, rather than being undefined.)
................
  r68304 | mark.dickinson | 2009-01-05 04:02:05 +1100 (Mon, 05 Jan 2009) | 2 lines
  
  Fix HAVE_DECL_ISINF/ISNAN test (again).
................
  r68311 | mark.dickinson | 2009-01-05 06:53:00 +1100 (Mon, 05 Jan 2009) | 2 lines
  
  Use C99 'isfinite' macro in preference to BSD-derived 'finite' function.
................
  r68312 | mark.dickinson | 2009-01-05 07:19:41 +1100 (Mon, 05 Jan 2009) | 4 lines
  
  It's wrong to use AC_REPLACE_FUNCS for hypot, since there's no longer any
  Python/hypot.c replacement file.  Use AC_CHECK_FUNCS instead.  This change
  should be backported to 2.6 and 3.0.
................
  r68314 | mark.dickinson | 2009-01-05 08:10:56 +1100 (Mon, 05 Jan 2009) | 5 lines
  
  Fix Decimal.from_float to use valid Python 2.3 syntax, as per
  comments at top of decimal.py.  (But note that the from_float
  method itself with still not be usable before Python 2.7.)
  See issue 4796 for discussion.
................
  r68317 | mark.dickinson | 2009-01-05 08:22:02 +1100 (Mon, 05 Jan 2009) | 2 lines
  
  More Python 2.3 compatibility fixes for decimal.py.
................
  r68318 | mark.dickinson | 2009-01-05 08:25:40 +1100 (Mon, 05 Jan 2009) | 2 lines
  
  Misc/NEWS entry for r68317
................
  r68319 | antoine.pitrou | 2009-01-05 08:29:23 +1100 (Mon, 05 Jan 2009) | 3 lines
  
  Issue #4272: Add an optional argument to the GzipFile constructor to override the timestamp in the gzip stream.
................
  r68325 | benjamin.peterson | 2009-01-05 09:00:18 +1100 (Mon, 05 Jan 2009) | 1 line
  
  use Jinja 2.1.1
................
  r68326 | georg.brandl | 2009-01-05 09:03:10 +1100 (Mon, 05 Jan 2009) | 2 lines
  
  Update make.bat.
................
  r68338 | neal.norwitz | 2009-01-05 14:57:25 +1100 (Mon, 05 Jan 2009) | 1 line
  
  Make sure to checkout any new packages
................
  r68344 | marc-andre.lemburg | 2009-01-06 06:43:35 +1100 (Tue, 06 Jan 2009) | 7 lines
  
  Fix #4846 (Py_UNICODE_ISSPACE causes linker error) by moving the declaration
  into the extern "C" section.
  
  Add a few more comments and apply some minor edits to make the file contents
  fit the original structure again.
................
  r68360 | antoine.pitrou | 2009-01-07 05:10:47 +1100 (Wed, 07 Jan 2009) | 7 lines
  
  Issue #1180193: When importing a module from a .pyc (or .pyo) file with
  an existing .py counterpart, override the co_filename attributes of all
  code objects if the original filename is obsolete (which can happen if the
  file has been renamed, moved, or if it is accessed through different paths).
  Patch by Ziga Seilnacht and Jean-Paul Calderone.
................
  r68361 | antoine.pitrou | 2009-01-07 05:34:08 +1100 (Wed, 07 Jan 2009) | 3 lines
  
  Use shutil.rmtree rather than os.rmdir.
................
  r68373 | hirokazu.yamamoto | 2009-01-07 20:42:28 +1100 (Wed, 07 Jan 2009) | 2 lines
  
  Issue #4864: test_msvc9compiler failed on VC6/7.
  Reviewed by Amaury Forgeot d'Arc.
................
  r68378 | mark.dickinson | 2009-01-08 04:48:33 +1100 (Thu, 08 Jan 2009) | 2 lines
  
  Issue #4869: clarify documentation for random.expovariate.
................
  r68381 | martin.v.loewis | 2009-01-08 05:40:40 +1100 (Thu, 08 Jan 2009) | 2 lines
  
  Issue #4850: Change COUNT_ALLOCS variables to Py_ssize_t.
................
  r68388 | benjamin.peterson | 2009-01-08 14:39:46 +1100 (Thu, 08 Jan 2009) | 1 line
  
  string exceptions are gone
................
  r68393 | benjamin.peterson | 2009-01-08 15:01:00 +1100 (Thu, 08 Jan 2009) | 1 line
  
  use new sphinx modules
................
  r68395 | raymond.hettinger | 2009-01-08 17:39:04 +1100 (Thu, 08 Jan 2009) | 1 line
  
  Forward port r68394 for issue 4816.
................
  r68415 | tarek.ziade | 2009-01-09 10:56:31 +1100 (Fri, 09 Jan 2009) | 1 line
  
  fixed #4394 make the storage of the password optional in .pypirc
................
  r68423 | benjamin.peterson | 2009-01-09 13:13:34 +1100 (Fri, 09 Jan 2009) | 29 lines
  
  Merged revisions 68306-68308,68340,68368,68422 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r68306 | benjamin.peterson | 2009-01-04 12:27:19 -0600 (Sun, 04 Jan 2009) | 1 line
    
    fix_urllib: add mappings for the url parsing functions
  ........
    r68307 | benjamin.peterson | 2009-01-04 12:30:01 -0600 (Sun, 04 Jan 2009) | 1 line
    
    remove duplicated function
  ........
    r68308 | benjamin.peterson | 2009-01-04 12:50:34 -0600 (Sun, 04 Jan 2009) | 1 line
    
    turtle is no longer renamed
  ........
    r68340 | georg.brandl | 2009-01-05 02:11:39 -0600 (Mon, 05 Jan 2009) | 2 lines
    
    Fix undefined locals in parse_tokens().
  ........
    r68368 | benjamin.peterson | 2009-01-06 17:56:10 -0600 (Tue, 06 Jan 2009) | 1 line
    
    fix typo (thanks to Robert Lehmann)
  ........
    r68422 | benjamin.peterson | 2009-01-08 20:01:03 -0600 (Thu, 08 Jan 2009) | 1 line
    
    run the imports fixers after fix_import, so fix_import doesn't try to make stdlib renames into relative imports #4876
  ........
................
  r68424 | benjamin.peterson | 2009-01-09 13:53:35 +1100 (Fri, 09 Jan 2009) | 1 line
  
  specify what -3 warnings are about
................
  r68425 | benjamin.peterson | 2009-01-09 13:56:32 +1100 (Fri, 09 Jan 2009) | 1 line
  
  fix markup
................
  r68426 | benjamin.peterson | 2009-01-09 14:03:05 +1100 (Fri, 09 Jan 2009) | 1 line
  
  fix spelling
................
  r68429 | benjamin.peterson | 2009-01-09 14:05:14 +1100 (Fri, 09 Jan 2009) | 1 line
  
  add -3 to manpage
................
  r68430 | benjamin.peterson | 2009-01-09 14:07:27 +1100 (Fri, 09 Jan 2009) | 1 line
  
  be more specific in -3 option help
................
  r68432 | benjamin.peterson | 2009-01-09 14:15:00 +1100 (Fri, 09 Jan 2009) | 1 line
  
  remove temporary code now
................
  r68435 | hirokazu.yamamoto | 2009-01-09 14:32:46 +1100 (Fri, 09 Jan 2009) | 1 line
  
  Bump up bzip2 version on VC6. (bzip2-1.0.3 -> bzip2-1.0.5)
................
  r68439 | hirokazu.yamamoto | 2009-01-09 15:10:40 +1100 (Fri, 09 Jan 2009) | 1 line
  
  Bump up bsddb version on VC6. (db-4.4.20 -> db-4.7.25)
................
  r68450 | jeffrey.yasskin | 2009-01-10 03:47:07 +1100 (Sat, 10 Jan 2009) | 3 lines
  
  Fix issue 4884, preventing a crash in the socket code when python is compiled
  with llvm-gcc and run with a glibc <2.10.
................
  r68455 | kristjan.jonsson | 2009-01-10 07:03:27 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Issue 3582.  Improved thread support and TLS for Windows
................
  r68457 | kristjan.jonsson | 2009-01-10 07:10:59 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Issue 3677:  Fix import from UNC paths on Windows.
................
  r68458 | kristjan.jonsson | 2009-01-10 07:23:16 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Issue 4336:  HTTPRequest._send_output() now deals with the case of the message body not being a string.  This allows clients to use endheaders(message_body) instead of endheaders() + send(message_body) without making any extra checks.
................
  r68459 | kristjan.jonsson | 2009-01-10 07:27:16 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Issue 4336:  Let users of HTTPConnection.endheaders() submit a message body to the function if required.
................
  r68460 | kristjan.jonsson | 2009-01-10 07:31:26 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Issue 4293:  Make Py_AddPendingCall() thread safe
................
  r68461 | kristjan.jonsson | 2009-01-10 08:35:16 +1100 (Sat, 10 Jan 2009) | 2 lines
  
  Issue 4293:  Make Py_AddPendingCall() thread safe
  Add test cases and documentation
................
  r68462 | antoine.pitrou | 2009-01-10 08:40:55 +1100 (Sat, 10 Jan 2009) | 6 lines
  
  Issue #4074: Change the criteria for doing a full garbage collection (i.e.
  collecting the oldest generation) so that allocating lots of objects without
  destroying them does not show quadratic performance. Based on a proposal by
  Martin von Löwis at http://mail.python.org/pipermail/python-dev/2008-June/080579.html.
................
  r68468 | hirokazu.yamamoto | 2009-01-10 19:09:43 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Bump up Tcl/Tk version on VC6. (tcl8.4.12 -> tcl8.5.2, tk8.4.12 -> tk8.5.2, tix8.4.0 -> tix8.4.3)
................
  r68469 | hirokazu.yamamoto | 2009-01-10 19:12:09 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Link to debug version of Tcl/Tk when python is built as debug version.
................
  r68470 | hirokazu.yamamoto | 2009-01-10 20:18:16 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Added helper script to build Tcl/Tk.
................
  r68476 | kristjan.jonsson | 2009-01-10 23:14:31 +1100 (Sat, 10 Jan 2009) | 1 line
  
  Issue 4906:  Preserve windows error state across PyThread_get_key_value
................
  r68480 | vinay.sajip | 2009-01-11 00:38:04 +1100 (Sun, 11 Jan 2009) | 1 line
  
  Minor documentation changes cross-referencing NullHandler to the documentation on configuring logging in a library.
................
  r68481 | vinay.sajip | 2009-01-11 00:42:04 +1100 (Sun, 11 Jan 2009) | 1 line
  
  Corrected an incorrect self-reference.
................
  r68484 | antoine.pitrou | 2009-01-11 03:13:45 +1100 (Sun, 11 Jan 2009) | 3 lines
  
  Issue #3860: GzipFile and BZ2File now support the context manager protocol.
................
  r68485 | antoine.pitrou | 2009-01-11 03:15:24 +1100 (Sun, 11 Jan 2009) | 1 line
  
  Add NEWS entry for r68484.
................
  r68487 | matthias.klose | 2009-01-11 04:00:42 +1100 (Sun, 11 Jan 2009) | 3 lines
  
  - Issue #4861: ctypes.util.find_library(): Robustify. Fix library detection on
    biarch systems. Try to rely on ldconfig only, without using objdump and gcc.
................
  r68493 | benjamin.peterson | 2009-01-11 04:18:55 +1100 (Sun, 11 Jan 2009) | 1 line
  
  rewrite verbose conditionals
................
  r68495 | benjamin.peterson | 2009-01-11 04:36:44 +1100 (Sun, 11 Jan 2009) | 1 line
  
  tp_iter only exists with Py_TPFLAGS_HAVE_ITER #4901
................
  r68496 | antoine.pitrou | 2009-01-11 05:33:21 +1100 (Sun, 11 Jan 2009) | 3 lines
  
  Add ACKS entries for some of the patches I've been committing.
................
  r68498 | benjamin.peterson | 2009-01-11 06:08:49 +1100 (Sun, 11 Jan 2009) | 1 line
  
  fix encoding
................
  r68499 | mark.dickinson | 2009-01-11 06:14:55 +1100 (Sun, 11 Jan 2009) | 2 lines
  
  Remove an unnecessary check from test_decimal.
................
  r68501 | vinay.sajip | 2009-01-11 06:22:57 +1100 (Sun, 11 Jan 2009) | 1 line
  
  Corrected minor typo and added .currentmodule directives to fix missing cross-references.
................
  r68512 | benjamin.peterson | 2009-01-11 09:42:10 +1100 (Sun, 11 Jan 2009) | 1 line
  
  make tests fail if they can't be imported
................
  r68514 | benjamin.peterson | 2009-01-11 10:41:59 +1100 (Sun, 11 Jan 2009) | 1 line
  
  move seealso to a more appropiate place
................
  r68515 | benjamin.peterson | 2009-01-11 10:49:08 +1100 (Sun, 11 Jan 2009) | 1 line
  
  macos 9 isn't supported
................
  r68521 | hirokazu.yamamoto | 2009-01-11 14:28:13 +1100 (Sun, 11 Jan 2009) | 1 line
  
  Fixed version number in build_ssl.bat.
................
  r68523 | martin.v.loewis | 2009-01-11 20:26:54 +1100 (Sun, 11 Jan 2009) | 2 lines
  
  Issue #4279: Fix build of parsermodule under Cygwin.
................
  r68527 | martin.v.loewis | 2009-01-11 20:43:55 +1100 (Sun, 11 Jan 2009) | 2 lines
  
  Issue #4895: Use _strdup on Windows CE.
................
  r68532 | kristjan.jonsson | 2009-01-12 03:23:37 +1100 (Mon, 12 Jan 2009) | 1 line
  
  Issue 4879: Allow buffering for HTTPResponse
................
  r68534 | gregory.p.smith | 2009-01-12 04:53:33 +1100 (Mon, 12 Jan 2009) | 2 lines
  
  correct email address
................
  r68535 | gregory.p.smith | 2009-01-12 04:57:54 +1100 (Mon, 12 Jan 2009) | 9 lines
  
  Update the documentation for binascii and zlib crc32/adler32 functions
  to better describe the signed vs unsigned return value behavior on
  different platforms and versions of python.  Mention the workaround to
  make them all return the same thing by using & 0xffffffff.
  
  Fixes issue4903.
  
  Also needs to be merged into release26-maint, release30-maint, & py3k.
................
  r68536 | benjamin.peterson | 2009-01-12 06:48:15 +1100 (Mon, 12 Jan 2009) | 1 line
  
  add email addresses
................
  r68540 | martin.v.loewis | 2009-01-12 18:57:11 +1100 (Mon, 12 Jan 2009) | 2 lines
  
  Issue #4915: Port sysmodule to Windows CE.
................
  r68542 | martin.v.loewis | 2009-01-12 19:11:24 +1100 (Mon, 12 Jan 2009) | 2 lines
  
  Issue #4893: Use NT threading on CE.
................
  r68544 | kristjan.jonsson | 2009-01-12 20:20:34 +1100 (Mon, 12 Jan 2009) | 1 line
  
  Update Misc/NEWS for issue 3582
................
  r68545 | kristjan.jonsson | 2009-01-12 20:24:04 +1100 (Mon, 12 Jan 2009) | 1 line
  
  Misc/NEWS for issue 4293
................
  r68546 | raymond.hettinger | 2009-01-12 21:37:32 +1100 (Mon, 12 Jan 2009) | 1 line
  
  Optimize heapq.nsmallest/nlargest for cases where n==1 or n>=size.
................
  r68547 | kristjan.jonsson | 2009-01-13 05:09:27 +1100 (Tue, 13 Jan 2009) | 1 line
  
  Add tests for invalid format specifiers in strftime, and for handling of invalid file descriptors in the os module.
................
  r68552 | vinay.sajip | 2009-01-13 07:36:18 +1100 (Tue, 13 Jan 2009) | 1 line
  
  Minor changes/corrections in markup.
................
  r68559 | raymond.hettinger | 2009-01-13 09:58:41 +1100 (Tue, 13 Jan 2009) | 1 line
  
  Issue 1696199: Add collections.Counter().
................
  r68560 | amaury.forgeotdarc | 2009-01-13 10:36:55 +1100 (Tue, 13 Jan 2009) | 6 lines
  
  #3720: Interpreter crashes when an evil iterator removes its own next function.
  
  Now the slot is filled with a function that always raises.
  
  Will not backport: extensions compiled with 2.6.x would not run on 2.6.0.
................
  r68562 | raymond.hettinger | 2009-01-13 12:05:03 +1100 (Tue, 13 Jan 2009) | 7 lines
  
  Simplify Counter() API.  Replace items keyword argument
  with a mapping.  Makes Counter() idempotent, makes update()
  API the same as Counter.__init__(), makes a more readable
  repr, makes the API more dict-like, and allows Steven
  Bethard's update() example to work.
................
  r68563 | benjamin.peterson | 2009-01-13 12:49:10 +1100 (Tue, 13 Jan 2009) | 1 line
  
  small logic correction
................
  r68565 | raymond.hettinger | 2009-01-13 14:49:43 +1100 (Tue, 13 Jan 2009) | 1 line
  
  Minor documentation tweaks and simpler update() example.
................
  r68566 | raymond.hettinger | 2009-01-13 15:13:53 +1100 (Tue, 13 Jan 2009) | 1 line
  
  Fixup and simplify docstrings and doctests.
................
  r68567 | raymond.hettinger | 2009-01-13 15:50:35 +1100 (Tue, 13 Jan 2009) | 1 line
  
  Speed-up __repr__.  Eliminate duplicate tests.  Use a from-irmport.
................
  r68568 | georg.brandl | 2009-01-13 19:11:07 +1100 (Tue, 13 Jan 2009) | 2 lines
  
  Fix call signature and markup.
................
  r68569 | raymond.hettinger | 2009-01-13 19:38:14 +1100 (Tue, 13 Jan 2009) | 7 lines
  
  Add table of idioms/patterns for using Counter objects.
  Improve the appearance and flow of the References section -- it used
  to have a box around it that wasn't distinct from the preceding code
  boxes and it had a weird bolding pattern and hanging indents that
  made the section disproportionately large.
................
  r68570 | raymond.hettinger | 2009-01-13 20:08:32 +1100 (Tue, 13 Jan 2009) | 5 lines
  
  Issue 4922: Incorrect comments for MutableSet.add() and MutableSet.discard().
  
  Needs to be backported to 2.6 and forward ported to 3.0 and 3.1.
................
  r68571 | armin.ronacher | 2009-01-13 22:52:23 +1100 (Tue, 13 Jan 2009) | 3 lines
  
  ast.literal_eval can properly evaluate complex numbers now.  This fixes issue4907.
................
  r68572 | andrew.kuchling | 2009-01-14 00:40:54 +1100 (Wed, 14 Jan 2009) | 1 line
  
  Note that first coord. is left alone
................
  r68575 | thomas.heller | 2009-01-14 04:32:28 +1100 (Wed, 14 Jan 2009) | 1 line
  
  Fix refcount leak in error cases.  Bug found by coverity.
................
  r68579 | benjamin.peterson | 2009-01-14 08:42:23 +1100 (Wed, 14 Jan 2009) | 1 line
  
  make bytearrayobject.o depend on the stringlib #4936
................
  r68580 | benjamin.peterson | 2009-01-14 08:43:11 +1100 (Wed, 14 Jan 2009) | 1 line
  
  add bytearrayobject.h to PYTHON_HEADERS
................
  r68582 | georg.brandl | 2009-01-14 09:14:01 +1100 (Wed, 14 Jan 2009) | 2 lines
  
  Use assertRaises.
................
  r68584 | benjamin.peterson | 2009-01-14 09:22:41 +1100 (Wed, 14 Jan 2009) | 1 line
  
  de-spacify
................
  r68589 | antoine.pitrou | 2009-01-14 10:13:52 +1100 (Wed, 14 Jan 2009) | 5 lines
  
  Issue #4935: The overflow checking code in the expandtabs() method common
  to str, bytes and bytearray could be optimized away by the compiler, letting
  the interpreter segfault instead of raising an error.
................
  r68592 | amaury.forgeotdarc | 2009-01-14 10:19:08 +1100 (Wed, 14 Jan 2009) | 5 lines
  
  #4807: Remove a wrong usage of wsprintf in the winreg module
  ("windows sprintf", different than swprintf)
  
  Needed for the windows CE port.
................
  r68596 | amaury.forgeotdarc | 2009-01-14 10:39:22 +1100 (Wed, 14 Jan 2009) | 3 lines
  
  #1162154: inspect.getmembers() now skips attributes that raise AttributeError,
  e.g. a __slots__ attribute which has not been set.
................
  r68597 | benjamin.peterson | 2009-01-14 10:43:50 +1100 (Wed, 14 Jan 2009) | 1 line
  
  fix test_xmlrpc failures #4939
................
  r68603 | raymond.hettinger | 2009-01-14 11:15:21 +1100 (Wed, 14 Jan 2009) | 1 line
  
  Minor doc tweaks.
................
  r68604 | raymond.hettinger | 2009-01-14 12:15:06 +1100 (Wed, 14 Jan 2009) | 1 line
  
  Add tests for __init__() and update() with no args.
................
  r68605 | raymond.hettinger | 2009-01-14 12:39:51 +1100 (Wed, 14 Jan 2009) | 1 line
  
  Fix-up indentation of sample code blocks for namedtuple mthod definitions.
................


Added:
   python/branches/tlee-ast-optimize/Doc/tools/rstlint.py
      - copied unchanged from r68605, /python/trunk/Doc/tools/rstlint.py
   python/branches/tlee-ast-optimize/Doc/tools/sphinxext/susp-ignored.csv
      - copied unchanged from r68605, /python/trunk/Doc/tools/sphinxext/susp-ignored.csv
   python/branches/tlee-ast-optimize/Doc/tools/sphinxext/suspicious.py
      - copied unchanged from r68605, /python/trunk/Doc/tools/sphinxext/suspicious.py
   python/branches/tlee-ast-optimize/Lib/distutils/tests/test_msvc9compiler.py
      - copied unchanged from r68605, /python/trunk/Lib/distutils/tests/test_msvc9compiler.py
   python/branches/tlee-ast-optimize/Lib/distutils/tests/test_register.py
      - copied unchanged from r68605, /python/trunk/Lib/distutils/tests/test_register.py
   python/branches/tlee-ast-optimize/Lib/distutils/tests/test_sdist.py
      - copied unchanged from r68605, /python/trunk/Lib/distutils/tests/test_sdist.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_isinstance.py
      - copied unchanged from r68605, /python/trunk/Lib/lib2to3/fixes/fix_isinstance.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_reduce.py
      - copied unchanged from r68605, /python/trunk/Lib/lib2to3/fixes/fix_reduce.py
   python/branches/tlee-ast-optimize/Lib/test/test_zipimport_support.py
      - copied unchanged from r68605, /python/trunk/Lib/test/test_zipimport_support.py
   python/branches/tlee-ast-optimize/PC/VC6/build_tkinter.py
      - copied unchanged from r68605, /python/trunk/PC/VC6/build_tkinter.py
   python/branches/tlee-ast-optimize/PC/VC6/tcl852.patch
      - copied unchanged from r68605, /python/trunk/PC/VC6/tcl852.patch
   python/branches/tlee-ast-optimize/PC/os2emx/python27.def
      - copied unchanged from r68605, /python/trunk/PC/os2emx/python27.def
Removed:
   python/branches/tlee-ast-optimize/Doc/tools/sphinx-web.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/tests/benchmark.py
   python/branches/tlee-ast-optimize/Lib/test/crashers/iter.py
   python/branches/tlee-ast-optimize/PC/os2emx/python26.def
   python/branches/tlee-ast-optimize/Python/getmtime.c
   python/branches/tlee-ast-optimize/RISCOS/Python/getmtime_riscos.c
Modified:
   python/branches/tlee-ast-optimize/   (props changed)
   python/branches/tlee-ast-optimize/Doc/ACKS.txt
   python/branches/tlee-ast-optimize/Doc/Makefile
   python/branches/tlee-ast-optimize/Doc/README.txt
   python/branches/tlee-ast-optimize/Doc/c-api/arg.rst
   python/branches/tlee-ast-optimize/Doc/c-api/buffer.rst
   python/branches/tlee-ast-optimize/Doc/c-api/conversion.rst
   python/branches/tlee-ast-optimize/Doc/c-api/exceptions.rst
   python/branches/tlee-ast-optimize/Doc/c-api/file.rst
   python/branches/tlee-ast-optimize/Doc/c-api/init.rst
   python/branches/tlee-ast-optimize/Doc/c-api/long.rst
   python/branches/tlee-ast-optimize/Doc/c-api/module.rst
   python/branches/tlee-ast-optimize/Doc/c-api/reflection.rst
   python/branches/tlee-ast-optimize/Doc/c-api/sequence.rst
   python/branches/tlee-ast-optimize/Doc/c-api/set.rst
   python/branches/tlee-ast-optimize/Doc/c-api/structures.rst
   python/branches/tlee-ast-optimize/Doc/c-api/sys.rst
   python/branches/tlee-ast-optimize/Doc/c-api/typeobj.rst
   python/branches/tlee-ast-optimize/Doc/data/refcounts.dat
   python/branches/tlee-ast-optimize/Doc/distutils/apiref.rst
   python/branches/tlee-ast-optimize/Doc/distutils/builtdist.rst
   python/branches/tlee-ast-optimize/Doc/distutils/configfile.rst
   python/branches/tlee-ast-optimize/Doc/distutils/packageindex.rst
   python/branches/tlee-ast-optimize/Doc/distutils/setupscript.rst
   python/branches/tlee-ast-optimize/Doc/distutils/uploading.rst
   python/branches/tlee-ast-optimize/Doc/documenting/markup.rst
   python/branches/tlee-ast-optimize/Doc/documenting/rest.rst
   python/branches/tlee-ast-optimize/Doc/extending/building.rst
   python/branches/tlee-ast-optimize/Doc/extending/extending.rst
   python/branches/tlee-ast-optimize/Doc/extending/newtypes.rst
   python/branches/tlee-ast-optimize/Doc/extending/windows.rst
   python/branches/tlee-ast-optimize/Doc/glossary.rst
   python/branches/tlee-ast-optimize/Doc/howto/curses.rst
   python/branches/tlee-ast-optimize/Doc/howto/doanddont.rst
   python/branches/tlee-ast-optimize/Doc/howto/functional.rst
   python/branches/tlee-ast-optimize/Doc/howto/regex.rst
   python/branches/tlee-ast-optimize/Doc/howto/sockets.rst
   python/branches/tlee-ast-optimize/Doc/howto/unicode.rst
   python/branches/tlee-ast-optimize/Doc/howto/urllib2.rst
   python/branches/tlee-ast-optimize/Doc/howto/webservers.rst
   python/branches/tlee-ast-optimize/Doc/includes/mp_distributing.py   (contents, props changed)
   python/branches/tlee-ast-optimize/Doc/install/index.rst
   python/branches/tlee-ast-optimize/Doc/library/2to3.rst
   python/branches/tlee-ast-optimize/Doc/library/abc.rst
   python/branches/tlee-ast-optimize/Doc/library/aifc.rst
   python/branches/tlee-ast-optimize/Doc/library/al.rst
   python/branches/tlee-ast-optimize/Doc/library/ast.rst
   python/branches/tlee-ast-optimize/Doc/library/audioop.rst
   python/branches/tlee-ast-optimize/Doc/library/bastion.rst
   python/branches/tlee-ast-optimize/Doc/library/bdb.rst
   python/branches/tlee-ast-optimize/Doc/library/binascii.rst
   python/branches/tlee-ast-optimize/Doc/library/bsddb.rst
   python/branches/tlee-ast-optimize/Doc/library/bz2.rst
   python/branches/tlee-ast-optimize/Doc/library/cd.rst
   python/branches/tlee-ast-optimize/Doc/library/cmath.rst
   python/branches/tlee-ast-optimize/Doc/library/codeop.rst
   python/branches/tlee-ast-optimize/Doc/library/collections.rst
   python/branches/tlee-ast-optimize/Doc/library/compiler.rst
   python/branches/tlee-ast-optimize/Doc/library/configparser.rst
   python/branches/tlee-ast-optimize/Doc/library/cookielib.rst
   python/branches/tlee-ast-optimize/Doc/library/crypt.rst
   python/branches/tlee-ast-optimize/Doc/library/csv.rst
   python/branches/tlee-ast-optimize/Doc/library/ctypes.rst
   python/branches/tlee-ast-optimize/Doc/library/datetime.rst
   python/branches/tlee-ast-optimize/Doc/library/decimal.rst
   python/branches/tlee-ast-optimize/Doc/library/difflib.rst
   python/branches/tlee-ast-optimize/Doc/library/dircache.rst
   python/branches/tlee-ast-optimize/Doc/library/dis.rst
   python/branches/tlee-ast-optimize/Doc/library/dl.rst
   python/branches/tlee-ast-optimize/Doc/library/email.mime.rst
   python/branches/tlee-ast-optimize/Doc/library/fileinput.rst
   python/branches/tlee-ast-optimize/Doc/library/fl.rst
   python/branches/tlee-ast-optimize/Doc/library/fm.rst
   python/branches/tlee-ast-optimize/Doc/library/fpformat.rst
   python/branches/tlee-ast-optimize/Doc/library/fractions.rst
   python/branches/tlee-ast-optimize/Doc/library/ftplib.rst
   python/branches/tlee-ast-optimize/Doc/library/functions.rst
   python/branches/tlee-ast-optimize/Doc/library/getopt.rst
   python/branches/tlee-ast-optimize/Doc/library/gettext.rst
   python/branches/tlee-ast-optimize/Doc/library/gl.rst
   python/branches/tlee-ast-optimize/Doc/library/gzip.rst
   python/branches/tlee-ast-optimize/Doc/library/hashlib.rst
   python/branches/tlee-ast-optimize/Doc/library/heapq.rst
   python/branches/tlee-ast-optimize/Doc/library/htmllib.rst
   python/branches/tlee-ast-optimize/Doc/library/idle.rst
   python/branches/tlee-ast-optimize/Doc/library/imageop.rst
   python/branches/tlee-ast-optimize/Doc/library/imgfile.rst
   python/branches/tlee-ast-optimize/Doc/library/io.rst
   python/branches/tlee-ast-optimize/Doc/library/itertools.rst
   python/branches/tlee-ast-optimize/Doc/library/jpeg.rst
   python/branches/tlee-ast-optimize/Doc/library/json.rst
   python/branches/tlee-ast-optimize/Doc/library/locale.rst
   python/branches/tlee-ast-optimize/Doc/library/logging.rst
   python/branches/tlee-ast-optimize/Doc/library/macos.rst
   python/branches/tlee-ast-optimize/Doc/library/mailbox.rst
   python/branches/tlee-ast-optimize/Doc/library/marshal.rst
   python/branches/tlee-ast-optimize/Doc/library/math.rst
   python/branches/tlee-ast-optimize/Doc/library/mhlib.rst
   python/branches/tlee-ast-optimize/Doc/library/mmap.rst
   python/branches/tlee-ast-optimize/Doc/library/msvcrt.rst
   python/branches/tlee-ast-optimize/Doc/library/multiprocessing.rst
   python/branches/tlee-ast-optimize/Doc/library/mutex.rst
   python/branches/tlee-ast-optimize/Doc/library/new.rst
   python/branches/tlee-ast-optimize/Doc/library/nntplib.rst
   python/branches/tlee-ast-optimize/Doc/library/numbers.rst
   python/branches/tlee-ast-optimize/Doc/library/operator.rst
   python/branches/tlee-ast-optimize/Doc/library/optparse.rst
   python/branches/tlee-ast-optimize/Doc/library/os.rst
   python/branches/tlee-ast-optimize/Doc/library/ossaudiodev.rst
   python/branches/tlee-ast-optimize/Doc/library/othergui.rst
   python/branches/tlee-ast-optimize/Doc/library/parser.rst
   python/branches/tlee-ast-optimize/Doc/library/pdb.rst
   python/branches/tlee-ast-optimize/Doc/library/pickle.rst
   python/branches/tlee-ast-optimize/Doc/library/popen2.rst
   python/branches/tlee-ast-optimize/Doc/library/profile.rst
   python/branches/tlee-ast-optimize/Doc/library/pydoc.rst
   python/branches/tlee-ast-optimize/Doc/library/pyexpat.rst
   python/branches/tlee-ast-optimize/Doc/library/random.rst
   python/branches/tlee-ast-optimize/Doc/library/re.rst
   python/branches/tlee-ast-optimize/Doc/library/repr.rst
   python/branches/tlee-ast-optimize/Doc/library/rexec.rst
   python/branches/tlee-ast-optimize/Doc/library/rlcompleter.rst
   python/branches/tlee-ast-optimize/Doc/library/robotparser.rst
   python/branches/tlee-ast-optimize/Doc/library/sched.rst
   python/branches/tlee-ast-optimize/Doc/library/sgmllib.rst
   python/branches/tlee-ast-optimize/Doc/library/shutil.rst
   python/branches/tlee-ast-optimize/Doc/library/signal.rst
   python/branches/tlee-ast-optimize/Doc/library/simplexmlrpcserver.rst
   python/branches/tlee-ast-optimize/Doc/library/smtplib.rst
   python/branches/tlee-ast-optimize/Doc/library/socket.rst
   python/branches/tlee-ast-optimize/Doc/library/socketserver.rst
   python/branches/tlee-ast-optimize/Doc/library/sqlite3.rst
   python/branches/tlee-ast-optimize/Doc/library/ssl.rst
   python/branches/tlee-ast-optimize/Doc/library/statvfs.rst
   python/branches/tlee-ast-optimize/Doc/library/stdtypes.rst
   python/branches/tlee-ast-optimize/Doc/library/string.rst
   python/branches/tlee-ast-optimize/Doc/library/stringio.rst
   python/branches/tlee-ast-optimize/Doc/library/subprocess.rst
   python/branches/tlee-ast-optimize/Doc/library/sunaudio.rst
   python/branches/tlee-ast-optimize/Doc/library/sys.rst
   python/branches/tlee-ast-optimize/Doc/library/tempfile.rst
   python/branches/tlee-ast-optimize/Doc/library/tk.rst
   python/branches/tlee-ast-optimize/Doc/library/tkinter.rst
   python/branches/tlee-ast-optimize/Doc/library/trace.rst
   python/branches/tlee-ast-optimize/Doc/library/traceback.rst
   python/branches/tlee-ast-optimize/Doc/library/turtle.rst
   python/branches/tlee-ast-optimize/Doc/library/undoc.rst
   python/branches/tlee-ast-optimize/Doc/library/unicodedata.rst
   python/branches/tlee-ast-optimize/Doc/library/unittest.rst
   python/branches/tlee-ast-optimize/Doc/library/urllib.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/library/warnings.rst
   python/branches/tlee-ast-optimize/Doc/library/webbrowser.rst
   python/branches/tlee-ast-optimize/Doc/library/winsound.rst
   python/branches/tlee-ast-optimize/Doc/library/wsgiref.rst
   python/branches/tlee-ast-optimize/Doc/library/xml.etree.elementtree.rst
   python/branches/tlee-ast-optimize/Doc/library/xmlrpclib.rst
   python/branches/tlee-ast-optimize/Doc/library/zipfile.rst
   python/branches/tlee-ast-optimize/Doc/library/zipimport.rst
   python/branches/tlee-ast-optimize/Doc/library/zlib.rst
   python/branches/tlee-ast-optimize/Doc/license.rst
   python/branches/tlee-ast-optimize/Doc/make.bat
   python/branches/tlee-ast-optimize/Doc/reference/datamodel.rst
   python/branches/tlee-ast-optimize/Doc/reference/expressions.rst
   python/branches/tlee-ast-optimize/Doc/reference/lexical_analysis.rst
   python/branches/tlee-ast-optimize/Doc/reference/simple_stmts.rst
   python/branches/tlee-ast-optimize/Doc/tools/   (props changed)
   python/branches/tlee-ast-optimize/Doc/tools/sphinxext/download.html
   python/branches/tlee-ast-optimize/Doc/tools/sphinxext/layout.html
   python/branches/tlee-ast-optimize/Doc/tools/sphinxext/pyspecific.py
   python/branches/tlee-ast-optimize/Doc/tutorial/classes.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/controlflow.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/datastructures.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/errors.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/index.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/inputoutput.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/interpreter.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/introduction.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/modules.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/stdlib.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/stdlib2.rst
   python/branches/tlee-ast-optimize/Doc/tutorial/whatnow.rst
   python/branches/tlee-ast-optimize/Doc/using/cmdline.rst
   python/branches/tlee-ast-optimize/Doc/using/unix.rst
   python/branches/tlee-ast-optimize/Doc/using/windows.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.0.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.1.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.2.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.3.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.4.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.5.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.6.rst
   python/branches/tlee-ast-optimize/Doc/whatsnew/2.7.rst
   python/branches/tlee-ast-optimize/Include/abstract.h
   python/branches/tlee-ast-optimize/Include/object.h
   python/branches/tlee-ast-optimize/Include/opcode.h
   python/branches/tlee-ast-optimize/Include/pymacconfig.h
   python/branches/tlee-ast-optimize/Include/pymath.h
   python/branches/tlee-ast-optimize/Include/pyport.h
   python/branches/tlee-ast-optimize/Include/unicodeobject.h
   python/branches/tlee-ast-optimize/LICENSE
   python/branches/tlee-ast-optimize/Lib/_abcoll.py
   python/branches/tlee-ast-optimize/Lib/ast.py
   python/branches/tlee-ast-optimize/Lib/bdb.py
   python/branches/tlee-ast-optimize/Lib/cgi.py
   python/branches/tlee-ast-optimize/Lib/collections.py
   python/branches/tlee-ast-optimize/Lib/compiler/misc.py
   python/branches/tlee-ast-optimize/Lib/compiler/pyassem.py
   python/branches/tlee-ast-optimize/Lib/compiler/pycodegen.py
   python/branches/tlee-ast-optimize/Lib/compiler/symbols.py
   python/branches/tlee-ast-optimize/Lib/compiler/transformer.py
   python/branches/tlee-ast-optimize/Lib/compiler/visitor.py
   python/branches/tlee-ast-optimize/Lib/ctypes/test/__init__.py
   python/branches/tlee-ast-optimize/Lib/ctypes/util.py
   python/branches/tlee-ast-optimize/Lib/decimal.py
   python/branches/tlee-ast-optimize/Lib/dis.py
   python/branches/tlee-ast-optimize/Lib/distutils/ccompiler.py
   python/branches/tlee-ast-optimize/Lib/distutils/command/register.py
   python/branches/tlee-ast-optimize/Lib/distutils/command/sdist.py
   python/branches/tlee-ast-optimize/Lib/distutils/command/upload.py
   python/branches/tlee-ast-optimize/Lib/distutils/config.py
   python/branches/tlee-ast-optimize/Lib/distutils/dist.py
   python/branches/tlee-ast-optimize/Lib/distutils/msvc9compiler.py
   python/branches/tlee-ast-optimize/Lib/distutils/tests/test_config.py
   python/branches/tlee-ast-optimize/Lib/distutils/tests/test_dist.py
   python/branches/tlee-ast-optimize/Lib/distutils/tests/test_upload.py
   python/branches/tlee-ast-optimize/Lib/distutils/util.py
   python/branches/tlee-ast-optimize/Lib/doctest.py
   python/branches/tlee-ast-optimize/Lib/fractions.py
   python/branches/tlee-ast-optimize/Lib/getopt.py
   python/branches/tlee-ast-optimize/Lib/gzip.py
   python/branches/tlee-ast-optimize/Lib/heapq.py
   python/branches/tlee-ast-optimize/Lib/httplib.py
   python/branches/tlee-ast-optimize/Lib/idlelib/NEWS.txt
   python/branches/tlee-ast-optimize/Lib/idlelib/help.txt
   python/branches/tlee-ast-optimize/Lib/idlelib/macosxSupport.py
   python/branches/tlee-ast-optimize/Lib/inspect.py
   python/branches/tlee-ast-optimize/Lib/io.py
   python/branches/tlee-ast-optimize/Lib/lib-tk/ScrolledText.py
   python/branches/tlee-ast-optimize/Lib/lib-tk/tkColorChooser.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/   (props changed)
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_base.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_util.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_apply.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_execfile.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_has_key.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_import.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports2.py   (contents, props changed)
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_intern.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_long.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_repr.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_urllib.py   (contents, props changed)
   python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_xrange.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/main.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/pgen2/driver.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/pygram.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/pytree.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/refactor.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/tests/data/infinite_recursion.py   (props changed)
   python/branches/tlee-ast-optimize/Lib/lib2to3/tests/data/py3_test_grammar.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_fixers.py
   python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_util.py
   python/branches/tlee-ast-optimize/Lib/linecache.py
   python/branches/tlee-ast-optimize/Lib/logging/__init__.py
   python/branches/tlee-ast-optimize/Lib/logging/handlers.py
   python/branches/tlee-ast-optimize/Lib/opcode.py
   python/branches/tlee-ast-optimize/Lib/pdb.py
   python/branches/tlee-ast-optimize/Lib/plat-mac/EasyDialogs.py
   python/branches/tlee-ast-optimize/Lib/plat-mac/bundlebuilder.py
   python/branches/tlee-ast-optimize/Lib/plat-mac/macostools.py
   python/branches/tlee-ast-optimize/Lib/plat-mac/videoreader.py
   python/branches/tlee-ast-optimize/Lib/pydoc.py
   python/branches/tlee-ast-optimize/Lib/random.py
   python/branches/tlee-ast-optimize/Lib/re.py
   python/branches/tlee-ast-optimize/Lib/runpy.py
   python/branches/tlee-ast-optimize/Lib/ssl.py
   python/branches/tlee-ast-optimize/Lib/subprocess.py
   python/branches/tlee-ast-optimize/Lib/tarfile.py
   python/branches/tlee-ast-optimize/Lib/test/decimaltestdata/extra.decTest
   python/branches/tlee-ast-optimize/Lib/test/list_tests.py
   python/branches/tlee-ast-optimize/Lib/test/pickletester.py
   python/branches/tlee-ast-optimize/Lib/test/test_array.py
   python/branches/tlee-ast-optimize/Lib/test/test_ast.py
   python/branches/tlee-ast-optimize/Lib/test/test_bytes.py
   python/branches/tlee-ast-optimize/Lib/test/test_bz2.py
   python/branches/tlee-ast-optimize/Lib/test/test_capi.py
   python/branches/tlee-ast-optimize/Lib/test/test_cgi.py
   python/branches/tlee-ast-optimize/Lib/test/test_cmd_line_script.py
   python/branches/tlee-ast-optimize/Lib/test/test_collections.py
   python/branches/tlee-ast-optimize/Lib/test/test_datetime.py
   python/branches/tlee-ast-optimize/Lib/test/test_decimal.py
   python/branches/tlee-ast-optimize/Lib/test/test_deque.py
   python/branches/tlee-ast-optimize/Lib/test/test_dict.py
   python/branches/tlee-ast-optimize/Lib/test/test_dis.py
   python/branches/tlee-ast-optimize/Lib/test/test_doctest.py
   python/branches/tlee-ast-optimize/Lib/test/test_file.py
   python/branches/tlee-ast-optimize/Lib/test/test_fileio.py
   python/branches/tlee-ast-optimize/Lib/test/test_fractions.py
   python/branches/tlee-ast-optimize/Lib/test/test_generators.py
   python/branches/tlee-ast-optimize/Lib/test/test_getopt.py
   python/branches/tlee-ast-optimize/Lib/test/test_gzip.py
   python/branches/tlee-ast-optimize/Lib/test/test_hash.py
   python/branches/tlee-ast-optimize/Lib/test/test_hotshot.py
   python/branches/tlee-ast-optimize/Lib/test/test_import.py
   python/branches/tlee-ast-optimize/Lib/test/test_inspect.py
   python/branches/tlee-ast-optimize/Lib/test/test_int.py
   python/branches/tlee-ast-optimize/Lib/test/test_io.py
   python/branches/tlee-ast-optimize/Lib/test/test_iter.py
   python/branches/tlee-ast-optimize/Lib/test/test_itertools.py
   python/branches/tlee-ast-optimize/Lib/test/test_logging.py
   python/branches/tlee-ast-optimize/Lib/test/test_long.py
   python/branches/tlee-ast-optimize/Lib/test/test_macos.py
   python/branches/tlee-ast-optimize/Lib/test/test_os.py
   python/branches/tlee-ast-optimize/Lib/test/test_parser.py
   python/branches/tlee-ast-optimize/Lib/test/test_py3kwarn.py
   python/branches/tlee-ast-optimize/Lib/test/test_set.py
   python/branches/tlee-ast-optimize/Lib/test/test_struct.py
   python/branches/tlee-ast-optimize/Lib/test/test_subprocess.py
   python/branches/tlee-ast-optimize/Lib/test/test_sys.py
   python/branches/tlee-ast-optimize/Lib/test/test_tarfile.py
   python/branches/tlee-ast-optimize/Lib/test/test_textwrap.py
   python/branches/tlee-ast-optimize/Lib/test/test_unittest.py
   python/branches/tlee-ast-optimize/Lib/test/test_urllib2.py
   python/branches/tlee-ast-optimize/Lib/test/test_urllib2_localnet.py
   python/branches/tlee-ast-optimize/Lib/test/test_urllibnet.py
   python/branches/tlee-ast-optimize/Lib/test/test_with.py
   python/branches/tlee-ast-optimize/Lib/test/test_xmlrpc.py
   python/branches/tlee-ast-optimize/Lib/test/test_zipfile.py
   python/branches/tlee-ast-optimize/Lib/test/test_zipimport.py
   python/branches/tlee-ast-optimize/Lib/textwrap.py
   python/branches/tlee-ast-optimize/Lib/unittest.py
   python/branches/tlee-ast-optimize/Lib/urllib.py
   python/branches/tlee-ast-optimize/Lib/urllib2.py
   python/branches/tlee-ast-optimize/Lib/xmlrpclib.py
   python/branches/tlee-ast-optimize/Lib/zipfile.py
   python/branches/tlee-ast-optimize/Mac/IDLE/Makefile.in
   python/branches/tlee-ast-optimize/Mac/Modules/MacOS.c
   python/branches/tlee-ast-optimize/Mac/PythonLauncher/Makefile.in
   python/branches/tlee-ast-optimize/Makefile.pre.in
   python/branches/tlee-ast-optimize/Misc/ACKS
   python/branches/tlee-ast-optimize/Misc/NEWS
   python/branches/tlee-ast-optimize/Misc/build.sh
   python/branches/tlee-ast-optimize/Misc/developers.txt
   python/branches/tlee-ast-optimize/Misc/python.man
   python/branches/tlee-ast-optimize/Modules/_collectionsmodule.c
   python/branches/tlee-ast-optimize/Modules/_ctypes/callproc.c
   python/branches/tlee-ast-optimize/Modules/_ctypes/cfield.c
   python/branches/tlee-ast-optimize/Modules/_fileio.c
   python/branches/tlee-ast-optimize/Modules/_hotshot.c
   python/branches/tlee-ast-optimize/Modules/_struct.c
   python/branches/tlee-ast-optimize/Modules/_testcapimodule.c
   python/branches/tlee-ast-optimize/Modules/_tkinter.c
   python/branches/tlee-ast-optimize/Modules/bz2module.c
   python/branches/tlee-ast-optimize/Modules/cPickle.c
   python/branches/tlee-ast-optimize/Modules/dbmmodule.c
   python/branches/tlee-ast-optimize/Modules/gcmodule.c
   python/branches/tlee-ast-optimize/Modules/itertoolsmodule.c
   python/branches/tlee-ast-optimize/Modules/main.c
   python/branches/tlee-ast-optimize/Modules/mathmodule.c
   python/branches/tlee-ast-optimize/Modules/parsermodule.c
   python/branches/tlee-ast-optimize/Modules/posixmodule.c
   python/branches/tlee-ast-optimize/Modules/socketmodule.c
   python/branches/tlee-ast-optimize/Modules/zipimport.c
   python/branches/tlee-ast-optimize/Objects/abstract.c
   python/branches/tlee-ast-optimize/Objects/bytearrayobject.c
   python/branches/tlee-ast-optimize/Objects/dictobject.c
   python/branches/tlee-ast-optimize/Objects/fileobject.c
   python/branches/tlee-ast-optimize/Objects/frameobject.c
   python/branches/tlee-ast-optimize/Objects/intobject.c
   python/branches/tlee-ast-optimize/Objects/listobject.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/stringlib/transmogrify.h
   python/branches/tlee-ast-optimize/Objects/stringobject.c
   python/branches/tlee-ast-optimize/Objects/tupleobject.c
   python/branches/tlee-ast-optimize/Objects/typeobject.c
   python/branches/tlee-ast-optimize/Objects/unicodeobject.c
   python/branches/tlee-ast-optimize/PC/VC6/_bsddb.dsp
   python/branches/tlee-ast-optimize/PC/VC6/_tkinter.dsp
   python/branches/tlee-ast-optimize/PC/VC6/bz2.dsp
   python/branches/tlee-ast-optimize/PC/VC6/pythoncore.dsp
   python/branches/tlee-ast-optimize/PC/VC6/readme.txt
   python/branches/tlee-ast-optimize/PC/VS7.1/pythoncore.vcproj
   python/branches/tlee-ast-optimize/PC/VS7.1/readme.txt
   python/branches/tlee-ast-optimize/PC/VS8.0/build_ssl.bat
   python/branches/tlee-ast-optimize/PC/VS8.0/pyproject.vsprops
   python/branches/tlee-ast-optimize/PC/VS8.0/pythoncore.vcproj
   python/branches/tlee-ast-optimize/PC/_winreg.c
   python/branches/tlee-ast-optimize/PC/example_nt/example.vcproj
   python/branches/tlee-ast-optimize/PC/msvcrtmodule.c
   python/branches/tlee-ast-optimize/PC/os2emx/Makefile
   python/branches/tlee-ast-optimize/PC/os2emx/README.os2emx
   python/branches/tlee-ast-optimize/PC/os2vacpp/makefile
   python/branches/tlee-ast-optimize/PC/os2vacpp/makefile.omk
   python/branches/tlee-ast-optimize/PC/os2vacpp/python.def
   python/branches/tlee-ast-optimize/PC/pyconfig.h
   python/branches/tlee-ast-optimize/PCbuild/build_ssl.bat
   python/branches/tlee-ast-optimize/PCbuild/pythoncore.vcproj
   python/branches/tlee-ast-optimize/Parser/asdl.py
   python/branches/tlee-ast-optimize/Parser/printgrammar.c
   python/branches/tlee-ast-optimize/Python/ast.c
   python/branches/tlee-ast-optimize/Python/ceval.c
   python/branches/tlee-ast-optimize/Python/compile.c
   python/branches/tlee-ast-optimize/Python/getargs.c
   python/branches/tlee-ast-optimize/Python/getcopyright.c
   python/branches/tlee-ast-optimize/Python/graminit.c
   python/branches/tlee-ast-optimize/Python/import.c
   python/branches/tlee-ast-optimize/Python/pythonrun.c
   python/branches/tlee-ast-optimize/Python/sysmodule.c
   python/branches/tlee-ast-optimize/Python/thread.c
   python/branches/tlee-ast-optimize/Python/thread_nt.h
   python/branches/tlee-ast-optimize/README
   python/branches/tlee-ast-optimize/RISCOS/Makefile
   python/branches/tlee-ast-optimize/Tools/msi/crtlicense.txt
   python/branches/tlee-ast-optimize/Tools/msi/msi.py
   python/branches/tlee-ast-optimize/Tools/msi/uuids.py
   python/branches/tlee-ast-optimize/Tools/pybench/Lists.py
   python/branches/tlee-ast-optimize/Tools/scripts/patchcheck.py
   python/branches/tlee-ast-optimize/configure
   python/branches/tlee-ast-optimize/configure.in
   python/branches/tlee-ast-optimize/pyconfig.h.in
   python/branches/tlee-ast-optimize/setup.py

Modified: python/branches/tlee-ast-optimize/Doc/ACKS.txt
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/ACKS.txt	(original)
+++ python/branches/tlee-ast-optimize/Doc/ACKS.txt	Wed Jan 14 13:24:17 2009
@@ -60,6 +60,7 @@
    * Peter Funk
    * Lele Gaifax
    * Matthew Gallagher
+   * Gabriel Genellina
    * Ben Gertzfield
    * Nadim Ghaznavi
    * Jonathan Giddy

Modified: python/branches/tlee-ast-optimize/Doc/Makefile
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/Makefile	(original)
+++ python/branches/tlee-ast-optimize/Doc/Makefile	Wed Jan 14 13:24:17 2009
@@ -9,12 +9,12 @@
 SPHINXOPTS   =
 PAPER        =
 SOURCES      =
-DISTVERSION  =
+DISTVERSION  = $(shell $(PYTHON) tools/sphinxext/patchlevel.py)
 
 ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees -D latex_paper_size=$(PAPER) \
                 $(SPHINXOPTS) . build/$(BUILDER) $(SOURCES)
 
-.PHONY: help checkout update build html htmlhelp clean coverage dist
+.PHONY: help checkout update build html htmlhelp clean coverage dist check
 
 help:
 	@echo "Please use \`make <target>' where <target> is one of"
@@ -24,6 +24,7 @@
 	@echo "  text      to make plain text files"
 	@echo "  changes   to make an overview over all changed/added/deprecated items"
 	@echo "  linkcheck to check all external links for integrity"
+	@echo "  suspicious to check for suspicious markup in output text"
 	@echo "  coverage  to check documentation coverage for library and C API"
 	@echo "  dist      to create a \"dist\" directory with archived docs for download"
 
@@ -36,9 +37,9 @@
 	  echo "Checking out Docutils..."; \
 	  svn checkout $(SVNROOT)/external/docutils-0.5/docutils tools/docutils; \
 	fi
-	@if [ ! -d tools/jinja ]; then \
+	@if [ ! -d tools/jinja2 ]; then \
 	  echo "Checking out Jinja..."; \
-	  svn checkout $(SVNROOT)/external/Jinja-1.2/jinja tools/jinja; \
+	  svn checkout $(SVNROOT)/external/Jinja-2.1.1/jinja2 tools/jinja2; \
 	fi
 	@if [ ! -d tools/pygments ]; then \
 	  echo "Checking out Pygments..."; \
@@ -48,7 +49,7 @@
 update: checkout
 	svn update tools/sphinx
 	svn update tools/docutils
-	svn update tools/jinja
+	svn update tools/jinja2
 	svn update tools/pygments
 
 build: checkout
@@ -84,6 +85,11 @@
 	@echo "Link check complete; look for any errors in the above output " \
 	      "or in build/$(BUILDER)/output.txt"
 
+suspicious: BUILDER = suspicious
+suspicious: build
+	@echo "Suspicious check complete; look for any errors in the above output " \
+	      "or in build/$(BUILDER)/suspicious.txt"
+
 coverage: BUILDER = coverage
 coverage: build
 	@echo "Coverage finished; see c.txt and python.txt in build/coverage"
@@ -111,33 +117,35 @@
 
 	# archive the HTML
 	make html
-	cp -pPR build/html dist/python$(DISTVERSION)-docs-html
-	tar -C dist -cf dist/python$(DISTVERSION)-docs-html.tar python$(DISTVERSION)-docs-html
-	bzip2 -9 -k dist/python$(DISTVERSION)-docs-html.tar
-	(cd dist; zip -q -r -9 python$(DISTVERSION)-docs-html.zip python$(DISTVERSION)-docs-html)
-	rm -r dist/python$(DISTVERSION)-docs-html
-	rm dist/python$(DISTVERSION)-docs-html.tar
+	cp -pPR build/html dist/python-$(DISTVERSION)-docs-html
+	tar -C dist -cf dist/python-$(DISTVERSION)-docs-html.tar python-$(DISTVERSION)-docs-html
+	bzip2 -9 -k dist/python-$(DISTVERSION)-docs-html.tar
+	(cd dist; zip -q -r -9 python-$(DISTVERSION)-docs-html.zip python-$(DISTVERSION)-docs-html)
+	rm -r dist/python-$(DISTVERSION)-docs-html
+	rm dist/python-$(DISTVERSION)-docs-html.tar
 
 	# archive the text build
 	make text
-	cp -pPR build/text dist/python$(DISTVERSION)-docs-text
-	tar -C dist -cf dist/python$(DISTVERSION)-docs-text.tar python$(DISTVERSION)-docs-text
-	bzip2 -9 -k dist/python$(DISTVERSION)-docs-text.tar
-	(cd dist; zip -q -r -9 python$(DISTVERSION)-docs-text.zip python$(DISTVERSION)-docs-text)
-	rm -r dist/python$(DISTVERSION)-docs-text
-	rm dist/python$(DISTVERSION)-docs-text.tar
+	cp -pPR build/text dist/python-$(DISTVERSION)-docs-text
+	tar -C dist -cf dist/python-$(DISTVERSION)-docs-text.tar python-$(DISTVERSION)-docs-text
+	bzip2 -9 -k dist/python-$(DISTVERSION)-docs-text.tar
+	(cd dist; zip -q -r -9 python-$(DISTVERSION)-docs-text.zip python-$(DISTVERSION)-docs-text)
+	rm -r dist/python-$(DISTVERSION)-docs-text
+	rm dist/python-$(DISTVERSION)-docs-text.tar
 	
 	# archive the A4 latex
 	-rm -r build/latex
 	make latex PAPER=a4
 	(cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2)
-	cp build/latex/docs-pdf.zip dist/python$(DISTVERSION)-docs-pdf-a4.zip
-	cp build/latex/docs-pdf.tar.bz2 dist/python$(DISTVERSION)-docs-pdf-a4.tar.bz2
+	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-a4.zip
+	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-a4.tar.bz2
 
 	# archive the letter latex
 	rm -r build/latex
 	make latex PAPER=letter
 	(cd build/latex; make clean && make all-pdf && make FMT=pdf zip bz2)
-	cp build/latex/docs-pdf.zip dist/python$(DISTVERSION)-docs-pdf-letter.zip
-	cp build/latex/docs-pdf.tar.bz2 dist/python$(DISTVERSION)-docs-pdf-letter.tar.bz2
+	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-letter.zip
+	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-letter.tar.bz2
 
+check:
+	$(PYTHON) tools/rstlint.py -i tools

Modified: python/branches/tlee-ast-optimize/Doc/README.txt
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/README.txt	(original)
+++ python/branches/tlee-ast-optimize/Doc/README.txt	Wed Jan 14 13:24:17 2009
@@ -76,8 +76,7 @@
 
    svn co http://svn.python.org/projects/doctools/trunk/sphinx tools/sphinx
 
-Then, you need to install Docutils 0.4 (the SVN snapshot won't work), either
-by checking it out via ::
+Then, you need to install Docutils, either by checking it out via ::
 
    svn co http://svn.python.org/projects/external/docutils-0.4/docutils tools/docutils
 
@@ -94,19 +93,18 @@
 
    python tools/sphinx-build.py -b<builder> . build/<outputdirectory>
 
-where `<builder>` is one of html, web or htmlhelp (for explanations see the make
-targets above).
+where `<builder>` is one of html, text, latex, or htmlhelp (for explanations see
+the make targets above).
 
 
 Contributing
 ============
 
-For bugs in the content, the online version at http://docs.python.org/ has a
-"suggest change" facility that can be used to correct errors in the source text
-and submit them as a patch to the maintainers.
+Bugs in the content should be reported to the Python bug tracker at
+http://bugs.python.org.
 
-Bugs in the toolset should be reported in the Python bug tracker at
-http://bugs.python.org/.
+Bugs in the toolset should be reported in the Sphinx bug tracker at
+http://www.bitbucket.org/birkenfeld/sphinx/issues/.
 
 You can also send a mail to the Python Documentation Team at docs at python.org,
 and we will process your request as soon as possible.

Modified: python/branches/tlee-ast-optimize/Doc/c-api/arg.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/arg.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/arg.rst	Wed Jan 14 13:24:17 2009
@@ -46,12 +46,12 @@
    :ctype:`Py_ssize_t` rather than an int.
 
 ``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer \*]
-  Similar to ``s#``, this code fills a Py_buffer structure provided by the caller.
-  The buffer gets locked, so that the caller can subsequently use the buffer even
-  inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is responsible for calling
-  ``PyBuffer_Release`` with the structure after it has processed the data.
+   Similar to ``s#``, this code fills a Py_buffer structure provided by the caller.
+   The buffer gets locked, so that the caller can subsequently use the buffer even
+   inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is responsible for calling
+   ``PyBuffer_Release`` with the structure after it has processed the data.
 
-  .. versionadded:: 2.6
+   .. versionadded:: 2.6
 
 ``z`` (string or ``None``) [const char \*]
    Like ``s``, but the Python object may also be ``None``, in which case the C
@@ -63,7 +63,7 @@
 ``z*`` (string or ``None`` or any buffer compatible object) [Py_buffer*]
    This is to ``s*`` as ``z`` is to ``s``.
 
-  .. versionadded:: 2.6
+   .. versionadded:: 2.6
 
 ``u`` (Unicode object) [Py_UNICODE \*]
    Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of
@@ -136,8 +136,9 @@
    them. Instead, the implementation assumes that the string object uses the
    encoding passed in as parameter.
 
-``b`` (integer) [char]
-   Convert a Python integer to a tiny int, stored in a C :ctype:`char`.
+``b`` (integer) [unsigned char]
+   Convert a nonnegative Python integer to an unsigned tiny int, stored in a C
+   :ctype:`unsigned char`.
 
 ``B`` (integer) [unsigned char]
    Convert a Python integer to a tiny int without overflow checking, stored in a C
@@ -251,7 +252,7 @@
    or use ``w#`` instead.  Only single-segment buffer objects are accepted;
    :exc:`TypeError` is raised for all others.
 
-``w#`` (read-write character buffer) [char \*, int]
+``w#`` (read-write character buffer) [char \*, Py_ssize_t]
    Like ``s#``, but accepts any object which implements the read-write buffer
    interface.  The :ctype:`char \*` variable is set to point to the first byte of
    the buffer, and the :ctype:`int` is set to the length of the buffer.  Only
@@ -260,6 +261,7 @@
 
 ``w*`` (read-write byte-oriented buffer) [Py_buffer \*]
    This is to ``w`` what ``s*`` is to ``s``.
+
    .. versionadded:: 2.6
 
 ``(items)`` (tuple) [*matching-items*]
@@ -297,8 +299,8 @@
 
 ``;``
    The list of format units ends here; the string after the semicolon is used as
-   the error message *instead* of the default error message.  Clearly, ``:`` and
-   ``;`` mutually exclude each other.
+   the error message *instead* of the default error message.  ``:`` and ``;``
+   mutually exclude each other.
 
 Note that any Python object references which are provided to the caller are
 *borrowed* references; do not decrement their reference count!
@@ -533,3 +535,8 @@
 
    If there is an error in the format string, the :exc:`SystemError` exception is
    set and *NULL* returned.
+
+.. cfunction:: PyObject* Py_VaBuildValue(const char *format, va_list vargs)
+
+   Identical to :cfunc:`Py_BuildValue`, except that it accepts a va_list
+   rather than a variable number of arguments.

Modified: python/branches/tlee-ast-optimize/Doc/c-api/buffer.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/buffer.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/buffer.rst	Wed Jan 14 13:24:17 2009
@@ -30,7 +30,7 @@
 
 .. index:: single: PyBufferProcs
 
-More information on the buffer interface is provided in the section 
+More information on the buffer interface is provided in the section
 :ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
 
 A "buffer object" is defined in the :file:`bufferobject.h` header (included by

Modified: python/branches/tlee-ast-optimize/Doc/c-api/conversion.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/conversion.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/conversion.rst	Wed Jan 14 13:24:17 2009
@@ -77,7 +77,7 @@
 
    .. versionadded:: 2.4
 
- 
+
 .. cfunction:: double PyOS_ascii_atof(const char *nptr)
 
    Convert a string to a :ctype:`double` in a locale-independent way.
@@ -86,7 +86,7 @@
 
    See the Unix man page :manpage:`atof(2)` for details.
 
-   
+
 .. cfunction:: char * PyOS_stricmp(char *s1, char *s2)
 
    Case insensitive comparison of strings. The function works almost

Modified: python/branches/tlee-ast-optimize/Doc/c-api/exceptions.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/exceptions.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/exceptions.rst	Wed Jan 14 13:24:17 2009
@@ -73,11 +73,10 @@
 
 .. cfunction:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
 
-   Return true if the *given* exception matches the exception in *exc*.  If *exc*
-   is a class object, this also returns true when *given* is an instance of a
-   subclass.  If *exc* is a tuple, all exceptions in the tuple (and recursively in
-   subtuples) are searched for a match.  If *given* is *NULL*, a memory access
-   violation will occur.
+   Return true if the *given* exception matches the exception in *exc*.  If
+   *exc* is a class object, this also returns true when *given* is an instance
+   of a subclass.  If *exc* is a tuple, all exceptions in the tuple (and
+   recursively in subtuples) are searched for a match.
 
 
 .. cfunction:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)

Modified: python/branches/tlee-ast-optimize/Doc/c-api/file.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/file.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/file.rst	Wed Jan 14 13:24:17 2009
@@ -63,8 +63,8 @@
    Return the file object associated with *p* as a :ctype:`FILE\*`.
 
    If the caller will ever use the returned :ctype:`FILE\*` object while
-   the GIL is released it must also call the `PyFile_IncUseCount` and
-   `PyFile_DecUseCount` functions described below as appropriate.
+   the GIL is released it must also call the :cfunc:`PyFile_IncUseCount` and
+   :cfunc:`PyFile_DecUseCount` functions described below as appropriate.
 
 
 .. cfunction:: void PyFile_IncUseCount(PyFileObject \*p)
@@ -72,13 +72,13 @@
    Increments the PyFileObject's internal use count to indicate
    that the underlying :ctype:`FILE\*` is being used.
    This prevents Python from calling f_close() on it from another thread.
-   Callers of this must call `PyFile_DecUseCount` when they are
+   Callers of this must call :cfunc:`PyFile_DecUseCount` when they are
    finished with the :ctype:`FILE\*`.  Otherwise the file object will
    never be closed by Python.
 
    The GIL must be held while calling this function.
 
-   The suggested use is to call this after `PyFile_AsFile` just before
+   The suggested use is to call this after :cfunc:`PyFile_AsFile` just before
    you release the GIL.
 
    .. versionadded:: 2.6
@@ -88,7 +88,7 @@
 
    Decrements the PyFileObject's internal unlocked_count member to
    indicate that the caller is done with its own use of the :ctype:`FILE\*`.
-   This may only be called to undo a prior call to `PyFile_IncUseCount`.
+   This may only be called to undo a prior call to :cfunc:`PyFile_IncUseCount`.
 
    The GIL must be held while calling this function.
 

Modified: python/branches/tlee-ast-optimize/Doc/c-api/init.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/init.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/init.rst	Wed Jan 14 13:24:17 2009
@@ -780,6 +780,50 @@
    .. versionadded:: 2.3
 
 
+
+Asynchronous Notifications
+==========================
+
+A mechanism is provided to make asynchronous notifications to the the main
+interpreter thread.  These notifications take the form of a function
+pointer and a void argument.
+
+.. index:: single: setcheckinterval() (in module sys)
+
+Every check interval, when the interpreter lock is released and reacquired,
+python will also call any such provided functions.  This can be used for
+example by asynchronous IO handlers.  The notification can be scheduled
+from a worker thread and the actual call than made at the earliest
+convenience by the main thread where it has possession of the global
+interpreter lock and can perform any Python API calls.
+
+.. cfunction:: void Py_AddPendingCall( int (*func)(void *, void *arg) )
+
+   .. index:: single: Py_AddPendingCall()
+
+   Post a notification to the Python main thread.  If successful,
+   *func* will be called with the argument *arg* at the earliest
+   convenience.  *func* will be called having the global interpreter
+   lock held and can thus use the full Python API and can take any
+   action such as setting object attributes to signal IO completion.
+   It must return 0 on success, or -1 signalling an exception.
+   The notification function won't be interrupted to perform another
+   asynchronous notification recursively,
+   but it can still be interrupted to switch threads if the interpreter
+   lock is released, for example, if it calls back into python code.
+
+   This function returns 0 on success in which case the notification has been
+   scheduled.  Otherwise, for example if the notification buffer is full,
+   it returns -1 without setting any exception.
+
+   This function can be called on any thread, be it a Python thread or
+   some other system thread.  If it is a Python thread, it doesen't matter if
+   it holds the global interpreter lock or not.
+
+   .. versionadded:: 2.7
+
+
+
 .. _profiling:
 
 Profiling and Tracing
@@ -902,7 +946,7 @@
 
    Return a tuple of function call counts.  There are constants defined for the
    positions within the tuple:
-   
+
    +-------------------------------+-------+
    | Name                          | Value |
    +===============================+=======+
@@ -928,7 +972,7 @@
    +-------------------------------+-------+
    | :const:`PCALL_POP`            | 10    |
    +-------------------------------+-------+
-   
+
    :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created.
    :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used.
 

Modified: python/branches/tlee-ast-optimize/Doc/c-api/long.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/long.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/long.rst	Wed Jan 14 13:24:17 2009
@@ -126,7 +126,7 @@
 
    Return a C :ctype:`long` representation of the contents of *pylong*.  If
    *pylong* is greater than :const:`LONG_MAX`, an :exc:`OverflowError` is raised
-   and ``-1`` will be returned. 
+   and ``-1`` will be returned.
 
 
 .. cfunction:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)

Modified: python/branches/tlee-ast-optimize/Doc/c-api/module.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/module.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/module.rst	Wed Jan 14 13:24:17 2009
@@ -106,7 +106,7 @@
 
 .. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro)
 
-   Add an int constant to *module*. The name and the value are taken from 
+   Add an int constant to *module*. The name and the value are taken from
    *macro*. For example ``PyModule_AddConstant(module, AF_INET)`` adds the int
    constant *AF_INET* with the value of *AF_INET* to *module*.
    Return ``-1`` on error, ``0`` on success.

Modified: python/branches/tlee-ast-optimize/Doc/c-api/reflection.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/reflection.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/reflection.rst	Wed Jan 14 13:24:17 2009
@@ -15,7 +15,7 @@
 
    Return a dictionary of the local variables in the current execution frame,
    or *NULL* if no frame is currently executing.
-   
+
 
 .. cfunction:: PyObject* PyEval_GetGlobals()
 

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	Wed Jan 14 13:24:17 2009
@@ -143,9 +143,9 @@
 
    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 
+   So, only use the underlying array pointer in contexts where the sequence
    cannot change.
 
    .. versionadded:: 2.4

Modified: python/branches/tlee-ast-optimize/Doc/c-api/set.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/set.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/set.rst	Wed Jan 14 13:24:17 2009
@@ -101,7 +101,7 @@
 
    .. versionchanged:: 2.6
       Now guaranteed to return a brand-new :class:`frozenset`.  Formerly,
-      frozensets of zero-length were a singleton.  This got in the way of 
+      frozensets of zero-length were a singleton.  This got in the way of
       building-up new frozensets with :meth:`PySet_Add`.
 
 The following functions and macros are available for instances of :class:`set`

Modified: python/branches/tlee-ast-optimize/Doc/c-api/structures.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/structures.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/structures.rst	Wed Jan 14 13:24:17 2009
@@ -205,6 +205,68 @@
    .. versionadded:: 2.4
 
 
+.. ctype:: PyMemberDef
+
+   Structure which describes an attribute of a type which corresponds to a C
+   struct member.  Its fields are:
+
+   +------------------+-------------+-------------------------------+
+   | Field            | C Type      | Meaning                       |
+   +==================+=============+===============================+
+   | :attr:`name`     | char \*     | name of the member            |
+   +------------------+-------------+-------------------------------+
+   | :attr:`type`     | int         | the type of the member in the |
+   |                  |             | C struct                      |
+   +------------------+-------------+-------------------------------+
+   | :attr:`offset`   | Py_ssize_t  | the offset in bytes that the  |
+   |                  |             | member is located on the      |
+   |                  |             | type's object struct          |
+   +------------------+-------------+-------------------------------+
+   | :attr:`flags`    | int         | flag bits indicating if the   |
+   |                  |             | field should be read-only or  |
+   |                  |             | writable                      |
+   +------------------+-------------+-------------------------------+
+   | :attr:`doc`      | char \*     | points to the contents of the |
+   |                  |             | docstring                     |
+   +------------------+-------------+-------------------------------+
+
+   :attr:`type` can be one of many ``T_`` macros corresponding to various C
+   types.  When the member is accessed in Python, it will be converted to the
+   equivalent Python type.
+
+   =============== ==================
+   Macro name      C type
+   =============== ==================
+   T_SHORT         short
+   T_INT           int
+   T_LONG          long
+   T_FLOAT         float
+   T_DOUBLE        double
+   T_STRING        char \*
+   T_OBJECT        PyObject \*
+   T_OBJECT_EX     PyObject \*
+   T_CHAR          char
+   T_BYTE          char
+   T_UNBYTE        unsigned char
+   T_UINT          unsigned int
+   T_USHORT        unsigned short
+   T_ULONG         unsigned long
+   T_BOOL          char
+   T_LONGLONG      long long
+   T_ULONGLONG     unsigned long long
+   T_PYSSIZET      Py_ssize_t
+   =============== ==================
+
+   :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` differ in that
+   :cmacro:`T_OBJECT` returns ``None`` if the member is *NULL* and
+   :cmacro:`T_OBJECT_EX` raises an :exc:`AttributeError`.
+
+   :attr:`flags` can be 0 for write and read access or :cmacro:`READONLY` for
+   read-only access.  Using :cmacro:`T_STRING` for :attr:`type` implies
+   :cmacro:`READONLY`.  Only :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX`
+   members can be deleted.  (They are set to *NULL*).
+
+
 .. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name)
 
    Return a bound method object for an extension type implemented in C.  This can

Modified: python/branches/tlee-ast-optimize/Doc/c-api/sys.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/sys.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/sys.rst	Wed Jan 14 13:24:17 2009
@@ -15,13 +15,6 @@
    one of the strings ``'<stdin>'`` or ``'???'``.
 
 
-.. cfunction:: long PyOS_GetLastModificationTime(char *filename)
-
-   Return the time of last modification of the file *filename*. The result is
-   encoded in the same way as the timestamp returned by the standard C library
-   function :cfunc:`time`.
-
-
 .. cfunction:: void PyOS_AfterFork()
 
    Function to update some internal state after a process fork; this should be

Modified: python/branches/tlee-ast-optimize/Doc/c-api/typeobj.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/c-api/typeobj.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/c-api/typeobj.rst	Wed Jan 14 13:24:17 2009
@@ -743,7 +743,7 @@
    :attr:`__weakref__`, the type inherits its :attr:`tp_weaklistoffset` from its
    base type.
 
-The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_CLASS` flag bit is
+The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_ITER` flag bit is
 set.
 
 

Modified: python/branches/tlee-ast-optimize/Doc/data/refcounts.dat
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/data/refcounts.dat	(original)
+++ python/branches/tlee-ast-optimize/Doc/data/refcounts.dat	Wed Jan 14 13:24:17 2009
@@ -841,9 +841,6 @@
 PyNumber_Xor:PyObject*:o1:0:
 PyNumber_Xor:PyObject*:o2:0:
 
-PyOS_GetLastModificationTime:long:::
-PyOS_GetLastModificationTime:char*:filename::
-
 PyObject_AsFileDescriptor:int::: 
 PyObject_AsFileDescriptor:PyObject*:o:0:
 

Modified: python/branches/tlee-ast-optimize/Doc/distutils/apiref.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/distutils/apiref.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/distutils/apiref.rst	Wed Jan 14 13:24:17 2009
@@ -88,9 +88,9 @@
    | *options*          | default options for the setup  | a string                                                    |
    |                    | script                         |                                                             |
    +--------------------+--------------------------------+-------------------------------------------------------------+
-   | *license*          | The license for the package    |                                                             |
+   | *license*          | The license for the package    | a string                                                    |
    +--------------------+--------------------------------+-------------------------------------------------------------+
-   | *keywords*         | Descriptive meta-data. See     |                                                             |
+   | *keywords*         | Descriptive meta-data, see     |                                                             |
    |                    | :pep:`314`                     |                                                             |
    +--------------------+--------------------------------+-------------------------------------------------------------+
    | *platforms*        |                                |                                                             |
@@ -98,6 +98,13 @@
    | *cmdclass*         | A mapping of command names to  | a dictionary                                                |
    |                    | :class:`Command` subclasses    |                                                             |
    +--------------------+--------------------------------+-------------------------------------------------------------+
+   | *data_files*       | A list of data files to        | a list                                                      |
+   |                    | install                        |                                                             |
+   +--------------------+--------------------------------+-------------------------------------------------------------+
+   | *package_dir*      | A mapping of package to        | a dictionary                                                |
+   |                    | directory names                |                                                             |
+   +--------------------+--------------------------------+-------------------------------------------------------------+
+
 
 
 .. function:: run_setup(script_name[, script_args=None, stop_after='run'])
@@ -181,9 +188,10 @@
    |                        | for C/C++ header files (in     |                           |
    |                        | Unix form for portability)     |                           |
    +------------------------+--------------------------------+---------------------------+
-   | *define_macros*        | list of macros to define; each | (string,string)  tuple or |
-   |                        | macro is defined using a       | (name,``None``)           |
-   |                        | 2-tuple, where 'value' is      |                           |
+   | *define_macros*        | list of macros to define; each | (string, string) tuple or |
+   |                        | macro is defined using a       | (name, ``None``)          |
+   |                        | 2-tuple ``(name, value)``,     |                           |
+   |                        | where *value* is               |                           |
    |                        | either the string to define it |                           |
    |                        | to or ``None`` to define it    |                           |
    |                        | without a particular value     |                           |
@@ -747,7 +755,7 @@
       standard output, otherwise do nothing.
 
 .. % \subsection{Compiler-specific modules}
-.. % 
+.. %
 .. % The following modules implement concrete subclasses of the abstract
 .. % \class{CCompiler} class. They should not be instantiated directly, but should
 .. % be created using \function{distutils.ccompiler.new_compiler()} factory
@@ -851,7 +859,7 @@
 Macintosh. Needs work to support CW on Windows or Mac OS X.
 
 .. % \subsection{Utility modules}
-.. % 
+.. %
 .. % The following modules all provide general utility functions. They haven't
 .. % all been documented yet.
 
@@ -1100,6 +1108,24 @@
 
    For non-POSIX platforms, currently just returns ``sys.platform``.
 
+   For MacOS X systems the OS version reflects the minimal version on which
+   binaries will run (that is, the value of ``MACOSX_DEPLOYMENT_TARGET``
+   during the build of Python), not the OS version of the current system.
+
+   For universal binary builds on MacOS X the architecture value reflects
+   the univeral binary status instead of the architecture of the current
+   processor. For 32-bit universal binaries the architecture is ``fat``,
+   for 64-bit universal binaries the architecture is ``fat64``, and
+   for 4-way universal binaries the architecture is ``universal``.
+
+   Examples of returned values on MacOS X:
+
+   * ``macosx-10.3-ppc``
+
+   * ``macosx-10.3-fat``
+
+   * ``macosx-10.5-universal``
+
    .. % XXX isn't this also provided by some other non-distutils module?
 
 
@@ -1667,7 +1693,7 @@
 
 .. % todo
 .. % \section{Distutils Commands}
-.. % 
+.. %
 .. % This part of Distutils implements the various Distutils commands, such
 .. % as \code{build}, \code{install} \&c. Each command is implemented as a
 .. % separate module, with the command name as the name of the module.

Modified: python/branches/tlee-ast-optimize/Doc/distutils/builtdist.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/distutils/builtdist.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/distutils/builtdist.rst	Wed Jan 14 13:24:17 2009
@@ -268,13 +268,13 @@
 .. % \longprogramopt{spec-file} option; used in conjunction with
 .. % \longprogramopt{spec-only}, this gives you an opportunity to customize
 .. % the \file{.spec} file manually:
-.. % 
+.. %
 .. % \ begin{verbatim}
 .. % > python setup.py bdist_rpm --spec-only
 .. % # ...edit dist/FooBar-1.0.spec
 .. % > python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec
 .. % \ end{verbatim}
-.. % 
+.. %
 .. % (Although a better way to do this is probably to override the standard
 .. % \command{bdist\_rpm} command with one that writes whatever else you want
 .. % to the \file{.spec} file.)
@@ -334,31 +334,31 @@
 Cross-compiling on Windows
 ==========================
 
-Starting with Python 2.6, distutils is capable of cross-compiling between 
-Windows platforms.  In practice, this means that with the correct tools 
+Starting with Python 2.6, distutils is capable of cross-compiling between
+Windows platforms.  In practice, this means that with the correct tools
 installed, you can use a 32bit version of Windows to create 64bit extensions
 and vice-versa.
 
-To build for an alternate platform, specify the :option:`--plat-name` option 
-to the build command.  Valid values are currently 'win32', 'win-amd64' and 
+To build for an alternate platform, specify the :option:`--plat-name` option
+to the build command.  Valid values are currently 'win32', 'win-amd64' and
 'win-ia64'.  For example, on a 32bit version of Windows, you could execute::
 
    python setup.py build --plat-name=win-amd64
 
-to build a 64bit version of your extension.  The Windows Installers also 
+to build a 64bit version of your extension.  The Windows Installers also
 support this option, so the command::
 
    python setup.py build --plat-name=win-amd64 bdist_wininst
 
 would create a 64bit installation executable on your 32bit version of Windows.
 
-To cross-compile, you must download the Python source code and cross-compile 
+To cross-compile, you must download the Python source code and cross-compile
 Python itself for the platform you are targetting - it is not possible from a
 binary installtion of Python (as the .lib etc file for other platforms are
-not included.)  In practice, this means the user of a 32 bit operating 
-system will need to use Visual Studio 2008 to open the 
-:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the 
-"x64" configuration of the 'pythoncore' project before cross-compiling 
+not included.)  In practice, this means the user of a 32 bit operating
+system will need to use Visual Studio 2008 to open the
+:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the
+"x64" configuration of the 'pythoncore' project before cross-compiling
 extensions is possible.
 
 Note that by default, Visual Studio 2008 does not install 64bit compilers or

Modified: python/branches/tlee-ast-optimize/Doc/distutils/configfile.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/distutils/configfile.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/distutils/configfile.rst	Wed Jan 14 13:24:17 2009
@@ -63,7 +63,7 @@
      --include-dirs (-I)  list of directories to search for header files
      --define (-D)        C preprocessor macros to define
      --undef (-U)         C preprocessor macros to undefine
-     --swig-opts          list of SWIG command line options        
+     --swig-opts          list of SWIG command line options
    [...]
 
 Note that an option spelled :option:`--foo-bar` on the command-line  is spelled

Modified: python/branches/tlee-ast-optimize/Doc/distutils/packageindex.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/distutils/packageindex.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/distutils/packageindex.rst	Wed Jan 14 13:24:17 2009
@@ -8,17 +8,17 @@
 packaged with distutils. The distutils command :command:`register` is used to
 submit your distribution's meta-data to the index. It is invoked as follows::
 
-   python setup.py register
+    python setup.py register
 
 Distutils will respond with the following prompt::
 
-   running register
-   We need to know who you are, so please choose either:
-    1. use your existing login,
-    2. register as a new user,
-    3. have the server generate a new password for you (and email it to you), or
-    4. quit
-   Your selection [default 1]:
+    running register
+    We need to know who you are, so please choose either:
+        1. use your existing login,
+        2. register as a new user,
+        3. have the server generate a new password for you (and email it to you), or
+        4. quit
+    Your selection [default 1]:
 
 Note: if your username and password are saved locally, you will not see this
 menu.
@@ -55,40 +55,50 @@
 
 The format of the :file:`.pypirc` file is as follows::
 
-   [distutils]
-   index-servers =
-     pypi
+    [distutils]
+    index-servers =
+        pypi
 
-   [pypi]
-   repository: <repository-url>
-   username: <username>
-   password: <password>
+    [pypi]
+    repository: <repository-url>
+    username: <username>
+    password: <password>
 
-*repository* can be omitted and defaults to ``http://www.python.org/pypi``.
+The *distutils* section defines a *index-servers* variable that lists the
+name of all sections describing a repository.
 
-If you want to define another server a new section can be created::
+Each section describing a repository defines three variables:
 
-   [distutils]
-   index-servers =
-     pypi
-     other
- 
-   [pypi]
-   repository: <repository-url>
-   username: <username>
-   password: <password>
+- *repository*, that defines the url of the PyPI server. Defaults to
+    ``http://www.python.org/pypi``.
+- *username*, which is the registered username on the PyPI server.
+- *password*, that will be used to authenticate. If omitted the user
+    will be prompt to type it when needed.
 
-   [other]
-   repository: http://example.com/pypi
-   username: <username>
-   password: <password>
+If you want to define another server a new section can be created and
+listed in the *index-servers* variable::
 
-The command can then be called with the -r option::
+    [distutils]
+    index-servers =
+        pypi
+        other
 
-   python setup.py register -r http://example.com/pypi
+    [pypi]
+    repository: <repository-url>
+    username: <username>
+    password: <password>
 
-Or even with the section name::
+    [other]
+    repository: http://example.com/pypi
+    username: <username>
+    password: <password>
 
-   python setup.py register -r other
+:command:`register` can then be called with the -r option to point the
+repository to work with::
 
- 
+    python setup.py register -r http://example.com/pypi
+
+The name of the section that describes the repository may also be used
+for conveniency::
+
+    python setup.py register -r other

Modified: python/branches/tlee-ast-optimize/Doc/distutils/setupscript.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/distutils/setupscript.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/distutils/setupscript.rst	Wed Jan 14 13:24:17 2009
@@ -213,7 +213,7 @@
 this::
 
    setup(...,
-         ext_modules=[Extension('_foo', ['foo.i'], 
+         ext_modules=[Extension('_foo', ['foo.i'],
                                 swig_opts=['-modern', '-I../include'])],
          py_modules=['foo'],
         )
@@ -563,6 +563,8 @@
 +----------------------+---------------------------+-----------------+--------+
 | ``classifiers``      | a list of classifiers     | list of strings | \(4)   |
 +----------------------+---------------------------+-----------------+--------+
+| ``platforms``        | a list of platforms       | list of strings |        |
++----------------------+---------------------------+-----------------+--------+
 
 Notes:
 

Modified: python/branches/tlee-ast-optimize/Doc/distutils/uploading.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/distutils/uploading.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/distutils/uploading.rst	Wed Jan 14 13:24:17 2009
@@ -13,7 +13,7 @@
 The command is invoked immediately after building one or more distribution
 files.  For example, the command ::
 
-   python setup.py sdist bdist_wininst upload
+    python setup.py sdist bdist_wininst upload
 
 will cause the source distribution and the Windows installer to be uploaded to
 PyPI.  Note that these will be uploaded even if they are built using an earlier
@@ -22,11 +22,14 @@
 
 The :command:`upload` command uses the username, password, and repository URL
 from the :file:`$HOME/.pypirc` file (see section :ref:`pypirc` for more on this
-file).
+file). If a :command:`register` command was previously called in the same command,
+and if the password was entered in the prompt, :command:`upload` will reuse the
+entered password. This is useful if you do not want to store a clear text
+password in the :file:`$HOME/.pypirc` file.
 
 You can specify another PyPI server with the :option:`--repository=*url*` option::
 
-   python setup.py sdist bdist_wininst upload -r http://example.com/pypi
+    python setup.py sdist bdist_wininst upload -r http://example.com/pypi
 
 See section :ref:`pypirc` for more on defining several servers.
 
@@ -35,9 +38,8 @@
 be available for execution on the system :envvar:`PATH`.  You can also specify
 which key to use for signing using the :option:`--identity=*name*` option.
 
-Other :command:`upload` options include  :option:`--repository=*url*` 
-or :option:`--repository=*section*` where `url` is the url of the server
-and `section` the name of the section in :file:`$HOME/.pypirc`, and
+Other :command:`upload` options include :option:`--repository=<url>` or
+:option:`--repository=<section>` where *url* is the url of the server and
+*section* the name of the section in :file:`$HOME/.pypirc`, and
 :option:`--show-response` (which displays the full response text from the PyPI
 server for help in debugging upload problems).
-

Modified: python/branches/tlee-ast-optimize/Doc/documenting/markup.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/documenting/markup.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/documenting/markup.rst	Wed Jan 14 13:24:17 2009
@@ -508,7 +508,7 @@
    curly braces to indicate a "variable" part, as in ``:file:``.
 
    If you don't need the "variable part" indication, use the standard
-   ````code```` instead.   
+   ````code```` instead.
 
 .. describe:: var
 
@@ -599,7 +599,7 @@
    Example::
 
       .. versionadded:: 2.5
-         The `spam` parameter.
+         The *spam* parameter.
 
    Note that there must be no blank line between the directive head and the
    explanation; this is to make these blocks visually continuous in the markup.
@@ -760,14 +760,14 @@
    Blank lines are not allowed within ``productionlist`` directive arguments.
 
    The definition can contain token names which are marked as interpreted text
-   (e.g. ``sum ::= `integer` "+" `integer```) -- this generates cross-references
+   (e.g. ``unaryneg ::= "-" `integer```) -- this generates cross-references
    to the productions of these tokens.
 
    Note that no further reST parsing is done in the production, so that you
    don't have to escape ``*`` or ``|`` characters.
 
 
-.. XXX describe optional first parameter 
+.. XXX describe optional first parameter
 
 The following is an example taken from the Python Reference Manual::
 

Modified: python/branches/tlee-ast-optimize/Doc/documenting/rest.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/documenting/rest.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/documenting/rest.rst	Wed Jan 14 13:24:17 2009
@@ -98,7 +98,7 @@
 -----------
 
 Literal code blocks are introduced by ending a paragraph with the special marker
-``::``.  The literal block must be indented, to be able to include blank lines::
+``::``.  The literal block must be indented::
 
    This is a normal text paragraph. The next paragraph is a code sample::
 

Modified: python/branches/tlee-ast-optimize/Doc/extending/building.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/extending/building.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/extending/building.rst	Wed Jan 14 13:24:17 2009
@@ -39,7 +39,7 @@
 
 With this :file:`setup.py`, and a file :file:`demo.c`, running ::
 
-   python setup.py build 
+   python setup.py build
 
 will compile :file:`demo.c`, and produce an extension module named ``demo`` in
 the :file:`build` directory. Depending on the system, the module file will end

Modified: python/branches/tlee-ast-optimize/Doc/extending/extending.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/extending/extending.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/extending/extending.rst	Wed Jan 14 13:24:17 2009
@@ -471,7 +471,7 @@
 :cfunc:`PyEval_CallObject`.  This function has two arguments, both pointers to
 arbitrary Python objects: the Python function, and the argument list.  The
 argument list must always be a tuple object, whose length is the number of
-arguments.  To call the Python function with no arguments, pass in NULL, or 
+arguments.  To call the Python function with no arguments, pass in NULL, or
 an empty tuple; to call it with one argument, pass a singleton tuple.
 :cfunc:`Py_BuildValue` returns a tuple when its format string consists of zero
 or more format codes between parentheses.  For example::
@@ -510,7 +510,7 @@
    if (result == NULL)
        return NULL; /* Pass error back */
    ...use result...
-   Py_DECREF(result); 
+   Py_DECREF(result);
 
 Depending on the desired interface to the Python callback function, you may also
 have to provide an argument list to :cfunc:`PyEval_CallObject`.  In some cases
@@ -535,7 +535,7 @@
 the error check!  Also note that strictly speaking this code is not complete:
 :cfunc:`Py_BuildValue` may run out of memory, and this should be checked.
 
-You may also call a function with keyword arguments by using 
+You may also call a function with keyword arguments by using
 :cfunc:`PyEval_CallObjectWithKeywords`.  As in the above example, we use
 :cfunc:`Py_BuildValue` to construct the dictionary. ::
 
@@ -671,7 +671,7 @@
 
    static PyObject *
    keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
-   {  
+   {
        int voltage;
        char *state = "a stiff";
        char *action = "voom";
@@ -679,11 +679,11 @@
 
        static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
 
-       if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, 
+       if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                         &voltage, &state, &action, &type))
-           return NULL; 
+           return NULL;
 
-       printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", 
+       printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
               action, voltage);
        printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
 
@@ -865,7 +865,7 @@
 The advantage of borrowing over owning a reference is that you don't need to
 take care of disposing of the reference on all possible paths through the code
 --- in other words, with a borrowed reference you don't run the risk of leaking
-when a premature exit is taken.  The disadvantage of borrowing over leaking is
+when a premature exit is taken.  The disadvantage of borrowing over owning is
 that there are some subtle situations where in seemingly correct code a borrowed
 reference can be used after the owner from which it was borrowed has in fact
 disposed of it.

Modified: python/branches/tlee-ast-optimize/Doc/extending/newtypes.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/extending/newtypes.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/extending/newtypes.rst	Wed Jan 14 13:24:17 2009
@@ -840,8 +840,8 @@
 previous sections. We will break down the main differences between them. ::
 
    typedef struct {
-   	PyListObject list;
-   	int state;
+       PyListObject list;
+       int state;
    } Shoddy;
 
 The primary difference for derived type objects is that the base type's object
@@ -854,10 +854,10 @@
    static int
    Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
    {
-   	if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
-   		return -1;
-   	self->state = 0;
-   	return 0;
+       if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
+          return -1;
+       self->state = 0;
+       return 0;
    }
 
 In the :attr:`__init__` method for our type, we can see how to call through to
@@ -876,18 +876,18 @@
    PyMODINIT_FUNC
    initshoddy(void)
    {
-   	PyObject *m;
+       PyObject *m;
 
-   	ShoddyType.tp_base = &PyList_Type;
-   	if (PyType_Ready(&ShoddyType) < 0)
-   		return;
-
-   	m = Py_InitModule3("shoddy", NULL, "Shoddy module");
-   	if (m == NULL)
-   		return;
+       ShoddyType.tp_base = &PyList_Type;
+       if (PyType_Ready(&ShoddyType) < 0)
+           return;
+
+       m = Py_InitModule3("shoddy", NULL, "Shoddy module");
+       if (m == NULL)
+           return;
 
-   	Py_INCREF(&ShoddyType);
-   	PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
+       Py_INCREF(&ShoddyType);
+       PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
    }
 
 Before calling :cfunc:`PyType_Ready`, the type structure must have the
@@ -1167,7 +1167,7 @@
    typedef struct PyMethodDef {
        char        *ml_name;       /* method name */
        PyCFunction  ml_meth;       /* implementation function */
-       int	         ml_flags;      /* flags */
+       int          ml_flags;      /* flags */
        char        *ml_doc;        /* docstring */
    } PyMethodDef;
 
@@ -1234,7 +1234,7 @@
 of *NULL* is required.
 
 .. XXX Descriptors need to be explained in more detail somewhere, but not here.
-   
+
    Descriptor objects have two handler functions which correspond to the
    \member{tp_getattro} and \member{tp_setattro} handlers.  The
    \method{__get__()} handler is a function which is passed the descriptor,

Modified: python/branches/tlee-ast-optimize/Doc/extending/windows.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/extending/windows.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/extending/windows.rst	Wed Jan 14 13:24:17 2009
@@ -102,7 +102,7 @@
    and it should call :cfunc:`Py_InitModule` with the string ``"spam"`` as its
    first argument (use the minimal :file:`example.c` in this directory as a guide).
    By convention, it lives in a file called :file:`spam.c` or :file:`spammodule.c`.
-   The output file should be called :file:`spam.pyd` (in Release mode) or  
+   The output file should be called :file:`spam.pyd` (in Release mode) or
    :file:`spam_d.pyd` (in Debug mode). The extension :file:`.pyd` was chosen
    to avoid confusion with a system library :file:`spam.dll` to which your module
    could be a Python interface.

Modified: python/branches/tlee-ast-optimize/Doc/glossary.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/glossary.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/glossary.rst	Wed Jan 14 13:24:17 2009
@@ -11,7 +11,7 @@
    ``>>>``
       The default Python prompt of the interactive shell.  Often seen for code
       examples which can be executed interactively in the interpreter.
-    
+
    ``...``
       The default Python prompt of the interactive shell when entering code for
       an indented code block or within a pair of matching left and right
@@ -50,11 +50,11 @@
       A value associated with an object which is referenced by name using
       dotted expressions.  For example, if an object *o* has an attribute
       *a* it would be referenced as *o.a*.
-    
+
    BDFL
       Benevolent Dictator For Life, a.k.a. `Guido van Rossum
       <http://www.python.org/~guido/>`_, Python's creator.
-    
+
    bytecode
       Python source code is compiled into bytecode, the internal representation
       of a Python program in the interpreter.  The bytecode is also cached in
@@ -67,11 +67,11 @@
       A template for creating user-defined objects. Class definitions
       normally contain method definitions which operate on instances of the
       class.
-    
+
    classic class
       Any class which does not inherit from :class:`object`.  See
       :term:`new-style class`.  Classic classes will be removed in Python 3.0.
-    
+
    coercion
       The implicit conversion of an instance of one type to another during an
       operation which involves two arguments of the same type.  For example,
@@ -84,7 +84,7 @@
       ``operator.add(3.0, 4.5)``.  Without coercion, all arguments of even
       compatible types would have to be normalized to the same value by the
       programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``.
-    
+
    complex number
       An extension of the familiar real number system in which all numbers are
       expressed as a sum of a real part and an imaginary part.  Imaginary
@@ -96,7 +96,7 @@
       :mod:`math` module, use :mod:`cmath`.  Use of complex numbers is a fairly
       advanced mathematical feature.  If you're not aware of a need for them,
       it's almost certain you can safely ignore them.
-    
+
    context manager
       An object which controls the environment seen in a :keyword:`with`
       statement by defining :meth:`__enter__` and :meth:`__exit__` methods.
@@ -123,6 +123,9 @@
          def f(...):
              ...
 
+      See :ref:`the documentation for function definition <function>` for more
+      about decorators.
+
    descriptor
       Any *new-style* object which defines the methods :meth:`__get__`,
       :meth:`__set__`, or :meth:`__delete__`.  When a class attribute is a
@@ -135,7 +138,7 @@
       class methods, static methods, and reference to super classes.
 
       For more information about descriptors' methods, see :ref:`descriptors`.
-    
+
    dictionary
       An associative array, where arbitrary keys are mapped to values.  The use
       of :class:`dict` closely resembles that for :class:`list`, but the keys can
@@ -149,8 +152,8 @@
       of the enclosing class, function or module.  Since it is available via
       introspection, it is the canonical place for documentation of the
       object.
-    
-   duck-typing 
+
+   duck-typing
       A pythonic programming style which determines an object's type by inspection
       of its method or attribute signature rather than by explicit relationship
       to some type object ("If it looks like a duck and quacks like a duck, it
@@ -160,13 +163,13 @@
       :func:`isinstance`. (Note, however, that duck-typing can be complemented
       with abstract base classes.) Instead, it typically employs :func:`hasattr`
       tests or :term:`EAFP` programming.
-    
+
    EAFP
       Easier to ask for forgiveness than permission.  This common Python coding
       style assumes the existence of valid keys or attributes and catches
       exceptions if the assumption proves false.  This clean and fast style is
       characterized by the presence of many :keyword:`try` and :keyword:`except`
-      statements.  The technique contrasts with the :term:`LBYL` style 
+      statements.  The technique contrasts with the :term:`LBYL` style
       common to many other languages such as C.
 
    expression
@@ -192,14 +195,14 @@
       which are not compatible with the current interpreter.  For example, the
       expression ``11/4`` currently evaluates to ``2``. If the module in which
       it is executed had enabled *true division* by executing::
-    
+
          from __future__ import division
-    
+
       the expression ``11/4`` would evaluate to ``2.75``.  By importing the
       :mod:`__future__` module and evaluating its variables, you can see when a
       new feature was first added to the language and when it will become the
       default::
-    
+
          >>> import __future__
          >>> __future__.division
          _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
@@ -208,7 +211,7 @@
       The process of freeing memory when it is not used anymore.  Python
       performs garbage collection via reference counting and a cyclic garbage
       collector that is able to detect and break reference cycles.
-    
+
    generator
       A function which returns an iterator.  It looks like a normal function
       except that values are returned to the caller using a :keyword:`yield`
@@ -218,21 +221,21 @@
       stopped at the :keyword:`yield` keyword (returning the result) and is
       resumed there when the next element is requested by calling the
       :meth:`next` method of the returned iterator.
-    
+
       .. index:: single: generator expression
-    
+
    generator expression
       An expression that returns a generator.  It looks like a normal expression
       followed by a :keyword:`for` expression defining a loop variable, range,
       and an optional :keyword:`if` expression.  The combined expression
       generates values for an enclosing function::
-    
+
          >>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
          285
-    
+
    GIL
       See :term:`global interpreter lock`.
-    
+
    global interpreter lock
       The lock used by Python threads to assure that only one thread
       executes in the :term:`CPython` :term:`virtual machine` at a time.
@@ -258,21 +261,21 @@
       containers (such as lists or dictionaries) are.  Objects which are
       instances of user-defined classes are hashable by default; they all
       compare unequal, and their hash value is their :func:`id`.
-    
+
    IDLE
       An Integrated Development Environment for Python.  IDLE is a basic editor
       and interpreter environment which ships with the standard distribution of
       Python.  Good for beginners, it also serves as clear example code for
       those wanting to implement a moderately sophisticated, multi-platform GUI
       application.
-    
+
    immutable
       An object with a fixed value.  Immutable objects include numbers, strings and
       tuples.  Such an object cannot be altered.  A new object has to
       be created if a different value has to be stored.  They play an important
       role in places where a constant hash value is needed, for example as a key
       in a dictionary.
-    
+
    integer division
       Mathematical division discarding any remainder.  For example, the
       expression ``11/4`` currently evaluates to ``2`` in contrast to the
@@ -284,7 +287,7 @@
       divided by a float will result in a float value, possibly with a decimal
       fraction.  Integer division can be forced by using the ``//`` operator
       instead of the ``/`` operator.  See also :term:`__future__`.
-    
+
    interactive
       Python has an interactive interpreter which means you can enter
       statements and expressions at the interpreter prompt, immediately
@@ -292,7 +295,7 @@
       arguments (possibly by selecting it from your computer's main
       menu). It is a very powerful way to test out new ideas or inspect
       modules and packages (remember ``help(x)``).
-    
+
    interpreted
       Python is an interpreted language, as opposed to a compiled one,
       though the distinction can be blurry because of the presence of the
@@ -301,7 +304,7 @@
       Interpreted languages typically have a shorter development/debug cycle
       than compiled ones, though their programs generally also run more
       slowly.  See also :term:`interactive`.
-    
+
    iterable
       A container object capable of returning its members one at a
       time. Examples of iterables include all sequence types (such as
@@ -317,7 +320,7 @@
       statement does that automatically for you, creating a temporary unnamed
       variable to hold the iterator for the duration of the loop.  See also
       :term:`iterator`, :term:`sequence`, and :term:`generator`.
-    
+
    iterator
       An object representing a stream of data.  Repeated calls to the iterator's
       :meth:`next` method return successive items in the stream.  When no more
@@ -332,7 +335,7 @@
       :func:`iter` function or use it in a :keyword:`for` loop.  Attempting this
       with an iterator will just return the same exhausted iterator object used
       in the previous iteration pass, making it appear like an empty container.
-    
+
       More information can be found in :ref:`typeiter`.
 
    keyword argument
@@ -356,7 +359,7 @@
       A built-in Python :term:`sequence`.  Despite its name it is more akin
       to an array in other languages than to a linked list since access to
       elements are O(1).
-    
+
    list comprehension
       A compact way to process all or part of the elements in a sequence and
       return a list with the results.  ``result = ["0x%02x" % x for x in
@@ -364,11 +367,11 @@
       even hex numbers (0x..) in the range from 0 to 255. The :keyword:`if`
       clause is optional.  If omitted, all elements in ``range(256)`` are
       processed.
-    
+
    mapping
       A container object (such as :class:`dict`) which supports arbitrary key
       lookups using the special method :meth:`__getitem__`.
-    
+
    metaclass
       The class of a class.  Class definitions create a class name, a class
       dictionary, and a list of base classes.  The metaclass is responsible for
@@ -387,7 +390,7 @@
       of an instance of that class, the method will get the instance object as
       its first :term:`argument` (which is usually called ``self``).
       See :term:`function` and :term:`nested scope`.
-    
+
    mutable
       Mutable objects can change their value but keep their :func:`id`.  See
       also :term:`immutable`.
@@ -404,7 +407,7 @@
       :func:`collections.namedtuple`.  The latter approach automatically
       provides extra features such as a self-documenting representation like
       ``Employee(name='jones', title='programmer')``.
-    
+
    namespace
       The place where a variable is stored.  Namespaces are implemented as
       dictionaries.  There are the local, global and builtin namespaces as well
@@ -416,7 +419,7 @@
       :func:`random.seed` or :func:`itertools.izip` makes it clear that those
       functions are implemented by the :mod:`random` and :mod:`itertools`
       modules, respectively.
-    
+
    nested scope
       The ability to refer to a variable in an enclosing definition.  For
       instance, a function defined inside another function can refer to
@@ -424,7 +427,7 @@
       reference and not for assignment which will always write to the innermost
       scope.  In contrast, local variables both read and write in the innermost
       scope.  Likewise, global variables read and write to the global namespace.
-    
+
    new-style class
       Any class which inherits from :class:`object`.  This includes all built-in
       types like :class:`list` and :class:`dict`.  Only new-style classes can
@@ -437,7 +440,7 @@
       Any data with state (attributes or value) and defined behavior
       (methods).  Also the ultimate base class of any :term:`new-style
       class`.
-    
+
    positional argument
       The arguments assigned to local names inside a function or method,
       determined by the order in which they were given in the call.  ``*`` is
@@ -445,7 +448,7 @@
       definition), or pass several arguments as a list to a function.  See
       :term:`argument`.
 
-   Python 3000 
+   Python 3000
       Nickname for the next major Python version, 3.0 (coined long ago
       when the release of version 3 was something in the distant future.)  This
       is also abbreviated "Py3k".
@@ -457,7 +460,7 @@
       to loop over all elements of an iterable using a :keyword:`for`
       statement.  Many other languages don't have this type of construct, so
       people unfamiliar with Python sometimes use a numerical counter instead::
-     
+
           for i in range(len(food)):
               print food[i]
 
@@ -480,7 +483,7 @@
       dictionaries.  Though popular, the technique is somewhat tricky to get
       right and is best reserved for rare cases where there are large numbers of
       instances in a memory-critical application.
-    
+
    sequence
       An :term:`iterable` which supports efficient element access using integer
       indices via the :meth:`__getitem__` special method and defines a
@@ -498,6 +501,12 @@
       (subscript) notation uses :class:`slice` objects internally (or in older
       versions, :meth:`__getslice__` and :meth:`__setslice__`).
 
+   special method
+      A method that is called implicitly by Python to execute a certain
+      operation on a type, such as addition.  Such methods have names starting
+      and ending with double underscores.  Special methods are documented in
+      :ref:`specialnames`.
+
    statement
       A statement is part of a suite (a "block" of code).  A statement is either
       an :term:`expression` or a one of several constructs with a keyword, such
@@ -520,7 +529,7 @@
    virtual machine
       A computer defined entirely in software.  Python's virtual machine
       executes the :term:`bytecode` emitted by the bytecode compiler.
-    
+
    Zen of Python
       Listing of Python design principles and philosophies that are helpful in
       understanding and using the language.  The listing can be found by typing

Modified: python/branches/tlee-ast-optimize/Doc/howto/curses.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/curses.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/curses.rst	Wed Jan 14 13:24:17 2009
@@ -297,7 +297,7 @@
 could code::
 
    stdscr.addstr(0, 0, "Current mode: Typing mode",
-   	      curses.A_REVERSE)
+                 curses.A_REVERSE)
    stdscr.refresh()
 
 The curses library also supports color on those terminals that provide it, The
@@ -399,8 +399,8 @@
 
    curses.echo()            # Enable echoing of characters
 
-   # Get a 15-character string, with the cursor on the top line 
-   s = stdscr.getstr(0,0, 15)  
+   # Get a 15-character string, with the cursor on the top line
+   s = stdscr.getstr(0,0, 15)
 
 The Python :mod:`curses.textpad` module supplies something better. With it, you
 can turn a window into a text box that supports an Emacs-like set of

Modified: python/branches/tlee-ast-optimize/Doc/howto/doanddont.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/doanddont.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/doanddont.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ************************************
-  Idioms and Anti-Idioms in Python  
+  Idioms and Anti-Idioms in Python
 ************************************
 
 :Author: Moshe Zadka
@@ -127,7 +127,7 @@
    # bar.py
    from foo import a
    if something():
-       a = 2 # danger: foo.a != a 
+       a = 2 # danger: foo.a != a
 
 Good example::
 
@@ -303,6 +303,6 @@
 
 This version is bulletproof::
 
-   value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9] 
+   value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9]
            + calculate_number(10, 20)*forbulate(500, 360))
 

Modified: python/branches/tlee-ast-optimize/Doc/howto/functional.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/functional.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/functional.rst	Wed Jan 14 13:24:17 2009
@@ -145,7 +145,7 @@
 functions are also easier to read and to check for errors.
 
 
-Ease of debugging and testing 
+Ease of debugging and testing
 -----------------------------
 
 Testing and debugging a functional-style program is easier.
@@ -213,7 +213,7 @@
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
-    >>>      
+    >>>
 
 Python expects iterable objects in several different contexts, the most
 important being the ``for`` statement.  In the statement ``for X in Y``, Y must
@@ -362,7 +362,7 @@
 comprehensions are surrounded by square brackets ("[]").  Generator expressions
 have the form::
 
-    ( expression for expr in sequence1 
+    ( expression for expr in sequence1
                  if condition1
                  for expr2 in sequence2
                  if condition2
@@ -404,7 +404,7 @@
                  if not (conditionN):
                      continue   # Skip this element
 
-                 # Output the value of 
+                 # Output the value of
                  # the expression.
 
 This means that when there are multiple ``for...in`` clauses but no ``if``
@@ -418,8 +418,8 @@
     >>> seq1 = 'abc'
     >>> seq2 = (1,2,3)
     >>> [(x,y) for x in seq1 for y in seq2]
-    [('a', 1), ('a', 2), ('a', 3), 
-     ('b', 1), ('b', 2), ('b', 3), 
+    [('a', 1), ('a', 2), ('a', 3),
+     ('b', 1), ('b', 2), ('b', 3),
      ('c', 1), ('c', 2), ('c', 3)]
 
 To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
@@ -585,7 +585,7 @@
     9
     >>> print it.next()
     Traceback (most recent call last):
-      File ``t.py'', line 15, in ?
+      File "t.py", line 15, in ?
         print it.next()
     StopIteration
 
@@ -728,7 +728,7 @@
         if line.strip() == '':
             print 'Blank line at line #%i' % i
 
-``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the
+``sorted(iterable, [cmp=None], [key=None], [reverse=False])`` collects all the
 elements of the iterable into a list, sorts the list, and returns the sorted
 result.  The ``cmp``, ``key``, and ``reverse`` arguments are passed through to
 the constructed list's ``.sort()`` method. ::
@@ -759,7 +759,7 @@
     True
     >>> all([0,1,0])
     False
-    >>> all([0,0,0]) 
+    >>> all([0,0,0])
     False
     >>> all([1,1,1])
     True
@@ -845,7 +845,7 @@
 4) Convert the lambda to a def statement, using that name.
 5) Remove the comment.
 
-I really like these rules, but you're free to disagree 
+I really like these rules, but you're free to disagree
 about whether this lambda-free style is better.
 
 
@@ -970,7 +970,7 @@
 ``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
 of tuples, and calls ``f()`` using these tuples as the arguments::
 
-    itertools.starmap(os.path.join, 
+    itertools.starmap(os.path.join,
                       [('/usr', 'bin', 'java'), ('/bin', 'python'),
                        ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
     =>
@@ -1039,9 +1039,9 @@
 
 ::
 
-    city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), 
+    city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
                  ('Anchorage', 'AK'), ('Nome', 'AK'),
-                 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), 
+                 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
                  ...
                 ]
 
@@ -1056,7 +1056,7 @@
     where
     iterator-1 =>
       ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
-    iterator-2 => 
+    iterator-2 =>
       ('Anchorage', 'AK'), ('Nome', 'AK')
     iterator-3 =>
       ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
@@ -1150,7 +1150,7 @@
 
     >>> double(add(5, 6))
     22
-                    
+
 The ``unpack`` keyword is provided to work around the fact that Python functions
 are not always `fully curried <http://en.wikipedia.org/wiki/Currying>`__.  By
 default, it is expected that the ``inner`` function will return a single object
@@ -1159,15 +1159,15 @@
 will be expanded before being passed to ``outer``. Put simply, ::
 
     compose(f, g)(5, 6)
-                    
+
 is equivalent to::
 
     f(g(5, 6))
-                    
+
 while ::
 
     compose(f, g, unpack=True)(5, 6)
-                    
+
 is equivalent to::
 
     f(*g(5, 6))
@@ -1178,20 +1178,20 @@
 ``functional`` and ``functools``). ::
 
     from functional import compose, partial
-        
+
     multi_compose = partial(reduce, compose)
-        
-    
+
+
 We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of
 ``"".join(...)`` that converts its arguments to string::
 
     from functional import compose, partial
-        
+
     join = compose("".join, partial(map, str))
 
 
 ``flip(func)``
-                    
+
 ``flip()`` wraps the callable in ``func`` and causes it to receive its
 non-keyword arguments in reverse order. ::
 
@@ -1206,7 +1206,7 @@
     (7, 6, 5)
 
 ``foldl(func, start, iterable)``
-                    
+
 ``foldl()`` takes a binary function, a starting value (usually some kind of
 'zero'), and an iterable.  The function is applied to the starting value and the
 first element of the list, then the result of that and the second element of the
@@ -1220,7 +1220,7 @@
 
     f(f(f(0, 1), 2), 3)
 
-    
+
 ``foldl()`` is roughly equivalent to the following recursive function::
 
     def foldl(func, start, seq):
@@ -1298,7 +1298,7 @@
 Text Processing".
 
 Mertz also wrote a 3-part series of articles on functional programming
-for IBM's DeveloperWorks site; see 
+for IBM's DeveloperWorks site; see
 `part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__,
 `part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and
 `part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__,

Modified: python/branches/tlee-ast-optimize/Doc/howto/regex.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/regex.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/regex.rst	Wed Jan 14 13:24:17 2009
@@ -1,7 +1,7 @@
 .. _regex-howto:
 
 ****************************
-  Regular Expression HOWTO  
+  Regular Expression HOWTO
 ****************************
 
 :Author: A.M. Kuchling
@@ -611,7 +611,7 @@
    is to read? ::
 
       charref = re.compile(r"""
-       &[#]		     # Start of a numeric entity reference
+       &[#]                # Start of a numeric entity reference
        (
            0[0-7]+         # Octal form
          | [0-9]+          # Decimal form
@@ -732,7 +732,7 @@
       >>> p = re.compile('\bclass\b')
       >>> print p.search('no class at all')
       None
-      >>> print p.search('\b' + 'class' + '\b')  
+      >>> print p.search('\b' + 'class' + '\b')
       <re.MatchObject instance at 80c3ee0>
 
    Second, inside a character class, where there's no use for this assertion,
@@ -917,7 +917,7 @@
 
    InternalDate = re.compile(r'INTERNALDATE "'
            r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
-   	r'(?P<year>[0-9][0-9][0-9][0-9])'
+           r'(?P<year>[0-9][0-9][0-9][0-9])'
            r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
            r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
            r'"')
@@ -1236,9 +1236,9 @@
 only report a successful match which will start at 0; if the match wouldn't
 start at zero,  :func:`match` will *not* report it. ::
 
-   >>> print re.match('super', 'superstition').span()  
+   >>> print re.match('super', 'superstition').span()
    (0, 5)
-   >>> print re.match('super', 'insuperable')    
+   >>> print re.match('super', 'insuperable')
    None
 
 On the other hand, :func:`search` will scan forward through the string,

Modified: python/branches/tlee-ast-optimize/Doc/howto/sockets.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/sockets.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/sockets.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  Socket Programming HOWTO  
+  Socket Programming HOWTO
 ****************************
 
 :Author: Gordon McMillan
@@ -63,7 +63,7 @@
    #create an INET, STREAMing socket
    s = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM)
-   #now connect to the web server on port 80 
+   #now connect to the web server on port 80
    # - the normal http port
    s.connect(("www.mcmillan-inc.com", 80))
 
@@ -78,7 +78,7 @@
    #create an INET, STREAMing socket
    serversocket = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM)
-   #bind the socket to a public host, 
+   #bind the socket to a public host,
    # and a well-known port
    serversocket.bind((socket.gethostname(), 80))
    #become a server socket
@@ -185,38 +185,38 @@
 length message::
 
    class mysocket:
-       '''demonstration class only 
+       '''demonstration class only
          - coded for clarity, not efficiency
        '''
 
        def __init__(self, sock=None):
-   	if sock is None:
-   	    self.sock = socket.socket(
-   		socket.AF_INET, socket.SOCK_STREAM)
-   	else:
-   	    self.sock = sock
+           if sock is None:
+               self.sock = socket.socket(
+                   socket.AF_INET, socket.SOCK_STREAM)
+           else:
+               self.sock = sock
 
        def connect(self, host, port):
-   	self.sock.connect((host, port))
+           self.sock.connect((host, port))
 
        def mysend(self, msg):
-   	totalsent = 0
-   	while totalsent < MSGLEN:
-   	    sent = self.sock.send(msg[totalsent:])
-   	    if sent == 0:
-   		raise RuntimeError, \
-   		    "socket connection broken"
-   	    totalsent = totalsent + sent
+           totalsent = 0
+           while totalsent < MSGLEN:
+               sent = self.sock.send(msg[totalsent:])
+               if sent == 0:
+                   raise RuntimeError, \
+                       "socket connection broken"
+               totalsent = totalsent + sent
 
        def myreceive(self):
-   	msg = ''
-   	while len(msg) < MSGLEN:
-   	    chunk = self.sock.recv(MSGLEN-len(msg))
-   	    if chunk == '':
-   		raise RuntimeError, \
-   		    "socket connection broken"
-   	    msg = msg + chunk
-   	return msg
+           msg = ''
+           while len(msg) < MSGLEN:
+               chunk = self.sock.recv(MSGLEN-len(msg))
+               if chunk == '':
+                   raise RuntimeError, \
+                       "socket connection broken"
+               msg = msg + chunk
+           return msg
 
 The sending code here is usable for almost any messaging scheme - in Python you
 send strings, and you can use ``len()`` to determine its length (even if it has
@@ -343,9 +343,9 @@
 
    ready_to_read, ready_to_write, in_error = \
                   select.select(
-                     potential_readers, 
-                     potential_writers, 
-                     potential_errs, 
+                     potential_readers,
+                     potential_writers,
+                     potential_errs,
                      timeout)
 
 You pass ``select`` three lists: the first contains all sockets that you might

Modified: python/branches/tlee-ast-optimize/Doc/howto/unicode.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/unicode.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/unicode.rst	Wed Jan 14 13:24:17 2009
@@ -30,8 +30,8 @@
 looking at Apple ][ BASIC programs, published in French-language publications in
 the mid-1980s, that had lines like these::
 
-	PRINT "FICHER EST COMPLETE."
-	PRINT "CARACTERE NON ACCEPTE."
+   PRINT "FICHIER EST COMPLETE."
+   PRINT "CARACTERE NON ACCEPTE."
 
 Those messages should contain accents, and they just look wrong to someone who
 can read French.
@@ -89,11 +89,11 @@
 character with value 0x12ca (4810 decimal).  The Unicode standard contains a lot
 of tables listing characters and their corresponding code points::
 
-	0061    'a'; LATIN SMALL LETTER A
-	0062    'b'; LATIN SMALL LETTER B
-	0063    'c'; LATIN SMALL LETTER C
-        ...
-	007B	'{'; LEFT CURLY BRACKET
+   0061    'a'; LATIN SMALL LETTER A
+   0062    'b'; LATIN SMALL LETTER B
+   0063    'c'; LATIN SMALL LETTER C
+   ...
+   007B    '{'; LEFT CURLY BRACKET
 
 Strictly, these definitions imply that it's meaningless to say 'this is
 character U+12ca'.  U+12ca is a code point, which represents some particular
@@ -122,8 +122,8 @@
 representation, the string "Python" would look like this::
 
        P           y           t           h           o           n
-    0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 
-       0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 
+    0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
+       0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 
 This representation is straightforward but using it presents a number of
 problems.
@@ -181,7 +181,7 @@
    between 128 and 255.
 3. Code points >0x7ff are turned into three- or four-byte sequences, where each
    byte of the sequence is between 128 and 255.
-    
+
 UTF-8 has several convenient properties:
 
 1. It can handle any Unicode code point.
@@ -252,7 +252,7 @@
     >>> unicode('abcdef' + chr(255))
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
-    UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: 
+    UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6:
                         ordinal not in range(128)
 
 The ``errors`` argument specifies the response when the input string can't be
@@ -264,7 +264,7 @@
     >>> unicode('\x80abc', errors='strict')
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
-    UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: 
+    UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
                         ordinal not in range(128)
     >>> unicode('\x80abc', errors='replace')
     u'\ufffdabc'
@@ -350,7 +350,7 @@
     >>> u2 = utf8_version.decode('utf-8')            # Decode using UTF-8
     >>> u == u2                                      # The two strings match
     True
- 
+
 The low-level routines for registering and accessing the available encodings are
 found in the :mod:`codecs` module.  However, the encoding and decoding functions
 returned by this module are usually more low-level than is comfortable, so I'm
@@ -362,8 +362,8 @@
 The most commonly used part of the :mod:`codecs` module is the
 :func:`codecs.open` function which will be discussed in the section on input and
 output.
-            
-            
+
+
 Unicode Literals in Python Source Code
 --------------------------------------
 
@@ -381,10 +381,10 @@
 
     >>> s = u"a\xac\u1234\u20ac\U00008000"
                ^^^^ two-digit hex escape
-                   ^^^^^^ four-digit Unicode escape 
+                   ^^^^^^ four-digit Unicode escape
                                ^^^^^^^^^^ eight-digit Unicode escape
     >>> for c in s:  print ord(c),
-    ... 
+    ...
     97 172 4660 8364 32768
 
 Using escape sequences for code points greater than 127 is fine in small doses,
@@ -404,10 +404,10 @@
 
     #!/usr/bin/env python
     # -*- coding: latin-1 -*-
-    
+
     u = u'abcdé'
     print ord(u[-1])
-    
+
 The syntax is inspired by Emacs's notation for specifying variables local to a
 file.  Emacs supports many different variables, but Python only supports
 'coding'.  The ``-*-`` symbols indicate to Emacs that the comment is special;
@@ -427,10 +427,10 @@
 When you run it with Python 2.4, it will output the following warning::
 
     amk:~$ python p263.py
-    sys:1: DeprecationWarning: Non-ASCII character '\xe9' 
-         in file p263.py on line 2, but no encoding declared; 
+    sys:1: DeprecationWarning: Non-ASCII character '\xe9'
+         in file p263.py on line 2, but no encoding declared;
          see http://www.python.org/peps/pep-0263.html for details
-  
+
 
 Unicode Properties
 ------------------
@@ -446,13 +446,13 @@
 prints the numeric value of one particular character::
 
     import unicodedata
-    
+
     u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231)
-    
+
     for i, c in enumerate(u):
         print i, '%04x' % ord(c), unicodedata.category(c),
         print unicodedata.name(c)
-    
+
     # Get numeric value of second character
     print unicodedata.numeric(u[1])
 
@@ -597,25 +597,25 @@
 path will return the 8-bit versions of the filenames.  For example, assuming the
 default filesystem encoding is UTF-8, running the following program::
 
-	fn = u'filename\u4500abc'
-	f = open(fn, 'w')
-	f.close()
-
-	import os
-	print os.listdir('.')
-	print os.listdir(u'.')
+   fn = u'filename\u4500abc'
+   f = open(fn, 'w')
+   f.close()
+
+   import os
+   print os.listdir('.')
+   print os.listdir(u'.')
 
 will produce the following output::
 
-	amk:~$ python t.py
-	['.svn', 'filename\xe4\x94\x80abc', ...]
-	[u'.svn', u'filename\u4500abc', ...]
+   amk:~$ python t.py
+   ['.svn', 'filename\xe4\x94\x80abc', ...]
+   [u'.svn', u'filename\u4500abc', ...]
 
 The first list contains UTF-8-encoded filenames, and the second list contains
 the Unicode versions.
 
 
-	
+
 Tips for Writing Unicode-aware Programs
 ---------------------------------------
 
@@ -661,7 +661,7 @@
         unicode_name = filename.decode(encoding)
         f = open(unicode_name, 'r')
         # ... return contents of file ...
-        
+
 However, if an attacker could specify the ``'base64'`` encoding, they could pass
 ``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
 ``'/etc/passwd'``, to read a system file.  The above code looks for ``'/'``
@@ -697,32 +697,32 @@
 .. comment Describe obscure -U switch somewhere?
 .. comment Describe use of codecs.StreamRecoder and StreamReaderWriter
 
-.. comment 
+.. comment
    Original outline:
 
    - [ ] Unicode introduction
        - [ ] ASCII
        - [ ] Terms
-	   - [ ] Character
-	   - [ ] Code point
-	 - [ ] Encodings
-	    - [ ] Common encodings: ASCII, Latin-1, UTF-8
+           - [ ] Character
+           - [ ] Code point
+         - [ ] Encodings
+            - [ ] Common encodings: ASCII, Latin-1, UTF-8
        - [ ] Unicode Python type
-	   - [ ] Writing unicode literals
-	       - [ ] Obscurity: -U switch
-	   - [ ] Built-ins
-	       - [ ] unichr()
-	       - [ ] ord()
-	       - [ ] unicode() constructor
-	   - [ ] Unicode type
-	       - [ ] encode(), decode() methods
+           - [ ] Writing unicode literals
+               - [ ] Obscurity: -U switch
+           - [ ] Built-ins
+               - [ ] unichr()
+               - [ ] ord()
+               - [ ] unicode() constructor
+           - [ ] Unicode type
+               - [ ] encode(), decode() methods
        - [ ] Unicodedata module for character properties
        - [ ] I/O
-	   - [ ] Reading/writing Unicode data into files
-	       - [ ] Byte-order marks
-	   - [ ] Unicode filenames
+           - [ ] Reading/writing Unicode data into files
+               - [ ] Byte-order marks
+           - [ ] Unicode filenames
        - [ ] Writing Unicode programs
-	   - [ ] Do everything in Unicode
-	   - [ ] Declaring source code encodings (PEP 263)
+           - [ ] Do everything in Unicode
+           - [ ] Declaring source code encodings (PEP 263)
        - [ ] Other issues
-	   - [ ] Building Python (UCS2, UCS4)
+           - [ ] Building Python (UCS2, UCS4)

Modified: python/branches/tlee-ast-optimize/Doc/howto/urllib2.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/urllib2.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/urllib2.rst	Wed Jan 14 13:24:17 2009
@@ -10,7 +10,7 @@
     HOWTO, available at `urllib2 - Le Manuel manquant
     <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_.
 
- 
+
 
 Introduction
 ============
@@ -19,9 +19,9 @@
 
     You may also find useful the following article on fetching web resources
     with Python :
-    
+
     * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_
-    
+
         A tutorial on *Basic Authentication*, with examples in Python.
 
 **urllib2** is a `Python <http://www.python.org>`_ module for fetching URLs
@@ -98,7 +98,7 @@
 *not* from ``urllib2``. ::
 
     import urllib
-    import urllib2  
+    import urllib2
 
     url = 'http://www.someserver.com/cgi-bin/register.cgi'
     values = {'name' : 'Michael Foord',
@@ -161,15 +161,15 @@
 Explorer [#]_. ::
 
     import urllib
-    import urllib2  
-    
+    import urllib2
+
     url = 'http://www.someserver.com/cgi-bin/register.cgi'
-    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' 
+    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
     values = {'name' : 'Michael Foord',
               'location' : 'Northampton',
               'language' : 'Python' }
     headers = { 'User-Agent' : user_agent }
-    
+
     data = urllib.urlencode(values)
     req = urllib2.Request(url, data, headers)
     response = urllib2.urlopen(req)
@@ -183,7 +183,7 @@
 ===================
 
 *urlopen* raises :exc:`URLError` when it cannot handle a response (though as usual
-with Python APIs, builtin exceptions such as 
+with Python APIs, builtin exceptions such as
 :exc:`ValueError`, :exc:`TypeError` etc. may also
 be raised).
 
@@ -309,18 +309,18 @@
 geturl, and info, methods. ::
 
     >>> req = urllib2.Request('http://www.python.org/fish.html')
-    >>> try: 
+    >>> try:
     >>>     urllib2.urlopen(req)
     >>> except URLError, e:
     >>>     print e.code
     >>>     print e.read()
-    >>> 
+    >>>
     404
-    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
+    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
-    <?xml-stylesheet href="./css/ht2html.css" 
+    <?xml-stylesheet href="./css/ht2html.css"
         type="text/css"?>
-    <html><head><title>Error 404: File Not Found</title> 
+    <html><head><title>Error 404: File Not Found</title>
     ...... etc...
 
 Wrapping it Up
@@ -372,7 +372,7 @@
             print 'Error code: ', e.code
     else:
         # everything is fine
-        
+
 
 info and geturl
 ===============
@@ -443,7 +443,7 @@
 and a 'realm'. The header looks like : ``Www-authenticate: SCHEME
 realm="REALM"``.
 
-e.g. :: 
+e.g. ::
 
     Www-authenticate: Basic realm="cPanel Users"
 
@@ -467,24 +467,24 @@
 than the URL you pass to .add_password() will also match. ::
 
     # create a password manager
-    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()                        
+    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
 
     # Add the username and password.
-    # If we knew the realm, we could use it instead of ``None``.
+    # If we knew the realm, we could use it instead of None.
     top_level_url = "http://example.com/foo/"
     password_mgr.add_password(None, top_level_url, username, password)
 
-    handler = urllib2.HTTPBasicAuthHandler(password_mgr)                            
+    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
 
     # create "opener" (OpenerDirector instance)
-    opener = urllib2.build_opener(handler)                       
+    opener = urllib2.build_opener(handler)
 
     # use the opener to fetch a URL
-    opener.open(a_url)      
+    opener.open(a_url)
 
     # Install the opener.
     # Now all calls to urllib2.urlopen use our opener.
-    urllib2.install_opener(opener)                               
+    urllib2.install_opener(opener)
 
 .. note::
 
@@ -540,7 +540,7 @@
 
     # timeout in seconds
     timeout = 10
-    socket.setdefaulttimeout(timeout) 
+    socket.setdefaulttimeout(timeout)
 
     # this call to urllib2.urlopen now uses the default timeout
     # we have set in the socket module
@@ -557,7 +557,7 @@
 This document was reviewed and revised by John Lee.
 
 .. [#] For an introduction to the CGI protocol see
-       `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_. 
+       `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_.
 .. [#] Like Google for example. The *proper* way to use google from a program
        is to use `PyGoogle <http://pygoogle.sourceforge.net>`_ of course. See
        `Voidspace Google <http://www.voidspace.org.uk/python/recipebook.shtml#google>`_
@@ -574,6 +574,6 @@
        is set to use the proxy, which urllib2 picks up on. In order to test
        scripts with a localhost server, I have to prevent urllib2 from using
        the proxy.
-.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe 
+.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
        <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195>`_.
- 
+

Modified: python/branches/tlee-ast-optimize/Doc/howto/webservers.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/howto/webservers.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/howto/webservers.rst	Wed Jan 14 13:24:17 2009
@@ -88,7 +88,7 @@
    <http://wiki.python.org/moin/CgiScripts>`_ with some additional information
    about CGI in Python.
 
-   
+
 Simple script for testing CGI
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
@@ -386,7 +386,7 @@
 
    You might be interested in some WSGI-supporting modules already contained in
    the standard library, namely:
-    
+
    * :mod:`wsgiref` -- some tiny utilities and servers for WSGI
 
 
@@ -499,7 +499,7 @@
    time in looking through the most popular ones.  Some frameworks have their
    own template engine or have a recommentation for one.  It's wise to use
    these.
-  
+
    Popular template engines include:
 
    * Mako
@@ -687,7 +687,7 @@
 found in the Python wiki.
 
 .. seealso::
-    
+
    The Python wiki contains an extensive list of `web frameworks
    <http://wiki.python.org/moin/WebFrameworks>`_.
 

Modified: python/branches/tlee-ast-optimize/Doc/includes/mp_distributing.py
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/includes/mp_distributing.py	(original)
+++ python/branches/tlee-ast-optimize/Doc/includes/mp_distributing.py	Wed Jan 14 13:24:17 2009
@@ -1,364 +1,364 @@
-#
-# Module to allow spawning of processes on foreign host
-#
-# Depends on `multiprocessing` package -- tested with `processing-0.60`
-#
-# Copyright (c) 2006-2008, R Oudkerk
-# All rights reserved.
-#
-
-__all__ = ['Cluster', 'Host', 'get_logger', 'current_process']
-
-#
-# Imports
-#
-
-import sys
-import os
-import tarfile
-import shutil
-import subprocess
-import logging
-import itertools
-import Queue
-
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
-
-from multiprocessing import Process, current_process, cpu_count
-from multiprocessing import util, managers, connection, forking, pool
-
-#
-# Logging
-#
-
-def get_logger():
-    return _logger
-
-_logger = logging.getLogger('distributing')
-_logger.propogate = 0
-
-_formatter = logging.Formatter(util.DEFAULT_LOGGING_FORMAT)
-_handler = logging.StreamHandler()
-_handler.setFormatter(_formatter)
-_logger.addHandler(_handler)
-
-info = _logger.info
-debug = _logger.debug
-
-#
-# Get number of cpus
-#
-
-try:
-    slot_count = cpu_count()
-except NotImplemented:
-    slot_count = 1
-        
-#
-# Manager type which spawns subprocesses
-#
-
-class HostManager(managers.SyncManager):
-    '''
-    Manager type used for spawning processes on a (presumably) foreign host
-    '''    
-    def __init__(self, address, authkey):
-        managers.SyncManager.__init__(self, address, authkey)
-        self._name = 'Host-unknown'
-
-    def Process(self, group=None, target=None, name=None, args=(), kwargs={}):
-        if hasattr(sys.modules['__main__'], '__file__'):
-            main_path = os.path.basename(sys.modules['__main__'].__file__)
-        else:
-            main_path = None
-        data = pickle.dumps((target, args, kwargs))
-        p = self._RemoteProcess(data, main_path)
-        if name is None:
-            temp = self._name.split('Host-')[-1] + '/Process-%s'
-            name = temp % ':'.join(map(str, p.get_identity()))
-        p.set_name(name)
-        return p
-
-    @classmethod
-    def from_address(cls, address, authkey):
-        manager = cls(address, authkey)
-        managers.transact(address, authkey, 'dummy')
-        manager._state.value = managers.State.STARTED
-        manager._name = 'Host-%s:%s' % manager.address
-        manager.shutdown = util.Finalize(
-            manager, HostManager._finalize_host,
-            args=(manager._address, manager._authkey, manager._name),
-            exitpriority=-10
-            )
-        return manager
-
-    @staticmethod
-    def _finalize_host(address, authkey, name):
-        managers.transact(address, authkey, 'shutdown')
-        
-    def __repr__(self):
-        return '<Host(%s)>' % self._name
-
-#
-# Process subclass representing a process on (possibly) a remote machine
-#
-
-class RemoteProcess(Process):
-    '''
-    Represents a process started on a remote host
-    '''
-    def __init__(self, data, main_path):
-        assert not main_path or os.path.basename(main_path) == main_path
-        Process.__init__(self)
-        self._data = data
-        self._main_path = main_path
-        
-    def _bootstrap(self):
-        forking.prepare({'main_path': self._main_path})
-        self._target, self._args, self._kwargs = pickle.loads(self._data)
-        return Process._bootstrap(self)
-        
-    def get_identity(self):
-        return self._identity
-
-HostManager.register('_RemoteProcess', RemoteProcess)
-
-#
-# A Pool class that uses a cluster
-#
-
-class DistributedPool(pool.Pool):
-    
-    def __init__(self, cluster, processes=None, initializer=None, initargs=()):
-        self._cluster = cluster
-        self.Process = cluster.Process
-        pool.Pool.__init__(self, processes or len(cluster),
-                           initializer, initargs)
-        
-    def _setup_queues(self):
-        self._inqueue = self._cluster._SettableQueue()
-        self._outqueue = self._cluster._SettableQueue()
-        self._quick_put = self._inqueue.put
-        self._quick_get = self._outqueue.get
-
-    @staticmethod
-    def _help_stuff_finish(inqueue, task_handler, size):
-        inqueue.set_contents([None] * size)
-
-#
-# Manager type which starts host managers on other machines
-#
-
-def LocalProcess(**kwds):
-    p = Process(**kwds)
-    p.set_name('localhost/' + p.name)
-    return p
-
-class Cluster(managers.SyncManager):
-    '''
-    Represents collection of slots running on various hosts.
-    
-    `Cluster` is a subclass of `SyncManager` so it allows creation of
-    various types of shared objects.
-    '''
-    def __init__(self, hostlist, modules):
-        managers.SyncManager.__init__(self, address=('localhost', 0))
-        self._hostlist = hostlist
-        self._modules = modules
-        if __name__ not in modules:
-            modules.append(__name__)
-        files = [sys.modules[name].__file__ for name in modules]
-        for i, file in enumerate(files):
-            if file.endswith('.pyc') or file.endswith('.pyo'):
-                files[i] = file[:-4] + '.py'
-        self._files = [os.path.abspath(file) for file in files]
-        
-    def start(self):
-        managers.SyncManager.start(self)
-        
-        l = connection.Listener(family='AF_INET', authkey=self._authkey)
-        
-        for i, host in enumerate(self._hostlist):
-            host._start_manager(i, self._authkey, l.address, self._files)
-
-        for host in self._hostlist:
-            if host.hostname != 'localhost':
-                conn = l.accept()
-                i, address, cpus = conn.recv()
-                conn.close()
-                other_host = self._hostlist[i]
-                other_host.manager = HostManager.from_address(address,
-                                                              self._authkey)
-                other_host.slots = other_host.slots or cpus
-                other_host.Process = other_host.manager.Process
-            else:
-                host.slots = host.slots or slot_count
-                host.Process = LocalProcess
-
-        self._slotlist = [
-            Slot(host) for host in self._hostlist for i in range(host.slots)
-            ]
-        self._slot_iterator = itertools.cycle(self._slotlist)
-        self._base_shutdown = self.shutdown
-        del self.shutdown
-        
-    def shutdown(self):
-        for host in self._hostlist:
-            if host.hostname != 'localhost':
-                host.manager.shutdown()
-        self._base_shutdown()
-        
-    def Process(self, group=None, target=None, name=None, args=(), kwargs={}):
-        slot = self._slot_iterator.next()
-        return slot.Process(
-            group=group, target=target, name=name, args=args, kwargs=kwargs
-            )
-
-    def Pool(self, processes=None, initializer=None, initargs=()):
-        return DistributedPool(self, processes, initializer, initargs)
-    
-    def __getitem__(self, i):
-        return self._slotlist[i]
-
-    def __len__(self):
-        return len(self._slotlist)
-
-    def __iter__(self):
-        return iter(self._slotlist)
-
-#
-# Queue subclass used by distributed pool
-#
-
-class SettableQueue(Queue.Queue):
-    def empty(self):
-        return not self.queue
-    def full(self):
-        return self.maxsize > 0 and len(self.queue) == self.maxsize
-    def set_contents(self, contents):
-        # length of contents must be at least as large as the number of
-        # threads which have potentially called get()
-        self.not_empty.acquire()
-        try:
-            self.queue.clear()
-            self.queue.extend(contents)
-            self.not_empty.notifyAll()
-        finally:
-            self.not_empty.release()
-            
-Cluster.register('_SettableQueue', SettableQueue)
-
-#
-# Class representing a notional cpu in the cluster
-#
-
-class Slot(object):
-    def __init__(self, host):
-        self.host = host
-        self.Process = host.Process
-
-#
-# Host
-#
-
-class Host(object):
-    '''
-    Represents a host to use as a node in a cluster.
-
-    `hostname` gives the name of the host.  If hostname is not
-    "localhost" then ssh is used to log in to the host.  To log in as
-    a different user use a host name of the form
-    "username at somewhere.org"
-
-    `slots` is used to specify the number of slots for processes on
-    the host.  This affects how often processes will be allocated to
-    this host.  Normally this should be equal to the number of cpus on
-    that host.
-    '''
-    def __init__(self, hostname, slots=None):
-        self.hostname = hostname
-        self.slots = slots
-        
-    def _start_manager(self, index, authkey, address, files):
-        if self.hostname != 'localhost':
-            tempdir = copy_to_remote_temporary_directory(self.hostname, files)
-            debug('startup files copied to %s:%s', self.hostname, tempdir)
-            p = subprocess.Popen(
-                ['ssh', self.hostname, 'python', '-c',
-                 '"import os; os.chdir(%r); '
-                 'from distributing import main; main()"' % tempdir],
-                stdin=subprocess.PIPE
-                )
-            data = dict(
-                name='BoostrappingHost', index=index,
-                dist_log_level=_logger.getEffectiveLevel(),
-                dir=tempdir, authkey=str(authkey), parent_address=address
-                )
-            pickle.dump(data, p.stdin, pickle.HIGHEST_PROTOCOL)
-            p.stdin.close()
-
-#
-# Copy files to remote directory, returning name of directory
-#
-
-unzip_code = '''"
-import tempfile, os, sys, tarfile
-tempdir = tempfile.mkdtemp(prefix='distrib-')
-os.chdir(tempdir)
-tf = tarfile.open(fileobj=sys.stdin, mode='r|gz')
-for ti in tf:
-    tf.extract(ti)
-print tempdir
-"'''
-
-def copy_to_remote_temporary_directory(host, files):
-    p = subprocess.Popen(
-        ['ssh', host, 'python', '-c', unzip_code],
-        stdout=subprocess.PIPE, stdin=subprocess.PIPE
-        )
-    tf = tarfile.open(fileobj=p.stdin, mode='w|gz')
-    for name in files:
-        tf.add(name, os.path.basename(name))
-    tf.close()
-    p.stdin.close()
-    return p.stdout.read().rstrip()
-
-#
-# Code which runs a host manager
-#
-
-def main():   
-    # get data from parent over stdin
-    data = pickle.load(sys.stdin)
-    sys.stdin.close()
-
-    # set some stuff
-    _logger.setLevel(data['dist_log_level'])
-    forking.prepare(data)
-    
-    # create server for a `HostManager` object
-    server = managers.Server(HostManager._registry, ('', 0), data['authkey'])
-    current_process()._server = server
-    
-    # report server address and number of cpus back to parent
-    conn = connection.Client(data['parent_address'], authkey=data['authkey'])
-    conn.send((data['index'], server.address, slot_count))
-    conn.close()
-    
-    # set name etc
-    current_process().set_name('Host-%s:%s' % server.address)
-    util._run_after_forkers()
-    
-    # register a cleanup function
-    def cleanup(directory):
-        debug('removing directory %s', directory)
-        shutil.rmtree(directory)
-        debug('shutting down host manager')
-    util.Finalize(None, cleanup, args=[data['dir']], exitpriority=0)
-    
-    # start host manager
-    debug('remote host manager starting in %s', data['dir'])
-    server.serve_forever()
+#
+# Module to allow spawning of processes on foreign host
+#
+# Depends on `multiprocessing` package -- tested with `processing-0.60`
+#
+# Copyright (c) 2006-2008, R Oudkerk
+# All rights reserved.
+#
+
+__all__ = ['Cluster', 'Host', 'get_logger', 'current_process']
+
+#
+# Imports
+#
+
+import sys
+import os
+import tarfile
+import shutil
+import subprocess
+import logging
+import itertools
+import Queue
+
+try:
+    import cPickle as pickle
+except ImportError:
+    import pickle
+
+from multiprocessing import Process, current_process, cpu_count
+from multiprocessing import util, managers, connection, forking, pool
+
+#
+# Logging
+#
+
+def get_logger():
+    return _logger
+
+_logger = logging.getLogger('distributing')
+_logger.propogate = 0
+
+_formatter = logging.Formatter(util.DEFAULT_LOGGING_FORMAT)
+_handler = logging.StreamHandler()
+_handler.setFormatter(_formatter)
+_logger.addHandler(_handler)
+
+info = _logger.info
+debug = _logger.debug
+
+#
+# Get number of cpus
+#
+
+try:
+    slot_count = cpu_count()
+except NotImplemented:
+    slot_count = 1
+
+#
+# Manager type which spawns subprocesses
+#
+
+class HostManager(managers.SyncManager):
+    '''
+    Manager type used for spawning processes on a (presumably) foreign host
+    '''
+    def __init__(self, address, authkey):
+        managers.SyncManager.__init__(self, address, authkey)
+        self._name = 'Host-unknown'
+
+    def Process(self, group=None, target=None, name=None, args=(), kwargs={}):
+        if hasattr(sys.modules['__main__'], '__file__'):
+            main_path = os.path.basename(sys.modules['__main__'].__file__)
+        else:
+            main_path = None
+        data = pickle.dumps((target, args, kwargs))
+        p = self._RemoteProcess(data, main_path)
+        if name is None:
+            temp = self._name.split('Host-')[-1] + '/Process-%s'
+            name = temp % ':'.join(map(str, p.get_identity()))
+        p.set_name(name)
+        return p
+
+    @classmethod
+    def from_address(cls, address, authkey):
+        manager = cls(address, authkey)
+        managers.transact(address, authkey, 'dummy')
+        manager._state.value = managers.State.STARTED
+        manager._name = 'Host-%s:%s' % manager.address
+        manager.shutdown = util.Finalize(
+            manager, HostManager._finalize_host,
+            args=(manager._address, manager._authkey, manager._name),
+            exitpriority=-10
+            )
+        return manager
+
+    @staticmethod
+    def _finalize_host(address, authkey, name):
+        managers.transact(address, authkey, 'shutdown')
+
+    def __repr__(self):
+        return '<Host(%s)>' % self._name
+
+#
+# Process subclass representing a process on (possibly) a remote machine
+#
+
+class RemoteProcess(Process):
+    '''
+    Represents a process started on a remote host
+    '''
+    def __init__(self, data, main_path):
+        assert not main_path or os.path.basename(main_path) == main_path
+        Process.__init__(self)
+        self._data = data
+        self._main_path = main_path
+
+    def _bootstrap(self):
+        forking.prepare({'main_path': self._main_path})
+        self._target, self._args, self._kwargs = pickle.loads(self._data)
+        return Process._bootstrap(self)
+
+    def get_identity(self):
+        return self._identity
+
+HostManager.register('_RemoteProcess', RemoteProcess)
+
+#
+# A Pool class that uses a cluster
+#
+
+class DistributedPool(pool.Pool):
+
+    def __init__(self, cluster, processes=None, initializer=None, initargs=()):
+        self._cluster = cluster
+        self.Process = cluster.Process
+        pool.Pool.__init__(self, processes or len(cluster),
+                           initializer, initargs)
+
+    def _setup_queues(self):
+        self._inqueue = self._cluster._SettableQueue()
+        self._outqueue = self._cluster._SettableQueue()
+        self._quick_put = self._inqueue.put
+        self._quick_get = self._outqueue.get
+
+    @staticmethod
+    def _help_stuff_finish(inqueue, task_handler, size):
+        inqueue.set_contents([None] * size)
+
+#
+# Manager type which starts host managers on other machines
+#
+
+def LocalProcess(**kwds):
+    p = Process(**kwds)
+    p.set_name('localhost/' + p.name)
+    return p
+
+class Cluster(managers.SyncManager):
+    '''
+    Represents collection of slots running on various hosts.
+
+    `Cluster` is a subclass of `SyncManager` so it allows creation of
+    various types of shared objects.
+    '''
+    def __init__(self, hostlist, modules):
+        managers.SyncManager.__init__(self, address=('localhost', 0))
+        self._hostlist = hostlist
+        self._modules = modules
+        if __name__ not in modules:
+            modules.append(__name__)
+        files = [sys.modules[name].__file__ for name in modules]
+        for i, file in enumerate(files):
+            if file.endswith('.pyc') or file.endswith('.pyo'):
+                files[i] = file[:-4] + '.py'
+        self._files = [os.path.abspath(file) for file in files]
+
+    def start(self):
+        managers.SyncManager.start(self)
+
+        l = connection.Listener(family='AF_INET', authkey=self._authkey)
+
+        for i, host in enumerate(self._hostlist):
+            host._start_manager(i, self._authkey, l.address, self._files)
+
+        for host in self._hostlist:
+            if host.hostname != 'localhost':
+                conn = l.accept()
+                i, address, cpus = conn.recv()
+                conn.close()
+                other_host = self._hostlist[i]
+                other_host.manager = HostManager.from_address(address,
+                                                              self._authkey)
+                other_host.slots = other_host.slots or cpus
+                other_host.Process = other_host.manager.Process
+            else:
+                host.slots = host.slots or slot_count
+                host.Process = LocalProcess
+
+        self._slotlist = [
+            Slot(host) for host in self._hostlist for i in range(host.slots)
+            ]
+        self._slot_iterator = itertools.cycle(self._slotlist)
+        self._base_shutdown = self.shutdown
+        del self.shutdown
+
+    def shutdown(self):
+        for host in self._hostlist:
+            if host.hostname != 'localhost':
+                host.manager.shutdown()
+        self._base_shutdown()
+
+    def Process(self, group=None, target=None, name=None, args=(), kwargs={}):
+        slot = self._slot_iterator.next()
+        return slot.Process(
+            group=group, target=target, name=name, args=args, kwargs=kwargs
+            )
+
+    def Pool(self, processes=None, initializer=None, initargs=()):
+        return DistributedPool(self, processes, initializer, initargs)
+
+    def __getitem__(self, i):
+        return self._slotlist[i]
+
+    def __len__(self):
+        return len(self._slotlist)
+
+    def __iter__(self):
+        return iter(self._slotlist)
+
+#
+# Queue subclass used by distributed pool
+#
+
+class SettableQueue(Queue.Queue):
+    def empty(self):
+        return not self.queue
+    def full(self):
+        return self.maxsize > 0 and len(self.queue) == self.maxsize
+    def set_contents(self, contents):
+        # length of contents must be at least as large as the number of
+        # threads which have potentially called get()
+        self.not_empty.acquire()
+        try:
+            self.queue.clear()
+            self.queue.extend(contents)
+            self.not_empty.notifyAll()
+        finally:
+            self.not_empty.release()
+
+Cluster.register('_SettableQueue', SettableQueue)
+
+#
+# Class representing a notional cpu in the cluster
+#
+
+class Slot(object):
+    def __init__(self, host):
+        self.host = host
+        self.Process = host.Process
+
+#
+# Host
+#
+
+class Host(object):
+    '''
+    Represents a host to use as a node in a cluster.
+
+    `hostname` gives the name of the host.  If hostname is not
+    "localhost" then ssh is used to log in to the host.  To log in as
+    a different user use a host name of the form
+    "username at somewhere.org"
+
+    `slots` is used to specify the number of slots for processes on
+    the host.  This affects how often processes will be allocated to
+    this host.  Normally this should be equal to the number of cpus on
+    that host.
+    '''
+    def __init__(self, hostname, slots=None):
+        self.hostname = hostname
+        self.slots = slots
+
+    def _start_manager(self, index, authkey, address, files):
+        if self.hostname != 'localhost':
+            tempdir = copy_to_remote_temporary_directory(self.hostname, files)
+            debug('startup files copied to %s:%s', self.hostname, tempdir)
+            p = subprocess.Popen(
+                ['ssh', self.hostname, 'python', '-c',
+                 '"import os; os.chdir(%r); '
+                 'from distributing import main; main()"' % tempdir],
+                stdin=subprocess.PIPE
+                )
+            data = dict(
+                name='BoostrappingHost', index=index,
+                dist_log_level=_logger.getEffectiveLevel(),
+                dir=tempdir, authkey=str(authkey), parent_address=address
+                )
+            pickle.dump(data, p.stdin, pickle.HIGHEST_PROTOCOL)
+            p.stdin.close()
+
+#
+# Copy files to remote directory, returning name of directory
+#
+
+unzip_code = '''"
+import tempfile, os, sys, tarfile
+tempdir = tempfile.mkdtemp(prefix='distrib-')
+os.chdir(tempdir)
+tf = tarfile.open(fileobj=sys.stdin, mode='r|gz')
+for ti in tf:
+    tf.extract(ti)
+print tempdir
+"'''
+
+def copy_to_remote_temporary_directory(host, files):
+    p = subprocess.Popen(
+        ['ssh', host, 'python', '-c', unzip_code],
+        stdout=subprocess.PIPE, stdin=subprocess.PIPE
+        )
+    tf = tarfile.open(fileobj=p.stdin, mode='w|gz')
+    for name in files:
+        tf.add(name, os.path.basename(name))
+    tf.close()
+    p.stdin.close()
+    return p.stdout.read().rstrip()
+
+#
+# Code which runs a host manager
+#
+
+def main():
+    # get data from parent over stdin
+    data = pickle.load(sys.stdin)
+    sys.stdin.close()
+
+    # set some stuff
+    _logger.setLevel(data['dist_log_level'])
+    forking.prepare(data)
+
+    # create server for a `HostManager` object
+    server = managers.Server(HostManager._registry, ('', 0), data['authkey'])
+    current_process()._server = server
+
+    # report server address and number of cpus back to parent
+    conn = connection.Client(data['parent_address'], authkey=data['authkey'])
+    conn.send((data['index'], server.address, slot_count))
+    conn.close()
+
+    # set name etc
+    current_process().set_name('Host-%s:%s' % server.address)
+    util._run_after_forkers()
+
+    # register a cleanup function
+    def cleanup(directory):
+        debug('removing directory %s', directory)
+        shutil.rmtree(directory)
+        debug('shutting down host manager')
+    util.Finalize(None, cleanup, args=[data['dir']], exitpriority=0)
+
+    # start host manager
+    debug('remote host manager starting in %s', data['dir'])
+    server.serve_forever()

Modified: python/branches/tlee-ast-optimize/Doc/install/index.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/install/index.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/install/index.rst	Wed Jan 14 13:24:17 2009
@@ -3,7 +3,7 @@
 .. _install-index:
 
 *****************************
-  Installing Python Modules  
+  Installing Python Modules
 *****************************
 
 :Author: Greg Ward
@@ -18,7 +18,7 @@
    Thus, I have to be sure to explain the basics at some point:
    sys.path and PYTHONPATH at least.  Should probably give pointers to
    other docs on "import site", PYTHONSTARTUP, PYTHONHOME, etc.
-   
+
    Finally, it might be useful to include all the material from my "Care
    and Feeding of a Python Installation" talk in here somewhere.  Yow!
 
@@ -268,7 +268,7 @@
 statements shown below, and get the output as shown, to find out my
 :file:`{prefix}` and :file:`{exec-prefix}`::
 
-   Python 2.4 (#26, Aug  7 2004, 17:19:02) 
+   Python 2.4 (#26, Aug  7 2004, 17:19:02)
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.prefix
@@ -587,11 +587,11 @@
    $ python
    Python 2.2 (#11, Oct  3 2002, 13:31:27)
    [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
-   Type ``help'', ``copyright'', ``credits'' or ``license'' for more information.
+   Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.path
-   ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', 
-    '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', 
+   ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',
+    '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',
     '/usr/local/lib/python2.3/site-packages']
    >>>
 

Modified: python/branches/tlee-ast-optimize/Doc/library/2to3.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/2to3.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/2to3.rst	Wed Jan 14 13:24:17 2009
@@ -3,7 +3,7 @@
 2to3 - Automated Python 2 to 3 code translation
 ===============================================
 
-.. sectionauthor:: Benjamin Peterson
+.. sectionauthor:: Benjamin Peterson <benjamin at python.org>
 
 2to3 is a Python program that reads Python 2.x source code and applies a series
 of *fixers* to transform it into valid Python 3.x code.  The standard library

Modified: python/branches/tlee-ast-optimize/Doc/library/abc.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/abc.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/abc.rst	Wed Jan 14 13:24:17 2009
@@ -43,15 +43,15 @@
       Register *subclass* as a "virtual subclass" of this ABC. For
       example::
 
-	from abc import ABCMeta
+        from abc import ABCMeta
 
-	class MyABC:
-	    __metaclass__ = ABCMeta
+        class MyABC:
+            __metaclass__ = ABCMeta
 
-	MyABC.register(tuple)
+        MyABC.register(tuple)
 
-	assert issubclass(tuple, MyABC)
-	assert isinstance((), MyABC)
+        assert issubclass(tuple, MyABC)
+        assert isinstance((), MyABC)
 
    You can also override this method in an abstract base class:
 
@@ -130,7 +130,7 @@
    A decorator indicating abstract methods.
 
    Using this decorator requires that the class's metaclass is :class:`ABCMeta` or
-   is derived from it. 
+   is derived from it.
    A class that has a metaclass derived from :class:`ABCMeta`
    cannot be instantiated unless all of its abstract methods and
    properties are overridden.
@@ -166,7 +166,7 @@
    A subclass of the built-in :func:`property`, indicating an abstract property.
 
    Using this function requires that the class's metaclass is :class:`ABCMeta` or
-   is derived from it. 
+   is derived from it.
    A class that has a metaclass derived from :class:`ABCMeta` cannot be
    instantiated unless all of its abstract methods and properties are overridden.
    The abstract properties can be called using any of the normal

Modified: python/branches/tlee-ast-optimize/Doc/library/aifc.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/aifc.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/aifc.rst	Wed Jan 14 13:24:17 2009
@@ -17,7 +17,7 @@
 ability to compress the audio data.
 
 .. warning::
-   
+
    Some operations may only work under IRIX; these will raise :exc:`ImportError`
    when attempting to import the :mod:`cl` module, which is only available on IRIX.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/al.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/al.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/al.rst	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,7 @@
    :platform: IRIX
    :synopsis: Audio functions on the SGI.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`al` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/ast.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/ast.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/ast.rst	Wed Jan 14 13:24:17 2009
@@ -127,7 +127,7 @@
    Parse an expression into an AST node.  Equivalent to ``compile(expr,
    filename, mode, ast.PyCF_ONLY_AST)``.
 
-   
+
 .. function:: literal_eval(node_or_string)
 
    Safely evaluate an expression node or a string containing a Python
@@ -191,7 +191,7 @@
 
    A node visitor base class that walks the abstract syntax tree and calls a
    visitor function for every node found.  This function may return a value
-   which is forwarded by the `visit` method.
+   which is forwarded by the :meth:`visit` method.
 
    This class is meant to be subclassed, with the subclass adding visitor
    methods.
@@ -205,7 +205,7 @@
    .. method:: generic_visit(node)
 
       This visitor calls :meth:`visit` on all children of the node.
-      
+
       Note that child nodes of nodes that have a custom visitor method won't be
       visited unless the visitor calls :meth:`generic_visit` or visits them
       itself.
@@ -220,11 +220,11 @@
    A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
    allows modification of nodes.
 
-   The `NodeTransformer` will walk the AST and use the return value of the
-   visitor methods to replace or remove the old node.  If the return value of
-   the visitor method is ``None``, the node will be removed from its location,
-   otherwise it is replaced with the return value.  The return value may be the
-   original node in which case no replacement takes place.
+   The :class:`NodeTransformer` will walk the AST and use the return value of
+   the visitor methods to replace or remove the old node.  If the return value
+   of the visitor method is ``None``, the node will be removed from its
+   location, otherwise it is replaced with the return value.  The return value
+   may be the original node in which case no replacement takes place.
 
    Here is an example transformer that rewrites all occurrences of name lookups
    (``foo``) to ``data['foo']``::

Modified: python/branches/tlee-ast-optimize/Doc/library/audioop.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/audioop.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/audioop.rst	Wed Jan 14 13:24:17 2009
@@ -265,7 +265,7 @@
        in_test = inputdata[pos*2:]
        ipos, factor = audioop.findfit(in_test, out_test)
        # Optional (for better cancellation):
-       # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)], 
+       # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
        #              out_test)
        prefill = '\0'*(pos+ipos)*2
        postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))

Modified: python/branches/tlee-ast-optimize/Doc/library/bastion.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/bastion.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/bastion.rst	Wed Jan 14 13:24:17 2009
@@ -5,10 +5,10 @@
 .. module:: Bastion
    :synopsis: Providing restricted access to objects.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`Bastion` module has been removed in Python 3.0.
-   
+
 .. moduleauthor:: Barry Warsaw <bwarsaw at python.org>
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/bdb.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/bdb.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/bdb.rst	Wed Jan 14 13:24:17 2009
@@ -325,7 +325,7 @@
 
    Check whether we should break here, depending on the way the breakpoint *b*
    was set.
-   
+
    If it was set via line number, it checks if ``b.line`` is the same as the one
    in the frame also passed as argument.  If the breakpoint was set via function
    name, we have to check we are in the right frame (the right function) and if
@@ -335,7 +335,7 @@
 
    Determine if there is an effective (active) breakpoint at this line of code.
    Return breakpoint number or 0 if none.
-	
+
    Called only if we know there is a breakpoint at this location.  Returns the
    breakpoint that was triggered and a flag that indicates if it is ok to delete
    a temporary breakpoint.

Modified: python/branches/tlee-ast-optimize/Doc/library/binascii.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/binascii.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/binascii.rst	Wed Jan 14 13:24:17 2009
@@ -113,8 +113,25 @@
       print binascii.crc32("hello world")
       # Or, in two pieces:
       crc = binascii.crc32("hello")
-      crc = binascii.crc32(" world", crc)
-      print crc
+      crc = binascii.crc32(" world", crc) & 0xffffffff
+      print 'crc32 = 0x%08x' % crc
+
+.. note::
+   To generate the same numeric value across all Python versions and
+   platforms use crc32(data) & 0xffffffff.  If you are only using
+   the checksum in packed binary format this is not necessary as the
+   return value will have the correct 32bit binary representation
+   regardless of sign.
+
+.. versionchanged:: 2.6
+   The return value will always be in the range [-2**31, 2**31-1]
+   regardless of platform.  In the past the value would be signed on
+   some platforms and unsigned on others.  Use & 0xffffffff on the
+   value if you want it to match 3.0 behavior.
+
+.. versionchanged:: 3.0
+   The return value will always be unsigned and in the range [0, 2**32-1]
+   regardless of platform.
 
 
 .. function:: b2a_hex(data)

Modified: python/branches/tlee-ast-optimize/Doc/library/bsddb.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/bsddb.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/bsddb.rst	Wed Jan 14 13:24:17 2009
@@ -172,7 +172,7 @@
    >>> import bsddb
    >>> db = bsddb.btopen('/tmp/spam.db', 'c')
    >>> for i in range(10): db['%d'%i] = '%d'% (i*i)
-   ... 
+   ...
    >>> db['3']
    '9'
    >>> db.keys()
@@ -185,7 +185,7 @@
    ('9', '81')
    >>> db.set_location('2')
    ('2', '4')
-   >>> db.previous() 
+   >>> db.previous()
    ('1', '1')
    >>> for k, v in db.iteritems():
    ...     print k, v

Modified: python/branches/tlee-ast-optimize/Doc/library/bz2.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/bz2.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/bz2.rst	Wed Jan 14 13:24:17 2009
@@ -93,7 +93,7 @@
       performance optimizations previously implemented in the :mod:`xreadlines`
       module.
 
-      .. deprecated:: 2.3 
+      .. deprecated:: 2.3
          This exists only for compatibility with the method by this name on
          :class:`file` objects, which is deprecated.  Use ``for line in file``
          instead.

Modified: python/branches/tlee-ast-optimize/Doc/library/cd.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/cd.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/cd.rst	Wed Jan 14 13:24:17 2009
@@ -6,8 +6,8 @@
    :platform: IRIX
    :synopsis: Interface to the CD-ROM on Silicon Graphics systems.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`cd` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/cmath.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/cmath.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/cmath.rst	Wed Jan 14 13:24:17 2009
@@ -70,9 +70,9 @@
 
 .. function:: polar(x)
 
-   Convert a :class:`complex` from rectangular coordinates to polar 
+   Convert a :class:`complex` from rectangular coordinates to polar
    coordinates. The function returns a tuple with the two elements
-   *r* and *phi*. *r* is the distance from 0 and *phi* the phase 
+   *r* and *phi*. *r* is the distance from 0 and *phi* the phase
    angle.
 
    .. versionadded:: 2.6

Modified: python/branches/tlee-ast-optimize/Doc/library/codeop.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/codeop.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/codeop.rst	Wed Jan 14 13:24:17 2009
@@ -43,7 +43,7 @@
    other value will cause :exc:`ValueError` to  be raised.
 
    .. warning::
-      
+
       It is possible (but not likely) that the parser stops parsing with a
       successful outcome before reaching the end of the source; in this case,
       trailing symbols may be ignored instead of causing an error.  For example,

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	Wed Jan 14 13:24:17 2009
@@ -53,36 +53,36 @@
 :class:`Hashable`                                 ``__hash__``
 :class:`Iterable`                                 ``__iter__``
 :class:`Iterator`          :class:`Iterable`      ``__next__``            ``__iter__``
-:class:`Sized`          			  ``__len__``
+:class:`Sized`                                    ``__len__``
 :class:`Callable`                                 ``__call__``
-                                                  
+
 :class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
                            :class:`Iterable`,     and ``__len__``         ``index``, and ``count``
-                           :class:`Container`     
-                                                  
+                           :class:`Container`
+
 :class:`MutableSequence`   :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
+                                                  ``__iter__``, and
                                                   ``__len__``
-                                                  
+
 :class:`MappingView`       :class:`Sized`                                 ``__len__``
 :class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
                            :class:`Set`                                   ``__iter__``
@@ -96,7 +96,7 @@
 
     size = None
     if isinstance(myvar, collections.Sized):
-	size = len(myvar)
+        size = len(myvar)
 
 Several of the ABCs are also useful as mixins that make it easier to develop
 classes supporting container APIs.  For example, to write a class supporting
@@ -152,6 +152,139 @@
 (For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
 
 
+.. _counter-objects:
+
+:class:`Counter` objects
+------------------------
+
+A counter tool is provided to support convenient and rapid tallies.
+For example::
+
+    # Tally repeated words in a list
+    >>> words = ['red', 'blue', 'red', 'green', 'blue', 'blue']
+    >>> cnt = Counter()
+    >>> for word in words:
+    ...     cnt[word] += 1
+    >>> cnt
+    Counter({'blue': 3, 'red': 2, 'green': 1})
+
+    # Find the ten most common words in Hamlet
+    >>> import re
+    >>> words = re.findall('\w+', open('hamlet.txt').read().lower())
+    >>> Counter(hamlet_words).most_common(10)
+    [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
+     ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
+
+.. class:: Counter([iterable-or-mapping])
+
+   A :class:`Counter` is a :class:`dict` subclass for counting hashable items.
+   It is an unordered collection where elements are stored as dictionary keys
+   and their counts are stored as dictionary values.  Counts are allowed to be
+   any integer value including zero or negative counts.  The :class:`Counter`
+   class is similar to bags or multisets in other languages.
+
+   Elements are counted from an *iterable* or initialized from another
+   *mapping* (or counter)::
+
+       >>> c = Counter()                            # a new, empty counter
+       >>> c = Counter('gallahad')                  # a new counter from an iterable
+       >>> c = Counter({'red': 4, 'blue': 2})       # a new counter from a mapping
+
+   The returned object has a dictionary style interface except that it returns
+   a zero count for missing items (instead of raising a :exc:`KeyError` like a
+   dictionary would)::
+
+        >>> c = Counter(['egg', 'ham'])
+        >>> c['bacon']                              # count of a missing element is zero
+        0
+
+   Assigning a count of zero or reducing the count to zero leaves the
+   element in the dictionary.  Use ``del`` to remove the entry entirely:
+
+        >>> c = Counter(['arthur', 'gwain'])
+        >>> c['arthur'] = 0                         # set the count of 'arthur' to zero
+        >>> 'arthur' in c                           # but 'arthur' is still in the counter
+        True
+        >>> del c['arthur']                         # del will completely remove the entry
+
+   .. versionadded:: 2.7
+
+
+   Counter objects support two methods beyond those available for all
+   dictionaries:
+
+   .. method:: elements()
+
+      Return an iterator over elements repeating each as many times as its count.
+      Elements are returned in arbitrary order.  If an element's count has been
+      set to zero or a negative number, :meth:`elements` will ignore it.
+
+            >>> c = Counter({'a': 4, 'b': 2, 'd': 0, 'e': -2})
+            >>> list(c.elements())
+            ['a', 'a', 'a', 'a', 'b', 'b']
+
+   .. method:: most_common([n])
+
+      Return a list of the *n* most common elements and their counts from
+      the most common to the least.  If *n* is not specified or is ``None``,
+      return a list of all element counts in decreasing order of frequency.
+      Elements with equal counts are ordered arbitrarily::
+
+            >>> Counter('abracadabra').most_common(3)
+            [('a', 5), ('r', 2), ('b', 2)]
+
+   The usual dictionary methods are available for :class:`Counter` objects.
+   All of those work the same as they do for dictionaries except for two
+   which work differently for counters.
+
+   .. method:: fromkeys(iterable)
+
+       There is no equivalent class method for :class:`Counter` objects.
+       Raises a :exc:`NotImplementedError` when called.
+
+   .. method:: update([iterable-or-mapping])
+
+       Like :meth:`dict.update` but adds-in counts instead of replacing them.
+
+       Elements are counted from an *iterable* or added-in from another
+       *mapping* (or counter)::
+
+            >>> c = Counter('which')
+            >>> c.update('witch')           # add elements from another iterable
+            >>> d = Counter('watch')
+            >>> c.update(d)                 # add elements from another counter
+            >>> c['h']                      # four 'h' in which, witch, and watch
+            4
+
+Common patterns for working with :class:`Counter` objects::
+
+    sum(c.values())               # total of all counts
+    c.clear()                     # reset all counts
+    list(c)                       # list unique elements
+    set(c)                        # convert to a set
+    dict(c)                       # convert to a regular dictionary
+    c.items()                     # convert to a list of (elem, cnt) pairs
+    Counter(dict(list_of_pairs))  # convert from a list of (elem, cnt) pairs
+    c.most_common()[:-n:-1]       # n least common elements
+
+**References**:
+
+* Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_
+
+* `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
+  in Smalltalk
+* `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
+  tutorial with standalone examples
+
+* An early Python `Bag <http://code.activestate.com/recipes/259174/>`_ recipe
+  for Python 2.4 and a `Counter <http://code.activestate.com/recipes/576611/>`_
+  comformant recipe for Python 2.5 and later
+
+* Use cases for multisets and mathematical operations on multisets.
+   Knuth, Donald. The Art of Computer Programming Volume II,
+   Section 4.6.3, Exercise 19
+
+
 
 .. _deque-objects:
 
@@ -549,8 +682,8 @@
                if kwds:
                    raise ValueError('Got unexpected field names: %r' % kwds.keys())
                return result
-   <BLANKLINE>            
-           def __getnewargs__(self): 
+   <BLANKLINE>
+           def __getnewargs__(self):
                return tuple(self)
    <BLANKLINE>
            x = property(itemgetter(0))
@@ -591,7 +724,7 @@
 
    Class method that makes a new instance from an existing sequence or iterable.
 
-.. doctest::
+   .. doctest::
 
       >>> t = [11, 22]
       >>> Point._make(t)
@@ -607,9 +740,7 @@
 .. method:: somenamedtuple._replace(kwargs)
 
    Return a new instance of the named tuple replacing specified fields with new
-   values:
-
-::
+   values::
 
       >>> p = Point(x=11, y=22)
       >>> p._replace(x=33)
@@ -623,7 +754,7 @@
    Tuple of strings listing the field names.  Useful for introspection
    and for creating new named tuple types from existing named tuples.
 
-.. doctest::
+   .. doctest::
 
       >>> p._fields            # view the field names
       ('x', 'y')

Modified: python/branches/tlee-ast-optimize/Doc/library/compiler.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/compiler.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/compiler.rst	Wed Jan 14 13:24:17 2009
@@ -559,24 +559,24 @@
    >>> import compiler
    >>> mod = compiler.parseFile("/tmp/doublelib.py")
    >>> mod
-   Module('This is an example module.\n\nThis is the docstring.\n', 
+   Module('This is an example module.\n\nThis is the docstring.\n',
           Stmt([Function(None, 'double', ['x'], [], 0,
-                         'Return twice the argument', 
+                         'Return twice the argument',
                          Stmt([Return(Mul((Name('x'), Const(2))))]))]))
    >>> from compiler.ast import *
-   >>> Module('This is an example module.\n\nThis is the docstring.\n', 
+   >>> Module('This is an example module.\n\nThis is the docstring.\n',
    ...    Stmt([Function(None, 'double', ['x'], [], 0,
-   ...                   'Return twice the argument', 
+   ...                   'Return twice the argument',
    ...                   Stmt([Return(Mul((Name('x'), Const(2))))]))]))
-   Module('This is an example module.\n\nThis is the docstring.\n', 
+   Module('This is an example module.\n\nThis is the docstring.\n',
           Stmt([Function(None, 'double', ['x'], [], 0,
-                         'Return twice the argument', 
+                         'Return twice the argument',
                          Stmt([Return(Mul((Name('x'), Const(2))))]))]))
    >>> mod.doc
    'This is an example module.\n\nThis is the docstring.\n'
    >>> for node in mod.node.nodes:
    ...     print node
-   ... 
+   ...
    Function(None, 'double', ['x'], [], 0, 'Return twice the argument',
             Stmt([Return(Mul((Name('x'), Const(2))))]))
    >>> func = mod.node.nodes[0]

Modified: python/branches/tlee-ast-optimize/Doc/library/configparser.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/configparser.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/configparser.rst	Wed Jan 14 13:24:17 2009
@@ -11,9 +11,9 @@
 
 .. note::
 
-   The :mod:`ConfigParser` module has been renamed to `configparser` in Python
-   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
-   your sources to 3.0.
+   The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
 
 .. index::
    pair: .ini; file

Modified: python/branches/tlee-ast-optimize/Doc/library/cookielib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/cookielib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/cookielib.rst	Wed Jan 14 13:24:17 2009
@@ -733,7 +733,7 @@
 The :class:`Cookie` class also defines the following method:
 
 
-.. method:: Cookie.is_expired([now=:const:`None`])
+.. method:: Cookie.is_expired([now=None])
 
    True if cookie has passed the time at which the server requested it should
    expire.  If *now* is given (in seconds since the epoch), return whether the

Modified: python/branches/tlee-ast-optimize/Doc/library/crypt.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/crypt.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/crypt.rst	Wed Jan 14 13:24:17 2009
@@ -51,7 +51,7 @@
        username = raw_input('Python login:')
        cryptedpasswd = pwd.getpwnam(username)[1]
        if cryptedpasswd:
-           if cryptedpasswd == 'x' or cryptedpasswd == '*': 
+           if cryptedpasswd == 'x' or cryptedpasswd == '*':
                raise "Sorry, currently no support for shadow passwords"
            cleartext = getpass.getpass()
            return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd

Modified: python/branches/tlee-ast-optimize/Doc/library/csv.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/csv.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/csv.rst	Wed Jan 14 13:24:17 2009
@@ -76,7 +76,7 @@
    performed.
 
    A short usage example::
- 
+
       >>> import csv
       >>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|')
       >>> for row in spamReader:

Modified: python/branches/tlee-ast-optimize/Doc/library/ctypes.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/ctypes.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/ctypes.rst	Wed Jan 14 13:24:17 2009
@@ -1378,24 +1378,22 @@
 The *mode* parameter can be used to specify how the library is loaded.  For
 details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
 
-The *use_errno* parameter, when set to True, enables a ctypes
-mechanism that allows to access the system `errno` error number in a
-safe way.  `ctypes` maintains a thread-local copy of the systems
-`errno` variable; if you call foreign functions created with
-`use_errno=True` then the `errno` value before the function call is
-swapped with the ctypes private copy, the same happens immediately
-after the function call.
-
-The function `ctypes.get_errno()` returns the value of the ctypes
-private copy, and the function `ctypes.set_errno(value)` changes the
-ctypes private copy to `value` and returns the former value.
-
-The *use_last_error* parameter, when set to True, enables the same
-mechanism for the Windows error code which is managed by the
-:func:`GetLastError` and :func:`SetLastError` Windows API functions;
-`ctypes.get_last_error()` and `ctypes.set_last_error(value)` are used
-to request and change the ctypes private copy of the windows error
-code.
+The *use_errno* parameter, when set to True, enables a ctypes mechanism that
+allows to access the system :data:`errno` error number in a safe way.
+:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
+variable; if you call foreign functions created with ``use_errno=True`` then the
+:data:`errno` value before the function call is swapped with the ctypes private
+copy, the same happens immediately after the function call.
+
+The function :func:`ctypes.get_errno` returns the value of the ctypes private
+copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
+to a new value and returns the former value.
+
+The *use_last_error* parameter, when set to True, enables the same mechanism for
+the Windows error code which is managed by the :func:`GetLastError` and
+:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
+:func:`ctypes.set_last_error` are used to request and change the ctypes private
+copy of the windows error code.
 
 .. versionadded:: 2.6
    The ``use_last_error`` and ``use_errno`` optional parameters
@@ -1602,22 +1600,23 @@
 .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
 
    The returned function prototype creates functions that use the standard C
-   calling convention.  The function will release the GIL during the call.
-   If `use_errno` is set to True, the ctypes private copy of the system `errno`
-   variable is exchanged with the real `errno` value bafore and after the call;
-   `use_last_error` does the same for the Windows error code.
+   calling convention.  The function will release the GIL during the call.  If
+   *use_errno* is set to True, the ctypes private copy of the system
+   :data:`errno` variable is exchanged with the real :data:`errno` value bafore
+   and after the call; *use_last_error* does the same for the Windows error
+   code.
 
    .. versionchanged:: 2.6
-      The optional `use_errno` and `use_last_error` parameters were
-      added.
+      The optional *use_errno* and *use_last_error* parameters were added.
 
 
 .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
 
    Windows only: The returned function prototype creates functions that use the
-   ``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
-   is the same as :func:`CFUNCTYPE`.  The function will release the GIL during the
-   call. `use_errno` and `use_last_error` have the same meaning as above.
+   ``stdcall`` calling convention, except on Windows CE where
+   :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`.  The function will
+   release the GIL during the call.  *use_errno* and *use_last_error* have the
+   same meaning as above.
 
 
 .. function:: PYFUNCTYPE(restype, *argtypes)
@@ -1864,10 +1863,10 @@
 .. function:: find_library(name)
    :module: ctypes.util
 
-   Try to find a library and return a pathname.  `name` is the library name without
-   any prefix like `lib`, suffix like ``.so``, ``.dylib`` or version number (this
-   is the form used for the posix linker option :option:`-l`).  If no library can
-   be found, returns ``None``.
+   Try to find a library and return a pathname.  *name* is the library name
+   without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
+   number (this is the form used for the posix linker option :option:`-l`).  If
+   no library can be found, returns ``None``.
 
    The exact functionality is system dependent.
 
@@ -1905,14 +1904,14 @@
 .. function:: get_errno()
 
    Returns the current value of the ctypes-private copy of the system
-   `errno` variable in the calling thread.
+   :data:`errno` variable in the calling thread.
 
    .. versionadded:: 2.6
 
 .. function:: get_last_error()
 
    Windows only: returns the current value of the ctypes-private copy of the system
-   `LastError` variable in the calling thread.
+   :data:`LastError` variable in the calling thread.
 
    .. versionadded:: 2.6
 
@@ -1969,17 +1968,16 @@
 
 .. function:: set_errno(value)
 
-   Set the  current value of the ctypes-private copy of the system
-   `errno` variable in the calling thread to `value` and return the
-   previous value.
+   Set the current value of the ctypes-private copy of the system :data:`errno`
+   variable in the calling thread to *value* and return the previous value.
 
    .. versionadded:: 2.6
 
 .. function:: set_last_error(value)
 
-   Windows only: set the current value of the ctypes-private copy of
-   the system `LastError` variable in the calling thread to `value`
-   and return the previous value.
+   Windows only: set the current value of the ctypes-private copy of the system
+   :data:`LastError` variable in the calling thread to *value* and return the
+   previous value.
 
    .. versionadded:: 2.6
 

Modified: python/branches/tlee-ast-optimize/Doc/library/datetime.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/datetime.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/datetime.rst	Wed Jan 14 13:24:17 2009
@@ -266,10 +266,10 @@
 considered to be true if and only if it isn't equal to ``timedelta(0)``.
 
 Example usage:
-    
+
     >>> from datetime import timedelta
     >>> year = timedelta(days=365)
-    >>> another_year = timedelta(weeks=40, days=84, hours=23, 
+    >>> another_year = timedelta(weeks=40, days=84, hours=23,
     ...                          minutes=50, seconds=600)  # adds up to 365 days
     >>> year == another_year
     True
@@ -517,10 +517,10 @@
     True
     >>> my_birthday = date(today.year, 6, 24)
     >>> if my_birthday < today:
-    ...     my_birthday = my_birthday.replace(year=today.year + 1) 
+    ...     my_birthday = my_birthday.replace(year=today.year + 1)
     >>> my_birthday
     datetime.date(2008, 6, 24)
-    >>> time_to_birthday = abs(my_birthday - today) 
+    >>> time_to_birthday = abs(my_birthday - today)
     >>> time_to_birthday.days
     202
 
@@ -1015,7 +1015,7 @@
     >>> tt = dt.timetuple()
     >>> for it in tt:   # doctest: +SKIP
     ...     print it
-    ... 
+    ...
     2006    # year
     11      # month
     21      # day
@@ -1044,23 +1044,23 @@
     ...     def __init__(self):         # DST starts last Sunday in March
     ...         d = datetime(dt.year, 4, 1)   # ends last Sunday in October
     ...         self.dston = d - timedelta(days=d.weekday() + 1)
-    ...         d = datetime(dt.year, 11, 1)    
+    ...         d = datetime(dt.year, 11, 1)
     ...         self.dstoff = d - timedelta(days=d.weekday() + 1)
     ...     def utcoffset(self, dt):
     ...         return timedelta(hours=1) + self.dst(dt)
-    ...     def dst(self, dt):              
+    ...     def dst(self, dt):
     ...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
     ...             return timedelta(hours=1)
     ...         else:
     ...             return timedelta(0)
     ...     def tzname(self,dt):
     ...          return "GMT +1"
-    ... 
+    ...
     >>> class GMT2(tzinfo):
     ...     def __init__(self):
-    ...         d = datetime(dt.year, 4, 1)  
+    ...         d = datetime(dt.year, 4, 1)
     ...         self.dston = d - timedelta(days=d.weekday() + 1)
-    ...         d = datetime(dt.year, 11, 1)    
+    ...         d = datetime(dt.year, 11, 1)
     ...         self.dstoff = d - timedelta(days=d.weekday() + 1)
     ...     def utcoffset(self, dt):
     ...         return timedelta(hours=1) + self.dst(dt)
@@ -1071,7 +1071,7 @@
     ...             return timedelta(0)
     ...     def tzname(self,dt):
     ...         return "GMT +2"
-    ... 
+    ...
     >>> gmt1 = GMT1()
     >>> # Daylight Saving Time
     >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
@@ -1092,7 +1092,7 @@
     datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
     >>> dt2.utctimetuple() == dt3.utctimetuple()
     True
- 
+
 
 
 .. _datetime-time:
@@ -1240,12 +1240,12 @@
    return ``None`` or a string object.
 
 Example:
-    
+
     >>> from datetime import time, tzinfo
     >>> class GMT1(tzinfo):
     ...     def utcoffset(self, dt):
-    ...         return timedelta(hours=1) 
-    ...     def dst(self, dt):              
+    ...         return timedelta(hours=1)
+    ...     def dst(self, dt):
     ...         return timedelta(0)
     ...     def tzname(self,dt):
     ...         return "Europe/Prague"
@@ -1476,7 +1476,7 @@
 :class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
 other fixed-offset :class:`tzinfo` subclass (such as a class representing only
 EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
-    
+
 
 .. _strftime-behavior:
 
@@ -1521,7 +1521,7 @@
 
 The full set of format codes supported varies across platforms, because Python
 calls the platform C library's :func:`strftime` function, and platform
-variations are common.  
+variations are common.
 
 The following is a list of all the format codes that the C standard (1989
 version) requires, and these work on all platforms with a standard C

Modified: python/branches/tlee-ast-optimize/Doc/library/decimal.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/decimal.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/decimal.rst	Wed Jan 14 13:24:17 2009
@@ -328,7 +328,7 @@
       infinity       ::=  'Infinity' | 'Inf'
       nan            ::=  'NaN' [digits] | 'sNaN' [digits]
       numeric-value  ::=  decimal-part [exponent-part] | infinity
-      numeric-string ::=  [sign] numeric-value | [sign] nan  
+      numeric-string ::=  [sign] numeric-value | [sign] nan
 
    If *value* is a :class:`tuple`, it should have three components, a sign
    (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
@@ -484,6 +484,29 @@
 
       .. versionadded:: 2.6
 
+   .. method:: from_float(f)
+
+      Classmethod that converts a float to a decimal number, exactly.
+
+      Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
+      Since 0.1 is not exactly representable in binary floating point, the
+      value is stored as the nearest representable value which is
+      `0x1.999999999999ap-4`.  That equivalent value in decimal is
+      `0.1000000000000000055511151231257827021181583404541015625`.
+
+      .. doctest::
+
+          >>> Decimal.from_float(0.1)
+          Decimal('0.1000000000000000055511151231257827021181583404541015625')
+          >>> Decimal.from_float(float('nan'))
+          Decimal('NaN')
+          >>> Decimal.from_float(float('inf'))
+          Decimal('Infinity')
+          >>> Decimal.from_float(float('-inf'))
+          Decimal('-Infinity')
+
+      .. versionadded:: 2.7
+
    .. method:: fma(other, third[, context])
 
       Fused multiply-add.  Return self*other+third with no rounding of the
@@ -947,7 +970,7 @@
    * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
    * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
    * :const:`ROUND_UP` (away from zero).
-   * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero 
+   * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
      would have been 0 or 5; otherwise towards zero)
 
    The *traps* and *flags* fields list any signals to be set. Generally, new
@@ -1007,6 +1030,26 @@
       If the argument is a string, no leading or trailing whitespace is
       permitted.
 
+   .. method:: create_decimal_from_float(f)
+
+      Creates a new Decimal instance from a float *f* but rounding using *self*
+      as the context.  Unlike the :meth:`Decimal.from_float` class method,
+      the context precision, rounding method, flags, and traps are applied to
+      the conversion.
+
+      .. doctest::
+
+         >>> context = Context(prec=5, rounding=ROUND_DOWN)
+         >>> context.create_decimal_from_float(math.pi)
+         Decimal('3.1415')
+         >>> context = Context(prec=5, traps=[Inexact])
+         >>> context.create_decimal_from_float(math.pi)
+         Traceback (most recent call last):
+             ...
+         Inexact: None
+
+      .. versionadded:: 2.7
+
    .. method:: Etiny()
 
       Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
@@ -1168,7 +1211,7 @@
 
    .. method:: logical_and(x, y)
 
-      Applies the logical operation `and` between each operand's digits.
+      Applies the logical operation *and* between each operand's digits.
 
 
    .. method:: logical_invert(x)
@@ -1178,12 +1221,12 @@
 
    .. method:: logical_or(x, y)
 
-      Applies the logical operation `or` between each operand's digits.
+      Applies the logical operation *or* between each operand's digits.
 
 
    .. method:: logical_xor(x, y)
 
-      Applies the logical operation `xor` between each operand's digits.
+      Applies the logical operation *xor* between each operand's digits.
 
 
    .. method:: max(x, y)
@@ -1270,7 +1313,7 @@
       that would be obtained by computing ``(x**y) % modulo`` with unbounded
       precision, but is computed more efficiently.  It is always exact.
 
-      .. versionchanged:: 2.6 
+      .. versionchanged:: 2.6
          ``y`` may now be nonintegral in ``x**y``.
          Stricter requirements for the three-argument version.
 
@@ -1294,8 +1337,8 @@
 
    .. method:: remainder_near(x, y)
 
-      Returns `x - y * n`, where *n* is the integer nearest the exact value
-      of `x / y` (if the result is `0` then its sign will be the sign of *x*).
+      Returns ``x - y * n``, where *n* is the integer nearest the exact value
+      of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
 
 
    .. method:: rotate(x, y)
@@ -1412,7 +1455,7 @@
       sqrt(-x) and x > 0
       0 ** 0
       x ** (non-integer)
-      x ** Infinity      
+      x ** Infinity
 
 
 .. class:: Overflow
@@ -1515,7 +1558,7 @@
    Decimal('9.51111111')
    >>> u + (v + w)
    Decimal('9.51111111')
-   >>> 
+   >>>
    >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
    >>> (u*v) + (u*w)
    Decimal('0.0060000')
@@ -1654,7 +1697,7 @@
 
        """
        q = Decimal(10) ** -places      # 2 places --> '0.01'
-       sign, digits, exp = value.quantize(q).as_tuple()  
+       sign, digits, exp = value.quantize(q).as_tuple()
        result = []
        digits = map(str, digits)
        build, next = result.append, digits.pop
@@ -1711,12 +1754,12 @@
        getcontext().prec += 2
        i, lasts, s, fact, num = 0, 0, 1, 1, 1
        while s != lasts:
-           lasts = s    
+           lasts = s
            i += 1
            fact *= i
-           num *= x     
-           s += num / fact   
-       getcontext().prec -= 2        
+           num *= x
+           s += num / fact
+       getcontext().prec -= 2
        return +s
 
    def cos(x):
@@ -1733,13 +1776,13 @@
        getcontext().prec += 2
        i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
        while s != lasts:
-           lasts = s    
+           lasts = s
            i += 2
            fact *= i * (i-1)
            num *= x * x
            sign *= -1
-           s += num / fact * sign 
-       getcontext().prec -= 2        
+           s += num / fact * sign
+       getcontext().prec -= 2
        return +s
 
    def sin(x):
@@ -1756,13 +1799,13 @@
        getcontext().prec += 2
        i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
        while s != lasts:
-           lasts = s    
+           lasts = s
            i += 2
            fact *= i * (i-1)
            num *= x * x
            sign *= -1
-           s += num / fact * sign 
-       getcontext().prec -= 2        
+           s += num / fact * sign
+       getcontext().prec -= 2
        return +s
 
 
@@ -1796,7 +1839,7 @@
    >>> Decimal('3.214').quantize(TWOPLACES)
    Decimal('3.21')
 
-   >>> # Validate that a number does not exceed two places 
+   >>> # Validate that a number does not exceed two places
    >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
    Decimal('3.21')
 
@@ -1880,13 +1923,14 @@
     def float_to_decimal(f):
         "Convert a floating point number to a Decimal with no loss of information"
         n, d = f.as_integer_ratio()
-        with localcontext() as ctx:
-            ctx.traps[Inexact] = True
-            while True:
-                try:
-                   return Decimal(n) / Decimal(d)
-                except Inexact:
-                    ctx.prec += 1
+        numerator, denominator = Decimal(n), Decimal(d)
+        ctx = Context(prec=60)
+        result = ctx.divide(numerator, denominator)
+        while ctx.flags[Inexact]:
+            ctx.flags[Inexact] = False
+            ctx.prec *= 2
+            result = ctx.divide(numerator, denominator)
+        return result
 
 .. doctest::
 

Modified: python/branches/tlee-ast-optimize/Doc/library/difflib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/difflib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/difflib.rst	Wed Jan 14 13:24:17 2009
@@ -428,7 +428,7 @@
 
       .. XXX Explain why a dummy is used!
 
-      .. versionchanged:: 2.5 
+      .. versionchanged:: 2.5
          The guarantee that adjacent triples always describe non-adjacent blocks
          was implemented.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/dircache.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/dircache.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/dircache.rst	Wed Jan 14 13:24:17 2009
@@ -5,11 +5,11 @@
 .. module:: dircache
    :synopsis: Return directory listing, with cache mechanism.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`dircache` module has been removed in Python 3.0.
-   
-   
+
+
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/dis.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/dis.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/dis.rst	Wed Jan 14 13:24:17 2009
@@ -64,8 +64,21 @@
 
 .. function:: disco(code[, lasti])
 
-   A synonym for disassemble.  It is more convenient to type, and kept for
-   compatibility with earlier Python releases.
+   A synonym for :func:`disassemble`.  It is more convenient to type, and kept
+   for compatibility with earlier Python releases.
+
+
+.. function:: findlinestarts(code)
+
+   This generator function uses the ``co_firstlineno`` and ``co_lnotab``
+   attributes of the code object *code* to find the offsets which are starts of
+   lines in the source code.  They are generated as ``(offset, lineno)`` pairs.
+
+
+.. function:: findlabels(code)
+
+   Detect all offsets in the code object *code* which are jump targets, and
+   return a list of these offsets.
 
 
 .. data:: opname
@@ -463,9 +476,11 @@
    address to jump to (which should be a ``FOR_ITER`` instruction).
 
 
-.. opcode:: LIST_APPEND ()
+.. opcode:: LIST_APPEND (i)
 
-   Calls ``list.append(TOS1, TOS)``.  Used to implement list comprehensions.
+   Calls ``list.append(TOS[-i], TOS)``.  Used to implement list comprehensions.
+   While the appended value is popped off, the list object remains on the
+   stack so that it is available for further iterations of the loop.
 
 
 .. opcode:: LOAD_LOCALS ()
@@ -755,7 +770,7 @@
    opcode finds the keyword parameters first.  For each keyword argument, the value
    is on top of the key.  Below the keyword parameters, the positional parameters
    are on the stack, with the right-most parameter on top.  Below the parameters,
-   the function object to call is on the stack.  Pops all function arguments, and 
+   the function object to call is on the stack.  Pops all function arguments, and
    the function itself off the stack, and pushes the return value.
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/dl.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/dl.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/dl.rst	Wed Jan 14 13:24:17 2009
@@ -6,11 +6,11 @@
    :platform: Unix
    :synopsis: Call C functions in shared objects.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`dl` module has been removed in Python 3.0. Use the :mod:`ctypes`
     module instead.
-   
+
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
 The :mod:`dl` module defines an interface to the :cfunc:`dlopen` function, which
@@ -91,9 +91,9 @@
    Return the pointer for the function named *name*, as a number, if it exists in
    the referenced shared object, otherwise ``None``. This is useful in code like::
 
-      >>> if a.sym('time'): 
+      >>> if a.sym('time'):
       ...     a.call('time')
-      ... else: 
+      ... else:
       ...     time.time()
 
    (Note that this function will return a non-zero number, as zero is the *NULL*

Modified: python/branches/tlee-ast-optimize/Doc/library/email.mime.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/email.mime.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/email.mime.rst	Wed Jan 14 13:24:17 2009
@@ -2,7 +2,7 @@
 ----------------------------------------------------------
 
 .. module:: email.mime
-   :synopsis: Build MIME messages. 
+   :synopsis: Build MIME messages.
 
 
 Ordinarily, you get a message object structure by passing a file or some text to
@@ -19,6 +19,7 @@
 
 Here are the classes:
 
+.. currentmodule:: email.mime.base
 
 .. class:: MIMEBase(_maintype, _subtype, **_params)
 
@@ -39,6 +40,8 @@
    :mailheader:`MIME-Version` header (always set to ``1.0``).
 
 
+.. currentmodule:: email.mime.nonmultipart
+
 .. class:: MIMENonMultipart()
 
    Module: :mod:`email.mime.nonmultipart`
@@ -52,14 +55,16 @@
    .. versionadded:: 2.2.2
 
 
-.. class:: MIMEMultipart([subtype[, boundary[, _subparts[, _params]]]])
+.. currentmodule:: email.mime.multipart
+
+.. class:: MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]])
 
    Module: :mod:`email.mime.multipart`
 
    A subclass of :class:`MIMEBase`, this is an intermediate base class for MIME
    messages that are :mimetype:`multipart`.  Optional *_subtype* defaults to
    :mimetype:`mixed`, but can be used to specify the subtype of the message.  A
-   :mailheader:`Content-Type` header of :mimetype:`multipart/`*_subtype* will be
+   :mailheader:`Content-Type` header of :mimetype:`multipart/_subtype` will be
    added to the message object.  A :mailheader:`MIME-Version` header will also be
    added.
 
@@ -77,6 +82,8 @@
    .. versionadded:: 2.2.2
 
 
+.. currentmodule:: email.mime.application
+
 .. class:: MIMEApplication(_data[, _subtype[, _encoder[, **_params]]])
 
    Module: :mod:`email.mime.application`
@@ -99,6 +106,8 @@
    .. versionadded:: 2.5
 
 
+.. currentmodule:: email.mime.audio
+
 .. class:: MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]])
 
    Module: :mod:`email.mime.audio`
@@ -122,6 +131,8 @@
    *_params* are passed straight through to the base class constructor.
 
 
+.. currentmodule:: email.mime.image
+
 .. class:: MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]])
 
    Module: :mod:`email.mime.image`
@@ -145,6 +156,8 @@
    *_params* are passed straight through to the :class:`MIMEBase` constructor.
 
 
+.. currentmodule:: email.mime.message
+
 .. class:: MIMEMessage(_msg[, _subtype])
 
    Module: :mod:`email.mime.message`
@@ -158,6 +171,8 @@
    :mimetype:`rfc822`.
 
 
+.. currentmodule:: email.mime.text
+
 .. class:: MIMEText(_text[, _subtype[, _charset]])
 
    Module: :mod:`email.mime.text`

Modified: python/branches/tlee-ast-optimize/Doc/library/fileinput.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/fileinput.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/fileinput.rst	Wed Jan 14 13:24:17 2009
@@ -151,7 +151,7 @@
 when standard input is read.
 
 .. warning::
-   
+
    The current implementation does not work for MS-DOS 8+3 filesystems.
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/fl.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/fl.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/fl.rst	Wed Jan 14 13:24:17 2009
@@ -6,8 +6,8 @@
    :platform: IRIX
    :synopsis: FORMS library for applications with graphical user interfaces.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`fl` module has been deprecated for removal in Python 3.0.
 
@@ -484,8 +484,8 @@
    :platform: IRIX
    :synopsis: Constants used with the fl module.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`FL` module has been deprecated for removal in Python 3.0.
 
@@ -506,8 +506,8 @@
    :platform: IRIX
    :synopsis: Functions for loading stored FORMS designs.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`flp` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/fm.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/fm.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/fm.rst	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,7 @@
    :platform: IRIX
    :synopsis: Font Manager interface for SGI workstations.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`fm` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/fpformat.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/fpformat.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/fpformat.rst	Wed Jan 14 13:24:17 2009
@@ -5,10 +5,10 @@
 .. module:: fpformat
    :synopsis: General floating point formatting functions.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`fpformat` module has been removed in Python 3.0.
-   
+
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/fractions.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/fractions.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/fractions.rst	Wed Jan 14 13:24:17 2009
@@ -101,11 +101,11 @@
 
 .. function:: gcd(a, b)
 
-   Return the greatest common divisor of the integers `a` and `b`.  If
-   either `a` or `b` is nonzero, then the absolute value of `gcd(a,
-   b)` is the largest integer that divides both `a` and `b`.  `gcd(a,b)`
-   has the same sign as `b` if `b` is nonzero; otherwise it takes the sign
-   of `a`.  `gcd(0, 0)` returns `0`.
+   Return the greatest common divisor of the integers *a* and *b*.  If either
+   *a* or *b* is nonzero, then the absolute value of ``gcd(a, b)`` is the
+   largest integer that divides both *a* and *b*.  ``gcd(a,b)`` has the same
+   sign as *b* if *b* is nonzero; otherwise it takes the sign of *a*.  ``gcd(0,
+   0)`` returns ``0``.
 
 
 .. seealso::

Modified: python/branches/tlee-ast-optimize/Doc/library/ftplib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/ftplib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/ftplib.rst	Wed Jan 14 13:24:17 2009
@@ -1,4 +1,3 @@
-
 :mod:`ftplib` --- FTP protocol client
 =====================================
 

Modified: python/branches/tlee-ast-optimize/Doc/library/functions.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/functions.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/functions.rst	Wed Jan 14 13:24:17 2009
@@ -8,67 +8,6 @@
 available.  They are listed here in alphabetical order.
 
 
-.. function:: __import__(name[, globals[, locals[, fromlist[, level]]]])
-
-   .. index::
-      statement: import
-      module: ihooks
-      module: rexec
-      module: imp
-
-   .. note::
-
-      This is an advanced function that is not needed in everyday Python
-      programming.
-
-   The function is invoked by the :keyword:`import` statement.  It mainly exists
-   so that you can replace it with another function that has a compatible
-   interface, in order to change the semantics of the :keyword:`import` statement.
-   See the built-in module :mod:`imp`, which defines some useful operations out
-   of which you can build your own :func:`__import__` function.
-
-   For example, the statement ``import spam`` results in the following call:
-   ``__import__('spam', globals(), locals(), [], -1)``; the statement
-   ``from spam.ham import eggs`` results in ``__import__('spam.ham', globals(),
-   locals(), ['eggs'], -1)``.  Note that even though ``locals()`` and ``['eggs']``
-   are passed in as arguments, the :func:`__import__` function does not set the
-   local variable named ``eggs``; this is done by subsequent code that is generated
-   for the import statement.  (In fact, the standard implementation does not use
-   its *locals* argument at all, and uses its *globals* only to determine the
-   package context of the :keyword:`import` statement.)
-
-   When the *name* variable is of the form ``package.module``, normally, the
-   top-level package (the name up till the first dot) is returned, *not* the
-   module named by *name*.  However, when a non-empty *fromlist* argument is
-   given, the module named by *name* is returned.  This is done for
-   compatibility with the :term:`bytecode` generated for the different kinds of import
-   statement; when using ``import spam.ham.eggs``, the top-level package
-   :mod:`spam` must be placed in the importing namespace, but when using ``from
-   spam.ham import eggs``, the ``spam.ham`` subpackage must be used to find the
-   ``eggs`` variable.  As a workaround for this behavior, use :func:`getattr` to
-   extract the desired components.  For example, you could define the following
-   helper::
-
-      def my_import(name):
-          mod = __import__(name)
-          components = name.split('.')
-          for comp in components[1:]:
-              mod = getattr(mod, comp)
-          return mod
-
-   *level* specifies whether to use absolute or relative imports. The default is
-   ``-1`` which indicates both absolute and relative imports will be attempted.
-   ``0`` means only perform absolute imports. Positive values for *level* indicate
-   the number of parent directories to search relative to the directory of the
-   module calling :func:`__import__`.
-
-   .. versionchanged:: 2.5
-      The level parameter was added.
-
-   .. versionchanged:: 2.5
-      Keyword support for parameters was added.
-
-
 .. function:: abs(x)
 
    Return the absolute value of a number.  The argument may be a plain or long
@@ -949,7 +888,7 @@
    .. versionchanged:: 2.5
       Use *fget*'s docstring if no *doc* given.
 
-   .. versionchanged:: 2.6 
+   .. versionchanged:: 2.6
       The ``getter``, ``setter``, and ``deleter`` attributes were added.
 
 
@@ -1239,10 +1178,10 @@
    single inheritance, "super" can be used to refer to parent classes without
    naming them explicitly, thus making the code more maintainable.  This use
    closely parallels the use of "super" in other programming languages.
-   
+
    The second use case is to support cooperative multiple inheritence in a
-   dynamic execution environment.  This use case is unique to Python and is 
-   not found in statically compiled languages or languages that only support 
+   dynamic execution environment.  This use case is unique to Python and is
+   not found in statically compiled languages or languages that only support
    single inheritance.  This makes in possible to implement "diamond diagrams"
    where multiple base classes implement the same method.  Good design dictates
    that this method have the same calling signature in every case (because the
@@ -1303,7 +1242,7 @@
 
       >>> class X(object):
       ...     a = 1
-      ...     
+      ...
       >>> X = type('X', (object,), dict(a=1))
 
    .. versionadded:: 2.2
@@ -1419,6 +1358,83 @@
       Formerly, :func:`zip` required at least one argument and ``zip()`` raised a
       :exc:`TypeError` instead of returning an empty list.
 
+
+.. function:: __import__(name[, globals[, locals[, fromlist[, level]]]])
+
+   .. index::
+      statement: import
+      module: imp
+
+   .. note::
+
+      This is an advanced function that is not needed in everyday Python
+      programming.
+
+   This function is invoked by the :keyword:`import` statement.  It can be
+   replaced (by importing the :mod:`builtins` module and assigning to
+   ``builtins.__import__``) in order to change semantics of the
+   :keyword:`import` statement, but nowadays it is usually simpler to use import
+   hooks (see :pep:`302`).  Direct use of :func:`__import__` is rare, except in
+   cases where you want to import a module whose name is only known at runtime.
+
+   The function imports the module *name*, potentially using the given *globals*
+   and *locals* to determine how to interpret the name in a package context.
+   The *fromlist* gives the names of objects or submodules that should be
+   imported from the module given by *name*.  The standard implementation does
+   not use its *locals* argument at all, and uses its *globals* only to
+   determine the package context of the :keyword:`import` statement.
+
+   *level* specifies whether to use absolute or relative imports.  The default
+   is ``-1`` which indicates both absolute and relative imports will be
+   attempted.  ``0`` means only perform absolute imports.  Positive values for
+   *level* indicate the number of parent directories to search relative to the
+   directory of the module calling :func:`__import__`.
+
+   When the *name* variable is of the form ``package.module``, normally, the
+   top-level package (the name up till the first dot) is returned, *not* the
+   module named by *name*.  However, when a non-empty *fromlist* argument is
+   given, the module named by *name* is returned.
+
+   For example, the statement ``import spam`` results in bytecode resembling the
+   following code::
+
+      spam = __import__('spam', globals(), locals(), [], -1)
+
+   The statement ``import spam.ham`` results in this call::
+
+      spam = __import__('spam.ham', globals(), locals(), [], -1)
+
+   Note how :func:`__import__` returns the toplevel module here because this is
+   the object that is bound to a name by the :keyword:`import` statement.
+
+   On the other hand, the statement ``from spam.ham import eggs, sausage as
+   saus`` results in ::
+
+      _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
+      eggs = _temp.eggs
+      saus = _temp.sausage
+
+   Here, the ``spam.ham`` module is returned from :func:`__import__`.  From this
+   object, the names to import are retrieved and assigned to their respective
+   names.
+
+   If you simply want to import a module (potentially within a package) by name,
+   you can get it from :data:`sys.modules`::
+
+      >>> import sys
+      >>> name = 'foo.bar.baz'
+      >>> __import__(name)
+      <module 'foo' from ...>
+      >>> baz = sys.modules[name]
+      >>> baz
+      <module 'foo.bar.baz' from ...>
+
+   .. versionchanged:: 2.5
+      The level parameter was added.
+
+   .. versionchanged:: 2.5
+      Keyword support for parameters was added.
+
 ..  ---------------------------------------------------------------------------
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/getopt.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/getopt.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/getopt.rst	Wed Jan 14 13:24:17 2009
@@ -63,8 +63,8 @@
    non-option argument is encountered.
 
    If the first character of the option string is '+', or if the environment
-   variable POSIXLY_CORRECT is set, then option processing stops as soon as a
-   non-option argument is encountered.
+   variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
+   soon as a non-option argument is encountered.
 
    .. versionadded:: 2.3
 

Modified: python/branches/tlee-ast-optimize/Doc/library/gettext.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/gettext.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/gettext.rst	Wed Jan 14 13:24:17 2009
@@ -648,10 +648,9 @@
 
    animals = ['mollusk',
               'albatross',
-   	   'rat',
-   	   'penguin',
-   	   'python',
-   	   ]
+              'rat',
+              'penguin',
+              'python', ]
    # ...
    for a in animals:
        print a
@@ -666,10 +665,9 @@
 
    animals = [_('mollusk'),
               _('albatross'),
-   	   _('rat'),
-   	   _('penguin'),
-   	   _('python'),
-   	   ]
+              _('rat'),
+              _('penguin'),
+              _('python'), ]
 
    del _
 
@@ -692,10 +690,9 @@
 
    animals = [N_('mollusk'),
               N_('albatross'),
-   	   N_('rat'),
-   	   N_('penguin'),
-   	   N_('python'),
-   	   ]
+              N_('rat'),
+              N_('penguin'),
+              N_('python'), ]
 
    # ...
    for a in animals:

Modified: python/branches/tlee-ast-optimize/Doc/library/gl.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/gl.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/gl.rst	Wed Jan 14 13:24:17 2009
@@ -6,8 +6,8 @@
    :platform: IRIX
    :synopsis: Functions from the Silicon Graphics Graphics Library.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`gl` module has been deprecated for removal in Python 3.0.
 
@@ -166,8 +166,8 @@
    :platform: IRIX
    :synopsis: Constants used with the gl module.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`DEVICE` module has been deprecated for removal in Python 3.0.
 
@@ -184,8 +184,8 @@
    :platform: IRIX
    :synopsis: Constants used with the gl module.
    :deprecated:
-   
-   
+
+
 .. deprecated:: 2.6
     The :mod:`GL` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/gzip.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/gzip.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/gzip.rst	Wed Jan 14 13:24:17 2009
@@ -7,7 +7,7 @@
 This module provides a simple interface to compress and decompress files just
 like the GNU programs :program:`gzip` and :program:`gunzip` would.
 
-The data compression is provided by the :mod:``zlib`` module.
+The data compression is provided by the :mod:`zlib` module.
 
 The :mod:`gzip` module provides the :class:`GzipFile` class which is modeled
 after Python's File Object. The :class:`GzipFile` class reads and writes
@@ -24,7 +24,7 @@
 The module defines the following items:
 
 
-.. class:: GzipFile([filename[, mode[, compresslevel[, fileobj]]]])
+.. class:: GzipFile([filename[, mode[, compresslevel[, fileobj[, mtime]]]]])
 
    Constructor for the :class:`GzipFile` class, which simulates most of the methods
    of a file object, with the exception of the :meth:`readinto` and
@@ -52,6 +52,15 @@
    level of compression; ``1`` is fastest and produces the least compression, and
    ``9`` is slowest and produces the most compression.  The default is ``9``.
 
+   The *mtime* argument is an optional numeric timestamp to be written to
+   the stream when compressing.  All :program:`gzip`compressed streams are
+   required to contain a timestamp.  If omitted or ``None``, the current
+   time is used.  This module ignores the timestamp when decompressing;
+   however, some programs, such as :program:`gunzip`\ , make use of it.
+   The format of the timestamp is the same as that of the return value of
+   ``time.time()`` and of the ``st_mtime`` member of the object returned
+   by ``os.stat()``.
+
    Calling a :class:`GzipFile` object's :meth:`close` method does not close
    *fileobj*, since you might wish to append more material after the compressed
    data.  This also allows you to pass a :class:`StringIO` object opened for

Modified: python/branches/tlee-ast-optimize/Doc/library/hashlib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/hashlib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/hashlib.rst	Wed Jan 14 13:24:17 2009
@@ -4,8 +4,8 @@
 
 .. module:: hashlib
    :synopsis: Secure hash and message digest algorithms.
-.. moduleauthor:: Gregory P. Smith <greg at users.sourceforge.net>
-.. sectionauthor:: Gregory P. Smith <greg at users.sourceforge.net>
+.. moduleauthor:: Gregory P. Smith <greg at krypto.org>
+.. sectionauthor:: Gregory P. Smith <greg at krypto.org>
 
 
 .. versionadded:: 2.5

Modified: python/branches/tlee-ast-optimize/Doc/library/heapq.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/heapq.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/heapq.rst	Wed Jan 14 13:24:17 2009
@@ -88,6 +88,21 @@
    >>> print data == ordered
    True
 
+Using a heap to insert items at the correct place in a priority queue:
+
+   >>> heap = []
+   >>> data = [(1, 'J'), (4, 'N'), (3, 'H'), (2, 'O')]
+   >>> for item in data:
+   ...     heappush(heap, item)
+   ...
+   >>> while heap:
+   ...     print heappop(heap)[1]
+   J
+   O
+   H
+   N
+
+
 The module also offers three general purpose functions based on heaps.
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/htmllib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/htmllib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/htmllib.rst	Wed Jan 14 13:24:17 2009
@@ -4,7 +4,7 @@
 .. module:: htmllib
    :synopsis: A parser for HTML documents.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`htmllib` module has been removed in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/idle.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/idle.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/idle.rst	Wed Jan 14 13:24:17 2009
@@ -230,7 +230,7 @@
    Keywords
       orange
 
-   Strings 
+   Strings
       green
 
    Comments

Modified: python/branches/tlee-ast-optimize/Doc/library/imageop.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/imageop.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/imageop.rst	Wed Jan 14 13:24:17 2009
@@ -5,7 +5,7 @@
 .. module:: imageop
    :synopsis: Manipulate raw image data.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`imageop` module has been removed in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/imgfile.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/imgfile.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/imgfile.rst	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,7 @@
    :platform: IRIX
    :synopsis: Support for SGI imglib files.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`imgfile` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/io.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/io.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/io.rst	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,7 @@
 .. moduleauthor:: Guido van Rossum <guido at python.org>
 .. moduleauthor:: Mike Verdone <mike.verdone at gmail.com>
 .. moduleauthor:: Mark Russell <mark.russell at zen.co.uk>
-.. sectionauthor:: Benjamin Peterson
+.. sectionauthor:: Benjamin Peterson <benjamin at python.org>
 .. versionadded:: 2.6
 
 The :mod:`io` module provides the Python interfaces to stream handling.  The
@@ -215,7 +215,7 @@
    .. method:: close()
 
       Flush and close this stream. This method has no effect if the file is
-      already closed. Once the file is closed, any operation on the file 
+      already closed. Once the file is closed, any operation on the file
       (e.g. reading or writing) will raise an :exc:`IOError`. The internal
       file descriptor isn't closed if *closefd* was False.
 
@@ -629,7 +629,7 @@
    .. attribute:: line_buffering
 
       Whether line buffering is enabled.
-   
+
 
 .. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
 

Modified: python/branches/tlee-ast-optimize/Doc/library/itertools.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/itertools.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/itertools.rst	Wed Jan 14 13:24:17 2009
@@ -76,7 +76,7 @@
 
 .. function:: itertools.chain.from_iterable(iterable)
 
-   Alternate constructor for :func:`chain`.  Gets chained inputs from a 
+   Alternate constructor for :func:`chain`.  Gets chained inputs from a
    single iterable argument that is evaluated lazily.  Equivalent to::
 
       @classmethod
@@ -93,9 +93,9 @@
 
    Return *r* length subsequences of elements from the input *iterable*.
 
-   Combinations are emitted in lexicographic sort order.  So, if the 
+   Combinations are emitted in lexicographic sort order.  So, if the
    input *iterable* is sorted, the combination tuples will be produced
-   in sorted order.  
+   in sorted order.
 
    Elements are treated as unique based on their position, not on their
    value.  So if the input elements are unique, there will be no repeat
@@ -108,6 +108,8 @@
             # combinations(range(4), 3) --> 012 013 023 123
             pool = tuple(iterable)
             n = len(pool)
+            if r > n:
+                return
             indices = range(r)
             yield tuple(pool[i] for i in indices)
             while 1:
@@ -132,6 +134,9 @@
                 if sorted(indices) == list(indices):
                     yield tuple(pool[i] for i in indices)
 
+   The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n``
+   or zero when ``r > n``.
+
    .. versionadded:: 2.6
 
 .. function:: count([n])
@@ -314,7 +319,7 @@
           for i, element in enumerate(iterable):
               if i == nexti:
                   yield element
-                  nexti = it.next()          
+                  nexti = it.next()
 
    If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
    then the step defaults to one.
@@ -380,12 +385,12 @@
    Return successive *r* length permutations of elements in the *iterable*.
 
    If *r* is not specified or is ``None``, then *r* defaults to the length
-   of the *iterable* and all possible full-length permutations 
+   of the *iterable* and all possible full-length permutations
    are generated.
 
-   Permutations are emitted in lexicographic sort order.  So, if the 
+   Permutations are emitted in lexicographic sort order.  So, if the
    input *iterable* is sorted, the permutation tuples will be produced
-   in sorted order.  
+   in sorted order.
 
    Elements are treated as unique based on their position, not on their
    value.  So if the input elements are unique, there will be no repeat
@@ -399,6 +404,8 @@
             pool = tuple(iterable)
             n = len(pool)
             r = n if r is None else r
+            if r > n:
+                return
             indices = range(n)
             cycles = range(n, n-r, -1)
             yield tuple(pool[i] for i in indices[:r])
@@ -416,7 +423,7 @@
                 else:
                     return
 
-   The code for :func:`permutations` can be also expressed as a subsequence of 
+   The code for :func:`permutations` can be also expressed as a subsequence of
    :func:`product`, filtered to exclude entries with repeated elements (those
    from the same position in the input pool)::
 
@@ -428,6 +435,9 @@
                 if len(set(indices)) == r:
                     yield tuple(pool[i] for i in indices)
 
+   The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n``
+   or zero when ``r > n``.
+
    .. versionadded:: 2.6
 
 .. function:: product(*iterables[, repeat])
@@ -547,7 +557,7 @@
 
 .. doctest::
 
-   # Show a dictionary sorted and grouped by value
+   >>> # Show a dictionary sorted and grouped by value
    >>> from operator import itemgetter
    >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
    >>> di = sorted(d.iteritems(), key=itemgetter(1))
@@ -558,13 +568,13 @@
    2 ['b', 'd', 'f']
    3 ['g']
 
-   # Find runs of consecutive numbers using groupby.  The key to the solution
-   # is differencing with a range so that consecutive numbers all appear in
-   # same group.
+   >>> # Find runs of consecutive numbers using groupby.  The key to the solution
+   >>> # is differencing with a range so that consecutive numbers all appear in
+   >>> # same group.
    >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
    >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
    ...     print map(itemgetter(1), g)
-   ... 
+   ...
    [1]
    [4, 5, 6]
    [10]
@@ -674,7 +684,8 @@
        return (d for d, s in izip(data, selectors) if s)
 
    def combinations_with_replacement(iterable, r):
-       "combinations_with_replacement('ABC', 3) --> AA AB AC BB BC CC"
+       "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
+       # number items returned:  (n+r-1)! / r! / (n-1)!
        pool = tuple(iterable)
        n = len(pool)
        indices = [0] * r
@@ -687,3 +698,27 @@
                return
            indices[i:] = [indices[i] + 1] * (r - i)
            yield tuple(pool[i] for i in indices)
+
+    def unique_everseen(iterable, key=None):
+        "List unique elements, preserving order. Remember all elements ever seen."
+        # unique_everseen('AAAABBBCCDAABBB') --> A B C D
+        # unique_everseen('ABBCcAD', str.lower) --> A B C D
+        seen = set()
+        seen_add = seen.add
+        if key is None:
+            for element in iterable:
+                if element not in seen:
+                    seen_add(element)
+                    yield element
+        else:
+            for element in iterable:
+                k = key(element)
+                if k not in seen:
+                    seen_add(k)
+                    yield element
+
+    def unique_justseen(iterable, key=None):
+        "List unique elements, preserving order. Remember only the element just seen."
+        # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
+        # unique_justseen('ABBCcAD', str.lower) --> A B C A D
+        return imap(next, imap(itemgetter(1), groupby(iterable, key)))

Modified: python/branches/tlee-ast-optimize/Doc/library/jpeg.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/jpeg.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/jpeg.rst	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,7 @@
    :platform: IRIX
    :synopsis: Read and write image files in compressed JPEG format.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`jpeg` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/json.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/json.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/json.rst	Wed Jan 14 13:24:17 2009
@@ -14,7 +14,7 @@
 :mod:`marshal` and :mod:`pickle` modules.
 
 Encoding basic Python object hierarchies::
-    
+
     >>> import json
     >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
     '["foo", {"bar": ["baz", null, 1.0, 2]}]'
@@ -43,12 +43,12 @@
     >>> import json
     >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
     {
-        "4": 5, 
+        "4": 5,
         "6": 7
     }
 
 Decoding JSON::
-    
+
     >>> import json
     >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
     [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
@@ -66,7 +66,7 @@
     ...     if '__complex__' in dct:
     ...         return complex(dct['real'], dct['imag'])
     ...     return dct
-    ... 
+    ...
     >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
     ...     object_hook=as_complex)
     (1+2j)
@@ -75,26 +75,26 @@
     Decimal('1.1')
 
 Extending :class:`JSONEncoder`::
-    
+
     >>> import json
     >>> class ComplexEncoder(json.JSONEncoder):
     ...     def default(self, obj):
     ...         if isinstance(obj, complex):
     ...             return [obj.real, obj.imag]
     ...         return json.JSONEncoder.default(self, obj)
-    ... 
+    ...
     >>> dumps(2 + 1j, cls=ComplexEncoder)
     '[2.0, 1.0]'
     >>> ComplexEncoder().encode(2 + 1j)
     '[2.0, 1.0]'
     >>> list(ComplexEncoder().iterencode(2 + 1j))
     ['[', '2.0', ', ', '1.0', ']']
-    
+
 
 .. highlight:: none
 
 Using json.tool from the shell to validate and pretty-print::
-    
+
     $ echo '{"json":"obj"}' | python -mjson.tool
     {
         "json": "obj"
@@ -104,7 +104,7 @@
 
 .. highlight:: python
 
-.. note:: 
+.. note::
 
    The JSON produced by this module's default settings is a subset of
    YAML, so it may be used as a serializer for that as well.
@@ -152,7 +152,7 @@
    *default(obj)* is a function that should return a serializable version of
    *obj* or raise :exc:`TypeError`.  The default simply raises :exc:`TypeError`.
 
-   To use a custom :class:`JSONEncoder`` subclass (e.g. one that overrides the
+   To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
    :meth:`default` method to serialize additional types), specify it with the
    *cls* kwarg.
 
@@ -166,7 +166,7 @@
    :func:`dump`.
 
 
-.. function load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]])
+.. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]])
 
    Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON
    document) to a Python object.
@@ -202,7 +202,7 @@
    class.
 
 
-.. function loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]])
+.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]])
 
    Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
    document) to a Python object.
@@ -368,7 +368,7 @@
 
       For example, to support arbitrary iterators, you could implement default
       like this::
-            
+
          def default(self, o):
             try:
                 iterable = iter(o)
@@ -392,6 +392,6 @@
 
       Encode the given object, *o*, and yield each string representation as
       available.  For example::
-            
+
             for chunk in JSONEncoder().iterencode(bigobject):
                 mysocket.write(chunk)

Modified: python/branches/tlee-ast-optimize/Doc/library/locale.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/locale.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/locale.rst	Wed Jan 14 13:24:17 2009
@@ -494,7 +494,7 @@
    >>> import locale
    >>> loc = locale.getlocale() # get current locale
    >>> locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform
-   >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut 
+   >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
    >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
    >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
    >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale

Modified: python/branches/tlee-ast-optimize/Doc/library/logging.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/logging.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/logging.rst	Wed Jan 14 13:24:17 2009
@@ -121,7 +121,7 @@
 messages at different log levels.  This allows you to instrument your code with
 debug messages, for example, but turning the log level down so that those debug
 messages are not written for your production system.  The default levels are
-``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``UNSET``.
+``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``NOTSET``.
 
 The logger, handler, and log message call each specify a level.  The log message
 is only emitted if the handler and logger are configured to emit messages of
@@ -422,6 +422,8 @@
 code approach, mainly separation of configuration and code and the ability of
 noncoders to easily modify the logging properties.
 
+.. _library-config:
+
 Configuring Logging for a Library
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
@@ -461,6 +463,12 @@
 libraries, then the logger name specified can be "orgname.foo" rather than
 just "foo".
 
+.. versionadded:: 2.7
+
+The :class:`NullHandler` class was not present in previous versions, but is now
+included, so that it need not be defined in library code.
+
+
 
 Logging Levels
 --------------
@@ -524,39 +532,55 @@
 
 #. :class:`FileHandler` instances send error messages to disk files.
 
-#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log
-   files at a certain point. It is not meant to be  instantiated directly. Instead,
-   use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`.
+#. :class:`handlers.BaseRotatingHandler` is the base class for handlers that
+   rotate log files at a certain point. It is not meant to be  instantiated
+   directly. Instead, use :class:`RotatingFileHandler` or
+   :class:`TimedRotatingFileHandler`.
 
-#. :class:`RotatingFileHandler` instances send error messages to disk files,
+#. :class:`handlers.RotatingFileHandler` instances send error messages to disk files,
    with support for maximum log file sizes and log file rotation.
 
-#. :class:`TimedRotatingFileHandler` instances send error messages to disk files
+#. :class:`handlers.TimedRotatingFileHandler` instances send error messages to disk files
    rotating the log file at certain timed intervals.
 
-#. :class:`SocketHandler` instances send error messages to TCP/IP sockets.
+#. :class:`handlers.SocketHandler` instances send error messages to TCP/IP sockets.
 
-#. :class:`DatagramHandler` instances send error messages to UDP sockets.
+#. :class:`handlers.DatagramHandler` instances send error messages to UDP sockets.
 
-#. :class:`SMTPHandler` instances send error messages to a designated email
+#. :class:`handlers.SMTPHandler` instances send error messages to a designated email
    address.
 
-#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon,
+#. :class:`handlers.SysLogHandler` instances send error messages to a Unix syslog daemon,
    possibly on a remote machine.
 
-#. :class:`NTEventLogHandler` instances send error messages to a Windows
+#. :class:`handlers.NTEventLogHandler` instances send error messages to a Windows
    NT/2000/XP event log.
 
-#. :class:`MemoryHandler` instances send error messages to a buffer in memory,
+#. :class:`handlers.MemoryHandler` instances send error messages to a buffer in memory,
    which is flushed whenever specific criteria are met.
 
-#. :class:`HTTPHandler` instances send error messages to an HTTP server using
+#. :class:`handlers.HTTPHandler` instances send error messages to an HTTP server using
    either ``GET`` or ``POST`` semantics.
 
-The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the
-core logging package. The other handlers are defined in a sub- module,
-:mod:`logging.handlers`. (There is also another sub-module,
-:mod:`logging.config`, for configuration functionality.)
+#. :class:`handlers.WatchedFileHandler` instances watch the file they are logging to. If
+the file changes, it is closed and reopened using the file name. This handler
+is only useful on Unix-like systems; Windows does not support the underlying
+mechanism used.
+
+#. :class:`NullHandler` instances do nothing with error messages. They are used
+   by library developers who want to use logging, but want to avoid the "No
+   handlers could be found for logger XXX" message which can be displayed if
+   the library user has not configured logging. See :ref:`library-config` for
+   more information.
+
+.. versionadded:: 2.7
+
+The :class:`NullHandler` class was not present in previous versions.
+
+The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
+classes are defined in the core logging package. The other handlers are
+defined in a sub- module, :mod:`logging.handlers`. (There is also another
+sub-module, :mod:`logging.config`, for configuration functionality.)
 
 Logged messages are formatted for presentation through instances of the
 :class:`Formatter` class. They are initialized with a format string suitable for
@@ -1599,11 +1623,35 @@
       Outputs the record to the file.
 
 
+NullHandler
+^^^^^^^^^^^
+
+.. versionadded:: 2.7
+
+The :class:`NullHandler` class, located in the core :mod:`logging` package,
+does not do any formatting or output. It is essentially a "no-op" handler
+for use by library developers.
+
+
+.. class:: NullHandler()
+
+   Returns a new instance of the :class:`NullHandler` class.
+
+
+   .. method:: emit(record)
+
+      This method does nothing.
+
+See :ref:`library-config` for more information on how to use
+:class:`NullHandler`.
+
 WatchedFileHandler
 ^^^^^^^^^^^^^^^^^^
 
 .. versionadded:: 2.6
 
+.. module:: logging.handlers
+
 The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
 module, is a :class:`FileHandler` which watches the file it is logging to. If
 the file changes, it is closed and reopened using the file name.
@@ -2050,6 +2098,8 @@
 Formatter Objects
 -----------------
 
+.. currentmodule:: logging
+
 :class:`Formatter`\ s have the following attributes and methods. They are
 responsible for converting a :class:`LogRecord` to (usually) a string which can
 be interpreted by either a human or an external system. The base
@@ -2285,12 +2335,12 @@
 
 .. function:: fileConfig(fname[, defaults])
 
-   Reads the logging configuration from a ConfigParser-format file named *fname*.
-   This function can be called several times from an application, allowing an end
-   user the ability to select from various pre-canned configurations (if the
-   developer provides a mechanism to present the choices and load the chosen
-   configuration). Defaults to be passed to ConfigParser can be specified in the
-   *defaults* argument.
+   Reads the logging configuration from a :mod:`ConfigParser`\-format file named
+   *fname*. This function can be called several times from an application,
+   allowing an end user the ability to select from various pre-canned
+   configurations (if the developer provides a mechanism to present the choices
+   and load the chosen configuration). Defaults to be passed to the ConfigParser
+   can be specified in the *defaults* argument.
 
 
 .. function:: listen([port])
@@ -2321,17 +2371,17 @@
 ^^^^^^^^^^^^^^^^^^^^^^^^^
 
 The configuration file format understood by :func:`fileConfig` is based on
-ConfigParser functionality. The file must contain sections called ``[loggers]``,
-``[handlers]`` and ``[formatters]`` which identify by name the entities of each
-type which are defined in the file. For each such entity, there is a separate
-section which identified how that entity is configured. Thus, for a logger named
-``log01`` in the ``[loggers]`` section, the relevant configuration details are
-held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
-the ``[handlers]`` section will have its configuration held in a section called
-``[handler_hand01]``, while a formatter called ``form01`` in the
-``[formatters]`` section will have its configuration specified in a section
-called ``[formatter_form01]``. The root logger configuration must be specified
-in a section called ``[logger_root]``.
+:mod:`ConfigParser` functionality. The file must contain sections called
+``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
+entities of each type which are defined in the file. For each such entity,
+there is a separate section which identifies how that entity is configured.
+Thus, for a logger named ``log01`` in the ``[loggers]`` section, the relevant
+configuration details are held in a section ``[logger_log01]``. Similarly, a
+handler called ``hand01`` in the ``[handlers]`` section will have its
+configuration held in a section called ``[handler_hand01]``, while a formatter
+called ``form01`` in the ``[formatters]`` section will have its configuration
+specified in a section called ``[formatter_form01]``. The root logger
+configuration must be specified in a section called ``[logger_root]``.
 
 Examples of these sections in the file are given below. ::
 

Modified: python/branches/tlee-ast-optimize/Doc/library/macos.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/macos.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/macos.rst	Wed Jan 14 13:24:17 2009
@@ -82,7 +82,7 @@
    parameter can be a pathname or an ``FSSpec`` or  ``FSRef`` object.
 
    .. note::
-      
+
       It is not possible to use an ``FSSpec`` in 64-bit mode.
 
 
@@ -93,7 +93,7 @@
    strings.
 
    .. note::
-      
+
       It is not possible to use an ``FSSpec`` in 64-bit mode.
 
 .. function:: openrf(name [, mode])

Modified: python/branches/tlee-ast-optimize/Doc/library/mailbox.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/mailbox.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/mailbox.rst	Wed Jan 14 13:24:17 2009
@@ -1686,7 +1686,7 @@
                # that's better than losing a message completely.
                box.lock()
                box.add(message)
-               box.flush()         
+               box.flush()
                box.unlock()
 
                # Remove original message

Modified: python/branches/tlee-ast-optimize/Doc/library/marshal.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/marshal.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/marshal.rst	Wed Jan 14 13:24:17 2009
@@ -45,7 +45,7 @@
 (they will cause infinite loops).
 
 .. warning::
-   
+
    On machines where C's ``long int`` type has more than 32 bits (such as the
    DEC Alpha), it is possible to create plain Python integers that are longer
    than 32 bits. If such an integer is marshaled and read back in on a machine

Modified: python/branches/tlee-ast-optimize/Doc/library/math.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/math.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/math.rst	Wed Jan 14 13:24:17 2009
@@ -21,8 +21,9 @@
 The following functions are provided by this module.  Except when explicitly
 noted otherwise, all return values are floats.
 
-Number-theoretic and representation functions:
 
+Number-theoretic and representation functions
+---------------------------------------------
 
 .. function:: ceil(x)
 
@@ -108,7 +109,7 @@
 .. function:: isnan(x)
 
    Checks if the float *x* is a NaN (not a number). NaNs are part of the
-   IEEE 754 standards. Operation like but not limited to ``inf * 0``, 
+   IEEE 754 standards. Operation like but not limited to ``inf * 0``,
    ``inf / inf`` or any operation involving a NaN, e.g. ``nan * 1``, return
    a NaN.
 
@@ -123,8 +124,8 @@
 
 .. function:: modf(x)
 
-   Return the fractional and integer parts of *x*.  Both results carry the sign of
-   *x*, and both are floats.
+   Return the fractional and integer parts of *x*.  Both results carry the sign
+   of *x* and are floats.
 
 
 .. function:: trunc(x)
@@ -146,7 +147,9 @@
 platform C double type), in which case any float *x* with ``abs(x) >= 2**52``
 necessarily has no fractional bits.
 
-Power and logarithmic functions:
+
+Power and logarithmic functions
+-------------------------------
 
 .. function:: exp(x)
 
@@ -193,7 +196,8 @@
    Return the square root of *x*.
 
 
-Trigonometric functions:
+Trigonometric functions
+-----------------------
 
 .. function:: acos(x)
 
@@ -241,7 +245,8 @@
    Return the tangent of *x* radians.
 
 
-Angular conversion:
+Angular conversion
+------------------
 
 .. function:: degrees(x)
 
@@ -253,7 +258,8 @@
    Converts angle *x* from degrees to radians.
 
 
-Hyperbolic functions:
+Hyperbolic functions
+--------------------
 
 .. function:: acosh(x)
 
@@ -291,7 +297,8 @@
    Return the hyperbolic tangent of *x*.
 
 
-The module also defines two mathematical constants:
+Constants
+---------
 
 .. data:: pi
 

Modified: python/branches/tlee-ast-optimize/Doc/library/mhlib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/mhlib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/mhlib.rst	Wed Jan 14 13:24:17 2009
@@ -4,7 +4,7 @@
 .. module:: mhlib
    :synopsis: Manipulate MH mailboxes from Python.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`mhlib` module has been removed in Python 3.0. Use the
     :mod:`mailbox` instead.

Modified: python/branches/tlee-ast-optimize/Doc/library/mmap.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/mmap.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/mmap.rst	Wed Jan 14 13:24:17 2009
@@ -93,7 +93,7 @@
    will be relative to the offset from the beginning of the file. *offset*
    defaults to 0.  *offset* must be a multiple of the PAGESIZE or
    ALLOCATIONGRANULARITY.
-   
+
    This example shows a simple way of using :class:`mmap`::
 
       import mmap

Modified: python/branches/tlee-ast-optimize/Doc/library/msvcrt.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/msvcrt.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/msvcrt.rst	Wed Jan 14 13:24:17 2009
@@ -18,7 +18,7 @@
 
 The module implements both the normal and wide char variants of the console I/O
 api. The normal API deals only with ASCII characters and is of limited use
-for internationalized applications. The wide char API should be used where 
+for internationalized applications. The wide char API should be used where
 ever possible
 
 .. _msvcrt-files:
@@ -98,13 +98,13 @@
    return the keycode.  The :kbd:`Control-C` keypress cannot be read with this
    function.
 
-   
+
 .. function:: getwch()
 
    Wide char variant of :func:`getch`, returning a Unicode value.
-   
+
    .. versionadded:: 2.6
-   
+
 
 .. function:: getche()
 
@@ -115,7 +115,7 @@
 .. function:: getwche()
 
    Wide char variant of :func:`getche`, returning a Unicode value.
-   
+
    .. versionadded:: 2.6
 
 
@@ -123,24 +123,24 @@
 
    Print the character *char* to the console without buffering.
 
-   
+
 .. function:: putwch(unicode_char)
 
    Wide char variant of :func:`putch`, accepting a Unicode value.
-   
+
    .. versionadded:: 2.6
-   
+
 
 .. function:: ungetch(char)
 
    Cause the character *char* to be "pushed back" into the console buffer; it will
    be the next character read by :func:`getch` or :func:`getche`.
 
-   
+
 .. function:: ungetwch(unicode_char)
 
    Wide char variant of :func:`ungetch`, accepting a Unicode value.
-   
+
    .. versionadded:: 2.6
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/multiprocessing.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/multiprocessing.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/multiprocessing.rst	Wed Jan 14 13:24:17 2009
@@ -21,9 +21,9 @@
 .. warning::
 
     Some of this package's functionality requires a functioning shared semaphore
-    implementation on the host operating system. Without one, the 
-    :mod:`multiprocessing.synchronize` module will be disabled, and attempts to 
-    import it will result in an :exc:`ImportError`. See 
+    implementation on the host operating system. Without one, the
+    :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
+    import it will result in an :exc:`ImportError`. See
     :issue:`3770` for additional information.
 
 .. note::
@@ -37,8 +37,8 @@
         >>> from multiprocessing import Pool
         >>> p = Pool(5)
         >>> def f(x):
-        ... 	return x*x
-        ... 
+        ...     return x*x
+        ...
         >>> p.map(f, [1,2,3])
         Process PoolWorker-1:
         Process PoolWorker-2:
@@ -77,11 +77,11 @@
         print 'module name:', __name__
         print 'parent process:', os.getppid()
         print 'process id:', os.getpid()
-    
+
     def f(name):
         info('function f')
         print 'hello', name
-    
+
     if __name__ == '__main__':
         info('main line')
         p = Process(target=f, args=('bob',))
@@ -109,12 +109,12 @@
       def f(q):
           q.put([42, None, 'hello'])
 
-       if __name__ == '__main__':
-           q = Queue()
-           p = Process(target=f, args=(q,))
-           p.start()
-           print q.get()    # prints "[42, None, 'hello']"
-           p.join()
+      if __name__ == '__main__':
+          q = Queue()
+          p = Process(target=f, args=(q,))
+          p.start()
+          print q.get()    # prints "[42, None, 'hello']"
+          p.join()
 
    Queues are thread and process safe.
 
@@ -358,7 +358,7 @@
 
    .. attribute:: daemon
 
-      The process's daemon flag, a Boolean value.  This must be called before
+      The process's daemon flag, a Boolean value.  This must be set before
       :meth:`start` is called.
 
       The initial value is inherited from the creating process.
@@ -543,7 +543,7 @@
 
    .. method:: put(item[, block[, timeout]])
 
-      Put item into the queue.  If the optional argument *block* is ``True`` 
+      Put item into the queue.  If the optional argument *block* is ``True``
       (the default) and *timeout* is ``None`` (the default), block if necessary until
       a free slot is available.  If *timeout* is a positive number, it blocks at
       most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
@@ -858,7 +858,7 @@
    acceptable.  If *block* is ``True`` and *timeout* is not ``None`` then it
    specifies a timeout in seconds.  If *block* is ``False`` then *timeout* is
    ignored.
-   
+
    Note that on OS/X ``sem_timedwait`` is unsupported, so timeout arguments
    for these will be ignored.
 
@@ -1135,22 +1135,22 @@
       server process which is using the given address and authentication key.
 
    .. method:: get_server()
-      
+
       Returns a :class:`Server` object which represents the actual server under
-      the control of the Manager. The :class:`Server` object supports the 
-      :meth:`serve_forever` method::
-      
-       >>> from multiprocessing.managers import BaseManager
-       >>> m = BaseManager(address=('', 50000), authkey='abc'))
-       >>> server = m.get_server()
-       >>> s.serve_forever()
-       
-       :class:`Server` additionally have an :attr:`address` attribute.
+      the control of the Manager. The :class:`Server` object supports the
+      :meth:`serve_forever` method:
+
+      >>> from multiprocessing.managers import BaseManager
+      >>> m = BaseManager(address=('', 50000), authkey='abc'))
+      >>> server = m.get_server()
+      >>> s.serve_forever()
+
+      :class:`Server` additionally have an :attr:`address` attribute.
 
    .. method:: connect()
-   
-      Connect a local manager object to a remote manager process::
-      
+
+      Connect a local manager object to a remote manager process:
+
       >>> from multiprocessing.managers import BaseManager
       >>> m = BaseManager(address='127.0.0.1', authkey='abc))
       >>> m.connect()
@@ -1295,7 +1295,7 @@
 >>>>>>>>>>>>>>>>>>>
 
 To create one's own manager, one creates a subclass of :class:`BaseManager` and
-use the :meth:`~BaseManager.resgister` classmethod to register new types or
+use the :meth:`~BaseManager.register` classmethod to register new types or
 callables with the manager class.  For example::
 
    from multiprocessing.managers import BaseManager
@@ -1360,7 +1360,7 @@
    >>> queue.get()
    'hello'
 
-Local processes can also access that queue, using the code from above on the 
+Local processes can also access that queue, using the code from above on the
 client to access it remotely::
 
     >>> from multiprocessing import Process, Queue
@@ -1371,12 +1371,12 @@
     ...         super(Worker, self).__init__()
     ...     def run(self):
     ...         self.q.put('local hello')
-    ... 
+    ...
     >>> queue = Queue()
     >>> w = Worker(queue)
     >>> w.start()
     >>> class QueueManager(BaseManager): pass
-    ... 
+    ...
     >>> QueueManager.register('get_queue', callable=lambda: queue)
     >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
     >>> s = m.get_server()
@@ -1438,13 +1438,13 @@
 
    Proxy objects are instances of subclasses of :class:`BaseProxy`.
 
-   .. method:: _call_method(methodname[, args[, kwds]])
+   .. method:: _callmethod(methodname[, args[, kwds]])
 
       Call and return the result of a method of the proxy's referent.
 
       If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
 
-         proxy._call_method(methodname, args, kwds)
+         proxy._callmethod(methodname, args, kwds)
 
       will evaluate the expression ::
 
@@ -1457,26 +1457,26 @@
       argument of :meth:`BaseManager.register`.
 
       If an exception is raised by the call, then then is re-raised by
-      :meth:`_call_method`.  If some other exception is raised in the manager's
+      :meth:`_callmethod`.  If some other exception is raised in the manager's
       process then this is converted into a :exc:`RemoteError` exception and is
-      raised by :meth:`_call_method`.
+      raised by :meth:`_callmethod`.
 
       Note in particular that an exception will be raised if *methodname* has
       not been *exposed*
 
-      An example of the usage of :meth:`_call_method`::
+      An example of the usage of :meth:`_callmethod`::
 
          >>> l = manager.list(range(10))
-         >>> l._call_method('__len__')
+         >>> l._callmethod('__len__')
          10
-         >>> l._call_method('__getslice__', (2, 7))   # equiv to `l[2:7]`
+         >>> l._callmethod('__getslice__', (2, 7))   # equiv to `l[2:7]`
          [2, 3, 4, 5, 6]
-         >>> l._call_method('__getitem__', (20,))     # equiv to `l[20]`
+         >>> l._callmethod('__getitem__', (20,))     # equiv to `l[20]`
          Traceback (most recent call last):
          ...
          IndexError: list index out of range
 
-   .. method:: _get_value()
+   .. method:: _getvalue()
 
       Return a copy of the referent.
 
@@ -1810,9 +1810,9 @@
   filesystem.
 
 * An ``'AF_PIPE'`` address is a string of the form
-   ``r'\\\\.\\pipe\\PipeName'``.  To use :func:`Client` to connect to a named
-   pipe on a remote computer called ServerName* one should use an address of the
-   form ``r'\\\\ServerName\\pipe\\PipeName'`` instead.
+   :samp:`r'\\\\.\\pipe\\{PipeName}'`.  To use :func:`Client` to connect to a named
+   pipe on a remote computer called *ServerName* one should use an address of the
+   form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.
 
 Note that any string beginning with two backslashes is assumed by default to be
 an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.
@@ -2120,7 +2120,7 @@
 .. literalinclude:: ../includes/mp_benchmarks.py
 
 An example/demo of how to use the :class:`managers.SyncManager`, :class:`Process`
-and others to build a system which can distribute processes and work via a 
+and others to build a system which can distribute processes and work via a
 distributed queue to a "cluster" of machines on a network, accessible via SSH.
 You will need to have private key authentication for all hosts configured for
 this to work.

Modified: python/branches/tlee-ast-optimize/Doc/library/mutex.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/mutex.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/mutex.rst	Wed Jan 14 13:24:17 2009
@@ -5,7 +5,7 @@
 .. module:: mutex
    :synopsis: Lock and queue for mutual exclusion.
    :deprecated:
-   
+
 .. deprecated::
    The :mod:`mutex` module has been removed in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/new.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/new.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/new.rst	Wed Jan 14 13:24:17 2009
@@ -1,4 +1,3 @@
-
 :mod:`new` --- Creation of runtime internal objects
 ===================================================
 
@@ -7,7 +6,8 @@
    :deprecated:
 
 .. deprecated:: 2.6
-   The :mod:`new` module has been removed in Python 3.0.
+   The :mod:`new` module has been removed in Python 3.0.  Use the :mod:`types`
+   module's classes instead.
 
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 

Modified: python/branches/tlee-ast-optimize/Doc/library/nntplib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/nntplib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/nntplib.rst	Wed Jan 14 13:24:17 2009
@@ -24,16 +24,16 @@
    Group comp.lang.python has 59 articles, range 3742 to 3803
    >>> resp, subs = s.xhdr('subject', first + '-' + last)
    >>> for id, sub in subs[-10:]: print id, sub
-   ... 
+   ...
    3792 Re: Removing elements from a list while iterating...
    3793 Re: Who likes Info files?
    3794 Emacs and doc strings
    3795 a few questions about the Mac implementation
    3796 Re: executable python scripts
    3797 Re: executable python scripts
-   3798 Re: a few questions about the Mac implementation 
+   3798 Re: a few questions about the Mac implementation
    3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules
-   3802 Re: executable python scripts 
+   3802 Re: executable python scripts
    3803 Re: \POSIX{} wait and SIGCHLD
    >>> s.quit()
    '205 news.cwi.nl closing connection.  Goodbye.'

Modified: python/branches/tlee-ast-optimize/Doc/library/numbers.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/numbers.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/numbers.rst	Wed Jan 14 13:24:17 2009
@@ -51,14 +51,14 @@
    :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``,
    ``%``, ``<``, ``<=``, ``>``, and ``>=``.
 
-   Real also provides defaults for :func:`complex`, :attr:`Complex.real`,
-   :attr:`Complex.imag`, and :meth:`Complex.conjugate`.
+   Real also provides defaults for :func:`complex`, :attr:`~Complex.real`,
+   :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`.
 
 
 .. class:: Rational
 
    Subtypes :class:`Real` and adds
-   :attr:`Rational.numerator` and :attr:`Rational.denominator` properties, which
+   :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which
    should be in lowest terms. With these, it provides a default for
    :func:`float`.
 
@@ -74,8 +74,8 @@
 .. class:: Integral
 
    Subtypes :class:`Rational` and adds a conversion to :class:`int`.
-   Provides defaults for :func:`float`, :attr:`Rational.numerator`, and
-   :attr:`Rational.denominator`, and bit-string operations: ``<<``,
+   Provides defaults for :func:`float`, :attr:`~Rational.numerator`, and
+   :attr:`~Rational.denominator`, and bit-string operations: ``<<``,
    ``>>``, ``&``, ``^``, ``|``, ``~``.
 
 
@@ -171,7 +171,7 @@
        knowledge of ``A``, so it can handle those instances before
        delegating to :class:`Complex`.
 
-If ``A<:Complex`` and ``B<:Real`` without sharing any other knowledge,
+If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
 then the appropriate shared operation is the one involving the built
 in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b
 == b+a``.

Modified: python/branches/tlee-ast-optimize/Doc/library/operator.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/operator.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/operator.rst	Wed Jan 14 13:24:17 2009
@@ -7,7 +7,7 @@
 
 
 .. testsetup::
-   
+
    import operator
    from operator import itemgetter
 
@@ -240,6 +240,10 @@
 
    Delete the slice of *a* from index *b* to index *c-1*.
 
+   .. deprecated:: 2.6
+      This function is removed in Python 3.x.  Use :func:`delitem` with a slice
+      index.
+
 
 .. function:: getitem(a, b)
               __getitem__(a, b)
@@ -252,6 +256,10 @@
 
    Return the slice of *a* from index *b* to index *c-1*.
 
+   .. deprecated:: 2.6
+      This function is removed in Python 3.x.  Use :func:`getitem` with a slice
+      index.
+
 
 .. function:: indexOf(a, b)
 
@@ -283,6 +291,11 @@
 
    Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
 
+   .. deprecated:: 2.6
+      This function is removed in Python 3.x.  Use :func:`setitem` with a slice
+      index.
+
+
 Many operations have an "in-place" version.  The following functions provide a
 more primitive access to in-place operators than the usual syntax does; for
 example, the :term:`statement` ``x += y`` is equivalent to
@@ -424,7 +437,7 @@
 
       >>> class C:
       ...     pass
-      ... 
+      ...
       >>> import operator
       >>> obj = C()
       >>> operator.isMappingType(obj)
@@ -534,9 +547,9 @@
                 def g(obj):
                     return tuple(obj[item] for item in items)
             return g
-   
-   The items can be any type accepted by the operand's :meth:`__getitem__` 
-   method.  Dictionaries accept any hashable value.  Lists, tuples, and 
+
+   The items can be any type accepted by the operand's :meth:`__getitem__`
+   method.  Dictionaries accept any hashable value.  Lists, tuples, and
    strings accept an index or a slice:
 
       >>> itemgetter(1)('ABCDEFG')

Modified: python/branches/tlee-ast-optimize/Doc/library/optparse.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/optparse.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/optparse.rst	Wed Jan 14 13:24:17 2009
@@ -548,8 +548,8 @@
 :class:`OptionGroup` to a parser is easy::
 
     group = OptionGroup(parser, "Dangerous Options",
-			"Caution: use these options at your own risk.  "
-			"It is believed that some of them bite.")
+                        "Caution: use these options at your own risk.  "
+                        "It is believed that some of them bite.")
     group.add_option("-g", action="store_true", help="Group option.")
     parser.add_option_group(group)
 
@@ -563,12 +563,12 @@
       -q, --quiet          be vewwy quiet (I'm hunting wabbits)
       -fFILE, --file=FILE  write output to FILE
       -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
-			   [default], 'expert'
+                           [default], 'expert'
 
       Dangerous Options:
-	Caution: use of these options is at your own risk.  It is believed that
-	some of them bite.
-	-g                 Group option.
+      Caution: use of these options is at your own risk.  It is believed that
+      some of them bite.
+      -g                 Group option.
 
 .. _optparse-printing-version-string:
 
@@ -799,7 +799,7 @@
 The keyword arguments define attributes of the new Option object.  The most
 important option attribute is :attr:`action`, and it largely determines which
 other attributes are relevant or required.  If you pass irrelevant option
-attributes, or fail to pass required ones, :mod:`optparse` raises an 
+attributes, or fail to pass required ones, :mod:`optparse` raises an
 :exc:`OptionError` exception explaining your mistake.
 
 An option's *action* determines what :mod:`optparse` does when it encounters
@@ -1630,36 +1630,33 @@
 Nevertheless, here's a stab at a callback for an option with variable
 arguments::
 
-   def vararg_callback(option, opt_str, value, parser):
-       assert value is None
-       done = 0
-       value = []
-       rargs = parser.rargs
-       while rargs:
-           arg = rargs[0]
-
-           # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
-           # etc.  Note that this also stops on "-3" or "-3.0", so if
-           # your option takes numeric values, you will need to handle
-           # this.
-           if ((arg[:2] == "--" and len(arg) > 2) or
-               (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
-               break
-           else:
-               value.append(arg)
-               del rargs[0]
+    def vararg_callback(option, opt_str, value, parser):
+        assert value is None
+        value = []
+
+        def floatable(str):
+            try:
+                float(str)
+                return True
+            except ValueError:
+                return False
+
+        for arg in parser.rargs:
+            # stop on --foo like options
+            if arg[:2] == "--" and len(arg) > 2:
+                break
+            # stop on -a, but not on -3 or -3.0
+            if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
+                break
+            value.append(arg)
 
-       setattr(parser.values, option.dest, value)
+        del parser.rargs[:len(value)]
+        setattr(parser.values, option.dest, value))
 
    [...]
    parser.add_option("-c", "--callback", dest="vararg_attr",
                      action="callback", callback=vararg_callback)
 
-The main weakness with this particular implementation is that negative numbers
-in the arguments following ``"-c"`` will be interpreted as further options
-(probably causing an error), rather than as arguments to ``"-c"``.  Fixing this
-is left as an exercise for the reader.
-
 
 .. _optparse-extending-optparse:
 

Modified: python/branches/tlee-ast-optimize/Doc/library/os.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/os.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/os.rst	Wed Jan 14 13:24:17 2009
@@ -368,7 +368,7 @@
    is returned. Availability: Unix, Windows.
 
    .. deprecated:: 2.6
-      This function is obsolete.  Use the :mod:`subprocess` module.  Check 
+      This function is obsolete.  Use the :mod:`subprocess` module.  Check
       especially the :ref:`subprocess-replacements` section.
 
    .. versionchanged:: 2.0
@@ -418,7 +418,7 @@
    child_stdout)``.
 
    .. deprecated:: 2.6
-      This function is obsolete.  Use the :mod:`subprocess` module.  Check 
+      This function is obsolete.  Use the :mod:`subprocess` module.  Check
       especially the :ref:`subprocess-replacements` section.
 
    Availability: Unix, Windows.
@@ -432,7 +432,7 @@
    child_stdout, child_stderr)``.
 
    .. deprecated:: 2.6
-      This function is obsolete.  Use the :mod:`subprocess` module.  Check 
+      This function is obsolete.  Use the :mod:`subprocess` module.  Check
       especially the :ref:`subprocess-replacements` section.
 
    Availability: Unix, Windows.
@@ -446,7 +446,7 @@
    child_stdout_and_stderr)``.
 
    .. deprecated:: 2.6
-      This function is obsolete.  Use the :mod:`subprocess` module.  Check 
+      This function is obsolete.  Use the :mod:`subprocess` module.  Check
       especially the :ref:`subprocess-replacements` section.
 
    Availability: Unix, Windows.
@@ -681,10 +681,11 @@
       :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
       method.
 
-The following data items are available for use in constructing the *flags*
-parameter to the :func:`open` function.  Some items will not be available on all
-platforms.  For descriptions of their availability and use, consult
-:manpage:`open(2)`.
+The following constants are options for the *flags* parameter to the
+:func:`open` function.  They can be combined using the bitwise OR operator
+``|``.  Some of them are not available on all platforms.  For descriptions of
+their availability and use, consult the :manpage:`open(2)` manual page on Unix
+or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>` on Windows.
 
 
 .. data:: O_RDONLY
@@ -695,8 +696,7 @@
           O_EXCL
           O_TRUNC
 
-   Options for the *flag* argument to the :func:`open` function. These can be
-   combined using the bitwise OR operator ``|``. Availability: Unix, Windows.
+   These constants are available on Unix and Windows.
 
 
 .. data:: O_DSYNC
@@ -708,8 +708,7 @@
           O_SHLOCK
           O_EXLOCK
 
-   More options for the *flag* argument to the :func:`open` function. Availability:
-   Unix.
+   These constants are only available on Unix.
 
 
 .. data:: O_BINARY
@@ -720,8 +719,7 @@
           O_SEQUENTIAL
           O_TEXT
 
-   Options for the *flag* argument to the :func:`open` function. These can be
-   combined using the bitwise OR operator ``|``. Availability: Windows.
+   These constants are only available on Windows.
 
 
 .. data:: O_ASYNC
@@ -730,8 +728,8 @@
           O_NOFOLLOW
           O_NOATIME
 
-   Options for the *flag* argument to the :func:`open` function. These are
-   GNU extensions and not present if they are not defined by the C library.
+   These constants are GNU extensions and not present if they are not defined by
+   the C library.
 
 
 .. data:: SEEK_SET
@@ -1451,7 +1449,7 @@
    These functions all execute a new program, replacing the current process; they
    do not return.  On Unix, the new executable is loaded into the current process,
    and will have the same process id as the caller.  Errors will be reported as
-   :exc:`OSError` exceptions.  
+   :exc:`OSError` exceptions.
 
    The current process is replaced immediately. Open file objects and
    descriptors are not flushed, so if there may be data buffered
@@ -1483,7 +1481,7 @@
    used to define the environment variables for the new process (these are used
    instead of the current process' environment); the functions :func:`execl`,
    :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
-   inherit the environment of the current process. 
+   inherit the environment of the current process.
 
    Availability: Unix, Windows.
 
@@ -1720,7 +1718,7 @@
 
    (Note that the :mod:`subprocess` module provides more powerful facilities for
    spawning new processes and retrieving their results; using that module is
-   preferable to using these functions.  Check specially the *Replacing Older 
+   preferable to using these functions.  Check specially the *Replacing Older
    Functions with the subprocess Module* section in that documentation page.)
 
    If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new

Modified: python/branches/tlee-ast-optimize/Doc/library/ossaudiodev.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/ossaudiodev.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/ossaudiodev.rst	Wed Jan 14 13:24:17 2009
@@ -18,26 +18,26 @@
    use ALSA, you'll have to make sure its OSS compatibility layer
    is active to use ossaudiodev, but you're gonna need it for the vast
    majority of Linux audio apps anyways.
-   
+
    Sounds like things are also complicated for other BSDs.  In response
    to my python-dev query, Thomas Wouters said:
-   
+
    > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
    > OSS installation manual tells you to remove references to OSS/Free from the
    > kernel :)
-   
+
    but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
    from its <soundcard.h>:
    >  * WARNING!  WARNING!
    >  * This is an OSS (Linux) audio emulator.
    >  * Use the Native NetBSD API for developing new code, and this
    >  * only for compiling Linux programs.
-   
+
    There's also an ossaudio manpage on OpenBSD that explains things
    further.  Presumably NetBSD and OpenBSD have a different standard
    audio interface.  That's the great thing about standards, there are so
    many to choose from ... ;-)
-   
+
    This probably all warrants a footnote or two, but I don't understand
    things well enough right now to write it!   --GPW
 

Modified: python/branches/tlee-ast-optimize/Doc/library/othergui.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/othergui.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/othergui.rst	Wed Jan 14 13:24:17 2009
@@ -70,7 +70,7 @@
       Robin Dunn.
 
 PyGTK, PyQt, and wxPython, all have a modern look and feel and more
-widgets than Tkinter. In addition, there are many other GUI toolkits for 
+widgets than Tkinter. In addition, there are many other GUI toolkits for
 Python, both cross-platform, and platform-specific. See the `GUI Programming
 <http://wiki.python.org/moin/GuiProgramming>`_ page in the Python Wiki for a
 much more complete list, and also for links to documents where the

Modified: python/branches/tlee-ast-optimize/Doc/library/parser.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/parser.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/parser.rst	Wed Jan 14 13:24:17 2009
@@ -641,7 +641,7 @@
 while the long form uses an indented block and allows nested definitions::
 
    def make_power(exp):
-       "Make a function that raises an argument to the exponent `exp'."
+       "Make a function that raises an argument to the exponent `exp`."
        def raiser(x, y=exp):
            return x ** y
        return raiser

Modified: python/branches/tlee-ast-optimize/Doc/library/pdb.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/pdb.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/pdb.rst	Wed Jan 14 13:24:17 2009
@@ -37,7 +37,7 @@
    (Pdb) continue
    NameError: 'spam'
    > <string>(1)?()
-   (Pdb) 
+   (Pdb)
 
 :file:`pdb.py` can also be invoked as a script to debug other scripts.  For
 example::
@@ -68,7 +68,7 @@
    >>> pdb.pm()
    > ./mymodule.py(3)test2()
    -> print spam
-   (Pdb) 
+   (Pdb)
 
 The module defines the following functions; each enters the debugger in a
 slightly different way:
@@ -109,7 +109,7 @@
 
 .. function:: post_mortem([traceback])
 
-   Enter post-mortem debugging of the given *traceback* object.  If no 
+   Enter post-mortem debugging of the given *traceback* object.  If no
    *traceback* is given, it uses the one of the exception that is currently
    being handled (an exception must be being handled if the default is to be
    used).

Modified: python/branches/tlee-ast-optimize/Doc/library/pickle.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/pickle.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/pickle.rst	Wed Jan 14 13:24:17 2009
@@ -413,7 +413,7 @@
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 .. method:: object.__getinitargs__()
-   
+
    When a pickled class instance is unpickled, its :meth:`__init__` method is
    normally *not* invoked.  If it is desirable that the :meth:`__init__` method
    be called on unpickling, an old-style class can define a method
@@ -430,31 +430,31 @@
    is affected by the values passed to the :meth:`__new__` method for the type
    (as it is for tuples and strings).  Instances of a :term:`new-style class`
    ``C`` are created using ::
-    
+
       obj = C.__new__(C, *args)
-    
+
    where *args* is the result of calling :meth:`__getnewargs__` on the original
    object; if there is no :meth:`__getnewargs__`, an empty tuple is assumed.
 
 .. method:: object.__getstate__()
-   
+
    Classes can further influence how their instances are pickled; if the class
    defines the method :meth:`__getstate__`, it is called and the return state is
    pickled as the contents for the instance, instead of the contents of the
    instance's dictionary.  If there is no :meth:`__getstate__` method, the
    instance's :attr:`__dict__` is pickled.
 
-.. method:: object.__setstate__() 
-   
+.. method:: object.__setstate__()
+
    Upon unpickling, if the class also defines the method :meth:`__setstate__`,
    it is called with the unpickled state. [#]_ If there is no
    :meth:`__setstate__` method, the pickled state must be a dictionary and its
    items are assigned to the new instance's dictionary.  If a class defines both
    :meth:`__getstate__` and :meth:`__setstate__`, the state object needn't be a
    dictionary and these methods can do what they want. [#]_
-    
+
    .. warning::
-    
+
       For :term:`new-style class`\es, if :meth:`__getstate__` returns a false
       value, the :meth:`__setstate__` method will not be called.
 
@@ -463,7 +463,7 @@
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 .. method:: object.__reduce__()
-   
+
    When the :class:`Pickler` encounters an object of a type it knows nothing
    about --- such as an extension type --- it looks in two places for a hint of
    how to pickle it.  One alternative is for the object to implement a
@@ -518,7 +518,7 @@
      is primarily used for dictionary subclasses, but may be used by other
      classes as long as they implement :meth:`__setitem__`.
 
-.. method:: object.__reduce_ex__(protocol) 
+.. method:: object.__reduce_ex__(protocol)
 
    It is sometimes useful to know the protocol version when implementing
    :meth:`__reduce__`.  This can be done by implementing a method named

Modified: python/branches/tlee-ast-optimize/Doc/library/popen2.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/popen2.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/popen2.rst	Wed Jan 14 13:24:17 2009
@@ -9,7 +9,7 @@
 
 
 .. deprecated:: 2.6
-   This module is obsolete.  Use the :mod:`subprocess` module.  Check 
+   This module is obsolete.  Use the :mod:`subprocess` module.  Check
    especially the :ref:`subprocess-replacements` section.
 
 This module allows you to spawn processes and connect to their

Modified: python/branches/tlee-ast-optimize/Doc/library/profile.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/profile.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/profile.rst	Wed Jan 14 13:24:17 2009
@@ -51,17 +51,17 @@
 
 The Python standard library provides three different profilers:
 
-#. :mod:`cProfile` is recommended for most users; it's a C extension 
+#. :mod:`cProfile` is recommended for most users; it's a C extension
    with reasonable overhead
-   that makes it suitable for profiling long-running programs. 
+   that makes it suitable for profiling long-running programs.
    Based on :mod:`lsprof`,
-   contributed by Brett Rosen and Ted Czotter.  
+   contributed by Brett Rosen and Ted Czotter.
 
    .. versionadded:: 2.5
 
 #. :mod:`profile`, a pure Python module whose interface is imitated by
-   :mod:`cProfile`.  Adds significant overhead to profiled programs. 
-   If you're trying to extend 
+   :mod:`cProfile`.  Adds significant overhead to profiled programs.
+   If you're trying to extend
    the profiler in some way, the task might be easier with this module.
    Copyright © 1994, by InfoSeek Corporation.
 
@@ -72,7 +72,7 @@
    the overhead of profiling, at the expense of longer data
    post-processing times.  It is no longer maintained and may be
    dropped in a future version of Python.
- 
+
 
    .. versionchanged:: 2.5
       The results should be more meaningful than in the past: the timing core
@@ -276,24 +276,24 @@
    that the text string in the far right column was used to sort the output. The
    column headings include:
 
-   ncalls 
+   ncalls
       for the number of calls,
 
-   tottime 
+   tottime
       for the total time spent in the given function (and excluding time made in calls
       to sub-functions),
 
-   percall 
+   percall
       is the quotient of ``tottime`` divided by ``ncalls``
 
-   cumtime 
+   cumtime
       is the total time spent in this and all subfunctions (from invocation till
       exit). This figure is accurate *even* for recursive functions.
 
-   percall 
+   percall
       is the quotient of ``cumtime`` divided by primitive calls
 
-   filename:lineno(function) 
+   filename:lineno(function)
       provides the respective data of each function
 
    When there are two numbers in the first column (for example, ``43/3``), then the

Modified: python/branches/tlee-ast-optimize/Doc/library/pydoc.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/pydoc.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/pydoc.rst	Wed Jan 14 13:24:17 2009
@@ -36,6 +36,13 @@
 Unix), and refers to an existing Python source file, then documentation is
 produced for that file.
 
+.. note::
+
+   In order to find objects and their documentation, :mod:`pydoc` imports the
+   module(s) to be documented.  Therefore, any code on module level will be
+   executed on that occasion.  Use an ``if __name__ == '__main__':`` guard to
+   only execute code when a file is invoked as a script and not just imported.
+
 Specifying a :option:`-w` flag before the argument will cause HTML documentation
 to be written out to a file in the current directory, instead of displaying text
 on the console.

Modified: python/branches/tlee-ast-optimize/Doc/library/pyexpat.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/pyexpat.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/pyexpat.rst	Wed Jan 14 13:24:17 2009
@@ -182,9 +182,9 @@
 
 .. attribute:: xmlparser.buffer_size
 
-   The size of the buffer used when :attr:`buffer_text` is true.  
-   A new buffer size can be set by assigning a new integer value 
-   to this attribute.  
+   The size of the buffer used when :attr:`buffer_text` is true.
+   A new buffer size can be set by assigning a new integer value
+   to this attribute.
    When the size is changed, the buffer will be flushed.
 
    .. versionadded:: 2.3

Modified: python/branches/tlee-ast-optimize/Doc/library/random.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/random.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/random.rst	Wed Jan 14 13:24:17 2009
@@ -210,9 +210,11 @@
 
 .. function:: expovariate(lambd)
 
-   Exponential distribution.  *lambd* is 1.0 divided by the desired mean.  (The
-   parameter would be called "lambda", but that is a reserved word in Python.)
-   Returned values range from 0 to positive infinity.
+   Exponential distribution.  *lambd* is 1.0 divided by the desired
+   mean.  It should be nonzero.  (The parameter would be called
+   "lambda", but that is a reserved word in Python.)  Returned values
+   range from 0 to positive infinity if *lambd* is positive, and from
+   negative infinity to 0 if *lambd* is negative.
 
 
 .. function:: gammavariate(alpha, beta)

Modified: python/branches/tlee-ast-optimize/Doc/library/re.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/re.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/re.rst	Wed Jan 14 13:24:17 2009
@@ -750,6 +750,11 @@
    were provided.
 
 
+.. attribute:: RegexObject.groups
+
+   The number of capturing groups in the pattern.
+
+
 .. attribute:: RegexObject.groupindex
 
    A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
@@ -989,14 +994,14 @@
 
    >>> pair.match("717ak").group(1)
    '7'
-   
+
    # Error because re.match() returns None, which doesn't have a group() method:
    >>> pair.match("718ak").group(1)
    Traceback (most recent call last):
      File "<pyshell#23>", line 1, in <module>
        re.match(r".*(.).*\1", "718ak").group(1)
    AttributeError: 'NoneType' object has no attribute 'group'
-   
+
    >>> pair.match("354aa").group(1)
    'a'
 
@@ -1105,7 +1110,7 @@
 Making a Phonebook
 ^^^^^^^^^^^^^^^^^^
 
-:func:`split` splits a string into a list delimited by the passed pattern.  The 
+:func:`split` splits a string into a list delimited by the passed pattern.  The
 method is invaluable for converting textual data into data structures that can be
 easily read and modified by Python as demonstrated in the following example that
 creates a phonebook.
@@ -1114,7 +1119,7 @@
 triple-quoted string syntax:
 
    >>> input = """Ross McFluff: 834.345.1254 155 Elm Street
-   ... 
+   ...
    ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
    ... Frank Burger: 925.541.7625 662 South Dogwood Way
    ...

Modified: python/branches/tlee-ast-optimize/Doc/library/repr.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/repr.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/repr.rst	Wed Jan 14 13:24:17 2009
@@ -125,15 +125,15 @@
 the handling of types already supported. This example shows how special support
 for file objects could be added::
 
-   import repr
+   import repr as reprlib
    import sys
 
-   class MyRepr(repr.Repr):
+   class MyRepr(reprlib.Repr):
        def repr_file(self, obj, level):
            if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
                return obj.name
            else:
-               return `obj`
+               return repr(obj)
 
    aRepr = MyRepr()
    print aRepr.repr(sys.stdin)          # prints '<stdin>'

Modified: python/branches/tlee-ast-optimize/Doc/library/rexec.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/rexec.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/rexec.rst	Wed Jan 14 13:24:17 2009
@@ -5,7 +5,7 @@
 .. module:: rexec
    :synopsis: Basic restricted execution framework.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`rexec` module has been removed in Python 3.0.
 
@@ -272,7 +272,7 @@
                pass
            elif mode in ('w', 'wb', 'a', 'ab'):
                # check filename : must begin with /tmp/
-               if file[:5]!='/tmp/': 
+               if file[:5]!='/tmp/':
                    raise IOError, "can't write outside /tmp"
                elif (string.find(file, '/../') >= 0 or
                     file[:3] == '../' or file[-3:] == '/..'):

Modified: python/branches/tlee-ast-optimize/Doc/library/rlcompleter.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/rlcompleter.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/rlcompleter.rst	Wed Jan 14 13:24:17 2009
@@ -61,6 +61,6 @@
    If called for a dotted name, it will try to evaluate anything without obvious
    side-effects (functions will not be evaluated, but it can generate calls to
    :meth:`__getattr__`) up to the last part, and find matches for the rest via the
-   :func:`dir` function.  Any exception raised during the evaluation of the 
+   :func:`dir` function.  Any exception raised during the evaluation of the
    expression is caught, silenced and :const:`None` is returned.
 

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	Wed Jan 14 13:24:17 2009
@@ -13,7 +13,7 @@
    single: World Wide Web
    single: URL
    single: robots.txt
-   
+
 .. note::
    The :mod:`robotparser` module has been renamed :mod:`urllib.robotparser` in
    Python 3.0.

Modified: python/branches/tlee-ast-optimize/Doc/library/sched.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/sched.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/sched.rst	Wed Jan 14 13:24:17 2009
@@ -42,7 +42,7 @@
    930343700.276
 
 In multi-threaded environments, the :class:`scheduler` class has limitations
-with respect to thread-safety, inability to insert a new task before 
+with respect to thread-safety, inability to insert a new task before
 the one currently pending in a running scheduler, and holding up the main
 thread until the event queue is empty.  Instead, the preferred approach
 is to use the :class:`threading.Timer` class instead.
@@ -58,8 +58,8 @@
     ...     print time.time()
     ...     Timer(5, print_time, ()).start()
     ...     Timer(10, print_time, ()).start()
-    ...     time.sleep(11)	# sleep while time-delay events execute
-    ...     print time.time()     
+    ...     time.sleep(11)  # sleep while time-delay events execute
+    ...     print time.time()
     ...
     >>> print_some_times()
     930343690.257

Modified: python/branches/tlee-ast-optimize/Doc/library/sgmllib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/sgmllib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/sgmllib.rst	Wed Jan 14 13:24:17 2009
@@ -4,7 +4,7 @@
 .. module:: sgmllib
    :synopsis: Only as much of an SGML parser as needed to parse HTML.
    :deprecated:
-   
+
 .. deprecated:: 2.6
     The :mod:`sgmllib` module has been removed in Python 3.0.
 

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	Wed Jan 14 13:24:17 2009
@@ -20,7 +20,7 @@
 
    Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
    can't copy all file metadata.
-   
+
    On POSIX platforms, this means that file owner and group are lost as well
    as ACLs.  On Mac OS, the resource fork and other metadata are not used.
    This means that resources will be lost and file type and creator codes will
@@ -43,7 +43,8 @@
 
    Copy the contents (no metadata) of the file named *src* to a file named *dst*.
    *dst* must be the complete target file name; look at :func:`copy` for a copy that
-   accepts a target directory path.
+   accepts a target directory path.  If *src* and *dst* are the same files,
+   :exc:`Error` is raised.
    The destination location must be writable; otherwise,  an :exc:`IOError` exception
    will be raised. If *dst* already exists, it will be replaced.   Special files
    such as character or block devices and pipes cannot be copied with this
@@ -123,7 +124,7 @@
       error. Copy permissions and times of directories using :func:`copystat`.
 
    .. versionchanged:: 2.6
-      Added the *ignore* argument to be able to influence what is being copied. 
+      Added the *ignore* argument to be able to influence what is being copied.
 
 
 .. function:: rmtree(path[, ignore_errors[, onerror]])
@@ -155,7 +156,7 @@
    Recursively move a file or directory to another location.
 
    If the destination is on the current filesystem, then simply use rename.
-   Otherwise, copy src to the dst and then remove src.
+   Otherwise, copy src (with :func:`copy2`) to the dst and then remove src.
 
    .. versionadded:: 2.3
 
@@ -188,7 +189,7 @@
        os.makedirs(dst)
        errors = []
        for name in names:
-           if name in ignored_names:   
+           if name in ignored_names:
                continue
            srcname = os.path.join(src, name)
            dstname = os.path.join(dst, name)
@@ -220,7 +221,7 @@
 Another example that uses the :func:`ignore_patterns` helper::
 
    from shutil import copytree, ignore_patterns
-   
+
    copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
 
 This will copy everything except ``.pyc`` files and files or directories whose
@@ -230,7 +231,7 @@
 
    from shutil import copytree
    import logging
-   
+
    def _logpath(path, names):
        logging.info('Working in %s' % path)
        return []   # nothing will be ignored

Modified: python/branches/tlee-ast-optimize/Doc/library/signal.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/signal.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/signal.rst	Wed Jan 14 13:24:17 2009
@@ -39,12 +39,12 @@
 * Some care must be taken if both signals and threads are used in the same
   program.  The fundamental thing to remember in using signals and threads
   simultaneously is: always perform :func:`signal` operations in the main thread
-  of execution.  Any thread can perform an :func:`alarm`, :func:`getsignal`, 
-  :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread 
-  can set a new signal handler, and the main thread will be the only one to 
-  receive signals (this is enforced by the Python :mod:`signal` module, even 
-  if the underlying thread implementation supports sending signals to 
-  individual threads).  This means that signals can't be used as a means of 
+  of execution.  Any thread can perform an :func:`alarm`, :func:`getsignal`,
+  :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread
+  can set a new signal handler, and the main thread will be the only one to
+  receive signals (this is enforced by the Python :mod:`signal` module, even
+  if the underlying thread implementation supports sending signals to
+  individual threads).  This means that signals can't be used as a means of
   inter-thread communication.  Use locks instead.
 
 The variables defined in the :mod:`signal` module are:
@@ -52,10 +52,10 @@
 
 .. data:: SIG_DFL
 
-   This is one of two standard signal handling options; it will simply perform the
-   default function for the signal.  For example, on most systems the default
-   action for :const:`SIGQUIT` is to dump core and exit, while the default action
-   for :const:`SIGCLD` is to simply ignore it.
+   This is one of two standard signal handling options; it will simply perform
+   the default function for the signal.  For example, on most systems the
+   default action for :const:`SIGQUIT` is to dump core and exit, while the
+   default action for :const:`SIGCHLD` is to simply ignore it.
 
 
 .. data:: SIG_IGN
@@ -80,22 +80,22 @@
    One more than the number of the highest signal number.
 
 
-.. data:: ITIMER_REAL    
+.. data:: ITIMER_REAL
 
    Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration.
 
 
-.. data:: ITIMER_VIRTUAL 
+.. data:: ITIMER_VIRTUAL
 
-   Decrements interval timer only when the process is executing, and delivers 
+   Decrements interval timer only when the process is executing, and delivers
    SIGVTALRM upon expiration.
 
 
 .. data:: ITIMER_PROF
-   
-   Decrements interval timer both when the process executes and when the 
-   system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, 
-   this timer is usually used to profile the time spent by the application 
+
+   Decrements interval timer both when the process executes and when the
+   system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
+   this timer is usually used to profile the time spent by the application
    in user and kernel space. SIGPROF is delivered upon expiration.
 
 
@@ -105,7 +105,7 @@
 
    Raised to signal an error from the underlying :func:`setitimer` or
    :func:`getitimer` implementation. Expect this error if an invalid
-   interval timer or a negative time is passed to :func:`setitimer`. 
+   interval timer or a negative time is passed to :func:`setitimer`.
    This error is a subtype of :exc:`IOError`.
 
 
@@ -143,21 +143,21 @@
 
 .. function:: setitimer(which, seconds[, interval])
 
-   Sets given interval timer (one of :const:`signal.ITIMER_REAL`, 
+   Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
    :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
-   by *which* to fire after *seconds* (float is accepted, different from 
+   by *which* to fire after *seconds* (float is accepted, different from
    :func:`alarm`) and after that every *interval* seconds. The interval
    timer specified by *which* can be cleared by setting seconds to zero.
 
    When an interval timer fires, a signal is sent to the process.
-   The signal sent is dependent on the timer being used; 
-   :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`, 
+   The signal sent is dependent on the timer being used;
+   :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
    :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
    and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.
 
    The old values are returned as a tuple: (delay, interval).
 
-   Attempting to pass an invalid interval timer will cause a 
+   Attempting to pass an invalid interval timer will cause a
    :exc:`ItimerError`.
 
    .. versionadded:: 2.6
@@ -190,7 +190,7 @@
    will be restarted when interrupted by signal *signalnum*, otherwise system calls will
    be interrupted. Returns nothing. Availability: Unix (see the man page
    :manpage:`siginterrupt(3)` for further information).
-   
+
    Note that installing a signal handler with :func:`signal` will reset the restart
    behaviour to interruptible by implicitly calling :cfunc:`siginterrupt` with a true *flag*
    value for the given signal.
@@ -239,7 +239,7 @@
    signal.alarm(5)
 
    # This open() may hang indefinitely
-   fd = os.open('/dev/ttyS0', os.O_RDWR)  
+   fd = os.open('/dev/ttyS0', os.O_RDWR)
 
    signal.alarm(0)          # Disable the alarm
 

Modified: python/branches/tlee-ast-optimize/Doc/library/simplexmlrpcserver.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/simplexmlrpcserver.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/simplexmlrpcserver.rst	Wed Jan 14 13:24:17 2009
@@ -151,7 +151,7 @@
                                requestHandler=RequestHandler)
    server.register_introspection_functions()
 
-   # Register pow() function; this will use the value of 
+   # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)
 
@@ -160,10 +160,10 @@
        return x + y
    server.register_function(adder_function, 'add')
 
-   # Register an instance; all the methods of the instance are 
+   # Register an instance; all the methods of the instance are
    # published as XML-RPC methods (in this case, just 'div').
    class MyFuncs:
-       def div(self, x, y): 
+       def div(self, x, y):
            return x // y
 
    server.register_instance(MyFuncs())

Modified: python/branches/tlee-ast-optimize/Doc/library/smtplib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/smtplib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/smtplib.rst	Wed Jan 14 13:24:17 2009
@@ -189,9 +189,9 @@
 
    Identify yourself to an ESMTP server using ``EHLO``.  The hostname argument
    defaults to the fully qualified domain name of the local host.  Examine the
-   response for ESMTP option and store them for use by :meth:`has_extn`. 
-   Also sets several informational attributes: the message returned by 
-   the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp` 
+   response for ESMTP option and store them for use by :meth:`has_extn`.
+   Also sets several informational attributes: the message returned by
+   the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
    is set to true or false depending on whether the server supports ESMTP, and
    :attr:`esmtp_features` will be a dictionary containing the names of the
    SMTP service extensions this server supports, and their
@@ -207,7 +207,7 @@
    previous ``EHLO`` or ``HELO`` command this session.  It tries ESMTP ``EHLO``
    first.
 
-   :exc:SMTPHeloError
+   :exc:`SMTPHeloError`
      The server didn't reply properly to the ``HELO`` greeting.
 
    .. versionadded:: 2.6

Modified: python/branches/tlee-ast-optimize/Doc/library/socket.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/socket.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/socket.rst	Wed Jan 14 13:24:17 2009
@@ -184,10 +184,10 @@
 
 .. data:: SIO_*
           RCVALL_*
-          
+
    Constants for Windows' WSAIoctl(). The constants are used as arguments to the
    :meth:`ioctl` method of socket objects.
-   
+
    .. versionadded:: 2.6
 
 .. data:: TIPC_*
@@ -222,7 +222,7 @@
    all the necessary arguments for creating the corresponding socket. *host* is a domain
    name, a string representation of an IPv4/v6 address or ``None``. *port* is a string
    service name such as ``'http'``, a numeric port number or ``None``.
-   The rest of the arguments are optional and must be numeric if specified.  
+   The rest of the arguments are optional and must be numeric if specified.
    By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API.
 
    The :func:`getaddrinfo` function returns a list of 5-tuples with the following
@@ -588,14 +588,14 @@
    contents of the buffer (see the optional built-in module :mod:`struct` for a way
    to decode C structures encoded as strings).
 
-   
+
 .. method:: socket.ioctl(control, option)
 
-   :platform: Windows 
-   
+   :platform: Windows
+
    The :meth:`ioctl` method is a limited interface to the WSAIoctl system
    interface. Please refer to the MSDN documentation for more information.
-   
+
    .. versionadded:: 2.6
 
 
@@ -852,20 +852,21 @@
    HOST = None               # Symbolic name meaning all available interfaces
    PORT = 50007              # Arbitrary non-privileged port
    s = None
-   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
+   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
+                                 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
-   	s = socket.socket(af, socktype, proto)
+           s = socket.socket(af, socktype, proto)
        except socket.error, msg:
-   	s = None
-   	continue
+           s = None
+           continue
        try:
-   	s.bind(sa)
-   	s.listen(1)
+           s.bind(sa)
+           s.listen(1)
        except socket.error, msg:
-   	s.close()
-   	s = None
-   	continue
+           s.close()
+           s = None
+           continue
        break
    if s is None:
        print 'could not open socket'
@@ -890,16 +891,16 @@
    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        try:
-   	s = socket.socket(af, socktype, proto)
+           s = socket.socket(af, socktype, proto)
        except socket.error, msg:
-   	s = None
-   	continue
+           s = None
+           continue
        try:
-   	s.connect(sa)
+           s.connect(sa)
        except socket.error, msg:
-   	s.close()
-   	s = None
-   	continue
+           s.close()
+           s = None
+           continue
        break
    if s is None:
        print 'could not open socket'
@@ -909,7 +910,7 @@
    s.close()
    print 'Received', repr(data)
 
-   
+
 The last example shows how to write a very simple network sniffer with raw
 sockets on Windows. The example requires administrator privileges to modify
 the interface::
@@ -918,19 +919,19 @@
 
    # the public network interface
    HOST = socket.gethostbyname(socket.gethostname())
-   
+
    # create a raw socket and bind it to the public interface
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
    s.bind((HOST, 0))
-   
+
    # Include IP headers
    s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
-   
+
    # receive all packages
    s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
-   
+
    # receive a package
    print s.recvfrom(65565)
-   
+
    # disabled promiscuous mode
    s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

Modified: python/branches/tlee-ast-optimize/Doc/library/socketserver.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/socketserver.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/socketserver.rst	Wed Jan 14 13:24:17 2009
@@ -7,9 +7,9 @@
 
 .. note::
 
-   The :mod:`SocketServer` module has been renamed to `socketserver` in Python
-   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
-   your sources to 3.0.
+   The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
 
 
 The :mod:`SocketServer` module simplifies the task of writing network servers.
@@ -448,7 +448,7 @@
 
    if __name__ == "__main__":
       HOST, PORT = "localhost", 9999
-      server = SocketServer.UDPServer((HOST, PORT), BaseUDPRequestHandler)
+      server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
       server.serve_forever()
 
 This is the client side::

Modified: python/branches/tlee-ast-optimize/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/sqlite3.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/sqlite3.rst	Wed Jan 14 13:24:17 2009
@@ -244,7 +244,7 @@
 
 .. method:: Connection.rollback()
 
-   This method rolls back any changes to the database since the last call to 
+   This method rolls back any changes to the database since the last call to
    :meth:`commit`.
 
 .. method:: Connection.close()
@@ -487,29 +487,29 @@
    .. literalinclude:: ../includes/sqlite3/executescript.py
 
 
-.. method:: Cursor.fetchone() 
-          
+.. method:: Cursor.fetchone()
+
    Fetches the next row of a query result set, returning a single sequence,
    or :const:`None` when no more data is available.
 
 
 .. method:: Cursor.fetchmany([size=cursor.arraysize])
-          
+
    Fetches the next set of rows of a query result, returning a list.  An empty
    list is returned when no more rows are available.
-   
+
    The number of rows to fetch per call is specified by the *size* parameter.
    If it is not given, the cursor's arraysize determines the number of rows
    to be fetched. The method should try to fetch as many rows as indicated by
    the size parameter. If this is not possible due to the specified number of
    rows not being available, fewer rows may be returned.
-   
+
    Note there are performance considerations involved with the *size* parameter.
    For optimal performance, it is usually best to use the arraysize attribute.
    If the *size* parameter is used, then it is best for it to retain the same
    value from one :meth:`fetchmany` call to the next.
-            
-.. method:: Cursor.fetchall() 
+
+.. method:: Cursor.fetchall()
 
    Fetches all (remaining) rows of a query result, returning a list.  Note that
    the cursor's arraysize attribute can affect the performance of this operation.
@@ -546,8 +546,8 @@
 
    This read-only attribute provides the column names of the last query. To
    remain compatible with the Python DB API, it returns a 7-tuple for each
-   column where the last six items of each tuple are :const:`None`. 
-   
+   column where the last six items of each tuple are :const:`None`.
+
    It is set for ``SELECT`` statements without any matching rows as well.
 
 .. _sqlite3-row-objects:
@@ -558,7 +558,7 @@
 .. class:: Row
 
    A :class:`Row` instance serves as a highly optimized
-   :attr:`~Connection.row_factory` for :class:`Connection` objects. 
+   :attr:`~Connection.row_factory` for :class:`Connection` objects.
    It tries to mimic a tuple in most of its features.
 
    It supports mapping access by column name and index, iteration,
@@ -566,7 +566,7 @@
 
    If two :class:`Row` objects have exactly the same columns and their
    members are equal, they compare equal.
-   
+
    .. versionchanged:: 2.6
       Added iteration and equality (hashability).
 
@@ -793,7 +793,7 @@
 ------------------------
 
 By default, the :mod:`sqlite3` module opens transactions implicitly before a
-Data Modification Language (DML)  statement (i.e. 
+Data Modification Language (DML)  statement (i.e.
 ``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
 implicitly before a non-DML, non-query statement (i. e.
 anything other than ``SELECT`` or the aforementioned).

Modified: python/branches/tlee-ast-optimize/Doc/library/ssl.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/ssl.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/ssl.rst	Wed Jan 14 13:24:17 2009
@@ -48,7 +48,7 @@
 
 .. exception:: SSLError
 
-   Raised to signal an error from the underlying SSL implementation.  This 
+   Raised to signal an error from the underlying SSL implementation.  This
    signifies some problem in the higher-level
    encryption and authentication layer that's superimposed on the underlying
    network connection.  This error is a subtype of :exc:`socket.error`, which
@@ -173,7 +173,7 @@
      >>> import time
      >>> time.ctime(ssl.cert_time_to_seconds("May  9 00:00:00 2007 GMT"))
      'Wed May  9 00:00:00 2007'
-     >>> 
+     >>>
 
 .. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
 
@@ -385,7 +385,7 @@
 the client or server, and then the certificate for the issuer of that
 certificate, and then the certificate for the issuer of *that* certificate,
 and so on up the chain till you get to a certificate which is *self-signed*,
-that is, a certificate which has the same subject and issuer, 
+that is, a certificate which has the same subject and issuer,
 sometimes called a *root certificate*.  The certificates should just
 be concatenated together in the certificate file.  For example, suppose
 we had a three certificate chain, from our server certificate to the
@@ -422,13 +422,13 @@
 you only need the root certificates, and the remote peer is supposed to
 furnish the other certificates necessary to chain from its certificate to
 a root certificate.
-See :rfc:`4158` for more discussion of the way in which 
+See :rfc:`4158` for more discussion of the way in which
 certification chains can be built.
 
 If you are going to create a server that provides SSL-encrypted
 connection services, you will need to acquire a certificate for that
 service.  There are many ways of acquiring appropriate certificates,
-such as buying one from a certification authority.  Another common 
+such as buying one from a certification authority.  Another common
 practice is to generate a self-signed certificate.  The simplest
 way to do this is with the OpenSSL package, using something like
 the following::
@@ -570,7 +570,7 @@
 
 And go back to listening for new client connections.
 
-           
+
 .. seealso::
 
    Class :class:`socket.socket`

Modified: python/branches/tlee-ast-optimize/Doc/library/statvfs.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/statvfs.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/statvfs.rst	Wed Jan 14 13:24:17 2009
@@ -4,7 +4,7 @@
 .. module:: statvfs
    :synopsis: Constants for interpreting the result of os.statvfs().
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`statvfs` module has been deprecated for removal in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/stdtypes.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/stdtypes.rst	Wed Jan 14 13:24:17 2009
@@ -338,15 +338,13 @@
       module: math
       single: floor() (in module math)
       single: ceil() (in module math)
+      single: trunc() (in module math)
       pair: numeric; conversions
-      pair: C; language
 
-   Conversion from floating point to (long or plain) integer may round or
-   truncate as in C; see functions :func:`math.floor` and :func:`math.ceil` for
-   well-defined conversions.
-
-   .. deprecated:: 2.6
-      Instead, convert floats to long explicitly with :func:`trunc`.
+   Conversion from floats using :func:`int` or :func:`long` truncates toward
+   zero like the related function, :func:`math.trunc`.  Use the function
+   :func:`math.floor` to round downward and :func:`math.ceil` to round
+   upward.
 
 (3)
    See :ref:`built-in-funcs` for a full description.
@@ -362,9 +360,9 @@
    though the result's type is not necessarily int.
 
 (6)
-   float also accepts the strings "nan" and "inf" with an optional prefix "+" 
+   float also accepts the strings "nan" and "inf" with an optional prefix "+"
    or "-" for Not a Number (NaN) and positive or negative infinity.
-   
+
    .. versionadded:: 2.6
 
 (7)
@@ -447,6 +445,37 @@
    A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
 
 
+Additional Methods on Integer Types
+-----------------------------------
+
+.. method:: int.bit_length()
+.. method:: long.bit_length()
+
+    Return the number of bits necessary to represent an integer in binary,
+    excluding the sign and leading zeros::
+
+        >>> n = -37
+        >>> bin(n)
+        '-0b100101'
+        >>> n.bit_length()
+        6
+
+    More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
+    unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
+    Equivalently, when ``abs(x)`` is small enough to have a correctly
+    rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
+    If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
+
+    Equivalent to::
+
+        def bit_length(self):
+            s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
+            s = s.lstrip('-0b') # remove leading zeros and minus sign
+            return len(s)       # len('100101') --> 6
+
+    .. versionadded:: 2.7
+
+
 Additional Methods on Float
 ---------------------------
 
@@ -458,7 +487,7 @@
     original float and with a positive denominator.  Raises
     :exc:`OverflowError` on infinities and a :exc:`ValueError` on
     NaNs.
-    
+
     .. versionadded:: 2.6
 
 Two methods support conversion to
@@ -1178,7 +1207,7 @@
    Return the numeric string left filled with zeros in a string of length
    *width*.  A sign prefix is handled correctly.  The original string is
    returned if *width* is less than ``len(s)``.
-   
+
 
    .. versionadded:: 2.2.2
 
@@ -1190,7 +1219,7 @@
    otherwise. Numeric characters include digit characters, and all characters
    that have the Unicode numeric value property, e.g. U+2155,
    VULGAR FRACTION ONE FIFTH.
-   
+
 .. method:: unicode.isdecimal()
 
    Return ``True`` if there are only decimal characters in S, ``False``
@@ -1867,7 +1896,7 @@
       Return the item of *d* with key *key*.  Raises a :exc:`KeyError` if *key*
       is not in the map.
 
-      .. versionadded:: 2.5 
+      .. versionadded:: 2.5
          If a subclass of dict defines a method :meth:`__missing__`, if the key
          *key* is not present, the ``d[key]`` operation calls that method with
          the key *key* as argument.  The ``d[key]`` operation then returns or
@@ -2186,7 +2215,7 @@
    positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
    current position) and ``os.SEEK_END`` or ``2``  (seek relative to the file's
    end).  There is no return value.
-   
+
    For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
    ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/string.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/string.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/string.rst	Wed Jan 14 13:24:17 2009
@@ -126,7 +126,7 @@
       :meth:`format` is just a wrapper that calls :meth:`vformat`.
 
    .. method:: vformat(format_string, args, kwargs)
-   
+
       This function does the actual work of formatting.  It is exposed as a
       separate function for cases where you want to pass in a predefined
       dictionary of arguments, rather than unpacking and repacking the
@@ -139,12 +139,12 @@
    intended to be replaced by subclasses:
 
    .. method:: parse(format_string)
-   
+
       Loop over the format_string and return an iterable of tuples
       (*literal_text*, *field_name*, *format_spec*, *conversion*).  This is used
       by :meth:`vformat` to break the string in to either literal text, or
       replacement fields.
-      
+
       The values in the tuple conceptually represent a span of literal text
       followed by a single replacement field.  If there is no literal text
       (which can happen if two replacement fields occur consecutively), then
@@ -162,7 +162,7 @@
       *key* parameter to :meth:`get_value`.
 
    .. method:: get_value(key, args, kwargs)
-   
+
       Retrieve a given field value.  The *key* argument will be either an
       integer or a string.  If it is an integer, it represents the index of the
       positional argument in *args*; if it is a string, then it represents a
@@ -200,7 +200,7 @@
       method is provided so that subclasses can override it.
 
    .. method:: convert_field(value, conversion)
-   
+
       Converts the value (returned by :meth:`get_field`) given a conversion type
       (as in the tuple returned by the :meth:`parse` method.)  The default
       version understands 'r' (repr) and 's' (str) conversion types.
@@ -229,7 +229,7 @@
       element_index: `integer`
       conversion: "r" | "s"
       format_spec: <described in the next section>
-      
+
 In less formal terms, the replacement field starts with a *field_name*, which
 can either be a number (for a positional argument), or an identifier (for
 keyword arguments).  Following this is an optional *conversion* field, which is
@@ -249,7 +249,7 @@
    "My quest is {name}"             # References keyword argument 'name'
    "Weight in tons {0.weight}"      # 'weight' attribute of first positional arg
    "Units destroyed: {players[0]}"  # First element of keyword argument 'players'.
-   
+
 The *conversion* field causes a type coercion before formatting.  Normally, the
 job of formatting a value is done by the :meth:`__format__` method of the value
 itself.  However, in some cases it is desirable to force a type to be formatted
@@ -292,11 +292,11 @@
 Then the outer replacement field would be evaluated, producing::
 
    "noses     "
-   
+
 Which is substituted into the string, yielding::
-   
+
    "A man with two noses     "
-   
+
 (The extra space is because we specified a field width of 10, and because left
 alignment is the default for strings.)
 
@@ -328,7 +328,7 @@
    width: `integer`
    precision: `integer`
    type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
-   
+
 The *fill* character can be any character other than '}' (which signifies the
 end of the field).  The presence of a fill character is signaled by the *next*
 character, which must be one of the alignment options. If the second character
@@ -421,9 +421,9 @@
    +---------+----------------------------------------------------------+
    | None    | The same as ``'d'``.                                     |
    +---------+----------------------------------------------------------+
-                                                                         
+
 The available presentation types for floating point and decimal values are:
-                                                                         
+
    +---------+----------------------------------------------------------+
    | Type    | Meaning                                                  |
    +=========+==========================================================+

Modified: python/branches/tlee-ast-optimize/Doc/library/stringio.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/stringio.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/stringio.rst	Wed Jan 14 13:24:17 2009
@@ -52,7 +52,7 @@
    # 'First line.\nSecond line.\n'
    contents = output.getvalue()
 
-   # Close object and discard memory buffer -- 
+   # Close object and discard memory buffer --
    # .getvalue() will now raise an exception.
    output.close()
 
@@ -81,7 +81,7 @@
 
 Calling :func:`StringIO` with a Unicode string parameter populates
 the object with the buffer representation of the Unicode string, instead of
-encoding the string. 
+encoding the string.
 
 Another difference from the :mod:`StringIO` module is that calling
 :func:`StringIO` with a string parameter creates a read-only object. Unlike an
@@ -118,7 +118,7 @@
    # 'First line.\nSecond line.\n'
    contents = output.getvalue()
 
-   # Close object and discard memory buffer -- 
+   # Close object and discard memory buffer --
    # .getvalue() will now raise an exception.
    output.close()
 

Modified: python/branches/tlee-ast-optimize/Doc/library/subprocess.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/subprocess.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/subprocess.rst	Wed Jan 14 13:24:17 2009
@@ -73,13 +73,13 @@
    specified by the :envvar:`COMSPEC` environment variable.
 
    *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
-   standard output and standard error file handles, respectively.  Valid values are
-   ``PIPE``, an existing file descriptor (a positive integer), an existing file
-   object, and ``None``.  ``PIPE`` indicates that a new pipe to the child should be
-   created.  With ``None``, no redirection will occur; the child's file handles
-   will be inherited from the parent.  Additionally, *stderr* can be ``STDOUT``,
-   which indicates that the stderr data from the applications should be captured
-   into the same file handle as for stdout.
+   standard output and standard error file handles, respectively.  Valid values
+   are :data:`PIPE`, an existing file descriptor (a positive integer), an
+   existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
+   to the child should be created.  With ``None``, no redirection will occur;
+   the child's file handles will be inherited from the parent.  Additionally,
+   *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
+   applications should be captured into the same file handle as for stdout.
 
    If *preexec_fn* is set to a callable object, this object will be called in the
    child process just before the child is executed. (Unix only)
@@ -119,6 +119,20 @@
    of the main window and priority for the new process.  (Windows only)
 
 
+.. data:: PIPE
+
+   Special value that can be used as the *stdin*, *stdout* or *stderr* argument
+   to :class:`Popen` and indicates that a pipe to the standard stream should be
+   opened.
+
+
+.. data:: STDOUT
+
+   Special value that can be used as the *stderr* argument to :class:`Popen` and
+   indicates that standard error should go into the same handle as standard
+   output.
+
+
 Convenience Functions
 ^^^^^^^^^^^^^^^^^^^^^
 
@@ -149,6 +163,30 @@
    .. versionadded:: 2.5
 
 
+.. function:: check_output(*popenargs, **kwargs)
+
+   Run command with arguments and return its output as a byte string.
+
+   If the exit code was non-zero it raises a CalledProcessError.  The
+   CalledProcessError object will have the return code in the returncode
+   attribute and output in the output attribute.
+
+   The arguments are the same as for the Popen constructor.  Example:
+
+      >>> subprocess.check_output(["ls", "-l", "/dev/null"])
+      'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
+
+   The stdout argument is not allowed as it is used internally.
+   To capture standard error in the result, use stderr=subprocess.STDOUT.
+
+      >>> subprocess.check_output(
+              ["/bin/sh", "-c", "ls non_existant_file ; exit 0"],
+              stderr=subprocess.STDOUT)
+      'ls: non_existant_file: No such file or directory\n'
+
+   .. versionadded:: 2.7
+
+
 Exceptions
 ^^^^^^^^^^
 
@@ -207,7 +245,7 @@
    *input* argument should be a string to be sent to the child process, or
    ``None``, if no data should be sent to the child.
 
-   :meth:`communicate` returns a tuple ``(stdout, stderr)``.
+   :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
 
    Note that if you want to send data to the process's stdin, you need to create
    the Popen object with ``stdin=PIPE``.  Similarly, to get anything other than
@@ -261,20 +299,21 @@
 
 .. attribute:: Popen.stdin
 
-   If the *stdin* argument is ``PIPE``, this attribute is a file object that
-   provides input to the child process.  Otherwise, it is ``None``.
+   If the *stdin* argument was :data:`PIPE`, this attribute is a file object
+   that provides input to the child process.  Otherwise, it is ``None``.
 
 
 .. attribute:: Popen.stdout
 
-   If the *stdout* argument is ``PIPE``, this attribute is a file object that
-   provides output from the child process.  Otherwise, it is ``None``.
+   If the *stdout* argument was :data:`PIPE`, this attribute is a file object
+   that provides output from the child process.  Otherwise, it is ``None``.
 
 
 .. attribute:: Popen.stderr
 
-   If the *stderr* argument is ``PIPE``, this attribute is file object that
-   provides error output from the child process.  Otherwise, it is ``None``.
+   If the *stderr* argument was :data:`PIPE`, this attribute is a file object
+   that provides error output from the child process.  Otherwise, it is
+   ``None``.
 
 
 .. attribute:: Popen.pid
@@ -287,7 +326,7 @@
    The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
    by :meth:`communicate`).  A ``None`` value indicates that the process
    hasn't terminated yet.
-   
+
    A negative value ``-N`` indicates that the child was terminated by signal
    ``N`` (Unix only).
 
@@ -358,8 +397,8 @@
        print >>sys.stderr, "Execution failed:", e
 
 
-Replacing os.spawn\*
-^^^^^^^^^^^^^^^^^^^^
+Replacing the os.spawn family
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 P_NOWAIT example::
 
@@ -386,8 +425,8 @@
    Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
 
 
-Replacing os.popen\*
-^^^^^^^^^^^^^^^^^^^^
+Replacing os.popen, os.popen2, os.popen3
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 ::
 
@@ -430,8 +469,8 @@
    (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
 
 
-Replacing popen2.\*
-^^^^^^^^^^^^^^^^^^^
+Replacing functions from the popen2 module
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 .. note::
 
@@ -454,15 +493,15 @@
              stdin=PIPE, stdout=PIPE, close_fds=True)
    (child_stdout, child_stdin) = (p.stdout, p.stdin)
 
-The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen, except
-that:
+:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
+:class:`subprocess.Popen`, except that:
 
-* subprocess.Popen raises an exception if the execution fails
+* :class:`Popen` raises an exception if the execution fails.
 
 * the *capturestderr* argument is replaced with the *stderr* argument.
 
-* stdin=PIPE and stdout=PIPE must be specified.
+* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
 
 * popen2 closes all file descriptors by default, but you have to specify
-  close_fds=True with subprocess.Popen.
+  ``close_fds=True`` with :class:`Popen`.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/sunaudio.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/sunaudio.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/sunaudio.rst	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,7 @@
    :platform: SunOS
    :synopsis: Access to Sun audio hardware.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`sunaudiodev` module has been deprecated for removal in Python 3.0.
 
@@ -151,7 +151,7 @@
    :platform: SunOS
    :synopsis: Constants for use with sunaudiodev.
    :deprecated:
-   
+
 .. deprecated:: 2.6
    The :mod:`SUNAUDIODEV` module has been deprecated for removal in Python 3.0.
 

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	Wed Jan 14 13:24:17 2009
@@ -402,7 +402,7 @@
 
    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`. 
+   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.
@@ -566,6 +566,10 @@
    .. versionchanged:: 2.3
       Unicode strings are no longer ignored.
 
+   .. seealso::
+      Module :mod:`site` This describes how to use .pth files to extend
+      :data:`sys.path`.
+
 
 .. data:: platform
 
@@ -583,7 +587,6 @@
    Windows          ``'win32'``
    Windows/Cygwin   ``'cygwin'``
    Mac OS X         ``'darwin'``
-   Mac OS 9         ``'mac'``
    OS/2             ``'os2'``
    OS/2 EMX         ``'os2emx'``
    RiscOS           ``'riscos'``
@@ -731,7 +734,7 @@
 
    The events have the following meaning:
 
-   ``'call'`` 
+   ``'call'``
       A function is called (or some other code block entered).  The
       global trace function is called; *arg* is ``None``; the return value
       specifies the local trace function.
@@ -799,7 +802,7 @@
    prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts
    and (almost all of) its error messages go to ``stderr``.  ``stdout`` and
    ``stderr`` needn't be built-in file objects: any object is acceptable as long
-   as it has a :meth:`write` method that takes a string argument.  (Changing these 
+   as it has a :meth:`write` method that takes a string argument.  (Changing these
    objects doesn't affect the standard I/O streams of processes executed by
    :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
    the :mod:`os` module.)
@@ -869,10 +872,3 @@
    first three characters of :const:`version`.  It is provided in the :mod:`sys`
    module for informational purposes; modifying this value has no effect on the
    registry keys used by Python. Availability: Windows.
-
-
-.. seealso::
-
-   Module :mod:`site`
-      This describes how to use .pth files to extend ``sys.path``.
-

Modified: python/branches/tlee-ast-optimize/Doc/library/tempfile.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/tempfile.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/tempfile.rst	Wed Jan 14 13:24:17 2009
@@ -164,11 +164,11 @@
 
    .. warning::
 
-      Use of this function may introduce a security hole in your program.
-      By the time you get around to doing anything with the file name it
-      returns, someone else may have beaten you to the punch.
-      :func:`mktemp` usage can be replaced easily with
-      :func:`NamedTemporaryFile`, passing it the  `delete=False` parameter::
+      Use of this function may introduce a security hole in your program.  By
+      the time you get around to doing anything with the file name it returns,
+      someone else may have beaten you to the punch.  :func:`mktemp` usage can
+      be replaced easily with :func:`NamedTemporaryFile`, passing it the
+      ``delete=False`` parameter::
 
          >>> f = NamedTemporaryFile(delete=False)
          >>> f

Modified: python/branches/tlee-ast-optimize/Doc/library/tk.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/tk.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/tk.rst	Wed Jan 14 13:24:17 2009
@@ -22,15 +22,15 @@
 mechanism which allows Python and Tcl to interact.
 
 :mod:`Tkinter`'s chief virtues are that it is fast, and that it usually comes
-bundled with Python. Although its standard documentation is weak, good 
-material is available, which includes: references, tutorials, a book and 
-others. :mod:`Tkinter` is also famous for having an outdated look and feel, 
-which has been vastly improved in Tk 8.5. Nevertheless, there are many other 
-GUI libraries that you could be interested in. For more information about 
+bundled with Python. Although its standard documentation is weak, good
+material is available, which includes: references, tutorials, a book and
+others. :mod:`Tkinter` is also famous for having an outdated look and feel,
+which has been vastly improved in Tk 8.5. Nevertheless, there are many other
+GUI libraries that you could be interested in. For more information about
 alternatives, see the :ref:`other-gui-packages` section.
 
 .. toctree::
-   
+
    tkinter.rst
    tix.rst
    scrolledtext.rst

Modified: python/branches/tlee-ast-optimize/Doc/library/tkinter.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/tkinter.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/tkinter.rst	Wed Jan 14 13:24:17 2009
@@ -284,7 +284,7 @@
 someOptions), in C++, you would express this as fred.someAction(someOptions),
 and in Tk, you say::
 
-   .fred someAction someOptions 
+   .fred someAction someOptions
 
 Note that the object name, ``.fred``, starts with a dot.
 
@@ -490,7 +490,7 @@
 For more extensive information on the packer and the options that it can take,
 see the man pages and page 183 of John Ousterhout's book.
 
-anchor 
+anchor
    Anchor type.  Denotes where the packer is to place each slave in its parcel.
 
 expand
@@ -720,7 +720,7 @@
 they are denoted in Tk, which can be useful when referring to the Tk man pages.
 ::
 
-   Tk      Tkinter Event Field             Tk      Tkinter Event Field 
+   Tk      Tkinter Event Field             Tk      Tkinter Event Field
    --      -------------------             --      -------------------
    %f      focus                           %A      char
    %h      height                          %E      send_event

Modified: python/branches/tlee-ast-optimize/Doc/library/trace.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/trace.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/trace.rst	Wed Jan 14 13:24:17 2009
@@ -65,13 +65,13 @@
 
 :option:`--ignore-module`
    Accepts comma separated list of module names. Ignore each of the named
-   module and its submodules (if it is a package).  May be given 
+   module and its submodules (if it is a package).  May be given
    multiple times.
 
 :option:`--ignore-dir`
    Ignore all modules and packages in the named directory and subdirectories
    (multiple directories can be joined by os.pathsep).  May be given multiple
-   times. 
+   times.
 
 
 .. _trace-api:

Modified: python/branches/tlee-ast-optimize/Doc/library/traceback.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/traceback.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/traceback.rst	Wed Jan 14 13:24:17 2009
@@ -169,10 +169,10 @@
 
    def lumberjack():
        bright_side_of_death()
-   
+
    def bright_side_of_death():
        return tuple()[0]
-   
+
    try:
        lumberjack()
    except:
@@ -251,12 +251,12 @@
    >>> import traceback
    >>> def another_function():
    ...     lumberstack()
-   ... 
+   ...
    >>> def lumberstack():
    ...     traceback.print_stack()
    ...     print repr(traceback.extract_stack())
    ...     print repr(traceback.format_stack())
-   ... 
+   ...
    >>> another_function()
      File "<doctest>", line 10, in <module>
        another_function()

Modified: python/branches/tlee-ast-optimize/Doc/library/turtle.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/turtle.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/turtle.rst	Wed Jan 14 13:24:17 2009
@@ -325,8 +325,7 @@
 
    :param y: a number (integer or float)
 
-   Set the turtle's first coordinate to *y*, leave second coordinate
-   unchanged.
+   Set the turtle's second coordinate to *y*, leave first coordinate unchanged.
 
    >>> turtle.position()
    (0.00, 40.00)
@@ -1587,7 +1586,7 @@
 
    Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.
 
-   
+
 .. class:: ScrolledCavas(master)
 
    :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
@@ -1612,13 +1611,13 @@
    "compound"  ``None`` (a compund shape has to be constructed using the
                :meth:`addcomponent` method)
    =========== ===========
-                
+
    .. method:: addcomponent(poly, fill, outline=None)
 
       :param poly: a polygon, i.e. a tuple of pairs of numbers
       :param fill: a color the *poly* will be filled with
       :param outline: a color for the poly's outline (if given)
-     
+
       Example:
 
       >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
@@ -1662,31 +1661,31 @@
 
      >>> help(Screen.bgcolor)
      Help on method bgcolor in module turtle:
-    
+
      bgcolor(self, *args) unbound turtle.Screen method
          Set or return backgroundcolor of the TurtleScreen.
-    
+
          Arguments (if given): a color string or three numbers
          in the range 0..colormode or a 3-tuple of such numbers.
-    
-    
+
+
            >>> screen.bgcolor("orange")
            >>> screen.bgcolor()
            "orange"
            >>> screen.bgcolor(0.5,0,0.5)
            >>> screen.bgcolor()
            "#800080"
-    
+
      >>> help(Turtle.penup)
      Help on method penup in module turtle:
-    
+
      penup(self) unbound turtle.Turtle method
          Pull the pen up -- no drawing when moving.
-    
+
          Aliases: penup | pu | up
-    
+
          No argument
-    
+
          >>> turtle.penup()
 
 - The docstrings of the functions which are derived from methods have a modified
@@ -1694,32 +1693,32 @@
 
      >>> help(bgcolor)
      Help on function bgcolor in module turtle:
-    
+
      bgcolor(*args)
          Set or return backgroundcolor of the TurtleScreen.
-    
+
          Arguments (if given): a color string or three numbers
          in the range 0..colormode or a 3-tuple of such numbers.
-    
+
          Example::
-    
+
            >>> bgcolor("orange")
            >>> bgcolor()
            "orange"
            >>> bgcolor(0.5,0,0.5)
            >>> bgcolor()
            "#800080"
-    
+
      >>> help(penup)
      Help on function penup in module turtle:
-    
+
      penup()
          Pull the pen up -- no drawing when moving.
-    
+
          Aliases: penup | pu | up
-    
+
          No argument
-    
+
          Example:
          >>> penup()
 

Modified: python/branches/tlee-ast-optimize/Doc/library/undoc.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/undoc.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/undoc.rst	Wed Jan 14 13:24:17 2009
@@ -21,7 +21,7 @@
 
 :mod:`ihooks`
    --- Import hook support (for :mod:`rexec`; may become obsolete).
-   
+
    .. warning:: The :mod:`ihooks` module has been removed in Python 3.0.
 
 
@@ -54,7 +54,7 @@
 :mod:`linuxaudiodev`
    --- Play audio data on the Linux audio device.  Replaced in Python 2.3 by the
    :mod:`ossaudiodev` module.
-   
+
    .. warning:: The :mod:`linuxaudiodev` module has been removed in Python 3.0.
 
 :mod:`sunaudio`
@@ -240,7 +240,7 @@
 
 :mod:`timing`
    --- Measure time intervals to high resolution (use :func:`time.clock` instead).
-   
+
    .. warning:: The :mod:`timing` module has been removed in Python 3.0.
 
 
@@ -255,6 +255,6 @@
 
 :mod:`sv`
    --- Interface to the "simple video" board on SGI Indigo (obsolete hardware).
-   
+
    .. warning:: The :mod:`sv` module has been removed in Python 3.0.
 

Modified: python/branches/tlee-ast-optimize/Doc/library/unicodedata.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/unicodedata.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/unicodedata.rst	Wed Jan 14 13:24:17 2009
@@ -164,7 +164,7 @@
      File "<stdin>", line 1, in ?
    ValueError: not a decimal
    >>> unicodedata.category(u'A')  # 'L'etter, 'u'ppercase
-   'Lu'   
+   'Lu'
    >>> unicodedata.bidirectional(u'\u0660') # 'A'rabic, 'N'umber
    'AN'
 

Modified: python/branches/tlee-ast-optimize/Doc/library/unittest.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/unittest.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/unittest.rst	Wed Jan 14 13:24:17 2009
@@ -595,7 +595,7 @@
             TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
 
    Test that *first* and *second* are approximately equal by computing the
-   difference, rounding to the given number of decimal *places* (default 7), 
+   difference, rounding to the given number of decimal *places* (default 7),
    and comparing to zero.
    Note that comparing a given number of decimal places is not the same as
    comparing a given number of significant digits. If the values do not compare
@@ -606,15 +606,15 @@
             TestCase.failIfAlmostEqual(first, second[, places[, msg]])
 
    Test that *first* and *second* are not approximately equal by computing the
-   difference, rounding to the given number of decimal *places* (default 7), 
+   difference, rounding to the given number of decimal *places* (default 7),
    and comparing to zero.
    Note that comparing a given number of decimal places is not the same as
    comparing a given number of significant digits. If the values do not compare
    equal, the test will fail with the explanation given by *msg*, or :const:`None`.
 
 
-.. method:: TestCase.assertRaises(exception, callable, ...)
-            TestCase.failUnlessRaises(exception, callable, ...)
+.. method:: TestCase.assertRaises(exception[, callable, ...])
+            TestCase.failUnlessRaises(exception[, callable, ...])
 
    Test that an exception is raised when *callable* is called with any positional
    or keyword arguments that are also passed to :meth:`assertRaises`.  The test
@@ -622,6 +622,13 @@
    fails if no exception is raised.  To catch any of a group of exceptions, a tuple
    containing the exception classes may be passed as *exception*.
 
+   .. versionchanged:: 2.7
+
+      If *callable* is omitted or None, returns a context manager so that the code
+      under test can be written inline rather than as a function::
+
+        with self.failUnlessRaises(some_error_class):
+            do_something()
 
 .. method:: TestCase.failIf(expr[, msg])
             TestCase.assertFalse(expr[, msg])

Modified: python/branches/tlee-ast-optimize/Doc/library/urllib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/urllib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/urllib.rst	Wed Jan 14 13:24:17 2009
@@ -123,7 +123,7 @@
    .. versionchanged:: 2.6
       Added :meth:`getcode` to returned object and support for the
       :envvar:`no_proxy` environment variable.
-      
+
    .. deprecated:: 2.6
       The :func:`urlopen` function has been removed in Python 3.0 in favor
       of :func:`urllib2.urlopen`.

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	Wed Jan 14 13:24:17 2009
@@ -109,7 +109,7 @@
 
    .. attribute:: code
 
-      An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_. 
+      An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_.
       This numeric value corresponds to a value found in the dictionary of
       codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`.
 
@@ -391,23 +391,23 @@
 
 .. method:: OpenerDirector.add_handler(handler)
 
-   *handler* should be an instance of :class:`BaseHandler`.  The following methods
-   are searched, and added to the possible chains (note that HTTP errors are a
-   special case).
+   *handler* should be an instance of :class:`BaseHandler`.  The following
+   methods are searched, and added to the possible chains (note that HTTP errors
+   are a special case).
 
-   * :meth:`protocol_open` --- signal that the handler knows how to open *protocol*
-     URLs.
+   * :samp:`{protocol}_open` --- signal that the handler knows how to open
+     *protocol* URLs.
 
-   * :meth:`http_error_type` --- signal that the handler knows how to handle HTTP
-     errors with HTTP error code *type*.
+   * :samp:`http_error_{type}` --- signal that the handler knows how to handle
+     HTTP errors with HTTP error code *type*.
 
-   * :meth:`protocol_error` --- signal that the handler knows how to handle errors
-     from (non-\ ``http``) *protocol*.
+   * :samp:`{protocol}_error` --- signal that the handler knows how to handle
+     errors from (non-\ ``http``) *protocol*.
 
-   * :meth:`protocol_request` --- signal that the handler knows how to pre-process
-     *protocol* requests.
+   * :samp:`{protocol}_request` --- signal that the handler knows how to
+     pre-process *protocol* requests.
 
-   * :meth:`protocol_response` --- signal that the handler knows how to
+   * :samp:`{protocol}_response` --- signal that the handler knows how to
      post-process *protocol* responses.
 
 
@@ -441,24 +441,24 @@
 The order in which these methods are called within each stage is determined by
 sorting the handler instances.
 
-#. Every handler with a method named like :meth:`protocol_request` has that
+#. Every handler with a method named like :samp:`{protocol}_request` has that
    method called to pre-process the request.
 
-#. Handlers with a method named like :meth:`protocol_open` are called to handle
+#. Handlers with a method named like :samp:`{protocol}_open` are called to handle
    the request. This stage ends when a handler either returns a non-\ :const:`None`
    value (ie. a response), or raises an exception (usually :exc:`URLError`).
    Exceptions are allowed to propagate.
 
    In fact, the above algorithm is first tried for methods named
-   :meth:`default_open`.  If all such methods return :const:`None`, the algorithm
-   is repeated for methods named like :meth:`protocol_open`.  If all such methods
-   return :const:`None`, the algorithm is repeated for methods named
-   :meth:`unknown_open`.
+   :meth:`default_open`.  If all such methods return :const:`None`, the
+   algorithm is repeated for methods named like :samp:`{protocol}_open`.  If all
+   such methods return :const:`None`, the algorithm is repeated for methods
+   named :meth:`unknown_open`.
 
    Note that the implementation of these methods may involve calls of the parent
    :class:`OpenerDirector` instance's :meth:`.open` and :meth:`.error` methods.
 
-#. Every handler with a method named like :meth:`protocol_response` has that
+#. Every handler with a method named like :samp:`{protocol}_response` has that
    method called to post-process the response.
 
 
@@ -514,8 +514,10 @@
 .. method:: BaseHandler.protocol_open(req)
    :noindex:
 
+   ("protocol" is to be replaced by the protocol name.)
+
    This method is *not* defined in :class:`BaseHandler`, but subclasses should
-   define it if they want to handle URLs with the given protocol.
+   define it if they want to handle URLs with the given *protocol*.
 
    This method, if defined, will be called by the parent :class:`OpenerDirector`.
    Return values should be the same as for  :meth:`default_open`.
@@ -563,8 +565,10 @@
 .. method:: BaseHandler.protocol_request(req)
    :noindex:
 
+   ("protocol" is to be replaced by the protocol name.)
+
    This method is *not* defined in :class:`BaseHandler`, but subclasses should
-   define it if they want to pre-process requests of the given protocol.
+   define it if they want to pre-process requests of the given *protocol*.
 
    This method, if defined, will be called by the parent :class:`OpenerDirector`.
    *req* will be a :class:`Request` object. The return value should be a
@@ -574,8 +578,10 @@
 .. method:: BaseHandler.protocol_response(req, response)
    :noindex:
 
+   ("protocol" is to be replaced by the protocol name.)
+
    This method is *not* defined in :class:`BaseHandler`, but subclasses should
-   define it if they want to post-process responses of the given protocol.
+   define it if they want to post-process responses of the given *protocol*.
 
    This method, if defined, will be called by the parent :class:`OpenerDirector`.
    *req* will be a :class:`Request` object. *response* will be an object
@@ -660,7 +666,9 @@
 .. method:: ProxyHandler.protocol_open(request)
    :noindex:
 
-   The :class:`ProxyHandler` will have a method :meth:`protocol_open` for every
+   ("protocol" is to be replaced by the protocol name.)
+
+   The :class:`ProxyHandler` will have a method :samp:`{protocol}_open` for every
    *protocol* which has a proxy in the *proxies* dictionary given in the
    constructor.  The method will modify requests to go through the proxy, by
    calling ``request.set_proxy()``, and call the next handler in the chain to
@@ -865,9 +873,10 @@
    For 200 error codes, the response object is returned immediately.
 
    For non-200 error codes, this simply passes the job on to the
-   :meth:`protocol_error_code` handler methods, via :meth:`OpenerDirector.error`.
-   Eventually, :class:`urllib2.HTTPDefaultErrorHandler` will raise an
-   :exc:`HTTPError` if no other handler handles the error.
+   :samp:`{protocol}_error_code` handler methods, via
+   :meth:`OpenerDirector.error`.  Eventually,
+   :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no
+   other handler handles the error.
 
 
 .. _urllib2-examples:

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	Wed Jan 14 13:24:17 2009
@@ -290,7 +290,7 @@
 
    .. versionadded:: 2.5
 
-The following classes provide the implementations of the parse results::
+The following classes provide the implementations of the parse results:
 
 
 .. class:: BaseResult

Modified: python/branches/tlee-ast-optimize/Doc/library/warnings.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/warnings.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/warnings.rst	Wed Jan 14 13:24:17 2009
@@ -274,7 +274,7 @@
 
 .. function:: warnpy3k(message[, category[, stacklevel]])
 
-   Issue a warning related to Python 3.x deprecation. Warnings are only shown 
+   Issue a warning related to Python 3.x deprecation. Warnings are only shown
    when Python is started with the -3 option. Like :func:`warn` *message* must
    be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
    is using :exc:`DeprecationWarning` as default warning class.
@@ -288,7 +288,7 @@
    this function with an alternative implementation by assigning to
    ``warnings.showwarning``.
    *line* is a line of source code to be included in the warning
-   message; if *line* is not supplied, :func:`showwarning` will 
+   message; if *line* is not supplied, :func:`showwarning` will
    try to read the line specified by *filename* and *lineno*.
 
    .. versionchanged:: 2.6
@@ -299,8 +299,8 @@
 .. function:: formatwarning(message, category, filename, lineno[, line])
 
    Format a warning the standard way.  This returns a string  which may contain
-   embedded newlines and ends in a newline.  *line* is 
-   a line of source code to be included in the warning message; if *line* is not supplied, 
+   embedded newlines and ends in a newline.  *line* is
+   a line of source code to be included in the warning message; if *line* is not supplied,
    :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
 
    .. versionchanged:: 2.6

Modified: python/branches/tlee-ast-optimize/Doc/library/webbrowser.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/webbrowser.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/webbrowser.rst	Wed Jan 14 13:24:17 2009
@@ -160,7 +160,7 @@
 
    url = 'http://www.python.org'
 
-   # Open URL in a new tab, if a browser window is already open. 
+   # Open URL in a new tab, if a browser window is already open.
    webbrowser.open_new_tab(url + '/doc')
 
    # Open URL in new window, raising the window if possible.
@@ -172,7 +172,7 @@
 Browser Controller Objects
 --------------------------
 
-Browser controllers provide two methods which parallel two of the module-level
+Browser controllers provide these methods which parallel two of the module-level
 convenience functions:
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/winsound.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/winsound.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/winsound.rst	Wed Jan 14 13:24:17 2009
@@ -30,8 +30,9 @@
    Call the underlying :cfunc:`PlaySound` function from the Platform API.  The
    *sound* parameter may be a filename, audio data as a string, or ``None``.  Its
    interpretation depends on the value of *flags*, which can be a bitwise ORed
-   combination of the constants described below.  If the system indicates an error,
-   :exc:`RuntimeError` is raised.
+   combination of the constants described below. If the *sound* parameter is
+   ``None``, any currently playing waveform sound is stopped. If the system
+   indicates an error, :exc:`RuntimeError` is raised.
 
 
 .. function:: MessageBeep([type=MB_OK])
@@ -108,6 +109,10 @@
 
    Stop playing all instances of the specified sound.
 
+   .. note::
+
+      This flag is not supported on modern Windows platforms.
+
 
 .. data:: SND_ASYNC
 

Modified: python/branches/tlee-ast-optimize/Doc/library/wsgiref.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/wsgiref.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/wsgiref.rst	Wed Jan 14 13:24:17 2009
@@ -170,7 +170,7 @@
       filelike = StringIO("This is an example file-like object"*10)
       wrapper = FileWrapper(filelike, blksize=5)
 
-      for chunk in wrapper: 
+      for chunk in wrapper:
           print chunk
 
 
@@ -415,7 +415,7 @@
       from wsgiref.validate import validator
       from wsgiref.simple_server import make_server
 
-      # Our callable object which is intentionally not compliant to the 
+      # Our callable object which is intentionally not compliant to the
       # standard, so the validator is going to break
       def simple_app(environ, start_response):
           status = '200 OK' # HTTP Status

Modified: python/branches/tlee-ast-optimize/Doc/library/xml.etree.elementtree.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/xml.etree.elementtree.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/xml.etree.elementtree.rst	Wed Jan 14 13:24:17 2009
@@ -34,7 +34,7 @@
 A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
 
 See http://effbot.org/zone/element-index.htm for tutorials and links to other
-docs. Fredrik Lundh's page is also the location of the development version of the 
+docs. Fredrik Lundh's page is also the location of the development version of the
 xml.etree.ElementTree.
 
 .. _elementtree-functions:
@@ -94,6 +94,16 @@
    *events* is a list of events to report back.  If omitted, only "end" events are
    reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs.
 
+   .. note::
+
+      :func:`iterparse` only guarantees that it has seen the ">"
+      character of a starting tag when it emits a "start" event, so the
+      attributes are defined, but the contents of the text and tail attributes
+      are undefined at that point.  The same applies to the element children;
+      they may or may not be present.
+
+      If you need a fully populated element, look for "end" events instead.
+
 
 .. function:: parse(source[, parser])
 
@@ -369,7 +379,7 @@
             <title>Example page</title>
         </head>
         <body>
-            <p>Moved to <a href="http://example.org/">example.org</a> 
+            <p>Moved to <a href="http://example.org/">example.org</a>
             or <a href="http://example.com/">example.com</a>.</p>
         </body>
     </html>
@@ -476,9 +486,9 @@
 
 :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method
 for each opening tag, its :meth:`end` method for each closing tag,
-and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close` 
-calls *target*\'s method :meth:`close`. 
-:class:`XMLTreeBuilder` can be used not only for building a tree structure. 
+and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close`
+calls *target*\'s method :meth:`close`.
+:class:`XMLTreeBuilder` can be used not only for building a tree structure.
 This is an example of counting the maximum depth of an XML file::
 
     >>> from xml.etree.ElementTree import XMLTreeBuilder
@@ -486,16 +496,16 @@
     ...     maxDepth = 0
     ...     depth = 0
     ...     def start(self, tag, attrib):   # Called for each opening tag.
-    ...         self.depth += 1 
+    ...         self.depth += 1
     ...         if self.depth > self.maxDepth:
     ...             self.maxDepth = self.depth
     ...     def end(self, tag):             # Called for each closing tag.
     ...         self.depth -= 1
-    ...     def data(self, data):   
+    ...     def data(self, data):
     ...         pass            # We do not need to do anything with data.
     ...     def close(self):    # Called when all data has been parsed.
     ...         return self.maxDepth
-    ... 
+    ...
     >>> target = MaxDepth()
     >>> parser = XMLTreeBuilder(target=target)
     >>> exampleXml = """

Modified: python/branches/tlee-ast-optimize/Doc/library/xmlrpclib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/xmlrpclib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/xmlrpclib.rst	Wed Jan 14 13:24:17 2009
@@ -560,8 +560,8 @@
            self.proxy = proxy
        def make_connection(self, host):
            self.realhost = host
-   	h = httplib.HTTP(self.proxy)
-   	return h
+           h = httplib.HTTP(self.proxy)
+           return h
        def send_request(self, connection, handler, request_body):
            connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
        def send_host(self, connection, host):

Modified: python/branches/tlee-ast-optimize/Doc/library/zipfile.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/zipfile.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/zipfile.rst	Wed Jan 14 13:24:17 2009
@@ -66,9 +66,11 @@
 .. function:: is_zipfile(filename)
 
    Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
-   otherwise returns ``False``.  This module does not currently handle ZIP files
-   which have appended comments.
+   otherwise returns ``False``.  *filename* may be a file or file-like object too.
+   This module does not currently handle ZIP files which have appended comments.
 
+   .. versionchanged:: 2.7
+      Support for file and file-like objects.
 
 .. data:: ZIP_STORED
 
@@ -200,7 +202,7 @@
 
 .. method:: ZipFile.extractall([path[, members[, pwd]]])
 
-   Extract all members from the archive to the current working directory.  *path* 
+   Extract all members from the archive to the current working directory.  *path*
    specifies a different directory to extract to.  *members* is optional and must
    be a subset of the list returned by :meth:`namelist`.  *pwd* is the password
    used for encrypted files.
@@ -280,9 +282,9 @@
 
    .. note::
 
-      When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter, 
-      the compression method used will be that specified in the *compress_type* 
-      member of the given :class:`ZipInfo` instance.  By default, the 
+      When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter,
+      the compression method used will be that specified in the *compress_type*
+      member of the given :class:`ZipInfo` instance.  By default, the
       :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
 
 The following data attributes are also available:
@@ -296,9 +298,9 @@
 
 .. attribute:: ZipFile.comment
 
-   The comment text associated with the ZIP file.  If assigning a comment to a 
-   :class:`ZipFile` instance created with mode 'a' or 'w', this should be a 
-   string no longer than 65535 bytes.  Comments longer than this will be 
+   The comment text associated with the ZIP file.  If assigning a comment to a
+   :class:`ZipFile` instance created with mode 'a' or 'w', this should be a
+   string no longer than 65535 bytes.  Comments longer than this will be
    truncated in the written archive when :meth:`ZipFile.close` is called.
 
 .. _pyzipfile-objects:
@@ -327,10 +329,10 @@
    internal use only.  The :meth:`writepy` method makes archives with file names
    like this::
 
-      string.pyc                                # Top level name 
-      test/__init__.pyc                         # Package directory 
+      string.pyc                                # Top level name
+      test/__init__.pyc                         # Package directory
       test/test_support.pyc                          # Module test.test_support
-      test/bogus/__init__.pyc                   # Subpackage directory 
+      test/bogus/__init__.pyc                   # Subpackage directory
       test/bogus/myfile.pyc                     # Submodule test.bogus.myfile
 
 

Modified: python/branches/tlee-ast-optimize/Doc/library/zipimport.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/zipimport.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/zipimport.rst	Wed Jan 14 13:24:17 2009
@@ -148,7 +148,7 @@
     --------                   -------
         8467                   1 file
    $ ./python
-   Python 2.3 (#1, Aug 1 2003, 19:54:32) 
+   Python 2.3 (#1, Aug 1 2003, 19:54:32)
    >>> import sys
    >>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
    >>> import jwzthreading

Modified: python/branches/tlee-ast-optimize/Doc/library/zlib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/library/zlib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/library/zlib.rst	Wed Jan 14 13:24:17 2009
@@ -31,22 +31,34 @@
    Exception raised on compression and decompression errors.
 
 
-.. function:: adler32(string[, value])
+.. function:: adler32(data[, value])
 
-   Computes a Adler-32 checksum of *string*.  (An Adler-32 checksum is almost as
+   Computes a Adler-32 checksum of *data*.  (An Adler-32 checksum is almost as
    reliable as a CRC32 but can be computed much more quickly.)  If *value* is
    present, it is used as the starting value of the checksum; otherwise, a fixed
    default value is used.  This allows computing a running checksum over the
-   concatenation of several input strings.  The algorithm is not cryptographically
+   concatenation of several inputs.  The algorithm is not cryptographically
    strong, and should not be used for authentication or digital signatures.  Since
    the algorithm is designed for use as a checksum algorithm, it is not suitable
    for use as a general hash algorithm.
 
    This function always returns an integer object.
 
-   .. versionchanged:: 2.6
-     For consistent cross-platform behavior we always return a signed integer.
-     ie: Results in the (2**31)...(2**32-1) range will be negative.
+.. note::
+   To generate the same numeric value across all Python versions and
+   platforms use adler32(data) & 0xffffffff.  If you are only using
+   the checksum in packed binary format this is not necessary as the
+   return value will have the correct 32bit binary representation
+   regardless of sign.
+
+.. versionchanged:: 2.6
+   The return value will always be in the range [-2**31, 2**31-1]
+   regardless of platform.  In older versions the value would be
+   signed on some platforms and unsigned on others.
+
+.. versionchanged:: 3.0
+   The return value will always be unsigned and in the range [0, 2**32-1]
+   regardless of platform.
 
 
 .. function:: compress(string[, level])
@@ -66,25 +78,37 @@
    ``9`` is slowest and produces the most.  The default value is ``6``.
 
 
-.. function:: crc32(string[, value])
+.. function:: crc32(data[, value])
 
    .. index::
       single: Cyclic Redundancy Check
       single: checksum; Cyclic Redundancy Check
 
-   Computes a CRC (Cyclic Redundancy Check)  checksum of *string*. If *value* is
+   Computes a CRC (Cyclic Redundancy Check)  checksum of *data*. If *value* is
    present, it is used as the starting value of the checksum; otherwise, a fixed
    default value is used.  This allows computing a running checksum over the
-   concatenation of several input strings.  The algorithm is not cryptographically
+   concatenation of several inputs.  The algorithm is not cryptographically
    strong, and should not be used for authentication or digital signatures.  Since
    the algorithm is designed for use as a checksum algorithm, it is not suitable
    for use as a general hash algorithm.
 
    This function always returns an integer object.
 
-   .. versionchanged:: 2.6
-     For consistent cross-platform behavior we always return a signed integer.
-     ie: Results in the (2**31)...(2**32-1) range will be negative.
+.. note::
+   To generate the same numeric value across all Python versions and
+   platforms use crc32(data) & 0xffffffff.  If you are only using
+   the checksum in packed binary format this is not necessary as the
+   return value will have the correct 32bit binary representation
+   regardless of sign.
+
+.. versionchanged:: 2.6
+   The return value will always be in the range [-2**31, 2**31-1]
+   regardless of platform.  In older versions the value would be
+   signed on some platforms and unsigned on others.
+
+.. versionchanged:: 3.0
+   The return value will always be unsigned and in the range [0, 2**32-1]
+   regardless of platform.
 
 
 .. function:: decompress(string[, wbits[, bufsize]])

Modified: python/branches/tlee-ast-optimize/Doc/license.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/license.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/license.rst	Wed Jan 14 13:24:17 2009
@@ -88,8 +88,14 @@
 +----------------+--------------+-----------+------------+-----------------+
 | 2.5.1          | 2.5          | 2007      | PSF        | yes             |
 +----------------+--------------+-----------+------------+-----------------+
+| 2.5.2          | 2.5.1        | 2008      | PSF        | yes             |
++----------------+--------------+-----------+------------+-----------------+
+| 2.5.3          | 2.5.2        | 2008      | PSF        | yes             |
++----------------+--------------+-----------+------------+-----------------+
 | 2.6            | 2.5          | 2008      | PSF        | yes             |
 +----------------+--------------+-----------+------------+-----------------+
+| 2.6.1          | 2.6          | 2008      | PSF        | yes             |
++----------------+--------------+-----------+------------+-----------------+
 
 .. note::
 
@@ -118,7 +124,7 @@
    analyze, test, perform and/or display publicly, prepare derivative works,
    distribute, and otherwise use Python |release| alone or in any derivative
    version, provided, however, that PSF's License Agreement and PSF's notice of
-   copyright, i.e., "Copyright © 2001-2008 Python Software Foundation; All Rights
+   copyright, i.e., "Copyright © 2001-2009 Python Software Foundation; All Rights
    Reserved" are retained in Python |release| alone or in any derivative version
    prepared by Licensee.
 
@@ -380,8 +386,8 @@
 
 The source for the :mod:`fpectl` module includes the following notice::
 
-     ---------------------------------------------------------------------  
-    /                       Copyright (c) 1996.                           \ 
+     ---------------------------------------------------------------------
+    /                       Copyright (c) 1996.                           \
    |          The Regents of the University of California.                 |
    |                        All rights reserved.                           |
    |                                                                       |
@@ -413,7 +419,7 @@
    |   opinions  of authors expressed herein do not necessarily state or   |
    |   reflect those of the United States Government or  the  University   |
    |   of  California,  and shall not be used for advertising or product   |
-    \  endorsement purposes.                                              / 
+    \  endorsement purposes.                                              /
      ---------------------------------------------------------------------
 
 
@@ -447,7 +453,7 @@
 
      This code implements the MD5 Algorithm defined in RFC 1321, whose
      text is available at
-   	http://www.ietf.org/rfc/rfc1321.txt
+           http://www.ietf.org/rfc/rfc1321.txt
      The code is derived from the text of the RFC, including the test suite
      (section A.5) but excluding the rest of Appendix A.  It does not include
      any code or documentation that is identified in the RFC as being
@@ -458,12 +464,12 @@
      that follows (in reverse chronological order):
 
      2002-04-13 lpd Removed support for non-ANSI compilers; removed
-   	references to Ghostscript; clarified derivation from RFC 1321;
-   	now handles byte order either statically or dynamically.
+           references to Ghostscript; clarified derivation from RFC 1321;
+           now handles byte order either statically or dynamically.
      1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
      1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
-   	added conditionalization for C++ compilation from Martin
-   	Purschke <purschke at bnl.gov>.
+           added conditionalization for C++ compilation from Martin
+           Purschke <purschke at bnl.gov>.
      1999-05-03 lpd Original version.
 
 

Modified: python/branches/tlee-ast-optimize/Doc/make.bat
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/make.bat	(original)
+++ python/branches/tlee-ast-optimize/Doc/make.bat	Wed Jan 14 13:24:17 2009
@@ -8,34 +8,41 @@
 if "%1" EQU "" goto help
 if "%1" EQU "html" goto build
 if "%1" EQU "htmlhelp" goto build
-if "%1" EQU "web" goto build
-if "%1" EQU "webrun" goto webrun
+if "%1" EQU "latex" goto build
+if "%1" EQU "text" goto build
+if "%1" EQU "suspicious" goto build
+if "%1" EQU "linkcheck" goto build
+if "%1" EQU "changes" goto build
 if "%1" EQU "checkout" goto checkout
 if "%1" EQU "update" goto update
 
 :help
+set this=%~n0
 echo HELP
 echo.
-echo builddoc checkout
-echo builddoc update
-echo builddoc html
-echo builddoc htmlhelp
-echo builddoc web
-echo builddoc webrun
+echo %this% checkout
+echo %this% update
+echo %this% html
+echo %this% htmlhelp
+echo %this% latex
+echo %this% text
+echo %this% suspicious
+echo %this% linkcheck
+echo %this% changes
 echo.
 goto end
 
 :checkout
 svn co %SVNROOT%/doctools/trunk/sphinx tools/sphinx
-svn co %SVNROOT%/external/docutils-0.4/docutils tools/docutils
-svn co %SVNROOT%/external/Jinja-1.1/jinja tools/jinja
-svn co %SVNROOT%/external/Pygments-0.9/pygments tools/pygments
+svn co %SVNROOT%/external/docutils-0.5/docutils tools/docutils
+svn co %SVNROOT%/external/Jinja-2.1.1/jinja2 tools/jinja2
+svn co %SVNROOT%/external/Pygments-0.11.1/pygments tools/pygments
 goto end
 
 :update
 svn update tools/sphinx
 svn update tools/docutils
-svn update tools/jinja
+svn update tools/jinja2
 svn update tools/pygments
 goto end
 
@@ -43,13 +50,8 @@
 if not exist build mkdir build
 if not exist build\%1 mkdir build\%1
 if not exist build\doctrees mkdir build\doctrees
-cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%1
+cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%*
 if "%1" EQU "htmlhelp" "%HTMLHELP%" build\htmlhelp\pydoc.hhp
 goto end
 
-:webrun
-set PYTHONPATH=tools
-%PYTHON% -m sphinx.web build\web
-goto end
-
 :end

Modified: python/branches/tlee-ast-optimize/Doc/reference/datamodel.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/reference/datamodel.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/reference/datamodel.rst	Wed Jan 14 13:24:17 2009
@@ -1162,9 +1162,10 @@
 Basic customization
 -------------------
 
-
 .. method:: object.__new__(cls[, ...])
 
+   .. index:: pair: subclassing; immutable types
+
    Called to create a new instance of class *cls*.  :meth:`__new__` is a static
    method (special-cased so you need not declare it as such) that takes the class
    of which an instance was requested as its first argument.  The remaining
@@ -2369,7 +2370,7 @@
    True
 
 In addition to bypassing any instance attributes in the interest of
-correctness, implicit special method lookup may also bypass the
+correctness, implicit special method lookup generally also bypasses the
 :meth:`__getattribute__` method even of the object's metaclass::
 
    >>> class Meta(type):

Modified: python/branches/tlee-ast-optimize/Doc/reference/expressions.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/reference/expressions.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/reference/expressions.rst	Wed Jan 14 13:24:17 2009
@@ -560,7 +560,7 @@
 .. productionlist::
    slicing: `simple_slicing` | `extended_slicing`
    simple_slicing: `primary` "[" `short_slice` "]"
-   extended_slicing: `primary` "[" `slice_list` "]" 
+   extended_slicing: `primary` "[" `slice_list` "]"
    slice_list: `slice_item` ("," `slice_item`)* [","]
    slice_item: `expression` | `proper_slice` | `ellipsis`
    proper_slice: `short_slice` | `long_slice`
@@ -664,7 +664,7 @@
 the call.
 
 .. note::
-   
+
    An implementation may provide builtin functions whose positional parameters do
    not have names, even if they are 'named' for the purpose of documentation, and
    which therefore cannot be supplied by keyword.  In CPython, this is the case for
@@ -1321,7 +1321,7 @@
 .. rubric:: Footnotes
 
 .. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
-   variables of each ``for`` it contains into the containing scope.  However, this 
+   variables of each ``for`` it contains into the containing scope.  However, this
    behavior is deprecated, and relying on it will not work in Python 3.0
 
 .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
@@ -1354,7 +1354,7 @@
    only, but this caused surprises because people expected to be able to test a
    dictionary for emptiness by comparing it to ``{}``.
 
-.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of 
+.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
    descriptors, you may notice seemingly unusual behaviour in certain uses of
    the :keyword:`is` operator, like those involving comparisons between instance
    methods, or constants.  Check their documentation for more info.

Modified: python/branches/tlee-ast-optimize/Doc/reference/lexical_analysis.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/reference/lexical_analysis.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/reference/lexical_analysis.rst	Wed Jan 14 13:24:17 2009
@@ -341,13 +341,13 @@
 language, and cannot be used as ordinary identifiers.  They must be spelled
 exactly as written here::
 
-   and       del       from      not       while    
-   as        elif      global    or        with     
-   assert    else      if        pass      yield    
-   break     except    import    print              
-   class     exec      in        raise              
-   continue  finally   is        return             
-   def       for       lambda    try 
+   and       del       from      not       while
+   as        elif      global    or        with
+   assert    else      if        pass      yield
+   break     except    import    print
+   class     exec      in        raise
+   continue  finally   is        return
+   def       for       lambda    try
 
 .. versionchanged:: 2.4
    :const:`None` became a constant and is now recognized by the compiler as a name
@@ -654,7 +654,7 @@
 
    7     2147483647                        0177
    3L    79228162514264337593543950336L    0377L   0x100000000L
-         79228162514264337593543950336             0xdeadbeef						    
+         79228162514264337593543950336             0xdeadbeef
 
 
 .. _floating:
@@ -701,7 +701,7 @@
 part, add a floating point number to it, e.g., ``(3+4j)``.  Some examples of
 imaginary literals::
 
-   3.14j   10.j    10j     .001j   1e100j  3.14e-10j 
+   3.14j   10.j    10j     .001j   1e100j  3.14e-10j
 
 
 .. _operators:

Modified: python/branches/tlee-ast-optimize/Doc/reference/simple_stmts.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/reference/simple_stmts.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/reference/simple_stmts.rst	Wed Jan 14 13:24:17 2009
@@ -745,7 +745,7 @@
 searched inside the package.  A package is generally a subdirectory of a
 directory on ``sys.path`` that has a file :file:`__init__.py`.
 
-.. 
+..
    [XXX Can't be
    bothered to spell this out right now; see the URL
    http://www.python.org/doc/essays/packages.html for more details, also about how

Deleted: python/branches/tlee-ast-optimize/Doc/tools/sphinx-web.py
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tools/sphinx-web.py	Wed Jan 14 13:24:17 2009
+++ (empty file)
@@ -1,14 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-    Sphinx - Python documentation webserver
-    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-    :copyright: 2007 by Georg Brandl.
-    :license: Python license.
-"""
-
-import sys
-
-if __name__ == '__main__':
-    from sphinx.web import main
-    sys.exit(main(sys.argv))

Modified: python/branches/tlee-ast-optimize/Doc/tools/sphinxext/download.html
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tools/sphinxext/download.html	(original)
+++ python/branches/tlee-ast-optimize/Doc/tools/sphinxext/download.html	Wed Jan 14 13:24:17 2009
@@ -19,20 +19,20 @@
 <table class="docutils">
   <tr><th>Format</th><th>Packed as .zip</th><th>Packed as .tar.bz2</th></tr>
   <tr><td>PDF (US-Letter paper size)</td>
-    <td><a href="{{ dlbase }}/python-docs-pdf-letter.zip">Download</a> (ca. 8 MB)</td>
-    <td><a href="{{ dlbase }}/python-docs-pdf-letter.tar.bz2">Download</a> (ca. 8 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.zip">Download</a> (ca. 8 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-letter.tar.bz2">Download</a> (ca. 8 MB)</td>
   </tr>
   <tr><td>PDF (A4 paper size)</td>
-    <td><a href="{{ dlbase }}/python-docs-pdf-a4.zip">Download</a> (ca. 8 MB)</td>
-    <td><a href="{{ dlbase }}/python-docs-pdf-a4.tar.bz2">Download</a> (ca. 8 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.zip">Download</a> (ca. 8 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-pdf-a4.tar.bz2">Download</a> (ca. 8 MB)</td>
   </tr>
   <tr><td>HTML</td>
-    <td><a href="{{ dlbase }}/python-docs-html.zip">Download</a> (ca. 6 MB)</td>
-    <td><a href="{{ dlbase }}/python-docs-html.tar.bz2">Download</a> (ca. 4 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-html.zip">Download</a> (ca. 6 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-html.tar.bz2">Download</a> (ca. 4 MB)</td>
   </tr>
   <tr><td>Plain Text</td>
     <td><a href="{{ dlbase }}/python-docs-text.zip">Download</a> (ca. 2 MB)</td>
-    <td><a href="{{ dlbase }}/python-docs-text.tar.bz2">Download</a> (ca. 1.5 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.tar.bz2">Download</a> (ca. 1.5 MB)</td>
   </tr>
 </table>
 

Modified: python/branches/tlee-ast-optimize/Doc/tools/sphinxext/layout.html
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tools/sphinxext/layout.html	(original)
+++ python/branches/tlee-ast-optimize/Doc/tools/sphinxext/layout.html	Wed Jan 14 13:24:17 2009
@@ -1,4 +1,10 @@
 {% extends "!layout.html" %}
 {% block rootrellink %}
-<li><img src="{{ pathto('_static/py.png', 1) }}" alt="" style="vertical-align: middle; margin-top: -1px"/></li><li><a href="{{ pathto('index') }}">{{ shorttitle }}</a>{{ reldelim1 }}</li>
+        <li><img src="{{ pathto('_static/py.png', 1) }}" alt=""
+                 style="vertical-align: middle; margin-top: -1px"/></li>
+        <li><a href="{{ pathto('index') }}">{{ shorttitle }}</a>{{ reldelim1 }}</li>
+{% endblock %}
+{% block extrahead %}
+    <link rel="shortcut icon" type="image/png" href="{{ pathto('_static/py.png', 1) }}" />
+{{ super() }}
 {% endblock %}

Modified: python/branches/tlee-ast-optimize/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/tlee-ast-optimize/Doc/tools/sphinxext/pyspecific.py	Wed Jan 14 13:24:17 2009
@@ -47,8 +47,10 @@
 from pprint import pformat
 from docutils.io import StringOutput
 from docutils.utils import new_document
-from sphinx.builder import Builder
-from sphinx.textwriter import TextWriter
+
+from sphinx.builders import Builder
+from sphinx.writers.text import TextWriter
+
 
 class PydocTopicsBuilder(Builder):
     name = 'pydoc-topics'
@@ -84,6 +86,9 @@
         finally:
             f.close()
 
+# Support for checking for suspicious markup
+
+import suspicious
 
 # Support for documenting Opcodes
 
@@ -108,5 +113,6 @@
 def setup(app):
     app.add_role('issue', issue_role)
     app.add_builder(PydocTopicsBuilder)
+    app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
     app.add_description_unit('opcode', 'opcode', '%s (opcode)',
                              parse_opcode_signature)

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/classes.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/classes.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/classes.rst	Wed Jan 14 13:24:17 2009
@@ -250,7 +250,7 @@
    ...     def __init__(self, realpart, imagpart):
    ...         self.r = realpart
    ...         self.i = imagpart
-   ... 
+   ...
    >>> x = Complex(3.0, -4.5)
    >>> x.r, x.i
    (3.0, -4.5)
@@ -481,7 +481,7 @@
   ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a
   subclass of :class:`str` (they only share a common ancestor,
   :class:`basestring`).
-  
+
 
 
 .. _tut-multiple:
@@ -743,7 +743,7 @@
    f
    l
    o
-   g	
+   g
 
 Anything that can be done with generators can also be done with class based
 iterators as described in the previous section.  What makes generators so

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/controlflow.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/controlflow.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/controlflow.rst	Wed Jan 14 13:24:17 2009
@@ -62,7 +62,7 @@
    ... a = ['cat', 'window', 'defenestrate']
    >>> for x in a:
    ...     print x, len(x)
-   ... 
+   ...
    cat 3
    window 6
    defenestrate 12
@@ -75,7 +75,7 @@
 
    >>> for x in a[:]: # make a slice copy of the entire list
    ...    if len(x) > 6: a.insert(0, x)
-   ... 
+   ...
    >>> a
    ['defenestrate', 'cat', 'window', 'defenestrate']
 
@@ -104,19 +104,22 @@
    >>> range(-10, -100, -30)
    [-10, -40, -70]
 
-To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
-as follows::
+To iterate over the indices of a sequence, you can combine :func:`range` and
+:func:`len` as follows::
 
    >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
    >>> for i in range(len(a)):
    ...     print i, a[i]
-   ... 
+   ...
    0 Mary
    1 had
    2 a
    3 little
    4 lamb
 
+In most such cases, however, it is convenient to use the :func:`enumerate`
+function, see :ref:`tut-loopidioms`.
+
 
 .. _tut-break:
 
@@ -143,7 +146,7 @@
    ...     else:
    ...         # loop fell through without finding a factor
    ...         print n, 'is a prime number'
-   ... 
+   ...
    2 is a prime number
    3 is a prime number
    4 equals 2 * 2
@@ -164,43 +167,21 @@
 
    >>> while True:
    ...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
-   ... 
+   ...
 
-This is commonly used for creating minimal classes such as exceptions, or
-for ignoring unwanted exceptions::
+This is commonly used for creating minimal classes::
 
-   >>> class ParserError(Exception):
-   ...     pass
-   ... 
-   >>> try:
-   ...     import audioop
-   ... except ImportError:
+   >>> class MyEmptyClass:
    ...     pass
-   ... 
+   ...
 
 Another place :keyword:`pass` can be used is as a place-holder for a function or
-conditional body when you are working on new code, allowing you to keep
-thinking at a more abstract level.  However, as :keyword:`pass` is silently
-ignored, a better choice may be to raise a :exc:`NotImplementedError`
-exception::
+conditional body when you are working on new code, allowing you to keep thinking
+at a more abstract level.  The :keyword:`pass` is silently ignored::
 
    >>> def initlog(*args):
-   ...     raise NotImplementedError   # Open logfile if not already open
-   ...     if not logfp:
-   ...         raise NotImplementedError  # Set up dummy log back-end
-   ...     raise NotImplementedError('Call log initialization handler')
-   ... 
-
-If :keyword:`pass` were used here and you later ran tests, they may fail
-without indicating why.  Using :exc:`NotImplementedError` causes this code
-to raise an exception, telling you exactly where the incomplete code 
-is.  Note the two calling styles of the exceptions above.
-The first style, with no message but with an accompanying comment, 
-lets you easily leave the comment when you remove the exception,
-which ideally would be a good description for
-the block of code the exception is a placeholder for.  However, the 
-third example, providing a message for the exception, will produce 
-a more useful traceback.
+   ...     pass   # Remember to implement this!
+   ...
 
 .. _tut-functions:
 
@@ -216,7 +197,7 @@
    ...     while b < n:
    ...         print b,
    ...         a, b = b, a+b
-   ... 
+   ...
    >>> # Now call the function we just defined:
    ... fib(2000)
    1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
@@ -287,7 +268,7 @@
    ...         result.append(b)    # see below
    ...         a, b = b, a+b
    ...     return result
-   ... 
+   ...
    >>> f100 = fib2(100)    # call it
    >>> f100                # write the result
    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
@@ -422,7 +403,7 @@
 
    >>> def function(a):
    ...     pass
-   ... 
+   ...
    >>> function(0, a=0)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
@@ -475,7 +456,7 @@
 ------------------------
 
 .. index::
-  statement: *  
+  statement: *
 
 Finally, the least frequently used option is to specify that a function can be
 called with an arbitrary number of arguments.  These arguments will be wrapped
@@ -584,11 +565,11 @@
 
    >>> def my_function():
    ...     """Do nothing, but document it.
-   ... 
+   ...
    ...     No, really, it doesn't do anything.
    ...     """
    ...     pass
-   ... 
+   ...
    >>> print my_function.__doc__
    Do nothing, but document it.
 

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/datastructures.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/datastructures.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/datastructures.rst	Wed Jan 14 13:24:17 2009
@@ -214,7 +214,7 @@
    >>> def sum(seq):
    ...     def add(x,y): return x+y
    ...     return reduce(add, seq, 0)
-   ... 
+   ...
    >>> sum(range(1, 11))
    55
    >>> sum([])
@@ -251,7 +251,7 @@
    []
    >>> [[x,x**2] for x in vec]
    [[2, 4], [4, 16], [6, 36]]
-   >>> [x, x**2 for x in vec]	# error - parens required for tuples
+   >>> [x, x**2 for x in vec]  # error - parens required for tuples
      File "<stdin>", line 1, in ?
        [x, x**2 for x in vec]
                   ^
@@ -281,7 +281,7 @@
 powerful tool but -- like all powerful tools -- they need to be used carefully,
 if at all.
 
-Consider the following example of a 3x3 matrix held as a list containing three 
+Consider the following example of a 3x3 matrix held as a list containing three
 lists, one list per row::
 
     >>> mat = [
@@ -290,7 +290,7 @@
     ...        [7, 8, 9],
     ...       ]
 
-Now, if you wanted to swap rows and columns, you could use a list 
+Now, if you wanted to swap rows and columns, you could use a list
 comprehension::
 
     >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
@@ -308,7 +308,7 @@
             print row[i],
         print
 
-In real world, you should prefer builtin functions to complex flow statements. 
+In real world, you should prefer builtin functions to complex flow statements.
 The :func:`zip` function would do a great job for this use case::
 
     >>> zip(*mat)
@@ -551,7 +551,7 @@
    >>> answers = ['lancelot', 'the holy grail', 'blue']
    >>> for q, a in zip(questions, answers):
    ...     print 'What is your {0}?  It is {1}.'.format(q, a)
-   ...	
+   ...
    What is your name?  It is lancelot.
    What is your quest?  It is the holy grail.
    What is your favorite color?  It is blue.
@@ -574,7 +574,7 @@
    >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    >>> for f in sorted(set(basket)):
    ...     print f
-   ... 	
+   ...
    apple
    banana
    orange

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/errors.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/errors.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/errors.rst	Wed Jan 14 13:24:17 2009
@@ -91,7 +91,7 @@
    ...         break
    ...     except ValueError:
    ...         print "Oops!  That was no valid number.  Try again..."
-   ...     
+   ...
 
 The :keyword:`try` statement works as follows.
 
@@ -199,12 +199,12 @@
 
    >>> def this_fails():
    ...     x = 1/0
-   ... 
+   ...
    >>> try:
    ...     this_fails()
    ... except ZeroDivisionError as detail:
    ...     print 'Handling run-time error:', detail
-   ... 
+   ...
    Handling run-time error: integer division or modulo by zero
 
 
@@ -256,12 +256,12 @@
    ...         self.value = value
    ...     def __str__(self):
    ...         return repr(self.value)
-   ... 
+   ...
    >>> try:
    ...     raise MyError(2*2)
    ... except MyError as e:
    ...     print 'My exception occurred, value:', e.value
-   ... 
+   ...
    My exception occurred, value: 4
    >>> raise MyError, 'oops!'
    Traceback (most recent call last):
@@ -331,7 +331,7 @@
    ...     raise KeyboardInterrupt
    ... finally:
    ...     print 'Goodbye, world!'
-   ... 
+   ...
    Goodbye, world!
    Traceback (most recent call last):
      File "<stdin>", line 2, in ?

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/index.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/index.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/index.rst	Wed Jan 14 13:24:17 2009
@@ -1,7 +1,7 @@
 .. _tutorial-index:
 
 ######################
-  The Python Tutorial 
+  The Python Tutorial
 ######################
 
 :Release: |version|

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/inputoutput.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/inputoutput.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/inputoutput.rst	Wed Jan 14 13:24:17 2009
@@ -87,7 +87,7 @@
 
    >>> for x in range(1,11):
    ...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
-   ... 
+   ...
     1   1    1
     2   4    8
     3   9   27
@@ -148,7 +148,7 @@
    ...                                                    other='Georg')
    The story of Bill, Manfred, and Georg.
 
-An optional ``':``` and format specifier can follow the field name. This also
+An optional ``':'`` and format specifier can follow the field name. This also
 greater control over how the value is formatted.  The following example
 truncates the Pi to three places after the decimal.
 
@@ -162,7 +162,7 @@
    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
    >>> for name, phone in table.items():
    ...     print '{0:10} ==> {1:10d}'.format(name, phone)
-   ... 
+   ...
    Jack       ==>       4098
    Dcab       ==>       7678
    Sjoerd     ==>       4127
@@ -330,7 +330,7 @@
    >>> f = open('/tmp/workfile', 'r+')
    >>> f.write('0123456789abcdef')
    >>> f.seek(5)     # Go to the 6th byte in the file
-   >>> f.read(1)        
+   >>> f.read(1)
    '5'
    >>> f.seek(-3, 2) # Go to the 3rd byte before the end
    >>> f.read(1)

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/interpreter.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/interpreter.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/interpreter.rst	Wed Jan 14 13:24:17 2009
@@ -112,7 +112,7 @@
    >>> the_world_is_flat = 1
    >>> if the_world_is_flat:
    ...     print "Be careful not to fall off!"
-   ... 
+   ...
    Be careful not to fall off!
 
 
@@ -180,7 +180,7 @@
 best way to do it is to put one more special comment line right after the ``#!``
 line to define the source file encoding::
 
-   # -*- coding: encoding -*- 
+   # -*- coding: encoding -*-
 
 
 With that declaration, all characters in the source file will be treated as

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/introduction.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/introduction.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/introduction.rst	Wed Jan 14 13:24:17 2009
@@ -84,7 +84,7 @@
 
    >>> # try to access an undefined variable
    ... n
-   Traceback (most recent call last):   
+   Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'n' is not defined
 
@@ -219,14 +219,14 @@
 they will be included in the string. ::
 
    print """
-   Usage: thingy [OPTIONS] 
+   Usage: thingy [OPTIONS]
         -h                        Display this usage message
         -H hostname               Hostname to connect to
    """
 
 produces the following output::
 
-   Usage: thingy [OPTIONS] 
+   Usage: thingy [OPTIONS]
         -h                        Display this usage message
         -H hostname               Hostname to connect to
 
@@ -350,10 +350,10 @@
 Then the right edge of the last character of a string of *n* characters has
 index *n*, for example::
 
-    +---+---+---+---+---+ 
+    +---+---+---+---+---+
     | H | e | l | p | A |
-    +---+---+---+---+---+ 
-    0   1   2   3   4   5 
+    +---+---+---+---+---+
+    0   1   2   3   4   5
    -5  -4  -3  -2  -1
 
 The first row of numbers gives the position of the indices 0...5 in the string;
@@ -595,7 +595,7 @@
    >>> while b < 10:
    ...     print b
    ...     a, b = b, a+b
-   ... 
+   ...
    1
    1
    2
@@ -645,7 +645,7 @@
      >>> while b < 1000:
      ...     print b,
      ...     a, b = b, a+b
-     ... 
+     ...
      1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
 
   Note that the interpreter inserts a newline before it prints the next prompt if

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/modules.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/modules.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/modules.rst	Wed Jan 14 13:24:17 2009
@@ -281,7 +281,7 @@
    ['__name__', 'fib', 'fib2']
    >>> dir(sys)
    ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
-    '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 
+    '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
     'builtin_module_names', 'byteorder', 'callstats', 'copyright',
     'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
     'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
@@ -314,7 +314,7 @@
     'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
     'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
     'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
-    'NotImplementedError', 'OSError', 'OverflowError', 
+    'NotImplementedError', 'OSError', 'OverflowError',
     'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
     'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
     'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/stdlib.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/stdlib.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/stdlib.rst	Wed Jan 14 13:24:17 2009
@@ -136,7 +136,7 @@
    >>> random.random()    # random float
    0.17970987693706186
    >>> random.randrange(6)    # random integer chosen from range(6)
-   4   
+   4
 
 
 .. _tut-internet-access:

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/stdlib2.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/stdlib2.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/stdlib2.rst	Wed Jan 14 13:24:17 2009
@@ -62,7 +62,7 @@
    >>> locale.format("%d", x, grouping=True)
    '1,234,567'
    >>> locale.format("%s%.*f", (conv['currency_symbol'],
-   ...	      conv['frac_digits'], x), grouping=True)
+   ...               conv['frac_digits'], x), grouping=True)
    '$1,234,567.80'
 
 

Modified: python/branches/tlee-ast-optimize/Doc/tutorial/whatnow.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/tutorial/whatnow.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/tutorial/whatnow.rst	Wed Jan 14 13:24:17 2009
@@ -63,6 +63,6 @@
 
 .. Postings figure based on average of last six months activity as
    reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
-   days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?) 
+   days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?)
 
 

Modified: python/branches/tlee-ast-optimize/Doc/using/cmdline.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/using/cmdline.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/using/cmdline.rst	Wed Jan 14 13:24:17 2009
@@ -8,8 +8,8 @@
 The CPython interpreter scans the command line and the environment for various
 settings.
 
-.. note:: 
-   
+.. note::
+
    Other implementations' command line schemes may differ.  See
    :ref:`implementations` for further resources.
 
@@ -61,7 +61,7 @@
    Execute the Python code in *command*.  *command* can be one ore more
    statements separated by newlines, with significant leading whitespace as in
    normal module code.
-   
+
    If this option is given, the first element of :data:`sys.argv` will be
    ``"-c"`` and the current directory will be added to the start of
    :data:`sys.path` (allowing modules in that directory to be imported as top
@@ -72,7 +72,7 @@
 
    Search :data:`sys.path` for the named module and execute its contents as
    the :mod:`__main__` module.
-   
+
    Since the argument is a *module* name, you must not give a file extension
    (``.py``).  The ``module-name`` should be a valid Python module name, but
    the implementation may not always enforce this (e.g. it may allow you to
@@ -84,18 +84,18 @@
       written in C, since they do not have Python module files. However, it
       can still be used for precompiled modules, even if the original source
       file is not available.
-   
+
    If this option is given, the first element of :data:`sys.argv` will be the
    full path to the module file. As with the :option:`-c` option, the current
    directory will be added to the start of :data:`sys.path`.
-   
+
    Many standard library modules contain code that is invoked on their execution
    as a script.  An example is the :mod:`timeit` module::
 
        python -mtimeit -s 'setup here' 'benchmarked code here'
        python -mtimeit -h # for details
 
-   .. seealso:: 
+   .. seealso::
       :func:`runpy.run_module`
          The actual implementation of this feature.
 
@@ -163,7 +163,7 @@
                --version
 
    Print the Python version number and exit.  Example output could be::
-    
+
        Python 2.5.1
 
    .. versionchanged:: 2.5
@@ -201,7 +201,7 @@
    enter interactive mode after executing the script or the command, even when
    :data:`sys.stdin` does not appear to be a terminal.  The
    :envvar:`PYTHONSTARTUP` file is not read.
-   
+
    This can be useful to inspect global variables or a stack trace when a script
    raises an exception.  See also :envvar:`PYTHONINSPECT`.
 
@@ -221,7 +221,7 @@
 .. cmdoption:: -Q <arg>
 
    Division control. The argument must be one of the following:
-   
+
    ``old``
      division of int/int and long/long return an int or long (*default*)
    ``new``
@@ -264,10 +264,10 @@
 
 
 .. cmdoption:: -u
-   
+
    Force stdin, stdout and stderr to be totally unbuffered.  On systems where it
    matters, also put stdin, stdout and stderr in binary mode.
-   
+
    Note that there is internal buffering in :meth:`file.readlines` and
    :ref:`bltin-file-objects` (``for line in sys.stdin``) which is not influenced
    by this option.  To work around this, you will want to use
@@ -279,7 +279,7 @@
 .. XXX should the -U option be documented?
 
 .. cmdoption:: -v
-   
+
    Print a message each time a module is initialized, showing the place
    (filename or built-in module) from which it is loaded.  When given twice
    (:option:`-vv`), print a message for each file that is checked for when
@@ -288,13 +288,13 @@
 
 
 .. cmdoption:: -W arg
-   
+
    Warning control.  Python's warning machinery by default prints warning
    messages to :data:`sys.stderr`.  A typical warning message has the following
    form::
 
        file:line: category: message
-       
+
    By default, each warning is printed once for each source line where it
    occurs.  This option controls how often warnings are printed.
 
@@ -302,13 +302,13 @@
    one option, the action for the last matching option is performed.  Invalid
    :option:`-W` options are ignored (though, a warning message is printed about
    invalid options when the first warning is issued).
-   
+
    Warnings can also be controlled from within a Python program using the
    :mod:`warnings` module.
 
    The simplest form of argument is one of the following action strings (or a
    unique abbreviation):
-    
+
    ``ignore``
       Ignore all warnings.
    ``default``
@@ -324,9 +324,9 @@
       Print each warning only the first time it occurs in the program.
    ``error``
       Raise an exception instead of printing a warning message.
-      
-   The full form of argument is:: 
-   
+
+   The full form of argument is::
+
        action:message:category:module:line
 
    Here, *action* is as explained above but only applies to messages that match
@@ -347,16 +347,17 @@
 
 
 .. cmdoption:: -x
-   
+
    Skip the first line of the source, allowing use of non-Unix forms of
    ``#!cmd``.  This is intended for a DOS specific hack only.
-   
+
    .. warning:: The line numbers in error messages will be off by one!
 
 
 .. cmdoption:: -3
 
-   Warn about Python 3.x incompatibilities. Among these are:
+   Warn about Python 3.x incompatibilities which cannot be fixed trivially by
+   :ref:`2to3 <2to3-reference>`. Among these are:
 
    * :meth:`dict.has_key`
    * :func:`apply`
@@ -380,13 +381,13 @@
 These environment variables influence Python's behavior.
 
 .. envvar:: PYTHONHOME
-   
+
    Change the location of the standard Python libraries.  By default, the
    libraries are searched in :file:`{prefix}/lib/python{version}` and
    :file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and
    :file:`{exec_prefix}` are installation-dependent directories, both defaulting
    to :file:`/usr/local`.
-   
+
    When :envvar:`PYTHONHOME` is set to a single directory, its value replaces
    both :file:`{prefix}` and :file:`{exec_prefix}`.  To specify different values
    for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`.
@@ -402,11 +403,11 @@
    In addition to normal directories, individual :envvar:`PYTHONPATH` entries
    may refer to zipfiles containing pure Python modules (in either source or
    compiled form). Extension modules cannot be imported from zipfiles.
-   
+
    The default search path is installation dependent, but generally begins with
-   :file:`{prefix}/lib/python{version}`` (see :envvar:`PYTHONHOME` above).  It
+   :file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above).  It
    is *always* appended to :envvar:`PYTHONPATH`.
-   
+
    An additional directory will be inserted in the search path in front of
    :envvar:`PYTHONPATH` as described above under
    :ref:`using-on-interface-options`. The search path can be manipulated from
@@ -414,7 +415,7 @@
 
 
 .. envvar:: PYTHONSTARTUP
-   
+
    If this is the name of a readable file, the Python commands in that file are
    executed before the first prompt is displayed in interactive mode.  The file
    is executed in the same namespace where interactive commands are executed so
@@ -424,7 +425,7 @@
 
 
 .. envvar:: PYTHONY2K
-   
+
    Set this to a non-empty string to cause the :mod:`time` module to require
    dates specified as strings to include 4-digit years, otherwise 2-digit years
    are converted based on rules described in the :mod:`time` module
@@ -432,21 +433,21 @@
 
 
 .. envvar:: PYTHONOPTIMIZE
-   
+
    If this is set to a non-empty string it is equivalent to specifying the
    :option:`-O` option.  If set to an integer, it is equivalent to specifying
    :option:`-O` multiple times.
 
 
 .. envvar:: PYTHONDEBUG
-   
+
    If this is set to a non-empty string it is equivalent to specifying the
    :option:`-d` option.  If set to an integer, it is equivalent to specifying
    :option:`-d` multiple times.
 
 
 .. envvar:: PYTHONINSPECT
-   
+
    If this is set to a non-empty string it is equivalent to specifying the
    :option:`-i` option.
 
@@ -455,20 +456,20 @@
 
 
 .. envvar:: PYTHONUNBUFFERED
-   
+
    If this is set to a non-empty string it is equivalent to specifying the
    :option:`-u` option.
 
 
 .. envvar:: PYTHONVERBOSE
-   
+
    If this is set to a non-empty string it is equivalent to specifying the
    :option:`-v` option.  If set to an integer, it is equivalent to specifying
    :option:`-v` multiple times.
 
 
 .. envvar:: PYTHONCASEOK
-   
+
    If this is set, Python ignores case in :keyword:`import` statements.  This
    only works on Windows.
 

Modified: python/branches/tlee-ast-optimize/Doc/using/unix.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/using/unix.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/using/unix.rst	Wed Jan 14 13:24:17 2009
@@ -19,7 +19,7 @@
 package on all others.  However there are certain features you might want to use
 that are not available on your distro's package.  You can easily compile the
 latest version of Python from source.
-	
+
 In the event that Python doesn't come preinstalled and isn't in the repositories as
 well, you can easily make packages for your own distro.  Have a look at the
 following links:
@@ -45,8 +45,8 @@
 
 * OpenBSD users use::
 
-     pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz 
-	
+     pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz
+
   For example i386 users get the 2.5.1 version of Python using::
 
      pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
@@ -87,7 +87,7 @@
 
 Python-related paths and files
 ==============================
- 
+
 These are subject to difference depending on local installation conventions;
 :envvar:`prefix` (``${prefix}``) and :envvar:`exec_prefix` (``${exec_prefix}``)
 are installation-dependent and should be interpreted as for GNU software; they
@@ -112,7 +112,7 @@
 |                                               | by the user module; not used by default  |
 |                                               | or by most applications.                 |
 +-----------------------------------------------+------------------------------------------+
- 
+
 
 Miscellaneous
 =============
@@ -140,8 +140,8 @@
 Vim and Emacs are excellent editors which support Python very well.  For more
 information on how to code in python in these editors, look at:
 
-http://www.vim.org/scripts/script.php?script_id=790
-http://sourceforge.net/projects/python-mode
+* http://www.vim.org/scripts/script.php?script_id=790
+* http://sourceforge.net/projects/python-mode
 
 Geany is an excellent IDE with support for a lot of languages. For more
 information, read: http://geany.uvena.de/

Modified: python/branches/tlee-ast-optimize/Doc/using/windows.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/using/windows.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/using/windows.rst	Wed Jan 14 13:24:17 2009
@@ -88,9 +88,9 @@
 ---------------------------------------
 
 Windows has a built-in dialog for changing environment variables (following
-guide applies to XP classical view): Right-click the icon for your machine 
-(usually located on your Desktop and called "My Computer") and choose 
-:menuselection:`Properties` there.  Then, open the :guilabel:`Advanced` tab 
+guide applies to XP classical view): Right-click the icon for your machine
+(usually located on your Desktop and called "My Computer") and choose
+:menuselection:`Properties` there.  Then, open the :guilabel:`Advanced` tab
 and click the :guilabel:`Environment Variables` button.
 
 In short, your path is:
@@ -193,11 +193,11 @@
 
 #. Launch a command prompt.
 #. Associate the correct file group with ``.py`` scripts::
-   
+
       assoc .py=Python.File
 
 #. Redirect all Python files to the new executable::
-   
+
       ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
 
 

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.0.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.0.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.0.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.0  
+  What's New in Python 2.0
 ****************************
 
 :Author: A.M. Kuchling and Moshe Zadka
@@ -277,11 +277,11 @@
 finding all the strings in the list containing a given substring.  You could
 write the following to do it::
 
-   # Given the list L, make a list of all strings 
+   # Given the list L, make a list of all strings
    # containing the substring S.
-   sublist = filter( lambda s, substring=S: 
+   sublist = filter( lambda s, substring=S:
                         string.find(s, substring) != -1,
-   	          L)
+                     L)
 
 Because of Python's scoping rules, a default argument is used so that the
 anonymous function created by the :keyword:`lambda` statement knows what
@@ -291,9 +291,9 @@
 
 List comprehensions have the form::
 
-   [ expression for expr in sequence1 
+   [ expression for expr in sequence1
                 for expr2 in sequence2 ...
-   	     for exprN in sequenceN
+                for exprN in sequenceN
                 if condition ]
 
 The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
@@ -312,8 +312,8 @@
        ...
            for exprN in sequenceN:
                 if (condition):
-                     # Append the value of 
-                     # the expression to the 
+                     # Append the value of
+                     # the expression to the
                      # resulting list.
 
 This means that when there are multiple :keyword:`for`...\ :keyword:`in`
@@ -368,7 +368,7 @@
        def __init__(self, value):
            self.value = value
        def __iadd__(self, increment):
-   	return Number( self.value + increment)
+           return Number( self.value + increment)
 
    n = Number(5)
    n += 3
@@ -590,7 +590,7 @@
 
    def f():
        print "i=",i
-       i = i + 1 
+       i = i + 1
    f()
 
 Two new exceptions, :exc:`TabError` and :exc:`IndentationError`, have been
@@ -627,7 +627,7 @@
 the following lines of code::
 
    if dict.has_key( key ): return dict[key]
-   else: 
+   else:
        dict[key] = []
        return dict[key]
 
@@ -836,14 +836,14 @@
 :file:`setup.py` can be just a few lines long::
 
    from distutils.core import setup
-   setup (name = "foo", version = "1.0", 
+   setup (name = "foo", version = "1.0",
           py_modules = ["module1", "module2"])
 
 The :file:`setup.py` file isn't much more complicated if the software consists
 of a few packages::
 
    from distutils.core import setup
-   setup (name = "foo", version = "1.0", 
+   setup (name = "foo", version = "1.0",
           packages = ["package", "package.subpackage"])
 
 A C extension can be the most complicated case; here's an example taken from
@@ -852,15 +852,14 @@
    from distutils.core import setup, Extension
 
    expat_extension = Extension('xml.parsers.pyexpat',
-   	define_macros = [('XML_NS', None)],
-   	include_dirs = [ 'extensions/expat/xmltok',
-   	                 'extensions/expat/xmlparse' ],
-   	sources = [ 'extensions/pyexpat.c',
-   	            'extensions/expat/xmltok/xmltok.c',
-    		    'extensions/expat/xmltok/xmlrole.c',
-                     ]
+        define_macros = [('XML_NS', None)],
+        include_dirs = [ 'extensions/expat/xmltok',
+                         'extensions/expat/xmlparse' ],
+        sources = [ 'extensions/pyexpat.c',
+                    'extensions/expat/xmltok/xmltok.c',
+                    'extensions/expat/xmltok/xmlrole.c', ]
           )
-   setup (name = "PyXML", version = "0.5.4", 
+   setup (name = "PyXML", version = "0.5.4",
           ext_modules =[ expat_extension ] )
 
 The Distutils can also take care of creating source and binary distributions.

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.1.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.1.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.1.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.1  
+  What's New in Python 2.1
 ****************************
 
 :Author: A.M. Kuchling
@@ -98,7 +98,7 @@
    x = 1
    def f():
        # The next line is a syntax error
-       exec 'x=2'  
+       exec 'x=2'
        def g():
            return x
 

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.2.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.2.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.2.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.2  
+  What's New in Python 2.2
 ****************************
 
 :Author: A.M. Kuchling
@@ -295,7 +295,7 @@
 
    class D (B,C):
        def save (self):
-   	# Call superclass .save()
+           # Call superclass .save()
            super(D, self).save()
            # Save D's private information here
            ...
@@ -473,7 +473,7 @@
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
-   >>>      
+   >>>
 
 In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it
 expects something for which :func:`iter` will return an iterator. For backward
@@ -909,7 +909,7 @@
    x = 1
    def f():
        # The next line is a syntax error
-       exec 'x=2'  
+       exec 'x=2'
        def g():
            return x
 
@@ -952,8 +952,8 @@
      items = s.meerkat.getItems( {'channel': 4} )
 
      # 'items' is another list of dictionaries, like this:
-     # [{'link': 'http://freshmeat.net/releases/52719/', 
-     #   'description': 'A utility which converts HTML to XSL FO.', 
+     # [{'link': 'http://freshmeat.net/releases/52719/',
+     #   'description': 'A utility which converts HTML to XSL FO.',
      #   'title': 'html2fo 0.3 (Default)'}, ... ]
 
   The :mod:`SimpleXMLRPCServer` module makes it easy to create straightforward

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.3.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.3.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.3.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.3  
+  What's New in Python 2.3
 ****************************
 
 :Author: A.M. Kuchling
@@ -301,7 +301,7 @@
     --------                   -------
         8467                   1 file
    amk at nyman:~/src/python$ ./python
-   Python 2.3 (#1, Aug 1 2003, 19:54:32) 
+   Python 2.3 (#1, Aug 1 2003, 19:54:32)
    >>> import sys
    >>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
    >>> import jwzthreading
@@ -671,7 +671,7 @@
          # ...
          }
 
-   if (hasattr(core, 'setup_keywords') and 
+   if (hasattr(core, 'setup_keywords') and
        'classifiers' in core.setup_keywords):
        kw['classifiers'] = \
            ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
@@ -1027,7 +1027,7 @@
   creating small dictionaries::
 
      >>> dict(red=1, blue=2, green=3, black=4)
-     {'blue': 2, 'black': 4, 'green': 3, 'red': 1}    
+     {'blue': 2, 'black': 4, 'green': 3, 'red': 1}
 
   (Contributed by Just van Rossum.)
 
@@ -1622,7 +1622,7 @@
      ...         self.valuelist.pop(i)
      ...     def keys(self):
      ...         return list(self.keylist)
-     ... 
+     ...
      >>> s = SeqDict()
      >>> dir(s)      # See that other dictionary methods are implemented
      ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
@@ -1779,7 +1779,7 @@
                            set input filename
      -lLENGTH, --length=LENGTH
                            set maximum length of output
-   $ 
+   $
 
 See the module's documentation for more details.
 

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.4.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.4.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.4.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.4  
+  What's New in Python 2.4
 ****************************
 
 :Author: A.M. Kuchling
@@ -63,10 +63,10 @@
    >>> a.add('z')                          # add a new element
    >>> a.update('wxy')                     # add multiple new elements
    >>> a
-   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])       
+   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
    >>> a.remove('x')                       # take one element out
    >>> a
-   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])       
+   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
 
 The :func:`frozenset` type is an immutable version of :func:`set`. Since it is
 immutable and hashable, it may be used as a dictionary key or as a member of
@@ -351,7 +351,7 @@
 
    >>> for i in reversed(xrange(1,4)):
    ...    print i
-   ... 
+   ...
    3
    2
    1
@@ -366,7 +366,7 @@
    >>> input = open('/etc/passwd', 'r')
    >>> for line in reversed(list(input)):
    ...   print line
-   ... 
+   ...
    root:*:0:0:System Administrator:/var/root:/bin/tcsh
      ...
 
@@ -396,10 +396,10 @@
 different keyword arguments. ::
 
    class Popen(args, bufsize=0, executable=None,
-   	    stdin=None, stdout=None, stderr=None,
-   	    preexec_fn=None, close_fds=False, shell=False,
-   	    cwd=None, env=None, universal_newlines=False,
-   	    startupinfo=None, creationflags=0):
+               stdin=None, stdout=None, stderr=None,
+               preexec_fn=None, close_fds=False, shell=False,
+               cwd=None, env=None, universal_newlines=False,
+               startupinfo=None, creationflags=0):
 
 *args* is commonly a sequence of strings that will be the arguments to the
 program executed as the subprocess.  (If the *shell* argument is true, *args*
@@ -650,7 +650,7 @@
    28
    >>> decimal.Decimal(1) / decimal.Decimal(7)
    Decimal("0.1428571428571428571428571429")
-   >>> decimal.getcontext().prec = 9 
+   >>> decimal.getcontext().prec = 9
    >>> decimal.Decimal(1) / decimal.Decimal(7)
    Decimal("0.142857143")
 
@@ -665,7 +665,7 @@
    >>> decimal.getcontext().traps[decimal.DivisionByZero] = False
    >>> decimal.Decimal(1) / decimal.Decimal(0)
    Decimal("Infinity")
-   >>> 
+   >>>
 
 The :class:`Context` instance also has various methods for formatting  numbers
 such as :meth:`to_eng_string` and :meth:`to_sci_string`.
@@ -803,7 +803,7 @@
      >>> 'www.python.org'.split('.', 1)
      ['www', 'python.org']
      'www.python.org'.rsplit('.', 1)
-     ['www.python', 'org']        
+     ['www.python', 'org']
 
 * Three keyword parameters, *cmp*, *key*, and *reverse*, were added to the
   :meth:`sort` method of lists. These parameters make some common usages of
@@ -1045,7 +1045,7 @@
      >>> list(d)                 # list the contents of the deque
      ['g', 'h', 'i']
      >>> 'h' in d                # search the deque
-     True  
+     True
 
   Several modules, such as the :mod:`Queue` and :mod:`threading` modules, now take
   advantage of :class:`collections.deque` for improved performance.  (Contributed
@@ -1106,13 +1106,13 @@
      >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
      >>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
      ...    print key_val, list(it)
-     ... 
+     ...
      0 [2, 4, 6]
      1 [7]
      0 [8]
      1 [9, 11]
      0 [12, 14]
-     >>> 
+     >>>
 
   :func:`groupby` is typically used with sorted input.  The logic for
   :func:`groupby` is similar to the Unix ``uniq`` filter which makes it handy for
@@ -1120,21 +1120,21 @@
 
      >>> word = 'abracadabra'
      >>> letters = sorted(word)   # Turn string into a sorted list of letters
-     >>> letters 
+     >>> letters
      ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
      >>> for k, g in itertools.groupby(letters):
      ...    print k, list(g)
-     ... 
+     ...
      a ['a', 'a', 'a', 'a', 'a']
      b ['b', 'b']
      c ['c']
      d ['d']
      r ['r', 'r']
      >>> # List unique letters
-     >>> [k for k, g in groupby(letters)]                     
+     >>> [k for k, g in groupby(letters)]
      ['a', 'b', 'c', 'd', 'r']
      >>> # Count letter occurrences
-     >>> [(k, len(list(g))) for k, g in groupby(letters)]     
+     >>> [(k, len(list(g))) for k, g in groupby(letters)]
      [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
 
   (Contributed by Hye-Shik Chang.)
@@ -1175,7 +1175,7 @@
      import logging
      logging.basicConfig(filename='/var/log/application.log',
          level=0,  # Log all messages
-         format='%(levelname):%(process):%(thread):%(message)')	            
+         format='%(levelname):%(process):%(thread):%(message)')
 
   Other additions to the :mod:`logging` package include a :meth:`log(level, msg)`
   convenience method, as well as a :class:`TimedRotatingFileHandler` class that
@@ -1428,7 +1428,7 @@
 you get the following output::
 
    **********************************************************************
-   File ``t.py'', line 15, in g
+   File "t.py", line 15, in g
    Failed example:
        g(4)
    Differences (unified diff with -expected +actual):

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.5.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.5.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.5.rst	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.5  
+  What's New in Python 2.5
 ****************************
 
 :Author: A.M. Kuchling
@@ -220,7 +220,7 @@
 required packages. ::
 
    VERSION = '1.0'
-   setup(name='PyPackage', 
+   setup(name='PyPackage',
          version=VERSION,
          requires=['numarray', 'zlib (>=1.1.4)'],
          obsoletes=['OldPackage']
@@ -388,7 +388,7 @@
    else:
        else-block
    finally:
-       final-block 
+       final-block
 
 The code in *block-1* is executed.  If the code raises an exception, the various
 :keyword:`except` blocks are tested: if the exception is of class
@@ -485,7 +485,7 @@
    9
    >>> print it.next()
    Traceback (most recent call last):
-     File ``t.py'', line 15, in ?
+     File "t.py", line 15, in ?
        print it.next()
    StopIteration
 
@@ -835,8 +835,8 @@
        ...
    except (KeyboardInterrupt, SystemExit):
        raise
-   except: 
-       # Log error...  
+   except:
+       # Log error...
        # Continue running program...
 
 In Python 2.5, you can now write ``except Exception`` to achieve the same
@@ -947,7 +947,7 @@
 
    class C:
        def __index__ (self):
-           return self.value  
+           return self.value
 
 The return value must be either a Python integer or long integer. The
 interpreter will check that the type returned is correct, and raises a
@@ -1035,9 +1035,9 @@
 
      L = ['medium', 'longest', 'short']
      # Prints 'longest'
-     print max(L, key=len)              
+     print max(L, key=len)
      # Prints 'short', because lexicographically 'short' has the largest value
-     print max(L)         
+     print max(L)
 
   (Contributed by Steven Bethard and Raymond Hettinger.)
 
@@ -1070,8 +1070,8 @@
   using the default ASCII encoding.   The result of the comparison is false::
 
      >>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
-     __main__:1: UnicodeWarning: Unicode equal comparison failed 
-       to convert both arguments to Unicode - interpreting them 
+     __main__:1: UnicodeWarning: Unicode equal comparison failed
+       to convert both arguments to Unicode - interpreting them
        as being unequal
      False
      >>> chr(127) == unichr(127)   # chr(127) can be converted
@@ -1259,10 +1259,10 @@
 
   Printing ``index`` results in the following output::
 
-     defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'], 
-             'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'], 
-             'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'], 
-             'p': ['per'], 's': ['selva', 'smarrita'], 
+     defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
+             'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
+             'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
+             'p': ['per'], 's': ['selva', 'smarrita'],
              'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
 
   (Contributed by Guido van Rossum.)
@@ -1884,17 +1884,17 @@
 differently. ::
 
    # Old versions
-   h = md5.md5()   
-   h = md5.new()   
+   h = md5.md5()
+   h = md5.new()
 
-   # New version 
+   # New version
    h = hashlib.md5()
 
    # Old versions
-   h = sha.sha()   
-   h = sha.new()   
+   h = sha.sha()
+   h = sha.new()
 
-   # New version 
+   # New version
    h = hashlib.sha1()
 
    # Hash that weren't previously available
@@ -2191,7 +2191,7 @@
   case that your extensions were using it, you can replace it by something like
   the following::
 
-     range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", 
+     range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                                    start, stop, step);
 
 .. ======================================================================

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	Wed Jan 14 13:24:17 2009
@@ -586,30 +586,30 @@
 
 
     def factorial(queue, N):
-	"Compute a factorial."
-	# If N is a multiple of 4, this function will take much longer.
-	if (N % 4) == 0:
-	    time.sleep(.05 * N/4)
-
-	# Calculate the result
-	fact = 1L
-	for i in range(1, N+1):
-	    fact = fact * i
+        "Compute a factorial."
+        # If N is a multiple of 4, this function will take much longer.
+        if (N % 4) == 0:
+            time.sleep(.05 * N/4)
+
+        # Calculate the result
+        fact = 1L
+        for i in range(1, N+1):
+            fact = fact * i
 
-	# Put the result on the queue
-	queue.put(fact)
+        # Put the result on the queue
+        queue.put(fact)
 
     if __name__ == '__main__':
-	queue = Queue()
+        queue = Queue()
 
-	N = 5
+        N = 5
 
-	p = Process(target=factorial, args=(queue, N))
-	p.start()
-	p.join()
+        p = Process(target=factorial, args=(queue, N))
+        p.start()
+        p.join()
 
-	result = queue.get()
-	print 'Factorial', N, '=', result
+        result = queue.get()
+        print 'Factorial', N, '=', result
 
 A :class:`Queue` is used to communicate the input parameter *N* and
 the result.  The :class:`Queue` object is stored in a global variable.
@@ -630,12 +630,12 @@
     from multiprocessing import Pool
 
     def factorial(N, dictionary):
-	"Compute a factorial."
-	...
+        "Compute a factorial."
+        ...
     p = Pool(5)
     result = p.map(factorial, range(1, 1000, 10))
     for v in result:
-	print v
+        print v
 
 This produces the following output::
 
@@ -734,7 +734,7 @@
 
 Curly brackets can be escaped by doubling them::
 
-     >>> format("Empty dict: {{}}")
+     >>> "Empty dict: {{}}".format()
      "Empty dict: {}"
 
 Field names can be integers indicating positional arguments, such as
@@ -744,7 +744,7 @@
     >>> import sys
     >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
     Platform: darwin
-    Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41) 
+    Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
     [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
 
     >>> import mimetypes
@@ -958,8 +958,8 @@
 The primary use of :class:`bytes` in 2.6 will be to write tests of
 object type such as ``isinstance(x, bytes)``.  This will help the 2to3
 converter, which can't tell whether 2.x code intends strings to
-contain either characters or 8-bit bytes; you can now 
-use either :class:`bytes` or :class:`str` to represent your intention 
+contain either characters or 8-bit bytes; you can now
+use either :class:`bytes` or :class:`str` to represent your intention
 exactly, and the resulting code will also be correct in Python 3.0.
 
 There's also a ``__future__`` import that causes all string literals
@@ -1834,9 +1834,9 @@
   "/cgi-bin/add.py?category=1".  (Contributed by Alexandre Fiori and
   Nubis; :issue:`1817`.)
 
-  The :func:`parse_qs` and :func:`parse_qsl` functions have been 
+  The :func:`parse_qs` and :func:`parse_qsl` functions have been
   relocated from the :mod:`cgi` module to the :mod:`urlparse` module.
-  The versions still available in the :mod:`cgi` module will 
+  The versions still available in the :mod:`cgi` module will
   trigger :exc:`PendingDeprecationWarning` messages in 2.6
   (:issue:`600362`).
 
@@ -1885,9 +1885,9 @@
      ('id', 'name', 'type', 'size')
 
      >>> var = var_type(1, 'frequency', 'int', 4)
-     >>> print var[0], var.id		# Equivalent
+     >>> print var[0], var.id    # Equivalent
      1 1
-     >>> print var[2], var.type          # Equivalent
+     >>> print var[2], var.type  # Equivalent
      int int
      >>> var._asdict()
      {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
@@ -1931,7 +1931,7 @@
 * A new window method in the :mod:`curses` module,
   :meth:`chgat`, changes the display attributes for a certain number of
   characters on a single line.  (Contributed by Fabian Kreutz.)
-  
+
   ::
 
      # Boldface text starting at y=0,x=21
@@ -2046,8 +2046,8 @@
 
      >>> list(itertools.product([1,2,3], [4,5,6]))
      [(1, 4), (1, 5), (1, 6),
-	  (2, 4), (2, 5), (2, 6),
-	  (3, 4), (3, 5), (3, 6)]
+      (2, 4), (2, 5), (2, 6),
+      (3, 4), (3, 5), (3, 6)]
 
   The optional *repeat* keyword argument is used for taking the
   product of an iterable or a set of iterables with themselves,
@@ -2428,9 +2428,9 @@
   :issue:`742598`, :issue:`1193577`.)
 
 * The :mod:`sqlite3` module, maintained by Gerhard Haering,
-  has been updated from version 2.3.2 in Python 2.5 to 
+  has been updated from version 2.3.2 in Python 2.5 to
   version 2.4.1.
- 
+
 * The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
   using the format character ``'?'``.
   (Contributed by David Remahl.)
@@ -2525,9 +2525,9 @@
   ``with tempfile.NamedTemporaryFile() as tmp: ...``.
   (Contributed by Alexander Belopolsky; :issue:`2021`.)
 
-* The :mod:`test.test_support` module gained a number 
-  of context managers useful for writing tests. 
-  :func:`EnvironmentVarGuard` is a 
+* The :mod:`test.test_support` module gained a number
+  of context managers useful for writing tests.
+  :func:`EnvironmentVarGuard` is a
   context manager that temporarily changes environment variables and
   automatically restores them to their old values.
 
@@ -2542,7 +2542,7 @@
           f = urllib.urlopen('https://sf.net')
           ...
 
-  Finally, :func:`check_warnings` resets the :mod:`warning` module's 
+  Finally, :func:`check_warnings` resets the :mod:`warning` module's
   warning filters and returns an object that will record all warning
   messages triggered (:issue:`3781`)::
 
@@ -2582,7 +2582,7 @@
   :meth:`activeCount` method is renamed to :meth:`active_count`.  Both
   the 2.6 and 3.0 versions of the module support the same properties
   and renamed methods, but don't remove the old methods.  No date has been set
-  for the deprecation of the old APIs in Python 3.x; the old APIs won't 
+  for the deprecation of the old APIs in Python 3.x; the old APIs won't
   be removed in any 2.x version.
   (Carried out by several people, most notably Benjamin Peterson.)
 
@@ -2639,7 +2639,7 @@
   (Added by Facundo Batista.)
 
 * The Unicode database provided by the :mod:`unicodedata` module
-  has been updated to version 5.1.0.  (Updated by 
+  has been updated to version 5.1.0.  (Updated by
   Martin von Loewis; :issue:`3811`.)
 
 * The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
@@ -2650,7 +2650,7 @@
   A new function, :func:`catch_warnings`, is a context manager
   intended for testing purposes that lets you temporarily modify the
   warning filters and then restore their original values (:issue:`3781`).
-  
+
 * The XML-RPC :class:`SimpleXMLRPCServer` and :class:`DocXMLRPCServer`
   classes can now be prevented from immediately opening and binding to
   their socket by passing True as the ``bind_and_activate``
@@ -3213,6 +3213,9 @@
   set ``__hash__ = None`` in their definitions to indicate
   the fact.
 
+* String exceptions have been removed.  Attempting to use them raises a
+  :exc:`TypeError`.
+
 * The :meth:`__init__` method of :class:`collections.deque`
   now clears any existing contents of the deque
   before adding elements from the iterable.  This change makes the
@@ -3220,8 +3223,8 @@
 
 * :meth:`object.__init__` previously accepted arbitrary arguments and
   keyword arguments, ignoring them.  In Python 2.6, this is no longer
-  allowed and will result in a :exc:`TypeError`.  This will affect 
-  :meth:`__init__` methods that end up calling the corresponding 
+  allowed and will result in a :exc:`TypeError`.  This will affect
+  :meth:`__init__` methods that end up calling the corresponding
   method on :class:`object` (perhaps through using :func:`super`).
   See :issue:`1683368` for discussion.
 
@@ -3281,7 +3284,7 @@
 
 The author would like to thank the following people for offering
 suggestions, corrections and assistance with various drafts of this
-article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, 
-Jim Jewett, Kent Johnson, Chris Lambacher,  Martin Michlmayr, 
+article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy,
+Jim Jewett, Kent Johnson, Chris Lambacher,  Martin Michlmayr,
 Antoine Pitrou, Brian Warner.
 

Modified: python/branches/tlee-ast-optimize/Doc/whatsnew/2.7.rst
==============================================================================
--- python/branches/tlee-ast-optimize/Doc/whatsnew/2.7.rst	(original)
+++ python/branches/tlee-ast-optimize/Doc/whatsnew/2.7.rst	Wed Jan 14 13:24:17 2009
@@ -60,13 +60,34 @@
 .. ========================================================================
 
 
+Kristján Valur Jónsson, issue 4293
+Py_AddPendingCall is now thread safe.  This allows any worker thread
+to submit notifications to the python main thread.  This is particularly
+useful for asynchronous IO operations.
+
 
 Other Language Changes
 ======================
 
 Some smaller changes made to the core Python language are:
 
-* List of changes to be written here.
+* The :func:`int` and :func:`long` types gained a ``bit_length``
+  method that returns the number of bits necessary to represent
+  its argument in binary::
+
+      >>> n = 37
+      >>> bin(37)
+      '0b100101'
+      >>> n.bit_length()
+      6
+      >>> n = 2**123-1
+      >>> n.bit_length()
+      123
+      >>> (n+1).bit_length()
+      124
+
+  (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
+
 
 .. ======================================================================
 
@@ -87,7 +108,28 @@
 :file:`Misc/NEWS` file in the source tree for a more complete list of
 changes, or look through the Subversion logs for all the details.
 
-* To be written.
+* A new function in the :mod:`subprocess` module,
+  :func:`check_output`, runs a command with a specified set of arguments
+  and returns the command's output as a string if the command runs without
+  error, or raises a :exc:`CalledProcessError` exception otherwise.
+
+  ::
+
+    >>> subprocess.check_output(['df', '-h', '.'])
+    'Filesystem     Size   Used  Avail Capacity  Mounted on\n
+    /dev/disk0s2    52G    49G   3.0G    94%    /\n'
+
+    >>> subprocess.check_output(['df', '-h', '/bogus'])
+      ...
+    subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
+
+  (Contributed by Gregory P. Smith.)
+
+* It is not mandatory anymore to store clear text passwords in the
+  :file:`.pypirc` file when registering and uploading packages to PyPI. As long
+  as the username is present in that file, the :mod:`distutils` package will
+  prompt for the password if not present.  (Added by tarek, with the initial
+  contribution of Nathan Van Gheem; :issue:`4394`.)
 
 .. ======================================================================
 .. whole new modules get described in subsections here
@@ -100,13 +142,22 @@
 
 Changes to Python's build process and to the C API include:
 
-* To be written.
+* If you use the :file:`.gdbinit` file provided with Python,
+  the "pyo" macro in the 2.7 version will now work when the thread being
+  debugged doesn't hold the GIL; the macro will now acquire it before printing.
+  (Contributed by haypo XXX; :issue:`3632`.)
 
 .. ======================================================================
 
 Port-Specific Changes: Windows
 -----------------------------------
 
+* The :mod:`msvcrt` module now contains some constants from
+  the :file:`crtassem.h` header file:
+  :data:`CRT_ASSEMBLY_VERSION`,
+  :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
+  and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
+  (Added by Martin von Loewis (XXX check); :issue:`4365`.)
 
 .. ======================================================================
 

Modified: python/branches/tlee-ast-optimize/Include/abstract.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/abstract.h	(original)
+++ python/branches/tlee-ast-optimize/Include/abstract.h	Wed Jan 14 13:24:17 2009
@@ -636,7 +636,8 @@
 
 #define PyIter_Check(obj) \
     (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \
-     (obj)->ob_type->tp_iternext != NULL)
+     (obj)->ob_type->tp_iternext != NULL && \
+     (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented)
 
      PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *);
      /* Takes an iterator object and calls its tp_iternext slot,

Modified: python/branches/tlee-ast-optimize/Include/object.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/object.h	(original)
+++ python/branches/tlee-ast-optimize/Include/object.h	Wed Jan 14 13:24:17 2009
@@ -473,6 +473,7 @@
 PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
 PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
+PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
 PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
 					      PyObject *, PyObject *);

Modified: python/branches/tlee-ast-optimize/Include/opcode.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/opcode.h	(original)
+++ python/branches/tlee-ast-optimize/Include/opcode.h	Wed Jan 14 13:24:17 2009
@@ -22,7 +22,6 @@
 
 #define UNARY_INVERT	15
 
-#define LIST_APPEND	18
 #define BINARY_POWER	19
 
 #define BINARY_MULTIPLY	20
@@ -89,6 +88,7 @@
 #define DELETE_NAME	91	/* "" */
 #define UNPACK_SEQUENCE	92	/* Number of sequence items */
 #define FOR_ITER	93
+#define LIST_APPEND	94
 
 #define STORE_ATTR	95	/* Index in name list */
 #define DELETE_ATTR	96	/* "" */

Modified: python/branches/tlee-ast-optimize/Include/pymacconfig.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/pymacconfig.h	(original)
+++ python/branches/tlee-ast-optimize/Include/pymacconfig.h	Wed Jan 14 13:24:17 2009
@@ -15,6 +15,8 @@
 # undef SIZEOF_SIZE_T
 # undef SIZEOF_TIME_T
 # undef SIZEOF_VOID_P
+# undef SIZEOF__BOOL
+# undef WORDS_BIGENDIAN
 
 #    undef VA_LIST_IS_ARRAY
 #    if defined(__LP64__) && defined(__x86_64__)
@@ -28,12 +30,19 @@
 
 #    undef SIZEOF_LONG
 #    ifdef __LP64__
+#	 define SIZEOF__BOOL		1
+#        define SIZEOF__BOOL		1
 #        define SIZEOF_LONG 		8
 #        define SIZEOF_PTHREAD_T 	8
 #        define SIZEOF_SIZE_T 		8
 #        define SIZEOF_TIME_T 		8
 #        define SIZEOF_VOID_P 		8
 #    else
+#        ifdef __ppc__
+#	    define SIZEOF__BOOL		4
+#        else
+#	    define SIZEOF__BOOL		1
+#        endif
 #        define SIZEOF_LONG 		4
 #        define SIZEOF_PTHREAD_T 	4
 #        define SIZEOF_SIZE_T 		4
@@ -54,6 +63,11 @@
 
 #    endif
 
+#ifdef __BIG_ENDIAN__
+#define WORDS_BIGENDIAN 1
+#endif /* __BIG_ENDIAN */
+
+
 #endif /* defined(_APPLE__) */
 
 #endif /* PYMACCONFIG_H */

Modified: python/branches/tlee-ast-optimize/Include/pymath.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/pymath.h	(original)
+++ python/branches/tlee-ast-optimize/Include/pymath.h	Wed Jan 14 13:24:17 2009
@@ -87,7 +87,7 @@
  * Note: PC/pyconfig.h defines Py_IS_NAN as _isnan
  */
 #ifndef Py_IS_NAN
-#ifdef HAVE_ISNAN
+#if defined HAVE_DECL_ISNAN && HAVE_DECL_ISNAN == 1
 #define Py_IS_NAN(X) isnan(X)
 #else
 #define Py_IS_NAN(X) ((X) != (X))
@@ -104,7 +104,7 @@
  * Note: PC/pyconfig.h defines Py_IS_INFINITY as _isinf
  */
 #ifndef Py_IS_INFINITY
-#ifdef HAVE_ISINF
+#if defined HAVE_DECL_ISINF && HAVE_DECL_ISINF == 1
 #define Py_IS_INFINITY(X) isinf(X)
 #else
 #define Py_IS_INFINITY(X) ((X) && (X)*0.5 == (X))
@@ -118,7 +118,9 @@
  * Note: PC/pyconfig.h defines Py_IS_FINITE as _finite
  */
 #ifndef Py_IS_FINITE
-#ifdef HAVE_FINITE
+#if defined HAVE_DECL_ISFINITE && HAVE_DECL_ISFINITE == 1
+#define Py_IS_FINITE(X) isfinite(X)
+#elif defined HAVE_FINITE
 #define Py_IS_FINITE(X) finite(X)
 #else
 #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))

Modified: python/branches/tlee-ast-optimize/Include/pyport.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/pyport.h	(original)
+++ python/branches/tlee-ast-optimize/Include/pyport.h	Wed Jan 14 13:24:17 2009
@@ -709,6 +709,15 @@
 #define Py_FORMAT_PARSETUPLE(func,p1,p2)
 #endif
 
+/*
+ * Specify alignment on compilers that support it.
+ */
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define Py_ALIGNED(x) __attribute__((aligned(x)))
+#else
+#define Py_ALIGNED(x)
+#endif
+
 /* Eliminate end-of-loop code not reached warnings from SunPro C
  * when using do{...}while(0) macros
  */

Modified: python/branches/tlee-ast-optimize/Include/unicodeobject.h
==============================================================================
--- python/branches/tlee-ast-optimize/Include/unicodeobject.h	(original)
+++ python/branches/tlee-ast-optimize/Include/unicodeobject.h	Wed Jan 14 13:24:17 2009
@@ -130,6 +130,10 @@
 typedef unsigned long Py_UCS4; 
 #endif
 
+/* Py_UNICODE is the native Unicode storage format (code unit) used by
+   Python and represents a single Unicode element in the Unicode
+   type. */
+
 typedef PY_UNICODE_TYPE Py_UNICODE;
 
 /* --- UCS-2/UCS-4 Name Mangling ------------------------------------------ */
@@ -153,6 +157,7 @@
 # define PyUnicode_AsUnicode PyUnicodeUCS2_AsUnicode
 # define PyUnicode_AsUnicodeEscapeString PyUnicodeUCS2_AsUnicodeEscapeString
 # define PyUnicode_AsWideChar PyUnicodeUCS2_AsWideChar
+# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist
 # define PyUnicode_Compare PyUnicodeUCS2_Compare
 # define PyUnicode_Concat PyUnicodeUCS2_Concat
 # define PyUnicode_Contains PyUnicodeUCS2_Contains
@@ -182,13 +187,13 @@
 # define PyUnicode_Find PyUnicodeUCS2_Find
 # define PyUnicode_Format PyUnicodeUCS2_Format
 # define PyUnicode_FromEncodedObject PyUnicodeUCS2_FromEncodedObject
+# define PyUnicode_FromFormat PyUnicodeUCS2_FromFormat
+# define PyUnicode_FromFormatV PyUnicodeUCS2_FromFormatV
 # define PyUnicode_FromObject PyUnicodeUCS2_FromObject
 # define PyUnicode_FromOrdinal PyUnicodeUCS2_FromOrdinal
-# define PyUnicode_FromUnicode PyUnicodeUCS2_FromUnicode
 # define PyUnicode_FromString PyUnicodeUCS2_FromString
 # define PyUnicode_FromStringAndSize PyUnicodeUCS2_FromStringAndSize
-# define PyUnicode_FromFormatV PyUnicodeUCS2_FromFormatV
-# define PyUnicode_FromFormat PyUnicodeUCS2_FromFormat
+# define PyUnicode_FromUnicode PyUnicodeUCS2_FromUnicode
 # define PyUnicode_FromWideChar PyUnicodeUCS2_FromWideChar
 # define PyUnicode_GetDefaultEncoding PyUnicodeUCS2_GetDefaultEncoding
 # define PyUnicode_GetMax PyUnicodeUCS2_GetMax
@@ -209,7 +214,6 @@
 # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS2_AsDefaultEncodedString
 # define _PyUnicode_Fini _PyUnicodeUCS2_Fini
 # define _PyUnicode_Init _PyUnicodeUCS2_Init
-# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist
 # define _PyUnicode_IsAlpha _PyUnicodeUCS2_IsAlpha
 # define _PyUnicode_IsDecimalDigit _PyUnicodeUCS2_IsDecimalDigit
 # define _PyUnicode_IsDigit _PyUnicodeUCS2_IsDigit
@@ -240,6 +244,7 @@
 # define PyUnicode_AsUnicode PyUnicodeUCS4_AsUnicode
 # define PyUnicode_AsUnicodeEscapeString PyUnicodeUCS4_AsUnicodeEscapeString
 # define PyUnicode_AsWideChar PyUnicodeUCS4_AsWideChar
+# define PyUnicode_ClearFreeList PyUnicodeUCS4_ClearFreelist
 # define PyUnicode_Compare PyUnicodeUCS4_Compare
 # define PyUnicode_Concat PyUnicodeUCS4_Concat
 # define PyUnicode_Contains PyUnicodeUCS4_Contains
@@ -269,13 +274,13 @@
 # define PyUnicode_Find PyUnicodeUCS4_Find
 # define PyUnicode_Format PyUnicodeUCS4_Format
 # define PyUnicode_FromEncodedObject PyUnicodeUCS4_FromEncodedObject
+# define PyUnicode_FromFormat PyUnicodeUCS4_FromFormat
+# define PyUnicode_FromFormatV PyUnicodeUCS4_FromFormatV
 # define PyUnicode_FromObject PyUnicodeUCS4_FromObject
 # define PyUnicode_FromOrdinal PyUnicodeUCS4_FromOrdinal
-# define PyUnicode_FromUnicode PyUnicodeUCS4_FromUnicode
 # define PyUnicode_FromString PyUnicodeUCS4_FromString
 # define PyUnicode_FromStringAndSize PyUnicodeUCS4_FromStringAndSize
-# define PyUnicode_FromFormatV PyUnicodeUCS4_FromFormatV
-# define PyUnicode_FromFormat PyUnicodeUCS4_FromFormat
+# define PyUnicode_FromUnicode PyUnicodeUCS4_FromUnicode
 # define PyUnicode_FromWideChar PyUnicodeUCS4_FromWideChar
 # define PyUnicode_GetDefaultEncoding PyUnicodeUCS4_GetDefaultEncoding
 # define PyUnicode_GetMax PyUnicodeUCS4_GetMax
@@ -296,7 +301,6 @@
 # define _PyUnicode_AsDefaultEncodedString _PyUnicodeUCS4_AsDefaultEncodedString
 # define _PyUnicode_Fini _PyUnicodeUCS4_Fini
 # define _PyUnicode_Init _PyUnicodeUCS4_Init
-# define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist
 # define _PyUnicode_IsAlpha _PyUnicodeUCS4_IsAlpha
 # define _PyUnicode_IsDecimalDigit _PyUnicodeUCS4_IsDecimalDigit
 # define _PyUnicode_IsDigit _PyUnicodeUCS4_IsDigit
@@ -350,12 +354,12 @@
 
 #else
 
-/* Since splitting on whitespace is an important use case, and whitespace
-   in most situations is solely ASCII whitespace, we optimize for the common
-   case by using a quick look-up table with an inlined check.
- */
-PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
+/* Since splitting on whitespace is an important use case, and
+   whitespace in most situations is solely ASCII whitespace, we
+   optimize for the common case by using a quick look-up table
+   _Py_ascii_whitespace (see below) with an inlined check.
 
+ */
 #define Py_UNICODE_ISSPACE(ch) \
 	((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
 
@@ -389,13 +393,14 @@
 #define Py_UNICODE_COPY(target, source, length)				\
 	Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE))
 
-#define Py_UNICODE_FILL(target, value, length) do\
-    {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\
+#define Py_UNICODE_FILL(target, value, length) \
+    do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\
         for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
     } while (0)
 
-/* check if substring matches at given offset.  the offset must be
+/* Check if substring matches at given offset.  the offset must be
    valid, and the substring must not be empty */
+
 #define Py_UNICODE_MATCH(string, offset, substring) \
     ((*((string)->str + (offset)) == *((substring)->str)) && \
     ((*((string)->str + (offset) + (substring)->length-1) == *((substring)->str + (substring)->length-1))) && \
@@ -405,8 +410,6 @@
 extern "C" {
 #endif
 
-PyAPI_FUNC(int) PyUnicode_ClearFreeList(void);
-
 /* --- Unicode Type ------------------------------------------------------- */
 
 typedef struct {
@@ -605,6 +608,17 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal);
 
+/* --- Free-list management ----------------------------------------------- */
+
+/* Clear the free list used by the Unicode implementation.
+
+   This can be used to release memory used for objects on the free
+   list back to the Python memory allocator.
+
+*/
+
+PyAPI_FUNC(int) PyUnicode_ClearFreeList(void);
+
 /* === Builtin Codecs ===================================================== 
 
    Many of these APIs take two arguments encoding and errors. These
@@ -1323,6 +1337,10 @@
 
 /* === Characters Type APIs =============================================== */
 
+/* Helper array used by Py_UNICODE_ISSPACE(). */
+
+PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
+
 /* These should not be used directly. Use the Py_UNICODE_IS* and
    Py_UNICODE_TO* macros instead. 
 

Modified: python/branches/tlee-ast-optimize/LICENSE
==============================================================================
--- python/branches/tlee-ast-optimize/LICENSE	(original)
+++ python/branches/tlee-ast-optimize/LICENSE	Wed Jan 14 13:24:17 2009
@@ -55,7 +55,10 @@
     2.4.4           2.4.3       2006        PSF         yes
     2.5             2.4         2006        PSF         yes
     2.5.1           2.5         2007        PSF         yes
+    2.5.2           2.5.1       2008        PSF         yes
+    2.5.3           2.5.2       2008        PSF         yes
     2.6             2.5         2008        PSF         yes
+    2.6.1           2.6         2008        PSF         yes
 
 Footnotes:
 
@@ -85,15 +88,14 @@
 otherwise using this software ("Python") in source or binary form and
 its associated documentation.
 
-2. Subject to the terms and conditions of this License Agreement, PSF
-hereby grants Licensee a nonexclusive, royalty-free, world-wide
-license to reproduce, analyze, test, perform and/or display publicly,
-prepare derivative works, distribute, and otherwise use Python
-alone or in any derivative version, provided, however, that PSF's
-License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Python Software Foundation; 
-All Rights Reserved" are retained in Python alone or in any derivative 
-version prepared by Licensee.
+2. Subject to the terms and conditions of this License Agreement, PSF hereby
+grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+analyze, test, perform and/or display publicly, prepare derivative works,
+distribute, and otherwise use Python alone or in any derivative version,
+provided, however, that PSF's License Agreement and PSF's notice of copyright,
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Python
+Software Foundation; All Rights Reserved" are retained in Python alone or in any
+derivative version prepared by Licensee.
 
 3. In the event Licensee prepares a derivative work that is based on
 or incorporates Python or any part thereof, and wants to make

Modified: python/branches/tlee-ast-optimize/Lib/_abcoll.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/_abcoll.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/_abcoll.py	Wed Jan 14 13:24:17 2009
@@ -249,12 +249,12 @@
 
     @abstractmethod
     def add(self, value):
-        """Return True if it was added, False if already there."""
+        """Add an element."""
         raise NotImplementedError
 
     @abstractmethod
     def discard(self, value):
-        """Return True if it was deleted, False if not there."""
+        """Remove an element.  Do not raise an exception if absent."""
         raise NotImplementedError
 
     def remove(self, value):

Modified: python/branches/tlee-ast-optimize/Lib/ast.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/ast.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/ast.py	Wed Jan 14 13:24:17 2009
@@ -69,6 +69,18 @@
                 return _safe_names[node.id]
         elif isinstance(node, Const):
             return node.value
+        elif isinstance(node, BinOp) and \
+             isinstance(node.op, (Add, Sub)) and \
+             isinstance(node.right, Num) and \
+             isinstance(node.right.n, complex) and \
+             isinstance(node.left, Num) and \
+             isinstance(node.left.n, (int, long, float)):
+            left = node.left.n
+            right = node.right.n
+            if isinstance(node.op, Add):
+                return left + right
+            else:
+                return left - right
         raise ValueError('malformed string')
     return _convert(node_or_string)
 

Modified: python/branches/tlee-ast-optimize/Lib/bdb.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/bdb.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/bdb.py	Wed Jan 14 13:24:17 2009
@@ -347,7 +347,7 @@
             rv = frame.f_locals['__return__']
             s = s + '->'
             s = s + repr.repr(rv)
-        line = linecache.getline(filename, lineno)
+        line = linecache.getline(filename, lineno, frame.f_globals)
         if line: s = s + lprefix + line.strip()
         return s
 
@@ -589,7 +589,7 @@
         name = frame.f_code.co_name
         if not name: name = '???'
         fn = self.canonic(frame.f_code.co_filename)
-        line = linecache.getline(fn, frame.f_lineno)
+        line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
         print '+++', fn, frame.f_lineno, name, ':', line.strip()
     def user_return(self, frame, retval):
         print '+++ return', retval

Modified: python/branches/tlee-ast-optimize/Lib/cgi.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/cgi.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/cgi.py	Wed Jan 14 13:24:17 2009
@@ -289,16 +289,28 @@
     return partdict
 
 
+def _parseparam(s):
+    while s[:1] == ';':
+        s = s[1:]
+        end = s.find(';')
+        while end > 0 and s.count('"', 0, end) % 2:
+            end = s.find(';', end + 1)
+        if end < 0:
+            end = len(s)
+        f = s[:end]
+        yield f.strip()
+        s = s[end:]
+
 def parse_header(line):
     """Parse a Content-type like header.
 
     Return the main content-type and a dictionary of options.
 
     """
-    plist = [x.strip() for x in line.split(';')]
-    key = plist.pop(0).lower()
+    parts = _parseparam(';' + line)
+    key = parts.next()
     pdict = {}
-    for p in plist:
+    for p in parts:
         i = p.find('=')
         if i >= 0:
             name = p[:i].strip().lower()

Modified: python/branches/tlee-ast-optimize/Lib/collections.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/collections.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/collections.py	Wed Jan 14 13:24:17 2009
@@ -9,6 +9,11 @@
 from operator import itemgetter as _itemgetter
 from keyword import iskeyword as _iskeyword
 import sys as _sys
+import heapq as _heapq
+from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
+
+########################################################################
+###  namedtuple  #######################################################
 
 def namedtuple(typename, field_names, verbose=False):
     """Returns a new subclass of tuple with named fields.
@@ -108,7 +113,160 @@
     return result
 
 
+########################################################################
+###  Counter  ##########################################################
+
+class Counter(dict):
+    '''Dict subclass for counting hashable items.  Sometimes called a bag
+    or multiset.  Elements are stored as dictionary keys and their counts
+    are stored as dictionary values.
+
+    >>> c = Counter('abracadabra')      # count elements from a string
+
+    >>> c.most_common(3)                # three most common elements
+    [('a', 5), ('r', 2), ('b', 2)]
+    >>> sorted(c)                       # list all unique elements
+    ['a', 'b', 'c', 'd', 'r']
+    >>> ''.join(sorted(c.elements()))   # list elements with repetitions
+    'aaaaabbcdrr'
+    >>> sum(c.values())                 # total of all counts
+    11
 
+    >>> c['a']                          # count of letter 'a'
+    5
+    >>> for elem in 'shazam':           # update counts from an iterable
+    ...     c[elem] += 1                # by adding 1 to each element's count
+    >>> c['a']                          # now there are seven 'a'
+    7
+    >>> del c['r']                      # remove all 'r'
+    >>> c['r']                          # now there are zero 'r'
+    0
+
+    >>> d = Counter('simsalabim')       # make another counter
+    >>> c.update(d)                     # add in the second counter
+    >>> c['a']                          # now there are nine 'a'
+    9
+
+    >>> c.clear()                       # empty the counter
+    >>> c
+    Counter()
+
+    Note:  If a count is set to zero or reduced to zero, it will remain
+    in the counter until the entry is deleted or the counter is cleared:
+
+    >>> c = Counter('aaabbc')
+    >>> c['b'] -= 2                     # reduce the count of 'b' by two
+    >>> c.most_common()                 # 'b' is still in, but its count is zero
+    [('a', 3), ('c', 1), ('b', 0)]
+
+    '''
+    # References:
+    #   http://en.wikipedia.org/wiki/Multiset
+    #   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
+    #   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
+    #   http://code.activestate.com/recipes/259174/
+    #   Knuth, TAOCP Vol. II section 4.6.3
+
+    def __init__(self, iterable=None):
+        '''Create a new, empty Counter object.  And if given, count elements
+        from an input iterable.  Or, initialize the count from another mapping
+        of elements to their counts.
+
+        >>> c = Counter()                           # a new, empty counter
+        >>> c = Counter('gallahad')                 # a new counter from an iterable
+        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
+
+        '''
+        self.update(iterable)
+
+    def __missing__(self, key):
+        'The count of elements not in the Counter is zero.'
+        # Needed so that self[missing_item] does not raise KeyError
+        return 0
+
+    def most_common(self, n=None):
+        '''List the n most common elements and their counts from the most
+        common to the least.  If n is None, then list all element counts.
+
+        >>> Counter('abracadabra').most_common(3)
+        [('a', 5), ('r', 2), ('b', 2)]
+
+        '''
+        # Emulate Bag.sortedByCount from Smalltalk
+        if n is None:
+            return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)
+        return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))
+
+    def elements(self):
+        '''Iterator over elements repeating each as many times as its count.
+
+        >>> c = Counter('ABCABC')
+        >>> sorted(c.elements())
+        ['A', 'A', 'B', 'B', 'C', 'C']
+
+        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
+        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
+        >>> product = 1
+        >>> for factor in prime_factors.elements():     # loop over factors
+        ...     product *= factor                       # and multiply them
+        >>> product
+        1836
+
+        Note, if an element's count has been set to zero or is a negative
+        number, elements() will ignore it.
+
+        '''
+        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
+        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))
+
+    # Override dict methods where necessary
+
+    @classmethod
+    def fromkeys(cls, iterable, v=None):
+        # There is no equivalent method for counters because setting v=1
+        # means that no element can have a count greater than one.
+        raise NotImplementedError(
+            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')
+
+    def update(self, iterable=None):
+        '''Like dict.update() but add counts instead of replacing them.
+
+        Source can be an iterable, a dictionary, or another Counter instance.
+
+        >>> c = Counter('which')
+        >>> c.update('witch')           # add elements from another iterable
+        >>> d = Counter('watch')
+        >>> c.update(d)                 # add elements from another counter
+        >>> c['h']                      # four 'h' in which, witch, and watch
+        4
+
+        '''
+        # The regular dict.update() operation makes no sense here because the
+        # replace behavior results in the some of original untouched counts
+        # being mixed-in with all of the other counts for a mismash that
+        # doesn't have a straight-forward interpretation in most counting
+        # contexts.  Instead, we look to Knuth for suggested operations on
+        # multisets and implement the union-add operation discussed in
+        # TAOCP Volume II section 4.6.3 exercise 19.  The Wikipedia entry for
+        # multisets calls that operation a sum or join.
+
+        if iterable is not None:
+            if isinstance(iterable, Mapping):
+                for elem, count in iterable.iteritems():
+                    self[elem] += count
+            else:
+                for elem in iterable:
+                    self[elem] += 1
+
+    def copy(self):
+        'Like dict.copy() but returns a Counter instance instead of a dict.'
+        return Counter(self)
+
+    def __repr__(self):
+        if not self:
+            return '%s()' % self.__class__.__name__
+        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
+        return '%s({%s})' % (self.__class__.__name__, items)
 
 
 

Modified: python/branches/tlee-ast-optimize/Lib/compiler/misc.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/compiler/misc.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/compiler/misc.py	Wed Jan 14 13:24:17 2009
@@ -14,13 +14,13 @@
     def __len__(self):
         return len(self.elts)
     def __contains__(self, elt):
-        return self.elts.has_key(elt)
+        return elt in self.elts
     def add(self, elt):
         self.elts[elt] = elt
     def elements(self):
         return self.elts.keys()
     def has_elt(self, elt):
-        return self.elts.has_key(elt)
+        return elt in self.elts
     def remove(self, elt):
         del self.elts[elt]
     def copy(self):

Modified: python/branches/tlee-ast-optimize/Lib/compiler/pyassem.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/compiler/pyassem.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/compiler/pyassem.py	Wed Jan 14 13:24:17 2009
@@ -210,7 +210,7 @@
     order = []
     seen[b] = b
     for c in b.get_children():
-        if seen.has_key(c):
+        if c in seen:
             continue
         order = order + dfs_postorder(c, seen)
     order.append(b)
@@ -406,7 +406,7 @@
         seen = {}
 
         def max_depth(b, d):
-            if seen.has_key(b):
+            if b in seen:
                 return d
             seen[b] = 1
             d = d + depth[b]
@@ -482,7 +482,7 @@
         for name in self.cellvars:
             cells[name] = 1
         self.cellvars = [name for name in self.varnames
-                         if cells.has_key(name)]
+                         if name in cells]
         for name in self.cellvars:
             del cells[name]
         self.cellvars = self.cellvars + cells.keys()

Modified: python/branches/tlee-ast-optimize/Lib/compiler/pycodegen.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/compiler/pycodegen.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/compiler/pycodegen.py	Wed Jan 14 13:24:17 2009
@@ -570,16 +570,10 @@
             self.nextBlock(end)
 
     # list comprehensions
-    __list_count = 0
-
     def visitListComp(self, node):
         self.set_lineno(node)
         # setup list
-        tmpname = "$list%d" % self.__list_count
-        self.__list_count = self.__list_count + 1
         self.emit('BUILD_LIST', 0)
-        self.emit('DUP_TOP')
-        self._implicitNameOp('STORE', tmpname)
 
         stack = []
         for i, for_ in zip(range(len(node.quals)), node.quals):
@@ -591,9 +585,8 @@
                 self.visit(if_, cont)
             stack.insert(0, (start, cont, anchor))
 
-        self._implicitNameOp('LOAD', tmpname)
         self.visit(node.expr)
-        self.emit('LIST_APPEND')
+        self.emit('LIST_APPEND', len(node.quals) + 1)
 
         for start, cont, anchor in stack:
             if cont:
@@ -604,9 +597,6 @@
                 self.nextBlock(skip_one)
             self.emit('JUMP_ABSOLUTE', start)
             self.startBlock(anchor)
-        self._implicitNameOp('DELETE', tmpname)
-
-        self.__list_count = self.__list_count - 1
 
     def visitListCompFor(self, node):
         start = self.newBlock()

Modified: python/branches/tlee-ast-optimize/Lib/compiler/symbols.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/compiler/symbols.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/compiler/symbols.py	Wed Jan 14 13:24:17 2009
@@ -49,9 +49,9 @@
 
     def add_global(self, name):
         name = self.mangle(name)
-        if self.uses.has_key(name) or self.defs.has_key(name):
+        if name in self.uses or name in self.defs:
             pass # XXX warn about global following def/use
-        if self.params.has_key(name):
+        if name in self.params:
             raise SyntaxError, "%s in %s is global and parameter" % \
                   (name, self.name)
         self.globals[name] = 1
@@ -88,14 +88,13 @@
 
         The scope of a name could be LOCAL, GLOBAL, FREE, or CELL.
         """
-        if self.globals.has_key(name):
+        if name in self.globals:
             return SC_GLOBAL
-        if self.cells.has_key(name):
+        if name in self.cells:
             return SC_CELL
-        if self.defs.has_key(name):
+        if name in self.defs:
             return SC_LOCAL
-        if self.nested and (self.frees.has_key(name) or
-                            self.uses.has_key(name)):
+        if self.nested and (name in self.frees or name in self.uses):
             return SC_FREE
         if self.nested:
             return SC_UNKNOWN
@@ -108,8 +107,7 @@
         free = {}
         free.update(self.frees)
         for name in self.uses.keys():
-            if not (self.defs.has_key(name) or
-                    self.globals.has_key(name)):
+            if name not in self.defs and name not in self.globals:
                 free[name] = 1
         return free.keys()
 
@@ -134,7 +132,7 @@
         free.
         """
         self.globals[name] = 1
-        if self.frees.has_key(name):
+        if name in self.frees:
             del self.frees[name]
         for child in self.children:
             if child.check_name(name) == SC_FREE:

Modified: python/branches/tlee-ast-optimize/Lib/compiler/transformer.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/compiler/transformer.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/compiler/transformer.py	Wed Jan 14 13:24:17 2009
@@ -81,7 +81,7 @@
 
 def Node(*args):
     kind = args[0]
-    if nodes.has_key(kind):
+    if kind in nodes:
         try:
             return nodes[kind](*args[1:])
         except TypeError:
@@ -120,7 +120,7 @@
     def transform(self, tree):
         """Transform an AST into a modified parse tree."""
         if not (isinstance(tree, tuple) or isinstance(tree, list)):
-            tree = parser.ast2tuple(tree, line_info=1)
+            tree = parser.st2tuple(tree, line_info=1)
         return self.compile_node(tree)
 
     def parsesuite(self, text):

Modified: python/branches/tlee-ast-optimize/Lib/compiler/visitor.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/compiler/visitor.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/compiler/visitor.py	Wed Jan 14 13:24:17 2009
@@ -84,7 +84,7 @@
             meth(node, *args)
         elif self.VERBOSE > 0:
             klass = node.__class__
-            if not self.examples.has_key(klass):
+            if klass not in self.examples:
                 self.examples[klass] = klass
                 print
                 print self.visitor

Modified: python/branches/tlee-ast-optimize/Lib/ctypes/test/__init__.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/ctypes/test/__init__.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/ctypes/test/__init__.py	Wed Jan 14 13:24:17 2009
@@ -67,9 +67,6 @@
             if verbosity > 1:
                 print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
             continue
-        except Exception, detail:
-            print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail)
-            continue
         for name in dir(mod):
             if name.startswith("_"):
                 continue

Modified: python/branches/tlee-ast-optimize/Lib/ctypes/util.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/ctypes/util.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/ctypes/util.py	Wed Jan 14 13:24:17 2009
@@ -92,18 +92,20 @@
         expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
         fdout, ccout = tempfile.mkstemp()
         os.close(fdout)
-        cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \
+        cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; elif type cc >/dev/null 2>&1; then CC=cc;else exit 10; fi;' \
               '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name
         try:
             f = os.popen(cmd)
             trace = f.read()
-            f.close()
+            rv = f.close()
         finally:
             try:
                 os.unlink(ccout)
             except OSError, e:
                 if e.errno != errno.ENOENT:
                     raise
+        if rv == 10:
+            raise OSError, 'gcc or cc command not found'
         res = re.search(expr, trace)
         if not res:
             return None
@@ -125,7 +127,13 @@
             # assuming GNU binutils / ELF
             if not f:
                 return None
-            cmd = "objdump -p -j .dynamic 2>/dev/null " + f
+            cmd = 'if ! type objdump >/dev/null 2>&1; then exit 10; fi;' \
+                  "objdump -p -j .dynamic 2>/dev/null " + f
+            f = os.popen(cmd)
+            dump = f.read()
+            rv = f.close()
+            if rv == 10:
+                raise OSError, 'objdump command not found'
             res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read())
             if not res:
                 return None
@@ -171,8 +179,32 @@
                     return None
             return res.group(0)
 
+        def _findSoname_ldconfig(name):
+            import struct
+            if struct.calcsize('l') == 4:
+                machine = os.uname()[4] + '-32'
+            else:
+                machine = os.uname()[4] + '-64'
+            mach_map = {
+                'x86_64-64': 'libc6,x86-64',
+                'ppc64-64': 'libc6,64bit',
+                'sparc64-64': 'libc6,64bit',
+                's390x-64': 'libc6,64bit',
+                'ia64-64': 'libc6,IA-64',
+                }
+            abi_type = mach_map.get(machine, 'libc6')
+
+            # XXX assuming GLIBC's ldconfig (with option -p)
+            expr = r'(\S+)\s+\((%s(?:, OS ABI:[^\)]*)?)\)[^/]*(/[^\(\)\s]*lib%s\.[^\(\)\s]*)' \
+                   % (abi_type, re.escape(name))
+            res = re.search(expr,
+                            os.popen('/sbin/ldconfig -p 2>/dev/null').read())
+            if not res:
+                return None
+            return res.group(1)
+
         def find_library(name):
-            return _get_soname(_findLib_ldconfig(name) or _findLib_gcc(name))
+            return _findSoname_ldconfig(name) or _get_soname(_findLib_gcc(name))
 
 ################################################################
 # test code

Modified: python/branches/tlee-ast-optimize/Lib/decimal.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/decimal.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/decimal.py	Wed Jan 14 13:24:17 2009
@@ -135,6 +135,7 @@
 ]
 
 import copy as _copy
+import math as _math
 
 try:
     from collections import namedtuple as _namedtuple
@@ -216,7 +217,7 @@
         if args:
             ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
             return ans._fix_nan(context)
-        return NaN
+        return _NaN
 
 class ConversionSyntax(InvalidOperation):
     """Trying to convert badly formed string.
@@ -226,7 +227,7 @@
     syntax.  The result is [0,qNaN].
     """
     def handle(self, context, *args):
-        return NaN
+        return _NaN
 
 class DivisionByZero(DecimalException, ZeroDivisionError):
     """Division by 0.
@@ -242,7 +243,7 @@
     """
 
     def handle(self, context, sign, *args):
-        return Infsign[sign]
+        return _SignedInfinity[sign]
 
 class DivisionImpossible(InvalidOperation):
     """Cannot perform the division adequately.
@@ -253,7 +254,7 @@
     """
 
     def handle(self, context, *args):
-        return NaN
+        return _NaN
 
 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
     """Undefined result of division.
@@ -264,7 +265,7 @@
     """
 
     def handle(self, context, *args):
-        return NaN
+        return _NaN
 
 class Inexact(DecimalException):
     """Had to round, losing information.
@@ -290,7 +291,7 @@
     """
 
     def handle(self, context, *args):
-        return NaN
+        return _NaN
 
 class Rounded(DecimalException):
     """Number got rounded (not  necessarily changed during rounding).
@@ -340,15 +341,15 @@
     def handle(self, context, sign, *args):
         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
                                 ROUND_HALF_DOWN, ROUND_UP):
-            return Infsign[sign]
+            return _SignedInfinity[sign]
         if sign == 0:
             if context.rounding == ROUND_CEILING:
-                return Infsign[sign]
+                return _SignedInfinity[sign]
             return _dec_from_triple(sign, '9'*context.prec,
                             context.Emax-context.prec+1)
         if sign == 1:
             if context.rounding == ROUND_FLOOR:
-                return Infsign[sign]
+                return _SignedInfinity[sign]
             return _dec_from_triple(sign, '9'*context.prec,
                              context.Emax-context.prec+1)
 
@@ -653,6 +654,46 @@
 
         raise TypeError("Cannot convert %r to Decimal" % value)
 
+    # @classmethod, but @decorator is not valid Python 2.3 syntax, so
+    # don't use it (see notes on Py2.3 compatibility at top of file)
+    def from_float(cls, f):
+        """Converts a float to a decimal number, exactly.
+
+        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
+        Since 0.1 is not exactly representable in binary floating point, the
+        value is stored as the nearest representable value which is
+        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
+        is 0.1000000000000000055511151231257827021181583404541015625.
+
+        >>> Decimal.from_float(0.1)
+        Decimal('0.1000000000000000055511151231257827021181583404541015625')
+        >>> Decimal.from_float(float('nan'))
+        Decimal('NaN')
+        >>> Decimal.from_float(float('inf'))
+        Decimal('Infinity')
+        >>> Decimal.from_float(-float('inf'))
+        Decimal('-Infinity')
+        >>> Decimal.from_float(-0.0)
+        Decimal('-0')
+
+        """
+        if isinstance(f, (int, long)):        # handle integer inputs
+            return cls(f)
+        if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
+            return cls(repr(f))
+        if _math.copysign(1.0, f) == 1.0:
+            sign = 0
+        else:
+            sign = 1
+        n, d = abs(f).as_integer_ratio()
+        k = d.bit_length() - 1
+        result = _dec_from_triple(sign, str(n*5**k), -k)
+        if cls is Decimal:
+            return result
+        else:
+            return cls(result)
+    from_float = classmethod(from_float)
+
     def _isnan(self):
         """Returns whether the number is not actually one.
 
@@ -1171,12 +1212,12 @@
             if self._isinfinity():
                 if not other:
                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
-                return Infsign[resultsign]
+                return _SignedInfinity[resultsign]
 
             if other._isinfinity():
                 if not self:
                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
-                return Infsign[resultsign]
+                return _SignedInfinity[resultsign]
 
         resultexp = self._exp + other._exp
 
@@ -1226,7 +1267,7 @@
                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
 
             if self._isinfinity():
-                return Infsign[sign]
+                return _SignedInfinity[sign]
 
             if other._isinfinity():
                 context._raise_error(Clamped, 'Division by infinity')
@@ -1329,7 +1370,7 @@
                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
                 return ans, ans
             else:
-                return (Infsign[sign],
+                return (_SignedInfinity[sign],
                         context._raise_error(InvalidOperation, 'INF % x'))
 
         if not other:
@@ -1477,7 +1518,7 @@
             if other._isinfinity():
                 return context._raise_error(InvalidOperation, 'INF // INF')
             else:
-                return Infsign[self._sign ^ other._sign]
+                return _SignedInfinity[self._sign ^ other._sign]
 
         if not other:
             if self:
@@ -1515,13 +1556,13 @@
 
     __trunc__ = __int__
 
-    @property
     def real(self):
         return self
+    real = property(real)
 
-    @property
     def imag(self):
         return Decimal(0)
+    imag = property(imag)
 
     def conjugate(self):
         return self
@@ -1732,12 +1773,12 @@
                 if not other:
                     return context._raise_error(InvalidOperation,
                                                 'INF * 0 in fma')
-                product = Infsign[self._sign ^ other._sign]
+                product = _SignedInfinity[self._sign ^ other._sign]
             elif other._exp == 'F':
                 if not self:
                     return context._raise_error(InvalidOperation,
                                                 '0 * INF in fma')
-                product = Infsign[self._sign ^ other._sign]
+                product = _SignedInfinity[self._sign ^ other._sign]
         else:
             product = _dec_from_triple(self._sign ^ other._sign,
                                        str(int(self._int) * int(other._int)),
@@ -2087,7 +2128,7 @@
             if not self:
                 return context._raise_error(InvalidOperation, '0 ** 0')
             else:
-                return Dec_p1
+                return _One
 
         # result has sign 1 iff self._sign is 1 and other is an odd integer
         result_sign = 0
@@ -2109,19 +2150,19 @@
             if other._sign == 0:
                 return _dec_from_triple(result_sign, '0', 0)
             else:
-                return Infsign[result_sign]
+                return _SignedInfinity[result_sign]
 
         # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
         if self._isinfinity():
             if other._sign == 0:
-                return Infsign[result_sign]
+                return _SignedInfinity[result_sign]
             else:
                 return _dec_from_triple(result_sign, '0', 0)
 
         # 1**other = 1, but the choice of exponent and the flags
         # depend on the exponent of self, and on whether other is a
         # positive integer, a negative integer, or neither
-        if self == Dec_p1:
+        if self == _One:
             if other._isinteger():
                 # exp = max(self._exp*max(int(other), 0),
                 # 1-context.prec) but evaluating int(other) directly
@@ -2154,7 +2195,7 @@
             if (other._sign == 0) == (self_adj < 0):
                 return _dec_from_triple(result_sign, '0', 0)
             else:
-                return Infsign[result_sign]
+                return _SignedInfinity[result_sign]
 
         # from here on, the result always goes through the call
         # to _fix at the end of this function.
@@ -2563,10 +2604,10 @@
             sn = self._isnan()
             on = other._isnan()
             if sn or on:
-                if on == 1 and sn != 2:
-                    return self._fix_nan(context)
-                if sn == 1 and on != 2:
-                    return other._fix_nan(context)
+                if on == 1 and sn == 0:
+                    return self._fix(context)
+                if sn == 1 and on == 0:
+                    return other._fix(context)
                 return self._check_nans(other, context)
 
         c = self._cmp(other)
@@ -2605,10 +2646,10 @@
             sn = self._isnan()
             on = other._isnan()
             if sn or on:
-                if on == 1 and sn != 2:
-                    return self._fix_nan(context)
-                if sn == 1 and on != 2:
-                    return other._fix_nan(context)
+                if on == 1 and sn == 0:
+                    return self._fix(context)
+                if sn == 1 and on == 0:
+                    return other._fix(context)
                 return self._check_nans(other, context)
 
         c = self._cmp(other)
@@ -2674,9 +2715,9 @@
         """
         # if one is negative and the other is positive, it's easy
         if self._sign and not other._sign:
-            return Dec_n1
+            return _NegativeOne
         if not self._sign and other._sign:
-            return Dec_p1
+            return _One
         sign = self._sign
 
         # let's handle both NaN types
@@ -2686,51 +2727,51 @@
             if self_nan == other_nan:
                 if self._int < other._int:
                     if sign:
-                        return Dec_p1
+                        return _One
                     else:
-                        return Dec_n1
+                        return _NegativeOne
                 if self._int > other._int:
                     if sign:
-                        return Dec_n1
+                        return _NegativeOne
                     else:
-                        return Dec_p1
-                return Dec_0
+                        return _One
+                return _Zero
 
             if sign:
                 if self_nan == 1:
-                    return Dec_n1
+                    return _NegativeOne
                 if other_nan == 1:
-                    return Dec_p1
+                    return _One
                 if self_nan == 2:
-                    return Dec_n1
+                    return _NegativeOne
                 if other_nan == 2:
-                    return Dec_p1
+                    return _One
             else:
                 if self_nan == 1:
-                    return Dec_p1
+                    return _One
                 if other_nan == 1:
-                    return Dec_n1
+                    return _NegativeOne
                 if self_nan == 2:
-                    return Dec_p1
+                    return _One
                 if other_nan == 2:
-                    return Dec_n1
+                    return _NegativeOne
 
         if self < other:
-            return Dec_n1
+            return _NegativeOne
         if self > other:
-            return Dec_p1
+            return _One
 
         if self._exp < other._exp:
             if sign:
-                return Dec_p1
+                return _One
             else:
-                return Dec_n1
+                return _NegativeOne
         if self._exp > other._exp:
             if sign:
-                return Dec_n1
+                return _NegativeOne
             else:
-                return Dec_p1
-        return Dec_0
+                return _One
+        return _Zero
 
 
     def compare_total_mag(self, other):
@@ -2771,11 +2812,11 @@
 
         # exp(-Infinity) = 0
         if self._isinfinity() == -1:
-            return Dec_0
+            return _Zero
 
         # exp(0) = 1
         if not self:
-            return Dec_p1
+            return _One
 
         # exp(Infinity) = Infinity
         if self._isinfinity() == 1:
@@ -2927,15 +2968,15 @@
 
         # ln(0.0) == -Infinity
         if not self:
-            return negInf
+            return _NegativeInfinity
 
         # ln(Infinity) = Infinity
         if self._isinfinity() == 1:
-            return Inf
+            return _Infinity
 
         # ln(1.0) == 0.0
-        if self == Dec_p1:
-            return Dec_0
+        if self == _One:
+            return _Zero
 
         # ln(negative) raises InvalidOperation
         if self._sign == 1:
@@ -3007,11 +3048,11 @@
 
         # log10(0.0) == -Infinity
         if not self:
-            return negInf
+            return _NegativeInfinity
 
         # log10(Infinity) = Infinity
         if self._isinfinity() == 1:
-            return Inf
+            return _Infinity
 
         # log10(negative or -Infinity) raises InvalidOperation
         if self._sign == 1:
@@ -3063,7 +3104,7 @@
 
         # logb(+/-Inf) = +Inf
         if self._isinfinity():
-            return Inf
+            return _Infinity
 
         # logb(0) = -Inf, DivisionByZero
         if not self:
@@ -3133,7 +3174,7 @@
         (opa, opb) = self._fill_logical(context, self._int, other._int)
 
         # make the operation, and clean starting zeroes
-        result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
+        result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
 
     def logical_xor(self, other, context=None):
@@ -3147,7 +3188,7 @@
         (opa, opb) = self._fill_logical(context, self._int, other._int)
 
         # make the operation, and clean starting zeroes
-        result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
+        result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
 
     def max_mag(self, other, context=None):
@@ -3163,10 +3204,10 @@
             sn = self._isnan()
             on = other._isnan()
             if sn or on:
-                if on == 1 and sn != 2:
-                    return self._fix_nan(context)
-                if sn == 1 and on != 2:
-                    return other._fix_nan(context)
+                if on == 1 and sn == 0:
+                    return self._fix(context)
+                if sn == 1 and on == 0:
+                    return other._fix(context)
                 return self._check_nans(other, context)
 
         c = self.copy_abs()._cmp(other.copy_abs())
@@ -3193,10 +3234,10 @@
             sn = self._isnan()
             on = other._isnan()
             if sn or on:
-                if on == 1 and sn != 2:
-                    return self._fix_nan(context)
-                if sn == 1 and on != 2:
-                    return other._fix_nan(context)
+                if on == 1 and sn == 0:
+                    return self._fix(context)
+                if sn == 1 and on == 0:
+                    return other._fix(context)
                 return self._check_nans(other, context)
 
         c = self.copy_abs()._cmp(other.copy_abs())
@@ -3220,7 +3261,7 @@
             return ans
 
         if self._isinfinity() == -1:
-            return negInf
+            return _NegativeInfinity
         if self._isinfinity() == 1:
             return _dec_from_triple(0, '9'*context.prec, context.Etop())
 
@@ -3243,7 +3284,7 @@
             return ans
 
         if self._isinfinity() == 1:
-            return Inf
+            return _Infinity
         if self._isinfinity() == -1:
             return _dec_from_triple(1, '9'*context.prec, context.Etop())
 
@@ -3744,6 +3785,23 @@
                                      "diagnostic info too long in NaN")
         return d._fix(self)
 
+    def create_decimal_from_float(self, f):
+        """Creates a new Decimal instance from a float but rounding using self
+        as the context.
+
+        >>> context = Context(prec=5, rounding=ROUND_DOWN)
+        >>> context.create_decimal_from_float(3.1415926535897932)
+        Decimal('3.1415')
+        >>> context = Context(prec=5, traps=[Inexact])
+        >>> context.create_decimal_from_float(3.1415926535897932)
+        Traceback (most recent call last):
+            ...
+        Inexact: None
+
+        """
+        d = Decimal.from_float(f)       # An exact conversion
+        return d._fix(self)             # Apply the context rounding
+
     # Methods
     def abs(self, a):
         """Returns the absolute value of the operand.
@@ -5490,15 +5548,15 @@
 ##### Useful Constants (internal use only) ################################
 
 # Reusable defaults
-Inf = Decimal('Inf')
-negInf = Decimal('-Inf')
-NaN = Decimal('NaN')
-Dec_0 = Decimal(0)
-Dec_p1 = Decimal(1)
-Dec_n1 = Decimal(-1)
+_Infinity = Decimal('Inf')
+_NegativeInfinity = Decimal('-Inf')
+_NaN = Decimal('NaN')
+_Zero = Decimal(0)
+_One = Decimal(1)
+_NegativeOne = Decimal(-1)
 
-# Infsign[sign] is infinity w/ that sign
-Infsign = (Inf, negInf)
+# _SignedInfinity[sign] is infinity w/ that sign
+_SignedInfinity = (_Infinity, _NegativeInfinity)
 
 
 

Modified: python/branches/tlee-ast-optimize/Lib/dis.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/dis.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/dis.py	Wed Jan 14 13:24:17 2009
@@ -6,7 +6,8 @@
 from opcode import *
 from opcode import __all__ as _opcodes_all
 
-__all__ = ["dis","disassemble","distb","disco"] + _opcodes_all
+__all__ = ["dis", "disassemble", "distb", "disco",
+           "findlinestarts", "findlabels"] + _opcodes_all
 del _opcodes_all
 
 def dis(x=None):

Modified: python/branches/tlee-ast-optimize/Lib/distutils/ccompiler.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/ccompiler.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/ccompiler.py	Wed Jan 14 13:24:17 2009
@@ -1041,7 +1041,7 @@
         return move_file (src, dst, dry_run=self.dry_run)
 
     def mkpath (self, name, mode=0777):
-        mkpath (name, mode, self.dry_run)
+        mkpath (name, mode, dry_run=self.dry_run)
 
 
 # class CCompiler

Modified: python/branches/tlee-ast-optimize/Lib/distutils/command/register.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/command/register.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/command/register.py	Wed Jan 14 13:24:17 2009
@@ -141,12 +141,14 @@
         # get the user's login info
         choices = '1 2 3 4'.split()
         while choice not in choices:
-            print '''We need to know who you are, so please choose either:
+            self.announce('''\
+We need to know who you are, so please choose either:
  1. use your existing login,
  2. register as a new user,
  3. have the server generate a new password for you (and email it to you), or
  4. quit
-Your selection [default 1]: ''',
+Your selection [default 1]: ''', log.INFO)
+
             choice = raw_input()
             if not choice:
                 choice = '1'
@@ -167,19 +169,27 @@
             # send the info to the server and report the result
             code, result = self.post_to_server(self.build_post_data('submit'),
                 auth)
-            print 'Server response (%s): %s' % (code, result)
+            self.announce('Server response (%s): %s' % (code, result),
+                          log.INFO)
 
             # possibly save the login
-            if not self.has_config and code == 200:
-                print 'I can store your PyPI login so future submissions will be faster.'
-                print '(the login will be stored in %s)' % self._get_rc_file()
-                choice = 'X'
-                while choice.lower() not in 'yn':
-                    choice = raw_input('Save your login (y/N)?')
-                    if not choice:
-                        choice = 'n'
-                if choice.lower() == 'y':
-                    self._store_pypirc(username, password)
+            if code == 200:
+                if self.has_config:
+                    # sharing the password in the distribution instance
+                    # so the upload command can reuse it
+                    self.distribution.password = password
+                else:
+                    self.announce(('I can store your PyPI login so future '
+                                   'submissions will be faster.'), log.INFO)
+                    self.announce('(the login will be stored in %s)' % \
+                                  self._get_rc_file(), log.INFO)
+                    choice = 'X'
+                    while choice.lower() not in 'yn':
+                        choice = raw_input('Save your login (y/N)?')
+                        if not choice:
+                            choice = 'n'
+                    if choice.lower() == 'y':
+                        self._store_pypirc(username, password)
 
         elif choice == '2':
             data = {':action': 'user'}

Modified: python/branches/tlee-ast-optimize/Lib/distutils/command/sdist.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/command/sdist.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/command/sdist.py	Wed Jan 14 13:24:17 2009
@@ -7,6 +7,7 @@
 __revision__ = "$Id$"
 
 import os, string
+import sys
 from types import *
 from glob import glob
 from distutils.core import Command
@@ -354,8 +355,18 @@
 
         self.filelist.exclude_pattern(None, prefix=build.build_base)
         self.filelist.exclude_pattern(None, prefix=base_dir)
-        self.filelist.exclude_pattern(r'(^|/)(RCS|CVS|\.svn|\.hg|\.git|\.bzr|_darcs)/.*', is_regex=1)
 
+        # pruning out vcs directories
+        # both separators are used under win32
+        if sys.platform == 'win32':
+            seps = r'/|\\'
+        else:
+            seps = '/'
+
+        vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
+                    '_darcs']
+        vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
+        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
 
     def write_manifest (self):
         """Write the file list in 'self.filelist' (presumably as filled in

Modified: python/branches/tlee-ast-optimize/Lib/distutils/command/upload.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/command/upload.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/command/upload.py	Wed Jan 14 13:24:17 2009
@@ -50,6 +50,11 @@
             self.repository = config['repository']
             self.realm = config['realm']
 
+        # getting the password from the distribution
+        # if previously set by the register command
+        if not self.password and self.distribution.password:
+            self.password = self.distribution.password
+
     def run(self):
         if not self.distribution.dist_files:
             raise DistutilsOptionError("No dist file created in earlier command")

Modified: python/branches/tlee-ast-optimize/Lib/distutils/config.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/config.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/config.py	Wed Jan 14 13:24:17 2009
@@ -10,8 +10,8 @@
 from distutils.cmd import Command
 
 DEFAULT_PYPIRC = """\
-[pypirc]
-servers =
+[distutils]
+index-servers =
     pypi
 
 [pypi]
@@ -82,12 +82,12 @@
                 for server in _servers:
                     current = {'server': server}
                     current['username'] = config.get(server, 'username')
-                    current['password'] = config.get(server, 'password')
 
                     # optional params
                     for key, default in (('repository',
                                           self.DEFAULT_REPOSITORY),
-                                         ('realm', self.DEFAULT_REALM)):
+                                         ('realm', self.DEFAULT_REALM),
+                                         ('password', None)):
                         if config.has_option(server, key):
                             current[key] = config.get(server, key)
                         else:

Modified: python/branches/tlee-ast-optimize/Lib/distutils/dist.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/dist.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/dist.py	Wed Jan 14 13:24:17 2009
@@ -206,6 +206,7 @@
         self.extra_path = None
         self.scripts = None
         self.data_files = None
+        self.password = ''
 
         # And now initialize bookkeeping stuff that can't be supplied by
         # the caller at all.  'command_obj' maps command names to
@@ -235,7 +236,7 @@
             # command options will override any supplied redundantly
             # through the general options dictionary.
             options = attrs.get('options')
-            if options:
+            if options is not None:
                 del attrs['options']
                 for (command, cmd_options) in options.items():
                     opt_dict = self.get_option_dict(command)

Modified: python/branches/tlee-ast-optimize/Lib/distutils/msvc9compiler.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/msvc9compiler.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/msvc9compiler.py	Wed Jan 14 13:24:17 2009
@@ -247,7 +247,7 @@
     result = {}
 
     if vcvarsall is None:
-        raise IOError("Unable to find vcvarsall.bat")
+        raise DistutilsPlatformError("Unable to find vcvarsall.bat")
     log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version)
     popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch),
                              stdout=subprocess.PIPE,
@@ -255,7 +255,7 @@
 
     stdout, stderr = popen.communicate()
     if popen.wait() != 0:
-        raise IOError(stderr.decode("mbcs"))
+        raise DistutilsPlatformError(stderr.decode("mbcs"))
 
     stdout = stdout.decode("mbcs")
     for line in stdout.split("\n"):

Modified: python/branches/tlee-ast-optimize/Lib/distutils/tests/test_config.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/tests/test_config.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/tests/test_config.py	Wed Jan 14 13:24:17 2009
@@ -5,6 +5,8 @@
 
 from distutils.core import PyPIRCCommand
 from distutils.core import Distribution
+from distutils.log import set_threshold
+from distutils.log import WARN
 
 from distutils.tests import support
 
@@ -32,6 +34,17 @@
 password:secret
 """
 
+WANTED = """\
+[distutils]
+index-servers =
+    pypi
+
+[pypi]
+username:tarek
+password:xxx
+"""
+
+
 class PyPIRCCommandTestCase(support.TempdirManager, unittest.TestCase):
 
     def setUp(self):
@@ -53,6 +66,7 @@
             finalize_options = initialize_options
 
         self._cmd = command
+        self.old_threshold = set_threshold(WARN)
 
     def tearDown(self):
         """Removes the patch."""
@@ -62,6 +76,7 @@
             os.environ['HOME'] = self._old_home
         if os.path.exists(self.rc):
             os.remove(self.rc)
+        set_threshold(self.old_threshold)
 
     def test_server_registration(self):
         # This test makes sure PyPIRCCommand knows how to:
@@ -98,6 +113,20 @@
                   ('server', 'server-login'), ('username', 'tarek')]
         self.assertEquals(config, waited)
 
+    def test_server_empty_registration(self):
+
+        cmd = self._cmd(self.dist)
+        rc = cmd._get_rc_file()
+        self.assert_(not os.path.exists(rc))
+
+        cmd._store_pypirc('tarek', 'xxx')
+
+        self.assert_(os.path.exists(rc))
+        content = open(rc).read()
+
+        self.assertEquals(content, WANTED)
+
+
 def test_suite():
     return unittest.makeSuite(PyPIRCCommandTestCase)
 

Modified: python/branches/tlee-ast-optimize/Lib/distutils/tests/test_dist.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/tests/test_dist.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/tests/test_dist.py	Wed Jan 14 13:24:17 2009
@@ -8,6 +8,7 @@
 import StringIO
 import sys
 import unittest
+import warnings
 
 from test.test_support import TESTFN
 
@@ -131,6 +132,29 @@
             if os.path.exists(my_file):
                 os.remove(my_file)
 
+    def test_empty_options(self):
+        # an empty options dictionary should not stay in the
+        # list of attributes
+        klass = distutils.dist.Distribution
+
+        # catching warnings
+        warns = []
+        def _warn(msg):
+            warns.append(msg)
+
+        old_warn = warnings.warn
+        warnings.warn = _warn
+        try:
+            dist = klass(attrs={'author': 'xxx',
+                                'name': 'xxx',
+                                'version': 'xxx',
+                                'url': 'xxxx',
+                                'options': {}})
+        finally:
+            warnings.warn = old_warn
+
+        self.assertEquals(len(warns), 0)
+
 class MetadataTestCase(unittest.TestCase):
 
     def test_simple_metadata(self):

Modified: python/branches/tlee-ast-optimize/Lib/distutils/tests/test_upload.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/tests/test_upload.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/tests/test_upload.py	Wed Jan 14 13:24:17 2009
@@ -9,6 +9,17 @@
 from distutils.tests import support
 from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase
 
+PYPIRC_NOPASSWORD = """\
+[distutils]
+
+index-servers =
+    server1
+
+[server1]
+username:me
+"""
+
+
 class uploadTestCase(PyPIRCCommandTestCase):
 
     def test_finalize_options(self):
@@ -26,6 +37,24 @@
                              ('repository', 'http://pypi.python.org/pypi')):
             self.assertEquals(getattr(cmd, attr), waited)
 
+    def test_saved_password(self):
+        # file with no password
+        f = open(self.rc, 'w')
+        f.write(PYPIRC_NOPASSWORD)
+        f.close()
+
+        # make sure it passes
+        dist = Distribution()
+        cmd = upload(dist)
+        cmd.finalize_options()
+        self.assertEquals(cmd.password, None)
+
+        # make sure we get it as well, if another command
+        # initialized it at the dist level
+        dist.password = 'xxx'
+        cmd = upload(dist)
+        cmd.finalize_options()
+        self.assertEquals(cmd.password, 'xxx')
 
 def test_suite():
     return unittest.makeSuite(uploadTestCase)

Modified: python/branches/tlee-ast-optimize/Lib/distutils/util.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/distutils/util.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/distutils/util.py	Wed Jan 14 13:24:17 2009
@@ -100,7 +100,11 @@
         if not macver:
             macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
 
-        if not macver:
+        if 1:
+            # Always calculate the release of the running machine,
+            # needed to determine if we can build fat binaries or not.
+
+            macrelease = macver
             # Get the system version. Reading this plist is a documented
             # way to get the system version (see the documentation for
             # the Gestalt Manager)
@@ -116,16 +120,18 @@
                         r'<string>(.*?)</string>', f.read())
                 f.close()
                 if m is not None:
-                    macver = '.'.join(m.group(1).split('.')[:2])
+                    macrelease = '.'.join(m.group(1).split('.')[:2])
                 # else: fall back to the default behaviour
 
+        if not macver:
+            macver = macrelease
+
         if macver:
             from distutils.sysconfig import get_config_vars
             release = macver
             osname = "macosx"
 
-
-            if (release + '.') >= '10.4.' and \
+            if (macrelease + '.') >= '10.4.' and \
                     '-arch' in get_config_vars().get('CFLAGS', '').strip():
                 # The universal build will build fat binaries, but not on
                 # systems before 10.4
@@ -134,9 +140,13 @@
                 # 'universal' instead of 'fat'.
 
                 machine = 'fat'
+                cflags = get_config_vars().get('CFLAGS')
 
-                if '-arch x86_64' in get_config_vars().get('CFLAGS'):
-                    machine = 'universal'
+                if '-arch x86_64' in cflags:
+                    if '-arch i386' in cflags:
+                        machine = 'universal'
+                    else:
+                        machine = 'fat64'
 
             elif machine in ('PowerPC', 'Power_Macintosh'):
                 # Pick a sane name for the PPC architecture.

Modified: python/branches/tlee-ast-optimize/Lib/doctest.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/doctest.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/doctest.py	Wed Jan 14 13:24:17 2009
@@ -820,7 +820,15 @@
         # given object's docstring.
         try:
             file = inspect.getsourcefile(obj) or inspect.getfile(obj)
-            source_lines = linecache.getlines(file)
+            if module is not None:
+                # Supply the module globals in case the module was
+                # originally loaded via a PEP 302 loader and
+                # file is not a valid filesystem path
+                source_lines = linecache.getlines(file, module.__dict__)
+            else:
+                # No access to a loader, so assume it's a normal
+                # filesystem path
+                source_lines = linecache.getlines(file)
             if not source_lines:
                 source_lines = None
         except TypeError:
@@ -1433,8 +1441,10 @@
         d = self._name2ft
         for name, (f, t) in other._name2ft.items():
             if name in d:
-                print "*** DocTestRunner.merge: '" + name + "' in both" \
-                    " testers; summing outcomes."
+                # Don't print here by default, since doing
+                #     so breaks some of the buildbots
+                #print "*** DocTestRunner.merge: '" + name + "' in both" \
+                #    " testers; summing outcomes."
                 f2, t2 = d[name]
                 f = f + f2
                 t = t + t2

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	Wed Jan 14 13:24:17 2009
@@ -111,7 +111,7 @@
 
         """
         if isinstance(f, numbers.Integral):
-            f = float(f)
+            return cls(f)
         elif not isinstance(f, float):
             raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                             (cls.__name__, f, type(f).__name__))

Modified: python/branches/tlee-ast-optimize/Lib/getopt.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/getopt.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/getopt.py	Wed Jan 14 13:24:17 2009
@@ -130,7 +130,7 @@
 
         if args[0][:2] == '--':
             opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
-        elif args[0][:1] == '-':
+        elif args[0][:1] == '-' and args[0] != '-':
             opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
         else:
             if all_options_first:

Modified: python/branches/tlee-ast-optimize/Lib/gzip.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/gzip.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/gzip.py	Wed Jan 14 13:24:17 2009
@@ -42,7 +42,7 @@
     max_read_chunk = 10 * 1024 * 1024   # 10Mb
 
     def __init__(self, filename=None, mode=None,
-                 compresslevel=9, fileobj=None):
+                 compresslevel=9, fileobj=None, mtime=None):
         """Constructor for the GzipFile class.
 
         At least one of fileobj and filename must be given a
@@ -69,6 +69,15 @@
         level of compression; 1 is fastest and produces the least compression,
         and 9 is slowest and produces the most compression.  The default is 9.
 
+        The mtime argument is an optional numeric timestamp to be written
+        to the stream when compressing.  All gzip compressed streams
+        are required to contain a timestamp.  If omitted or None, the
+        current time is used.  This module ignores the timestamp when
+        decompressing; however, some programs, such as gunzip, make use
+        of it.  The format of the timestamp is the same as that of the
+        return value of time.time() and of the st_mtime member of the
+        object returned by os.stat().
+
         """
 
         # guarantee the file is opened in binary mode on platforms
@@ -107,6 +116,7 @@
 
         self.fileobj = fileobj
         self.offset = 0
+        self.mtime = mtime
 
         if self.mode == WRITE:
             self._write_gzip_header()
@@ -140,7 +150,10 @@
         if fname:
             flags = FNAME
         self.fileobj.write(chr(flags))
-        write32u(self.fileobj, long(time.time()))
+        mtime = self.mtime
+        if mtime is None:
+            mtime = time.time()
+        write32u(self.fileobj, long(mtime))
         self.fileobj.write('\002')
         self.fileobj.write('\377')
         if fname:
@@ -158,10 +171,10 @@
         if method != 8:
             raise IOError, 'Unknown compression method'
         flag = ord( self.fileobj.read(1) )
-        # modtime = self.fileobj.read(4)
+        self.mtime = read32(self.fileobj)
         # extraflag = self.fileobj.read(1)
         # os = self.fileobj.read(1)
-        self.fileobj.read(6)
+        self.fileobj.read(2)
 
         if flag & FEXTRA:
             # Read & discard the extra field, if present
@@ -441,6 +454,14 @@
         else:
             raise StopIteration
 
+    def __enter__(self):
+        if self.fileobj is None:
+            raise ValueError("I/O operation on closed GzipFile object")
+        return self
+
+    def __exit__(self, *args):
+        self.close()
+
 
 def _test():
     # Act like gzip; with -d, act like gunzip.

Modified: python/branches/tlee-ast-optimize/Lib/heapq.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/heapq.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/heapq.py	Wed Jan 14 13:24:17 2009
@@ -129,7 +129,7 @@
 __all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
            'nlargest', 'nsmallest', 'heappushpop']
 
-from itertools import islice, repeat, count, imap, izip, tee
+from itertools import islice, repeat, count, imap, izip, tee, chain
 from operator import itemgetter, neg
 import bisect
 
@@ -354,6 +354,32 @@
 
     Equivalent to:  sorted(iterable, key=key)[:n]
     """
+    # Short-cut for n==1 is to use min() when len(iterable)>0
+    if n == 1:
+        it = iter(iterable)
+        head = list(islice(it, 1))
+        if not head:
+            return []
+        if key is None:
+            return [min(chain(head, it))]
+        return [min(chain(head, it), key=key)]
+
+    # When n>=size, it's faster to use sort()
+    try:
+        size = len(iterable)
+    except (TypeError, AttributeError):
+        pass
+    else:
+        if n >= size:
+            return sorted(iterable, key=key)[:n]
+
+    # When key is none, use simpler decoration
+    if key is None:
+        it = izip(iterable, count())                        # decorate
+        result = _nsmallest(n, it)
+        return map(itemgetter(0), result)                   # undecorate
+
+    # General case, slowest method
     in1, in2 = tee(iterable)
     it = izip(imap(key, in1), count(), in2)                 # decorate
     result = _nsmallest(n, it)
@@ -365,6 +391,33 @@
 
     Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
     """
+
+    # Short-cut for n==1 is to use max() when len(iterable)>0
+    if n == 1:
+        it = iter(iterable)
+        head = list(islice(it, 1))
+        if not head:
+            return []
+        if key is None:
+            return [max(chain(head, it))]
+        return [max(chain(head, it), key=key)]
+
+    # When n>=size, it's faster to use sort()
+    try:
+        size = len(iterable)
+    except (TypeError, AttributeError):
+        pass
+    else:
+        if n >= size:
+            return sorted(iterable, key=key, reverse=True)[:n]
+
+    # When key is none, use simpler decoration
+    if key is None:
+        it = izip(iterable, imap(neg, count()))             # decorate
+        result = _nlargest(n, it)
+        return map(itemgetter(0), result)                   # undecorate
+
+    # General case, slowest method
     in1, in2 = tee(iterable)
     it = izip(imap(key, in1), imap(neg, count()), in2)      # decorate
     result = _nlargest(n, it)

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	Wed Jan 14 13:24:17 2009
@@ -325,13 +325,18 @@
 
     # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
 
-    def __init__(self, sock, debuglevel=0, strict=0, method=None):
-        # The buffer size is specified as zero, because the headers of
-        # the response are read with readline().  If the reads were
-        # buffered the readline() calls could consume some of the
-        # response, which make be read via a recv() on the underlying
-        # socket.
-        self.fp = sock.makefile('rb', 0)
+    def __init__(self, sock, debuglevel=0, strict=0, method=None, buffering=False):
+        if buffering:
+            # The caller won't be using any sock.recv() calls, so buffering
+            # is fine and recommendef for performance
+            self.fp = sock.makefile('rb')
+        else:
+            # The buffer size is specified as zero, because the headers of
+            # the response are read with readline().  If the reads were
+            # buffered the readline() calls could consume some of the
+            # response, which make be read via a recv() on the underlying
+            # socket.
+            self.fp = sock.makefile('rb', 0)
         self.debuglevel = debuglevel
         self.strict = strict
         self._method = method
@@ -738,6 +743,7 @@
         """Send the currently buffered request and clear the buffer.
 
         Appends an extra \\r\\n to the buffer.
+        A message_body may be specified, to be appended to the request.
         """
         self._buffer.extend(("", ""))
         msg = "\r\n".join(self._buffer)
@@ -745,9 +751,14 @@
         # If msg and message_body are sent in a single send() call,
         # it will avoid performance problems caused by the interaction
         # between delayed ack and the Nagle algorithim.
-        if message_body is not None:
+        if isinstance(message_body, str):
             msg += message_body
+            message_body = None
         self.send(msg)
+        if message_body is not None:
+            #message_body was not a string (i.e. it is a file) and
+            #we must run the risk of Nagle
+            self.send(message_body)
 
     def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
         """Send a request to the server.
@@ -927,14 +938,9 @@
             self._set_content_length(body)
         for hdr, value in headers.iteritems():
             self.putheader(hdr, value)
-        if isinstance(body, str):
-            self.endheaders(body)
-        else:
-            self.endheaders()
-            if body:  # when body is a file rather than a string
-                self.send(body)
+        self.endheaders(body)
 
-    def getresponse(self):
+    def getresponse(self, buffering=False):
         "Get the response from the server."
 
         # if a prior response has been completed, then forget about it.
@@ -960,13 +966,15 @@
         if self.__state != _CS_REQ_SENT or self.__response:
             raise ResponseNotReady()
 
+        args = (self.sock,)
+        kwds = {"strict":self.strict, "method":self._method}
         if self.debuglevel > 0:
-            response = self.response_class(self.sock, self.debuglevel,
-                                           strict=self.strict,
-                                           method=self._method)
-        else:
-            response = self.response_class(self.sock, strict=self.strict,
-                                           method=self._method)
+            args += (self.debuglevel,)
+        if buffering:
+            #only add this keyword if non-default, for compatibility with
+            #other response_classes.
+            kwds["buffering"] = True;
+        response = self.response_class(*args, **kwds)
 
         response.begin()
         assert response.will_close != _UNKNOWN
@@ -1030,7 +1038,7 @@
         "Provide a getfile, since the superclass' does not use this concept."
         return self.file
 
-    def getreply(self):
+    def getreply(self, buffering=False):
         """Compat definition since superclass does not define it.
 
         Returns a tuple consisting of:
@@ -1039,7 +1047,12 @@
         - any RFC822 headers in the response from the server
         """
         try:
-            response = self._conn.getresponse()
+            if not buffering:
+                response = self._conn.getresponse()
+            else:
+                #only add this keyword if non-default for compatibility
+                #with other connection classes
+                response = self._conn.getresponse(buffering)
         except BadStatusLine, e:
             ### hmm. if getresponse() ever closes the socket on a bad request,
             ### then we are going to have problems with self.sock

Modified: python/branches/tlee-ast-optimize/Lib/idlelib/NEWS.txt
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/idlelib/NEWS.txt	(original)
+++ python/branches/tlee-ast-optimize/Lib/idlelib/NEWS.txt	Wed Jan 14 13:24:17 2009
@@ -3,6 +3,8 @@
 
 *Release date: XX-XXX-2008*
 
+- Issue #3549: On MacOS the preferences menu was not present
+
 - Issue #2665: On Windows, an IDLE installation upgraded from an old version
   would not start if a custom theme was defined.
 

Modified: python/branches/tlee-ast-optimize/Lib/idlelib/help.txt
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/idlelib/help.txt	(original)
+++ python/branches/tlee-ast-optimize/Lib/idlelib/help.txt	Wed Jan 14 13:24:17 2009
@@ -90,7 +90,10 @@
 	Configure IDLE -- Open a configuration dialog.  Fonts, indentation,
                           keybindings, and color themes may be altered.
                           Startup Preferences may be set, and Additional Help
-                          Souces can be specified.
+                          Sources can be specified.
+			  
+			  On MacOS X this menu is not present, use
+			  menu 'IDLE -> Preferences...' instead.
 	---
 	Code Context --	  Open a pane at the top of the edit window which
 			  shows the block context of the section of code

Modified: python/branches/tlee-ast-optimize/Lib/idlelib/macosxSupport.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/idlelib/macosxSupport.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/idlelib/macosxSupport.py	Wed Jan 14 13:24:17 2009
@@ -89,7 +89,9 @@
 
     ###check if Tk version >= 8.4.14; if so, use hard-coded showprefs binding
     tkversion = root.tk.eval('info patchlevel')
-    if tkversion >= '8.4.14':
+    # Note: we cannot check if the string tkversion >= '8.4.14', because
+    # the string '8.4.7' is greater than the string '8.4.14'.
+    if map(int, tkversion.split('.')) >= (8, 4, 14):
         Bindings.menudefs[0] =  ('application', [
                 ('About IDLE', '<<about-idle>>'),
                 None,

Modified: python/branches/tlee-ast-optimize/Lib/inspect.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/inspect.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/inspect.py	Wed Jan 14 13:24:17 2009
@@ -158,9 +158,8 @@
     Generator function objects provides same attributes as functions.
 
     See isfunction.__doc__ for attributes listing."""
-    if (isfunction(object) or ismethod(object)) and \
-        object.func_code.co_flags & CO_GENERATOR:
-        return True
+    return bool((isfunction(object) or ismethod(object)) and
+                object.func_code.co_flags & CO_GENERATOR)
 
 def isgenerator(object):
     """Return true if the object is a generator.
@@ -254,7 +253,10 @@
     Optionally, only return members that satisfy a given predicate."""
     results = []
     for key in dir(object):
-        value = getattr(object, key)
+        try:
+            value = getattr(object, key)
+        except AttributeError:
+            continue
         if not predicate or predicate(value):
             results.append((key, value))
     results.sort()

Modified: python/branches/tlee-ast-optimize/Lib/io.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/io.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/io.py	Wed Jan 14 13:24:17 2009
@@ -1167,7 +1167,7 @@
 
     @property
     def closed(self):
-        return self.writer.closed()
+        return self.writer.closed
 
 
 class BufferedRandom(BufferedWriter, BufferedReader):
@@ -1292,25 +1292,23 @@
     """
     def __init__(self, decoder, translate, errors='strict'):
         codecs.IncrementalDecoder.__init__(self, errors=errors)
-        self.buffer = b''
         self.translate = translate
         self.decoder = decoder
         self.seennl = 0
+        self.pendingcr = False
 
     def decode(self, input, final=False):
         # decode input (with the eventual \r from a previous pass)
-        if self.buffer:
-            input = self.buffer + input
-
         output = self.decoder.decode(input, final=final)
+        if self.pendingcr and (output or final):
+            output = "\r" + output
+            self.pendingcr = False
 
         # retain last \r even when not translating data:
         # then readline() is sure to get \r\n in one pass
         if output.endswith("\r") and not final:
             output = output[:-1]
-            self.buffer = b'\r'
-        else:
-            self.buffer = b''
+            self.pendingcr = True
 
         # Record which newlines are read
         crlf = output.count('\r\n')
@@ -1329,20 +1327,19 @@
 
     def getstate(self):
         buf, flag = self.decoder.getstate()
-        return buf + self.buffer, flag
+        flag <<= 1
+        if self.pendingcr:
+            flag |= 1
+        return buf, flag
 
     def setstate(self, state):
         buf, flag = state
-        if buf.endswith(b'\r'):
-            self.buffer = b'\r'
-            buf = buf[:-1]
-        else:
-            self.buffer = b''
-        self.decoder.setstate((buf, flag))
+        self.pendingcr = bool(flag & 1)
+        self.decoder.setstate((buf, flag >> 1))
 
     def reset(self):
         self.seennl = 0
-        self.buffer = b''
+        self.pendingcr = False
         self.decoder.reset()
 
     _LF = 1

Modified: python/branches/tlee-ast-optimize/Lib/lib-tk/ScrolledText.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib-tk/ScrolledText.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib-tk/ScrolledText.py	Wed Jan 14 13:24:17 2009
@@ -1,43 +1,52 @@
-# A ScrolledText widget feels like a text widget but also has a
-# vertical scroll bar on its right.  (Later, options may be added to
-# add a horizontal bar as well, to make the bars disappear
-# automatically when not needed, to move them to the other side of the
-# window, etc.)
-#
-# Configuration options are passed to the Text widget.
-# A Frame widget is inserted between the master and the text, to hold
-# the Scrollbar widget.
-# Most methods calls are inherited from the Text widget; Pack methods
-# are redirected to the Frame widget however.
+"""A ScrolledText widget feels like a text widget but also has a
+vertical scroll bar on its right.  (Later, options may be added to
+add a horizontal bar as well, to make the bars disappear
+automatically when not needed, to move them to the other side of the
+window, etc.)
 
-from Tkinter import *
-from Tkinter import _cnfmerge
+Configuration options are passed to the Text widget.
+A Frame widget is inserted between the master and the text, to hold
+the Scrollbar widget.
+Most methods calls are inherited from the Text widget; Pack, Grid and
+Place methods are redirected to the Frame widget however.
+"""
+
+__all__ = ['ScrolledText']
+
+from Tkinter import Frame, Text, Scrollbar, Pack, Grid, Place
+from Tkconstants import RIGHT, LEFT, Y, BOTH
 
 class ScrolledText(Text):
-    def __init__(self, master=None, cnf=None, **kw):
-        if cnf is None:
-            cnf = {}
-        if kw:
-            cnf = _cnfmerge((cnf, kw))
-        fcnf = {}
-        for k in cnf.keys():
-            if type(k) == ClassType or k == 'name':
-                fcnf[k] = cnf[k]
-                del cnf[k]
-        self.frame = Frame(master, **fcnf)
-        self.vbar = Scrollbar(self.frame, name='vbar')
+    def __init__(self, master=None, **kw):
+        self.frame = Frame(master)
+        self.vbar = Scrollbar(self.frame)
         self.vbar.pack(side=RIGHT, fill=Y)
-        cnf['name'] = 'text'
-        Text.__init__(self, self.frame, **cnf)
-        self.pack(side=LEFT, fill=BOTH, expand=1)
-        self['yscrollcommand'] = self.vbar.set
+
+        kw.update({'yscrollcommand': self.vbar.set})
+        Text.__init__(self, self.frame, **kw)
+        self.pack(side=LEFT, fill=BOTH, expand=True)
         self.vbar['command'] = self.yview
 
         # Copy geometry methods of self.frame -- hack!
-        methods = Pack.__dict__.keys()
-        methods = methods + Grid.__dict__.keys()
-        methods = methods + Place.__dict__.keys()
+        methods = vars(Pack).keys() + vars(Grid).keys() + vars(Place).keys()
 
         for m in methods:
             if m[0] != '_' and m != 'config' and m != 'configure':
                 setattr(self, m, getattr(self.frame, m))
+
+    def __str__(self):
+        return str(self.frame)
+
+
+def example():
+    import __main__
+    from Tkconstants import END
+
+    stext = ScrolledText(bg='white', height=10)
+    stext.insert(END, __main__.__doc__)
+    stext.pack(fill=BOTH, side=LEFT, expand=True)
+    stext.focus_set()
+    stext.mainloop()
+
+if __name__ == "__main__":
+    example()

Modified: python/branches/tlee-ast-optimize/Lib/lib-tk/tkColorChooser.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib-tk/tkColorChooser.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib-tk/tkColorChooser.py	Wed Jan 14 13:24:17 2009
@@ -34,19 +34,22 @@
         try:
             # make sure initialcolor is a tk color string
             color = self.options["initialcolor"]
-            if type(color) == type(()):
+            if isinstance(color, tuple):
                 # assume an RGB triplet
                 self.options["initialcolor"] = "#%02x%02x%02x" % color
         except KeyError:
             pass
 
     def _fixresult(self, widget, result):
+        # result can be somethings: an empty tuple, an empty string or
+        # a Tcl_Obj, so this somewhat weird check handles that
+        if not result or not str(result):
+            return None, None # canceled
+
         # to simplify application code, the color chooser returns
         # an RGB tuple together with the Tk color string
-        if not result:
-            return None, None # canceled
         r, g, b = widget.winfo_rgb(result)
-        return (r/256, g/256, b/256), result
+        return (r/256, g/256, b/256), str(result)
 
 
 #
@@ -66,5 +69,4 @@
 # test stuff
 
 if __name__ == "__main__":
-
     print "color", askcolor()

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_base.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_base.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_base.py	Wed Jan 14 13:24:17 2009
@@ -94,10 +94,6 @@
         """
         raise NotImplementedError()
 
-    def parenthesize(self, node):
-        """Wrapper around pygram.parenthesize()."""
-        return pygram.parenthesize(node)
-
     def new_name(self, template="xxx_todo_changeme"):
         """Return a string suitable for use as an identifier
 

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_util.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_util.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixer_util.py	Wed Jan 14 13:24:17 2009
@@ -158,6 +158,9 @@
 ### Misc
 ###########################################################
 
+def parenthesize(node):
+    return Node(syms.atom, [LParen(), node, RParen()])
+
 
 consuming_calls = set(["sorted", "list", "set", "any", "all", "tuple", "sum",
                        "min", "max"])
@@ -219,6 +222,29 @@
             return True
     return False
 
+def is_probably_builtin(node):
+    """
+    Check that something isn't an attribute or function name etc.
+    """
+    prev = node.get_prev_sibling()
+    if prev is not None and prev.type == token.DOT:
+        # Attribute lookup.
+        return False
+    parent = node.parent
+    if parent.type in (syms.funcdef, syms.classdef):
+        return False
+    if parent.type == syms.expr_stmt and parent.children[0] is node:
+        # Assignment.
+        return False
+    if parent.type == syms.parameters or \
+            (parent.type == syms.typedargslist and (
+            (prev is not None and prev.type == token.COMMA) or
+            parent.children[0] is node
+            )):
+        # The name of an argument.
+        return False
+    return True
+
 ###########################################################
 ### The following functions are to find bindings in a suite
 ###########################################################
@@ -232,20 +258,77 @@
     suite.parent = parent
     return suite
 
-def does_tree_import(package, name, node):
-    """ Returns true if name is imported from package at the
-        top level of the tree which node belongs to.
-        To cover the case of an import like 'import foo', use
-        Null for the package and 'foo' for the name. """
+def find_root(node):
+    """Find the top level namespace."""
     # Scamper up to the top level namespace
     while node.type != syms.file_input:
         assert node.parent, "Tree is insane! root found before "\
                            "file_input node was found."
         node = node.parent
+    return node
 
-    binding = find_binding(name, node, package)
+def does_tree_import(package, name, node):
+    """ Returns true if name is imported from package at the
+        top level of the tree which node belongs to.
+        To cover the case of an import like 'import foo', use
+        None for the package and 'foo' for the name. """
+    binding = find_binding(name, find_root(node), package)
     return bool(binding)
 
+def is_import(node):
+    """Returns true if the node is an import statement."""
+    return node.type in (syms.import_name, syms.import_from)
+
+def touch_import(package, name, node):
+    """ Works like `does_tree_import` but adds an import statement
+        if it was not imported. """
+    def is_import_stmt(node):
+        return node.type == syms.simple_stmt and node.children and \
+               is_import(node.children[0])
+
+    root = find_root(node)
+
+    if does_tree_import(package, name, root):
+        return
+
+    add_newline_before = False
+
+    # figure out where to insert the new import.  First try to find
+    # the first import and then skip to the last one.
+    insert_pos = offset = 0
+    for idx, node in enumerate(root.children):
+        if not is_import_stmt(node):
+            continue
+        for offset, node2 in enumerate(root.children[idx:]):
+            if not is_import_stmt(node2):
+                break
+        insert_pos = idx + offset
+        break
+
+    # if there are no imports where we can insert, find the docstring.
+    # if that also fails, we stick to the beginning of the file
+    if insert_pos == 0:
+        for idx, node in enumerate(root.children):
+            if node.type == syms.simple_stmt and node.children and \
+               node.children[0].type == token.STRING:
+                insert_pos = idx + 1
+                add_newline_before
+                break
+
+    if package is None:
+        import_ = Node(syms.import_name, [
+            Leaf(token.NAME, 'import'),
+            Leaf(token.NAME, name, prefix=' ')
+        ])
+    else:
+        import_ = FromImport(package, [Leaf(token.NAME, name, prefix=' ')])
+
+    children = [import_, Newline()]
+    if add_newline_before:
+        children.insert(0, Newline())
+    root.insert_child(insert_pos, Node(syms.simple_stmt, children))
+
+
 _def_syms = set([syms.classdef, syms.funcdef])
 def find_binding(name, node, package=None):
     """ Returns the node which binds variable name, otherwise None.
@@ -285,7 +368,7 @@
         if ret:
             if not package:
                 return ret
-            if ret.type in (syms.import_name, syms.import_from):
+            if is_import(ret):
                 return ret
     return None
 

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_apply.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_apply.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_apply.py	Wed Jan 14 13:24:17 2009
@@ -9,7 +9,7 @@
 from .. import pytree
 from ..pgen2 import token
 from .. import fixer_base
-from ..fixer_util import Call, Comma
+from ..fixer_util import Call, Comma, parenthesize
 
 class FixApply(fixer_base.BaseFix):
 
@@ -39,7 +39,7 @@
             (func.type != syms.power or
              func.children[-2].type == token.DOUBLESTAR)):
             # Need to parenthesize
-            func = self.parenthesize(func)
+            func = parenthesize(func)
         func.set_prefix("")
         args = args.clone()
         args.set_prefix("")

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_execfile.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_execfile.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_execfile.py	Wed Jan 14 13:24:17 2009
@@ -7,9 +7,9 @@
 exec() function.
 """
 
-from .. import pytree
 from .. import fixer_base
-from ..fixer_util import Comma, Name, Call, LParen, RParen, Dot
+from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node,
+                          ArgList, String, syms)
 
 
 class FixExecfile(fixer_base.BaseFix):
@@ -22,16 +22,30 @@
 
     def transform(self, node, results):
         assert results
-        syms = self.syms
         filename = results["filename"]
         globals = results.get("globals")
         locals = results.get("locals")
-        args = [Name('open'), LParen(), filename.clone(), RParen(), Dot(),
-                Name('read'), LParen(), RParen()]
-        args[0].set_prefix("")
+
+        # Copy over the prefix from the right parentheses end of the execfile
+        # call.
+        execfile_paren = node.children[-1].children[-1].clone()
+        # Construct open().read().
+        open_args = ArgList([filename.clone()], rparen=execfile_paren)
+        open_call = Node(syms.power, [Name("open"), open_args])
+        read = [Node(syms.trailer, [Dot(), Name('read')]),
+                Node(syms.trailer, [LParen(), RParen()])]
+        open_expr = [open_call] + read
+        # Wrap the open call in a compile call. This is so the filename will be
+        # preserved in the execed code.
+        filename_arg = filename.clone()
+        filename_arg.set_prefix(" ")
+        exec_str = String("'exec'", " ")
+        compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str]
+        compile_call = Call(Name("compile"), compile_args, "")
+        # Finally, replace the execfile call with an exec call.
+        args = [compile_call]
         if globals is not None:
             args.extend([Comma(), globals.clone()])
         if locals is not None:
             args.extend([Comma(), locals.clone()])
-
         return Call(Name("exec"), args, prefix=node.get_prefix())

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_has_key.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_has_key.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_has_key.py	Wed Jan 14 13:24:17 2009
@@ -33,7 +33,7 @@
 from .. import pytree
 from ..pgen2 import token
 from .. import fixer_base
-from ..fixer_util import Name
+from ..fixer_util import Name, parenthesize
 
 
 class FixHasKey(fixer_base.BaseFix):
@@ -86,7 +86,7 @@
             after = [n.clone() for n in after]
         if arg.type in (syms.comparison, syms.not_test, syms.and_test,
                         syms.or_test, syms.test, syms.lambdef, syms.argument):
-            arg = self.parenthesize(arg)
+            arg = parenthesize(arg)
         if len(before) == 1:
             before = before[0]
         else:
@@ -98,12 +98,12 @@
             n_op = pytree.Node(syms.comp_op, (n_not, n_op))
         new = pytree.Node(syms.comparison, (arg, n_op, before))
         if after:
-            new = self.parenthesize(new)
+            new = parenthesize(new)
             new = pytree.Node(syms.power, (new,) + tuple(after))
         if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr,
                                 syms.and_expr, syms.shift_expr,
                                 syms.arith_expr, syms.term,
                                 syms.factor, syms.power):
-            new = self.parenthesize(new)
+            new = parenthesize(new)
         new.set_prefix(prefix)
         return new

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_import.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_import.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_import.py	Wed Jan 14 13:24:17 2009
@@ -13,55 +13,78 @@
 # Local imports
 from .. import fixer_base
 from os.path import dirname, join, exists, pathsep
-from ..fixer_util import FromImport, syms
+from ..fixer_util import FromImport, syms, token
+
+
+def traverse_imports(names):
+    """
+    Walks over all the names imported in a dotted_as_names node.
+    """
+    pending = [names]
+    while pending:
+        node = pending.pop()
+        if node.type == token.NAME:
+            yield node.value
+        elif node.type == syms.dotted_name:
+            yield "".join([ch.value for ch in node.children])
+        elif node.type == syms.dotted_as_name:
+            pending.append(node.children[0])
+        elif node.type == syms.dotted_as_names:
+            pending.extend(node.children[::-2])
+        else:
+            raise AssertionError("unkown node type")
+
 
 class FixImport(fixer_base.BaseFix):
 
     PATTERN = """
-    import_from< type='from' imp=any 'import' ['('] any [')'] >
+    import_from< 'from' imp=any 'import' ['('] any [')'] >
     |
-    import_name< type='import' imp=any >
+    import_name< 'import' imp=any >
     """
 
     def transform(self, node, results):
         imp = results['imp']
 
-        mod_name = unicode(imp.children[0] if imp.type == syms.dotted_as_name \
-                               else imp)
-
-        if mod_name.startswith('.'):
-            # Already a new-style import
-            return
-
-        if not probably_a_local_import(mod_name, self.filename):
-            # I guess this is a global import -- skip it!
-            return
-
-        if results['type'].value == 'from':
+        if node.type == syms.import_from:
             # Some imps are top-level (eg: 'import ham')
             # some are first level (eg: 'import ham.eggs')
             # some are third level (eg: 'import ham.eggs as spam')
             # Hence, the loop
             while not hasattr(imp, 'value'):
                 imp = imp.children[0]
-            imp.value = "." + imp.value
-            node.changed()
+            if self.probably_a_local_import(imp.value):
+                imp.value = "." + imp.value
+                imp.changed()
+                return node
         else:
-            new = FromImport('.', getattr(imp, 'content', None) or [imp])
+            have_local = False
+            have_absolute = False
+            for mod_name in traverse_imports(imp):
+                if self.probably_a_local_import(mod_name):
+                    have_local = True
+                else:
+                    have_absolute = True
+            if have_absolute:
+                if have_local:
+                    # We won't handle both sibling and absolute imports in the
+                    # same statement at the moment.
+                    self.warning(node, "absolute and local imports together")
+                return
+
+            new = FromImport('.', [imp])
             new.set_prefix(node.get_prefix())
-            node = new
-        return node
+            return new
 
-def probably_a_local_import(imp_name, file_path):
-    # Must be stripped because the right space is included by the parser
-    imp_name = imp_name.split('.', 1)[0].strip()
-    base_path = dirname(file_path)
-    base_path = join(base_path, imp_name)
-    # If there is no __init__.py next to the file its not in a package
-    # so can't be a relative import.
-    if not exists(join(dirname(base_path), '__init__.py')):
+    def probably_a_local_import(self, imp_name):
+        imp_name = imp_name.split('.', 1)[0]
+        base_path = dirname(self.filename)
+        base_path = join(base_path, imp_name)
+        # If there is no __init__.py next to the file its not in a package
+        # so can't be a relative import.
+        if not exists(join(dirname(base_path), '__init__.py')):
+            return False
+        for ext in ['.py', pathsep, '.pyc', '.so', '.sl', '.pyd']:
+            if exists(base_path + ext):
+                return True
         return False
-    for ext in ['.py', pathsep, '.pyc', '.so', '.sl', '.pyd']:
-        if exists(base_path + ext):
-            return True
-    return False

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	Wed Jan 14 13:24:17 2009
@@ -25,7 +25,6 @@
            'tkFont': 'tkinter.font',
            'tkMessageBox': 'tkinter.messagebox',
            'ScrolledText': 'tkinter.scrolledtext',
-           'turtle': 'tkinter.turtle',
            'Tkconstants': 'tkinter.constants',
            'Tix': 'tkinter.tix',
            'Tkinter': 'tkinter',
@@ -42,6 +41,8 @@
            'DocXMLRPCServer': 'xmlrpc.server',
            'SimpleXMLRPCServer': 'xmlrpc.server',
            'httplib': 'http.client',
+           'htmlentitydefs' : 'html.entities',
+           'HTMLParser' : 'html.parser',
            'Cookie': 'http.cookies',
            'cookielib': 'http.cookiejar',
            'BaseHTTPServer': 'http.server',
@@ -64,16 +65,17 @@
     mod_list = ' | '.join(["module_name='%s'" % key for key in mapping])
     bare_names = alternates(mapping.keys())
 
-    yield """name_import=import_name< 'import' ((%s)
-                          | dotted_as_names< any* (%s) any* >) >
+    yield """name_import=import_name< 'import' ((%s) |
+               multiple_imports=dotted_as_names< any* (%s) any* >) >
           """ % (mod_list, mod_list)
     yield """import_from< 'from' (%s) 'import' ['(']
               ( any | import_as_name< any 'as' any > |
                 import_as_names< any* >)  [')'] >
           """ % mod_list
-    yield """import_name< 'import'
-                          dotted_as_name< (%s) 'as' any > >
-          """ % mod_list
+    yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > |
+               multiple_imports=dotted_as_names<
+                 any* dotted_as_name< (%s) 'as' any > any* >) >
+          """ % (mod_list, mod_list)
 
     # Find usages of module members in code e.g. thread.foo(bar)
     yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names
@@ -86,6 +88,10 @@
     # This is overridden in fix_imports2.
     mapping = MAPPING
 
+    # We want to run this fixer late, so fix_import doesn't try to make stdlib
+    # renames into relative imports.
+    run_order = 6
+
     def build_pattern(self):
         return "|".join(build_pattern(self.mapping))
 
@@ -100,8 +106,8 @@
         match = super(FixImports, self).match
         results = match(node)
         if results:
-            # Module usage could be in the trailier of an attribute lookup, so
-            # we might have nested matches when "bare_with_attr" is present.
+            # Module usage could be in the trailer of an attribute lookup, so we
+            # might have nested matches when "bare_with_attr" is present.
             if "bare_with_attr" not in results and \
                     any([match(obj) for obj in attr_chain(node, "parent")]):
                 return False
@@ -115,12 +121,20 @@
     def transform(self, node, results):
         import_mod = results.get("module_name")
         if import_mod:
-            new_name = self.mapping[(import_mod or mod_name).value]
+            new_name = self.mapping[import_mod.value]
+            import_mod.replace(Name(new_name, prefix=import_mod.get_prefix()))
             if "name_import" in results:
                 # If it's not a "from x import x, y" or "import x as y" import,
                 # marked its usage to be replaced.
                 self.replace[import_mod.value] = new_name
-            import_mod.replace(Name(new_name, prefix=import_mod.get_prefix()))
+            if "multiple_imports" in results:
+                # This is a nasty hack to fix multiple imports on a
+                # line (e.g., "import StringIO, urlparse"). The problem is that I
+                # can't figure out an easy way to make a pattern recognize the
+                # keys of MAPPING randomly sprinkled in an import statement.
+                results = self.match(node)
+                if results:
+                    self.transform(node, results)
         else:
             # Replace usage of the module.
             bare_name = results["bare_with_attr"][0]

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports2.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports2.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_imports2.py	Wed Jan 14 13:24:17 2009
@@ -11,6 +11,6 @@
 
 class FixImports2(fix_imports.FixImports):
 
-    order = "post"
+    run_order = 7
 
     mapping = MAPPING

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_intern.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_intern.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_intern.py	Wed Jan 14 13:24:17 2009
@@ -8,7 +8,7 @@
 # Local imports
 from .. import pytree
 from .. import fixer_base
-from ..fixer_util import Name, Attr
+from ..fixer_util import Name, Attr, touch_import
 
 
 class FixIntern(fixer_base.BaseFix):
@@ -40,4 +40,5 @@
                                         newarglist,
                                         results["rpar"].clone()])] + after)
         new.set_prefix(node.get_prefix())
+        touch_import(None, 'sys', node)
         return new

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_long.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_long.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_long.py	Wed Jan 14 13:24:17 2009
@@ -2,34 +2,21 @@
 # Licensed to PSF under a Contributor Agreement.
 
 """Fixer that turns 'long' into 'int' everywhere.
-
-This also strips the trailing 'L' or 'l' from long loterals.
 """
 
 # Local imports
-from .. import pytree
 from .. import fixer_base
-from ..fixer_util import Name, Number
+from ..fixer_util import Name, Number, is_probably_builtin
 
 
 class FixLong(fixer_base.BaseFix):
 
-    PATTERN = """
-    (long_type = 'long' | number = NUMBER)
-    """
+    PATTERN = "'long'"
 
-    static_long = Name("long")
     static_int = Name("int")
 
     def transform(self, node, results):
-        long_type = results.get("long_type")
-        number = results.get("number")
-        new = None
-        if long_type:
-            assert node == self.static_long, node
+        if is_probably_builtin(node):
             new = self.static_int.clone()
-        if number and node.value[-1] in ("l", "L"):
-            new = Number(node.value[:-1])
-        if new is not None:
             new.set_prefix(node.get_prefix())
             return new

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_repr.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_repr.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_repr.py	Wed Jan 14 13:24:17 2009
@@ -5,7 +5,7 @@
 
 # Local imports
 from .. import fixer_base
-from ..fixer_util import Call, Name
+from ..fixer_util import Call, Name, parenthesize
 
 
 class FixRepr(fixer_base.BaseFix):
@@ -18,5 +18,5 @@
         expr = results["expr"].clone()
 
         if expr.type == self.syms.testlist1:
-            expr = self.parenthesize(expr)
+            expr = parenthesize(expr)
         return Call(Name("repr"), [expr], prefix=node.get_prefix())

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_urllib.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_urllib.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_urllib.py	Wed Jan 14 13:24:17 2009
@@ -15,7 +15,10 @@
                      '_urlopener', 'urlcleanup']),
                 ('urllib.parse',
                     ['quote', 'quote_plus', 'unquote', 'unquote_plus',
-                     'urlencode', 'pahtname2url', 'url2pathname']),
+                     'urlencode', 'pathname2url', 'url2pathname', 'splitattr',
+                     'splithost', 'splitnport', 'splitpasswd', 'splitport',
+                     'splitquery', 'splittag', 'splittype', 'splituser',
+                     'splitvalue', ]),
                 ('urllib.error',
                     ['ContentTooShortError'])],
            'urllib2' : [
@@ -29,17 +32,17 @@
                      'AbstractBasicAuthHandler',
                      'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler',
                      'AbstractDigestAuthHandler',
-                     'HTTPDigestAuthHander', 'ProxyDigestAuthHandler',
+                     'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler',
                      'HTTPHandler', 'HTTPSHandler', 'FileHandler',
                      'FTPHandler', 'CacheFTPHandler',
                      'UnknownHandler']),
                 ('urllib.error',
-                    ['URLError', 'HTTPError'])],
+                    ['URLError', 'HTTPError']),
+           ]
 }
 
-
-# def alternates(members):
-#     return "(" + "|".join(map(repr, members)) + ")"
+# Duplicate the url parsing functions for urllib2.
+MAPPING["urllib2"].append(MAPPING["urllib"][1])
 
 
 def build_pattern():

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_xrange.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_xrange.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/fixes/fix_xrange.py	Wed Jan 14 13:24:17 2009
@@ -12,7 +12,9 @@
 class FixXrange(fixer_base.BaseFix):
 
     PATTERN = """
-              power< (name='range'|name='xrange') trailer< '(' [any] ')' > any* >
+              power<
+                 (name='range'|name='xrange') trailer< '(' args=any ')' >
+              rest=any* >
               """
 
     def transform(self, node, results):
@@ -30,11 +32,14 @@
 
     def transform_range(self, node, results):
         if not self.in_special_context(node):
-            arg = node.clone()
-            arg.set_prefix("")
-            call = Call(Name("list"), [arg])
-            call.set_prefix(node.get_prefix())
-            return call
+            range_call = Call(Name("range"), [results["args"].clone()])
+            # Encase the range call in list().
+            list_call = Call(Name("list"), [range_call],
+                             prefix=node.get_prefix())
+            # Put things that were after the range() call after the list call.
+            for n in results["rest"]:
+                list_call.append_child(n)
+            return list_call
         return node
 
     P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/main.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/main.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/main.py	Wed Jan 14 13:24:17 2009
@@ -5,6 +5,7 @@
 import sys
 import os
 import logging
+import shutil
 import optparse
 
 from . import refactor
@@ -39,6 +40,8 @@
         # Actually write the new file
         super(StdoutRefactoringTool, self).write_file(new_text,
                                                       filename, old_text)
+        if not self.nobackups:
+            shutil.copymode(backup, filename)
 
     def print_output(self, lines):
         for line in lines:
@@ -56,7 +59,7 @@
     Returns a suggested exit status (0, 1, 2).
     """
     # Set up option parser
-    parser = optparse.OptionParser(usage="refactor.py [options] file|dir ...")
+    parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
     parser.add_option("-d", "--doctests_only", action="store_true",
                       help="Fix up doctests only")
     parser.add_option("-f", "--fix", action="append", default=[],

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/pgen2/driver.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/pgen2/driver.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/pgen2/driver.py	Wed Jan 14 13:24:17 2009
@@ -77,7 +77,8 @@
                 column = 0
         else:
             # We never broke out -- EOF is too soon (how can this happen???)
-            raise parse.ParseError("incomplete input", t, v, x)
+            raise parse.ParseError("incomplete input",
+                                   type, value, (prefix, start))
         return p.rootnode
 
     def parse_stream_raw(self, stream, debug=False):

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/pygram.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/pygram.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/pygram.py	Wed Jan 14 13:24:17 2009
@@ -29,10 +29,3 @@
 
 python_grammar = driver.load_grammar(_GRAMMAR_FILE)
 python_symbols = Symbols(python_grammar)
-
-
-def parenthesize(node):
-    return pytree.Node(python_symbols.atom,
-                       (pytree.Leaf(token.LPAR, "("),
-                        node,
-                        pytree.Leaf(token.RPAR, ")")))

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/pytree.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/pytree.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/pytree.py	Wed Jan 14 13:24:17 2009
@@ -279,18 +279,21 @@
         child.parent = self
         self.children[i].parent = None
         self.children[i] = child
+        self.changed()
 
     def insert_child(self, i, child):
         """Equivalent to 'node.children.insert(i, child)'. This method also
         sets the child's parent attribute appropriately."""
         child.parent = self
         self.children.insert(i, child)
+        self.changed()
 
     def append_child(self, child):
         """Equivalent to 'node.children.append(child)'. This method also
         sets the child's parent attribute appropriately."""
         child.parent = self
         self.children.append(child)
+        self.changed()
 
 
 class Leaf(Base):

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/refactor.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/refactor.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/refactor.py	Wed Jan 14 13:24:17 2009
@@ -123,8 +123,8 @@
                                     logger=self.logger)
         self.pre_order, self.post_order = self.get_fixers()
 
-        self.pre_order_mapping = get_headnode_dict(self.pre_order)
-        self.post_order_mapping = get_headnode_dict(self.post_order)
+        self.pre_order_heads = get_headnode_dict(self.pre_order)
+        self.post_order_heads = get_headnode_dict(self.post_order)
 
         self.files = []  # List of files that were or should be modified
 
@@ -287,17 +287,13 @@
         Returns:
             True if the tree was modified, False otherwise.
         """
-        # Two calls to chain are required because pre_order.values()
-        #   will be a list of lists of fixers:
-        #   [[<fixer ...>, <fixer ...>], [<fixer ...>]]
-        all_fixers = chain(self.pre_order, self.post_order)
-        for fixer in all_fixers:
+        for fixer in chain(self.pre_order, self.post_order):
             fixer.start_tree(tree, name)
 
-        self.traverse_by(self.pre_order_mapping, tree.pre_order())
-        self.traverse_by(self.post_order_mapping, tree.post_order())
+        self.traverse_by(self.pre_order_heads, tree.pre_order())
+        self.traverse_by(self.post_order_heads, tree.post_order())
 
-        for fixer in all_fixers:
+        for fixer in chain(self.pre_order, self.post_order):
             fixer.finish_tree(tree, name)
         return tree.was_changed
 

Deleted: python/branches/tlee-ast-optimize/Lib/lib2to3/tests/benchmark.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/tests/benchmark.py	Wed Jan 14 13:24:17 2009
+++ (empty file)
@@ -1,58 +0,0 @@
-#!/usr/bin/env python2.5
-"""
-This is a benchmarking script to test the speed of 2to3's pattern matching
-system. It's equivalent to "refactor.py -f all" for every Python module
-in sys.modules, but without engaging the actual transformations.
-"""
-
-__author__ = "Collin Winter <collinw at gmail.com>"
-
-# Python imports
-import os.path
-import sys
-from time import time
-
-# Test imports
-from .support import adjust_path
-adjust_path()
-
-# Local imports
-from .. import refactor
-
-### Mock code for refactor.py and the fixers
-###############################################################################
-class Options:
-    def __init__(self, **kwargs):
-        for k, v in kwargs.items():
-            setattr(self, k, v)
-
-        self.verbose = False
-
-def dummy_transform(*args, **kwargs):
-    pass
-
-### Collect list of modules to match against
-###############################################################################
-files = []
-for mod in sys.modules.values():
-    if mod is None or not hasattr(mod, '__file__'):
-        continue
-    f = mod.__file__
-    if f.endswith('.pyc'):
-        f = f[:-1]
-    if f.endswith('.py'):
-        files.append(f)
-
-### Set up refactor and run the benchmark
-###############################################################################
-options = Options(fix=["all"], print_function=False, doctests_only=False)
-refactor = refactor.RefactoringTool(options)
-for fixer in refactor.fixers:
-    # We don't want them to actually fix the tree, just match against it.
-    fixer.transform = dummy_transform
-
-t = time()
-for f in files:
-    print "Matching", f
-    refactor.refactor_file(f)
-print "%d seconds to match %d files" % (time() - t, len(sys.modules))

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/tests/data/py3_test_grammar.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/tests/data/py3_test_grammar.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/tests/data/py3_test_grammar.py	Wed Jan 14 13:24:17 2009
@@ -485,6 +485,14 @@
         global a, b
         global one, two, three, four, five, six, seven, eight, nine, ten
 
+    def testNonlocal(self):
+        # 'nonlocal' NAME (',' NAME)*
+        x = 0
+        y = 0
+        def f():
+            nonlocal x
+            nonlocal x, y
+
     def testAssert(self):
         # assert_stmt: 'assert' test [',' test]
         assert 1

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	Wed Jan 14 13:24:17 2009
@@ -293,30 +293,30 @@
 
     def test_prefix_preservation(self):
         b = """x =   intern(  a  )"""
-        a = """x =   sys.intern(  a  )"""
+        a = """import sys\nx =   sys.intern(  a  )"""
         self.check(b, a)
 
         b = """y = intern("b" # test
               )"""
-        a = """y = sys.intern("b" # test
+        a = """import sys\ny = sys.intern("b" # test
               )"""
         self.check(b, a)
 
         b = """z = intern(a+b+c.d,   )"""
-        a = """z = sys.intern(a+b+c.d,   )"""
+        a = """import sys\nz = sys.intern(a+b+c.d,   )"""
         self.check(b, a)
 
     def test(self):
         b = """x = intern(a)"""
-        a = """x = sys.intern(a)"""
+        a = """import sys\nx = sys.intern(a)"""
         self.check(b, a)
 
         b = """z = intern(a+b+c.d,)"""
-        a = """z = sys.intern(a+b+c.d,)"""
+        a = """import sys\nz = sys.intern(a+b+c.d,)"""
         self.check(b, a)
 
         b = """intern("y%s" % 5).replace("y", "")"""
-        a = """sys.intern("y%s" % 5).replace("y", "")"""
+        a = """import sys\nsys.intern("y%s" % 5).replace("y", "")"""
         self.check(b, a)
 
     # These should not be refactored
@@ -337,6 +337,35 @@
         s = """intern()"""
         self.unchanged(s)
 
+class Test_reduce(FixerTestCase):
+    fixer = "reduce"
+
+    def test_simple_call(self):
+        b = "reduce(a, b, c)"
+        a = "from functools import reduce\nreduce(a, b, c)"
+        self.check(b, a)
+
+    def test_call_with_lambda(self):
+        b = "reduce(lambda x, y: x + y, seq)"
+        a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
+        self.check(b, a)
+
+    def test_unchanged(self):
+        s = "reduce(a)"
+        self.unchanged(s)
+
+        s = "reduce(a, b=42)"
+        self.unchanged(s)
+
+        s = "reduce(a, b, c, d)"
+        self.unchanged(s)
+
+        s = "reduce(**c)"
+        self.unchanged(s)
+
+        s = "reduce()"
+        self.unchanged(s)
+
 class Test_print(FixerTestCase):
     fixer = "print"
 
@@ -1044,26 +1073,26 @@
         a = """z = type(x) in (int, int)"""
         self.check(b, a)
 
-    def test_4(self):
-        b = """a = 12L"""
-        a = """a = 12"""
-        self.check(b, a)
+    def test_unchanged(self):
+        s = """long = True"""
+        self.unchanged(s)
 
-    def test_5(self):
-        b = """b = 0x12l"""
-        a = """b = 0x12"""
-        self.check(b, a)
+        s = """s.long = True"""
+        self.unchanged(s)
 
-    def test_unchanged_1(self):
-        s = """a = 12"""
+        s = """def long(): pass"""
         self.unchanged(s)
 
-    def test_unchanged_2(self):
-        s = """b = 0x12"""
+        s = """class long(): pass"""
         self.unchanged(s)
 
-    def test_unchanged_3(self):
-        s = """c = 3.14"""
+        s = """def f(long): pass"""
+        self.unchanged(s)
+
+        s = """def f(g, long): pass"""
+        self.unchanged(s)
+
+        s = """def f(x, long=True): pass"""
         self.unchanged(s)
 
     def test_prefix_preservation(self):
@@ -1071,6 +1100,73 @@
         a = """x =   int(  x  )"""
         self.check(b, a)
 
+
+class Test_execfile(FixerTestCase):
+    fixer = "execfile"
+
+    def test_conversion(self):
+        b = """execfile("fn")"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'))"""
+        self.check(b, a)
+
+        b = """execfile("fn", glob)"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'), glob)"""
+        self.check(b, a)
+
+        b = """execfile("fn", glob, loc)"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)"""
+        self.check(b, a)
+
+        b = """execfile("fn", globals=glob)"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)"""
+        self.check(b, a)
+
+        b = """execfile("fn", locals=loc)"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)"""
+        self.check(b, a)
+
+        b = """execfile("fn", globals=glob, locals=loc)"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)"""
+        self.check(b, a)
+
+    def test_spacing(self):
+        b = """execfile( "fn" )"""
+        a = """exec(compile(open( "fn" ).read(), "fn", 'exec'))"""
+        self.check(b, a)
+
+        b = """execfile("fn",  globals = glob)"""
+        a = """exec(compile(open("fn").read(), "fn", 'exec'),  globals = glob)"""
+        self.check(b, a)
+
+
+class Test_isinstance(FixerTestCase):
+    fixer = "isinstance"
+
+    def test_remove_multiple_items(self):
+        b = """isinstance(x, (int, int, int))"""
+        a = """isinstance(x, int)"""
+        self.check(b, a)
+
+        b = """isinstance(x, (int, float, int, int, float))"""
+        a = """isinstance(x, (int, float))"""
+        self.check(b, a)
+
+        b = """isinstance(x, (int, float, int, int, float, str))"""
+        a = """isinstance(x, (int, float, str))"""
+        self.check(b, a)
+
+        b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""
+        a = """isinstance(foo() + bar(), (x(), y(), x(), int))"""
+        self.check(b, a)
+
+    def test_prefix_preservation(self):
+        b = """if    isinstance(  foo(), (  bar, bar, baz )) : pass"""
+        a = """if    isinstance(  foo(), (  bar, baz )) : pass"""
+        self.check(b, a)
+
+    def test_unchanged(self):
+        self.unchanged("isinstance(x, (str, int))")
+
 class Test_dict(FixerTestCase):
     fixer = "dict"
 
@@ -1287,6 +1383,14 @@
         a = """x = list(range(10, 3, 9)) + [4]"""
         self.check(b, a)
 
+        b = """x = range(10)[::-1]"""
+        a = """x = list(range(10))[::-1]"""
+        self.check(b, a)
+
+        b = """x = range(10)  [3]"""
+        a = """x = list(range(10))  [3]"""
+        self.check(b, a)
+
     def test_xrange_in_for(self):
         b = """for i in xrange(10):\n    j=i"""
         a = """for i in range(10):\n    j=i"""
@@ -1422,9 +1526,8 @@
         s = "foo(xreadlines)"
         self.unchanged(s)
 
-class Test_imports(FixerTestCase):
-    fixer = "imports"
-    from ..fixes.fix_imports import MAPPING as modules
+
+class ImportsFixerTests:
 
     def test_import_module(self):
         for old, new in self.modules.items():
@@ -1522,18 +1625,36 @@
             self.check(b, a)
 
 
+class Test_imports(FixerTestCase, ImportsFixerTests):
+    fixer = "imports"
+    from ..fixes.fix_imports import MAPPING as modules
+
+    def test_multiple_imports(self):
+        b = """import urlparse, cStringIO"""
+        a = """import urllib.parse, io"""
+        self.check(b, a)
+
+    def test_multiple_imports_as(self):
+        b = """
+            import copy_reg as bar, HTMLParser as foo, urlparse
+            s = urlparse.spam(bar.foo())
+            """
+        a = """
+            import copyreg as bar, html.parser as foo, urllib.parse
+            s = urllib.parse.spam(bar.foo())
+            """
+        self.check(b, a)
 
-class Test_imports2(Test_imports):
+
+class Test_imports2(FixerTestCase, ImportsFixerTests):
     fixer = "imports2"
     from ..fixes.fix_imports2 import MAPPING as modules
 
 
-class Test_imports_fixer_order(Test_imports):
-
-    fixer = None
+class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests):
 
     def setUp(self):
-        Test_imports.setUp(self, ['imports', 'imports2'])
+        super(Test_imports_fixer_order, self).setUp(['imports', 'imports2'])
         from ..fixes.fix_imports2 import MAPPING as mapping2
         self.modules = mapping2.copy()
         from ..fixes.fix_imports import MAPPING as mapping1
@@ -3406,11 +3527,30 @@
         a = "from . import foo, bar"
         self.check_both(b, a)
 
+        b = "import foo, bar, x"
+        a = "from . import foo, bar, x"
+        self.check_both(b, a)
+
+        b = "import x, y, z"
+        a = "from . import x, y, z"
+        self.check_both(b, a)
+
     def test_import_as(self):
         b = "import foo as x"
         a = "from . import foo as x"
         self.check_both(b, a)
 
+        b = "import a as b, b as c, c as d"
+        a = "from . import a as b, b as c, c as d"
+        self.check_both(b, a)
+
+    def test_local_and_absolute(self):
+        self.always_exists = False
+        self.present_files = set(["foo.py", "__init__.py"])
+
+        s = "import foo, bar"
+        self.warns_unchanged(s, "absolute and local imports together")
+
     def test_dotted_import(self):
         b = "import foo.bar"
         a = "from . import foo.bar"

Modified: python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_util.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_util.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/lib2to3/tests/test_util.py	Wed Jan 14 13:24:17 2009
@@ -526,6 +526,33 @@
                     b = 7"""
         self.failIf(self.find_binding("a", s))
 
+class Test_touch_import(support.TestCase):
+
+    def test_after_docstring(self):
+        node = parse('"""foo"""\nbar()')
+        fixer_util.touch_import(None, "foo", node)
+        self.assertEqual(str(node), '"""foo"""\nimport foo\nbar()\n\n')
+
+    def test_after_imports(self):
+        node = parse('"""foo"""\nimport bar\nbar()')
+        fixer_util.touch_import(None, "foo", node)
+        self.assertEqual(str(node), '"""foo"""\nimport bar\nimport foo\nbar()\n\n')
+
+    def test_beginning(self):
+        node = parse('bar()')
+        fixer_util.touch_import(None, "foo", node)
+        self.assertEqual(str(node), 'import foo\nbar()\n\n')
+
+    def test_from_import(self):
+        node = parse('bar()')
+        fixer_util.touch_import("cgi", "escape", node)
+        self.assertEqual(str(node), 'from cgi import escape\nbar()\n\n')
+
+    def test_name_import(self):
+        node = parse('bar()')
+        fixer_util.touch_import(None, "cgi", node)
+        self.assertEqual(str(node), 'import cgi\nbar()\n\n')
+
 
 if __name__ == "__main__":
     import __main__

Modified: python/branches/tlee-ast-optimize/Lib/linecache.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/linecache.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/linecache.py	Wed Jan 14 13:24:17 2009
@@ -88,21 +88,20 @@
             get_source = getattr(loader, 'get_source', None)
 
             if name and get_source:
-                if basename.startswith(name.split('.')[-1]+'.'):
-                    try:
-                        data = get_source(name)
-                    except (ImportError, IOError):
-                        pass
-                    else:
-                        if data is None:
-                            # No luck, the PEP302 loader cannot find the source
-                            # for this module.
-                            return []
-                        cache[filename] = (
-                            len(data), None,
-                            [line+'\n' for line in data.splitlines()], fullname
-                        )
-                        return cache[filename][2]
+                try:
+                    data = get_source(name)
+                except (ImportError, IOError):
+                    pass
+                else:
+                    if data is None:
+                        # No luck, the PEP302 loader cannot find the source
+                        # for this module.
+                        return []
+                    cache[filename] = (
+                        len(data), None,
+                        [line+'\n' for line in data.splitlines()], fullname
+                    )
+                    return cache[filename][2]
 
         # Try looking through the module search path.
 

Modified: python/branches/tlee-ast-optimize/Lib/logging/__init__.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/logging/__init__.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/logging/__init__.py	Wed Jan 14 13:24:17 2009
@@ -31,7 +31,7 @@
            'INFO', 'LogRecord', 'Logger', 'Manager', 'NOTSET', 'PlaceHolder',
            'RootLogger', 'StreamHandler', 'WARN', 'WARNING']
 
-import sys, os, types, time, string, cStringIO, traceback
+import sys, os, types, time, string, cStringIO, traceback, warnings
 
 try:
     import codecs
@@ -46,8 +46,8 @@
 
 __author__  = "Vinay Sajip <vinay_sajip at red-dove.com>"
 __status__  = "production"
-__version__ = "0.5.0.5"
-__date__    = "24 January 2008"
+__version__ = "0.5.0.6"
+__date__    = "03 December 2008"
 
 #---------------------------------------------------------------------------
 #   Miscellaneous module data
@@ -846,7 +846,7 @@
         Add the specified logger as a child of this placeholder.
         """
         #if alogger not in self.loggers:
-        if not self.loggerMap.has_key(alogger):
+        if alogger not in self.loggerMap:
             #self.loggers.append(alogger)
             self.loggerMap[alogger] = None
 
@@ -1488,3 +1488,56 @@
             old_exit(status)
 
     sys.exit = exithook
+
+# Null handler
+
+class NullHandler(Handler):
+    """
+    This handler does nothing. It's intended to be used to avoid the
+    "No handlers could be found for logger XXX" one-off warning. This is
+    important for library code, which may contain code to log events. If a user
+    of the library does not configure logging, the one-off warning might be
+    produced; to avoid this, the library developer simply needs to instantiate
+    a NullHandler and add it to the top-level logger of the library module or
+    package.
+    """
+    def emit(self, record):
+        pass
+
+# Warnings integration
+
+_warnings_showwarning = None
+
+def _showwarning(message, category, filename, lineno, file=None, line=None):
+    """
+    Implementation of showwarnings which redirects to logging, which will first
+    check to see if the file parameter is None. If a file is specified, it will
+    delegate to the original warnings implementation of showwarning. Otherwise,
+    it will call warnings.formatwarning and will log the resulting string to a
+    warnings logger named "py.warnings" with level logging.WARNING.
+    """
+    if file is not None:
+        if _warnings_showwarning is not None:
+            _warnings_showwarning(message, category, filename, lineno, file, line)
+    else:
+        s = warnings.formatwarning(message, category, filename, lineno, line)
+        logger = getLogger("py.warnings")
+        if not logger.handlers:
+            logger.addHandler(NullHandler())
+        logger.warning("%s", s)
+
+def captureWarnings(capture):
+    """
+    If capture is true, redirect all warnings to the logging package.
+    If capture is False, ensure that warnings are not redirected to logging
+    but to their original destinations.
+    """
+    global _warnings_showwarning
+    if capture:
+        if _warnings_showwarning is None:
+            _warnings_showwarning = warnings.showwarning
+            warnings.showwarning = _showwarning
+    else:
+        if _warnings_showwarning is not None:
+            warnings.showwarning = _warnings_showwarning
+            _warnings_showwarning = None

Modified: python/branches/tlee-ast-optimize/Lib/logging/handlers.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/logging/handlers.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/logging/handlers.py	Wed Jan 14 13:24:17 2009
@@ -1027,9 +1027,7 @@
                 h.putheader("Content-type",
                             "application/x-www-form-urlencoded")
                 h.putheader("Content-length", str(len(data)))
-            h.endheaders()
-            if self.method == "POST":
-                h.send(data)
+            h.endheaders(data if self.method == "POST" else None)
             h.getreply()    #can't do anything with the result
         except (KeyboardInterrupt, SystemExit):
             raise

Modified: python/branches/tlee-ast-optimize/Lib/opcode.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/opcode.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/opcode.py	Wed Jan 14 13:24:17 2009
@@ -58,7 +58,6 @@
 
 def_op('UNARY_INVERT', 15)
 
-def_op('LIST_APPEND', 18)
 def_op('BINARY_POWER', 19)
 def_op('BINARY_MULTIPLY', 20)
 def_op('BINARY_DIVIDE', 21)
@@ -128,7 +127,7 @@
 name_op('DELETE_NAME', 91)      # ""
 def_op('UNPACK_SEQUENCE', 92)   # Number of tuple items
 jrel_op('FOR_ITER', 93)
-
+def_op('LIST_APPEND', 94)
 name_op('STORE_ATTR', 95)       # Index in name list
 name_op('DELETE_ATTR', 96)      # ""
 name_op('STORE_GLOBAL', 97)     # ""

Modified: python/branches/tlee-ast-optimize/Lib/pdb.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/pdb.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/pdb.py	Wed Jan 14 13:24:17 2009
@@ -440,7 +440,7 @@
         Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
         line or EOF). Warning: testing is not comprehensive.
         """
-        line = linecache.getline(filename, lineno)
+        line = linecache.getline(filename, lineno, self.curframe.f_globals)
         if not line:
             print >>self.stdout, 'End of file'
             return 0
@@ -768,7 +768,7 @@
         breaklist = self.get_file_breaks(filename)
         try:
             for lineno in range(first, last+1):
-                line = linecache.getline(filename, lineno)
+                line = linecache.getline(filename, lineno, self.curframe.f_globals)
                 if not line:
                     print >>self.stdout, '[EOF]'
                     break

Modified: python/branches/tlee-ast-optimize/Lib/plat-mac/EasyDialogs.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/plat-mac/EasyDialogs.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/plat-mac/EasyDialogs.py	Wed Jan 14 13:24:17 2009
@@ -573,7 +573,7 @@
         del d
 
 def _process_Nav_args(dftflags, **args):
-    import aepack
+    import Carbon.AppleEvents
     import Carbon.AE
     import Carbon.File
     for k in args.keys():
@@ -585,11 +585,14 @@
     if args.has_key('defaultLocation') and \
             not isinstance(args['defaultLocation'], Carbon.AE.AEDesc):
         defaultLocation = args['defaultLocation']
-        if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)):
-            args['defaultLocation'] = aepack.pack(defaultLocation)
+        if isinstance(defaultLocation, Carbon.File.FSSpec):
+            args['defaultLocation'] = Carbon.AE.AECreateDesc(
+                    Carbon.AppleEvents.typeFSS, defaultLocation.data)
         else:
-            defaultLocation = Carbon.File.FSRef(defaultLocation)
-            args['defaultLocation'] = aepack.pack(defaultLocation)
+            if not isinstance(defaultLocation, Carbon.File.FSRef):
+                defaultLocation = Carbon.File.FSRef(defaultLocation)
+            args['defaultLocation'] = Carbon.AE.AECreateDesc(
+                    Carbon.AppleEvents.typeFSRef, defaultLocation.data)
     if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType):
         typeList = args['typeList'][:]
         # Workaround for OSX typeless files:

Modified: python/branches/tlee-ast-optimize/Lib/plat-mac/bundlebuilder.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/plat-mac/bundlebuilder.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/plat-mac/bundlebuilder.py	Wed Jan 14 13:24:17 2009
@@ -245,14 +245,14 @@
     del sys.path[1:]  # sys.path[0] is Contents/Resources/
 """
 
-if USE_ZIPIMPORT:
-    ZIP_ARCHIVE = "Modules.zip"
-    SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
-    def getPycData(fullname, code, ispkg):
-        if ispkg:
-            fullname += ".__init__"
-        path = fullname.replace(".", os.sep) + PYC_EXT
-        return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
+ZIP_ARCHIVE = "Modules.zip"
+SITE_PY_ZIP = SITE_PY + ("sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE)
+
+def getPycData(fullname, code, ispkg):
+    if ispkg:
+        fullname += ".__init__"
+    path = fullname.replace(".", os.sep) + PYC_EXT
+    return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
 
 #
 # Extension modules can't be in the modules zip archive, so a placeholder
@@ -301,6 +301,9 @@
 libdir = os.path.join(os.path.dirname(execdir), "Frameworks")
 mainprogram = os.path.join(resdir, "%(mainprogram)s")
 
+if %(optimize)s:
+    sys.argv.insert(1, '-O')
+
 sys.argv.insert(1, mainprogram)
 if %(standalone)s or %(semi_standalone)s:
     os.environ["PYTHONPATH"] = resdir
@@ -311,6 +314,7 @@
     if pypath:
         pypath = ":" + pypath
     os.environ["PYTHONPATH"] = resdir + pypath
+
 os.environ["PYTHONEXECUTABLE"] = executable
 os.environ["DYLD_LIBRARY_PATH"] = libdir
 os.environ["DYLD_FRAMEWORK_PATH"] = libdir
@@ -350,6 +354,8 @@
 
 class AppBuilder(BundleBuilder):
 
+    use_zipimport = USE_ZIPIMPORT
+
     # Override type of the bundle.
     type = "APPL"
 
@@ -506,6 +512,7 @@
                 hashbang = os.path.realpath(sys.executable)
             standalone = self.standalone
             semi_standalone = self.semi_standalone
+            optimize = sys.flags.optimize
             open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
             os.chmod(bootstrappath, 0775)
 
@@ -552,13 +559,14 @@
             self.files.append((src, dst))
 
     def _getSiteCode(self):
-        return compile(SITE_PY % {"semi_standalone": self.semi_standalone},
+        if self.use_zipimport:
+            return compile(SITE_PY % {"semi_standalone": self.semi_standalone},
                      "<-bundlebuilder.py->", "exec")
 
     def addPythonModules(self):
         self.message("Adding Python modules", 1)
 
-        if USE_ZIPIMPORT:
+        if self.use_zipimport:
             # Create a zip file containing all modules as pyc.
             import zipfile
             relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
@@ -624,7 +632,7 @@
         self.message("Finding module dependencies", 1)
         import modulefinder
         mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
-        if USE_ZIPIMPORT:
+        if self.use_zipimport:
             # zipimport imports zlib, must add it manually
             mf.import_hook("zlib")
         # manually add our own site.py
@@ -658,7 +666,7 @@
                 filename = os.path.basename(path)
                 pathitems = name.split(".")[:-1] + [filename]
                 dstpath = pathjoin(*pathitems)
-                if USE_ZIPIMPORT:
+                if self.use_zipimport:
                     if name != "zlib":
                         # neatly pack all extension modules in a subdirectory,
                         # except zlib, since it's neccesary for bootstrapping.
@@ -672,9 +680,9 @@
                 self.files.append((path, pathjoin("Contents", "Resources", dstpath)))
             if mod.__code__ is not None:
                 ispkg = mod.__path__ is not None
-                if not USE_ZIPIMPORT or name != "site":
+                if not self.use_zipimport or name != "site":
                     # Our site.py is doing the bootstrapping, so we must
-                    # include a real .pyc file if USE_ZIPIMPORT is True.
+                    # include a real .pyc file if self.use_zipimport is True.
                     self.pymodules.append((name, mod.__code__, ispkg))
 
         if hasattr(mf, "any_missing_maybe"):
@@ -820,6 +828,7 @@
       --semi-standalone  build a standalone application, which depends on
                          an installed Python, yet includes all third-party
                          modules.
+      --no-zipimport     Do not copy code into a zip file
       --python=FILE      Python to use in #! line in stead of current Python
       --lib=FILE         shared library or framework to be copied into
                          the bundle
@@ -847,7 +856,9 @@
         "mainprogram=", "creator=", "nib=", "plist=", "link",
         "link-exec", "help", "verbose", "quiet", "argv", "standalone",
         "exclude=", "include=", "package=", "strip", "iconfile=",
-        "lib=", "python=", "semi-standalone", "bundle-id=", "destroot=")
+        "lib=", "python=", "semi-standalone", "bundle-id=", "destroot="
+        "no-zipimport"
+        )
 
     try:
         options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
@@ -911,6 +922,8 @@
             builder.strip = 1
         elif opt == '--destroot':
             builder.destroot = arg
+        elif opt == '--no-zipimport':
+            builder.use_zipimport = False
 
     if len(args) != 1:
         usage("Must specify one command ('build', 'report' or 'help')")

Modified: python/branches/tlee-ast-optimize/Lib/plat-mac/macostools.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/plat-mac/macostools.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/plat-mac/macostools.py	Wed Jan 14 13:24:17 2009
@@ -62,7 +62,14 @@
     if os.sep == ':' and not ':' in head:
         head = head + ':'
     mkdirs(head)
-    os.mkdir(dst, 0777)
+
+    try:
+        os.mkdir(dst, 0777)
+    except OSError, e:
+        # be happy if someone already created the path
+        if e.errno != errno.EEXIST:
+            raise
+
 
 def touched(dst):
     """Tell the finder a file has changed. No-op on MacOSX."""

Modified: python/branches/tlee-ast-optimize/Lib/plat-mac/videoreader.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/plat-mac/videoreader.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/plat-mac/videoreader.py	Wed Jan 14 13:24:17 2009
@@ -18,7 +18,7 @@
 from Carbon import QDOffscreen
 from Carbon import Res
 try:
-    import MediaDescr
+    from Carbon import MediaDescr
 except ImportError:
     def _audiodescr(data):
         return None
@@ -238,12 +238,12 @@
         width = self.videodescr['width']
         height = self.videodescr['height']
         start = 0
-        rv = ''
+        rv = []
         for i in range(height):
             nextline = Qdoffs.GetPixMapBytes(self.pixmap, start, width*4)
             start = start + rowbytes
-            rv = rv + nextline
-        return rv
+            rv.append(nextline)
+        return ''.join(rv)
 
 def reader(url):
     try:
@@ -255,9 +255,9 @@
 def _test():
     import EasyDialogs
     try:
-        import img
+        from PIL import Image
     except ImportError:
-        img = None
+        Image = None
     import MacOS
     Qt.EnterMovies()
     path = EasyDialogs.AskFileForOpen(message='Video to convert')
@@ -277,13 +277,11 @@
         fname = 'frame%04.4d.jpg'%num
         num = num+1
         pname = os.path.join(dstdir, fname)
-        if not img: print 'Not',
+        if not Image: print 'Not',
         print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))
-        if img:
-            wrt = img.writer(imgfmt, pname)
-            wrt.width = imgw
-            wrt.height = imgh
-            wrt.write(data)
+        if Image:
+            img = Image.fromstring("RGBA", (imgw, imgh), data)
+            img.save(pname, 'JPEG')
             timestamp, data = rdr.ReadVideo()
             MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
             if num > 20:

Modified: python/branches/tlee-ast-optimize/Lib/pydoc.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/pydoc.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/pydoc.py	Wed Jan 14 13:24:17 2009
@@ -1574,6 +1574,42 @@
         'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
         'yield': ('yield', ''),
     }
+    # Either add symbols to this dictionary or to the symbols dictionary
+    # directly: Whichever is easier. They are merged later.
+    _symbols_inverse = {
+        'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'),
+        'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
+                       '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
+        'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
+        'UNARY' : ('-', '~'),
+        'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
+                                '^=', '<<=', '>>=', '**=', '//='),
+        'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
+        'COMPLEX' : ('j', 'J')
+    }
+    symbols = {
+        '%': 'OPERATORS FORMATTING',
+        '**': 'POWER',
+        ',': 'TUPLES LISTS FUNCTIONS',
+        '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
+        '...': 'ELLIPSIS',
+        ':': 'SLICINGS DICTIONARYLITERALS',
+        '@': 'def class',
+        '\\': 'STRINGS',
+        '_': 'PRIVATENAMES',
+        '__': 'PRIVATENAMES SPECIALMETHODS',
+        '`': 'BACKQUOTES',
+        '(': 'TUPLES FUNCTIONS CALLS',
+        ')': 'TUPLES FUNCTIONS CALLS',
+        '[': 'LISTS SUBSCRIPTS SLICINGS',
+        ']': 'LISTS SUBSCRIPTS SLICINGS'
+    }
+    for topic, symbols_ in _symbols_inverse.iteritems():
+        for symbol in symbols_:
+            topics = symbols.get(symbol, topic)
+            if topic not in topics:
+                topics = topics + ' ' + topic
+            symbols[symbol] = topics
 
     topics = {
         'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
@@ -1717,10 +1753,12 @@
         if type(request) is type(''):
             if request == 'help': self.intro()
             elif request == 'keywords': self.listkeywords()
+            elif request == 'symbols': self.listsymbols()
             elif request == 'topics': self.listtopics()
             elif request == 'modules': self.listmodules()
             elif request[:8] == 'modules ':
                 self.listmodules(split(request)[1])
+            elif request in self.symbols: self.showsymbol(request)
             elif request in self.keywords: self.showtopic(request)
             elif request in self.topics: self.showtopic(request)
             elif request: doc(request, 'Help on %s:')
@@ -1766,6 +1804,14 @@
 ''')
         self.list(self.keywords.keys())
 
+    def listsymbols(self):
+        self.output.write('''
+Here is a list of the punctuation symbols which Python assigns special meaning
+to. Enter any symbol to get more help.
+
+''')
+        self.list(self.symbols.keys())
+
     def listtopics(self):
         self.output.write('''
 Here is a list of available topics.  Enter any topic name to get more help.
@@ -1773,7 +1819,7 @@
 ''')
         self.list(self.topics.keys())
 
-    def showtopic(self, topic):
+    def showtopic(self, topic, more_xrefs=''):
         try:
             import pydoc_topics
         except ImportError:
@@ -1787,7 +1833,7 @@
             self.output.write('no documentation found for %s\n' % repr(topic))
             return
         if type(target) is type(''):
-            return self.showtopic(target)
+            return self.showtopic(target, more_xrefs)
 
         label, xrefs = target
         try:
@@ -1796,6 +1842,8 @@
             self.output.write('no documentation found for %s\n' % repr(topic))
             return
         pager(strip(doc) + '\n')
+        if more_xrefs:
+            xrefs = (xrefs or '') + ' ' + more_xrefs
         if xrefs:
             import StringIO, formatter
             buffer = StringIO.StringIO()
@@ -1803,6 +1851,11 @@
                 'Related help topics: ' + join(split(xrefs), ', ') + '\n')
             self.output.write('\n%s\n' % buffer.getvalue())
 
+    def showsymbol(self, symbol):
+        target = self.symbols[symbol]
+        topic, _, xrefs = target.partition(' ')
+        self.showtopic(topic, xrefs)
+
     def listmodules(self, key=''):
         if key:
             self.output.write('''

Modified: python/branches/tlee-ast-optimize/Lib/random.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/random.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/random.py	Wed Jan 14 13:24:17 2009
@@ -413,9 +413,11 @@
     def expovariate(self, lambd):
         """Exponential distribution.
 
-        lambd is 1.0 divided by the desired mean.  (The parameter would be
-        called "lambda", but that is a reserved word in Python.)  Returned
-        values range from 0 to positive infinity.
+        lambd is 1.0 divided by the desired mean.  It should be
+        nonzero.  (The parameter would be called "lambda", but that is
+        a reserved word in Python.)  Returned values range from 0 to
+        positive infinity if lambd is positive, and from negative
+        infinity to 0 if lambd is negative.
 
         """
         # lambd: rate lambd = 1/mean

Modified: python/branches/tlee-ast-optimize/Lib/re.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/re.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/re.py	Wed Jan 14 13:24:17 2009
@@ -145,7 +145,8 @@
     """Return the string obtained by replacing the leftmost
     non-overlapping occurrences of the pattern in string by the
     replacement repl.  repl can be either a string or a callable;
-    if a callable, it's passed the match object and must return
+    if a string, backslash escapes in it are processed.  If it is
+    a callable, it's passed the match object and must return
     a replacement string to be used."""
     return _compile(pattern, 0).sub(repl, string, count)
 
@@ -155,7 +156,8 @@
     non-overlapping occurrences of the pattern in the source
     string by the replacement repl.  number is the number of
     substitutions that were made. repl can be either a string or a
-    callable; if a callable, it's passed the match object and must
+    callable; if a string, backslash escapes in it are processed.
+    If it is a callable, it's passed the match object and must
     return a replacement string to be used."""
     return _compile(pattern, 0).subn(repl, string, count)
 

Modified: python/branches/tlee-ast-optimize/Lib/runpy.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/runpy.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/runpy.py	Wed Jan 14 13:24:17 2009
@@ -65,13 +65,14 @@
 
 # This helper is needed due to a missing component in the PEP 302
 # loader protocol (specifically, "get_filename" is non-standard)
+# Since we can't introduce new features in maintenance releases,
+# support was added to zipimporter under the name '_get_filename'
 def _get_filename(loader, mod_name):
-    try:
-        get_filename = loader.get_filename
-    except AttributeError:
-        return None
-    else:
-        return get_filename(mod_name)
+    for attr in ("get_filename", "_get_filename"):
+        meth = getattr(loader, attr, None)
+        if meth is not None:
+            return meth(mod_name)
+    return None
 
 # Helper to get the loader, code and filename for a module
 def _get_module_details(mod_name):

Modified: python/branches/tlee-ast-optimize/Lib/ssl.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/ssl.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/ssl.py	Wed Jan 14 13:24:17 2009
@@ -74,7 +74,7 @@
      SSL_ERROR_EOF, \
      SSL_ERROR_INVALID_ERROR_CODE
 
-from socket import socket, _fileobject
+from socket import socket, _fileobject, error as socket_error
 from socket import getnameinfo as _getnameinfo
 import base64        # for DER-to-PEM translation
 
@@ -103,7 +103,7 @@
         # see if it's connected
         try:
             socket.getpeername(self)
-        except:
+        except socket_error:
             # no, no connection yet
             self._sslobj = None
         else:
@@ -441,7 +441,7 @@
                             PROTOCOL_SSLv23, None)
     try:
         sock.getpeername()
-    except:
+    except socket_error:
         # no, no connection yet
         pass
     else:

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	Wed Jan 14 13:24:17 2009
@@ -107,7 +107,7 @@
 (Windows only)
 
 
-This module also defines two shortcut functions:
+This module also defines some shortcut functions:
 
 call(*popenargs, **kwargs):
     Run command with arguments.  Wait for command to complete, then
@@ -127,6 +127,17 @@
 
     check_call(["ls", "-l"])
 
+check_output(*popenargs, **kwargs):
+   Run command with arguments and return its output as a byte string.
+
+   If the exit code was non-zero it raises a CalledProcessError.  The
+   CalledProcessError object will have the return code in the returncode
+   attribute and output in the output attribute.
+
+   The arguments are the same as for the Popen constructor.  Example:
+
+      output = subprocess.check_output(["ls", "-l", "/dev/null"])
+
 Exceptions
 ----------
 Exceptions raised in the child process, before the new program has
@@ -141,8 +152,8 @@
 
 A ValueError will be raised if Popen is called with invalid arguments.
 
-check_call() will raise CalledProcessError, if the called process
-returns a non-zero return code.
+check_call() and check_output() will raise CalledProcessError, if the
+called process returns a non-zero return code.
 
 
 Security
@@ -361,12 +372,15 @@
 
 # Exception classes used by this module.
 class CalledProcessError(Exception):
-    """This exception is raised when a process run by check_call() returns
-    a non-zero exit status.  The exit status will be stored in the
-    returncode attribute."""
-    def __init__(self, returncode, cmd):
+    """This exception is raised when a process run by check_call() or
+    check_output() returns a non-zero exit status.
+    The exit status will be stored in the returncode attribute;
+    check_output() will also store the output in the output attribute.
+    """
+    def __init__(self, returncode, cmd, output=None):
         self.returncode = returncode
         self.cmd = cmd
+        self.output = output
     def __str__(self):
         return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
 
@@ -403,7 +417,8 @@
     import fcntl
     import pickle
 
-__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
+__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
+           "check_output", "CalledProcessError"]
 
 try:
     MAXFD = os.sysconf("SC_OPEN_MAX")
@@ -455,12 +470,45 @@
     check_call(["ls", "-l"])
     """
     retcode = call(*popenargs, **kwargs)
-    cmd = kwargs.get("args")
-    if cmd is None:
-        cmd = popenargs[0]
     if retcode:
+        cmd = kwargs.get("args")
+        if cmd is None:
+            cmd = popenargs[0]
         raise CalledProcessError(retcode, cmd)
-    return retcode
+    return 0
+
+
+def check_output(*popenargs, **kwargs):
+    """Run command with arguments and return its output as a byte string.
+
+    If the exit code was non-zero it raises a CalledProcessError.  The
+    CalledProcessError object will have the return code in the returncode
+    attribute and output in the output attribute.
+
+    The arguments are the same as for the Popen constructor.  Example:
+
+    >>> check_output(["ls", "-l", "/dev/null"])
+    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
+
+    The stdout argument is not allowed as it is used internally.
+    To capture standard error in the result, use stderr=subprocess.STDOUT.
+
+    >>> check_output(["/bin/sh", "-c",
+                      "ls -l non_existant_file ; exit 0"],
+                     stderr=subprocess.STDOUT)
+    'ls: non_existant_file: No such file or directory\n'
+    """
+    if 'stdout' in kwargs:
+        raise ValueError('stdout argument not allowed, it will be overridden.')
+    process = Popen(*popenargs, stdout=PIPE, **kwargs)
+    output, unused_err = process.communicate()
+    retcode = process.poll()
+    if retcode:
+        cmd = kwargs.get("args")
+        if cmd is None:
+            cmd = popenargs[0]
+        raise CalledProcessError(retcode, cmd, output=output)
+    return output
 
 
 def list2cmdline(seq):

Modified: python/branches/tlee-ast-optimize/Lib/tarfile.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/tarfile.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/tarfile.py	Wed Jan 14 13:24:17 2009
@@ -2284,10 +2284,6 @@
         """
         if not hasattr(os, 'utime'):
             return
-        if sys.platform == "win32" and tarinfo.isdir():
-            # According to msdn.microsoft.com, it is an error (EACCES)
-            # to use utime() on directories.
-            return
         try:
             os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
         except EnvironmentError, e:

Deleted: python/branches/tlee-ast-optimize/Lib/test/crashers/iter.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/crashers/iter.py	Wed Jan 14 13:24:17 2009
+++ (empty file)
@@ -1,53 +0,0 @@
-# Calls to PyIter_Next, or direct calls to tp_iternext, on an object
-# which might no longer be an iterable because its 'next' method was
-# removed.  These are all variants of Issue3720.
-
-"""
-Run this script with an argument between 1 and <N> to test for
-different crashes.
-"""
-N = 8
-
-import sys
-
-class Foo(object):
-    def __iter__(self):
-        return self
-    def next(self):
-        del Foo.next
-        return (1, 2)
-
-def case1():
-    list(enumerate(Foo()))
-
-def case2():
-    x, y = Foo()
-
-def case3():
-    filter(None, Foo())
-
-def case4():
-    map(None, Foo(), Foo())
-
-def case5():
-    max(Foo())
-
-def case6():
-    sum(Foo(), ())
-
-def case7():
-    dict(Foo())
-
-def case8():
-    sys.stdout.writelines(Foo())
-
-# etc...
-
-
-if __name__ == '__main__':
-    if len(sys.argv) < 2:
-        print __doc__.replace('<N>', str(N))
-    else:
-        n = int(sys.argv[1])
-        func = globals()['case%d' % n]
-        func()

Modified: python/branches/tlee-ast-optimize/Lib/test/decimaltestdata/extra.decTest
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/decimaltestdata/extra.decTest	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/decimaltestdata/extra.decTest	Wed Jan 14 13:24:17 2009
@@ -154,6 +154,23 @@
 extr1302 fma 0E123 -Inf sNaN789 -> NaN Invalid_operation
 extr1302 fma -Inf 0E-456 sNaN148 -> NaN Invalid_operation
 
+-- max/min/max_mag/min_mag bug in 2.5.2/2.6/3.0: max(NaN, finite) gave
+-- incorrect answers when the finite number required rounding; similarly
+-- for the other thre functions
+maxexponent: 999
+minexponent: -999
+precision: 6
+rounding: half_even
+extr1400 max NaN 1234567 -> 1.23457E+6 Inexact Rounded
+extr1401 max 3141590E-123 NaN1729 -> 3.14159E-117 Rounded
+extr1402 max -7.654321 -NaN -> -7.65432 Inexact Rounded
+extr1410 min -NaN -765432.1 -> -765432 Inexact Rounded
+extr1411 min 3141592 NaN -> 3.14159E+6 Inexact Rounded
+extr1420 max_mag 0.1111111 -NaN123 -> 0.111111 Inexact Rounded
+extr1421 max_mag NaN999999999 0.001234567 -> 0.00123457 Inexact Rounded
+extr1430 min_mag 9181716151 -NaN -> 9.18172E+9 Inexact Rounded
+extr1431 min_mag NaN4 1.818180E100 -> 1.81818E+100 Rounded
+
 -- Tests for the is_* boolean operations
 precision: 9
 maxExponent: 999

Modified: python/branches/tlee-ast-optimize/Lib/test/list_tests.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/list_tests.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/list_tests.py	Wed Jan 14 13:24:17 2009
@@ -84,6 +84,8 @@
         self.assertRaises(StopIteration, r.next)
         self.assertEqual(list(reversed(self.type2test())),
                          self.type2test())
+        # Bug 3689: make sure list-reversed-iterator doesn't have __len__
+        self.assertRaises(TypeError, len, reversed([1,2,3]))
 
     def test_setitem(self):
         a = self.type2test([0, 1])

Modified: python/branches/tlee-ast-optimize/Lib/test/pickletester.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/pickletester.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/pickletester.py	Wed Jan 14 13:24:17 2009
@@ -480,14 +480,21 @@
 
     if have_unicode:
         def test_unicode(self):
-            endcases = [unicode(''), unicode('<\\u>'), unicode('<\\\u1234>'),
-                        unicode('<\n>'),  unicode('<\\>')]
+            endcases = [u'', u'<\\u>', u'<\\\u1234>', u'<\n>',
+                        u'<\\>', u'<\\\U00012345>']
             for proto in protocols:
                 for u in endcases:
                     p = self.dumps(u, proto)
                     u2 = self.loads(p)
                     self.assertEqual(u2, u)
 
+        def test_unicode_high_plane(self):
+            t = u'\U00012345'
+            for proto in protocols:
+                p = self.dumps(t, proto)
+                t2 = self.loads(p)
+                self.assertEqual(t2, t)
+
     def test_ints(self):
         import sys
         for proto in protocols:

Modified: python/branches/tlee-ast-optimize/Lib/test/test_array.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_array.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_array.py	Wed Jan 14 13:24:17 2009
@@ -7,7 +7,7 @@
 from test import test_support
 from weakref import proxy
 import array, cStringIO
-from cPickle import loads, dumps
+from cPickle import loads, dumps, HIGHEST_PROTOCOL
 
 class ArraySubclass(array.array):
     pass
@@ -97,7 +97,7 @@
         self.assertEqual(a, b)
 
     def test_pickle(self):
-        for protocol in (0, 1, 2):
+        for protocol in range(HIGHEST_PROTOCOL + 1):
             a = array.array(self.typecode, self.example)
             b = loads(dumps(a, protocol))
             self.assertNotEqual(id(a), id(b))
@@ -112,7 +112,7 @@
             self.assertEqual(type(a), type(b))
 
     def test_pickle_for_empty_array(self):
-        for protocol in (0, 1, 2):
+        for protocol in range(HIGHEST_PROTOCOL + 1):
             a = array.array(self.typecode)
             b = loads(dumps(a, protocol))
             self.assertNotEqual(id(a), id(b))

Modified: python/branches/tlee-ast-optimize/Lib/test/test_ast.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_ast.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_ast.py	Wed Jan 14 13:24:17 2009
@@ -272,6 +272,12 @@
         self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
         self.assertRaises(ValueError, ast.literal_eval, 'foo()')
 
+    def test_literal_eval_issue4907(self):
+        self.assertEqual(ast.literal_eval('2j'), 2j)
+        self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
+        self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
+        self.assertRaises(ValueError, ast.literal_eval, '2 + (3 + 4j)')
+
 
 def test_main():
     test_support.run_unittest(AST_Tests, ASTHelpers_Test)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_bytes.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_bytes.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_bytes.py	Wed Jan 14 13:24:17 2009
@@ -752,6 +752,38 @@
         self.assertEqual(b, b"")
         self.assertEqual(c, b"")
 
+    # XXX memoryview not available
+    def XXXtest_resize_forbidden(self):
+        # #4509: can't resize a bytearray when there are buffer exports, even
+        # if it wouldn't reallocate the underlying buffer.
+        # Furthermore, no destructive changes to the buffer may be applied
+        # before raising the error.
+        b = bytearray(range(10))
+        v = memoryview(b)
+        def resize(n):
+            b[1:-1] = range(n + 1, 2*n - 1)
+        resize(10)
+        orig = b[:]
+        self.assertRaises(BufferError, resize, 11)
+        self.assertEquals(b, orig)
+        self.assertRaises(BufferError, resize, 9)
+        self.assertEquals(b, orig)
+        self.assertRaises(BufferError, resize, 0)
+        self.assertEquals(b, orig)
+        # Other operations implying resize
+        self.assertRaises(BufferError, b.pop, 0)
+        self.assertEquals(b, orig)
+        self.assertRaises(BufferError, b.remove, b[1])
+        self.assertEquals(b, orig)
+        def delitem():
+            del b[1]
+        self.assertRaises(BufferError, delitem)
+        self.assertEquals(b, orig)
+        # deleting a non-contiguous slice
+        def delslice():
+            b[1:-1:2] = b""
+        self.assertRaises(BufferError, delslice)
+        self.assertEquals(b, orig)
 
 class AssortedBytesTest(unittest.TestCase):
     #
@@ -840,11 +872,21 @@
 
     def test_translate(self):
         b = b'hello'
+        ba = bytearray(b)
         rosetta = bytearray(range(0, 256))
         rosetta[ord('o')] = ord('e')
         c = b.translate(rosetta, b'l')
         self.assertEqual(b, b'hello')
         self.assertEqual(c, b'hee')
+        c = ba.translate(rosetta, b'l')
+        self.assertEqual(ba, b'hello')
+        self.assertEqual(c, b'hee')
+        c = b.translate(None, b'e')
+        self.assertEqual(c, b'hllo')
+        c = ba.translate(None, b'e')
+        self.assertEqual(c, b'hllo')
+        self.assertRaises(TypeError, b.translate, None, None)
+        self.assertRaises(TypeError, ba.translate, None, None)
 
     def test_split_bytearray(self):
         self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b'])

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	Wed Jan 14 13:24:17 2009
@@ -284,6 +284,28 @@
         bz2f.close()
         self.assertEqual(xlines, ['Test'])
 
+    def testContextProtocol(self):
+        # BZ2File supports the context management protocol
+        f = None
+        with BZ2File(self.filename, "wb") as f:
+            f.write(b"xxx")
+        f = BZ2File(self.filename, "rb")
+        f.close()
+        try:
+            with f:
+                pass
+        except ValueError:
+            pass
+        else:
+            self.fail("__enter__ on a closed file didn't raise an exception")
+        try:
+            with BZ2File(self.filename, "wb") as f:
+                1/0
+        except ZeroDivisionError:
+            pass
+        else:
+            self.fail("1/0 didn't raise an exception")
+
 
 class BZ2CompressorTest(BaseTest):
     def testCompress(self):

Modified: python/branches/tlee-ast-optimize/Lib/test/test_capi.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_capi.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_capi.py	Wed Jan 14 13:24:17 2009
@@ -2,9 +2,74 @@
 # these are all functions _testcapi exports whose name begins with 'test_'.
 
 import sys
+import time
+import random
+import unittest
+import threading
 from test import test_support
 import _testcapi
 
+class TestPendingCalls(unittest.TestCase):
+
+    def pendingcalls_submit(self, l, n):
+        def callback():
+            #this function can be interrupted by thread switching so let's
+            #use an atomic operation
+            l.append(None)
+
+        for i in range(n):
+            time.sleep(random.random()*0.02) #0.01 secs on average
+            #try submitting callback until successful.
+            #rely on regular interrupt to flush queue if we are
+            #unsuccessful.
+            while True:
+                if _testcapi._pending_threadfunc(callback):
+                    break;
+
+    def pendingcalls_wait(self, l, n):
+        #now, stick around until l[0] has grown to 10
+        count = 0;
+        while len(l) != n:
+            #this busy loop is where we expect to be interrupted to
+            #run our callbacks.  Note that callbacks are only run on the
+            #main thread
+            if False and test_support.verbose:
+                print "(%i)"%(len(l),),
+            for i in xrange(1000):
+                a = i*i
+            count += 1
+            self.failUnless(count < 10000,
+                "timeout waiting for %i callbacks, got %i"%(n, len(l)))
+        if False and test_support.verbose:
+            print "(%i)"%(len(l),)
+
+    def test_pendingcalls_threaded(self):
+        l = []
+
+        #do every callback on a separate thread
+        n = 32
+        threads = []
+        for i in range(n):
+            t = threading.Thread(target=self.pendingcalls_submit, args = (l, 1))
+            t.start()
+            threads.append(t)
+
+        self.pendingcalls_wait(l, n)
+
+        for t in threads:
+            t.join()
+
+    def test_pendingcalls_non_threaded(self):
+        #again, just using the main thread, likely they will all be dispathced at
+        #once.  It is ok to ask for too many, because we loop until we find a slot.
+        #the loop can be interrupted to dispatch.
+        #there are only 32 dispatch slots, so we go for twice that!
+        l = []
+        n = 64
+        self.pendingcalls_submit(l, n)
+        self.pendingcalls_wait(l, n)
+
+
 def test_main():
 
     for name in dir(_testcapi):
@@ -50,5 +115,7 @@
         t.start()
         t.join()
 
+    test_support.run_unittest(TestPendingCalls)
+
 if __name__ == "__main__":
     test_main()

Modified: python/branches/tlee-ast-optimize/Lib/test/test_cgi.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_cgi.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_cgi.py	Wed Jan 14 13:24:17 2009
@@ -354,6 +354,32 @@
         self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
                          cgi.parse_qsl('a=A1&b=B2&B=B3'))
 
+    def test_parse_header(self):
+        self.assertEqual(
+            cgi.parse_header("text/plain"),
+            ("text/plain", {}))
+        self.assertEqual(
+            cgi.parse_header("text/vnd.just.made.this.up ; "),
+            ("text/vnd.just.made.this.up", {}))
+        self.assertEqual(
+            cgi.parse_header("text/plain;charset=us-ascii"),
+            ("text/plain", {"charset": "us-ascii"}))
+        self.assertEqual(
+            cgi.parse_header('text/plain ; charset="us-ascii"'),
+            ("text/plain", {"charset": "us-ascii"}))
+        self.assertEqual(
+            cgi.parse_header('text/plain ; charset="us-ascii"; another=opt'),
+            ("text/plain", {"charset": "us-ascii", "another": "opt"}))
+        self.assertEqual(
+            cgi.parse_header('attachment; filename="silly.txt"'),
+            ("attachment", {"filename": "silly.txt"}))
+        self.assertEqual(
+            cgi.parse_header('attachment; filename="strange;name"'),
+            ("attachment", {"filename": "strange;name"}))
+        self.assertEqual(
+            cgi.parse_header('attachment; filename="strange;name";size=123;'),
+            ("attachment", {"filename": "strange;name", "size": "123"}))
+
 
 def test_main():
     run_unittest(CgiTests)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_cmd_line_script.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_cmd_line_script.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_cmd_line_script.py	Wed Jan 14 13:24:17 2009
@@ -75,36 +75,66 @@
         compiled_name = script_name + 'o'
     return compiled_name
 
-def _make_test_zip(zip_dir, zip_basename, script_name):
+def _make_test_zip(zip_dir, zip_basename, script_name, name_in_zip=None):
     zip_filename = zip_basename+os.extsep+'zip'
     zip_name = os.path.join(zip_dir, zip_filename)
     zip_file = zipfile.ZipFile(zip_name, 'w')
-    zip_file.write(script_name, os.path.basename(script_name))
+    if name_in_zip is None:
+        name_in_zip = os.path.basename(script_name)
+    zip_file.write(script_name, name_in_zip)
     zip_file.close()
-    # if verbose:
+    #if verbose:
     #    zip_file = zipfile.ZipFile(zip_name, 'r')
     #    print 'Contents of %r:' % zip_name
     #    zip_file.printdir()
     #    zip_file.close()
-    return zip_name
+    return zip_name, os.path.join(zip_name, name_in_zip)
 
 def _make_test_pkg(pkg_dir):
     os.mkdir(pkg_dir)
     _make_test_script(pkg_dir, '__init__', '')
 
+def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
+                       source=test_source, depth=1):
+    init_name = _make_test_script(zip_dir, '__init__', '')
+    init_basename = os.path.basename(init_name)
+    script_name = _make_test_script(zip_dir, script_basename, source)
+    pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)]
+    script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name))
+    zip_filename = zip_basename+os.extsep+'zip'
+    zip_name = os.path.join(zip_dir, zip_filename)
+    zip_file = zipfile.ZipFile(zip_name, 'w')
+    for name in pkg_names:
+        init_name_in_zip = os.path.join(name, init_basename)
+        zip_file.write(init_name, init_name_in_zip)
+    zip_file.write(script_name, script_name_in_zip)
+    zip_file.close()
+    os.unlink(init_name)
+    os.unlink(script_name)
+    #if verbose:
+    #    zip_file = zipfile.ZipFile(zip_name, 'r')
+    #    print 'Contents of %r:' % zip_name
+    #    zip_file.printdir()
+    #    zip_file.close()
+    return zip_name, os.path.join(zip_name, script_name_in_zip)
+
 # There's no easy way to pass the script directory in to get
 # -m to work (avoiding that is the whole point of making
 # directories and zipfiles executable!)
 # So we fake it for testing purposes with a custom launch script
 launch_source = """\
 import sys, os.path, runpy
-sys.path[0:0] = os.path.dirname(__file__)
+sys.path.insert(0, %s)
 runpy._run_module_as_main(%r)
 """
 
-def _make_launch_script(script_dir, script_basename, module_name):
-    return _make_test_script(script_dir, script_basename,
-                             launch_source % module_name)
+def _make_launch_script(script_dir, script_basename, module_name, path=None):
+    if path is None:
+        path = "os.path.dirname(__file__)"
+    else:
+        path = repr(path)
+    source = launch_source % (path, module_name)
+    return _make_test_script(script_dir, script_basename, source)
 
 class CmdLineTest(unittest.TestCase):
     def _check_script(self, script_name, expected_file,
@@ -155,15 +185,15 @@
     def test_zipfile(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
-            zip_name = _make_test_zip(script_dir, 'test_zip', script_name)
-            self._check_script(zip_name, None, zip_name, '')
+            zip_name, run_name = _make_test_zip(script_dir, 'test_zip', script_name)
+            self._check_script(zip_name, run_name, zip_name, '')
 
     def test_zipfile_compiled(self):
         with temp_dir() as script_dir:
             script_name = _make_test_script(script_dir, '__main__')
             compiled_name = _compile_test_script(script_name)
-            zip_name = _make_test_zip(script_dir, 'test_zip', compiled_name)
-            self._check_script(zip_name, None, zip_name, '')
+            zip_name, run_name = _make_test_zip(script_dir, 'test_zip', compiled_name)
+            self._check_script(zip_name, run_name, zip_name, '')
 
     def test_module_in_package(self):
         with temp_dir() as script_dir:
@@ -171,8 +201,19 @@
             _make_test_pkg(pkg_dir)
             script_name = _make_test_script(pkg_dir, 'script')
             launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script')
-            self._check_script(launch_name, script_name,
-                               script_name, 'test_pkg')
+            self._check_script(launch_name, script_name, script_name, 'test_pkg')
+
+    def test_module_in_package_in_zipfile(self):
+        with temp_dir() as script_dir:
+            zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
+            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
+            self._check_script(launch_name, run_name, run_name, 'test_pkg')
+
+    def test_module_in_subpackage_in_zipfile(self):
+        with temp_dir() as script_dir:
+            zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
+            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
+            self._check_script(launch_name, run_name, run_name, 'test_pkg.test_pkg')
 
 
 def test_main():

Modified: python/branches/tlee-ast-optimize/Lib/test/test_collections.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_collections.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_collections.py	Wed Jan 14 13:24:17 2009
@@ -1,6 +1,6 @@
 import unittest, doctest
 from test import test_support
-from collections import namedtuple
+from collections import namedtuple, Counter, Mapping
 import pickle, cPickle, copy
 from collections import Hashable, Iterable, Iterator
 from collections import Sized, Container, Callable
@@ -346,11 +346,109 @@
             self.failUnless(issubclass(sample, MutableSequence))
         self.failIf(issubclass(basestring, MutableSequence))
 
+class TestCounter(unittest.TestCase):
+
+    def test_basics(self):
+        c = Counter('abcaba')
+        self.assert_(isinstance(c, dict))
+        self.assert_(isinstance(c, Mapping))
+        self.assert_(issubclass(Counter, dict))
+        self.assert_(issubclass(Counter, Mapping))
+        self.assertEqual(len(c), 3)
+        self.assertEqual(sum(c.values()), 6)
+        self.assertEqual(sorted(c.values()), [1, 2, 3])
+        self.assertEqual(sorted(c.keys()), ['a', 'b', 'c'])
+        self.assertEqual(sorted(c), ['a', 'b', 'c'])
+        self.assertEqual(sorted(c.items()),
+                         [('a', 3), ('b', 2), ('c', 1)])
+        self.assertEqual(c['b'], 2)
+        self.assertEqual(c['z'], 0)
+        self.assertEqual(c.has_key('c'), True)
+        self.assertEqual(c.has_key('z'), False)
+        self.assertEqual(c.__contains__('c'), True)
+        self.assertEqual(c.__contains__('z'), False)
+        self.assertEqual(c.get('b', 10), 2)
+        self.assertEqual(c.get('z', 10), 10)
+        self.assertEqual(c, dict(a=3, b=2, c=1))
+        self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})")
+        self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)])
+        for i in range(5):
+            self.assertEqual(c.most_common(i),
+                             [('a', 3), ('b', 2), ('c', 1)][:i])
+        self.assertEqual(''.join(sorted(c.elements())), 'aaabbc')
+        c['a'] += 1         # increment an existing value
+        c['b'] -= 2         # sub existing value to zero
+        del c['c']          # remove an entry
+        c['d'] -= 2         # sub from a missing value
+        c['e'] = -5         # directly assign a missing value
+        c['f'] += 4         # add to a missing value
+        self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4))
+        self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff')
+        self.assertEqual(c.pop('f'), 4)
+        self.assertEqual('f' in c, False)
+        for i in range(3):
+            elem, cnt = c.popitem()
+            self.assertEqual(elem in c, False)
+        c.clear()
+        self.assertEqual(c, {})
+        self.assertEqual(repr(c), 'Counter()')
+        self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc')
+        self.assertRaises(TypeError, hash, c)
+        c.update(dict(a=5, b=3, c=1))
+        c.update(Counter('a' * 50 + 'b' * 30))
+        c.update()          # test case with no args
+        c.__init__('a' * 500 + 'b' * 300)
+        c.__init__('cdc')
+        c.__init__()
+        self.assertEqual(c, dict(a=555, b=333, c=3, d=1))
+        self.assertEqual(c.setdefault('d', 5), 1)
+        self.assertEqual(c['d'], 1)
+        self.assertEqual(c.setdefault('e', 5), 5)
+        self.assertEqual(c['e'], 5)
+
+    def test_copying(self):
+        # Check that counters are copyable, deepcopyable, picklable, and
+        #have a repr/eval round-trip
+        words = Counter('which witch had which witches wrist watch'.split())
+        update_test = Counter()
+        update_test.update(words)
+        for i, dup in enumerate([
+                    words.copy(),
+                    copy.copy(words),
+                    copy.deepcopy(words),
+                    pickle.loads(pickle.dumps(words, 0)),
+                    pickle.loads(pickle.dumps(words, 1)),
+                    pickle.loads(pickle.dumps(words, 2)),
+                    pickle.loads(pickle.dumps(words, -1)),
+                    cPickle.loads(cPickle.dumps(words, 0)),
+                    cPickle.loads(cPickle.dumps(words, 1)),
+                    cPickle.loads(cPickle.dumps(words, 2)),
+                    cPickle.loads(cPickle.dumps(words, -1)),
+                    eval(repr(words)),
+                    update_test,
+                    Counter(words),
+                    ]):
+            msg = (i, dup, words)
+            self.assert_(dup is not words)
+            self.assertEquals(dup, words)
+            self.assertEquals(len(dup), len(words))
+            self.assertEquals(type(dup), type(words))
+
+    def test_conversions(self):
+        # Convert to: set, list, dict
+        s = 'she sells sea shells by the sea shore'
+        self.assertEqual(sorted(Counter(s).elements()), sorted(s))
+        self.assertEqual(sorted(Counter(s)), sorted(set(s)))
+        self.assertEqual(dict(Counter(s)), dict(Counter(s).items()))
+        self.assertEqual(set(Counter(s)), set(s))
+
+
 import doctest, collections
 
 def test_main(verbose=None):
     NamedTupleDocs = doctest.DocTestSuite(module=collections)
-    test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, TestCollectionABCs]
+    test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs,
+                    TestCollectionABCs, TestCounter]
     test_support.run_unittest(*test_classes)
     test_support.run_doctest(collections, verbose)
 

Modified: python/branches/tlee-ast-optimize/Lib/test/test_datetime.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_datetime.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_datetime.py	Wed Jan 14 13:24:17 2009
@@ -856,6 +856,14 @@
         # A naive object replaces %z and %Z w/ empty strings.
         self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
 
+        #make sure that invalid format specifiers are handled correctly
+        self.assertRaises(ValueError, t.strftime, "%e")
+        self.assertRaises(ValueError, t.strftime, "%")
+        self.assertRaises(ValueError, t.strftime, "%#")
+
+        #check that this standard extension works
+        t.strftime("%f")
+
 
     def test_format(self):
         dt = self.theclass(2007, 9, 10)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_decimal.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_decimal.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_decimal.py	Wed Jan 14 13:24:17 2009
@@ -168,7 +168,6 @@
         -context.Emin > DEC_MAX_MATH):
         return True
     if not v._is_special and v and (
-        len(v._int) > DEC_MAX_MATH or
         v.adjusted() > DEC_MAX_MATH or
         v.adjusted() < 1-2*DEC_MAX_MATH):
         return True
@@ -1361,6 +1360,55 @@
             r = d.to_integral(ROUND_DOWN)
             self.assertEqual(Decimal(math.trunc(d)), r)
 
+    def test_from_float(self):
+
+        class  MyDecimal(Decimal):
+            pass
+
+        r = MyDecimal.from_float(0.1)
+        self.assertEqual(type(r), MyDecimal)
+        self.assertEqual(str(r),
+                '0.1000000000000000055511151231257827021181583404541015625')
+        bigint = 12345678901234567890123456789
+        self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
+        self.assert_(MyDecimal.from_float(float('nan')).is_qnan())
+        self.assert_(MyDecimal.from_float(float('inf')).is_infinite())
+        self.assert_(MyDecimal.from_float(float('-inf')).is_infinite())
+        self.assertEqual(str(MyDecimal.from_float(float('nan'))),
+                         str(Decimal('NaN')))
+        self.assertEqual(str(MyDecimal.from_float(float('inf'))),
+                         str(Decimal('Infinity')))
+        self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
+                         str(Decimal('-Infinity')))
+        self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
+        for i in range(200):
+            x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
+            self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
+
+    def test_create_decimal_from_float(self):
+        context = Context(prec=5, rounding=ROUND_DOWN)
+        self.assertEqual(
+            context.create_decimal_from_float(math.pi),
+            Decimal('3.1415')
+        )
+        context = Context(prec=5, rounding=ROUND_UP)
+        self.assertEqual(
+            context.create_decimal_from_float(math.pi),
+            Decimal('3.1416')
+        )
+        context = Context(prec=5, traps=[Inexact])
+        self.assertRaises(
+            Inexact,
+            context.create_decimal_from_float,
+            math.pi
+        )
+        self.assertEqual(repr(context.create_decimal_from_float(-0.0)),
+                         "Decimal('-0')")
+        self.assertEqual(repr(context.create_decimal_from_float(1.0)),
+                         "Decimal('1')")
+        self.assertEqual(repr(context.create_decimal_from_float(10)),
+                         "Decimal('10')")
+
 class ContextAPItests(unittest.TestCase):
 
     def test_pickle(self):

Modified: python/branches/tlee-ast-optimize/Lib/test/test_deque.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_deque.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_deque.py	Wed Jan 14 13:24:17 2009
@@ -1,7 +1,8 @@
 from collections import deque
 import unittest
 from test import test_support, seq_tests
-from weakref import proxy
+import gc
+import weakref
 import copy
 import cPickle as pickle
 import random
@@ -373,7 +374,7 @@
 
     def test_pickle(self):
         d = deque(xrange(200))
-        for i in (0, 1, 2):
+        for i in range(pickle.HIGHEST_PROTOCOL + 1):
             s = pickle.dumps(d, i)
             e = pickle.loads(s)
             self.assertNotEqual(id(d), id(e))
@@ -382,7 +383,7 @@
 ##    def test_pickle_recursive(self):
 ##        d = deque('abc')
 ##        d.append(d)
-##        for i in (0, 1, 2):
+##        for i in range(pickle.HIGHEST_PROTOCOL + 1):
 ##            e = pickle.loads(pickle.dumps(d, i))
 ##            self.assertNotEqual(id(d), id(e))
 ##            self.assertEqual(id(e), id(e[-1]))
@@ -418,6 +419,22 @@
             d.append(1)
             gc.collect()
 
+    def test_container_iterator(self):
+        # Bug #3680: tp_traverse was not implemented for deque iterator objects
+        class C(object):
+            pass
+        for i in range(2):
+            obj = C()
+            ref = weakref.ref(obj)
+            if i == 0:
+                container = deque([obj, 1])
+            else:
+                container = reversed(deque([obj, 1]))
+            obj.x = iter(container)
+            del obj, container
+            gc.collect()
+            self.assert_(ref() is None, "Cycle was not collected")
+
 class TestVariousIteratorArgs(unittest.TestCase):
 
     def test_constructor(self):
@@ -528,7 +545,7 @@
 
     def test_weakref(self):
         d = deque('gallahad')
-        p = proxy(d)
+        p = weakref.proxy(d)
         self.assertEqual(str(p), str(d))
         d = None
         self.assertRaises(ReferenceError, str, p)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_dict.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_dict.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_dict.py	Wed Jan 14 13:24:17 2009
@@ -2,6 +2,7 @@
 from test import test_support
 
 import UserDict, random, string
+import gc, weakref
 
 
 class DictTest(unittest.TestCase):
@@ -554,6 +555,19 @@
             pass
         d = {}
 
+    def test_container_iterator(self):
+        # Bug #3680: tp_traverse was not implemented for dictiter objects
+        class C(object):
+            pass
+        iterators = (dict.iteritems, dict.itervalues, dict.iterkeys)
+        for i in iterators:
+            obj = C()
+            ref = weakref.ref(obj)
+            container = {obj: 1}
+            obj.x = i(container)
+            del obj, container
+            gc.collect()
+            self.assert_(ref() is None, "Cycle was not collected")
 
 
 from test import mapping_tests

Modified: python/branches/tlee-ast-optimize/Lib/test/test_dis.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_dis.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_dis.py	Wed Jan 14 13:24:17 2009
@@ -54,29 +54,25 @@
 
 dis_bug1333982 = """\
  %-4d         0 LOAD_CONST               1 (0)
-              3 JUMP_IF_TRUE            41 (to 47)
+              3 JUMP_IF_TRUE            33 (to 39)
               6 POP_TOP
               7 LOAD_GLOBAL              0 (AssertionError)
              10 BUILD_LIST               0
-             13 DUP_TOP
-             14 STORE_FAST               1 (_[1])
-             17 LOAD_FAST                0 (x)
-             20 GET_ITER
-        >>   21 FOR_ITER                13 (to 37)
-             24 STORE_FAST               2 (s)
-             27 LOAD_FAST                1 (_[1])
-             30 LOAD_FAST                2 (s)
-             33 LIST_APPEND
-             34 JUMP_ABSOLUTE           21
-        >>   37 DELETE_FAST              1 (_[1])
-
- %-4d        40 LOAD_CONST               2 (1)
-             43 BINARY_ADD
-             44 RAISE_VARARGS            2
-        >>   47 POP_TOP
+             13 LOAD_FAST                0 (x)
+             16 GET_ITER
+        >>   17 FOR_ITER                12 (to 32)
+             20 STORE_FAST               1 (s)
+             23 LOAD_FAST                1 (s)
+             26 LIST_APPEND              2
+             29 JUMP_ABSOLUTE           17
+
+ %-4d   >>   32 LOAD_CONST               2 (1)
+             35 BINARY_ADD
+             36 RAISE_VARARGS            2
+        >>   39 POP_TOP
 
- %-4d        48 LOAD_CONST               0 (None)
-             51 RETURN_VALUE
+ %-4d        40 LOAD_CONST               0 (None)
+             43 RETURN_VALUE
 """%(bug1333982.func_code.co_firstlineno + 1,
      bug1333982.func_code.co_firstlineno + 2,
      bug1333982.func_code.co_firstlineno + 3)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_doctest.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_doctest.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_doctest.py	Wed Jan 14 13:24:17 2009
@@ -6,6 +6,9 @@
 import doctest
 import warnings
 
+# NOTE: There are some additional tests relating to interaction with
+#       zipimport in the test_zipimport_support test module.
+
 ######################################################################
 ## Sample Objects (used by test cases)
 ######################################################################
@@ -369,7 +372,7 @@
     >>> tests = finder.find(sample_func)
 
     >>> print tests  # doctest: +ELLIPSIS
-    [<DocTest sample_func from ...:13 (1 example)>]
+    [<DocTest sample_func from ...:16 (1 example)>]
 
 The exact name depends on how test_doctest was invoked, so allow for
 leading path components.

Modified: python/branches/tlee-ast-optimize/Lib/test/test_file.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_file.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_file.py	Wed Jan 14 13:24:17 2009
@@ -120,9 +120,24 @@
         except:
             self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
 
+    def testReadWhenWriting(self):
+        self.assertRaises(IOError, self.f.read)
 
 class OtherFileTests(unittest.TestCase):
 
+    def testOpenDir(self):
+        this_dir = os.path.dirname(__file__)
+        for mode in (None, "w"):
+            try:
+                if mode:
+                    f = open(this_dir, mode)
+                else:
+                    f = open(this_dir)
+            except IOError as e:
+                self.assertEqual(e.filename, this_dir)
+            else:
+                self.fail("opening a directory didn't raise an IOError")
+
     def testModeStrings(self):
         # check invalid mode strings
         for mode in ("", "aU", "wU+"):
@@ -531,6 +546,20 @@
         finally:
             sys.stdout = save_stdout
 
+    def test_del_stdout_before_print(self):
+        # Issue 4597: 'print' with no argument wasn't reporting when
+        # sys.stdout was deleted.
+        save_stdout = sys.stdout
+        del sys.stdout
+        try:
+            print
+        except RuntimeError as e:
+            self.assertEquals(str(e), "lost sys.stdout")
+        else:
+            self.fail("Expected RuntimeError")
+        finally:
+            sys.stdout = save_stdout
+
 
 def test_main():
     # Historically, these tests have been sloppy about removing TESTFN.

Modified: python/branches/tlee-ast-optimize/Lib/test/test_fileio.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_fileio.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_fileio.py	Wed Jan 14 13:24:17 2009
@@ -109,6 +109,7 @@
             _fileio._FileIO('.', 'r')
         except IOError as e:
             self.assertNotEqual(e.errno, 0)
+            self.assertEqual(e.filename, ".")
         else:
             self.fail("Should have raised IOError")
 

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	Wed Jan 14 13:24:17 2009
@@ -139,6 +139,8 @@
     def testFromFloat(self):
         self.assertRaises(TypeError, F.from_float, 3+4j)
         self.assertEquals((10, 1), _components(F.from_float(10)))
+        bigint = 1234567890123456789
+        self.assertEquals((bigint, 1), _components(F.from_float(bigint)))
         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)))

Modified: python/branches/tlee-ast-optimize/Lib/test/test_generators.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_generators.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_generators.py	Wed Jan 14 13:24:17 2009
@@ -928,6 +928,16 @@
 'f'
 >>> repr(g)  # doctest: +ELLIPSIS
 '<generator object f at ...>'
+
+Lambdas shouldn't have their usual return behavior.
+
+>>> x = lambda: (yield 1)
+>>> list(x())
+[1]
+
+>>> x = lambda: ((yield 1), (yield 2))
+>>> list(x())
+[1, 2]
 """
 
 # conjoin is a simple backtracking generator, named in honor of Icon's

Modified: python/branches/tlee-ast-optimize/Lib/test/test_getopt.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_getopt.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_getopt.py	Wed Jan 14 13:24:17 2009
@@ -124,6 +124,11 @@
         self.assertEqual(opts, [('-a', ''), ('-b', '1'),
                                 ('--alpha', ''), ('--beta', '2')])
 
+        # recognize "-" as an argument
+        opts, args = getopt.gnu_getopt(['-a', '-', '-b', '-'], 'ab:', [])
+        self.assertEqual(args, ['-'])
+        self.assertEqual(opts, [('-a', ''), ('-b', '-')])
+
         # Posix style via +
         opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta='])
         self.assertEqual(opts, [('-a', '')])

Modified: python/branches/tlee-ast-optimize/Lib/test/test_gzip.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_gzip.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_gzip.py	Wed Jan 14 13:24:17 2009
@@ -6,6 +6,7 @@
 from test import test_support
 import os
 import gzip
+import struct
 
 
 data1 = """  int length=DEFAULTALLOC, err = Z_OK;
@@ -160,6 +161,87 @@
             self.assertEqual(f.name, self.filename)
             f.close()
 
+    def test_mtime(self):
+        mtime = 123456789
+        fWrite = gzip.GzipFile(self.filename, 'w', mtime = mtime)
+        fWrite.write(data1)
+        fWrite.close()
+        fRead = gzip.GzipFile(self.filename)
+        dataRead = fRead.read()
+        self.assertEqual(dataRead, data1)
+        self.assert_(hasattr(fRead, 'mtime'))
+        self.assertEqual(fRead.mtime, mtime)
+        fRead.close()
+
+    def test_metadata(self):
+        mtime = 123456789
+
+        fWrite = gzip.GzipFile(self.filename, 'w', mtime = mtime)
+        fWrite.write(data1)
+        fWrite.close()
+
+        fRead = open(self.filename, 'rb')
+
+        # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
+
+        idBytes = fRead.read(2)
+        self.assertEqual(idBytes, '\x1f\x8b') # gzip ID
+
+        cmByte = fRead.read(1)
+        self.assertEqual(cmByte, '\x08') # deflate
+
+        flagsByte = fRead.read(1)
+        self.assertEqual(flagsByte, '\x08') # only the FNAME flag is set
+
+        mtimeBytes = fRead.read(4)
+        self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
+
+        xflByte = fRead.read(1)
+        self.assertEqual(xflByte, '\x02') # maximum compression
+
+        osByte = fRead.read(1)
+        self.assertEqual(osByte, '\xff') # OS "unknown" (OS-independent)
+
+        # Since the FNAME flag is set, the zero-terminated filename follows.
+        # RFC 1952 specifies that this is the name of the input file, if any.
+        # However, the gzip module defaults to storing the name of the output
+        # file in this field.
+        nameBytes = fRead.read(len(self.filename) + 1)
+        self.assertEqual(nameBytes, self.filename + '\x00')
+
+        # Since no other flags were set, the header ends here.
+        # Rather than process the compressed data, let's seek to the trailer.
+        fRead.seek(os.stat(self.filename).st_size - 8)
+
+        crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
+        self.assertEqual(crc32Bytes, '\xaf\xd7d\x83')
+
+        isizeBytes = fRead.read(4)
+        self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
+
+        fRead.close()
+
+    def test_with_open(self):
+        # GzipFile supports the context management protocol
+        with gzip.GzipFile(self.filename, "wb") as f:
+            f.write(b"xxx")
+        f = gzip.GzipFile(self.filename, "rb")
+        f.close()
+        try:
+            with f:
+                pass
+        except ValueError:
+            pass
+        else:
+            self.fail("__enter__ on a closed file didn't raise an exception")
+        try:
+            with gzip.GzipFile(self.filename, "wb") as f:
+                1/0
+        except ZeroDivisionError:
+            pass
+        else:
+            self.fail("1/0 didn't raise an exception")
+
 def test_main(verbose=None):
     test_support.run_unittest(TestGzip)
 

Modified: python/branches/tlee-ast-optimize/Lib/test/test_hash.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_hash.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_hash.py	Wed Jan 14 13:24:17 2009
@@ -111,9 +111,32 @@
             self.assertFalse(isinstance(obj, Hashable), repr(obj))
 
 
+# Issue #4701: Check that some builtin types are correctly hashable
+#  (This test only used to fail in Python 3.0, but has been included
+#   in 2.x along with the lazy call to PyType_Ready in PyObject_Hash)
+class DefaultIterSeq(object):
+    seq = range(10)
+    def __len__(self):
+        return len(self.seq)
+    def __getitem__(self, index):
+        return self.seq[index]
+
+class HashBuiltinsTestCase(unittest.TestCase):
+    hashes_to_check = [xrange(10),
+                       enumerate(xrange(10)),
+                       iter(DefaultIterSeq()),
+                       iter(lambda: 0, 0),
+                      ]
+
+    def test_hashes(self):
+        _default_hash = object.__hash__
+        for obj in self.hashes_to_check:
+            self.assertEqual(hash(obj), _default_hash(obj))
+
 def test_main():
     test_support.run_unittest(HashEqualityTestCase,
-                              HashInheritanceTestCase)
+                              HashInheritanceTestCase,
+                              HashBuiltinsTestCase)
 
 
 if __name__ == "__main__":

Modified: python/branches/tlee-ast-optimize/Lib/test/test_hotshot.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_hotshot.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_hotshot.py	Wed Jan 14 13:24:17 2009
@@ -3,6 +3,8 @@
 import os
 import pprint
 import unittest
+import _hotshot
+import gc
 
 from test import test_support
 
@@ -124,6 +126,10 @@
             if os.path.exists(test_support.TESTFN):
                 os.remove(test_support.TESTFN)
 
+    def test_logreader_eof_error(self):
+        self.assertRaises((IOError, EOFError), _hotshot.logreader, ".")
+        gc.collect()
+
 def test_main():
     test_support.run_unittest(HotShotTestCase)
 

Modified: python/branches/tlee-ast-optimize/Lib/test/test_import.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_import.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_import.py	Wed Jan 14 13:24:17 2009
@@ -5,6 +5,7 @@
 import sys
 import py_compile
 import warnings
+import marshal
 from test.test_support import unlink, TESTFN, unload, run_unittest, check_warnings
 
 
@@ -231,6 +232,97 @@
         else:
             self.fail("import by path didn't raise an exception")
 
+class TestPycRewriting(unittest.TestCase):
+    # Test that the `co_filename` attribute on code objects always points
+    # to the right file, even when various things happen (e.g. both the .py
+    # and the .pyc file are renamed).
+
+    module_name = "unlikely_module_name"
+    module_source = """
+import sys
+code_filename = sys._getframe().f_code.co_filename
+module_filename = __file__
+constant = 1
+def func():
+    pass
+func_filename = func.func_code.co_filename
+"""
+    dir_name = os.path.abspath(TESTFN)
+    file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
+    compiled_name = file_name + ("c" if __debug__ else "o")
+
+    def setUp(self):
+        self.sys_path = sys.path[:]
+        self.orig_module = sys.modules.pop(self.module_name, None)
+        os.mkdir(self.dir_name)
+        with open(self.file_name, "w") as f:
+            f.write(self.module_source)
+        sys.path.insert(0, self.dir_name)
+
+    def tearDown(self):
+        sys.path[:] = self.sys_path
+        if self.orig_module is not None:
+            sys.modules[self.module_name] = self.orig_module
+        else:
+            del sys.modules[self.module_name]
+        for file_name in self.file_name, self.compiled_name:
+            if os.path.exists(file_name):
+                os.remove(file_name)
+        if os.path.exists(self.dir_name):
+            shutil.rmtree(self.dir_name)
+
+    def import_module(self):
+        ns = globals()
+        __import__(self.module_name, ns, ns)
+        return sys.modules[self.module_name]
+
+    def test_basics(self):
+        mod = self.import_module()
+        self.assertEqual(mod.module_filename, self.file_name)
+        self.assertEqual(mod.code_filename, self.file_name)
+        self.assertEqual(mod.func_filename, self.file_name)
+        del sys.modules[self.module_name]
+        mod = self.import_module()
+        self.assertEqual(mod.module_filename, self.compiled_name)
+        self.assertEqual(mod.code_filename, self.file_name)
+        self.assertEqual(mod.func_filename, self.file_name)
+
+    def test_incorrect_code_name(self):
+        py_compile.compile(self.file_name, dfile="another_module.py")
+        mod = self.import_module()
+        self.assertEqual(mod.module_filename, self.compiled_name)
+        self.assertEqual(mod.code_filename, self.file_name)
+        self.assertEqual(mod.func_filename, self.file_name)
+
+    def test_module_without_source(self):
+        target = "another_module.py"
+        py_compile.compile(self.file_name, dfile=target)
+        os.remove(self.file_name)
+        mod = self.import_module()
+        self.assertEqual(mod.module_filename, self.compiled_name)
+        self.assertEqual(mod.code_filename, target)
+        self.assertEqual(mod.func_filename, target)
+
+    def test_foreign_code(self):
+        py_compile.compile(self.file_name)
+        with open(self.compiled_name, "rb") as f:
+            header = f.read(8)
+            code = marshal.load(f)
+        constants = list(code.co_consts)
+        foreign_code = test_main.func_code
+        pos = constants.index(1)
+        constants[pos] = foreign_code
+        code = type(code)(code.co_argcount, code.co_nlocals, code.co_stacksize,
+                          code.co_flags, code.co_code, tuple(constants),
+                          code.co_names, code.co_varnames, code.co_filename,
+                          code.co_name, code.co_firstlineno, code.co_lnotab,
+                          code.co_freevars, code.co_cellvars)
+        with open(self.compiled_name, "wb") as f:
+            f.write(header)
+            marshal.dump(code, f)
+        mod = self.import_module()
+        self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
+
 class PathsTests(unittest.TestCase):
     path = TESTFN
 
@@ -297,7 +389,7 @@
         self.assertRaises(ValueError, check_relative)
 
 def test_main(verbose=None):
-    run_unittest(ImportTest, PathsTests, RelativeImport)
+    run_unittest(ImportTest, TestPycRewriting, PathsTests, RelativeImport)
 
 if __name__ == '__main__':
     # test needs to be a package, so we can do relative import

Modified: python/branches/tlee-ast-optimize/Lib/test/test_inspect.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_inspect.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_inspect.py	Wed Jan 14 13:24:17 2009
@@ -16,6 +16,9 @@
 # getclasstree, getargspec, getargvalues, formatargspec, formatargvalues,
 # currentframe, stack, trace, isdatadescriptor
 
+# NOTE: There are some additional tests relating to interaction with
+#       zipimport in the test_zipimport_support test module.
+
 modfile = mod.__file__
 if modfile.endswith(('c', 'o')):
     modfile = modfile[:-1]
@@ -88,6 +91,17 @@
         self.assert_(inspect.isroutine(mod.spam))
         self.assert_(inspect.isroutine([].count))
 
+    def test_get_slot_members(self):
+        class C(object):
+            __slots__ = ("a", "b")
+
+        x = C()
+        x.a = 42
+        members = dict(inspect.getmembers(x))
+        self.assert_('a' in members)
+        self.assert_('b' not in members)
+
+
 class TestInterpreterStack(IsTestBase):
     def __init__(self, *args, **kwargs):
         unittest.TestCase.__init__(self, *args, **kwargs)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_int.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_int.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_int.py	Wed Jan 14 13:24:17 2009
@@ -2,6 +2,7 @@
 
 import unittest
 from test.test_support import run_unittest, have_unicode
+import math
 
 L = [
         ('0', 0),
@@ -240,6 +241,40 @@
         self.assertEqual(int('2br45qc', 35), 4294967297L)
         self.assertEqual(int('1z141z5', 36), 4294967297L)
 
+    def test_bit_length(self):
+        tiny = 1e-10
+        for x in xrange(-65000, 65000):
+            k = x.bit_length()
+            # Check equivalence with Python version
+            self.assertEqual(k, len(bin(x).lstrip('-0b')))
+            # Behaviour as specified in the docs
+            if x != 0:
+                self.assert_(2**(k-1) <= abs(x) < 2**k)
+            else:
+                self.assertEqual(k, 0)
+            # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
+            if x != 0:
+                # When x is an exact power of 2, numeric errors can
+                # cause floor(log(x)/log(2)) to be one too small; for
+                # small x this can be fixed by adding a small quantity
+                # to the quotient before taking the floor.
+                self.assertEqual(k, 1 + math.floor(
+                        math.log(abs(x))/math.log(2) + tiny))
+
+        self.assertEqual((0).bit_length(), 0)
+        self.assertEqual((1).bit_length(), 1)
+        self.assertEqual((-1).bit_length(), 1)
+        self.assertEqual((2).bit_length(), 2)
+        self.assertEqual((-2).bit_length(), 2)
+        for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64]:
+            a = 2**i
+            self.assertEqual((a-1).bit_length(), i)
+            self.assertEqual((1-a).bit_length(), i)
+            self.assertEqual((a).bit_length(), i+1)
+            self.assertEqual((-a).bit_length(), i+1)
+            self.assertEqual((a+1).bit_length(), i+1)
+            self.assertEqual((-a-1).bit_length(), i+1)
+
     def test_intconversion(self):
         # Test __int__()
         class ClassicMissingMethods:

Modified: python/branches/tlee-ast-optimize/Lib/test/test_io.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_io.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_io.py	Wed Jan 14 13:24:17 2009
@@ -554,8 +554,9 @@
         r = MockRawIO(())
         w = MockRawIO()
         pair = io.BufferedRWPair(r, w)
+        self.assertFalse(pair.closed)
 
-        # XXX need implementation
+        # XXX More Tests
 
 
 class BufferedRandomTest(unittest.TestCase):
@@ -680,8 +681,9 @@
     @classmethod
     def lookupTestDecoder(cls, name):
         if cls.codecEnabled and name == 'test_decoder':
+            latin1 = codecs.lookup('latin-1')
             return codecs.CodecInfo(
-                name='test_decoder', encode=None, decode=None,
+                name='test_decoder', encode=latin1.encode, decode=None,
                 incrementalencoder=None,
                 streamreader=None, streamwriter=None,
                 incrementaldecoder=cls)
@@ -840,8 +842,11 @@
             [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ],
             [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ],
         ]
-
-        encodings = ('utf-8', 'latin-1')
+        encodings = (
+            'utf-8', 'latin-1',
+            'utf-16', 'utf-16-le', 'utf-16-be',
+            'utf-32', 'utf-32-le', 'utf-32-be',
+        )
 
         # Try a range of buffer sizes to test the case where \r is the last
         # character in TextIOWrapper._pending_line.
@@ -1195,56 +1200,84 @@
 
         self.assertEqual(buffer.seekable(), txt.seekable())
 
-    def test_newline_decoder(self):
-        import codecs
-        decoder = codecs.getincrementaldecoder("utf-8")()
-        decoder = io.IncrementalNewlineDecoder(decoder, translate=True)
-
-        self.assertEquals(decoder.decode(b'\xe8\xa2\x88'), u"\u8888")
-
-        self.assertEquals(decoder.decode(b'\xe8'), u"")
-        self.assertEquals(decoder.decode(b'\xa2'), u"")
-        self.assertEquals(decoder.decode(b'\x88'), u"\u8888")
+    def check_newline_decoder_utf8(self, decoder):
+        # UTF-8 specific tests for a newline decoder
+        def _check_decode(b, s, **kwargs):
+            # We exercise getstate() / setstate() as well as decode()
+            state = decoder.getstate()
+            self.assertEquals(decoder.decode(b, **kwargs), s)
+            decoder.setstate(state)
+            self.assertEquals(decoder.decode(b, **kwargs), s)
+
+        _check_decode(b'\xe8\xa2\x88', "\u8888")
+
+        _check_decode(b'\xe8', "")
+        _check_decode(b'\xa2', "")
+        _check_decode(b'\x88', "\u8888")
+
+        _check_decode(b'\xe8', "")
+        _check_decode(b'\xa2', "")
+        _check_decode(b'\x88', "\u8888")
 
-        self.assertEquals(decoder.decode(b'\xe8'), u"")
+        _check_decode(b'\xe8', "")
         self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True)
 
-        decoder.setstate((b'', 0))
-        self.assertEquals(decoder.decode(b'\n'), u"\n")
-        self.assertEquals(decoder.decode(b'\r'), u"")
-        self.assertEquals(decoder.decode(b'', final=True), u"\n")
-        self.assertEquals(decoder.decode(b'\r', final=True), u"\n")
-
-        self.assertEquals(decoder.decode(b'\r'), u"")
-        self.assertEquals(decoder.decode(b'a'), u"\na")
-
-        self.assertEquals(decoder.decode(b'\r\r\n'), u"\n\n")
-        self.assertEquals(decoder.decode(b'\r'), u"")
-        self.assertEquals(decoder.decode(b'\r'), u"\n")
-        self.assertEquals(decoder.decode(b'\na'), u"\na")
-
-        self.assertEquals(decoder.decode(b'\xe8\xa2\x88\r\n'), u"\u8888\n")
-        self.assertEquals(decoder.decode(b'\xe8\xa2\x88'), u"\u8888")
-        self.assertEquals(decoder.decode(b'\n'), u"\n")
-        self.assertEquals(decoder.decode(b'\xe8\xa2\x88\r'), u"\u8888")
-        self.assertEquals(decoder.decode(b'\n'), u"\n")
-
-        decoder = codecs.getincrementaldecoder("utf-8")()
-        decoder = io.IncrementalNewlineDecoder(decoder, translate=True)
+        decoder.reset()
+        _check_decode(b'\n', "\n")
+        _check_decode(b'\r', "")
+        _check_decode(b'', "\n", final=True)
+        _check_decode(b'\r', "\n", final=True)
+
+        _check_decode(b'\r', "")
+        _check_decode(b'a', "\na")
+
+        _check_decode(b'\r\r\n', "\n\n")
+        _check_decode(b'\r', "")
+        _check_decode(b'\r', "\n")
+        _check_decode(b'\na', "\na")
+
+        _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n")
+        _check_decode(b'\xe8\xa2\x88', "\u8888")
+        _check_decode(b'\n', "\n")
+        _check_decode(b'\xe8\xa2\x88\r', "\u8888")
+        _check_decode(b'\n', "\n")
+
+    def check_newline_decoder(self, decoder, encoding):
+        result = []
+        encoder = codecs.getincrementalencoder(encoding)()
+        def _decode_bytewise(s):
+            for b in encoder.encode(s):
+                result.append(decoder.decode(b))
         self.assertEquals(decoder.newlines, None)
-        decoder.decode(b"abc\n\r")
-        self.assertEquals(decoder.newlines, u'\n')
-        decoder.decode(b"\nabc")
+        _decode_bytewise("abc\n\r")
+        self.assertEquals(decoder.newlines, '\n')
+        _decode_bytewise("\nabc")
         self.assertEquals(decoder.newlines, ('\n', '\r\n'))
-        decoder.decode(b"abc\r")
+        _decode_bytewise("abc\r")
         self.assertEquals(decoder.newlines, ('\n', '\r\n'))
-        decoder.decode(b"abc")
+        _decode_bytewise("abc")
         self.assertEquals(decoder.newlines, ('\r', '\n', '\r\n'))
-        decoder.decode(b"abc\r")
+        _decode_bytewise("abc\r")
+        self.assertEquals("".join(result), "abc\n\nabcabc\nabcabc")
         decoder.reset()
-        self.assertEquals(decoder.decode(b"abc"), "abc")
+        self.assertEquals(decoder.decode("abc".encode(encoding)), "abc")
         self.assertEquals(decoder.newlines, None)
 
+    def test_newline_decoder(self):
+        encodings = (
+            'utf-8', 'latin-1',
+            'utf-16', 'utf-16-le', 'utf-16-be',
+            'utf-32', 'utf-32-le', 'utf-32-be',
+        )
+        for enc in encodings:
+            decoder = codecs.getincrementaldecoder(enc)()
+            decoder = io.IncrementalNewlineDecoder(decoder, translate=True)
+            self.check_newline_decoder(decoder, enc)
+        decoder = codecs.getincrementaldecoder("utf-8")()
+        decoder = io.IncrementalNewlineDecoder(decoder, translate=True)
+        self.check_newline_decoder_utf8(decoder)
+
+
 # XXX Tests for open()
 
 class MiscIOTest(unittest.TestCase):

Modified: python/branches/tlee-ast-optimize/Lib/test/test_iter.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_iter.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_iter.py	Wed Jan 14 13:24:17 2009
@@ -120,6 +120,13 @@
     def test_seq_class_iter(self):
         self.check_iterator(iter(SequenceClass(10)), range(10))
 
+    # Test a new_style class with __iter__ but no next() method
+    def test_new_style_iter_class(self):
+        class IterClass(object):
+            def __iter__(self):
+                return self
+        self.assertRaises(TypeError, iter, IterClass())
+
     # Test two-argument iter() with callable instance
     def test_iter_callable(self):
         class C:
@@ -877,6 +884,21 @@
         self.assertEqual(list(b), zip(range(5), range(5)))
         self.assertEqual(list(b), [])
 
+    def test_3720(self):
+        # Avoid a crash, when an iterator deletes its next() method.
+        class BadIterator(object):
+            def __iter__(self):
+                return self
+            def next(self):
+                del BadIterator.next
+                return 1
+
+        try:
+            for i in BadIterator() :
+                pass
+        except TypeError:
+            pass
+
 
 def test_main():
     run_unittest(TestCase)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_itertools.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_itertools.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_itertools.py	Wed Jan 14 13:24:17 2009
@@ -71,11 +71,11 @@
         self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
 
     def test_combinations(self):
-        self.assertRaises(TypeError, combinations, 'abc')   # missing r argument
+        self.assertRaises(TypeError, combinations, 'abc')       # missing r argument
         self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
         self.assertRaises(TypeError, combinations, None)        # pool is not iterable
         self.assertRaises(ValueError, combinations, 'abc', -2)  # r is negative
-        self.assertRaises(ValueError, combinations, 'abc', 32)  # r is too big
+        self.assertEqual(list(combinations('abc', 32)), [])     # r > n
         self.assertEqual(list(combinations(range(4), 3)),
                                            [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
 
@@ -83,6 +83,8 @@
             'Pure python version shown in the docs'
             pool = tuple(iterable)
             n = len(pool)
+            if r > n:
+                return
             indices = range(r)
             yield tuple(pool[i] for i in indices)
             while 1:
@@ -106,9 +108,9 @@
 
         for n in range(7):
             values = [5*x-12 for x in range(n)]
-            for r in range(n+1):
+            for r in range(n+2):
                 result = list(combinations(values, r))
-                self.assertEqual(len(result), fact(n) / fact(r) / fact(n-r)) # right number of combs
+                self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
                 self.assertEqual(len(result), len(set(result)))         # no repeats
                 self.assertEqual(result, sorted(result))                # lexicographic order
                 for c in result:
@@ -119,7 +121,7 @@
                     self.assertEqual(list(c),
                                      [e for e in values if e in c])      # comb is a subsequence of the input iterable
                 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
-                self.assertEqual(result, list(combinations2(values, r))) # matches first pure python version
+                self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
 
         # Test implementation detail:  tuple re-use
         self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
@@ -130,7 +132,7 @@
         self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
         self.assertRaises(TypeError, permutations, None)        # pool is not iterable
         self.assertRaises(ValueError, permutations, 'abc', -2)  # r is negative
-        self.assertRaises(ValueError, permutations, 'abc', 32)  # r is too big
+        self.assertEqual(list(permutations('abc', 32)), [])     # r > n
         self.assertRaises(TypeError, permutations, 'abc', 's')  # r is not an int or None
         self.assertEqual(list(permutations(range(3), 2)),
                                            [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
@@ -140,6 +142,8 @@
             pool = tuple(iterable)
             n = len(pool)
             r = n if r is None else r
+            if r > n:
+                return
             indices = range(n)
             cycles = range(n, n-r, -1)
             yield tuple(pool[i] for i in indices[:r])
@@ -168,9 +172,9 @@
 
         for n in range(7):
             values = [5*x-12 for x in range(n)]
-            for r in range(n+1):
+            for r in range(n+2):
                 result = list(permutations(values, r))
-                self.assertEqual(len(result), fact(n) / fact(n-r))      # right number of perms
+                self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r))      # right number of perms
                 self.assertEqual(len(result), len(set(result)))         # no repeats
                 self.assertEqual(result, sorted(result))                # lexicographic order
                 for p in result:
@@ -178,7 +182,7 @@
                     self.assertEqual(len(set(p)), r)                    # no duplicate elements
                     self.assert_(all(e in values for e in p))           # elements taken from input iterable
                 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
-                self.assertEqual(result, list(permutations2(values, r))) # matches first pure python version
+                self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
                 if r == n:
                     self.assertEqual(result, list(permutations(values, None))) # test r as None
                     self.assertEqual(result, list(permutations(values)))       # test default r
@@ -1277,6 +1281,30 @@
 ...         indices[i:] = [indices[i] + 1] * (r - i)
 ...         yield tuple(pool[i] for i in indices)
 
+>>> def unique_everseen(iterable, key=None):
+...     "List unique elements, preserving order. Remember all elements ever seen."
+...     # unique_everseen('AAAABBBCCDAABBB') --> A B C D
+...     # unique_everseen('ABBCcAD', str.lower) --> A B C D
+...     seen = set()
+...     seen_add = seen.add
+...     if key is None:
+...         for element in iterable:
+...             if element not in seen:
+...                 seen_add(element)
+...                 yield element
+...     else:
+...         for element in iterable:
+...             k = key(element)
+...             if k not in seen:
+...                 seen_add(k)
+...                 yield element
+
+>>> def unique_justseen(iterable, key=None):
+...     "List unique elements, preserving order. Remember only the element just seen."
+...     # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
+...     # unique_justseen('ABBCcAD', str.lower) --> A B C A D
+...     return imap(next, imap(itemgetter(1), groupby(iterable, key)))
+
 This is not part of the examples but it tests to make sure the definitions
 perform as purported.
 
@@ -1339,6 +1367,38 @@
 >>> list(combinations_with_replacement('abc', 2))
 [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
 
+>>> list(combinations_with_replacement('01', 3))
+[('0', '0', '0'), ('0', '0', '1'), ('0', '1', '1'), ('1', '1', '1')]
+
+>>> def combinations_with_replacement2(iterable, r):
+...     'Alternate version that filters from product()'
+...     pool = tuple(iterable)
+...     n = len(pool)
+...     for indices in product(range(n), repeat=r):
+...         if sorted(indices) == list(indices):
+...             yield tuple(pool[i] for i in indices)
+
+>>> list(combinations_with_replacement('abc', 2)) == list(combinations_with_replacement2('abc', 2))
+True
+
+>>> list(combinations_with_replacement('01', 3)) == list(combinations_with_replacement2('01', 3))
+True
+
+>>> list(combinations_with_replacement('2310', 6)) == list(combinations_with_replacement2('2310', 6))
+True
+
+>>> list(unique_everseen('AAAABBBCCDAABBB'))
+['A', 'B', 'C', 'D']
+
+>>> list(unique_everseen('ABBCcAD', str.lower))
+['A', 'B', 'C', 'D']
+
+>>> list(unique_justseen('AAAABBBCCDAABBB'))
+['A', 'B', 'C', 'D', 'A', 'B']
+
+>>> list(unique_justseen('ABBCcAD', str.lower))
+['A', 'B', 'C', 'A', 'D']
+
 """
 
 __test__ = {'libreftest' : libreftest}

Modified: python/branches/tlee-ast-optimize/Lib/test/test_logging.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_logging.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_logging.py	Wed Jan 14 13:24:17 2009
@@ -18,7 +18,7 @@
 
 """Test harness for the logging module. Run all tests.
 
-Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
+Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved.
 """
 
 import logging
@@ -44,6 +44,7 @@
 import time
 import types
 import unittest
+import warnings
 import weakref
 
 
@@ -885,6 +886,32 @@
             if os.path.isfile(fn):
                 os.remove(fn)
 
+class WarningsTest(BaseTest):
+    def test_warnings(self):
+        logging.captureWarnings(True)
+        warnings.filterwarnings("always", category=UserWarning)
+        try:
+            file = cStringIO.StringIO()
+            h = logging.StreamHandler(file)
+            logger = logging.getLogger("py.warnings")
+            logger.addHandler(h)
+            warnings.warn("I'm warning you...")
+            logger.removeHandler(h)
+            s = file.getvalue()
+            h.close()
+            self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)
+
+            #See if an explicit file uses the original implementation
+            file = cStringIO.StringIO()
+            warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, file,
+                                 "Dummy line")
+            s = file.getvalue()
+            file.close()
+            self.assertEqual(s, "dummy.py:42: UserWarning: Explicit\n  Dummy line\n")
+        finally:
+            warnings.resetwarnings()
+            logging.captureWarnings(False)
+
 # Set the locale to the platform-dependent default.  I have no idea
 # why the test does this, but in any case we save the current locale
 # first and restore it at the end.
@@ -893,7 +920,7 @@
     run_unittest(BuiltinLevelsTest, BasicFilterTest,
                     CustomLevelsAndFiltersTest, MemoryHandlerTest,
                     ConfigFileTest, SocketHandlerTest, MemoryTest,
-                    EncodingTest)
+                    EncodingTest, WarningsTest)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/tlee-ast-optimize/Lib/test/test_long.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_long.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_long.py	Wed Jan 14 13:24:17 2009
@@ -3,6 +3,7 @@
 import sys
 
 import random
+import math
 
 # Used for lazy formatting of failure messages
 class Frm(object):
@@ -752,6 +753,42 @@
         self.assertRaises(OverflowError, long, float('-inf'))
         self.assertRaises(ValueError, long, float('nan'))
 
+    def test_bit_length(self):
+        tiny = 1e-10
+        for x in xrange(-65000, 65000):
+            x = long(x)
+            k = x.bit_length()
+            # Check equivalence with Python version
+            self.assertEqual(k, len(bin(x).lstrip('-0b')))
+            # Behaviour as specified in the docs
+            if x != 0:
+                self.assert_(2**(k-1) <= abs(x) < 2**k)
+            else:
+                self.assertEqual(k, 0)
+            # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
+            if x != 0:
+                # When x is an exact power of 2, numeric errors can
+                # cause floor(log(x)/log(2)) to be one too small; for
+                # small x this can be fixed by adding a small quantity
+                # to the quotient before taking the floor.
+                self.assertEqual(k, 1 + math.floor(
+                        math.log(abs(x))/math.log(2) + tiny))
+
+        self.assertEqual((0L).bit_length(), 0)
+        self.assertEqual((1L).bit_length(), 1)
+        self.assertEqual((-1L).bit_length(), 1)
+        self.assertEqual((2L).bit_length(), 2)
+        self.assertEqual((-2L).bit_length(), 2)
+        for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
+            a = 2L**i
+            self.assertEqual((a-1).bit_length(), i)
+            self.assertEqual((1-a).bit_length(), i)
+            self.assertEqual((a).bit_length(), i+1)
+            self.assertEqual((-a).bit_length(), i+1)
+            self.assertEqual((a+1).bit_length(), i+1)
+            self.assertEqual((-a-1).bit_length(), i+1)
+
+
 def test_main():
     test_support.run_unittest(LongTest)
 

Modified: python/branches/tlee-ast-optimize/Lib/test/test_macos.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_macos.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_macos.py	Wed Jan 14 13:24:17 2009
@@ -3,11 +3,66 @@
 import Carbon.File
 from test import test_support
 import os
+import subprocess
 
 TESTFN2 = test_support.TESTFN + '2'
 
 class TestMacOS(unittest.TestCase):
 
+    def testGetCreatorAndType(self):
+        if not os.path.exists('/Developer/Tools/SetFile'):
+            return
+
+        try:
+            fp = open(test_support.TESTFN, 'w')
+            fp.write('\n')
+            fp.close()
+
+            subprocess.call(
+                    ['/Developer/Tools/SetFile', '-t', 'ABCD', '-c', 'EFGH',
+                        test_support.TESTFN])
+
+            cr, tp = MacOS.GetCreatorAndType(test_support.TESTFN)
+            self.assertEquals(tp, 'ABCD')
+            self.assertEquals(cr, 'EFGH')
+
+        finally:
+            os.unlink(test_support.TESTFN)
+
+    def testSetCreatorAndType(self):
+        if not os.path.exists('/Developer/Tools/GetFileInfo'):
+            return
+
+        try:
+            fp = open(test_support.TESTFN, 'w')
+            fp.write('\n')
+            fp.close()
+
+            MacOS.SetCreatorAndType(test_support.TESTFN,
+                    'ABCD', 'EFGH')
+
+            cr, tp = MacOS.GetCreatorAndType(test_support.TESTFN)
+            self.assertEquals(cr, 'ABCD')
+            self.assertEquals(tp, 'EFGH')
+
+            data = subprocess.Popen(["/Developer/Tools/GetFileInfo", test_support.TESTFN],
+                    stdout=subprocess.PIPE).communicate()[0]
+
+            tp = None
+            cr = None
+            for  ln in data.splitlines():
+                if ln.startswith('type:'):
+                    tp = ln.split()[-1][1:-1]
+                if ln.startswith('creator:'):
+                    cr = ln.split()[-1][1:-1]
+
+            self.assertEquals(cr, 'ABCD')
+            self.assertEquals(tp, 'EFGH')
+
+        finally:
+            os.unlink(test_support.TESTFN)
+
+
     def testOpenRF(self):
         try:
             fp = open(test_support.TESTFN, 'w')

Modified: python/branches/tlee-ast-optimize/Lib/test/test_os.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_os.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_os.py	Wed Jan 14 13:24:17 2009
@@ -533,6 +533,55 @@
     def test_chmod(self):
         self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
 
+class TestInvalidFD(unittest.TestCase):
+    singles = ["fchdir", "fdopen", "close", "dup", "fdatasync", "fstat",
+               "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
+    def get_single(f):
+        def helper(self):
+            if  getattr(os, f, None):
+                self.assertRaises(OSError, getattr(os, f), 10)
+        return helper
+    for f in singles:
+        locals()["test_"+f] = get_single(f)
+
+    def test_isatty(self):
+        self.assertEqual(os.isatty(10), False)
+
+    def test_closerange(self):
+        self.assertEqual(os.closerange(10, 20), None)
+
+    def test_dup2(self):
+        self.assertRaises(OSError, os.dup2, 10, 20)
+
+    def test_fchmod(self):
+        if hasattr(os, "fchmod"):
+            self.assertRaises(OSError, os.fchmod, 10, 0)
+
+    def test_fchown(self):
+        if hasattr(os, "fchown"):
+            self.assertRaises(OSError, os.fchmod, 10, -1, -1)
+
+    def test_fpathconf(self):
+        if hasattr(os, "fpathconf"):
+            self.assertRaises(OSError, os.fpathconf, 10, "foo")
+
+    def test_ftruncate(self):
+        if hasattr(os, "ftruncate"):
+            self.assertRaises(OSError, os.ftruncate, 10, 0)
+
+    def test_lseek(self):
+        self.assertRaises(OSError, os.lseek, 10, 0, 0)
+
+    def test_read(self):
+        self.assertRaises(OSError, os.read, 10, 1)
+
+    def test_tcsetpgrpt(self):
+        if hasattr(os, "tcsetpgrp"):
+            self.assertRaises(OSError, os.tcsetpgrp, 10, 0)
+
+    def test_write(self):
+        self.assertRaises(OSError, os.write, 10, " ")
+
 if sys.platform != 'win32':
     class Win32ErrorTests(unittest.TestCase):
         pass
@@ -547,7 +596,8 @@
         MakedirTests,
         DevNullTests,
         URandomTests,
-        Win32ErrorTests
+        Win32ErrorTests,
+        TestInvalidFD
     )
 
 if __name__ == "__main__":

Modified: python/branches/tlee-ast-optimize/Lib/test/test_parser.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_parser.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_parser.py	Wed Jan 14 13:24:17 2009
@@ -200,6 +200,16 @@
         self.check_suite("with open('x'): pass\n")
         self.check_suite("with open('x') as f: pass\n")
 
+    def test_try_stmt(self):
+        self.check_suite("try: pass\nexcept: pass\n")
+        self.check_suite("try: pass\nfinally: pass\n")
+        self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
+        self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
+                         "finally: pass\n")
+        self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
+        self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
+                         "finally: pass\n")
+
     def test_position(self):
         # An absolutely minimal test of position information.  Better
         # tests would be a big project.

Modified: python/branches/tlee-ast-optimize/Lib/test/test_py3kwarn.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_py3kwarn.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_py3kwarn.py	Wed Jan 14 13:24:17 2009
@@ -126,6 +126,16 @@
             w.reset()
             self.assertWarning(meth >= func, w, expected)
 
+    def test_frame_attributes(self):
+        template = "%s has been removed in 3.x"
+        f = sys._getframe(0)
+        for attr in ("f_exc_traceback", "f_exc_value", "f_exc_type"):
+            expected = template % attr
+            with check_warnings() as w:
+                self.assertWarning(getattr(f, attr), w, expected)
+                w.reset()
+                self.assertWarning(setattr(f, attr, None), w, expected)
+
     def test_sort_cmp_arg(self):
         expected = "the cmp argument is not supported in 3.x"
         lst = range(5)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_set.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_set.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_set.py	Wed Jan 14 13:24:17 2009
@@ -1,6 +1,7 @@
 import unittest
 from test import test_support
-from weakref import proxy
+import gc
+import weakref
 import operator
 import copy
 import pickle
@@ -221,7 +222,7 @@
         self.failIf(set('cbs').issuperset('a'))
 
     def test_pickling(self):
-        for i in (0, 1, 2):
+        for i in range(pickle.HIGHEST_PROTOCOL + 1):
             p = pickle.dumps(self.s, i)
             dup = pickle.loads(p)
             self.assertEqual(self.s, dup, "%s != %s" % (self.s, dup))
@@ -322,6 +323,18 @@
         self.assertEqual(sum(elem.hash_count for elem in d), n)
         self.assertEqual(d3, dict.fromkeys(d, 123))
 
+    def test_container_iterator(self):
+        # Bug #3680: tp_traverse was not implemented for set iterator object
+        class C(object):
+            pass
+        obj = C()
+        ref = weakref.ref(obj)
+        container = set([obj, 1])
+        obj.x = iter(container)
+        del obj, container
+        gc.collect()
+        self.assert_(ref() is None, "Cycle was not collected")
+
 class TestSet(TestJointOps):
     thetype = set
 
@@ -538,7 +551,7 @@
 
     def test_weakref(self):
         s = self.thetype('gallahad')
-        p = proxy(s)
+        p = weakref.proxy(s)
         self.assertEqual(str(p), str(s))
         s = None
         self.assertRaises(ReferenceError, str, p)

Modified: python/branches/tlee-ast-optimize/Lib/test/test_struct.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_struct.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_struct.py	Wed Jan 14 13:24:17 2009
@@ -2,6 +2,8 @@
 import unittest
 import struct
 import warnings
+warnings.filterwarnings("ignore", "struct integer overflow masking is deprecated",
+                        DeprecationWarning)
 
 from functools import wraps
 from test.test_support import TestFailed, verbose, run_unittest
@@ -461,6 +463,11 @@
                 self.check_float_coerce(endian + fmt, 1.0)
                 self.check_float_coerce(endian + fmt, 1.5)
 
+    def test_issue4228(self):
+        # Packing a long may yield either 32 or 64 bits
+        x = struct.pack('L', -1)[:4]
+        self.assertEqual(x, '\xff'*4)
+
     def test_unpack_from(self):
         test_string = 'abcd01234'
         fmt = '4s'

Modified: python/branches/tlee-ast-optimize/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_subprocess.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_subprocess.py	Wed Jan 14 13:24:17 2009
@@ -72,6 +72,40 @@
         else:
             self.fail("Expected CalledProcessError")
 
+    def test_check_output(self):
+        # check_output() function with zero return code
+        output = subprocess.check_output(
+                [sys.executable, "-c", "print 'BDFL'"])
+        self.assertTrue('BDFL' in output)
+
+    def test_check_output_nonzero(self):
+        # check_call() function with non-zero return code
+        try:
+            subprocess.check_output(
+                    [sys.executable, "-c", "import sys; sys.exit(5)"])
+        except subprocess.CalledProcessError, e:
+            self.assertEqual(e.returncode, 5)
+        else:
+            self.fail("Expected CalledProcessError")
+
+    def test_check_output_stderr(self):
+        # check_output() function stderr redirected to stdout
+        output = subprocess.check_output(
+                [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
+                stderr=subprocess.STDOUT)
+        self.assertTrue('BDFL' in output)
+
+    def test_check_output_stdout_arg(self):
+        # check_output() function stderr redirected to stdout
+        try:
+            output = subprocess.check_output(
+                    [sys.executable, "-c", "print 'will not be run'"],
+                    stdout=sys.stdout)
+        except ValueError, e:
+            self.assertTrue('stdout' in e.args[0])
+        else:
+            self.fail("Expected ValueError when stdout arg supplied.")
+
     def test_call_kwargs(self):
         # call() function with keyword args
         newenv = os.environ.copy()

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	Wed Jan 14 13:24:17 2009
@@ -631,8 +631,8 @@
         # slice
         check(slice(1), size(h + '3P'))
         # str
-        check('', size(vh + 'lic'))
-        check('abc', size(vh + 'lic') + 3*self.c)
+        check('', struct.calcsize(vh + 'li') + 1)
+        check('abc', struct.calcsize(vh + 'li') + 1 + 3*self.c)
         # super
         check(super(int), size(h + '3P'))
         # tuple

Modified: python/branches/tlee-ast-optimize/Lib/test/test_tarfile.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_tarfile.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_tarfile.py	Wed Jan 14 13:24:17 2009
@@ -256,17 +256,14 @@
     def test_extractall(self):
         # Test if extractall() correctly restores directory permissions
         # and times (see issue1735).
-        if sys.platform == "win32":
-            # Win32 has no support for utime() on directories or
-            # fine grained permissions.
-            return
-
         tar = tarfile.open(tarname, encoding="iso8859-1")
         directories = [t for t in tar if t.isdir()]
         tar.extractall(TEMPDIR, directories)
         for tarinfo in directories:
             path = os.path.join(TEMPDIR, tarinfo.name)
-            self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
+            if sys.platform != "win32":
+                # Win32 has no support for fine grained permissions.
+                self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
             self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
         tar.close()
 

Modified: python/branches/tlee-ast-optimize/Lib/test/test_textwrap.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_textwrap.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_textwrap.py	Wed Jan 14 13:24:17 2009
@@ -174,7 +174,7 @@
         text = ("Python 1.0.0 was released on 1994-01-26.  Python 1.0.1 was\n"
                 "released on 1994-02-15.")
 
-        self.check_wrap(text, 30, ['Python 1.0.0 was released on',
+        self.check_wrap(text, 35, ['Python 1.0.0 was released on',
                                    '1994-01-26.  Python 1.0.1 was',
                                    'released on 1994-02-15.'])
         self.check_wrap(text, 40, ['Python 1.0.0 was released on 1994-01-26.',
@@ -353,6 +353,14 @@
             otext = self.wrapper.fill(text)
             assert isinstance(otext, unicode)
 
+        def test_no_split_at_umlaut(self):
+            text = u"Die Empf\xe4nger-Auswahl"
+            self.check_wrap(text, 13, [u"Die", u"Empf\xe4nger-", u"Auswahl"])
+
+        def test_umlaut_followed_by_dash(self):
+            text = u"aa \xe4\xe4-\xe4\xe4"
+            self.check_wrap(text, 7, [u"aa \xe4\xe4-", u"\xe4\xe4"])
+
     def test_split(self):
         # Ensure that the standard _split() method works as advertised
         # in the comments

Modified: python/branches/tlee-ast-optimize/Lib/test/test_unittest.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_unittest.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_unittest.py	Wed Jan 14 13:24:17 2009
@@ -2284,6 +2284,43 @@
         self.assertRaises(AssertionError,
                           self.failIfAlmostEqual, 0, .1+.1j, places=0)
 
+    def test_assertRaises(self):
+        def _raise(e):
+            raise e
+        self.assertRaises(KeyError, _raise, KeyError)
+        self.assertRaises(KeyError, _raise, KeyError("key"))
+        try:
+            self.assertRaises(KeyError, lambda: None)
+        except AssertionError as e:
+            self.assert_("KeyError not raised" in e, str(e))
+        else:
+            self.fail("assertRaises() didn't fail")
+        try:
+            self.assertRaises(KeyError, _raise, ValueError)
+        except ValueError:
+            pass
+        else:
+            self.fail("assertRaises() didn't let exception pass through")
+        with self.assertRaises(KeyError):
+            raise KeyError
+        with self.assertRaises(KeyError):
+            raise KeyError("key")
+        try:
+            with self.assertRaises(KeyError):
+                pass
+        except AssertionError as e:
+            self.assert_("KeyError not raised" in e, str(e))
+        else:
+            self.fail("assertRaises() didn't fail")
+        try:
+            with self.assertRaises(KeyError):
+                raise ValueError
+        except ValueError:
+            pass
+        else:
+            self.fail("assertRaises() didn't let exception pass through")
+
+
 ######################################################################
 ## Main
 ######################################################################

Modified: python/branches/tlee-ast-optimize/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_urllib2.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_urllib2.py	Wed Jan 14 13:24:17 2009
@@ -1104,6 +1104,51 @@
         else:
             self.assert_(False)
 
+class RequestTests(unittest.TestCase):
+
+    def setUp(self):
+        self.get = urllib2.Request("http://www.python.org/~jeremy/")
+        self.post = urllib2.Request("http://www.python.org/~jeremy/",
+                                    "data",
+                                    headers={"X-Test": "test"})
+
+    def test_method(self):
+        self.assertEqual("POST", self.post.get_method())
+        self.assertEqual("GET", self.get.get_method())
+
+    def test_add_data(self):
+        self.assert_(not self.get.has_data())
+        self.assertEqual("GET", self.get.get_method())
+        self.get.add_data("spam")
+        self.assert_(self.get.has_data())
+        self.assertEqual("POST", self.get.get_method())
+
+    def test_get_full_url(self):
+        self.assertEqual("http://www.python.org/~jeremy/",
+                         self.get.get_full_url())
+
+    def test_selector(self):
+        self.assertEqual("/~jeremy/", self.get.get_selector())
+        req = urllib2.Request("http://www.python.org/")
+        self.assertEqual("/", req.get_selector())
+
+    def test_get_type(self):
+        self.assertEqual("http", self.get.get_type())
+
+    def test_get_host(self):
+        self.assertEqual("www.python.org", self.get.get_host())
+
+    def test_get_host_unquote(self):
+        req = urllib2.Request("http://www.%70ython.org/")
+        self.assertEqual("www.python.org", req.get_host())
+
+    def test_proxy(self):
+        self.assert_(not self.get.has_proxy())
+        self.get.set_proxy("www.perl.org", "http")
+        self.assert_(self.get.has_proxy())
+        self.assertEqual("www.python.org", self.get.get_origin_req_host())
+        self.assertEqual("www.perl.org", self.get.get_host())
+
 
 def test_main(verbose=None):
     from test import test_urllib2
@@ -1112,7 +1157,8 @@
     tests = (TrivialTests,
              OpenerDirectorTests,
              HandlerTests,
-             MiscTests)
+             MiscTests,
+             RequestTests)
     test_support.run_unittest(*tests)
 
 if __name__ == "__main__":

Modified: python/branches/tlee-ast-optimize/Lib/test/test_urllib2_localnet.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_urllib2_localnet.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_urllib2_localnet.py	Wed Jan 14 13:24:17 2009
@@ -474,7 +474,7 @@
                           # domain will be spared to serve its defined
                           # purpose.
                           # urllib2.urlopen, "http://www.sadflkjsasadf.com/")
-                          urllib2.urlopen, "http://www.python.invalid./")
+                          urllib2.urlopen, "http://sadflkjsasf.i.nvali.d/")
 
 
 def test_main():

Modified: python/branches/tlee-ast-optimize/Lib/test/test_urllibnet.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_urllibnet.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_urllibnet.py	Wed Jan 14 13:24:17 2009
@@ -137,7 +137,7 @@
                           # domain will be spared to serve its defined
                           # purpose.
                           # urllib.urlopen, "http://www.sadflkjsasadf.com/")
-                          urllib.urlopen, "http://www.python.invalid./")
+                          urllib.urlopen, "http://sadflkjsasf.i.nvali.d/")
 
 class urlretrieveNetworkTests(unittest.TestCase):
     """Tests urllib.urlretrieve using the network."""

Modified: python/branches/tlee-ast-optimize/Lib/test/test_with.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_with.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_with.py	Wed Jan 14 13:24:17 2009
@@ -503,6 +503,36 @@
 
         self.assertRaises(GeneratorExit, shouldThrow)
 
+    def testErrorsInBool(self):
+        # issue4589: __exit__ return code may raise an exception
+        # when looking at its truth value.
+
+        class cm(object):
+            def __init__(self, bool_conversion):
+                class Bool:
+                    def __nonzero__(self):
+                        return bool_conversion()
+                self.exit_result = Bool()
+            def __enter__(self):
+                return 3
+            def __exit__(self, a, b, c):
+                return self.exit_result
+
+        def trueAsBool():
+            with cm(lambda: True):
+                self.fail("Should NOT see this")
+        trueAsBool()
+
+        def falseAsBool():
+            with cm(lambda: False):
+                self.fail("Should raise")
+        self.assertRaises(AssertionError, falseAsBool)
+
+        def failAsBool():
+            with cm(lambda: 1//0):
+                self.fail("Should NOT see this")
+        self.assertRaises(ZeroDivisionError, failAsBool)
+
 
 class NonLocalFlowControlTestCase(unittest.TestCase):
 

Modified: python/branches/tlee-ast-optimize/Lib/test/test_xmlrpc.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_xmlrpc.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_xmlrpc.py	Wed Jan 14 13:24:17 2009
@@ -655,7 +655,7 @@
     def getvalue(self):
         return self.data.getvalue()
 
-    def makefile(self, x, y):
+    def makefile(self, x='r', y=-1):
         raise RuntimeError
 
 class FakeTransport(xmlrpclib.Transport):

Modified: python/branches/tlee-ast-optimize/Lib/test/test_zipfile.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_zipfile.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_zipfile.py	Wed Jan 14 13:24:17 2009
@@ -634,20 +634,49 @@
     def testIsZipErroneousFile(self):
         # This test checks that the is_zipfile function correctly identifies
         # a file that is not a zip file
-        fp = open(TESTFN, "w")
-        fp.write("this is not a legal zip file\n")
-        fp.close()
+
+        # - passing a filename
+        with open(TESTFN, "w") as fp:
+            fp.write("this is not a legal zip file\n")
         chk = zipfile.is_zipfile(TESTFN)
-        self.assert_(chk is False)
+        self.assert_(not chk)
+        # - passing a file object
+        with open(TESTFN, "rb") as fp:
+            chk = zipfile.is_zipfile(fp)
+            self.assert_(not chk)
+        # - passing a file-like object
+        fp = StringIO()
+        fp.write("this is not a legal zip file\n")
+        chk = zipfile.is_zipfile(fp)
+        self.assert_(not chk)
+        fp.seek(0,0)
+        chk = zipfile.is_zipfile(fp)
+        self.assert_(not chk)
 
     def testIsZipValidFile(self):
         # This test checks that the is_zipfile function correctly identifies
         # a file that is a zip file
+
+        # - passing a filename
         zipf = zipfile.ZipFile(TESTFN, mode="w")
         zipf.writestr("foo.txt", "O, for a Muse of Fire!")
         zipf.close()
         chk = zipfile.is_zipfile(TESTFN)
-        self.assert_(chk is True)
+        self.assert_(chk)
+        # - passing a file object
+        with open(TESTFN, "rb") as fp:
+            chk = zipfile.is_zipfile(fp)
+            self.assert_(chk)
+            fp.seek(0,0)
+            zip_contents = fp.read()
+        # - passing a file-like object
+        fp = StringIO()
+        fp.write(zip_contents)
+        chk = zipfile.is_zipfile(fp)
+        self.assert_(chk)
+        fp.seek(0,0)
+        chk = zipfile.is_zipfile(fp)
+        self.assert_(chk)
 
     def testNonExistentFileRaisesIOError(self):
         # make sure we don't raise an AttributeError when a partially-constructed

Modified: python/branches/tlee-ast-optimize/Lib/test/test_zipimport.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/test/test_zipimport.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/test/test_zipimport.py	Wed Jan 14 13:24:17 2009
@@ -214,16 +214,24 @@
             zi = zipimport.zipimporter(TEMP_ZIP)
             self.assertEquals(zi.archive, TEMP_ZIP)
             self.assertEquals(zi.is_package(TESTPACK), True)
-            zi.load_module(TESTPACK)
+            mod = zi.load_module(TESTPACK)
+            self.assertEquals(zi._get_filename(TESTPACK), mod.__file__)
 
             self.assertEquals(zi.is_package(packdir + '__init__'), False)
             self.assertEquals(zi.is_package(packdir + TESTPACK2), True)
             self.assertEquals(zi.is_package(packdir2 + TESTMOD), False)
 
-            mod_name = packdir2 + TESTMOD
-            mod = __import__(module_path_to_dotted_name(mod_name))
+            mod_path = packdir2 + TESTMOD
+            mod_name = module_path_to_dotted_name(mod_path)
+            pkg = __import__(mod_name)
+            mod = sys.modules[mod_name]
             self.assertEquals(zi.get_source(TESTPACK), None)
-            self.assertEquals(zi.get_source(mod_name), None)
+            self.assertEquals(zi.get_source(mod_path), None)
+            self.assertEquals(zi._get_filename(mod_path), mod.__file__)
+            # To pass in the module name instead of the path, we must use the right importer
+            loader = mod.__loader__
+            self.assertEquals(loader.get_source(mod_name), None)
+            self.assertEquals(loader._get_filename(mod_name), mod.__file__)
 
             # test prefix and archivepath members
             zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
@@ -251,15 +259,23 @@
             self.assertEquals(zi.archive, TEMP_ZIP)
             self.assertEquals(zi.prefix, packdir)
             self.assertEquals(zi.is_package(TESTPACK2), True)
-            zi.load_module(TESTPACK2)
+            mod = zi.load_module(TESTPACK2)
+            self.assertEquals(zi._get_filename(TESTPACK2), mod.__file__)
 
             self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
             self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
 
-            mod_name = TESTPACK2 + os.sep + TESTMOD
-            mod = __import__(module_path_to_dotted_name(mod_name))
+            mod_path = TESTPACK2 + os.sep + TESTMOD
+            mod_name = module_path_to_dotted_name(mod_path)
+            pkg = __import__(mod_name)
+            mod = sys.modules[mod_name]
             self.assertEquals(zi.get_source(TESTPACK2), None)
-            self.assertEquals(zi.get_source(mod_name), None)
+            self.assertEquals(zi.get_source(mod_path), None)
+            self.assertEquals(zi._get_filename(mod_path), mod.__file__)
+            # To pass in the module name instead of the path, we must use the right importer
+            loader = mod.__loader__
+            self.assertEquals(loader.get_source(mod_name), None)
+            self.assertEquals(loader._get_filename(mod_name), mod.__file__)
         finally:
             z.close()
             os.remove(TEMP_ZIP)

Modified: python/branches/tlee-ast-optimize/Lib/textwrap.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/textwrap.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/textwrap.py	Wed Jan 14 13:24:17 2009
@@ -17,7 +17,7 @@
 #except NameError:
 #    (True, False) = (1, 0)
 
-__all__ = ['TextWrapper', 'wrap', 'fill']
+__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent']
 
 # Hardcode the recognized whitespace characters to the US-ASCII
 # whitespace characters.  The main reason for doing this is that in
@@ -86,7 +86,7 @@
     # (after stripping out empty strings).
     wordsep_re = re.compile(
         r'(\s+|'                                  # any whitespace
-        r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|'   # hyphenated words
+        r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|'   # hyphenated words
         r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))')   # em-dash
 
     # This less funky little regex just split on recognized spaces. E.g.
@@ -124,6 +124,13 @@
         self.drop_whitespace = drop_whitespace
         self.break_on_hyphens = break_on_hyphens
 
+        # recompile the regexes for Unicode mode -- done in this clumsy way for
+        # backwards compatibility because it's rather common to monkey-patch
+        # the TextWrapper class' wordsep_re attribute.
+        self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U)
+        self.wordsep_simple_re_uni = re.compile(
+            self.wordsep_simple_re.pattern, re.U)
+
 
     # -- Private methods -----------------------------------------------
     # (possibly useful for subclasses to override)
@@ -160,10 +167,17 @@
           'use', ' ', 'the', ' ', '-b', ' ', option!'
         otherwise.
         """
-        if self.break_on_hyphens is True:
-            chunks = self.wordsep_re.split(text)
+        if isinstance(text, unicode):
+            if self.break_on_hyphens:
+                pat = self.wordsep_re_uni
+            else:
+                pat = self.wordsep_simple_re_uni
         else:
-            chunks = self.wordsep_simple_re.split(text)
+            if self.break_on_hyphens:
+                pat = self.wordsep_re
+            else:
+                pat = self.wordsep_simple_re
+        chunks = pat.split(text)
         chunks = filter(None, chunks)  # remove empty chunks
         return chunks
 

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	Wed Jan 14 13:24:17 2009
@@ -67,16 +67,6 @@
 ##############################################################################
 # Backward compatibility
 ##############################################################################
-if sys.version_info[:2] < (2, 2):
-    def isinstance(obj, clsinfo):
-        import __builtin__
-        if type(clsinfo) in (tuple, list):
-            for cls in clsinfo:
-                if cls is type: cls = types.ClassType
-                if __builtin__.isinstance(obj, cls):
-                    return 1
-            return 0
-        else: return __builtin__.isinstance(obj, clsinfo)
 
 def _CmpToKey(mycmp):
     'Convert a cmp= function into a key= function'
@@ -91,15 +81,12 @@
 # Test framework core
 ##############################################################################
 
-# All classes defined herein are 'new-style' classes, allowing use of 'super()'
-__metaclass__ = type
-
 def _strclass(cls):
     return "%s.%s" % (cls.__module__, cls.__name__)
 
 __unittest = 1
 
-class TestResult:
+class TestResult(object):
     """Holder for test result information.
 
     Test results are automatically managed by the TestCase and TestSuite
@@ -174,7 +161,26 @@
                (_strclass(self.__class__), self.testsRun, len(self.errors),
                 len(self.failures))
 
-class TestCase:
+class AssertRaisesContext(object):
+    def __init__(self, expected, test_case):
+        self.expected = expected
+        self.failureException = test_case.failureException
+    def __enter__(self):
+        pass
+    def __exit__(self, exc_type, exc_value, traceback):
+        if exc_type is None:
+            try:
+                exc_name = self.expected.__name__
+            except AttributeError:
+                exc_name = str(self.expected)
+            raise self.failureException(
+                "{0} not raised".format(exc_name))
+        if issubclass(exc_type, self.expected):
+            return True
+        # Let unexpected exceptions skip through
+        return False
+
+class TestCase(object):
     """A class whose instances are single test cases.
 
     By default, the test code itself should be placed in a method named
@@ -212,8 +218,8 @@
             testMethod = getattr(self, methodName)
             self._testMethodDoc = testMethod.__doc__
         except AttributeError:
-            raise ValueError, "no such test method in %s: %s" % \
-                  (self.__class__, methodName)
+            raise ValueError("no such test method in %s: %s" % \
+                  (self.__class__, methodName))
 
     def setUp(self):
         "Hook method for setting up the test fixture before exercising it."
@@ -268,9 +274,7 @@
         try:
             try:
                 self.setUp()
-            except KeyboardInterrupt:
-                raise
-            except:
+            except Exception:
                 result.addError(self, self._exc_info())
                 return
 
@@ -280,16 +284,12 @@
                 ok = True
             except self.failureException:
                 result.addFailure(self, self._exc_info())
-            except KeyboardInterrupt:
-                raise
-            except:
+            except Exception:
                 result.addError(self, self._exc_info())
 
             try:
                 self.tearDown()
-            except KeyboardInterrupt:
-                raise
-            except:
+            except Exception:
                 result.addError(self, self._exc_info())
                 ok = False
             if ok: result.addSuccess(self)
@@ -314,48 +314,49 @@
 
     def fail(self, msg=None):
         """Fail immediately, with the given message."""
-        raise self.failureException, msg
+        raise self.failureException(msg)
 
     def failIf(self, expr, msg=None):
         "Fail the test if the expression is true."
-        if expr: raise self.failureException, msg
+        if expr: raise self.failureException(msg)
 
     def failUnless(self, expr, msg=None):
         """Fail the test unless the expression is true."""
-        if not expr: raise self.failureException, msg
+        if not expr: raise self.failureException(msg)
 
-    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
+    def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
         """Fail unless an exception of class excClass is thrown
            by callableObj when invoked with arguments args and keyword
            arguments kwargs. If a different type of exception is
            thrown, it will not be caught, and the test case will be
            deemed to have suffered an error, exactly as for an
            unexpected exception.
+
+           If called with callableObj omitted or None, will return a
+           context object used like this::
+
+                with self.failUnlessRaises(some_error_class):
+                    do_something()
         """
-        try:
+        context = AssertRaisesContext(excClass, self)
+        if callableObj is None:
+            return context
+        with context:
             callableObj(*args, **kwargs)
-        except excClass:
-            return
-        else:
-            if hasattr(excClass,'__name__'): excName = excClass.__name__
-            else: excName = str(excClass)
-            raise self.failureException, "%s not raised" % excName
 
     def failUnlessEqual(self, first, second, msg=None):
         """Fail if the two objects are unequal as determined by the '=='
            operator.
         """
         if not first == second:
-            raise self.failureException, \
-                  (msg or '%r != %r' % (first, second))
+            raise self.failureException(msg or '%r != %r' % (first, second))
 
     def failIfEqual(self, first, second, msg=None):
         """Fail if the two objects are equal as determined by the '=='
            operator.
         """
         if first == second:
-            raise self.failureException, \
-                  (msg or '%r == %r' % (first, second))
+            raise self.failureException(msg or '%r == %r' % (first, second))
 
     def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
         """Fail if the two objects are unequal as determined by their
@@ -366,8 +367,8 @@
            as significant digits (measured from the most signficant digit).
         """
         if round(abs(second-first), places) != 0:
-            raise self.failureException, \
-                  (msg or '%r != %r within %r places' % (first, second, places))
+            raise self.failureException(
+                  msg or '%r != %r within %r places' % (first, second, places))
 
     def failIfAlmostEqual(self, first, second, places=7, msg=None):
         """Fail if the two objects are equal as determined by their
@@ -378,8 +379,8 @@
            as significant digits (measured from the most signficant digit).
         """
         if round(abs(second-first), places) == 0:
-            raise self.failureException, \
-                  (msg or '%r == %r within %r places' % (first, second, places))
+            raise self.failureException(
+                  msg or '%r == %r within %r places' % (first, second, places))
 
     # Synonyms for assertion methods
 
@@ -399,7 +400,7 @@
 
 
 
-class TestSuite:
+class TestSuite(object):
     """A test suite is a composite test consisting of a number of TestCases.
 
     For use, create an instance of TestSuite, then add test case instances.
@@ -532,7 +533,7 @@
 # Locating and loading tests
 ##############################################################################
 
-class TestLoader:
+class TestLoader(object):
     """This class is responsible for loading tests according to various
     criteria and returning them wrapped in a TestSuite
     """
@@ -583,12 +584,12 @@
         for part in parts:
             parent, obj = obj, getattr(obj, part)
 
-        if type(obj) == types.ModuleType:
+        if isinstance(obj, types.ModuleType):
             return self.loadTestsFromModule(obj)
         elif (isinstance(obj, (type, types.ClassType)) and
               issubclass(obj, TestCase)):
             return self.loadTestsFromTestCase(obj)
-        elif (type(obj) == types.UnboundMethodType and
+        elif (isinstance(obj, types.UnboundMethodType) and
               isinstance(parent, (type, types.ClassType)) and
               issubclass(parent, TestCase)):
             return TestSuite([parent(obj.__name__)])
@@ -653,7 +654,7 @@
 # Text UI
 ##############################################################################
 
-class _WritelnDecorator:
+class _WritelnDecorator(object):
     """Used to decorate file-like objects with a handy 'writeln' method"""
     def __init__(self,stream):
         self.stream = stream
@@ -732,7 +733,7 @@
             self.stream.writeln("%s" % err)
 
 
-class TextTestRunner:
+class TextTestRunner(object):
     """A test runner class that displays results in textual form.
 
     It prints out the names of tests as they are run, errors as they
@@ -778,7 +779,7 @@
 # Facilities for running tests from the command line
 ##############################################################################
 
-class TestProgram:
+class TestProgram(object):
     """A command-line program that runs a set of tests; this is primarily
        for making test modules conveniently executable.
     """
@@ -800,7 +801,7 @@
     def __init__(self, module='__main__', defaultTest=None,
                  argv=None, testRunner=TextTestRunner,
                  testLoader=defaultTestLoader):
-        if type(module) == type(''):
+        if isinstance(module, basestring):
             self.module = __import__(module)
             for part in module.split('.')[1:]:
                 self.module = getattr(self.module, part)

Modified: python/branches/tlee-ast-optimize/Lib/urllib.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/urllib.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/urllib.py	Wed Jan 14 13:24:17 2009
@@ -335,9 +335,7 @@
         if auth: h.putheader('Authorization', 'Basic %s' % auth)
         if realhost: h.putheader('Host', realhost)
         for args in self.addheaders: h.putheader(*args)
-        h.endheaders()
-        if data is not None:
-            h.send(data)
+        h.endheaders(data)
         errcode, errmsg, headers = h.getreply()
         fp = h.getfile()
         if errcode == -1:
@@ -430,9 +428,7 @@
             if auth: h.putheader('Authorization', 'Basic %s' % auth)
             if realhost: h.putheader('Host', realhost)
             for args in self.addheaders: h.putheader(*args)
-            h.endheaders()
-            if data is not None:
-                h.send(data)
+            h.endheaders(data)
             errcode, errmsg, headers = h.getreply()
             fp = h.getfile()
             if errcode == -1:

Modified: python/branches/tlee-ast-optimize/Lib/urllib2.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/urllib2.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/urllib2.py	Wed Jan 14 13:24:17 2009
@@ -1100,7 +1100,10 @@
             (name.title(), val) for name, val in headers.items())
         try:
             h.request(req.get_method(), req.get_selector(), req.data, headers)
-            r = h.getresponse()
+            try:
+                r = h.getresponse(buffering=True)
+            except TypeError: #buffering kw not supported
+                r = h.getresponse()
         except socket.error, err: # XXX what error?
             raise URLError(err)
 

Modified: python/branches/tlee-ast-optimize/Lib/xmlrpclib.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/xmlrpclib.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/xmlrpclib.py	Wed Jan 14 13:24:17 2009
@@ -1234,7 +1234,7 @@
         self.send_user_agent(h)
         self.send_content(h, request_body)
 
-        errcode, errmsg, headers = h.getreply()
+        errcode, errmsg, headers = h.getreply(buffering=True)
 
         if errcode != 200:
             raise ProtocolError(
@@ -1245,12 +1245,7 @@
 
         self.verbose = verbose
 
-        try:
-            sock = h._conn.sock
-        except AttributeError:
-            sock = None
-
-        return self._parse_response(h.getfile(), sock)
+        return self.parse_response(h.getfile())
 
     ##
     # Create parser.
@@ -1355,29 +1350,12 @@
     # @return Response tuple and target method.
 
     def parse_response(self, file):
-        # compatibility interface
-        return self._parse_response(file, None)
-
-    ##
-    # Parse response (alternate interface).  This is similar to the
-    # parse_response method, but also provides direct access to the
-    # underlying socket object (where available).
-    #
-    # @param file Stream.
-    # @param sock Socket handle (or None, if the socket object
-    #    could not be accessed).
-    # @return Response tuple and target method.
-
-    def _parse_response(self, file, sock):
         # read response from input file/socket, and parse it
 
         p, u = self.getparser()
 
         while 1:
-            if sock:
-                response = sock.recv(1024)
-            else:
-                response = file.read(1024)
+            response = file.read(1024)
             if not response:
                 break
             if self.verbose:

Modified: python/branches/tlee-ast-optimize/Lib/zipfile.py
==============================================================================
--- python/branches/tlee-ast-optimize/Lib/zipfile.py	(original)
+++ python/branches/tlee-ast-optimize/Lib/zipfile.py	Wed Jan 14 13:24:17 2009
@@ -128,18 +128,30 @@
 _CD64_DIRECTORY_SIZE = 8
 _CD64_OFFSET_START_CENTDIR = 9
 
-def is_zipfile(filename):
-    """Quickly see if file is a ZIP file by checking the magic number."""
+def _check_zipfile(fp):
     try:
-        fpin = open(filename, "rb")
-        endrec = _EndRecData(fpin)
-        fpin.close()
-        if endrec:
-            return True                 # file has correct magic number
+        if _EndRecData(fp):
+            return True         # file has correct magic number
     except IOError:
         pass
     return False
 
+def is_zipfile(filename):
+    """Quickly see if a file is a ZIP file by checking the magic number.
+
+    The filename argument may be a file or file-like object too.
+    """
+    result = False
+    try:
+        if hasattr(filename, "read"):
+            result = _check_zipfile(fp=filename)
+        else:
+            with open(filename, "rb") as fp:
+                result = _check_zipfile(fp)
+    except IOError:
+        pass
+    return result
+
 def _EndRecData64(fpin, offset, endrec):
     """
     Read the ZIP64 end-of-archive records and use that to update endrec

Modified: python/branches/tlee-ast-optimize/Mac/IDLE/Makefile.in
==============================================================================
--- python/branches/tlee-ast-optimize/Mac/IDLE/Makefile.in	(original)
+++ python/branches/tlee-ast-optimize/Mac/IDLE/Makefile.in	Wed Jan 14 13:24:17 2009
@@ -29,10 +29,10 @@
 install: IDLE.app $(srcdir)/config-main.def $(srcdir)/config-extensions.def
 	test -d "$(DESTDIR)$(PYTHONAPPSDIR)" || mkdir -p "$(DESTDIR)$(PYTHONAPPSDIR)"
 	-test -d "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" && rm -r "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app"
-	cp -PR IDLE.app "$(DESTDIR)$(PYTHONAPPSDIR)"
+	/bin/cp -PR IDLE.app "$(DESTDIR)$(PYTHONAPPSDIR)"
 	touch "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app"
-	cp $(srcdir)/config-main.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-main.def"
-	cp $(srcdir)/config-extensions.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-extensions.def"
+	/bin/cp $(srcdir)/config-main.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-main.def"
+	/bin/cp $(srcdir)/config-extensions.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-extensions.def"
 
 clean:
 	rm -rf IDLE.app

Modified: python/branches/tlee-ast-optimize/Mac/Modules/MacOS.c
==============================================================================
--- python/branches/tlee-ast-optimize/Mac/Modules/MacOS.c	(original)
+++ python/branches/tlee-ast-optimize/Mac/Modules/MacOS.c	Wed Jan 14 13:24:17 2009
@@ -30,6 +30,9 @@
 #include <Carbon/Carbon.h>
 #include <ApplicationServices/ApplicationServices.h>
 
+#include <arpa/inet.h>  /* for ntohl, htonl */
+
+
 #ifndef HAVE_OSX105_SDK
 typedef SInt16	FSIORefNum;
 #endif
@@ -310,6 +313,10 @@
 		if ((err = FSpGetFInfo(&fss, &info)) != noErr) {
 			return PyErr_Mac(MacOS_Error, err);
 		}
+
+		info.fdCreator = ntohl(info.fdCreator);
+		info.fdType = ntohl(info.fdType);
+
 		creator = PyString_FromStringAndSize(
 				(char *)&info.fdCreator, 4);
 		type = PyString_FromStringAndSize((char *)&info.fdType, 4);
@@ -341,6 +348,8 @@
 
 	} 
 	finfo = (FileInfo*)&(cataloginfo.finderInfo);
+	finfo->fileCreator = ntohl(finfo->fileCreator);
+	finfo->fileType = ntohl(finfo->fileType);
 	creator = PyString_FromStringAndSize((char*)&(finfo->fileCreator), 4);
 	type = PyString_FromStringAndSize((char*)&(finfo->fileType), 4);
 

Modified: python/branches/tlee-ast-optimize/Mac/PythonLauncher/Makefile.in
==============================================================================
--- python/branches/tlee-ast-optimize/Mac/PythonLauncher/Makefile.in	(original)
+++ python/branches/tlee-ast-optimize/Mac/PythonLauncher/Makefile.in	Wed Jan 14 13:24:17 2009
@@ -29,7 +29,7 @@
 install: Python\ Launcher.app
 	test -d "$(DESTDIR)$(PYTHONAPPSDIR)" || mkdir -p "$(DESTDIR)$(PYTHONAPPSDIR)"
 	-test -d "$(DESTDIR)$(PYTHONAPPSDIR)/Python Launcher.app" && rm -r "$(DESTDIR)$(PYTHONAPPSDIR)/Python Launcher.app"
-	cp -r "Python Launcher.app" "$(DESTDIR)$(PYTHONAPPSDIR)"
+	/bin/cp -r "Python Launcher.app" "$(DESTDIR)$(PYTHONAPPSDIR)"
 	touch "$(DESTDIR)$(PYTHONAPPSDIR)/Python Launcher.app"
 
 clean:

Modified: python/branches/tlee-ast-optimize/Makefile.pre.in
==============================================================================
--- python/branches/tlee-ast-optimize/Makefile.pre.in	(original)
+++ python/branches/tlee-ast-optimize/Makefile.pre.in	Wed Jan 14 13:24:17 2009
@@ -265,7 +265,6 @@
 		Python/getargs.o \
 		Python/getcompiler.o \
 		Python/getcopyright.o \
-		Python/getmtime.o \
 		Python/getplatform.o \
 		Python/getversion.o \
 		Python/graminit.o \
@@ -415,10 +414,14 @@
 	if test $(INSTSONAME) != $(LDLIBRARY); then \
 		$(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 		$(LN) -f $(INSTSONAME) $@; \
-	else\
+	else \
 		$(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 	fi
 
+libpython$(VERSION).dylib: $(LIBRARY_OBJS)
+	 $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+		 
+
 libpython$(VERSION).sl: $(LIBRARY_OBJS)
 	$(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST)
 
@@ -562,6 +565,9 @@
 Objects/unicodeobject.o: $(srcdir)/Objects/unicodeobject.c \
 				$(STRINGLIB_HEADERS)
 
+Objects/bytearrayobject.o: $(srcdir)/Objects/bytearrayobject.c \
+				$(STRINGLIB_HEADERS)
+
 Objects/stringobject.o: $(srcdir)/Objects/stringobject.c \
 				$(STRINGLIB_HEADERS)
 
@@ -582,6 +588,7 @@
 		Include/ast.h \
 		Include/bitset.h \
 		Include/boolobject.h \
+		Include/bytearrayobject.h \
 		Include/bytes_methods.h \
 		Include/bytesobject.h \
 		Include/bufferobject.h \
@@ -769,13 +776,13 @@
 		fi; \
 	done
 	$(INSTALL_PROGRAM) $(BUILDPYTHON) $(DESTDIR)$(BINDIR)/python$(VERSION)$(EXE)
-	if test -f libpython$(VERSION)$(SO); then \
-		if test "$(SO)" = .dll; then \
-			$(INSTALL_SHARED) libpython$(VERSION)$(SO) $(DESTDIR)$(BINDIR); \
+	if test -f $(LDLIBRARY); then \
+		if test -n "$(DLLLIBRARY)" ; then \
+			$(INSTALL_SHARED) $(DLLLIBRARY) $(DESTDIR)$(BINDIR); \
 		else \
-			$(INSTALL_SHARED) libpython$(VERSION)$(SO) $(DESTDIR)$(LIBDIR)/$(INSTSONAME); \
-			if test libpython$(VERSION)$(SO) != $(INSTSONAME); then \
-				(cd $(DESTDIR)$(LIBDIR); $(LN) -sf $(INSTSONAME) libpython$(VERSION)$(SO)); \
+			$(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(LIBDIR)/$(INSTSONAME); \
+			if test $(LDLIBRARY) != $(INSTSONAME); then \
+				(cd $(DESTDIR)$(LIBDIR); $(LN) -sf $(INSTSONAME) $(LDLIBRARY)) \
 			fi \
 		fi; \
 	else	true; \
@@ -906,7 +913,7 @@
 	export PYTHONPATH; PYTHONPATH="`pwd`/Lib"; \
 	export DYLD_FRAMEWORK_PATH; DYLD_FRAMEWORK_PATH="`pwd`"; \
 	export EXE; EXE="$(BUILDEXE)"; \
-	cd $(srcdir)/Lib/$(PLATDIR); ./regen
+	cd $(srcdir)/Lib/$(PLATDIR); $(RUNSHARED) ./regen
 
 # Install the include files
 INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY)
@@ -1069,7 +1076,7 @@
 # This installs the Demos and Tools into the applications directory.
 # It is not part of a normal frameworkinstall
 frameworkinstallextras:
-	cd Mac && Make installextras DESTDIR="$(DESTDIR)"
+	cd Mac && $(MAKE) installextras DESTDIR="$(DESTDIR)"
 
 # This installs a few of the useful scripts in Tools/scripts
 scriptsinstall:

Modified: python/branches/tlee-ast-optimize/Misc/ACKS
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/ACKS	(original)
+++ python/branches/tlee-ast-optimize/Misc/ACKS	Wed Jan 14 13:24:17 2009
@@ -84,6 +84,7 @@
 Sebastian Boving
 Monty Brandenberg
 Georg Brandl
+Christopher Brannon
 Terrence Brannon
 Dave Brennan
 Tom Bridgman
@@ -178,6 +179,7 @@
 Quinn Dunkan
 Robin Dunn
 Luke Dunstan
+Virgil Dupras
 Andy Dustman
 Gary Duzan
 Eugene Dvurechenski
@@ -245,6 +247,7 @@
 Harry Henry Gebel
 Marius Gedminas
 Thomas Gellekum
+Gabriel Genellina
 Christos Georgiou
 Ben Gertzfield
 Dinu Gherman
@@ -312,6 +315,7 @@
 Naofumi Honda
 Jeffrey Honig
 Rob Hooft
+Michiel de Hoon
 Brian Hooper
 Randall Hopper
 Nadav Horesh
@@ -343,6 +347,7 @@
 Flemming Kjær Jensen
 Jiba
 Orjan Johansen
+Fredrik Johansson
 Gregory K. Johnson
 Simon Johnston
 Evan Jones
@@ -371,6 +376,7 @@
 Taek Joo Kim
 Paul Kippes
 Steve Kirsch
+Sebastian Kirsche
 Ron Klatchko
 Bastian Kleineidam
 Bob Kline
@@ -426,6 +432,7 @@
 Jason Lowe
 Tony Lownds
 Ray Loyzaga
+Lukas Lueg
 Loren Luke
 Fredrik Lundh
 Mark Lutz

Modified: python/branches/tlee-ast-optimize/Misc/NEWS
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/NEWS	(original)
+++ python/branches/tlee-ast-optimize/Misc/NEWS	Wed Jan 14 13:24:17 2009
@@ -12,14 +12,87 @@
 Core and Builtins
 -----------------
 
+- Issue #4807: Port the _winreg module to Windows CE.
+
+- Issue #4935: The overflow checking code in the expandtabs() method common
+  to str, bytes and bytearray could be optimized away by the compiler, letting
+  the interpreter segfault instead of raising an error.
+
+- Issue #3720: Fix a crash when an iterator modifies its class and removes its
+  __next__ method.
+
+- Issue #4893: Use NT threading on CE.
+
+- Issue #4915: Port sysmodule to Windows CE.
+
+- Issue #4074: Change the criteria for doing a full garbage collection (i.e.
+  collecting the oldest generation) so that allocating lots of objects without
+  destroying them does not show quadratic performance. Based on a proposal by
+  Martin von Löwis at
+  http://mail.python.org/pipermail/python-dev/2008-June/080579.html.
+
+- Issue #4850: Change COUNT_ALLOCS variables to Py_ssize_t.
+
+- Issue #1180193: When importing a module from a .pyc (or .pyo) file with
+  an existing .py counterpart, override the co_filename attributes of all
+  code objects if the original filename is obsolete (which can happen if the
+  file has been renamed, moved, or if it is accessed through different paths).
+  Patch by Ziga Seilnacht and Jean-Paul Calderone.
+
+- Issue #4075: Use OutputDebugStringW in Py_FatalError.
+
+- Issue #4797: IOError.filename was not set when _fileio.FileIO failed to open
+  file with `str' filename on Windows.
+
+- Issue #3680: Reference cycles created through a dict, set or deque iterator
+  did not get collected.
+
+- Issue #4701: PyObject_Hash now implicitly calls PyType_Ready on types
+  where the tp_hash and tp_dict slots are both NULL.
+
+- Issue #4764: With io.open, IOError.filename is set when trying to open a
+  directory on POSIX systems.
+
+- Issue #4764: IOError.filename is set when trying to open a directory on POSIX
+  systems.
+
+- Issue #4759: None is now allowed as the first argument of
+  bytearray.translate().  It was always allowed for bytes.translate().
+
+- Added test case to ensure attempts to read from a file opened for writing
+  fail.
+
+- Issue #2467: gc.DEBUG_STATS reported invalid elapsed times. Also, always
+  print elapsed times, not only when some objects are uncollectable /
+  unreachable. Original patch by Neil Schemenauer.
+
+- Issue #3439: Add a bit_length method to int and long.
+
+- Issue #2183: Simplify and optimize bytecode for list comprehensions.
+  Original patch by Neal Norwitz.
+
+- Issue #4597: Fixed exception handling when the __exit__ function of a
+  context manager returns a value that cannot be converted to a bool.
+
+- Issue #4597: Fixed several opcodes that weren't always propagating
+  exceptions.
+
+- Issue #4445: Replace "sizeof(PyStringObject)" with
+  "offsetof(PyStringObject, ob_sval) + 1" when allocating memory for
+  str instances.  On a typical machine this saves 3 bytes of memory
+  (on average) per string allocation.
+
 - Issue #3996: On Windows, the PyOS_CheckStack function would cause the
   interpreter to abort ("Fatal Python error: Could not reset the stack!")
   instead of throwing a MemoryError.
 
+- Issue #3689: The list reversed iterator now supports __length_hint__
+  instead of __len__.  Behavior now matches other reversed iterators.
+
 - Issue #4367: Python would segfault during compiling when the unicodedata
   module couldn't be imported and \N escapes were present.
 
-- Issue #4233: Changed semantic of ``_fileio.FileIO``'s ``close()`` 
+- Issue #4233: Changed semantic of ``_fileio.FileIO``'s ``close()``
   method on file objects with closefd=False. The file descriptor is still
   kept open but the file object behaves like a closed file. The ``FileIO``
   object also got a new readonly attribute ``closefd``.
@@ -54,9 +127,136 @@
   KeyError would always report the empty frozenset([]) as the missing key. Now
   it correctly refers to the initial element.
 
+- Issue #4509: Various issues surrounding resize of bytearray objects to
+  which there are buffer exports.
+
+- Issue #4748: Lambda generators no longer return a value.
+
+- Issue #3582: Use native TLS functions on Windows
+
 Library
 -------
 
+- Issue #1162154: inspect.getmembers() now skips attributes that raise
+  AttributeError, e.g. a __slots__ attribute which has not been set.
+
+- Issue #1696199: Add collections.Counter() for rapid and convenient
+  counting.
+
+- Issue #3860: GzipFile and BZ2File now support the context manager protocol.
+
+- Issue #4272: Add an optional argument to the GzipFile constructor to override
+  the timestamp in the gzip stream. The default value remains the current time.
+  The information can be used by e.g. gunzip when decompressing. Patch by
+  Jacques Frechet.
+
+- Restore Python 2.3 compatibility for decimal.py.
+
+- Issue #1702551: distutils sdist was not excluding VCS directories under 
+  Windows. Inital solution by Guy Dalberto.
+
+- The _tkinter module functions "createfilehandler", "deletefilehandler",
+  "createtimerhandler", "mainloop", "dooneevent" and "quit" have been
+  deprecated for removal in 3.x
+
+- Issue #4796: Added Decimal.from_float() and Context.create_decimal_from_float()
+  to the decimal module.
+
+- Issue #4812: add missing underscore prefix to some internal-use-only
+  constants in the decimal module.  (Dec_0 becomes _Dec_0, etc.)
+
+- Issue #4795: inspect.isgeneratorfunction() returns False instead of None when
+  the function is not a generator.
+
+- Issue #4702: Throwing a DistutilsPlatformError instead of IOError in case 
+  no MSVC compiler is found under Windows. Original patch by Philip Jenvey. 
+
+- Issue #4646: distutils was choking on empty options arg in the setup 
+  function. Original patch by Thomas Heller.
+
+- Fractions.from_float() no longer loses precision for integers too big to
+  cast as floats.
+
+- Issue 4790: The nsmallest() and nlargest() functions in the heapq module
+  did unnecessary work in the common case where no key function was specified.
+
+- Issue #3767: Convert Tk object to string in tkColorChooser.
+
+- Issue #3248: Allow placing ScrolledText in a PanedWindow.
+
+- Issue #4444: Allow assertRaises() to be used as a context handler, so that
+  the code under test can be written inline if more practical.
+
+- Issue #4739: Add pydoc help topics for symbols, so that e.g. help('@')
+  works as expected in the interactive environment.
+
+- Issue #4756: zipfile.is_zipfile() now supports file-like objects. Patch by
+  Gabriel Genellina.
+
+- Issue #4400: .pypirc default generated file was broken in distutils.
+
+- Issue #4736: io.BufferedRWPair's closed property now functions properly.
+
+- Issue #3954: Fix a potential SystemError in _hotshot.logreader error
+  handling.
+
+- Issue #4574: fix a crash in io.IncrementalNewlineDecoder when a carriage
+  return encodes to more than one byte in the source encoding (e.g. UTF-16)
+  and gets split on a chunk boundary.
+
+- Issue #4223: inspect.getsource() will now correctly display source code
+  for packages loaded via zipimport (or any other conformant PEP 302
+  loader). Original patch by Alexander Belopolsky.
+
+- Issue #4201: pdb can now access and display source code loaded via
+  zipimport (or any other conformant PEP 302 loader). Original patch by
+  Alexander Belopolsky.
+
+- Issue #4197: doctests in modules loaded via zipimport (or any other PEP
+  302 conformant loader) will now work correctly in most cases (they
+  are still subject to the constraints that exist for all code running
+  from inside a module loaded via a PEP 302 loader and attempting to
+  perform IO operations based on __file__). Original patch by
+  Alexander Belopolsky.
+
+- Issues #4082 and #4512: Add runpy support to zipimport in a manner that
+  allows backporting to maintenance branches. Original patch by
+  Alexander Belopolsky.
+
+- Issue #4163: Use unicode-friendly word splitting in the textwrap functions
+  when given an unicode string.
+
+- Issue #4616: TarFile.utime(): Restore directory times on Windows.
+
+- Issue #4084: Fix max, min, max_mag and min_mag Decimal methods to
+  give correct results in the case where one argument is a quiet NaN
+  and the other is a finite number that requires rounding.
+
+- Issue #1030250: Distutils created directories even when run with the
+  --dry-run option.
+
+- Issue #4483: _dbm module now builds on systems with gdbm & gdbm_compat
+  libs.
+
+- Issue #4529: fix the parser module's validation of try-except-finally
+  statements.
+
+- Issue #4458: getopt.gnu_getopt() now recognizes a single "-" as an argument,
+  not a malformed option.
+
+- Added the subprocess.check_output() convenience function to get output
+  from a subprocess on success or raise an exception on error.
+
+- Issue #1055234: cgi.parse_header(): Fixed parsing of header parameters to
+  support unusual filenames (such as those containing semi-colons) in
+  Content-Disposition headers.
+
+- Issue #4384: Added logging integration with warnings module using
+  captureWarnings(). This change includes a NullHandler which does nothing;
+  it will be of use to library developers who want to avoid the "No handlers
+  could be found for logger XXX" message which can appear if the library user
+  doesn't configure logging.
+
 - Issue #3741: DISTUTILS_USE_SDK set causes msvc9compiler.py to raise an
   exception.
 
@@ -86,9 +286,46 @@
 - Issue #4014: Don't claim that Python has an Alpha release status, in addition
   to claiming it is Mature.
 
+- Issue #4730: Fixed the cPickle module to handle correctly astral characters
+  when protocol 0 is used.
+
+- Issue #1594: MacOS.GetCreatorAndType now always returns a big-endian result,
+  to be consistent with Apple tools.
+
+- Issue #900949: plat-mac/videoreader.py no longer relies on a non-existing
+  module. 
+
+- Issue #16278952: plat-mac/videoreader.py now correctly imports MediaDescr
+
+- Issue #1737832 : plat-mac/EasyDialog.py no longer uses the broken aepack
+  module.
+
+- Issue #1149804: macostools.mkdirs now even works when another process
+  creates one of the needed subdirectories.
+
+- Issue #900506: added --no-zipimport flag to the bundlebuilder script
+
+- Issue #841800: bundlebuilder now works with 'python -O'
+
+- Issue #4861: ctypes.util.find_library(): Robustify. Fix library detection on
+  biarch systems. Try to rely on ldconfig only, without using objdump and gcc.
+
+Tools/Demos
+-----------
+
+- Issue #4677: add two list comprehension tests to pybench.
+
 Build
 -----
 
+- Issue #4895: Use _strdup on Windows CE.
+
+- Issue #4472: "configure --enable-shared" now works on OSX
+
+- Issues #4728 and #4060: WORDS_BIGEDIAN is now correct in Universal builds.
+
+- Issue #4389: Add icon to the uninstall entry in "add-and-remove-programs".
+
 - Issue #4289: Remove Cancel button from AdvancedDlg.
 
 - Issue #1656675: Register a drop handler for .py* files on Windows.
@@ -106,12 +343,33 @@
 C-API
 -----
 
+- Issue #4720: The format for PyArg_ParseTupleAndKeywords can begin with '|'.
+
+- Issue #3632: from the gdb debugger, the 'pyo' macro can now be called when
+  the GIL is released, or owned by another thread.
+
 - Issue #4122: On Windows, fix a compilation error when using the
   Py_UNICODE_ISSPACE macro in an extension module.
+  
+- Issue #4293: Py_AddPendingCall is now thread safe and can be used for
+  asynchronous notifications to python from any thread.  Documentation added.
 
 Extension Modules
 -----------------
 
+- Issue #4279: Fix build of parsermodule under Cygwin.
+
+- Issue #4051: Prevent conflict of UNICODE macros in cPickle.
+
+- Issue #4228: Pack negative values the same way as 2.4 in struct's L format.
+
+- Issue #1040026: Fix os.times result on systems where HZ is incorrect.
+
+- Issues #3167, #3682: Fix test_math failures for log, log10 on Solaris,
+  OpenBSD.
+
+- Issue #4365: Add crtassem.h constants to the msvcrt module.
+
 - Issue #4396: The parser module now correctly validates the with statement.
 
 

Modified: python/branches/tlee-ast-optimize/Misc/build.sh
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/build.sh	(original)
+++ python/branches/tlee-ast-optimize/Misc/build.sh	Wed Jan 14 13:24:17 2009
@@ -262,7 +262,7 @@
     echo "Conflict detected in $CONFLICTED_FILE.  Doc build skipped." > ../build/$F
     err=1
 else
-    make update html >& ../build/$F
+    make checkout update html >& ../build/$F
     err=$?
 fi
 update_status "Making doc" "$F" $start

Modified: python/branches/tlee-ast-optimize/Misc/developers.txt
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/developers.txt	(original)
+++ python/branches/tlee-ast-optimize/Misc/developers.txt	Wed Jan 14 13:24:17 2009
@@ -17,6 +17,9 @@
 Permissions History
 -------------------
 
+- Tarek Ziadé as given SVN access on Decmeber 21 2008 by NCN,
+  for maintenance of distutils.
+
 - Hirokazu Yamamoto was given SVN access on August 12 2008 by MvL,
   for contributions to the Windows build.
 

Modified: python/branches/tlee-ast-optimize/Misc/python.man
==============================================================================
--- python/branches/tlee-ast-optimize/Misc/python.man	(original)
+++ python/branches/tlee-ast-optimize/Misc/python.man	Wed Jan 14 13:24:17 2009
@@ -54,6 +54,9 @@
 [
 .B \-x
 ]
+[
+.B \-3
+]
 .br
        [
 .B \-c
@@ -236,6 +239,9 @@
 Skip the first line of the source.  This is intended for a DOS
 specific hack only.  Warning: the line numbers in error messages will
 be off by one!
+.TP
+.B \-3
+Warn about Python 3.x incompatibilities that 2to3 cannot trivially fix.
 .SH INTERPRETER INTERFACE
 The interpreter interface resembles that of the UNIX shell: when
 called with standard input connected to a tty device, it prompts for

Modified: python/branches/tlee-ast-optimize/Modules/_collectionsmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_collectionsmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_collectionsmodule.c	Wed Jan 14 13:24:17 2009
@@ -958,7 +958,7 @@
 {
 	dequeiterobject *it;
 
-	it = PyObject_New(dequeiterobject, &dequeiter_type);
+	it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
 	if (it == NULL)
 		return NULL;
 	it->b = deque->leftblock;
@@ -967,14 +967,22 @@
 	it->deque = deque;
 	it->state = deque->state;
 	it->counter = deque->len;
+	PyObject_GC_Track(it);
 	return (PyObject *)it;
 }
 
+static int
+dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
+{
+	Py_VISIT(dio->deque);
+	return 0;
+}
+
 static void
 dequeiter_dealloc(dequeiterobject *dio)
 {
 	Py_XDECREF(dio->deque);
-	Py_TYPE(dio)->tp_free(dio);
+	PyObject_GC_Del(dio);
 }
 
 static PyObject *
@@ -1039,9 +1047,9 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
 	0,					/* tp_doc */
-	0,					/* tp_traverse */
+	(traverseproc)dequeiter_traverse,	/* tp_traverse */
 	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
@@ -1060,7 +1068,7 @@
 {
 	dequeiterobject *it;
 
-	it = PyObject_New(dequeiterobject, &dequereviter_type);
+	it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
 	if (it == NULL)
 		return NULL;
 	it->b = deque->rightblock;
@@ -1069,6 +1077,7 @@
 	it->deque = deque;
 	it->state = deque->state;
 	it->counter = deque->len;
+	PyObject_GC_Track(it);
 	return (PyObject *)it;
 }
 
@@ -1121,9 +1130,9 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
 	0,					/* tp_doc */
-	0,					/* tp_traverse */
+	(traverseproc)dequeiter_traverse,	/* tp_traverse */
 	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */

Modified: python/branches/tlee-ast-optimize/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_ctypes/callproc.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_ctypes/callproc.c	Wed Jan 14 13:24:17 2009
@@ -221,7 +221,7 @@
 	n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
 			  NULL,
 			  code,
-			  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
+			  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
 			  (LPTSTR) &lpMsgBuf,
 			  0,
 			  NULL);

Modified: python/branches/tlee-ast-optimize/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_ctypes/cfield.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_ctypes/cfield.c	Wed Jan 14 13:24:17 2009
@@ -1452,11 +1452,14 @@
 		size += 1; /* terminating NUL */
 		size *= sizeof(wchar_t);
 		buffer = (wchar_t *)PyMem_Malloc(size);
-		if (!buffer)
+		if (!buffer) {
+			Py_DECREF(value);
 			return PyErr_NoMemory();
+		}
 		memset(buffer, 0, size);
 		keep = PyCObject_FromVoidPtr(buffer, PyMem_Free);
 		if (!keep) {
+			Py_DECREF(value);
 			PyMem_Free(buffer);
 			return NULL;
 		}

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	Wed Jan 14 13:24:17 2009
@@ -98,7 +98,7 @@
    directories, so we need a check.  */
 
 static int
-dircheck(PyFileIOObject* self)
+dircheck(PyFileIOObject* self, char *name)
 {
 #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
 	struct stat buf;
@@ -109,8 +109,8 @@
 		PyObject *exc;
 		internal_close(self);
 
-		exc = PyObject_CallFunction(PyExc_IOError, "(is)",
-					    EISDIR, msg);
+		exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
+					    EISDIR, msg, name);
 		PyErr_SetObject(PyExc_IOError, exc);
 		Py_XDECREF(exc);
 		return -1;
@@ -265,13 +265,14 @@
 		Py_END_ALLOW_THREADS
 		if (self->fd < 0) {
 #ifdef MS_WINDOWS
-			PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
-#else
-			PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
+			if (widename != NULL)
+				PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
+			else
 #endif
+				PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
 			goto error;
 		}
-		if(dircheck(self) < 0)
+		if(dircheck(self, name) < 0)
 			goto error;
 	}
 

Modified: python/branches/tlee-ast-optimize/Modules/_hotshot.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_hotshot.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_hotshot.c	Wed Jan 14 13:24:17 2009
@@ -1357,20 +1357,16 @@
             self->logfp = fopen(filename, "rb");
             if (self->logfp == NULL) {
                 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
-                Py_DECREF(self);
-                self = NULL;
-                goto finally;
+                goto error;
             }
             self->info = PyDict_New();
-            if (self->info == NULL) {
-                Py_DECREF(self);
-                goto finally;
-            }
+            if (self->info == NULL)
+                goto error;
             /* read initial info */
             for (;;) {
                 if ((c = fgetc(self->logfp)) == EOF) {
                     eof_error(self);
-                    break;
+                    goto error;
                 }
                 if (c != WHAT_ADD_INFO) {
                     ungetc(c, self->logfp);
@@ -1383,13 +1379,15 @@
                     else
                         PyErr_SetString(PyExc_RuntimeError,
                                         "unexpected error");
-                    break;
+                    goto error;
                 }
             }
         }
     }
- finally:
     return (PyObject *) self;
+  error:
+    Py_DECREF(self);
+    return NULL;
 }
 
 

Modified: python/branches/tlee-ast-optimize/Modules/_struct.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_struct.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_struct.c	Wed Jan 14 13:24:17 2009
@@ -663,7 +663,7 @@
 		return -1;
 #if (SIZEOF_LONG > SIZEOF_INT)
 	if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
-		return _range_error(f, 0);
+		RANGE_ERROR(x, f, 0, -1);
 #endif
 	y = (int)x;
 	memcpy(p, (char *)&y, sizeof y);
@@ -675,12 +675,12 @@
 {
 	unsigned long x;
 	unsigned int y;
-	if (get_ulong(v, &x) < 0)
-		return _range_error(f, 1);
+	if (get_wrapped_ulong(v, &x) < 0)
+		return -1;
 	y = (unsigned int)x;
 #if (SIZEOF_LONG > SIZEOF_INT)
 	if (x > ((unsigned long)UINT_MAX))
-		return _range_error(f, 1);
+		RANGE_ERROR(y, f, 1, -1);
 #endif
 	memcpy(p, (char *)&y, sizeof y);
 	return 0;
@@ -700,8 +700,8 @@
 np_ulong(char *p, PyObject *v, const formatdef *f)
 {
 	unsigned long x;
-	if (get_ulong(v, &x) < 0)
-		return _range_error(f, 1);
+	if (get_wrapped_ulong(v, &x) < 0)
+		return -1;
 	memcpy(p, (char *)&x, sizeof x);
 	return 0;
 }

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	Wed Jan 14 13:24:17 2009
@@ -173,6 +173,106 @@
 }
 
 
+/* Issue #4701: Check that PyObject_Hash implicitly calls
+ *   PyType_Ready if it hasn't already been called
+ */
+static PyTypeObject _HashInheritanceTester_Type = {
+	PyObject_HEAD_INIT(NULL)
+	0,			/* Number of items for varobject */
+	"hashinheritancetester",	/* Name of this type */
+	sizeof(PyObject),	/* Basic object size */
+	0,			/* Item size for varobject */
+	(destructor)PyObject_Del, /* tp_dealloc */
+	0,			/* tp_print */
+	0,			/* tp_getattr */
+	0,			/* tp_setattr */
+	0,			/* tp_compare */
+	0,			/* tp_repr */
+	0,			/* tp_as_number */
+	0,			/* tp_as_sequence */
+	0,			/* tp_as_mapping */
+	0,			/* tp_hash */
+	0,			/* tp_call */
+	0,			/* tp_str */
+	PyObject_GenericGetAttr,  /* tp_getattro */
+	0,			/* tp_setattro */
+	0,			/* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,	/* tp_flags */
+	0,			/* tp_doc */
+	0,			/* tp_traverse */
+	0,			/* tp_clear */
+	0,			/* tp_richcompare */
+	0,			/* tp_weaklistoffset */
+	0,			/* tp_iter */
+	0,			/* tp_iternext */
+	0,			/* tp_methods */
+	0,			/* tp_members */
+	0,			/* tp_getset */
+	0,			/* tp_base */
+	0,			/* tp_dict */
+	0,			/* tp_descr_get */
+	0,			/* tp_descr_set */
+	0,			/* tp_dictoffset */
+	0,			/* tp_init */
+	0,			/* tp_alloc */
+	PyType_GenericNew,		/* tp_new */
+};
+
+static PyObject*
+test_lazy_hash_inheritance(PyObject* self)
+{
+	PyTypeObject *type;
+	PyObject *obj;
+	long hash;
+
+	type = &_HashInheritanceTester_Type;
+	obj = PyObject_New(PyObject, type);
+	if (obj == NULL) {
+		PyErr_Clear();
+		PyErr_SetString(
+			TestError,
+			"test_lazy_hash_inheritance: failed to create object");
+		return NULL;
+	}
+
+	if (type->tp_dict != NULL) {
+		PyErr_SetString(
+			TestError,
+			"test_lazy_hash_inheritance: type initialised too soon");
+		Py_DECREF(obj);
+		return NULL;
+	}
+
+	hash = PyObject_Hash(obj);
+	if ((hash == -1) && PyErr_Occurred()) {
+		PyErr_Clear();
+		PyErr_SetString(
+			TestError,
+			"test_lazy_hash_inheritance: could not hash object");
+		Py_DECREF(obj);
+		return NULL;
+	}
+
+	if (type->tp_dict == NULL) {
+		PyErr_SetString(
+			TestError,
+			"test_lazy_hash_inheritance: type not initialised by hash()");
+		Py_DECREF(obj);
+		return NULL;
+	}
+
+	if (type->tp_hash != PyType_Type.tp_hash) {
+		PyErr_SetString(
+			TestError,
+			"test_lazy_hash_inheritance: unexpected hash function");
+		Py_DECREF(obj);
+		return NULL;
+	}
+
+	Py_RETURN_NONE;
+}
+
+
 /* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG)
    PyLong_{As, From}{Unsigned,}LongLong().
 
@@ -474,6 +574,8 @@
 
 #ifdef Py_USING_UNICODE
 
+static volatile int x;
+
 /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
    of an error.
 */
@@ -486,7 +588,7 @@
 
 	/* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
 	/* Just use the macro and check that it compiles */
-	int x = Py_UNICODE_ISSPACE(25);
+	x = Py_UNICODE_ISSPACE(25);
 
         tuple = PyTuple_New(1);
         if (tuple == NULL)
@@ -519,6 +621,32 @@
 }
 
 static PyObject *
+test_empty_argparse(PyObject *self)
+{
+	/* Test that formats can begin with '|'. See issue #4720. */
+	PyObject *tuple, *dict = NULL;
+	static char *kwlist[] = {NULL};
+	int result;
+	tuple = PyTuple_New(0);
+	if (!tuple)
+		return NULL;
+	if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
+		goto done;
+	dict = PyDict_New();
+	if (!dict)
+		goto done;
+	result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
+  done:
+	Py_DECREF(tuple);
+	Py_XDECREF(dict);
+	if (result < 0)
+		return NULL;
+	else {
+		Py_RETURN_NONE;
+	}
+}
+
+static PyObject *
 codec_incrementalencoder(PyObject *self, PyObject *args)
 {
 	const char *encoding, *errors = NULL;
@@ -709,6 +837,43 @@
 		return NULL;
 	Py_RETURN_NONE;
 }
+
+/* test Py_AddPendingCalls using threads */
+static int _pending_callback(void *arg)
+{
+	/* we assume the argument is callable object to which we own a reference */
+	PyObject *callable = (PyObject *)arg;
+	PyObject *r = PyObject_CallObject(callable, NULL);
+	Py_DECREF(callable);
+	Py_XDECREF(r);
+	return r != NULL ? 0 : -1;
+}
+
+/* The following requests n callbacks to _pending_callback.  It can be
+ * run from any python thread.
+ */
+PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
+{
+	PyObject *callable;
+	int r;
+	if (PyArg_ParseTuple(arg, "O", &callable) == 0)
+		return NULL;
+
+	/* create the reference for the callbackwhile we hold the lock */
+	Py_INCREF(callable);
+
+	Py_BEGIN_ALLOW_THREADS
+	r = Py_AddPendingCall(&_pending_callback, callable);
+	Py_END_ALLOW_THREADS
+
+	if (r<0) {
+		Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
+		Py_INCREF(Py_False);
+		return Py_False;
+	}
+	Py_INCREF(Py_True);
+	return Py_True;
+}
 #endif
 
 /* Some tests of PyString_FromFormat().  This needs more tests. */
@@ -777,9 +942,11 @@
 	{"test_config",		(PyCFunction)test_config,	 METH_NOARGS},
 	{"test_list_api",	(PyCFunction)test_list_api,	 METH_NOARGS},
 	{"test_dict_iteration",	(PyCFunction)test_dict_iteration,METH_NOARGS},
+	{"test_lazy_hash_inheritance",	(PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
 	{"test_long_api",	(PyCFunction)test_long_api,	 METH_NOARGS},
 	{"test_long_numbits",	(PyCFunction)test_long_numbits,	 METH_NOARGS},
 	{"test_k_code",		(PyCFunction)test_k_code,	 METH_NOARGS},
+	{"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
 	{"test_null_strings",	(PyCFunction)test_null_strings,	 METH_NOARGS},
 	{"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
 	{"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
@@ -811,6 +978,7 @@
 #endif
 #ifdef WITH_THREAD
 	{"_test_thread_state",  test_thread_state, 		 METH_VARARGS},
+	{"_pending_threadfunc",	pending_threadfunc,		 METH_VARARGS},
 #endif
 	{"traceback_print", traceback_print, 	         METH_VARARGS},
 	{NULL, NULL} /* sentinel */
@@ -962,6 +1130,8 @@
 	if (m == NULL)
 		return;
 
+	Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
+
 	Py_TYPE(&test_structmembersType)=&PyType_Type;
 	Py_INCREF(&test_structmembersType);
 	PyModule_AddObject(m, "test_structmembersType", (PyObject *)&test_structmembersType);

Modified: python/branches/tlee-ast-optimize/Modules/_tkinter.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/_tkinter.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/_tkinter.c	Wed Jan 14 13:24:17 2009
@@ -2255,6 +2255,12 @@
 	PyObject *file, *func;
 	int mask, tfile;
 
+	if (!self && Py_Py3kWarningFlag) {
+		if (PyErr_Warn(PyExc_DeprecationWarning,
+					"_tkinter.createfilehandler is gone in 3.x") < 0)
+			return NULL;
+	}
+
 	if (!PyArg_ParseTuple(args, "OiO:createfilehandler",
 			      &file, &mask, &func))
 		return NULL;
@@ -2299,6 +2305,12 @@
 	PyObject *file;
 	int tfile;
 
+	if (!self && Py_Py3kWarningFlag) {
+		if (PyErr_Warn(PyExc_DeprecationWarning,
+					"_tkinter.deletefilehandler is gone in 3.x") < 0)
+			return NULL;
+	}
+
 	if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
 		return NULL;
 
@@ -2472,6 +2484,12 @@
 	PyObject *func;
 	TkttObject *v;
 
+	if (!self && Py_Py3kWarningFlag) {
+		if (PyErr_Warn(PyExc_DeprecationWarning,
+					"_tkinter.createtimerhandler is gone in 3.x") < 0)
+			return NULL;
+	}
+
 	if (!PyArg_ParseTuple(args, "iO:createtimerhandler",
 			      &milliseconds, &func))
 		return NULL;
@@ -2515,6 +2533,12 @@
 	PyThreadState *tstate = PyThreadState_Get();
 #endif
 
+	if (!self && Py_Py3kWarningFlag) {
+		if (PyErr_Warn(PyExc_DeprecationWarning,
+					"_tkinter.mainloop is gone in 3.x") < 0)
+			return NULL;
+	}
+
 	if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
 		return NULL;
 
@@ -2590,6 +2614,12 @@
 	int flags = 0;
 	int rv;
 
+	if (!self && Py_Py3kWarningFlag) {
+		if (PyErr_Warn(PyExc_DeprecationWarning,
+					"_tkinter.dooneevent is gone in 3.x") < 0)
+			return NULL;
+	}
+
 	if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
 		return NULL;
 
@@ -2603,6 +2633,12 @@
 Tkapp_Quit(PyObject *self, PyObject *args)
 {
 
+	if (!self && Py_Py3kWarningFlag) {
+		if (PyErr_Warn(PyExc_DeprecationWarning,
+					"_tkinter.createfilehandler is gone in 3.x") < 0)
+			return NULL;
+	}
+
 	if (!PyArg_ParseTuple(args, ":quit"))
 		return NULL;
 

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	Wed Jan 14 13:24:17 2009
@@ -1201,6 +1201,36 @@
 	return ret;
 }
 
+PyDoc_STRVAR(BZ2File_enter_doc,
+"__enter__() -> self.");
+
+static PyObject *
+BZ2File_enter(BZ2FileObject *self)
+{
+	if (self->mode == MODE_CLOSED) {
+		PyErr_SetString(PyExc_ValueError,
+			"I/O operation on closed file");
+		return NULL;
+	}
+	Py_INCREF(self);
+	return (PyObject *) self;
+}
+
+PyDoc_STRVAR(BZ2File_exit_doc,
+"__exit__(*excinfo) -> None.  Closes the file.");
+
+static PyObject *
+BZ2File_exit(BZ2FileObject *self, PyObject *args)
+{
+	PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL);
+	if (!ret)
+		/* If error occurred, pass through */
+		return NULL;
+	Py_DECREF(ret);
+	Py_RETURN_NONE;
+}
+
+
 static PyObject *BZ2File_getiter(BZ2FileObject *self);
 
 static PyMethodDef BZ2File_methods[] = {
@@ -1213,6 +1243,8 @@
 	{"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__},
 	{"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__},
 	{"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__},
+	{"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc},
+	{"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc},
 	{NULL,		NULL}		/* sentinel */
 };
 

Modified: python/branches/tlee-ast-optimize/Modules/cPickle.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/cPickle.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/cPickle.c	Wed Jan 14 13:24:17 2009
@@ -18,6 +18,14 @@
 #define HIGHEST_PROTOCOL 2
 
 /*
+ * Note: The UNICODE macro controls the TCHAR meaning of the win32 API. Since
+ * all headers have already been included here, we can safely redefine it.
+ */
+#ifdef UNICODE
+#  undef UNICODE
+#endif
+
+/*
  * Pickle opcodes.  These must be kept in synch with pickle.py.  Extensive
  * docs are in pickletools.py.
  */
@@ -1255,42 +1263,91 @@
 /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates
    backslash and newline characters to \uXXXX escapes. */
 static PyObject *
-modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, int size)
+modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
 {
-	PyObject *repr;
-	char *p;
-	char *q;
+    PyObject *repr;
+    char *p;
+    char *q;
+
+    static const char *hexdigit = "0123456789abcdef";
+#ifdef Py_UNICODE_WIDE
+    const Py_ssize_t expandsize = 10;
+#else
+    const Py_ssize_t expandsize = 6;
+#endif
 
-	static const char *hexdigit = "0123456789ABCDEF";
+    if (size > PY_SSIZE_T_MAX / expandsize)
+        return PyErr_NoMemory();
 
-	repr = PyString_FromStringAndSize(NULL, 6 * size);
-	if (repr == NULL)
-		return NULL;
-	if (size == 0)
-		return repr;
+    repr = PyString_FromStringAndSize(NULL, expandsize * size);
+    if (repr == NULL)
+        return NULL;
+    if (size == 0)
+	return repr;
 
-	p = q = PyString_AS_STRING(repr);
-	while (size-- > 0) {
-		Py_UNICODE ch = *s++;
-		/* Map 16-bit characters to '\uxxxx' */
-		if (ch >= 256 || ch == '\\' || ch == '\n') {
-			*p++ = '\\';
-			*p++ = 'u';
-			*p++ = hexdigit[(ch >> 12) & 0xf];
-			*p++ = hexdigit[(ch >> 8) & 0xf];
-			*p++ = hexdigit[(ch >> 4) & 0xf];
-			*p++ = hexdigit[ch & 15];
-		}
-		/* Copy everything else as-is */
-		else
-			*p++ = (char) ch;
+    p = q = PyString_AS_STRING(repr);
+    while (size-- > 0) {
+        Py_UNICODE ch = *s++;
+#ifdef Py_UNICODE_WIDE
+	/* Map 32-bit characters to '\Uxxxxxxxx' */
+	if (ch >= 0x10000) {
+            *p++ = '\\';
+            *p++ = 'U';
+            *p++ = hexdigit[(ch >> 28) & 0xf];
+            *p++ = hexdigit[(ch >> 24) & 0xf];
+            *p++ = hexdigit[(ch >> 20) & 0xf];
+            *p++ = hexdigit[(ch >> 16) & 0xf];
+            *p++ = hexdigit[(ch >> 12) & 0xf];
+            *p++ = hexdigit[(ch >> 8) & 0xf];
+            *p++ = hexdigit[(ch >> 4) & 0xf];
+            *p++ = hexdigit[ch & 15];
+        }
+        else
+#else
+	/* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
+	if (ch >= 0xD800 && ch < 0xDC00) {
+	    Py_UNICODE ch2;
+	    Py_UCS4 ucs;
+
+	    ch2 = *s++;
+	    size--;
+	    if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
+		ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
+		*p++ = '\\';
+		*p++ = 'U';
+		*p++ = hexdigit[(ucs >> 28) & 0xf];
+		*p++ = hexdigit[(ucs >> 24) & 0xf];
+		*p++ = hexdigit[(ucs >> 20) & 0xf];
+		*p++ = hexdigit[(ucs >> 16) & 0xf];
+		*p++ = hexdigit[(ucs >> 12) & 0xf];
+		*p++ = hexdigit[(ucs >> 8) & 0xf];
+		*p++ = hexdigit[(ucs >> 4) & 0xf];
+		*p++ = hexdigit[ucs & 0xf];
+		continue;
+	    }
+	    /* Fall through: isolated surrogates are copied as-is */
+	    s--;
+	    size++;
 	}
-	*p = '\0';
-	_PyString_Resize(&repr, p - q);
-	return repr;
+#endif
+	/* Map 16-bit characters to '\uxxxx' */
+	if (ch >= 256 || ch == '\\' || ch == '\n') {
+            *p++ = '\\';
+            *p++ = 'u';
+            *p++ = hexdigit[(ch >> 12) & 0xf];
+            *p++ = hexdigit[(ch >> 8) & 0xf];
+            *p++ = hexdigit[(ch >> 4) & 0xf];
+            *p++ = hexdigit[ch & 15];
+        }
+	/* Copy everything else as-is */
+	else
+            *p++ = (char) ch;
+    }
+    *p = '\0';
+    _PyString_Resize(&repr, p - q);
+    return repr;
 }
 
-
 static int
 save_unicode(Picklerobject *self, PyObject *args, int doput)
 {

Modified: python/branches/tlee-ast-optimize/Modules/dbmmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/dbmmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/dbmmodule.c	Wed Jan 14 13:24:17 2009
@@ -21,6 +21,9 @@
 #elif defined(HAVE_GDBM_NDBM_H)
 #include <gdbm/ndbm.h>
 static char *which_dbm = "GNU gdbm";
+#elif defined(HAVE_GDBM_DASH_NDBM_H)
+#include <gdbm-ndbm.h>
+static char *which_dbm = "GNU gdbm";
 #elif defined(HAVE_BERKDB_H)
 #include <db.h>
 static char *which_dbm = "Berkeley DB";

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	Wed Jan 14 13:24:17 2009
@@ -63,6 +63,55 @@
 /* Python string used to look for __del__ attribute. */
 static PyObject *delstr = NULL;
 
+/* This is the number of objects who survived the last full collection. It
+   approximates the number of long lived objects tracked by the GC.
+
+   (by "full collection", we mean a collection of the oldest generation).
+*/
+static Py_ssize_t long_lived_total = 0;
+
+/* This is the number of objects who survived all "non-full" collections,
+   and are awaiting to undergo a full collection for the first time.
+
+*/
+static Py_ssize_t long_lived_pending = 0;
+
+/*
+   NOTE: about the counting of long-lived objects.
+
+   To limit the cost of garbage collection, there are two strategies;
+     - make each collection faster, e.g. by scanning fewer objects
+     - do less collections
+   This heuristic is about the latter strategy.
+
+   In addition to the various configurable thresholds, we only trigger a
+   full collection if the ratio
+	long_lived_pending / long_lived_total
+   is above a given value (hardwired to 25%).
+
+   The reason is that, while "non-full" collections (i.e., collections of
+   the young and middle generations) will always examine roughly the same
+   number of objects -- determined by the aforementioned thresholds --,
+   the cost of a full collection is proportional to the total number of
+   long-lived objects, which is virtually unbounded.
+
+   Indeed, it has been remarked that doing a full collection every
+   <constant number> of object creations entails a dramatic performance
+   degradation in workloads which consist in creating and storing lots of
+   long-lived objects (e.g. building a large list of GC-tracked objects would
+   show quadratic performance, instead of linear as expected: see issue #4074).
+
+   Using the above ratio, instead, yields amortized linear performance in
+   the total number of objects (the effect of which can be summarized
+   thusly: "each full garbage collection is more and more costly as the
+   number of objects grows, but we do fewer and fewer of them").
+
+   This heuristic was suggested by Martin von Löwis on python-dev in
+   June 2008. His original analysis and proposal can be found at:
+	http://mail.python.org/pipermail/python-dev/2008-June/080579.html
+*/
+
+
 /* set for debugging information */
 #define DEBUG_STATS		(1<<0) /* print collection statistics */
 #define DEBUG_COLLECTABLE	(1<<1) /* print collectable objects */
@@ -740,6 +789,24 @@
 	(void)PyFloat_ClearFreeList();
 }
 
+static double
+get_time(void)
+{
+	double result = 0;
+	if (tmod != NULL) {
+		PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
+		if (f == NULL) {
+			PyErr_Clear();
+		}
+		else {
+			if (PyFloat_Check(f))
+				result = PyFloat_AsDouble(f);
+			Py_DECREF(f);
+		}
+	}
+	return result;
+}
+
 /* This is the main function.  Read this to understand how the
  * collection process works. */
 static Py_ssize_t
@@ -762,16 +829,7 @@
 	}
 
 	if (debug & DEBUG_STATS) {
-		if (tmod != NULL) {
-			PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
-			if (f == NULL) {
-				PyErr_Clear();
-			}
-			else {
-				t1 = PyFloat_AsDouble(f);
-				Py_DECREF(f);
-			}
-		}
+		t1 = get_time();
 		PySys_WriteStderr("gc: collecting generation %d...\n",
 				  generation);
 		PySys_WriteStderr("gc: objects in each generation:");
@@ -817,8 +875,16 @@
 	move_unreachable(young, &unreachable);
 
 	/* Move reachable objects to next generation. */
-	if (young != old)
+	if (young != old) {
+		if (generation == NUM_GENERATIONS - 2) {
+			long_lived_pending += gc_list_size(young);
+		}
 		gc_list_merge(young, old);
+	}
+	else {
+		long_lived_pending = 0;
+		long_lived_total = gc_list_size(young);
+	}
 
 	/* All objects in unreachable are trash, but objects reachable from
 	 * finalizers can't safely be deleted.  Python programmers should take
@@ -844,17 +910,6 @@
 		if (debug & DEBUG_COLLECTABLE) {
 			debug_cycle("collectable", FROM_GC(gc));
 		}
-		if (tmod != NULL && (debug & DEBUG_STATS)) {
-			PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
-			if (f == NULL) {
-				PyErr_Clear();
-			}
-			else {
-				t1 = PyFloat_AsDouble(f)-t1;
-				Py_DECREF(f);
-				PySys_WriteStderr("gc: %.4fs elapsed.\n", t1);
-			}
-		}
 	}
 
 	/* Clear weakrefs and invoke callbacks as necessary. */
@@ -876,14 +931,19 @@
 			debug_cycle("uncollectable", FROM_GC(gc));
 	}
 	if (debug & DEBUG_STATS) {
+		double t2 = get_time();
 		if (m == 0 && n == 0)
-			PySys_WriteStderr("gc: done.\n");
+			PySys_WriteStderr("gc: done");
 		else
 			PySys_WriteStderr(
 			    "gc: done, "
 			    "%" PY_FORMAT_SIZE_T "d unreachable, "
-			    "%" PY_FORMAT_SIZE_T "d uncollectable.\n",
+			    "%" PY_FORMAT_SIZE_T "d uncollectable",
 			    n+m, n);
+		if (t1 && t2) {
+			PySys_WriteStderr(", %.4fs elapsed", t2-t1);
+		}
+		PySys_WriteStderr(".\n");
 	}
 
 	/* Append instances in the uncollectable set to a Python
@@ -918,6 +978,13 @@
 	 * generations younger than it will be collected. */
 	for (i = NUM_GENERATIONS-1; i >= 0; i--) {
 		if (generations[i].count > generations[i].threshold) {
+			/* Avoid quadratic performance degradation in number
+			   of tracked objects. See comments at the beginning
+			   of this file, and issue #4074.
+			*/
+			if (i == NUM_GENERATIONS - 1
+			    && long_lived_pending < long_lived_total / 4)
+				continue;
 			n = collect(i);
 			break;
 		}

Modified: python/branches/tlee-ast-optimize/Modules/itertoolsmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/itertoolsmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/itertoolsmodule.c	Wed Jan 14 13:24:17 2009
@@ -886,7 +886,6 @@
 	long ok;
 	PyObject *(*iternext)(PyObject *);
 
-	assert(PyIter_Check(it));
 	iternext = *Py_TYPE(it)->tp_iternext;
 	for (;;) {
 		item = iternext(it);
@@ -1031,7 +1030,6 @@
 	if (lz->stop == 1)
 		return NULL;
 
-	assert(PyIter_Check(it));
 	item = (*Py_TYPE(it)->tp_iternext)(it);
 	if (item == NULL)
 		return NULL;
@@ -1218,7 +1216,6 @@
 	Py_ssize_t oldnext;
 	PyObject *(*iternext)(PyObject *);
 
-	assert(PyIter_Check(it));
 	iternext = *Py_TYPE(it)->tp_iternext;
 	while (lz->cnt < lz->next) {
 		item = iternext(it);
@@ -1229,7 +1226,6 @@
 	}
 	if (lz->stop != -1 && lz->cnt >= lz->stop)
 		return NULL;
-	assert(PyIter_Check(it));
 	item = iternext(it);
 	if (item == NULL)
 		return NULL;
@@ -1361,7 +1357,6 @@
 	PyObject *result;
 	PyObject *it = lz->it;
 
-	assert(PyIter_Check(it));
 	args = (*Py_TYPE(it)->tp_iternext)(it);
 	if (args == NULL)
 		return NULL;
@@ -2059,10 +2054,6 @@
 		PyErr_SetString(PyExc_ValueError, "r must be non-negative");
 		goto error;
 	}
-	if (r > n) {
-		PyErr_SetString(PyExc_ValueError, "r cannot be bigger than the iterable");
-		goto error;
-	}
 
 	indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
 	if (indices == NULL) {
@@ -2082,7 +2073,7 @@
 	co->indices = indices;
 	co->result = NULL;
 	co->r = r;
-	co->stopped = 0;
+	co->stopped = r > n ? 1 : 0;
 
 	return (PyObject *)co;
 
@@ -2318,10 +2309,6 @@
 		PyErr_SetString(PyExc_ValueError, "r must be non-negative");
 		goto error;
 	}
-	if (r > n) {
-		PyErr_SetString(PyExc_ValueError, "r cannot be bigger than the iterable");
-		goto error;
-	}
 
 	indices = PyMem_Malloc(n * sizeof(Py_ssize_t));
 	cycles = PyMem_Malloc(r * sizeof(Py_ssize_t));
@@ -2345,7 +2332,7 @@
 	po->cycles = cycles;
 	po->result = NULL;
 	po->r = r;
-	po->stopped = 0;
+	po->stopped = r > n ? 1 : 0;
 
 	return (PyObject *)po;
 
@@ -2585,7 +2572,6 @@
 	long ok;
 	PyObject *(*iternext)(PyObject *);
 
-	assert(PyIter_Check(it));
 	iternext = *Py_TYPE(it)->tp_iternext;
 	for (;;) {
 		item = iternext(it);
@@ -2729,7 +2715,6 @@
 	long ok;
 	PyObject *(*iternext)(PyObject *);
 
-	assert(PyIter_Check(it));
 	iternext = *Py_TYPE(it)->tp_iternext;
 	for (;;) {
 		item = iternext(it);
@@ -3067,7 +3052,6 @@
 		Py_INCREF(result);
 		for (i=0 ; i < tuplesize ; i++) {
 			it = PyTuple_GET_ITEM(lz->ittuple, i);
-			assert(PyIter_Check(it));
 			item = (*Py_TYPE(it)->tp_iternext)(it);
 			if (item == NULL) {
 				Py_DECREF(result);
@@ -3083,7 +3067,6 @@
 			return NULL;
 		for (i=0 ; i < tuplesize ; i++) {
 			it = PyTuple_GET_ITEM(lz->ittuple, i);
-			assert(PyIter_Check(it));
 			item = (*Py_TYPE(it)->tp_iternext)(it);
 			if (item == NULL) {
 				Py_DECREF(result);
@@ -3419,7 +3402,6 @@
                                 Py_INCREF(lz->fillvalue);
                                 item = lz->fillvalue;
                         } else {
-                                assert(PyIter_Check(it));
                                 item = (*Py_TYPE(it)->tp_iternext)(it);
                                 if (item == NULL) {
                                         lz->numactive -= 1;      
@@ -3448,7 +3430,6 @@
                                 Py_INCREF(lz->fillvalue);
                                 item = lz->fillvalue;
                         } else {
-                                assert(PyIter_Check(it));
                                 item = (*Py_TYPE(it)->tp_iternext)(it);
                                 if (item == NULL) {
                                         lz->numactive -= 1;      

Modified: python/branches/tlee-ast-optimize/Modules/main.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/main.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/main.c	Wed Jan 14 13:24:17 2009
@@ -86,7 +86,7 @@
 -x     : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
 ";
 static char *usage_4 = "\
--3     : warn about Python 3.x incompatibilities\n\
+-3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix\n\
 file   : program read from script file\n\
 -      : program read from stdin (default; interactive mode if a tty)\n\
 arg ...: arguments passed to program in sys.argv[1:]\n\n\

Modified: python/branches/tlee-ast-optimize/Modules/mathmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/mathmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/mathmodule.c	Wed Jan 14 13:24:17 2009
@@ -137,6 +137,58 @@
 }
 
 /*
+    Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
+    log(-ve), log(NaN).  Here are wrappers for log and log10 that deal with
+    special values directly, passing positive non-special values through to
+    the system log/log10.
+ */
+
+static double
+m_log(double x)
+{
+	if (Py_IS_FINITE(x)) {
+		if (x > 0.0)
+			return log(x);
+		errno = EDOM;
+		if (x == 0.0)
+			return -Py_HUGE_VAL; /* log(0) = -inf */
+		else
+			return Py_NAN; /* log(-ve) = nan */
+	}
+	else if (Py_IS_NAN(x))
+		return x; /* log(nan) = nan */
+	else if (x > 0.0)
+		return x; /* log(inf) = inf */
+	else {
+		errno = EDOM;
+		return Py_NAN; /* log(-inf) = nan */
+	}
+}
+
+static double
+m_log10(double x)
+{
+	if (Py_IS_FINITE(x)) {
+		if (x > 0.0)
+			return log10(x);
+		errno = EDOM;
+		if (x == 0.0)
+			return -Py_HUGE_VAL; /* log10(0) = -inf */
+		else
+			return Py_NAN; /* log10(-ve) = nan */
+	}
+	else if (Py_IS_NAN(x))
+		return x; /* log10(nan) = nan */
+	else if (x > 0.0)
+		return x; /* log10(inf) = inf */
+	else {
+		errno = EDOM;
+		return Py_NAN; /* log10(-inf) = nan */
+	}
+}
+
+
+/*
    math_1 is used to wrap a libm function f that takes a double
    arguments and returns a double.
 
@@ -578,7 +630,10 @@
 	return NULL;
 }
 
-PyDoc_STRVAR(math_factorial_doc, "Return n!");
+PyDoc_STRVAR(math_factorial_doc,
+"factorial(x) -> Integral\n"
+"\n"
+"Find x!. Raise a ValueError if x is negative or non-integral.");
 
 static PyObject *
 math_trunc(PyObject *self, PyObject *number)
@@ -712,7 +767,7 @@
 "modf(x)\n"
 "\n"
 "Return the fractional and integer parts of x.  Both results carry the sign\n"
-"of x.  The integer part is returned as a real.");
+"of x and are floats.");
 
 /* A decent logarithm is easy to compute even for huge longs, but libm can't
    do that by itself -- loghelper can.  func is log or log10, and name is
@@ -758,11 +813,11 @@
 	if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
 		return NULL;
 
-	num = loghelper(arg, log, "log");
+	num = loghelper(arg, m_log, "log");
 	if (num == NULL || base == NULL)
 		return num;
 
-	den = loghelper(base, log, "log");
+	den = loghelper(base, m_log, "log");
 	if (den == NULL) {
 		Py_DECREF(num);
 		return NULL;
@@ -781,7 +836,7 @@
 static PyObject *
 math_log10(PyObject *self, PyObject *arg)
 {
-	return loghelper(arg, log10, "log10");
+	return loghelper(arg, m_log10, "log10");
 }
 
 PyDoc_STRVAR(math_log10_doc,

Modified: python/branches/tlee-ast-optimize/Modules/parsermodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/parsermodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/parsermodule.c	Wed Jan 14 13:24:17 2009
@@ -2057,6 +2057,7 @@
 
 /*  try_stmt:
  *      'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
+                                                   ['finally' ':' suite]
  *    | 'try' ':' suite 'finally' ':' suite
  *
  */
@@ -2082,35 +2083,34 @@
         PyErr_Format(parser_error,
                      "Illegal number of children for try/%s node.", name);
     }
-    /*  Skip past except_clause sections:  */
+    /* Handle try/finally statement */
+    if (res && (TYPE(CHILD(tree, pos)) == NAME) &&
+        (strcmp(STR(CHILD(tree, pos)), "finally") == 0)) {
+        res = (validate_numnodes(tree, 6, "try/finally")
+               && validate_colon(CHILD(tree, 4))
+               && validate_suite(CHILD(tree, 5)));
+        return (res);
+    }
+    /* try/except statement: skip past except_clause sections */
     while (res && (TYPE(CHILD(tree, pos)) == except_clause)) {
         res = (validate_except_clause(CHILD(tree, pos))
                && validate_colon(CHILD(tree, pos + 1))
                && validate_suite(CHILD(tree, pos + 2)));
         pos += 3;
     }
-    if (res && (pos < nch)) {
-        res = validate_ntype(CHILD(tree, pos), NAME);
-        if (res && (strcmp(STR(CHILD(tree, pos)), "finally") == 0))
-            res = (validate_numnodes(tree, 6, "try/finally")
-                   && validate_colon(CHILD(tree, 4))
-                   && validate_suite(CHILD(tree, 5)));
-        else if (res) {
-            if (nch == (pos + 3)) {
-                res = ((strcmp(STR(CHILD(tree, pos)), "except") == 0)
-                       || (strcmp(STR(CHILD(tree, pos)), "else") == 0));
-                if (!res)
-                    err_string("illegal trailing triple in try statement");
-            }
-            else if (nch == (pos + 6)) {
-                res = (validate_name(CHILD(tree, pos), "except")
-                       && validate_colon(CHILD(tree, pos + 1))
-                       && validate_suite(CHILD(tree, pos + 2))
-                       && validate_name(CHILD(tree, pos + 3), "else"));
-            }
-            else
-                res = validate_numnodes(tree, pos + 3, "try/except");
-        }
+    /* skip else clause */
+    if (res && (TYPE(CHILD(tree, pos)) == NAME) &&
+        (strcmp(STR(CHILD(tree, pos)), "else") == 0)) {
+        res = (validate_colon(CHILD(tree, pos + 1))
+               && validate_suite(CHILD(tree, pos + 2)));
+        pos += 3;
+    }
+    if (res && pos < nch) {
+        /* last clause must be a finally */
+        res = (validate_name(CHILD(tree, pos), "finally")
+               && validate_numnodes(tree, pos + 3, "try/except/finally")
+               && validate_colon(CHILD(tree, pos + 1))
+               && validate_suite(CHILD(tree, pos + 2)));
     }
     return (res);
 }

Modified: python/branches/tlee-ast-optimize/Modules/posixmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/posixmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/posixmodule.c	Wed Jan 14 13:24:17 2009
@@ -5957,10 +5957,6 @@
 
 
 #ifdef HAVE_TIMES
-#ifndef HZ
-#define HZ 60 /* Universal constant :-) */
-#endif /* HZ */
-
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
 static long
 system_uptime(void)
@@ -5986,6 +5982,8 @@
 			     (double)system_uptime() / 1000);
 }
 #else /* not OS2 */
+#define NEED_TICKS_PER_SECOND
+static long ticks_per_second = -1;
 static PyObject *
 posix_times(PyObject *self, PyObject *noargs)
 {
@@ -5996,11 +5994,11 @@
 	if (c == (clock_t) -1)
 		return posix_error();
 	return Py_BuildValue("ddddd",
-			     (double)t.tms_utime / HZ,
-			     (double)t.tms_stime / HZ,
-			     (double)t.tms_cutime / HZ,
-			     (double)t.tms_cstime / HZ,
-			     (double)c / HZ);
+			     (double)t.tms_utime / ticks_per_second,
+			     (double)t.tms_stime / ticks_per_second,
+			     (double)t.tms_cutime / ticks_per_second,
+			     (double)t.tms_cstime / ticks_per_second,
+			     (double)c / ticks_per_second);
 }
 #endif /* not OS2 */
 #endif /* HAVE_TIMES */
@@ -8962,6 +8960,15 @@
 
 		statvfs_result_desc.name = MODNAME ".statvfs_result";
 		PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc);
+#ifdef NEED_TICKS_PER_SECOND
+#  if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
+		ticks_per_second = sysconf(_SC_CLK_TCK);
+#  elif defined(HZ)
+		ticks_per_second = HZ;
+#  else
+		ticks_per_second = 60; /* magic fallback value; may be bogus */
+#  endif
+#endif
 	}
 	Py_INCREF((PyObject*) &StatResultType);
 	PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);

Modified: python/branches/tlee-ast-optimize/Modules/socketmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/socketmodule.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/socketmodule.c	Wed Jan 14 13:24:17 2009
@@ -3334,7 +3334,11 @@
 #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
 	struct hostent_data data;
 #else
-	char buf[16384];
+	/* glibcs up to 2.10 assume that the buf argument to
+	   gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
+	   does not ensure. The attribute below instructs the compiler
+	   to maintain this alignment. */
+	char buf[16384] Py_ALIGNED(8);
 	int buf_len = (sizeof buf) - 1;
 	int errnop;
 #endif

Modified: python/branches/tlee-ast-optimize/Modules/zipimport.c
==============================================================================
--- python/branches/tlee-ast-optimize/Modules/zipimport.c	(original)
+++ python/branches/tlee-ast-optimize/Modules/zipimport.c	Wed Jan 14 13:24:17 2009
@@ -369,6 +369,29 @@
 	return NULL;
 }
 
+/* Return a string matching __file__ for the named module */
+static PyObject *
+zipimporter_get_filename(PyObject *obj, PyObject *args)
+{
+    ZipImporter *self = (ZipImporter *)obj;
+    PyObject *code;
+    char *fullname, *modpath;
+    int ispackage;
+
+    if (!PyArg_ParseTuple(args, "s:zipimporter._get_filename",
+                         &fullname))
+        return NULL;
+
+    /* Deciding the filename requires working out where the code
+       would come from if the module was actually loaded */
+    code = get_module_code(self, fullname, &ispackage, &modpath);
+    if (code == NULL)
+        return NULL;
+    Py_DECREF(code); /* Only need the path info */
+
+    return PyString_FromString(modpath);
+}
+
 /* Return a bool signifying whether the module is a package or not. */
 static PyObject *
 zipimporter_is_package(PyObject *obj, PyObject *args)
@@ -528,6 +551,12 @@
 is the module couldn't be found, return None if the archive does\n\
 contain the module, but has no source for it.");
 
+
+PyDoc_STRVAR(doc_get_filename,
+"_get_filename(fullname) -> filename string.\n\
+\n\
+Return the filename for the specified module.");
+
 static PyMethodDef zipimporter_methods[] = {
 	{"find_module", zipimporter_find_module, METH_VARARGS,
 	 doc_find_module},
@@ -539,6 +568,8 @@
 	 doc_get_code},
 	{"get_source", zipimporter_get_source, METH_VARARGS,
 	 doc_get_source},
+	{"_get_filename", zipimporter_get_filename, METH_VARARGS,
+	 doc_get_filename},
 	{"is_package", zipimporter_is_package, METH_VARARGS,
 	 doc_is_package},
 	{NULL,		NULL}	/* sentinel */

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	Wed Jan 14 13:24:17 2009
@@ -3067,7 +3067,6 @@
 PyIter_Next(PyObject *iter)
 {
 	PyObject *result;
-	assert(PyIter_Check(iter));
 	result = (*iter->ob_type->tp_iternext)(iter);
 	if (result == NULL &&
 	    PyErr_Occurred() &&

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	Wed Jan 14 13:24:17 2009
@@ -154,6 +154,17 @@
     return view->len;
 }
 
+static int
+_canresize(PyByteArrayObject *self)
+{
+    if (self->ob_exports > 0) {
+        PyErr_SetString(PyExc_BufferError,
+                "Existing exports of data: object cannot be re-sized");
+        return 0;
+    }
+    return 1;
+}
+
 /* Direct API functions */
 
 PyObject *
@@ -229,6 +240,13 @@
     assert(PyByteArray_Check(self));
     assert(size >= 0);
 
+    if (size == Py_SIZE(self)) {
+        return 0;
+    }
+    if (!_canresize((PyByteArrayObject *)self)) {
+        return -1;
+    }
+
     if (size < alloc / 2) {
         /* Major downsize; resize down to exact size */
         alloc = size + 1;
@@ -248,16 +266,6 @@
         alloc = size + 1;
     }
 
-    if (((PyByteArrayObject *)self)->ob_exports > 0) {
-            /*
-            fprintf(stderr, "%d: %s", ((PyByteArrayObject *)self)->ob_exports,
-                    ((PyByteArrayObject *)self)->ob_bytes);
-            */
-            PyErr_SetString(PyExc_BufferError,
-                    "Existing exports of data: object cannot be re-sized");
-            return -1;
-    }
-
     sval = PyMem_Realloc(((PyByteArrayObject *)self)->ob_bytes, alloc);
     if (sval == NULL) {
         PyErr_NoMemory();
@@ -522,6 +530,10 @@
 
     if (avail != needed) {
         if (avail > needed) {
+            if (!_canresize(self)) {
+                res = -1;
+                goto finish;
+            }
             /*
               0   lo               hi               old_size
               |   |<----avail----->|<-----tomove------>|
@@ -654,6 +666,8 @@
         stop = start;
     if (step == 1) {
         if (slicelen != needed) {
+            if (!_canresize(self))
+                return -1;
             if (slicelen > needed) {
                 /*
                   0   start           stop              old_size
@@ -689,6 +703,8 @@
             /* Delete slice */
             Py_ssize_t cur, i;
 
+            if (!_canresize(self))
+                return -1;
             if (step < 0) {
                 stop = start + 1;
                 start = stop + step * (slicelen - 1) - 1;
@@ -1427,28 +1443,32 @@
     PyObject *input_obj = (PyObject*)self;
     const char *output_start;
     Py_ssize_t inlen;
-    PyObject *result;
+    PyObject *result = NULL;
     int trans_table[256];
-    PyObject *tableobj, *delobj = NULL;
+    PyObject *tableobj = NULL, *delobj = NULL;
     Py_buffer vtable, vdel;
 
     if (!PyArg_UnpackTuple(args, "translate", 1, 2,
                            &tableobj, &delobj))
           return NULL;
 
-    if (_getbuffer(tableobj, &vtable) < 0)
+    if (tableobj == Py_None) {
+        table = NULL;
+        tableobj = NULL;
+    } else if (_getbuffer(tableobj, &vtable) < 0) {
         return NULL;
-
-    if (vtable.len != 256) {
-        PyErr_SetString(PyExc_ValueError,
-                        "translation table must be 256 characters long");
-        result = NULL;
-        goto done;
+    } else {
+        if (vtable.len != 256) {
+            PyErr_SetString(PyExc_ValueError,
+                            "translation table must be 256 characters long");
+            goto done;
+        }
+        table = (const char*)vtable.buf;
     }
 
     if (delobj != NULL) {
         if (_getbuffer(delobj, &vdel) < 0) {
-            result = NULL;
+            delobj = NULL;  /* don't try to release vdel buffer on exit */
             goto done;
         }
     }
@@ -1457,7 +1477,6 @@
         vdel.len = 0;
     }
 
-    table = (const char *)vtable.buf;
     inlen = PyByteArray_GET_SIZE(input_obj);
     result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
     if (result == NULL)
@@ -1465,7 +1484,7 @@
     output_start = output = PyByteArray_AsString(result);
     input = PyByteArray_AS_STRING(input_obj);
 
-    if (vdel.len == 0) {
+    if (vdel.len == 0 && table != NULL) {
         /* If no deletions are required, use faster code */
         for (i = inlen; --i >= 0; ) {
             c = Py_CHARMASK(*input++);
@@ -1474,8 +1493,13 @@
         goto done;
     }
 
-    for (i = 0; i < 256; i++)
-        trans_table[i] = Py_CHARMASK(table[i]);
+    if (table == NULL) {
+        for (i = 0; i < 256; i++)
+            trans_table[i] = Py_CHARMASK(i);
+    } else {
+        for (i = 0; i < 256; i++)
+            trans_table[i] = Py_CHARMASK(table[i]);
+    }
 
     for (i = 0; i < vdel.len; i++)
         trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
@@ -1491,7 +1515,8 @@
         PyByteArray_Resize(result, output - output_start);
 
 done:
-    PyBuffer_Release(&vtable);
+    if (tableobj != NULL)
+        PyBuffer_Release(&vtable);
     if (delobj != NULL)
         PyBuffer_Release(&vdel);
     return result;
@@ -2730,6 +2755,8 @@
         PyErr_SetString(PyExc_IndexError, "pop index out of range");
         return NULL;
     }
+    if (!_canresize(self))
+        return NULL;
 
     value = self->ob_bytes[where];
     memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
@@ -2760,6 +2787,8 @@
         PyErr_SetString(PyExc_ValueError, "value not found in bytes");
         return NULL;
     }
+    if (!_canresize(self))
+        return NULL;
 
     memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
     if (PyByteArray_Resize((PyObject *)self, n - 1) < 0)

Modified: python/branches/tlee-ast-optimize/Objects/dictobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/dictobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/dictobject.c	Wed Jan 14 13:24:17 2009
@@ -2331,7 +2331,7 @@
 dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
 {
 	dictiterobject *di;
-	di = PyObject_New(dictiterobject, itertype);
+	di = PyObject_GC_New(dictiterobject, itertype);
 	if (di == NULL)
 		return NULL;
 	Py_INCREF(dict);
@@ -2348,6 +2348,7 @@
 	}
 	else
 		di->di_result = NULL;
+	_PyObject_GC_TRACK(di);
 	return (PyObject *)di;
 }
 
@@ -2356,7 +2357,15 @@
 {
 	Py_XDECREF(di->di_dict);
 	Py_XDECREF(di->di_result);
-	PyObject_Del(di);
+	PyObject_GC_Del(di);
+}
+
+static int
+dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
+{
+	Py_VISIT(di->di_dict);
+	Py_VISIT(di->di_result);
+	return 0;
 }
 
 static PyObject *
@@ -2435,9 +2444,9 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  	0,					/* tp_doc */
- 	0,					/* tp_traverse */
+ 	(traverseproc)dictiter_traverse,	/* tp_traverse */
  	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
@@ -2507,9 +2516,9 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  	0,					/* tp_doc */
- 	0,					/* tp_traverse */
+ 	(traverseproc)dictiter_traverse,	/* tp_traverse */
  	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
@@ -2593,9 +2602,9 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  	0,					/* tp_doc */
- 	0,					/* tp_traverse */
+ 	(traverseproc)dictiter_traverse,	/* tp_traverse */
  	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */

Modified: python/branches/tlee-ast-optimize/Objects/fileobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/fileobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/fileobject.c	Wed Jan 14 13:24:17 2009
@@ -132,8 +132,8 @@
 	if (fstat(fileno(f->f_fp), &buf) == 0 &&
 	    S_ISDIR(buf.st_mode)) {
 		char *msg = strerror(EISDIR);
-		PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(is)",
-						      EISDIR, msg);
+		PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
+						      EISDIR, msg, f->f_name);
 		PyErr_SetObject(PyExc_IOError, exc);
 		Py_XDECREF(exc);
 		return NULL;

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	Wed Jan 14 13:24:17 2009
@@ -20,12 +20,38 @@
 	{"f_builtins",	T_OBJECT,	OFF(f_builtins),RO},
 	{"f_globals",	T_OBJECT,	OFF(f_globals),	RO},
 	{"f_lasti",	T_INT,		OFF(f_lasti),	RO},
-	{"f_exc_type",	T_OBJECT,	OFF(f_exc_type)},
-	{"f_exc_value",	T_OBJECT,	OFF(f_exc_value)},
-	{"f_exc_traceback", T_OBJECT,	OFF(f_exc_traceback)},
 	{NULL}	/* Sentinel */
 };
 
+#define WARN_GET_SET(NAME) \
+static PyObject * frame_get_ ## NAME(PyFrameObject *f) { \
+	if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
+		return NULL; \
+	if (f->NAME) { \
+		Py_INCREF(f->NAME); \
+		return f->NAME; \
+	} \
+        Py_RETURN_NONE;	\
+} \
+static int frame_set_ ## NAME(PyFrameObject *f, PyObject *new) { \
+	if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
+		return -1; \
+	if (f->NAME) { \
+		Py_CLEAR(f->NAME); \
+	} \
+        if (new == Py_None) \
+            new = NULL; \
+	Py_XINCREF(new); \
+	f->NAME = new; \
+	return 0; \
+}
+
+
+WARN_GET_SET(f_exc_traceback)
+WARN_GET_SET(f_exc_type)
+WARN_GET_SET(f_exc_value)
+
+
 static PyObject *
 frame_getlocals(PyFrameObject *f, void *closure)
 {
@@ -353,6 +379,12 @@
 			(setter)frame_setlineno, NULL},
 	{"f_trace",	(getter)frame_gettrace, (setter)frame_settrace, NULL},
 	{"f_restricted",(getter)frame_getrestricted,NULL, NULL},
+	{"f_exc_traceback", (getter)frame_get_f_exc_traceback,
+	                (setter)frame_set_f_exc_traceback, NULL},
+        {"f_exc_type",  (getter)frame_get_f_exc_type,
+                        (setter)frame_set_f_exc_type, NULL},
+        {"f_exc_value", (getter)frame_get_f_exc_value,
+                        (setter)frame_set_f_exc_value, NULL},
 	{0}
 };
 

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	Wed Jan 14 13:24:17 2009
@@ -78,7 +78,8 @@
 static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
 #endif
 #ifdef COUNT_ALLOCS
-int quick_int_allocs, quick_neg_int_allocs;
+Py_ssize_t quick_int_allocs;
+Py_ssize_t quick_neg_int_allocs;
 #endif
 
 PyObject *
@@ -1138,6 +1139,40 @@
 	return NULL;
 }
 
+static const unsigned char BitLengthTable[32] = {
+	0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
+	5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
+};
+
+static PyObject *
+int_bit_length(PyIntObject *v)
+{
+	unsigned long n;
+	long r = 0;
+
+	if (v->ob_ival < 0)
+		/* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
+		n = 0U-(unsigned long)v->ob_ival;
+	else
+		n = (unsigned long)v->ob_ival;
+
+	while (n >= 32) {
+		r += 6;
+		n >>= 6;
+	}
+	r += (long)(BitLengthTable[n]);
+	return PyInt_FromLong(r);
+}
+
+PyDoc_STRVAR(int_bit_length_doc,
+"int.bit_length() -> int\n\
+\n\
+Number of bits necessary to represent self in binary.\n\
+>>> bin(37)\n\
+'0b100101'\n\
+>>> (37).bit_length()\n\
+6");
+
 #if 0
 static PyObject *
 int_is_finite(PyObject *v)
@@ -1149,6 +1184,8 @@
 static PyMethodDef int_methods[] = {
 	{"conjugate",	(PyCFunction)int_int,	METH_NOARGS,
 	 "Returns self, the complex conjugate of any int."},
+	{"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
+	 int_bit_length_doc},
 #if 0
 	{"is_finite",	(PyCFunction)int_is_finite,	METH_NOARGS,
 	 "Returns always True."},

Modified: python/branches/tlee-ast-optimize/Objects/listobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/listobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/listobject.c	Wed Jan 14 13:24:17 2009
@@ -2911,11 +2911,11 @@
 static void listreviter_dealloc(listreviterobject *);
 static int listreviter_traverse(listreviterobject *, visitproc, void *);
 static PyObject *listreviter_next(listreviterobject *);
-static Py_ssize_t listreviter_len(listreviterobject *);
+static PyObject *listreviter_len(listreviterobject *);
 
-static PySequenceMethods listreviter_as_sequence = {
-	(lenfunc)listreviter_len,	/* sq_length */
-	0,				/* sq_concat */
+static PyMethodDef listreviter_methods[] = {
+	{"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
+ 	{NULL,		NULL}		/* sentinel */
 };
 
 PyTypeObject PyListRevIter_Type = {
@@ -2931,7 +2931,7 @@
 	0,					/* tp_compare */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
-	&listreviter_as_sequence,		/* tp_as_sequence */
+	0,					/* tp_as_sequence */
 	0,					/* tp_as_mapping */
 	0,					/* tp_hash */
 	0,					/* tp_call */
@@ -2947,6 +2947,7 @@
 	0,					/* tp_weaklistoffset */
 	PyObject_SelfIter,			/* tp_iter */
 	(iternextfunc)listreviter_next,		/* tp_iternext */
+	listreviter_methods,		/* tp_methods */
 	0,
 };
 
@@ -3002,11 +3003,11 @@
 	return NULL;
 }
 
-static Py_ssize_t
+static PyObject *
 listreviter_len(listreviterobject *it)
 {
 	Py_ssize_t len = it->it_index + 1;
 	if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
-		return 0;
-	return len;
+		len = 0;
+	return PyLong_FromSsize_t(len);
 }

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	Wed Jan 14 13:24:17 2009
@@ -3451,6 +3451,75 @@
 	return PyInt_FromSsize_t(res);
 }
 
+static const unsigned char BitLengthTable[32] = {
+	0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
+	5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
+};
+
+static PyObject *
+long_bit_length(PyLongObject *v)
+{
+	PyLongObject *result, *x, *y;
+	Py_ssize_t ndigits, msd_bits = 0;
+	digit msd;
+
+	assert(v != NULL);
+	assert(PyLong_Check(v));
+
+	ndigits = ABS(Py_SIZE(v));
+	if (ndigits == 0)
+		return PyInt_FromLong(0);
+
+	msd = v->ob_digit[ndigits-1];
+	while (msd >= 32) {
+		msd_bits += 6;
+		msd >>= 6;
+	}
+	msd_bits += (long)(BitLengthTable[msd]);
+
+	if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
+		return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
+
+	/* expression above may overflow; use Python integers instead */
+	result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
+	if (result == NULL)
+		return NULL;
+	x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
+	if (x == NULL)
+		goto error;
+	y = (PyLongObject *)long_mul(result, x);
+	Py_DECREF(x);
+	if (y == NULL)
+		goto error;
+	Py_DECREF(result);
+	result = y;
+
+	x = (PyLongObject *)PyLong_FromLong(msd_bits);
+	if (x == NULL)
+		goto error;
+	y = (PyLongObject *)long_add(result, x);
+	Py_DECREF(x);
+	if (y == NULL)
+		goto error;
+	Py_DECREF(result);
+	result = y;
+
+	return (PyObject *)result;
+
+error:
+	Py_DECREF(result);
+	return NULL;
+}
+
+PyDoc_STRVAR(long_bit_length_doc,
+"long.bit_length() -> int or long\n\
+\n\
+Number of bits necessary to represent self in binary.\n\
+>>> bin(37L)\n\
+'0b100101'\n\
+>>> (37L).bit_length()\n\
+6");
+
 #if 0
 static PyObject *
 long_is_finite(PyObject *v)
@@ -3462,6 +3531,8 @@
 static PyMethodDef long_methods[] = {
 	{"conjugate",	(PyCFunction)long_long,	METH_NOARGS,
 	 "Returns self, the complex conjugate of any long."},
+	{"bit_length",	(PyCFunction)long_bit_length, METH_NOARGS,
+	 long_bit_length_doc},
 #if 0
 	{"is_finite",	(PyCFunction)long_is_finite,	METH_NOARGS,
 	 "Returns always True."},

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	Wed Jan 14 13:24:17 2009
@@ -81,24 +81,29 @@
    garbage itself. If unlist_types_without_objects
    is set, they will be removed from the type_list
    once the last object is deallocated. */
-int unlist_types_without_objects;
-extern int tuple_zero_allocs, fast_tuple_allocs;
-extern int quick_int_allocs, quick_neg_int_allocs;
-extern int null_strings, one_strings;
+static int unlist_types_without_objects;
+extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
+extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
+extern Py_ssize_t null_strings, one_strings;
 void
 dump_counts(FILE* f)
 {
 	PyTypeObject *tp;
 
 	for (tp = type_list; tp; tp = tp->tp_next)
-		fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
+		fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
+			"freed: %" PY_FORMAT_SIZE_T "d, "
+			"max in use: %" PY_FORMAT_SIZE_T "d\n",
 			tp->tp_name, tp->tp_allocs, tp->tp_frees,
 			tp->tp_maxalloc);
-	fprintf(f, "fast tuple allocs: %d, empty: %d\n",
+	fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
+		"empty: %" PY_FORMAT_SIZE_T "d\n",
 		fast_tuple_allocs, tuple_zero_allocs);
-	fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
+	fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
+		"neg: %" PY_FORMAT_SIZE_T "d\n",
 		quick_int_allocs, quick_neg_int_allocs);
-	fprintf(f, "null strings: %d, 1-strings: %d\n",
+	fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
+		"1-strings: %" PY_FORMAT_SIZE_T "d\n",
 		null_strings, one_strings);
 }
 
@@ -331,8 +336,11 @@
 	if (op == NULL)
 		fprintf(stderr, "NULL\n");
 	else {
+		PyGILState_STATE gil;
 		fprintf(stderr, "object  : ");
+		gil = PyGILState_Ensure();
 		(void)PyObject_Print(op, stderr, 0);
+		PyGILState_Release(gil);
 		/* XXX(twouters) cast refcount to long until %zd is
 		   universally available */
 		fprintf(stderr, "\n"
@@ -1097,6 +1105,17 @@
 	PyTypeObject *tp = v->ob_type;
 	if (tp->tp_hash != NULL)
 		return (*tp->tp_hash)(v);
+	/* To keep to the general practice that inheriting
+	 * solely from object in C code should work without
+	 * an explicit call to PyType_Ready, we implicitly call
+	 * PyType_Ready here and then check the tp_hash slot again
+	 */
+	if (tp->tp_dict == NULL) {
+		if (PyType_Ready(tp) < 0)
+			return -1;
+		if (tp->tp_hash != NULL)
+			return (*tp->tp_hash)(v);
+	}
 	if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
 		return _Py_HashPointer(v); /* Use address as hash value */
 	}
@@ -1286,6 +1305,20 @@
 	return obj;
 }
 
+/* Helper used when the __next__ method is removed from a type:
+   tp_iternext is never NULL and can be safely called without checking
+   on every iteration.
+ */
+
+PyObject *
+_PyObject_NextNotImplemented(PyObject *self)
+{
+	PyErr_Format(PyExc_TypeError,
+		     "'%.200s' object is not iterable",
+		     Py_TYPE(self)->tp_name);
+	return NULL;
+}
+
 /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
 
 PyObject *

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	Wed Jan 14 13:24:17 2009
@@ -810,7 +810,14 @@
 setiter_dealloc(setiterobject *si)
 {
 	Py_XDECREF(si->si_set);
-	PyObject_Del(si);
+	PyObject_GC_Del(si);
+}
+
+static int
+setiter_traverse(setiterobject *si, visitproc visit, void *arg)
+{
+	Py_VISIT(si->si_set);
+	return 0;
 }
 
 static PyObject *
@@ -888,9 +895,9 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  	0,					/* tp_doc */
- 	0,					/* tp_traverse */
+ 	(traverseproc)setiter_traverse,		/* tp_traverse */
  	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
@@ -903,7 +910,7 @@
 static PyObject *
 set_iter(PySetObject *so)
 {
-	setiterobject *si = PyObject_New(setiterobject, &PySetIter_Type);
+	setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
 	if (si == NULL)
 		return NULL;
 	Py_INCREF(so);
@@ -911,6 +918,7 @@
 	si->si_used = so->used;
 	si->si_pos = 0;
 	si->len = so->used;
+	_PyObject_GC_TRACK(si);
 	return (PyObject *)si;
 }
 

Modified: python/branches/tlee-ast-optimize/Objects/stringlib/transmogrify.h
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/stringlib/transmogrify.h	(original)
+++ python/branches/tlee-ast-optimize/Objects/stringlib/transmogrify.h	Wed Jan 14 13:24:17 2009
@@ -22,76 +22,69 @@
 {
     const char *e, *p;
     char *q;
-    Py_ssize_t i, j, old_j;
+    size_t i, j;
     PyObject *u;
     int tabsize = 8;
-
+    
     if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
-	return NULL;
-
+        return NULL;
+    
     /* First pass: determine size of output string */
-    i = j = old_j = 0;
+    i = j = 0;
     e = STRINGLIB_STR(self) + STRINGLIB_LEN(self);
     for (p = STRINGLIB_STR(self); p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0) {
-		j += tabsize - (j % tabsize);
-                /* XXX: this depends on a signed integer overflow to < 0 */
-                /* C compilers, including gcc, do -NOT- guarantee this. */
-		if (old_j > j) {
-		    PyErr_SetString(PyExc_OverflowError,
-				    "result is too long");
-		    return NULL;
-		}
-		old_j = j;
+            if (tabsize > 0) {
+                j += tabsize - (j % tabsize);
+                if (j > PY_SSIZE_T_MAX) {
+                    PyErr_SetString(PyExc_OverflowError,
+                                    "result is too long");
+                    return NULL;
+                }
             }
-	}
+        }
         else {
             j++;
             if (*p == '\n' || *p == '\r') {
                 i += j;
-                old_j = j = 0;
-                /* XXX: this depends on a signed integer overflow to < 0 */
-                /* C compilers, including gcc, do -NOT- guarantee this. */
-                if (i < 0) {
+                j = 0;
+                if (i > PY_SSIZE_T_MAX) {
                     PyErr_SetString(PyExc_OverflowError,
                                     "result is too long");
                     return NULL;
                 }
             }
         }
-
-    if ((i + j) < 0) {
-        /* XXX: this depends on a signed integer overflow to < 0 */
-        /* C compilers, including gcc, do -NOT- guarantee this. */
+    
+    if ((i + j) > PY_SSIZE_T_MAX) {
         PyErr_SetString(PyExc_OverflowError, "result is too long");
         return NULL;
     }
-
+    
     /* Second pass: create output string and fill it */
     u = STRINGLIB_NEW(NULL, i + j);
     if (!u)
         return NULL;
-
+    
     j = 0;
     q = STRINGLIB_STR(u);
-
+    
     for (p = STRINGLIB_STR(self); p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0) {
-		i = tabsize - (j % tabsize);
-		j += i;
-		while (i--)
-		    *q++ = ' ';
-	    }
-	}
-	else {
+            if (tabsize > 0) {
+                i = tabsize - (j % tabsize);
+                j += i;
+                while (i--)
+                    *q++ = ' ';
+            }
+        }
+        else {
             j++;
-	    *q++ = *p;
+            *q++ = *p;
             if (*p == '\n' || *p == '\r')
                 j = 0;
         }
-
+    
     return u;
 }
 

Modified: python/branches/tlee-ast-optimize/Objects/stringobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/stringobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/stringobject.c	Wed Jan 14 13:24:17 2009
@@ -4,9 +4,10 @@
 
 #include "Python.h"
 #include <ctype.h>
+#include <stddef.h>
 
 #ifdef COUNT_ALLOCS
-int null_strings, one_strings;
+Py_ssize_t null_strings, one_strings;
 #endif
 
 static PyStringObject *characters[UCHAR_MAX + 1];
@@ -22,6 +23,14 @@
 */
 static PyObject *interned;
 
+/* PyStringObject_SIZE gives the basic size of a string; any memory allocation
+   for a string of length n should request PyStringObject_SIZE + n bytes.
+
+   Using PyStringObject_SIZE instead of sizeof(PyStringObject) saves
+   3 bytes per string allocation on a typical system.
+*/
+#define PyStringObject_SIZE (offsetof(PyStringObject, ob_sval) + 1)
+
 /*
    For both PyString_FromString() and PyString_FromStringAndSize(), the
    parameter `size' denotes number of characters to allocate, not counting any
@@ -74,13 +83,13 @@
 		return (PyObject *)op;
 	}
 
-	if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
+	if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
 		PyErr_SetString(PyExc_OverflowError, "string is too large");
 		return NULL;
 	}
 
 	/* Inline PyObject_NewVar */
-	op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
+	op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
 	if (op == NULL)
 		return PyErr_NoMemory();
 	PyObject_INIT_VAR(op, &PyString_Type, size);
@@ -114,7 +123,7 @@
 
 	assert(str != NULL);
 	size = strlen(str);
-	if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
+	if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
 		PyErr_SetString(PyExc_OverflowError,
 			"string is too long for a Python string");
 		return NULL;
@@ -135,7 +144,7 @@
 	}
 
 	/* Inline PyObject_NewVar */
-	op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
+	op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
 	if (op == NULL)
 		return PyErr_NoMemory();
 	PyObject_INIT_VAR(op, &PyString_Type, size);
@@ -992,14 +1001,14 @@
 				"strings are too large to concat");
 		return NULL;
 	}
-	  
+
 	/* Inline PyObject_NewVar */
-	if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
+	if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
 		PyErr_SetString(PyExc_OverflowError,
 				"strings are too large to concat");
 		return NULL;
 	}
-	op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
+	op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
 	if (op == NULL)
 		return PyErr_NoMemory();
 	PyObject_INIT_VAR(op, &PyString_Type, size);
@@ -1036,13 +1045,12 @@
 		return (PyObject *)a;
 	}
 	nbytes = (size_t)size;
-	if (nbytes + sizeof(PyStringObject) <= nbytes) {
+	if (nbytes + PyStringObject_SIZE <= nbytes) {
 		PyErr_SetString(PyExc_OverflowError,
 			"repeated string is too long");
 		return NULL;
 	}
-	op = (PyStringObject *)
-		PyObject_MALLOC(sizeof(PyStringObject) + nbytes);
+	op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + nbytes);
 	if (op == NULL)
 		return PyErr_NoMemory();
 	PyObject_INIT_VAR(op, &PyString_Type, size);
@@ -3940,7 +3948,7 @@
 string_sizeof(PyStringObject *v)
 {
 	Py_ssize_t res;
-	res = sizeof(PyStringObject) + v->ob_size * v->ob_type->tp_itemsize;
+	res = PyStringObject_SIZE + v->ob_size * v->ob_type->tp_itemsize;
 	return PyInt_FromSsize_t(res);
 }
 
@@ -4179,7 +4187,7 @@
 PyTypeObject PyString_Type = {
 	PyVarObject_HEAD_INIT(&PyType_Type, 0)
 	"str",
-	sizeof(PyStringObject),
+	PyStringObject_SIZE,
 	sizeof(char),
  	string_dealloc, 			/* tp_dealloc */
 	(printfunc)string_print, 		/* tp_print */
@@ -4275,7 +4283,7 @@
 	_Py_DEC_REFTOTAL;
 	_Py_ForgetReference(v);
 	*pv = (PyObject *)
-		PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
+		PyObject_REALLOC((char *)v, PyStringObject_SIZE + newsize);
 	if (*pv == NULL) {
 		PyObject_Del(v);
 		PyErr_NoMemory();

Modified: python/branches/tlee-ast-optimize/Objects/tupleobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/tupleobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/tupleobject.c	Wed Jan 14 13:24:17 2009
@@ -19,8 +19,8 @@
 static int numfree[PyTuple_MAXSAVESIZE];
 #endif
 #ifdef COUNT_ALLOCS
-int fast_tuple_allocs;
-int tuple_zero_allocs;
+Py_ssize_t fast_tuple_allocs;
+Py_ssize_t tuple_zero_allocs;
 #endif
 
 PyObject *

Modified: python/branches/tlee-ast-optimize/Objects/typeobject.c
==============================================================================
--- python/branches/tlee-ast-optimize/Objects/typeobject.c	(original)
+++ python/branches/tlee-ast-optimize/Objects/typeobject.c	Wed Jan 14 13:24:17 2009
@@ -6090,8 +6090,12 @@
 	}
 	do {
 		descr = _PyType_Lookup(type, p->name_strobj);
-		if (descr == NULL)
+		if (descr == NULL) {
+			if (ptr == (void**)&type->tp_iternext) {
+				specific = _PyObject_NextNotImplemented;
+			}
 			continue;
+		}
 		if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
 			void **tptr = resolve_slotdups(type, p->name_strobj);
 			if (tptr == NULL || tptr == ptr)

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	Wed Jan 14 13:24:17 2009
@@ -386,7 +386,8 @@
     }
 }
 
-int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
+static
+int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
 {
     register PyUnicodeObject *v;
 
@@ -395,7 +396,7 @@
 	PyErr_BadInternalCall();
 	return -1;
     }
-    v = (PyUnicodeObject *)*unicode;
+    v = *unicode;
     if (v == NULL || !PyUnicode_Check(v) || Py_REFCNT(v) != 1 || length < 0) {
 	PyErr_BadInternalCall();
 	return -1;
@@ -412,7 +413,7 @@
 	Py_UNICODE_COPY(w->str, v->str,
 			length < v->length ? length : v->length);
 	Py_DECREF(*unicode);
-	*unicode = (PyObject *)w;
+	*unicode = w;
 	return 0;
     }
 
@@ -421,9 +422,10 @@
     return unicode_resize(v, length);
 }
 
-/* Internal API for use in unicodeobject.c only ! */
-#define _PyUnicode_Resize(unicodevar, length) \
-        PyUnicode_Resize(((PyObject **)(unicodevar)), length)
+int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
+{
+    return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
+}
 
 PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
 				Py_ssize_t size)
@@ -937,7 +939,7 @@
 		PyObject_Free(callresults);
 	if (abuffer)
 		PyObject_Free(abuffer);
-	_PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
+	PyUnicode_Resize(&string, s - PyUnicode_AS_UNICODE(string));
 	return string;
  fail:
 	if (callresults) {
@@ -1345,7 +1347,7 @@
                  const char *encoding, const char *reason,
                  const char *input, Py_ssize_t insize, Py_ssize_t *startinpos,
                  Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
-                 PyObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
+                 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
 {
     static char *argparse = "O!n;decoding error handler must return (unicode, int) tuple";
 
@@ -1405,7 +1407,7 @@
     if (requiredsize > outsize) {
 	if (requiredsize<2*outsize)
 	    requiredsize = 2*outsize;
-	if (PyUnicode_Resize(output, requiredsize) < 0)
+	if (_PyUnicode_Resize(output, requiredsize) < 0)
 	    goto onError;
 	*outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
     }
@@ -1604,7 +1606,7 @@
              errors, &errorHandler,
              "utf7", errmsg,
              starts, size, &startinpos, &endinpos, &exc, &s,
-             (PyObject **)&unicode, &outpos, &p))
+             &unicode, &outpos, &p))
         goto onError;
     }
 
@@ -1615,7 +1617,7 @@
              errors, &errorHandler,
              "utf7", "unterminated shift sequence",
              starts, size, &startinpos, &endinpos, &exc, &s,
-             (PyObject **)&unicode, &outpos, &p))
+             &unicode, &outpos, &p))
             goto onError;
         if (s < e)
            goto restart;
@@ -1942,7 +1944,7 @@
 	     errors, &errorHandler,
 	     "utf8", errmsg,
 	     starts, size, &startinpos, &endinpos, &exc, &s,
-	     (PyObject **)&unicode, &outpos, &p))
+	     &unicode, &outpos, &p))
 	goto onError;
     }
     if (consumed)
@@ -2222,7 +2224,7 @@
          errors, &errorHandler,
          "utf32", errmsg,
          starts, size, &startinpos, &endinpos, &exc, &s,
-         (PyObject **)&unicode, &outpos, &p))
+         &unicode, &outpos, &p))
 	    goto onError;
     }
 
@@ -2496,7 +2498,7 @@
 	         errors, &errorHandler,
 	         "utf16", errmsg,
 	         starts, size, &startinpos, &endinpos, &exc, (const char **)&q,
-	         (PyObject **)&unicode, &outpos, &p))
+	         &unicode, &outpos, &p))
 	    goto onError;
     }
 
@@ -2717,7 +2719,7 @@
                     errors, &errorHandler,
                     "unicodeescape", "end of string in escape sequence",
                     starts, size, &startinpos, &endinpos, &exc, &s,
-                    (PyObject **)&v, &outpos, &p))
+                    &v, &outpos, &p))
                     goto onError;
                 goto nextByte;
             }
@@ -2729,7 +2731,7 @@
                         errors, &errorHandler,
                         "unicodeescape", message,
                         starts, size, &startinpos, &endinpos, &exc, &s,
-                        (PyObject **)&v, &outpos, &p))
+                        &v, &outpos, &p))
                         goto onError;
                     goto nextByte;
                 }
@@ -2768,7 +2770,7 @@
                     errors, &errorHandler,
                     "unicodeescape", "illegal Unicode character",
                     starts, size, &startinpos, &endinpos, &exc, &s,
-                    (PyObject **)&v, &outpos, &p))
+                    &v, &outpos, &p))
                     goto onError;
             }
             break;
@@ -2810,7 +2812,7 @@
                 errors, &errorHandler,
                 "unicodeescape", message,
                 starts, size, &startinpos, &endinpos, &exc, &s,
-                (PyObject **)&v, &outpos, &p))
+                &v, &outpos, &p))
                 goto onError;
             break;
 
@@ -2824,7 +2826,7 @@
                     errors, &errorHandler,
                     "unicodeescape", message,
                     starts, size, &startinpos, &endinpos, &exc, &s,
-                    (PyObject **)&v, &outpos, &p))
+                    &v, &outpos, &p))
                     goto onError;
             }
             else {
@@ -3113,7 +3115,7 @@
 		    errors, &errorHandler,
 		    "rawunicodeescape", "truncated \\uXXXX",
 		    starts, size, &startinpos, &endinpos, &exc, &s,
-		    (PyObject **)&v, &outpos, &p))
+		    &v, &outpos, &p))
 		    goto onError;
 		goto nextByte;
 	    }
@@ -3145,7 +3147,7 @@
                     errors, &errorHandler,
                     "rawunicodeescape", "\\Uxxxxxxxx out of range",
 		    starts, size, &startinpos, &endinpos, &exc, &s,
-		    (PyObject **)&v, &outpos, &p))
+		    &v, &outpos, &p))
 		    goto onError;
         }
 	nextByte:
@@ -3315,7 +3317,7 @@
                     errors, &errorHandler,
                     "unicode_internal", reason,
                     starts, size, &startinpos, &endinpos, &exc, &s,
-                    (PyObject **)&v, &outpos, &p)) {
+                    &v, &outpos, &p)) {
                 goto onError;
             }
         }
@@ -3695,7 +3697,7 @@
 		 errors, &errorHandler,
 		 "ascii", "ordinal not in range(128)",
 		 starts, size, &startinpos, &endinpos, &exc, &s,
-		 (PyObject **)&v, &outpos, &p))
+		 &v, &outpos, &p))
 		goto onError;
 	}
     }
@@ -3996,7 +3998,7 @@
 		     errors, &errorHandler,
 		     "charmap", "character maps to <undefined>",
 		     starts, size, &startinpos, &endinpos, &exc, &s,
-		     (PyObject **)&v, &outpos, &p)) {
+		     &v, &outpos, &p)) {
 		    goto onError;
 		}
 		continue;
@@ -4046,7 +4048,7 @@
 		     errors, &errorHandler,
 		     "charmap", "character maps to <undefined>",
 		     starts, size, &startinpos, &endinpos, &exc, &s,
-		     (PyObject **)&v, &outpos, &p)) {
+		     &v, &outpos, &p)) {
 		    Py_DECREF(x);
 		    goto onError;
 		}
@@ -4797,7 +4799,7 @@
 	/* exponentially overallocate to minimize reallocations */
 	if (requiredsize < 2 * oldsize)
 	    requiredsize = 2 * oldsize;
-	if (_PyUnicode_Resize(outobj, requiredsize) < 0)
+	if (PyUnicode_Resize(outobj, requiredsize) < 0)
 	    return -1;
 	*outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
     }
@@ -4976,7 +4978,7 @@
     /* Resize if we allocated to much */
     respos = str-PyUnicode_AS_UNICODE(res);
     if (respos<PyUnicode_GET_SIZE(res)) {
-	if (_PyUnicode_Resize(&res, respos) < 0)
+	if (PyUnicode_Resize(&res, respos) < 0)
 	    goto onError;
     }
     Py_XDECREF(exc);

Modified: python/branches/tlee-ast-optimize/PC/VC6/_bsddb.dsp
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VC6/_bsddb.dsp	(original)
+++ python/branches/tlee-ast-optimize/PC/VC6/_bsddb.dsp	Wed Jan 14 13:24:17 2009
@@ -44,7 +44,7 @@
 # PROP Target_Dir ""
 F90=df.exe
 # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\db-4.4.20\build_win32" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\db-4.7.25\build_windows" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
 # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
 # ADD BASE RSC /l 0x409 /d "NDEBUG"
@@ -54,7 +54,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
-# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ..\..\..\db-4.4.20\build_win32\Release\libdb44s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /out:"./_bsddb.pyd"
+# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib ..\..\..\db-4.7.25\build_windows\Release\libdb47s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /out:"./_bsddb.pyd"
 # SUBTRACT LINK32 /pdb:none
 
 !ELSEIF  "$(CFG)" == "_bsddb - Win32 Debug"
@@ -72,7 +72,7 @@
 # PROP Target_Dir ""
 F90=df.exe
 # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\db-4.4.20\build_win32" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\db-4.7.25\build_windows" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
 # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
 # ADD BASE RSC /l 0x409 /d "_DEBUG"
@@ -82,7 +82,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ..\..\..\db-4.4.20\build_win32\Release\libdb44s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrtd" /out:"./_bsddb_d.pyd" /pdbtype:sept
+# ADD LINK32 user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib ..\..\..\db-4.7.25\build_windows\Release\libdb47s.lib /nologo /base:"0x1e180000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrtd" /out:"./_bsddb_d.pyd" /pdbtype:sept
 # SUBTRACT LINK32 /pdb:none
 
 !ENDIF 

Modified: python/branches/tlee-ast-optimize/PC/VC6/_tkinter.dsp
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VC6/_tkinter.dsp	(original)
+++ python/branches/tlee-ast-optimize/PC/VC6/_tkinter.dsp	Wed Jan 14 13:24:17 2009
@@ -54,7 +54,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 ..\..\..\tcltk\lib\tk84.lib ..\..\..\tcltk\lib\tcl84.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter_d.pyd" /pdbtype:sept /libpath:"C:\Program Files\Tcl\lib"
+# ADD LINK32 ..\..\..\tcltk\lib\tk85g.lib ..\..\..\tcltk\lib\tcl85g.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter_d.pyd" /pdbtype:sept
 # SUBTRACT LINK32 /pdb:none
 
 !ELSEIF  "$(CFG)" == "_tkinter - Win32 Release"
@@ -82,7 +82,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
-# ADD LINK32 ..\..\..\tcltk\lib\tk84.lib ..\..\..\tcltk\lib\tcl84.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter.pyd" /libpath:"C:\Program Files\Tcl\lib"
+# ADD LINK32 ..\..\..\tcltk\lib\tk85.lib ..\..\..\tcltk\lib\tcl85.lib odbc32.lib odbccp32.lib user32.lib kernel32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /base:"0x1e190000" /subsystem:windows /dll /debug /machine:I386 /out:"./_tkinter.pyd"
 # SUBTRACT LINK32 /pdb:none
 
 !ENDIF 

Modified: python/branches/tlee-ast-optimize/PC/VC6/bz2.dsp
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VC6/bz2.dsp	(original)
+++ python/branches/tlee-ast-optimize/PC/VC6/bz2.dsp	Wed Jan 14 13:24:17 2009
@@ -44,7 +44,7 @@
 # PROP Target_Dir ""
 F90=df.exe
 # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.3" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MD /W3 /GX /Zi /O2 /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.5" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
 # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
 # ADD BASE RSC /l 0x409 /d "NDEBUG"
@@ -54,7 +54,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
-# ADD LINK32 ..\..\..\bzip2-1.0.3\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./bz2.pyd"
+# ADD LINK32 ..\..\..\bzip2-1.0.5\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./bz2.pyd"
 # SUBTRACT LINK32 /pdb:none /nodefaultlib
 
 !ELSEIF  "$(CFG)" == "bz2 - Win32 Debug"
@@ -72,7 +72,7 @@
 # PROP Target_Dir ""
 F90=df.exe
 # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.3" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MDd /W3 /Gm /GX /Zi /Od /I "..\..\Include" /I ".." /I "..\..\..\bzip2-1.0.5" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /YX /FD /c
 # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
 # ADD BASE RSC /l 0x409 /d "_DEBUG"
@@ -82,7 +82,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 ..\..\..\bzip2-1.0.3\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrt" /nodefaultlib:"libc" /out:"./bz2_d.pyd" /pdbtype:sept
+# ADD LINK32 ..\..\..\bzip2-1.0.5\libbz2.lib /nologo /base:"0x1D170000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"msvcrt" /nodefaultlib:"libc" /out:"./bz2_d.pyd" /pdbtype:sept
 # SUBTRACT LINK32 /pdb:none
 
 !ENDIF 

Modified: python/branches/tlee-ast-optimize/PC/VC6/pythoncore.dsp
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VC6/pythoncore.dsp	(original)
+++ python/branches/tlee-ast-optimize/PC/VC6/pythoncore.dsp	Wed Jan 14 13:24:17 2009
@@ -410,10 +410,6 @@
 # End Source File
 # Begin Source File
 
-SOURCE=..\..\Python\getmtime.c
-# End Source File
-# Begin Source File
-
 SOURCE=..\..\Python\getopt.c
 # End Source File
 # Begin Source File

Modified: python/branches/tlee-ast-optimize/PC/VC6/readme.txt
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VC6/readme.txt	(original)
+++ python/branches/tlee-ast-optimize/PC/VC6/readme.txt	Wed Jan 14 13:24:17 2009
@@ -63,18 +63,25 @@
 
 _tkinter
     Python wrapper for the Tk windowing system.  Requires building
-    Tcl/Tk first.  Following are instructions for Tcl/Tk 8.4.12.
+    Tcl/Tk first.  Following are instructions for Tcl/Tk 8.5.2.
 
     Get source
     ----------
     In the dist directory, run
-    svn export http://svn.python.org/projects/external/tcl8.4.12
-    svn export http://svn.python.org/projects/external/tk8.4.12
-    svn export http://svn.python.org/projects/external/tix-8.4.0
+    svn export http://svn.python.org/projects/external/tcl-8.5.2.1 tcl8.5.2
+    svn export http://svn.python.org/projects/external/tk-8.5.2.0 tk8.5.2
+    svn export http://svn.python.org/projects/external/tix-8.4.3.1 tix8.4.3
+
+    Debug Build
+    -----------
+    To build debug version, add DEBUG=1 to all nmake call bellow.
 
     Build Tcl first (done here w/ MSVC 6 on Win2K)
     ---------------
-    cd dist\tcl8.4.12\win
+    If your environment doesn't have struct _stat64, you need to apply
+    tcl852.patch in this directory to dist\tcl8.5.2\generic\tcl.h.
+
+    cd dist\tcl8.5.2\win
     run vcvars32.bat
     nmake -f makefile.vc
     nmake -f makefile.vc INSTALLDIR=..\..\tcltk install
@@ -84,16 +91,16 @@
     Optional:  run tests, via
         nmake -f makefile.vc test
 
-        all.tcl:        Total   10835   Passed  10096   Skipped 732     Failed  7
-        Sourced 129 Test Files.
-        Files with failing tests: exec.test expr.test io.test main.test string.test stri
+        all.tcl:        Total   24242   Passed  23358   Skipped 877     Failed  7
+        Sourced 137 Test Files.
+        Files with failing tests: exec.test http.test io.test main.test string.test stri
         ngObj.test
 
     Build Tk
     --------
-    cd dist\tk8.4.12\win
-    nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12
-    nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 INSTALLDIR=..\..\tcltk install
+    cd dist\tk8.5.2\win
+    nmake -f makefile.vc TCLDIR=..\..\tcl8.5.2
+    nmake -f makefile.vc TCLDIR=..\..\tcl8.5.2 INSTALLDIR=..\..\tcltk install
 
     XXX Should we compile with OPTS=threads?
 
@@ -101,26 +108,26 @@
     XXX failed.  It popped up tons of little windows, and did lots of
     XXX stuff, and nothing blew up.
 
-   Built Tix
-   ---------
-   cd dist\tix-8.4.0\win
-   nmake -f python.mak
-   nmake -f python.mak install
+    Build Tix
+    ---------
+    cd dist\tix8.4.3\win
+    nmake -f python.mak TCL_MAJOR=8 TCL_MINOR=5 TCL_PATCH=2 MACHINE=IX86 DEBUG=0
+    nmake -f python.mak TCL_MAJOR=8 TCL_MINOR=5 TCL_PATCH=2 MACHINE=IX86 DEBUG=0 INSTALL_DIR=..\..\tcltk install
 
 bz2
     Python wrapper for the libbz2 compression library.  Homepage
-        http://sources.redhat.com/bzip2/
+        http://www.bzip.org/
     Download the source from the python.org copy into the dist
     directory:
 
-    svn export http://svn.python.org/projects/external/bzip2-1.0.3
+    svn export http://svn.python.org/projects/external/bzip2-1.0.5
 
     And requires building bz2 first.
 
-    cd dist\bzip2-1.0.3
+    cd dist\bzip2-1.0.5
     nmake -f makefile.msc
 
-    All of this managed to build bzip2-1.0.3\libbz2.lib, which the Python
+    All of this managed to build bzip2-1.0.5\libbz2.lib, which the Python
     project links in.
 
 
@@ -128,23 +135,23 @@
     To use the version of bsddb that Python is built with by default, invoke
     (in the dist directory)
 
-     svn export http://svn.python.org/projects/external/db-4.4.20
+     svn export http://svn.python.org/projects/external/db-4.7.25.0 db-4.7.25
 
-    Then open db-4.4.20\build_win32\Berkeley_DB.dsw and build the "db_static"
-    project for "Release" mode.
+    Then open db-4.7.25\build_windows\Berkeley_DB.dsw and build the
+    "db_static" project for "Release" mode.
 
     Alternatively, if you want to start with the original sources,
-    go to Sleepycat's download page:
-        http://www.sleepycat.com/downloads/releasehistorybdb.html
+    go to Oracle's download page:
+        http://www.oracle.com/technology/software/products/berkeley-db/db/
 
-    and download version 4.4.20.
+    and download version 4.7.25.
 
     With or without strong cryptography? You can choose either with or
     without strong cryptography, as per the instructions below.  By
     default, Python is built and distributed WITHOUT strong crypto.
 
     Unpack the sources; if you downloaded the non-crypto version, rename
-    the directory from db-4.4.20.NC to db-4.4.20.
+    the directory from db-4.7.25.NC to db-4.7.25.
 
     Now apply any patches that apply to your version.
 

Modified: python/branches/tlee-ast-optimize/PC/VS7.1/pythoncore.vcproj
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VS7.1/pythoncore.vcproj	(original)
+++ python/branches/tlee-ast-optimize/PC/VS7.1/pythoncore.vcproj	Wed Jan 14 13:24:17 2009
@@ -39,15 +39,15 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26.dll"
+				OutputFile="./python27.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26.pdb"
+				ProgramDatabaseFile=".\./python27.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26.lib"
+				ImportLibrary=".\./python27.lib"
 				TargetMachine="1"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -99,15 +99,15 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26_d.dll"
+				OutputFile="./python27_d.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26_d.pdb"
+				ProgramDatabaseFile=".\./python27_d.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26_d.lib"
+				ImportLibrary=".\./python27_d.lib"
 				TargetMachine="1"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -166,15 +166,15 @@
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26.dll"
+				OutputFile="./python27.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="FALSE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26.pdb"
+				ProgramDatabaseFile=".\./python27.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26.lib"
+				ImportLibrary=".\./python27.lib"
 				TargetMachine="0"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -233,15 +233,15 @@
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26.dll"
+				OutputFile="./python27.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26.pdb"
+				ProgramDatabaseFile=".\./python27.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26.lib"
+				ImportLibrary=".\./python27.lib"
 				TargetMachine="0"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -569,9 +569,6 @@
 			RelativePath="..\..\Python\getcopyright.c">
 		</File>
 		<File
-			RelativePath="..\..\Python\getmtime.c">
-		</File>
-		<File
 			RelativePath="..\..\Python\getopt.c">
 		</File>
 		<File

Modified: python/branches/tlee-ast-optimize/PC/VS7.1/readme.txt
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VS7.1/readme.txt	(original)
+++ python/branches/tlee-ast-optimize/PC/VS7.1/readme.txt	Wed Jan 14 13:24:17 2009
@@ -12,7 +12,7 @@
 The proper order to build subprojects:
 
 1) pythoncore (this builds the main Python DLL and library files,
-               python26.{dll, lib} in Release mode)
+               python27.{dll, lib} in Release mode)
               NOTE:  in previous releases, this subproject was
               named after the release number, e.g. python20.
 
@@ -26,7 +26,7 @@
    test slave; see SUBPROJECTS below)
 
 When using the Debug setting, the output files have a _d added to
-their name:  python26_d.dll, python_d.exe, parser_d.pyd, and so on.
+their name:  python27_d.dll, python_d.exe, parser_d.pyd, and so on.
 
 SUBPROJECTS
 -----------

Modified: python/branches/tlee-ast-optimize/PC/VS8.0/build_ssl.bat
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VS8.0/build_ssl.bat	(original)
+++ python/branches/tlee-ast-optimize/PC/VS8.0/build_ssl.bat	Wed Jan 14 13:24:17 2009
@@ -2,10 +2,10 @@
 if not defined HOST_PYTHON (
   if %1 EQU Debug (
     set HOST_PYTHON=python_d.exe
-    if not exist python30_d.dll exit 1
+    if not exist python27_d.dll exit 1
   ) ELSE (
     set HOST_PYTHON=python.exe
-    if not exist python30.dll exit 1
+    if not exist python27.dll exit 1
   )
 )
 %HOST_PYTHON% build_ssl.py %1 %2 %3

Modified: python/branches/tlee-ast-optimize/PC/VS8.0/pyproject.vsprops
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VS8.0/pyproject.vsprops	(original)
+++ python/branches/tlee-ast-optimize/PC/VS8.0/pyproject.vsprops	Wed Jan 14 13:24:17 2009
@@ -38,7 +38,7 @@
 	/>
 	<UserMacro
 		Name="PyDllName"
-		Value="python26"
+		Value="python27"
 	/>
 	<UserMacro
 		Name="PythonExe"

Modified: python/branches/tlee-ast-optimize/PC/VS8.0/pythoncore.vcproj
==============================================================================
--- python/branches/tlee-ast-optimize/PC/VS8.0/pythoncore.vcproj	(original)
+++ python/branches/tlee-ast-optimize/PC/VS8.0/pythoncore.vcproj	Wed Jan 14 13:24:17 2009
@@ -1687,10 +1687,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Python\getmtime.c"
-				>
-			</File>
-			<File
 				RelativePath="..\..\Python\getopt.c"
 				>
 			</File>

Modified: python/branches/tlee-ast-optimize/PC/_winreg.c
==============================================================================
--- python/branches/tlee-ast-optimize/PC/_winreg.c	(original)
+++ python/branches/tlee-ast-optimize/PC/_winreg.c	Wed Jan 14 13:24:17 2009
@@ -410,21 +410,17 @@
 static int
 PyHKEY_printFunc(PyObject *ob, FILE *fp, int flags)
 {
-	PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
-	char resBuf[160];
-	wsprintf(resBuf, "<PyHKEY at %p (%p)>",
-		 ob, pyhkey->hkey);
-	fputs(resBuf, fp);
-	return 0;
+    PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
+    fprintf(fp, "<PyHKEY at %p (%p)>",
+            ob, pyhkey->hkey);
+    return 0;
 }
 
 static PyObject *
 PyHKEY_strFunc(PyObject *ob)
 {
-	PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
-	char resBuf[160];
-	wsprintf(resBuf, "<PyHKEY:%p>", pyhkey->hkey);
-	return PyString_FromString(resBuf);
+    PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
+    return PyString_FromFormat("<PyHKEY:%p>", pyhkey->hkey);
 }
 
 static int

Modified: python/branches/tlee-ast-optimize/PC/example_nt/example.vcproj
==============================================================================
--- python/branches/tlee-ast-optimize/PC/example_nt/example.vcproj	(original)
+++ python/branches/tlee-ast-optimize/PC/example_nt/example.vcproj	Wed Jan 14 13:24:17 2009
@@ -39,7 +39,7 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalOptions="/export:initexample"
-				AdditionalDependencies="odbc32.lib odbccp32.lib python26.lib"
+				AdditionalDependencies="odbc32.lib odbccp32.lib python27.lib"
 				OutputFile=".\Release/example.pyd"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
@@ -105,7 +105,7 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalOptions="/export:initexample"
-				AdditionalDependencies="odbc32.lib odbccp32.lib python26_d.lib"
+				AdditionalDependencies="odbc32.lib odbccp32.lib python27_d.lib"
 				OutputFile=".\Debug/example_d.pyd"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"

Modified: python/branches/tlee-ast-optimize/PC/msvcrtmodule.c
==============================================================================
--- python/branches/tlee-ast-optimize/PC/msvcrtmodule.c	(original)
+++ python/branches/tlee-ast-optimize/PC/msvcrtmodule.c	Wed Jan 14 13:24:17 2009
@@ -22,6 +22,12 @@
 #include <conio.h>
 #include <sys/locking.h>
 
+#ifdef _MSC_VER
+#if _MSC_VER >= 1500
+#include <crtassem.h>
+#endif
+#endif
+
 // Force the malloc heap to clean itself up, and free unused blocks
 // back to the OS.  (According to the docs, only works on NT.)
 static PyObject *
@@ -298,6 +304,7 @@
 PyMODINIT_FUNC
 initmsvcrt(void)
 {
+	int st;
 	PyObject *d;
 	PyObject *m = Py_InitModule("msvcrt", msvcrt_functions);
 	if (m == NULL)
@@ -310,4 +317,21 @@
 	insertint(d, "LK_NBRLCK", _LK_NBRLCK);
 	insertint(d, "LK_RLCK", _LK_RLCK);
 	insertint(d, "LK_UNLCK", _LK_UNLCK);
+
+	/* constants for the crt versions */
+#ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN
+	st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN",
+					_VC_ASSEMBLY_PUBLICKEYTOKEN);
+	if (st < 0)return;
+#endif
+#ifdef _CRT_ASSEMBLY_VERSION
+	st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION",
+					_CRT_ASSEMBLY_VERSION);
+	if (st < 0)return;
+#endif
+#ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX
+	st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX",
+					__LIBRARIES_ASSEMBLY_NAME_PREFIX);
+	if (st < 0)return;
+#endif
 }

Modified: python/branches/tlee-ast-optimize/PC/os2emx/Makefile
==============================================================================
--- python/branches/tlee-ast-optimize/PC/os2emx/Makefile	(original)
+++ python/branches/tlee-ast-optimize/PC/os2emx/Makefile	Wed Jan 14 13:24:17 2009
@@ -237,7 +237,7 @@
 
 # Output file names
 PYTHON_VER=	2.6
-PYTHON_LIB=	python26
+PYTHON_LIB=	python27
 PYTHON.LIB=	$(PYTHON_LIB)_s$A
 PYTHON.IMPLIB=	$(PYTHON_LIB)$A
 ifeq ($(EXEOMF),yes)
@@ -351,7 +351,6 @@
 		Python/getargs.c \
 		Python/getcompiler.c \
 		Python/getcopyright.c \
-		Python/getmtime.c \
 		Python/getplatform.c \
 		Python/getversion.c \
 		Python/graminit.c \

Modified: python/branches/tlee-ast-optimize/PC/os2emx/README.os2emx
==============================================================================
--- python/branches/tlee-ast-optimize/PC/os2emx/README.os2emx	(original)
+++ python/branches/tlee-ast-optimize/PC/os2emx/README.os2emx	Wed Jan 14 13:24:17 2009
@@ -309,7 +309,7 @@
    to be installed in a directory other than the PYTHONHOME directory, set 
    the value of the Makefile variable EXE_DIR to the appropriate directory.
 
-3. If you wish the Python core DLL (python26.dll) to be installed in a 
+3. If you wish the Python core DLL (python27.dll) to be installed in a 
    directory other than the directory in which the Python executables are 
    installed (by default, the PYTHONHOME directory), set the value of the 
    Makefile variable DLL_DIR to the appropriate directory.  This DLL must 

Deleted: python/branches/tlee-ast-optimize/PC/os2emx/python26.def
==============================================================================
--- python/branches/tlee-ast-optimize/PC/os2emx/python26.def	Wed Jan 14 13:24:17 2009
+++ (empty file)
@@ -1,1314 +0,0 @@
-LIBRARY python26 INITINSTANCE TERMINSTANCE 
-DESCRIPTION "Python 2.6 Core DLL" 
-PROTMODE 
-DATA MULTIPLE NONSHARED 
-EXPORTS 
-
-; From python26_s.lib(config)
-  "_PyImport_Inittab"
-
-; From python26_s.lib(dlfcn)
-;  "dlopen"
-;  "dlsym"
-;  "dlclose"
-;  "dlerror"
-
-; From python26_s.lib(getpathp)
-  "Py_GetProgramFullPath"
-  "Py_GetPrefix"
-  "Py_GetExecPrefix"
-  "Py_GetPath"
-
-; From python26_s.lib(getbuildinfo)
-  "Py_GetBuildInfo"
-  "_Py_svnversion"
-
-; From python26_s.lib(main)
-  "Py_Main"
-  "Py_GetArgcArgv"
-
-; From python26_s.lib(acceler)
-  "PyGrammar_AddAccelerators"
-  "PyGrammar_RemoveAccelerators"
-
-; From python26_s.lib(grammar1)
-  "PyGrammar_FindDFA"
-  "PyGrammar_LabelRepr"
-
-; From python26_s.lib(listnode)
-  "PyNode_ListTree"
-
-; From python26_s.lib(node)
-  "PyNode_New"
-  "PyNode_AddChild"
-  "PyNode_Free"
-
-; From python26_s.lib(parser)
-  "PyParser_AddToken"
-  "PyParser_New"
-  "PyParser_Delete"
-
-; From python26_s.lib(parsetok)
-  "Py_TabcheckFlag"
-  "PyParser_ParseString"
-  "PyParser_ParseStringFlagsFilename"
-  "PyParser_ParseFile"
-  "PyParser_ParseFileFlags"
-  "PyParser_ParseStringFlags"
-
-; From python26_s.lib(bitset)
-  "_Py_newbitset"
-  "_Py_delbitset"
-  "_Py_addbit"
-  "_Py_samebitset"
-  "_Py_mergebitset"
-
-; From python26_s.lib(metagrammar)
-  "_Py_meta_grammar"
-  "Py_meta_grammar"
-
-; From python26_s.lib(tokenizer)
-  "PyToken_OneChar"
-  "PyToken_TwoChars"
-  "PyToken_ThreeChars"
-  "PyTokenizer_FromString"
-  "PyTokenizer_Free"
-  "PyTokenizer_FromFile"
-  "PyTokenizer_Get"
-  "_PyParser_TokenNames"
-
-; From python26_s.lib(myreadline)
-  "_PyOS_ReadlineTState"
-  "PyOS_ReadlineFunctionPointer"
-  "PyOS_StdioReadline"
-  "PyOS_Readline"
-  "PyOS_InputHook"
-
-; From python26_s.lib(abstract)
-  "_PyObject_LengthHint"
-  "PyMapping_Size"
-  "PyObject_CallMethod"
-  "PyObject_GetItem"
-  "PySequence_GetItem"
-  "PyObject_SetItem"
-  "PySequence_SetItem"
-  "PyObject_DelItem"
-  "PySequence_DelItem"
-  "PyNumber_Multiply"
-  "PyNumber_InPlaceAdd"
-  "PyNumber_InPlaceMultiply"
-  "PyNumber_Int"
-  "PyNumber_Long"
-  "PyNumber_Float"
-  "PySequence_Concat"
-  "PySequence_Repeat"
-  "PySequence_InPlaceConcat"
-  "PySequence_InPlaceRepeat"
-  "PySequence_GetSlice"
-  "PySequence_SetSlice"
-  "PySequence_Tuple"
-  "PyObject_GetIter"
-  "PyIter_Next"
-  "PySequence_Fast"
-  "_PySequence_IterSearch"
-  "PyObject_CallFunction"
-  "_PyObject_CallFunction_SizeT"
-  "_PyObject_CallMethod_SizeT"
-  "PyObject_CallMethodObjArgs"
-  "PyObject_CallFunctionObjArgs"
-  "PyObject_Cmp"
-  "PyObject_Call"
-  "PyObject_CallObject"
-  "PyObject_Type"
-  "PyObject_Size"
-  "PyObject_Length"
-  "PyObject_DelItemString"
-  "PyObject_AsCharBuffer"
-  "PyObject_CheckReadBuffer"
-  "PyObject_AsReadBuffer"
-  "PyObject_AsWriteBuffer"
-  "PyNumber_Check"
-  "PyNumber_Add"
-  "PyNumber_Subtract"
-  "PyNumber_Divide"
-  "PyNumber_FloorDivide"
-  "PyNumber_TrueDivide"
-  "PyNumber_Remainder"
-  "PyNumber_Divmod"
-  "PyNumber_Power"
-  "PyNumber_Negative"
-  "PyNumber_Positive"
-  "PyNumber_Absolute"
-  "PyNumber_Invert"
-  "PyNumber_Lshift"
-  "PyNumber_Rshift"
-  "PyNumber_And"
-  "PyNumber_Xor"
-  "PyNumber_Or"
-  "PyNumber_Index"
-  "PyNumber_InPlaceSubtract"
-  "PyNumber_InPlaceDivide"
-  "PyNumber_InPlaceFloorDivide"
-  "PyNumber_InPlaceTrueDivide"
-  "PyNumber_InPlaceRemainder"
-  "PyNumber_InPlacePower"
-  "PyNumber_InPlaceLshift"
-  "PyNumber_InPlaceRshift"
-  "PyNumber_InPlaceAnd"
-  "PyNumber_InPlaceXor"
-  "PyNumber_InPlaceOr"
-  "PySequence_Check"
-  "PySequence_Size"
-  "PySequence_Length"
-  "PySequence_DelSlice"
-  "PySequence_List"
-  "PySequence_Count"
-  "PySequence_Contains"
-  "PySequence_In"
-  "PySequence_Index"
-  "PyMapping_Check"
-  "PyMapping_Length"
-  "PyMapping_HasKeyString"
-  "PyMapping_HasKey"
-  "PyMapping_GetItemString"
-  "PyMapping_SetItemString"
-  "PyObject_IsInstance"
-  "PyObject_IsSubclass"
-
-; From python26_s.lib(boolobject)
-  "PyBool_FromLong"
-  "PyBool_Type"
-  "_Py_ZeroStruct"
-  "_Py_TrueStruct"
-
-; From python26_s.lib(bufferobject)
-  "PyBuffer_FromObject"
-  "PyBuffer_FromReadWriteObject"
-  "PyBuffer_FromMemory"
-  "PyBuffer_FromReadWriteMemory"
-  "PyBuffer_New"
-  "PyBuffer_Type"
-
-; From python26_s.lib(cellobject)
-  "PyCell_New"
-  "PyCell_Get"
-  "PyCell_Set"
-  "PyCell_Type"
-
-; From python26_s.lib(classobject)
-  "PyClass_New"
-  "PyClass_IsSubclass"
-  "PyInstance_New"
-  "PyInstance_NewRaw"
-  "PyMethod_New"
-  "PyMethod_Function"
-  "PyMethod_Self"
-  "PyMethod_Class"
-  "_PyInstance_Lookup"
-  "PyMethod_Fini"
-  "PyClass_Type"
-  "PyInstance_Type"
-  "PyMethod_Type"
-
-; From python26_s.lib(cobject)
-  "PyCObject_FromVoidPtr"
-  "PyCObject_FromVoidPtrAndDesc"
-  "PyCObject_AsVoidPtr"
-  "PyCObject_GetDesc"
-  "PyCObject_Import"
-  "PyCObject_SetVoidPtr"
-  "PyCObject_Type"
-
-; From python26_s.lib(codeobject)
-  "PyCode_New"
-  "PyCode_Addr2Line"
-  "PyCode_CheckLineNumber"
-  "PyCode_Type"
-
-; From python26_s.lib(complexobject)
-  "_Py_c_pow"
-  "_Py_c_sum"
-  "_Py_c_diff"
-  "_Py_c_neg"
-  "_Py_c_prod"
-  "_Py_c_quot"
-  "PyComplex_FromCComplex"
-  "PyComplex_FromDoubles"
-  "PyComplex_RealAsDouble"
-  "PyComplex_ImagAsDouble"
-  "PyComplex_AsCComplex"
-  "PyComplex_Type"
-
-; From python26_s.lib(descrobject)
-  "PyWrapper_New"
-  "PyDescr_NewMethod"
-  "PyDescr_NewClassMethod"
-  "PyDescr_NewMember"
-  "PyDescr_NewGetSet"
-  "PyDescr_NewWrapper"
-  "PyDictProxy_New"
-  "PyWrapperDescr_Type"
-  "PyProperty_Type"
-
-; From python26_s.lib(dictobject)
-  "PyDict_New"
-  "PyDict_GetItem"
-  "PyDict_SetItem"
-  "PyDict_DelItem"
-  "PyDict_Clear"
-  "PyDict_MergeFromSeq2"
-  "PyDict_Merge"
-  "PyDict_Keys"
-  "PyDict_Values"
-  "PyDict_Contains"
-  "PyDict_Next"
-  "PyDict_Items"
-  "PyDict_Size"
-  "PyDict_Copy"
-  "PyDict_Update"
-  "PyDict_GetItemString"
-  "PyDict_SetItemString"
-  "PyDict_DelItemString"
-  "PyDict_Type"
-  "PyDictIterKey_Type"
-  "PyDictIterValue_Type"
-  "PyDictIterItem_Type"
-
-; From python26_s.lib(enumobject)
-  "PyEnum_Type"
-  "PyReversed_Type"
-
-; From python26_s.lib(fileobject)
-  "PyFile_FromString"
-  "Py_UniversalNewlineFread"
-  "PyFile_GetLine"
-  "PyFile_SoftSpace"
-  "PyFile_WriteObject"
-  "PyFile_WriteString"
-  "PyObject_AsFileDescriptor"
-  "Py_UniversalNewlineFgets"
-  "PyFile_SetBufSize"
-  "PyFile_SetEncoding"
-  "PyFile_FromFile"
-  "PyFile_AsFile"
-  "PyFile_Name"
-  "PyFile_Type"
-
-; From python26_s.lib(floatobject)
-  "PyFloat_FromString"
-  "PyFloat_AsDouble"
-  "PyFloat_Fini"
-  "_PyFloat_Pack4"
-  "_PyFloat_Pack8"
-  "_PyFloat_Unpack4"
-  "_PyFloat_Unpack8"
-  "PyFloat_FromDouble"
-  "PyFloat_AsReprString"
-  "PyFloat_AsString"
-  "_PyFloat_Init"
-  "PyFloat_AsStringEx"
-  "PyFloat_Type"
-
-; From python26_s.lib(frameobject)
-  "PyFrame_New"
-  "PyFrame_FastToLocals"
-  "PyFrame_LocalsToFast"
-  "_PyFrame_Init"
-  "PyFrame_Fini"
-  "PyFrame_BlockSetup"
-  "PyFrame_BlockPop"
-  "PyFrame_Type"
-
-; From python26_s.lib(funcobject)
-  "PyFunction_New"
-  "PyFunction_GetCode"
-  "PyFunction_GetGlobals"
-  "PyFunction_GetModule"
-  "PyFunction_GetDefaults"
-  "PyFunction_SetDefaults"
-  "PyFunction_GetClosure"
-  "PyFunction_SetClosure"
-  "PyClassMethod_New"
-  "PyStaticMethod_New"
-  "PyFunction_Type"
-  "PyClassMethod_Type"
-  "PyStaticMethod_Type"
-
-; From python26_s.lib(genobject)
-  "PyGen_New"
-  "PyGen_NeedsFinalizing"
-  "PyGen_Type"
-
-; From python26_s.lib(intobject)
-  "PyInt_AsLong"
-  "PyInt_AsUnsignedLongMask"
-  "PyInt_AsUnsignedLongLongMask"
-  "PyInt_FromString"
-  "PyInt_AsSsize_t"
-  "PyInt_Fini"
-  "PyInt_FromUnicode"
-  "PyInt_FromLong"
-  "PyInt_FromSize_t"
-  "PyInt_FromSsize_t"
-  "PyInt_GetMax"
-  "_PyInt_Init"
-  "PyInt_Type"
-
-; From python26_s.lib(iterobject)
-  "PySeqIter_New"
-  "PyCallIter_New"
-  "PySeqIter_Type"
-  "PyCallIter_Type"
-
-; From python26_s.lib(listobject)
-  "PyList_New"
-  "PyList_Append"
-  "PyList_Size"
-  "PyList_GetItem"
-  "PyList_SetItem"
-  "PyList_Insert"
-  "PyList_GetSlice"
-  "PyList_SetSlice"
-  "PyList_Sort"
-  "PyList_Reverse"
-  "PyList_AsTuple"
-  "_PyList_Extend"
-  "PyList_Fini"
-  "PyList_Type"
-  "PyListIter_Type"
-  "PyListRevIter_Type"
-
-; From python26_s.lib(longobject)
-  "PyLong_FromDouble"
-  "PyLong_AsLong"
-  "_PyLong_AsSsize_t"
-  "PyLong_AsUnsignedLong"
-  "_PyLong_FromByteArray"
-  "_PyLong_AsByteArray"
-  "PyLong_AsDouble"
-  "PyLong_FromLongLong"
-  "PyLong_AsLongLong"
-  "PyLong_FromString"
-  "PyLong_FromLong"
-  "PyLong_FromUnsignedLong"
-  "PyLong_AsUnsignedLongMask"
-  "_PyLong_FromSize_t"
-  "_PyLong_FromSsize_t"
-  "_PyLong_AsScaledDouble"
-  "PyLong_FromVoidPtr"
-  "PyLong_AsVoidPtr"
-  "PyLong_FromUnsignedLongLong"
-  "PyLong_AsUnsignedLongLong"
-  "PyLong_AsUnsignedLongLongMask"
-  "PyLong_FromUnicode"
-  "_PyLong_Sign"
-  "_PyLong_NumBits"
-  "_PyLong_New"
-  "_PyLong_Copy"
-  "PyLong_Type"
-  "_PyLong_DigitValue"
-
-; From python26_s.lib(methodobject)
-  "PyCFunction_Call"
-  "Py_FindMethodInChain"
-  "PyCFunction_GetFunction"
-  "PyCFunction_GetSelf"
-  "PyCFunction_GetFlags"
-  "Py_FindMethod"
-  "PyCFunction_NewEx"
-  "PyCFunction_Fini"
-  "PyCFunction_New"
-  "PyCFunction_Type"
-
-; From python26_s.lib(moduleobject)
-  "PyModule_New"
-  "_PyModule_Clear"
-  "PyModule_GetDict"
-  "PyModule_GetName"
-  "PyModule_GetFilename"
-  "PyModule_Type"
-
-; From python26_s.lib(object)
-  "Py_DivisionWarningFlag"
-  "PyObject_Str"
-  "PyObject_Repr"
-  "_PyObject_Str"
-  "PyObject_Unicode"
-  "PyObject_GetAttr"
-  "PyObject_IsTrue"
-  "PyNumber_CoerceEx"
-  "PyObject_Compare"
-  "PyObject_RichCompare"
-  "_Py_HashDouble"
-  "PyObject_Hash"
-  "PyObject_SetAttr"
-  "PyObject_GenericGetAttr"
-  "PyObject_GenericSetAttr"
-  "PyCallable_Check"
-  "PyObject_Dir"
-  "PyMem_Malloc"
-  "PyMem_Realloc"
-  "PyMem_Free"
-  "PyObject_Print"
-  "_PyObject_Dump"
-  "PyObject_RichCompareBool"
-  "PyObject_GetAttrString"
-  "PyObject_SetAttrString"
-  "PyObject_HasAttrString"
-  "PyObject_HasAttr"
-  "_PyObject_GetDictPtr"
-  "PyObject_SelfIter"
-  "PyObject_Not"
-  "PyNumber_Coerce"
-  "Py_ReprEnter"
-  "Py_ReprLeave"
-  "_Py_HashPointer"
-  "Py_IncRef"
-  "Py_DecRef"
-  "_PyTrash_deposit_object"
-  "_PyTrash_destroy_chain"
-  "PyObject_Init"
-  "PyObject_InitVar"
-  "_PyObject_New"
-  "_PyObject_NewVar"
-  "_PyObject_Del"
-  "_Py_ReadyTypes"
-  "_Py_SwappedOp"
-  "_Py_NotImplementedStruct"
-  "_Py_NoneStruct"
-  "_Py_cobject_hack"
-  "_Py_abstract_hack"
-  "_PyTrash_delete_nesting"
-  "_PyTrash_delete_later"
-
-; From python26_s.lib(obmalloc)
-  "PyObject_Malloc"
-  "PyObject_Free"
-  "PyObject_Realloc"
-
-; From python26_s.lib(rangeobject)
-  "PyRange_Type"
-
-; From python26_s.lib(setobject)
-  "PySet_Pop"
-  "PySet_New"
-  "PyFrozenSet_New"
-  "PySet_Size"
-  "PySet_Clear"
-  "PySet_Contains"
-  "PySet_Discard"
-  "PySet_Add"
-  "_PySet_Next"
-  "_PySet_Update"
-  "PySet_Fini"
-  "PySet_Type"
-  "PyFrozenSet_Type"
-
-; From python26_s.lib(sliceobject)
-  "_PySlice_FromIndices"
-  "PySlice_GetIndices"
-  "PySlice_GetIndicesEx"
-  "PySlice_New"
-  "_Py_EllipsisObject"
-  "PySlice_Type"
-
-; From python26_s.lib(stringobject)
-  "PyString_FromStringAndSize"
-  "PyString_InternInPlace"
-  "PyString_FromString"
-  "PyString_FromFormatV"
-  "PyString_AsString"
-  "_PyString_Resize"
-  "PyString_FromFormat"
-  "PyString_AsDecodedString"
-  "PyString_AsEncodedString"
-  "PyString_DecodeEscape"
-  "PyString_Repr"
-  "PyString_AsStringAndSize"
-  "_PyString_FormatLong"
-  "PyString_Format"
-  "_Py_ReleaseInternedStrings"
-  "PyString_Size"
-  "PyString_Concat"
-  "PyString_ConcatAndDel"
-  "_PyString_Eq"
-  "PyString_InternImmortal"
-  "PyString_InternFromString"
-  "_PyString_Join"
-  "PyString_Decode"
-  "PyString_Encode"
-  "PyString_AsEncodedObject"
-  "PyString_AsDecodedObject"
-  "PyString_Fini"
-  "PyString_Type"
-  "PyBaseString_Type"
-
-; From python26_s.lib(structseq)
-  "PyStructSequence_InitType"
-  "PyStructSequence_New"
-  "PyStructSequence_UnnamedField"
-
-; From python26_s.lib(tupleobject)
-  "PyTuple_New"
-  "PyTuple_Pack"
-  "_PyTuple_Resize"
-  "PyTuple_Size"
-  "PyTuple_GetItem"
-  "PyTuple_SetItem"
-  "PyTuple_GetSlice"
-  "PyTuple_Fini"
-  "PyTuple_Type"
-  "PyTupleIter_Type"
-
-; From python26_s.lib(typeobject)
-  "PyType_IsSubtype"
-  "_PyType_Lookup"
-  "PyType_Ready"
-  "PyType_GenericAlloc"
-  "_PyObject_SlotCompare"
-  "PyType_GenericNew"
-  "PyType_Type"
-  "PyBaseObject_Type"
-  "PySuper_Type"
-
-; From python26_s.lib(unicodeobject)
-  "PyUnicodeUCS2_Resize"
-  "PyUnicodeUCS2_FromOrdinal"
-  "PyUnicodeUCS2_FromObject"
-  "PyUnicodeUCS2_FromEncodedObject"
-  "PyUnicodeUCS2_Decode"
-  "PyUnicodeUCS2_GetDefaultEncoding"
-  "PyUnicodeUCS2_DecodeUTF8"
-  "PyUnicodeUCS2_DecodeLatin1"
-  "PyUnicodeUCS2_DecodeASCII"
-  "PyUnicodeUCS2_AsEncodedString"
-  "PyUnicodeUCS2_AsUTF8String"
-  "PyUnicodeUCS2_AsLatin1String"
-  "PyUnicodeUCS2_AsASCIIString"
-  "PyUnicode_DecodeUTF7"
-  "PyUnicode_EncodeUTF7"
-  "PyUnicodeUCS2_DecodeUTF8Stateful"
-  "PyUnicodeUCS2_EncodeUTF8"
-  "PyUnicodeUCS2_DecodeUTF16Stateful"
-  "PyUnicodeUCS2_AsUTF16String"
-  "PyUnicodeUCS2_DecodeUnicodeEscape"
-  "PyUnicodeUCS2_DecodeRawUnicodeEscape"
-  "PyUnicodeUCS2_EncodeRawUnicodeEscape"
-  "_PyUnicode_DecodeUnicodeInternal"
-  "PyUnicodeUCS2_DecodeCharmap"
-  "PyUnicode_BuildEncodingMap"
-  "PyUnicodeUCS2_EncodeCharmap"
-  "PyUnicodeUCS2_TranslateCharmap"
-  "PyUnicodeUCS2_EncodeDecimal"
-  "PyUnicodeUCS2_Count"
-  "PyUnicodeUCS2_Find"
-  "PyUnicodeUCS2_Join"
-  "PyUnicodeUCS2_Splitlines"
-  "PyUnicodeUCS2_Compare"
-  "PyUnicodeUCS2_Contains"
-  "PyUnicodeUCS2_Concat"
-  "_PyUnicode_XStrip"
-  "PyUnicodeUCS2_Replace"
-  "PyUnicodeUCS2_Split"
-  "PyUnicodeUCS2_RSplit"
-  "PyUnicodeUCS2_Format"
-  "_PyUnicodeUCS2_Init"
-  "_PyUnicodeUCS2_Fini"
-  "PyUnicodeUCS2_FromUnicode"
-  "PyUnicodeUCS2_AsUnicode"
-  "PyUnicodeUCS2_GetSize"
-  "PyUnicodeUCS2_GetMax"
-  "_PyUnicodeUCS2_AsDefaultEncodedString"
-  "PyUnicodeUCS2_SetDefaultEncoding"
-  "PyUnicodeUCS2_Encode"
-  "PyUnicodeUCS2_AsEncodedObject"
-  "PyUnicodeUCS2_DecodeUTF16"
-  "PyUnicodeUCS2_EncodeUTF16"
-  "PyUnicodeUCS2_AsUnicodeEscapeString"
-  "PyUnicodeUCS2_EncodeUnicodeEscape"
-  "PyUnicodeUCS2_AsRawUnicodeEscapeString"
-  "PyUnicodeUCS2_EncodeLatin1"
-  "PyUnicodeUCS2_EncodeASCII"
-  "PyUnicodeUCS2_AsCharmapString"
-  "PyUnicodeUCS2_Partition"
-  "PyUnicodeUCS2_RPartition"
-  "PyUnicodeUCS2_Translate"
-  "PyUnicodeUCS2_Tailmatch"
-  "PyUnicode_AsDecodedObject"
-  "PyUnicode_Type"
-
-; From python26_s.lib(unicodectype)
-  "_PyUnicode_TypeRecords"
-  "_PyUnicodeUCS2_ToNumeric"
-  "_PyUnicodeUCS2_IsLowercase"
-  "_PyUnicodeUCS2_IsUppercase"
-  "_PyUnicodeUCS2_IsTitlecase"
-  "_PyUnicodeUCS2_IsWhitespace"
-  "_PyUnicodeUCS2_IsLinebreak"
-  "_PyUnicodeUCS2_ToLowercase"
-  "_PyUnicodeUCS2_ToUppercase"
-  "_PyUnicodeUCS2_ToTitlecase"
-  "_PyUnicodeUCS2_ToDecimalDigit"
-  "_PyUnicodeUCS2_ToDigit"
-  "_PyUnicodeUCS2_IsDecimalDigit"
-  "_PyUnicodeUCS2_IsDigit"
-  "_PyUnicodeUCS2_IsNumeric"
-  "_PyUnicodeUCS2_IsAlpha"
-
-; From python26_s.lib(weakrefobject)
-  "PyWeakref_NewRef"
-  "PyWeakref_NewProxy"
-  "PyObject_ClearWeakRefs"
-  "PyWeakref_GetObject"
-  "_PyWeakref_GetWeakrefCount"
-  "_PyWeakref_ClearRef"
-  "_PyWeakref_RefType"
-  "_PyWeakref_ProxyType"
-  "_PyWeakref_CallableProxyType"
-
-; From python26_s.lib(Python-ast)
-;  "init_ast"
-  "Module"
-  "Interactive"
-  "Expression"
-  "Suite"
-  "FunctionDef"
-  "ClassDef"
-  "Return"
-  "Delete"
-  "Assign"
-  "AugAssign"
-  "Print"
-  "For"
-  "While"
-  "If"
-  "With"
-  "Raise"
-  "TryExcept"
-  "TryFinally"
-  "Assert"
-  "Import"
-  "ImportFrom"
-  "Exec"
-  "Global"
-  "Expr"
-  "Pass"
-  "Break"
-  "Continue"
-  "BoolOp"
-  "BinOp"
-  "UnaryOp"
-  "Lambda"
-  "IfExp"
-  "Dict"
-  "ListComp"
-  "GeneratorExp"
-  "Yield"
-  "Compare"
-  "Call"
-  "Repr"
-  "Num"
-  "Str"
-  "Attribute"
-  "Subscript"
-  "Name"
-  "List"
-  "Tuple"
-  "Ellipsis"
-  "Slice"
-  "ExtSlice"
-  "Index"
-  "comprehension"
-  "excepthandler"
-  "arguments"
-  "keyword"
-  "alias"
-  "PyAST_mod2obj"
-
-; From python26_s.lib(asdl)
-  "asdl_seq_new"
-  "asdl_int_seq_new"
-
-; From python26_s.lib(ast)
-  "PyAST_FromNode"
-
-; From python26_s.lib(bltinmodule)
-  "_PyBuiltin_Init"
-  "Py_FileSystemDefaultEncoding"
-
-; From python26_s.lib(exceptions)
-  "PyUnicodeEncodeError_GetStart"
-  "PyUnicodeDecodeError_GetStart"
-  "PyUnicodeEncodeError_GetEnd"
-  "PyUnicodeDecodeError_GetEnd"
-  "_PyExc_Init"
-  "PyUnicodeDecodeError_Create"
-  "PyUnicodeEncodeError_Create"
-  "PyUnicodeTranslateError_Create"
-  "PyUnicodeEncodeError_GetEncoding"
-  "PyUnicodeDecodeError_GetEncoding"
-  "PyUnicodeEncodeError_GetObject"
-  "PyUnicodeDecodeError_GetObject"
-  "PyUnicodeTranslateError_GetObject"
-  "PyUnicodeTranslateError_GetStart"
-  "PyUnicodeEncodeError_SetStart"
-  "PyUnicodeDecodeError_SetStart"
-  "PyUnicodeTranslateError_SetStart"
-  "PyUnicodeTranslateError_GetEnd"
-  "PyUnicodeEncodeError_SetEnd"
-  "PyUnicodeDecodeError_SetEnd"
-  "PyUnicodeTranslateError_SetEnd"
-  "PyUnicodeEncodeError_GetReason"
-  "PyUnicodeDecodeError_GetReason"
-  "PyUnicodeTranslateError_GetReason"
-  "PyUnicodeEncodeError_SetReason"
-  "PyUnicodeDecodeError_SetReason"
-  "PyUnicodeTranslateError_SetReason"
-  "_PyExc_Fini"
-  "PyExc_BaseException"
-  "PyExc_Exception"
-  "PyExc_StandardError"
-  "PyExc_TypeError"
-  "PyExc_StopIteration"
-  "PyExc_GeneratorExit"
-  "PyExc_SystemExit"
-  "PyExc_KeyboardInterrupt"
-  "PyExc_ImportError"
-  "PyExc_EnvironmentError"
-  "PyExc_IOError"
-  "PyExc_OSError"
-  "PyExc_EOFError"
-  "PyExc_RuntimeError"
-  "PyExc_NotImplementedError"
-  "PyExc_NameError"
-  "PyExc_UnboundLocalError"
-  "PyExc_AttributeError"
-  "PyExc_IndexError"
-  "PyExc_SyntaxError"
-  "PyExc_IndentationError"
-  "PyExc_TabError"
-  "PyExc_LookupError"
-  "PyExc_KeyError"
-  "PyExc_ValueError"
-  "PyExc_UnicodeError"
-  "PyExc_UnicodeEncodeError"
-  "PyExc_UnicodeDecodeError"
-  "PyExc_UnicodeTranslateError"
-  "PyExc_AssertionError"
-  "PyExc_ArithmeticError"
-  "PyExc_FloatingPointError"
-  "PyExc_OverflowError"
-  "PyExc_ZeroDivisionError"
-  "PyExc_SystemError"
-  "PyExc_ReferenceError"
-  "PyExc_MemoryError"
-  "PyExc_Warning"
-  "PyExc_UserWarning"
-  "PyExc_DeprecationWarning"
-  "PyExc_PendingDeprecationWarning"
-  "PyExc_SyntaxWarning"
-  "PyExc_RuntimeWarning"
-  "PyExc_FutureWarning"
-  "PyExc_ImportWarning"
-  "PyExc_MemoryErrorInst"
-
-; From python26_s.lib(ceval)
-  "PyEval_EvalFrameEx"
-  "PyEval_CallObjectWithKeywords"
-  "PyEval_EvalCodeEx"
-  "PyEval_GetFrame"
-  "PyEval_CallObject"
-  "PyEval_SetProfile"
-  "PyEval_SetTrace"
-  "PyEval_GetBuiltins"
-  "PyEval_GetGlobals"
-  "PyEval_GetLocals"
-  "PyEval_GetRestricted"
-  "PyEval_MergeCompilerFlags"
-  "Py_FlushLine"
-  "Py_AddPendingCall"
-  "Py_MakePendingCalls"
-  "Py_SetRecursionLimit"
-  "Py_GetRecursionLimit"
-  "_Py_CheckRecursiveCall"
-  "PyEval_GetFuncName"
-  "PyEval_GetFuncDesc"
-  "PyEval_GetCallStats"
-  "PyEval_EvalFrame"
-  "PyEval_SaveThread"
-  "PyEval_RestoreThread"
-  "PyEval_ThreadsInitialized"
-  "PyEval_InitThreads"
-  "PyEval_AcquireLock"
-  "PyEval_ReleaseLock"
-  "PyEval_AcquireThread"
-  "PyEval_ReleaseThread"
-  "PyEval_ReInitThreads"
-  "_PyEval_SliceIndex"
-  "PyEval_EvalCode"
-  "_PyEval_CallTracing"
-  "_Py_CheckRecursionLimit"
-  "_Py_CheckInterval"
-  "_Py_Ticker"
-
-; From python26_s.lib(compile)
-  "_Py_Mangle"
-  "PyAST_Compile"
-  "PyNode_Compile"
-  "Py_OptimizeFlag"
-
-; From python26_s.lib(codecs)
-  "_PyCodec_Lookup"
-  "PyCodec_Encode"
-  "PyCodec_Decode"
-  "PyCodec_IgnoreErrors"
-  "PyCodec_ReplaceErrors"
-  "PyCodec_XMLCharRefReplaceErrors"
-  "PyCodec_BackslashReplaceErrors"
-  "PyCodec_Register"
-  "PyCodec_Encoder"
-  "PyCodec_Decoder"
-  "PyCodec_IncrementalEncoder"
-  "PyCodec_IncrementalDecoder"
-  "PyCodec_StreamReader"
-  "PyCodec_StreamWriter"
-  "PyCodec_RegisterError"
-  "PyCodec_LookupError"
-  "PyCodec_StrictErrors"
-
-; From python26_s.lib(errors)
-  "PyErr_SetNone"
-  "PyErr_SetString"
-  "PyErr_GivenExceptionMatches"
-  "PyErr_NormalizeException"
-  "PyErr_Fetch"
-  "PyErr_Clear"
-  "PyErr_NoMemory"
-  "PyErr_SetFromErrnoWithFilenameObject"
-  "PyErr_Format"
-  "PyErr_NewException"
-  "PyErr_WriteUnraisable"
-  "PyErr_SyntaxLocation"
-  "PyErr_ProgramText"
-  "PyErr_SetObject"
-  "PyErr_Occurred"
-  "PyErr_Restore"
-  "PyErr_ExceptionMatches"
-  "PyErr_BadArgument"
-  "PyErr_SetFromErrno"
-  "PyErr_SetFromErrnoWithFilename"
-  "PyErr_BadInternalCall"
-  "_PyErr_BadInternalCall"
-  "PyErr_Warn"
-  "PyErr_WarnExplicit"
-
-; From python26_s.lib(frozen)
-  "PyImport_FrozenModules"
-
-; From python26_s.lib(frozenmain)
-  "Py_FrozenMain"
-
-; From python26_s.lib(future)
-  "PyFuture_FromAST"
-
-; From python26_s.lib(getargs)
-  "PyArg_Parse"
-  "_PyArg_Parse_SizeT"
-  "PyArg_ParseTuple"
-  "_PyArg_ParseTuple_SizeT"
-  "PyArg_ParseTupleAndKeywords"
-  "_PyArg_ParseTupleAndKeywords_SizeT"
-  "PyArg_UnpackTuple"
-  "_PyArg_NoKeywords"
-  "PyArg_VaParse"
-  "PyArg_VaParseTupleAndKeywords"
-  "_PyArg_VaParse_SizeT"
-  "_PyArg_VaParseTupleAndKeywords_SizeT"
-
-; From python26_s.lib(getcompiler)
-  "Py_GetCompiler"
-
-; From python26_s.lib(getcopyright)
-  "Py_GetCopyright"
-
-; From python26_s.lib(getmtime)
-  "PyOS_GetLastModificationTime"
-
-; From python26_s.lib(getplatform)
-  "Py_GetPlatform"
-
-; From python26_s.lib(getversion)
-  "Py_GetVersion"
-
-; From python26_s.lib(graminit)
-  "_PyParser_Grammar"
-
-; From python26_s.lib(import)
-  "_PyImport_Init"
-  "_PyImportHooks_Init"
-  "PyImport_ImportModule"
-  "PyImport_Cleanup"
-  "_PyImport_FixupExtension"
-  "PyImport_AddModule"
-  "PyImport_ExecCodeModuleEx"
-  "PyImport_ImportFrozenModule"
-  "PyImport_ImportModuleEx"
-  "PyImport_ImportModuleLevel"
-  "PyImport_ReloadModule"
-  "PyImport_Import"
-;  "initimp"
-  "_PyImport_Fini"
-  "PyImport_GetMagicNumber"
-  "PyImport_ExecCodeModule"
-  "PyImport_GetModuleDict"
-  "_PyImport_FindModule"
-  "_PyImport_IsScript"
-  "_PyImport_ReInitLock"
-  "_PyImport_FindExtension"
-  "PyImport_AppendInittab"
-  "PyImport_ExtendInittab"
-  "PyImport_Inittab"
-  "_PyImport_Filetab"
-
-; From python26_s.lib(importdl)
-  "_PyImport_LoadDynamicModule"
-
-; From python26_s.lib(marshal)
-  "PyMarshal_ReadLongFromFile"
-  "PyMarshal_WriteObjectToString"
-  "PyMarshal_WriteLongToFile"
-  "PyMarshal_WriteObjectToFile"
-  "PyMarshal_ReadShortFromFile"
-  "PyMarshal_ReadObjectFromFile"
-  "PyMarshal_ReadLastObjectFromFile"
-  "PyMarshal_ReadObjectFromString"
-  "PyMarshal_Init"
-
-; From python26_s.lib(modsupport)
-  "Py_InitModule4"
-  "Py_BuildValue"
-  "_Py_BuildValue_SizeT"
-  "PyEval_CallFunction"
-  "PyEval_CallMethod"
-  "_Py_VaBuildValue_SizeT"
-  "Py_VaBuildValue"
-  "PyModule_AddObject"
-  "PyModule_AddIntConstant"
-  "PyModule_AddStringConstant"
-  "_Py_PackageContext"
-
-; From python26_s.lib(mysnprintf)
-  "PyOS_snprintf"
-  "PyOS_vsnprintf"
-
-; From python26_s.lib(mystrtoul)
-  "PyOS_strtoul"
-  "PyOS_strtol"
-
-; From python26_s.lib(pyarena)
-  "PyArena_New"
-  "PyArena_Free"
-  "PyArena_Malloc"
-  "PyArena_AddPyObject"
-
-; From python26_s.lib(pyfpe)
-  "PyFPE_dummy"
-
-; From python26_s.lib(pystate)
-  "PyInterpreterState_Clear"
-  "PyThreadState_Clear"
-  "_PyThread_CurrentFrames"
-  "PyGILState_Ensure"
-  "PyGILState_Release"
-  "PyInterpreterState_New"
-  "PyInterpreterState_Delete"
-  "PyThreadState_Delete"
-  "PyThreadState_New"
-  "PyThreadState_DeleteCurrent"
-  "PyThreadState_Get"
-  "PyThreadState_Swap"
-  "PyThreadState_GetDict"
-  "PyThreadState_SetAsyncExc"
-  "PyGILState_GetThisThreadState"
-  "PyInterpreterState_Head"
-  "PyInterpreterState_Next"
-  "PyInterpreterState_ThreadHead"
-  "PyThreadState_Next"
-  "_PyGILState_Init"
-  "_PyGILState_Fini"
-  "_PyThreadState_Current"
-  "_PyThreadState_GetFrame"
-
-; From python26_s.lib(pystrtod)
-  "PyOS_ascii_strtod"
-  "PyOS_ascii_formatd"
-  "PyOS_ascii_atof"
-
-; From python26_s.lib(pythonrun)
-  "Py_IgnoreEnvironmentFlag"
-  "Py_DebugFlag"
-  "Py_VerboseFlag"
-  "Py_NoSiteFlag"
-  "Py_InteractiveFlag"
-  "Py_FrozenFlag"
-  "Py_InitializeEx"
-  "Py_FatalError"
-  "Py_NewInterpreter"
-  "PyErr_Print"
-  "PyRun_InteractiveOneFlags"
-  "PyParser_ASTFromFile"
-  "PyRun_SimpleFileExFlags"
-  "PyRun_FileExFlags"
-  "Py_Exit"
-  "PyErr_PrintEx"
-  "PyErr_Display"
-  "Py_SetProgramName"
-  "Py_GetProgramName"
-  "Py_SetPythonHome"
-  "Py_GetPythonHome"
-  "Py_Initialize"
-  "Py_Finalize"
-  "Py_IsInitialized"
-  "Py_EndInterpreter"
-  "PyRun_AnyFileFlags"
-  "Py_FdIsInteractive"
-  "PyRun_InteractiveLoopFlags"
-  "PyRun_AnyFileExFlags"
-  "PyRun_SimpleStringFlags"
-  "PyRun_StringFlags"
-  "PyParser_ASTFromString"
-  "PyParser_SimpleParseStringFlags"
-  "PyParser_SimpleParseFileFlags"
-  "Py_CompileStringFlags"
-  "Py_SymtableString"
-  "Py_AtExit"
-  "PyOS_getsig"
-  "PyOS_setsig"
-  "PyParser_SetError"
-  "PyModule_GetWarningsModule"
-  "PyParser_SimpleParseStringFlagsFilename"
-  "PyParser_SimpleParseStringFilename"
-  "PyParser_SimpleParseFile"
-  "PyParser_SimpleParseString"
-  "PyRun_AnyFile"
-  "PyRun_AnyFileEx"
-  "PyRun_File"
-  "PyRun_FileEx"
-  "PyRun_FileFlags"
-  "PyRun_SimpleFile"
-  "PyRun_SimpleFileEx"
-  "PyRun_String"
-  "PyRun_SimpleString"
-  "Py_CompileString"
-  "PyRun_InteractiveOne"
-  "PyRun_InteractiveLoop"
-  "Py_UseClassExceptionsFlag"
-  "Py_UnicodeFlag"
-  "_Py_QnewFlag"
-
-; From python26_s.lib(structmember)
-  "PyMember_Get"
-  "PyMember_GetOne"
-  "PyMember_SetOne"
-  "PyMember_Set"
-
-; From python26_s.lib(symtable)
-  "PySymtable_Build"
-  "PySymtable_Free"
-  "PyST_GetScope"
-  "PySymtable_Lookup"
-  "PySTEntry_Type"
-
-; From python26_s.lib(sysmodule)
-  "_PySys_Init"
-  "PySys_WriteStderr"
-  "PySys_SetPath"
-  "PySys_SetArgv"
-  "PySys_WriteStdout"
-  "Py_SubversionRevision"
-  "Py_SubversionShortBranch"
-  "PySys_GetObject"
-  "PySys_SetObject"
-  "PySys_GetFile"
-  "PySys_ResetWarnOptions"
-  "PySys_AddWarnOption"
-
-; From python26_s.lib(traceback)
-  "PyTraceBack_Here"
-  "PyTraceBack_Print"
-  "PyTraceBack_Type"
-
-; From python26_s.lib(getopt)
-  "_PyOS_GetOpt"
-  "_PyOS_opterr"
-  "_PyOS_optind"
-  "_PyOS_optarg"
-
-; From python26_s.lib(dynload_shlib)
-  "_PyImport_DynLoadFiletab"
-  "_PyImport_GetDynLoadFunc"
-
-; From python26_s.lib(thread)
-  "PyThread_delete_key_value"
-  "PyThread_init_thread"
-  "PyThread_start_new_thread"
-  "PyThread_exit_thread"
-  "PyThread_get_thread_ident"
-  "PyThread_allocate_lock"
-  "PyThread_free_lock"
-  "PyThread_acquire_lock"
-  "PyThread_release_lock"
-  "PyThread_get_stacksize"
-  "PyThread_set_stacksize"
-  "PyThread_create_key"
-  "PyThread_delete_key"
-  "PyThread_set_key_value"
-  "PyThread_get_key_value"
-  "PyThread__exit_thread"
-
-; From python26_s.lib(gcmodule)
-;  "initgc"
-  "_PyObject_GC_New"
-  "_PyObject_GC_NewVar"
-  "PyGC_Collect"
-  "_PyObject_GC_Resize"
-  "_PyObject_GC_Malloc"
-  "PyObject_GC_Track"
-  "PyObject_GC_UnTrack"
-  "PyObject_GC_Del"
-  "_PyGC_Dump"
-  "_PyObject_GC_Track"
-  "_PyObject_GC_UnTrack"
-  "_PyObject_GC_Del"
-  "_PyGC_generation0"
-
-; From python26_s.lib(signalmodule)
-;  "initsignal"
-  "PyErr_CheckSignals"
-  "PyErr_SetInterrupt"
-  "PyOS_FiniInterrupts"
-  "PyOS_InterruptOccurred"
-  "PyOS_InitInterrupts"
-  "PyOS_AfterFork"
-
-; From python26_s.lib(posixmodule)
-;  "initos2"
-
-; From python26_s.lib(threadmodule)
-;  "initthread"
-
-; From python26_s.lib(arraymodule)
-;  "initarray"
-;  "array_methods"
-
-; From python26_s.lib(binascii)
-;  "initbinascii"
-
-; From python26_s.lib(cmathmodule)
-;  "initcmath"
-
-; From python26_s.lib(_codecsmodule)
-;  "init_codecs"
-
-; From python26_s.lib(collectionsmodule)
-;  "initcollections"
-  "dequeiter_type"
-  "dequereviter_type"
-
-; From python26_s.lib(cPickle)
-;  "initcPickle"
-;  "fast_save_leave"
-
-; From python26_s.lib(cStringIO)
-;  "initcStringIO"
-
-; From python26_s.lib(_csv)
-;  "init_csv"
-
-; From python26_s.lib(datetimemodule)
-;  "initdatetime"
-
-; From python26_s.lib(dlmodule)
-;  "initdl"
-
-; From python26_s.lib(errnomodule)
-;  "initerrno"
-
-; From python26_s.lib(fcntlmodule)
-;  "initfcntl"
-
-; From python26_s.lib(_functoolsmodule)
-;  "init_functools"
-
-; From python26_s.lib(_heapqmodule)
-;  "init_heapq"
-
-; From python26_s.lib(imageop)
-;  "initimageop"
-
-; From python26_s.lib(itertoolsmodule)
-;  "inititertools"
-
-; From python26_s.lib(_localemodule)
-;  "init_locale"
-
-; From python26_s.lib(mathmodule)
-;  "initmath"
-
-; From python26_s.lib(md5)
-  "md5_finish"
-  "md5_init"
-  "md5_append"
-
-; From python26_s.lib(md5module)
-;  "init_md5"
-
-; From python26_s.lib(operator)
-;  "initoperator"
-
-; From python26_s.lib(_randommodule)
-;  "init_random"
-
-; From python26_s.lib(rgbimgmodule)
-;  "initrgbimg"
-
-; From python26_s.lib(shamodule)
-;  "init_sha"
-
-; From python26_s.lib(sha256module)
-;  "init_sha256"
-
-; From python26_s.lib(sha512module)
-;  "init_sha512"
-
-; From python26_s.lib(_sre)
-;  "init_sre"
-
-; From python26_s.lib(stropmodule)
-;  "initstrop"
-
-; From python26_s.lib(_struct)
-;  "init_struct"
-
-; From python26_s.lib(symtablemodule)
-;  "init_symtable"
-
-; From python26_s.lib(termios)
-;  "inittermios"
-
-; From python26_s.lib(timemodule)
-;  "inittime"
-  "_PyTime_DoubleToTimet"
-;  "inittimezone"
-
-; From python26_s.lib(timingmodule)
-;  "inittiming"
-
-; From python26_s.lib(_weakref)
-;  "init_weakref"
-
-; From python26_s.lib(xxsubtype)
-;  "initxxsubtype"
-
-; From python26_s.lib(zipimport)
-;  "initzipimport"

Modified: python/branches/tlee-ast-optimize/PC/os2vacpp/makefile
==============================================================================
--- python/branches/tlee-ast-optimize/PC/os2vacpp/makefile	(original)
+++ python/branches/tlee-ast-optimize/PC/os2vacpp/makefile	Wed Jan 14 13:24:17 2009
@@ -1693,8 +1693,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-getmtime.obj: pyconfig.h
-
 getplatform.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \

Modified: python/branches/tlee-ast-optimize/PC/os2vacpp/makefile.omk
==============================================================================
--- python/branches/tlee-ast-optimize/PC/os2vacpp/makefile.omk	(original)
+++ python/branches/tlee-ast-optimize/PC/os2vacpp/makefile.omk	Wed Jan 14 13:24:17 2009
@@ -1155,8 +1155,6 @@
 	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
 	 stringobject.h sysmodule.h traceback.h tupleobject.h
 
-getmtime.obj: pyconfig.h
-
 getplatform.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \

Modified: python/branches/tlee-ast-optimize/PC/os2vacpp/python.def
==============================================================================
--- python/branches/tlee-ast-optimize/PC/os2vacpp/python.def	(original)
+++ python/branches/tlee-ast-optimize/PC/os2vacpp/python.def	Wed Jan 14 13:24:17 2009
@@ -284,7 +284,6 @@
                PyNumber_Xor
                PyOS_AfterFork
                PyOS_FiniInterrupts
-               PyOS_GetLastModificationTime
                PyOS_InitInterrupts
                PyOS_InterruptOccurred
                PyOS_Readline

Modified: python/branches/tlee-ast-optimize/PC/pyconfig.h
==============================================================================
--- python/branches/tlee-ast-optimize/PC/pyconfig.h	(original)
+++ python/branches/tlee-ast-optimize/PC/pyconfig.h	Wed Jan 14 13:24:17 2009
@@ -88,6 +88,12 @@
 #define USE_SOCKET
 #endif
 
+/* CE6 doesn't have strdup() but _strdup(). Assume the same for earlier versions. */
+#if defined(MS_WINCE)
+#  include <stdlib.h>
+#  define strdup _strdup
+#endif
+
 #ifdef MS_WINCE
 /* Python uses GetVersion() to distinguish between
  * Windows NT and 9x/ME where OS Unicode support is concerned.
@@ -399,11 +405,11 @@
 /* Define to 1 if you have the `copysign' function. */
 #define HAVE_COPYSIGN 1
 
-/* Define to 1 if you have the `isinf' function. */
-#define HAVE_ISINF 1
+/* Define to 1 if you have the `isinf' macro. */
+#define HAVE_DECL_ISINF 1
 
 /* Define to 1 if you have the `isnan' function. */
-#define HAVE_ISNAN 1
+#define HAVE_DECL_ISNAN 1
 
 /* Define if on AIX 3.
    System headers sometimes define this.

Modified: python/branches/tlee-ast-optimize/PCbuild/build_ssl.bat
==============================================================================
--- python/branches/tlee-ast-optimize/PCbuild/build_ssl.bat	(original)
+++ python/branches/tlee-ast-optimize/PCbuild/build_ssl.bat	Wed Jan 14 13:24:17 2009
@@ -2,10 +2,10 @@
 if not defined HOST_PYTHON (
   if %1 EQU Debug (
     set HOST_PYTHON=python_d.exe
-    if not exist python30_d.dll exit 1
+    if not exist python27_d.dll exit 1
   ) ELSE (
     set HOST_PYTHON=python.exe
-    if not exist python30.dll exit 1
+    if not exist python27.dll exit 1
   )
 )
 %HOST_PYTHON% build_ssl.py %1 %2 %3

Modified: python/branches/tlee-ast-optimize/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/tlee-ast-optimize/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/tlee-ast-optimize/PCbuild/pythoncore.vcproj	Wed Jan 14 13:24:17 2009
@@ -1687,10 +1687,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Python\getmtime.c"
-				>
-			</File>
-			<File
 				RelativePath="..\Python\getopt.c"
 				>
 			</File>

Modified: python/branches/tlee-ast-optimize/Parser/asdl.py
==============================================================================
--- python/branches/tlee-ast-optimize/Parser/asdl.py	(original)
+++ python/branches/tlee-ast-optimize/Parser/asdl.py	Wed Jan 14 13:24:17 2009
@@ -167,7 +167,7 @@
         return Product(fields)
 
     def p_sum_0(self, (constructor,)):
-        " sum ::= constructor """
+        " sum ::= constructor "
         return [constructor]
 
     def p_sum_1(self, (constructor, _, sum)):

Modified: python/branches/tlee-ast-optimize/Parser/printgrammar.c
==============================================================================
--- python/branches/tlee-ast-optimize/Parser/printgrammar.c	(original)
+++ python/branches/tlee-ast-optimize/Parser/printgrammar.c	Wed Jan 14 13:24:17 2009
@@ -16,6 +16,7 @@
 	fprintf(fp, "/* Generated by Parser/pgen */\n\n");
 	fprintf(fp, "#include \"pgenheaders.h\"\n");
 	fprintf(fp, "#include \"grammar.h\"\n");
+	fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n");
 	printdfas(g, fp);
 	printlabels(g, fp);
 	fprintf(fp, "grammar _PyParser_Grammar = {\n");

Modified: python/branches/tlee-ast-optimize/Python/ast.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/ast.c	(original)
+++ python/branches/tlee-ast-optimize/Python/ast.c	Wed Jan 14 13:24:17 2009
@@ -3184,6 +3184,7 @@
         int imflag;
 #endif
 
+        assert(s != NULL);
         errno = 0;
         end = s + strlen(s) - 1;
 #ifndef WITHOUT_COMPLEX

Modified: python/branches/tlee-ast-optimize/Python/ceval.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/ceval.c	(original)
+++ python/branches/tlee-ast-optimize/Python/ceval.c	Wed Jan 14 13:24:17 2009
@@ -213,6 +213,7 @@
 #include "pythread.h"
 
 static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */
+static PyThread_type_lock pending_lock = 0; /* for pending calls */
 static long main_thread = 0;
 
 int
@@ -284,6 +285,7 @@
 	  adding a new function to each thread_*.h.  Instead, just
 	  create a new lock and waste a little bit of memory */
 	interpreter_lock = PyThread_allocate_lock();
+	pending_lock = PyThread_allocate_lock();
 	PyThread_acquire_lock(interpreter_lock, 1);
 	main_thread = PyThread_get_thread_ident();
 
@@ -356,19 +358,145 @@
 #ifdef WITH_THREAD
    Any thread can schedule pending calls, but only the main thread
    will execute them.
+   There is no facility to schedule calls to a particular thread, but
+   that should be easy to change, should that ever be required.  In
+   that case, the static variables here should go into the python
+   threadstate.
 #endif
+*/
+
+#ifdef WITH_THREAD
+
+/* The WITH_THREAD implementation is thread-safe.  It allows
+   scheduling to be made from any thread, and even from an executing
+   callback.
+ */
+
+#define NPENDINGCALLS 32
+static struct {
+	int (*func)(void *);
+	void *arg;
+} pendingcalls[NPENDINGCALLS];
+static int pendingfirst = 0;
+static int pendinglast = 0;
+static volatile int pendingcalls_to_do = 1; /* trigger initialization of lock */
+static char pendingbusy = 0;
+
+int
+Py_AddPendingCall(int (*func)(void *), void *arg)
+{
+	int i, j, result=0;
+	PyThread_type_lock lock = pending_lock;
+	
+	/* try a few times for the lock.  Since this mechanism is used
+	 * for signal handling (on the main thread), there is a (slim)
+	 * chance that a signal is delivered on the same thread while we
+	 * hold the lock during the Py_MakePendingCalls() function.
+	 * This avoids a deadlock in that case.
+	 * Note that signals can be delivered on any thread.  In particular,
+	 * on Windows, a SIGINT is delivered on a system-created worker
+	 * thread.
+	 * We also check for lock being NULL, in the unlikely case that
+	 * this function is called before any bytecode evaluation takes place.
+	 */
+	if (lock != NULL) {
+		for (i = 0; i<100; i++) {
+			if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
+				break;
+		}
+		if (i == 100)
+			return -1;
+	}
+
+	i = pendinglast;
+	j = (i + 1) % NPENDINGCALLS;
+	if (j == pendingfirst) {
+		result = -1; /* Queue full */
+	} else {
+		pendingcalls[i].func = func;
+		pendingcalls[i].arg = arg;
+		pendinglast = j;
+	}
+	/* signal main loop */
+	_Py_Ticker = 0;
+	pendingcalls_to_do = 1;
+	if (lock != NULL)
+		PyThread_release_lock(lock);
+	return result;
+}
+
+int
+Py_MakePendingCalls(void)
+{
+	int i;
+	int r = 0;
+
+	if (!pending_lock) {
+		/* initial allocation of the lock */
+		pending_lock = PyThread_allocate_lock();
+		if (pending_lock == NULL)
+			return -1;
+	}
 
-   XXX WARNING!  ASYNCHRONOUSLY EXECUTING CODE!
+	/* only service pending calls on main thread */
+	if (main_thread && PyThread_get_thread_ident() != main_thread)
+		return 0; 
+	/* don't perform recursive pending calls */
+	if (pendingbusy)
+		return 0;
+	pendingbusy = 1;
+	/* perform a bounded number of calls, in case of recursion */
+	for (i=0; i<NPENDINGCALLS; i++) {
+		int j;  
+		int (*func)(void *);
+		void *arg;
+		
+		/* pop one item off the queue while holding the lock */
+		PyThread_acquire_lock(pending_lock, WAIT_LOCK);
+		j = pendingfirst;
+		if (j == pendinglast) {
+			func = NULL; /* Queue empty */
+		} else {
+			func = pendingcalls[j].func;
+			arg = pendingcalls[j].arg;
+			pendingfirst = (j + 1) % NPENDINGCALLS;
+		}
+		pendingcalls_to_do = pendingfirst != pendinglast;
+		PyThread_release_lock(pending_lock);
+		/* having released the lock, perform the callback */
+		if (func == NULL)
+			break;
+		r = func(arg);
+		if (r)
+			break;
+	}
+	pendingbusy = 0;
+	return r;
+}
+
+#else /* if ! defined WITH_THREAD */
+
+/*
+   WARNING!  ASYNCHRONOUSLY EXECUTING CODE!
+   This code is used for signal handling in python that isn't built
+   with WITH_THREAD.
+   Don't use this implementation when Py_AddPendingCalls() can happen
+   on a different thread!
+ 
    There are two possible race conditions:
-   (1) nested asynchronous registry calls;
-   (2) registry calls made while pending calls are being processed.
-   While (1) is very unlikely, (2) is a real possibility.
+   (1) nested asynchronous calls to Py_AddPendingCall()
+   (2) AddPendingCall() calls made while pending calls are being processed.
+   
+   (1) is very unlikely because typically signal delivery
+   is blocked during signal handling.  So it should be impossible.
+   (2) is a real possibility.
    The current code is safe against (2), but not against (1).
    The safety against (2) is derived from the fact that only one
-   thread (the main thread) ever takes things out of the queue.
-
-   XXX Darn!  With the advent of thread state, we should have an array
-   of pending calls per thread in the thread state!  Later...
+   thread is present, interrupted by signals, and that the critical
+   section is protected with the "busy" variable.  On Windows, which
+   delivers SIGINT on a system thread, this does not hold and therefore
+   Windows really shouldn't use this version.
+   The two threads could theoretically wiggle around the "busy" variable.
 */
 
 #define NPENDINGCALLS 32
@@ -378,7 +506,7 @@
 } pendingcalls[NPENDINGCALLS];
 static volatile int pendingfirst = 0;
 static volatile int pendinglast = 0;
-static volatile int things_to_do = 0;
+static volatile int pendingcalls_to_do = 0;
 
 int
 Py_AddPendingCall(int (*func)(void *), void *arg)
@@ -386,8 +514,6 @@
 	static volatile int busy = 0;
 	int i, j;
 	/* XXX Begin critical section */
-	/* XXX If you want this to be safe against nested
-	   XXX asynchronous calls, you'll have to work harder! */
 	if (busy)
 		return -1;
 	busy = 1;
@@ -402,7 +528,7 @@
 	pendinglast = j;
 
 	_Py_Ticker = 0;
-	things_to_do = 1; /* Signal main loop */
+	pendingcalls_to_do = 1; /* Signal main loop */
 	busy = 0;
 	/* XXX End critical section */
 	return 0;
@@ -412,14 +538,10 @@
 Py_MakePendingCalls(void)
 {
 	static int busy = 0;
-#ifdef WITH_THREAD
-	if (main_thread && PyThread_get_thread_ident() != main_thread)
-		return 0;
-#endif
 	if (busy)
 		return 0;
 	busy = 1;
-	things_to_do = 0;
+	pendingcalls_to_do = 0;
 	for (;;) {
 		int i;
 		int (*func)(void *);
@@ -432,7 +554,7 @@
 		pendingfirst = (i + 1) % NPENDINGCALLS;
 		if (func(arg) < 0) {
 			busy = 0;
-			things_to_do = 1; /* We're not done yet */
+			pendingcalls_to_do = 1; /* We're not done yet */
 			return -1;
 		}
 	}
@@ -440,6 +562,8 @@
 	return 0;
 }
 
+#endif /* WITH_THREAD */
+
 
 /* The interpreter's recursion limit */
 
@@ -504,10 +628,17 @@
 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
 static int unpack_iterable(PyObject *, int, PyObject **);
 
+/* Records whether tracing is on for any thread.  Counts the number of
+   threads for which tstate->c_tracefunc is non-NULL, so if the value
+   is 0, we know we don't have to check this thread's c_tracefunc.
+   This speeds up the if statement in PyEval_EvalFrameEx() after
+   fast_next_opcode*/
+static int _Py_TracingPossible = 0;
+
 /* for manipulating the thread switch and periodic "stuff" - used to be
    per thread, now just a pair o' globals */
 int _Py_CheckInterval = 100;
-volatile int _Py_Ticker = 100;
+volatile int _Py_Ticker = 0; /* so that we hit a "tick" first thing */
 
 PyObject *
 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
@@ -825,7 +956,7 @@
 		/* Do periodic things.  Doing this every time through
 		   the loop would add too much overhead, so we do it
 		   only every Nth instruction.  We also do it if
-		   ``things_to_do'' is set, i.e. when an asynchronous
+		   ``pendingcalls_to_do'' is set, i.e. when an asynchronous
 		   event needs attention (e.g. a signal handler or
 		   async I/O handler); see Py_AddPendingCall() and
 		   Py_MakePendingCalls() above. */
@@ -841,12 +972,12 @@
 #ifdef WITH_TSC
 			ticked = 1;
 #endif
-			if (things_to_do) {
+			if (pendingcalls_to_do) {
 				if (Py_MakePendingCalls() < 0) {
 					why = WHY_EXCEPTION;
 					goto on_error;
 				}
-				if (things_to_do)
+				if (pendingcalls_to_do)
 					/* MakePendingCalls() didn't succeed.
 					   Force early re-execution of this
 					   "periodic" code, possibly after
@@ -886,7 +1017,8 @@
 
 		/* line-by-line tracing support */
 
-		if (tstate->c_tracefunc != NULL && !tstate->tracing) {
+		if (_Py_TracingPossible &&
+		    tstate->c_tracefunc != NULL && !tstate->tracing) {
 			/* see maybe_call_line_trace
 			   for expository comments */
 			f->f_stacktop = stack_pointer;
@@ -1041,6 +1173,7 @@
 			}
 			Py_FatalError("invalid argument to DUP_TOPX"
 				      " (bytecode corruption?)");
+			/* Never returns, so don't bother to set why. */
 			break;
 
 		case UNARY_POSITIVE:
@@ -1285,9 +1418,8 @@
 
 		case LIST_APPEND:
 			w = POP();
-			v = POP();
+			v = stack_pointer[-oparg];
 			err = PyList_Append(v, w);
-			Py_DECREF(v);
 			Py_DECREF(w);
 			if (err == 0) {
 				PREDICT(JUMP_ABSOLUTE);
@@ -1634,9 +1766,11 @@
 		case PRINT_NEWLINE:
 			if (stream == NULL || stream == Py_None) {
 				w = PySys_GetObject("stdout");
-				if (w == NULL)
+				if (w == NULL) {
 					PyErr_SetString(PyExc_RuntimeError,
 							"lost sys.stdout");
+					why = WHY_EXCEPTION;
+				}
 			}
 			if (w != NULL) {
 				/* w.write() may replace sys.stdout, so we
@@ -1862,6 +1996,7 @@
 				PyErr_Format(PyExc_SystemError,
 					     "no locals when loading %s",
 					     PyObject_REPR(w));
+				why = WHY_EXCEPTION;
 				break;
 			}
 			if (PyDict_CheckExact(v)) {
@@ -2337,11 +2472,20 @@
 			/* XXX Not the fastest way to call it... */
 			x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
 							 NULL);
-			if (x == NULL) {
-				Py_DECREF(exit_func);
+			Py_DECREF(exit_func);
+			if (x == NULL)
 				break; /* Go to error exit */
-			}
-			if (u != Py_None && PyObject_IsTrue(x)) {
+
+			if (u != Py_None)
+				err = PyObject_IsTrue(x);
+			else
+				err = 0;
+			Py_DECREF(x);
+
+			if (err < 0)
+				break; /* Go to error exit */
+			else if (err > 0) {
+				err = 0;
 				/* There was an exception and a true return */
 				STACKADJ(-2);
 				Py_INCREF(Py_None);
@@ -2353,8 +2497,6 @@
 				/* The stack was rearranged to remove EXIT
 				   above. Let END_FINALLY do its thing */
 			}
-			Py_DECREF(x);
-			Py_DECREF(exit_func);
 			PREDICT(END_FINALLY);
 			break;
 		}
@@ -2451,7 +2593,10 @@
 			Py_DECREF(v);
 			if (x != NULL) {
 				v = POP();
-				err = PyFunction_SetClosure(x, v);
+				if (PyFunction_SetClosure(x, v) != 0) {
+					/* Can't happen unless bytecode is corrupt. */
+					why = WHY_EXCEPTION;
+				}
 				Py_DECREF(v);
 			}
 			if (x != NULL && oparg > 0) {
@@ -2465,7 +2610,11 @@
 					w = POP();
 					PyTuple_SET_ITEM(v, oparg, w);
 				}
-				err = PyFunction_SetDefaults(x, v);
+				if (PyFunction_SetDefaults(x, v) != 0) {
+					/* Can't happen unless
+                                           PyFunction_SetDefaults changes. */
+					why = WHY_EXCEPTION;
+				}
 				Py_DECREF(v);
 			}
 			PUSH(x);
@@ -3414,6 +3563,7 @@
 {
 	PyThreadState *tstate = PyThreadState_GET();
 	PyObject *temp = tstate->c_traceobj;
+	_Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
 	Py_XINCREF(arg);
 	tstate->c_tracefunc = NULL;
 	tstate->c_traceobj = NULL;

Modified: python/branches/tlee-ast-optimize/Python/compile.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/compile.c	(original)
+++ python/branches/tlee-ast-optimize/Python/compile.c	Wed Jan 14 13:24:17 2009
@@ -739,7 +739,7 @@
 			return 0;
 
 		case LIST_APPEND:
-			return -2;
+			return -1;
 
 		case BINARY_POWER:
 		case BINARY_MULTIPLY:
@@ -1589,7 +1589,12 @@
 	
 	c->u->u_argcount = asdl_seq_LEN(args->args);
 	VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
-	ADDOP_IN_SCOPE(c, RETURN_VALUE);
+	if (c->u->u_ste->ste_generator) {
+		ADDOP_IN_SCOPE(c, POP_TOP);
+	}
+	else {
+		ADDOP_IN_SCOPE(c, RETURN_VALUE);
+	}
 	co = assemble(c, 1);
 	compiler_exit_scope(c);
 	if (co == NULL)
@@ -2654,9 +2659,8 @@
 }
 
 static int
-compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
-			    asdl_seq *generators, int gen_index, 
-			    expr_ty elt)
+compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
+			    int gen_index, expr_ty elt)
 {
 	/* generate code for the iterator, then each of the ifs,
 	   and then write to the element */
@@ -2693,16 +2697,13 @@
 	} 
 
 	if (++gen_index < asdl_seq_LEN(generators))
-	    if (!compiler_listcomp_generator(c, tmpname, 
-					     generators, gen_index, elt))
+	    if (!compiler_listcomp_generator(c, generators, gen_index, elt))
 		return 0;
 
 	/* only append after the last for generator */
 	if (gen_index >= asdl_seq_LEN(generators)) {
-	    if (!compiler_nameop(c, tmpname, Load))
-		return 0;
 	    VISIT(c, expr, elt);
-	    ADDOP(c, LIST_APPEND);
+	    ADDOP_I(c, LIST_APPEND, gen_index+1);
 
 	    compiler_use_next_block(c, skip);
 	}
@@ -2714,10 +2715,6 @@
 	} 
 	ADDOP_JABS(c, JUMP_ABSOLUTE, start);
 	compiler_use_next_block(c, anchor);
-	/* delete the temporary list name added to locals */
-	if (gen_index == 1)
-	    if (!compiler_nameop(c, tmpname, Del))
-		return 0;
 	
 	return 1;
 }
@@ -2725,21 +2722,10 @@
 static int
 compiler_listcomp(struct compiler *c, expr_ty e)
 {
-	identifier tmp;
-	int rc = 0;
-	asdl_seq *generators = e->v.ListComp.generators;
-
 	assert(e->kind == ListComp_kind);
-	tmp = compiler_new_tmpname(c);
-	if (!tmp)
-		return 0;
 	ADDOP_I(c, BUILD_LIST, 0);
-	ADDOP(c, DUP_TOP);
-	if (compiler_nameop(c, tmp, Store))
-	    rc = compiler_listcomp_generator(c, tmp, generators, 0, 
-					     e->v.ListComp.elt);
-	Py_DECREF(tmp);
-	return rc;
+	return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
+					   e->v.ListComp.elt);
 }
 
 static int

Modified: python/branches/tlee-ast-optimize/Python/getargs.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/getargs.c	(original)
+++ python/branches/tlee-ast-optimize/Python/getargs.c	Wed Jan 14 13:24:17 2009
@@ -1601,7 +1601,7 @@
 		}
 	}
 
-	if (!IS_END_OF_FORMAT(*format)) {
+	if (!IS_END_OF_FORMAT(*format) && *format != '|') {
 		PyErr_Format(PyExc_RuntimeError,
 			"more argument specifiers than keyword list entries "
 			"(remaining format:'%s')", format);

Modified: python/branches/tlee-ast-optimize/Python/getcopyright.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/getcopyright.c	(original)
+++ python/branches/tlee-ast-optimize/Python/getcopyright.c	Wed Jan 14 13:24:17 2009
@@ -4,7 +4,7 @@
 
 static char cprt[] = 
 "\
-Copyright (c) 2001-2008 Python Software Foundation.\n\
+Copyright (c) 2001-2009 Python Software Foundation.\n\
 All Rights Reserved.\n\
 \n\
 Copyright (c) 2000 BeOpen.com.\n\

Deleted: python/branches/tlee-ast-optimize/Python/getmtime.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/getmtime.c	Wed Jan 14 13:24:17 2009
+++ (empty file)
@@ -1,26 +0,0 @@
-
-/* Subroutine to get the last modification time of a file */
-
-/* (A separate file because this may be OS dependent) */
-
-#include "Python.h"
-#include "pyconfig.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-time_t
-PyOS_GetLastModificationTime(char *path, FILE *fp)
-{
-	struct stat st;
-	if (fstat(fileno(fp), &st) != 0)
-		return -1;
-	else
-		return st.st_mtime;
-}
-
-#ifdef __cplusplus
-}
-#endif
-

Modified: python/branches/tlee-ast-optimize/Python/graminit.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/graminit.c	(original)
+++ python/branches/tlee-ast-optimize/Python/graminit.c	Wed Jan 14 13:24:17 2009
@@ -2,6 +2,7 @@
 
 #include "pgenheaders.h"
 #include "grammar.h"
+PyAPI_DATA(grammar) _PyParser_Grammar;
 static arc arcs_0_0[3] = {
 	{2, 1},
 	{3, 1},

Modified: python/branches/tlee-ast-optimize/Python/import.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/import.c	(original)
+++ python/branches/tlee-ast-optimize/Python/import.c	Wed Jan 14 13:24:17 2009
@@ -29,8 +29,6 @@
 typedef unsigned short mode_t;
 #endif
 
-extern time_t PyOS_GetLastModificationTime(char *, FILE *);
-						/* In getmtime.c */
 
 /* Magic word to reject .pyc files generated by other Python versions.
    It should change for each incompatible change to the bytecode.
@@ -75,9 +73,10 @@
        Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
        Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
        Python 2.6a1: 62161 (WITH_CLEANUP optimization)
+       Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
 .
 */
-#define MAGIC (62161 | ((long)'\r'<<16) | ((long)'\n'<<24))
+#define MAGIC (62171 | ((long)'\r'<<16) | ((long)'\n'<<24))
 
 /* Magic word as global; note that _PyImport_Init() can change the
    value of this global to accommodate for alterations of how the
@@ -930,6 +929,49 @@
 		PySys_WriteStderr("# wrote %s\n", cpathname);
 }
 
+static void
+update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
+{
+	PyObject *constants, *tmp;
+	Py_ssize_t i, n;
+
+	if (!_PyString_Eq(co->co_filename, oldname))
+		return;
+
+	tmp = co->co_filename;
+	co->co_filename = newname;
+	Py_INCREF(co->co_filename);
+	Py_DECREF(tmp);
+
+	constants = co->co_consts;
+	n = PyTuple_GET_SIZE(constants);
+	for (i = 0; i < n; i++) {
+		tmp = PyTuple_GET_ITEM(constants, i);
+		if (PyCode_Check(tmp))
+			update_code_filenames((PyCodeObject *)tmp,
+					      oldname, newname);
+	}
+}
+
+static int
+update_compiled_module(PyCodeObject *co, char *pathname)
+{
+	PyObject *oldname, *newname;
+
+	if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)
+		return 0;
+
+	newname = PyString_FromString(pathname);
+	if (newname == NULL)
+		return -1;
+
+	oldname = co->co_filename;
+	Py_INCREF(oldname);
+	update_code_filenames(co, oldname, newname);
+	Py_DECREF(oldname);
+	Py_DECREF(newname);
+	return 1;
+}
 
 /* Load a source module from a given file and return its module
    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
@@ -970,6 +1012,8 @@
 		fclose(fpc);
 		if (co == NULL)
 			return NULL;
+		if (update_compiled_module(co, pathname) < 0)
+			return NULL;
 		if (Py_VerboseFlag)
 			PySys_WriteStderr("import %s # precompiled from %s\n",
 				name, cpathname);
@@ -3174,24 +3218,11 @@
 		return -1;
 	} else {
 #ifndef RISCOS
+#ifndef MS_WINDOWS
 		struct stat statbuf;
 		int rv;
 
 		rv = stat(path, &statbuf);
-#ifdef MS_WINDOWS
-		/* MS Windows stat() chokes on paths like C:\path\. Try to
-		 * recover *one* time by stripping off a trailing slash or
-		 * backslash. http://bugs.python.org/issue1293
- 		 */
-		if (rv != 0 && pathlen <= MAXPATHLEN &&
-		    (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
-			char mangled[MAXPATHLEN+1];
-
-			strcpy(mangled, path);
-			mangled[pathlen-1] = '\0';
-			rv = stat(mangled, &statbuf);
-		}
-#endif
 		if (rv == 0) {
 			/* it exists */
 			if (S_ISDIR(statbuf.st_mode)) {
@@ -3201,7 +3232,24 @@
 				return -1;
 			}
 		}
-#else
+#else /* MS_WINDOWS */
+		DWORD rv;
+		/* see issue1293 and issue3677:
+		 * stat() on Windows doesn't recognise paths like
+		 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
+		 */
+		rv = GetFileAttributesA(path);
+		if (rv != INVALID_FILE_ATTRIBUTES) {
+			/* it exists */
+			if (rv & FILE_ATTRIBUTE_DIRECTORY) {
+				/* it's a directory */
+				PyErr_SetString(PyExc_ImportError,
+						"existing directory");
+				return -1;
+			}
+		}
+#endif
+#else /* RISCOS */
 		if (object_exists(path)) {
 			/* it exists */
 			if (isdir(path)) {

Modified: python/branches/tlee-ast-optimize/Python/pythonrun.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/pythonrun.c	(original)
+++ python/branches/tlee-ast-optimize/Python/pythonrun.c	Wed Jan 14 13:24:17 2009
@@ -22,6 +22,10 @@
 #include <signal.h>
 #endif
 
+#ifdef MS_WINDOWS
+#include "malloc.h" /* for alloca */
+#endif
+
 #ifdef HAVE_LANGINFO_H
 #include <locale.h>
 #include <langinfo.h>
@@ -1670,9 +1674,21 @@
 {
 	fprintf(stderr, "Fatal Python error: %s\n", msg);
 #ifdef MS_WINDOWS
-	OutputDebugString("Fatal Python error: ");
-	OutputDebugString(msg);
-	OutputDebugString("\n");
+	{
+		size_t len = strlen(msg);
+		WCHAR* buffer;
+		size_t i;
+
+		/* Convert the message to wchar_t. This uses a simple one-to-one
+		conversion, assuming that the this error message actually uses ASCII
+		only. If this ceases to be true, we will have to convert. */
+		buffer = alloca( (len+1) * (sizeof *buffer));
+		for( i=0; i<=len; ++i)
+			buffer[i] = msg[i];
+		OutputDebugStringW(L"Fatal Python error: ");
+		OutputDebugStringW(buffer);
+		OutputDebugStringW(L"\n");
+	}
 #ifdef _DEBUG
 	DebugBreak();
 #endif

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	Wed Jan 14 13:24:17 2009
@@ -1296,8 +1296,13 @@
 		PyDict_SetItemString(sysdict, key, v);	\
 	Py_XDECREF(v)
 
+	/* Check that stdin is not a directory
+	Using shell redirection, you can redirect stdin to a directory,
+	crashing the Python interpreter. Catch this common mistake here
+	and output a useful error message. Note that under MS Windows,
+	the shell already prevents that. */
+#if !defined(MS_WINDOWS)
 	{
-		/* XXX: does this work on Win/Win64? (see posix_fstat) */
 		struct stat sb;
 		if (fstat(fileno(stdin), &sb) == 0 &&
 		    S_ISDIR(sb.st_mode)) {
@@ -1307,6 +1312,7 @@
 			exit(EXIT_FAILURE);
 		}
 	}
+#endif
 
 	/* Closing the standard FILE* if sys.std* goes aways causes problems
 	 * for embedded Python usages. Closing them when somebody explicitly
@@ -1526,7 +1532,7 @@
 {
 #if defined(HAVE_REALPATH)
 	char fullpath[MAXPATHLEN];
-#elif defined(MS_WINDOWS)
+#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
 	char fullpath[MAX_PATH];
 #endif
 	PyObject *av = makeargvobject(argc, argv);
@@ -1571,7 +1577,10 @@
 #if SEP == '\\' /* Special case for MS filename syntax */
 		if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
 			char *q;
-#ifdef MS_WINDOWS
+#if defined(MS_WINDOWS) && !defined(MS_WINCE)
+			/* This code here replaces the first element in argv with the full
+			path that it represents. Under CE, there are no relative paths so
+			the argument must be the full path anyway. */
 			char *ptemp;
 			if (GetFullPathName(argv0,
 					   sizeof(fullpath),

Modified: python/branches/tlee-ast-optimize/Python/thread.c
==============================================================================
--- python/branches/tlee-ast-optimize/Python/thread.c	(original)
+++ python/branches/tlee-ast-optimize/Python/thread.c	Wed Jan 14 13:24:17 2009
@@ -137,10 +137,6 @@
 #include "thread_beos.h"
 #endif
 
-#ifdef WINCE_THREADS
-#include "thread_wince.h"
-#endif
-
 #ifdef PLAN9_THREADS
 #include "thread_plan9.h"
 #endif

Modified: python/branches/tlee-ast-optimize/Python/thread_nt.h
==============================================================================
--- python/branches/tlee-ast-optimize/Python/thread_nt.h	(original)
+++ python/branches/tlee-ast-optimize/Python/thread_nt.h	Wed Jan 14 13:24:17 2009
@@ -104,20 +104,21 @@
 typedef struct {
 	void (*func)(void*);
 	void *arg;
-	long id;
-	HANDLE done;
 } callobj;
 
-static int
+/* thunker to call adapt between the function type used by the system's
+thread start function and the internally used one. */
+#if defined(MS_WINCE)
+static DWORD WINAPI
+#else
+static unsigned __stdcall
+#endif
 bootstrap(void *call)
 {
 	callobj *obj = (callobj*)call;
-	/* copy callobj since other thread might free it before we're done */
 	void (*func)(void*) = obj->func;
 	void *arg = obj->arg;
-
-	obj->id = PyThread_get_thread_ident();
-	ReleaseSemaphore(obj->done, 1, NULL);
+	HeapFree(GetProcessHeap(), 0, obj);
 	func(arg);
 	return 0;
 }
@@ -125,42 +126,55 @@
 long
 PyThread_start_new_thread(void (*func)(void *), void *arg)
 {
-	Py_uintptr_t rv;
-	callobj obj;
-
+	HANDLE hThread;
+	unsigned threadID;
+	callobj *obj;
+	
 	dprintf(("%ld: PyThread_start_new_thread called\n",
 		 PyThread_get_thread_ident()));
 	if (!initialized)
 		PyThread_init_thread();
 
-	obj.id = -1;	/* guilty until proved innocent */
-	obj.func = func;
-	obj.arg = arg;
-	obj.done = CreateSemaphore(NULL, 0, 1, NULL);
-	if (obj.done == NULL)
+	obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj));
+	if (!obj)
 		return -1;
-
-	rv = _beginthread(bootstrap,
+	obj->func = func;
+	obj->arg = arg;
+#if defined(MS_WINCE)
+	hThread = CreateThread(NULL,
+	                       Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T),
+	                       bootstrap, obj, 0, &threadID);
+#else
+	hThread = (HANDLE)_beginthreadex(0,
 			  Py_SAFE_DOWNCAST(_pythread_stacksize,
-					   Py_ssize_t, int),
-			  &obj);
-	if (rv == (Py_uintptr_t)-1) {
+					   Py_ssize_t, unsigned int),
+			  bootstrap, obj,
+			  0, &threadID);
+#endif
+	if (hThread == 0) {
+#if defined(MS_WINCE)
+		/* Save error in variable, to prevent PyThread_get_thread_ident
+		   from clobbering it. */
+		unsigned e = GetLastError();
+		dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n",
+		         PyThread_get_thread_ident(), e));
+#else
 		/* I've seen errno == EAGAIN here, which means "there are
 		 * too many threads".
 		 */
-		dprintf(("%ld: PyThread_start_new_thread failed: %p errno %d\n",
-		         PyThread_get_thread_ident(), (void*)rv, errno));
-		obj.id = -1;
+		int e = errno;
+		dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n",
+		         PyThread_get_thread_ident(), e));
+#endif
+		threadID = (unsigned)-1;
+		HeapFree(GetProcessHeap(), 0, obj);
 	}
 	else {
 		dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n",
-		         PyThread_get_thread_ident(), (void*)rv));
-		/* wait for thread to initialize, so we can get its id */
-		WaitForSingleObject(obj.done, INFINITE);
-		assert(obj.id != -1);
+		         PyThread_get_thread_ident(), (void*)hThread));
+		CloseHandle(hThread);
 	}
-	CloseHandle((HANDLE)obj.done);
-	return obj.id;
+	return (long) threadID;
 }
 
 /*
@@ -176,52 +190,26 @@
 	return GetCurrentThreadId();
 }
 
-static void
-do_PyThread_exit_thread(int no_cleanup)
-{
-	dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
-	if (!initialized)
-		if (no_cleanup)
-			_exit(0);
-		else
-			exit(0);
-	_endthread();
-}
-
 void
 PyThread_exit_thread(void)
 {
-	do_PyThread_exit_thread(0);
-}
-
-void
-PyThread__exit_thread(void)
-{
-	do_PyThread_exit_thread(1);
-}
-
-#ifndef NO_EXIT_PROG
-static void
-do_PyThread_exit_prog(int status, int no_cleanup)
-{
-	dprintf(("PyThread_exit_prog(%d) called\n", status));
+	dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
 	if (!initialized)
-		if (no_cleanup)
-			_exit(status);
-		else
-			exit(status);
+		exit(0);
+#if defined(MS_WINCE)
+	ExitThread(0);
+#else
+	_endthreadex(0);
+#endif
 }
 
+#ifndef NO_EXIT_PROG
 void
 PyThread_exit_prog(int status)
 {
-	do_PyThread_exit_prog(status, 0);
-}
-
-void
-PyThread__exit_prog(int status)
-{
-	do_PyThread_exit_prog(status, 1);
+	dprintf(("PyThread_exit_prog(%d) called\n", status));
+	if (!initialized)
+		exit(status);
 }
 #endif /* NO_EXIT_PROG */
 
@@ -309,3 +297,73 @@
 }
 
 #define THREAD_SET_STACKSIZE(x)	_pythread_nt_set_stacksize(x)
+
+
+/* use native Windows TLS functions */
+#define Py_HAVE_NATIVE_TLS
+
+#ifdef Py_HAVE_NATIVE_TLS
+int
+PyThread_create_key(void)
+{
+	return (int) TlsAlloc();
+}
+
+void
+PyThread_delete_key(int key)
+{
+	TlsFree(key);
+}
+
+/* We must be careful to emulate the strange semantics implemented in thread.c,
+ * where the value is only set if it hasn't been set before.
+ */
+int
+PyThread_set_key_value(int key, void *value)
+{
+	BOOL ok;
+	void *oldvalue;
+
+	assert(value != NULL);
+	oldvalue = TlsGetValue(key);
+	if (oldvalue != NULL)
+		/* ignore value if already set */
+		return 0;
+	ok = TlsSetValue(key, value);
+	if (!ok)
+		return -1;
+	return 0;
+}
+
+void *
+PyThread_get_key_value(int key)
+{
+	/* because TLS is used in the Py_END_ALLOW_THREAD macro,
+	 * it is necessary to preserve the windows error state, because
+	 * it is assumed to be preserved across the call to the macro.
+	 * Ideally, the macro should be fixed, but it is simpler to
+	 * do it here.
+	 */
+	DWORD error = GetLastError();
+	void *result = TlsGetValue(key);
+	SetLastError(error);
+	return result;
+}
+
+void
+PyThread_delete_key_value(int key)
+{
+	/* NULL is used as "key missing", and it is also the default
+	 * given by TlsGetValue() if nothing has been set yet.
+	 */
+	TlsSetValue(key, NULL);
+}
+
+/* reinitialization of TLS is not necessary after fork when using
+ * the native TLS functions.  And forking isn't supported on Windows either.
+ */
+void
+PyThread_ReInitTLS(void)
+{}
+
+#endif

Modified: python/branches/tlee-ast-optimize/README
==============================================================================
--- python/branches/tlee-ast-optimize/README	(original)
+++ python/branches/tlee-ast-optimize/README	Wed Jan 14 13:24:17 2009
@@ -1,7 +1,7 @@
-This is Python version 2.6
-==========================
+This is Python version 2.7 alpha 0
+==================================
 
-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
 Python Software Foundation.
 All rights reserved.
 

Modified: python/branches/tlee-ast-optimize/RISCOS/Makefile
==============================================================================
--- python/branches/tlee-ast-optimize/RISCOS/Makefile	(original)
+++ python/branches/tlee-ast-optimize/RISCOS/Makefile	Wed Jan 14 13:24:17 2009
@@ -135,7 +135,6 @@
 OBJECTS_RISCOS = \
 	@.Python.o.dynload_riscos\
 	@.Python.o.getcwd_riscos\
-	@.Python.o.getmtime_riscos\
 	@.o.unixstuff
 
 

Deleted: python/branches/tlee-ast-optimize/RISCOS/Python/getmtime_riscos.c
==============================================================================
--- python/branches/tlee-ast-optimize/RISCOS/Python/getmtime_riscos.c	Wed Jan 14 13:24:17 2009
+++ (empty file)
@@ -1,20 +0,0 @@
-#include <stdio.h>
-
-#define __swi
-#include "oslib/osfile.h"
-
-long PyOS_GetLastModificationTime(char *path, FILE *fp)
-{
-  int obj;
-  bits load, exec, ftype;
-
-  if (xosfile_read_stamped_no_path(path, &obj, &load, &exec, 0, 0, &ftype)) return -1;
-  if (obj != osfile_IS_FILE) return -1;
-  if (ftype == osfile_TYPE_UNTYPED) return -1;
-
-  load &= 0xFF;
-  load -= 51;
-  if (exec < 1855548004U) load--;
-  exec -= 1855548004U;
-  return exec/100+42949672*load+(95*load)/100;
-}

Modified: python/branches/tlee-ast-optimize/Tools/msi/crtlicense.txt
==============================================================================
--- python/branches/tlee-ast-optimize/Tools/msi/crtlicense.txt	(original)
+++ python/branches/tlee-ast-optimize/Tools/msi/crtlicense.txt	Wed Jan 14 13:24:17 2009
@@ -26,7 +26,7 @@
 - alter any copyright, trademark or patent notice in Microsoft's
 Distributable Code;
 
-- use Microsoft’s trademarks in your programs’ names or in a way that
+- use Microsoft's trademarks in your programs' names or in a way that
 suggests your programs come from or are endorsed by Microsoft;
 
 - distribute Microsoft's Distributable Code to run on a platform other

Modified: python/branches/tlee-ast-optimize/Tools/msi/msi.py
==============================================================================
--- python/branches/tlee-ast-optimize/Tools/msi/msi.py	(original)
+++ python/branches/tlee-ast-optimize/Tools/msi/msi.py	Wed Jan 14 13:24:17 2009
@@ -116,6 +116,8 @@
 
 # Compute the name that Sphinx gives to the docfile
 docfile = ""
+if micro:
+    docfile = str(micro)
 if level < 0xf:
     docfile = '%x%s' % (level, serial)
 docfile = 'python%s%s%s.chm' % (major, minor, docfile)
@@ -1248,7 +1250,10 @@
                "[TARGETDIR]Doc\\"+docfile , "REGISTRY.doc"),
               ("Modules", -1, prefix+r"\Modules", "+", None, "REGISTRY"),
               ("AppPaths", -1, r"Software\Microsoft\Windows\CurrentVersion\App Paths\Python.exe",
-               "", r"[TARGETDIR]Python.exe", "REGISTRY.def")
+               "", r"[TARGETDIR]Python.exe", "REGISTRY.def"),
+              ("DisplayIcon", -1,
+               r"Software\Microsoft\Windows\CurrentVersion\Uninstall\%s" % product_code,
+               "DisplayIcon", "[TARGETDIR]python.exe", "REGISTRY.def")
               ])
     # Shortcuts, see "Shortcut Table"
     add_data(db, "Directory",

Modified: python/branches/tlee-ast-optimize/Tools/msi/uuids.py
==============================================================================
--- python/branches/tlee-ast-optimize/Tools/msi/uuids.py	(original)
+++ python/branches/tlee-ast-optimize/Tools/msi/uuids.py	Wed Jan 14 13:24:17 2009
@@ -47,4 +47,7 @@
     '2.6.121': '{bbd34464-ddeb-4028-99e5-f16c4a8fbdb3}', # 2.6c1
     '2.6.122': '{8f64787e-a023-4c60-bfee-25d3a3f592c6}', # 2.6c2
     '2.6.150': '{110eb5c4-e995-4cfb-ab80-a5f315bea9e8}', # 2.6.0
+    '2.6.1150':'{9cc89170-000b-457d-91f1-53691f85b223}', # 2.6.1
+    '2.6.2121':'{adac412b-b209-4c15-b6ab-dca1b6e47144}', # 2.6.2c1
+    '2.6.2150':'{24aab420-4e30-4496-9739-3e216f3de6ae}', # 2.6.2
 }

Modified: python/branches/tlee-ast-optimize/Tools/pybench/Lists.py
==============================================================================
--- python/branches/tlee-ast-optimize/Tools/pybench/Lists.py	(original)
+++ python/branches/tlee-ast-optimize/Tools/pybench/Lists.py	Wed Jan 14 13:24:17 2009
@@ -293,3 +293,58 @@
 
         for i in xrange(self.rounds):
             pass
+
+class SimpleListComprehensions(Test):
+
+    version = 2.0
+    operations = 6
+    rounds = 20000
+
+    def test(self):
+
+        n = range(10) * 10
+
+        for i in xrange(self.rounds):
+            l = [x for x in n]
+            l = [x for x in n if x]
+            l = [x for x in n if not x]
+
+            l = [x for x in n]
+            l = [x for x in n if x]
+            l = [x for x in n if not x]
+
+    def calibrate(self):
+
+        n = range(10) * 10
+
+        for i in xrange(self.rounds):
+            pass
+
+class NestedListComprehensions(Test):
+
+    version = 2.0
+    operations = 6
+    rounds = 20000
+
+    def test(self):
+
+        m = range(10)
+        n = range(10)
+
+        for i in xrange(self.rounds):
+            l = [x for x in n for y in m]
+            l = [y for x in n for y in m]
+
+            l = [x for x in n for y in m if y]
+            l = [y for x in n for y in m if x]
+
+            l = [x for x in n for y in m if not y]
+            l = [y for x in n for y in m if not x]
+
+    def calibrate(self):
+
+        m = range(10)
+        n = range(10)
+
+        for i in xrange(self.rounds):
+            pass

Modified: python/branches/tlee-ast-optimize/Tools/scripts/patchcheck.py
==============================================================================
--- python/branches/tlee-ast-optimize/Tools/scripts/patchcheck.py	(original)
+++ python/branches/tlee-ast-optimize/Tools/scripts/patchcheck.py	Wed Jan 14 13:24:17 2009
@@ -62,12 +62,12 @@
 @status("Misc/ACKS updated", modal=True)
 def credit_given(file_paths):
     """Check if Misc/ACKS has been changed."""
-    return True if 'Misc/ACKS' in file_paths else False
+    return 'Misc/ACKS' in file_paths
 
 @status("Misc/NEWS updated", modal=True)
 def reported_news(file_paths):
     """Check if Misc/NEWS has been changed."""
-    return True if 'Misc/NEWS' in file_paths else False
+    return 'Misc/NEWS' in file_paths
 
 
 def main():

Modified: python/branches/tlee-ast-optimize/configure
==============================================================================
--- python/branches/tlee-ast-optimize/configure	(original)
+++ python/branches/tlee-ast-optimize/configure	Wed Jan 14 13:24:17 2009
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.in Revision: 67227 .
+# From configure.in Revision: 68299 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.61 for python 2.7.
 #
@@ -2256,7 +2256,7 @@
 if test "${with_gcc+set}" = set; then
   withval=$with_gcc;
 	case $withval in
-	no)	CC=cc
+	no)	CC=${CC:-cc}
 		without_gcc=yes;;
 	yes)	CC=gcc
 		without_gcc=no;;
@@ -4139,6 +4139,12 @@
 	  BLDLIBRARY='-L. -lpython$(VERSION)'
 	  RUNSHARED=DLL_PATH=`pwd`:${DLL_PATH:-/atheos/sys/libs:/atheos/autolnk/lib}
 	  ;;
+    Darwin*)
+    	LDLIBRARY='libpython$(VERSION).dylib'
+	BLDLIBRARY='-L. -lpython$(VERSION)'
+	RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}'
+	;;
+
   esac
 else # shared is disabled
   case $ac_sys_system in
@@ -13003,6 +13009,7 @@
 { echo "$as_me:$LINENO: result: $SO" >&5
 echo "${ECHO_T}$SO" >&6; }
 
+
 cat >>confdefs.h <<_ACEOF
 #define SHLIB_EXT "$SO"
 _ACEOF
@@ -13403,7 +13410,7 @@
 fi
 	# Dynamic linking for HP-UX
 
-# only check for sem_ini if thread support is requested
+# only check for sem_init if thread support is requested
 if test "$with_threads" = "yes" -o -z "$with_threads"; then
     { echo "$as_me:$LINENO: checking for library containing sem_init" >&5
 echo $ECHO_N "checking for library containing sem_init... $ECHO_C" >&6; }
@@ -21516,6 +21523,94 @@
 LIBS_SAVE=$LIBS
 LIBS="$LIBS $LIBM"
 
+# Detect whether system arithmetic is subject to x87-style double
+# rounding issues.  The result of this test has little meaning on non
+# IEEE 754 platforms.  On IEEE 754, test should return 1 if rounding
+# mode is round-to-nearest and double rounding issues are present, and
+# 0 otherwise.  See http://bugs.python.org/issue2937 for more info.
+{ echo "$as_me:$LINENO: checking for x87-style double rounding" >&5
+echo $ECHO_N "checking for x87-style double rounding... $ECHO_C" >&6; }
+if test "${ac_cv_x87_double_rounding+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+
+if test "$cross_compiling" = yes; then
+  ac_cv_x87_double_rounding=no
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+#include <stdlib.h>
+#include <math.h>
+int main() {
+    volatile double x, y, z;
+    /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */
+    x = 0.99999999999999989; /* 1-2**-53 */
+    y = 1./x;
+    if (y != 1.)
+        exit(0);
+    /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */
+    x = 1e16;
+    y = 2.99999;
+    z = x + y;
+    if (z != 1e16+4.)
+        exit(0);
+    /* both tests show evidence of double rounding */
+    exit(1);
+}
+
+_ACEOF
+rm -f conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_x87_double_rounding=no
+else
+  echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_x87_double_rounding=yes
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+
+
+fi
+
+{ echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5
+echo "${ECHO_T}$ac_cv_x87_double_rounding" >&6; }
+if test "$ac_cv_x87_double_rounding" = yes
+then
+
+cat >>confdefs.h <<\_ACEOF
+#define X87_DOUBLE_ROUNDING 1
+_ACEOF
+
+fi
+
+
 # On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of
 # -0. on some architectures.
 { echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5
@@ -21593,7 +21688,14 @@
 fi
 
 
-for ac_func in hypot
+
+
+
+
+
+
+
+for ac_func in acosh asinh atanh copysign expm1 finite hypot log1p
 do
 as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
 { echo "$as_me:$LINENO: checking for $ac_func" >&5
@@ -21683,33 +21785,79 @@
 #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
 _ACEOF
 
-else
-  case " $LIBOBJS " in
-  *" $ac_func.$ac_objext "* ) ;;
-  *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext"
- ;;
-esac
-
 fi
 done
 
+{ echo "$as_me:$LINENO: checking whether isinf is declared" >&5
+echo $ECHO_N "checking whether isinf is declared... $ECHO_C" >&6; }
+if test "${ac_cv_have_decl_isinf+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <math.h>
 
+int
+main ()
+{
+#ifndef isinf
+  (void) isinf;
+#endif
 
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_have_decl_isinf=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
+	ac_cv_have_decl_isinf=no
+fi
 
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5
+echo "${ECHO_T}$ac_cv_have_decl_isinf" >&6; }
+if test $ac_cv_have_decl_isinf = yes; then
 
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ISINF 1
+_ACEOF
 
 
+else
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ISINF 0
+_ACEOF
 
 
-
-
-for ac_func in acosh asinh atanh copysign expm1 finite isinf isnan log1p
-do
-as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+fi
+{ echo "$as_me:$LINENO: checking whether isnan is declared" >&5
+echo $ECHO_N "checking whether isnan is declared... $ECHO_C" >&6; }
+if test "${ac_cv_have_decl_isnan+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -21718,53 +21866,94 @@
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
+#include <math.h>
 
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
+int
+main ()
+{
+#ifndef isnan
+  (void) isnan;
 #endif
 
-#undef $ac_func
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_have_decl_isnan=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
 
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
+	ac_cv_have_decl_isnan=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5
+echo "${ECHO_T}$ac_cv_have_decl_isnan" >&6; }
+if test $ac_cv_have_decl_isnan = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ISNAN 1
+_ACEOF
+
+
+else
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ISNAN 0
+_ACEOF
+
+
+fi
+{ echo "$as_me:$LINENO: checking whether isfinite is declared" >&5
+echo $ECHO_N "checking whether isfinite is declared... $ECHO_C" >&6; }
+if test "${ac_cv_have_decl_isfinite+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <math.h>
 
 int
 main ()
 {
-return $ac_func ();
+#ifndef isfinite
+  (void) isfinite;
+#endif
+
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try="$ac_link"
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
@@ -21773,29 +21962,34 @@
   (exit $ac_status); } && {
 	 test -z "$ac_c_werror_flag" ||
 	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=yes"
+       } && test -s conftest.$ac_objext; then
+  ac_cv_have_decl_isfinite=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-	eval "$as_ac_var=no"
+	ac_cv_have_decl_isfinite=no
 fi
 
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-ac_res=`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` = yes; then
+{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5
+echo "${ECHO_T}$ac_cv_have_decl_isfinite" >&6; }
+if test $ac_cv_have_decl_isfinite = yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ISFINITE 1
+_ACEOF
+
+
+else
   cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+#define HAVE_DECL_ISFINITE 0
 _ACEOF
 
+
 fi
-done
+
 
 
 LIBS=$LIBS_SAVE

Modified: python/branches/tlee-ast-optimize/configure.in
==============================================================================
--- python/branches/tlee-ast-optimize/configure.in	(original)
+++ python/branches/tlee-ast-optimize/configure.in	Wed Jan 14 13:24:17 2009
@@ -1,7 +1,7 @@
 dnl ***********************************************
 dnl * Please run autoreconf to test your changes! *
 dnl ***********************************************
-dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.63).
+dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.61).
 
 # Set VERSION so we only need to edit in one place (i.e., here)
 m4_define(PYTHON_VERSION, 2.7)
@@ -407,7 +407,7 @@
             AC_HELP_STRING(--without-gcc,never use gcc),
 [
 	case $withval in
-	no)	CC=cc
+	no)	CC=${CC:-cc}
 		without_gcc=yes;;
 	yes)	CC=gcc
 		without_gcc=no;;
@@ -737,6 +737,12 @@
 	  BLDLIBRARY='-L. -lpython$(VERSION)'
 	  RUNSHARED=DLL_PATH=`pwd`:${DLL_PATH:-/atheos/sys/libs:/atheos/autolnk/lib}
 	  ;;
+    Darwin*)
+    	LDLIBRARY='libpython$(VERSION).dylib'
+	BLDLIBRARY='-L. -lpython$(VERSION)'
+	RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}'
+	;;
+
   esac
 else # shared is disabled
   case $ac_sys_system in
@@ -1597,6 +1603,7 @@
 	sleep 10
 fi
 AC_MSG_RESULT($SO)
+
 AC_DEFINE_UNQUOTED(SHLIB_EXT, "$SO", [Define this to be extension of shared libraries (including the dot!).])
 # LDSHARED is the ld *command* used to create shared library
 # -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5
@@ -1844,7 +1851,7 @@
 AC_CHECK_LIB(dl, dlopen)	# Dynamic linking for SunOS/Solaris and SYSV
 AC_CHECK_LIB(dld, shl_load)	# Dynamic linking for HP-UX
 
-# only check for sem_ini if thread support is requested
+# only check for sem_init if thread support is requested
 if test "$with_threads" = "yes" -o -z "$with_threads"; then
     AC_SEARCH_LIBS(sem_init, pthread rt posix4) # 'Real Time' functions on Solaris
 						# posix4 on Solaris 2.6
@@ -3136,6 +3143,44 @@
 LIBS_SAVE=$LIBS
 LIBS="$LIBS $LIBM"
 
+# Detect whether system arithmetic is subject to x87-style double
+# rounding issues.  The result of this test has little meaning on non
+# IEEE 754 platforms.  On IEEE 754, test should return 1 if rounding
+# mode is round-to-nearest and double rounding issues are present, and
+# 0 otherwise.  See http://bugs.python.org/issue2937 for more info.
+AC_MSG_CHECKING(for x87-style double rounding)
+AC_CACHE_VAL(ac_cv_x87_double_rounding, [
+AC_TRY_RUN([
+#include <stdlib.h>
+#include <math.h>
+int main() {
+    volatile double x, y, z;
+    /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */
+    x = 0.99999999999999989; /* 1-2**-53 */
+    y = 1./x;
+    if (y != 1.)
+        exit(0);
+    /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */
+    x = 1e16;
+    y = 2.99999;
+    z = x + y;
+    if (z != 1e16+4.)
+        exit(0);
+    /* both tests show evidence of double rounding */
+    exit(1);
+}
+],
+ac_cv_x87_double_rounding=no,
+ac_cv_x87_double_rounding=yes,
+ac_cv_x87_double_rounding=no)])
+AC_MSG_RESULT($ac_cv_x87_double_rounding)
+if test "$ac_cv_x87_double_rounding" = yes
+then
+  AC_DEFINE(X87_DOUBLE_ROUNDING, 1,
+  [Define if arithmetic is subject to x87-style double rounding issue])
+fi
+
+
 # On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of
 # -0. on some architectures.
 AC_MSG_CHECKING(whether tanh preserves the sign of zero)
@@ -3162,9 +3207,8 @@
   [Define if tanh(-0.) is -0., or if platform doesn't have signed zeros])
 fi
 
-AC_REPLACE_FUNCS(hypot)
-
-AC_CHECK_FUNCS(acosh asinh atanh copysign expm1 finite isinf isnan log1p)
+AC_CHECK_FUNCS([acosh asinh atanh copysign expm1 finite hypot log1p])
+AC_CHECK_DECLS([isinf, isnan, isfinite], [], [], [[#include <math.h>]])
 
 LIBS=$LIBS_SAVE
 

Modified: python/branches/tlee-ast-optimize/pyconfig.h.in
==============================================================================
--- python/branches/tlee-ast-optimize/pyconfig.h.in	(original)
+++ python/branches/tlee-ast-optimize/pyconfig.h.in	Wed Jan 14 13:24:17 2009
@@ -115,6 +115,18 @@
 /* Define if you have the 'resize_term' function. */
 #undef HAVE_CURSES_RESIZE_TERM
 
+/* Define to 1 if you have the declaration of `isfinite', and to 0 if you
+   don't. */
+#undef HAVE_DECL_ISFINITE
+
+/* Define to 1 if you have the declaration of `isinf', and to 0 if you don't.
+   */
+#undef HAVE_DECL_ISINF
+
+/* Define to 1 if you have the declaration of `isnan', and to 0 if you don't.
+   */
+#undef HAVE_DECL_ISNAN
+
 /* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
    */
 #undef HAVE_DECL_TZNAME
@@ -315,12 +327,6 @@
 /* Define to 1 if you have the <io.h> header file. */
 #undef HAVE_IO_H
 
-/* Define to 1 if you have the `isinf' function. */
-#undef HAVE_ISINF
-
-/* Define to 1 if you have the `isnan' function. */
-#undef HAVE_ISNAN
-
 /* Define to 1 if you have the `kill' function. */
 #undef HAVE_KILL
 
@@ -983,6 +989,9 @@
    first (like Motorola and SPARC, unlike Intel and VAX). */
 #undef WORDS_BIGENDIAN
 
+/* Define if arithmetic is subject to x87-style double rounding issue */
+#undef X87_DOUBLE_ROUNDING
+
 /* Define to 1 if on AIX 3.
    System headers sometimes define this.
    We just want to avoid a redefinition error message.  */

Modified: python/branches/tlee-ast-optimize/setup.py
==============================================================================
--- python/branches/tlee-ast-optimize/setup.py	(original)
+++ python/branches/tlee-ast-optimize/setup.py	Wed Jan 14 13:24:17 2009
@@ -215,7 +215,8 @@
 
         if missing:
             print
-            print "Failed to find the necessary bits to build these modules:"
+            print ("Python build finished, but the necessary bits to build "
+                   "these modules were not found:")
             print_three_column(missing)
             print ("To find the necessary bits, look in setup.py in"
                    " detect_modules() for the module's name.")
@@ -1019,11 +1020,22 @@
                 exts.append( Extension('dbm', ['dbmmodule.c'],
                                        define_macros=[('HAVE_NDBM_H',None)],
                                        libraries = ndbm_libs ) )
-            elif (self.compiler.find_library_file(lib_dirs, 'gdbm')
-                  and find_file("gdbm/ndbm.h", inc_dirs, []) is not None):
-                exts.append( Extension('dbm', ['dbmmodule.c'],
-                                       define_macros=[('HAVE_GDBM_NDBM_H',None)],
-                                       libraries = ['gdbm'] ) )
+            elif self.compiler.find_library_file(lib_dirs, 'gdbm'):
+                gdbm_libs = ['gdbm']
+                if self.compiler.find_library_file(lib_dirs, 'gdbm_compat'):
+                    gdbm_libs.append('gdbm_compat')
+                if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
+                    exts.append( Extension(
+                        'dbm', ['dbmmodule.c'],
+                        define_macros=[('HAVE_GDBM_NDBM_H',None)],
+                        libraries = gdbm_libs ) )
+                elif find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
+                    exts.append( Extension(
+                        'dbm', ['dbmmodule.c'],
+                        define_macros=[('HAVE_GDBM_DASH_NDBM_H',None)],
+                        libraries = gdbm_libs ) )
+                else:
+                    missing.append('dbm')
             elif db_incs is not None:
                 exts.append( Extension('dbm', ['dbmmodule.c'],
                                        library_dirs=dblib_dir,


More information about the Python-checkins mailing list