[Python-3000-checkins] r57154 - in python/branches/py3k-buffer: Demo/cgi/cgi2.py Demo/classes/Dbm.py Demo/metaclasses/Enum.py Demo/newmetaclasses/Enum.py Demo/pdist/cmdfw.py Demo/pdist/cmptree.py Demo/pdist/cvslib.py Demo/pdist/rrcs.py Demo/pdist/server.py Demo/scripts/ftpstats.py Demo/scripts/markov.py Demo/scripts/morse.py Demo/scripts/newslist.py Demo/scripts/toaiff.py Demo/threads/Coroutine.py Demo/tix/samples/OptMenu.py Demo/tkinter/guido/AttrDialog.py Demo/xml/elem_count.py Demo/xml/roundtrip.py Doc/Makefile.deps Doc/api/concrete.tex Doc/ext/newtypes.tex Doc/howto/urllib2.rst Doc/info/Makefile Doc/lib/lib.tex Doc/lib/libaudioop.tex Doc/lib/libbsddb.tex Doc/lib/librunpy.tex Doc/lib/libstringio.tex Doc/lib/libsun.tex Doc/lib/libsunaudio.tex Doc/lib/libundoc.tex Doc/lib/libxmlrpclib.tex Doc/lib/sqlite3/adapter_datetime.py Doc/lib/sqlite3/adapter_point_1.py Doc/lib/sqlite3/adapter_point_2.py Doc/lib/sqlite3/collation_reverse.py Doc/lib/sqlite3/complete_statement.py Doc/lib/sqlite3/converter_point.py Doc/lib/sqlite3/countcursors.py Doc/lib/sqlite3/execsql_fetchonerow.py Doc/lib/sqlite3/execsql_printall_1.py Doc/lib/sqlite3/execute_1.py Doc/lib/sqlite3/execute_2.py Doc/lib/sqlite3/execute_3.py Doc/lib/sqlite3/executemany_1.py Doc/lib/sqlite3/executemany_2.py Doc/lib/sqlite3/md5func.py Doc/lib/sqlite3/mysumaggr.py Doc/lib/sqlite3/parse_colnames.py Doc/lib/sqlite3/pysqlite_datetime.py Doc/lib/sqlite3/row_factory.py Doc/lib/sqlite3/shortcut_methods.py Doc/lib/sqlite3/simple_tableprinter.py Doc/lib/sqlite3/text_factory.py Doc/ref/ref3.tex Doc/tools/indfix.py Doc/tools/sgmlconv/docfixer.py Doc/tut/tut.tex Doc/whatsnew/whatsnew25.tex Include/object.h Include/structmember.h Include/unicodeobject.h Lib/BaseHTTPServer.py Lib/SocketServer.py Lib/StringIO.py Lib/abc.py Lib/asynchat.py Lib/audiodev.py Lib/bsddb/__init__.py Lib/bsddb/dbshelve.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compare.py Lib/bsddb/test/test_compat.py Lib/bsddb/test/test_cursor_pget_bug.py Lib/bsddb/test/test_dbobj.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_get_none.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_sequence.py Lib/bsddb/test/test_thread.py Lib/code.py Lib/cookielib.py Lib/ctypes/test/test_arrays.py Lib/ctypes/test/test_buffers.py Lib/ctypes/test/test_callbacks.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_random_things.py Lib/ctypes/test/test_repr.py Lib/ctypes/test/test_stringptr.py Lib/distutils/command/register.py Lib/distutils/command/upload.py Lib/distutils/tests/test_build_py.py Lib/distutils/tests/test_dist.py Lib/doctest.py Lib/dumbdbm.py Lib/email/generator.py Lib/email/iterators.py Lib/email/message.py Lib/email/mime/audio.py Lib/email/parser.py Lib/email/test/test_email.py Lib/email/test/test_email_renamed.py Lib/email/test/test_email_torture.py Lib/email/utils.py Lib/httplib.py Lib/idlelib/EditorWindow.py Lib/idlelib/PyShell.py Lib/idlelib/ScriptBinding.py Lib/idlelib/run.py Lib/io.py Lib/logging/__init__.py Lib/mailbox.py Lib/mimetools.py Lib/optparse.py Lib/pickletools.py Lib/plat-mac/Carbon/AppleEvents.py Lib/plat-mac/aepack.py Lib/plat-mac/aetools.py Lib/plat-mac/aetypes.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/plistlib.py Lib/plat-sunos5/SUNAUDIODEV.py Lib/pprint.py Lib/pydoc.py Lib/quopri.py Lib/runpy.py Lib/sgmllib.py Lib/shelve.py Lib/smtpd.py Lib/smtplib.py Lib/socket.py Lib/tarfile.py Lib/tempfile.py Lib/test/README Lib/test/output/test_linuxaudiodev Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/test_bsddb3.py Lib/test/test_linuxaudiodev.py Lib/test/test_sunaudiodev.py Lib/test/test_wsgiref.py Lib/threading.py Lib/toaiff.py Lib/traceback.py Lib/urllib.py Lib/urllib2.py Lib/uu.py Lib/wsgiref/handlers.py Lib/wsgiref/simple_server.py Lib/wsgiref/util.py Lib/xdrlib.py Lib/xml/dom/minidom.py Lib/xml/dom/pulldom.py Lib/xml/etree/ElementTree.py Lib/xml/sax/__init__.py Lib/xmlrpclib.py Mac/Demo/sound/morse.py Mac/Modules/ae/_AEmodule.c Makefile.pre.in Misc/ACKS Misc/BeOS-setup.py Misc/NEWS Misc/cheatsheet Modules/Setup.dist Modules/_bsddb.c Modules/_collectionsmodule.c Modules/_csv.c Modules/_ctypes/cfield.c Modules/_elementtree.c Modules/_fileio.c Modules/_hotshot.c Modules/_sqlite/row.c Modules/_ssl.c Modules/atexitmodule.c Modules/bz2module.c Modules/cStringIO.c Modules/cjkcodecs/_codecs_cn.c Modules/dbmmodule.c Modules/linuxaudiodev.c Modules/mmapmodule.c Modules/socketmodule.c Modules/sunaudiodev.c Modules/unicodedata.c Modules/zipimport.c Objects/boolobject.c Objects/bytesobject.c Objects/complexobject.c Objects/dictobject.c Objects/floatobject.c Objects/frameobject.c Objects/genobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/object.c Objects/setobject.c Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c PC/VC6/pythoncore.dsp PC/_winreg.c PC/os2emx/Makefile PC/os2emx/python25.def PC/os2vacpp/makefile PC/os2vacpp/makefile.omk PC/pyconfig.h PCbuild/pythoncore.vcproj PCbuild8/pythoncore/pythoncore.vcproj Parser/tokenizer.c Python/ast.c Python/import.c Python/mactoolboxglue.c Python/marshal.c Python/structmember.c Python/symtable.c RISCOS/Makefile Tools/audiopy Tools/bgen/bgen/bgenGenerator.py Tools/bgen/bgen/bgenGeneratorGroup.py Tools/bgen/bgen/scantools.py Tools/faqwiz/faqw.py Tools/faqwiz/faqwiz.py Tools/framer/example.py Tools/framer/framer/bases.py Tools/framer/framer/function.py Tools/framer/framer/member.py Tools/i18n/makelocalealias.py Tools/i18n/msgfmt.py Tools/i18n/pygettext.py Tools/modulator/Tkextra.py Tools/msi/msi.py Tools/msi/msilib.py Tools/pybench/pybench.py Tools/pynche/ColorDB.py Tools/pynche/Main.py Tools/pynche/Switchboard.py Tools/scripts/byext.py Tools/scripts/byteyears.py Tools/scripts/checkappend.py Tools/scripts/checkpyc.py Tools/scripts/cleanfuture.py Tools/scripts/combinerefs.py Tools/scripts/crlf.py Tools/scripts/cvsfiles.py Tools/scripts/dutree.py Tools/scripts/finddiv.py Tools/scripts/findlinksto.py Tools/scripts/findnocoding.py Tools/scripts/fixcid.py Tools/scripts/fixdiv.py Tools/scripts/fixheader.py Tools/scripts/fixnotice.py Tools/scripts/fixps.py Tools/scripts/ftpmirror.py Tools/scripts/google.py Tools/scripts/lfcr.py Tools/scripts/linktree.py Tools/scripts/lll.py Tools/scripts/logmerge.py Tools/scripts/mailerdaemon.py Tools/scripts/mkreal.py Tools/scripts/ndiff.py Tools/scripts/objgraph.py Tools/scripts/pdeps.py Tools/scripts/pysource.py Tools/scripts/rgrep.py Tools/scripts/suff.py Tools/scripts/texcheck.py Tools/scripts/texi2html.py Tools/scripts/treesync.py Tools/scripts/untabify.py Tools/scripts/which.py Tools/scripts/xxci.py Tools/unicode/comparecodecs.py Tools/unicode/gencodec.py Tools/unicode/listcodecs.py Tools/unicode/makeunicodedata.py Tools/unicode/mkstringprep.py Tools/versioncheck/checkversions.py Tools/versioncheck/pyversioncheck.py Tools/webchecker/wcgui.py Tools/webchecker/webchecker.py Tools/webchecker/websucker.py configure configure.in pyconfig.h.in runtests.sh setup.py

travis.oliphant python-3000-checkins at python.org
Fri Aug 17 20:48:52 CEST 2007


Author: travis.oliphant
Date: Fri Aug 17 20:48:09 2007
New Revision: 57154

Added:
   python/branches/py3k-buffer/Demo/scripts/toaiff.py
      - copied unchanged from r56848, python/branches/py3k-struni/Demo/scripts/toaiff.py
Removed:
   python/branches/py3k-buffer/Demo/scripts/morse.py
   python/branches/py3k-buffer/Doc/lib/libsun.tex
   python/branches/py3k-buffer/Doc/lib/libsunaudio.tex
   python/branches/py3k-buffer/Lib/StringIO.py
   python/branches/py3k-buffer/Lib/audiodev.py
   python/branches/py3k-buffer/Lib/plat-sunos5/SUNAUDIODEV.py
   python/branches/py3k-buffer/Lib/test/output/test_linuxaudiodev
   python/branches/py3k-buffer/Lib/test/test_linuxaudiodev.py
   python/branches/py3k-buffer/Lib/test/test_sunaudiodev.py
   python/branches/py3k-buffer/Lib/toaiff.py
   python/branches/py3k-buffer/Mac/Demo/sound/morse.py
   python/branches/py3k-buffer/Modules/linuxaudiodev.c
   python/branches/py3k-buffer/Modules/sunaudiodev.c
   python/branches/py3k-buffer/Objects/intobject.c
   python/branches/py3k-buffer/Tools/audiopy/
Modified:
   python/branches/py3k-buffer/   (props changed)
   python/branches/py3k-buffer/Demo/cgi/cgi2.py
   python/branches/py3k-buffer/Demo/classes/Dbm.py
   python/branches/py3k-buffer/Demo/metaclasses/Enum.py
   python/branches/py3k-buffer/Demo/newmetaclasses/Enum.py
   python/branches/py3k-buffer/Demo/pdist/cmdfw.py
   python/branches/py3k-buffer/Demo/pdist/cmptree.py
   python/branches/py3k-buffer/Demo/pdist/cvslib.py
   python/branches/py3k-buffer/Demo/pdist/rrcs.py
   python/branches/py3k-buffer/Demo/pdist/server.py
   python/branches/py3k-buffer/Demo/scripts/ftpstats.py
   python/branches/py3k-buffer/Demo/scripts/markov.py
   python/branches/py3k-buffer/Demo/scripts/newslist.py
   python/branches/py3k-buffer/Demo/threads/Coroutine.py
   python/branches/py3k-buffer/Demo/tix/samples/OptMenu.py
   python/branches/py3k-buffer/Demo/tkinter/guido/AttrDialog.py
   python/branches/py3k-buffer/Demo/xml/elem_count.py
   python/branches/py3k-buffer/Demo/xml/roundtrip.py
   python/branches/py3k-buffer/Doc/Makefile.deps
   python/branches/py3k-buffer/Doc/api/concrete.tex
   python/branches/py3k-buffer/Doc/ext/newtypes.tex
   python/branches/py3k-buffer/Doc/howto/urllib2.rst
   python/branches/py3k-buffer/Doc/info/Makefile
   python/branches/py3k-buffer/Doc/lib/lib.tex
   python/branches/py3k-buffer/Doc/lib/libaudioop.tex
   python/branches/py3k-buffer/Doc/lib/libbsddb.tex
   python/branches/py3k-buffer/Doc/lib/librunpy.tex
   python/branches/py3k-buffer/Doc/lib/libstringio.tex
   python/branches/py3k-buffer/Doc/lib/libundoc.tex
   python/branches/py3k-buffer/Doc/lib/libxmlrpclib.tex
   python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_datetime.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_1.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_2.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/collation_reverse.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/complete_statement.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/converter_point.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/countcursors.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_fetchonerow.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_printall_1.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/execute_1.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/execute_2.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/execute_3.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_1.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_2.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/md5func.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/mysumaggr.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/parse_colnames.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/pysqlite_datetime.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/row_factory.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/shortcut_methods.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/simple_tableprinter.py
   python/branches/py3k-buffer/Doc/lib/sqlite3/text_factory.py
   python/branches/py3k-buffer/Doc/ref/ref3.tex
   python/branches/py3k-buffer/Doc/tools/indfix.py
   python/branches/py3k-buffer/Doc/tools/sgmlconv/docfixer.py
   python/branches/py3k-buffer/Doc/tut/tut.tex
   python/branches/py3k-buffer/Doc/whatsnew/whatsnew25.tex
   python/branches/py3k-buffer/Include/object.h
   python/branches/py3k-buffer/Include/structmember.h
   python/branches/py3k-buffer/Include/unicodeobject.h
   python/branches/py3k-buffer/Lib/BaseHTTPServer.py
   python/branches/py3k-buffer/Lib/SocketServer.py
   python/branches/py3k-buffer/Lib/abc.py
   python/branches/py3k-buffer/Lib/asynchat.py
   python/branches/py3k-buffer/Lib/bsddb/__init__.py
   python/branches/py3k-buffer/Lib/bsddb/dbshelve.py
   python/branches/py3k-buffer/Lib/bsddb/dbtables.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_associate.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_basics.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_compare.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_compat.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_cursor_pget_bug.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_dbobj.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_dbshelve.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_get_none.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_join.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_recno.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_sequence.py
   python/branches/py3k-buffer/Lib/bsddb/test/test_thread.py
   python/branches/py3k-buffer/Lib/code.py
   python/branches/py3k-buffer/Lib/cookielib.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_arrays.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_buffers.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_callbacks.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_numbers.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_random_things.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_repr.py
   python/branches/py3k-buffer/Lib/ctypes/test/test_stringptr.py
   python/branches/py3k-buffer/Lib/distutils/command/register.py
   python/branches/py3k-buffer/Lib/distutils/command/upload.py
   python/branches/py3k-buffer/Lib/distutils/tests/test_build_py.py
   python/branches/py3k-buffer/Lib/distutils/tests/test_dist.py
   python/branches/py3k-buffer/Lib/doctest.py
   python/branches/py3k-buffer/Lib/dumbdbm.py
   python/branches/py3k-buffer/Lib/email/generator.py
   python/branches/py3k-buffer/Lib/email/iterators.py
   python/branches/py3k-buffer/Lib/email/message.py
   python/branches/py3k-buffer/Lib/email/mime/audio.py
   python/branches/py3k-buffer/Lib/email/parser.py
   python/branches/py3k-buffer/Lib/email/test/test_email.py
   python/branches/py3k-buffer/Lib/email/test/test_email_renamed.py
   python/branches/py3k-buffer/Lib/email/test/test_email_torture.py
   python/branches/py3k-buffer/Lib/email/utils.py
   python/branches/py3k-buffer/Lib/httplib.py
   python/branches/py3k-buffer/Lib/idlelib/EditorWindow.py
   python/branches/py3k-buffer/Lib/idlelib/PyShell.py
   python/branches/py3k-buffer/Lib/idlelib/ScriptBinding.py
   python/branches/py3k-buffer/Lib/idlelib/run.py
   python/branches/py3k-buffer/Lib/io.py
   python/branches/py3k-buffer/Lib/logging/__init__.py
   python/branches/py3k-buffer/Lib/mailbox.py
   python/branches/py3k-buffer/Lib/mimetools.py
   python/branches/py3k-buffer/Lib/optparse.py
   python/branches/py3k-buffer/Lib/pickletools.py
   python/branches/py3k-buffer/Lib/plat-mac/Carbon/AppleEvents.py
   python/branches/py3k-buffer/Lib/plat-mac/aepack.py
   python/branches/py3k-buffer/Lib/plat-mac/aetools.py
   python/branches/py3k-buffer/Lib/plat-mac/aetypes.py
   python/branches/py3k-buffer/Lib/plat-mac/gensuitemodule.py
   python/branches/py3k-buffer/Lib/plat-mac/plistlib.py
   python/branches/py3k-buffer/Lib/pprint.py
   python/branches/py3k-buffer/Lib/pydoc.py
   python/branches/py3k-buffer/Lib/quopri.py
   python/branches/py3k-buffer/Lib/runpy.py
   python/branches/py3k-buffer/Lib/sgmllib.py
   python/branches/py3k-buffer/Lib/shelve.py
   python/branches/py3k-buffer/Lib/smtpd.py
   python/branches/py3k-buffer/Lib/smtplib.py
   python/branches/py3k-buffer/Lib/socket.py
   python/branches/py3k-buffer/Lib/tarfile.py
   python/branches/py3k-buffer/Lib/tempfile.py
   python/branches/py3k-buffer/Lib/test/README
   python/branches/py3k-buffer/Lib/test/pickletester.py
   python/branches/py3k-buffer/Lib/test/regrtest.py
   python/branches/py3k-buffer/Lib/test/test_bsddb3.py
   python/branches/py3k-buffer/Lib/test/test_wsgiref.py
   python/branches/py3k-buffer/Lib/threading.py
   python/branches/py3k-buffer/Lib/traceback.py
   python/branches/py3k-buffer/Lib/urllib.py
   python/branches/py3k-buffer/Lib/urllib2.py
   python/branches/py3k-buffer/Lib/uu.py
   python/branches/py3k-buffer/Lib/wsgiref/handlers.py
   python/branches/py3k-buffer/Lib/wsgiref/simple_server.py
   python/branches/py3k-buffer/Lib/wsgiref/util.py
   python/branches/py3k-buffer/Lib/xdrlib.py
   python/branches/py3k-buffer/Lib/xml/dom/minidom.py
   python/branches/py3k-buffer/Lib/xml/dom/pulldom.py
   python/branches/py3k-buffer/Lib/xml/etree/ElementTree.py
   python/branches/py3k-buffer/Lib/xml/sax/__init__.py
   python/branches/py3k-buffer/Lib/xmlrpclib.py
   python/branches/py3k-buffer/Mac/Modules/ae/_AEmodule.c
   python/branches/py3k-buffer/Makefile.pre.in
   python/branches/py3k-buffer/Misc/ACKS
   python/branches/py3k-buffer/Misc/BeOS-setup.py
   python/branches/py3k-buffer/Misc/NEWS
   python/branches/py3k-buffer/Misc/cheatsheet
   python/branches/py3k-buffer/Modules/Setup.dist
   python/branches/py3k-buffer/Modules/_bsddb.c
   python/branches/py3k-buffer/Modules/_collectionsmodule.c
   python/branches/py3k-buffer/Modules/_csv.c
   python/branches/py3k-buffer/Modules/_ctypes/cfield.c
   python/branches/py3k-buffer/Modules/_elementtree.c
   python/branches/py3k-buffer/Modules/_fileio.c
   python/branches/py3k-buffer/Modules/_hotshot.c
   python/branches/py3k-buffer/Modules/_sqlite/row.c
   python/branches/py3k-buffer/Modules/_ssl.c
   python/branches/py3k-buffer/Modules/atexitmodule.c
   python/branches/py3k-buffer/Modules/bz2module.c
   python/branches/py3k-buffer/Modules/cStringIO.c
   python/branches/py3k-buffer/Modules/cjkcodecs/_codecs_cn.c
   python/branches/py3k-buffer/Modules/dbmmodule.c
   python/branches/py3k-buffer/Modules/mmapmodule.c
   python/branches/py3k-buffer/Modules/socketmodule.c
   python/branches/py3k-buffer/Modules/unicodedata.c
   python/branches/py3k-buffer/Modules/zipimport.c
   python/branches/py3k-buffer/Objects/boolobject.c
   python/branches/py3k-buffer/Objects/bytesobject.c
   python/branches/py3k-buffer/Objects/complexobject.c
   python/branches/py3k-buffer/Objects/dictobject.c
   python/branches/py3k-buffer/Objects/floatobject.c
   python/branches/py3k-buffer/Objects/frameobject.c
   python/branches/py3k-buffer/Objects/genobject.c
   python/branches/py3k-buffer/Objects/listobject.c
   python/branches/py3k-buffer/Objects/longobject.c
   python/branches/py3k-buffer/Objects/object.c
   python/branches/py3k-buffer/Objects/setobject.c
   python/branches/py3k-buffer/Objects/stringobject.c
   python/branches/py3k-buffer/Objects/tupleobject.c
   python/branches/py3k-buffer/Objects/typeobject.c
   python/branches/py3k-buffer/Objects/unicodeobject.c
   python/branches/py3k-buffer/PC/VC6/pythoncore.dsp
   python/branches/py3k-buffer/PC/_winreg.c
   python/branches/py3k-buffer/PC/os2emx/Makefile
   python/branches/py3k-buffer/PC/os2emx/python25.def
   python/branches/py3k-buffer/PC/os2vacpp/makefile
   python/branches/py3k-buffer/PC/os2vacpp/makefile.omk
   python/branches/py3k-buffer/PC/pyconfig.h
   python/branches/py3k-buffer/PCbuild/pythoncore.vcproj
   python/branches/py3k-buffer/PCbuild8/pythoncore/pythoncore.vcproj
   python/branches/py3k-buffer/Parser/tokenizer.c
   python/branches/py3k-buffer/Python/ast.c
   python/branches/py3k-buffer/Python/import.c
   python/branches/py3k-buffer/Python/mactoolboxglue.c
   python/branches/py3k-buffer/Python/marshal.c
   python/branches/py3k-buffer/Python/structmember.c
   python/branches/py3k-buffer/Python/symtable.c
   python/branches/py3k-buffer/RISCOS/Makefile
   python/branches/py3k-buffer/Tools/bgen/bgen/bgenGenerator.py
   python/branches/py3k-buffer/Tools/bgen/bgen/bgenGeneratorGroup.py
   python/branches/py3k-buffer/Tools/bgen/bgen/scantools.py
   python/branches/py3k-buffer/Tools/faqwiz/faqw.py
   python/branches/py3k-buffer/Tools/faqwiz/faqwiz.py
   python/branches/py3k-buffer/Tools/framer/example.py
   python/branches/py3k-buffer/Tools/framer/framer/bases.py
   python/branches/py3k-buffer/Tools/framer/framer/function.py
   python/branches/py3k-buffer/Tools/framer/framer/member.py
   python/branches/py3k-buffer/Tools/i18n/makelocalealias.py
   python/branches/py3k-buffer/Tools/i18n/msgfmt.py
   python/branches/py3k-buffer/Tools/i18n/pygettext.py
   python/branches/py3k-buffer/Tools/modulator/Tkextra.py
   python/branches/py3k-buffer/Tools/msi/msi.py
   python/branches/py3k-buffer/Tools/msi/msilib.py
   python/branches/py3k-buffer/Tools/pybench/pybench.py
   python/branches/py3k-buffer/Tools/pynche/ColorDB.py
   python/branches/py3k-buffer/Tools/pynche/Main.py
   python/branches/py3k-buffer/Tools/pynche/Switchboard.py
   python/branches/py3k-buffer/Tools/scripts/byext.py
   python/branches/py3k-buffer/Tools/scripts/byteyears.py
   python/branches/py3k-buffer/Tools/scripts/checkappend.py
   python/branches/py3k-buffer/Tools/scripts/checkpyc.py
   python/branches/py3k-buffer/Tools/scripts/cleanfuture.py
   python/branches/py3k-buffer/Tools/scripts/combinerefs.py
   python/branches/py3k-buffer/Tools/scripts/crlf.py
   python/branches/py3k-buffer/Tools/scripts/cvsfiles.py
   python/branches/py3k-buffer/Tools/scripts/dutree.py
   python/branches/py3k-buffer/Tools/scripts/finddiv.py
   python/branches/py3k-buffer/Tools/scripts/findlinksto.py
   python/branches/py3k-buffer/Tools/scripts/findnocoding.py
   python/branches/py3k-buffer/Tools/scripts/fixcid.py
   python/branches/py3k-buffer/Tools/scripts/fixdiv.py
   python/branches/py3k-buffer/Tools/scripts/fixheader.py
   python/branches/py3k-buffer/Tools/scripts/fixnotice.py
   python/branches/py3k-buffer/Tools/scripts/fixps.py
   python/branches/py3k-buffer/Tools/scripts/ftpmirror.py
   python/branches/py3k-buffer/Tools/scripts/google.py
   python/branches/py3k-buffer/Tools/scripts/lfcr.py
   python/branches/py3k-buffer/Tools/scripts/linktree.py
   python/branches/py3k-buffer/Tools/scripts/lll.py
   python/branches/py3k-buffer/Tools/scripts/logmerge.py
   python/branches/py3k-buffer/Tools/scripts/mailerdaemon.py
   python/branches/py3k-buffer/Tools/scripts/mkreal.py
   python/branches/py3k-buffer/Tools/scripts/ndiff.py
   python/branches/py3k-buffer/Tools/scripts/objgraph.py
   python/branches/py3k-buffer/Tools/scripts/pdeps.py
   python/branches/py3k-buffer/Tools/scripts/pysource.py
   python/branches/py3k-buffer/Tools/scripts/rgrep.py
   python/branches/py3k-buffer/Tools/scripts/suff.py
   python/branches/py3k-buffer/Tools/scripts/texcheck.py
   python/branches/py3k-buffer/Tools/scripts/texi2html.py
   python/branches/py3k-buffer/Tools/scripts/treesync.py
   python/branches/py3k-buffer/Tools/scripts/untabify.py
   python/branches/py3k-buffer/Tools/scripts/which.py
   python/branches/py3k-buffer/Tools/scripts/xxci.py
   python/branches/py3k-buffer/Tools/unicode/comparecodecs.py
   python/branches/py3k-buffer/Tools/unicode/gencodec.py
   python/branches/py3k-buffer/Tools/unicode/listcodecs.py
   python/branches/py3k-buffer/Tools/unicode/makeunicodedata.py
   python/branches/py3k-buffer/Tools/unicode/mkstringprep.py
   python/branches/py3k-buffer/Tools/versioncheck/checkversions.py
   python/branches/py3k-buffer/Tools/versioncheck/pyversioncheck.py
   python/branches/py3k-buffer/Tools/webchecker/wcgui.py
   python/branches/py3k-buffer/Tools/webchecker/webchecker.py
   python/branches/py3k-buffer/Tools/webchecker/websucker.py
   python/branches/py3k-buffer/configure
   python/branches/py3k-buffer/configure.in
   python/branches/py3k-buffer/pyconfig.h.in
   python/branches/py3k-buffer/runtests.sh
   python/branches/py3k-buffer/setup.py
Log:
Merge in changes from py3k-struni branch between revisions 56547 and 56848 to the py3k-buffer branch

Modified: python/branches/py3k-buffer/Demo/cgi/cgi2.py
==============================================================================
--- python/branches/py3k-buffer/Demo/cgi/cgi2.py	(original)
+++ python/branches/py3k-buffer/Demo/cgi/cgi2.py	Fri Aug 17 20:48:09 2007
@@ -14,7 +14,7 @@
         print("<h1>No Form Keys</h1>")
     else:
         print("<h1>Form Keys</h1>")
-        for key in list(form.keys()):
+        for key in form.keys():
             value = form[key].value
             print("<p>", cgi.escape(key), ":", cgi.escape(value))
 

Modified: python/branches/py3k-buffer/Demo/classes/Dbm.py
==============================================================================
--- python/branches/py3k-buffer/Demo/classes/Dbm.py	(original)
+++ python/branches/py3k-buffer/Demo/classes/Dbm.py	Fri Aug 17 20:48:09 2007
@@ -12,7 +12,7 @@
 
     def __repr__(self):
         s = ''
-        for key in list(self.keys()):
+        for key in self.keys():
             t = repr(key) + ': ' + repr(self[key])
             if s: t = ', ' + t
             s = s + t
@@ -32,7 +32,7 @@
 
     def keys(self):
         res = []
-        for key in list(self.db.keys()):
+        for key in self.db.keys():
             res.append(eval(key))
         return res
 

Modified: python/branches/py3k-buffer/Demo/metaclasses/Enum.py
==============================================================================
--- python/branches/py3k-buffer/Demo/metaclasses/Enum.py	(original)
+++ python/branches/py3k-buffer/Demo/metaclasses/Enum.py	Fri Aug 17 20:48:09 2007
@@ -42,7 +42,7 @@
         self.__name__ = name
         self.__bases__ = bases
         self.__dict = {}
-        for key, value in list(dict.items()):
+        for key, value in dict.items():
             self.__dict[key] = EnumInstance(name, key, value)
 
     def __getattr__(self, name):
@@ -80,7 +80,7 @@
             s = s + '(' + string.join([x.__name__ for x in self.__bases__], ", ") + ')'
         if self.__dict:
             list = []
-            for key, value in list(self.__dict.items()):
+            for key, value in self.__dict.items():
                 list.append("%s: %s" % (key, int(value)))
             s = "%s: {%s}" % (s, string.join(list, ", "))
         return s

Modified: python/branches/py3k-buffer/Demo/newmetaclasses/Enum.py
==============================================================================
--- python/branches/py3k-buffer/Demo/newmetaclasses/Enum.py	(original)
+++ python/branches/py3k-buffer/Demo/newmetaclasses/Enum.py	Fri Aug 17 20:48:09 2007
@@ -20,7 +20,7 @@
     def __init__(cls, name, bases, dict):
         super(EnumMetaclass, cls).__init__(name, bases, dict)
         cls._members = []
-        for attr in list(dict.keys()):
+        for attr in dict.keys():
             if not (attr.startswith('__') and attr.endswith('__')):
                 enumval = EnumInstance(name, attr, dict[attr])
                 setattr(cls, attr, enumval)

Modified: python/branches/py3k-buffer/Demo/pdist/cmdfw.py
==============================================================================
--- python/branches/py3k-buffer/Demo/pdist/cmdfw.py	(original)
+++ python/branches/py3k-buffer/Demo/pdist/cmdfw.py	Fri Aug 17 20:48:09 2007
@@ -104,9 +104,7 @@
             c = c.__bases__[0]
         if docstrings:
             print("where subcommand can be:")
-            names = list(docstrings.keys())
-            names.sort()
-            for name in names:
+            for name in sorted(docstrings.keys()):
                 print(docstrings[name])
         if self.PostUsageMessage:
             print(self.PostUsageMessage)

Modified: python/branches/py3k-buffer/Demo/pdist/cmptree.py
==============================================================================
--- python/branches/py3k-buffer/Demo/pdist/cmptree.py	(original)
+++ python/branches/py3k-buffer/Demo/pdist/cmptree.py	Fri Aug 17 20:48:09 2007
@@ -89,7 +89,7 @@
                 else:
                     print("same mtime but different sum?!?!", end=' ')
                 print()
-    for name in list(lsumdict.keys()):
+    for name in lsumdict.keys():
         if not list(rsumdict.keys()):
             print(repr(name), "only locally", end=' ')
             fl()

Modified: python/branches/py3k-buffer/Demo/pdist/cvslib.py
==============================================================================
--- python/branches/py3k-buffer/Demo/pdist/cvslib.py	(original)
+++ python/branches/py3k-buffer/Demo/pdist/cvslib.py	Fri Aug 17 20:48:09 2007
@@ -223,15 +223,12 @@
         f.close()
 
     def getlocalfiles(self):
-        list = list(self.entries.keys())
+        entries_keys = set(self.entries.keys())
         addlist = os.listdir(os.curdir)
         for name in addlist:
-            if name in list:
-                continue
             if not self.ignored(name):
-                list.append(name)
-        list.sort()
-        for file in list:
+                entries_keys.add(name)
+        for file in sorted(entries_keys):
             try:
                 e = self.entries[file]
             except KeyError:
@@ -257,19 +254,17 @@
         print('-'*50)
 
     def keys(self):
-        keys = list(self.entries.keys())
-        keys.sort()
-        return keys
+        return sorted(self.entries.keys())
 
     def values(self):
         def value(key, self=self):
             return self.entries[key]
-        return list(map(value, list(self.keys())))
+        return [value(k) for k in self.keys()]
 
     def items(self):
         def item(key, self=self):
             return (key, self.entries[key])
-        return list(map(item, list(self.keys())))
+        return [item(k) for k in self.keys()]
 
     def cvsexists(self, file):
         file = os.path.join("CVS", file)

Modified: python/branches/py3k-buffer/Demo/pdist/rrcs.py
==============================================================================
--- python/branches/py3k-buffer/Demo/pdist/rrcs.py	(original)
+++ python/branches/py3k-buffer/Demo/pdist/rrcs.py	Fri Aug 17 20:48:09 2007
@@ -71,11 +71,9 @@
     x.unlock(fn)
 
 def info(x, copts, fn):
-    dict = x.info(fn)
-    keys = list(dict.keys())
-    keys.sort()
-    for key in keys:
-        print(key + ':', dict[key])
+    info_dict = x.info(fn)
+    for key in sorted(info_dict.keys()):
+        print(key + ':', info_dict[key])
     print('='*70)
 
 def head(x, copts, fn):

Modified: python/branches/py3k-buffer/Demo/pdist/server.py
==============================================================================
--- python/branches/py3k-buffer/Demo/pdist/server.py	(original)
+++ python/branches/py3k-buffer/Demo/pdist/server.py	Fri Aug 17 20:48:09 2007
@@ -101,9 +101,7 @@
 
     def _listmethods(self, cl=None):
         if not cl: cl = self.__class__
-        names = list(cl.__dict__.keys())
-        names = [x for x in names if x[0] != '_']
-        names.sort()
+        names = sorted([x for x in cl.__dict__.keys() if x[0] != '_'])
         for base in cl.__bases__:
             basenames = self._listmethods(base)
             basenames = list(filter(lambda x, names=names: x not in names, basenames))

Modified: python/branches/py3k-buffer/Demo/scripts/ftpstats.py
==============================================================================
--- python/branches/py3k-buffer/Demo/scripts/ftpstats.py	(original)
+++ python/branches/py3k-buffer/Demo/scripts/ftpstats.py	Fri Aug 17 20:48:09 2007
@@ -106,9 +106,7 @@
     n = len(title)
     print('='*((70-n)/2), title, '='*((71-n)/2))
     list = []
-    keys = list(dict.keys())
-    keys.sort()
-    for key in keys:
+    for key in sorted(dict.keys()):
         n = len(str(key))
         list.append((len(dict[key]), key))
     maxkeylength = 0
@@ -128,8 +126,7 @@
     n = len(title)
     print('='*((70-n)/2), title, '='*((71-n)/2))
     list = []
-    keys = list(dict.keys())
-    for key in keys:
+    for key in dict.keys():
         list.append((-len(dict[key]), key))
     list.sort()
     for count, key in list[:maxitems]:

Modified: python/branches/py3k-buffer/Demo/scripts/markov.py
==============================================================================
--- python/branches/py3k-buffer/Demo/scripts/markov.py	(original)
+++ python/branches/py3k-buffer/Demo/scripts/markov.py	Fri Aug 17 20:48:09 2007
@@ -87,7 +87,7 @@
         return
     if debug: print('done.')
     if debug > 1:
-        for key in list(m.trans.keys()):
+        for key in m.trans.keys():
             if key is None or len(key) < histsize:
                 print(repr(key), m.trans[key])
         if histsize == 0: print(repr(''), m.trans[''])

Deleted: /python/branches/py3k-buffer/Demo/scripts/morse.py
==============================================================================
--- /python/branches/py3k-buffer/Demo/scripts/morse.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,149 +0,0 @@
-# DAH should be three DOTs.
-# Space between DOTs and DAHs should be one DOT.
-# Space between two letters should be one DAH.
-# Space between two words should be DOT DAH DAH.
-
-import sys, math, audiodev
-
-DOT = 30
-DAH = 3 * DOT
-OCTAVE = 2                              # 1 == 441 Hz, 2 == 882 Hz, ...
-
-morsetab = {
-        'A': '.-',              'a': '.-',
-        'B': '-...',            'b': '-...',
-        'C': '-.-.',            'c': '-.-.',
-        'D': '-..',             'd': '-..',
-        'E': '.',               'e': '.',
-        'F': '..-.',            'f': '..-.',
-        'G': '--.',             'g': '--.',
-        'H': '....',            'h': '....',
-        'I': '..',              'i': '..',
-        'J': '.---',            'j': '.---',
-        'K': '-.-',             'k': '-.-',
-        'L': '.-..',            'l': '.-..',
-        'M': '--',              'm': '--',
-        'N': '-.',              'n': '-.',
-        'O': '---',             'o': '---',
-        'P': '.--.',            'p': '.--.',
-        'Q': '--.-',            'q': '--.-',
-        'R': '.-.',             'r': '.-.',
-        'S': '...',             's': '...',
-        'T': '-',               't': '-',
-        'U': '..-',             'u': '..-',
-        'V': '...-',            'v': '...-',
-        'W': '.--',             'w': '.--',
-        'X': '-..-',            'x': '-..-',
-        'Y': '-.--',            'y': '-.--',
-        'Z': '--..',            'z': '--..',
-        '0': '-----',
-        '1': '.----',
-        '2': '..---',
-        '3': '...--',
-        '4': '....-',
-        '5': '.....',
-        '6': '-....',
-        '7': '--...',
-        '8': '---..',
-        '9': '----.',
-        ',': '--..--',
-        '.': '.-.-.-',
-        '?': '..--..',
-        ';': '-.-.-.',
-        ':': '---...',
-        "'": '.----.',
-        '-': '-....-',
-        '/': '-..-.',
-        '(': '-.--.-',
-        ')': '-.--.-',
-        '_': '..--.-',
-        ' ': ' '
-}
-
-# If we play at 44.1 kHz (which we do), then if we produce one sine
-# wave in 100 samples, we get a tone of 441 Hz.  If we produce two
-# sine waves in these 100 samples, we get a tone of 882 Hz.  882 Hz
-# appears to be a nice one for playing morse code.
-def mkwave(octave):
-    global sinewave, nowave
-    sinewave = ''
-    for i in range(100):
-        val = int(math.sin(math.pi * float(i) * octave / 50.0) * 30000)
-        sinewave = sinewave + chr((val >> 8) & 255) + chr(val & 255)
-    nowave = '\0' * 200
-
-mkwave(OCTAVE)
-
-def main():
-    import getopt, string
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], 'o:p:')
-    except getopt.error:
-        sys.stderr.write('Usage ' + sys.argv[0] +
-                         ' [ -o outfile ] [ args ] ...\n')
-        sys.exit(1)
-    dev = None
-    for o, a in opts:
-        if o == '-o':
-            import aifc
-            dev = aifc.open(a, 'w')
-            dev.setframerate(44100)
-            dev.setsampwidth(2)
-            dev.setnchannels(1)
-        if o == '-p':
-            mkwave(string.atoi(a))
-    if not dev:
-        import audiodev
-        dev = audiodev.AudioDev()
-        dev.setoutrate(44100)
-        dev.setsampwidth(2)
-        dev.setnchannels(1)
-        dev.close = dev.stop
-        dev.writeframesraw = dev.writeframes
-    if args:
-        line = string.join(args)
-    else:
-        line = sys.stdin.readline()
-    while line:
-        mline = morse(line)
-        play(mline, dev)
-        if hasattr(dev, 'wait'):
-            dev.wait()
-        if not args:
-            line = sys.stdin.readline()
-        else:
-            line = ''
-    dev.close()
-
-# Convert a string to morse code with \001 between the characters in
-# the string.
-def morse(line):
-    res = ''
-    for c in line:
-        try:
-            res = res + morsetab[c] + '\001'
-        except KeyError:
-            pass
-    return res
-
-# Play a line of morse code.
-def play(line, dev):
-    for c in line:
-        if c == '.':
-            sine(dev, DOT)
-        elif c == '-':
-            sine(dev, DAH)
-        else:                   # space
-            pause(dev, DAH + DOT)
-        pause(dev, DOT)
-
-def sine(dev, length):
-    for i in range(length):
-        dev.writeframesraw(sinewave)
-
-def pause(dev, length):
-    for i in range(length):
-        dev.writeframesraw(nowave)
-
-if __name__ == '__main__' or sys.argv[0] == __name__:
-    main()

Modified: python/branches/py3k-buffer/Demo/scripts/newslist.py
==============================================================================
--- python/branches/py3k-buffer/Demo/scripts/newslist.py	(original)
+++ python/branches/py3k-buffer/Demo/scripts/newslist.py	Fri Aug 17 20:48:09 2007
@@ -172,10 +172,9 @@
         createpage(p[1:], tree, p)
         return
 
-    kl = list(tree.keys())
+    kl = sorted(tree.keys())
 
     if l > 1:
-        kl.sort()
         if indent > 0:
             # Create a sub-list
             f.write('<LI>'+p[1:]+'\n<UL>')

Modified: python/branches/py3k-buffer/Demo/threads/Coroutine.py
==============================================================================
--- python/branches/py3k-buffer/Demo/threads/Coroutine.py	(original)
+++ python/branches/py3k-buffer/Demo/threads/Coroutine.py	Fri Aug 17 20:48:09 2007
@@ -127,7 +127,7 @@
         if self.killed:
             raise TypeError('kill() called on dead coroutines')
         self.killed = 1
-        for coroutine in list(self.invokedby.keys()):
+        for coroutine in self.invokedby.keys():
             coroutine.resume()
 
     def back(self, data=None):

Modified: python/branches/py3k-buffer/Demo/tix/samples/OptMenu.py
==============================================================================
--- python/branches/py3k-buffer/Demo/tix/samples/OptMenu.py	(original)
+++ python/branches/py3k-buffer/Demo/tix/samples/OptMenu.py	Fri Aug 17 20:48:09 2007
@@ -40,7 +40,7 @@
     #        global variables "demo_opt_from" and "demo_opt_to". Otherwise
     #        the OptionMenu widget will complain about "unknown options"!
     #
-    for opt in list(options.keys()):
+    for opt in options.keys():
         from_file.add_command(opt, label=options[opt])
         to_file.add_command(opt, label=options[opt])
 

Modified: python/branches/py3k-buffer/Demo/tkinter/guido/AttrDialog.py
==============================================================================
--- python/branches/py3k-buffer/Demo/tkinter/guido/AttrDialog.py	(original)
+++ python/branches/py3k-buffer/Demo/tkinter/guido/AttrDialog.py	Fri Aug 17 20:48:09 2007
@@ -112,7 +112,7 @@
     def addchoices(self):
         self.choices = {}
         list = []
-        for k, dc in list(self.options.items()):
+        for k, dc in self.options.items():
             list.append((k, dc))
         list.sort()
         for k, (d, c) in list:
@@ -260,7 +260,7 @@
             classes = {}
             for c in (self.classes,
                       self.addclasses[self.klass]):
-                for k in list(c.keys()):
+                for k in c.keys():
                     classes[k] = c[k]
             self.classes = classes
 
@@ -273,7 +273,7 @@
     def update(self):
         self.current = {}
         self.options = {}
-        for k, v in list(self.configuration.items()):
+        for k, v in self.configuration.items():
             if len(v) > 4:
                 self.current[k] = v[4]
                 self.options[k] = v[3], v[2] # default, klass

Modified: python/branches/py3k-buffer/Demo/xml/elem_count.py
==============================================================================
--- python/branches/py3k-buffer/Demo/xml/elem_count.py	(original)
+++ python/branches/py3k-buffer/Demo/xml/elem_count.py	Fri Aug 17 20:48:09 2007
@@ -15,7 +15,7 @@
         self._attrs = self._attrs + len(attrs)
         self._elem_types[name] = self._elem_types.get(name, 0) + 1
 
-        for name in list(attrs.keys()):
+        for name in attrs.keys():
             self._attr_types[name] = self._attr_types.get(name, 0) + 1
 
     def endDocument(self):
@@ -23,11 +23,11 @@
         print("There were", self._attrs, "attributes.")
 
         print("---ELEMENT TYPES")
-        for pair in  list(self._elem_types.items()):
+        for pair in  self._elem_types.items():
             print("%20s %d" % pair)
 
         print("---ATTRIBUTE TYPES")
-        for pair in  list(self._attr_types.items()):
+        for pair in  self._attr_types.items():
             print("%20s %d" % pair)
 
 

Modified: python/branches/py3k-buffer/Demo/xml/roundtrip.py
==============================================================================
--- python/branches/py3k-buffer/Demo/xml/roundtrip.py	(original)
+++ python/branches/py3k-buffer/Demo/xml/roundtrip.py	Fri Aug 17 20:48:09 2007
@@ -22,7 +22,7 @@
 
     def startElement(self, name, attrs):
         self._out.write('<' + name)
-        for (name, value) in list(attrs.items()):
+        for (name, value) in attrs.items():
             self._out.write(' %s="%s"' % (name, saxutils.escape(value)))
         self._out.write('>')
 

Modified: python/branches/py3k-buffer/Doc/Makefile.deps
==============================================================================
--- python/branches/py3k-buffer/Doc/Makefile.deps	(original)
+++ python/branches/py3k-buffer/Doc/Makefile.deps	Fri Aug 17 20:48:09 2007
@@ -199,7 +199,6 @@
 	lib/libcrypto.tex \
 	lib/libhashlib.tex \
 	lib/libhmac.tex \
-	lib/libsun.tex \
 	lib/libxdrlib.tex \
 	lib/libimghdr.tex \
 	lib/libformatter.tex \
@@ -259,7 +258,6 @@
 	lib/libsymbol.tex \
 	lib/libbinhex.tex \
 	lib/libuu.tex \
-	lib/libsunaudio.tex \
 	lib/libfileinput.tex \
 	lib/libimaplib.tex \
 	lib/libpoplib.tex \

Modified: python/branches/py3k-buffer/Doc/api/concrete.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/api/concrete.tex	(original)
+++ python/branches/py3k-buffer/Doc/api/concrete.tex	Fri Aug 17 20:48:09 2007
@@ -996,10 +996,11 @@
   \var{u} is \NULL{}.
 \end{cfuncdesc}
 
-\begin{cfuncdesc}{PyObject*}{PyUnicode_FromString}{const char *u}
+\begin{cfuncdesc}{PyObject*}{PyUnicode_FromStringAndSize}{const char *u,
+                                                       Py_ssize_t size}
   Create a Unicode Object from the char buffer \var{u}.
-  \var{u} must be 0-terminated, the bytes will be interpreted as
-  being latin-1 encoded. \var{u} may also be \NULL{} which causes the
+  The bytes will be interpreted as being UTF-8 encoded. 
+  \var{u} may also be \NULL{} which causes the
   contents to be undefined. It is the user's responsibility to fill
   in the needed data.  The buffer is copied into the new object.
   If the buffer is not \NULL{}, the return value might be a shared object.
@@ -1008,6 +1009,12 @@
   \versionadded{3.0}
 \end{cfuncdesc}
 
+\begin{cfuncdesc}{PyObject*}{PyUnicode_FromString}{const char*u}
+   Create a Unicode object from an UTF-8 encoded null-terminated
+   char buffer \var{u}.
+   \versionadded{3.0}
+\end{funcdesc}
+
 \begin{cfuncdesc}{PyObject*}{PyUnicode_FromFormat}{const char *format, ...}
   Take a C \cfunction{printf()}-style \var{format} string and a
   variable number of arguments, calculate the size of the resulting

Modified: python/branches/py3k-buffer/Doc/ext/newtypes.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/ext/newtypes.tex	(original)
+++ python/branches/py3k-buffer/Doc/ext/newtypes.tex	Fri Aug 17 20:48:09 2007
@@ -1151,23 +1151,16 @@
 
 \subsection{Object Presentation}
 
-In Python, there are three ways to generate a textual representation
-of an object: the \function{repr()}\bifuncindex{repr} function (or
-equivalent back-tick syntax), the \function{str()}\bifuncindex{str}
-function, and the \keyword{print} statement.  For most objects, the
-\keyword{print} statement is equivalent to the \function{str()}
-function, but it is possible to special-case printing to a
-\ctype{FILE*} if necessary; this should only be done if efficiency is
-identified as a problem and profiling suggests that creating a
-temporary string object to be written to a file is too expensive.
+In Python, there are two ways to generate a textual representation
+of an object: the \function{repr()}\bifuncindex{repr} function, and
+the \function{str()}\bifuncindex{str} function.  (The
+\keyword{print} function just calls \function{str()}.)
 
-These handlers are all optional, and most types at most need to
-implement the \member{tp_str} and \member{tp_repr} handlers.
+These handlers are both optional.
 
 \begin{verbatim}
     reprfunc tp_repr;
     reprfunc tp_str;
-    printfunc tp_print;
 \end{verbatim}
 
 The \member{tp_repr} handler should return a string object containing
@@ -1750,7 +1743,7 @@
 data type, do the following: Download and unpack the Python source
 distribution.  Go the \file{Objects} directory, then search the
 C source files for \code{tp_} plus the function you want (for
-example, \code{tp_print} or \code{tp_compare}).  You will find
+example, \code{tp_compare}).  You will find
 examples of the function you want to implement.
 
 When you need to verify that an object is an instance of the type

Modified: python/branches/py3k-buffer/Doc/howto/urllib2.rst
==============================================================================
--- python/branches/py3k-buffer/Doc/howto/urllib2.rst	(original)
+++ python/branches/py3k-buffer/Doc/howto/urllib2.rst	Fri Aug 17 20:48:09 2007
@@ -541,7 +541,9 @@
 .. note::
 
     Currently ``urllib2`` *does not* support fetching of ``https``
-    locations through a proxy. This can be a problem.
+    locations through a proxy.  However, this can be enabled by extending
+    urllib2 as shown in the recipe [#]_.
+
 
 Sockets and Layers
 ==================
@@ -596,3 +598,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 
+       <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195>`_.
+ 

Modified: python/branches/py3k-buffer/Doc/info/Makefile
==============================================================================
--- python/branches/py3k-buffer/Doc/info/Makefile	(original)
+++ python/branches/py3k-buffer/Doc/info/Makefile	Fri Aug 17 20:48:09 2007
@@ -34,10 +34,10 @@
 
 check-emacs-version:
 	@v="`$(EMACS) --version 2>&1 | egrep '^(GNU |X)Emacs [12]*'`"; \
-	if `echo "$$v" | grep '^GNU Emacs 21' >/dev/null 2>&1`; then \
+	if `echo "$$v" | grep '^GNU Emacs 2[12]' >/dev/null 2>&1`; then \
 	  echo "Using $(EMACS) to build the info docs"; \
 	else \
-	  echo "GNU Emacs 21 is required to build the info docs"; \
+	  echo "GNU Emacs 21 or 22 is required to build the info docs"; \
 	  echo "Found $$v"; \
 	  false; \
 	fi

Modified: python/branches/py3k-buffer/Doc/lib/lib.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/lib.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/lib.tex	Fri Aug 17 20:48:09 2007
@@ -416,10 +416,6 @@
 % OTHER PLATFORM-SPECIFIC STUFF
 % =============
 
-\input{libsun}                  % SUNOS ONLY
-\input{libsunaudio}
-% XXX(nnorwitz): the modules below this comment should be kept.
-
 \input{windows}                 % MS Windows ONLY
 \input{libmsilib}
 \input{libmsvcrt}
@@ -430,9 +426,6 @@
 \input{libundoc}
 
 %\chapter{Obsolete Modules}
-%\input{libcmpcache}
-%\input{libcmp}
-%\input{libni}
 
 \chapter{Reporting Bugs}
 \input{reportingbugs}

Modified: python/branches/py3k-buffer/Doc/lib/libaudioop.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/libaudioop.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/libaudioop.tex	Fri Aug 17 20:48:09 2007
@@ -7,9 +7,8 @@
 
 The \module{audioop} module contains some useful operations on sound
 fragments.  It operates on sound fragments consisting of signed
-integer samples 8, 16 or 32 bits wide, stored in Python strings.  This
-is the same format as used by the \refmodule{al} and \refmodule{sunaudiodev}
-modules.  All scalar items are integers, unless specified otherwise.
+integer samples 8, 16 or 32 bits wide, stored in Python strings.
+All scalar items are integers, unless specified otherwise.
 
 % This para is mostly here to provide an excuse for the index entries...
 This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings.

Modified: python/branches/py3k-buffer/Doc/lib/libbsddb.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/libbsddb.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/libbsddb.tex	Fri Aug 17 20:48:09 2007
@@ -93,6 +93,17 @@
 interpretation.
 \end{funcdesc}
 
+\begin{classdesc}{StringKeys}{db}
+  Wrapper class around a DB object that supports string keys
+  (rather than bytes). All keys are encoded as UTF-8, then passed
+  to the underlying object. \versionadded{3.0}
+\end{classdesc}
+
+\begin{classdesc}{StringValues}{db}
+  Wrapper class around a DB object that supports string values
+  (rather than bytes). All values are encoded as UTF-8, then passed
+  to the underlying object. \versionadded{3.0}
+\end{classdesc}
 
 \begin{seealso}
   \seemodule{dbhash}{DBM-style interface to the \module{bsddb}}

Modified: python/branches/py3k-buffer/Doc/lib/librunpy.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/librunpy.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/librunpy.tex	Fri Aug 17 20:48:09 2007
@@ -56,9 +56,11 @@
 If the argument \var{alter_sys} is supplied and evaluates to
 \code{True}, then \code{sys.argv[0]} is updated with the value of
 \code{__file__} and \code{sys.modules[__name__]} is updated with a
-temporary module object for the module being executed. Both
-\code{sys.argv[0]} and \code{sys.modules[__name__]} are restored to
-their original values before the function returns.
+new module object for the module being executed. Note that neither
+\code{sys.argv[0]} nor \code{sys.modules[__name__]} are restored to
+their original values before the function returns - if client code
+needs these values preserved, it must either save them explicitly or
+else avoid enabling the automatic alterations to \module{sys}.
 
 Note that this manipulation of \module{sys} is not thread-safe. Other
 threads may see the partially initialised module, as well as the

Modified: python/branches/py3k-buffer/Doc/lib/libstringio.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/libstringio.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/libstringio.tex	Fri Aug 17 20:48:09 2007
@@ -78,6 +78,10 @@
 module, those provided by this module are not able to accept Unicode
 strings that cannot be encoded as plain \ASCII{} strings.
 
+Calling \function{StringIO()} with a Unicode string parameter populates
+the object with the buffer representation of the Unicode string, instead of
+encoding the string.
+
 Another difference from the \refmodule{StringIO} module is that calling
 \function{StringIO()} with a string parameter creates a read-only object.
 Unlike an object created without a string parameter, it does not have

Deleted: /python/branches/py3k-buffer/Doc/lib/libsun.tex
==============================================================================
--- /python/branches/py3k-buffer/Doc/lib/libsun.tex	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,7 +0,0 @@
-\chapter{SunOS Specific Services}
-\label{sunos}
-
-The modules described in this chapter provide interfaces to features
-that are unique to SunOS 5 (also known as Solaris version 2).
-
-\localmoduletable

Deleted: /python/branches/py3k-buffer/Doc/lib/libsunaudio.tex
==============================================================================
--- /python/branches/py3k-buffer/Doc/lib/libsunaudio.tex	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,146 +0,0 @@
-\section{\module{sunaudiodev} ---
-         Access to Sun audio hardware}
-
-\declaremodule{builtin}{sunaudiodev}
-  \platform{SunOS}
-\modulesynopsis{Access to Sun audio hardware.}
-
-
-This module allows you to access the Sun audio interface. The Sun
-audio hardware is capable of recording and playing back audio data
-in u-LAW\index{u-LAW} format with a sample rate of 8K per second. A
-full description can be found in the \manpage{audio}{7I} manual page.
-
-The module
-\refmodule[sunaudiodev-constants]{SUNAUDIODEV}\refstmodindex{SUNAUDIODEV} 
-defines constants which may be used with this module.
-
-This module defines the following variables and functions:
-
-\begin{excdesc}{error}
-This exception is raised on all errors. The argument is a string
-describing what went wrong.
-\end{excdesc}
-
-\begin{funcdesc}{open}{mode}
-This function opens the audio device and returns a Sun audio device
-object. This object can then be used to do I/O on. The \var{mode} parameter
-is one of \code{'r'} for record-only access, \code{'w'} for play-only
-access, \code{'rw'} for both and \code{'control'} for access to the
-control device. Since only one process is allowed to have the recorder
-or player open at the same time it is a good idea to open the device
-only for the activity needed. See \manpage{audio}{7I} for details.
-
-As per the manpage, this module first looks in the environment
-variable \code{AUDIODEV} for the base audio device filename.  If not
-found, it falls back to \file{/dev/audio}.  The control device is
-calculated by appending ``ctl'' to the base audio device.
-\end{funcdesc}
-
-
-\subsection{Audio Device Objects \label{audio-device-objects}}
-
-The audio device objects are returned by \function{open()} define the
-following methods (except \code{control} objects which only provide
-\method{getinfo()}, \method{setinfo()}, \method{fileno()}, and
-\method{drain()}):
-
-\begin{methoddesc}[audio device]{close}{}
-This method explicitly closes the device. It is useful in situations
-where deleting the object does not immediately close it since there
-are other references to it. A closed device should not be used again.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{fileno}{}
-Returns the file descriptor associated with the device.  This can be
-used to set up \code{SIGPOLL} notification, as described below.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{drain}{}
-This method waits until all pending output is processed and then returns.
-Calling this method is often not necessary: destroying the object will
-automatically close the audio device and this will do an implicit drain.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{flush}{}
-This method discards all pending output. It can be used avoid the
-slow response to a user's stop request (due to buffering of up to one
-second of sound).
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{getinfo}{}
-This method retrieves status information like input and output volume,
-etc. and returns it in the form of
-an audio status object. This object has no methods but it contains a
-number of attributes describing the current device status. The names
-and meanings of the attributes are described in
-\code{<sun/audioio.h>} and in the \manpage{audio}{7I}
-manual page.  Member names
-are slightly different from their C counterparts: a status object is
-only a single structure. Members of the \cdata{play} substructure have
-\samp{o_} prepended to their name and members of the \cdata{record}
-structure have \samp{i_}. So, the C member \cdata{play.sample_rate} is
-accessed as \member{o_sample_rate}, \cdata{record.gain} as \member{i_gain}
-and \cdata{monitor_gain} plainly as \member{monitor_gain}.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{ibufcount}{}
-This method returns the number of samples that are buffered on the
-recording side, i.e.\ the program will not block on a
-\function{read()} call of so many samples.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{obufcount}{}
-This method returns the number of samples buffered on the playback
-side. Unfortunately, this number cannot be used to determine a number
-of samples that can be written without blocking since the kernel
-output queue length seems to be variable.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{read}{size}
-This method reads \var{size} samples from the audio input and returns
-them as a Python string. The function blocks until enough data is available.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{setinfo}{status}
-This method sets the audio device status parameters. The \var{status}
-parameter is an device status object as returned by \function{getinfo()} and
-possibly modified by the program.
-\end{methoddesc}
-
-\begin{methoddesc}[audio device]{write}{samples}
-Write is passed a Python string containing audio samples to be played.
-If there is enough buffer space free it will immediately return,
-otherwise it will block.
-\end{methoddesc}
-
-The audio device supports asynchronous notification of various events,
-through the SIGPOLL signal.  Here's an example of how you might enable
-this in Python:
-
-\begin{verbatim}
-def handle_sigpoll(signum, frame):
-    print 'I got a SIGPOLL update'
-
-import fcntl, signal, STROPTS
-
-signal.signal(signal.SIGPOLL, handle_sigpoll)
-fcntl.ioctl(audio_obj.fileno(), STROPTS.I_SETSIG, STROPTS.S_MSG)
-\end{verbatim}
-
-
-\section{\module{SUNAUDIODEV} ---
-         Constants used with \module{sunaudiodev}}
-
-\declaremodule[sunaudiodev-constants]{standard}{SUNAUDIODEV}
-  \platform{SunOS}
-\modulesynopsis{Constants for use with \refmodule{sunaudiodev}.}
-
-
-This is a companion module to
-\refmodule{sunaudiodev}\refbimodindex{sunaudiodev} which defines
-useful symbolic constants like \constant{MIN_GAIN},
-\constant{MAX_GAIN}, \constant{SPEAKER}, etc. The names of the
-constants are the same names as used in the C include file
-\code{<sun/audioio.h>}, with the leading string \samp{AUDIO_}
-stripped.

Modified: python/branches/py3k-buffer/Doc/lib/libundoc.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/libundoc.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/libundoc.tex	Fri Aug 17 20:48:09 2007
@@ -52,19 +52,8 @@
 \section{Multimedia}
 
 \begin{description}
-\item[\module{audiodev}]
---- Platform-independent API for playing audio data.
-
-\item[\module{linuxaudiodev}]
---- Play audio data on the Linux audio device.  Replaced in Python 2.3
-    by the \module{ossaudiodev} module.
-
 \item[\module{sunaudio}]
 --- Interpret Sun audio headers (may become obsolete or a tool/demo).
-
-\item[\module{toaiff}]
---- Convert "arbitrary" sound files to AIFF files; should probably
-    become a tool or demo.  Requires the external program \program{sox}.
 \end{description}
 
 

Modified: python/branches/py3k-buffer/Doc/lib/libxmlrpclib.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/libxmlrpclib.tex	(original)
+++ python/branches/py3k-buffer/Doc/lib/libxmlrpclib.tex	Fri Aug 17 20:48:09 2007
@@ -94,7 +94,8 @@
 \samp{>}, and \samp{\&} will be automatically escaped.  However, it's
 the caller's responsibility to ensure that the string is free of
 characters that aren't allowed in XML, such as the control characters
-with ASCII values between 0 and 31; failing to do this will result in
+with ASCII values between 0 and 31 (except, of course, tab, newline and
+carriage return); failing to do this will result in
 an XML-RPC request that isn't well-formed XML.  If you have to pass
 arbitrary strings via XML-RPC, use the \class{Binary} wrapper class
 described below.

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_datetime.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_datetime.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_datetime.py	Fri Aug 17 20:48:09 2007
@@ -11,4 +11,4 @@
 
 now = datetime.datetime.now()
 cur.execute("select ?", (now,))
-print cur.fetchone()[0]
+print(cur.fetchone()[0])

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_1.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_1.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_1.py	Fri Aug 17 20:48:09 2007
@@ -13,4 +13,4 @@
 
 p = Point(4.0, -3.2)
 cur.execute("select ?", (p,))
-print cur.fetchone()[0]
+print(cur.fetchone()[0])

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_2.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_2.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/adapter_point_2.py	Fri Aug 17 20:48:09 2007
@@ -14,4 +14,4 @@
 
 p = Point(4.0, -3.2)
 cur.execute("select ?", (p,))
-print cur.fetchone()[0]
+print(cur.fetchone()[0])

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/collation_reverse.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/collation_reverse.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/collation_reverse.py	Fri Aug 17 20:48:09 2007
@@ -11,5 +11,5 @@
 cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
 cur.execute("select x from test order by x collate reverse")
 for row in cur:
-    print row
+    print(row)
 con.close()

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/complete_statement.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/complete_statement.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/complete_statement.py	Fri Aug 17 20:48:09 2007
@@ -8,11 +8,11 @@
 
 buffer = ""
 
-print "Enter your SQL commands to execute in sqlite3."
-print "Enter a blank line to exit."
+print("Enter your SQL commands to execute in sqlite3.")
+print("Enter a blank line to exit.")
 
 while True:
-    line = raw_input()
+    line = input()
     if line == "":
         break
     buffer += line
@@ -22,9 +22,9 @@
             cur.execute(buffer)
 
             if buffer.lstrip().upper().startswith("SELECT"):
-                print cur.fetchall()
+                print(cur.fetchall())
         except sqlite3.Error as e:
-            print "An error occurred:", e.args[0]
+            print("An error occurred:", e.args[0])
         buffer = ""
 
 con.close()

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/converter_point.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/converter_point.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/converter_point.py	Fri Aug 17 20:48:09 2007
@@ -11,7 +11,7 @@
     return "%f;%f" % (point.x, point.y)
 
 def convert_point(s):
-    x, y = map(float, s.split(";"))
+    x, y = list(map(float, s.split(";")))
     return Point(x, y)
 
 # Register the adapter
@@ -30,7 +30,7 @@
 
 cur.execute("insert into test(p) values (?)", (p,))
 cur.execute("select p from test")
-print "with declared types:", cur.fetchone()[0]
+print("with declared types:", cur.fetchone()[0])
 cur.close()
 con.close()
 
@@ -42,6 +42,6 @@
 
 cur.execute("insert into test(p) values (?)", (p,))
 cur.execute('select p as "p [point]" from test')
-print "with column names:", cur.fetchone()[0]
+print("with column names:", cur.fetchone()[0])
 cur.close()
 con.close()

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/countcursors.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/countcursors.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/countcursors.py	Fri Aug 17 20:48:09 2007
@@ -12,4 +12,4 @@
 con = sqlite3.connect(":memory:", factory=CountCursorsConnection)
 cur1 = con.cursor()
 cur2 = con.cursor()
-print con.numcursors
+print(con.numcursors)

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_fetchonerow.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_fetchonerow.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_fetchonerow.py	Fri Aug 17 20:48:09 2007
@@ -9,9 +9,9 @@
 # resulting sequences to yield their elements (name_last, age):
 cur.execute(SELECT)
 for (name_last, age) in cur:
-    print '%s is %d years old.' % (name_last, age)
+    print('%s is %d years old.' % (name_last, age))
 
 # 2. Equivalently:
 cur.execute(SELECT)
 for row in cur:
-    print '%s is %d years old.' % (row[0], row[1])
+    print('%s is %d years old.' % (row[0], row[1]))

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_printall_1.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_printall_1.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/execsql_printall_1.py	Fri Aug 17 20:48:09 2007
@@ -10,4 +10,4 @@
 cur.execute("select * from people order by age")
 
 # Retrieve all rows as a sequence and print that sequence:
-print cur.fetchall()
+print(cur.fetchall())

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/execute_1.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/execute_1.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/execute_1.py	Fri Aug 17 20:48:09 2007
@@ -8,4 +8,4 @@
 age = 72
 
 cur.execute("select name_last, age from people where name_last=? and age=?", (who, age))
-print cur.fetchone()
+print(cur.fetchone())

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/execute_2.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/execute_2.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/execute_2.py	Fri Aug 17 20:48:09 2007
@@ -9,4 +9,4 @@
 
 cur.execute("select name_last, age from people where name_last=:who and age=:age",
     {"who": who, "age": age})
-print cur.fetchone()
+print(cur.fetchone())

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/execute_3.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/execute_3.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/execute_3.py	Fri Aug 17 20:48:09 2007
@@ -9,4 +9,4 @@
 
 cur.execute("select name_last, age from people where name_last=:who and age=:age",
     locals())
-print cur.fetchone()
+print(cur.fetchone())

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_1.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_1.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_1.py	Fri Aug 17 20:48:09 2007
@@ -21,4 +21,4 @@
 cur.executemany("insert into characters(c) values (?)", theIter)
 
 cur.execute("select c from characters")
-print cur.fetchall()
+print(cur.fetchall())

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_2.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_2.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/executemany_2.py	Fri Aug 17 20:48:09 2007
@@ -12,4 +12,4 @@
 cur.executemany("insert into characters(c) values (?)", char_generator())
 
 cur.execute("select c from characters")
-print cur.fetchall()
+print(cur.fetchall())

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/md5func.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/md5func.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/md5func.py	Fri Aug 17 20:48:09 2007
@@ -1,11 +1,11 @@
 import sqlite3
-import md5
+import hashlib
 
 def md5sum(t):
-    return md5.md5(t).hexdigest()
+    return hashlib.md5(t).hexdigest()
 
 con = sqlite3.connect(":memory:")
 con.create_function("md5", 1, md5sum)
 cur = con.cursor()
 cur.execute("select md5(?)", ("foo",))
-print cur.fetchone()[0]
+print(cur.fetchone()[0])

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/mysumaggr.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/mysumaggr.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/mysumaggr.py	Fri Aug 17 20:48:09 2007
@@ -17,4 +17,4 @@
 cur.execute("insert into test(i) values (1)")
 cur.execute("insert into test(i) values (2)")
 cur.execute("select mysum(i) from test")
-print cur.fetchone()[0]
+print(cur.fetchone()[0])

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/parse_colnames.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/parse_colnames.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/parse_colnames.py	Fri Aug 17 20:48:09 2007
@@ -5,4 +5,4 @@
 cur = con.cursor()
 cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),))
 dt = cur.fetchone()[0]
-print dt, type(dt)
+print(dt, type(dt))

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/pysqlite_datetime.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/pysqlite_datetime.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/pysqlite_datetime.py	Fri Aug 17 20:48:09 2007
@@ -11,10 +11,10 @@
 cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
 cur.execute("select d, ts from test")
 row = cur.fetchone()
-print today, "=>", row[0], type(row[0])
-print now, "=>", row[1], type(row[1])
+print(today, "=>", row[0], type(row[0]))
+print(now, "=>", row[1], type(row[1]))
 
 cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
 row = cur.fetchone()
-print "current_date", row[0], type(row[0])
-print "current_timestamp", row[1], type(row[1])
+print("current_date", row[0], type(row[0]))
+print("current_timestamp", row[1], type(row[1]))

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/row_factory.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/row_factory.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/row_factory.py	Fri Aug 17 20:48:09 2007
@@ -10,4 +10,4 @@
 con.row_factory = dict_factory
 cur = con.cursor()
 cur.execute("select 1 as a")
-print cur.fetchone()["a"]
+print(cur.fetchone()["a"])

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/shortcut_methods.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/shortcut_methods.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/shortcut_methods.py	Fri Aug 17 20:48:09 2007
@@ -15,7 +15,7 @@
 
 # Print the table contents
 for row in con.execute("select firstname, lastname from person"):
-    print row
+    print(row)
 
 # Using a dummy WHERE clause to not let SQLite take the shortcut table deletes.
-print "I just deleted", con.execute("delete from person where 1=1").rowcount, "rows"
+print("I just deleted", con.execute("delete from person where 1=1").rowcount, "rows")

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/simple_tableprinter.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/simple_tableprinter.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/simple_tableprinter.py	Fri Aug 17 20:48:09 2007
@@ -11,9 +11,9 @@
 
 # Print a header.
 for fieldDesc in cur.description:
-    print fieldDesc[0].ljust(FIELD_MAX_WIDTH) ,
-print # Finish the header with a newline.
-print '-' * 78
+    print(fieldDesc[0].ljust(FIELD_MAX_WIDTH), end=' ')
+print() # Finish the header with a newline.
+print('-' * 78)
 
 # For each row, print the value of each field left-justified within
 # the maximum possible width of that field.
@@ -21,6 +21,6 @@
 for row in cur:
     for fieldIndex in fieldIndices:
         fieldValue = str(row[fieldIndex])
-        print fieldValue.ljust(FIELD_MAX_WIDTH) ,
+        print(fieldValue.ljust(FIELD_MAX_WIDTH), end=' ')
 
-    print # Finish the row with a newline.
+    print() # Finish the row with a newline.

Modified: python/branches/py3k-buffer/Doc/lib/sqlite3/text_factory.py
==============================================================================
--- python/branches/py3k-buffer/Doc/lib/sqlite3/text_factory.py	(original)
+++ python/branches/py3k-buffer/Doc/lib/sqlite3/text_factory.py	Fri Aug 17 20:48:09 2007
@@ -6,7 +6,7 @@
 # Create the table
 con.execute("create table person(lastname, firstname)")
 
-AUSTRIA = u"\xd6sterreich"
+AUSTRIA = "\xd6sterreich"
 
 # by default, rows are returned as Unicode
 cur.execute("select ?", (AUSTRIA,))
@@ -25,17 +25,17 @@
 # we can also implement a custom text_factory ...
 # here we implement one that will ignore Unicode characters that cannot be
 # decoded from UTF-8
-con.text_factory = lambda x: unicode(x, "utf-8", "ignore")
-cur.execute("select ?", ("this is latin1 and would normally create errors" + u"\xe4\xf6\xfc".encode("latin1"),))
+con.text_factory = lambda x: str(x, "utf-8", "ignore")
+cur.execute("select ?", ("this is latin1 and would normally create errors" + "\xe4\xf6\xfc".encode("latin1"),))
 row = cur.fetchone()
-assert type(row[0]) == unicode
+assert type(row[0]) == str
 
 # pysqlite offers a builtin optimized text_factory that will return bytestring
 # objects, if the data is in ASCII only, and otherwise return unicode objects
 con.text_factory = sqlite3.OptimizedUnicode
 cur.execute("select ?", (AUSTRIA,))
 row = cur.fetchone()
-assert type(row[0]) == unicode
+assert type(row[0]) == str
 
 cur.execute("select ?", ("Germany",))
 row = cur.fetchone()

Modified: python/branches/py3k-buffer/Doc/ref/ref3.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/ref/ref3.tex	(original)
+++ python/branches/py3k-buffer/Doc/ref/ref3.tex	Fri Aug 17 20:48:09 2007
@@ -1724,7 +1724,6 @@
   \ttindex{__imul__()}
   \ttindex{__contains__()}
   \ttindex{__iter__()}}
-\withsubitem{(numeric object method)}
 
 \begin{methoddesc}[container object]{__len__}{self}
 Called to implement the built-in function

Modified: python/branches/py3k-buffer/Doc/tools/indfix.py
==============================================================================
--- python/branches/py3k-buffer/Doc/tools/indfix.py	(original)
+++ python/branches/py3k-buffer/Doc/tools/indfix.py	Fri Aug 17 20:48:09 2007
@@ -19,7 +19,7 @@
 __version__ = '$Revision$'
 
 import re
-import StringIO
+import io
 import sys
 
 
@@ -50,7 +50,7 @@
         ifp = open(ifn)
     if ofn is None:
         ofn = ifn
-    ofp = StringIO.StringIO()
+    ofp = io.StringIO()
     entries = []
     match = breakable_re.match
     write = ofp.write

Modified: python/branches/py3k-buffer/Doc/tools/sgmlconv/docfixer.py
==============================================================================
--- python/branches/py3k-buffer/Doc/tools/sgmlconv/docfixer.py	(original)
+++ python/branches/py3k-buffer/Doc/tools/sgmlconv/docfixer.py	Fri Aug 17 20:48:09 2007
@@ -1055,8 +1055,8 @@
         ofp = sys.stdout
     elif len(sys.argv) == 3:
         ifp = open(sys.argv[1])
-        import StringIO
-        ofp = StringIO.StringIO()
+        import io
+        ofp = io.StringIO()
     else:
         usage()
         sys.exit(2)

Modified: python/branches/py3k-buffer/Doc/tut/tut.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/tut/tut.tex	(original)
+++ python/branches/py3k-buffer/Doc/tut/tut.tex	Fri Aug 17 20:48:09 2007
@@ -2942,15 +2942,14 @@
 statement looks for a top-level module with the given name.
 
 When packages are structured into subpackages (as with the
-\module{sound} package in the example), there's no shortcut to refer
-to submodules of sibling packages - the full name of the subpackage
-must be used.  For example, if the module
-\module{sound.filters.vocoder} needs to use the \module{echo} module
-in the \module{sound.effects} package, it can use \code{from
-sound.effects import echo}.
+\module{sound} package in the example), you can use absolute
+imports to refer to submodules of siblings packages.
+For example, if the module \module{sound.filters.vocoder} needs to
+use the \module{echo} module in the \module{sound.effects} package,
+it can use \code{from sound.effects import echo}.
 
 Starting with Python 2.5, in addition to the implicit relative imports
-described above, you can write explicit relative imports with the
+described above, you can also write explicit relative imports with the
 \code{from module import name} form of import statement. These explicit
 relative imports use leading dots to indicate the current and parent
 packages involved in the relative import. From the \module{surround}
@@ -3748,7 +3747,9 @@
 \keyword{finally} clause has been executed.  The \keyword{finally} clause
 is also executed ``on the way out'' when any other clause of the
 \keyword{try} statement is left via a \keyword{break}, \keyword{continue}
-or \keyword{return} statement.  A more complicated example:
+or \keyword{return} statement.  A more complicated example (having
+\keyword{except} and \keyword{finally} clauses in the same \keyword{try}
+statement works as of Python 2.5):
 
 \begin{verbatim}
 >>> def divide(x, y):

Modified: python/branches/py3k-buffer/Doc/whatsnew/whatsnew25.tex
==============================================================================
--- python/branches/py3k-buffer/Doc/whatsnew/whatsnew25.tex	(original)
+++ python/branches/py3k-buffer/Doc/whatsnew/whatsnew25.tex	Fri Aug 17 20:48:09 2007
@@ -640,15 +640,20 @@
 \end{verbatim}
 
 The expression is evaluated, and it should result in an object that
-supports the context management protocol.  This object may return a
-value that can optionally be bound to the name \var{variable}.  (Note
-carefully that \var{variable} is \emph{not} assigned the result of
-\var{expression}.)  The object can then run set-up code
-before \var{with-block} is executed and some clean-up code
-is executed after the block is done, even if the block raised an exception.
+supports the context management protocol (that is, has \method{__enter__()}
+and \method{__exit__()} methods.
 
-To enable the statement in Python 2.5, you need 
-to add the following directive to your module:
+The object's \method{__enter__()} is called before \var{with-block} is
+executed and therefore can run set-up code. It also may return a value
+that is bound to the name \var{variable}, if given.  (Note carefully
+that \var{variable} is \emph{not} assigned the result of \var{expression}.)
+
+After execution of the \var{with-block} is finished, the object's
+\method{__exit__()} method is called, even if the block raised an exception,
+and can therefore run clean-up code.
+
+To enable the statement in Python 2.5, you need to add the following
+directive to your module:
 
 \begin{verbatim}
 from __future__ import with_statement
@@ -668,9 +673,13 @@
 \end{verbatim}
 
 After this statement has executed, the file object in \var{f} will
-have been automatically closed, even if the 'for' loop
+have been automatically closed, even if the \keyword{for} loop
 raised an exception part-way through the block.
 
+\note{In this case, \var{f} is the same object created by
+      \function{open()}, because \method{file.__enter__()} returns
+      \var{self}.}
+
 The \module{threading} module's locks and condition variables 
 also support the '\keyword{with}' statement:
 

Modified: python/branches/py3k-buffer/Include/object.h
==============================================================================
--- python/branches/py3k-buffer/Include/object.h	(original)
+++ python/branches/py3k-buffer/Include/object.h	Fri Aug 17 20:48:09 2007
@@ -145,12 +145,10 @@
 typedef struct bufferinfo {
 	void *buf;         
         Py_ssize_t len;
+        Py_ssize_t itemsize;  
         int readonly;
-        Py_ssize_t itemsize;  /* This is Py_ssize_t so it can
-                                 be the strides array for the most
-                                 common case */
+        int ndim 
         char *format;
-        int ndim;
         Py_ssize_t *shape;
         Py_ssize_t *strides;
         Py_ssize_t *suboffsets;

Modified: python/branches/py3k-buffer/Include/structmember.h
==============================================================================
--- python/branches/py3k-buffer/Include/structmember.h	(original)
+++ python/branches/py3k-buffer/Include/structmember.h	Fri Aug 17 20:48:09 2007
@@ -68,11 +68,12 @@
 #ifdef HAVE_LONG_LONG
 #define T_LONGLONG      17  
 #define T_ULONGLONG     18
-#define T_PYSSIZET       19 /* Py_ssize_t */
 #endif /* HAVE_LONG_LONG */
 
+#define T_PYSSIZET      19      /* Py_ssize_t */
 #define T_NONE          20      /* Value is always None */
 
+
 /* Flags */
 #define READONLY	1
 #define RO		READONLY		/* Shorthand */

Modified: python/branches/py3k-buffer/Include/unicodeobject.h
==============================================================================
--- python/branches/py3k-buffer/Include/unicodeobject.h	(original)
+++ python/branches/py3k-buffer/Include/unicodeobject.h	Fri Aug 17 20:48:09 2007
@@ -710,7 +710,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length,	 		/* number of Py_UNICODE chars to encode */
+    Py_ssize_t length,	 	/* number of Py_UNICODE chars to encode */
     int encodeSetO,             /* force the encoder to encode characters in
                                    Set O, as described in RFC2152 */
     int encodeWhiteSpace,       /* force the encoder to encode space, tab,
@@ -730,7 +730,7 @@
     const char *string, 	/* UTF-8 encoded string */
     Py_ssize_t length,	 	/* size of string */
     const char *errors,		/* error handling */
-    Py_ssize_t *consumed		/* bytes consumed */
+    Py_ssize_t *consumed	/* bytes consumed */
     );
 
 PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String(
@@ -739,7 +739,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length,	 		/* number of Py_UNICODE chars to encode */
+    Py_ssize_t length,	 	/* number of Py_UNICODE chars to encode */
     const char *errors		/* error handling */
     );
 
@@ -784,7 +784,7 @@
     int *byteorder,		/* pointer to byteorder to use
 				   0=native;-1=LE,1=BE; updated on
 				   exit */
-    Py_ssize_t *consumed		/* bytes consumed */
+    Py_ssize_t *consumed	/* bytes consumed */
     );
 
 /* Returns a Python string using the UTF-16 encoding in native byte
@@ -816,7 +816,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length,	 		/* number of Py_UNICODE chars to encode */
+    Py_ssize_t length,	 	/* number of Py_UNICODE chars to encode */
     const char *errors,		/* error handling */
     int byteorder		/* byteorder to use 0=BOM+native;-1=LE,1=BE */
     );
@@ -835,7 +835,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length	 		/* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length	 	/* Number of Py_UNICODE chars to encode */
     );
 
 /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
@@ -852,7 +852,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length	 		/* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length	 	/* Number of Py_UNICODE chars to encode */
     );
 
 /* --- Unicode Internal Codec ---------------------------------------------
@@ -883,7 +883,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length,	 		/* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length,	 	/* Number of Py_UNICODE chars to encode */
     const char *errors		/* error handling */
     );
 
@@ -905,7 +905,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length,	 		/* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length,	 	/* Number of Py_UNICODE chars to encode */
     const char *errors		/* error handling */
     );
 
@@ -968,7 +968,7 @@
 
 PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap(
     const Py_UNICODE *data, 	/* Unicode char buffer */
-    Py_ssize_t length,	 		/* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length,	 	/* Number of Py_UNICODE chars to encode */
     PyObject *table,		/* Translate table */
     const char *errors		/* error handling */
     );
@@ -996,7 +996,7 @@
 
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
     const Py_UNICODE *data,     /* Unicode char buffer */
-    Py_ssize_t length,              /* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
     const char *errors          /* error handling */
     );
 
@@ -1028,7 +1028,7 @@
 
 PyAPI_FUNC(int) PyUnicode_EncodeDecimal(
     Py_UNICODE *s,		/* Unicode buffer */
-    Py_ssize_t length,			/* Number of Py_UNICODE chars to encode */
+    Py_ssize_t length,		/* Number of Py_UNICODE chars to encode */
     char *output,		/* Output buffer; must have size >= length */
     const char *errors		/* error handling */
     );

Modified: python/branches/py3k-buffer/Lib/BaseHTTPServer.py
==============================================================================
--- python/branches/py3k-buffer/Lib/BaseHTTPServer.py	(original)
+++ python/branches/py3k-buffer/Lib/BaseHTTPServer.py	Fri Aug 17 20:48:09 2007
@@ -230,7 +230,7 @@
         self.command = None  # set in case of error on the first line
         self.request_version = version = "HTTP/0.9" # Default
         self.close_connection = 1
-        requestline = self.raw_requestline
+        requestline = str(self.raw_requestline, 'iso-8859-1')
         if requestline[-2:] == '\r\n':
             requestline = requestline[:-2]
         elif requestline[-1:] == '\n':

Modified: python/branches/py3k-buffer/Lib/SocketServer.py
==============================================================================
--- python/branches/py3k-buffer/Lib/SocketServer.py	(original)
+++ python/branches/py3k-buffer/Lib/SocketServer.py	Fri Aug 17 20:48:09 2007
@@ -574,10 +574,10 @@
     """Define self.rfile and self.wfile for datagram sockets."""
 
     def setup(self):
-        from io import StringIO
+        from io import BytesIO
         self.packet, self.socket = self.request
-        self.rfile = StringIO(self.packet)
-        self.wfile = StringIO()
+        self.rfile = BytesIO(self.packet)
+        self.wfile = BytesIO()
 
     def finish(self):
         self.socket.sendto(self.wfile.getvalue(), self.client_address)

Deleted: /python/branches/py3k-buffer/Lib/StringIO.py
==============================================================================
--- /python/branches/py3k-buffer/Lib/StringIO.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,324 +0,0 @@
-r"""File-like objects that read from or write to a string buffer.
-
-This implements (nearly) all stdio methods.
-
-f = StringIO()      # ready for writing
-f = StringIO(buf)   # ready for reading
-f.close()           # explicitly release resources held
-flag = f.isatty()   # always false
-pos = f.tell()      # get current position
-f.seek(pos)         # set current position
-f.seek(pos, mode)   # mode 0: absolute; 1: relative; 2: relative to EOF
-buf = f.read()      # read until EOF
-buf = f.read(n)     # read up to n bytes
-buf = f.readline()  # read until end of line ('\n') or EOF
-list = f.readlines()# list of f.readline() results until EOF
-f.truncate([size])  # truncate file at to at most size (default: current pos)
-f.write(buf)        # write at current position
-f.writelines(list)  # for line in list: f.write(line)
-f.getvalue()        # return whole file's contents as a string
-
-Notes:
-- Using a real file is often faster (but less convenient).
-- There's also a much faster implementation in C, called cStringIO, but
-  it's not subclassable.
-- fileno() is left unimplemented so that code which uses it triggers
-  an exception early.
-- Seeking far beyond EOF and then writing will insert real null
-  bytes that occupy space in the buffer.
-- There's a simple test set (see end of this file).
-"""
-try:
-    from errno import EINVAL
-except ImportError:
-    EINVAL = 22
-
-__all__ = ["StringIO"]
-
-def _complain_ifclosed(closed):
-    if closed:
-        raise ValueError, "I/O operation on closed file"
-
-class StringIO:
-    """class StringIO([buffer])
-
-    When a StringIO object is created, it can be initialized to an existing
-    string by passing the string to the constructor. If no string is given,
-    the StringIO will start empty.
-
-    The StringIO object can accept either Unicode or 8-bit strings, but
-    mixing the two may take some care. If both are used, 8-bit strings that
-    cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause
-    a UnicodeError to be raised when getvalue() is called.
-    """
-    def __init__(self, buf = ''):
-        # Force self.buf to be a string or unicode
-        if not isinstance(buf, basestring):
-            buf = str(buf)
-        self.buf = buf
-        self.len = len(buf)
-        self.buflist = []
-        self.pos = 0
-        self.closed = False
-
-    def __iter__(self):
-        return self
-
-    def __next__(self):
-        """A file object is its own iterator, for example iter(f) returns f
-        (unless f is closed). When a file is used as an iterator, typically
-        in a for loop (for example, for line in f: print line), the __next__()
-        method is called repeatedly. This method returns the next input line,
-        or raises StopIteration when EOF is hit.
-        """
-        _complain_ifclosed(self.closed)
-        r = self.readline()
-        if not r:
-            raise StopIteration
-        return r
-
-    def close(self):
-        """Free the memory buffer.
-        """
-        if not self.closed:
-            self.closed = True
-            del self.buf, self.pos
-
-    def isatty(self):
-        """Returns False because StringIO objects are not connected to a
-        tty-like device.
-        """
-        _complain_ifclosed(self.closed)
-        return False
-
-    def seek(self, pos, mode = 0):
-        """Set the file's current position.
-
-        The mode argument is optional and defaults to 0 (absolute file
-        positioning); other values are 1 (seek relative to the current
-        position) and 2 (seek relative to the file's end).
-
-        There is no return value.
-        """
-        _complain_ifclosed(self.closed)
-        if self.buflist:
-            self.buf += ''.join(self.buflist)
-            self.buflist = []
-        if mode == 1:
-            pos += self.pos
-        elif mode == 2:
-            pos += self.len
-        self.pos = max(0, pos)
-
-    def tell(self):
-        """Return the file's current position."""
-        _complain_ifclosed(self.closed)
-        return self.pos
-
-    def read(self, n=None):
-        """Read at most size bytes from the file
-        (less if the read hits EOF before obtaining size bytes).
-
-        If the size argument is negative or omitted, read all data until EOF
-        is reached. The bytes are returned as a string object. An empty
-        string is returned when EOF is encountered immediately.
-        """
-        _complain_ifclosed(self.closed)
-        if self.buflist:
-            self.buf += ''.join(self.buflist)
-            self.buflist = []
-        if n is None:
-            n = -1
-        if n < 0:
-            newpos = self.len
-        else:
-            newpos = min(self.pos+n, self.len)
-        r = self.buf[self.pos:newpos]
-        self.pos = newpos
-        return r
-
-    def readline(self, length=None):
-        r"""Read one entire line from the file.
-
-        A trailing newline character is kept in the string (but may be absent
-        when a file ends with an incomplete line). If the size argument is
-        present and non-negative, it is a maximum byte count (including the
-        trailing newline) and an incomplete line may be returned.
-
-        An empty string is returned only when EOF is encountered immediately.
-
-        Note: Unlike stdio's fgets(), the returned string contains null
-        characters ('\0') if they occurred in the input.
-        """
-        _complain_ifclosed(self.closed)
-        if self.buflist:
-            self.buf += ''.join(self.buflist)
-            self.buflist = []
-        i = self.buf.find('\n', self.pos)
-        if i < 0:
-            newpos = self.len
-        else:
-            newpos = i+1
-        if length is not None:
-            if self.pos + length < newpos:
-                newpos = self.pos + length
-        r = self.buf[self.pos:newpos]
-        self.pos = newpos
-        return r
-
-    def readlines(self, sizehint = 0):
-        """Read until EOF using readline() and return a list containing the
-        lines thus read.
-
-        If the optional sizehint argument is present, instead of reading up
-        to EOF, whole lines totalling approximately sizehint bytes (or more
-        to accommodate a final whole line).
-        """
-        total = 0
-        lines = []
-        line = self.readline()
-        while line:
-            lines.append(line)
-            total += len(line)
-            if 0 < sizehint <= total:
-                break
-            line = self.readline()
-        return lines
-
-    def truncate(self, size=None):
-        """Truncate the file's size.
-
-        If the optional size argument is present, the file is truncated to
-        (at most) that size. The size defaults to the current position.
-        The current file position is not changed unless the position
-        is beyond the new file size.
-
-        If the specified size exceeds the file's current size, the
-        file remains unchanged.
-        """
-        _complain_ifclosed(self.closed)
-        if size is None:
-            size = self.pos
-        elif size < 0:
-            raise IOError(EINVAL, "Negative size not allowed")
-        elif size < self.pos:
-            self.pos = size
-        self.buf = self.getvalue()[:size]
-        self.len = size
-
-    def write(self, s):
-        """Write a string to the file.
-
-        There is no return value.
-        """
-        _complain_ifclosed(self.closed)
-        if not s: return
-        # Force s to be a string or unicode
-        if not isinstance(s, basestring):
-            s = str(s)
-        spos = self.pos
-        slen = self.len
-        if spos == slen:
-            self.buflist.append(s)
-            self.len = self.pos = spos + len(s)
-            return
-        if spos > slen:
-            self.buflist.append('\0'*(spos - slen))
-            slen = spos
-        newpos = spos + len(s)
-        if spos < slen:
-            if self.buflist:
-                self.buf += ''.join(self.buflist)
-            self.buflist = [self.buf[:spos], s, self.buf[newpos:]]
-            self.buf = ''
-            if newpos > slen:
-                slen = newpos
-        else:
-            self.buflist.append(s)
-            slen = newpos
-        self.len = slen
-        self.pos = newpos
-
-    def writelines(self, iterable):
-        """Write a sequence of strings to the file. The sequence can be any
-        iterable object producing strings, typically a list of strings. There
-        is no return value.
-
-        (The name is intended to match readlines(); writelines() does not add
-        line separators.)
-        """
-        write = self.write
-        for line in iterable:
-            write(line)
-
-    def flush(self):
-        """Flush the internal buffer
-        """
-        _complain_ifclosed(self.closed)
-
-    def getvalue(self):
-        """
-        Retrieve the entire contents of the "file" at any time before
-        the StringIO object's close() method is called.
-
-        The StringIO object can accept either Unicode or 8-bit strings,
-        but mixing the two may take some care. If both are used, 8-bit
-        strings that cannot be interpreted as 7-bit ASCII (that use the
-        8th bit) will cause a UnicodeError to be raised when getvalue()
-        is called.
-        """
-        if self.buflist:
-            self.buf += ''.join(self.buflist)
-            self.buflist = []
-        return self.buf
-
-
-# A little test suite
-
-def test():
-    import sys
-    if sys.argv[1:]:
-        file = sys.argv[1]
-    else:
-        file = '/etc/passwd'
-    lines = open(file, 'r').readlines()
-    text = open(file, 'r').read()
-    f = StringIO()
-    for line in lines[:-2]:
-        f.write(line)
-    f.writelines(lines[-2:])
-    if f.getvalue() != text:
-        raise RuntimeError, 'write failed'
-    length = f.tell()
-    print('File length =', length)
-    f.seek(len(lines[0]))
-    f.write(lines[1])
-    f.seek(0)
-    print('First line =', repr(f.readline()))
-    print('Position =', f.tell())
-    line = f.readline()
-    print('Second line =', repr(line))
-    f.seek(-len(line), 1)
-    line2 = f.read(len(line))
-    if line != line2:
-        raise RuntimeError, 'bad result after seek back'
-    f.seek(len(line2), 1)
-    list = f.readlines()
-    line = list[-1]
-    f.seek(f.tell() - len(line))
-    line2 = f.read()
-    if line != line2:
-        raise RuntimeError, 'bad result after seek back from EOF'
-    print('Read', len(list), 'more lines')
-    print('File length =', f.tell())
-    if f.tell() != length:
-        raise RuntimeError, 'bad length'
-    f.truncate(length/2)
-    f.seek(0, 2)
-    print('Truncated length =', f.tell())
-    if f.tell() != length/2:
-        raise RuntimeError, 'truncate did not adjust length'
-    f.close()
-
-if __name__ == '__main__':
-    test()

Modified: python/branches/py3k-buffer/Lib/abc.py
==============================================================================
--- python/branches/py3k-buffer/Lib/abc.py	(original)
+++ python/branches/py3k-buffer/Lib/abc.py	Fri Aug 17 20:48:09 2007
@@ -24,6 +24,33 @@
     return funcobj
 
 
+class abstractproperty(property):
+    """A decorator indicating abstract properties.
+
+    Requires that the metaclass is ABCMeta or derived from it.  A
+    class that has a metaclass derived from ABCMeta cannot be
+    instantiated unless all of its abstract properties are overridden.
+    The abstract properties can be called using any of the the normal
+    'super' call mechanisms.
+
+    Usage:
+
+        class C(metaclass=ABCMeta):
+            @abstractproperty
+            def my_abstract_property(self):
+                ...
+
+    This defines a read-only property; you can also define a read-write
+    abstract property using the 'long' form of property declaration:
+
+        class C(metaclass=ABCMeta):
+            def getx(self): ...
+            def setx(self, value): ...
+            x = abstractproperty(getx, setx)
+    """
+    __isabstractmethod__ = True
+
+
 class _Abstract(object):
 
     """Helper class inserted into the bases by ABCMeta (using _fix_bases()).

Modified: python/branches/py3k-buffer/Lib/asynchat.py
==============================================================================
--- python/branches/py3k-buffer/Lib/asynchat.py	(original)
+++ python/branches/py3k-buffer/Lib/asynchat.py	Fri Aug 17 20:48:09 2007
@@ -104,7 +104,7 @@
             if not terminator:
                 # no terminator, collect it all
                 self.collect_incoming_data (self.ac_in_buffer)
-                self.ac_in_buffer = ''
+                self.ac_in_buffer = b''
             elif isinstance(terminator, int) or isinstance(terminator, int):
                 # numeric terminator
                 n = terminator

Deleted: /python/branches/py3k-buffer/Lib/audiodev.py
==============================================================================
--- /python/branches/py3k-buffer/Lib/audiodev.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,257 +0,0 @@
-"""Classes for manipulating audio devices (currently only for Sun and SGI)"""
-
-__all__ = ["error","AudioDev"]
-
-class error(Exception):
-    pass
-
-class Play_Audio_sgi:
-    # Private instance variables
-##      if 0: access frameratelist, nchannelslist, sampwidthlist, oldparams, \
-##                params, config, inited_outrate, inited_width, \
-##                inited_nchannels, port, converter, classinited: private
-
-    classinited = 0
-    frameratelist = nchannelslist = sampwidthlist = None
-
-    def initclass(self):
-        import AL
-        self.frameratelist = [
-                  (48000, AL.RATE_48000),
-                  (44100, AL.RATE_44100),
-                  (32000, AL.RATE_32000),
-                  (22050, AL.RATE_22050),
-                  (16000, AL.RATE_16000),
-                  (11025, AL.RATE_11025),
-                  ( 8000,  AL.RATE_8000),
-                  ]
-        self.nchannelslist = [
-                  (1, AL.MONO),
-                  (2, AL.STEREO),
-                  (4, AL.QUADRO),
-                  ]
-        self.sampwidthlist = [
-                  (1, AL.SAMPLE_8),
-                  (2, AL.SAMPLE_16),
-                  (3, AL.SAMPLE_24),
-                  ]
-        self.classinited = 1
-
-    def __init__(self):
-        import al, AL
-        if not self.classinited:
-            self.initclass()
-        self.oldparams = []
-        self.params = [AL.OUTPUT_RATE, 0]
-        self.config = al.newconfig()
-        self.inited_outrate = 0
-        self.inited_width = 0
-        self.inited_nchannels = 0
-        self.converter = None
-        self.port = None
-        return
-
-    def __del__(self):
-        if self.port:
-            self.stop()
-        if self.oldparams:
-            import al, AL
-            al.setparams(AL.DEFAULT_DEVICE, self.oldparams)
-            self.oldparams = []
-
-    def wait(self):
-        if not self.port:
-            return
-        import time
-        while self.port.getfilled() > 0:
-            time.sleep(0.1)
-        self.stop()
-
-    def stop(self):
-        if self.port:
-            self.port.closeport()
-            self.port = None
-        if self.oldparams:
-            import al, AL
-            al.setparams(AL.DEFAULT_DEVICE, self.oldparams)
-            self.oldparams = []
-
-    def setoutrate(self, rate):
-        for (raw, cooked) in self.frameratelist:
-            if rate == raw:
-                self.params[1] = cooked
-                self.inited_outrate = 1
-                break
-        else:
-            raise error, 'bad output rate'
-
-    def setsampwidth(self, width):
-        for (raw, cooked) in self.sampwidthlist:
-            if width == raw:
-                self.config.setwidth(cooked)
-                self.inited_width = 1
-                break
-        else:
-            if width == 0:
-                import AL
-                self.inited_width = 0
-                self.config.setwidth(AL.SAMPLE_16)
-                self.converter = self.ulaw2lin
-            else:
-                raise error, 'bad sample width'
-
-    def setnchannels(self, nchannels):
-        for (raw, cooked) in self.nchannelslist:
-            if nchannels == raw:
-                self.config.setchannels(cooked)
-                self.inited_nchannels = 1
-                break
-        else:
-            raise error, 'bad # of channels'
-
-    def writeframes(self, data):
-        if not (self.inited_outrate and self.inited_nchannels):
-            raise error, 'params not specified'
-        if not self.port:
-            import al, AL
-            self.port = al.openport('Python', 'w', self.config)
-            self.oldparams = self.params[:]
-            al.getparams(AL.DEFAULT_DEVICE, self.oldparams)
-            al.setparams(AL.DEFAULT_DEVICE, self.params)
-        if self.converter:
-            data = self.converter(data)
-        self.port.writesamps(data)
-
-    def getfilled(self):
-        if self.port:
-            return self.port.getfilled()
-        else:
-            return 0
-
-    def getfillable(self):
-        if self.port:
-            return self.port.getfillable()
-        else:
-            return self.config.getqueuesize()
-
-    # private methods
-##      if 0: access *: private
-
-    def ulaw2lin(self, data):
-        import audioop
-        return audioop.ulaw2lin(data, 2)
-
-class Play_Audio_sun:
-##      if 0: access outrate, sampwidth, nchannels, inited_outrate, inited_width, \
-##                inited_nchannels, converter: private
-
-    def __init__(self):
-        self.outrate = 0
-        self.sampwidth = 0
-        self.nchannels = 0
-        self.inited_outrate = 0
-        self.inited_width = 0
-        self.inited_nchannels = 0
-        self.converter = None
-        self.port = None
-        return
-
-    def __del__(self):
-        self.stop()
-
-    def setoutrate(self, rate):
-        self.outrate = rate
-        self.inited_outrate = 1
-
-    def setsampwidth(self, width):
-        self.sampwidth = width
-        self.inited_width = 1
-
-    def setnchannels(self, nchannels):
-        self.nchannels = nchannels
-        self.inited_nchannels = 1
-
-    def writeframes(self, data):
-        if not (self.inited_outrate and self.inited_width and self.inited_nchannels):
-            raise error, 'params not specified'
-        if not self.port:
-            import sunaudiodev, SUNAUDIODEV
-            self.port = sunaudiodev.open('w')
-            info = self.port.getinfo()
-            info.o_sample_rate = self.outrate
-            info.o_channels = self.nchannels
-            if self.sampwidth == 0:
-                info.o_precision = 8
-                self.o_encoding = SUNAUDIODEV.ENCODING_ULAW
-                # XXX Hack, hack -- leave defaults
-            else:
-                info.o_precision = 8 * self.sampwidth
-                info.o_encoding = SUNAUDIODEV.ENCODING_LINEAR
-                self.port.setinfo(info)
-        if self.converter:
-            data = self.converter(data)
-        self.port.write(data)
-
-    def wait(self):
-        if not self.port:
-            return
-        self.port.drain()
-        self.stop()
-
-    def stop(self):
-        if self.port:
-            self.port.flush()
-            self.port.close()
-            self.port = None
-
-    def getfilled(self):
-        if self.port:
-            return self.port.obufcount()
-        else:
-            return 0
-
-##    # Nobody remembers what this method does, and it's broken. :-(
-##    def getfillable(self):
-##        return BUFFERSIZE - self.getfilled()
-
-def AudioDev():
-    # Dynamically try to import and use a platform specific module.
-    try:
-        import al
-    except ImportError:
-        try:
-            import sunaudiodev
-            return Play_Audio_sun()
-        except ImportError:
-            try:
-                import Audio_mac
-            except ImportError:
-                raise error, 'no audio device'
-            else:
-                return Audio_mac.Play_Audio_mac()
-    else:
-        return Play_Audio_sgi()
-
-def test(fn = None):
-    import sys
-    if sys.argv[1:]:
-        fn = sys.argv[1]
-    else:
-        fn = 'f:just samples:just.aif'
-    import aifc
-    af = aifc.open(fn, 'r')
-    print(fn, af.getparams())
-    p = AudioDev()
-    p.setoutrate(af.getframerate())
-    p.setsampwidth(af.getsampwidth())
-    p.setnchannels(af.getnchannels())
-    BUFSIZ = af.getframerate()/af.getsampwidth()/af.getnchannels()
-    while 1:
-        data = af.readframes(BUFSIZ)
-        if not data: break
-        print(len(data))
-        p.writeframes(data)
-    p.wait()
-
-if __name__ == '__main__':
-    test()

Modified: python/branches/py3k-buffer/Lib/bsddb/__init__.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/__init__.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/__init__.py	Fri Aug 17 20:48:09 2007
@@ -64,15 +64,9 @@
 
 #----------------------------------------------------------------------
 
-import sys, os
+import sys, os, UserDict
+from weakref import ref
 
-# for backwards compatibility with python versions older than 2.3, the
-# iterator interface is dynamically defined and added using a mixin
-# class.  old python can't tokenize it due to the yield keyword.
-if sys.version >= '2.3':
-    import UserDict
-    from weakref import ref
-    exec("""
 class _iter_mixin(UserDict.DictMixin):
     def _make_iter_cursor(self):
         cur = _DeadlockWrap(self.db.cursor)
@@ -145,10 +139,6 @@
         except _bsddb.DBCursorClosedError:
             # the database was modified during iteration.  abort.
             return
-""")
-else:
-    class _iter_mixin: pass
-
 
 class _DBWithCursor(_iter_mixin):
     """
@@ -290,6 +280,138 @@
         self._checkOpen()
         return _DeadlockWrap(self.db.sync)
 
+class _ExposedProperties:
+    @property
+    def _cursor_refs(self):
+        return self.db._cursor_refs
+
+class StringKeys(UserDict.DictMixin, _ExposedProperties):
+    """Wrapper around DB object that automatically encodes
+    all keys as UTF-8; the keys must be strings."""
+
+    def __init__(self, db):
+        self.db = db
+
+    def __len__(self):
+        return len(self.db)
+
+    def __getitem__(self, key):
+        return self.db[key.encode("utf-8")]
+
+    def __setitem__(self, key, value):
+        self.db[key.encode("utf-8")] = value
+
+    def __delitem__(self, key):
+        del self.db[key.encode("utf-8")]
+
+    def __iter__(self):
+        for k in self.db:
+            yield k.decode("utf-8")
+
+    def close(self):
+        self.db.close()
+
+    def keys(self):
+        for k in self.db.keys():
+            yield k.decode("utf-8")
+
+    def has_key(self, key):
+        return self.db.has_key(key.encode("utf-8"))
+
+    __contains__ = has_key
+
+    def values(self):
+        return self.db.values()
+
+    def items(self):
+        for k,v in self.db.items():
+            yield k.decode("utf-8"), v
+
+    def set_location(self, key):
+        return self.db.set_location(key.encode("utf-8"))
+
+    def next(self):
+        key, value = self.db.next()
+        return key.decode("utf-8"), value
+
+    def previous(self):
+        key, value = self.db.previous()
+        return key.decode("utf-8"), value
+
+    def first(self):
+        key, value = self.db.first()
+        return key.decode("utf-8"), value
+
+    def last(self):
+        key, value = self.db.last()
+        return key.decode("utf-8"), value
+
+    def sync(self):
+        return self.db.sync()
+
+class StringValues(UserDict.DictMixin, _ExposedProperties):
+    """Wrapper around DB object that automatically encodes
+    all keys as UTF-8; the keys must be strings."""
+
+    def __init__(self, db):
+        self.db = db
+
+    def __len__(self):
+        return len(self.db)
+
+    def __getitem__(self, key):
+        return self.db[key].decode("utf-8")
+
+    def __setitem__(self, key, value):
+        self.db[key] = value.encode("utf-8")
+
+    def __delitem__(self, key):
+        del self.db[key]
+
+    def __iter__(self):
+        return iter(self.db)
+
+    def close(self):
+        self.db.close()
+
+    def keys(self):
+        return self.db.keys()
+
+    def has_key(self, key):
+        return self.db.has_key(key)
+
+    __contains__ = has_key
+
+    def values(self):
+        for v in self.db.values():
+            yield v.decode("utf-8")
+
+    def items(self):
+        for k,v in self.db.items():
+            yield k, v.decode("utf-8")
+
+    def set_location(self, key):
+        return self.db.set_location(key)
+
+    def next(self):
+        key, value = self.db.next()
+        return key, value.decode("utf-8")
+
+    def previous(self):
+        key, value = self.db.previous()
+        return key, value.decode("utf-8")
+
+    def first(self):
+        key, value = self.db.first()
+        return key, value.decode("utf-8")
+
+    def last(self):
+        key, value = self.db.last()
+        return key, value.decode("utf-8")
+
+    def sync(self):
+        return self.db.sync()
+
 
 #----------------------------------------------------------------------
 # Compatibility object factory functions
@@ -375,7 +497,7 @@
         if file is not None and os.path.isfile(file):
             os.unlink(file)
     else:
-        raise error, "flags should be one of 'r', 'w', 'c' or 'n'"
+        raise error, "flags should be one of 'r', 'w', 'c' or 'n', not "+repr(flag)
     return flags | db.DB_THREAD
 
 #----------------------------------------------------------------------

Modified: python/branches/py3k-buffer/Lib/bsddb/dbshelve.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/dbshelve.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/dbshelve.py	Fri Aug 17 20:48:09 2007
@@ -29,7 +29,7 @@
 
 #------------------------------------------------------------------------
 
-import cPickle
+import pickle
 try:
     from UserDict import DictMixin
 except ImportError:
@@ -104,11 +104,11 @@
 
     def __getitem__(self, key):
         data = self.db[key]
-        return cPickle.loads(data)
+        return pickle.loads(data)
 
 
     def __setitem__(self, key, value):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         self.db[key] = data
 
 
@@ -131,7 +131,7 @@
         newitems = []
 
         for k, v in items:
-            newitems.append( (k, cPickle.loads(v)) )
+            newitems.append( (k, pickle.loads(v)) )
         return newitems
 
     def values(self, txn=None):
@@ -140,13 +140,13 @@
         else:
             values = self.db.values()
 
-        return map(cPickle.loads, values)
+        return map(pickle.loads, values)
 
     #-----------------------------------
     # Other methods
 
     def __append(self, value, txn=None):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         return self.db.append(data, txn)
 
     def append(self, value, txn=None):
@@ -158,7 +158,7 @@
 
     def associate(self, secondaryDB, callback, flags=0):
         def _shelf_callback(priKey, priData, realCallback=callback):
-            data = cPickle.loads(priData)
+            data = pickle.loads(priData)
             return realCallback(priKey, data)
         return self.db.associate(secondaryDB, _shelf_callback, flags)
 
@@ -171,15 +171,15 @@
         # off.
         data = self.db.get(*args, **kw)
         try:
-            return cPickle.loads(data)
-        except (TypeError, cPickle.UnpicklingError):
+            return pickle.loads(data)
+        except (TypeError, pickle.UnpicklingError, EOFError):
             return data  # we may be getting the default value, or None,
                          # so it doesn't need unpickled.
 
     def get_both(self, key, value, txn=None, flags=0):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         data = self.db.get(key, data, txn, flags)
-        return cPickle.loads(data)
+        return pickle.loads(data)
 
 
     def cursor(self, txn=None, flags=0):
@@ -189,7 +189,7 @@
 
 
     def put(self, key, value, txn=None, flags=0):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         return self.db.put(key, data, txn, flags)
 
 
@@ -233,7 +233,7 @@
 
 
     def put(self, key, value, flags=0):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         return self.dbc.put(key, data, flags)
 
 
@@ -251,7 +251,7 @@
         return self._extract(rec)
 
     def get_3(self, key, value, flags):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         rec = self.dbc.get(key, flags)
         return self._extract(rec)
 
@@ -268,7 +268,7 @@
 
 
     def get_both(self, key, value, flags=0):
-        data = cPickle.dumps(value, self.binary)
+        data = pickle.dumps(value, self.binary)
         rec = self.dbc.get_both(key, flags)
         return self._extract(rec)
 
@@ -292,7 +292,7 @@
             return None
         else:
             key, data = rec
-            return key, cPickle.loads(data)
+            return key, pickle.loads(data)
 
     #----------------------------------------------
     # Methods allowed to pass-through to self.dbc

Modified: python/branches/py3k-buffer/Lib/bsddb/dbtables.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/dbtables.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/dbtables.py	Fri Aug 17 20:48:09 2007
@@ -90,8 +90,8 @@
 #
 # keys used to store database metadata
 #
-_table_names_key = '__TABLE_NAMES__'  # list of the tables in this db
-_columns = '._COLUMNS__'  # table_name+this key contains a list of columns
+_table_names_key = b'__TABLE_NAMES__'  # list of the tables in this db
+_columns = b'._COLUMNS__'  # table_name+this key contains a list of columns
 
 def _columns_key(table):
     return table + _columns

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_associate.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_associate.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_associate.py	Fri Aug 17 20:48:09 2007
@@ -176,8 +176,8 @@
     def addDataToDB(self, d, txn=None):
         for key, value in musicdata.items():
             if type(self.keytype) == type(''):
-                key = "%02d" % key
-            d.put(key, '|'.join(value), txn=txn)
+                key = ("%02d" % key).encode("utf-8")
+            d.put(key, '|'.join(value).encode("utf-8"), txn=txn)
 
     def createDB(self, txn=None):
         self.cur = None
@@ -247,14 +247,14 @@
 
     def finish_test(self, secDB, txn=None):
         # 'Blues' should not be in the secondary database
-        vals = secDB.pget('Blues', txn=txn)
+        vals = secDB.pget(b'Blues', txn=txn)
         assert vals == None, vals
 
-        vals = secDB.pget('Unknown', txn=txn)
-        assert vals[0] == 99 or vals[0] == '99', vals
-        vals[1].index('Unknown')
-        vals[1].index('Unnamed')
-        vals[1].index('unknown')
+        vals = secDB.pget(b'Unknown', txn=txn)
+        assert vals[0] == 99 or vals[0] == b'99', vals
+        vals[1].index(b'Unknown')
+        vals[1].index(b'Unnamed')
+        vals[1].index(b'unknown')
 
         if verbose:
             print("Primary key traversal:")
@@ -279,18 +279,18 @@
         count = 0
 
         # test cursor pget
-        vals = self.cur.pget('Unknown', flags=db.DB_LAST)
-        assert vals[1] == 99 or vals[1] == '99', vals
-        assert vals[0] == 'Unknown'
-        vals[2].index('Unknown')
-        vals[2].index('Unnamed')
-        vals[2].index('unknown')
+        vals = self.cur.pget(b'Unknown', flags=db.DB_LAST)
+        assert vals[1] == 99 or vals[1] == b'99', vals
+        assert vals[0] == b'Unknown'
+        vals[2].index(b'Unknown')
+        vals[2].index(b'Unnamed')
+        vals[2].index(b'unknown')
 
-        vals = self.cur.pget('Unknown', data='wrong value', flags=db.DB_GET_BOTH)
+        vals = self.cur.pget(b'Unknown', data=b'wrong value', flags=db.DB_GET_BOTH)
         assert vals == None, vals
 
         rec = self.cur.first()
-        assert rec[0] == "Jazz"
+        assert rec[0] == b"Jazz"
         while rec is not None:
             count = count + 1
             if verbose:
@@ -302,14 +302,15 @@
         self.cur = None
 
     def getGenre(self, priKey, priData):
-        assert type(priData) == type("")
+        assert type(priData) == type(b"")
+        priData = priData.decode("utf-8")
         if verbose:
             print('getGenre key: %r data: %r' % (priKey, priData))
         genre = priData.split('|')[2]
         if genre == 'Blues':
             return db.DB_DONOTINDEX
         else:
-            return genre
+            return genre.encode("utf-8")
 
 
 #----------------------------------------------------------------------
@@ -382,7 +383,7 @@
     def addDataToDB(self, d):
         for key, value in musicdata.items():
             if type(self.keytype) == type(''):
-                key = "%02d" % key
+                key = ("%02d" % key).encode("utf-8")
             d.put(key, value)    # save the value as is this time
 
 
@@ -394,7 +395,7 @@
         if genre == 'Blues':
             return db.DB_DONOTINDEX
         else:
-            return genre
+            return genre.encode("utf-8")
 
 
 class ShelveAssociateHashTestCase(ShelveAssociateTestCase):
@@ -426,7 +427,7 @@
     def writer1(self, d):
         for key, value in musicdata.items():
             if type(self.keytype) == type(''):
-                key = "%02d" % key
+                key = ("%02d" % key).encode("utf-8")
             d.put(key, '|'.join(value))
 
     def writer2(self, d):

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_basics.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_basics.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_basics.py	Fri Aug 17 20:48:09 2007
@@ -22,7 +22,7 @@
 
 from .test_all import verbose
 
-DASH = '-'
+DASH = b'-'
 
 
 #----------------------------------------------------------------------
@@ -116,13 +116,15 @@
 
         for x in range(self._numKeys//2):
             key = '%04d' % (self._numKeys - x)  # insert keys in reverse order
+            key = key.encode("utf-8")
             data = self.makeData(key)
             d.put(key, data, _txn)
 
-        d.put('empty value', '', _txn)
+        d.put(b'empty value', b'', _txn)
 
         for x in range(self._numKeys//2-1):
             key = '%04d' % x  # and now some in forward order
+            key = key.encode("utf-8")
             data = self.makeData(key)
             d.put(key, data, _txn)
 
@@ -148,20 +150,20 @@
             print('\n', '-=' * 30)
             print("Running %s.test01_GetsAndPuts..." % self.__class__.__name__)
 
-        for key in ['0001', '0100', '0400', '0700', '0999']:
+        for key in [b'0001', b'0100', b'0400', b'0700', b'0999']:
             data = d.get(key)
             if verbose:
                 print(data)
 
-        assert d.get('0321') == '0321-0321-0321-0321-0321'
+        assert d.get(b'0321') == b'0321-0321-0321-0321-0321'
 
         # By default non-existant keys return None...
-        assert d.get('abcd') == None
+        assert d.get(b'abcd') == None
 
         # ...but they raise exceptions in other situations.  Call
         # set_get_returns_none() to change it.
         try:
-            d.delete('abcd')
+            d.delete(b'abcd')
         except db.DBNotFoundError as val:
             assert val.args[0] == db.DB_NOTFOUND
             if verbose: print(val)
@@ -169,18 +171,18 @@
             self.fail("expected exception")
 
 
-        d.put('abcd', 'a new record')
-        assert d.get('abcd') == 'a new record'
+        d.put(b'abcd', b'a new record')
+        assert d.get(b'abcd') == b'a new record'
 
-        d.put('abcd', 'same key')
+        d.put(b'abcd', b'same key')
         if self.dbsetflags & db.DB_DUP:
-            assert d.get('abcd') == 'a new record'
+            assert d.get(b'abcd') == b'a new record'
         else:
-            assert d.get('abcd') == 'same key'
+            assert d.get(b'abcd') == b'same key'
 
 
         try:
-            d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE)
+            d.put(b'abcd', b'this should fail', flags=db.DB_NOOVERWRITE)
         except db.DBKeyExistError as val:
             assert val.args[0] == db.DB_KEYEXIST
             if verbose: print(val)
@@ -188,9 +190,9 @@
             self.fail("expected exception")
 
         if self.dbsetflags & db.DB_DUP:
-            assert d.get('abcd') == 'a new record'
+            assert d.get(b'abcd') == b'a new record'
         else:
-            assert d.get('abcd') == 'same key'
+            assert d.get(b'abcd') == b'same key'
 
 
         d.sync()
@@ -204,24 +206,24 @@
             self.d.open(self.filename)
         d = self.d
 
-        assert d.get('0321') == '0321-0321-0321-0321-0321'
+        assert d.get(b'0321') == b'0321-0321-0321-0321-0321'
         if self.dbsetflags & db.DB_DUP:
-            assert d.get('abcd') == 'a new record'
+            assert d.get(b'abcd') == b'a new record'
         else:
-            assert d.get('abcd') == 'same key'
+            assert d.get(b'abcd') == b'same key'
 
-        rec = d.get_both('0555', '0555-0555-0555-0555-0555')
+        rec = d.get_both(b'0555', b'0555-0555-0555-0555-0555')
         if verbose:
             print(rec)
 
-        assert d.get_both('0555', 'bad data') == None
+        assert d.get_both(b'0555', b'bad data') == None
 
         # test default value
-        data = d.get('bad key', 'bad data')
-        assert data == 'bad data'
+        data = d.get(b'bad key', b'bad data')
+        assert data == b'bad data'
 
         # any object can pass through
-        data = d.get('bad key', self)
+        data = d.get(b'bad key', self)
         assert data == self
 
         s = d.stat()
@@ -241,7 +243,7 @@
             print("Running %s.test02_DictionaryMethods..." % \
                   self.__class__.__name__)
 
-        for key in ['0002', '0101', '0401', '0701', '0998']:
+        for key in [b'0002', b'0101', b'0401', b'0701', b'0998']:
             data = d[key]
             assert data == self.makeData(key)
             if verbose:
@@ -252,12 +254,12 @@
         assert len(keys) == self._numKeys
         assert type(keys) == type([])
 
-        d['new record'] = 'a new record'
+        d[b'new record'] = b'a new record'
         assert len(d) == self._numKeys+1
         keys = d.keys()
         assert len(keys) == self._numKeys+1
 
-        d['new record'] = 'a replacement record'
+        d[b'new record'] = b'a replacement record'
         assert len(d) == self._numKeys+1
         keys = d.keys()
         assert len(keys) == self._numKeys+1
@@ -266,10 +268,10 @@
             print("the first 10 keys are:")
             pprint(keys[:10])
 
-        assert d['new record'] == 'a replacement record'
+        assert d[b'new record'] == b'a replacement record'
 
-        assert d.has_key('0001') == 1
-        assert d.has_key('spam') == 0
+        assert d.has_key(b'0001') == 1
+        assert d.has_key(b'spam') == 0
 
         items = d.items()
         assert len(items) == self._numKeys+1
@@ -343,20 +345,20 @@
 
         assert count == self._numKeys
 
-        rec = c.set('0505')
+        rec = c.set(b'0505')
         rec2 = c.current()
-        assert rec == rec2
-        assert rec[0] == '0505'
-        assert rec[1] == self.makeData('0505')
+        assert rec == rec2, (repr(rec),repr(rec2))
+        assert rec[0] == b'0505'
+        assert rec[1] == self.makeData(b'0505')
         assert c.get_current_size() == len(rec[1])
 
         # make sure we get empty values properly
-        rec = c.set('empty value')
-        assert rec[1] == ''
+        rec = c.set(b'empty value')
+        assert rec[1] == b''
         assert c.get_current_size() == 0
 
         try:
-            n = c.set('bad key')
+            n = c.set(b'bad key')
         except db.DBNotFoundError as val:
             assert val.args[0] == db.DB_NOTFOUND
             if verbose: print(val)
@@ -366,11 +368,11 @@
             if n != None:
                 self.fail("expected None: %r" % (n,))
 
-        rec = c.get_both('0404', self.makeData('0404'))
-        assert rec == ('0404', self.makeData('0404'))
+        rec = c.get_both(b'0404', self.makeData(b'0404'))
+        assert rec == (b'0404', self.makeData(b'0404'))
 
         try:
-            n = c.get_both('0404', 'bad data')
+            n = c.get_both(b'0404', b'bad data')
         except db.DBNotFoundError as val:
             assert val.args[0] == db.DB_NOTFOUND
             if verbose: print(val)
@@ -381,21 +383,21 @@
                 self.fail("expected None: %r" % (n,))
 
         if self.d.get_type() == db.DB_BTREE:
-            rec = c.set_range('011')
+            rec = c.set_range(b'011')
             if verbose:
                 print("searched for '011', found: ", rec)
 
-            rec = c.set_range('011',dlen=0,doff=0)
+            rec = c.set_range(b'011',dlen=0,doff=0)
             if verbose:
                 print("searched (partial) for '011', found: ", rec)
-            if rec[1] != '': self.fail('expected empty data portion')
+            if rec[1] != b'': self.fail('expected empty data portion')
 
-            ev = c.set_range('empty value')
+            ev = c.set_range(b'empty value')
             if verbose:
                 print("search for 'empty value' returned", ev)
-            if ev[1] != '': self.fail('empty value lookup failed')
+            if ev[1] != b'': self.fail('empty value lookup failed')
 
-        c.set('0499')
+        c.set(b'0499')
         c.delete()
         try:
             rec = c.current()
@@ -413,12 +415,12 @@
         c2 = c.dup(db.DB_POSITION)
         assert c.current() == c2.current()
 
-        c2.put('', 'a new value', db.DB_CURRENT)
+        c2.put(b'', b'a new value', db.DB_CURRENT)
         assert c.current() == c2.current()
-        assert c.current()[1] == 'a new value'
+        assert c.current()[1] == b'a new value'
 
-        c2.put('', 'er', db.DB_CURRENT, dlen=0, doff=5)
-        assert c2.current()[1] == 'a newer value'
+        c2.put(b'', b'er', db.DB_CURRENT, dlen=0, doff=5)
+        assert c2.current()[1] == b'a newer value'
 
         c.close()
         c2.close()
@@ -507,14 +509,14 @@
             print("Running %s.test04_PartialGetAndPut..." % \
                   self.__class__.__name__)
 
-        key = "partialTest"
-        data = "1" * 1000 + "2" * 1000
+        key = b"partialTest"
+        data = b"1" * 1000 + b"2" * 1000
         d.put(key, data)
         assert d.get(key) == data
-        assert d.get(key, dlen=20, doff=990) == ("1" * 10) + ("2" * 10)
+        assert d.get(key, dlen=20, doff=990) == (b"1" * 10) + (b"2" * 10)
 
-        d.put("partialtest2", ("1" * 30000) + "robin" )
-        assert d.get("partialtest2", dlen=5, doff=30000) == "robin"
+        d.put(b"partialtest2", (b"1" * 30000) + b"robin" )
+        assert d.get(b"partialtest2", dlen=5, doff=30000) == b"robin"
 
         # There seems to be a bug in DB here...  Commented out the test for
         # now.
@@ -522,11 +524,11 @@
 
         if self.dbsetflags != db.DB_DUP:
             # Partial put with duplicate records requires a cursor
-            d.put(key, "0000", dlen=2000, doff=0)
-            assert d.get(key) == "0000"
+            d.put(key, b"0000", dlen=2000, doff=0)
+            assert d.get(key) == b"0000"
 
-            d.put(key, "1111", dlen=1, doff=2)
-            assert d.get(key) == "0011110"
+            d.put(key, b"1111", dlen=1, doff=2)
+            assert d.get(key) == b"0011110"
 
     #----------------------------------------
 
@@ -537,9 +539,9 @@
             print("Running %s.test05_GetSize..." % self.__class__.__name__)
 
         for i in range(1, 50000, 500):
-            key = "size%s" % i
+            key = ("size%s" % i).encode("utf-8")
             #print "before ", i,
-            d.put(key, "1" * i)
+            d.put(key, b"1" * i)
             #print "after",
             assert d.get_size(key) == i
             #print "done"
@@ -556,7 +558,7 @@
             print('\n', '-=' * 30)
             print("Running %s.test99_Truncate..." % self.__class__.__name__)
 
-        d.put("abcde", "ABCDE");
+        d.put(b"abcde", b"ABCDE");
         num = d.truncate()
         assert num >= 1, "truncate returned <= 0 on non-empty database"
         num = d.truncate()
@@ -650,19 +652,19 @@
             print('\n', '-=' * 30)
             print("Running %s.test06_Transactions..." % self.__class__.__name__)
 
-        assert d.get('new rec', txn=self.txn) == None
-        d.put('new rec', 'this is a new record', self.txn)
-        assert d.get('new rec', txn=self.txn) == 'this is a new record'
+        assert d.get(b'new rec', txn=self.txn) == None
+        d.put(b'new rec', b'this is a new record', self.txn)
+        assert d.get(b'new rec', txn=self.txn) == b'this is a new record'
         self.txn.abort()
-        assert d.get('new rec') == None
+        assert d.get(b'new rec') == None
 
         self.txn = self.env.txn_begin()
 
-        assert d.get('new rec', txn=self.txn) == None
-        d.put('new rec', 'this is a new record', self.txn)
-        assert d.get('new rec', txn=self.txn) == 'this is a new record'
+        assert d.get(b'new rec', txn=self.txn) == None
+        d.put(b'new rec', b'this is a new record', self.txn)
+        assert d.get(b'new rec', txn=self.txn) == b'this is a new record'
         self.txn.commit()
-        assert d.get('new rec') == 'this is a new record'
+        assert d.get(b'new rec') == b'this is a new record'
 
         self.txn = self.env.txn_begin()
         c = d.cursor(self.txn)
@@ -715,7 +717,7 @@
             print('\n', '-=' * 30)
             print("Running %s.test07_TxnTruncate..." % self.__class__.__name__)
 
-        d.put("abcde", "ABCDE");
+        d.put(b"abcde", b"ABCDE");
         txn = self.env.txn_begin()
         num = d.truncate(txn)
         assert num >= 1, "truncate returned <= 0 on non-empty database"
@@ -772,7 +774,7 @@
             print("Record #200 is ", rec)
 
         c = d.cursor()
-        c.set('0200')
+        c.set(b'0200')
         num = c.get_recno()
         assert type(num) == type(1)
         if verbose:
@@ -800,39 +802,40 @@
             print("Running %s.test08_DuplicateKeys..." % \
                   self.__class__.__name__)
 
-        d.put("dup0", "before")
+        d.put(b"dup0", b"before")
         for x in "The quick brown fox jumped over the lazy dog.".split():
-            d.put("dup1", x)
-        d.put("dup2", "after")
+            x = x.encode("ascii")
+            d.put(b"dup1", x)
+        d.put(b"dup2", b"after")
 
-        data = d.get("dup1")
-        assert data == "The"
+        data = d.get(b"dup1")
+        assert data == b"The"
         if verbose:
             print(data)
 
         c = d.cursor()
-        rec = c.set("dup1")
-        assert rec == ('dup1', 'The')
+        rec = c.set(b"dup1")
+        assert rec == (b'dup1', b'The')
 
         next = c.next()
-        assert next == ('dup1', 'quick')
+        assert next == (b'dup1', b'quick')
 
-        rec = c.set("dup1")
+        rec = c.set(b"dup1")
         count = c.count()
         assert count == 9
 
         next_dup = c.next_dup()
-        assert next_dup == ('dup1', 'quick')
+        assert next_dup == (b'dup1', b'quick')
 
-        rec = c.set('dup1')
+        rec = c.set(b'dup1')
         while rec is not None:
             if verbose:
                 print(rec)
             rec = c.next_dup()
 
-        c.set('dup1')
+        c.set(b'dup1')
         rec = c.next_nodup()
-        assert rec[0] != 'dup1'
+        assert rec[0] != b'dup1'
         if verbose:
             print(rec)
 
@@ -880,9 +883,11 @@
                 self.dbopenflags|db.DB_CREATE)
 
         for x in "The quick brown fox jumped over the lazy dog".split():
+            x = x.encode("ascii")
             d2.put(x, self.makeData(x))
 
         for x in string.letters:
+            x = x.encode("ascii")
             d3.put(x, x*70)
 
         d1.sync()

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_compare.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_compare.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_compare.py	Fri Aug 17 20:48:09 2007
@@ -3,7 +3,7 @@
 """
 
 import sys, os, re
-from cStringIO import StringIO
+from io import StringIO
 
 from . import test_all
 

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_compat.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_compat.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_compat.py	Fri Aug 17 20:48:09 2007
@@ -9,12 +9,7 @@
 
 from .test_all import verbose
 
-try:
-    # For Pythons w/distutils pybsddb
-    from bsddb3 import db, hashopen, btopen, rnopen
-except ImportError:
-    # For Python 2.3
-    from bsddb import db, hashopen, btopen, rnopen
+from bsddb import db, hashopen, btopen, rnopen
 
 
 class CompatibilityTestCase(unittest.TestCase):
@@ -41,31 +36,31 @@
 
         f = rnopen(self.filename, 'c')
         for x in range(len(data)):
-            f[x+1] = data[x]
+            f[x+1] = data[x].encode("ascii")
 
         getTest = (f[1], f[2], f[3])
         if verbose:
             print('%s %s %s' % getTest)
 
-        assert getTest[1] == 'quick', 'data mismatch!'
+        assert getTest[1] == b'quick', 'data mismatch!'
 
         rv = f.set_location(3)
-        if rv != (3, 'brown'):
+        if rv != (3, b'brown'):
             self.fail('recno database set_location failed: '+repr(rv))
 
-        f[25] = 'twenty-five'
+        f[25] = b'twenty-five'
         f.close()
         del f
 
         f = rnopen(self.filename, 'w')
-        f[20] = 'twenty'
+        f[20] = b'twenty'
 
         def noRec(f):
             rec = f[15]
         self.assertRaises(KeyError, noRec, f)
 
         def badKey(f):
-            rec = f['a string']
+            rec = f[b'a string']
         self.assertRaises(TypeError, badKey, f)
 
         del f[3]
@@ -101,20 +96,20 @@
         else:
             if verbose: print("truth test: false")
 
-        f['0'] = ''
-        f['a'] = 'Guido'
-        f['b'] = 'van'
-        f['c'] = 'Rossum'
-        f['d'] = 'invented'
+        f[b'0'] = b''
+        f[b'a'] = b'Guido'
+        f[b'b'] = b'van'
+        f[b'c'] = b'Rossum'
+        f[b'd'] = b'invented'
         # 'e' intentionally left out
-        f['f'] = 'Python'
+        f[b'f'] = b'Python'
         if verbose:
             print('%s %s %s' % (f['a'], f['b'], f['c']))
 
         if verbose:
             print('key ordering...')
         start = f.set_location(f.first()[0])
-        if start != ('0', ''):
+        if start != (b'0', b''):
             self.fail("incorrect first() result: "+repr(start))
         while 1:
             try:
@@ -126,17 +121,17 @@
             if verbose:
                 print(rec)
 
-        assert f.has_key('f'), 'Error, missing key!'
+        assert f.has_key(b'f'), 'Error, missing key!'
 
         # test that set_location() returns the next nearest key, value
         # on btree databases and raises KeyError on others.
         if factory == btopen:
-            e = f.set_location('e')
-            if e != ('f', 'Python'):
+            e = f.set_location(b'e')
+            if e != (b'f', b'Python'):
                 self.fail('wrong key,value returned: '+repr(e))
         else:
             try:
-                e = f.set_location('e')
+                e = f.set_location(b'e')
             except KeyError:
                 pass
             else:
@@ -160,7 +155,7 @@
         if verbose:
             print('modification...')
         f = factory(self.filename, 'w')
-        f['d'] = 'discovered'
+        f[b'd'] = b'discovered'
 
         if verbose:
             print('access...')
@@ -170,7 +165,7 @@
                 print(word)
 
         def noRec(f):
-            rec = f['no such key']
+            rec = f[b'no such key']
         self.assertRaises(KeyError, noRec, f)
 
         def badKey(f):

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_cursor_pget_bug.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_cursor_pget_bug.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_cursor_pget_bug.py	Fri Aug 17 20:48:09 2007
@@ -1,12 +1,7 @@
 import unittest
 import sys, os, glob
 
-try:
-    # For Pythons w/distutils pybsddb
-    from bsddb3 import db
-except ImportError:
-    # For Python 2.3
-    from bsddb import db
+from bsddb import db
 
 
 #----------------------------------------------------------------------
@@ -29,9 +24,9 @@
         self.secondary_db.set_flags(db.DB_DUP)
         self.secondary_db.open(self.db_name, 'secondary', db.DB_BTREE, db.DB_CREATE)
         self.primary_db.associate(self.secondary_db, lambda key, data: data)
-        self.primary_db.put('salad', 'eggs')
-        self.primary_db.put('spam', 'ham')
-        self.primary_db.put('omelet', 'eggs')
+        self.primary_db.put(b'salad', b'eggs')
+        self.primary_db.put(b'spam', b'ham')
+        self.primary_db.put(b'omelet', b'eggs')
 
 
     def tearDown(self):
@@ -48,11 +43,11 @@
     def test_pget(self):
         cursor = self.secondary_db.cursor()
 
-        self.assertEquals(('eggs', 'salad', 'eggs'), cursor.pget(key='eggs', flags=db.DB_SET))
-        self.assertEquals(('eggs', 'omelet', 'eggs'), cursor.pget(db.DB_NEXT_DUP))
+        self.assertEquals((b'eggs', b'salad', b'eggs'), cursor.pget(key=b'eggs', flags=db.DB_SET))
+        self.assertEquals((b'eggs', b'omelet', b'eggs'), cursor.pget(db.DB_NEXT_DUP))
         self.assertEquals(None, cursor.pget(db.DB_NEXT_DUP))
 
-        self.assertEquals(('ham', 'spam', 'ham'), cursor.pget('ham', 'spam', flags=db.DB_SET))
+        self.assertEquals((b'ham', b'spam', b'ham'), cursor.pget(b'ham', b'spam', flags=db.DB_SET))
         self.assertEquals(None, cursor.pget(db.DB_NEXT_DUP))
 
         cursor.close()

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_dbobj.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_dbobj.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_dbobj.py	Fri Aug 17 20:48:09 2007
@@ -38,17 +38,17 @@
         class TestDBEnv(dbobj.DBEnv): pass
         class TestDB(dbobj.DB):
             def put(self, key, *args, **kwargs):
-                key = key.upper()
+                key = key.decode("ascii").upper().encode("ascii")
                 # call our parent classes put method with an upper case key
                 return dbobj.DB.put(self, key, *args, **kwargs)
         self.env = TestDBEnv()
         self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL)
         self.db = TestDB(self.env)
         self.db.open(self.db_name, db.DB_HASH, db.DB_CREATE)
-        self.db.put('spam', 'eggs')
-        assert self.db.get('spam') == None, \
+        self.db.put(b'spam', b'eggs')
+        assert self.db.get(b'spam') == None, \
                "overridden dbobj.DB.put() method failed [1]"
-        assert self.db.get('SPAM') == 'eggs', \
+        assert self.db.get(b'SPAM') == b'eggs', \
                "overridden dbobj.DB.put() method failed [2]"
         self.db.close()
         self.env.close()
@@ -59,14 +59,14 @@
         self.db = dbobj.DB(self.env)
         self.db.open(self.db_name+'02', db.DB_HASH, db.DB_CREATE)
         # __setitem__
-        self.db['spam'] = 'eggs'
+        self.db[b'spam'] = b'eggs'
         # __len__
         assert len(self.db) == 1
         # __getitem__
-        assert self.db['spam'] == 'eggs'
+        assert self.db[b'spam'] == b'eggs'
         # __del__
-        del self.db['spam']
-        assert self.db.get('spam') == None, "dbobj __del__ failed"
+        del self.db[b'spam']
+        assert self.db.get(b'spam') == None, "dbobj __del__ failed"
         self.db.close()
         self.env.close()
 

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_dbshelve.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_dbshelve.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_dbshelve.py	Fri Aug 17 20:48:09 2007
@@ -8,12 +8,7 @@
 from types import *
 import unittest
 
-try:
-    # For Pythons w/distutils pybsddb
-    from bsddb3 import db, dbshelve
-except ImportError:
-    # For Python 2.3
-    from bsddb import db, dbshelve
+from bsddb import db, dbshelve
 
 from .test_all import verbose
 
@@ -56,15 +51,15 @@
 
     def populateDB(self, d):
         for x in string.letters:
-            d['S' + x] = 10 * x           # add a string
-            d['I' + x] = ord(x)           # add an integer
-            d['L' + x] = [x] * 10         # add a list
+            d[('S' + x).encode("ascii")] = 10 * x           # add a string
+            d[('I' + x).encode("ascii")] = ord(x)           # add an integer
+            d[('L' + x).encode("ascii")] = [x] * 10         # add a list
 
             inst = DataClass()            # add an instance
             inst.S = 10 * x
             inst.I = ord(x)
             inst.L = [x] * 10
-            d['O' + x] = inst
+            d[('O' + x).encode("ascii")] = inst
 
 
     # overridable in derived classes to affect how the shelf is created/opened
@@ -98,14 +93,14 @@
             print("keys:", k)
             print("stats:", s)
 
-        assert 0 == d.has_key('bad key')
-        assert 1 == d.has_key('IA')
-        assert 1 == d.has_key('OA')
-
-        d.delete('IA')
-        del d['OA']
-        assert 0 == d.has_key('IA')
-        assert 0 == d.has_key('OA')
+        assert 0 == d.has_key(b'bad key')
+        assert 1 == d.has_key(b'IA')
+        assert 1 == d.has_key(b'OA')
+
+        d.delete(b'IA')
+        del d[b'OA']
+        assert 0 == d.has_key(b'IA')
+        assert 0 == d.has_key(b'OA')
         assert len(d) == l-2
 
         values = []
@@ -127,18 +122,18 @@
         for key, value in items:
             self.checkrec(key, value)
 
-        assert d.get('bad key') == None
-        assert d.get('bad key', None) == None
-        assert d.get('bad key', 'a string') == 'a string'
-        assert d.get('bad key', [1, 2, 3]) == [1, 2, 3]
+        assert d.get(b'bad key') == None
+        assert d.get(b'bad key', None) == None
+        assert d.get(b'bad key', b'a string') == b'a string'
+        assert d.get(b'bad key', [1, 2, 3]) == [1, 2, 3]
 
         d.set_get_returns_none(0)
-        self.assertRaises(db.DBNotFoundError, d.get, 'bad key')
+        self.assertRaises(db.DBNotFoundError, d.get, b'bad key')
         d.set_get_returns_none(1)
 
-        d.put('new key', 'new data')
-        assert d.get('new key') == 'new data'
-        assert d['new key'] == 'new data'
+        d.put(b'new key', b'new data')
+        assert d.get(b'new key') == b'new data'
+        assert d[b'new key'] == b'new data'
 
 
 
@@ -156,7 +151,7 @@
         while rec is not None:
             count = count + 1
             if verbose:
-                print(rec)
+                print(repr(rec))
             key, value = rec
             self.checkrec(key, value)
             rec = c.next()
@@ -177,34 +172,32 @@
 
         assert count == len(d)
 
-        c.set('SS')
+        c.set(b'SS')
         key, value = c.current()
         self.checkrec(key, value)
         del c
 
-
-
     def checkrec(self, key, value):
-        x = key[1]
-        if key[0] == 'S':
-            assert type(value) == StringType
-            assert value == 10 * x
-
-        elif key[0] == 'I':
-            assert type(value) == IntType
-            assert value == ord(x)
-
-        elif key[0] == 'L':
-            assert type(value) == ListType
-            assert value == [x] * 10
-
-        elif key[0] == 'O':
-            assert value.S == 10 * x
-            assert value.I == ord(x)
-            assert value.L == [x] * 10
+        x = key[1:]
+        if key[0:1] == b'S':
+            self.assertEquals(type(value), str)
+            self.assertEquals(value, 10 * x.decode("ascii"))
+
+        elif key[0:1] == b'I':
+            self.assertEquals(type(value), int)
+            self.assertEquals(value, ord(x))
+
+        elif key[0:1] == b'L':
+            self.assertEquals(type(value), list)
+            self.assertEquals(value, [x.decode("ascii")] * 10)
+
+        elif key[0:1] == b'O':
+            self.assertEquals(value.S, 10 * x.decode("ascii"))
+            self.assertEquals(value.I, ord(x))
+            self.assertEquals(value.L, [x.decode("ascii")] * 10)
 
         else:
-            raise AssertionError, 'Unknown key type, fix the test'
+            self.fail('Unknown key type, fix the test')
 
 #----------------------------------------------------------------------
 

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_get_none.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_get_none.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_get_none.py	Fri Aug 17 20:48:09 2007
@@ -7,12 +7,7 @@
 from pprint import pprint
 import unittest
 
-try:
-    # For Pythons w/distutils pybsddb
-    from bsddb3 import db
-except ImportError:
-    # For Python 2.3
-    from bsddb import db
+from bsddb import db
 
 from .test_all import verbose
 
@@ -36,13 +31,14 @@
         d.set_get_returns_none(1)
 
         for x in string.letters:
+            x = x.encode("ascii")
             d.put(x, x * 40)
 
-        data = d.get('bad key')
+        data = d.get(b'bad key')
         assert data == None
 
-        data = d.get('a')
-        assert data == 'a'*40
+        data = d.get(b'a')
+        assert data == b'a'*40
 
         count = 0
         c = d.cursor()
@@ -64,13 +60,14 @@
         d.set_get_returns_none(0)
 
         for x in string.letters:
+            x = x.encode("ascii")
             d.put(x, x * 40)
 
-        self.assertRaises(db.DBNotFoundError, d.get, 'bad key')
-        self.assertRaises(KeyError, d.get, 'bad key')
+        self.assertRaises(db.DBNotFoundError, d.get, b'bad key')
+        self.assertRaises(KeyError, d.get, b'bad key')
 
-        data = d.get('a')
-        assert data == 'a'*40
+        data = d.get(b'a')
+        assert data == b'a'*40
 
         count = 0
         exceptionHappened = 0

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_join.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_join.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_join.py	Fri Aug 17 20:48:09 2007
@@ -15,12 +15,7 @@
 import unittest
 from .test_all import verbose
 
-try:
-    # For Pythons w/distutils pybsddb
-    from bsddb3 import db, dbshelve
-except ImportError:
-    # For Python 2.3
-    from bsddb import db, dbshelve
+from bsddb import db, dbshelve, StringKeys
 
 
 #----------------------------------------------------------------------
@@ -44,6 +39,9 @@
     ('black', "shotgun"),
 ]
 
+def ASCII(s):
+    return s.encode("ascii")
+
 class JoinTestCase(unittest.TestCase):
     keytype = ''
 
@@ -72,13 +70,13 @@
         # create and populate primary index
         priDB = db.DB(self.env)
         priDB.open(self.filename, "primary", db.DB_BTREE, db.DB_CREATE)
-        [priDB.put(*t) for t in ProductIndex]
+        [priDB.put(ASCII(k),ASCII(v)) for k,v in ProductIndex]
 
         # create and populate secondary index
         secDB = db.DB(self.env)
         secDB.set_flags(db.DB_DUP | db.DB_DUPSORT)
         secDB.open(self.filename, "secondary", db.DB_BTREE, db.DB_CREATE)
-        [secDB.put(*t) for t in ColorIndex]
+        [secDB.put(ASCII(k),ASCII(v)) for k,v in ColorIndex]
 
         sCursor = None
         jCursor = None
@@ -87,7 +85,7 @@
             sCursor = secDB.cursor()
             # Don't do the .set() in an assert, or you can get a bogus failure
             # when running python -O
-            tmp = sCursor.set('red')
+            tmp = sCursor.set(b'red')
             assert tmp
 
             # FIXME: jCursor doesn't properly hold a reference to its
@@ -95,11 +93,11 @@
             # can cause a crash.
             jCursor = priDB.join([sCursor])
 
-            if jCursor.get(0) != ('apple', "Convenience Store"):
+            if jCursor.get(0) != (b'apple', b"Convenience Store"):
                 self.fail("join cursor positioned wrong")
-            if jCursor.join_item() != 'chainsaw':
+            if jCursor.join_item() != b'chainsaw':
                 self.fail("DBCursor.join_item returned wrong item")
-            if jCursor.get(0)[0] != 'strawberry':
+            if jCursor.get(0)[0] != b'strawberry':
                 self.fail("join cursor returned wrong thing")
             if jCursor.get(0):  # there were only three red items to return
                 self.fail("join cursor returned too many items")

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_recno.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_recno.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_recno.py	Fri Aug 17 20:48:09 2007
@@ -58,7 +58,7 @@
             if verbose:
                 print(data)
 
-            assert type(data) == type("")
+            assert type(data) == bytes
             assert data == d.get(recno)
 
         try:
@@ -106,7 +106,7 @@
         assert type(items[0]) == type(())
         assert len(items[0]) == 2
         assert type(items[0][0]) == type(123)
-        assert type(items[0][1]) == type("")
+        assert type(items[0][1]) == bytes
         assert len(items) == len(d)
 
         assert d.has_key(25)
@@ -117,8 +117,8 @@
         d.delete(13)
         assert not d.has_key(13)
 
-        data = d.get_both(26, "z" * 60)
-        assert data == "z" * 60, 'was %r' % data
+        data = d.get_both(26, b"z" * 60)
+        assert data == b"z" * 60, 'was %r' % data
         if verbose:
             print(data)
 
@@ -138,11 +138,11 @@
         if verbose:
             print(rec)
 
-        c.put(-1, "a replacement record", db.DB_CURRENT)
+        c.put(-1, b"a replacement record", db.DB_CURRENT)
 
         c.set(50)
         rec = c.current()
-        assert rec == (50, "a replacement record")
+        assert rec == (50, b"a replacement record")
         if verbose:
             print(rec)
 
@@ -165,8 +165,8 @@
         c = d.cursor()
 
         # put a record beyond the consecutive end of the recno's
-        d[100] = "way out there"
-        assert d[100] == "way out there"
+        d[100] = b"way out there"
+        assert d[100] == b"way out there"
 
         try:
             data = d[99]

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_sequence.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_sequence.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_sequence.py	Fri Aug 17 20:48:09 2007
@@ -50,39 +50,39 @@
         start_value = 10 * self.int_32_max
         self.assertEqual(0xA00000000, start_value)
         self.assertEquals(None, self.seq.init_value(start_value))
-        self.assertEquals(None, self.seq.open(key='id', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'id', txn=None, flags=db.DB_CREATE))
         self.assertEquals(start_value, self.seq.get(5))
         self.assertEquals(start_value + 5, self.seq.get())
 
     def test_remove(self):
         self.seq = db.DBSequence(self.d, flags=0)
-        self.assertEquals(None, self.seq.open(key='foo', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'foo', txn=None, flags=db.DB_CREATE))
         self.assertEquals(None, self.seq.remove(txn=None, flags=0))
         del self.seq
 
     def test_get_key(self):
         self.seq = db.DBSequence(self.d, flags=0)
-        key = 'foo'
+        key = b'foo'
         self.assertEquals(None, self.seq.open(key=key, txn=None, flags=db.DB_CREATE))
         self.assertEquals(key, self.seq.get_key())
 
     def test_get_dbp(self):
         self.seq = db.DBSequence(self.d, flags=0)
-        self.assertEquals(None, self.seq.open(key='foo', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'foo', txn=None, flags=db.DB_CREATE))
         self.assertEquals(self.d, self.seq.get_dbp())
 
     def test_cachesize(self):
         self.seq = db.DBSequence(self.d, flags=0)
         cashe_size = 10
         self.assertEquals(None, self.seq.set_cachesize(cashe_size))
-        self.assertEquals(None, self.seq.open(key='foo', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'foo', txn=None, flags=db.DB_CREATE))
         self.assertEquals(cashe_size, self.seq.get_cachesize())
 
     def test_flags(self):
         self.seq = db.DBSequence(self.d, flags=0)
         flag = db.DB_SEQ_WRAP;
         self.assertEquals(None, self.seq.set_flags(flag))
-        self.assertEquals(None, self.seq.open(key='foo', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'foo', txn=None, flags=db.DB_CREATE))
         self.assertEquals(flag, self.seq.get_flags() & flag)
 
     def test_range(self):
@@ -90,12 +90,12 @@
         seq_range = (10 * self.int_32_max, 11 * self.int_32_max - 1)
         self.assertEquals(None, self.seq.set_range(seq_range))
         self.seq.init_value(seq_range[0])
-        self.assertEquals(None, self.seq.open(key='foo', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'foo', txn=None, flags=db.DB_CREATE))
         self.assertEquals(seq_range, self.seq.get_range())
 
     def test_stat(self):
         self.seq = db.DBSequence(self.d, flags=0)
-        self.assertEquals(None, self.seq.open(key='foo', txn=None, flags=db.DB_CREATE))
+        self.assertEquals(None, self.seq.open(key=b'foo', txn=None, flags=db.DB_CREATE))
         stat = self.seq.stat()
         for param in ('nowait', 'min', 'max', 'value', 'current',
                       'flags', 'cache_size', 'last_value', 'wait'):

Modified: python/branches/py3k-buffer/Lib/bsddb/test/test_thread.py
==============================================================================
--- python/branches/py3k-buffer/Lib/bsddb/test/test_thread.py	(original)
+++ python/branches/py3k-buffer/Lib/bsddb/test/test_thread.py	Fri Aug 17 20:48:09 2007
@@ -10,7 +10,7 @@
 from pprint import pprint
 from random import random
 
-DASH = '-'
+DASH = b'-'
 
 try:
     from threading import Thread, currentThread
@@ -120,7 +120,7 @@
             print("%s: creating records %d - %d" % (name, start, stop))
 
         for x in range(start, stop):
-            key = '%04d' % x
+            key = ('%04d' % x).encode("ascii")
             dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                  max_retries=12)
             if verbose and x % 100 == 0:
@@ -224,7 +224,7 @@
 
         # create a bunch of records
         for x in range(start, stop):
-            key = '%04d' % x
+            key = ('%04d' % x).encode("ascii")
             dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                  max_retries=12)
 
@@ -234,7 +234,7 @@
             # do a bit or reading too
             if random() <= 0.05:
                 for y in range(start, x):
-                    key = '%04d' % x
+                    key = ('%04d' % x).encode("ascii")
                     data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
                     self.assertEqual(data, self.makeData(key))
 
@@ -247,7 +247,7 @@
 
         # read them back, deleting a few
         for x in range(start, stop):
-            key = '%04d' % x
+            key = ('%04d' % x).encode("ascii")
             data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
             if verbose and x % 100 == 0:
                 print("%s: fetched record (%s, %s)" % (name, key, data))
@@ -348,7 +348,7 @@
             try:
                 txn = self.env.txn_begin(None, self.txnFlag)
                 for x in range(start, stop):
-                    key = '%04d' % x
+                    key = ('%04d' % x).encode("ascii")
                     d.put(key, self.makeData(key), txn)
                     if verbose and x % 100 == 0:
                         print("%s: records %d - %d finished" % (name, start, x))
@@ -383,7 +383,7 @@
                 txn = self.env.txn_begin(None, self.txnFlag)
                 for x in range(10):
                     key = int(random() * howMany) + start
-                    key = '%04d' % key
+                    key = ('%04d' % key).encode("ascii")
                     data = d.get(key, None, txn, db.DB_RMW)
                     if data is not None:
                         d.delete(key, txn)

Modified: python/branches/py3k-buffer/Lib/code.py
==============================================================================
--- python/branches/py3k-buffer/Lib/code.py	(original)
+++ python/branches/py3k-buffer/Lib/code.py	Fri Aug 17 20:48:09 2007
@@ -111,16 +111,16 @@
         if filename and type is SyntaxError:
             # Work hard to stuff the correct filename in the exception
             try:
-                msg, (dummy_filename, lineno, offset, line) = value
-            except:
+                msg, (dummy_filename, lineno, offset, line) = value.args
+            except ValueError:
                 # Not the format we expect; leave it alone
                 pass
             else:
                 # Stuff in the right filename
                 value = SyntaxError(msg, (filename, lineno, offset, line))
                 sys.last_value = value
-        list = traceback.format_exception_only(type, value)
-        map(self.write, list)
+        lines = traceback.format_exception_only(type, value)
+        self.write(''.join(lines))
 
     def showtraceback(self):
         """Display the exception that just occurred.
@@ -137,13 +137,13 @@
             sys.last_traceback = tb
             tblist = traceback.extract_tb(tb)
             del tblist[:1]
-            list = traceback.format_list(tblist)
-            if list:
-                list.insert(0, "Traceback (most recent call last):\n")
-            list[len(list):] = traceback.format_exception_only(type, value)
+            lines = traceback.format_list(tblist)
+            if lines:
+                lines.insert(0, "Traceback (most recent call last):\n")
+            lines.extend(traceback.format_exception_only(type, value))
         finally:
             tblist = tb = None
-        map(self.write, list)
+        self.write(''.join(lines))
 
     def write(self, data):
         """Write a string.
@@ -184,7 +184,7 @@
     def interact(self, banner=None):
         """Closely emulate the interactive Python console.
 
-        The optional banner argument specify the banner to print
+        The optional banner argument specifies the banner to print
         before the first interaction; by default it prints a banner
         similar to the one printed by the real Python interpreter,
         followed by the current class name in parentheses (so as not

Modified: python/branches/py3k-buffer/Lib/cookielib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/cookielib.py	(original)
+++ python/branches/py3k-buffer/Lib/cookielib.py	Fri Aug 17 20:48:09 2007
@@ -58,7 +58,7 @@
     # catching input that's bad in unexpected ways.  Warn if any
     # exceptions are caught there.
     import warnings, traceback, StringIO
-    f = StringIO.StringIO()
+    f = io.StringIO()
     traceback.print_exc(None, f)
     msg = f.getvalue()
     warnings.warn("cookielib bug!\n%s" % msg, stacklevel=2)
@@ -644,8 +644,6 @@
     # And here, kind of: draft-fielding-uri-rfc2396bis-03
     # (And in draft IRI specification: draft-duerst-iri-05)
     # (And here, for new URI schemes: RFC 2718)
-    if isinstance(path, str):
-        path = path.encode("utf-8")
     path = urllib.quote(path, HTTP_PATH_SAFE)
     path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
     return path

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_arrays.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_arrays.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_arrays.py	Fri Aug 17 20:48:09 2007
@@ -48,12 +48,12 @@
         # CharArray("abc")
         self.assertRaises(TypeError, CharArray, "abc")
 
-        self.failUnlessEqual(ca[0], "a")
-        self.failUnlessEqual(ca[1], "b")
-        self.failUnlessEqual(ca[2], "c")
-        self.failUnlessEqual(ca[-3], "a")
-        self.failUnlessEqual(ca[-2], "b")
-        self.failUnlessEqual(ca[-1], "c")
+        self.failUnlessEqual(ca[0], b"a")
+        self.failUnlessEqual(ca[1], b"b")
+        self.failUnlessEqual(ca[2], b"c")
+        self.failUnlessEqual(ca[-3], b"a")
+        self.failUnlessEqual(ca[-2], b"b")
+        self.failUnlessEqual(ca[-1], b"c")
 
         self.failUnlessEqual(len(ca), 3)
 

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_buffers.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_buffers.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_buffers.py	Fri Aug 17 20:48:09 2007
@@ -7,21 +7,21 @@
         b = create_string_buffer(32)
         self.failUnlessEqual(len(b), 32)
         self.failUnlessEqual(sizeof(b), 32 * sizeof(c_char))
-        self.failUnless(type(b[0]) is str)
+        self.failUnless(type(b[0]) is bytes)
 
         b = create_string_buffer("abc")
         self.failUnlessEqual(len(b), 4) # trailing nul char
         self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char))
-        self.failUnless(type(b[0]) is str)
-        self.failUnlessEqual(b[0], "a")
+        self.failUnless(type(b[0]) is bytes)
+        self.failUnlessEqual(b[0], b"a")
         self.failUnlessEqual(b[:], "abc\0")
 
     def test_string_conversion(self):
         b = create_string_buffer("abc")
         self.failUnlessEqual(len(b), 4) # trailing nul char
         self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char))
-        self.failUnless(type(b[0]) is str)
-        self.failUnlessEqual(b[0], "a")
+        self.failUnless(type(b[0]) is bytes)
+        self.failUnlessEqual(b[0], b"a")
         self.failUnlessEqual(b[:], "abc\0")
 
     try:

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_callbacks.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_callbacks.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_callbacks.py	Fri Aug 17 20:48:09 2007
@@ -78,8 +78,8 @@
         self.check_type(c_double, -3.14)
 
     def test_char(self):
-        self.check_type(c_char, "x")
-        self.check_type(c_char, "a")
+        self.check_type(c_char, b"x")
+        self.check_type(c_char, b"a")
 
     # disabled: would now (correctly) raise a RuntimeWarning about
     # a memory leak.  A callback function cannot return a non-integral

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_numbers.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_numbers.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_numbers.py	Fri Aug 17 20:48:09 2007
@@ -177,11 +177,11 @@
         a = array('b', [0])
         a[0] = ord('x')
         v = c_char.from_address(a.buffer_info()[0])
-        self.failUnlessEqual(v.value, 'x')
+        self.failUnlessEqual(v.value, b'x')
         self.failUnless(type(v) is c_char)
 
         a[0] = ord('?')
-        self.failUnlessEqual(v.value, '?')
+        self.failUnlessEqual(v.value, b'?')
 
     # array does not support c_bool / 't'
     # def test_bool_from_address(self):

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_random_things.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_random_things.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_random_things.py	Fri Aug 17 20:48:09 2007
@@ -37,9 +37,9 @@
 
     def capture_stderr(self, func, *args, **kw):
         # helper - call function 'func', and return the captured stderr
-        import StringIO
+        import io
         old_stderr = sys.stderr
-        logger = sys.stderr = StringIO.StringIO()
+        logger = sys.stderr = io.StringIO()
         try:
             func(*args, **kw)
         finally:

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_repr.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_repr.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_repr.py	Fri Aug 17 20:48:09 2007
@@ -22,7 +22,7 @@
             self.failUnlessEqual("<X object at", repr(typ(42))[:12])
 
     def test_char(self):
-        self.failUnlessEqual("c_char('x')", repr(c_char('x')))
+        self.failUnlessEqual("c_char(b'x')", repr(c_char('x')))
         self.failUnlessEqual("<X object at", repr(X('x'))[:12])
 
 if __name__ == "__main__":

Modified: python/branches/py3k-buffer/Lib/ctypes/test/test_stringptr.py
==============================================================================
--- python/branches/py3k-buffer/Lib/ctypes/test/test_stringptr.py	(original)
+++ python/branches/py3k-buffer/Lib/ctypes/test/test_stringptr.py	Fri Aug 17 20:48:09 2007
@@ -66,7 +66,7 @@
         buf = c_buffer("abcdef")
         r = strchr(buf, "c")
         x = r[0], r[1], r[2], r[3], r[4]
-        self.failUnlessEqual(x, ("c", "d", "e", "f", "\000"))
+        self.failUnlessEqual(x, (b"c", b"d", b"e", b"f", b"\000"))
         del buf
         # x1 will NOT be the same as x, usually:
         x1 = r[0], r[1], r[2], r[3], r[4]

Modified: python/branches/py3k-buffer/Lib/distutils/command/register.py
==============================================================================
--- python/branches/py3k-buffer/Lib/distutils/command/register.py	(original)
+++ python/branches/py3k-buffer/Lib/distutils/command/register.py	Fri Aug 17 20:48:09 2007
@@ -8,7 +8,7 @@
 __revision__ = "$Id$"
 
 import sys, os, urllib2, getpass, urlparse
-import StringIO, ConfigParser
+import io, ConfigParser
 
 from distutils.core import Command
 from distutils.errors import *
@@ -22,7 +22,7 @@
 
     description = ("register the distribution with the Python package index")
 
-    DEFAULT_REPOSITORY = 'http://www.python.org/pypi'
+    DEFAULT_REPOSITORY = 'http://pypi.python.org/pypi'
 
     user_options = [
         ('repository=', 'r',
@@ -253,7 +253,7 @@
         boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
         sep_boundary = '\n--' + boundary
         end_boundary = sep_boundary + '--'
-        body = StringIO.StringIO()
+        body = io.StringIO()
         for key, value in data.items():
             # handle multiple entries for the same name
             if type(value) not in (type([]), type( () )):

Modified: python/branches/py3k-buffer/Lib/distutils/command/upload.py
==============================================================================
--- python/branches/py3k-buffer/Lib/distutils/command/upload.py	(original)
+++ python/branches/py3k-buffer/Lib/distutils/command/upload.py	Fri Aug 17 20:48:09 2007
@@ -14,13 +14,12 @@
 import httplib
 import base64
 import urlparse
-import cStringIO as StringIO
 
 class upload(Command):
 
     description = "upload binary package to PyPI"
 
-    DEFAULT_REPOSITORY = 'http://www.python.org/pypi'
+    DEFAULT_REPOSITORY = 'http://pypi.python.org/pypi'
 
     user_options = [
         ('repository=', 'r',
@@ -135,7 +134,7 @@
         boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
         sep_boundary = '\n--' + boundary
         end_boundary = sep_boundary + '--'
-        body = StringIO.StringIO()
+        body = io.StringIO()
         for key, value in data.items():
             # handle multiple entries for the same name
             if type(value) != type([]):

Modified: python/branches/py3k-buffer/Lib/distutils/tests/test_build_py.py
==============================================================================
--- python/branches/py3k-buffer/Lib/distutils/tests/test_build_py.py	(original)
+++ python/branches/py3k-buffer/Lib/distutils/tests/test_build_py.py	Fri Aug 17 20:48:09 2007
@@ -2,7 +2,7 @@
 
 import os
 import sys
-import StringIO
+import io
 import unittest
 
 from distutils.command.build_py import build_py
@@ -69,7 +69,7 @@
         open(os.path.join(testdir, "testfile"), "w").close()
 
         os.chdir(sources)
-        sys.stdout = StringIO.StringIO()
+        sys.stdout = io.StringIO()
 
         try:
             dist = Distribution({"packages": ["pkg"],

Modified: python/branches/py3k-buffer/Lib/distutils/tests/test_dist.py
==============================================================================
--- python/branches/py3k-buffer/Lib/distutils/tests/test_dist.py	(original)
+++ python/branches/py3k-buffer/Lib/distutils/tests/test_dist.py	Fri Aug 17 20:48:09 2007
@@ -4,7 +4,7 @@
 import distutils.dist
 import os
 import shutil
-import StringIO
+import io
 import sys
 import tempfile
 import unittest
@@ -177,7 +177,7 @@
                            "obsoletes": ["my.pkg (splat)"]})
 
     def format_metadata(self, dist):
-        sio = StringIO.StringIO()
+        sio = io.StringIO()
         dist.metadata.write_pkg_file(sio)
         return sio.getvalue()
 

Modified: python/branches/py3k-buffer/Lib/doctest.py
==============================================================================
--- python/branches/py3k-buffer/Lib/doctest.py	(original)
+++ python/branches/py3k-buffer/Lib/doctest.py	Fri Aug 17 20:48:09 2007
@@ -98,7 +98,7 @@
 import sys, traceback, inspect, linecache, os, re
 import unittest, difflib, pdb, tempfile
 import warnings
-from StringIO import StringIO
+from io import StringIO
 
 # There are 4 basic classes:
 #  - Example: a <source, want> pair, plus an intra-docstring line number.
@@ -209,7 +209,7 @@
         filename = _module_relative_path(package, filename)
         if hasattr(package, '__loader__'):
             if hasattr(package.__loader__, 'get_data'):
-                return package.__loader__.get_data(filename), filename
+                return package.__loader__.get_data(filename).decode('utf-8'), filename
     return open(filename, encoding="utf-8").read(), filename
 
 def _indent(s, indent=4):

Modified: python/branches/py3k-buffer/Lib/dumbdbm.py
==============================================================================
--- python/branches/py3k-buffer/Lib/dumbdbm.py	(original)
+++ python/branches/py3k-buffer/Lib/dumbdbm.py	Fri Aug 17 20:48:09 2007
@@ -115,6 +115,7 @@
     sync = _commit
 
     def __getitem__(self, key):
+        key = key.decode("latin-1")
         pos, siz = self._index[key]     # may raise KeyError
         f = _io.open(self._datfile, 'rb')
         f.seek(pos)
@@ -159,8 +160,9 @@
         f.close()
 
     def __setitem__(self, key, val):
-        if not isinstance(key, basestring):
-            raise TypeError("keys must be strings")
+        if not isinstance(key, bytes):
+            raise TypeError("keys must be bytes")
+        key = key.decode("latin-1") # hashable bytes
         if not isinstance(val, (str8, bytes)):
             raise TypeError("values must be byte strings")
         if key not in self._index:
@@ -188,6 +190,7 @@
             # (so that _commit() never gets called).
 
     def __delitem__(self, key):
+        key = key.decode("latin-1")
         # The blocks used by the associated value are lost.
         del self._index[key]
         # XXX It's unclear why we do a _commit() here (the code always

Modified: python/branches/py3k-buffer/Lib/email/generator.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/generator.py	(original)
+++ python/branches/py3k-buffer/Lib/email/generator.py	Fri Aug 17 20:48:09 2007
@@ -12,7 +12,7 @@
 import random
 import warnings
 
-from cStringIO import StringIO
+from io import StringIO
 from email.header import Header
 
 UNDERSCORE = '_'

Modified: python/branches/py3k-buffer/Lib/email/iterators.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/iterators.py	(original)
+++ python/branches/py3k-buffer/Lib/email/iterators.py	Fri Aug 17 20:48:09 2007
@@ -12,7 +12,7 @@
     ]
 
 import sys
-from cStringIO import StringIO
+from io import StringIO
 
 
 

Modified: python/branches/py3k-buffer/Lib/email/message.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/message.py	(original)
+++ python/branches/py3k-buffer/Lib/email/message.py	Fri Aug 17 20:48:09 2007
@@ -10,7 +10,7 @@
 import uu
 import binascii
 import warnings
-from cStringIO import StringIO
+from io import StringIO
 
 # Intrapackage imports
 import email.charset

Modified: python/branches/py3k-buffer/Lib/email/mime/audio.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/mime/audio.py	(original)
+++ python/branches/py3k-buffer/Lib/email/mime/audio.py	Fri Aug 17 20:48:09 2007
@@ -8,7 +8,7 @@
 
 import sndhdr
 
-from cStringIO import StringIO
+from io import StringIO
 from email import encoders
 from email.mime.nonmultipart import MIMENonMultipart
 

Modified: python/branches/py3k-buffer/Lib/email/parser.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/parser.py	(original)
+++ python/branches/py3k-buffer/Lib/email/parser.py	Fri Aug 17 20:48:09 2007
@@ -7,7 +7,7 @@
 __all__ = ['Parser', 'HeaderParser']
 
 import warnings
-from cStringIO import StringIO
+from io import StringIO
 
 from email.feedparser import FeedParser
 from email.message import Message

Modified: python/branches/py3k-buffer/Lib/email/test/test_email.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/test/test_email.py	(original)
+++ python/branches/py3k-buffer/Lib/email/test/test_email.py	Fri Aug 17 20:48:09 2007
@@ -9,7 +9,7 @@
 import difflib
 import unittest
 import warnings
-from cStringIO import StringIO
+from io import StringIO
 
 import email
 

Modified: python/branches/py3k-buffer/Lib/email/test/test_email_renamed.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/test/test_email_renamed.py	(original)
+++ python/branches/py3k-buffer/Lib/email/test/test_email_renamed.py	Fri Aug 17 20:48:09 2007
@@ -9,7 +9,7 @@
 import difflib
 import unittest
 import warnings
-from cStringIO import StringIO
+from io import StringIO
 
 import email
 

Modified: python/branches/py3k-buffer/Lib/email/test/test_email_torture.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/test/test_email_torture.py	(original)
+++ python/branches/py3k-buffer/Lib/email/test/test_email_torture.py	Fri Aug 17 20:48:09 2007
@@ -9,7 +9,7 @@
 import sys
 import os
 import unittest
-from cStringIO import StringIO
+from io import StringIO
 from types import ListType
 
 from email.test.test_email import TestEmailBase

Modified: python/branches/py3k-buffer/Lib/email/utils.py
==============================================================================
--- python/branches/py3k-buffer/Lib/email/utils.py	(original)
+++ python/branches/py3k-buffer/Lib/email/utils.py	Fri Aug 17 20:48:09 2007
@@ -27,7 +27,7 @@
 import socket
 import urllib
 import warnings
-from cStringIO import StringIO
+from io import StringIO
 
 from email._parseaddr import quote
 from email._parseaddr import AddressList as _AddressList

Modified: python/branches/py3k-buffer/Lib/httplib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/httplib.py	(original)
+++ python/branches/py3k-buffer/Lib/httplib.py	Fri Aug 17 20:48:09 2007
@@ -67,12 +67,11 @@
 """
 
 import errno
+import io
 import mimetools
 import socket
 from urlparse import urlsplit
 
-from io import StringIO
-
 __all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection",
            "HTTPException", "NotConnected", "UnknownProtocol",
            "UnknownTransferEncoding", "UnimplementedFileMode",
@@ -264,7 +263,7 @@
                 except IOError:
                     startofline = tell = None
                     self.seekable = 0
-            line = self.fp.readline()
+            line = str(self.fp.readline(), "iso-8859-1")
             if not line:
                 self.status = 'EOF in headers'
                 break
@@ -317,8 +316,20 @@
 
     # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
 
+    # The bytes from the socket object are iso-8859-1 strings.
+    # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
+    # text following RFC 2047.  The basic status line parsing only
+    # accepts iso-8859-1.
+
     def __init__(self, sock, debuglevel=0, strict=0, method=None):
-        self.fp = sock.makefile('rb', 0)
+        # XXX If the response includes a content-length header, we
+        # need to make sure that the client doesn't read more than the
+        # specified number of bytes.  If it does, it will block until
+        # the server times out and closes the connection.  (The only
+        # applies to HTTP/1.1 connections.)  Since some clients access
+        # self.fp directly rather than calling read(), this is a little
+        # tricky.
+        self.fp = sock.makefile("rb", 0)
         self.debuglevel = debuglevel
         self.strict = strict
         self._method = method
@@ -336,8 +347,8 @@
         self.will_close = _UNKNOWN      # conn will close at end of response
 
     def _read_status(self):
-        # Initialize with Simple-Response defaults
-        line = self.fp.readline()
+        # Initialize with Simple-Response defaults.
+        line = str(self.fp.readline(), "iso-8859-1")
         if self.debuglevel > 0:
             print("reply:", repr(line))
         if not line:
@@ -354,13 +365,15 @@
                 # empty version will cause next test to fail and status
                 # will be treated as 0.9 response.
                 version = ""
-        if not version.startswith('HTTP/'):
+        if not version.startswith("HTTP/"):
             if self.strict:
                 self.close()
                 raise BadStatusLine(line)
             else:
-                # assume it's a Simple-Response from an 0.9 server
-                self.fp = LineAndFileWrapper(line, self.fp)
+                # Assume it's a Simple-Response from an 0.9 server.
+                # We have to convert the first line back to raw bytes
+                # because self.fp.readline() needs to return bytes.
+                self.fp = LineAndFileWrapper(bytes(line), self.fp)
                 return "HTTP/0.9", 200, ""
 
         # The status code is a three-digit number
@@ -392,11 +405,11 @@
 
         self.status = status
         self.reason = reason.strip()
-        if version == 'HTTP/1.0':
+        if version == "HTTP/1.0":
             self.version = 10
-        elif version.startswith('HTTP/1.'):
+        elif version.startswith("HTTP/1."):
             self.version = 11   # use HTTP/1.1 code for HTTP/1.x where x>=1
-        elif version == 'HTTP/0.9':
+        elif version == "HTTP/0.9":
             self.version = 9
         else:
             raise UnknownProtocol(version)
@@ -405,19 +418,19 @@
             self.length = None
             self.chunked = 0
             self.will_close = 1
-            self.msg = HTTPMessage(StringIO())
+            self.msg = HTTPMessage(io.BytesIO())
             return
 
         self.msg = HTTPMessage(self.fp, 0)
         if self.debuglevel > 0:
             for hdr in self.msg.headers:
-                print("header:", hdr, end=' ')
+                print("header:", hdr, end=" ")
 
         # don't let the msg keep an fp
         self.msg.fp = None
 
         # are we using the chunked-style of transfer encoding?
-        tr_enc = self.msg.getheader('transfer-encoding')
+        tr_enc = self.msg.getheader("transfer-encoding")
         if tr_enc and tr_enc.lower() == "chunked":
             self.chunked = 1
             self.chunk_left = None
@@ -429,35 +442,34 @@
 
         # do we have a Content-Length?
         # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
-        length = self.msg.getheader('content-length')
+        self.length = None
+        length = self.msg.getheader("content-length")
         if length and not self.chunked:
             try:
                 self.length = int(length)
             except ValueError:
-                self.length = None
-        else:
-            self.length = None
+                pass
 
         # does the body have a fixed length? (of zero)
         if (status == NO_CONTENT or status == NOT_MODIFIED or
             100 <= status < 200 or      # 1xx codes
-            self._method == 'HEAD'):
+            self._method == "HEAD"):
             self.length = 0
 
         # if the connection remains open, and we aren't using chunked, and
         # a content-length was not provided, then assume that the connection
         # WILL close.
-        if not self.will_close and \
-           not self.chunked and \
-           self.length is None:
+        if (not self.will_close and
+            not self.chunked and
+            self.length is None):
             self.will_close = 1
 
     def _check_close(self):
-        conn = self.msg.getheader('connection')
+        conn = self.msg.getheader("connection")
         if self.version == 11:
             # An HTTP/1.1 proxy is assumed to stay open unless
             # explicitly closed.
-            conn = self.msg.getheader('connection')
+            conn = self.msg.getheader("connection")
             if conn and "close" in conn.lower():
                 return True
             return False
@@ -466,7 +478,7 @@
         # connections, using rules different than HTTP/1.1.
 
         # For older HTTP, Keep-Alive indiciates persistent connection.
-        if self.msg.getheader('keep-alive'):
+        if self.msg.getheader("keep-alive"):
             return False
 
         # At least Akamai returns a "Connection: Keep-Alive" header,
@@ -475,7 +487,7 @@
             return False
 
         # Proxy-Connection is a netscape hack.
-        pconn = self.msg.getheader('proxy-connection')
+        pconn = self.msg.getheader("proxy-connection")
         if pconn and "keep-alive" in pconn.lower():
             return False
 
@@ -487,6 +499,20 @@
             self.fp.close()
             self.fp = None
 
+    # These implementations are for the benefit of io.BufferedReader.
+
+    # XXX This class should probably be revised to act more like
+    # the "raw stream" that BufferedReader expects.
+
+    @property
+    def closed(self):
+        return self.isclosed()
+
+    def flush(self):
+        self.fp.flush()
+
+    # End of "raw stream" methods
+
     def isclosed(self):
         # NOTE: it is possible that we will not ever call self.close(). This
         #       case occurs when will_close is TRUE, length is None, and we
@@ -500,7 +526,7 @@
 
     def read(self, amt=None):
         if self.fp is None:
-            return ''
+            return ""
 
         if self.chunked:
             return self._read_chunked(amt)
@@ -532,14 +558,14 @@
     def _read_chunked(self, amt):
         assert self.chunked != _UNKNOWN
         chunk_left = self.chunk_left
-        value = ''
+        value = ""
 
         # XXX This accumulates chunks by repeated string concatenation,
         # which is not efficient as the number or size of chunks gets big.
         while True:
             if chunk_left is None:
                 line = self.fp.readline()
-                i = line.find(';')
+                i = line.find(";")
                 if i >= 0:
                     line = line[:i] # strip chunk-extensions
                 chunk_left = int(line, 16)
@@ -568,7 +594,7 @@
         ### note: we shouldn't have any trailers!
         while True:
             line = self.fp.readline()
-            if line == '\r\n':
+            if line == "\r\n":
                 break
 
         # we read everything; close the "file"
@@ -597,7 +623,7 @@
                 raise IncompleteRead(s)
             s.append(chunk)
             amt -= len(chunk)
-        return ''.join(s)
+        return "".join(s)
 
     def getheader(self, name, default=None):
         if self.msg is None:
@@ -892,7 +918,7 @@
             self.send(body)
 
     def getresponse(self):
-        "Get the response from the server."
+        """Get the response from the server."""
 
         # if a prior response has been completed, then forget about it.
         if self.__response and self.__response.isclosed():
@@ -992,11 +1018,11 @@
     def __init__(self, sock, ssl, bufsize=None):
         SharedSocketClient.__init__(self, sock)
         self._ssl = ssl
-        self._buf = ''
+        self._buf = b""
         self._bufsize = bufsize or self.__class__.BUFSIZE
 
     def _read(self):
-        buf = ''
+        buf = b""
         # put in a loop so that we retry on transient errors
         while True:
             try:
@@ -1027,13 +1053,13 @@
         avail = len(self._buf)
         while size is None or avail < size:
             s = self._read()
-            if s == '':
+            if s == b"":
                 break
             L.append(s)
             avail += len(s)
-        all = "".join(L)
+        all = b"".join(L)
         if size is None:
-            self._buf = ''
+            self._buf = b""
             return all
         else:
             self._buf = all[size:]
@@ -1041,20 +1067,20 @@
 
     def readline(self):
         L = [self._buf]
-        self._buf = ''
+        self._buf = b""
         while 1:
             i = L[-1].find("\n")
             if i >= 0:
                 break
             s = self._read()
-            if s == '':
+            if s == b"":
                 break
             L.append(s)
         if i == -1:
             # loop exited because there is no more data
-            return "".join(L)
+            return b"".join(L)
         else:
-            all = "".join(L)
+            all = b"".join(L)
             # XXX could do enough bookkeeping not to do a 2nd search
             i = all.find("\n") + 1
             line = all[:i]
@@ -1117,6 +1143,9 @@
     def __getattr__(self, attr):
         return getattr(self._sock, attr)
 
+    def close(self):
+        SharedSocketClient.close(self)
+        self._ssl = None
 
 class HTTPSConnection(HTTPConnection):
     "This class allows communication via SSL."
@@ -1199,10 +1228,6 @@
         try:
             response = self._conn.getresponse()
         except BadStatusLine as e:
-            ### hmm. if getresponse() ever closes the socket on a bad request,
-            ### then we are going to have problems with self.sock
-
-            ### should we keep this behavior? do people use it?
             # keep the socket open (as a file), and return it
             self.file = self._conn.sock.makefile('rb', 0)
 
@@ -1393,7 +1418,7 @@
     status, reason, headers = h.getreply()
     print('status =', status)
     print('reason =', reason)
-    print("read", len(h.getfile().read()))
+    print('read', len(h.getfile().read()))
     print()
     if headers:
         for header in headers.headers: print(header.strip())

Modified: python/branches/py3k-buffer/Lib/idlelib/EditorWindow.py
==============================================================================
--- python/branches/py3k-buffer/Lib/idlelib/EditorWindow.py	(original)
+++ python/branches/py3k-buffer/Lib/idlelib/EditorWindow.py	Fri Aug 17 20:48:09 2007
@@ -1,6 +1,7 @@
 import sys
 import os
 import re
+import string
 import imp
 from itertools import count
 from Tkinter import *
@@ -602,6 +603,19 @@
         theme = idleConf.GetOption('main','Theme','name')
         self.text.config(idleConf.GetHighlight(theme, "normal"))
 
+    IDENTCHARS = string.ascii_letters + string.digits + "_"
+
+    def colorize_syntax_error(self, text, pos):
+        text.tag_add("ERROR", pos)
+        char = text.get(pos)
+        if char and char in self.IDENTCHARS:
+            text.tag_add("ERROR", pos + " wordstart", pos)
+        if '\n' == text.get(pos):   # error at line end
+            text.mark_set("insert", pos)
+        else:
+            text.mark_set("insert", pos + "+1c")
+        text.see(pos)
+
     def ResetFont(self):
         "Update the text widgets' font if it is changed"
         # Called from configDialog.py
@@ -1004,6 +1018,8 @@
                                   "n" * newtabwidth)
             text.configure(tabs=pixels)
 
+### begin autoindent code ###  (configuration was moved to beginning of class)
+
     # If ispythonsource and guess are true, guess a good value for
     # indentwidth based on file content (if possible), and if
     # indentwidth != tabwidth set usetabs false.

Modified: python/branches/py3k-buffer/Lib/idlelib/PyShell.py
==============================================================================
--- python/branches/py3k-buffer/Lib/idlelib/PyShell.py	(original)
+++ python/branches/py3k-buffer/Lib/idlelib/PyShell.py	Fri Aug 17 20:48:09 2007
@@ -3,7 +3,6 @@
 import os
 import os.path
 import sys
-import string
 import getopt
 import re
 import socket
@@ -35,7 +34,6 @@
 from . import RemoteDebugger
 from . import macosxSupport
 
-IDENTCHARS = string.ascii_letters + string.digits + "_"
 LOCALHOST = '127.0.0.1'
 
 try:
@@ -624,47 +622,30 @@
             \n""" % (filename,))
 
     def showsyntaxerror(self, filename=None):
-        """Extend base class method: Add Colorizing
+        """Override Interactive Interpreter method: Use Colorizing
 
         Color the offending position instead of printing it and pointing at it
         with a caret.
 
         """
-        text = self.tkconsole.text
-        stuff = self.unpackerror()
-        if stuff:
-            msg, lineno, offset, line = stuff
-            if lineno == 1:
-                pos = "iomark + %d chars" % (offset-1)
-            else:
-                pos = "iomark linestart + %d lines + %d chars" % \
-                      (lineno-1, offset-1)
-            text.tag_add("ERROR", pos)
-            text.see(pos)
-            char = text.get(pos)
-            if char and char in IDENTCHARS:
-                text.tag_add("ERROR", pos + " wordstart", pos)
-            self.tkconsole.resetoutput()
-            self.write("SyntaxError: %s\n" % str(msg))
-        else:
-            self.tkconsole.resetoutput()
-            InteractiveInterpreter.showsyntaxerror(self, filename)
-        self.tkconsole.showprompt()
-
-    def unpackerror(self):
+        tkconsole = self.tkconsole
+        text = tkconsole.text
+        text.tag_remove("ERROR", "1.0", "end")
         type, value, tb = sys.exc_info()
-        ok = type is SyntaxError
-        if ok:
-            try:
-                msg, (dummy_filename, lineno, offset, line) = value
-                if not offset:
-                    offset = 0
-            except:
-                ok = 0
-        if ok:
-            return msg, lineno, offset, line
+        msg = value.msg or "<no detail available>"
+        lineno = value.lineno or 1
+        offset = value.offset or 0
+        if offset == 0:
+            lineno += 1 #mark end of offending line
+        if lineno == 1:
+            pos = "iomark + %d chars" % (offset-1)
         else:
-            return None
+            pos = "iomark linestart + %d lines + %d chars" % \
+                  (lineno-1, offset-1)
+        tkconsole.colorize_syntax_error(text, pos)
+        tkconsole.resetoutput()
+        self.write("SyntaxError: %s\n" % msg)
+        tkconsole.showprompt()
 
     def showtraceback(self):
         "Extend base class method to reset output properly"

Modified: python/branches/py3k-buffer/Lib/idlelib/ScriptBinding.py
==============================================================================
--- python/branches/py3k-buffer/Lib/idlelib/ScriptBinding.py	(original)
+++ python/branches/py3k-buffer/Lib/idlelib/ScriptBinding.py	Fri Aug 17 20:48:09 2007
@@ -23,12 +23,11 @@
 import tabnanny
 import tokenize
 import tkMessageBox
+from .EditorWindow import EditorWindow
 from . import PyShell
 
 from .configHandler import idleConf
 
-IDENTCHARS = string.ascii_letters + string.digits + "_"
-
 indent_message = """Error: Inconsistent indentation detected!
 
 1) Your indentation is outright incorrect (easy to fix), OR
@@ -83,7 +82,7 @@
         self.shell = shell = self.flist.open_shell()
         saved_stream = shell.get_warning_stream()
         shell.set_warning_stream(shell.stderr)
-        f = open(filename, 'r')
+        f = file(filename, 'r')
         source = f.read()
         f.close()
         if '\r' in source:
@@ -91,40 +90,25 @@
             source = re.sub(r"\r", "\n", source)
         if source and source[-1] != '\n':
             source = source + '\n'
-        text = self.editwin.text
+        editwin = self.editwin
+        text = editwin.text
         text.tag_remove("ERROR", "1.0", "end")
         try:
-            try:
-                # If successful, return the compiled code
-                return compile(source, filename, "exec")
-            except (SyntaxError, OverflowError) as err:
-                try:
-                    msg, (errorfilename, lineno, offset, line) = err.args
-                    if not errorfilename:
-                        err.args = msg, (filename, lineno, offset, line)
-                        err.filename = filename
-                    self.colorize_syntax_error(msg, lineno, offset)
-                except:
-                    msg = str(err)
-                self.errorbox("Syntax error",
-                              "There's an error in your program:\n" + msg)
-                return False
+            # If successful, return the compiled code
+            return compile(source, filename, "exec")
+        except (SyntaxError, OverflowError) as value:
+            msg = value.msg or "<no detail available>"
+            lineno = value.lineno or 1
+            offset = value.offset or 0
+            if offset == 0:
+                lineno += 1  #mark end of offending line
+            pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
+            editwin.colorize_syntax_error(text, pos)
+            self.errorbox("SyntaxError", "%-20s" % msg)
+            return False
         finally:
             shell.set_warning_stream(saved_stream)
 
-    def colorize_syntax_error(self, msg, lineno, offset):
-        text = self.editwin.text
-        pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
-        text.tag_add("ERROR", pos)
-        char = text.get(pos)
-        if char and char in IDENTCHARS:
-            text.tag_add("ERROR", pos + " wordstart", pos)
-        if '\n' == text.get(pos):   # error at line end
-            text.mark_set("insert", pos)
-        else:
-            text.mark_set("insert", pos + "+1c")
-        text.see(pos)
-
     def run_module_event(self, event):
         """Run the module after setting up the environment.
 
@@ -199,10 +183,10 @@
                                   icon=tkMessageBox.QUESTION,
                                   type=tkMessageBox.OKCANCEL,
                                   default=tkMessageBox.OK,
-                                  master=self.editwin.text)
+                                  parent=self.editwin.text)
         return mb.show()
 
     def errorbox(self, title, message):
         # XXX This should really be a function of EditorWindow...
-        tkMessageBox.showerror(title, message, master=self.editwin.text)
+        tkMessageBox.showerror(title, message, parent=self.editwin.text)
         self.editwin.text.focus_set()

Modified: python/branches/py3k-buffer/Lib/idlelib/run.py
==============================================================================
--- python/branches/py3k-buffer/Lib/idlelib/run.py	(original)
+++ python/branches/py3k-buffer/Lib/idlelib/run.py	Fri Aug 17 20:48:09 2007
@@ -149,14 +149,14 @@
     typ, val, tb = excinfo = sys.exc_info()
     sys.last_type, sys.last_value, sys.last_traceback = excinfo
     tbe = traceback.extract_tb(tb)
-    print('\nTraceback (most recent call last):', file=efile)
+    print('Traceback (most recent call last):', file=efile)
     exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
                "RemoteDebugger.py", "bdb.py")
     cleanup_traceback(tbe, exclude)
     traceback.print_list(tbe, file=efile)
     lines = traceback.format_exception_only(typ, val)
     for line in lines:
-        print(line, end=' ', file=efile)
+        print(line, end='', file=efile)
 
 def cleanup_traceback(tb, exclude):
     "Remove excluded traces from beginning/end of tb; get cached lines"
@@ -193,14 +193,16 @@
     """XXX How to do this now?"""
 
 def exit():
-    """Exit subprocess, possibly after first deleting sys.exitfunc
+    """Exit subprocess, possibly after first clearing exit functions.
 
     If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any
-    sys.exitfunc will be removed before exiting.  (VPython support)
+    functions registered with atexit will be removed before exiting.
+    (VPython support)
 
     """
     if no_exitfunc:
-        del sys.exitfunc
+        import atexit
+        atexit._clear()
     sys.exit(0)
 
 class MyRPCServer(rpc.RPCServer):

Modified: python/branches/py3k-buffer/Lib/io.py
==============================================================================
--- python/branches/py3k-buffer/Lib/io.py	(original)
+++ python/branches/py3k-buffer/Lib/io.py	Fri Aug 17 20:48:09 2007
@@ -303,6 +303,8 @@
 
         Returns False if we don't know.
         """
+        if self.closed:
+            raise ValueError("isatty() on closed file")
         return False
 
     ### Readline[s] and writelines ###
@@ -442,58 +444,6 @@
         return self._mode
 
 
-class SocketIO(RawIOBase):
-
-    """Raw I/O implementation for stream sockets."""
-
-    # XXX More docs
-
-    def __init__(self, sock, mode):
-        assert mode in ("r", "w", "rw")
-        RawIOBase.__init__(self)
-        self._sock = sock
-        self._mode = mode
-
-    def readinto(self, b):
-        return self._sock.recv_into(b)
-
-    def read(self, n: int = None) -> bytes:
-        """read(n: int) -> bytes.  Read and return up to n bytes.
-
-        Returns an empty bytes array on EOF, or None if the object is
-        set not to block and has no data to read.
-        """
-        if n is None:
-            n = -1
-        if n >= 0:
-            return RawIOBase.read(self, n)
-        # Support reading until the end.
-        # XXX Why doesn't RawIOBase support this?
-        data = b""
-        while True:
-            more = RawIOBase.read(self, DEFAULT_BUFFER_SIZE)
-            if not more:
-                break
-            data += more
-        return data
-
-    def write(self, b):
-        return self._sock.send(b)
-
-    def close(self):
-        if not self.closed:
-            RawIOBase.close(self)
-
-    def readable(self):
-        return "r" in self._mode
-
-    def writable(self):
-        return "w" in self._mode
-
-    def fileno(self):
-        return self._sock.fileno()
-
-
 class BufferedIOBase(IOBase):
 
     """Base class for buffered IO objects.
@@ -1286,11 +1236,16 @@
 
     # XXX This is really slow, but fully functional
 
-    def __init__(self, initial_value=""):
-        super(StringIO, self).__init__(BytesIO(), "utf-8")
+    def __init__(self, initial_value="", encoding="utf-8", newline=None):
+        super(StringIO, self).__init__(BytesIO(),
+                                       encoding=encoding,
+                                       newline=newline)
         if initial_value:
+            if not isinstance(initial_value, basestring):
+                initial_value = str(initial_value)
             self.write(initial_value)
             self.seek(0)
 
     def getvalue(self):
-        return self.buffer.getvalue().decode("utf-8")
+        self.flush()
+        return self.buffer.getvalue().decode(self._encoding)

Modified: python/branches/py3k-buffer/Lib/logging/__init__.py
==============================================================================
--- python/branches/py3k-buffer/Lib/logging/__init__.py	(original)
+++ python/branches/py3k-buffer/Lib/logging/__init__.py	Fri Aug 17 20:48:09 2007
@@ -26,7 +26,7 @@
 To use, simply 'import logging' and log away!
 """
 
-import sys, os, time, cStringIO, traceback
+import sys, os, time, io, traceback
 
 try:
     import codecs
@@ -396,7 +396,7 @@
         This default implementation just uses
         traceback.print_exception()
         """
-        sio = cStringIO.StringIO()
+        sio = io.StringIO()
         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
         s = sio.getvalue()
         sio.close()

Modified: python/branches/py3k-buffer/Lib/mailbox.py
==============================================================================
--- python/branches/py3k-buffer/Lib/mailbox.py	(original)
+++ python/branches/py3k-buffer/Lib/mailbox.py	Fri Aug 17 20:48:09 2007
@@ -19,7 +19,7 @@
 import email.message
 import email.generator
 import rfc822
-import StringIO
+import io
 try:
     if sys.platform == 'os2emx':
         # OS/2 EMX fcntl() not adequate
@@ -194,7 +194,7 @@
         # used in strings and by email.Message are translated here.
         """Dump message contents to target file."""
         if isinstance(message, email.message.Message):
-            buffer = StringIO.StringIO()
+            buffer = io.StringIO()
             gen = email.generator.Generator(buffer, mangle_from_, 0)
             gen.flatten(message)
             buffer.seek(0)
@@ -1141,13 +1141,13 @@
         start, stop = self._lookup(key)
         self._file.seek(start)
         self._file.readline()   # Skip '1,' line specifying labels.
-        original_headers = StringIO.StringIO()
+        original_headers = io.StringIO()
         while True:
             line = self._file.readline()
             if line == '*** EOOH ***' + os.linesep or not line:
                 break
             original_headers.write(line.replace(os.linesep, '\n'))
-        visible_headers = StringIO.StringIO()
+        visible_headers = io.StringIO()
         while True:
             line = self._file.readline()
             if line == os.linesep or not line:
@@ -1166,7 +1166,7 @@
         start, stop = self._lookup(key)
         self._file.seek(start)
         self._file.readline()   # Skip '1,' line specifying labels.
-        original_headers = StringIO.StringIO()
+        original_headers = io.StringIO()
         while True:
             line = self._file.readline()
             if line == '*** EOOH ***' + os.linesep or not line:
@@ -1182,7 +1182,7 @@
 
     def get_file(self, key):
         """Return a file-like representation or raise a KeyError."""
-        return StringIO.StringIO(self.get_string(key).replace('\n',
+        return io.StringIO(self.get_string(key).replace('\n',
                                                               os.linesep))
 
     def get_labels(self):
@@ -1259,7 +1259,7 @@
         else:
             self._file.write('1,,' + os.linesep)
         if isinstance(message, email.message.Message):
-            orig_buffer = StringIO.StringIO()
+            orig_buffer = io.StringIO()
             orig_generator = email.generator.Generator(orig_buffer, False, 0)
             orig_generator.flatten(message)
             orig_buffer.seek(0)
@@ -1270,7 +1270,7 @@
                     break
             self._file.write('*** EOOH ***' + os.linesep)
             if isinstance(message, BabylMessage):
-                vis_buffer = StringIO.StringIO()
+                vis_buffer = io.StringIO()
                 vis_generator = email.generator.Generator(vis_buffer, False, 0)
                 vis_generator.flatten(message.get_visible())
                 while True:

Modified: python/branches/py3k-buffer/Lib/mimetools.py
==============================================================================
--- python/branches/py3k-buffer/Lib/mimetools.py	(original)
+++ python/branches/py3k-buffer/Lib/mimetools.py	Fri Aug 17 20:48:09 2007
@@ -144,6 +144,7 @@
 
 
 # Subroutines for decoding some common content-transfer-types
+# Input and output must be files opened in binary mode
 
 def decode(input, output, encoding):
     """Decode common content-transfer-encodings (base64, quopri, uuencode)."""
@@ -157,7 +158,7 @@
         import uu
         return uu.decode(input, output)
     if encoding in ('7bit', '8bit'):
-        return output.write(input.read())
+        return output.write(input.read().decode("Latin-1"))
     if encoding in decodetab:
         pipethrough(input, decodetab[encoding], output)
     else:

Modified: python/branches/py3k-buffer/Lib/optparse.py
==============================================================================
--- python/branches/py3k-buffer/Lib/optparse.py	(original)
+++ python/branches/py3k-buffer/Lib/optparse.py	Fri Aug 17 20:48:09 2007
@@ -1621,13 +1621,6 @@
         result.append(self.format_epilog(formatter))
         return "".join(result)
 
-    # used by test suite
-    def _get_encoding(self, file):
-        encoding = getattr(file, "encoding", None)
-        if not encoding:
-            encoding = sys.getdefaultencoding()
-        return encoding
-
     def print_help(self, file=None):
         """print_help(file : file = stdout)
 
@@ -1636,8 +1629,7 @@
         """
         if file is None:
             file = sys.stdout
-        encoding = self._get_encoding(file)
-        file.write(self.format_help().encode(encoding, "replace"))
+        file.write(self.format_help())
 
 # class OptionParser
 

Modified: python/branches/py3k-buffer/Lib/pickletools.py
==============================================================================
--- python/branches/py3k-buffer/Lib/pickletools.py	(original)
+++ python/branches/py3k-buffer/Lib/pickletools.py	Fri Aug 17 20:48:09 2007
@@ -1797,8 +1797,8 @@
     is None.
 
     If the pickle has a tell() method, pos was the value of pickle.tell()
-    before reading the current opcode.  If the pickle is a string object,
-    it's wrapped in a StringIO object, and the latter's tell() result is
+    before reading the current opcode.  If the pickle is a bytes object,
+    it's wrapped in a BytesIO object, and the latter's tell() result is
     used.  Else (the pickle doesn't have a tell(), and it's not obvious how
     to query its current position) pos is None.
     """

Modified: python/branches/py3k-buffer/Lib/plat-mac/Carbon/AppleEvents.py
==============================================================================
--- python/branches/py3k-buffer/Lib/plat-mac/Carbon/AppleEvents.py	(original)
+++ python/branches/py3k-buffer/Lib/plat-mac/Carbon/AppleEvents.py	Fri Aug 17 20:48:09 2007
@@ -1,6 +1,6 @@
 # Generated from 'AEDataModel.h'
 
-def FOUR_CHAR_CODE(x): return x
+def FOUR_CHAR_CODE(x): return bytes(x)
 typeBoolean = FOUR_CHAR_CODE('bool')
 typeChar = FOUR_CHAR_CODE('TEXT')
 typeSInt16 = FOUR_CHAR_CODE('shor')

Modified: python/branches/py3k-buffer/Lib/plat-mac/aepack.py
==============================================================================
--- python/branches/py3k-buffer/Lib/plat-mac/aepack.py	(original)
+++ python/branches/py3k-buffer/Lib/plat-mac/aepack.py	Fri Aug 17 20:48:09 2007
@@ -17,7 +17,7 @@
 from Carbon.AppleEvents import *
 import MacOS
 import Carbon.File
-import StringIO
+import io
 import aetypes
 from aetypes import mkenum, ObjectSpecifier
 import os
@@ -25,30 +25,36 @@
 # These ones seem to be missing from AppleEvents
 # (they're in AERegistry.h)
 
-#typeColorTable = 'clrt'
-#typeDrawingArea = 'cdrw'
-#typePixelMap = 'cpix'
-#typePixelMapMinus = 'tpmm'
-#typeRotation = 'trot'
-#typeTextStyles = 'tsty'
-#typeStyledText = 'STXT'
-#typeAEText = 'tTXT'
-#typeEnumeration = 'enum'
-
+#typeColorTable = b'clrt'
+#typeDrawingArea = b'cdrw'
+#typePixelMap = b'cpix'
+#typePixelMapMinus = b'tpmm'
+#typeRotation = b'trot'
+#typeTextStyles = b'tsty'
+#typeStyledText = b'STXT'
+#typeAEText = b'tTXT'
+#typeEnumeration = b'enum'
+
+def b2i(byte_string):
+    result = 0
+    for byte in byte_string:
+        result <<= 8
+        result += byte
+    return result
 #
 # Some AE types are immedeately coerced into something
 # we like better (and which is equivalent)
 #
 unpacker_coercions = {
-    typeComp : typeFloat,
-    typeColorTable : typeAEList,
-    typeDrawingArea : typeAERecord,
-    typeFixed : typeFloat,
-    typeExtended : typeFloat,
-    typePixelMap : typeAERecord,
-    typeRotation : typeAERecord,
-    typeStyledText : typeAERecord,
-    typeTextStyles : typeAERecord,
+    b2i(typeComp) : typeFloat,
+    b2i(typeColorTable) : typeAEList,
+    b2i(typeDrawingArea) : typeAERecord,
+    b2i(typeFixed) : typeFloat,
+    b2i(typeExtended) : typeFloat,
+    b2i(typePixelMap) : typeAERecord,
+    b2i(typeRotation) : typeAERecord,
+    b2i(typeStyledText) : typeAERecord,
+    b2i(typeTextStyles) : typeAERecord,
 };
 
 #
@@ -72,33 +78,35 @@
     """Pack a python object into an AE descriptor"""
 
     if forcetype:
-        if isinstance(x, str):
+        if isinstance(x, bytes):
             return AE.AECreateDesc(forcetype, x)
         else:
             return pack(x).AECoerceDesc(forcetype)
 
     if x == None:
-        return AE.AECreateDesc('null', '')
+        return AE.AECreateDesc(b'null', '')
 
     if isinstance(x, AEDescType):
         return x
     if isinstance(x, FSSType):
-        return AE.AECreateDesc('fss ', x.data)
+        return AE.AECreateDesc(b'fss ', x.data)
     if isinstance(x, FSRefType):
-        return AE.AECreateDesc('fsrf', x.data)
+        return AE.AECreateDesc(b'fsrf', x.data)
     if isinstance(x, AliasType):
-        return AE.AECreateDesc('alis', x.data)
+        return AE.AECreateDesc(b'alis', x.data)
     if isinstance(x, int):
-        return AE.AECreateDesc('long', struct.pack('l', x))
+        return AE.AECreateDesc(b'long', struct.pack('l', x))
     if isinstance(x, float):
-        return AE.AECreateDesc('doub', struct.pack('d', x))
+        return AE.AECreateDesc(b'doub', struct.pack('d', x))
+    if isinstance(x, (bytes, str8)):
+        return AE.AECreateDesc(b'TEXT', x)
     if isinstance(x, str):
-        return AE.AECreateDesc('TEXT', x)
-    if isinstance(x, unicode):
+        # See http://developer.apple.com/documentation/Carbon/Reference/Apple_Event_Manager/Reference/reference.html#//apple_ref/doc/constant_group/typeUnicodeText
+        # for the possible encodings.
         data = x.encode('utf16')
         if data[:2] == '\xfe\xff':
             data = data[2:]
-        return AE.AECreateDesc('utxt', data)
+        return AE.AECreateDesc(b'utxt', data)
     if isinstance(x, list):
         lst = AE.AECreateList('', 0)
         for item in x:
@@ -112,37 +120,37 @@
         return record
     if isinstance(x, type) and issubclass(x, ObjectSpecifier):
         # Note: we are getting a class object here, not an instance
-        return AE.AECreateDesc('type', x.want)
+        return AE.AECreateDesc(b'type', x.want)
     if hasattr(x, '__aepack__'):
         return x.__aepack__()
     if hasattr(x, 'which'):
-        return AE.AECreateDesc('TEXT', x.which)
+        return AE.AECreateDesc(b'TEXT', x.which)
     if hasattr(x, 'want'):
-        return AE.AECreateDesc('TEXT', x.want)
-    return AE.AECreateDesc('TEXT', repr(x)) # Copout
+        return AE.AECreateDesc(b'TEXT', x.want)
+    return AE.AECreateDesc(b'TEXT', repr(x)) # Copout
 
 def unpack(desc, formodulename=""):
     """Unpack an AE descriptor to a python object"""
     t = desc.type
 
-    if t in unpacker_coercions:
-        desc = desc.AECoerceDesc(unpacker_coercions[t])
+    if b2i(t) in unpacker_coercions:
+        desc = desc.AECoerceDesc(unpacker_coercions[b2i(t)])
         t = desc.type # This is a guess by Jack....
 
     if t == typeAEList:
         l = []
         for i in range(desc.AECountItems()):
-            keyword, item = desc.AEGetNthDesc(i+1, '****')
+            keyword, item = desc.AEGetNthDesc(i+1, b'****')
             l.append(unpack(item, formodulename))
         return l
     if t == typeAERecord:
         d = {}
         for i in range(desc.AECountItems()):
-            keyword, item = desc.AEGetNthDesc(i+1, '****')
-            d[keyword] = unpack(item, formodulename)
+            keyword, item = desc.AEGetNthDesc(i+1, b'****')
+            d[b2i(keyword)] = unpack(item, formodulename)
         return d
     if t == typeAEText:
-        record = desc.AECoerceDesc('reco')
+        record = desc.AECoerceDesc(b'reco')
         return mkaetext(unpack(record, formodulename))
     if t == typeAlias:
         return Carbon.File.Alias(rawdata=desc.data)
@@ -170,7 +178,7 @@
     if t == typeFSRef:
         return Carbon.File.FSRef(rawdata=desc.data)
     if t == typeInsertionLoc:
-        record = desc.AECoerceDesc('reco')
+        record = desc.AECoerceDesc(b'reco')
         return mkinsertionloc(unpack(record, formodulename))
     # typeInteger equal to typeLongInteger
     if t == typeIntlText:
@@ -194,7 +202,7 @@
             v = 0x100000000 + v
         return v
     if t == typeObjectSpecifier:
-        record = desc.AECoerceDesc('reco')
+        record = desc.AECoerceDesc(b'reco')
         # If we have been told the name of the module we are unpacking aedescs for,
         # we can attempt to create the right type of python object from that module.
         if formodulename:
@@ -234,14 +242,14 @@
     #
     # The following are special
     #
-    if t == 'rang':
-        record = desc.AECoerceDesc('reco')
+    if t == b'rang':
+        record = desc.AECoerceDesc(b'reco')
         return mkrange(unpack(record, formodulename))
-    if t == 'cmpd':
-        record = desc.AECoerceDesc('reco')
+    if t == b'cmpd':
+        record = desc.AECoerceDesc(b'reco')
         return mkcomparison(unpack(record, formodulename))
-    if t == 'logi':
-        record = desc.AECoerceDesc('reco')
+    if t == b'logi':
+        record = desc.AECoerceDesc(b'reco')
         return mklogical(unpack(record, formodulename))
     return mkunknown(desc.type, desc.data)
 
@@ -297,39 +305,44 @@
     return aetypes.Keyword(keyword)
 
 def mkrange(dict):
-    return aetypes.Range(dict['star'], dict['stop'])
+    return aetypes.Range(dict[b2i(b'star')], dict[b2i(b'stop')])
 
 def mkcomparison(dict):
-    return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2'])
+    return aetypes.Comparison(dict[b2i(b'obj1')],
+                              dict[b2i(b'relo')].enum,
+                              dict[b2i(b'obj2')])
 
 def mklogical(dict):
-    return aetypes.Logical(dict['logc'], dict['term'])
+    return aetypes.Logical(dict[b2i(b'logc')], dict[b2i(b'term')])
 
 def mkstyledtext(dict):
-    return aetypes.StyledText(dict['ksty'], dict['ktxt'])
+    return aetypes.StyledText(dict[b2i(b'ksty')], dict[b2i(b'ktxt')])
 
 def mkaetext(dict):
-    return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText])
+    return aetypes.AEText(dict[b2i(keyAEScriptTag)],
+                          dict[b2i(keyAEStyles)],
+                          dict[b2i(keyAEText)])
 
 def mkinsertionloc(dict):
-    return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition])
+    return aetypes.InsertionLoc(dict[b2i(keyAEObject)],
+                                dict[b2i(keyAEPosition)])
 
 def mkobject(dict):
-    want = dict['want'].type
-    form = dict['form'].enum
-    seld = dict['seld']
-    fr   = dict['from']
-    if form in ('name', 'indx', 'rang', 'test'):
-        if want == 'text': return aetypes.Text(seld, fr)
-        if want == 'cha ': return aetypes.Character(seld, fr)
-        if want == 'cwor': return aetypes.Word(seld, fr)
-        if want == 'clin': return aetypes.Line(seld, fr)
-        if want == 'cpar': return aetypes.Paragraph(seld, fr)
-        if want == 'cwin': return aetypes.Window(seld, fr)
-        if want == 'docu': return aetypes.Document(seld, fr)
-        if want == 'file': return aetypes.File(seld, fr)
-        if want == 'cins': return aetypes.InsertionPoint(seld, fr)
-    if want == 'prop' and form == 'prop' and aetypes.IsType(seld):
+    want = dict[b2i(b'want')].type
+    form = dict[b2i(b'form')].enum
+    seld = dict[b2i(b'seld')]
+    fr   = dict[b2i(b'from')]
+    if form in (b'name', b'indx', b'rang', b'test'):
+        if want == b'text': return aetypes.Text(seld, fr)
+        if want == b'cha ': return aetypes.Character(seld, fr)
+        if want == b'cwor': return aetypes.Word(seld, fr)
+        if want == b'clin': return aetypes.Line(seld, fr)
+        if want == b'cpar': return aetypes.Paragraph(seld, fr)
+        if want == b'cwin': return aetypes.Window(seld, fr)
+        if want == b'docu': return aetypes.Document(seld, fr)
+        if want == b'file': return aetypes.File(seld, fr)
+        if want == b'cins': return aetypes.InsertionPoint(seld, fr)
+    if want == b'prop' and form == b'prop' and aetypes.IsType(seld):
         return aetypes.Property(seld.type, fr)
     return aetypes.ObjectSpecifier(want, form, seld, fr)
 
@@ -338,14 +351,15 @@
 # to __class__ is safe. Moreover, shouldn't there be a better
 # initializer for the classes in the suites?
 def mkobjectfrommodule(dict, modulename):
-    if isinstance(dict['want'], type) and issubclass(dict['want'], ObjectSpecifier):
+    if (isinstance(dict[b2i(b'want')], type) and
+        issubclass(dict[b2i(b'want')], ObjectSpecifier)):
         # The type has already been converted to Python. Convert back:-(
-        classtype = dict['want']
-        dict['want'] = aetypes.mktype(classtype.want)
-    want = dict['want'].type
+        classtype = dict[b2i(b'want')]
+        dict[b2i(b'want')] = aetypes.mktype(classtype.want)
+    want = dict[b2i(b'want')].type
     module = __import__(modulename)
     codenamemapper = module._classdeclarations
-    classtype = codenamemapper.get(want, None)
+    classtype = codenamemapper.get(b2i(want), None)
     newobj = mkobject(dict)
     if classtype:
         assert issubclass(classtype, ObjectSpecifier)
@@ -356,7 +370,7 @@
     if modulename:
         module = __import__(modulename)
         codenamemapper = module._classdeclarations
-        classtype = codenamemapper.get(typecode, None)
+        classtype = codenamemapper.get(b2i(typecode), None)
         if classtype:
             return classtype
     return aetypes.mktype(typecode)

Modified: python/branches/py3k-buffer/Lib/plat-mac/aetools.py
==============================================================================
--- python/branches/py3k-buffer/Lib/plat-mac/aetools.py	(original)
+++ python/branches/py3k-buffer/Lib/plat-mac/aetools.py	Fri Aug 17 20:48:09 2007
@@ -21,7 +21,6 @@
 """
 
 
-from types import *
 from Carbon import AE
 from Carbon import Evt
 from Carbon import AppleEvents
@@ -167,11 +166,11 @@
         self.target_signature = None
         if signature is None:
             signature = self._signature
-        if type(signature) == AEDescType:
+        if isinstance(signature, AEDescType):
             self.target = signature
         elif hasattr(signature, '__aepack__'):
             self.target = signature.__aepack__()
-        elif type(signature) == StringType and len(signature) == 4:
+        elif isinstance(signature, str) and len(signature) == 4:
             self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
             self.target_signature = signature
         else:

Modified: python/branches/py3k-buffer/Lib/plat-mac/aetypes.py
==============================================================================
--- python/branches/py3k-buffer/Lib/plat-mac/aetypes.py	(original)
+++ python/branches/py3k-buffer/Lib/plat-mac/aetypes.py	Fri Aug 17 20:48:09 2007
@@ -16,6 +16,14 @@
     if isinstance(s, str): return repr(s)
     else: return str(s)
 
+def _four_char_code(four_chars):
+    """Convert a str or bytes object into a 4-byte array.
+
+    four_chars must contain only ASCII characters.
+
+    """
+    return bytes("%-4.4s" % str(four_chars))
+
 class Unknown:
     """An uninterpreted AE object"""
 
@@ -33,13 +41,13 @@
     """An AE enumeration value"""
 
     def __init__(self, enum):
-        self.enum = "%-4.4s" % str(enum)
+        self.enum = _four_char_code(enum)
 
     def __repr__(self):
         return "Enum(%r)" % (self.enum,)
 
     def __str__(self):
-        return self.enum.strip()
+        return self.enum.strip(b' ')
 
     def __aepack__(self):
         return pack(self.enum, typeEnumeration)
@@ -100,7 +108,7 @@
     """An AE 4-char typename object"""
 
     def __init__(self, type):
-        self.type = "%-4.4s" % str(type)
+        self.type = _four_char_code(type)
 
     def __repr__(self):
         return "Type(%r)" % (self.type,)
@@ -123,7 +131,7 @@
     """An AE 4-char keyword object"""
 
     def __init__(self, keyword):
-        self.keyword = "%-4.4s" % str(keyword)
+        self.keyword = _four_char_code(keyword)
 
     def __repr__(self):
         return "Keyword(%r)" % self.keyword
@@ -161,7 +169,7 @@
 
     def __init__(self, obj1, relo, obj2):
         self.obj1 = obj1
-        self.relo = "%-4.4s" % str(relo)
+        self.relo = _four_char_code(relo)
         self.obj2 = obj2
 
     def __repr__(self):
@@ -190,7 +198,7 @@
 
     def __init__(self, abso):
 #       self.obj1 = obj1
-        self.abso = "%-4.4s" % str(abso)
+        self.abso = _four_char_code(abso)
 
     def __repr__(self):
         return "Ordinal(%r)" % (self.abso,)
@@ -214,7 +222,7 @@
     """An AE logical expression object"""
 
     def __init__(self, logc, term):
-        self.logc = "%-4.4s" % str(logc)
+        self.logc = _four_char_code(logc)
         self.term = term
 
     def __repr__(self):
@@ -554,12 +562,12 @@
 class %s(ComponentItem): want = '%s'
 """
 
-exec(template % ("Text", 'text'))
-exec(template % ("Character", 'cha '))
-exec(template % ("Word", 'cwor'))
-exec(template % ("Line", 'clin'))
-exec(template % ("paragraph", 'cpar'))
-exec(template % ("Window", 'cwin'))
-exec(template % ("Document", 'docu'))
-exec(template % ("File", 'file'))
-exec(template % ("InsertionPoint", 'cins'))
+exec(template % ("Text", b'text'))
+exec(template % ("Character", b'cha '))
+exec(template % ("Word", b'cwor'))
+exec(template % ("Line", b'clin'))
+exec(template % ("paragraph", b'cpar'))
+exec(template % ("Window", b'cwin'))
+exec(template % ("Document", b'docu'))
+exec(template % ("File", b'file'))
+exec(template % ("InsertionPoint", b'cins'))

Modified: python/branches/py3k-buffer/Lib/plat-mac/gensuitemodule.py
==============================================================================
--- python/branches/py3k-buffer/Lib/plat-mac/gensuitemodule.py	(original)
+++ python/branches/py3k-buffer/Lib/plat-mac/gensuitemodule.py	Fri Aug 17 20:48:09 2007
@@ -12,7 +12,7 @@
 import string
 import sys
 import types
-import StringIO
+import io
 import keyword
 import macresource
 import aetools
@@ -266,7 +266,7 @@
 
 def decode(data, verbose=None):
     """Decode a resource into a python data structure"""
-    f = StringIO.StringIO(data)
+    f = io.StringIO(data)
     aete = generic(getaete, f)
     aete = simplify(aete)
     processed = f.tell()

Modified: python/branches/py3k-buffer/Lib/plat-mac/plistlib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/plat-mac/plistlib.py	(original)
+++ python/branches/py3k-buffer/Lib/plat-mac/plistlib.py	Fri Aug 17 20:48:09 2007
@@ -12,8 +12,8 @@
 with a file name or a (readable) file object as the only argument. It
 returns the top level object (again, usually a dictionary).
 
-To work with plist data in strings, you can use readPlistFromString()
-and writePlistToString().
+To work with plist data in bytes objects, you can use readPlistFromBytes()
+and writePlistToBytes().
 
 Values can be strings, integers, floats, booleans, tuples, lists,
 dictionaries, Data or datetime.datetime objects. String values (including
@@ -21,7 +21,7 @@
 UTF-8.
 
 The <data> plist type is supported through the Data class. This is a
-thin wrapper around a Python string.
+thin wrapper around a Python bytes object.
 
 Generate Plist example:
 
@@ -36,8 +36,8 @@
             aTrueValue=True,
             aFalseValue=False,
         ),
-        someData = Data("<binary gunk>"),
-        someMoreData = Data("<lots of binary gunk>" * 10),
+        someData = Data(b"<binary gunk>"),
+        someMoreData = Data(b"<lots of binary gunk>" * 10),
         aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
     )
     # unicode keys are possible, but a little awkward to use:
@@ -52,7 +52,7 @@
 
 
 __all__ = [
-    "readPlist", "writePlist", "readPlistFromString", "writePlistToString",
+    "readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes",
     "readPlistFromResource", "writePlistToResource",
     "Plist", "Data", "Dict"
 ]
@@ -60,7 +60,7 @@
 
 import binascii
 import datetime
-from cStringIO import StringIO
+from io import BytesIO
 import re
 
 
@@ -71,7 +71,7 @@
     """
     didOpen = 0
     if isinstance(pathOrFile, str):
-        pathOrFile = open(pathOrFile)
+        pathOrFile = open(pathOrFile, 'rb')
         didOpen = 1
     p = PlistParser()
     rootObject = p.parse(pathOrFile)
@@ -86,7 +86,7 @@
     """
     didOpen = 0
     if isinstance(pathOrFile, str):
-        pathOrFile = open(pathOrFile, "w")
+        pathOrFile = open(pathOrFile, 'wb')
         didOpen = 1
     writer = PlistWriter(pathOrFile)
     writer.writeln("<plist version=\"1.0\">")
@@ -96,16 +96,16 @@
         pathOrFile.close()
 
 
-def readPlistFromString(data):
-    """Read a plist data from a string. Return the root object.
+def readPlistFromBytes(data):
+    """Read a plist data from a bytes object. Return the root object.
     """
-    return readPlist(StringIO(data))
+    return readPlist(BytesIO(data))
 
 
-def writePlistToString(rootObject):
-    """Return 'rootObject' as a plist-formatted string.
+def writePlistToBytes(rootObject):
+    """Return 'rootObject' as a plist-formatted bytes object.
     """
-    f = StringIO()
+    f = BytesIO()
     writePlist(rootObject, f)
     return f.getvalue()
 
@@ -145,7 +145,6 @@
 
 
 class DumbXMLWriter:
-
     def __init__(self, file, indentLevel=0, indent="\t"):
         self.file = file
         self.stack = []
@@ -172,9 +171,12 @@
 
     def writeln(self, line):
         if line:
-            self.file.write(self.indentLevel * self.indent + line + "\n")
-        else:
-            self.file.write("\n")
+            # plist has fixed encoding of utf-8
+            if isinstance(line, str):
+                line = line.encode('utf-8')
+            self.file.write(self.indentLevel * self.indent)
+            self.file.write(line)
+        self.file.write('\n')
 
 
 # Contents should conform to a subset of ISO 8601
@@ -355,13 +357,15 @@
     for i in range(0, len(s), maxbinsize):
         chunk = s[i : i + maxbinsize]
         pieces.append(binascii.b2a_base64(chunk))
-    return "".join(pieces)
+    return b''.join(pieces)
 
 class Data:
 
     """Wrapper for binary data."""
 
     def __init__(self, data):
+        if not isinstance(data, bytes):
+            raise TypeError("data must be as bytes")
         self.data = data
 
     def fromBase64(cls, data):
@@ -426,11 +430,7 @@
             self.stack[-1].append(value)
 
     def getData(self):
-        data = "".join(self.data)
-        try:
-            data = data.encode("ascii")
-        except UnicodeError:
-            pass
+        data = ''.join(self.data)
         self.data = []
         return data
 

Deleted: /python/branches/py3k-buffer/Lib/plat-sunos5/SUNAUDIODEV.py
==============================================================================
--- /python/branches/py3k-buffer/Lib/plat-sunos5/SUNAUDIODEV.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,40 +0,0 @@
-# Symbolic constants for use with sunaudiodev module
-# The names are the same as in audioio.h with the leading AUDIO_
-# removed.
-
-# Not all values are supported on all releases of SunOS.
-
-# Encoding types, for fields i_encoding and o_encoding
-
-ENCODING_NONE = 0                       # no encoding assigned
-ENCODING_ULAW = 1                       # u-law encoding
-ENCODING_ALAW = 2                       # A-law encoding
-ENCODING_LINEAR = 3                     # Linear PCM encoding
-
-# Gain ranges for i_gain, o_gain and monitor_gain
-
-MIN_GAIN = 0                            # minimum gain value
-MAX_GAIN = 255                          # maximum gain value
-
-# Balance values for i_balance and o_balance
-
-LEFT_BALANCE = 0                        # left channel only
-MID_BALANCE = 32                        # equal left/right channel
-RIGHT_BALANCE = 64                      # right channel only
-BALANCE_SHIFT = 3
-
-# Port names for i_port and o_port
-
-PORT_A = 1
-PORT_B = 2
-PORT_C = 3
-PORT_D = 4
-
-SPEAKER = 0x01                          # output to built-in speaker
-HEADPHONE = 0x02                        # output to headphone jack
-LINE_OUT = 0x04                         # output to line out
-
-MICROPHONE = 0x01                       # input from microphone
-LINE_IN = 0x02                          # input from line in
-CD = 0x04                               # input from on-board CD inputs
-INTERNAL_CD_IN = CD                     # input from internal CDROM

Modified: python/branches/py3k-buffer/Lib/pprint.py
==============================================================================
--- python/branches/py3k-buffer/Lib/pprint.py	(original)
+++ python/branches/py3k-buffer/Lib/pprint.py	Fri Aug 17 20:48:09 2007
@@ -36,7 +36,7 @@
 
 import sys as _sys
 
-from StringIO import StringIO as _StringIO
+from io import StringIO as _StringIO
 
 __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
            "PrettyPrinter"]

Modified: python/branches/py3k-buffer/Lib/pydoc.py
==============================================================================
--- python/branches/py3k-buffer/Lib/pydoc.py	(original)
+++ python/branches/py3k-buffer/Lib/pydoc.py	Fri Aug 17 20:48:09 2007
@@ -1804,8 +1804,8 @@
         document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
         file.close()
 
-        import htmllib, formatter, StringIO
-        buffer = StringIO.StringIO()
+        import htmllib, formatter, io
+        buffer = io.StringIO()
         parser = htmllib.HTMLParser(
             formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
         parser.start_table = parser.do_p
@@ -1816,7 +1816,7 @@
         buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n  ')
         pager('  ' + buffer.strip() + '\n')
         if xrefs:
-            buffer = StringIO.StringIO()
+            buffer = io.StringIO()
             formatter.DumbWriter(buffer).send_flowing_data(
                 'Related help topics: ' + ', '.join(xrefs.split()) + '\n')
             self.output.write('\n%s\n' % buffer.getvalue())
@@ -1900,9 +1900,9 @@
             else:
                 loader = importer.find_module(modname)
                 if hasattr(loader,'get_source'):
-                    import StringIO
+                    import io
                     desc = source_synopsis(
-                        StringIO.StringIO(loader.get_source(modname))
+                        io.StringIO(loader.get_source(modname))
                     ) or ''
                     if hasattr(loader,'get_filename'):
                         path = loader.get_filename(modname)

Modified: python/branches/py3k-buffer/Lib/quopri.py
==============================================================================
--- python/branches/py3k-buffer/Lib/quopri.py	(original)
+++ python/branches/py3k-buffer/Lib/quopri.py	Fri Aug 17 20:48:09 2007
@@ -6,10 +6,10 @@
 
 __all__ = ["encode", "decode", "encodestring", "decodestring"]
 
-ESCAPE = '='
+ESCAPE = b'='
 MAXLINESIZE = 76
-HEX = '0123456789ABCDEF'
-EMPTYSTRING = ''
+HEX = b'0123456789ABCDEF'
+EMPTYSTRING = b''
 
 try:
     from binascii import a2b_qp, b2a_qp
@@ -19,23 +19,25 @@
 
 
 def needsquoting(c, quotetabs, header):
-    """Decide whether a particular character needs to be quoted.
+    """Decide whether a particular byte ordinal needs to be quoted.
 
     The 'quotetabs' flag indicates whether embedded tabs and spaces should be
     quoted.  Note that line-ending tabs and spaces are always encoded, as per
     RFC 1521.
     """
-    if c in ' \t':
+    assert isinstance(c, bytes)
+    if c in b' \t':
         return quotetabs
     # if header, we have to escape _ because _ is used to escape space
-    if c == '_':
+    if c == b'_':
         return header
-    return c == ESCAPE or not (' ' <= c <= '~')
+    return c == ESCAPE or not (b' ' <= c <= b'~')
 
 def quote(c):
     """Quote a single character."""
-    i = ord(c)
-    return ESCAPE + HEX[i//16] + HEX[i%16]
+    assert isinstance(c, bytes) and len(c)==1
+    c = ord(c)
+    return ESCAPE + bytes((HEX[c//16], HEX[c%16]))
 
 
 
@@ -56,12 +58,12 @@
         output.write(odata)
         return
 
-    def write(s, output=output, lineEnd='\n'):
+    def write(s, output=output, lineEnd=b'\n'):
         # RFC 1521 requires that the line ending in a space or tab must have
         # that trailing character encoded.
-        if s and s[-1:] in ' \t':
-            output.write(s[:-1] + quote(s[-1]) + lineEnd)
-        elif s == '.':
+        if s and s[-1:] in b' \t':
+            output.write(s[:-1] + quote(s[-1:]) + lineEnd)
+        elif s == b'.':
             output.write(quote(s) + lineEnd)
         else:
             output.write(s + lineEnd)
@@ -73,16 +75,17 @@
             break
         outline = []
         # Strip off any readline induced trailing newline
-        stripped = ''
-        if line[-1:] == '\n':
+        stripped = b''
+        if line[-1:] == b'\n':
             line = line[:-1]
-            stripped = '\n'
+            stripped = b'\n'
         # Calculate the un-length-limited encoded line
         for c in line:
+            c = bytes((c,))
             if needsquoting(c, quotetabs, header):
                 c = quote(c)
-            if header and c == ' ':
-                outline.append('_')
+            if header and c == b' ':
+                outline.append(b'_')
             else:
                 outline.append(c)
         # First, write out the previous line
@@ -94,7 +97,7 @@
         while len(thisline) > MAXLINESIZE:
             # Don't forget to include the soft line break `=' sign in the
             # length calculation!
-            write(thisline[:MAXLINESIZE-1], lineEnd='=\n')
+            write(thisline[:MAXLINESIZE-1], lineEnd=b'=\n')
             thisline = thisline[MAXLINESIZE-1:]
         # Write out the current line
         prevline = thisline
@@ -105,9 +108,9 @@
 def encodestring(s, quotetabs = 0, header = 0):
     if b2a_qp is not None:
         return b2a_qp(s, quotetabs = quotetabs, header = header)
-    from io import StringIO
-    infp = StringIO(s)
-    outfp = StringIO()
+    from io import BytesIO
+    infp = BytesIO(s)
+    outfp = BytesIO()
     encode(infp, outfp, quotetabs, header)
     return outfp.getvalue()
 
@@ -124,44 +127,44 @@
         output.write(odata)
         return
 
-    new = ''
+    new = b''
     while 1:
         line = input.readline()
         if not line: break
         i, n = 0, len(line)
-        if n > 0 and line[n-1] == '\n':
+        if n > 0 and line[n-1:n] == b'\n':
             partial = 0; n = n-1
             # Strip trailing whitespace
-            while n > 0 and line[n-1] in " \t\r":
+            while n > 0 and line[n-1:n] in b" \t\r":
                 n = n-1
         else:
             partial = 1
         while i < n:
-            c = line[i]
-            if c == '_' and header:
-                new = new + ' '; i = i+1
+            c = line[i:i+1]
+            if c == b'_' and header:
+                new = new + b' '; i = i+1
             elif c != ESCAPE:
                 new = new + c; i = i+1
             elif i+1 == n and not partial:
                 partial = 1; break
             elif i+1 < n and line[i+1] == ESCAPE:
                 new = new + ESCAPE; i = i+2
-            elif i+2 < n and ishex(line[i+1]) and ishex(line[i+2]):
-                new = new + chr(unhex(line[i+1:i+3])); i = i+3
+            elif i+2 < n and ishex(line[i+1:i+2]) and ishex(line[i+2:i+3]):
+                new = new + bytes((unhex(line[i+1:i+3]),)); i = i+3
             else: # Bad escape sequence -- leave it in
                 new = new + c; i = i+1
         if not partial:
-            output.write(new + '\n')
-            new = ''
+            output.write(new + b'\n')
+            new = b''
     if new:
         output.write(new)
 
 def decodestring(s, header = 0):
     if a2b_qp is not None:
         return a2b_qp(s, header = header)
-    from io import StringIO
-    infp = StringIO(s)
-    outfp = StringIO()
+    from io import BytesIO
+    infp = BytesIO(s)
+    outfp = BytesIO()
     decode(infp, outfp, header = header)
     return outfp.getvalue()
 
@@ -169,21 +172,23 @@
 
 # Other helper functions
 def ishex(c):
-    """Return true if the character 'c' is a hexadecimal digit."""
-    return '0' <= c <= '9' or 'a' <= c <= 'f' or 'A' <= c <= 'F'
+    """Return true if the byte ordinal 'c' is a hexadecimal digit in ASCII."""
+    assert isinstance(c, bytes)
+    return b'0' <= c <= b'9' or b'a' <= c <= b'f' or b'A' <= c <= b'F'
 
 def unhex(s):
     """Get the integer value of a hexadecimal number."""
     bits = 0
     for c in s:
-        if '0' <= c <= '9':
+        c = bytes((c,))
+        if b'0' <= c <= b'9':
             i = ord('0')
-        elif 'a' <= c <= 'f':
+        elif b'a' <= c <= b'f':
             i = ord('a')-10
-        elif 'A' <= c <= 'F':
-            i = ord('A')-10
+        elif b'A' <= c <= b'F':
+            i = ord(b'A')-10
         else:
-            break
+            assert False, "non-hex digit "+repr(c)
         bits = bits*16 + (ord(c) - i)
     return bits
 
@@ -214,18 +219,18 @@
     sts = 0
     for file in args:
         if file == '-':
-            fp = sys.stdin
+            fp = sys.stdin.buffer
         else:
             try:
-                fp = open(file)
+                fp = open(file, "rb")
             except IOError as msg:
                 sys.stderr.write("%s: can't open (%s)\n" % (file, msg))
                 sts = 1
                 continue
         if deco:
-            decode(fp, sys.stdout)
+            decode(fp, sys.stdout.buffer)
         else:
-            encode(fp, sys.stdout, tabs)
+            encode(fp, sys.stdout.buffer, tabs)
         if fp is not sys.stdin:
             fp.close()
     if sts:

Modified: python/branches/py3k-buffer/Lib/runpy.py
==============================================================================
--- python/branches/py3k-buffer/Lib/runpy.py	(original)
+++ python/branches/py3k-buffer/Lib/runpy.py	Fri Aug 17 20:48:09 2007
@@ -33,36 +33,21 @@
     return run_globals
 
 def _run_module_code(code, init_globals=None,
-                    mod_name=None, mod_fname=None,
-                    mod_loader=None, alter_sys=False):
+                     mod_name=None, mod_fname=None,
+                     mod_loader=None, alter_sys=False):
     """Helper for run_module"""
     # Set up the top level namespace dictionary
     if alter_sys:
-        # Modify sys.argv[0] and sys.module[mod_name]
-        temp_module = imp.new_module(mod_name)
-        mod_globals = temp_module.__dict__
-        saved_argv0 = sys.argv[0]
-        restore_module = mod_name in sys.modules
-        if restore_module:
-            saved_module = sys.modules[mod_name]
+        # Modify sys.argv[0] and sys.modules[mod_name]
         sys.argv[0] = mod_fname
-        sys.modules[mod_name] = temp_module
-        try:
-            _run_code(code, mod_globals, init_globals,
-                      mod_name, mod_fname, mod_loader)
-        finally:
-            sys.argv[0] = saved_argv0
-        if restore_module:
-            sys.modules[mod_name] = saved_module
-        else:
-            del sys.modules[mod_name]
-        # Copy the globals of the temporary module, as they
-        # may be cleared when the temporary module goes away
-        return mod_globals.copy()
+        module = imp.new_module(mod_name)
+        sys.modules[mod_name] = module
+        mod_globals = module.__dict__
     else:
         # Leave the sys module alone
-        return _run_code(code, {}, init_globals,
-                         mod_name, mod_fname, mod_loader)
+        mod_globals = {}
+    return _run_code(code, mod_globals, init_globals,
+                     mod_name, mod_fname, mod_loader)
 
 
 # This helper is needed due to a missing component in the PEP 302
@@ -84,10 +69,13 @@
     """
     loader = get_loader(mod_name)
     if loader is None:
-        raise ImportError("No module named " + mod_name)
+        raise ImportError("No module named %s" % mod_name)
+    if loader.is_package(mod_name):
+        raise ImportError(("%s is a package and cannot " +
+                          "be directly executed") % mod_name)
     code = loader.get_code(mod_name)
     if code is None:
-        raise ImportError("No code object available for " + mod_name)
+        raise ImportError("No code object available for %s" % mod_name)
     filename = _get_filename(loader, mod_name)
     if run_name is None:
         run_name = mod_name

Modified: python/branches/py3k-buffer/Lib/sgmllib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/sgmllib.py	(original)
+++ python/branches/py3k-buffer/Lib/sgmllib.py	Fri Aug 17 20:48:09 2007
@@ -428,7 +428,7 @@
         if replacement is None:
             self.unknown_entityref(name)
         else:
-            self.handle_data(self.convert_entityref(name))
+            self.handle_data(replacement)
 
     # Example -- handle data, should be overridden
     def handle_data(self, data):

Modified: python/branches/py3k-buffer/Lib/shelve.py
==============================================================================
--- python/branches/py3k-buffer/Lib/shelve.py	(original)
+++ python/branches/py3k-buffer/Lib/shelve.py	Fri Aug 17 20:48:09 2007
@@ -57,7 +57,7 @@
 """
 
 from pickle import Pickler, Unpickler
-from io import StringIO
+from io import BytesIO
 
 import UserDict
 import warnings
@@ -97,7 +97,7 @@
         try:
             value = self.cache[key]
         except KeyError:
-            f = StringIO(self.dict[key])
+            f = BytesIO(self.dict[key])
             value = Unpickler(f).load()
             if self.writeback:
                 self.cache[key] = value
@@ -106,7 +106,7 @@
     def __setitem__(self, key, value):
         if self.writeback:
             self.cache[key] = value
-        f = StringIO()
+        f = BytesIO()
         p = Pickler(f, self._protocol)
         p.dump(value)
         self.dict[key] = f.getvalue()
@@ -161,27 +161,27 @@
 
     def set_location(self, key):
         (key, value) = self.dict.set_location(key)
-        f = StringIO(value)
+        f = BytesIO(value)
         return (key, Unpickler(f).load())
 
     def next(self):
         (key, value) = next(self.dict)
-        f = StringIO(value)
+        f = BytesIO(value)
         return (key, Unpickler(f).load())
 
     def previous(self):
         (key, value) = self.dict.previous()
-        f = StringIO(value)
+        f = BytesIO(value)
         return (key, Unpickler(f).load())
 
     def first(self):
         (key, value) = self.dict.first()
-        f = StringIO(value)
+        f = BytesIO(value)
         return (key, Unpickler(f).load())
 
     def last(self):
         (key, value) = self.dict.last()
-        f = StringIO(value)
+        f = BytesIO(value)
         return (key, Unpickler(f).load())
 
 

Modified: python/branches/py3k-buffer/Lib/smtpd.py
==============================================================================
--- python/branches/py3k-buffer/Lib/smtpd.py	(original)
+++ python/branches/py3k-buffer/Lib/smtpd.py	Fri Aug 17 20:48:09 2007
@@ -132,7 +132,7 @@
 
     # Implementation of base class abstract method
     def collect_incoming_data(self, data):
-        self.__line.append(data)
+        self.__line.append(str(data, "utf8"))
 
     # Implementation of base class abstract method
     def found_terminator(self):

Modified: python/branches/py3k-buffer/Lib/smtplib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/smtplib.py	(original)
+++ python/branches/py3k-buffer/Lib/smtplib.py	Fri Aug 17 20:48:09 2007
@@ -344,11 +344,11 @@
             self.file = self.sock.makefile('rb')
         while 1:
             line = self.file.readline()
-            if line == '':
+            if not line:
                 self.close()
                 raise SMTPServerDisconnected("Connection unexpectedly closed")
             if self.debuglevel > 0: print('reply:', repr(line), file=stderr)
-            resp.append(line[4:].strip(b' \t\n'))
+            resp.append(line[4:].strip(b' \t\r\n'))
             code=line[:3]
             # Check that the error code is syntactically correct.
             # Don't attempt to read a continuation line if it is broken.
@@ -358,7 +358,7 @@
                 errcode = -1
                 break
             # Check if multiline response.
-            if line[3:4]!="-":
+            if line[3:4] != b"-":
                 break
 
         errmsg = b"\n".join(resp)

Modified: python/branches/py3k-buffer/Lib/socket.py
==============================================================================
--- python/branches/py3k-buffer/Lib/socket.py	(original)
+++ python/branches/py3k-buffer/Lib/socket.py	Fri Aug 17 20:48:09 2007
@@ -89,22 +89,67 @@
 
 # True if os.dup() can duplicate socket descriptors.
 # (On Windows at least, os.dup only works on files)
-_can_dup_socket = hasattr(_socket, "dup")
+_can_dup_socket = hasattr(_socket.socket, "dup")
 
 if _can_dup_socket:
     def fromfd(fd, family=AF_INET, type=SOCK_STREAM, proto=0):
         nfd = os.dup(fd)
         return socket(family, type, proto, fileno=nfd)
 
+class SocketCloser:
+
+    """Helper to manage socket close() logic for makefile().
+
+    The OS socket should not be closed until the socket and all
+    of its makefile-children are closed.  If the refcount is zero
+    when socket.close() is called, this is easy: Just close the
+    socket.  If the refcount is non-zero when socket.close() is
+    called, then the real close should not occur until the last
+    makefile-child is closed.
+    """
+
+    def __init__(self, sock):
+        self._sock = sock
+        self._makefile_refs = 0
+        # Test whether the socket is open.
+        try:
+            sock.fileno()
+            self._socket_open = True
+        except error:
+            self._socket_open = False
+
+    def socket_close(self):
+        self._socket_open = False
+        self.close()
+
+    def makefile_open(self):
+        self._makefile_refs += 1
+
+    def makefile_close(self):
+        self._makefile_refs -= 1
+        self.close()
+
+    def close(self):
+        if not (self._socket_open or self._makefile_refs):
+            self._sock._real_close()
+
 
 class socket(_socket.socket):
 
     """A subclass of _socket.socket adding the makefile() method."""
 
-    __slots__ = ["__weakref__"]
+    __slots__ = ["__weakref__", "_closer"]
     if not _can_dup_socket:
         __slots__.append("_base")
 
+    def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
+        if fileno is None:
+            _socket.socket.__init__(self, family, type, proto)
+        else:
+            _socket.socket.__init__(self, family, type, proto, fileno)
+        # Defer creating a SocketCloser until makefile() is actually called.
+        self._closer = None
+
     def __repr__(self):
         """Wrap __repr__() to reveal the real class name."""
         s = _socket.socket.__repr__(self)
@@ -128,14 +173,6 @@
             conn.close()
         return wrapper, addr
 
-    if not _can_dup_socket:
-        def close(self):
-            """Wrap close() to close the _base as well."""
-            _socket.socket.close(self)
-            base = getattr(self, "_base", None)
-            if base is not None:
-                base.close()
-
     def makefile(self, mode="r", buffering=None, *,
                  encoding=None, newline=None):
         """Return an I/O stream connected to the socket.
@@ -156,7 +193,9 @@
             rawmode += "r"
         if writing:
             rawmode += "w"
-        raw = io.SocketIO(self, rawmode)
+        if self._closer is None:
+            self._closer = SocketCloser(self)
+        raw = SocketIO(self, rawmode, self._closer)
         if buffering is None:
             buffering = -1
         if buffering < 0:
@@ -183,6 +222,65 @@
         text.mode = mode
         return text
 
+    def close(self):
+        if self._closer is None:
+            self._real_close()
+        else:
+            self._closer.socket_close()
+
+    # _real_close calls close on the _socket.socket base class.
+
+    if not _can_dup_socket:
+        def _real_close(self):
+            _socket.socket.close(self)
+            base = getattr(self, "_base", None)
+            if base is not None:
+                self._base = None
+                base.close()
+    else:
+        def _real_close(self):
+            _socket.socket.close(self)
+
+
+class SocketIO(io.RawIOBase):
+
+    """Raw I/O implementation for stream sockets.
+
+    This class supports the makefile() method on sockets.  It provides
+    the raw I/O interface on top of a socket object.
+    """
+
+    # XXX More docs
+
+    def __init__(self, sock, mode, closer):
+        assert mode in ("r", "w", "rw")
+        io.RawIOBase.__init__(self)
+        self._sock = sock
+        self._mode = mode
+        self._closer = closer
+        closer.makefile_open()
+
+    def readinto(self, b):
+        return self._sock.recv_into(b)
+
+    def write(self, b):
+        return self._sock.send(b)
+
+    def readable(self):
+        return "r" in self._mode
+
+    def writable(self):
+        return "w" in self._mode
+
+    def fileno(self):
+        return self._sock.fileno()
+
+    def close(self):
+        if self.closed:
+            return
+        self._closer.makefile_close()
+        io.RawIOBase.close(self)
+
 
 def getfqdn(name=''):
     """Get fully qualified domain name from name.

Modified: python/branches/py3k-buffer/Lib/tarfile.py
==============================================================================
--- python/branches/py3k-buffer/Lib/tarfile.py	(original)
+++ python/branches/py3k-buffer/Lib/tarfile.py	Fri Aug 17 20:48:09 2007
@@ -72,33 +72,33 @@
 #---------------------------------------------------------
 # tar constants
 #---------------------------------------------------------
-NUL = "\0"                      # the null character
+NUL = b"\0"                     # the null character
 BLOCKSIZE = 512                 # length of processing blocks
 RECORDSIZE = BLOCKSIZE * 20     # length of records
-GNU_MAGIC = "ustar  \0"         # magic gnu tar string
-POSIX_MAGIC = "ustar\x0000"     # magic posix tar string
+GNU_MAGIC = b"ustar  \0"        # magic gnu tar string
+POSIX_MAGIC = b"ustar\x0000"    # magic posix tar string
 
 LENGTH_NAME = 100               # maximum length of a filename
 LENGTH_LINK = 100               # maximum length of a linkname
 LENGTH_PREFIX = 155             # maximum length of the prefix field
 
-REGTYPE = "0"                   # regular file
-AREGTYPE = "\0"                 # regular file
-LNKTYPE = "1"                   # link (inside tarfile)
-SYMTYPE = "2"                   # symbolic link
-CHRTYPE = "3"                   # character special device
-BLKTYPE = "4"                   # block special device
-DIRTYPE = "5"                   # directory
-FIFOTYPE = "6"                  # fifo special device
-CONTTYPE = "7"                  # contiguous file
-
-GNUTYPE_LONGNAME = "L"          # GNU tar longname
-GNUTYPE_LONGLINK = "K"          # GNU tar longlink
-GNUTYPE_SPARSE = "S"            # GNU tar sparse file
-
-XHDTYPE = "x"                   # POSIX.1-2001 extended header
-XGLTYPE = "g"                   # POSIX.1-2001 global header
-SOLARIS_XHDTYPE = "X"           # Solaris extended header
+REGTYPE = b"0"                  # regular file
+AREGTYPE = b"\0"                # regular file
+LNKTYPE = b"1"                  # link (inside tarfile)
+SYMTYPE = b"2"                  # symbolic link
+CHRTYPE = b"3"                  # character special device
+BLKTYPE = b"4"                  # block special device
+DIRTYPE = b"5"                  # directory
+FIFOTYPE = b"6"                 # fifo special device
+CONTTYPE = b"7"                 # contiguous file
+
+GNUTYPE_LONGNAME = b"L"         # GNU tar longname
+GNUTYPE_LONGLINK = b"K"         # GNU tar longlink
+GNUTYPE_SPARSE = b"S"           # GNU tar sparse file
+
+XHDTYPE = b"x"                  # POSIX.1-2001 extended header
+XGLTYPE = b"g"                  # POSIX.1-2001 global header
+SOLARIS_XHDTYPE = b"X"          # Solaris extended header
 
 USTAR_FORMAT = 0                # POSIX.1-1988 (ustar) format
 GNU_FORMAT = 1                  # GNU tar format
@@ -173,19 +173,19 @@
 # Some useful functions
 #---------------------------------------------------------
 
-def stn(s, length):
-    """Convert a python string to a null-terminated string buffer.
+def stn(s, length, encoding, errors):
+    """Convert a string to a null-terminated bytes object.
     """
+    s = s.encode(encoding, errors)
     return s[:length] + (length - len(s)) * NUL
 
-def nts(s):
-    """Convert a null-terminated string field to a python string.
+def nts(s, encoding, errors):
+    """Convert a null-terminated bytes object to a string.
     """
-    # Use the string up to the first null char.
-    p = s.find("\0")
-    if p == -1:
-        return s
-    return s[:p]
+    p = s.find(b"\0")
+    if p != -1:
+        s = s[:p]
+    return s.decode(encoding, errors)
 
 def nti(s):
     """Convert a number field to a python number.
@@ -194,7 +194,7 @@
     # itn() below.
     if s[0] != chr(0o200):
         try:
-            n = int(nts(s) or "0", 8)
+            n = int(nts(s, "ascii", "strict") or "0", 8)
         except ValueError:
             raise HeaderError("invalid header")
     else:
@@ -214,7 +214,7 @@
     # encoding, the following digits-1 bytes are a big-endian
     # representation. This allows values up to (256**(digits-1))-1.
     if 0 <= n < 8 ** (digits - 1):
-        s = "%0*o" % (digits - 1, n) + NUL
+        s = bytes("%0*o" % (digits - 1, n)) + NUL
     else:
         if format != GNU_FORMAT or n >= 256 ** (digits - 1):
             raise ValueError("overflow in number field")
@@ -224,33 +224,13 @@
             # this could raise OverflowError.
             n = struct.unpack("L", struct.pack("l", n))[0]
 
-        s = ""
+        s = b""
         for i in range(digits - 1):
-            s = chr(n & 0o377) + s
+            s.insert(0, n & 0o377)
             n >>= 8
-        s = chr(0o200) + s
+        s.insert(0, 0o200)
     return s
 
-def uts(s, encoding, errors):
-    """Convert a unicode object to a string.
-    """
-    if errors == "utf-8":
-        # An extra error handler similar to the -o invalid=UTF-8 option
-        # in POSIX.1-2001. Replace untranslatable characters with their
-        # UTF-8 representation.
-        try:
-            return s.encode(encoding, "strict")
-        except UnicodeEncodeError:
-            x = []
-            for c in s:
-                try:
-                    x.append(c.encode(encoding, "strict"))
-                except UnicodeEncodeError:
-                    x.append(c.encode("utf8"))
-            return "".join(x)
-    else:
-        return s.encode(encoding, errors)
-
 def calc_chksums(buf):
     """Calculate the checksum for a member's header by summing up all
        characters except for the chksum field which is treated as if
@@ -412,7 +392,7 @@
         self.comptype = comptype
         self.fileobj  = fileobj
         self.bufsize  = bufsize
-        self.buf      = ""
+        self.buf      = b""
         self.pos      = 0
         self.closed   = False
 
@@ -434,7 +414,7 @@
             except ImportError:
                 raise CompressionError("bz2 module is not available")
             if mode == "r":
-                self.dbuf = ""
+                self.dbuf = b""
                 self.cmp = bz2.BZ2Decompressor()
             else:
                 self.cmp = bz2.BZ2Compressor()
@@ -451,10 +431,11 @@
                                             self.zlib.DEF_MEM_LEVEL,
                                             0)
         timestamp = struct.pack("<L", int(time.time()))
-        self.__write("\037\213\010\010%s\002\377" % timestamp)
+        self.__write(b"\037\213\010\010" + timestamp + b"\002\377")
         if self.name.endswith(".gz"):
             self.name = self.name[:-3]
-        self.__write(self.name + NUL)
+        # RFC1952 says we must use ISO-8859-1 for the FNAME field.
+        self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
 
     def write(self, s):
         """Write string s to the stream.
@@ -487,7 +468,7 @@
 
         if self.mode == "w" and self.buf:
             self.fileobj.write(self.buf)
-            self.buf = ""
+            self.buf = b""
             if self.comptype == "gz":
                 # The native zlib crc is an unsigned 32-bit integer, but
                 # the Python wrapper implicitly casts that to a signed C
@@ -507,12 +488,12 @@
         """Initialize for reading a gzip compressed fileobj.
         """
         self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
-        self.dbuf = ""
+        self.dbuf = b""
 
         # taken from gzip.GzipFile with some alterations
-        if self.__read(2) != "\037\213":
+        if self.__read(2) != b"\037\213":
             raise ReadError("not a gzip file")
-        if self.__read(1) != "\010":
+        if self.__read(1) != b"\010":
             raise CompressionError("unsupported compression method")
 
         flag = ord(self.__read(1))
@@ -577,7 +558,6 @@
             return self.__read(size)
 
         c = len(self.dbuf)
-        t = [self.dbuf]
         while c < size:
             buf = self.__read(self.bufsize)
             if not buf:
@@ -586,27 +566,26 @@
                 buf = self.cmp.decompress(buf)
             except IOError:
                 raise ReadError("invalid compressed data")
-            t.append(buf)
+            self.dbuf += buf
             c += len(buf)
-        t = "".join(t)
-        self.dbuf = t[size:]
-        return t[:size]
+        buf = self.dbuf[:size]
+        self.dbuf = self.dbuf[size:]
+        return buf
 
     def __read(self, size):
         """Return size bytes from stream. If internal buffer is empty,
            read another block from the stream.
         """
         c = len(self.buf)
-        t = [self.buf]
         while c < size:
             buf = self.fileobj.read(self.bufsize)
             if not buf:
                 break
-            t.append(buf)
+            self.buf += buf
             c += len(buf)
-        t = "".join(t)
-        self.buf = t[size:]
-        return t[:size]
+        buf = self.buf[:size]
+        self.buf = self.buf[size:]
+        return buf
 # class _Stream
 
 class _StreamProxy(object):
@@ -623,7 +602,7 @@
         return self.buf
 
     def getcomptype(self):
-        if self.buf.startswith("\037\213\010"):
+        if self.buf.startswith(b"\037\213\010"):
             return "gz"
         if self.buf.startswith("BZh91"):
             return "bz2"
@@ -655,22 +634,20 @@
         if self.mode == "r":
             self.bz2obj = bz2.BZ2Decompressor()
             self.fileobj.seek(0)
-            self.buf = ""
+            self.buf = b""
         else:
             self.bz2obj = bz2.BZ2Compressor()
 
     def read(self, size):
-        b = [self.buf]
         x = len(self.buf)
         while x < size:
             try:
                 raw = self.fileobj.read(self.blocksize)
                 data = self.bz2obj.decompress(raw)
-                b.append(data)
+                self.buf += data
             except EOFError:
                 break
             x += len(data)
-        self.buf = "".join(b)
 
         buf = self.buf[:size]
         self.buf = self.buf[size:]
@@ -713,6 +690,12 @@
         self.sparse = sparse
         self.position = 0
 
+    def seekable(self):
+        if not hasattr(self.fileobj, "seekable"):
+            # XXX gzip.GzipFile and bz2.BZ2File
+            return True
+        return self.fileobj.seekable()
+
     def tell(self):
         """Return the current file position.
         """
@@ -746,14 +729,14 @@
     def readsparse(self, size):
         """Read operation for sparse files.
         """
-        data = []
+        data = b""
         while size > 0:
             buf = self.readsparsesection(size)
             if not buf:
                 break
             size -= len(buf)
-            data.append(buf)
-        return "".join(data)
+            data += buf
+        return data
 
     def readsparsesection(self, size):
         """Read a single section of a sparse file.
@@ -761,7 +744,7 @@
         section = self.sparse.find(self.position)
 
         if section is None:
-            return ""
+            return b""
 
         size = min(size, section.offset + section.size - self.position)
 
@@ -793,7 +776,16 @@
         self.size = tarinfo.size
 
         self.position = 0
-        self.buffer = ""
+        self.buffer = b""
+
+    def readable(self):
+        return True
+
+    def writable(self):
+        return False
+
+    def seekable(self):
+        return self.fileobj.seekable()
 
     def read(self, size=None):
         """Read at most size bytes from the file. If size is not
@@ -802,11 +794,11 @@
         if self.closed:
             raise ValueError("I/O operation on closed file")
 
-        buf = ""
+        buf = b""
         if self.buffer:
             if size is None:
                 buf = self.buffer
-                self.buffer = ""
+                self.buffer = b""
             else:
                 buf = self.buffer[:size]
                 self.buffer = self.buffer[size:]
@@ -819,6 +811,9 @@
         self.position += len(buf)
         return buf
 
+    # XXX TextIOWrapper uses the read1() method.
+    read1 = read
+
     def readline(self, size=-1):
         """Read one entire line from the file. If size is present
            and non-negative, return a string with at most that
@@ -827,16 +822,14 @@
         if self.closed:
             raise ValueError("I/O operation on closed file")
 
-        if "\n" in self.buffer:
-            pos = self.buffer.find("\n") + 1
-        else:
-            buffers = [self.buffer]
+        pos = self.buffer.find(b"\n") + 1
+        if pos == 0:
+            # no newline found.
             while True:
                 buf = self.fileobj.read(self.blocksize)
-                buffers.append(buf)
-                if not buf or "\n" in buf:
-                    self.buffer = "".join(buffers)
-                    pos = self.buffer.find("\n") + 1
+                self.buffer += buf
+                if not buf or b"\n" in buf:
+                    pos = self.buffer.find(b"\n") + 1
                     if pos == 0:
                         # no newline found.
                         pos = len(self.buffer)
@@ -886,7 +879,7 @@
         else:
             raise ValueError("Invalid argument")
 
-        self.buffer = ""
+        self.buffer = b""
         self.fileobj.seek(self.position)
 
     def close(self):
@@ -955,7 +948,7 @@
     def __repr__(self):
         return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
 
-    def get_info(self, encoding, errors):
+    def get_info(self):
         """Return the TarInfo's attributes as a dictionary.
         """
         info = {
@@ -977,27 +970,23 @@
         if info["type"] == DIRTYPE and not info["name"].endswith("/"):
             info["name"] += "/"
 
-        for key in ("name", "linkname", "uname", "gname"):
-            if isinstance(info[key], str):
-                info[key] = info[key].encode(encoding, errors)
-
         return info
 
     def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="strict"):
         """Return a tar header as a string of 512 byte blocks.
         """
-        info = self.get_info(encoding, errors)
+        info = self.get_info()
 
         if format == USTAR_FORMAT:
-            return self.create_ustar_header(info)
+            return self.create_ustar_header(info, encoding, errors)
         elif format == GNU_FORMAT:
-            return self.create_gnu_header(info)
+            return self.create_gnu_header(info, encoding, errors)
         elif format == PAX_FORMAT:
             return self.create_pax_header(info, encoding, errors)
         else:
             raise ValueError("invalid format")
 
-    def create_ustar_header(self, info):
+    def create_ustar_header(self, info, encoding, errors):
         """Return the object as a ustar header block.
         """
         info["magic"] = POSIX_MAGIC
@@ -1008,21 +997,21 @@
         if len(info["name"]) > LENGTH_NAME:
             info["prefix"], info["name"] = self._posix_split_name(info["name"])
 
-        return self._create_header(info, USTAR_FORMAT)
+        return self._create_header(info, USTAR_FORMAT, encoding, errors)
 
-    def create_gnu_header(self, info):
+    def create_gnu_header(self, info, encoding, errors):
         """Return the object as a GNU header block sequence.
         """
         info["magic"] = GNU_MAGIC
 
-        buf = ""
+        buf = b""
         if len(info["linkname"]) > LENGTH_LINK:
-            buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK)
+            buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
 
         if len(info["name"]) > LENGTH_NAME:
-            buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME)
+            buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
 
-        return buf + self._create_header(info, GNU_FORMAT)
+        return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
 
     def create_pax_header(self, info, encoding, errors):
         """Return the object as a ustar header block. If it cannot be
@@ -1042,17 +1031,15 @@
                 # The pax header has priority.
                 continue
 
-            val = info[name].decode(encoding, errors)
-
             # Try to encode the string as ASCII.
             try:
-                val.encode("ascii")
+                info[name].encode("ascii", "strict")
             except UnicodeEncodeError:
-                pax_headers[hname] = val
+                pax_headers[hname] = info[name]
                 continue
 
             if len(info[name]) > length:
-                pax_headers[hname] = val
+                pax_headers[hname] = info[name]
 
         # Test number fields for values that exceed the field limit or values
         # that like to be stored as float.
@@ -1069,17 +1056,17 @@
 
         # Create a pax extended header if necessary.
         if pax_headers:
-            buf = self._create_pax_generic_header(pax_headers)
+            buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding, errors)
         else:
-            buf = ""
+            buf = b""
 
-        return buf + self._create_header(info, USTAR_FORMAT)
+        return buf + self._create_header(info, USTAR_FORMAT, encoding, errors)
 
     @classmethod
-    def create_pax_global_header(cls, pax_headers):
+    def create_pax_global_header(cls, pax_headers, encoding, errors):
         """Return the object as a pax global header block sequence.
         """
-        return cls._create_pax_generic_header(pax_headers, type=XGLTYPE)
+        return cls._create_pax_generic_header(pax_headers, XGLTYPE, encoding, errors)
 
     def _posix_split_name(self, name):
         """Split a name longer than 100 chars into a prefix
@@ -1097,31 +1084,31 @@
         return prefix, name
 
     @staticmethod
-    def _create_header(info, format):
+    def _create_header(info, format, encoding, errors):
         """Return a header block. info is a dictionary with file
            information, format must be one of the *_FORMAT constants.
         """
         parts = [
-            stn(info.get("name", ""), 100),
+            stn(info.get("name", ""), 100, encoding, errors),
             itn(info.get("mode", 0) & 0o7777, 8, format),
             itn(info.get("uid", 0), 8, format),
             itn(info.get("gid", 0), 8, format),
             itn(info.get("size", 0), 12, format),
             itn(info.get("mtime", 0), 12, format),
-            "        ", # checksum field
+            b"        ", # checksum field
             info.get("type", REGTYPE),
-            stn(info.get("linkname", ""), 100),
-            stn(info.get("magic", POSIX_MAGIC), 8),
-            stn(info.get("uname", "root"), 32),
-            stn(info.get("gname", "root"), 32),
+            stn(info.get("linkname", ""), 100, encoding, errors),
+            info.get("magic", POSIX_MAGIC),
+            stn(info.get("uname", "root"), 32, encoding, errors),
+            stn(info.get("gname", "root"), 32, encoding, errors),
             itn(info.get("devmajor", 0), 8, format),
             itn(info.get("devminor", 0), 8, format),
-            stn(info.get("prefix", ""), 155)
+            stn(info.get("prefix", ""), 155, encoding, errors)
         ]
 
-        buf = struct.pack("%ds" % BLOCKSIZE, "".join(parts))
+        buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
         chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
-        buf = buf[:-364] + "%06o\0" % chksum + buf[-357:]
+        buf = buf[:-364] + bytes("%06o\0" % chksum) + buf[-357:]
         return buf
 
     @staticmethod
@@ -1135,11 +1122,11 @@
         return payload
 
     @classmethod
-    def _create_gnu_long_header(cls, name, type):
+    def _create_gnu_long_header(cls, name, type, encoding, errors):
         """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
            for name.
         """
-        name += NUL
+        name = name.encode(encoding, errors) + NUL
 
         info = {}
         info["name"] = "././@LongLink"
@@ -1148,16 +1135,16 @@
         info["magic"] = GNU_MAGIC
 
         # create extended header + name blocks.
-        return cls._create_header(info, USTAR_FORMAT) + \
+        return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
                 cls._create_payload(name)
 
     @classmethod
-    def _create_pax_generic_header(cls, pax_headers, type=XHDTYPE):
+    def _create_pax_generic_header(cls, pax_headers, type, encoding, errors):
         """Return a POSIX.1-2001 extended or global header sequence
            that contains a list of keyword, value pairs. The values
-           must be unicode objects.
+           must be strings.
         """
-        records = []
+        records = b""
         for keyword, value in pax_headers.items():
             keyword = keyword.encode("utf8")
             value = value.encode("utf8")
@@ -1168,8 +1155,7 @@
                 if n == p:
                     break
                 p = n
-            records.append("%d %s=%s\n" % (p, keyword, value))
-        records = "".join(records)
+            records += bytes(str(p)) + b" " + keyword + b"=" + value + b"\n"
 
         # We use a hardcoded "././@PaxHeader" name like star does
         # instead of the one that POSIX recommends.
@@ -1180,12 +1166,12 @@
         info["magic"] = POSIX_MAGIC
 
         # Create pax header + record blocks.
-        return cls._create_header(info, USTAR_FORMAT) + \
+        return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
                 cls._create_payload(records)
 
     @classmethod
-    def frombuf(cls, buf):
-        """Construct a TarInfo object from a 512 byte string buffer.
+    def frombuf(cls, buf, encoding, errors):
+        """Construct a TarInfo object from a 512 byte bytes object.
         """
         if len(buf) != BLOCKSIZE:
             raise HeaderError("truncated header")
@@ -1198,7 +1184,7 @@
 
         obj = cls()
         obj.buf = buf
-        obj.name = nts(buf[0:100])
+        obj.name = nts(buf[0:100], encoding, errors)
         obj.mode = nti(buf[100:108])
         obj.uid = nti(buf[108:116])
         obj.gid = nti(buf[116:124])
@@ -1206,12 +1192,12 @@
         obj.mtime = nti(buf[136:148])
         obj.chksum = chksum
         obj.type = buf[156:157]
-        obj.linkname = nts(buf[157:257])
-        obj.uname = nts(buf[265:297])
-        obj.gname = nts(buf[297:329])
+        obj.linkname = nts(buf[157:257], encoding, errors)
+        obj.uname = nts(buf[265:297], encoding, errors)
+        obj.gname = nts(buf[297:329], encoding, errors)
         obj.devmajor = nti(buf[329:337])
         obj.devminor = nti(buf[337:345])
-        prefix = nts(buf[345:500])
+        prefix = nts(buf[345:500], encoding, errors)
 
         # Old V7 tar format represents a directory as a regular
         # file with a trailing slash.
@@ -1235,7 +1221,7 @@
         buf = tarfile.fileobj.read(BLOCKSIZE)
         if not buf:
             return
-        obj = cls.frombuf(buf)
+        obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
         obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
         return obj._proc_member(tarfile)
 
@@ -1295,9 +1281,9 @@
         # the longname information.
         next.offset = self.offset
         if self.type == GNUTYPE_LONGNAME:
-            next.name = nts(buf)
+            next.name = nts(buf, tarfile.encoding, tarfile.errors)
         elif self.type == GNUTYPE_LONGLINK:
-            next.linkname = nts(buf)
+            next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
 
         return next
 
@@ -1324,12 +1310,12 @@
             lastpos = offset + numbytes
             pos += 24
 
-        isextended = ord(buf[482])
+        isextended = bool(buf[482])
         origsize = nti(buf[483:495])
 
         # If the isextended flag is given,
         # there are extra headers to process.
-        while isextended == 1:
+        while isextended:
             buf = tarfile.fileobj.read(BLOCKSIZE)
             pos = 0
             for i in range(21):
@@ -1344,7 +1330,7 @@
                 realpos += numbytes
                 lastpos = offset + numbytes
                 pos += 24
-            isextended = ord(buf[504])
+            isextended = bool(buf[504])
 
         if lastpos < origsize:
             sp.append(_hole(lastpos, origsize - lastpos))
@@ -1431,8 +1417,6 @@
                     value = PAX_NUMBER_FIELDS[keyword](value)
                 except ValueError:
                     value = 0
-            else:
-                value = uts(value, encoding, errors)
 
             setattr(self, keyword, value)
 
@@ -1542,7 +1526,7 @@
         if errors is not None:
             self.errors = errors
         elif mode == "r":
-            self.errors = "utf-8"
+            self.errors = "replace"
         else:
             self.errors = "strict"
 
@@ -1560,7 +1544,7 @@
         self.closed = False
         self.members = []       # list of members as TarInfo objects
         self._loaded = False    # flag if all members have been read
-        self.offset = 0        # current position in the archive file
+        self.offset = 0         # current position in the archive file
         self.inodes = {}        # dictionary caching the inodes of
                                 # archive members already added
 
@@ -1575,14 +1559,15 @@
             while True:
                 if self.next() is None:
                     if self.offset > 0:
-                        self.fileobj.seek(- BLOCKSIZE, 1)
+                        self.fileobj.seek(self.fileobj.tell() - BLOCKSIZE)
                     break
 
         if self.mode in "aw":
             self._loaded = True
 
             if self.pax_headers:
-                buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
+                buf = self.tarinfo.create_pax_global_header(
+                        self.pax_headers.copy(), self.encoding, self.errors)
                 self.fileobj.write(buf)
                 self.offset += len(buf)
 

Modified: python/branches/py3k-buffer/Lib/tempfile.py
==============================================================================
--- python/branches/py3k-buffer/Lib/tempfile.py	(original)
+++ python/branches/py3k-buffer/Lib/tempfile.py	Fri Aug 17 20:48:09 2007
@@ -197,7 +197,7 @@
             filename = _os.path.join(dir, name)
             try:
                 fd = _os.open(filename, flags, 0o600)
-                fp = _os.fdopen(fd, 'w')
+                fp = _io.open(fd, 'w')
                 fp.write('blat')
                 fp.close()
                 _os.unlink(filename)
@@ -438,7 +438,7 @@
         flags |= _os.O_TEMPORARY
 
     (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
-    file = _os.fdopen(fd, mode, bufsize)
+    file = _io.open(fd, mode, bufsize)
     return _TemporaryFileWrapper(file, name, delete)
 
 if _os.name != 'posix' or _os.sys.platform == 'cygwin':
@@ -471,7 +471,7 @@
         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
         try:
             _os.unlink(name)
-            return _os.fdopen(fd, mode, bufsize)
+            return _io.open(fd, mode, bufsize)
         except:
             _os.close(fd)
             raise

Modified: python/branches/py3k-buffer/Lib/test/README
==============================================================================
--- python/branches/py3k-buffer/Lib/test/README	(original)
+++ python/branches/py3k-buffer/Lib/test/README	Fri Aug 17 20:48:09 2007
@@ -372,7 +372,7 @@
 
     * ``findfile(file)`` - you can call this function to locate a file
       somewhere along sys.path or in the Lib/test tree - see
-      test_linuxaudiodev.py for an example of its use.
+      test_ossaudiodev.py for an example of its use.
 
     * ``fcmp(x,y)`` - you can call this function to compare two floating
       point numbers when you expect them to only be approximately equal

Deleted: /python/branches/py3k-buffer/Lib/test/output/test_linuxaudiodev
==============================================================================
--- /python/branches/py3k-buffer/Lib/test/output/test_linuxaudiodev	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,7 +0,0 @@
-test_linuxaudiodev
-expected rate >= 0, not -1
-expected sample size >= 0, not -2
-nchannels must be 1 or 2, not 3
-unknown audio encoding: 177
-for linear unsigned 16-bit little-endian audio, expected sample size 16, not 8
-for linear unsigned 8-bit audio, expected sample size 8, not 16

Modified: python/branches/py3k-buffer/Lib/test/pickletester.py
==============================================================================
--- python/branches/py3k-buffer/Lib/test/pickletester.py	(original)
+++ python/branches/py3k-buffer/Lib/test/pickletester.py	Fri Aug 17 20:48:09 2007
@@ -406,7 +406,7 @@
     # is a mystery.  cPickle also suppresses PUT for objects with a refcount
     # of 1.
     def dont_test_disassembly(self):
-        from cStringIO import StringIO
+        from io import StringIO
         from pickletools import dis
 
         for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS):
@@ -951,8 +951,8 @@
         self.assertEqual(self.module.HIGHEST_PROTOCOL, 2)
 
     def test_callapi(self):
-        from cStringIO import StringIO
-        f = StringIO()
+        from io import BytesIO
+        f = BytesIO()
         # With and without keyword arguments
         self.module.dump(123, f, -1)
         self.module.dump(123, file=f, protocol=-1)

Modified: python/branches/py3k-buffer/Lib/test/regrtest.py
==============================================================================
--- python/branches/py3k-buffer/Lib/test/regrtest.py	(original)
+++ python/branches/py3k-buffer/Lib/test/regrtest.py	Fri Aug 17 20:48:09 2007
@@ -125,7 +125,7 @@
 import random
 import warnings
 import re
-import StringIO
+import io
 import traceback
 
 # I see no other way to suppress these warnings;
@@ -537,7 +537,7 @@
     if verbose:
         cfp = None
     else:
-        cfp = StringIO.StringIO()  # XXX Should use io.StringIO()
+        cfp = io.StringIO()  # XXX Should use io.StringIO()
 
     try:
         save_stdout = sys.stdout
@@ -1106,8 +1106,6 @@
             self.expected = set(s.split())
 
             # expected to be skipped on every platform, even Linux
-            self.expected.add('test_linuxaudiodev')
-
             if not os.path.supports_unicode_filenames:
                 self.expected.add('test_pep277')
 
@@ -1134,7 +1132,6 @@
                     self.expected.add(skip)
 
             if sys.platform != 'sunos5':
-                self.expected.add('test_sunaudiodev')
                 self.expected.add('test_nis')
 
             self.valid = True

Modified: python/branches/py3k-buffer/Lib/test/test_bsddb3.py
==============================================================================
--- python/branches/py3k-buffer/Lib/test/test_bsddb3.py	(original)
+++ python/branches/py3k-buffer/Lib/test/test_bsddb3.py	Fri Aug 17 20:48:09 2007
@@ -24,28 +24,29 @@
 def suite():
     try:
         # this is special, it used to segfault the interpreter
-        import bsddb.test.test_1413192
+        #import bsddb.test.test_1413192
+        pass
     except:
         for f in ['__db.001', '__db.002', '__db.003', 'log.0000000001']:
             unlink(f)
 
     test_modules = [
-        'test_associate',
-        'test_basics',
-        'test_compat',
-        'test_dbobj',
+        #'test_associate',
+        #'test_basics',
+        #'test_compat',
+        #'test_dbobj',
         'test_dbshelve',
-        'test_dbtables',
-        'test_env_close',
-        'test_get_none',
-        'test_join',
-        'test_lock',
-        'test_misc',
-        'test_queue',
-        'test_recno',
-        'test_thread',
-        'test_sequence',
-        'test_cursor_pget_bug',
+        #'test_dbtables',
+        #'test_env_close',
+        #'test_get_none',
+        #'test_join',
+        #'test_lock',
+        #'test_misc',
+        #'test_queue',
+        #'test_recno',
+        #'test_thread',
+        #'test_sequence',
+        #'test_cursor_pget_bug',
         ]
 
     alltests = unittest.TestSuite()

Deleted: /python/branches/py3k-buffer/Lib/test/test_linuxaudiodev.py
==============================================================================
--- /python/branches/py3k-buffer/Lib/test/test_linuxaudiodev.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,92 +0,0 @@
-from test import test_support
-test_support.requires('audio')
-
-from test.test_support import verbose, findfile, TestFailed, TestSkipped
-
-import errno
-import fcntl
-import linuxaudiodev
-import os
-import sys
-import select
-import sunaudio
-import time
-import audioop
-
-SND_FORMAT_MULAW_8 = 1
-
-def play_sound_file(path):
-    fp = open(path, 'r')
-    size, enc, rate, nchannels, extra = sunaudio.gethdr(fp)
-    data = fp.read()
-    fp.close()
-
-    if enc != SND_FORMAT_MULAW_8:
-        print("Expect .au file with 8-bit mu-law samples")
-        return
-
-    try:
-        a = linuxaudiodev.open('w')
-    except linuxaudiodev.error as msg:
-        if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
-            raise TestSkipped, msg
-        raise TestFailed, msg
-
-    # convert the data to 16-bit signed
-    data = audioop.ulaw2lin(data, 2)
-
-    # set the data format
-    if sys.byteorder == 'little':
-        fmt = linuxaudiodev.AFMT_S16_LE
-    else:
-        fmt = linuxaudiodev.AFMT_S16_BE
-
-    # at least check that these methods can be invoked
-    a.bufsize()
-    a.obufcount()
-    a.obuffree()
-    a.getptr()
-    a.fileno()
-
-    # set parameters based on .au file headers
-    a.setparameters(rate, 16, nchannels, fmt)
-    a.write(data)
-    a.flush()
-    a.close()
-
-def test_errors():
-    a = linuxaudiodev.open("w")
-    size = 8
-    fmt = linuxaudiodev.AFMT_U8
-    rate = 8000
-    nchannels = 1
-    try:
-        a.setparameters(-1, size, nchannels, fmt)
-    except ValueError as msg:
-        print(msg)
-    try:
-        a.setparameters(rate, -2, nchannels, fmt)
-    except ValueError as msg:
-        print(msg)
-    try:
-        a.setparameters(rate, size, 3, fmt)
-    except ValueError as msg:
-        print(msg)
-    try:
-        a.setparameters(rate, size, nchannels, 177)
-    except ValueError as msg:
-        print(msg)
-    try:
-        a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE)
-    except ValueError as msg:
-        print(msg)
-    try:
-        a.setparameters(rate, 16, nchannels, fmt)
-    except ValueError as msg:
-        print(msg)
-
-def test():
-    play_sound_file(findfile('audiotest.au'))
-    test_errors()
-
-test()

Deleted: /python/branches/py3k-buffer/Lib/test/test_sunaudiodev.py
==============================================================================
--- /python/branches/py3k-buffer/Lib/test/test_sunaudiodev.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,28 +0,0 @@
-from test.test_support import verbose, findfile, TestFailed, TestSkipped
-import sunaudiodev
-import os
-
-try:
-    audiodev = os.environ["AUDIODEV"]
-except KeyError:
-    audiodev = "/dev/audio"
-
-if not os.path.exists(audiodev):
-    raise TestSkipped("no audio device found!")
-
-def play_sound_file(path):
-    fp = open(path, 'r')
-    data = fp.read()
-    fp.close()
-    try:
-        a = sunaudiodev.open('w')
-    except sunaudiodev.error as msg:
-        raise TestFailed, msg
-    else:
-        a.write(data)
-        a.close()
-
-def test():
-    play_sound_file(findfile('audiotest.au'))
-
-test()

Modified: python/branches/py3k-buffer/Lib/test/test_wsgiref.py
==============================================================================
--- python/branches/py3k-buffer/Lib/test/test_wsgiref.py	(original)
+++ python/branches/py3k-buffer/Lib/test/test_wsgiref.py	Fri Aug 17 20:48:09 2007
@@ -7,7 +7,7 @@
 from wsgiref.validate import validator
 from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, demo_app
 from wsgiref.simple_server import make_server
-from io import StringIO, BytesIO, BufferedReader
+from io import StringIO, BytesIO
 from SocketServer import BaseServer
 import re, sys
 
@@ -49,10 +49,8 @@
 
 def run_amock(app=hello_app, data=b"GET / HTTP/1.0\n\n"):
     server = make_server("", 80, app, MockServer, MockHandler)
-    inp = BufferedReader(BytesIO(data))
-    out = StringIO()
-    olderr = sys.stderr
-    err = sys.stderr = StringIO()
+    inp, out, err, olderr = BytesIO(data), StringIO(), StringIO(), sys.stderr
+    sys.stderr = err
 
     try:
         server.finish_request((inp, out), ("127.0.0.1",8888))

Modified: python/branches/py3k-buffer/Lib/threading.py
==============================================================================
--- python/branches/py3k-buffer/Lib/threading.py	(original)
+++ python/branches/py3k-buffer/Lib/threading.py	Fri Aug 17 20:48:09 2007
@@ -85,9 +85,10 @@
         self.__count = 0
 
     def __repr__(self):
+        owner = self.__owner
         return "<%s(%s, %d)>" % (
                 self.__class__.__name__,
-                self.__owner and self.__owner.getName(),
+                owner and owner.getName(),
                 self.__count)
 
     def acquire(self, blocking=1):

Deleted: /python/branches/py3k-buffer/Lib/toaiff.py
==============================================================================
--- /python/branches/py3k-buffer/Lib/toaiff.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,107 +0,0 @@
-"""Convert "arbitrary" sound files to AIFF (Apple and SGI's audio format).
-
-Input may be compressed.
-Uncompressed file type may be AIFF, WAV, VOC, 8SVX, NeXT/Sun, and others.
-An exception is raised if the file is not of a recognized type.
-Returned filename is either the input filename or a temporary filename;
-in the latter case the caller must ensure that it is removed.
-Other temporary files used are removed by the function.
-"""
-
-import os
-import tempfile
-import pipes
-import sndhdr
-
-__all__ = ["error", "toaiff"]
-
-table = {}
-
-t = pipes.Template()
-t.append('sox -t au - -t aiff -r 8000 -', '--')
-table['au'] = t
-
-# XXX The following is actually sub-optimal.
-# XXX The HCOM sampling rate can be 22k, 22k/2, 22k/3 or 22k/4.
-# XXX We must force the output sampling rate else the SGI won't play
-# XXX files sampled at 5.5k or 7.333k; however this means that files
-# XXX sampled at 11k are unnecessarily expanded.
-# XXX Similar comments apply to some other file types.
-t = pipes.Template()
-t.append('sox -t hcom - -t aiff -r 22050 -', '--')
-table['hcom'] = t
-
-t = pipes.Template()
-t.append('sox -t voc - -t aiff -r 11025 -', '--')
-table['voc'] = t
-
-t = pipes.Template()
-t.append('sox -t wav - -t aiff -', '--')
-table['wav'] = t
-
-t = pipes.Template()
-t.append('sox -t 8svx - -t aiff -r 16000 -', '--')
-table['8svx'] = t
-
-t = pipes.Template()
-t.append('sox -t sndt - -t aiff -r 16000 -', '--')
-table['sndt'] = t
-
-t = pipes.Template()
-t.append('sox -t sndr - -t aiff -r 16000 -', '--')
-table['sndr'] = t
-
-uncompress = pipes.Template()
-uncompress.append('uncompress', '--')
-
-
-class error(Exception):
-    pass
-
-def toaiff(filename):
-    temps = []
-    ret = None
-    try:
-        ret = _toaiff(filename, temps)
-    finally:
-        for temp in temps[:]:
-            if temp != ret:
-                try:
-                    os.unlink(temp)
-                except os.error:
-                    pass
-                temps.remove(temp)
-    return ret
-
-def _toaiff(filename, temps):
-    if filename[-2:] == '.Z':
-        (fd, fname) = tempfile.mkstemp()
-        os.close(fd)
-        temps.append(fname)
-        sts = uncompress.copy(filename, fname)
-        if sts:
-            raise error, filename + ': uncompress failed'
-    else:
-        fname = filename
-    try:
-        ftype = sndhdr.whathdr(fname)
-        if ftype:
-            ftype = ftype[0] # All we're interested in
-    except IOError as msg:
-        if type(msg) == type(()) and len(msg) == 2 and \
-                type(msg[0]) == type(0) and type(msg[1]) == type(''):
-            msg = msg[1]
-        if type(msg) != type(''):
-            msg = repr(msg)
-        raise error, filename + ': ' + msg
-    if ftype == 'aiff':
-        return fname
-    if ftype is None or not ftype in table:
-        raise error, '%s: unsupported audio file type %r' % (filename, ftype)
-    (fd, temp) = tempfile.mkstemp()
-    os.close(fd)
-    temps.append(temp)
-    sts = table[ftype].copy(fname, temp)
-    if sts:
-        raise error, filename + ': conversion to aiff failed'
-    return temp

Modified: python/branches/py3k-buffer/Lib/traceback.py
==============================================================================
--- python/branches/py3k-buffer/Lib/traceback.py	(original)
+++ python/branches/py3k-buffer/Lib/traceback.py	Fri Aug 17 20:48:09 2007
@@ -161,7 +161,6 @@
     string in the list.
 
     """
-
     # Gracefully handle (the way Python 2.4 and earlier did) the case of
     # being called with (None, None).
     if etype is None:
@@ -177,28 +176,24 @@
 
     # It was a syntax error; show exactly where the problem was found.
     lines = []
-    try:
-        msg, (filename, lineno, offset, badline) = value.args
-    except Exception:
-        pass
-    else:
-        filename = filename or "<string>"
-        lines.append('  File "%s", line %d\n' % (filename, lineno))
-        if badline is not None:
-            lines.append('    %s\n' % badline.strip())
-            if offset is not None:
-                caretspace = badline[:offset].lstrip()
-                # non-space whitespace (likes tabs) must be kept for alignment
-                caretspace = ((c.isspace() and c or ' ') for c in caretspace)
-                # only three spaces to account for offset1 == pos 0
-                lines.append('   %s^\n' % ''.join(caretspace))
-            value = msg
-
-    lines.append(_format_final_exc_line(stype, value))
+    filename = value.filename or "<string>"
+    lineno = str(value.lineno) or '?'
+    lines.append('  File "%s", line %s\n' % (filename, lineno))
+    badline = value.text
+    offset = value.offset
+    if badline is not None:
+        lines.append('    %s\n' % badline.strip())
+        if offset is not None:
+            caretspace = badline[:offset].lstrip()
+            # non-space whitespace (likes tabs) must be kept for alignment
+            caretspace = ((c.isspace() and c or ' ') for c in caretspace)
+            # only three spaces to account for offset1 == pos 0
+            lines.append('   %s^\n' % ''.join(caretspace))
+    msg = value.msg or "<no detail available>"
+    lines.append("%s: %s\n" % (stype, msg))
     return lines
 
 def _format_final_exc_line(etype, value):
-    """Return a list of a single line -- normal case for format_exception_only"""
     valuestr = _some_str(value)
     if value is None or not valuestr:
         line = "%s\n" % etype

Modified: python/branches/py3k-buffer/Lib/urllib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/urllib.py	(original)
+++ python/branches/py3k-buffer/Lib/urllib.py	Fri Aug 17 20:48:09 2007
@@ -81,11 +81,13 @@
         return opener.open(url)
     else:
         return opener.open(url, data)
+
 def urlretrieve(url, filename=None, reporthook=None, data=None):
     global _urlopener
     if not _urlopener:
         _urlopener = FancyURLopener()
     return _urlopener.retrieve(url, filename, reporthook, data)
+
 def urlcleanup():
     if _urlopener:
         _urlopener.cleanup()
@@ -310,37 +312,44 @@
             auth = base64.b64encode(user_passwd).strip()
         else:
             auth = None
-        h = httplib.HTTP(host)
+        http_conn = httplib.HTTPConnection(host)
+        # XXX We should fix urllib so that it works with HTTP/1.1.
+        http_conn._http_vsn = 10
+        http_conn._http_vsn_str = "HTTP/1.0"
+
+        headers = {}
+        if proxy_auth:
+            headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
+        if auth:
+            headers["Authorization"] =  "Basic %s" % auth
+        if realhost:
+            headers["Host"] = realhost
+        for header, value in self.addheaders:
+            headers[header] = value
+
         if data is not None:
-            h.putrequest('POST', selector)
-            h.putheader('Content-Type', 'application/x-www-form-urlencoded')
-            h.putheader('Content-Length', '%d' % len(data))
+            headers["Content-Type"] = "application/x-www-form-urlencoded"
+            http_conn.request("POST", selector, data, headers)
         else:
-            h.putrequest('GET', selector)
-        if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth)
-        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)
-        errcode, errmsg, headers = h.getreply()
-        fp = h.getfile()
-        if errcode == -1:
-            if fp: fp.close()
+            http_conn.request("GET", selector, headers=headers)
+
+        try:
+            response = http_conn.getresponse()
+        except httplib.BadStatusLine:
             # something went wrong with the HTTP status line
-            raise IOError, ('http protocol error', 0,
-                            'got a bad status line', None)
-        if errcode == 200:
-            return addinfourl(fp, headers, "http:" + url)
+            raise IOError('http protocol error', 0,
+                          'got a bad status line', None)
+
+        if response.status == 200:
+            return addinfourl(response.fp, response.msg, "http:" + url)
         else:
-            if data is None:
-                return self.http_error(url, fp, errcode, errmsg, headers)
-            else:
-                return self.http_error(url, fp, errcode, errmsg, headers, data)
+            return self.http_error(
+                url, response.fp,
+                response.status, response.reason, response.msg, data)
 
     def http_error(self, url, fp, errcode, errmsg, headers, data=None):
         """Handle http errors.
+
         Derived class can override this, or provide specific handlers
         named http_error_DDD where DDD is the 3-digit error code."""
         # First check if there's a specific handler for this error
@@ -872,6 +881,8 @@
 class addbase:
     """Base class for addinfo and addclosehook."""
 
+    # XXX Add a method to expose the timeout on the underlying socket?
+
     def __init__(self, fp):
         self.fp = fp
         self.read = self.fp.read
@@ -1133,7 +1144,23 @@
 always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                'abcdefghijklmnopqrstuvwxyz'
                '0123456789' '_.-')
-_safemaps = {}
+_safe_quoters= {}
+
+class Quoter:
+    def __init__(self, safe):
+        self.cache = {}
+        self.safe = safe + always_safe
+
+    def __call__(self, c):
+        try:
+            return self.cache[c]
+        except KeyError:
+            if ord(c) < 256:
+                res = (c in self.safe) and c or ('%%%02X' % ord(c))
+                self.cache[c] = res
+                return res
+            else:
+                return "".join(['%%%02X' % i for i in c.encode("utf-8")])
 
 def quote(s, safe = '/'):
     """quote('abc def') -> 'abc%20def'
@@ -1158,15 +1185,11 @@
     """
     cachekey = (safe, always_safe)
     try:
-        safe_map = _safemaps[cachekey]
+        quoter = _safe_quoters[cachekey]
     except KeyError:
-        safe += always_safe
-        safe_map = {}
-        for i in range(256):
-            c = chr(i)
-            safe_map[c] = (c in safe) and c or ('%%%02X' % i)
-        _safemaps[cachekey] = safe_map
-    res = map(safe_map.__getitem__, s)
+        quoter = Quoter(safe)
+        _safe_quoters[cachekey] = quoter
+    res = map(quoter, s)
     return ''.join(res)
 
 def quote_plus(s, safe = ''):

Modified: python/branches/py3k-buffer/Lib/urllib2.py
==============================================================================
--- python/branches/py3k-buffer/Lib/urllib2.py	(original)
+++ python/branches/py3k-buffer/Lib/urllib2.py	Fri Aug 17 20:48:09 2007
@@ -679,7 +679,7 @@
             proxy_type = orig_type
         if user and password:
             user_pass = '%s:%s' % (unquote(user), unquote(password))
-            creds = base64.b64encode(user_pass).strip()
+            creds = str(base64.b64encode(user_pass)).strip()
             req.add_header('Proxy-authorization', 'Basic ' + creds)
         hostport = unquote(hostport)
         req.set_proxy(hostport, proxy_type)
@@ -802,7 +802,7 @@
         user, pw = self.passwd.find_user_password(realm, host)
         if pw is not None:
             raw = "%s:%s" % (user, pw)
-            auth = 'Basic %s' % base64.b64encode(raw).strip()
+            auth = 'Basic %s' % str(base64.b64encode(raw)).strip()
             if req.headers.get(self.auth_header, None) == auth:
                 return None
             req.add_header(self.auth_header, auth)
@@ -1072,6 +1072,10 @@
         # Pick apart the HTTPResponse object to get the addinfourl
         # object initialized properly.
 
+        # XXX Should an HTTPResponse object really be passed to
+        # BufferedReader?  If so, we should change httplib to support
+        # this use directly.
+
         # Add some fake methods to the reader to satisfy BufferedReader.
         r.readable = lambda: True
         r.writable = r.seekable = lambda: False
@@ -1283,7 +1287,6 @@
 
     def connect_ftp(self, user, passwd, host, port, dirs, timeout):
         fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
-##        fw.ftp.set_debuglevel(1)
         return fw
 
 class CacheFTPHandler(FTPHandler):

Modified: python/branches/py3k-buffer/Lib/uu.py
==============================================================================
--- python/branches/py3k-buffer/Lib/uu.py	(original)
+++ python/branches/py3k-buffer/Lib/uu.py	Fri Aug 17 20:48:09 2007
@@ -45,7 +45,7 @@
     # If in_file is a pathname open it and change defaults
     #
     if in_file == '-':
-        in_file = sys.stdin
+        in_file = sys.stdin.buffer
     elif isinstance(in_file, basestring):
         if name is None:
             name = os.path.basename(in_file)
@@ -59,9 +59,9 @@
     # Open out_file if it is a pathname
     #
     if out_file == '-':
-        out_file = sys.stdout
+        out_file = sys.stdout.buffer
     elif isinstance(out_file, basestring):
-        out_file = open(out_file, 'w')
+        out_file = open(out_file, 'wb')
     #
     # Set defaults for name and mode
     #
@@ -86,9 +86,9 @@
     # Open the input file, if needed.
     #
     if in_file == '-':
-        in_file = sys.stdin
+        in_file = sys.stdin.buffer
     elif isinstance(in_file, basestring):
-        in_file = open(in_file)
+        in_file = open(in_file, 'rb')
     #
     # Read until a begin is encountered or we've exhausted the file
     #
@@ -96,17 +96,18 @@
         hdr = in_file.readline()
         if not hdr:
             raise Error('No valid begin line found in input file')
-        if not hdr.startswith('begin'):
+        if not hdr.startswith(b'begin'):
             continue
-        hdrfields = hdr.split(' ', 2)
-        if len(hdrfields) == 3 and hdrfields[0] == 'begin':
+        hdrfields = hdr.split(b' ', 2)
+        if len(hdrfields) == 3 and hdrfields[0] == b'begin':
             try:
                 int(hdrfields[1], 8)
                 break
             except ValueError:
                 pass
     if out_file is None:
-        out_file = hdrfields[2].rstrip()
+        # If the filename isn't ASCII, what's up with that?!?
+        out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii")
         if os.path.exists(out_file):
             raise Error('Cannot overwrite existing file: %s' % out_file)
     if mode is None:
@@ -116,7 +117,7 @@
     #
     opened = False
     if out_file == '-':
-        out_file = sys.stdout
+        out_file = sys.stdout.buffer
     elif isinstance(out_file, basestring):
         fp = open(out_file, 'wb')
         try:
@@ -129,12 +130,12 @@
     # Main decoding loop
     #
     s = in_file.readline()
-    while s and s.strip() != 'end':
+    while s and s.strip(b' \t\r\n\f') != b'end':
         try:
             data = binascii.a2b_uu(s)
         except binascii.Error as v:
             # Workaround for broken uuencoders by /Fredrik Lundh
-            nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3
+            nbytes = (((s[0]-32) & 63) * 4 + 5) // 3
             data = binascii.a2b_uu(s[:nbytes])
             if not quiet:
                 sys.stderr.write("Warning: %s\n" % v)
@@ -158,8 +159,9 @@
         parser.error('incorrect number of arguments')
         sys.exit(1)
 
-    input = sys.stdin
-    output = sys.stdout
+    # Use the binary streams underlying stdin/stdout
+    input = sys.stdin.buffer
+    output = sys.stdout.buffer
     if len(args) > 0:
         input = args[0]
     if len(args) > 1:
@@ -168,7 +170,7 @@
     if options.decode:
         if options.text:
             if isinstance(output, basestring):
-                output = open(output, 'w')
+                output = open(output, 'wb')
             else:
                 print(sys.argv[0], ': cannot do -t to stdout')
                 sys.exit(1)
@@ -176,7 +178,7 @@
     else:
         if options.text:
             if isinstance(input, basestring):
-                input = open(input, 'r')
+                input = open(input, 'rb')
             else:
                 print(sys.argv[0], ': cannot do -t from stdin')
                 sys.exit(1)

Modified: python/branches/py3k-buffer/Lib/wsgiref/handlers.py
==============================================================================
--- python/branches/py3k-buffer/Lib/wsgiref/handlers.py	(original)
+++ python/branches/py3k-buffer/Lib/wsgiref/handlers.py	Fri Aug 17 20:48:09 2007
@@ -1,6 +1,5 @@
 """Base classes for server/gateway implementations"""
 
-from types import StringType
 from .util import FileWrapper, guess_scheme, is_hop_by_hop
 from .headers import Headers
 
@@ -158,14 +157,14 @@
         elif self.headers is not None:
             raise AssertionError("Headers already set!")
 
-        assert type(status) is StringType,"Status must be a string"
+        assert type(status) is str,"Status must be a string"
         assert len(status)>=4,"Status must be at least 4 characters"
         assert int(status[:3]),"Status message must begin w/3-digit code"
         assert status[3]==" ", "Status message must have a space after code"
         if __debug__:
             for name,val in headers:
-                assert type(name) is StringType,"Header names must be strings"
-                assert type(val) is StringType,"Header values must be strings"
+                assert type(name) is str,"Header names must be strings"
+                assert type(val) is str,"Header values must be strings"
                 assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
         self.status = status
         self.headers = self.headers_class(headers)
@@ -189,7 +188,7 @@
     def write(self, data):
         """'write()' callable as specified by PEP 333"""
 
-        assert type(data) is StringType,"write() argument must be string"
+        assert type(data) is str,"write() argument must be string"
 
         if not self.status:
             raise AssertionError("write() before start_response()")

Modified: python/branches/py3k-buffer/Lib/wsgiref/simple_server.py
==============================================================================
--- python/branches/py3k-buffer/Lib/wsgiref/simple_server.py	(original)
+++ python/branches/py3k-buffer/Lib/wsgiref/simple_server.py	Fri Aug 17 20:48:09 2007
@@ -163,7 +163,7 @@
 
 
 def demo_app(environ,start_response):
-    from StringIO import StringIO
+    from io import StringIO
     stdout = StringIO()
     print("Hello world!", file=stdout)
     print(file=stdout)

Modified: python/branches/py3k-buffer/Lib/wsgiref/util.py
==============================================================================
--- python/branches/py3k-buffer/Lib/wsgiref/util.py	(original)
+++ python/branches/py3k-buffer/Lib/wsgiref/util.py	Fri Aug 17 20:48:09 2007
@@ -149,7 +149,7 @@
     environ.setdefault('wsgi.multithread', 0)
     environ.setdefault('wsgi.multiprocess', 0)
 
-    from StringIO import StringIO
+    from io import StringIO
     environ.setdefault('wsgi.input', StringIO(""))
     environ.setdefault('wsgi.errors', StringIO())
     environ.setdefault('wsgi.url_scheme',guess_scheme(environ))

Modified: python/branches/py3k-buffer/Lib/xdrlib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/xdrlib.py	(original)
+++ python/branches/py3k-buffer/Lib/xdrlib.py	Fri Aug 17 20:48:09 2007
@@ -5,7 +5,7 @@
 """
 
 import struct
-from io import StringIO as _StringIO
+from io import BytesIO
 
 __all__ = ["Error", "Packer", "Unpacker", "ConversionError"]
 
@@ -40,7 +40,7 @@
         self.reset()
 
     def reset(self):
-        self.__buf = _StringIO()
+        self.__buf = BytesIO()
 
     def get_buffer(self):
         return self.__buf.getvalue()
@@ -54,8 +54,8 @@
     pack_enum = pack_int
 
     def pack_bool(self, x):
-        if x: self.__buf.write('\0\0\0\1')
-        else: self.__buf.write('\0\0\0\0')
+        if x: self.__buf.write(b'\0\0\0\1')
+        else: self.__buf.write(b'\0\0\0\0')
 
     def pack_uhyper(self, x):
         self.pack_uint(x>>32 & 0xffffffff)
@@ -78,7 +78,7 @@
             raise ValueError, 'fstring size must be nonnegative'
         data = s[:n]
         n = ((n+3)//4)*4
-        data = data + (n - len(data)) * '\0'
+        data = data + (n - len(data)) * b'\0'
         self.__buf.write(data)
 
     pack_fopaque = pack_fstring

Modified: python/branches/py3k-buffer/Lib/xml/dom/minidom.py
==============================================================================
--- python/branches/py3k-buffer/Lib/xml/dom/minidom.py	(original)
+++ python/branches/py3k-buffer/Lib/xml/dom/minidom.py	Fri Aug 17 20:48:09 2007
@@ -14,6 +14,7 @@
  * SAX 2 namespaces
 """
 
+import io
 import xml.dom
 
 from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
@@ -44,20 +45,20 @@
     def toxml(self, encoding = None):
         return self.toprettyxml("", "", encoding)
 
-    def toprettyxml(self, indent="\t", newl="\n", encoding = None):
+    def toprettyxml(self, indent="\t", newl="\n", encoding=None):
         # indent = the indentation string to prepend, per level
         # newl = the newline string to append
-        writer = _get_StringIO()
-        if encoding is not None:
-            import codecs
-            # Can't use codecs.getwriter to preserve 2.0 compatibility
-            writer = codecs.lookup(encoding)[3](writer)
+        use_encoding = "utf-8" if encoding is None else encoding
+        writer = io.StringIO(encoding=use_encoding)
         if self.nodeType == Node.DOCUMENT_NODE:
             # Can pass encoding only to document, to put it into XML header
             self.writexml(writer, "", indent, newl, encoding)
         else:
             self.writexml(writer, "", indent, newl)
-        return writer.getvalue()
+        if encoding is None:
+            return writer.getvalue()
+        else:
+            return writer.buffer.getvalue()
 
     def hasChildNodes(self):
         if self.childNodes:
@@ -360,7 +361,7 @@
 
     def _get_localName(self):
         if 'localName' in self.__dict__:
-          return self.__dict__['localName']
+            return self.__dict__['localName']
         return self.nodeName.split(":", 1)[-1]
 
     def _get_name(self):
@@ -665,7 +666,7 @@
 
     def _get_localName(self):
         if 'localName' in self.__dict__:
-          return self.__dict__['localName']
+            return self.__dict__['localName']
         return self.tagName.split(":", 1)[-1]
 
     def _get_tagName(self):
@@ -1897,11 +1898,6 @@
         return (None, fields[0])
 
 
-def _get_StringIO():
-    # we can't use cStringIO since it doesn't support Unicode strings
-    from StringIO import StringIO
-    return StringIO()
-
 def _do_pulldom_parse(func, args, kwargs):
     events = func(*args, **kwargs)
     toktype, rootNode = events.getEvent()

Modified: python/branches/py3k-buffer/Lib/xml/dom/pulldom.py
==============================================================================
--- python/branches/py3k-buffer/Lib/xml/dom/pulldom.py	(original)
+++ python/branches/py3k-buffer/Lib/xml/dom/pulldom.py	Fri Aug 17 20:48:09 2007
@@ -2,11 +2,6 @@
 import xml.sax.handler
 import types
 
-try:
-    _StringTypes = [types.StringType, types.UnicodeType]
-except AttributeError:
-    _StringTypes = [types.StringType]
-
 START_ELEMENT = "START_ELEMENT"
 END_ELEMENT = "END_ELEMENT"
 COMMENT = "COMMENT"
@@ -330,7 +325,7 @@
 def parse(stream_or_string, parser=None, bufsize=None):
     if bufsize is None:
         bufsize = default_bufsize
-    if type(stream_or_string) in _StringTypes:
+    if isinstance(stream_or_string, basestring):
         stream = open(stream_or_string)
     else:
         stream = stream_or_string
@@ -340,9 +335,9 @@
 
 def parseString(string, parser=None):
     try:
-        from cStringIO import StringIO
+        from io import StringIO
     except ImportError:
-        from StringIO import StringIO
+        from io import StringIO
 
     bufsize = len(string)
     buf = StringIO(string)

Modified: python/branches/py3k-buffer/Lib/xml/etree/ElementTree.py
==============================================================================
--- python/branches/py3k-buffer/Lib/xml/etree/ElementTree.py	(original)
+++ python/branches/py3k-buffer/Lib/xml/etree/ElementTree.py	Fri Aug 17 20:48:09 2007
@@ -625,25 +625,26 @@
     # Writes the element tree to a file, as XML.
     #
     # @param file A file name, or a file object opened for writing.
-    # @param encoding Optional output encoding (default is US-ASCII).
+    # @param encoding Optional output encoding (default is None)
 
-    def write(self, file, encoding="us-ascii"):
+    def write(self, file, encoding=None):
         assert self._root is not None
         if not hasattr(file, "write"):
-            file = open(file, "wb")
-        if not encoding:
-            encoding = "us-ascii"
-        elif encoding != "utf-8" and encoding != "us-ascii":
-            file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
+            if encoding:
+                file = open(file, "wb")
+            else:
+                file = open(file, "w")
+        if encoding and encoding != "utf-8":
+            file.write(_encode("<?xml version='1.0' encoding='%s'?>\n" % encoding, encoding))
         self._write(file, self._root, encoding, {})
 
     def _write(self, file, node, encoding, namespaces):
         # write XML to file
         tag = node.tag
         if tag is Comment:
-            file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
+            file.write(_encode("<!-- %s -->" % _escape_cdata(node.text), encoding))
         elif tag is ProcessingInstruction:
-            file.write("<?%s?>" % _escape_cdata(node.text, encoding))
+            file.write(_encode("<?%s?>" % _escape_cdata(node.text), encoding))
         else:
             items = list(node.items())
             xmlns_items = [] # new namespaces in this scope
@@ -653,7 +654,7 @@
                     if xmlns: xmlns_items.append(xmlns)
             except TypeError:
                 _raise_serialization_error(tag)
-            file.write("<" + _encode(tag, encoding))
+            file.write(_encode("<" + tag, encoding))
             if items or xmlns_items:
                 items.sort() # lexical order
                 for k, v in items:
@@ -669,24 +670,22 @@
                             if xmlns: xmlns_items.append(xmlns)
                     except TypeError:
                         _raise_serialization_error(v)
-                    file.write(" %s=\"%s\"" % (_encode(k, encoding),
-                                               _escape_attrib(v, encoding)))
+                    file.write(_encode(" %s=\"%s\"" % (k, _escape_attrib(v)), encoding))
                 for k, v in xmlns_items:
-                    file.write(" %s=\"%s\"" % (_encode(k, encoding),
-                                               _escape_attrib(v, encoding)))
+                    file.write(_encode(" %s=\"%s\"" % (k, _escape_attrib(v)), encoding))
             if node.text or len(node):
-                file.write(">")
+                file.write(_encode(">", encoding))
                 if node.text:
-                    file.write(_escape_cdata(node.text, encoding))
+                    file.write(_encode(_escape_cdata(node.text), encoding))
                 for n in node:
                     self._write(file, n, encoding, namespaces)
-                file.write("</" + _encode(tag, encoding) + ">")
+                file.write(_encode("</" + tag + ">", encoding))
             else:
-                file.write(" />")
+                file.write(_encode(" />", encoding))
             for k, v in xmlns_items:
                 del namespaces[v]
         if node.tail:
-            file.write(_escape_cdata(node.tail, encoding))
+            file.write(_encode(_escape_cdata(node.tail), encoding))
 
 # --------------------------------------------------------------------
 # helpers
@@ -722,15 +721,12 @@
         sys.stdout.write("\n")
 
 def _encode(s, encoding):
-    try:
+    if encoding:
         return s.encode(encoding)
-    except AttributeError:
-        return s # 1.5.2: assume the string uses the right encoding
+    else:
+        return s
 
-if sys.version[:3] == "1.5":
-    _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2
-else:
-    _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))
+_escape = re.compile(r"[&<>\"\u0080-\uffff]+")
 
 _escape_map = {
     "&": "&amp;",
@@ -772,14 +768,9 @@
 # the following functions assume an ascii-compatible encoding
 # (or "utf-16")
 
-def _escape_cdata(text, encoding=None):
+def _escape_cdata(text):
     # escape character data
     try:
-        if encoding:
-            try:
-                text = _encode(text, encoding)
-            except UnicodeError:
-                return _encode_entity(text)
         text = text.replace("&", "&amp;")
         text = text.replace("<", "&lt;")
         text = text.replace(">", "&gt;")
@@ -787,14 +778,9 @@
     except (TypeError, AttributeError):
         _raise_serialization_error(text)
 
-def _escape_attrib(text, encoding=None):
+def _escape_attrib(text):
     # escape attribute value
     try:
-        if encoding:
-            try:
-                text = _encode(text, encoding)
-            except UnicodeError:
-                return _encode_entity(text)
         text = text.replace("&", "&amp;")
         text = text.replace("'", "&apos;") # FIXME: overkill
         text = text.replace("\"", "&quot;")
@@ -969,10 +955,11 @@
 
 ##
 # Generates a string representation of an XML element, including all
-# subelements.
+# subelements.  If encoding is None, the return type is a string;
+# otherwise it is a bytes array.
 #
 # @param element An Element instance.
-# @return An encoded string containing the XML data.
+# @return An (optionally) encoded string containing the XML data.
 # @defreturn string
 
 def tostring(element, encoding=None):
@@ -982,7 +969,10 @@
     file = dummy()
     file.write = data.append
     ElementTree(element).write(file, encoding)
-    return "".join(data)
+    if encoding:
+        return b"".join(data)
+    else:
+        return "".join(data)
 
 ##
 # Generic element structure builder.  This builder converts a sequence
@@ -1114,20 +1104,11 @@
             parser.StartElementHandler = self._start_list
         except AttributeError:
             pass
-        encoding = None
-        if not parser.returns_unicode:
-            encoding = "utf-8"
+        encoding = "utf-8"
         # target.xml(encoding, None)
         self._doctype = None
         self.entity = {}
 
-    def _fixtext(self, text):
-        # convert text string to ascii, if possible
-        try:
-            return _encode(text, "ascii")
-        except UnicodeError:
-            return text
-
     def _fixname(self, key):
         # expand qname, and convert name string to ascii, if possible
         try:
@@ -1136,7 +1117,7 @@
             name = key
             if "}" in name:
                 name = "{" + name
-            self._names[key] = name = self._fixtext(name)
+            self._names[key] = name
         return name
 
     def _start(self, tag, attrib_in):
@@ -1144,7 +1125,7 @@
         tag = fixname(tag)
         attrib = {}
         for key, value in attrib_in.items():
-            attrib[fixname(key)] = self._fixtext(value)
+            attrib[fixname(key)] = value
         return self._target.start(tag, attrib)
 
     def _start_list(self, tag, attrib_in):
@@ -1153,11 +1134,11 @@
         attrib = {}
         if attrib_in:
             for i in range(0, len(attrib_in), 2):
-                attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])
+                attrib[fixname(attrib_in[i])] = attrib_in[i+1]
         return self._target.start(tag, attrib)
 
     def _data(self, text):
-        return self._target.data(self._fixtext(text))
+        return self._target.data(text)
 
     def _end(self, tag):
         return self._target.end(self._fixname(tag))

Modified: python/branches/py3k-buffer/Lib/xml/sax/__init__.py
==============================================================================
--- python/branches/py3k-buffer/Lib/xml/sax/__init__.py	(original)
+++ python/branches/py3k-buffer/Lib/xml/sax/__init__.py	Fri Aug 17 20:48:09 2007
@@ -33,10 +33,7 @@
     parser.parse(source)
 
 def parseString(string, handler, errorHandler=ErrorHandler()):
-    try:
-        from cStringIO import StringIO
-    except ImportError:
-        from StringIO import StringIO
+    from io import BytesIO
 
     if errorHandler is None:
         errorHandler = ErrorHandler()
@@ -45,7 +42,7 @@
     parser.setErrorHandler(errorHandler)
 
     inpsrc = InputSource()
-    inpsrc.setByteStream(StringIO(string))
+    inpsrc.setByteStream(BytesIO(string))
     parser.parse(inpsrc)
 
 # this is the parser list used by the make_parser function if no

Modified: python/branches/py3k-buffer/Lib/xmlrpclib.py
==============================================================================
--- python/branches/py3k-buffer/Lib/xmlrpclib.py	(original)
+++ python/branches/py3k-buffer/Lib/xmlrpclib.py	Fri Aug 17 20:48:09 2007
@@ -165,7 +165,7 @@
 def _stringify(string):
     # convert to 7-bit ascii if possible
     try:
-        return string.encode("ascii")
+        return string.decode("ascii")
     except UnicodeError:
         return string
 
@@ -384,11 +384,13 @@
         return self.data != other
 
     def decode(self, data):
-        self.data = base64.decodestring(data)
+        self.data = str8(base64.decodestring(data))
 
     def encode(self, out):
         out.write("<value><base64>\n")
-        base64.encode(io.StringIO(self.data), out)
+        encoded = base64.encodestring(self.data)
+        out.write(encoded.decode('ascii'))
+        out.write('\n')
         out.write("</base64></value>\n")
 
 def _binary(data):
@@ -485,8 +487,6 @@
             parser.EndElementHandler = target.end
             parser.CharacterDataHandler = target.data
             encoding = None
-            if not parser.returns_unicode:
-                encoding = "utf-8"
             target.xml(encoding, None)
 
         def feed(self, data):
@@ -617,7 +617,6 @@
     dispatch[str8] = dump_string
 
     def dump_unicode(self, value, write, escape=escape):
-        value = value.encode(self.encoding)
         write("<value><string>")
         write(escape(value))
         write("</string></value>\n")
@@ -646,9 +645,7 @@
         write("<value><struct>\n")
         for k, v in value.items():
             write("<member>\n")
-            if isinstance(k, basestring):
-                k = k.encode(self.encoding)
-            else:
+            if not isinstance(k, basestring):
                 raise TypeError, "dictionary key must be string"
             write("<name>%s</name>\n" % escape(k))
             dump(v, write)

Deleted: /python/branches/py3k-buffer/Mac/Demo/sound/morse.py
==============================================================================
--- /python/branches/py3k-buffer/Mac/Demo/sound/morse.py	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,180 +0,0 @@
-import sys, math, audiodev
-
-DOT = 30
-DAH = 80
-OCTAVE = 2                              # 1 == 441 Hz, 2 == 882 Hz, ...
-SAMPWIDTH = 2
-FRAMERATE = 44100
-BASEFREQ = 441
-QSIZE = 20000
-
-morsetab = {
-        'A': '.-',              'a': '.-',
-        'B': '-...',            'b': '-...',
-        'C': '-.-.',            'c': '-.-.',
-        'D': '-..',             'd': '-..',
-        'E': '.',               'e': '.',
-        'F': '..-.',            'f': '..-.',
-        'G': '--.',             'g': '--.',
-        'H': '....',            'h': '....',
-        'I': '..',              'i': '..',
-        'J': '.---',            'j': '.---',
-        'K': '-.-',             'k': '-.-',
-        'L': '.-..',            'l': '.-..',
-        'M': '--',              'm': '--',
-        'N': '-.',              'n': '-.',
-        'O': '---',             'o': '---',
-        'P': '.--.',            'p': '.--.',
-        'Q': '--.-',            'q': '--.-',
-        'R': '.-.',             'r': '.-.',
-        'S': '...',             's': '...',
-        'T': '-',               't': '-',
-        'U': '..-',             'u': '..-',
-        'V': '...-',            'v': '...-',
-        'W': '.--',             'w': '.--',
-        'X': '-..-',            'x': '-..-',
-        'Y': '-.--',            'y': '-.--',
-        'Z': '--..',            'z': '--..',
-        '0': '-----',
-        '1': '.----',
-        '2': '..---',
-        '3': '...--',
-        '4': '....-',
-        '5': '.....',
-        '6': '-....',
-        '7': '--...',
-        '8': '---..',
-        '9': '----.',
-        ',': '--..--',
-        '.': '.-.-.-',
-        '?': '..--..',
-        ';': '-.-.-.',
-        ':': '---...',
-        "'": '.----.',
-        '-': '-....-',
-        '/': '-..-.',
-        '(': '-.--.-',
-        ')': '-.--.-',
-        '_': '..--.-',
-        ' ': ' '
-}
-
-# If we play at 44.1 kHz (which we do), then if we produce one sine
-# wave in 100 samples, we get a tone of 441 Hz.  If we produce two
-# sine waves in these 100 samples, we get a tone of 882 Hz.  882 Hz
-# appears to be a nice one for playing morse code.
-def mkwave(octave):
-    global sinewave, nowave
-    sinewave = ''
-    n = int(FRAMERATE / BASEFREQ)
-    for i in range(n):
-        val = int(math.sin(2 * math.pi * i * octave / n) * 0x7fff)
-        sample = chr((val >> 8) & 255) + chr(val & 255)
-        sinewave = sinewave + sample[:SAMPWIDTH]
-    nowave = '\0' * (n*SAMPWIDTH)
-
-mkwave(OCTAVE)
-
-class BufferedAudioDev:
-    def __init__(self, *args):
-        import audiodev
-        self._base = audiodev.AudioDev(*args)
-        self._buffer = []
-        self._filled = 0
-        self._addmethods(self._base, self._base.__class__)
-    def _addmethods(self, inst, cls):
-        for name in cls.__dict__.keys():
-            if not hasattr(self, name):
-                try:
-                    setattr(self, name, getattr(inst, name))
-                except:
-                    pass
-        for basecls in cls.__bases__:
-            self._addmethods(self, inst, basecls)
-    def writeframesraw(self, frames):
-        self._buffer.append(frames)
-        self._filled = self._filled + len(frames)
-        if self._filled >= QSIZE:
-            self.flush()
-    def wait(self):
-        self.flush()
-        self._base.wait()
-    def flush(self):
-        print 'flush: %d blocks, %d bytes' % (len(self._buffer), self._filled)
-        if self._buffer:
-            import string
-            self._base.writeframes(string.joinfields(self._buffer, ''))
-            self._buffer = []
-            self._filled = 0
-
-def main(args = sys.argv[1:]):
-    import getopt, string
-    try:
-        opts, args = getopt.getopt(args, 'o:p:')
-    except getopt.error:
-        sys.stderr.write('Usage ' + sys.argv[0] +
-                         ' [ -o outfile ] [ args ] ...\n')
-        sys.exit(1)
-    dev = None
-    for o, a in opts:
-        if o == '-o':
-            import aifc
-            dev = aifc.open(a, 'w')
-            dev.setframerate(FRAMERATE)
-            dev.setsampwidth(SAMPWIDTH)
-            dev.setnchannels(1)
-        if o == '-p':
-            mkwave(string.atoi(a))
-    if not dev:
-        dev = BufferedAudioDev()
-        dev.setoutrate(FRAMERATE)
-        dev.setsampwidth(SAMPWIDTH)
-        dev.setnchannels(1)
-        dev.close = dev.stop
-    if args:
-        line = string.join(args)
-    else:
-        line = sys.stdin.readline()
-    while line:
-        print line
-        mline = morse(line)
-        print mline
-        play(mline, dev)
-        if hasattr(dev, 'wait'):
-            dev.wait()
-        if not args:
-            line = sys.stdin.readline()
-        else:
-            line = ''
-    dev.close()
-
-# Convert a string to morse code with \001 between the characters in
-# the string.
-def morse(line):
-    res = ''
-    for c in line:
-        try:
-            res = res + morsetab[c] + '\001'
-        except KeyError:
-            pass
-    return res
-
-# Play a line of morse code.
-def play(line, dev):
-    for c in line:
-        if c == '.':
-            sine(dev, DOT)
-        elif c == '-':
-            sine(dev, DAH)
-        else:
-            pause(dev, DAH)
-        pause(dev, DOT)
-
-def sine(dev, length):
-    dev.writeframesraw(sinewave*length)
-
-def pause(dev, length):
-    dev.writeframesraw(nowave*length)
-
-if __name__ == '__main__' or sys.argv[0] == __name__:
-    main()

Modified: python/branches/py3k-buffer/Mac/Modules/ae/_AEmodule.c
==============================================================================
--- python/branches/py3k-buffer/Mac/Modules/ae/_AEmodule.c	(original)
+++ python/branches/py3k-buffer/Mac/Modules/ae/_AEmodule.c	Fri Aug 17 20:48:09 2007
@@ -835,9 +835,9 @@
 	OSErr err;
 
 	size = AEGetDescDataSize(&self->ob_itself);
-	if ( (res = PyString_FromStringAndSize(NULL, size)) == NULL )
+	if ( (res = PyBytes_FromStringAndSize(NULL, size)) == NULL )
 		return NULL;
-	if ( (ptr = PyString_AsString(res)) == NULL )
+	if ( (ptr = PyBytes_AsString(res)) == NULL )
 		return NULL;
 	if ( (err=AEGetDescData(&self->ob_itself, ptr, size)) < 0 )
 		return PyMac_Error(err);

Modified: python/branches/py3k-buffer/Makefile.pre.in
==============================================================================
--- python/branches/py3k-buffer/Makefile.pre.in	(original)
+++ python/branches/py3k-buffer/Makefile.pre.in	Fri Aug 17 20:48:09 2007
@@ -296,7 +296,6 @@
 		Objects/floatobject.o \
 		Objects/frameobject.o \
 		Objects/funcobject.o \
-		Objects/intobject.o \
 		Objects/iterobject.o \
 		Objects/listobject.o \
 		Objects/longobject.o \
@@ -610,7 +609,7 @@
 
 QUICKTESTOPTS=	$(TESTOPTS) -x test_thread test_signal test_strftime \
 		test_unicodedata test_re test_sre test_select test_poll \
-		test_linuxaudiodev test_struct test_sunaudiodev test_zlib
+		test_struct test_zlib
 quicktest:	all platform
 		-find $(srcdir)/Lib -name '*.py[co]' -print | xargs rm -f
 		-$(TESTPYTHON) $(TESTPROG) $(QUICKTESTOPTS)

Modified: python/branches/py3k-buffer/Misc/ACKS
==============================================================================
--- python/branches/py3k-buffer/Misc/ACKS	(original)
+++ python/branches/py3k-buffer/Misc/ACKS	Fri Aug 17 20:48:09 2007
@@ -134,6 +134,7 @@
 Dave Cole
 Benjamin Collar
 Jeffery Collins
+Paul Colomiets
 Matt Conway
 David M. Cooke
 Greg Copeland
@@ -523,6 +524,7 @@
 Brian Quinlan
 Anders Qvist
 Burton Radons
+Antti Rasinen
 Eric Raymond
 Edward K. Ream
 Marc Recht

Modified: python/branches/py3k-buffer/Misc/BeOS-setup.py
==============================================================================
--- python/branches/py3k-buffer/Misc/BeOS-setup.py	(original)
+++ python/branches/py3k-buffer/Misc/BeOS-setup.py	Fri Aug 17 20:48:09 2007
@@ -230,10 +230,6 @@
         # Fred Drake's interface to the Python parser
         exts.append( Extension('parser', ['parsermodule.c']) )
 
-        # cStringIO and cPickle
-        exts.append( Extension('cStringIO', ['cStringIO.c']) )
-        exts.append( Extension('cPickle', ['cPickle.c']) )
-
         # Memory-mapped files (also works on Win32).
         exts.append( Extension('mmap', ['mmapmodule.c']) )
 
@@ -445,15 +441,6 @@
                                    define_macros = expat_defs,
                                    libraries = ['expat']) )
 
-        # Platform-specific libraries
-        if platform == 'linux2':
-            # Linux-specific modules
-            exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
-
-        if platform == 'sunos5':
-            # SunOS specific modules
-            exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
-
         self.extensions.extend(exts)
 
         # Call the method for detecting whether _tkinter can be compiled

Modified: python/branches/py3k-buffer/Misc/NEWS
==============================================================================
--- python/branches/py3k-buffer/Misc/NEWS	(original)
+++ python/branches/py3k-buffer/Misc/NEWS	Fri Aug 17 20:48:09 2007
@@ -26,6 +26,8 @@
 Core and Builtins
 -----------------
 
+- PEP 3120: Change default encoding to UTF-8.
+
 - PEP 3123: Use proper C inheritance for PyObject.
 
 - Removed the __oct__ and __hex__ special methods and added a bin()
@@ -184,8 +186,12 @@
   AST -> bytecode mechanism.
 
 - Removed these modules:
-  * Bastion, bsddb185, exceptions, md5, MimeWriter, mimify, popen2, rexec,
-    sets, sha, stringold, strop, timing, xmllib.
+  * audiodev, Bastion, bsddb185, exceptions, linuxaudiodev,
+    md5, MimeWriter, mimify, popen2,
+    rexec, sets, sha, stringold, strop, sunaudiodev, timing, xmllib.
+
+- Moved these modules to Tools/Demos:
+  * toaiff
 
 - Remove obsolete IRIX modules: al/AL, cd/CD, cddb, cdplayer, cl/CL, DEVICE,
   ERRNO, FILE, fl/FL, flp, fm, GET, gl/GL, GLWS, IN, imgfile, IOCTL, jpeg,

Modified: python/branches/py3k-buffer/Misc/cheatsheet
==============================================================================
--- python/branches/py3k-buffer/Misc/cheatsheet	(original)
+++ python/branches/py3k-buffer/Misc/cheatsheet	Fri Aug 17 20:48:09 2007
@@ -1808,7 +1808,6 @@
 asynchat         Support for 'chat' style protocols
 asyncore         Asynchronous File I/O (in select style)
 atexit           Register functions to be called at exit of Python interpreter.
-audiodev         Audio support for a few platforms.
 base64           Conversions to/from base64 RFC-MIME transport encoding .
 BaseHTTPServer   Base class forhttp services.
 Bastion          "Bastionification" utility (control access to instance vars)
@@ -1871,7 +1870,6 @@
 inspect          Tool for probing live Python objects.
 keyword          List of Python keywords.
 linecache        Cache lines from files.
-linuxaudiodev    Lunix /dev/audio support.
 locale           Support for number formatting using the current locale
                  settings.
 logging          Python logging facility.
@@ -1946,7 +1944,6 @@
 textwrap         Object for wrapping and filling text.
 threading        Proposed new higher-level threading interfaces
 threading_api    (doc of the threading module)
-toaiff           Convert "arbitrary" sound files to AIFF files .
 token            Tokens (from "token.h").
 tokenize         Compiles a regular expression that recognizes Python tokens.
 traceback        Format and print Python stack traces.
@@ -2042,10 +2039,6 @@
             DEVICE      More constants for gl
             imgfile     Imglib image file interface
 
-* Suns *
-
-            sunaudiodev Access to sun audio interface
-
 
 Workspace exploration and idiom hints
 

Modified: python/branches/py3k-buffer/Modules/Setup.dist
==============================================================================
--- python/branches/py3k-buffer/Modules/Setup.dist	(original)
+++ python/branches/py3k-buffer/Modules/Setup.dist	Fri Aug 17 20:48:09 2007
@@ -236,17 +236,6 @@
 #_sha shamodule.c
 
 
-# SunOS specific modules -- off by default:
-
-#sunaudiodev sunaudiodev.c
-
-
-# A Linux specific module -- off by default; this may also work on 
-# some *BSDs.
-
-#linuxaudiodev linuxaudiodev.c
-
-
 # The _tkinter module.
 #
 # The command for _tkinter is long and site specific.  Please

Modified: python/branches/py3k-buffer/Modules/_bsddb.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_bsddb.c	(original)
+++ python/branches/py3k-buffer/Modules/_bsddb.c	Fri Aug 17 20:48:09 2007
@@ -99,7 +99,7 @@
 #endif
 
 #define PY_BSDDB_VERSION "4.5.0"
-static char *rcs_id = "$Id$";
+static char *svn_id = "$Id$";
 
 
 #if (PY_VERSION_HEX < 0x02050000)
@@ -413,7 +413,7 @@
         /* no need to do anything, the structure has already been zeroed */
     }
 
-    else if (PyString_Check(keyobj)) {
+    else if (PyBytes_Check(keyobj)) {
         /* verify access method type */
         type = _DB_get_type(self);
         if (type == -1)
@@ -425,8 +425,8 @@
             return 0;
         }
 
-        key->data = PyString_AS_STRING(keyobj);
-        key->size = PyString_GET_SIZE(keyobj);
+        key->data = PyBytes_AS_STRING(keyobj);
+        key->size = PyBytes_GET_SIZE(keyobj);
     }
 
     else if (PyInt_Check(keyobj)) {
@@ -460,7 +460,7 @@
     }
     else {
         PyErr_Format(PyExc_TypeError,
-                     "String or Integer object expected for key, %s found",
+                     "Bytes or Integer object expected for key, %s found",
                      Py_Type(keyobj)->tp_name);
         return 0;
     }
@@ -721,13 +721,13 @@
 
         case DB_RECNO:
         case DB_QUEUE:
-            retval = Py_BuildValue("is#", *((db_recno_t*)key.data),
+            retval = Py_BuildValue("iy#", *((db_recno_t*)key.data),
                                    data.data, data.size);
             break;
         case DB_HASH:
         case DB_BTREE:
         default:
-            retval = Py_BuildValue("s#s#", key.data, key.size,
+            retval = Py_BuildValue("y#y#", key.data, key.size,
                                    data.data, data.size);
             break;
         }
@@ -1179,10 +1179,10 @@
         MYDB_BEGIN_BLOCK_THREADS;
 
         if (type == DB_RECNO || type == DB_QUEUE)
-            args = Py_BuildValue("(ls#)", *((db_recno_t*)priKey->data),
+            args = Py_BuildValue("(ly#)", *((db_recno_t*)priKey->data),
                                  priData->data, priData->size);
         else
-            args = Py_BuildValue("(s#s#)", priKey->data, priKey->size,
+            args = Py_BuildValue("(y#y#)", priKey->data, priKey->size,
                                  priData->data, priData->size);
         if (args != NULL) {
                 result = PyEval_CallObject(callback, args);
@@ -1196,18 +1196,13 @@
         else if (PyInt_Check(result)) {
             retval = PyInt_AsLong(result);
         }
-        else if (PyString_Check(result)) {
+        else if (PyBytes_Check(result)) {
             char* data;
             Py_ssize_t size;
 
             CLEAR_DBT(*secKey);
-#if PYTHON_API_VERSION <= 1007
-            /* 1.5 compatibility */
-            size = PyString_Size(result);
-            data = PyString_AsString(result);
-#else
-            PyString_AsStringAndSize(result, &data, &size);
-#endif
+            size = PyBytes_Size(result);
+            data = PyBytes_AsString(result);
             secKey->flags = DB_DBT_APPMALLOC;   /* DB will free */
             secKey->data = malloc(size);        /* TODO, check this */
 	    if (secKey->data) {
@@ -1224,7 +1219,7 @@
         else {
             PyErr_SetString(
                PyExc_TypeError,
-               "DB associate callback should return DB_DONOTINDEX or string.");
+               "DB associate callback should return DB_DONOTINDEX or bytes.");
             PyErr_Print();
         }
 
@@ -1392,7 +1387,7 @@
         retval = Py_None;
     }
     else if (!err) {
-        retval = Py_BuildValue("s#s#", key.data, key.size, data.data,
+        retval = Py_BuildValue("y#y#", key.data, key.size, data.data,
                                data.size);
         FREE_DBT(key);
         FREE_DBT(data);
@@ -1545,10 +1540,10 @@
     }
     else if (!err) {
         if (flags & DB_SET_RECNO) /* return both key and data */
-            retval = Py_BuildValue("s#s#", key.data, key.size, data.data,
+            retval = Py_BuildValue("y#y#", key.data, key.size, data.data,
                                    data.size);
         else /* return just the data */
-            retval = PyString_FromStringAndSize((char*)data.data, data.size);
+            retval = PyBytes_FromStringAndSize((char*)data.data, data.size);
         FREE_DBT(data);
     }
     FREE_DBT(key);
@@ -1617,13 +1612,13 @@
     else if (!err) {
         PyObject *pkeyObj;
         PyObject *dataObj;
-        dataObj = PyString_FromStringAndSize(data.data, data.size);
+        dataObj = PyBytes_FromStringAndSize(data.data, data.size);
 
         if (self->primaryDBType == DB_RECNO ||
             self->primaryDBType == DB_QUEUE)
             pkeyObj = PyInt_FromLong(*(int *)pkey.data);
         else
-            pkeyObj = PyString_FromStringAndSize(pkey.data, pkey.size);
+            pkeyObj = PyBytes_FromStringAndSize(pkey.data, pkey.size);
 
         if (flags & DB_SET_RECNO) /* return key , pkey and data */
         {
@@ -1632,7 +1627,7 @@
             if (type == DB_RECNO || type == DB_QUEUE)
                 keyObj = PyInt_FromLong(*(int *)key.data);
             else
-                keyObj = PyString_FromStringAndSize(key.data, key.size);
+                keyObj = PyBytes_FromStringAndSize(key.data, key.size);
 #if (PY_VERSION_HEX >= 0x02040000)
             retval = PyTuple_Pack(3, keyObj, pkeyObj, dataObj);
 #else
@@ -1753,7 +1748,7 @@
     }
     else if (!err) {
         /* XXX(nnorwitz): can we do: retval = dataobj; Py_INCREF(retval); */
-        retval = PyString_FromStringAndSize((char*)data.data, data.size);
+        retval = PyBytes_FromStringAndSize((char*)data.data, data.size);
 
         /* Even though the flags require DB_DBT_MALLOC, data is not always
            allocated.  4.4: allocated, 4.5: *not* allocated. :-( */
@@ -2142,7 +2137,7 @@
     } else {
 	MYDB_BEGIN_BLOCK_THREADS;
 
-	args = Py_BuildValue("s#s#", leftKey->data, leftKey->size,
+	args = Py_BuildValue("y#y#", leftKey->data, leftKey->size,
 			     rightKey->data, rightKey->size);
 	if (args != NULL) {
 		/* XXX(twouters) I highly doubt this INCREF is correct */
@@ -2801,7 +2796,7 @@
         retval = NULL;
     }
     else {
-        retval = PyString_FromStringAndSize((char*)data.data, data.size);
+        retval = PyBytes_FromStringAndSize((char*)data.data, data.size);
         FREE_DBT(data);
     }
 
@@ -2952,7 +2947,7 @@
             case DB_BTREE:
             case DB_HASH:
             default:
-                item = PyString_FromStringAndSize((char*)key.data, key.size);
+                item = PyBytes_FromStringAndSize((char*)key.data, key.size);
                 break;
             case DB_RECNO:
             case DB_QUEUE:
@@ -2962,7 +2957,7 @@
             break;
 
         case _VALUES_LIST:
-            item = PyString_FromStringAndSize((char*)data.data, data.size);
+            item = PyBytes_FromStringAndSize((char*)data.data, data.size);
             break;
 
         case _ITEMS_LIST:
@@ -2970,12 +2965,12 @@
             case DB_BTREE:
             case DB_HASH:
             default:
-                item = Py_BuildValue("s#s#", key.data, key.size, data.data,
+                item = Py_BuildValue("y#y#", key.data, key.size, data.data,
                                      data.size);
                 break;
             case DB_RECNO:
             case DB_QUEUE:
-                item = Py_BuildValue("is#", *((db_recno_t*)key.data),
+                item = Py_BuildValue("iy#", *((db_recno_t*)key.data),
                                      data.data, data.size);
                 break;
             }
@@ -3219,12 +3214,12 @@
         case DB_BTREE:
         case DB_HASH:
         default:
-            retval = Py_BuildValue("s#s#", key.data, key.size,
+            retval = Py_BuildValue("y#y#", key.data, key.size,
                                    data.data, data.size);
             break;
         case DB_RECNO:
         case DB_QUEUE:
-            retval = Py_BuildValue("is#", *((db_recno_t*)key.data),
+            retval = Py_BuildValue("iy#", *((db_recno_t*)key.data),
                                    data.data, data.size);
             break;
         }
@@ -3303,13 +3298,13 @@
     else {
         PyObject *pkeyObj;
         PyObject *dataObj;
-        dataObj = PyString_FromStringAndSize(data.data, data.size);
+        dataObj = PyBytes_FromStringAndSize(data.data, data.size);
 
         if (self->mydb->primaryDBType == DB_RECNO ||
             self->mydb->primaryDBType == DB_QUEUE)
             pkeyObj = PyInt_FromLong(*(int *)pkey.data);
         else
-            pkeyObj = PyString_FromStringAndSize(pkey.data, pkey.size);
+            pkeyObj = PyBytes_FromStringAndSize(pkey.data, pkey.size);
 
         if (key.data && key.size) /* return key, pkey and data */
         {
@@ -3318,7 +3313,7 @@
             if (type == DB_RECNO || type == DB_QUEUE)
                 keyObj = PyInt_FromLong(*(int *)key.data);
             else
-                keyObj = PyString_FromStringAndSize(key.data, key.size);
+                keyObj = PyBytes_FromStringAndSize(key.data, key.size);
 #if (PY_VERSION_HEX >= 0x02040000)
             retval = PyTuple_Pack(3, keyObj, pkeyObj, dataObj);
 #else
@@ -3488,12 +3483,12 @@
         case DB_BTREE:
         case DB_HASH:
         default:
-            retval = Py_BuildValue("s#s#", key.data, key.size,
+            retval = Py_BuildValue("y#y#", key.data, key.size,
                                    data.data, data.size);
             break;
         case DB_RECNO:
         case DB_QUEUE:
-            retval = Py_BuildValue("is#", *((db_recno_t*)key.data),
+            retval = Py_BuildValue("iy#", *((db_recno_t*)key.data),
                                    data.data, data.size);
             break;
         }
@@ -3561,12 +3556,12 @@
         case DB_BTREE:
         case DB_HASH:
         default:
-            retval = Py_BuildValue("s#s#", key.data, key.size,
+            retval = Py_BuildValue("y#y#", key.data, key.size,
                                    data.data, data.size);
             break;
         case DB_RECNO:
         case DB_QUEUE:
-            retval = Py_BuildValue("is#", *((db_recno_t*)key.data),
+            retval = Py_BuildValue("iy#", *((db_recno_t*)key.data),
                                    data.data, data.size);
             break;
         }
@@ -3616,12 +3611,12 @@
         case DB_BTREE:
         case DB_HASH:
         default:
-            retval = Py_BuildValue("s#s#", key.data, key.size,
+            retval = Py_BuildValue("y#y#", key.data, key.size,
                                    data.data, data.size);
             break;
         case DB_RECNO:
         case DB_QUEUE:
-            retval = Py_BuildValue("is#", *((db_recno_t*)key.data),
+            retval = Py_BuildValue("iy#", *((db_recno_t*)key.data),
                                    data.data, data.size);
             break;
         }
@@ -3750,7 +3745,7 @@
         retval = NULL;
     }
     else {  /* Can only be used for BTrees, so no need to return int key */
-        retval = Py_BuildValue("s#s#", key.data, key.size,
+        retval = Py_BuildValue("y#y#", key.data, key.size,
                                data.data, data.size);
         FREE_DBT(data);
     }
@@ -3819,7 +3814,7 @@
         retval = NULL;
     }
     else {
-        retval = Py_BuildValue("s#", key.data, key.size);
+        retval = Py_BuildValue("y#", key.data, key.size);
         FREE_DBT(key);
     }
 
@@ -4610,7 +4605,7 @@
     if (log_list) {
         char **log_list_start;
         for (log_list_start = log_list; *log_list != NULL; ++log_list) {
-            item = PyString_FromString (*log_list);
+            item = PyUnicode_FromString (*log_list);
             if (item == NULL) {
                 Py_DECREF(list);
                 list = NULL;
@@ -4910,7 +4905,7 @@
 
     RETURN_IF_ERR();
 
-    return PyString_FromStringAndSize(key.data, key.size);
+    return PyBytes_FromStringAndSize(key.data, key.size);
 }
 
 static PyObject*
@@ -5335,7 +5330,7 @@
         if (self->db_env->db_home == NULL) {
             RETURN_NONE();
         }
-        return PyString_FromString(self->db_env->db_home);
+        return PyUnicode_FromString(self->db_env->db_home);
     }
 
     return Py_FindMethod(DBEnv_methods, (PyObject* )self, name);
@@ -5654,9 +5649,9 @@
 {
     PyObject* m;
     PyObject* d;
-    PyObject* pybsddb_version_s = PyString_FromString( PY_BSDDB_VERSION );
-    PyObject* db_version_s = PyString_FromString( DB_VERSION_STRING );
-    PyObject* cvsid_s = PyString_FromString( rcs_id );
+    PyObject* pybsddb_version_s = PyUnicode_FromString(PY_BSDDB_VERSION);
+    PyObject* db_version_s = PyUnicode_FromString(DB_VERSION_STRING);
+    PyObject* svnid_s = PyUnicode_FromString(svn_id);
 
     /* Initialize the type of the new type objects here; doing it here
        is required for portability to Windows without requiring C++. */
@@ -5683,12 +5678,12 @@
     /* Add some symbolic constants to the module */
     d = PyModule_GetDict(m);
     PyDict_SetItemString(d, "__version__", pybsddb_version_s);
-    PyDict_SetItemString(d, "cvsid", cvsid_s);
+    PyDict_SetItemString(d, "cvsid", svnid_s);
     PyDict_SetItemString(d, "DB_VERSION_STRING", db_version_s);
     Py_DECREF(pybsddb_version_s);
     pybsddb_version_s = NULL;
-    Py_DECREF(cvsid_s);
-    cvsid_s = NULL;
+    Py_DECREF(svnid_s);
+    svnid_s = NULL;
     Py_DECREF(db_version_s);
     db_version_s = NULL;
 

Modified: python/branches/py3k-buffer/Modules/_collectionsmodule.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_collectionsmodule.c	(original)
+++ python/branches/py3k-buffer/Modules/_collectionsmodule.c	Fri Aug 17 20:48:09 2007
@@ -633,46 +633,6 @@
 	return result;
 }
 
-static int
-deque_tp_print(PyObject *deque, FILE *fp, int flags)
-{
-	PyObject *it, *item;
-	char *emit = "";	/* No separator emitted on first pass */
-	char *separator = ", ";
-	int i;
-
-	i = Py_ReprEnter(deque);
-	if (i != 0) {
-		if (i < 0)
-			return i;
-		fputs("[...]", fp);
-		return 0;
-	}
-
-	it = PyObject_GetIter(deque);
-	if (it == NULL)
-		return -1;
-
-	fputs("deque([", fp);
-	while ((item = PyIter_Next(it)) != NULL) {
-		fputs(emit, fp);
-		emit = separator;
-		if (PyObject_Print(item, fp, 0) != 0) {
-			Py_DECREF(item);
-			Py_DECREF(it);
-			Py_ReprLeave(deque);
-			return -1;
-		}
-		Py_DECREF(item);
-	}
-	Py_ReprLeave(deque);
-	Py_DECREF(it);
-	if (PyErr_Occurred())
-		return -1;
-	fputs("])", fp);
-	return 0;
-}
-
 static PyObject *
 deque_richcompare(PyObject *v, PyObject *w, int op)
 {
@@ -824,7 +784,7 @@
 	0,				/* tp_itemsize */
 	/* methods */
 	(destructor)deque_dealloc,	/* tp_dealloc */
-	deque_tp_print,			/* tp_print */
+	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
 	0,				/* tp_compare */
@@ -1179,22 +1139,6 @@
 	PyDict_Type.tp_dealloc((PyObject *)dd);
 }
 
-static int
-defdict_print(defdictobject *dd, FILE *fp, int flags)
-{
-	int sts;
-	fprintf(fp, "defaultdict(");
-	if (dd->default_factory == NULL)
-		fprintf(fp, "None");
-	else {
-		PyObject_Print(dd->default_factory, fp, 0);
-	}
-	fprintf(fp, ", ");
-	sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
-	fprintf(fp, ")");
-	return sts;
-}
-
 static PyObject *
 defdict_repr(defdictobject *dd)
 {
@@ -1277,7 +1221,7 @@
 	0,				/* tp_itemsize */
 	/* methods */
 	(destructor)defdict_dealloc,	/* tp_dealloc */
-	(printfunc)defdict_print,	/* tp_print */
+	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
 	0,				/* tp_compare */

Modified: python/branches/py3k-buffer/Modules/_csv.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_csv.c	(original)
+++ python/branches/py3k-buffer/Modules/_csv.c	Fri Aug 17 20:48:09 2007
@@ -93,11 +93,11 @@
 
 typedef struct {
         PyObject_HEAD
-        
+
 	int doublequote;	/* is " represented by ""? */
-	char delimiter;		/* field separator */
-	char quotechar;		/* quote character */
-	char escapechar;	/* escape character */
+	Py_UNICODE delimiter;	/* field separator */
+	Py_UNICODE quotechar;	/* quote character */
+	Py_UNICODE escapechar;	/* escape character */
 	int skipinitialspace;	/* ignore spaces following delimiter? */
 	PyObject *lineterminator; /* string to write between records */
 	int quoting;		/* style of quoting to write */
@@ -116,9 +116,9 @@
 
 	PyObject *fields;	/* field list for current record */
 	ParserState state;	/* current CSV parse state */
-	char *field;		/* build current field in here */
+	Py_UNICODE *field;	/* build current field in here */
 	int field_size;		/* size of allocated buffer */
-	int field_len;		/* length of current field */
+    Py_ssize_t field_len;	/* length of current field */
 	int numeric_field;	/* treat field as numeric */
 	unsigned long line_num;	/* Source-file line number */
 } ReaderObj;
@@ -134,11 +134,11 @@
 
         DialectObj *dialect;    /* parsing dialect */
 
-	char *rec;		/* buffer for parser.join */
+	Py_UNICODE *rec;	/* buffer for parser.join */
 	int rec_size;		/* size of allocated record */
-	int rec_len;		/* length of record */
+	Py_ssize_t rec_len;	/* length of record */
 	int num_fields;		/* number of fields in record */
-} WriterObj;        
+} WriterObj;
 
 static PyTypeObject Writer_Type;
 
@@ -169,14 +169,14 @@
 }
 
 static PyObject *
-get_nullchar_as_None(char c)
+get_nullchar_as_None(Py_UNICODE c)
 {
         if (c == '\0') {
                 Py_INCREF(Py_None);
                 return Py_None;
         }
         else
-                return PyString_FromStringAndSize((char*)&c, 1);
+                return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1);
 }
 
 static PyObject *
@@ -186,6 +186,12 @@
 }
 
 static PyObject *
+Dialect_get_delimiter(DialectObj *self)
+{
+        return get_nullchar_as_None(self->delimiter);
+}
+
+static PyObject *
 Dialect_get_escapechar(DialectObj *self)
 {
         return get_nullchar_as_None(self->escapechar);
@@ -230,20 +236,21 @@
 }
 
 static int
-_set_char(const char *name, char *target, PyObject *src, char dflt)
+_set_char(const char *name, Py_UNICODE *target, PyObject *src, Py_UNICODE dflt)
 {
 	if (src == NULL)
 		*target = dflt;
 	else {
 		*target = '\0';
 		if (src != Py_None) {
-			const char *buf;
+			Py_UNICODE *buf;
 			Py_ssize_t len;
-			if (PyObject_AsCharBuffer(src, &buf, &len) < 0 ||
-				len > 1) {
+			buf = PyUnicode_AsUnicode(src);
+			len = PyUnicode_GetSize(src);
+			if (buf == NULL || len > 1) {
 				PyErr_Format(PyExc_TypeError,
 					"\"%s\" must be an 1-character string",
-					     name);
+					name);
 				return -1;
 			}
 			if (len > 0)
@@ -257,7 +264,7 @@
 _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
 {
 	if (src == NULL)
-		*target = PyString_FromString(dflt);
+		*target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL);
 	else {
 		if (src == Py_None)
 			*target = NULL;
@@ -291,7 +298,6 @@
 #define D_OFF(x) offsetof(DialectObj, x)
 
 static struct PyMemberDef Dialect_memberlist[] = {
-	{ "delimiter",          T_CHAR, D_OFF(delimiter), READONLY },
 	{ "skipinitialspace",   T_INT, D_OFF(skipinitialspace), READONLY },
 	{ "doublequote",        T_INT, D_OFF(doublequote), READONLY },
 	{ "strict",             T_INT, D_OFF(strict), READONLY },
@@ -299,6 +305,7 @@
 };
 
 static PyGetSetDef Dialect_getsetlist[] = {
+	{ "delimiter",          (getter)Dialect_get_delimiter},
 	{ "escapechar",		(getter)Dialect_get_escapechar},
 	{ "lineterminator",	(getter)Dialect_get_lineterminator},
 	{ "quotechar",		(getter)Dialect_get_quotechar},
@@ -528,7 +535,7 @@
 {
 	PyObject *field;
 
-	field = PyString_FromStringAndSize(self->field, self->field_len);
+	field = PyUnicode_FromUnicode(self->field, self->field_len);
 	if (field == NULL)
 		return -1;
 	self->field_len = 0;
@@ -556,11 +563,12 @@
 		self->field_size = 4096;
 		if (self->field != NULL)
 			PyMem_Free(self->field);
-		self->field = PyMem_Malloc(self->field_size);
+		self->field = PyMem_New(Py_UNICODE, self->field_size);
 	}
 	else {
 		self->field_size *= 2;
-		self->field = PyMem_Realloc(self->field, self->field_size);
+		self->field = PyMem_Resize(self->field, Py_UNICODE,
+					   self->field_size);
 	}
 	if (self->field == NULL) {
 		PyErr_NoMemory();
@@ -570,7 +578,7 @@
 }
 
 static int
-parse_add_char(ReaderObj *self, char c)
+parse_add_char(ReaderObj *self, Py_UNICODE c)
 {
 	if (self->field_len >= field_limit) {
 		PyErr_Format(error_obj, "field larger than field limit (%ld)",
@@ -584,7 +592,7 @@
 }
 
 static int
-parse_process_char(ReaderObj *self, char c)
+parse_process_char(ReaderObj *self, Py_UNICODE c)
 {
         DialectObj *dialect = self->dialect;
 
@@ -771,8 +779,8 @@
 {
         PyObject *lineobj;
         PyObject *fields = NULL;
-        char *line, c;
-	int linelen;
+        Py_UNICODE *line, c;
+        Py_ssize_t linelen;
 
 	if (parse_reset(self) < 0)
 		return NULL;
@@ -785,11 +793,9 @@
 					     "newline inside string");
                         return NULL;
                 }
-		++self->line_num;
-
-                line = PyString_AsString(lineobj);
-		linelen = PyString_Size(lineobj);
-
+                ++self->line_num;
+                line = PyUnicode_AsUnicode(lineobj);
+                linelen = PyUnicode_GetSize(lineobj);
                 if (line == NULL || linelen < 0) {
                         Py_DECREF(lineobj);
                         return NULL;
@@ -861,8 +867,8 @@
 #define R_OFF(x) offsetof(ReaderObj, x)
 
 static struct PyMemberDef Reader_memberlist[] = {
-	{ "dialect", T_OBJECT, R_OFF(dialect), RO },
-	{ "line_num", T_ULONG, R_OFF(line_num), RO },
+	{ "dialect", T_OBJECT, R_OFF(dialect), READONLY },
+	{ "line_num", T_ULONG, R_OFF(line_num), READONLY },
 	{ NULL }
 };
 
@@ -962,12 +968,13 @@
  * record length.
  */
 static int
-join_append_data(WriterObj *self, char *field, int quote_empty,
-		 int *quoted, int copy_phase)
+join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty,
+                 int *quoted, int copy_phase)
 {
         DialectObj *dialect = self->dialect;
-	int i, rec_len;
-	char *lineterm;
+        int i;
+        int rec_len;
+        Py_UNICODE *lineterm;
 
 #define ADDCH(c) \
 	do {\
@@ -976,7 +983,7 @@
 		rec_len++;\
 	} while(0)
 
-	lineterm = PyString_AsString(dialect->lineterminator);
+	lineterm = PyUnicode_AsUnicode(dialect->lineterminator);
 	if (lineterm == NULL)
 		return -1;
 
@@ -991,8 +998,9 @@
 		ADDCH(dialect->quotechar);
 
 	/* Copy/count field data */
-	for (i = 0;; i++) {
-		char c = field[i];
+	/* If field is null just pass over */
+	for (i = 0; field; i++) {
+		Py_UNICODE c = field[i];
 		int want_escape = 0;
 
 		if (c == '\0')
@@ -1000,8 +1008,8 @@
 
 		if (c == dialect->delimiter ||
 		    c == dialect->escapechar ||
-		    c == dialect->quotechar ||
-		    strchr(lineterm, c)) {
+		    c == dialect->quotechar  ||
+		    Py_UNICODE_strchr(lineterm, c)) {
 			if (dialect->quoting == QUOTE_NONE)
 				want_escape = 1;
 			else {
@@ -1033,7 +1041,7 @@
 	if (i == 0 && quote_empty) {
 		if (dialect->quoting == QUOTE_NONE) {
 			PyErr_Format(error_obj,
-                                     "single empty field record must be quoted");
+				"single empty field record must be quoted");
 			return -1;
 		}
 		else
@@ -1058,13 +1066,14 @@
 			self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
 			if (self->rec != NULL)
 				PyMem_Free(self->rec);
-			self->rec = PyMem_Malloc(self->rec_size);
+			self->rec = PyMem_New(Py_UNICODE, self->rec_size);
 		}
 		else {
-			char *old_rec = self->rec;
+			Py_UNICODE* old_rec = self->rec;
 
 			self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
-			self->rec = PyMem_Realloc(self->rec, self->rec_size);
+			self->rec = PyMem_Resize(self->rec, Py_UNICODE,
+                                     self->rec_size);
 			if (self->rec == NULL)
 				PyMem_Free(old_rec);
 		}
@@ -1077,7 +1086,7 @@
 }
 
 static int
-join_append(WriterObj *self, char *field, int *quoted, int quote_empty)
+join_append(WriterObj *self, Py_UNICODE *field, int *quoted, int quote_empty)
 {
 	int rec_len;
 
@@ -1099,9 +1108,9 @@
 join_append_lineterminator(WriterObj *self)
 {
 	int terminator_len;
-	char *terminator;
+	Py_UNICODE *terminator;
 
-	terminator_len = PyString_Size(self->dialect->lineterminator);
+	terminator_len = PyUnicode_GetSize(self->dialect->lineterminator);
 	if (terminator_len == -1)
 		return 0;
 
@@ -1109,10 +1118,11 @@
 	if (!join_check_rec_size(self, self->rec_len + terminator_len))
 		return 0;
 
-	terminator = PyString_AsString(self->dialect->lineterminator); 
+	terminator = PyUnicode_AsUnicode(self->dialect->lineterminator);
 	if (terminator == NULL)
 		return 0;
-	memmove(self->rec + self->rec_len, terminator, terminator_len);
+	memmove(self->rec + self->rec_len, terminator, 
+            sizeof(Py_UNICODE)*terminator_len);
 	self->rec_len += terminator_len;
 
 	return 1;
@@ -1161,26 +1171,27 @@
 			break;
 		}
 
-		if (PyString_Check(field)) {
+		if (PyUnicode_Check(field)) {
 			append_ok = join_append(self,
-						PyString_AS_STRING(field),
-                                                &quoted, len == 1);
+						PyUnicode_AS_UNICODE(field),
+						&quoted, len == 1);
 			Py_DECREF(field);
 		}
 		else if (field == Py_None) {
-			append_ok = join_append(self, "", &quoted, len == 1);
+			append_ok = join_append(self, NULL,
+                                    &quoted, len == 1);
 			Py_DECREF(field);
 		}
 		else {
 			PyObject *str;
 
-			str = PyObject_Str(field);
-			Py_DECREF(field);
+			str = PyObject_Unicode(field);
+ 			Py_DECREF(field);
 			if (str == NULL)
 				return NULL;
-
-			append_ok = join_append(self, PyString_AS_STRING(str), 
-                                                &quoted, len == 1);
+			append_ok = join_append(self,
+						PyUnicode_AS_UNICODE(str),
+						&quoted, len == 1);
 			Py_DECREF(str);
 		}
 		if (!append_ok)
@@ -1192,8 +1203,9 @@
 	if (!join_append_lineterminator(self))
 		return 0;
 
-	return PyObject_CallFunction(self->writeline, 
-                                     "(s#)", self->rec, self->rec_len);
+	return PyObject_CallFunction(self->writeline,
+				     "(u#)", self->rec,
+				     self->rec_len);
 }
 
 PyDoc_STRVAR(csv_writerows_doc,
@@ -1239,7 +1251,7 @@
 #define W_OFF(x) offsetof(WriterObj, x)
 
 static struct PyMemberDef Writer_memberlist[] = {
-	{ "dialect", T_OBJECT, W_OFF(dialect), RO },
+	{ "dialect", T_OBJECT, W_OFF(dialect), READONLY },
 	{ NULL }
 };
 

Modified: python/branches/py3k-buffer/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_ctypes/cfield.c	(original)
+++ python/branches/py3k-buffer/Modules/_ctypes/cfield.c	Fri Aug 17 20:48:09 2007
@@ -1156,7 +1156,7 @@
 static PyObject *
 c_get(void *ptr, Py_ssize_t size)
 {
-	return PyUnicode_FromStringAndSize((char *)ptr, 1);
+	return PyBytes_FromStringAndSize((char *)ptr, 1);
 }
 
 #ifdef CTYPES_UNICODE

Modified: python/branches/py3k-buffer/Modules/_elementtree.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_elementtree.c	(original)
+++ python/branches/py3k-buffer/Modules/_elementtree.c	Fri Aug 17 20:48:09 2007
@@ -1827,31 +1827,6 @@
 
 /* helpers */
 
-LOCAL(int)
-checkstring(const char* string, int size)
-{
-    int i;
-
-    /* check if an 8-bit string contains UTF-8 characters */
-    for (i = 0; i < size; i++)
-        if (string[i] & 0x80)
-            return 1;
-
-    return 0;
-}
-
-LOCAL(PyObject*)
-makestring(const char* string, int size)
-{
-    /* convert a UTF-8 string to either a 7-bit ascii string or a
-       Unicode string */
-
-    if (checkstring(string, size))
-        return PyUnicode_DecodeUTF8(string, size, "strict");
-
-    return PyString_FromStringAndSize(string, size);
-}
-
 LOCAL(PyObject*)
 makeuniversal(XMLParserObject* self, const char* string)
 {
@@ -1897,18 +1872,13 @@
         }
         
         /* decode universal name */
-        /* inline makestring, to avoid duplicating the source string if
-           it's not an utf-8 string */
         p = PyString_AS_STRING(tag);
-        if (checkstring(p, size)) {
-            value = PyUnicode_DecodeUTF8(p, size, "strict");
-            Py_DECREF(tag);
-            if (!value) {
-                Py_DECREF(key);
-                return NULL;
-            }
-        } else
-            value = tag; /* use tag as is */
+        value = PyUnicode_DecodeUTF8(p, size, "strict");
+        Py_DECREF(tag);
+        if (!value) {
+            Py_DECREF(key);
+            return NULL;
+        }
 
         /* add to names dictionary */
         if (PyDict_SetItem(self->names, key, value) < 0) {
@@ -1936,7 +1906,7 @@
     if (data_len < 2 || data_in[0] != '&')
         return;
 
-    key = makestring(data_in + 1, data_len - 2);
+    key = PyUnicode_DecodeUTF8(data_in + 1, data_len - 2, "strict");
     if (!key)
         return;
 
@@ -1985,7 +1955,7 @@
             return;
         while (attrib_in[0] && attrib_in[1]) {
             PyObject* key = makeuniversal(self, attrib_in[0]);
-            PyObject* value = makestring(attrib_in[1], strlen(attrib_in[1]));
+            PyObject* value = PyUnicode_DecodeUTF8(attrib_in[1], strlen(attrib_in[1]), "strict");
             if (!key || !value) {
                 Py_XDECREF(value);
                 Py_XDECREF(key);
@@ -2028,7 +1998,7 @@
     PyObject* data;
     PyObject* res;
 
-    data = makestring(data_in, data_len);
+    data = PyUnicode_DecodeUTF8(data_in, data_len, "strict");
     if (!data)
         return; /* parser will look for errors */
 
@@ -2092,7 +2062,7 @@
     PyObject* res;
 
     if (self->handle_comment) {
-        comment = makestring(comment_in, strlen(comment_in));
+        comment = PyUnicode_DecodeUTF8(comment_in, strlen(comment_in), "strict");
         if (comment) {
             res = PyObject_CallFunction(self->handle_comment, "O", comment);
             Py_XDECREF(res);
@@ -2110,8 +2080,8 @@
     PyObject* res;
 
     if (self->handle_pi) {
-        target = makestring(target_in, strlen(target_in));
-        data = makestring(data_in, strlen(data_in));
+        target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
+        data = PyUnicode_DecodeUTF8(data_in, strlen(data_in), "strict");
         if (target && data) {
             res = PyObject_CallFunction(self->handle_pi, "OO", target, data);
             Py_XDECREF(res);

Modified: python/branches/py3k-buffer/Modules/_fileio.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_fileio.c	(original)
+++ python/branches/py3k-buffer/Modules/_fileio.c	Fri Aug 17 20:48:09 2007
@@ -438,7 +438,7 @@
 	if (!self->readable)
 		return err_mode("reading");
 
-	if (!PyArg_ParseTuple(args, "|i", &size))
+	if (!PyArg_ParseTuple(args, "|n", &size))
 		return NULL;
 
         if (size < 0) {

Modified: python/branches/py3k-buffer/Modules/_hotshot.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_hotshot.c	(original)
+++ python/branches/py3k-buffer/Modules/_hotshot.c	Fri Aug 17 20:48:09 2007
@@ -1266,7 +1266,7 @@
 };
 
 static PyMemberDef logreader_members[] = {
-    {"info", T_OBJECT, offsetof(LogReaderObject, info), RO,
+    {"info", T_OBJECT, offsetof(LogReaderObject, info), READONLY,
      PyDoc_STR("Dictionary mapping informational keys to lists of values.")},
     {NULL}
 };

Modified: python/branches/py3k-buffer/Modules/_sqlite/row.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_sqlite/row.c	(original)
+++ python/branches/py3k-buffer/Modules/_sqlite/row.c	Fri Aug 17 20:48:09 2007
@@ -159,11 +159,6 @@
     return list;
 }
 
-static int pysqlite_row_print(pysqlite_Row* self, FILE *fp, int flags)
-{
-    return (&PyTuple_Type)->tp_print(self->data, fp, flags);
-}
-
 static PyObject* pysqlite_iter(pysqlite_Row* self)
 {
     return PyObject_GetIter(self->data);
@@ -188,7 +183,7 @@
         sizeof(pysqlite_Row),                           /* tp_basicsize */
         0,                                              /* tp_itemsize */
         (destructor)pysqlite_row_dealloc,               /* tp_dealloc */
-        (printfunc)pysqlite_row_print,                  /* tp_print */
+        0,				                /* tp_print */
         0,                                              /* tp_getattr */
         0,                                              /* tp_setattr */
         0,                                              /* tp_compare */

Modified: python/branches/py3k-buffer/Modules/_ssl.c
==============================================================================
--- python/branches/py3k-buffer/Modules/_ssl.c	(original)
+++ python/branches/py3k-buffer/Modules/_ssl.c	Fri Aug 17 20:48:09 2007
@@ -496,7 +496,7 @@
 	if (!PyArg_ParseTuple(args, "|i:read", &len))
 		return NULL;
 
-	if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
+	if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
 		return NULL;
 	
 	/* first check if there are bytes ready to be read */
@@ -518,7 +518,7 @@
 	do {
 		err = 0;
 		Py_BEGIN_ALLOW_THREADS
-		count = SSL_read(self->ssl, PyString_AsString(buf), len);
+		count = SSL_read(self->ssl, PyBytes_AS_STRING(buf), len);
 		err = SSL_get_error(self->ssl, count);
 		Py_END_ALLOW_THREADS
 		if(PyErr_CheckSignals()) {
@@ -545,12 +545,15 @@
 		return PySSL_SetError(self, count);
 	}
 	if (count != len)
-		_PyString_Resize(&buf, count);
+		if (PyBytes_Resize(buf, count) < 0) {
+                        Py_DECREF(buf);
+                        return NULL;
+                }
 	return buf;
 }
 
 PyDoc_STRVAR(PySSL_SSLread_doc,
-"read([len]) -> string\n\
+"read([len]) -> bytes\n\
 \n\
 Read up to len bytes from the SSL socket.");
 

Modified: python/branches/py3k-buffer/Modules/atexitmodule.c
==============================================================================
--- python/branches/py3k-buffer/Modules/atexitmodule.c	(original)
+++ python/branches/py3k-buffer/Modules/atexitmodule.c	Fri Aug 17 20:48:09 2007
@@ -145,6 +145,11 @@
     return func;
 }
 
+PyDoc_STRVAR(atexit_run_exitfuncs__doc__,
+"_run_exitfuncs() -> None\n\
+\n\
+Run all registered exit functions.");
+
 static PyObject *
 atexit_run_exitfuncs(PyObject *self)
 {
@@ -154,6 +159,11 @@
     Py_RETURN_NONE;
 }
 
+PyDoc_STRVAR(atexit_clear__doc__,
+"_clear() -> None\n\
+\n\
+Clear the list of previously registered exit functions.");
+
 static PyObject *
 atexit_clear(PyObject *self)
 {
@@ -172,6 +182,14 @@
     Py_RETURN_NONE;
 }
 
+PyDoc_STRVAR(atexit_unregister__doc__,
+"unregister(func) -> None\n\
+\n\
+Unregister a exit function which was previously registered using\n\
+atexit.register\n\
+\n\
+    func - function to be unregistered");
+
 static PyObject *
 atexit_unregister(PyObject *self, PyObject *func)
 {
@@ -197,11 +215,11 @@
     {"register", (PyCFunction) atexit_register, METH_VARARGS|METH_KEYWORDS,
         atexit_register__doc__},
     {"_clear", (PyCFunction) atexit_clear, METH_NOARGS,
-        NULL},
+        atexit_clear__doc__},
     {"unregister", (PyCFunction) atexit_unregister, METH_O,
-        NULL},
+        atexit_unregister__doc__},
     {"_run_exitfuncs", (PyCFunction) atexit_run_exitfuncs, METH_NOARGS,
-        NULL},
+        atexit_run_exitfuncs__doc__},
     {NULL, NULL}        /* sentinel */
 };
 
@@ -209,10 +227,10 @@
 /* Initialization function. */
 
 PyDoc_STRVAR(atexit__doc__,
-"atexit.py - allow programmer to define multiple exit functions to be executed\
+"allow programmer to define multiple exit functions to be executed\
 upon normal program termination.\n\
 \n\
-One public function, register, is defined.\n\
+Two public functions, register and unregister, are defined.\n\
 ");
 
 PyMODINIT_FUNC

Modified: python/branches/py3k-buffer/Modules/bz2module.c
==============================================================================
--- python/branches/py3k-buffer/Modules/bz2module.c	(original)
+++ python/branches/py3k-buffer/Modules/bz2module.c	Fri Aug 17 20:48:09 2007
@@ -431,7 +431,7 @@
 		goto cleanup;
 	}
 	ret = PyBytes_FromStringAndSize((char *)NULL, buffersize);
-	if (ret == NULL)
+	if (ret == NULL || buffersize == 0)
 		goto cleanup;
 	bytesread = 0;
 
@@ -1624,7 +1624,7 @@
 #define OFF(x) offsetof(BZ2DecompObject, x)
 
 static PyMemberDef BZ2Decomp_members[] = {
-	{"unused_data", T_OBJECT, OFF(unused_data), RO},
+	{"unused_data", T_OBJECT, OFF(unused_data), READONLY},
 	{NULL}	/* Sentinel */
 };
 

Modified: python/branches/py3k-buffer/Modules/cStringIO.c
==============================================================================
--- python/branches/py3k-buffer/Modules/cStringIO.c	(original)
+++ python/branches/py3k-buffer/Modules/cStringIO.c	Fri Aug 17 20:48:09 2007
@@ -664,8 +664,11 @@
   char *buf;
   Py_ssize_t size;
 
-  if (PyObject_AsCharBuffer(s, (const char **)&buf, &size) != 0)
-      return NULL;
+  if (PyObject_AsReadBuffer(s, (const void **)&buf, &size)) {
+    PyErr_Format(PyExc_TypeError, "expected read buffer, %.200s found",
+                 s->ob_type->tp_name);
+    return NULL;
+  }
 
   self = PyObject_New(Iobject, &Itype);
   if (!self) return NULL;

Modified: python/branches/py3k-buffer/Modules/cjkcodecs/_codecs_cn.c
==============================================================================
--- python/branches/py3k-buffer/Modules/cjkcodecs/_codecs_cn.c	(original)
+++ python/branches/py3k-buffer/Modules/cjkcodecs/_codecs_cn.c	Fri Aug 17 20:48:09 2007
@@ -197,6 +197,7 @@
 		REQUIRE_OUTBUF(2)
 
 		GBK_ENCODE(c, code)
+		else TRYMAP_ENC(gb18030ext, code, c);
 		else {
 			const struct _gb18030_to_unibmp_ranges *utrrange;
 

Modified: python/branches/py3k-buffer/Modules/dbmmodule.c
==============================================================================
--- python/branches/py3k-buffer/Modules/dbmmodule.c	(original)
+++ python/branches/py3k-buffer/Modules/dbmmodule.c	Fri Aug 17 20:48:09 2007
@@ -103,8 +103,7 @@
         check_dbmobject_open(dp);
 	drec = dbm_fetch(dp->di_dbm, krec);
 	if ( drec.dptr == 0 ) {
-		PyErr_SetString(PyExc_KeyError,
-				PyString_AS_STRING((PyStringObject *)key));
+		PyErr_SetObject(PyExc_KeyError, key);
 		return NULL;
 	}
 	if ( dbm_error(dp->di_dbm) ) {
@@ -135,8 +134,7 @@
 	if (w == NULL) {
 		if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
 			dbm_clearerr(dp->di_dbm);
-			PyErr_SetString(PyExc_KeyError,
-				      PyString_AS_STRING((PyStringObject *)v));
+			PyErr_SetObject(PyExc_KeyError, v);
 			return -1;
 		}
 	} else {

Deleted: /python/branches/py3k-buffer/Modules/linuxaudiodev.c
==============================================================================
--- /python/branches/py3k-buffer/Modules/linuxaudiodev.c	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,501 +0,0 @@
-/* Hey Emacs, this is -*-C-*- 
- ******************************************************************************
- * linuxaudiodev.c -- Linux audio device for python.
- * 
- * Author          : Peter Bosch
- * Created On      : Thu Mar  2 21:10:33 2000
- * Status          : Unknown, Use with caution!
- * 
- * Unless other notices are present in any part of this file
- * explicitly claiming copyrights for other people and/or 
- * organizations, the contents of this file is fully copyright 
- * (C) 2000 Peter Bosch, all rights reserved.
- ******************************************************************************
- */
-
-#include "Python.h"
-#include "structmember.h"
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#else
-#define O_RDONLY 00
-#define O_WRONLY 01
-#endif
-
-
-#include <sys/ioctl.h>
-#if defined(linux)
-#include <linux/soundcard.h>
-
-#ifndef HAVE_STDINT_H
-typedef unsigned long uint32_t;
-#endif
-
-#elif defined(__FreeBSD__)
-#include <machine/soundcard.h>
-
-#ifndef SNDCTL_DSP_CHANNELS
-#define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
-#endif
-
-#endif
-
-typedef struct {
-    PyObject_HEAD
-    int		x_fd;		/* The open file */
-    int         x_mode;           /* file mode */
-    int		x_icount;	/* Input count */
-    int		x_ocount;	/* Output count */
-    uint32_t	x_afmts;	/* Audio formats supported by hardware*/
-} lad_t;
-
-/* XXX several format defined in soundcard.h are not supported,
-   including _NE (native endian) options and S32 options
-*/
-
-static struct {
-    int		a_bps;
-    uint32_t	a_fmt;
-    char       *a_name;
-} audio_types[] = {
-    {  8, 	AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
-    {  8, 	AFMT_A_LAW,  "logarithmic A-law 8-bit audio" },
-    {  8,	AFMT_U8,     "linear unsigned 8-bit audio" },
-    {  8, 	AFMT_S8,     "linear signed 8-bit audio" },
-    { 16, 	AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
-    { 16, 	AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
-    { 16, 	AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
-    { 16, 	AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
-    { 16, 	AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
-};
-
-static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]);
-
-static PyTypeObject Ladtype;
-
-static PyObject *LinuxAudioError;
-
-static lad_t *
-newladobject(PyObject *arg)
-{
-    lad_t *xp;
-    int fd, afmts, imode;
-    char *basedev = NULL;
-    char *mode = NULL;
-
-    /* Two ways to call linuxaudiodev.open():
-         open(device, mode) (for consistency with builtin open())
-         open(mode)         (for backwards compatibility)
-       because the *first* argument is optional, parsing args is
-       a wee bit tricky. */
-    if (!PyArg_ParseTuple(arg, "s|s:open", &basedev, &mode))
-       return NULL;
-    if (mode == NULL) {                 /* only one arg supplied */
-       mode = basedev;
-       basedev = NULL;
-    }
-
-    if (strcmp(mode, "r") == 0)
-        imode = O_RDONLY;
-    else if (strcmp(mode, "w") == 0)
-        imode = O_WRONLY;
-    else {
-        PyErr_SetString(LinuxAudioError, "mode should be 'r' or 'w'");
-        return NULL;
-    }
-
-    /* Open the correct device.  The base device name comes from the
-     * AUDIODEV environment variable first, then /dev/dsp.  The
-     * control device tacks "ctl" onto the base device name.
-     * 
-     * Note that the only difference between /dev/audio and /dev/dsp
-     * is that the former uses logarithmic mu-law encoding and the
-     * latter uses 8-bit unsigned encoding.
-     */
-
-    if (basedev == NULL) {              /* called with one arg */
-       basedev = getenv("AUDIODEV");
-       if (basedev == NULL)             /* $AUDIODEV not set */
-          basedev = "/dev/dsp";
-    }
-
-    if ((fd = open(basedev, imode)) == -1) {
-        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
-        return NULL;
-    }
-    if (imode == O_WRONLY && ioctl(fd, SNDCTL_DSP_NONBLOCK, NULL) == -1) {
-        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
-        return NULL;
-    }
-    if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
-        PyErr_SetFromErrnoWithFilename(LinuxAudioError, basedev);
-        return NULL;
-    }
-    /* Create and initialize the object */
-    if ((xp = PyObject_New(lad_t, &Ladtype)) == NULL) {
-        close(fd);
-        return NULL;
-    }
-    xp->x_fd = fd;
-    xp->x_mode = imode;
-    xp->x_icount = xp->x_ocount = 0;
-    xp->x_afmts  = afmts;
-    return xp;
-}
-
-static void
-lad_dealloc(lad_t *xp)
-{
-    /* if already closed, don't reclose it */
-    if (xp->x_fd != -1)
-	close(xp->x_fd);
-    PyObject_Del(xp);
-}
-
-static PyObject *
-lad_read(lad_t *self, PyObject *args)
-{
-    int size, count;
-    char *cp;
-    PyObject *rv;
-	
-    if (!PyArg_ParseTuple(args, "i:read", &size))
-        return NULL;
-    rv = PyString_FromStringAndSize(NULL, size);
-    if (rv == NULL)
-        return NULL;
-    cp = PyString_AS_STRING(rv);
-    if ((count = read(self->x_fd, cp, size)) < 0) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        Py_DECREF(rv);
-        return NULL;
-    }
-    self->x_icount += count;
-    _PyString_Resize(&rv, count);
-    return rv;
-}
-
-static PyObject *
-lad_write(lad_t *self, PyObject *args)
-{
-    char *cp;
-    int rv, size;
-    fd_set write_set_fds;
-    struct timeval tv;
-    int select_retval;
-    
-    if (!PyArg_ParseTuple(args, "s#:write", &cp, &size)) 
-	return NULL;
-
-    /* use select to wait for audio device to be available */
-    FD_ZERO(&write_set_fds);
-    FD_SET(self->x_fd, &write_set_fds);
-    tv.tv_sec = 4; /* timeout values */
-    tv.tv_usec = 0; 
-
-    while (size > 0) {
-      select_retval = select(self->x_fd+1, NULL, &write_set_fds, NULL, &tv);
-      tv.tv_sec = 1; tv.tv_usec = 0; /* willing to wait this long next time*/
-      if (select_retval) {
-        if ((rv = write(self->x_fd, cp, size)) == -1) {
-	  if (errno != EAGAIN) {
-	    PyErr_SetFromErrno(LinuxAudioError);
-	    return NULL;
-	  } else {
-	    errno = 0; /* EAGAIN: buffer is full, try again */
-	  }
-        } else {
-	  self->x_ocount += rv;
-	  size -= rv;
-	  cp += rv;
-	}
-      } else {
-	/* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
-	PyErr_SetFromErrno(LinuxAudioError);
-	return NULL;
-      }
-    }
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyObject *
-lad_close(lad_t *self, PyObject *unused)
-{
-    if (self->x_fd >= 0) {
-        close(self->x_fd);
-        self->x_fd = -1;
-    }
-    Py_RETURN_NONE;
-}
-
-static PyObject *
-lad_fileno(lad_t *self, PyObject *unused)
-{
-    return PyInt_FromLong(self->x_fd);
-}
-
-static PyObject *
-lad_setparameters(lad_t *self, PyObject *args)
-{
-    int rate, ssize, nchannels, n, fmt, emulate=0;
-
-    if (!PyArg_ParseTuple(args, "iiii|i:setparameters",
-                          &rate, &ssize, &nchannels, &fmt, &emulate))
-        return NULL;
-  
-    if (rate < 0) {
-	PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
-		     rate); 
-	return NULL;
-    }
-    if (ssize < 0) {
-	PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
-		     ssize);
-	return NULL;
-    }
-    if (nchannels != 1 && nchannels != 2) {
-	PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
-		     nchannels);
-	return NULL;
-    }
-
-    for (n = 0; n < n_audio_types; n++)
-        if (fmt == audio_types[n].a_fmt)
-            break;
-    if (n == n_audio_types) {
-	PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
-	return NULL;
-    }
-    if (audio_types[n].a_bps != ssize) {
-	PyErr_Format(PyExc_ValueError, 
-		     "for %s, expected sample size %d, not %d",
-		     audio_types[n].a_name, audio_types[n].a_bps, ssize);
-	return NULL;
-    }
-
-    if (emulate == 0) {
-	if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
-	    PyErr_Format(PyExc_ValueError, 
-			 "%s format not supported by device",
-			 audio_types[n].a_name);
-	    return NULL;
-	}
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, 
-	      &audio_types[n].a_fmt) == -1) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, &nchannels) == -1) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_SPEED, &rate) == -1) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static int
-_ssize(lad_t *self, int *nchannels, int *ssize)
-{
-    int fmt;
-
-    fmt = 0;
-    if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0) 
-        return -errno;
-
-    switch (fmt) {
-    case AFMT_MU_LAW:
-    case AFMT_A_LAW:
-    case AFMT_U8:
-    case AFMT_S8:
-        *ssize = sizeof(char);
-        break;
-    case AFMT_S16_LE:
-    case AFMT_S16_BE:
-    case AFMT_U16_LE:
-    case AFMT_U16_BE:
-        *ssize = sizeof(short);
-        break;
-    case AFMT_MPEG:
-    case AFMT_IMA_ADPCM:
-    default:
-        return -EOPNOTSUPP;
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_CHANNELS, nchannels) < 0)
-        return -errno;
-    return 0;
-}
-
-
-/* bufsize returns the size of the hardware audio buffer in number 
-   of samples */
-static PyObject *
-lad_bufsize(lad_t *self, PyObject *unused)
-{
-    audio_buf_info ai;
-    int nchannels=0, ssize=0;
-
-    if (_ssize(self, &nchannels, &ssize) < 0 || !ssize || !nchannels) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    return PyInt_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
-}
-
-/* obufcount returns the number of samples that are available in the 
-   hardware for playing */
-static PyObject *
-lad_obufcount(lad_t *self, PyObject *unused)
-{
-    audio_buf_info ai;
-    int nchannels=0, ssize=0;
-
-    if (_ssize(self, &nchannels, &ssize) < 0 || !ssize || !nchannels) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) / 
-                          (ssize * nchannels));
-}
-
-/* obufcount returns the number of samples that can be played without
-   blocking */
-static PyObject *
-lad_obuffree(lad_t *self, PyObject *unused)
-{
-    audio_buf_info ai;
-    int nchannels=0, ssize=0;
-
-    if (_ssize(self, &nchannels, &ssize) < 0 || !ssize || !nchannels) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    if (ioctl(self->x_fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    return PyInt_FromLong(ai.bytes / (ssize * nchannels));
-}
-
-/* Flush the device */
-static PyObject *
-lad_flush(lad_t *self, PyObject *unused)
-{
-    if (ioctl(self->x_fd, SNDCTL_DSP_SYNC, NULL) == -1) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    Py_RETURN_NONE;
-}
-
-static PyObject *
-lad_getptr(lad_t *self, PyObject *unused)
-{
-    count_info info;
-    int req;
-
-    if (self->x_mode == O_RDONLY)
-	req = SNDCTL_DSP_GETIPTR;
-    else
-	req = SNDCTL_DSP_GETOPTR;
-    if (ioctl(self->x_fd, req, &info) == -1) {
-        PyErr_SetFromErrno(LinuxAudioError);
-        return NULL;
-    }
-    return Py_BuildValue("iii", info.bytes, info.blocks, info.ptr);
-}
-
-static PyMethodDef lad_methods[] = {
-    { "read",		(PyCFunction)lad_read, METH_VARARGS },
-    { "write",		(PyCFunction)lad_write, METH_VARARGS },
-    { "setparameters",	(PyCFunction)lad_setparameters, METH_VARARGS },
-    { "bufsize",	(PyCFunction)lad_bufsize, METH_VARARGS },
-    { "obufcount",	(PyCFunction)lad_obufcount, METH_NOARGS },
-    { "obuffree",	(PyCFunction)lad_obuffree, METH_NOARGS },
-    { "flush",		(PyCFunction)lad_flush, METH_NOARGS },
-    { "close",		(PyCFunction)lad_close, METH_NOARGS },
-    { "fileno",     	(PyCFunction)lad_fileno, METH_NOARGS },
-    { "getptr",         (PyCFunction)lad_getptr, METH_NOARGS },
-    { NULL,		NULL}		/* sentinel */
-};
-
-static PyObject *
-lad_getattr(lad_t *xp, char *name)
-{
-    return Py_FindMethod(lad_methods, (PyObject *)xp, name);
-}
-
-static PyTypeObject Ladtype = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "linuxaudiodev.linux_audio_device", /*tp_name*/
-    sizeof(lad_t),		/*tp_size*/
-    0,				/*tp_itemsize*/
-    /* methods */
-    (destructor)lad_dealloc,	/*tp_dealloc*/
-    0,				/*tp_print*/
-    (getattrfunc)lad_getattr,	/*tp_getattr*/
-    0,				/*tp_setattr*/
-    0,				/*tp_compare*/
-    0,				/*tp_repr*/
-};
-
-static PyObject *
-ladopen(PyObject *self, PyObject *args)
-{
-    return (PyObject *)newladobject(args);
-}
-
-static PyMethodDef linuxaudiodev_methods[] = {
-    { "open", ladopen, METH_VARARGS },
-    { 0, 0 },
-};
-
-void
-initlinuxaudiodev(void)
-{
-    PyObject *m;
-  
-    m = Py_InitModule("linuxaudiodev", linuxaudiodev_methods);
-    if (m == NULL)
-	return;
-
-    LinuxAudioError = PyErr_NewException("linuxaudiodev.error", NULL, NULL);
-    if (LinuxAudioError)
-	PyModule_AddObject(m, "error", LinuxAudioError);
-
-    if (PyModule_AddIntConstant(m, "AFMT_MU_LAW", (long)AFMT_MU_LAW) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_A_LAW", (long)AFMT_A_LAW) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_U8", (long)AFMT_U8) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_S8", (long)AFMT_S8) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_U16_BE", (long)AFMT_U16_BE) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_U16_LE", (long)AFMT_U16_LE) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_S16_BE", (long)AFMT_S16_BE) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_S16_LE", (long)AFMT_S16_LE) == -1)
-	return;
-    if (PyModule_AddIntConstant(m, "AFMT_S16_NE", (long)AFMT_S16_NE) == -1)
-	return;
-
-    return;
-}

Modified: python/branches/py3k-buffer/Modules/mmapmodule.c
==============================================================================
--- python/branches/py3k-buffer/Modules/mmapmodule.c	(original)
+++ python/branches/py3k-buffer/Modules/mmapmodule.c	Fri Aug 17 20:48:09 2007
@@ -232,7 +232,7 @@
 	if ((self->pos + num_bytes) > self->size) {
 		num_bytes -= (self->pos+num_bytes) - self->size;
 	}
-	result = Py_BuildValue("s#", self->data+self->pos, num_bytes);
+	result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes);
 	self->pos += num_bytes;
 	return result;
 }

Modified: python/branches/py3k-buffer/Modules/socketmodule.c
==============================================================================
--- python/branches/py3k-buffer/Modules/socketmodule.c	(original)
+++ python/branches/py3k-buffer/Modules/socketmodule.c	Fri Aug 17 20:48:09 2007
@@ -2193,6 +2193,10 @@
 		select_error();
 		return -1;
 	}
+        if (len == 0) {
+		/* If 0 bytes were requested, do nothing. */
+		return 0;
+	}
 
 #ifndef __VMS
 	Py_BEGIN_ALLOW_THREADS
@@ -2322,7 +2326,6 @@
 	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
 					 &buf, &buflen, &recvlen, &flags))
 		return NULL;
-	assert(buf != 0 && buflen > 0);
 
 	if (recvlen < 0) {
 		PyErr_SetString(PyExc_ValueError,

Deleted: /python/branches/py3k-buffer/Modules/sunaudiodev.c
==============================================================================
--- /python/branches/py3k-buffer/Modules/sunaudiodev.c	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,463 +0,0 @@
-
-/* Sad objects */
-
-#include "Python.h"
-#include "structmember.h"
-
-#ifdef HAVE_SYS_AUDIOIO_H
-#define SOLARIS
-#endif
-
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-
-#include <stropts.h>
-#include <sys/ioctl.h>
-#ifdef SOLARIS
-#include <sys/audioio.h>
-#else
-#include <sun/audioio.h>
-#endif
-
-/* #define offsetof(str,mem) ((int)(((str *)0)->mem)) */
-
-typedef struct {
-	PyObject_HEAD
-	int	x_fd;		/* The open file */
-	int	x_icount;	/* # samples read */
-	int	x_ocount;	/* # samples written */
-	int	x_isctl;	/* True if control device */
-	
-} sadobject;
-
-typedef struct {
-	PyObject_HEAD
-	audio_info_t ai;
-} sadstatusobject;
-
-static PyTypeObject Sadtype;
-static PyTypeObject Sadstatustype;
-static sadstatusobject *sads_alloc(void);	/* Forward */
-
-static PyObject *SunAudioError;
-
-#define is_sadobject(v)		(Py_Type(v) == &Sadtype)
-#define is_sadstatusobject(v)	(Py_Type(v) == &Sadstatustype)
-
-
-static sadobject *
-newsadobject(PyObject *args)
-{
-	sadobject *xp;
-	int fd;
-	char *mode;
-	int imode;
-	char* basedev;
-	char* ctldev;
-	char* opendev;
-
-	/* Check arg for r/w/rw */
-	if (!PyArg_ParseTuple(args, "s", &mode))
-		return NULL;
-	if (strcmp(mode, "r") == 0)
-		imode = 0;
-	else if (strcmp(mode, "w") == 0)
-		imode = 1;
-	else if (strcmp(mode, "rw") == 0)
-		imode = 2;
-	else if (strcmp(mode, "control") == 0)
-		imode = -1;
-	else {
-		PyErr_SetString(SunAudioError,
-			  "Mode should be one of 'r', 'w', 'rw' or 'control'");
-		return NULL;
-	}
-	
-	/* Open the correct device.  The base device name comes from the
-	 * AUDIODEV environment variable first, then /dev/audio.  The
-	 * control device tacks "ctl" onto the base device name.
-	 */
-	basedev = getenv("AUDIODEV");
-	if (!basedev)
-		basedev = "/dev/audio";
-	ctldev = PyMem_NEW(char, strlen(basedev) + 4);
-	if (!ctldev) {
-		PyErr_NoMemory();
-		return NULL;
-	}
-	strcpy(ctldev, basedev);
-	strcat(ctldev, "ctl");
-
-	if (imode < 0) {
-		opendev = ctldev;
-		fd = open(ctldev, 2);
-	}
-	else {
-		opendev = basedev;
-		fd = open(basedev, imode);
-	}
-	if (fd < 0) {
-		PyErr_SetFromErrnoWithFilename(SunAudioError, opendev);
-		PyMem_DEL(ctldev);
-		return NULL;
-	}
-	PyMem_DEL(ctldev);
-
-	/* Create and initialize the object */
-	xp = PyObject_New(sadobject, &Sadtype);
-	if (xp == NULL) {
-		close(fd);
-		return NULL;
-	}
-	xp->x_fd = fd;
-	xp->x_icount = xp->x_ocount = 0;
-	xp->x_isctl = (imode < 0);
-	
-	return xp;
-}
-
-/* Sad methods */
-
-static void
-sad_dealloc(sadobject *xp)
-{
-        close(xp->x_fd);
-	PyObject_Del(xp);
-}
-
-static PyObject *
-sad_read(sadobject *self, PyObject *args)
-{
-        int size, count;
-	char *cp;
-	PyObject *rv;
-	
-        if (!PyArg_ParseTuple(args, "i:read", &size))
-		return NULL;
-	rv = PyString_FromStringAndSize(NULL, size);
-	if (rv == NULL)
-		return NULL;
-
-	if (!(cp = PyString_AsString(rv)))
-		goto finally;
-
-	count = read(self->x_fd, cp, size);
-	if (count < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		goto finally;
-	}
-#if 0
-	/* TBD: why print this message if you can handle the condition?
-	 * assume it's debugging info which we can just as well get rid
-	 * of.  in any case this message should *not* be using printf!
-	 */
-	if (count != size)
-		printf("sunaudio: funny read rv %d wtd %d\n", count, size);
-#endif
-	self->x_icount += count;
-	return rv;
-
-  finally:
-	Py_DECREF(rv);
-	return NULL;
-}
-
-static PyObject *
-sad_write(sadobject *self, PyObject *args)
-{
-        char *cp;
-	int count, size;
-	
-        if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
-		return NULL;
-
-	count = write(self->x_fd, cp, size);
-	if (count < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-#if 0
-	if (count != size)
-		printf("sunaudio: funny write rv %d wanted %d\n", count, size);
-#endif
-	self->x_ocount += count;
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sad_getinfo(sadobject *self)
-{
-	sadstatusobject *rv;
-
-	if (!(rv = sads_alloc()))
-		return NULL;
-
-	if (ioctl(self->x_fd, AUDIO_GETINFO, &rv->ai) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		Py_DECREF(rv);
-		return NULL;
-	}
-	return (PyObject *)rv;
-}
-
-static PyObject *
-sad_setinfo(sadobject *self, sadstatusobject *arg)
-{
-	if (!is_sadstatusobject(arg)) {
-		PyErr_SetString(PyExc_TypeError,
-				"Must be sun audio status object");
-		return NULL;
-	}
-	if (ioctl(self->x_fd, AUDIO_SETINFO, &arg->ai) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sad_ibufcount(sadobject *self)
-{
-	audio_info_t ai;
-    
-	if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-	return PyInt_FromLong(ai.record.samples - self->x_icount);
-}
-
-static PyObject *
-sad_obufcount(sadobject *self)
-{
-	audio_info_t ai;
-    
-	if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-	/* x_ocount is in bytes, whereas play.samples is in frames */
-	/* we want frames */
-	return PyInt_FromLong(self->x_ocount / (ai.play.channels *
-						ai.play.precision / 8) -
-			      ai.play.samples);
-}
-
-static PyObject *
-sad_drain(sadobject *self)
-{
-	if (ioctl(self->x_fd, AUDIO_DRAIN, 0) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-#ifdef SOLARIS
-static PyObject *
-sad_getdev(sadobject *self)
-{
-	struct audio_device ad;
-
-	if (ioctl(self->x_fd, AUDIO_GETDEV, &ad) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-	return Py_BuildValue("(sss)", ad.name, ad.version, ad.config);
-}
-#endif
-
-static PyObject *
-sad_flush(sadobject *self)
-{
-	if (ioctl(self->x_fd, I_FLUSH, FLUSHW) < 0) {
-		PyErr_SetFromErrno(SunAudioError);
-		return NULL;
-	}
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sad_close(sadobject *self)
-{
-    
-	if (self->x_fd >= 0) {
-		close(self->x_fd);
-		self->x_fd = -1;
-	}
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sad_fileno(sadobject *self)
-{
-	return PyInt_FromLong(self->x_fd);
-}
-
-
-static PyMethodDef sad_methods[] = {
-        { "read",	(PyCFunction)sad_read, METH_VARARGS },
-        { "write",	(PyCFunction)sad_write, METH_VARARGS },
-        { "ibufcount",	(PyCFunction)sad_ibufcount, METH_NOARGS },
-        { "obufcount",	(PyCFunction)sad_obufcount, METH_NOARGS },
-#define CTL_METHODS 4
-        { "getinfo",	(PyCFunction)sad_getinfo, METH_NOARGS },
-        { "setinfo",	(PyCFunction)sad_setinfo, METH_O},
-        { "drain",	(PyCFunction)sad_drain, METH_NOARGS },
-        { "flush",	(PyCFunction)sad_flush, METH_NOARGS },
-#ifdef SOLARIS
-	{ "getdev",	(PyCFunction)sad_getdev, METH_NOARGS },
-#endif
-        { "close",	(PyCFunction)sad_close, METH_NOARGS },
-	{ "fileno",     (PyCFunction)sad_fileno, METH_NOARGS },
-	{NULL,		NULL}		/* sentinel */
-};
-
-static PyObject *
-sad_getattr(sadobject *xp, char *name)
-{
-	if (xp->x_isctl)
-		return Py_FindMethod(sad_methods+CTL_METHODS,
-				     (PyObject *)xp, name);
-	else
-		return Py_FindMethod(sad_methods, (PyObject *)xp, name);
-}
-
-/* ----------------------------------------------------------------- */
-
-static sadstatusobject *
-sads_alloc(void) {
-	return PyObject_New(sadstatusobject, &Sadstatustype);
-}
-
-static void
-sads_dealloc(sadstatusobject *xp)
-{
-	PyMem_DEL(xp);
-}
-
-#define OFF(x) offsetof(audio_info_t,x)
-static struct memberlist sads_ml[] = {
-	{ "i_sample_rate",	T_UINT,		OFF(record.sample_rate) },
-	{ "i_channels",		T_UINT,		OFF(record.channels) },
-	{ "i_precision",	T_UINT,		OFF(record.precision) },
-	{ "i_encoding",		T_UINT,		OFF(record.encoding) },
-	{ "i_gain",		T_UINT,		OFF(record.gain) },
-	{ "i_port",		T_UINT,		OFF(record.port) },
-	{ "i_samples",		T_UINT,		OFF(record.samples) },
-	{ "i_eof",		T_UINT,		OFF(record.eof) },
-	{ "i_pause",		T_UBYTE,	OFF(record.pause) },
-	{ "i_error",		T_UBYTE,	OFF(record.error) },
-	{ "i_waiting",		T_UBYTE,	OFF(record.waiting) },
-	{ "i_open",		T_UBYTE,	OFF(record.open) ,	 RO},
-	{ "i_active",		T_UBYTE,	OFF(record.active) ,	 RO},
-#ifdef SOLARIS
-	{ "i_buffer_size",	T_UINT,		OFF(record.buffer_size) },
-	{ "i_balance",		T_UBYTE,	OFF(record.balance) },
-	{ "i_avail_ports",	T_UINT,		OFF(record.avail_ports) },
-#endif
-
-	{ "o_sample_rate",	T_UINT,		OFF(play.sample_rate) },
-	{ "o_channels",		T_UINT,		OFF(play.channels) },
-	{ "o_precision",	T_UINT,		OFF(play.precision) },
-	{ "o_encoding",		T_UINT,		OFF(play.encoding) },
-	{ "o_gain",		T_UINT,		OFF(play.gain) },
-	{ "o_port",		T_UINT,		OFF(play.port) },
-	{ "o_samples",		T_UINT,		OFF(play.samples) },
-	{ "o_eof",		T_UINT,		OFF(play.eof) },
-	{ "o_pause",		T_UBYTE,	OFF(play.pause) },
-	{ "o_error",		T_UBYTE,	OFF(play.error) },
-	{ "o_waiting",		T_UBYTE,	OFF(play.waiting) },
-	{ "o_open",		T_UBYTE,	OFF(play.open) ,	 RO},
-	{ "o_active",		T_UBYTE,	OFF(play.active) ,	 RO},
-#ifdef SOLARIS
-	{ "o_buffer_size",	T_UINT,		OFF(play.buffer_size) },
-	{ "o_balance",		T_UBYTE,	OFF(play.balance) },
-	{ "o_avail_ports",	T_UINT,		OFF(play.avail_ports) },
-#endif
-
-	{ "monitor_gain",	T_UINT,		OFF(monitor_gain) },
-        { NULL,                 0,              0},
-};
-
-static PyObject *
-sads_getattr(sadstatusobject *xp, char *name)
-{
-	return PyMember_Get((char *)&xp->ai, sads_ml, name);
-}
-
-static int
-sads_setattr(sadstatusobject *xp, char *name, PyObject *v)
-{
-
-	if (v == NULL) {
-		PyErr_SetString(PyExc_TypeError,
-				"can't delete sun audio status attributes");
-		return -1;
-	}
-	return PyMember_Set((char *)&xp->ai, sads_ml, name, v);
-}
-
-/* ------------------------------------------------------------------- */
-
-
-static PyTypeObject Sadtype = {
-	PyVarObject_HEAD_INIT(&PyType_Type, 0)
-	"sunaudiodev.sun_audio_device",	/*tp_name*/
-	sizeof(sadobject),		/*tp_size*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)sad_dealloc,	/*tp_dealloc*/
-	0,				/*tp_print*/
-	(getattrfunc)sad_getattr,	/*tp_getattr*/
-	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
-	0,				/*tp_repr*/
-};
-
-static PyTypeObject Sadstatustype = {
-	PyVarObject_HEAD_INIT(&PyType_Type, 0)
-	"sunaudiodev.sun_audio_device_status", /*tp_name*/
-	sizeof(sadstatusobject),	/*tp_size*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)sads_dealloc,	/*tp_dealloc*/
-	0,				/*tp_print*/
-	(getattrfunc)sads_getattr,	/*tp_getattr*/
-	(setattrfunc)sads_setattr,	/*tp_setattr*/
-	0,				/*tp_compare*/
-	0,				/*tp_repr*/
-};
-/* ------------------------------------------------------------------- */
-
-static PyObject *
-sadopen(PyObject *self, PyObject *args)
-{
-	return (PyObject *)newsadobject(args);
-}
-    
-static PyMethodDef sunaudiodev_methods[] = {
-    { "open", sadopen, METH_VARARGS },
-    { 0, 0 },
-};
-
-void
-initsunaudiodev(void)
-{
-	PyObject *m, *d;
-
-	m = Py_InitModule("sunaudiodev", sunaudiodev_methods);
-	if (m == NULL)
-		return;
-	d = PyModule_GetDict(m);
-	SunAudioError = PyErr_NewException("sunaudiodev.error", NULL, NULL);
-	if (SunAudioError)
-		PyDict_SetItemString(d, "error", SunAudioError);
-}

Modified: python/branches/py3k-buffer/Modules/unicodedata.c
==============================================================================
--- python/branches/py3k-buffer/Modules/unicodedata.c	(original)
+++ python/branches/py3k-buffer/Modules/unicodedata.c	Fri Aug 17 20:48:09 2007
@@ -1077,8 +1077,7 @@
 unicodedata_lookup(PyObject* self, PyObject* args)
 {
     Py_UCS4 code;
-    Py_UNICODE str[1];
-    char errbuf[256];
+    Py_UNICODE str[2];
 
     char* name;
     int namelen;
@@ -1086,24 +1085,20 @@
         return NULL;
 
     if (!_getcode(self, name, namelen, &code)) {
-	/* XXX(nnorwitz): why are we allocating for the error msg?
-		Why not always use snprintf? */
-        char fmt[] = "undefined character name '%s'";
-        char *buf = PyMem_MALLOC(sizeof(fmt) + namelen);
-        if (buf)
-            sprintf(buf, fmt, name);
-        else {
-            buf = errbuf;
-            PyOS_snprintf(buf, sizeof(errbuf), fmt, name);
-        }
-        PyErr_SetString(PyExc_KeyError, buf);
-        if (buf != errbuf)
-        	PyMem_FREE(buf);
+        PyErr_Format(PyExc_KeyError, "undefined character name '%s'",
+                     name);
         return NULL;
     }
 
+#ifndef Py_UNICODE_WIDE
+    if (code >= 0x10000) {
+        str[0] = 0xd800 + ((code - 0x10000) >> 10);
+        str[1] = 0xdc00 + ((code - 0x10000) & 0x3ff);
+        return PyUnicode_FromUnicode(str, 2);
+    }
+#endif
     str[0] = (Py_UNICODE) code;
-    return PyUnicode_FromUnicode(str, 1);
+    return PyUnicode_FromUnicode(str, 1);    
 }
 
 /* XXX Add doc strings. */

Modified: python/branches/py3k-buffer/Modules/zipimport.c
==============================================================================
--- python/branches/py3k-buffer/Modules/zipimport.c	(original)
+++ python/branches/py3k-buffer/Modules/zipimport.c	Fri Aug 17 20:48:09 2007
@@ -475,8 +475,12 @@
 		strcpy(path + len, ".py");
 
 	toc_entry = PyDict_GetItemString(self->files, path);
-	if (toc_entry != NULL)
-		return get_data(PyString_AsString(self->archive), toc_entry);
+	if (toc_entry != NULL) {
+		PyObject *bytes = get_data(PyString_AsString(self->archive), toc_entry);
+		PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes));
+		Py_XDECREF(bytes);
+		return res;
+	}
 
 	/* we have the module, but no source */
 	Py_INCREF(Py_None);
@@ -857,8 +861,10 @@
 	}
 	buf[data_size] = '\0';
 
-	if (compress == 0)  /* data is not compressed */
+	if (compress == 0) {  /* data is not compressed */
+		raw_data = PyBytes_FromStringAndSize(buf, data_size);
 		return raw_data;
+	}
 
 	/* Decompress with zlib */
 	decompress = get_decompress_func();
@@ -896,8 +902,8 @@
 unmarshal_code(char *pathname, PyObject *data, time_t mtime)
 {
 	PyObject *code;
-	char *buf = PyString_AsString(data);
-	Py_ssize_t size = PyString_Size(data);
+	char *buf = PyBytes_AsString(data);
+	Py_ssize_t size = PyBytes_Size(data);
 
 	if (size <= 9) {
 		PyErr_SetString(ZipImportError,
@@ -942,14 +948,16 @@
 static PyObject *
 normalize_line_endings(PyObject *source)
 {
-	char *buf, *q, *p = PyString_AsString(source);
+	char *buf, *q, *p = PyBytes_AsString(source);
 	PyObject *fixed_source;
+	int len = 0;
 
-	if (!p)
-		return NULL;
+	if (!p) {
+		return PyBytes_FromStringAndSize("\n\0", 2);
+	}
 
 	/* one char extra for trailing \n and one for terminating \0 */
-	buf = (char *)PyMem_Malloc(PyString_Size(source) + 2);
+	buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2);
 	if (buf == NULL) {
 		PyErr_SetString(PyExc_MemoryError,
 				"zipimport: no memory to allocate "
@@ -965,10 +973,11 @@
 		}
 		else
 			*q++ = *p;
+		len++;
 	}
 	*q++ = '\n';  /* add trailing \n */
 	*q = '\0';
-	fixed_source = PyString_FromString(buf);
+	fixed_source = PyBytes_FromStringAndSize(buf, len + 2);
 	PyMem_Free(buf);
 	return fixed_source;
 }
@@ -984,7 +993,7 @@
 	if (fixed_source == NULL)
 		return NULL;
 
-	code = Py_CompileString(PyString_AsString(fixed_source), pathname,
+	code = Py_CompileString(PyBytes_AsString(fixed_source), pathname,
 				Py_file_input);
 	Py_DECREF(fixed_source);
 	return code;

Modified: python/branches/py3k-buffer/Objects/boolobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/boolobject.c	(original)
+++ python/branches/py3k-buffer/Objects/boolobject.c	Fri Aug 17 20:48:09 2007
@@ -3,15 +3,6 @@
 #include "Python.h"
 #include "longintrepr.h"
 
-/* We need to define bool_print to override int_print */
-
-static int
-bool_print(PyObject *self, FILE *fp, int flags)
-{
-	fputs(self == Py_False ? "False" : "True", fp);
-	return 0;
-}
-
 /* We define bool_repr to return "False" or "True" */
 
 static PyObject *false_str = NULL;
@@ -148,7 +139,7 @@
 	sizeof(struct _longobject),
 	0,
 	0,					/* tp_dealloc */
-	bool_print,				/* tp_print */
+	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/bytesobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/bytesobject.c	(original)
+++ python/branches/py3k-buffer/Objects/bytesobject.c	Fri Aug 17 20:48:09 2007
@@ -2576,7 +2576,10 @@
     argptr = ((PyBytesObject *)arg)->ob_bytes;
     argsize = Py_Size(arg);
     left = lstrip_helper(myptr, mysize, argptr, argsize);
-    right = rstrip_helper(myptr, mysize, argptr, argsize);
+    if (left == mysize)
+        right = left;
+    else
+        right = rstrip_helper(myptr, mysize, argptr, argsize);
     return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left);
 }
 
@@ -2798,11 +2801,13 @@
 static PyObject *
 bytes_reduce(PyBytesObject *self)
 {
-    return Py_BuildValue("(O(s#s))",
-                         Py_Type(self),
-                         self->ob_bytes == NULL ? "" : self->ob_bytes,
-                         Py_Size(self),
-                         "latin-1");
+    PyObject *latin1;
+    if (self->ob_bytes)
+	latin1 = PyUnicode_DecodeLatin1(self->ob_bytes, 
+					Py_Size(self), NULL);
+    else
+	latin1 = PyUnicode_FromString("");
+    return Py_BuildValue("(O(Ns))", Py_Type(self), latin1, "latin-1");
 }
 
 static PySequenceMethods bytes_as_sequence = {

Modified: python/branches/py3k-buffer/Objects/complexobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/complexobject.c	(original)
+++ python/branches/py3k-buffer/Objects/complexobject.c	Fri Aug 17 20:48:09 2007
@@ -327,16 +327,6 @@
 	}
 }
 
-static int
-complex_print(PyComplexObject *v, FILE *fp, int flags)
-{
-	char buf[100];
-	complex_to_buf(buf, sizeof(buf), v,
-		       (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
-	fputs(buf, fp);
-	return 0;
-}
-
 static PyObject *
 complex_repr(PyComplexObject *v)
 {
@@ -466,57 +456,18 @@
 static PyObject *
 complex_remainder(PyObject *v, PyObject *w)
 {
-        Py_complex div, mod;
-	Py_complex a, b;
-        TO_COMPLEX(v, a);
-        TO_COMPLEX(w, b);
-
-	if (PyErr_Warn(PyExc_DeprecationWarning,
-		       "complex divmod(), // and % are deprecated") < 0)
-		return NULL;
-
-	errno = 0;
-	div = c_quot(a, b); /* The raw divisor value. */
-	if (errno == EDOM) {
-		PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
-		return NULL;
-	}
-	div.real = floor(div.real); /* Use the floor of the real part. */
-	div.imag = 0.0;
-	mod = c_diff(a, c_prod(b, div));
-
-	return PyComplex_FromCComplex(mod);
+	PyErr_SetString(PyExc_TypeError,
+			"can't mod complex numbers.");
+	return NULL;
 }
 
 
 static PyObject *
 complex_divmod(PyObject *v, PyObject *w)
 {
-        Py_complex div, mod;
-	PyObject *d, *m, *z;
-	Py_complex a, b;
-        TO_COMPLEX(v, a);
-        TO_COMPLEX(w, b);
-
-	if (PyErr_Warn(PyExc_DeprecationWarning,
-		       "complex divmod(), // and % are deprecated") < 0)
-		return NULL;
-
-	errno = 0;
-	div = c_quot(a, b); /* The raw divisor value. */
-	if (errno == EDOM) {
-		PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
-		return NULL;
-	}
-	div.real = floor(div.real); /* Use the floor of the real part. */
-	div.imag = 0.0;
-	mod = c_diff(a, c_prod(b, div));
-	d = PyComplex_FromCComplex(div);
-	m = PyComplex_FromCComplex(mod);
-	z = PyTuple_Pack(2, d, m);
-	Py_XDECREF(d);
-	Py_XDECREF(m);
-	return z;
+	PyErr_SetString(PyExc_TypeError,
+			"can't take floor or mod of complex number.");
+	return NULL;
 }
 
 static PyObject *
@@ -560,15 +511,8 @@
 static PyObject *
 complex_int_div(PyObject *v, PyObject *w)
 {
-	PyObject *t, *r;
-	
-	t = complex_divmod(v, w);
-	if (t != NULL) {
-		r = PyTuple_GET_ITEM(t, 0);
-		Py_INCREF(r);
-		Py_DECREF(t);
-		return r;
-	}
+	PyErr_SetString(PyExc_TypeError,
+			"can't take floor of complex number.");
 	return NULL;
 }
 
@@ -665,6 +609,11 @@
 	return PyComplex_FromCComplex(c);
 }
 
+PyDoc_STRVAR(complex_conjugate_doc,
+"complex.conjugate() -> complex\n"
+"\n"
+"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
+
 static PyObject *
 complex_getnewargs(PyComplexObject *v)
 {
@@ -672,7 +621,8 @@
 }
 
 static PyMethodDef complex_methods[] = {
-	{"conjugate",	(PyCFunction)complex_conjugate,	METH_NOARGS},
+	{"conjugate",	(PyCFunction)complex_conjugate,	METH_NOARGS,
+	 complex_conjugate_doc},
 	{"__getnewargs__",	(PyCFunction)complex_getnewargs,	METH_NOARGS},
 	{NULL,		NULL}		/* sentinel */
 };
@@ -1045,7 +995,7 @@
 	sizeof(PyComplexObject),
 	0,
 	complex_dealloc,			/* tp_dealloc */
-	(printfunc)complex_print,		/* tp_print */
+	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/dictobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/dictobject.c	(original)
+++ python/branches/py3k-buffer/Objects/dictobject.c	Fri Aug 17 20:48:09 2007
@@ -886,51 +886,6 @@
 	Py_TRASHCAN_SAFE_END(mp)
 }
 
-static int
-dict_print(register dictobject *mp, register FILE *fp, register int flags)
-{
-	register Py_ssize_t i;
-	register Py_ssize_t any;
-	int status;
-
-	status = Py_ReprEnter((PyObject*)mp);
-	if (status != 0) {
-		if (status < 0)
-			return status;
-		fprintf(fp, "{...}");
-		return 0;
-	}
-
-	fprintf(fp, "{");
-	any = 0;
-	for (i = 0; i <= mp->ma_mask; i++) {
-		dictentry *ep = mp->ma_table + i;
-		PyObject *pvalue = ep->me_value;
-		if (pvalue != NULL) {
-			/* Prevent PyObject_Repr from deleting value during
-			   key format */
-			Py_INCREF(pvalue);
-			if (any++ > 0)
-				fprintf(fp, ", ");
-			if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
-				Py_DECREF(pvalue);
-				Py_ReprLeave((PyObject*)mp);
-				return -1;
-			}
-			fprintf(fp, ": ");
-			if (PyObject_Print(pvalue, fp, 0) != 0) {
-				Py_DECREF(pvalue);
-				Py_ReprLeave((PyObject*)mp);
-				return -1;
-			}
-			Py_DECREF(pvalue);
-		}
-	}
-	fprintf(fp, "}");
-	Py_ReprLeave((PyObject*)mp);
-	return 0;
-}
-
 static PyObject *
 dict_repr(dictobject *mp)
 {
@@ -1806,26 +1761,6 @@
 extern PyTypeObject PyDictIterItem_Type; /* Forward */
 static PyObject *dictiter_new(dictobject *, PyTypeObject *);
 
-#if 0
-static PyObject *
-dict_iterkeys(dictobject *dict)
-{
-	return dictiter_new(dict, &PyDictIterKey_Type);
-}
-
-static PyObject *
-dict_itervalues(dictobject *dict)
-{
-	return dictiter_new(dict, &PyDictIterValue_Type);
-}
-
-static PyObject *
-dict_iteritems(dictobject *dict)
-{
-	return dictiter_new(dict, &PyDictIterItem_Type);
-}
-#endif
-
 
 PyDoc_STRVAR(contains__doc__,
 "D.__contains__(k) -> True if D has a key k, else False");
@@ -1846,17 +1781,6 @@
 "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
 2-tuple; but raise KeyError if D is empty");
 
-#if 0
-PyDoc_STRVAR(keys__doc__,
-"D.keys() -> list of D's keys");
-
-PyDoc_STRVAR(items__doc__,
-"D.items() -> list of D's (key, value) pairs, as 2-tuples");
-
-PyDoc_STRVAR(values__doc__,
-"D.values() -> list of D's values");
-#endif
-
 PyDoc_STRVAR(update__doc__,
 "D.update(E, **F) -> None.  Update D from E and F: for k in E: D[k] = E[k]\
 \n(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]");
@@ -1871,25 +1795,17 @@
 PyDoc_STRVAR(copy__doc__,
 "D.copy() -> a shallow copy of D");
 
-#if 0
-PyDoc_STRVAR(iterkeys__doc__,
-"D.iterkeys() -> an iterator over the keys of D");
-
-PyDoc_STRVAR(itervalues__doc__,
-"D.itervalues() -> an iterator over the values of D");
-
-PyDoc_STRVAR(iteritems__doc__,
-"D.iteritems() -> an iterator over the (key, value) items of D");
-#endif
-
 /* Forward */
 static PyObject *dictkeys_new(PyObject *);
 static PyObject *dictitems_new(PyObject *);
 static PyObject *dictvalues_new(PyObject *);
 
-PyDoc_STRVAR(keys__doc__, "D.keys() -> a set-like object for D's keys");
-PyDoc_STRVAR(items__doc__, "D.items() -> a set-like object for D's items");
-PyDoc_STRVAR(values__doc__, "D.values() -> a set-like object for D's values");
+PyDoc_STRVAR(keys__doc__,
+	     "D.keys() -> a set-like object providing a view on D's keys");
+PyDoc_STRVAR(items__doc__,
+	     "D.items() -> a set-like object providing a view on D's items");
+PyDoc_STRVAR(values__doc__,
+	     "D.values() -> an object providing a view on D's values");
 
 static PyMethodDef mapp_methods[] = {
 	{"__contains__",(PyCFunction)dict_contains,     METH_O | METH_COEXIST,
@@ -1904,14 +1820,6 @@
 	 pop__doc__},
 	{"popitem",	(PyCFunction)dict_popitem,	METH_NOARGS,
 	 popitem__doc__},
-#if 0
-	{"keys",	(PyCFunction)dict_keys,		METH_NOARGS,
-	keys__doc__},
-	{"items",	(PyCFunction)dict_items,	METH_NOARGS,
-	 items__doc__},
-	{"values",	(PyCFunction)dict_values,	METH_NOARGS,
-	 values__doc__},
-#endif
 	{"keys",	(PyCFunction)dictkeys_new,	METH_NOARGS,
 	keys__doc__},
 	{"items",	(PyCFunction)dictitems_new,	METH_NOARGS,
@@ -1926,14 +1834,6 @@
 	 clear__doc__},
 	{"copy",	(PyCFunction)dict_copy,		METH_NOARGS,
 	 copy__doc__},
-#if 0
-	{"iterkeys",	(PyCFunction)dict_iterkeys,	METH_NOARGS,
-	 iterkeys__doc__},
-	{"itervalues",	(PyCFunction)dict_itervalues,	METH_NOARGS,
-	 itervalues__doc__},
-	{"iteritems",	(PyCFunction)dict_iteritems,	METH_NOARGS,
-	 iteritems__doc__},
-#endif
 	{NULL,		NULL}	/* sentinel */
 };
 
@@ -2029,7 +1929,7 @@
 	sizeof(dictobject),
 	0,
 	(destructor)dict_dealloc,		/* tp_dealloc */
-	(printfunc)dict_print,			/* tp_print */
+	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/floatobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/floatobject.c	(original)
+++ python/branches/py3k-buffer/Objects/floatobject.c	Fri Aug 17 20:48:09 2007
@@ -205,7 +205,7 @@
 {
 	register char *cp;
 	char format[32];
-	/* Subroutine for float_repr, float_str, float_print and others.
+	/* Subroutine for float_repr, float_str, and others.
 	   We want float numbers to be recognizable as such,
 	   i.e., they should contain a decimal point or an exponent.
 	   However, %g may print the number as an integer;
@@ -286,17 +286,6 @@
 #define PREC_REPR	17
 #define PREC_STR	12
 
-/* ARGSUSED */
-static int
-float_print(PyFloatObject *v, FILE *fp, int flags)
-{
-	char buf[100];
-	format_float(buf, sizeof(buf), v,
-		     (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
-	fputs(buf, fp);
-	return 0;
-}
-
 static PyObject *
 float_repr(PyFloatObject *v)
 {
@@ -742,17 +731,6 @@
 }
 
 static PyObject *
-float_pos(PyFloatObject *v)
-{
-	if (PyFloat_CheckExact(v)) {
-		Py_INCREF(v);
-		return (PyObject *)v;
-	}
-	else
-		return PyFloat_FromDouble(v->ob_fval);
-}
-
-static PyObject *
 float_abs(PyFloatObject *v)
 {
 	return PyFloat_FromDouble(fabs(v->ob_fval));
@@ -989,7 +967,15 @@
 "Overrides the automatic determination of C-level floating point type.\n"
 "This affects how floats are converted to and from binary strings.");
 
+static PyObject *
+float_getzero(PyObject *v, void *closure)
+{
+	return PyFloat_FromDouble(0.0);
+}
+
 static PyMethodDef float_methods[] = {
+  	{"conjugate",	(PyCFunction)float_float,	METH_NOARGS,
+	 "Returns self, the complex conjugate of any float."},
 	{"__getnewargs__",	(PyCFunction)float_getnewargs,	METH_NOARGS},
 	{"__getformat__",	(PyCFunction)float_getformat,	
 	 METH_O|METH_CLASS,		float_getformat_doc},
@@ -998,6 +984,18 @@
 	{NULL,		NULL}		/* sentinel */
 };
 
+static PyGetSetDef float_getset[] = {
+    {"real", 
+     (getter)float_float, (setter)NULL,
+     "the real part of a complex number",
+     NULL},
+    {"imag", 
+     (getter)float_getzero, (setter)NULL,
+     "the imaginary part of a complex number",
+     NULL},
+    {NULL}  /* Sentinel */
+};
+
 PyDoc_STRVAR(float_doc,
 "float(x) -> floating point number\n\
 \n\
@@ -1012,7 +1010,7 @@
 	float_divmod, 	/*nb_divmod*/
 	float_pow, 	/*nb_power*/
 	(unaryfunc)float_neg, /*nb_negative*/
-	(unaryfunc)float_pos, /*nb_positive*/
+	(unaryfunc)float_float, /*nb_positive*/
 	(unaryfunc)float_abs, /*nb_absolute*/
 	(inquiry)float_bool, /*nb_bool*/
 	0,		/*nb_invert*/
@@ -1049,7 +1047,7 @@
 	sizeof(PyFloatObject),
 	0,
 	(destructor)float_dealloc,		/* tp_dealloc */
-	(printfunc)float_print, 		/* tp_print */
+	0,			 		/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,			 		/* tp_compare */
@@ -1073,7 +1071,7 @@
 	0,					/* tp_iternext */
 	float_methods,				/* tp_methods */
 	0,					/* tp_members */
-	0,					/* tp_getset */
+	float_getset,				/* tp_getset */
 	0,					/* tp_base */
 	0,					/* tp_dict */
 	0,					/* tp_descr_get */

Modified: python/branches/py3k-buffer/Objects/frameobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/frameobject.c	(original)
+++ python/branches/py3k-buffer/Objects/frameobject.c	Fri Aug 17 20:48:09 2007
@@ -15,11 +15,11 @@
 #define OFF(x) offsetof(PyFrameObject, x)
 
 static PyMemberDef frame_memberlist[] = {
-	{"f_back",	T_OBJECT,	OFF(f_back),	RO},
-	{"f_code",	T_OBJECT,	OFF(f_code),	RO},
-	{"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_back",	T_OBJECT,	OFF(f_back),	READONLY},
+	{"f_code",	T_OBJECT,	OFF(f_code),	READONLY},
+	{"f_builtins",	T_OBJECT,	OFF(f_builtins),READONLY},
+	{"f_globals",	T_OBJECT,	OFF(f_globals),	READONLY},
+	{"f_lasti",	T_INT,		OFF(f_lasti),	READONLY},
 	{"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)},

Modified: python/branches/py3k-buffer/Objects/genobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/genobject.c	(original)
+++ python/branches/py3k-buffer/Objects/genobject.c	Fri Aug 17 20:48:09 2007
@@ -282,8 +282,8 @@
 
 
 static PyMemberDef gen_memberlist[] = {
-	{"gi_frame",	T_OBJECT, offsetof(PyGenObject, gi_frame),	RO},
-	{"gi_running",	T_INT,    offsetof(PyGenObject, gi_running),	RO},
+	{"gi_frame",	T_OBJECT, offsetof(PyGenObject, gi_frame),	READONLY},
+	{"gi_running",	T_INT,    offsetof(PyGenObject, gi_running),	READONLY},
 	{NULL}	/* Sentinel */
 };
 

Deleted: /python/branches/py3k-buffer/Objects/intobject.c
==============================================================================
--- /python/branches/py3k-buffer/Objects/intobject.c	Fri Aug 17 20:48:09 2007
+++ (empty file)
@@ -1,1226 +0,0 @@
-
-/* Integer object implementation */
-
-#include "Python.h"
-#include <ctype.h>
-
-long
-PyInt_GetMax(void)
-{
-	return LONG_MAX;	/* To initialize sys.maxint */
-}
-
-#if 0
-/* Integers are quite normal objects, to make object handling uniform.
-   (Using odd pointers to represent integers would save much space
-   but require extra checks for this special case throughout the code.)
-   Since a typical Python program spends much of its time allocating
-   and deallocating integers, these operations should be very fast.
-   Therefore we use a dedicated allocation scheme with a much lower
-   overhead (in space and time) than straight malloc(): a simple
-   dedicated free list, filled when necessary with memory from malloc().
-
-   block_list is a singly-linked list of all PyIntBlocks ever allocated,
-   linked via their next members.  PyIntBlocks are never returned to the
-   system before shutdown (PyInt_Fini).
-
-   free_list is a singly-linked list of available PyIntObjects, linked
-   via abuse of their ob_type members.
-*/
-
-#define BLOCK_SIZE	1000	/* 1K less typical malloc overhead */
-#define BHEAD_SIZE	8	/* Enough for a 64-bit pointer */
-#define N_INTOBJECTS	((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
-
-struct _intblock {
-	struct _intblock *next;
-	PyIntObject objects[N_INTOBJECTS];
-};
-
-typedef struct _intblock PyIntBlock;
-
-static PyIntBlock *block_list = NULL;
-static PyIntObject *free_list = NULL;
-
-static PyIntObject *
-fill_free_list(void)
-{
-	PyIntObject *p, *q;
-	/* Python's object allocator isn't appropriate for large blocks. */
-	p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
-	if (p == NULL)
-		return (PyIntObject *) PyErr_NoMemory();
-	((PyIntBlock *)p)->next = block_list;
-	block_list = (PyIntBlock *)p;
-	/* Link the int objects together, from rear to front, then return
-	   the address of the last int object in the block. */
-	p = &((PyIntBlock *)p)->objects[0];
-	q = p + N_INTOBJECTS;
-	while (--q > p)
-		Py_Type(q) = (struct _typeobject *)(q-1);
-	Py_Type(q) = NULL;
-	return p + N_INTOBJECTS - 1;
-}
-
-#ifndef NSMALLPOSINTS
-#define NSMALLPOSINTS		257
-#endif
-#ifndef NSMALLNEGINTS
-#define NSMALLNEGINTS		5
-#endif
-#if NSMALLNEGINTS + NSMALLPOSINTS > 0
-/* References to small integers are saved in this array so that they
-   can be shared.
-   The integers that are saved are those in the range
-   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
-*/
-static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
-#endif
-#ifdef COUNT_ALLOCS
-int quick_int_allocs, quick_neg_int_allocs;
-#endif
-
-PyObject *
-PyInt_FromLong(long ival)
-{
-	register PyIntObject *v;
-#if NSMALLNEGINTS + NSMALLPOSINTS > 0
-	if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
-		v = small_ints[ival + NSMALLNEGINTS];
-		Py_INCREF(v);
-#ifdef COUNT_ALLOCS
-		if (ival >= 0)
-			quick_int_allocs++;
-		else
-			quick_neg_int_allocs++;
-#endif
-		return (PyObject *) v;
-	}
-#endif
-	if (free_list == NULL) {
-		if ((free_list = fill_free_list()) == NULL)
-			return NULL;
-	}
-	/* Inline PyObject_New */
-	v = free_list;
-	free_list = (PyIntObject *)Py_Type(v);
-	PyObject_INIT(v, &PyInt_Type);
-	v->ob_ival = ival;
-	return (PyObject *) v;
-}
-
-PyObject *
-PyInt_FromSize_t(size_t ival)
-{
-	if (ival <= LONG_MAX)
-		return PyInt_FromLong((long)ival);
-	return _PyLong_FromSize_t(ival);
-}
-
-PyObject *
-PyInt_FromSsize_t(Py_ssize_t ival)
-{
-	if (ival >= LONG_MIN && ival <= LONG_MAX)
-		return PyInt_FromLong((long)ival);
-	return _PyLong_FromSsize_t(ival);
-}
-
-static void
-int_dealloc(PyIntObject *v)
-{
-	if (PyInt_CheckExact(v)) {
-		Py_Type(v) = (struct _typeobject *)free_list;
-		free_list = v;
-	}
-	else
-		Py_Type(v)->tp_free((PyObject *)v);
-}
-
-static void
-int_free(PyIntObject *v)
-{
-	Py_Type(v) = (struct _typeobject *)free_list;
-	free_list = v;
-}
-
-long
-PyInt_AsLong(register PyObject *op)
-{
-	PyNumberMethods *nb;
-	PyIntObject *io;
-	long val;
-
-	if (op && PyInt_Check(op))
-		return PyInt_AS_LONG((PyIntObject*) op);
-
-	if (op == NULL || (nb = Py_Type(op)->tp_as_number) == NULL ||
-	    nb->nb_int == NULL) {
-		PyErr_SetString(PyExc_TypeError, "an integer is required");
-		return -1;
-	}
-
-	io = (PyIntObject*) (*nb->nb_int) (op);
-	if (io == NULL)
-		return -1;
-	if (!PyInt_Check(io)) {
-		if (PyLong_Check(io)) {
-			/* got a long? => retry int conversion */
-			val = PyLong_AsLong((PyObject *)io);
-			Py_DECREF(io);
-			if ((val == -1) && PyErr_Occurred())
-				return -1;
-			return val;
-		}
-		else
-		{
-			Py_DECREF(io);
-			PyErr_SetString(PyExc_TypeError,
-					"nb_int should return int object");
-			return -1;
-		}
-	}
-
-	val = PyInt_AS_LONG(io);
-	Py_DECREF(io);
-
-	return val;
-}
-
-Py_ssize_t
-PyInt_AsSsize_t(register PyObject *op)
-{
-#if SIZEOF_SIZE_T != SIZEOF_LONG
-	PyNumberMethods *nb;
-	PyIntObject *io;
-	Py_ssize_t val;
-#endif
-
-	if (op == NULL) {
-		PyErr_SetString(PyExc_TypeError, "an integer is required");
-		return -1;
-	}
-
-	if (PyInt_Check(op))
-		return PyInt_AS_LONG((PyIntObject*) op);
-	if (PyLong_Check(op))
-		return _PyLong_AsSsize_t(op);
-#if SIZEOF_SIZE_T == SIZEOF_LONG
-	return PyInt_AsLong(op);
-#else
-
-	if ((nb = Py_Type(op)->tp_as_number) == NULL ||
-	    (nb->nb_int == NULL && nb->nb_long == 0)) {
-		PyErr_SetString(PyExc_TypeError, "an integer is required");
-		return -1;
-	}
-
-	if (nb->nb_long != 0)
-		io = (PyIntObject*) (*nb->nb_long) (op);
-	else
-		io = (PyIntObject*) (*nb->nb_int) (op);
-	if (io == NULL)
-		return -1;
-	if (!PyInt_Check(io)) {
-		if (PyLong_Check(io)) {
-			/* got a long? => retry int conversion */
-			val = _PyLong_AsSsize_t((PyObject *)io);
-			Py_DECREF(io);
-			if ((val == -1) && PyErr_Occurred())
-				return -1;
-			return val;
-		}
-		else
-		{
-			Py_DECREF(io);
-			PyErr_SetString(PyExc_TypeError,
-					"nb_int should return int object");
-			return -1;
-		}
-	}
-
-	val = PyInt_AS_LONG(io);
-	Py_DECREF(io);
-
-	return val;
-#endif
-}
-
-unsigned long
-PyInt_AsUnsignedLongMask(register PyObject *op)
-{
-	PyNumberMethods *nb;
-	PyIntObject *io;
-	unsigned long val;
-
-	if (op && PyInt_Check(op))
-		return PyInt_AS_LONG((PyIntObject*) op);
-	if (op && PyLong_Check(op))
-		return PyLong_AsUnsignedLongMask(op);
-
-	if (op == NULL || (nb = Py_Type(op)->tp_as_number) == NULL ||
-	    nb->nb_int == NULL) {
-		PyErr_SetString(PyExc_TypeError, "an integer is required");
-		return (unsigned long)-1;
-	}
-
-	io = (PyIntObject*) (*nb->nb_int) (op);
-	if (io == NULL)
-		return (unsigned long)-1;
-	if (!PyInt_Check(io)) {
-		if (PyLong_Check(io)) {
-			val = PyLong_AsUnsignedLongMask((PyObject *)io);
-			Py_DECREF(io);
-			if (PyErr_Occurred())
-				return (unsigned long)-1;
-			return val;
-		}
-		else
-		{
-			Py_DECREF(io);
-			PyErr_SetString(PyExc_TypeError,
-					"nb_int should return int object");
-			return (unsigned long)-1;
-		}
-	}
-
-	val = PyInt_AS_LONG(io);
-	Py_DECREF(io);
-
-	return val;
-}
-
-#ifdef HAVE_LONG_LONG
-unsigned PY_LONG_LONG
-PyInt_AsUnsignedLongLongMask(register PyObject *op)
-{
-	PyNumberMethods *nb;
-	PyIntObject *io;
-	unsigned PY_LONG_LONG val;
-
-	if (op && PyInt_Check(op))
-		return PyInt_AS_LONG((PyIntObject*) op);
-	if (op && PyLong_Check(op))
-		return PyLong_AsUnsignedLongLongMask(op);
-
-	if (op == NULL || (nb = Py_Type(op)->tp_as_number) == NULL ||
-	    nb->nb_int == NULL) {
-		PyErr_SetString(PyExc_TypeError, "an integer is required");
-		return (unsigned PY_LONG_LONG)-1;
-	}
-
-	io = (PyIntObject*) (*nb->nb_int) (op);
-	if (io == NULL)
-		return (unsigned PY_LONG_LONG)-1;
-	if (!PyInt_Check(io)) {
-		if (PyLong_Check(io)) {
-			val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
-			Py_DECREF(io);
-			if (PyErr_Occurred())
-				return (unsigned PY_LONG_LONG)-1;
-			return val;
-		}
-		else
-		{
-			Py_DECREF(io);
-			PyErr_SetString(PyExc_TypeError,
-					"nb_int should return int object");
-			return (unsigned PY_LONG_LONG)-1;
-		}
-	}
-
-	val = PyInt_AS_LONG(io);
-	Py_DECREF(io);
-
-	return val;
-}
-#endif
-
-PyObject *
-PyInt_FromString(char *s, char **pend, int base)
-{
-	char *end;
-	long x;
-	Py_ssize_t slen;
-	PyObject *sobj, *srepr;
-
-	if ((base != 0 && base < 2) || base > 36) {
-		PyErr_SetString(PyExc_ValueError,
-				"int() base must be >= 2 and <= 36");
-		return NULL;
-	}
-
-	while (*s && isspace(Py_CHARMASK(*s)))
-		s++;
-	errno = 0;
-	if (base == 0 && s[0] == '0') {
-		x = (long) PyOS_strtoul(s, &end, base);
-		if (x < 0)
-			return PyLong_FromString(s, pend, base);
-	}
-	else
-		x = PyOS_strtol(s, &end, base);
-	if (end == s || !isalnum(Py_CHARMASK(end[-1])))
-		goto bad;
-	while (*end && isspace(Py_CHARMASK(*end)))
-		end++;
-	if (*end != '\0') {
-  bad:
-		slen = strlen(s) < 200 ? strlen(s) : 200;
-		sobj = PyString_FromStringAndSize(s, slen);
-		if (sobj == NULL)
-			return NULL;
-		srepr = PyObject_ReprStr8(sobj);
-		Py_DECREF(sobj);
-		if (srepr == NULL)
-			return NULL;
-		PyErr_Format(PyExc_ValueError,
-			     "invalid literal for int() with base %d: %s",
-			     base, PyString_AS_STRING(srepr));
-		Py_DECREF(srepr);
-		return NULL;
-	}
-	else if (errno != 0)
-		return PyLong_FromString(s, pend, base);
-	if (pend)
-		*pend = end;
-	return PyInt_FromLong(x);
-}
-
-PyObject *
-PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
-{
-	PyObject *result;
-	char *buffer = (char *)PyMem_MALLOC(length+1);
-
-	if (buffer == NULL)
-		return PyErr_NoMemory();
-
-	if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
-		PyMem_FREE(buffer);
-		return NULL;
-	}
-	result = PyInt_FromString(buffer, NULL, base);
-	PyMem_FREE(buffer);
-	return result;
-}
-
-/* Methods */
-
-/* Integers are seen as the "smallest" of all numeric types and thus
-   don't have any knowledge about conversion of other types to
-   integers. */
-
-#define CONVERT_TO_LONG(obj, lng)		\
-	if (PyInt_Check(obj)) {			\
-		lng = PyInt_AS_LONG(obj);	\
-	}					\
-	else {					\
-		Py_INCREF(Py_NotImplemented);	\
-		return Py_NotImplemented;	\
-	}
-
-/* ARGSUSED */
-static int
-int_print(PyIntObject *v, FILE *fp, int flags)
-     /* flags -- not used but required by interface */
-{
-	fprintf(fp, "%ld", v->ob_ival);
-	return 0;
-}
-
-static PyObject *
-int_repr(PyIntObject *v)
-{
-	return PyUnicode_FromFormat("%ld", v->ob_ival);
-}
-
-static int
-int_compare(PyIntObject *v, PyIntObject *w)
-{
-	register long i = v->ob_ival;
-	register long j = w->ob_ival;
-	return (i < j) ? -1 : (i > j) ? 1 : 0;
-}
-
-static PyObject *
-int_richcompare(PyObject *self, PyObject *other, int op)
-{
-	if (!PyInt_Check(self) || !PyInt_Check(other)) {
-		Py_INCREF(Py_NotImplemented);
-		return Py_NotImplemented;
-	}
-	return Py_CmpToRich(op, int_compare((PyIntObject *)self, 
-					    (PyIntObject *)other));
-}
-
-static long
-int_hash(PyIntObject *v)
-{
-	/* XXX If this is changed, you also need to change the way
-	   Python's long, float and complex types are hashed. */
-	long x = v -> ob_ival;
-	if (x == -1)
-		x = -2;
-	return x;
-}
-
-static PyObject *
-int_add(PyIntObject *v, PyIntObject *w)
-{
-	register long a, b, x;
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	x = a + b;
-	if ((x^a) >= 0 || (x^b) >= 0)
-		return PyInt_FromLong(x);
-	return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
-}
-
-static PyObject *
-int_sub(PyIntObject *v, PyIntObject *w)
-{
-	register long a, b, x;
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	x = a - b;
-	if ((x^a) >= 0 || (x^~b) >= 0)
-		return PyInt_FromLong(x);
-	return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
-						     (PyObject *)w);
-}
-
-/*
-Integer overflow checking for * is painful:  Python tried a couple ways, but
-they didn't work on all platforms, or failed in endcases (a product of
--sys.maxint-1 has been a particular pain).
-
-Here's another way:
-
-The native long product x*y is either exactly right or *way* off, being
-just the last n bits of the true product, where n is the number of bits
-in a long (the delivered product is the true product plus i*2**n for
-some integer i).
-
-The native double product (double)x * (double)y is subject to three
-rounding errors:  on a sizeof(long)==8 box, each cast to double can lose
-info, and even on a sizeof(long)==4 box, the multiplication can lose info.
-But, unlike the native long product, it's not in *range* trouble:  even
-if sizeof(long)==32 (256-bit longs), the product easily fits in the
-dynamic range of a double.  So the leading 50 (or so) bits of the double
-product are correct.
-
-We check these two ways against each other, and declare victory if they're
-approximately the same.  Else, because the native long product is the only
-one that can lose catastrophic amounts of information, it's the native long
-product that must have overflowed.
-*/
-
-static PyObject *
-int_mul(PyObject *v, PyObject *w)
-{
-	long a, b;
-	long longprod;			/* a*b in native long arithmetic */
-	double doubled_longprod;	/* (double)longprod */
-	double doubleprod;		/* (double)a * (double)b */
-
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	longprod = a * b;
-	doubleprod = (double)a * (double)b;
-	doubled_longprod = (double)longprod;
-
-	/* Fast path for normal case:  small multiplicands, and no info
-	   is lost in either method. */
-	if (doubled_longprod == doubleprod)
-		return PyInt_FromLong(longprod);
-
-	/* Somebody somewhere lost info.  Close enough, or way off?  Note
-	   that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
-	   The difference either is or isn't significant compared to the
-	   true value (of which doubleprod is a good approximation).
-	*/
-	{
-		const double diff = doubled_longprod - doubleprod;
-		const double absdiff = diff >= 0.0 ? diff : -diff;
-		const double absprod = doubleprod >= 0.0 ? doubleprod :
-							  -doubleprod;
-		/* absdiff/absprod <= 1/32 iff
-		   32 * absdiff <= absprod -- 5 good bits is "close enough" */
-		if (32.0 * absdiff <= absprod)
-			return PyInt_FromLong(longprod);
-		else
-			return PyLong_Type.tp_as_number->nb_multiply(v, w);
-	}
-}
-
-/* Integer overflow checking for unary negation: on a 2's-complement
- * box, -x overflows iff x is the most negative long.  In this case we
- * get -x == x.  However, -x is undefined (by C) if x /is/ the most
- * negative long (it's a signed overflow case), and some compilers care.
- * So we cast x to unsigned long first.  However, then other compilers
- * warn about applying unary minus to an unsigned operand.  Hence the
- * weird "0-".
- */
-#define UNARY_NEG_WOULD_OVERFLOW(x)	\
-	((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
-
-/* Return type of i_divmod */
-enum divmod_result {
-	DIVMOD_OK,		/* Correct result */
-	DIVMOD_OVERFLOW,	/* Overflow, try again using longs */
-	DIVMOD_ERROR		/* Exception raised */
-};
-
-static enum divmod_result
-i_divmod(register long x, register long y,
-         long *p_xdivy, long *p_xmody)
-{
-	long xdivy, xmody;
-
-	if (y == 0) {
-		PyErr_SetString(PyExc_ZeroDivisionError,
-				"integer division or modulo by zero");
-		return DIVMOD_ERROR;
-	}
-	/* (-sys.maxint-1)/-1 is the only overflow case. */
-	if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
-		return DIVMOD_OVERFLOW;
-	xdivy = x / y;
-	xmody = x - xdivy * y;
-	/* If the signs of x and y differ, and the remainder is non-0,
-	 * C89 doesn't define whether xdivy is now the floor or the
-	 * ceiling of the infinitely precise quotient.  We want the floor,
-	 * and we have it iff the remainder's sign matches y's.
-	 */
-	if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
-		xmody += y;
-		--xdivy;
-		assert(xmody && ((y ^ xmody) >= 0));
-	}
-	*p_xdivy = xdivy;
-	*p_xmody = xmody;
-	return DIVMOD_OK;
-}
-
-static PyObject *
-int_floor_div(PyIntObject *x, PyIntObject *y)
-{
-	long xi, yi;
-	long d, m;
-	CONVERT_TO_LONG(x, xi);
-	CONVERT_TO_LONG(y, yi);
-	switch (i_divmod(xi, yi, &d, &m)) {
-	case DIVMOD_OK:
-		return PyInt_FromLong(d);
-	case DIVMOD_OVERFLOW:
-		return PyLong_Type.tp_as_number->nb_floor_divide((PyObject *)x,
-							         (PyObject *)y);
-	default:
-		return NULL;
-	}
-}
-
-static PyObject *
-int_true_divide(PyObject *v, PyObject *w)
-{
-	/* If they aren't both ints, give someone else a chance.  In
-	   particular, this lets int/long get handled by longs, which
-	   underflows to 0 gracefully if the long is too big to convert
-	   to float. */
-	if (PyInt_Check(v) && PyInt_Check(w))
-		return PyFloat_Type.tp_as_number->nb_true_divide(v, w);
-	Py_INCREF(Py_NotImplemented);
-	return Py_NotImplemented;
-}
-
-static PyObject *
-int_mod(PyIntObject *x, PyIntObject *y)
-{
-	long xi, yi;
-	long d, m;
-	CONVERT_TO_LONG(x, xi);
-	CONVERT_TO_LONG(y, yi);
-	switch (i_divmod(xi, yi, &d, &m)) {
-	case DIVMOD_OK:
-		return PyInt_FromLong(m);
-	case DIVMOD_OVERFLOW:
-		return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
-							      (PyObject *)y);
-	default:
-		return NULL;
-	}
-}
-
-static PyObject *
-int_divmod(PyIntObject *x, PyIntObject *y)
-{
-	long xi, yi;
-	long d, m;
-	CONVERT_TO_LONG(x, xi);
-	CONVERT_TO_LONG(y, yi);
-	switch (i_divmod(xi, yi, &d, &m)) {
-	case DIVMOD_OK:
-		return Py_BuildValue("(ll)", d, m);
-	case DIVMOD_OVERFLOW:
-		return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
-							   (PyObject *)y);
-	default:
-		return NULL;
-	}
-}
-
-static PyObject *
-int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
-{
-	register long iv, iw, iz=0, ix, temp, prev;
-	CONVERT_TO_LONG(v, iv);
-	CONVERT_TO_LONG(w, iw);
-	if (iw < 0) {
-		if ((PyObject *)z != Py_None) {
-			PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
-			     "cannot be negative when 3rd argument specified");
-			return NULL;
-		}
-		/* Return a float.  This works because we know that
-		   this calls float_pow() which converts its
-		   arguments to double. */
-		return PyFloat_Type.tp_as_number->nb_power(
-			(PyObject *)v, (PyObject *)w, (PyObject *)z);
-	}
- 	if ((PyObject *)z != Py_None) {
-		CONVERT_TO_LONG(z, iz);
-		if (iz == 0) {
-			PyErr_SetString(PyExc_ValueError,
-					"pow() 3rd argument cannot be 0");
-			return NULL;
-		}
-	}
-	/*
-	 * XXX: The original exponentiation code stopped looping
-	 * when temp hit zero; this code will continue onwards
-	 * unnecessarily, but at least it won't cause any errors.
-	 * Hopefully the speed improvement from the fast exponentiation
-	 * will compensate for the slight inefficiency.
-	 * XXX: Better handling of overflows is desperately needed.
-	 */
- 	temp = iv;
-	ix = 1;
-	while (iw > 0) {
-	 	prev = ix;	/* Save value for overflow check */
-	 	if (iw & 1) {
-		 	ix = ix*temp;
-			if (temp == 0)
-				break; /* Avoid ix / 0 */
-			if (ix / temp != prev) {
-				return PyLong_Type.tp_as_number->nb_power(
-					(PyObject *)v,
-					(PyObject *)w,
-					(PyObject *)z);
-			}
-		}
-	 	iw >>= 1;	/* Shift exponent down by 1 bit */
-	        if (iw==0) break;
-	 	prev = temp;
-	 	temp *= temp;	/* Square the value of temp */
-	 	if (prev != 0 && temp / prev != prev) {
-			return PyLong_Type.tp_as_number->nb_power(
-				(PyObject *)v, (PyObject *)w, (PyObject *)z);
-		}
-	 	if (iz) {
-			/* If we did a multiplication, perform a modulo */
-		 	ix = ix % iz;
-		 	temp = temp % iz;
-		}
-	}
-	if (iz) {
-	 	long div, mod;
-		switch (i_divmod(ix, iz, &div, &mod)) {
-		case DIVMOD_OK:
-			ix = mod;
-			break;
-		case DIVMOD_OVERFLOW:
-			return PyLong_Type.tp_as_number->nb_power(
-				(PyObject *)v, (PyObject *)w, (PyObject *)z);
-		default:
-			return NULL;
-		}
-	}
-	return PyInt_FromLong(ix);
-}
-
-static PyObject *
-int_neg(PyIntObject *v)
-{
-	register long a;
-	a = v->ob_ival;
-        /* check for overflow */
-	if (UNARY_NEG_WOULD_OVERFLOW(a)) {
-		PyObject *o = PyLong_FromLong(a);
-		if (o != NULL) {
-			PyObject *result = PyNumber_Negative(o);
-			Py_DECREF(o);
-			return result;
-		}
-		return NULL;
-	}
-	return PyInt_FromLong(-a);
-}
-
-static PyObject *
-int_pos(PyIntObject *v)
-{
-	if (PyInt_CheckExact(v)) {
-		Py_INCREF(v);
-		return (PyObject *)v;
-	}
-	else
-		return PyInt_FromLong(v->ob_ival);
-}
-
-static PyObject *
-int_abs(PyIntObject *v)
-{
-	if (v->ob_ival >= 0)
-		return int_pos(v);
-	else
-		return int_neg(v);
-}
-
-static int
-int_bool(PyIntObject *v)
-{
-	return v->ob_ival != 0;
-}
-
-static PyObject *
-int_invert(PyIntObject *v)
-{
-	return PyInt_FromLong(~v->ob_ival);
-}
-
-static PyObject *
-int_lshift(PyIntObject *v, PyIntObject *w)
-{
-	long a, b, c;
-	PyObject *vv, *ww, *result;
-
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	if (b < 0) {
-		PyErr_SetString(PyExc_ValueError, "negative shift count");
-		return NULL;
-	}
-	if (a == 0 || b == 0)
-		return int_pos(v);
-	if (b >= LONG_BIT) {
-		vv = PyLong_FromLong(PyInt_AS_LONG(v));
-		if (vv == NULL)
-			return NULL;
-		ww = PyLong_FromLong(PyInt_AS_LONG(w));
-		if (ww == NULL) {
-			Py_DECREF(vv);
-			return NULL;
-		}
-		result = PyNumber_Lshift(vv, ww);
-		Py_DECREF(vv);
-		Py_DECREF(ww);
-		return result;
-	}
-	c = a << b;
-	if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
-		vv = PyLong_FromLong(PyInt_AS_LONG(v));
-		if (vv == NULL)
-			return NULL;
-		ww = PyLong_FromLong(PyInt_AS_LONG(w));
-		if (ww == NULL) {
-			Py_DECREF(vv);
-			return NULL;
-		}
-		result = PyNumber_Lshift(vv, ww);
-		Py_DECREF(vv);
-		Py_DECREF(ww);
-		return result;
-	}
-	return PyInt_FromLong(c);
-}
-
-static PyObject *
-int_rshift(PyIntObject *v, PyIntObject *w)
-{
-	register long a, b;
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	if (b < 0) {
-		PyErr_SetString(PyExc_ValueError, "negative shift count");
-		return NULL;
-	}
-	if (a == 0 || b == 0)
-		return int_pos(v);
-	if (b >= LONG_BIT) {
-		if (a < 0)
-			a = -1;
-		else
-			a = 0;
-	}
-	else {
-		a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
-	}
-	return PyInt_FromLong(a);
-}
-
-static PyObject *
-int_and(PyIntObject *v, PyIntObject *w)
-{
-	register long a, b;
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	return PyInt_FromLong(a & b);
-}
-
-static PyObject *
-int_xor(PyIntObject *v, PyIntObject *w)
-{
-	register long a, b;
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	return PyInt_FromLong(a ^ b);
-}
-
-static PyObject *
-int_or(PyIntObject *v, PyIntObject *w)
-{
-	register long a, b;
-	CONVERT_TO_LONG(v, a);
-	CONVERT_TO_LONG(w, b);
-	return PyInt_FromLong(a | b);
-}
-
-static PyObject *
-int_int(PyIntObject *v)
-{
-	if (PyInt_CheckExact(v))
-		Py_INCREF(v);
-	else
-		v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
-	return (PyObject *)v;
-}
-
-static PyObject *
-int_long(PyIntObject *v)
-{
-	return PyLong_FromLong((v -> ob_ival));
-}
-
-static PyObject *
-int_float(PyIntObject *v)
-{
-	return PyFloat_FromDouble((double)(v -> ob_ival));
-}
-
-static PyObject *
-int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
-
-static PyObject *
-int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-	PyObject *x = NULL;
-	int base = -909;
-	static char *kwlist[] = {"x", "base", 0};
-
-	if (type != &PyInt_Type)
-		return int_subtype_new(type, args, kwds); /* Wimp out */
-	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
-					 &x, &base))
-		return NULL;
-	if (x == NULL)
-		return PyInt_FromLong(0L);
-	if (base == -909)
-		return PyNumber_Int(x);
-	if (PyString_Check(x)) {
-		/* Since PyInt_FromString doesn't have a length parameter,
-		 * check here for possible NULs in the string. */
-		char *string = PyString_AS_STRING(x);
-		if (strlen(string) != PyString_Size(x)) {
-			/* create a repr() of the input string,
-			 * just like PyInt_FromString does */
-			PyObject *srepr;
-			srepr = PyObject_ReprStr8(x);
-			if (srepr == NULL)
-				return NULL;
-			PyErr_Format(PyExc_ValueError,
-			     "invalid literal for int() with base %d: %s",
-			     base, PyString_AS_STRING(srepr));
-			Py_DECREF(srepr);
-			return NULL;
-		}
-		return PyInt_FromString(string, NULL, base);
-	}
-	if (PyUnicode_Check(x))
-		return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
-					 PyUnicode_GET_SIZE(x),
-					 base);
-	PyErr_SetString(PyExc_TypeError,
-			"int() can't convert non-string with explicit base");
-	return NULL;
-}
-
-/* Wimpy, slow approach to tp_new calls for subtypes of int:
-   first create a regular int from whatever arguments we got,
-   then allocate a subtype instance and initialize its ob_ival
-   from the regular int.  The regular int is then thrown away.
-*/
-static PyObject *
-int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-	PyObject *tmp, *newobj;
-	long ival;
-
-	assert(PyType_IsSubtype(type, &PyInt_Type));
-	tmp = int_new(&PyInt_Type, args, kwds);
-	if (tmp == NULL)
-		return NULL;
-	if (!PyInt_Check(tmp)) {
-		ival = PyLong_AsLong(tmp);
-		if (ival == -1 && PyErr_Occurred()) {
-			Py_DECREF(tmp);
-			return NULL;
-		}
-	} else {
-		ival = ((PyIntObject *)tmp)->ob_ival;
-	}
-
-	newobj = type->tp_alloc(type, 0);
-	if (newobj == NULL) {
-		Py_DECREF(tmp);
-		return NULL;
-	}
-	((PyIntObject *)newobj)->ob_ival = ival;
-	Py_DECREF(tmp);
-	return newobj;
-}
-
-static PyObject *
-int_getnewargs(PyIntObject *v)
-{
-	return Py_BuildValue("(l)", v->ob_ival);
-}
-
-static PyMethodDef int_methods[] = {
-	{"__getnewargs__",	(PyCFunction)int_getnewargs,	METH_NOARGS},
-	{NULL,		NULL}		/* sentinel */
-};
-
-PyDoc_STRVAR(int_doc,
-"int(x[, base]) -> integer\n\
-\n\
-Convert a string or number to an integer, if possible.  A floating point\n\
-argument will be truncated towards zero (this does not include a string\n\
-representation of a floating point number!)  When converting a string, use\n\
-the optional base.  It is an error to supply a base when converting a\n\
-non-string.  If base is zero, the proper base is guessed based on the\n\
-string content.  If the argument is outside the integer range a\n\
-long object will be returned instead.");
-
-static PyNumberMethods int_as_number = {
-	(binaryfunc)int_add,	/*nb_add*/
-	(binaryfunc)int_sub,	/*nb_subtract*/
-	(binaryfunc)int_mul,	/*nb_multiply*/
-	(binaryfunc)int_mod,	/*nb_remainder*/
-	(binaryfunc)int_divmod,	/*nb_divmod*/
-	(ternaryfunc)int_pow,	/*nb_power*/
-	(unaryfunc)int_neg,	/*nb_negative*/
-	(unaryfunc)int_pos,	/*nb_positive*/
-	(unaryfunc)int_abs,	/*nb_absolute*/
-	(inquiry)int_bool,	/*nb_bool*/
-	(unaryfunc)int_invert,	/*nb_invert*/
-	(binaryfunc)int_lshift,	/*nb_lshift*/
-	(binaryfunc)int_rshift,	/*nb_rshift*/
-	(binaryfunc)int_and,	/*nb_and*/
-	(binaryfunc)int_xor,	/*nb_xor*/
-	(binaryfunc)int_or,	/*nb_or*/
-	0,			/*nb_coerce*/
-	(unaryfunc)int_int,	/*nb_int*/
-	(unaryfunc)int_long,	/*nb_long*/
-	(unaryfunc)int_float,	/*nb_float*/
-	0,			/*nb_oct*/ /* not in use */
-	0, 			/*nb_hex*/ /* not in use */
-	0,			/*nb_inplace_add*/
-	0,			/*nb_inplace_subtract*/
-	0,			/*nb_inplace_multiply*/
-	0,			/*nb_inplace_remainder*/
-	0,			/*nb_inplace_power*/
-	0,			/*nb_inplace_lshift*/
-	0,			/*nb_inplace_rshift*/
-	0,			/*nb_inplace_and*/
-	0,			/*nb_inplace_xor*/
-	0,			/*nb_inplace_or*/
-	(binaryfunc)int_floor_div,	/* nb_floor_divide */
-	int_true_divide,	/* nb_true_divide */
-	0,			/* nb_inplace_floor_divide */
-	0,			/* nb_inplace_true_divide */
-	(unaryfunc)int_int,	/* nb_index */
-};
-
-PyTypeObject PyInt_Type = {
-	PyVarObject_HEAD_INIT(&PyType_Type, 0)
-	"int",
-	sizeof(PyIntObject),
-	0,
-	(destructor)int_dealloc,		/* tp_dealloc */
-	(printfunc)int_print,			/* tp_print */
-	0,					/* tp_getattr */
-	0,					/* tp_setattr */
-	0,					/* tp_compare */
-	(reprfunc)int_repr,			/* tp_repr */
-	&int_as_number,				/* tp_as_number */
-	0,					/* tp_as_sequence */
-	0,					/* tp_as_mapping */
-	(hashfunc)int_hash,			/* tp_hash */
-        0,					/* tp_call */
-        (reprfunc)int_repr,			/* tp_str */
-	PyObject_GenericGetAttr,		/* tp_getattro */
-	0,					/* tp_setattro */
-	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
-		Py_TPFLAGS_INT_SUBCLASS,	/* tp_flags */
-	int_doc,				/* tp_doc */
-	0,					/* tp_traverse */
-	0,					/* tp_clear */
-	int_richcompare,			/* tp_richcompare */
-	0,					/* tp_weaklistoffset */
-	0,					/* tp_iter */
-	0,					/* tp_iternext */
-	int_methods,				/* tp_methods */
-	0,					/* tp_members */
-	0,					/* tp_getset */
-	0,					/* tp_base */
-	0,					/* tp_dict */
-	0,					/* tp_descr_get */
-	0,					/* tp_descr_set */
-	0,					/* tp_dictoffset */
-	0,					/* tp_init */
-	0,					/* tp_alloc */
-	int_new,				/* tp_new */
-	(freefunc)int_free,           		/* tp_free */
-};
-
-int
-_PyInt_Init(void)
-{
-	PyIntObject *v;
-	int ival;
-#if NSMALLNEGINTS + NSMALLPOSINTS > 0
-	for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
-              if (!free_list && (free_list = fill_free_list()) == NULL)
-			return 0;
-		/* PyObject_New is inlined */
-		v = free_list;
-		free_list = (PyIntObject *)Py_Type(v);
-		PyObject_INIT(v, &PyInt_Type);
-		v->ob_ival = ival;
-		small_ints[ival + NSMALLNEGINTS] = v;
-	}
-#endif
-	return 1;
-}
-
-void
-PyInt_Fini(void)
-{
-	PyIntObject *p;
-	PyIntBlock *list, *next;
-	int i;
-	unsigned int ctr;
-	int bc, bf;	/* block count, number of freed blocks */
-	int irem, isum;	/* remaining unfreed ints per block, total */
-
-#if NSMALLNEGINTS + NSMALLPOSINTS > 0
-        PyIntObject **q;
-
-        i = NSMALLNEGINTS + NSMALLPOSINTS;
-        q = small_ints;
-        while (--i >= 0) {
-                Py_XDECREF(*q);
-                *q++ = NULL;
-        }
-#endif
-	bc = 0;
-	bf = 0;
-	isum = 0;
-	list = block_list;
-	block_list = NULL;
-	free_list = NULL;
-	while (list != NULL) {
-		bc++;
-		irem = 0;
-		for (ctr = 0, p = &list->objects[0];
-		     ctr < N_INTOBJECTS;
-		     ctr++, p++) {
-			if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
-				irem++;
-		}
-		next = list->next;
-		if (irem) {
-			list->next = block_list;
-			block_list = list;
-			for (ctr = 0, p = &list->objects[0];
-			     ctr < N_INTOBJECTS;
-			     ctr++, p++) {
-				if (!PyInt_CheckExact(p) ||
-				    p->ob_refcnt == 0) {
-					Py_Type(p) = (struct _typeobject *)
-						free_list;
-					free_list = p;
-				}
-#if NSMALLNEGINTS + NSMALLPOSINTS > 0
-				else if (-NSMALLNEGINTS <= p->ob_ival &&
-					 p->ob_ival < NSMALLPOSINTS &&
-					 small_ints[p->ob_ival +
-						    NSMALLNEGINTS] == NULL) {
-					Py_INCREF(p);
-					small_ints[p->ob_ival +
-						   NSMALLNEGINTS] = p;
-				}
-#endif
-			}
-		}
-		else {
-			PyMem_FREE(list);
-			bf++;
-		}
-		isum += irem;
-		list = next;
-	}
-	if (!Py_VerboseFlag)
-		return;
-	fprintf(stderr, "# cleanup ints");
-	if (!isum) {
-		fprintf(stderr, "\n");
-	}
-	else {
-		fprintf(stderr,
-			": %d unfreed int%s in %d out of %d block%s\n",
-			isum, isum == 1 ? "" : "s",
-			bc - bf, bc, bc == 1 ? "" : "s");
-	}
-	if (Py_VerboseFlag > 1) {
-		list = block_list;
-		while (list != NULL) {
-			for (ctr = 0, p = &list->objects[0];
-			     ctr < N_INTOBJECTS;
-			     ctr++, p++) {
-				if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
-					/* XXX(twouters) cast refcount to
-					   long until %zd is universally
-					   available
-					 */
-					fprintf(stderr,
-				"#   <int at %p, refcnt=%ld, val=%ld>\n",
-						p, (long)p->ob_refcnt,
-						p->ob_ival);
-			}
-			list = list->next;
-		}
-	}
-}
-#endif /* if 0 */

Modified: python/branches/py3k-buffer/Objects/listobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/listobject.c	(original)
+++ python/branches/py3k-buffer/Objects/listobject.c	Fri Aug 17 20:48:09 2007
@@ -272,33 +272,6 @@
 	Py_TRASHCAN_SAFE_END(op)
 }
 
-static int
-list_print(PyListObject *op, FILE *fp, int flags)
-{
-	int rc;
-	Py_ssize_t i;
-
-	rc = Py_ReprEnter((PyObject*)op);
-	if (rc != 0) {
-		if (rc < 0)
-			return rc;
-		fprintf(fp, "[...]");
-		return 0;
-	}
-	fprintf(fp, "[");
-	for (i = 0; i < Py_Size(op); i++) {
-		if (i > 0)
-			fprintf(fp, ", ");
-		if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
-			Py_ReprLeave((PyObject *)op);
-			return -1;
-		}
-	}
-	fprintf(fp, "]");
-	Py_ReprLeave((PyObject *)op);
-	return 0;
-}
-
 static PyObject *
 list_repr(PyListObject *v)
 {
@@ -2665,7 +2638,7 @@
 	sizeof(PyListObject),
 	0,
 	(destructor)list_dealloc,		/* tp_dealloc */
-	(printfunc)list_print,			/* tp_print */
+	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/longobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/longobject.c	(original)
+++ python/branches/py3k-buffer/Objects/longobject.c	Fri Aug 17 20:48:09 2007
@@ -7,6 +7,12 @@
 
 #include <ctype.h>
 
+long
+PyInt_GetMax(void)
+{
+	return LONG_MAX;	/* To initialize sys.maxint */
+}
+
 #ifndef NSMALLPOSINTS
 #define NSMALLPOSINTS		257
 #endif
@@ -1985,7 +1991,7 @@
 /* forward */
 static PyLongObject *x_divrem
 	(PyLongObject *, PyLongObject *, PyLongObject **);
-static PyObject *long_pos(PyLongObject *);
+static PyObject *long_long(PyObject *v);
 static int long_divrem(PyLongObject *, PyLongObject *,
 	PyLongObject **, PyLongObject **);
 
@@ -3181,17 +3187,6 @@
 }
 
 static PyObject *
-long_pos(PyLongObject *v)
-{
-	if (PyLong_CheckExact(v)) {
-		Py_INCREF(v);
-		return (PyObject *)v;
-	}
-	else
-		return _PyLong_Copy(v);
-}
-
-static PyObject *
 long_neg(PyLongObject *v)
 {
 	PyLongObject *z;
@@ -3209,7 +3204,7 @@
 	if (Py_Size(v) < 0)
 		return long_neg(v);
 	else
-		return long_pos(v);
+		return long_long((PyObject *)v);
 }
 
 static int
@@ -3496,12 +3491,6 @@
 }
 
 static PyObject *
-long_int(PyObject *v)
-{
-	return long_long(v);
-}
-
-static PyObject *
 long_float(PyObject *v)
 {
 	double result;
@@ -3607,11 +3596,38 @@
 	return Py_BuildValue("(N)", _PyLong_Copy(v));
 }
 
+static PyObject *
+long_getN(PyLongObject *v, void *context) {
+	return PyLong_FromLong((intptr_t)context);
+}
+
 static PyMethodDef long_methods[] = {
+	{"conjugate",	(PyCFunction)long_long,	METH_NOARGS,
+	 "Returns self, the complex conjugate of any int."},
 	{"__getnewargs__",	(PyCFunction)long_getnewargs,	METH_NOARGS},
 	{NULL,		NULL}		/* sentinel */
 };
 
+static PyGetSetDef long_getset[] = {
+    {"real", 
+     (getter)long_long, (setter)NULL,
+     "the real part of a complex number",
+     NULL},
+    {"imag", 
+     (getter)long_getN, (setter)NULL,
+     "the imaginary part of a complex number",
+     (void*)0},
+    {"numerator", 
+     (getter)long_long, (setter)NULL,
+     "the numerator of a rational number in lowest terms",
+     NULL},
+    {"denominator", 
+     (getter)long_getN, (setter)NULL,
+     "the denominator of a rational number in lowest terms",
+     (void*)1},
+    {NULL}  /* Sentinel */
+};
+
 PyDoc_STRVAR(long_doc,
 "int(x[, base]) -> integer\n\
 \n\
@@ -3629,7 +3645,7 @@
 			long_divmod,	/*nb_divmod*/
 			long_pow,	/*nb_power*/
 	(unaryfunc) 	long_neg,	/*nb_negative*/
-	(unaryfunc) 	long_pos,	/*tp_positive*/
+	(unaryfunc) 	long_long,	/*tp_positive*/
 	(unaryfunc) 	long_abs,	/*tp_absolute*/
 	(inquiry)	long_bool,	/*tp_bool*/
 	(unaryfunc)	long_invert,	/*nb_invert*/
@@ -3639,7 +3655,7 @@
 			long_xor,	/*nb_xor*/
 			long_or,	/*nb_or*/
 			0,		/*nb_coerce*/
-			long_int,	/*nb_int*/
+			long_long,	/*nb_int*/
 			long_long,	/*nb_long*/
 			long_float,	/*nb_float*/
 			0,		/*nb_oct*/ /* not used */
@@ -3694,7 +3710,7 @@
 	0,					/* tp_iternext */
 	long_methods,				/* tp_methods */
 	0,					/* tp_members */
-	0,					/* tp_getset */
+	long_getset,				/* tp_getset */
 	0,					/* tp_base */
 	0,					/* tp_dict */
 	0,					/* tp_descr_get */

Modified: python/branches/py3k-buffer/Objects/object.c
==============================================================================
--- python/branches/py3k-buffer/Objects/object.c	(original)
+++ python/branches/py3k-buffer/Objects/object.c	Fri Aug 17 20:48:09 2007
@@ -279,7 +279,7 @@
 			   universally available */
 			fprintf(fp, "<refcnt %ld at %p>",
 				(long)op->ob_refcnt, op);
-		else if (Py_Type(op)->tp_print == NULL) {
+		else {
 			PyObject *s;
 			if (flags & Py_PRINT_RAW)
 				s = PyObject_Str(op);
@@ -293,8 +293,6 @@
 			}
 			Py_XDECREF(s);
 		}
-		else
-			ret = (*Py_Type(op)->tp_print)(op, fp, flags);
 	}
 	if (ret == 0) {
 		if (ferror(fp)) {

Modified: python/branches/py3k-buffer/Objects/setobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/setobject.c	(original)
+++ python/branches/py3k-buffer/Objects/setobject.c	Fri Aug 17 20:48:09 2007
@@ -565,56 +565,14 @@
 	Py_TRASHCAN_SAFE_END(so)
 }
 
-static int
-set_tp_print(PySetObject *so, FILE *fp, int flags)
-{
-	setentry *entry;
-	Py_ssize_t pos=0;
-	char *emit = "";	/* No separator emitted on first pass */
-	char *separator = ", ";
-	int literalform = 0;
-	int status = Py_ReprEnter((PyObject*)so);
-
-	if (status != 0) {
-		if (status < 0)
-			return status;
-		fprintf(fp, "%s(...)", Py_Type(so)->tp_name);
-		return 0;
-	}        
-
-	if (!so->used) {
-		Py_ReprLeave((PyObject*)so);
-		fprintf(fp, "%s()", Py_Type(so)->tp_name);
-		return 0;
-	}
-
-	if (Py_Type(so) == &PySet_Type) {
-		literalform = 1;
-		fprintf(fp, "{");
-	} else
-		fprintf(fp, "%s([", Py_Type(so)->tp_name);
-	while (set_next(so, &pos, &entry)) {
-		fputs(emit, fp);
-		emit = separator;
-		if (PyObject_Print(entry->key, fp, 0) != 0) {
-			Py_ReprLeave((PyObject*)so);
-			return -1;
-		}
-	}
-	if (literalform)
-		fputs("}", fp);
-	else
-		fputs("])", fp);
-	Py_ReprLeave((PyObject*)so);
-	return 0;
-}
-
 static PyObject *
 set_repr(PySetObject *so)
 {
 	PyObject *keys, *result=NULL;
 	Py_UNICODE *u;
 	int status = Py_ReprEnter((PyObject*)so);
+	PyObject *listrepr;
+	Py_ssize_t newsize;
 
 	if (status != 0) {
 		if (status < 0)
@@ -632,30 +590,30 @@
 	if (keys == NULL)
 		goto done;
 
-	if (Py_Type(so) != &PySet_Type) {
-		result = PyUnicode_FromFormat("%s(%R)", Py_Type(so)->tp_name, keys);
+	listrepr = PyObject_Repr(keys);
+	Py_DECREF(keys);
+	if (listrepr == NULL) {
 		Py_DECREF(keys);
+		goto done;
 	}
-	else {
-		PyObject *listrepr = PyObject_Repr(keys);
-		Py_ssize_t newsize;
-		Py_DECREF(keys);
-		if (listrepr == NULL) {
-			Py_DECREF(keys);
-			goto done;
-		}
-		newsize = PyUnicode_GET_SIZE(listrepr);
-		result = PyUnicode_FromUnicode(NULL, newsize);
-		if (result) {
-			u = PyUnicode_AS_UNICODE(result);
-			*u++ = '{';
-			/* Omit the brackets from the listrepr */
-			Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1,
-			                   PyUnicode_GET_SIZE(listrepr)-2);
-			u += newsize-2;
-			*u++ = '}';
-		}
-		Py_DECREF(listrepr);
+	newsize = PyUnicode_GET_SIZE(listrepr);
+	result = PyUnicode_FromUnicode(NULL, newsize);
+	if (result) {
+		u = PyUnicode_AS_UNICODE(result);
+		*u++ = '{';
+		/* Omit the brackets from the listrepr */
+		Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1,
+				   PyUnicode_GET_SIZE(listrepr)-2);
+		u += newsize-2;
+		*u++ = '}';
+	}
+	Py_DECREF(listrepr);
+	if (Py_Type(so) != &PySet_Type) {
+		PyObject *tmp = PyUnicode_FromFormat("%s(%U)",
+						     Py_Type(so)->tp_name,
+						     result);
+		Py_DECREF(result);
+		result = tmp;
 	}
 done:
 	Py_ReprLeave((PyObject*)so);
@@ -1957,7 +1915,7 @@
 	0,				/* tp_itemsize */
 	/* methods */
 	(destructor)set_dealloc,	/* tp_dealloc */
-	(printfunc)set_tp_print,	/* tp_print */
+	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
 	set_nocmp,			/* tp_compare */
@@ -2050,7 +2008,7 @@
 	0,				/* tp_itemsize */
 	/* methods */
 	(destructor)set_dealloc,	/* tp_dealloc */
-	(printfunc)set_tp_print,	/* tp_print */
+	0,				/* tp_print */
 	0,				/* tp_getattr */
 	0,				/* tp_setattr */
 	set_nocmp,			/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/stringobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/stringobject.c	(original)
+++ python/branches/py3k-buffer/Objects/stringobject.c	Fri Aug 17 20:48:09 2007
@@ -764,71 +764,6 @@
 #include "stringlib/partition.h"
 
 
-static int
-string_print(PyStringObject *op, FILE *fp, int flags)
-{
-	Py_ssize_t i;
-	char c;
-	int quote;
-
-	/* XXX Ought to check for interrupts when writing long strings */
-	if (! PyString_CheckExact(op)) {
-		int ret;
-		/* A str subclass may have its own __str__ method. */
-		op = (PyStringObject *) PyObject_Str((PyObject *)op);
-		if (op == NULL)
-			return -1;
-		ret = string_print(op, fp, flags);
-		Py_DECREF(op);
-		return ret;
-	}
-	if (flags & Py_PRINT_RAW) {
-		char *data = op->ob_sval;
-		Py_ssize_t size = Py_Size(op);
-		while (size > INT_MAX) {
-			/* Very long strings cannot be written atomically.
-			 * But don't write exactly INT_MAX bytes at a time
-			 * to avoid memory aligment issues.
-			 */
-			const int chunk_size = INT_MAX & ~0x3FFF;
-			fwrite(data, 1, chunk_size, fp);
-			data += chunk_size;
-			size -= chunk_size;
-		}
-#ifdef __VMS
-                if (size) fwrite(data, (int)size, 1, fp);
-#else
-                fwrite(data, 1, (int)size, fp);
-#endif
-		return 0;
-	}
-
-	/* figure out which quote to use; single is preferred */
-	quote = '\'';
-	if (memchr(op->ob_sval, '\'', Py_Size(op)) &&
-	    !memchr(op->ob_sval, '"', Py_Size(op)))
-		quote = '"';
-
-	fputc(quote, fp);
-	for (i = 0; i < Py_Size(op); i++) {
-		c = op->ob_sval[i];
-		if (c == quote || c == '\\')
-			fprintf(fp, "\\%c", c);
-                else if (c == '\t')
-                        fprintf(fp, "\\t");
-                else if (c == '\n')
-                        fprintf(fp, "\\n");
-                else if (c == '\r')
-                        fprintf(fp, "\\r");
-		else if (c < ' ' || c >= 0x7f)
-			fprintf(fp, "\\x%02x", c & 0xff);
-		else
-			fputc(c, fp);
-	}
-	fputc(quote, fp);
-	return 0;
-}
-
 PyObject *
 PyString_Repr(PyObject *obj, int smartquotes)
 {
@@ -1832,7 +1767,7 @@
 "S.find(sub [,start [,end]]) -> int\n\
 \n\
 Return the lowest index in S where substring sub is found,\n\
-such that sub is contained within s[start,end].  Optional\n\
+such that sub is contained within s[start:end].  Optional\n\
 arguments start and end are interpreted as in slice notation.\n\
 \n\
 Return -1 on failure.");
@@ -1871,7 +1806,7 @@
 "S.rfind(sub [,start [,end]]) -> int\n\
 \n\
 Return the highest index in S where substring sub is found,\n\
-such that sub is contained within s[start,end].  Optional\n\
+such that sub is contained within s[start:end].  Optional\n\
 arguments start and end are interpreted as in slice notation.\n\
 \n\
 Return -1 on failure.");
@@ -3947,7 +3882,7 @@
 	sizeof(PyStringObject),
 	sizeof(char),
  	string_dealloc, 			/* tp_dealloc */
-	(printfunc)string_print, 		/* tp_print */
+	0,			 		/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/tupleobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/tupleobject.c	(original)
+++ python/branches/py3k-buffer/Objects/tupleobject.c	Fri Aug 17 20:48:09 2007
@@ -184,23 +184,6 @@
 	Py_TRASHCAN_SAFE_END(op)
 }
 
-static int
-tupleprint(PyTupleObject *op, FILE *fp, int flags)
-{
-	Py_ssize_t i;
-	fprintf(fp, "(");
-	for (i = 0; i < Py_Size(op); i++) {
-		if (i > 0)
-			fprintf(fp, ", ");
-		if (PyObject_Print(op->ob_item[i], fp, 0) != 0)
-			return -1;
-	}
-	if (Py_Size(op) == 1)
-		fprintf(fp, ",");
-	fprintf(fp, ")");
-	return 0;
-}
-
 static PyObject *
 tuplerepr(PyTupleObject *v)
 {
@@ -653,7 +636,7 @@
 	sizeof(PyTupleObject) - sizeof(PyObject *),
 	sizeof(PyObject *),
 	(destructor)tupledealloc,		/* tp_dealloc */
-	(printfunc)tupleprint,			/* tp_print */
+	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */

Modified: python/branches/py3k-buffer/Objects/typeobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/typeobject.c	(original)
+++ python/branches/py3k-buffer/Objects/typeobject.c	Fri Aug 17 20:48:09 2007
@@ -1579,7 +1579,8 @@
 	if (n == 0)
 		n = 1;
 	for (i = 0; i < n; i++, p++) {
-		if (i > 255 || (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_')) {
+		if (*p > 127 ||
+		    (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_')) {
 			PyErr_SetString(PyExc_TypeError,
 					"__slots__ must be identifiers");
 			return 0;
@@ -2200,11 +2201,21 @@
 	return list;
 }
 
+static PyObject *
+type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
+{
+	return PyDict_New();
+}
+
 static PyMethodDef type_methods[] = {
 	{"mro", (PyCFunction)mro_external, METH_NOARGS,
 	 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
 	{"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
 	 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
+        {"__prepare__", (PyCFunction)type_prepare,
+	 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+         PyDoc_STR("__prepare__() -> dict\n"
+                   "used to create the namespace for the class statement")},
 	{0}
 };
 
@@ -3247,7 +3258,6 @@
 	basebase = base->tp_base;
 
 	COPYSLOT(tp_dealloc);
-	COPYSLOT(tp_print);
 	if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
 		type->tp_getattr = base->tp_getattr;
 		type->tp_getattro = base->tp_getattro;
@@ -5199,10 +5209,8 @@
 
 	TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
 	       "x.__str__() <==> str(x)"),
-	TPSLOT("__str__", tp_print, NULL, NULL, ""),
 	TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
 	       "x.__repr__() <==> repr(x)"),
-	TPSLOT("__repr__", tp_print, NULL, NULL, ""),
 	TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
 	       "x.__cmp__(y) <==> cmp(x,y)"),
 	TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,

Modified: python/branches/py3k-buffer/Objects/unicodeobject.c
==============================================================================
--- python/branches/py3k-buffer/Objects/unicodeobject.c	(original)
+++ python/branches/py3k-buffer/Objects/unicodeobject.c	Fri Aug 17 20:48:09 2007
@@ -427,7 +427,9 @@
 {
     PyUnicodeObject *unicode;
     /* If the Unicode data is known at construction time, we can apply
-       some optimizations which share commonly used objects. */
+       some optimizations which share commonly used objects.
+       Also, this means the input must be UTF-8, so fall back to the
+       UTF-8 decoder at the end. */
     if (u != NULL) {
 
 	/* Optimization for empty strings */
@@ -436,8 +438,9 @@
 	    return (PyObject *)unicode_empty;
 	}
 
-	/* Single characters are shared when using this constructor */
-	if (size == 1) {
+	/* Single characters are shared when using this constructor.
+           Restrict to ASCII, since the input must be UTF-8. */
+	if (size == 1 && Py_CHARMASK(*u) < 128) {
 	    unicode = unicode_latin1[Py_CHARMASK(*u)];
 	    if (!unicode) {
 		unicode = _PyUnicode_New(1);
@@ -449,21 +452,14 @@
 	    Py_INCREF(unicode);
 	    return (PyObject *)unicode;
 	}
+
+        return PyUnicode_DecodeUTF8(u, size, NULL);
     }
 
     unicode = _PyUnicode_New(size);
     if (!unicode)
         return NULL;
 
-    /* Copy the Unicode data into the new object */
-    if (u != NULL) {
-        Py_UNICODE *p = unicode->str;
-        while (size--)
-            *p++ = Py_CHARMASK(*u++);
-        /* Don't need to write trailing 0 because
-           that's already done by _PyUnicode_New */
-    }
-
     return (PyObject *)unicode;
 }
 
@@ -1269,7 +1265,7 @@
 static
 int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
                  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,
+                 const char **input, const char **inend, Py_ssize_t *startinpos, Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
                  PyObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
 {
     static char *argparse = "O!n;decoding error handler must return (unicode, int) tuple";
@@ -1277,9 +1273,11 @@
     PyObject *restuple = NULL;
     PyObject *repunicode = NULL;
     Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
+    Py_ssize_t insize;
     Py_ssize_t requiredsize;
     Py_ssize_t newpos;
     Py_UNICODE *repptr;
+    PyObject *inputobj = NULL;
     Py_ssize_t repsize;
     int res = -1;
 
@@ -1291,7 +1289,7 @@
 
     if (*exceptionObject == NULL) {
     	*exceptionObject = PyUnicodeDecodeError_Create(
-	    encoding, input, insize, *startinpos, *endinpos, reason);
+	    encoding, *input, *inend-*input, *startinpos, *endinpos, reason);
 	if (*exceptionObject == NULL)
 	   goto onError;
     }
@@ -1313,6 +1311,19 @@
     }
     if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
 	goto onError;
+
+    /* Copy back the bytes variables, which might have been modified by the
+       callback */
+    inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
+    if (!inputobj)
+        goto onError;
+    if (!PyBytes_Check(inputobj)) {
+	PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
+    }
+    *input = PyBytes_AS_STRING(inputobj);
+    insize = PyBytes_GET_SIZE(inputobj);
+    *inend = *input + insize;
+
     if (newpos<0)
 	newpos = insize+newpos;
     if (newpos<0 || newpos>insize) {
@@ -1335,10 +1346,11 @@
 	*outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
     }
     *endinpos = newpos;
-    *inptr = input + newpos;
+    *inptr = *input + newpos;
     Py_UNICODE_COPY(*outptr, repptr, repsize);
     *outptr += repsize;
     *outpos += repsize;
+
     /* we made it! */
     res = 0;
 
@@ -1503,7 +1515,7 @@
         else if (SPECIAL(ch,0,0)) {
             errmsg = "unexpected special character";
             s++;
-	        goto utf7Error;
+            goto utf7Error;
         }
         else {
             *p++ = ch;
@@ -1516,7 +1528,7 @@
         if (unicode_decode_call_errorhandler(
              errors, &errorHandler,
              "utf7", errmsg,
-             starts, size, &startinpos, &endinpos, &exc, &s,
+             &starts, &e, &startinpos, &endinpos, &exc, &s,
              (PyObject **)&unicode, &outpos, &p))
         goto onError;
     }
@@ -1527,7 +1539,7 @@
         if (unicode_decode_call_errorhandler(
              errors, &errorHandler,
              "utf7", "unterminated shift sequence",
-             starts, size, &startinpos, &endinpos, &exc, &s,
+             &starts, &e, &startinpos, &endinpos, &exc, &s,
              (PyObject **)&unicode, &outpos, &p))
             goto onError;
         if (s < e)
@@ -1848,7 +1860,7 @@
     if (unicode_decode_call_errorhandler(
 	     errors, &errorHandler,
 	     "utf8", errmsg,
-	     starts, size, &startinpos, &endinpos, &exc, &s,
+	     &starts, &e, &startinpos, &endinpos, &exc, &s,
 	     (PyObject **)&unicode, &outpos, &p))
 	goto onError;
     }
@@ -2132,7 +2144,7 @@
 	if (unicode_decode_call_errorhandler(
 	         errors, &errorHandler,
 	         "utf16", errmsg,
-	         starts, size, &startinpos, &endinpos, &exc, (const char **)&q,
+	         &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
 	         (PyObject **)&unicode, &outpos, &p))
 	    goto onError;
     }
@@ -2342,7 +2354,7 @@
                 if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "unicodeescape", "end of string in escape sequence",
-                    starts, size, &startinpos, &endinpos, &exc, &s,
+                    &starts, &end, &startinpos, &endinpos, &exc, &s,
                     (PyObject **)&v, &outpos, &p))
                     goto onError;
                 goto nextByte;
@@ -2354,7 +2366,7 @@
                     if (unicode_decode_call_errorhandler(
                         errors, &errorHandler,
                         "unicodeescape", message,
-                        starts, size, &startinpos, &endinpos, &exc, &s,
+                        &starts, &end, &startinpos, &endinpos, &exc, &s,
                         (PyObject **)&v, &outpos, &p))
                         goto onError;
                     goto nextByte;
@@ -2393,7 +2405,7 @@
                 if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "unicodeescape", "illegal Unicode character",
-                    starts, size, &startinpos, &endinpos, &exc, &s,
+                    &starts, &end, &startinpos, &endinpos, &exc, &s,
                     (PyObject **)&v, &outpos, &p))
                     goto onError;
             }
@@ -2435,7 +2447,7 @@
             if (unicode_decode_call_errorhandler(
                 errors, &errorHandler,
                 "unicodeescape", message,
-                starts, size, &startinpos, &endinpos, &exc, &s,
+                &starts, &end, &startinpos, &endinpos, &exc, &s,
                 (PyObject **)&v, &outpos, &p))
                 goto onError;
             break;
@@ -2449,7 +2461,7 @@
                 if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "unicodeescape", message,
-                    starts, size, &startinpos, &endinpos, &exc, &s,
+                    &starts, &end, &startinpos, &endinpos, &exc, &s,
                     (PyObject **)&v, &outpos, &p))
                     goto onError;
             }
@@ -2728,7 +2740,7 @@
 		if (unicode_decode_call_errorhandler(
 		    errors, &errorHandler,
 		    "rawunicodeescape", "truncated \\uXXXX",
-		    starts, size, &startinpos, &endinpos, &exc, &s,
+		    &starts, &end, &startinpos, &endinpos, &exc, &s,
 		    (PyObject **)&v, &outpos, &p))
 		    goto onError;
 		goto nextByte;
@@ -2746,7 +2758,7 @@
             if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "rawunicodeescape", "\\Uxxxxxxxx out of range",
-		    starts, size, &startinpos, &endinpos, &exc, &s,
+		    &starts, &end, &startinpos, &endinpos, &exc, &s,
 		    (PyObject **)&v, &outpos, &p))
 		    goto onError;
         }
@@ -2897,7 +2909,7 @@
             if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "unicode_internal", reason,
-                    starts, size, &startinpos, &endinpos, &exc, &s,
+                    &starts, &end, &startinpos, &endinpos, &exc, &s,
                     (PyObject **)&v, &outpos, &p)) {
                 goto onError;
             }
@@ -3277,7 +3289,7 @@
 	    if (unicode_decode_call_errorhandler(
 		 errors, &errorHandler,
 		 "ascii", "ordinal not in range(128)",
-		 starts, size, &startinpos, &endinpos, &exc, &s,
+		 &starts, &e, &startinpos, &endinpos, &exc, &s,
 		 (PyObject **)&v, &outpos, &p))
 		goto onError;
 	}
@@ -3578,7 +3590,7 @@
 		if (unicode_decode_call_errorhandler(
 		     errors, &errorHandler,
 		     "charmap", "character maps to <undefined>",
-		     starts, size, &startinpos, &endinpos, &exc, &s,
+		     &starts, &e, &startinpos, &endinpos, &exc, &s,
 		     (PyObject **)&v, &outpos, &p)) {
 		    goto onError;
 		}
@@ -3628,7 +3640,7 @@
 		if (unicode_decode_call_errorhandler(
 		     errors, &errorHandler,
 		     "charmap", "character maps to <undefined>",
-		     starts, size, &startinpos, &endinpos, &exc, &s,
+		     &starts, &e, &startinpos, &endinpos, &exc, &s,
 		     (PyObject **)&v, &outpos, &p)) {
 		    Py_DECREF(x);
 		    goto onError;
@@ -6283,7 +6295,7 @@
 "S.find(sub [,start [,end]]) -> int\n\
 \n\
 Return the lowest index in S where substring sub is found,\n\
-such that sub is contained within s[start,end].  Optional\n\
+such that sub is contained within s[start:end].  Optional\n\
 arguments start and end are interpreted as in slice notation.\n\
 \n\
 Return -1 on failure.");
@@ -7137,7 +7149,7 @@
 "S.rfind(sub [,start [,end]]) -> int\n\
 \n\
 Return the highest index in S where substring sub is found,\n\
-such that sub is contained within s[start,end].  Optional\n\
+such that sub is contained within s[start:end].  Optional\n\
 arguments start and end are interpreted as in slice notation.\n\
 \n\
 Return -1 on failure.");
@@ -8561,9 +8573,9 @@
 }
 
 PyDoc_STRVAR(unicode_doc,
-"unicode(string [, encoding[, errors]]) -> object\n\
+"str(string [, encoding[, errors]]) -> object\n\
 \n\
-Create a new Unicode object from the given encoded string.\n\
+Create a new string object from the given encoded string.\n\
 encoding defaults to the current default string encoding.\n\
 errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
 

Modified: python/branches/py3k-buffer/PC/VC6/pythoncore.dsp
==============================================================================
--- python/branches/py3k-buffer/PC/VC6/pythoncore.dsp	(original)
+++ python/branches/py3k-buffer/PC/VC6/pythoncore.dsp	Fri Aug 17 20:48:09 2007
@@ -431,10 +431,6 @@
 # End Source File
 # Begin Source File
 
-SOURCE=..\..\Objects\intobject.c
-# End Source File
-# Begin Source File
-
 SOURCE=..\..\Objects\iterobject.c
 # End Source File
 # Begin Source File

Modified: python/branches/py3k-buffer/PC/_winreg.c
==============================================================================
--- python/branches/py3k-buffer/PC/_winreg.c	(original)
+++ python/branches/py3k-buffer/PC/_winreg.c	Fri Aug 17 20:48:09 2007
@@ -387,17 +387,6 @@
 	return PyLong_FromVoidPtr(pyhkey->hkey);
 }
 
-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;
-}
-
 static PyObject *
 PyHKEY_strFunc(PyObject *ob)
 {
@@ -464,7 +453,7 @@
 	sizeof(PyHKEYObject),
 	0,
 	PyHKEY_deallocFunc,		/* tp_dealloc */
-	PyHKEY_printFunc,		/* tp_print */
+	0,				/* tp_print */
 	PyHKEY_getattr,			/* tp_getattr */
 	0,				/* tp_setattr */
 	PyHKEY_compareFunc,		/* tp_compare */

Modified: python/branches/py3k-buffer/PC/os2emx/Makefile
==============================================================================
--- python/branches/py3k-buffer/PC/os2emx/Makefile	(original)
+++ python/branches/py3k-buffer/PC/os2emx/Makefile	Fri Aug 17 20:48:09 2007
@@ -381,7 +381,6 @@
 		Objects/frameobject.c \
 		Objects/funcobject.c \
 		Objects/genobject.c \
-		Objects/intobject.c \
 		Objects/iterobject.c \
 		Objects/listobject.c \
 		Objects/longobject.c \
@@ -420,7 +419,7 @@
 		Parser/printgrammar.c \
 		Parser/grammar.c \
 		Parser/firstsets.c) \
-		
+
 OBJ.PGEN=	$(addprefix $(OUT),$(notdir $(SRC.PGEN:.c=$O)))
 
 SRC.EXE=	$(TOP)Modules/python.c

Modified: python/branches/py3k-buffer/PC/os2emx/python25.def
==============================================================================
--- python/branches/py3k-buffer/PC/os2emx/python25.def	(original)
+++ python/branches/py3k-buffer/PC/os2emx/python25.def	Fri Aug 17 20:48:09 2007
@@ -339,21 +339,6 @@
   "PyGen_NeedsFinalizing"
   "PyGen_Type"
 
-; From python25_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 python25_s.lib(iterobject)
   "PySeqIter_New"
   "PyCallIter_New"

Modified: python/branches/py3k-buffer/PC/os2vacpp/makefile
==============================================================================
--- python/branches/py3k-buffer/PC/os2vacpp/makefile	(original)
+++ python/branches/py3k-buffer/PC/os2vacpp/makefile	Fri Aug 17 20:48:09 2007
@@ -158,7 +158,6 @@
                   $(PATHOBJ)\FloatObject.obj   \
                   $(PATHOBJ)\FrameObject.obj   \
                   $(PATHOBJ)\FuncObject.obj    \
-                  $(PATHOBJ)\IntObject.obj     \
                   $(PATHOBJ)\IterObject.obj    \
                   $(PATHOBJ)\ListObject.obj    \
                   $(PATHOBJ)\LongObject.obj    \
@@ -856,20 +855,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-sunaudiodev.obj: $(PY_INCLUDE)\abstract.h $(OS2TCPIP)\Include\sys\ioctl.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 \
-	 $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h \
-	 $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h \
-	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\structmember.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 syslogmodule.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 \
@@ -1077,19 +1062,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\structmember.h \
 	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
 
-intobject.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 $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 listobject.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 $(PY_INCLUDE)\floatobject.h \
@@ -1623,4 +1595,3 @@
 	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\structmember.h \
 	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-

Modified: python/branches/py3k-buffer/PC/os2vacpp/makefile.omk
==============================================================================
--- python/branches/py3k-buffer/PC/os2vacpp/makefile.omk	(original)
+++ python/branches/py3k-buffer/PC/os2vacpp/makefile.omk	Fri Aug 17 20:48:09 2007
@@ -123,7 +123,6 @@
                   FloatObject.obj   \
                   FrameObject.obj   \
                   FuncObject.obj    \
-                  IntObject.obj     \
                   ListObject.obj    \
                   LongObject.obj    \
                   MethodObject.obj  \
@@ -171,8 +170,6 @@
   #
   # Multimedia:
   # audioop.c       -- Various Compute Operations on Audio Samples
-  # imageop.c       -- Various Compute Operations on Video Samples
-  # sunaudiodev.c   -- Wrapper of Sun Audio Device API
 
   # Database:
   # dbmmodule.c     -- Wrapper of DBM Database API (Generic Flavor)
@@ -627,15 +624,6 @@
 	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
 	 stringobject.h sysmodule.h traceback.h tupleobject.h
 
-sunaudiodev.obj: abstract.h c:\mptn\include\sys\ioctl.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 methodobject.h modsupport.h \
-	 moduleobject.h mymalloc.h myproto.h object.h objimpl.h pydebug.h \
-	 pyerrors.h pyfpe.h pystate.h python.h pythonrun.h rangeobject.h \
-	 sliceobject.h stringobject.h structmember.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 syslogmodule.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 \
@@ -760,14 +748,6 @@
 	 stringobject.h structmember.h sysmodule.h traceback.h \
 	 tupleobject.h
 
-intobject.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 \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 listobject.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/py3k-buffer/PC/pyconfig.h
==============================================================================
--- python/branches/py3k-buffer/PC/pyconfig.h	(original)
+++ python/branches/py3k-buffer/PC/pyconfig.h	Fri Aug 17 20:48:09 2007
@@ -32,6 +32,11 @@
 #define MS_WINCE
 #endif
 
+/* Deprecated USE_DL_EXPORT macro - please use Py_BUILD_CORE */
+#ifdef USE_DL_EXPORT
+#	define Py_BUILD_CORE
+#endif /* USE_DL_EXPORT */
+
 /* Visual Studio 2005 introduces deprecation warnings for
    "insecure" and POSIX functions. The insecure functions should
    be replaced by *_s versions (according to Microsoft); the
@@ -140,7 +145,7 @@
 #if defined(_M_IA64)
 #define COMPILER _Py_PASTE_VERSION("64 bit (Itanium)")
 #define MS_WINI64
-#elif defined(_M_X64)
+#elif defined(_M_X64) || defined(_M_AMD64)
 #define COMPILER _Py_PASTE_VERSION("64 bit (AMD64)")
 #define MS_WINX64
 #else
@@ -151,12 +156,26 @@
 /* set the version macros for the windows headers */
 #ifdef MS_WINX64
 /* 64 bit only runs on XP or greater */
-#define _WIN32_WINNT 0x0501
-#define WINVER 0x0501
+#define Py_WINVER 0x0501
 #else
 /* NT 4.0 or greater required otherwise */
-#define _WIN32_WINNT 0x0400
-#define WINVER 0x0400
+#define Py_WINVER 0x0400
+#endif
+
+/* We only set these values when building Python - we don't want to force
+   these values on extensions, as that will affect the prototypes and
+   structures exposed in the Windows headers. Even when building Python, we
+   allow a single source file to override this - they may need access to
+   structures etc so it can optionally use new Windows features if it
+   determines at runtime they are available.
+*/
+#ifdef Py_BUILD_CORE
+#ifndef WINVER
+#define WINVER Py_WINVER
+#endif
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT Py_WINVER
+#endif
 #endif
 
 /* _W64 is not defined for VC6 or eVC4 */
@@ -287,11 +306,6 @@
 #	define MS_COREDLL	/* deprecated old symbol */
 #endif /* !MS_NO_COREDLL && ... */
 
-/* Deprecated USE_DL_EXPORT macro - please use Py_BUILD_CORE */
-#ifdef USE_DL_EXPORT
-#	define Py_BUILD_CORE
-#endif /* USE_DL_EXPORT */
-
 /*  All windows compilers that use this header support __declspec */
 #define HAVE_DECLSPEC_DLL
 

Modified: python/branches/py3k-buffer/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/py3k-buffer/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/py3k-buffer/PCbuild/pythoncore.vcproj	Fri Aug 17 20:48:09 2007
@@ -602,9 +602,6 @@
 			RelativePath="..\Python\importdl.c">
 		</File>
 		<File
-			RelativePath="..\Objects\intobject.c">
-		</File>
-		<File
 			RelativePath="..\Objects\iterobject.c">
 		</File>
 		<File

Modified: python/branches/py3k-buffer/PCbuild8/pythoncore/pythoncore.vcproj
==============================================================================
--- python/branches/py3k-buffer/PCbuild8/pythoncore/pythoncore.vcproj	(original)
+++ python/branches/py3k-buffer/PCbuild8/pythoncore/pythoncore.vcproj	Fri Aug 17 20:48:09 2007
@@ -856,10 +856,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Objects\intobject.c"
-				>
-			</File>
-			<File
 				RelativePath="..\..\Objects\iterobject.c"
 				>
 			</File>

Modified: python/branches/py3k-buffer/Parser/tokenizer.c
==============================================================================
--- python/branches/py3k-buffer/Parser/tokenizer.c	(original)
+++ python/branches/py3k-buffer/Parser/tokenizer.c	Fri Aug 17 20:48:09 2007
@@ -444,6 +444,34 @@
 	ungetc(c, tok->fp);
 }
 
+/* Check whether the characters at s start a valid
+   UTF-8 sequence. Return the number of characters forming
+   the sequence if yes, 0 if not.  */
+static int valid_utf8(const unsigned char* s)
+{
+	int expected = 0;
+	int length;
+	if (*s < 0x80)
+		/* single-byte code */
+		return 1;
+	if (*s < 0xc0)
+		/* following byte */
+		return 0;
+	if (*s < 0xE0)
+		expected = 1;
+	else if (*s < 0xF0)
+		expected = 2;
+	else if (*s < 0xF8)
+		expected = 3;
+	else
+		return 0;
+	length = expected + 1;
+	for (; expected; expected--)
+		if (s[expected] < 0x80 || s[expected] >= 0xC0)
+			return 0;
+	return length;
+}
+
 /* Read a line of input from TOK. Determine encoding
    if necessary.  */
 
@@ -478,12 +506,13 @@
 		}
 	}
 #ifndef PGEN
-	/* The default encoding is ASCII, so make sure we don't have any
-           non-ASCII bytes in it. */
+	/* The default encoding is UTF-8, so make sure we don't have any
+           non-UTF-8 sequences in it. */
 	if (line && !tok->encoding) {
 		unsigned char *c;
-		for (c = (unsigned char *)line; *c; c++)
-			if (*c > 127) {
+		int length;
+		for (c = (unsigned char *)line; *c; c += length)
+			if (!(length = valid_utf8(c))) {
 				badchar = *c;
 				break;
 			}
@@ -493,7 +522,7 @@
 		/* Need to add 1 to the line number, since this line
 		   has not been counted, yet.  */
 		sprintf(buf,
-			"Non-ASCII character '\\x%.2x' "
+			"Non-UTF-8 code starting with '\\x%.2x' "
 			"in file %.200s on line %i, "
 			"but no encoding declared; "
 			"see http://www.python.org/peps/pep-0263.html for details",

Modified: python/branches/py3k-buffer/Python/ast.c
==============================================================================
--- python/branches/py3k-buffer/Python/ast.c	(original)
+++ python/branches/py3k-buffer/Python/ast.c	Fri Aug 17 20:48:09 2007
@@ -203,7 +203,8 @@
         c.c_encoding = STR(n);
         n = CHILD(n, 0);
     } else {
-        c.c_encoding = NULL;
+	/* PEP 3120 */
+        c.c_encoding = "utf-8";
     }
     c.c_arena = arena;
 
@@ -3111,6 +3112,7 @@
     return v;
 }
 
+#ifdef Py_USING_UNICODE
 static PyObject *
 decode_unicode(const char *s, size_t len, int rawmode, const char *encoding)
 {
@@ -3173,6 +3175,7 @@
     Py_XDECREF(u);
     return v;
 }
+#endif
 
 /* s is a Python string literal, including the bracketing quote characters,
  * and r &/or u prefixes (if any), and embedded escape sequences (if any).

Modified: python/branches/py3k-buffer/Python/import.c
==============================================================================
--- python/branches/py3k-buffer/Python/import.c	(original)
+++ python/branches/py3k-buffer/Python/import.c	Fri Aug 17 20:48:09 2007
@@ -2620,7 +2620,7 @@
 	buf[2] = (char) ((pyc_magic >> 16) & 0xff);
 	buf[3] = (char) ((pyc_magic >> 24) & 0xff);
 
-	return PyString_FromStringAndSize(buf, 4);
+	return PyBytes_FromStringAndSize(buf, 4);
 }
 
 static PyObject *

Modified: python/branches/py3k-buffer/Python/mactoolboxglue.c
==============================================================================
--- python/branches/py3k-buffer/Python/mactoolboxglue.c	(original)
+++ python/branches/py3k-buffer/Python/mactoolboxglue.c	Fri Aug 17 20:48:09 2007
@@ -194,7 +194,7 @@
 PyMac_BuildOSType(OSType t)
 {
 	uint32_t tmp = htonl((uint32_t)t);
-	return PyString_FromStringAndSize((char *)&tmp, 4);
+	return PyBytes_FromStringAndSize((char *)&tmp, 4);
 }
 
 /* Convert an NumVersion value to a 4-element tuple */
@@ -215,7 +215,7 @@
 	if (PyUnicode_Check(v)) {
 		v = _PyUnicode_AsDefaultEncodedString(v, NULL);
 		if (v == NULL)
-			return NULL;
+			return 0;
 	}
 	if (PyString_Check(v)) {
 		ptr = PyString_AS_STRING(v);

Modified: python/branches/py3k-buffer/Python/marshal.c
==============================================================================
--- python/branches/py3k-buffer/Python/marshal.c	(original)
+++ python/branches/py3k-buffer/Python/marshal.c	Fri Aug 17 20:48:09 2007
@@ -1189,6 +1189,7 @@
 		return NULL;
 	}
 	rf.strings = PyList_New(0);
+	rf.depth = 0;
 	result = read_object(&rf);
 	Py_DECREF(rf.strings);
 	Py_DECREF(data);

Modified: python/branches/py3k-buffer/Python/structmember.c
==============================================================================
--- python/branches/py3k-buffer/Python/structmember.c	(original)
+++ python/branches/py3k-buffer/Python/structmember.c	Fri Aug 17 20:48:09 2007
@@ -156,6 +156,12 @@
 	return -1;
 }
 
+#define WARN(msg)					\
+    do {						\
+	if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0)	\
+		return -1;				\
+    } while (0)
+
 int
 PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v)
 {
@@ -174,60 +180,54 @@
 	addr += l->offset;
 	switch (l->type) {
 	case T_BYTE:{
-		long long_val;
-		long_val = PyInt_AsLong(v);
+		long long_val = PyInt_AsLong(v);
 		if ((long_val == -1) && PyErr_Occurred())
 			return -1;
+		*(char*)addr = (char)long_val;
 		/* XXX: For compatibility, only warn about truncations
 		   for now. */
 		if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN))
-			PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to char");
-		*(char*)addr = (char)long_val;
+			WARN("Truncation of value to char");
 		break;
 		}
 	case T_UBYTE:{
-		long long_val;
-		long_val = PyInt_AsLong(v);
+		long long_val = PyInt_AsLong(v);
 		if ((long_val == -1) && PyErr_Occurred())
 			return -1;
-		if ((long_val > UCHAR_MAX) || (long_val < 0))
-			PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to unsigned char");
 		*(unsigned char*)addr = (unsigned char)long_val;
+		if ((long_val > UCHAR_MAX) || (long_val < 0))
+			WARN("Truncation of value to unsigned char");
 		break;
 		}
 	case T_SHORT:{
-		long long_val;
-		long_val = PyInt_AsLong(v);
+		long long_val = PyInt_AsLong(v);
 		if ((long_val == -1) && PyErr_Occurred())
 			return -1;
-		if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN))
-			PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to short");
 		*(short*)addr = (short)long_val;
+		if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN))
+			WARN("Truncation of value to short");
 		break;
 		}
 	case T_USHORT:{
-		long long_val;
-		long_val = PyInt_AsLong(v);
+		long long_val = PyInt_AsLong(v);
 		if ((long_val == -1) && PyErr_Occurred())
 			return -1;
-		if ((long_val > USHRT_MAX) || (long_val < 0))
-			PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to unsigned short");
 		*(unsigned short*)addr = (unsigned short)long_val;
+		if ((long_val > USHRT_MAX) || (long_val < 0))
+			WARN("Truncation of value to unsigned short");
 		break;
 		}
   	case T_INT:{
-		long long_val;
-		long_val = PyInt_AsLong(v);
+		long long_val = PyInt_AsLong(v);
 		if ((long_val == -1) && PyErr_Occurred())
 			return -1;
-		if ((long_val > INT_MAX) || (long_val < INT_MIN))
-			PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to int");
 		*(int *)addr = (int)long_val;
+		if ((long_val > INT_MAX) || (long_val < INT_MIN))
+			WARN("Truncation of value to int");
 		break;
 		}
 	case T_UINT:{
-		unsigned long ulong_val;
-		ulong_val = PyLong_AsUnsignedLong(v);
+		unsigned long ulong_val = PyLong_AsUnsignedLong(v);
 		if ((ulong_val == (unsigned int)-1) && PyErr_Occurred()) {
 			/* XXX: For compatibility, accept negative int values
 			   as well. */
@@ -235,11 +235,12 @@
 			ulong_val = PyLong_AsLong(v);
 			if ((ulong_val == (unsigned int)-1) && PyErr_Occurred())
 				return -1;
-			PyErr_Warn(PyExc_RuntimeWarning, "Writing negative value into unsigned field");
-		}
+			*(unsigned int *)addr = (unsigned int)ulong_val;
+			WARN("Writing negative value into unsigned field");
+		} else
+			*(unsigned int *)addr = (unsigned int)ulong_val;
 		if (ulong_val > UINT_MAX)
-			PyErr_Warn(PyExc_RuntimeWarning, "Truncation of value to unsigned int");
-		*(unsigned int *)addr = (unsigned int)ulong_val;
+			WARN("Truncation of value to unsigned int");
 		break;
 		}
 	case T_LONG:{
@@ -256,9 +257,10 @@
 			   as well. */
 			PyErr_Clear();
 			*(unsigned long*)addr = PyLong_AsLong(v);
-			if ((*(unsigned long*)addr == (unsigned int)-1) && PyErr_Occurred())
+			if ((*(unsigned long*)addr == (unsigned int)-1)
+			    && PyErr_Occurred())
 				return -1;
-			PyErr_Warn(PyExc_RuntimeWarning, "Writing negative value into unsigned field");
+			WARN("Writing negative value into unsigned field");
 		}
 		break;
 		}
@@ -270,8 +272,7 @@
 		break;
 		}
 	case T_FLOAT:{
-		double double_val;
-		double_val = PyFloat_AsDouble(v);
+		double double_val = PyFloat_AsDouble(v);
 		if ((double_val == -1) && PyErr_Occurred())
 			return -1;
 		*(float*)addr = (float)double_val;

Modified: python/branches/py3k-buffer/Python/symtable.c
==============================================================================
--- python/branches/py3k-buffer/Python/symtable.c	(original)
+++ python/branches/py3k-buffer/Python/symtable.c	Fri Aug 17 20:48:09 2007
@@ -1471,10 +1471,10 @@
 	else {
             if (st->st_cur->ste_type != ModuleBlock) {
                 int lineno = st->st_cur->ste_lineno;
-                if (!symtable_warn(st, IMPORT_STAR_WARNING, lineno)) {
-                    Py_DECREF(store_name);
-                    return 0;
-		}
+                PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING);
+                PyErr_SyntaxLocation(st->st_filename, lineno);
+                Py_DECREF(store_name);
+                return 0;
             }
 	    st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR;
 	    Py_DECREF(store_name);

Modified: python/branches/py3k-buffer/RISCOS/Makefile
==============================================================================
--- python/branches/py3k-buffer/RISCOS/Makefile	(original)
+++ python/branches/py3k-buffer/RISCOS/Makefile	Fri Aug 17 20:48:09 2007
@@ -151,7 +151,6 @@
 	@.^.Objects.o.methodobject\
 	@.^.Objects.o.longobject\
 	@.^.Objects.o.listobject\
-	@.^.Objects.o.intobject\
 	@.^.Objects.o.boolobject\
 	@.^.Objects.o.iterobject\
 	@.^.Objects.o.funcobject\

Modified: python/branches/py3k-buffer/Tools/bgen/bgen/bgenGenerator.py
==============================================================================
--- python/branches/py3k-buffer/Tools/bgen/bgen/bgenGenerator.py	(original)
+++ python/branches/py3k-buffer/Tools/bgen/bgen/bgenGenerator.py	Fri Aug 17 20:48:09 2007
@@ -16,7 +16,7 @@
 class BaseFunctionGenerator:
 
     def __init__(self, name, condition=None, callname=None, modifiers=None):
-        if DEBUG: print "<--", name
+        if DEBUG: print("<--", name)
         self.name = name
         if callname:
             self.callname = callname
@@ -36,7 +36,7 @@
     def generate(self):
         if not self.checkgenerate():
             return
-        if DEBUG: print "-->", self.name
+        if DEBUG: print("-->", self.name)
         if self.condition:
             Output()
             Output(self.condition)
@@ -157,7 +157,7 @@
                         continue
                 else:
                     typeName = "?"
-                    print "Nameless type", arg.type
+                    print("Nameless type", arg.type)
 
                 str = typeName + ' ' + arg.name
             if arg.mode in (InMode, InOutMode):
@@ -294,7 +294,7 @@
                  (int, 'status', ErrorMode),
                  )
     eggs.setprefix("spam")
-    print "/* START */"
+    print("/* START */")
     eggs.generate()
 
 

Modified: python/branches/py3k-buffer/Tools/bgen/bgen/bgenGeneratorGroup.py
==============================================================================
--- python/branches/py3k-buffer/Tools/bgen/bgen/bgenGeneratorGroup.py	(original)
+++ python/branches/py3k-buffer/Tools/bgen/bgen/bgenGeneratorGroup.py	Fri Aug 17 20:48:09 2007
@@ -9,7 +9,7 @@
     def add(self, g, dupcheck=0):
         if dupcheck:
             if g in self.generators:
-                print 'DUP', g.name
+                print('DUP', g.name)
                 return
         g.setprefix(self.prefix)
         self.generators.append(g)
@@ -33,7 +33,7 @@
     group = GeneratorGroup("spam")
     eggs = FunctionGenerator(void, "eggs")
     group.add(eggs)
-    print "/* START */"
+    print("/* START */")
     group.generate()
 
 if __name__ == "__main__":

Modified: python/branches/py3k-buffer/Tools/bgen/bgen/scantools.py
==============================================================================
--- python/branches/py3k-buffer/Tools/bgen/bgen/scantools.py	(original)
+++ python/branches/py3k-buffer/Tools/bgen/bgen/scantools.py	Fri Aug 17 20:48:09 2007
@@ -162,11 +162,11 @@
 
     def error(self, format, *args):
         if self.silent >= 0:
-            print format%args
+            print(format%args)
 
     def report(self, format, *args):
         if not self.silent:
-            print format%args
+            print(format%args)
 
     def writeinitialdefs(self):
         pass
@@ -221,7 +221,7 @@
         """
         f = self.openrepairfile()
         if not f: return []
-        print "Reading repair file", repr(f.name), "..."
+        print("Reading repair file", repr(f.name), "...")
         list = []
         lineno = 0
         while 1:
@@ -237,31 +237,31 @@
             words = [s.strip() for s in line.split(':')]
             if words == ['']: continue
             if len(words) <> 3:
-                print "Line", startlineno,
-                print ": bad line (not 3 colon-separated fields)"
-                print repr(line)
+                print("Line", startlineno, end=' ')
+                print(": bad line (not 3 colon-separated fields)")
+                print(repr(line))
                 continue
             [fpat, pat, rep] = words
             if not fpat: fpat = "*"
             if not pat:
-                print "Line", startlineno,
-                print "Empty pattern"
-                print repr(line)
+                print("Line", startlineno, end=' ')
+                print("Empty pattern")
+                print(repr(line))
                 continue
             patparts = [s.strip() for s in pat.split(',')]
             repparts = [s.strip() for s in rep.split(',')]
             patterns = []
             for p in patparts:
                 if not p:
-                    print "Line", startlineno,
-                    print "Empty pattern part"
-                    print repr(line)
+                    print("Line", startlineno, end=' ')
+                    print("Empty pattern part")
+                    print(repr(line))
                     continue
                 pattern = p.split()
                 if len(pattern) > 3:
-                    print "Line", startlineno,
-                    print "Pattern part has > 3 words"
-                    print repr(line)
+                    print("Line", startlineno, end=' ')
+                    print("Pattern part has > 3 words")
+                    print(repr(line))
                     pattern = pattern[:3]
                 else:
                     while len(pattern) < 3:
@@ -270,15 +270,15 @@
             replacements = []
             for p in repparts:
                 if not p:
-                    print "Line", startlineno,
-                    print "Empty replacement part"
-                    print repr(line)
+                    print("Line", startlineno, end=' ')
+                    print("Empty replacement part")
+                    print(repr(line))
                     continue
                 replacement = p.split()
                 if len(replacement) > 3:
-                    print "Line", startlineno,
-                    print "Pattern part has > 3 words"
-                    print repr(line)
+                    print("Line", startlineno, end=' ')
+                    print("Pattern part has > 3 words")
+                    print(repr(line))
                     replacement = replacement[:3]
                 else:
                     while len(replacement) < 3:
@@ -294,8 +294,8 @@
         try:
             return open(filename, "rU")
         except IOError as msg:
-            print repr(filename), ":", msg
-            print "Cannot open repair file -- assume no repair needed"
+            print(repr(filename), ":", msg)
+            print("Cannot open repair file -- assume no repair needed")
             return None
 
     def initfiles(self):

Modified: python/branches/py3k-buffer/Tools/faqwiz/faqw.py
==============================================================================
--- python/branches/py3k-buffer/Tools/faqwiz/faqw.py	(original)
+++ python/branches/py3k-buffer/Tools/faqwiz/faqw.py	Fri Aug 17 20:48:09 2007
@@ -28,6 +28,6 @@
     sys.exit(n)
 except:
     t, v, tb = sys.exc_info()
-    print
+    print()
     import cgi
     cgi.print_exception(t, v, tb)

Modified: python/branches/py3k-buffer/Tools/faqwiz/faqwiz.py
==============================================================================
--- python/branches/py3k-buffer/Tools/faqwiz/faqwiz.py	(original)
+++ python/branches/py3k-buffer/Tools/faqwiz/faqwiz.py	Fri Aug 17 20:48:09 2007
@@ -158,8 +158,8 @@
     then = now + COOKIE_LIFETIME
     gmt = time.gmtime(then)
     path = os.environ.get('SCRIPT_NAME', '/cgi-bin/')
-    print "Set-Cookie: %s=%s; path=%s;" % (name, value, path),
-    print time.strftime("expires=%a, %d-%b-%y %X GMT", gmt)
+    print("Set-Cookie: %s=%s; path=%s;" % (name, value, path), end=' ')
+    print(time.strftime("expires=%a, %d-%b-%y %X GMT", gmt))
 
 class MagicDict:
 
@@ -273,22 +273,22 @@
                 raw = 0
                 continue
             if raw:
-                print line
+                print(line)
                 continue
             if not line.strip():
                 if pre:
-                    print '</PRE>'
+                    print('</PRE>')
                     pre = 0
                 else:
-                    print '<P>'
+                    print('<P>')
             else:
                 if not line[0].isspace():
                     if pre:
-                        print '</PRE>'
+                        print('</PRE>')
                         pre = 0
                 else:
                     if not pre:
-                        print '<PRE>'
+                        print('<PRE>')
                         pre = 1
                 if '/' in line or '@' in line:
                     line = translate(line, pre)
@@ -296,16 +296,16 @@
                     line = escape(line)
                 if not pre and '*' in line:
                     line = emphasize(line)
-                print line
+                print(line)
         if pre:
-            print '</PRE>'
+            print('</PRE>')
             pre = 0
         if edit:
-            print '<P>'
+            print('<P>')
             emit(ENTRY_FOOTER, self)
             if self.last_changed_date:
                 emit(ENTRY_LOGINFO, self)
-        print '<P>'
+        print('<P>')
 
 class FaqDir:
 
@@ -377,7 +377,7 @@
         self.dir = FaqDir()
 
     def go(self):
-        print 'Content-type: text/html'
+        print('Content-type: text/html')
         req = self.ui.req or 'home'
         mname = 'do_%s' % req
         try:
@@ -493,7 +493,7 @@
                 mtime = mtime = entry.getmtime()
                 if mtime > latest:
                     latest = mtime
-        print time.strftime(LAST_CHANGED, time.localtime(latest))
+        print(time.strftime(LAST_CHANGED, time.localtime(latest)))
         emit(EXPLAIN_MARKS)
 
     def format_all(self, files, edit=1, headers=1):
@@ -637,7 +637,7 @@
                 rev = line[9:].split()
                 mami = revparse(rev)
                 if not mami:
-                    print line
+                    print(line)
                 else:
                     emit(REVISIONLINK, entry, rev=rev, line=line)
                     if mami[1] > 1:
@@ -647,7 +647,7 @@
                         emit(DIFFLINK, entry, prev=rev, rev=headrev)
                     else:
                         headrev = rev
-                    print
+                    print()
                 athead = 0
             else:
                 athead = 0
@@ -656,8 +656,8 @@
                     athead = 1
                     sys.stdout.write('<HR>')
                 else:
-                    print line
-        print '</PRE>'
+                    print(line)
+        print('</PRE>')
 
     def do_revision(self):
         entry = self.dir.open(self.ui.file)
@@ -686,8 +686,8 @@
     def shell(self, command):
         output = os.popen(command).read()
         sys.stdout.write('<PRE>')
-        print escape(output)
-        print '</PRE>'
+        print(escape(output))
+        print('</PRE>')
 
     def do_new(self):
         entry = self.dir.new(section=int(self.ui.section))
@@ -759,9 +759,9 @@
 
     def cantcommit(self):
         self.prologue(T_CANTCOMMIT)
-        print CANTCOMMIT_HEAD
+        print(CANTCOMMIT_HEAD)
         self.errordetail()
-        print CANTCOMMIT_TAIL
+        print(CANTCOMMIT_TAIL)
 
     def errordetail(self):
         if PASSWORD and self.ui.password != PASSWORD:
@@ -827,7 +827,7 @@
         else:
             self.error(T_COMMITFAILED)
             emit(COMMITFAILED, sts=sts)
-        print '<PRE>%s</PRE>' % escape(output)
+        print('<PRE>%s</PRE>' % escape(output))
 
         try:
             os.unlink(tf.name)

Modified: python/branches/py3k-buffer/Tools/framer/example.py
==============================================================================
--- python/branches/py3k-buffer/Tools/framer/example.py	(original)
+++ python/branches/py3k-buffer/Tools/framer/example.py	Fri Aug 17 20:48:09 2007
@@ -14,7 +14,7 @@
 
     Usage:
 
-    from cStringIO import StringIO
+    from io import StringIO
 
     an_output_stream = StringIO()
     an_output_stream.write(some_stuff)

Modified: python/branches/py3k-buffer/Tools/framer/framer/bases.py
==============================================================================
--- python/branches/py3k-buffer/Tools/framer/framer/bases.py	(original)
+++ python/branches/py3k-buffer/Tools/framer/framer/bases.py	Fri Aug 17 20:48:09 2007
@@ -27,7 +27,7 @@
 
     def dump_methoddef(self, f, functions, vars):
         def p(templ, vars=vars): # helper function to generate output
-            print >> f, templ % vars
+            print(templ % vars, file=f)
 
         if not functions:
             return
@@ -77,12 +77,12 @@
 
     def dump(self, f):
         def p(templ, vars=self.__vars): # helper function to generate output
-            print >> f, templ % vars
+            print(templ % vars, file=f)
 
         p(template.module_start)
         if self.__members:
             p(template.member_include)
-        print >> f
+        print(file=f)
 
         if self.__doc__:
             p(template.module_doc)
@@ -111,10 +111,10 @@
 
         # defined after initvars() so that __vars is defined
         def p(templ, vars=self.__vars):
-            print >> f, templ % vars
+            print(templ % vars, file=f)
 
         if self.struct is not None:
-            print >> f, unindent(self.struct, False)
+            print(unindent(self.struct, False), file=f)
 
         if self.__doc__:
             p(template.docstring)
@@ -185,7 +185,7 @@
 
     def dump_memberdef(self, f):
         def p(templ, vars=self.__vars):
-            print >> f, templ % vars
+            print(templ % vars, file=f)
 
         if not self.__members:
             return
@@ -196,7 +196,7 @@
 
     def dump_slots(self, f):
         def p(templ, vars=self.__vars):
-            print >> f, templ % vars
+            print(templ % vars, file=f)
 
         if self.struct:
             p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]})
@@ -206,12 +206,12 @@
             val = self.__slots.get(s, s.default)
             ntabs = 4 - (4 + len(val)) / 8
             line = "        %s,%s/* %s */" % (val, "\t" * ntabs, s.name)
-            print >> f, line
+            print(line, file=f)
         p(template.type_struct_end)
 
     def dump_init(self, f):
         def p(templ):
-            print >> f, templ % self.__vars
+            print(templ % self.__vars, file=f)
 
         p(template.type_init_type)
         p(template.module_add_type)

Modified: python/branches/py3k-buffer/Tools/framer/framer/function.py
==============================================================================
--- python/branches/py3k-buffer/Tools/framer/framer/function.py	(original)
+++ python/branches/py3k-buffer/Tools/framer/framer/function.py	Fri Aug 17 20:48:09 2007
@@ -96,7 +96,7 @@
 
     def dump_decls(self, f):
         for a in self.args:
-            print >> f, "        %s" % a.decl()
+            print("        %s" % a.decl(), file=f)
 
 def ArgumentList(func, method):
     code = func.func_code
@@ -135,7 +135,7 @@
         def p(templ, vars=None): # helper function to generate output
             if vars is None:
                 vars = self.vars
-            print >> f, templ % vars
+            print(templ % vars, file=f)
 
         if self.__doc__:
             p(template.docstring)

Modified: python/branches/py3k-buffer/Tools/framer/framer/member.py
==============================================================================
--- python/branches/py3k-buffer/Tools/framer/framer/member.py	(original)
+++ python/branches/py3k-buffer/Tools/framer/framer/member.py	Fri Aug 17 20:48:09 2007
@@ -68,6 +68,6 @@
 
     def dump(self, f):
         if self.doc is None:
-            print >> f, template.memberdef_def % self.vars
+            print(template.memberdef_def % self.vars, file=f)
         else:
-            print >> f, template.memberdef_def_doc % self.vars
+            print(template.memberdef_def_doc % self.vars, file=f)

Modified: python/branches/py3k-buffer/Tools/i18n/makelocalealias.py
==============================================================================
--- python/branches/py3k-buffer/Tools/i18n/makelocalealias.py	(original)
+++ python/branches/py3k-buffer/Tools/i18n/makelocalealias.py	Fri Aug 17 20:48:09 2007
@@ -49,7 +49,7 @@
     items = data.items()
     items.sort()
     for k,v in items:
-        print '    %-40s%r,' % ('%r:' % k, v)
+        print('    %-40s%r,' % ('%r:' % k, v))
 
 def print_differences(data, olddata):
 
@@ -57,17 +57,17 @@
     items.sort()
     for k, v in items:
         if not data.has_key(k):
-            print '#    removed %r' % k
+            print('#    removed %r' % k)
         elif olddata[k] != data[k]:
-            print '#    updated %r -> %r to %r' % \
-                  (k, olddata[k], data[k])
+            print('#    updated %r -> %r to %r' % \
+                  (k, olddata[k], data[k]))
         # Additions are not mentioned
 
 if __name__ == '__main__':
     data = locale.locale_alias.copy()
     data.update(parse(LOCALE_ALIAS))
     print_differences(data, locale.locale_alias)
-    print
-    print 'locale_alias = {'
+    print()
+    print('locale_alias = {')
     pprint(data)
-    print '}'
+    print('}')

Modified: python/branches/py3k-buffer/Tools/i18n/msgfmt.py
==============================================================================
--- python/branches/py3k-buffer/Tools/i18n/msgfmt.py	(original)
+++ python/branches/py3k-buffer/Tools/i18n/msgfmt.py	Fri Aug 17 20:48:09 2007
@@ -38,9 +38,9 @@
 
 
 def usage(code, msg=''):
-    print >> sys.stderr, __doc__
+    print(__doc__, file=sys.stderr)
     if msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
     sys.exit(code)
 
 
@@ -111,7 +111,7 @@
     try:
         lines = open(infile).readlines()
     except IOError as msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
         sys.exit(1)
 
     section = None
@@ -154,9 +154,9 @@
         elif section == STR:
             msgstr += l
         else:
-            print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
-                  'before:'
-            print >> sys.stderr, l
+            print('Syntax error on %s:%d' % (infile, lno), \
+                  'before:', file=sys.stderr)
+            print(l, file=sys.stderr)
             sys.exit(1)
     # Add last entry
     if section == STR:
@@ -168,7 +168,7 @@
     try:
         open(outfile,"wb").write(output)
     except IOError as msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
 
 
 
@@ -185,14 +185,14 @@
         if opt in ('-h', '--help'):
             usage(0)
         elif opt in ('-V', '--version'):
-            print >> sys.stderr, "msgfmt.py", __version__
+            print("msgfmt.py", __version__, file=sys.stderr)
             sys.exit(0)
         elif opt in ('-o', '--output-file'):
             outfile = arg
     # do it
     if not args:
-        print >> sys.stderr, 'No input file given'
-        print >> sys.stderr, "Try `msgfmt --help' for more information."
+        print('No input file given', file=sys.stderr)
+        print("Try `msgfmt --help' for more information.", file=sys.stderr)
         return
 
     for filename in args:

Modified: python/branches/py3k-buffer/Tools/i18n/pygettext.py
==============================================================================
--- python/branches/py3k-buffer/Tools/i18n/pygettext.py	(original)
+++ python/branches/py3k-buffer/Tools/i18n/pygettext.py	Fri Aug 17 20:48:09 2007
@@ -197,9 +197,9 @@
 
 
 def usage(code, msg=''):
-    print >> sys.stderr, __doc__ % globals()
+    print(__doc__ % globals(), file=sys.stderr)
     if msg:
-        print >> sys.stderr, msg
+        print(msg, file=sys.stderr)
     sys.exit(code)
 
 
@@ -423,13 +423,13 @@
         elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
                            token.NEWLINE, tokenize.NL]:
             # warn if we see anything else than STRING or whitespace
-            print >> sys.stderr, _(
+            print(_(
                 '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
                 ) % {
                 'token': tstring,
                 'file': self.__curfile,
                 'lineno': self.__lineno
-                }
+                }, file=sys.stderr)
             self.__state = self.__waiting
 
     def __addentry(self, msg, lineno=None, isdocstring=0):
@@ -448,7 +448,7 @@
         timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
         # The time stamp in the header doesn't have the same format as that
         # generated by xgettext...
-        print >> fp, pot_header % {'time': timestamp, 'version': __version__}
+        print(pot_header % {'time': timestamp, 'version': __version__}, file=fp)
         # Sort the entries.  First sort each particular entry's keys, then
         # sort all the entries by their first item.
         reverse = {}
@@ -477,8 +477,8 @@
                 elif options.locationstyle == options.SOLARIS:
                     for filename, lineno in v:
                         d = {'filename': filename, 'lineno': lineno}
-                        print >>fp, _(
-                            '# File: %(filename)s, line: %(lineno)d') % d
+                        print(_(
+                            '# File: %(filename)s, line: %(lineno)d') % d, file=fp)
                 elif options.locationstyle == options.GNU:
                     # fit as many locations on one line, as long as the
                     # resulting line length doesn't exceeds 'options.width'
@@ -489,14 +489,14 @@
                         if len(locline) + len(s) <= options.width:
                             locline = locline + s
                         else:
-                            print >> fp, locline
+                            print(locline, file=fp)
                             locline = "#:" + s
                     if len(locline) > 2:
-                        print >> fp, locline
+                        print(locline, file=fp)
                 if isdocstring:
-                    print >> fp, '#, docstring'
-                print >> fp, 'msgid', normalize(k)
-                print >> fp, 'msgstr ""\n'
+                    print('#, docstring', file=fp)
+                print('msgid', normalize(k), file=fp)
+                print('msgstr ""\n', file=fp)
 
 
 
@@ -570,7 +570,7 @@
         elif opt in ('-v', '--verbose'):
             options.verbose = 1
         elif opt in ('-V', '--version'):
-            print _('pygettext.py (xgettext for Python) %s') % __version__
+            print(_('pygettext.py (xgettext for Python) %s') % __version__)
             sys.exit(0)
         elif opt in ('-w', '--width'):
             try:
@@ -603,8 +603,8 @@
             options.toexclude = fp.readlines()
             fp.close()
         except IOError:
-            print >> sys.stderr, _(
-                "Can't read --exclude-file: %s") % options.excludefilename
+            print(_(
+                "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)
             sys.exit(1)
     else:
         options.toexclude = []
@@ -623,12 +623,12 @@
     for filename in args:
         if filename == '-':
             if options.verbose:
-                print _('Reading standard input')
+                print(_('Reading standard input'))
             fp = sys.stdin
             closep = 0
         else:
             if options.verbose:
-                print _('Working on %s') % filename
+                print(_('Working on %s') % filename)
             fp = open(filename)
             closep = 1
         try:
@@ -636,8 +636,8 @@
             try:
                 tokenize.tokenize(fp.readline, eater)
             except tokenize.TokenError as e:
-                print >> sys.stderr, '%s: %s, line %d, column %d' % (
-                    e[0], filename, e[1][0], e[1][1])
+                print('%s: %s, line %d, column %d' % (
+                    e[0], filename, e[1][0], e[1][1]), file=sys.stderr)
         finally:
             if closep:
                 fp.close()

Modified: python/branches/py3k-buffer/Tools/modulator/Tkextra.py
==============================================================================
--- python/branches/py3k-buffer/Tools/modulator/Tkextra.py	(original)
+++ python/branches/py3k-buffer/Tools/modulator/Tkextra.py	Fri Aug 17 20:48:09 2007
@@ -198,7 +198,7 @@
                '',
                -1,
                'OK')
-    print 'pressed button', i
+    print('pressed button', i)
     i = dialog(mainWidget,
                'File Modified',
                'File "tcl.h" has been modified since '
@@ -209,13 +209,13 @@
                'Save File',
                'Discard Changes',
                'Return To Editor')
-    print 'pressed button', i
-    print message('Test of message')
-    print askyn('Test of yes/no')
-    print askync('Test of yes/no/cancel')
-    print askstr('Type a string:')
-    print strdialog(mainWidget, 'Question', 'Another string:', '',
-                  0, 'Save', 'Save as text')
+    print('pressed button', i)
+    print(message('Test of message'))
+    print(askyn('Test of yes/no'))
+    print(askync('Test of yes/no/cancel'))
+    print(askstr('Type a string:'))
+    print(strdialog(mainWidget, 'Question', 'Another string:', '',
+                  0, 'Save', 'Save as text'))
 
 def _test():
     import sys

Modified: python/branches/py3k-buffer/Tools/msi/msi.py
==============================================================================
--- python/branches/py3k-buffer/Tools/msi/msi.py	(original)
+++ python/branches/py3k-buffer/Tools/msi/msi.py	Fri Aug 17 20:48:09 2007
@@ -114,7 +114,7 @@
     dlltool = find_executable('dlltool')
 
     if not nm or not dlltool:
-        print warning % "nm and/or dlltool were not found"
+        print(warning % "nm and/or dlltool were not found")
         return False
 
     nm_command = '%s -Cs %s' % (nm, lib_file)
@@ -123,23 +123,23 @@
     export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match
 
     f = open(def_file,'w')
-    print >>f, "LIBRARY %s" % dll_file
-    print >>f, "EXPORTS"
+    print("LIBRARY %s" % dll_file, file=f)
+    print("EXPORTS", file=f)
 
     nm_pipe = os.popen(nm_command)
     for line in nm_pipe.readlines():
         m = export_match(line)
         if m:
-            print >>f, m.group(1)
+            print(m.group(1), file=f)
     f.close()
     exit = nm_pipe.close()
 
     if exit:
-        print warning % "nm did not run successfully"
+        print(warning % "nm did not run successfully")
         return False
 
     if os.system(dlltool_command) != 0:
-        print warning % "dlltool did not run successfully"
+        print(warning % "dlltool did not run successfully")
         return False
 
     return True
@@ -875,7 +875,7 @@
     # Check if _ctypes.pyd exists
     have_ctypes = os.path.exists(srcdir+"/PCBuild/_ctypes.pyd")
     if not have_ctypes:
-        print "WARNING: _ctypes.pyd not found, ctypes will not be included"
+        print("WARNING: _ctypes.pyd not found, ctypes will not be included")
         extensions.remove("_ctypes.pyd")
 
     # Add all .py files in Lib, except lib-tk, test
@@ -953,7 +953,7 @@
                 if f.endswith(".au") or f.endswith(".gif"):
                     lib.add_file(f)
                 else:
-                    print "WARNING: New file %s in email/test/data" % f
+                    print("WARNING: New file %s in email/test/data" % f)
         for f in os.listdir(lib.absolute):
             if os.path.isdir(os.path.join(lib.absolute, f)):
                 pydirs.append((lib, f))
@@ -968,7 +968,7 @@
         if f=="_tkinter.pyd":
             continue
         if not os.path.exists(srcdir+"/PCBuild/"+f):
-            print "WARNING: Missing extension", f
+            print("WARNING: Missing extension", f)
             continue
         dlls.append(f)
         lib.add_file(f)
@@ -982,7 +982,7 @@
     lib.add_file(srcdir+"/"+sqlite_dir+sqlite_arch+"/sqlite3.dll")
     if have_tcl:
         if not os.path.exists(srcdir+"/PCBuild/_tkinter.pyd"):
-            print "WARNING: Missing _tkinter.pyd"
+            print("WARNING: Missing _tkinter.pyd")
         else:
             lib.start_component("TkDLLs", tcltk)
             lib.add_file("_tkinter.pyd")
@@ -994,7 +994,7 @@
     for f in glob.glob1(srcdir+"/PCBuild", "*.pyd"):
         if f.endswith("_d.pyd"): continue # debug version
         if f in dlls: continue
-        print "WARNING: Unknown extension", f
+        print("WARNING: Unknown extension", f)
 
     # Add headers
     default_feature.set_current()

Modified: python/branches/py3k-buffer/Tools/msi/msilib.py
==============================================================================
--- python/branches/py3k-buffer/Tools/msi/msilib.py	(original)
+++ python/branches/py3k-buffer/Tools/msi/msilib.py	Fri Aug 17 20:48:09 2007
@@ -95,7 +95,7 @@
             index -= 1
             unk = type & ~knownbits
             if unk:
-                print "%s.%s unknown bits %x" % (self.name, name, unk)
+                print("%s.%s unknown bits %x" % (self.name, name, unk))
             size = type & datasizemask
             dtype = type & typemask
             if dtype == type_string:
@@ -114,7 +114,7 @@
                 tname="OBJECT"
             else:
                 tname="unknown"
-                print "%s.%sunknown integer type %d" % (self.name, name, size)
+                print("%s.%sunknown integer type %d" % (self.name, name, size))
             if type & type_nullable:
                 flags = ""
             else:
@@ -202,7 +202,7 @@
     v = seqmsi.OpenView("SELECT * FROM _Tables");
     v.Execute(None)
     f = open(destpath, "w")
-    print >>f, "import msilib,os;dirname=os.path.dirname(__file__)"
+    print("import msilib,os;dirname=os.path.dirname(__file__)", file=f)
     tables = []
     while 1:
         r = v.Fetch()
@@ -364,9 +364,9 @@
             logical = self.gen_id(dir, file)
         self.index += 1
         if full.find(" ")!=-1:
-            print >>self.file, '"%s" %s' % (full, logical)
+            print('"%s" %s' % (full, logical), file=self.file)
         else:
-            print >>self.file, '%s %s' % (full, logical)
+            print('%s %s' % (full, logical), file=self.file)
         return self.index, logical
 
     def commit(self, db):
@@ -386,7 +386,7 @@
             if not os.path.exists(cabarc):continue
             break
         else:
-            print "WARNING: cabarc.exe not found in registry"
+            print("WARNING: cabarc.exe not found in registry")
             cabarc = "cabarc.exe"
         cmd = r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name)
         p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,

Modified: python/branches/py3k-buffer/Tools/pybench/pybench.py
==============================================================================
--- python/branches/py3k-buffer/Tools/pybench/pybench.py	(original)
+++ python/branches/py3k-buffer/Tools/pybench/pybench.py	Fri Aug 17 20:48:09 2007
@@ -547,11 +547,11 @@
                            min_overhead * MILLI_SECONDS))
             self.roundtimes.append(total_eff_time)
             if self.verbose:
-                print(('                   '
-                       '               ------------------------------'))
-                print(('                   '
+                print('                   '
+                       '               ------------------------------')
+                print('                   '
                        '     Totals:    %6.0fms' %
-                       (total_eff_time * MILLI_SECONDS)))
+                       (total_eff_time * MILLI_SECONDS))
                 print()
             else:
                 print('* Round %i done in %.3f seconds.' % (i+1,
@@ -595,8 +595,8 @@
 
     def print_benchmark(self, hidenoise=0, limitnames=None):
 
-        print(('Test                          '
-               '   minimum  average  operation  overhead'))
+        print('Test                          '
+               '   minimum  average  operation  overhead')
         print('-' * LINE)
         tests = sorted(self.tests.items())
         total_min_time = 0.0
@@ -619,20 +619,20 @@
                    op_avg * MICRO_SECONDS,
                    min_overhead *MILLI_SECONDS))
         print('-' * LINE)
-        print(('Totals:                        '
+        print('Totals:                        '
                ' %6.0fms %6.0fms' %
                (total_min_time * MILLI_SECONDS,
                 total_avg_time * MILLI_SECONDS,
-                )))
+                ))
         print()
 
     def print_comparison(self, compare_to, hidenoise=0, limitnames=None):
 
         # Check benchmark versions
         if compare_to.version != self.version:
-            print(('* Benchmark versions differ: '
+            print('* Benchmark versions differ: '
                    'cannot compare this benchmark to "%s" !' %
-                   compare_to.name))
+                   compare_to.name)
             print()
             self.print_benchmark(hidenoise=hidenoise,
                                  limitnames=limitnames)
@@ -640,10 +640,10 @@
 
         # Print header
         compare_to.print_header('Comparing with')
-        print(('Test                          '
-               '   minimum run-time        average  run-time'))
-        print(('                              '
-               '   this    other   diff    this    other   diff'))
+        print('Test                          '
+               '   minimum run-time        average  run-time')
+        print('                              '
+               '   this    other   diff    this    other   diff')
         print('-' * LINE)
 
         # Print test comparisons
@@ -726,7 +726,7 @@
                      (other_total_avg_time * compare_to.warp) - 1.0) * PERCENT)
             else:
                 avg_diff = 'n/a'
-        print(('Totals:                       '
+        print('Totals:                       '
                '  %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' %
                (total_min_time * MILLI_SECONDS,
                 (other_total_min_time * compare_to.warp/self.warp
@@ -736,7 +736,7 @@
                 (other_total_avg_time * compare_to.warp/self.warp
                  * MILLI_SECONDS),
                 avg_diff
-               )))
+               ))
         print()
         print('(this=%s, other=%s)' % (self.name,
                                        compare_to.name))

Modified: python/branches/py3k-buffer/Tools/pynche/ColorDB.py
==============================================================================
--- python/branches/py3k-buffer/Tools/pynche/ColorDB.py	(original)
+++ python/branches/py3k-buffer/Tools/pynche/ColorDB.py	Fri Aug 17 20:48:09 2007
@@ -57,7 +57,7 @@
             # get this compiled regular expression from derived class
             mo = self._re.match(line)
             if not mo:
-                print >> sys.stderr, 'Error in', fp.name, ' line', lineno
+                print('Error in', fp.name, ' line', lineno, file=sys.stderr)
                 lineno += 1
                 continue
             # extract the red, green, blue, and name
@@ -254,26 +254,26 @@
 if __name__ == '__main__':
     colordb = get_colordb('/usr/openwin/lib/rgb.txt')
     if not colordb:
-        print 'No parseable color database found'
+        print('No parseable color database found')
         sys.exit(1)
     # on my system, this color matches exactly
     target = 'navy'
     red, green, blue = rgbtuple = colordb.find_byname(target)
-    print target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple)
+    print(target, ':', red, green, blue, triplet_to_rrggbb(rgbtuple))
     name, aliases = colordb.find_byrgb(rgbtuple)
-    print 'name:', name, 'aliases:', COMMASPACE.join(aliases)
+    print('name:', name, 'aliases:', COMMASPACE.join(aliases))
     r, g, b = (1, 1, 128)                         # nearest to navy
     r, g, b = (145, 238, 144)                     # nearest to lightgreen
     r, g, b = (255, 251, 250)                     # snow
-    print 'finding nearest to', target, '...'
+    print('finding nearest to', target, '...')
     import time
     t0 = time.time()
     nearest = colordb.nearest(r, g, b)
     t1 = time.time()
-    print 'found nearest color', nearest, 'in', t1-t0, 'seconds'
+    print('found nearest color', nearest, 'in', t1-t0, 'seconds')
     # dump the database
     for n in colordb.unique_names():
         r, g, b = colordb.find_byname(n)
         aliases = colordb.aliases_of(r, g, b)
-        print '%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b,
-                                             SPACE.join(aliases[1:]))
+        print('%20s: (%3d/%3d/%3d) == %s' % (n, r, g, b,
+                                             SPACE.join(aliases[1:])))

Modified: python/branches/py3k-buffer/Tools/pynche/Main.py
==============================================================================
--- python/branches/py3k-buffer/Tools/pynche/Main.py	(original)
+++ python/branches/py3k-buffer/Tools/pynche/Main.py	Fri Aug 17 20:48:09 2007
@@ -85,9 +85,9 @@
 
 
 def usage(code, msg=''):
-    print docstring()
+    print(docstring())
     if msg:
-        print msg
+        print(msg)
     sys.exit(code)
 
 
@@ -111,7 +111,7 @@
         # this to be escaped, which is a pain
         r, g, b = scan_color('#' + s)
     if r is None:
-        print 'Bad initial color, using gray50:', s
+        print('Bad initial color, using gray50:', s)
         r, g, b = scan_color('gray50')
     if r is None:
         usage(1, 'Cannot find an initial color to use')
@@ -203,11 +203,11 @@
         if opt in ('-h', '--help'):
             usage(0)
         elif opt in ('-v', '--version'):
-            print """\
+            print("""\
 Pynche -- The PYthon Natural Color and Hue Editor.
 Contact: %(AUTHNAME)s
 Email:   %(AUTHEMAIL)s
-Version: %(__version__)s""" % globals()
+Version: %(__version__)s""" % globals())
             sys.exit(0)
         elif opt in ('-d', '--database'):
             dbfile = arg

Modified: python/branches/py3k-buffer/Tools/pynche/Switchboard.py
==============================================================================
--- python/branches/py3k-buffer/Tools/pynche/Switchboard.py	(original)
+++ python/branches/py3k-buffer/Tools/pynche/Switchboard.py	Fri Aug 17 20:48:09 2007
@@ -65,8 +65,7 @@
                     fp = open(initfile)
                     self.__optiondb = marshal.load(fp)
                     if not isinstance(self.__optiondb, DictType):
-                        print >> sys.stderr, \
-                              'Problem reading options from file:', initfile
+                        print('Problem reading options from file:', initfile, file=sys.stderr)
                         self.__optiondb = {}
                 except (IOError, EOFError, ValueError):
                     pass
@@ -119,8 +118,8 @@
             try:
                 fp = open(self.__initfile, 'w')
             except IOError:
-                print >> sys.stderr, 'Cannot write options to file:', \
-                      self.__initfile
+                print('Cannot write options to file:', \
+                      self.__initfile, file=sys.stderr)
             else:
                 marshal.dump(self.__optiondb, fp)
         finally:

Modified: python/branches/py3k-buffer/Tools/scripts/byext.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/byext.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/byext.py	Fri Aug 17 20:48:09 2007
@@ -109,14 +109,14 @@
         cols.insert(0, "ext")
         def printheader():
             for col in cols:
-                print "%*s" % (colwidth[col], col),
-            print
+                print("%*s" % (colwidth[col], col), end=' ')
+            print()
         printheader()
         for ext in exts:
             for col in cols:
                 value = self.stats[ext].get(col, "")
-                print "%*s" % (colwidth[col], value),
-            print
+                print("%*s" % (colwidth[col], value), end=' ')
+            print()
         printheader() # Another header at the bottom
 
 def main():

Modified: python/branches/py3k-buffer/Tools/scripts/byteyears.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/byteyears.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/byteyears.py	Fri Aug 17 20:48:09 2007
@@ -52,8 +52,8 @@
             size = st[ST_SIZE]
             age = now - anytime
             byteyears = float(size) * float(age) / secs_per_year
-            print filename.ljust(maxlen),
-            print repr(int(byteyears)).rjust(8)
+            print(filename.ljust(maxlen), end=' ')
+            print(repr(int(byteyears)).rjust(8))
 
     sys.exit(status)
 

Modified: python/branches/py3k-buffer/Tools/scripts/checkappend.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/checkappend.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/checkappend.py	Fri Aug 17 20:48:09 2007
@@ -65,7 +65,7 @@
 def check(file):
     if os.path.isdir(file) and not os.path.islink(file):
         if verbose:
-            print "%r: listing directory" % (file,)
+            print("%r: listing directory" % (file,))
         names = os.listdir(file)
         for name in names:
             fullname = os.path.join(file, name)
@@ -82,11 +82,11 @@
         return
 
     if verbose > 1:
-        print "checking %r ..." % (file,)
+        print("checking %r ..." % (file,))
 
     ok = AppendChecker(file, f).run()
     if verbose and ok:
-        print "%r: Clean bill of health." % (file,)
+        print("%r: Clean bill of health." % (file,))
 
 [FIND_DOT,
  FIND_APPEND,
@@ -149,8 +149,8 @@
                         state = FIND_DOT
                 elif token == "," and self.level == 1:
                     self.nerrors = self.nerrors + 1
-                    print "%s(%d):\n%s" % (self.fname, self.lineno,
-                                           self.line)
+                    print("%s(%d):\n%s" % (self.fname, self.lineno,
+                                           self.line))
                     # don't gripe about this stmt again
                     state = FIND_STMT
 

Modified: python/branches/py3k-buffer/Tools/scripts/checkpyc.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/checkpyc.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/checkpyc.py	Fri Aug 17 20:48:09 2007
@@ -17,15 +17,15 @@
             silent = 1
     MAGIC = imp.get_magic()
     if not silent:
-        print 'Using MAGIC word', repr(MAGIC)
+        print('Using MAGIC word', repr(MAGIC))
     for dirname in sys.path:
         try:
             names = os.listdir(dirname)
         except os.error:
-            print 'Cannot list directory', repr(dirname)
+            print('Cannot list directory', repr(dirname))
             continue
         if not silent:
-            print 'Checking ', repr(dirname), '...'
+            print('Checking ', repr(dirname), '...')
         names.sort()
         for name in names:
             if name[-3:] == '.py':
@@ -33,29 +33,29 @@
                 try:
                     st = os.stat(name)
                 except os.error:
-                    print 'Cannot stat', repr(name)
+                    print('Cannot stat', repr(name))
                     continue
                 if verbose:
-                    print 'Check', repr(name), '...'
+                    print('Check', repr(name), '...')
                 name_c = name + 'c'
                 try:
                     f = open(name_c, 'r')
                 except IOError:
-                    print 'Cannot open', repr(name_c)
+                    print('Cannot open', repr(name_c))
                     continue
                 magic_str = f.read(4)
                 mtime_str = f.read(4)
                 f.close()
                 if magic_str <> MAGIC:
-                    print 'Bad MAGIC word in ".pyc" file',
-                    print repr(name_c)
+                    print('Bad MAGIC word in ".pyc" file', end=' ')
+                    print(repr(name_c))
                     continue
                 mtime = get_long(mtime_str)
                 if mtime == 0 or mtime == -1:
-                    print 'Bad ".pyc" file', repr(name_c)
+                    print('Bad ".pyc" file', repr(name_c))
                 elif mtime <> st[ST_MTIME]:
-                    print 'Out-of-date ".pyc" file',
-                    print repr(name_c)
+                    print('Out-of-date ".pyc" file', end=' ')
+                    print(repr(name_c))
 
 def get_long(s):
     if len(s) <> 4:

Modified: python/branches/py3k-buffer/Tools/scripts/cleanfuture.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/cleanfuture.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/cleanfuture.py	Fri Aug 17 20:48:09 2007
@@ -78,7 +78,7 @@
 def check(file):
     if os.path.isdir(file) and not os.path.islink(file):
         if verbose:
-            print "listing directory", file
+            print("listing directory", file)
         names = os.listdir(file)
         for name in names:
             fullname = os.path.join(file, name)
@@ -89,7 +89,7 @@
         return
 
     if verbose:
-        print "checking", file, "...",
+        print("checking", file, "...", end=' ')
     try:
         f = open(file)
     except IOError as msg:
@@ -103,33 +103,33 @@
     f.close()
     if changed:
         if verbose:
-            print "changed."
+            print("changed.")
             if dryrun:
-                print "But this is a dry run, so leaving it alone."
+                print("But this is a dry run, so leaving it alone.")
         for s, e, line in changed:
-            print "%r lines %d-%d" % (file, s+1, e+1)
+            print("%r lines %d-%d" % (file, s+1, e+1))
             for i in range(s, e+1):
-                print ff.lines[i],
+                print(ff.lines[i], end=' ')
             if line is None:
-                print "-- deleted"
+                print("-- deleted")
             else:
-                print "-- change to:"
-                print line,
+                print("-- change to:")
+                print(line, end=' ')
         if not dryrun:
             bak = file + ".bak"
             if os.path.exists(bak):
                 os.remove(bak)
             os.rename(file, bak)
             if verbose:
-                print "renamed", file, "to", bak
+                print("renamed", file, "to", bak)
             g = open(file, "w")
             ff.write(g)
             g.close()
             if verbose:
-                print "wrote new", file
+                print("wrote new", file)
     else:
         if verbose:
-            print "unchanged."
+            print("unchanged.")
 
 class FutureFinder:
 

Modified: python/branches/py3k-buffer/Tools/scripts/combinerefs.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/combinerefs.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/combinerefs.py	Fri Aug 17 20:48:09 2007
@@ -102,7 +102,7 @@
             addr, addr2rc[addr], addr2guts[addr] = m.groups()
             before += 1
         else:
-            print '??? skipped:', line
+            print('??? skipped:', line)
 
     after = 0
     for line in read(fi, crack, True):
@@ -111,17 +111,17 @@
         assert m
         addr, rc, guts = m.groups() # guts is type name here
         if addr not in addr2rc:
-            print '??? new object created while tearing down:', line.rstrip()
+            print('??? new object created while tearing down:', line.rstrip())
             continue
-        print addr,
+        print(addr, end=' ')
         if rc == addr2rc[addr]:
-            print '[%s]' % rc,
+            print('[%s]' % rc, end=' ')
         else:
-            print '[%s->%s]' % (addr2rc[addr], rc),
-        print guts, addr2guts[addr]
+            print('[%s->%s]' % (addr2rc[addr], rc), end=' ')
+        print(guts, addr2guts[addr])
 
     f.close()
-    print "%d objects before, %d after" % (before, after)
+    print("%d objects before, %d after" % (before, after))
 
 if __name__ == '__main__':
     combine(sys.argv[1])

Modified: python/branches/py3k-buffer/Tools/scripts/crlf.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/crlf.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/crlf.py	Fri Aug 17 20:48:09 2007
@@ -6,15 +6,15 @@
 def main():
     for filename in sys.argv[1:]:
         if os.path.isdir(filename):
-            print filename, "Directory!"
+            print(filename, "Directory!")
             continue
         data = open(filename, "rb").read()
         if '\0' in data:
-            print filename, "Binary!"
+            print(filename, "Binary!")
             continue
         newdata = data.replace("\r\n", "\n")
         if newdata != data:
-            print filename
+            print(filename)
             f = open(filename, "wb")
             f.write(newdata)
             f.close()

Modified: python/branches/py3k-buffer/Tools/scripts/cvsfiles.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/cvsfiles.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/cvsfiles.py	Fri Aug 17 20:48:09 2007
@@ -21,8 +21,8 @@
     try:
         opts, args = getopt.getopt(sys.argv[1:], "n:")
     except getopt.error as msg:
-        print msg
-        print __doc__,
+        print(msg)
+        print(__doc__, end=' ')
         return 1
     global cutofftime
     newerfile = None
@@ -57,7 +57,7 @@
                 if cutofftime and getmtime(fullname) <= cutofftime:
                     pass
                 else:
-                    print fullname
+                    print(fullname)
     for sub in subdirs:
         process(sub)
 

Modified: python/branches/py3k-buffer/Tools/scripts/dutree.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/dutree.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/dutree.py	Fri Aug 17 20:48:09 2007
@@ -51,7 +51,7 @@
         if tsub is None:
             psub = prefix
         else:
-            print prefix + repr(tsub).rjust(width) + ' ' + key
+            print(prefix + repr(tsub).rjust(width) + ' ' + key)
             psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
         if d.has_key(key):
             show(tsub, d[key][1], psub)

Modified: python/branches/py3k-buffer/Tools/scripts/finddiv.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/finddiv.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/finddiv.py	Fri Aug 17 20:48:09 2007
@@ -32,7 +32,7 @@
     listnames = 0
     for o, a in opts:
         if o == "-h":
-            print __doc__
+            print(__doc__)
             return
         if o == "-l":
             listnames = 1
@@ -60,11 +60,11 @@
     for type, token, (row, col), end, line in g:
         if token in ("/", "/="):
             if listnames:
-                print filename
+                print(filename)
                 break
             if row != lastrow:
                 lastrow = row
-                print "%s:%d:%s" % (filename, row, line),
+                print("%s:%d:%s" % (filename, row, line), end=' ')
     fp.close()
 
 def processdir(dir, listnames):

Modified: python/branches/py3k-buffer/Tools/scripts/findlinksto.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/findlinksto.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/findlinksto.py	Fri Aug 17 20:48:09 2007
@@ -16,8 +16,8 @@
             raise getopt.GetoptError('not enough arguments', None)
     except getopt.GetoptError as msg:
         sys.stdout = sys.stderr
-        print msg
-        print 'usage: findlinksto pattern directory ...'
+        print(msg)
+        print('usage: findlinksto pattern directory ...')
         sys.exit(2)
     pat, dirs = args[0], args[1:]
     prog = re.compile(pat)
@@ -29,13 +29,13 @@
         names[:] = []
         return
     if os.path.ismount(dirname):
-        print 'descend into', dirname
+        print('descend into', dirname)
     for name in names:
         name = os.path.join(dirname, name)
         try:
             linkto = os.readlink(name)
             if prog.search(linkto) is not None:
-                print name, '->', linkto
+                print(name, '->', linkto)
         except os.error:
             pass
 

Modified: python/branches/py3k-buffer/Tools/scripts/findnocoding.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/findnocoding.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/findnocoding.py	Fri Aug 17 20:48:09 2007
@@ -28,8 +28,8 @@
     pysource = pysource()
 
 
-    print >>sys.stderr, ("The pysource module is not available; "
-                         "no sophisticated Python source file search will be done.")
+    print("The pysource module is not available; "
+                         "no sophisticated Python source file search will be done.", file=sys.stderr)
 
 
 decl_re = re.compile(r"coding[=:]\s*([-\w.]+)")
@@ -79,8 +79,8 @@
 try:
     opts, args = getopt.getopt(sys.argv[1:], 'cd')
 except getopt.error as msg:
-    print >>sys.stderr, msg
-    print >>sys.stderr, usage
+    print(msg, file=sys.stderr)
+    print(usage, file=sys.stderr)
     sys.exit(1)
 
 is_python = pysource.looks_like_python
@@ -93,12 +93,12 @@
         debug = True
 
 if not args:
-    print >>sys.stderr, usage
+    print(usage, file=sys.stderr)
     sys.exit(1)
 
 for fullpath in pysource.walk_python_files(args, is_python):
     if debug:
-        print "Testing for coding: %s" % fullpath
+        print("Testing for coding: %s" % fullpath)
     result = needs_declaration(fullpath)
     if result:
-        print fullpath
+        print(fullpath)

Modified: python/branches/py3k-buffer/Tools/scripts/fixcid.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/fixcid.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/fixcid.py	Fri Aug 17 20:48:09 2007
@@ -244,7 +244,7 @@
             subst = Dict[found]
             if Program is InsideCommentProgram:
                 if not Docomments:
-                    print 'Found in comment:', found
+                    print('Found in comment:', found)
                     i = i + n
                     continue
                 if NotInComment.has_key(found):

Modified: python/branches/py3k-buffer/Tools/scripts/fixdiv.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/fixdiv.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/fixdiv.py	Fri Aug 17 20:48:09 2007
@@ -145,7 +145,7 @@
         return 2
     for o, a in opts:
         if o == "-h":
-            print __doc__
+            print(__doc__)
             return
         if o == "-m":
             global multi_ok
@@ -160,7 +160,7 @@
         return 1
     files = warnings.keys()
     if not files:
-        print "No classic division warnings read from", args[0]
+        print("No classic division warnings read from", args[0])
         return
     files.sort()
     exit = None
@@ -203,14 +203,14 @@
     return warnings
 
 def process(filename, list):
-    print "-"*70
+    print("-"*70)
     assert list # if this fails, readwarnings() is broken
     try:
         fp = open(filename)
     except IOError as msg:
         sys.stderr.write("can't open: %s\n" % msg)
         return 1
-    print "Index:", filename
+    print("Index:", filename)
     f = FileContext(fp)
     list.sort()
     index = 0 # list[:index] has been processed, list[index:] is still to do
@@ -248,10 +248,10 @@
                         lastrow = row
                     assert rows
                     if len(rows) == 1:
-                        print "*** More than one / operator in line", rows[0]
+                        print("*** More than one / operator in line", rows[0])
                     else:
-                        print "*** More than one / operator per statement",
-                        print "in lines %d-%d" % (rows[0], rows[-1])
+                        print("*** More than one / operator per statement", end=' ')
+                        print("in lines %d-%d" % (rows[0], rows[-1]))
             intlong = []
             floatcomplex = []
             bad = []
@@ -269,24 +269,24 @@
                 lastrow = row
                 line = chop(line)
                 if line[col:col+1] != "/":
-                    print "*** Can't find the / operator in line %d:" % row
-                    print "*", line
+                    print("*** Can't find the / operator in line %d:" % row)
+                    print("*", line)
                     continue
                 if bad:
-                    print "*** Bad warning for line %d:" % row, bad
-                    print "*", line
+                    print("*** Bad warning for line %d:" % row, bad)
+                    print("*", line)
                 elif intlong and not floatcomplex:
-                    print "%dc%d" % (row, row)
-                    print "<", line
-                    print "---"
-                    print ">", line[:col] + "/" + line[col:]
+                    print("%dc%d" % (row, row))
+                    print("<", line)
+                    print("---")
+                    print(">", line[:col] + "/" + line[col:])
                 elif floatcomplex and not intlong:
-                    print "True division / operator at line %d:" % row
-                    print "=", line
+                    print("True division / operator at line %d:" % row)
+                    print("=", line)
                 elif intlong and floatcomplex:
-                    print "*** Ambiguous / operator (%s, %s) at line %d:" % (
-                        "|".join(intlong), "|".join(floatcomplex), row)
-                    print "?", line
+                    print("*** Ambiguous / operator (%s, %s) at line %d:" % (
+                        "|".join(intlong), "|".join(floatcomplex), row))
+                    print("?", line)
     fp.close()
 
 def reportphantomwarnings(warnings, f):
@@ -301,15 +301,15 @@
     for block in blocks:
         row = block[0]
         whats = "/".join(block[1:])
-        print "*** Phantom %s warnings for line %d:" % (whats, row)
+        print("*** Phantom %s warnings for line %d:" % (whats, row))
         f.report(row, mark="*")
 
 def report(slashes, message):
     lastrow = None
     for (row, col), line in slashes:
         if row != lastrow:
-            print "*** %s on line %d:" % (message, row)
-            print "*", chop(line)
+            print("*** %s on line %d:" % (message, row))
+            print("*", chop(line))
             lastrow = row
 
 class FileContext:
@@ -354,7 +354,7 @@
                 line = self[first]
             except KeyError:
                 line = "<missing line>"
-            print mark, chop(line)
+            print(mark, chop(line))
 
 def scanline(g):
     slashes = []

Modified: python/branches/py3k-buffer/Tools/scripts/fixheader.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/fixheader.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/fixheader.py	Fri Aug 17 20:48:09 2007
@@ -32,18 +32,18 @@
             magic = magic + c.upper()
         else: magic = magic + '_'
     sys.stdout = f
-    print '#ifndef', magic
-    print '#define', magic
-    print '#ifdef __cplusplus'
-    print 'extern "C" {'
-    print '#endif'
-    print
+    print('#ifndef', magic)
+    print('#define', magic)
+    print('#ifdef __cplusplus')
+    print('extern "C" {')
+    print('#endif')
+    print()
     f.write(data)
-    print
-    print '#ifdef __cplusplus'
-    print '}'
-    print '#endif'
-    print '#endif /*', '!'+magic, '*/'
+    print()
+    print('#ifdef __cplusplus')
+    print('}')
+    print('#endif')
+    print('#endif /*', '!'+magic, '*/')
 
 if __name__ == '__main__':
     main()

Modified: python/branches/py3k-buffer/Tools/scripts/fixnotice.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/fixnotice.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/fixnotice.py	Fri Aug 17 20:48:09 2007
@@ -50,9 +50,9 @@
 
 
 def usage(code, msg=''):
-    print __doc__ % globals()
+    print(__doc__ % globals())
     if msg:
-        print msg
+        print(msg)
     sys.exit(code)
 
 
@@ -92,10 +92,10 @@
     i = data.find(OLD_NOTICE)
     if i < 0:
         if VERBOSE:
-            print 'no change:', file
+            print('no change:', file)
         return
     elif DRYRUN or VERBOSE:
-        print '   change:', file
+        print('   change:', file)
     if DRYRUN:
         # Don't actually change the file
         return

Modified: python/branches/py3k-buffer/Tools/scripts/fixps.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/fixps.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/fixps.py	Fri Aug 17 20:48:09 2007
@@ -12,18 +12,18 @@
         try:
             f = open(filename, 'r')
         except IOError as msg:
-            print filename, ': can\'t open :', msg
+            print(filename, ': can\'t open :', msg)
             continue
         line = f.readline()
         if not re.match('^#! */usr/local/bin/python', line):
-            print filename, ': not a /usr/local/bin/python script'
+            print(filename, ': not a /usr/local/bin/python script')
             f.close()
             continue
         rest = f.read()
         f.close()
         line = re.sub('/usr/local/bin/python',
                       '/usr/bin/env python', line)
-        print filename, ':', repr(line)
+        print(filename, ':', repr(line))
         f = open(filename, "w")
         f.write(line)
         f.write(rest)

Modified: python/branches/py3k-buffer/Tools/scripts/ftpmirror.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/ftpmirror.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/ftpmirror.py	Fri Aug 17 20:48:09 2007
@@ -29,8 +29,8 @@
 # Print usage message and exit
 def usage(*args):
     sys.stdout = sys.stderr
-    for msg in args: print msg
-    print __doc__
+    for msg in args: print(msg)
+    print(__doc__)
     sys.exit(2)
 
 verbose = 1 # 0 for -q, 2 for -v
@@ -82,22 +82,22 @@
             if args[3:]: usage('too many arguments')
     #
     f = ftplib.FTP()
-    if verbose: print "Connecting to '%s%s'..." % (host,
-                                                   (port and ":%d"%port or ""))
+    if verbose: print("Connecting to '%s%s'..." % (host,
+                                                   (port and ":%d"%port or "")))
     f.connect(host,port)
     if not nologin:
         if verbose:
-            print 'Logging in as %r...' % (login or 'anonymous')
+            print('Logging in as %r...' % (login or 'anonymous'))
         f.login(login, passwd, account)
-    if verbose: print 'OK.'
+    if verbose: print('OK.')
     pwd = f.pwd()
-    if verbose > 1: print 'PWD =', repr(pwd)
+    if verbose > 1: print('PWD =', repr(pwd))
     if remotedir:
-        if verbose > 1: print 'cwd(%s)' % repr(remotedir)
+        if verbose > 1: print('cwd(%s)' % repr(remotedir))
         f.cwd(remotedir)
-        if verbose > 1: print 'OK.'
+        if verbose > 1: print('OK.')
         pwd = f.pwd()
-        if verbose > 1: print 'PWD =', repr(pwd)
+        if verbose > 1: print('PWD =', repr(pwd))
     #
     mirrorsubdir(f, localdir)
 
@@ -105,11 +105,11 @@
 def mirrorsubdir(f, localdir):
     pwd = f.pwd()
     if localdir and not os.path.isdir(localdir):
-        if verbose: print 'Creating local directory', repr(localdir)
+        if verbose: print('Creating local directory', repr(localdir))
         try:
             makedir(localdir)
         except os.error as msg:
-            print "Failed to establish local directory", repr(localdir)
+            print("Failed to establish local directory", repr(localdir))
             return
     infofilename = os.path.join(localdir, '.mirrorinfo')
     try:
@@ -119,15 +119,15 @@
     try:
         info = eval(text)
     except (SyntaxError, NameError):
-        print 'Bad mirror info in', repr(infofilename)
+        print('Bad mirror info in', repr(infofilename))
         info = {}
     subdirs = []
     listing = []
-    if verbose: print 'Listing remote directory %r...' % (pwd,)
+    if verbose: print('Listing remote directory %r...' % (pwd,))
     f.retrlines('LIST', listing.append)
     filesfound = []
     for line in listing:
-        if verbose > 1: print '-->', repr(line)
+        if verbose > 1: print('-->', repr(line))
         if mac:
             # Mac listing has just filenames;
             # trailing / means subdirectory
@@ -141,14 +141,14 @@
             # Parse, assuming a UNIX listing
             words = line.split(None, 8)
             if len(words) < 6:
-                if verbose > 1: print 'Skipping short line'
+                if verbose > 1: print('Skipping short line')
                 continue
             filename = words[-1].lstrip()
             i = filename.find(" -> ")
             if i >= 0:
                 # words[0] had better start with 'l'...
                 if verbose > 1:
-                    print 'Found symbolic link %r' % (filename,)
+                    print('Found symbolic link %r' % (filename,))
                 linkto = filename[i+4:]
                 filename = filename[:i]
             infostuff = words[-5:-1]
@@ -157,21 +157,21 @@
         for pat in skippats:
             if fnmatch(filename, pat):
                 if verbose > 1:
-                    print 'Skip pattern', repr(pat),
-                    print 'matches', repr(filename)
+                    print('Skip pattern', repr(pat), end=' ')
+                    print('matches', repr(filename))
                 skip = 1
                 break
         if skip:
             continue
         if mode[0] == 'd':
             if verbose > 1:
-                print 'Remembering subdirectory', repr(filename)
+                print('Remembering subdirectory', repr(filename))
             subdirs.append(filename)
             continue
         filesfound.append(filename)
         if info.has_key(filename) and info[filename] == infostuff:
             if verbose > 1:
-                print 'Already have this version of',repr(filename)
+                print('Already have this version of',repr(filename))
             continue
         fullname = os.path.join(localdir, filename)
         tempname = os.path.join(localdir, '@'+filename)
@@ -187,20 +187,20 @@
             pass
         if mode[0] == 'l':
             if verbose:
-                print "Creating symlink %r -> %r" % (filename, linkto)
+                print("Creating symlink %r -> %r" % (filename, linkto))
             try:
                 os.symlink(linkto, tempname)
             except IOError as msg:
-                print "Can't create %r: %s" % (tempname, msg)
+                print("Can't create %r: %s" % (tempname, msg))
                 continue
         else:
             try:
                 fp = open(tempname, 'wb')
             except IOError as msg:
-                print "Can't create %r: %s" % (tempname, msg)
+                print("Can't create %r: %s" % (tempname, msg))
                 continue
             if verbose:
-                print 'Retrieving %r from %r as %r...' % (filename, pwd, fullname)
+                print('Retrieving %r from %r as %r...' % (filename, pwd, fullname))
             if verbose:
                 fp1 = LoggingFile(fp, 1024, sys.stdout)
             else:
@@ -210,7 +210,7 @@
                 f.retrbinary('RETR ' + filename,
                              fp1.write, 8*1024)
             except ftplib.error_perm as msg:
-                print msg
+                print(msg)
             t1 = time.time()
             bytes = fp.tell()
             fp.close()
@@ -223,29 +223,29 @@
         try:
             os.rename(tempname, fullname)
         except os.error as msg:
-            print "Can't rename %r to %r: %s" % (tempname, fullname, msg)
+            print("Can't rename %r to %r: %s" % (tempname, fullname, msg))
             continue
         info[filename] = infostuff
         writedict(info, infofilename)
         if verbose and mode[0] != 'l':
             dt = t1 - t0
             kbytes = bytes / 1024.0
-            print int(round(kbytes)),
-            print 'Kbytes in',
-            print int(round(dt)),
-            print 'seconds',
+            print(int(round(kbytes)), end=' ')
+            print('Kbytes in', end=' ')
+            print(int(round(dt)), end=' ')
+            print('seconds', end=' ')
             if t1 > t0:
-                print '(~%d Kbytes/sec)' % \
-                          int(round(kbytes/dt),)
-            print
+                print('(~%d Kbytes/sec)' % \
+                          int(round(kbytes/dt),))
+            print()
     #
     # Remove files from info that are no longer remote
     deletions = 0
     for filename in info.keys():
         if filename not in filesfound:
             if verbose:
-                print "Removing obsolete info entry for",
-                print repr(filename), "in", repr(localdir or ".")
+                print("Removing obsolete info entry for", end=' ')
+                print(repr(filename), "in", repr(localdir or "."))
             del info[filename]
             deletions = deletions + 1
     if deletions:
@@ -264,8 +264,8 @@
         for pat in skippats:
             if fnmatch(name, pat):
                 if verbose > 1:
-                    print 'Skip pattern', repr(pat),
-                    print 'matches', repr(name)
+                    print('Skip pattern', repr(pat), end=' ')
+                    print('matches', repr(name))
                 skip = 1
                 break
         if skip:
@@ -273,10 +273,10 @@
         fullname = os.path.join(localdir, name)
         if not rmok:
             if verbose:
-                print 'Local file', repr(fullname),
-                print 'is no longer pertinent'
+                print('Local file', repr(fullname), end=' ')
+                print('is no longer pertinent')
             continue
-        if verbose: print 'Removing local file/dir', repr(fullname)
+        if verbose: print('Removing local file/dir', repr(fullname))
         remove(fullname)
     #
     # Recursively mirror subdirectories
@@ -284,28 +284,28 @@
         if interactive:
             doit = askabout('subdirectory', subdir, pwd)
             if not doit: continue
-        if verbose: print 'Processing subdirectory', repr(subdir)
+        if verbose: print('Processing subdirectory', repr(subdir))
         localsubdir = os.path.join(localdir, subdir)
         pwd = f.pwd()
         if verbose > 1:
-            print 'Remote directory now:', repr(pwd)
-            print 'Remote cwd', repr(subdir)
+            print('Remote directory now:', repr(pwd))
+            print('Remote cwd', repr(subdir))
         try:
             f.cwd(subdir)
         except ftplib.error_perm as msg:
-            print "Can't chdir to", repr(subdir), ":", repr(msg)
+            print("Can't chdir to", repr(subdir), ":", repr(msg))
         else:
-            if verbose: print 'Mirroring as', repr(localsubdir)
+            if verbose: print('Mirroring as', repr(localsubdir))
             mirrorsubdir(f, localsubdir)
-            if verbose > 1: print 'Remote cwd ..'
+            if verbose > 1: print('Remote cwd ..')
             f.cwd('..')
         newpwd = f.pwd()
         if newpwd != pwd:
-            print 'Ended up in wrong directory after cd + cd ..'
-            print 'Giving up now.'
+            print('Ended up in wrong directory after cd + cd ..')
+            print('Giving up now.')
             break
         else:
-            if verbose > 1: print 'OK.'
+            if verbose > 1: print('OK.')
 
 # Helper to remove a file or directory tree
 def remove(fullname):
@@ -323,13 +323,13 @@
         try:
             os.rmdir(fullname)
         except os.error as msg:
-            print "Can't remove local directory %r: %s" % (fullname, msg)
+            print("Can't remove local directory %r: %s" % (fullname, msg))
             return 0
     else:
         try:
             os.unlink(fullname)
         except os.error as msg:
-            print "Can't remove local file %r: %s" % (fullname, msg)
+            print("Can't remove local file %r: %s" % (fullname, msg))
             return 0
     return 1
 
@@ -366,7 +366,7 @@
             return 1
         if reply in ['', 'n', 'no', 'nop', 'nope']:
             return 0
-        print 'Please answer yes or no.'
+        print('Please answer yes or no.')
 
 # Create a directory if it doesn't exist.  Recursively create the
 # parent directory as well if needed.

Modified: python/branches/py3k-buffer/Tools/scripts/google.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/google.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/google.py	Fri Aug 17 20:48:09 2007
@@ -5,7 +5,7 @@
 def main():
     args = sys.argv[1:]
     if not args:
-        print "Usage: %s querystring" % sys.argv[0]
+        print("Usage: %s querystring" % sys.argv[0])
         return
     list = []
     for arg in args:

Modified: python/branches/py3k-buffer/Tools/scripts/lfcr.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/lfcr.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/lfcr.py	Fri Aug 17 20:48:09 2007
@@ -7,15 +7,15 @@
 def main():
     for filename in sys.argv[1:]:
         if os.path.isdir(filename):
-            print filename, "Directory!"
+            print(filename, "Directory!")
             continue
         data = open(filename, "rb").read()
         if '\0' in data:
-            print filename, "Binary!"
+            print(filename, "Binary!")
             continue
         newdata = re.sub("\r?\n", "\r\n", data)
         if newdata != data:
-            print filename
+            print(filename)
             f = open(filename, "wb")
             f.write(newdata)
             f.close()

Modified: python/branches/py3k-buffer/Tools/scripts/linktree.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/linktree.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/linktree.py	Fri Aug 17 20:48:09 2007
@@ -18,7 +18,7 @@
 
 def main():
     if not 3 <= len(sys.argv) <= 4:
-        print 'usage:', sys.argv[0], 'oldtree newtree [linkto]'
+        print('usage:', sys.argv[0], 'oldtree newtree [linkto]')
         return 2
     oldtree, newtree = sys.argv[1], sys.argv[2]
     if len(sys.argv) > 3:
@@ -28,46 +28,46 @@
         link = LINK
         link_may_fail = 0
     if not os.path.isdir(oldtree):
-        print oldtree + ': not a directory'
+        print(oldtree + ': not a directory')
         return 1
     try:
         os.mkdir(newtree, 0o777)
     except os.error as msg:
-        print newtree + ': cannot mkdir:', msg
+        print(newtree + ': cannot mkdir:', msg)
         return 1
     linkname = os.path.join(newtree, link)
     try:
         os.symlink(os.path.join(os.pardir, oldtree), linkname)
     except os.error as msg:
         if not link_may_fail:
-            print linkname + ': cannot symlink:', msg
+            print(linkname + ': cannot symlink:', msg)
             return 1
         else:
-            print linkname + ': warning: cannot symlink:', msg
+            print(linkname + ': warning: cannot symlink:', msg)
     linknames(oldtree, newtree, link)
     return 0
 
 def linknames(old, new, link):
-    if debug: print 'linknames', (old, new, link)
+    if debug: print('linknames', (old, new, link))
     try:
         names = os.listdir(old)
     except os.error as msg:
-        print old + ': warning: cannot listdir:', msg
+        print(old + ': warning: cannot listdir:', msg)
         return
     for name in names:
         if name not in (os.curdir, os.pardir):
             oldname = os.path.join(old, name)
             linkname = os.path.join(link, name)
             newname = os.path.join(new, name)
-            if debug > 1: print oldname, newname, linkname
+            if debug > 1: print(oldname, newname, linkname)
             if os.path.isdir(oldname) and \
                not os.path.islink(oldname):
                 try:
                     os.mkdir(newname, 0o777)
                     ok = 1
                 except:
-                    print newname + \
-                          ': warning: cannot mkdir:', msg
+                    print(newname + \
+                          ': warning: cannot mkdir:', msg)
                     ok = 0
                 if ok:
                     linkname = os.path.join(os.pardir,

Modified: python/branches/py3k-buffer/Tools/scripts/lll.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/lll.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/lll.py	Fri Aug 17 20:48:09 2007
@@ -12,16 +12,16 @@
         if name not in (os.curdir, os.pardir):
             full = os.path.join(dirname, name)
             if os.path.islink(full):
-                print name, '->', os.readlink(full)
+                print(name, '->', os.readlink(full))
 def main():
     args = sys.argv[1:]
     if not args: args = [os.curdir]
     first = 1
     for arg in args:
         if len(args) > 1:
-            if not first: print
+            if not first: print()
             first = 0
-            print arg + ':'
+            print(arg + ':')
     lll(arg)
 
 if __name__ == '__main__':

Modified: python/branches/py3k-buffer/Tools/scripts/logmerge.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/logmerge.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/logmerge.py	Fri Aug 17 20:48:09 2007
@@ -53,7 +53,7 @@
         elif o == '-b':
             branch = a
         elif o == '-h':
-            print __doc__
+            print(__doc__)
             sys.exit(0)
     database = []
     while 1:
@@ -169,9 +169,9 @@
     for (date, working_file, rev, author, text) in database:
         if text != prevtext:
             if prev:
-                print sep2,
+                print(sep2, end=' ')
                 for (p_date, p_working_file, p_rev, p_author) in prev:
-                    print p_date, p_author, p_working_file, p_rev
+                    print(p_date, p_author, p_working_file, p_rev)
                 sys.stdout.writelines(prevtext)
             prev = []
         prev.append((date, working_file, rev, author))

Modified: python/branches/py3k-buffer/Tools/scripts/mailerdaemon.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/mailerdaemon.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/mailerdaemon.py	Fri Aug 17 20:48:09 2007
@@ -171,11 +171,11 @@
         fp = open(fn)
         m = ErrorMessage(fp)
         sender = m.getaddr('From')
-        print '%s\t%-40s\t'%(fn, sender[1]),
+        print('%s\t%-40s\t'%(fn, sender[1]), end=' ')
 
         if m.is_warning():
             fp.close()
-            print 'warning only'
+            print('warning only')
             nwarn = nwarn + 1
             if modify:
                 os.rename(fn, ','+fn)
@@ -185,11 +185,11 @@
         try:
             errors = m.get_errors()
         except Unparseable:
-            print '** Not parseable'
+            print('** Not parseable')
             nbad = nbad + 1
             fp.close()
             continue
-        print len(errors), 'errors'
+        print(len(errors), 'errors')
 
         # Remember them
         for e in errors:
@@ -211,16 +211,16 @@
             os.rename(fn, ','+fn)
 ##          os.unlink(fn)
 
-    print '--------------'
-    print nok, 'files parsed,',nwarn,'files warning-only,',
-    print nbad,'files unparseable'
-    print '--------------'
+    print('--------------')
+    print(nok, 'files parsed,',nwarn,'files warning-only,', end=' ')
+    print(nbad,'files unparseable')
+    print('--------------')
     list = []
     for e in errordict.keys():
         list.append((errordict[e], errorfirst[e], errorlast[e], e))
     list.sort()
     for num, first, last, e in list:
-        print '%d %s - %s\t%s' % (num, first, last, e)
+        print('%d %s - %s\t%s' % (num, first, last, e))
 
 def main():
     modify = 0

Modified: python/branches/py3k-buffer/Tools/scripts/mkreal.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/mkreal.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/mkreal.py	Fri Aug 17 20:48:09 2007
@@ -48,12 +48,12 @@
     if progname == '-c': progname = 'mkreal'
     args = sys.argv[1:]
     if not args:
-        print 'usage:', progname, 'path ...'
+        print('usage:', progname, 'path ...')
         sys.exit(2)
     status = 0
     for name in args:
         if not os.path.islink(name):
-            print progname+':', name+':', 'not a symlink'
+            print(progname+':', name+':', 'not a symlink')
             status = 1
         else:
             if os.path.isdir(name):

Modified: python/branches/py3k-buffer/Tools/scripts/ndiff.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/ndiff.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/ndiff.py	Fri Aug 17 20:48:09 2007
@@ -74,7 +74,7 @@
     a = f1.readlines(); f1.close()
     b = f2.readlines(); f2.close()
     for line in difflib.ndiff(a, b):
-        print line,
+        print(line, end=' ')
 
     return 1
 
@@ -109,8 +109,8 @@
         return fail("need 2 filename args")
     f1name, f2name = args
     if noisy:
-        print '-:', f1name
-        print '+:', f2name
+        print('-:', f1name)
+        print('+:', f2name)
     return fcompare(f1name, f2name)
 
 # read ndiff output from stdin, and print file1 (which=='1') or

Modified: python/branches/py3k-buffer/Tools/scripts/objgraph.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/objgraph.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/objgraph.py	Fri Aug 17 20:48:09 2007
@@ -80,7 +80,7 @@
             store(file2undef, fn, name)
             store(undef2file, name, fn)
         elif not type in ignore:
-            print fn + ':' + name + ': unknown type ' + type
+            print(fn + ':' + name + ': unknown type ' + type)
 
 # Print all names that were undefined in some module and where they are
 # defined.
@@ -89,7 +89,7 @@
     flist = file2undef.keys()
     flist.sort()
     for filename in flist:
-        print filename + ':'
+        print(filename + ':')
         elist = file2undef[filename]
         elist.sort()
         for ext in elist:
@@ -98,9 +98,9 @@
             else:
                 tabs = '\t\t'
             if not def2file.has_key(ext):
-                print '\t' + ext + tabs + ' *undefined'
+                print('\t' + ext + tabs + ' *undefined')
             else:
-                print '\t' + ext + tabs + flat(def2file[ext])
+                print('\t' + ext + tabs + flat(def2file[ext]))
 
 # Print for each module the names of the other modules that use it.
 #
@@ -114,14 +114,14 @@
                 callers = callers + undef2file[label]
         if callers:
             callers.sort()
-            print filename + ':'
+            print(filename + ':')
             lastfn = ''
             for fn in callers:
                 if fn <> lastfn:
-                    print '\t' + fn
+                    print('\t' + fn)
                 lastfn = fn
         else:
-            print filename + ': unused'
+            print(filename + ': unused')
 
 # Print undefined names and where they are used.
 #
@@ -134,11 +134,11 @@
     elist = undefs.keys()
     elist.sort()
     for ext in elist:
-        print ext + ':'
+        print(ext + ':')
         flist = undefs[ext]
         flist.sort()
         for filename in flist:
-            print '\t' + filename
+            print('\t' + filename)
 
 # Print warning messages about names defined in more than one file.
 #
@@ -149,8 +149,8 @@
     names.sort()
     for name in names:
         if len(def2file[name]) > 1:
-            print 'warning:', name, 'multiply defined:',
-            print flat(def2file[name])
+            print('warning:', name, 'multiply defined:', end=' ')
+            print(flat(def2file[name]))
     sys.stdout = savestdout
 
 # Main program
@@ -160,14 +160,14 @@
         optlist, args = getopt.getopt(sys.argv[1:], 'cdu')
     except getopt.error:
         sys.stdout = sys.stderr
-        print 'Usage:', os.path.basename(sys.argv[0]),
-        print           '[-cdu] [file] ...'
-        print '-c: print callers per objectfile'
-        print '-d: print callees per objectfile'
-        print '-u: print usage of undefined symbols'
-        print 'If none of -cdu is specified, all are assumed.'
-        print 'Use "nm -o" to generate the input (on IRIX: "nm -Bo"),'
-        print 'e.g.: nm -o /lib/libc.a | objgraph'
+        print('Usage:', os.path.basename(sys.argv[0]), end=' ')
+        print('[-cdu] [file] ...')
+        print('-c: print callers per objectfile')
+        print('-d: print callees per objectfile')
+        print('-u: print usage of undefined symbols')
+        print('If none of -cdu is specified, all are assumed.')
+        print('Use "nm -o" to generate the input (on IRIX: "nm -Bo"),')
+        print('e.g.: nm -o /lib/libc.a | objgraph')
         return 1
     optu = optc = optd = 0
     for opt, void in optlist:
@@ -192,15 +192,15 @@
     more = (optu + optc + optd > 1)
     if optd:
         if more:
-            print '---------------All callees------------------'
+            print('---------------All callees------------------')
         printcallee()
     if optu:
         if more:
-            print '---------------Undefined callees------------'
+            print('---------------Undefined callees------------')
         printundef()
     if optc:
         if more:
-            print '---------------All Callers------------------'
+            print('---------------All Callers------------------')
         printcaller()
     return 0
 

Modified: python/branches/py3k-buffer/Tools/scripts/pdeps.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/pdeps.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/pdeps.py	Fri Aug 17 20:48:09 2007
@@ -30,25 +30,25 @@
 def main():
     args = sys.argv[1:]
     if not args:
-        print 'usage: pdeps file.py file.py ...'
+        print('usage: pdeps file.py file.py ...')
         return 2
     #
     table = {}
     for arg in args:
         process(arg, table)
     #
-    print '--- Uses ---'
+    print('--- Uses ---')
     printresults(table)
     #
-    print '--- Used By ---'
+    print('--- Used By ---')
     inv = inverse(table)
     printresults(inv)
     #
-    print '--- Closure of Uses ---'
+    print('--- Closure of Uses ---')
     reach = closure(table)
     printresults(reach)
     #
-    print '--- Closure of Used By ---'
+    print('--- Closure of Used By ---')
     invreach = inverse(reach)
     printresults(invreach)
     #
@@ -151,12 +151,12 @@
     for mod in modules:
         list = table[mod]
         list.sort()
-        print mod.ljust(maxlen), ':',
+        print(mod.ljust(maxlen), ':', end=' ')
         if mod in list:
-            print '(*)',
+            print('(*)', end=' ')
         for ref in list:
-            print ref,
-        print
+            print(ref, end=' ')
+        print()
 
 
 # Call main and honor exit status

Modified: python/branches/py3k-buffer/Tools/scripts/pysource.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/pysource.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/pysource.py	Fri Aug 17 20:48:09 2007
@@ -27,7 +27,7 @@
 debug = False
 
 def print_debug(msg):
-    if debug: print msg
+    if debug: print(msg)
 
 
 def _open(fullpath):
@@ -124,7 +124,7 @@
 if __name__ == "__main__":
     # Two simple examples/tests
     for fullpath in walk_python_files(['.']):
-        print fullpath
-    print "----------"
+        print(fullpath)
+    print("----------")
     for fullpath in walk_python_files(['.'], is_python=can_be_compiled):
-        print fullpath
+        print(fullpath)

Modified: python/branches/py3k-buffer/Tools/scripts/rgrep.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/rgrep.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/rgrep.py	Fri Aug 17 20:48:09 2007
@@ -52,12 +52,12 @@
         lines.reverse()
         for line in lines:
             if prog.search(line):
-                print line
+                print(line)
 
 def usage(msg, code=2):
     sys.stdout = sys.stderr
-    print msg
-    print __doc__
+    print(msg)
+    print(__doc__)
     sys.exit(code)
 
 if __name__ == '__main__':

Modified: python/branches/py3k-buffer/Tools/scripts/suff.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/suff.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/suff.py	Fri Aug 17 20:48:09 2007
@@ -17,7 +17,7 @@
     keys = suffixes.keys()
     keys.sort()
     for suff in keys:
-        print repr(suff), len(suffixes[suff])
+        print(repr(suff), len(suffixes[suff]))
 
 def getsuffix(filename):
     suff = ''

Modified: python/branches/py3k-buffer/Tools/scripts/texcheck.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/texcheck.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/texcheck.py	Fri Aug 17 20:48:09 2007
@@ -65,10 +65,10 @@
     try:
         o_lineno, o_symbol = openers.pop()
     except IndexError:
-        print "\nDelimiter mismatch.  On line %d, encountered closing '%s' without corresponding open" % (c_lineno, c_symbol)
+        print("\nDelimiter mismatch.  On line %d, encountered closing '%s' without corresponding open" % (c_lineno, c_symbol))
         return
     if o_symbol in pairmap.get(c_symbol, [c_symbol]): return
-    print "\nOpener '%s' on line %d was not closed before encountering '%s' on line %d" % (o_symbol, o_lineno, c_symbol, c_lineno)
+    print("\nOpener '%s' on line %d was not closed before encountering '%s' on line %d" % (o_symbol, o_lineno, c_symbol, c_lineno))
     return
 
 def checkit(source, opts, morecmds=[]):
@@ -120,7 +120,7 @@
         # Check balancing of open/close parenthesis, brackets, and begin/end blocks
         for begend, name, punct in delimiters.findall(line):
             if '-v' in opts:
-                print lineno, '|', begend, name, punct,
+                print(lineno, '|', begend, name, punct, end=' ')
             if begend == 'begin' and '-d' not in opts:
                 openers.append((lineno, name))
             elif punct in openpunct:
@@ -130,7 +130,7 @@
             elif punct in pairmap:
                 matchclose(lineno, punct, openers, pairmap)
             if '-v' in opts:
-                print '   --> ', openers
+                print('   --> ', openers)
 
         # Balance opening and closing braces
         for open, close in braces.findall(line):
@@ -140,7 +140,7 @@
                 try:
                     bracestack.pop()
                 except IndexError:
-                    print r'Warning, unmatched } on line %s.' % (lineno,)
+                    print(r'Warning, unmatched } on line %s.' % (lineno,))
 
         # Optionally, skip LaTeX specific checks
         if '-d' in opts:
@@ -151,11 +151,11 @@
             if '822' in line or '.html' in line:
                 continue    # Ignore false positives for urls and for /rfc822
             if '\\' + cmd in validcmds:
-                print 'Warning, forward slash used on line %d with cmd: /%s' % (lineno, cmd)
+                print('Warning, forward slash used on line %d with cmd: /%s' % (lineno, cmd))
 
         # Check for markup requiring {} for correct spacing
         for cmd in spacingmarkup.findall(line):
-            print r'Warning, \%s should be written as \%s{} on line %d' % (cmd, cmd, lineno)
+            print(r'Warning, \%s should be written as \%s{} on line %d' % (cmd, cmd, lineno))
 
         # Validate commands
         nc = line.find(r'\newcommand')
@@ -165,7 +165,7 @@
             validcmds.add(line[start+1:end])
         for cmd in texcmd.findall(line):
             if cmd not in validcmds:
-                print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd)
+                print(r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd))
 
         # Check table levels (make sure lineii only inside tableii)
         m = tablestart.search(line)
@@ -174,23 +174,23 @@
             tablestartline = lineno
         m = tableline.search(line)
         if m and m.group(1) != tablelevel:
-            print r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline)
+            print(r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline))
         if tableend.search(line):
             tablelevel = ''
 
         # Style guide warnings
         if 'e.g.' in line or 'i.e.' in line:
-            print r'Style warning, avoid use of i.e or e.g. on line %d' % (lineno,)
+            print(r'Style warning, avoid use of i.e or e.g. on line %d' % (lineno,))
 
         for dw in doubledwords.findall(line):
-            print r'Doubled word warning.  "%s" on line %d' % (dw, lineno)
+            print(r'Doubled word warning.  "%s" on line %d' % (dw, lineno))
 
     lastline = lineno
     for lineno, symbol in openers:
-        print "Unmatched open delimiter '%s' on line %d" % (symbol, lineno)
+        print("Unmatched open delimiter '%s' on line %d" % (symbol, lineno))
     for lineno in bracestack:
-        print "Unmatched { on line %d" % (lineno,)
-    print 'Done checking %d lines.' % (lastline,)
+        print("Unmatched { on line %d" % (lineno,))
+    print('Done checking %d lines.' % (lastline,))
     return 0
 
 def main(args=None):
@@ -199,11 +199,11 @@
     optitems, arglist = getopt.getopt(args, "k:mdhs:v")
     opts = dict(optitems)
     if '-h' in opts or args==[]:
-        print __doc__
+        print(__doc__)
         return 0
 
     if len(arglist) < 1:
-        print 'Please specify a file to be checked'
+        print('Please specify a file to be checked')
         return 1
 
     for i, filespec in enumerate(arglist):
@@ -214,12 +214,12 @@
     err = []
 
     for filename in arglist:
-        print '=' * 30
-        print "Checking", filename
+        print('=' * 30)
+        print("Checking", filename)
         try:
             f = open(filename)
         except IOError:
-            print 'Cannot open file %s.' % arglist[0]
+            print('Cannot open file %s.' % arglist[0])
             return 2
 
         try:

Modified: python/branches/py3k-buffer/Tools/scripts/texi2html.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/texi2html.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/texi2html.py	Fri Aug 17 20:48:09 2007
@@ -275,7 +275,7 @@
                     if not self.skip: self.process(accu)
                     accu = []
                 if initial_lineno > 0:
-                    print '*** EOF before @bye'
+                    print('*** EOF before @bye')
                 break
             lineno = lineno + 1
             mo = cmprog.match(line)
@@ -306,10 +306,10 @@
                 accu.append(line)
         #
         if self.skip:
-            print '*** Still skipping at the end'
+            print('*** Still skipping at the end')
         if self.stack:
-            print '*** Stack not empty at the end'
-            print '***', self.stack
+            print('*** Stack not empty at the end')
+            print('***', self.stack)
         if self.includedepth == 0:
             while self.nodestack:
                 self.nodestack[-1].finalize()
@@ -338,7 +338,7 @@
         try:
             text = ''.join(args)
         except:
-            print args
+            print(args)
             raise TypeError
         if self.savetext <> None:
             self.savetext = self.savetext + text
@@ -350,7 +350,7 @@
     # Complete the current node -- write footnotes and close file
     def endnode(self):
         if self.savetext <> None:
-            print '*** Still saving text at end of node'
+            print('*** Still saving text at end of node')
             dummy = self.collectsavings()
         if self.footnotes:
             self.writefootnotes()
@@ -382,10 +382,10 @@
     # This mostly distinguishes between menus and normal text
     def process(self, accu):
         if self.debugging > 1:
-            print '!'*self.debugging, 'process:', self.skip, self.stack,
-            if accu: print accu[0][:30],
-            if accu[0][30:] or accu[1:]: print '...',
-            print
+            print('!'*self.debugging, 'process:', self.skip, self.stack, end=' ')
+            if accu: print(accu[0][:30], end=' ')
+            if accu[0][30:] or accu[1:]: print('...', end=' ')
+            print()
         if self.inmenu():
             # XXX should be done differently
             for line in accu:
@@ -461,7 +461,7 @@
                 continue
             if c == '}':
                 if not stack:
-                    print '*** Unmatched }'
+                    print('*** Unmatched }')
                     self.write('}')
                     continue
                 cmd = stack[-1]
@@ -509,12 +509,12 @@
                 continue
             method()
         if stack:
-            print '*** Stack not empty at para:', stack
+            print('*** Stack not empty at para:', stack)
 
     # --- Handle unknown embedded @-commands ---
 
     def unknown_open(self, cmd):
-        print '*** No open func for @' + cmd + '{...}'
+        print('*** No open func for @' + cmd + '{...}')
         cmd = cmd + '{'
         self.write('@', cmd)
         if not self.unknown.has_key(cmd):
@@ -523,7 +523,7 @@
             self.unknown[cmd] = self.unknown[cmd] + 1
 
     def unknown_close(self, cmd):
-        print '*** No close func for @' + cmd + '{...}'
+        print('*** No close func for @' + cmd + '{...}')
         cmd = '}' + cmd
         self.write('}')
         if not self.unknown.has_key(cmd):
@@ -532,7 +532,7 @@
             self.unknown[cmd] = self.unknown[cmd] + 1
 
     def unknown_handle(self, cmd):
-        print '*** No handler for @' + cmd
+        print('*** No handler for @' + cmd)
         self.write('@', cmd)
         if not self.unknown.has_key(cmd):
             self.unknown[cmd] = 1
@@ -555,9 +555,9 @@
         try:
             fp = open(file, 'r')
         except IOError as msg:
-            print '*** Can\'t open include file', repr(file)
+            print('*** Can\'t open include file', repr(file))
             return
-        print '!'*self.debugging, '--> file', repr(file)
+        print('!'*self.debugging, '--> file', repr(file))
         save_done = self.done
         save_skip = self.skip
         save_stack = self.stack
@@ -568,7 +568,7 @@
         self.done = save_done
         self.skip = save_skip
         self.stack = save_stack
-        print '!'*self.debugging, '<-- file', repr(file)
+        print('!'*self.debugging, '<-- file', repr(file))
 
     # --- Special Insertions ---
 
@@ -764,7 +764,7 @@
         elif os.path.exists(imagelocation+'.gif'):   # MySQL uses GIF files
             filename += '.gif'
         else:
-            print "*** Cannot find image " + imagelocation
+            print("*** Cannot find image " + imagelocation)
         #TODO: what is 'ext'?
         self.write('<IMG SRC="', filename, '"',                     \
                     width  and (' WIDTH="'  + width  + '"') or "",  \
@@ -871,8 +871,8 @@
         cmd = line[a:b]
         args = line[b:].strip()
         if self.debugging > 1:
-            print '!'*self.debugging, 'command:', self.skip, self.stack, \
-                  '@' + cmd, args
+            print('!'*self.debugging, 'command:', self.skip, self.stack, \
+                  '@' + cmd, args)
         try:
             func = getattr(self, 'do_' + cmd)
         except AttributeError:
@@ -890,7 +890,7 @@
             func(args)
 
     def unknown_cmd(self, cmd, args):
-        print '*** unknown', '@' + cmd, args
+        print('*** unknown', '@' + cmd, args)
         if not self.unknown.has_key(cmd):
             self.unknown[cmd] = 1
         else:
@@ -899,11 +899,11 @@
     def do_end(self, args):
         words = args.split()
         if not words:
-            print '*** @end w/o args'
+            print('*** @end w/o args')
         else:
             cmd = words[0]
             if not self.stack or self.stack[-1] <> cmd:
-                print '*** @end', cmd, 'unexpected'
+                print('*** @end', cmd, 'unexpected')
             else:
                 del self.stack[-1]
             try:
@@ -915,7 +915,7 @@
 
     def unknown_end(self, cmd):
         cmd = 'end ' + cmd
-        print '*** unknown', '@' + cmd
+        print('*** unknown', '@' + cmd)
         if not self.unknown.has_key(cmd):
             self.unknown[cmd] = 1
         else:
@@ -965,7 +965,7 @@
                 self.skip = self.skip - 1
             del self.stackinfo[len(self.stack) + 1]
         except KeyError:
-            print '*** end_ifset: KeyError :', len(self.stack) + 1
+            print('*** end_ifset: KeyError :', len(self.stack) + 1)
 
     def bgn_ifclear(self, args):
         if args in self.values.keys() \
@@ -980,7 +980,7 @@
                 self.skip = self.skip - 1
             del self.stackinfo[len(self.stack) + 1]
         except KeyError:
-            print '*** end_ifclear: KeyError :', len(self.stack) + 1
+            print('*** end_ifclear: KeyError :', len(self.stack) + 1)
 
     def open_value(self):
         self.startsaving()
@@ -990,7 +990,7 @@
         if key in self.values.keys():
             self.write(self.values[key])
         else:
-            print '*** Undefined value: ', key
+            print('*** Undefined value: ', key)
 
     # --- Beginning a file ---
 
@@ -1052,9 +1052,9 @@
         [name, next, prev, up] = parts[:4]
         file = self.dirname + '/' + makefile(name)
         if self.filenames.has_key(file):
-            print '*** Filename already in use: ', file
+            print('*** Filename already in use: ', file)
         else:
-            if self.debugging: print '!'*self.debugging, '--- writing', file
+            if self.debugging: print('!'*self.debugging, '--- writing', file)
         self.filenames[file] = 1
         # self.nodefp = open(file, 'w')
         self.nodename = name
@@ -1169,7 +1169,7 @@
         self.expand(args)
         self.write('</', type, '>\n')
         if self.debugging or self.print_headers:
-            print '---', args
+            print('---', args)
 
     def do_contents(self, args):
         # pass
@@ -1549,7 +1549,7 @@
         if self.whichindex.has_key(name):
             self.index(name, args)
         else:
-            print '*** No index named', repr(name)
+            print('*** No index named', repr(name))
 
     def do_cindex(self, args): self.index('cp', args)
     def do_findex(self, args): self.index('fn', args)
@@ -1565,12 +1565,12 @@
     def do_synindex(self, args):
         words = args.split()
         if len(words) <> 2:
-            print '*** bad @synindex', args
+            print('*** bad @synindex', args)
             return
         [old, new] = words
         if not self.whichindex.has_key(old) or \
                   not self.whichindex.has_key(new):
-            print '*** bad key(s) in @synindex', args
+            print('*** bad key(s) in @synindex', args)
             return
         if old <> new and \
                   self.whichindex[old] is not self.whichindex[new]:
@@ -1585,15 +1585,15 @@
             if self.whichindex.has_key(name):
                 self.prindex(name)
             else:
-                print '*** No index named', repr(name)
+                print('*** No index named', repr(name))
 
     def prindex(self, name):
         iscodeindex = (name not in self.noncodeindices)
         index = self.whichindex[name]
         if not index: return
         if self.debugging:
-            print '!'*self.debugging, '--- Generating', \
-                  self.indextitle[name], 'index'
+            print('!'*self.debugging, '--- Generating', \
+                  self.indextitle[name], 'index')
         #  The node already provides a title
         index1 = []
         junkprog = re.compile('^(@[a-z]+)?{')
@@ -1616,7 +1616,7 @@
         for sortkey, key, node in index1:
             if (key, node) == (prevkey, prevnode):
                 continue
-            if self.debugging > 1: print '!'*self.debugging, key, ':', node
+            if self.debugging > 1: print('!'*self.debugging, key, ':', node)
             self.write('<DT>')
             if iscodeindex: key = '@code{' + key + '}'
             if key != prevkey:
@@ -1629,11 +1629,11 @@
 
     def report(self):
         if self.unknown:
-            print '--- Unrecognized commands ---'
+            print('--- Unrecognized commands ---')
             cmds = self.unknown.keys()
             cmds.sort()
             for cmd in cmds:
-                print cmd.ljust(20), self.unknown[cmd]
+                print(cmd.ljust(20), self.unknown[cmd])
 
 
 class TexinfoParserHTML3(TexinfoParser):
@@ -1773,86 +1773,86 @@
         # PROJECT FILE
         try:
             fp = open(projectfile,'w')
-            print>>fp, '[OPTIONS]'
-            print>>fp, 'Auto Index=Yes'
-            print>>fp, 'Binary TOC=No'
-            print>>fp, 'Binary Index=Yes'
-            print>>fp, 'Compatibility=1.1'
-            print>>fp, 'Compiled file=' + resultfile + ''
-            print>>fp, 'Contents file=' + contentfile + ''
-            print>>fp, 'Default topic=' + defaulttopic + ''
-            print>>fp, 'Error log file=ErrorLog.log'
-            print>>fp, 'Index file=' + indexfile + ''
-            print>>fp, 'Title=' + title + ''
-            print>>fp, 'Display compile progress=Yes'
-            print>>fp, 'Full-text search=Yes'
-            print>>fp, 'Default window=main'
-            print>>fp, ''
-            print>>fp, '[WINDOWS]'
-            print>>fp, ('main=,"' + contentfile + '","' + indexfile
+            print('[OPTIONS]', file=fp)
+            print('Auto Index=Yes', file=fp)
+            print('Binary TOC=No', file=fp)
+            print('Binary Index=Yes', file=fp)
+            print('Compatibility=1.1', file=fp)
+            print('Compiled file=' + resultfile + '', file=fp)
+            print('Contents file=' + contentfile + '', file=fp)
+            print('Default topic=' + defaulttopic + '', file=fp)
+            print('Error log file=ErrorLog.log', file=fp)
+            print('Index file=' + indexfile + '', file=fp)
+            print('Title=' + title + '', file=fp)
+            print('Display compile progress=Yes', file=fp)
+            print('Full-text search=Yes', file=fp)
+            print('Default window=main', file=fp)
+            print('', file=fp)
+            print('[WINDOWS]', file=fp)
+            print('main=,"' + contentfile + '","' + indexfile
                         + '","","",,,,,0x23520,222,0x1046,[10,10,780,560],'
-                        '0xB0000,,,,,,0')
-            print>>fp, ''
-            print>>fp, '[FILES]'
-            print>>fp, ''
+                        '0xB0000,,,,,,0', file=fp)
+            print('', file=fp)
+            print('[FILES]', file=fp)
+            print('', file=fp)
             self.dumpfiles(fp)
             fp.close()
         except IOError as msg:
-            print projectfile, ':', msg
+            print(projectfile, ':', msg)
             sys.exit(1)
 
         # CONTENT FILE
         try:
             fp = open(contentfile,'w')
-            print>>fp, '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">'
-            print>>fp, '<!-- This file defines the table of contents -->'
-            print>>fp, '<HTML>'
-            print>>fp, '<HEAD>'
-            print>>fp, ('<meta name="GENERATOR"'
-                        'content="Microsoft&reg; HTML Help Workshop 4.1">')
-            print>>fp, '<!-- Sitemap 1.0 -->'
-            print>>fp, '</HEAD>'
-            print>>fp, '<BODY>'
-            print>>fp, '   <OBJECT type="text/site properties">'
-            print>>fp, '     <param name="Window Styles" value="0x800025">'
-            print>>fp, '     <param name="comment" value="title:">'
-            print>>fp, '     <param name="comment" value="base:">'
-            print>>fp, '   </OBJECT>'
+            print('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">', file=fp)
+            print('<!-- This file defines the table of contents -->', file=fp)
+            print('<HTML>', file=fp)
+            print('<HEAD>', file=fp)
+            print('<meta name="GENERATOR"'
+                        'content="Microsoft&reg; HTML Help Workshop 4.1">', file=fp)
+            print('<!-- Sitemap 1.0 -->', file=fp)
+            print('</HEAD>', file=fp)
+            print('<BODY>', file=fp)
+            print('   <OBJECT type="text/site properties">', file=fp)
+            print('     <param name="Window Styles" value="0x800025">', file=fp)
+            print('     <param name="comment" value="title:">', file=fp)
+            print('     <param name="comment" value="base:">', file=fp)
+            print('   </OBJECT>', file=fp)
             self.dumpnodes(fp)
-            print>>fp, '</BODY>'
-            print>>fp, '</HTML>'
+            print('</BODY>', file=fp)
+            print('</HTML>', file=fp)
             fp.close()
         except IOError as msg:
-            print contentfile, ':', msg
+            print(contentfile, ':', msg)
             sys.exit(1)
 
         # INDEX FILE
         try:
             fp = open(indexfile  ,'w')
-            print>>fp, '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">'
-            print>>fp, '<!-- This file defines the index -->'
-            print>>fp, '<HTML>'
-            print>>fp, '<HEAD>'
-            print>>fp, ('<meta name="GENERATOR"'
-                        'content="Microsoft&reg; HTML Help Workshop 4.1">')
-            print>>fp, '<!-- Sitemap 1.0 -->'
-            print>>fp, '</HEAD>'
-            print>>fp, '<BODY>'
-            print>>fp, '<OBJECT type="text/site properties">'
-            print>>fp, '</OBJECT>'
+            print('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">', file=fp)
+            print('<!-- This file defines the index -->', file=fp)
+            print('<HTML>', file=fp)
+            print('<HEAD>', file=fp)
+            print('<meta name="GENERATOR"'
+                        'content="Microsoft&reg; HTML Help Workshop 4.1">', file=fp)
+            print('<!-- Sitemap 1.0 -->', file=fp)
+            print('</HEAD>', file=fp)
+            print('<BODY>', file=fp)
+            print('<OBJECT type="text/site properties">', file=fp)
+            print('</OBJECT>', file=fp)
             self.dumpindex(fp)
-            print>>fp, '</BODY>'
-            print>>fp, '</HTML>'
+            print('</BODY>', file=fp)
+            print('</HTML>', file=fp)
             fp.close()
         except IOError as msg:
-            print indexfile  , ':', msg
+            print(indexfile  , ':', msg)
             sys.exit(1)
 
     def dumpfiles(self, outfile=sys.stdout):
         filelist = self.filenames.values()
         filelist.sort()
         for filename in filelist:
-            print>>outfile, filename
+            print(filename, file=outfile)
 
     def dumpnodes(self, outfile=sys.stdout):
         self.dumped = {}
@@ -1860,10 +1860,10 @@
             nodename, dummy, dummy, dummy, dummy = self.nodelist[0]
             self.topnode = nodename
 
-        print>>outfile,  '<UL>'
+        print('<UL>', file=outfile)
         for node in self.nodelist:
             self.dumpnode(node,0,outfile)
-        print>>outfile,  '</UL>'
+        print('</UL>', file=outfile)
 
     def dumpnode(self, node, indent=0, outfile=sys.stdout):
         if node:
@@ -1877,11 +1877,11 @@
             self.dumped[nodename] = 1
 
             # Print info for this node
-            print>>outfile, ' '*indent,
-            print>>outfile, '<LI><OBJECT type="text/sitemap">',
-            print>>outfile, '<param name="Name" value="' + nodename +'">',
-            print>>outfile, '<param name="Local" value="'+ filename +'">',
-            print>>outfile, '</OBJECT>'
+            print(' '*indent, end=' ', file=outfile)
+            print('<LI><OBJECT type="text/sitemap">', end=' ', file=outfile)
+            print('<param name="Name" value="' + nodename +'">', end=' ', file=outfile)
+            print('<param name="Local" value="'+ filename +'">', end=' ', file=outfile)
+            print('</OBJECT>', file=outfile)
 
             # Does this node have menu items?
             try:
@@ -1894,13 +1894,13 @@
         if menu:
             currentnode = self.current
             if currentnode != self.topnode:    # XXX this is a hack
-                print>>outfile, ' '*indent + '<UL>'
+                print(' '*indent + '<UL>', file=outfile)
                 indent += 2
             for item in menu:
                 menunode = self.getnode(item)
                 self.dumpnode(menunode,indent,outfile)
             if currentnode != self.topnode:    # XXX this is a hack
-                print>>outfile, ' '*indent + '</UL>'
+                print(' '*indent + '</UL>', file=outfile)
                 indent -= 2
 
     def getnode(self, nodename):
@@ -1914,16 +1914,16 @@
 
     # (args,nodename) == (key,location)
     def dumpindex(self, outfile=sys.stdout):
-        print>>outfile,  '<UL>'
+        print('<UL>', file=outfile)
         for (key,location) in self.indexlist:
             key = self.codeexpand(key)
             location = makefile(location)
             location = self.dirname + '/' + location
-            print>>outfile, '<LI><OBJECT type="text/sitemap">',
-            print>>outfile, '<param name="Name" value="' + key + '">',
-            print>>outfile, '<param name="Local" value="' + location + '">',
-            print>>outfile, '</OBJECT>'
-        print>>outfile,  '</UL>'
+            print('<LI><OBJECT type="text/sitemap">', end=' ', file=outfile)
+            print('<param name="Name" value="' + key + '">', end=' ', file=outfile)
+            print('<param name="Local" value="' + location + '">', end=' ', file=outfile)
+            print('</OBJECT>', file=outfile)
+        print('</UL>', file=outfile)
 
     def codeexpand(self, line):
         co = self.codeprog.match(line)
@@ -2041,8 +2041,8 @@
         helpbase = sys.argv[2]
         del sys.argv[1:3]
     if len(sys.argv) <> 3:
-        print 'usage: texi2hh [-d [-d]] [-p] [-c] [-3] [-H htmlhelp]', \
-              'inputfile outputdirectory'
+        print('usage: texi2hh [-d [-d]] [-p] [-c] [-3] [-H htmlhelp]', \
+              'inputfile outputdirectory')
         sys.exit(2)
 
     if html3:
@@ -2064,7 +2064,7 @@
     try:
         fp = open(file, 'r')
     except IOError as msg:
-        print file, ':', msg
+        print(file, ':', msg)
         sys.exit(1)
 
     parser.parse(fp)

Modified: python/branches/py3k-buffer/Tools/scripts/treesync.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/treesync.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/treesync.py	Fri Aug 17 20:48:09 2007
@@ -54,35 +54,35 @@
     try:
         [slave, master] = args
     except ValueError:
-        print "usage: python", sys.argv[0] or "treesync.py",
-        print "[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]",
-        print "slavedir masterdir"
+        print("usage: python", sys.argv[0] or "treesync.py", end=' ')
+        print("[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]", end=' ')
+        print("slavedir masterdir")
         return
     process(slave, master)
 
 def process(slave, master):
     cvsdir = os.path.join(master, "CVS")
     if not os.path.isdir(cvsdir):
-        print "skipping master subdirectory", master
-        print "-- not under CVS"
+        print("skipping master subdirectory", master)
+        print("-- not under CVS")
         return
-    print "-"*40
-    print "slave ", slave
-    print "master", master
+    print("-"*40)
+    print("slave ", slave)
+    print("master", master)
     if not os.path.isdir(slave):
         if not okay("create slave directory %s?" % slave,
                     answer=create_directories):
-            print "skipping master subdirectory", master
-            print "-- no corresponding slave", slave
+            print("skipping master subdirectory", master)
+            print("-- no corresponding slave", slave)
             return
-        print "creating slave directory", slave
+        print("creating slave directory", slave)
         try:
             os.mkdir(slave)
         except os.error as msg:
-            print "can't make slave directory", slave, ":", msg
+            print("can't make slave directory", slave, ":", msg)
             return
         else:
-            print "made slave directory", slave
+            print("made slave directory", slave)
     cvsdir = None
     subdirs = []
     names = os.listdir(master)
@@ -117,13 +117,13 @@
         mf = None
     if not sf:
         if not mf:
-            print "Neither master nor slave exists", master
+            print("Neither master nor slave exists", master)
             return
-        print "Creating missing slave", slave
+        print("Creating missing slave", slave)
         copy(master, slave, answer=create_files)
         return
     if not mf:
-        print "Not updating missing master", master
+        print("Not updating missing master", master)
         return
     if sf and mf:
         if identical(sf, mf):
@@ -134,22 +134,22 @@
         # Master is newer -- copy master to slave
         sf.close()
         mf.close()
-        print "Master             ", master
-        print "is newer than slave", slave
+        print("Master             ", master)
+        print("is newer than slave", slave)
         copy(master, slave, answer=write_slave)
         return
     # Slave is newer -- copy slave to master
-    print "Slave is", sft-mft, "seconds newer than master"
+    print("Slave is", sft-mft, "seconds newer than master")
     # But first check what to do about CRLF
     mf.seek(0)
     fun = funnychars(mf)
     mf.close()
     sf.close()
     if fun:
-        print "***UPDATING MASTER (BINARY COPY)***"
+        print("***UPDATING MASTER (BINARY COPY)***")
         copy(slave, master, "rb", answer=write_master)
     else:
-        print "***UPDATING MASTER***"
+        print("***UPDATING MASTER***")
         copy(slave, master, "r", answer=write_master)
 
 BUFSIZE = 16*1024
@@ -174,8 +174,8 @@
     return 0
 
 def copy(src, dst, rmode="rb", wmode="wb", answer='ask'):
-    print "copying", src
-    print "     to", dst
+    print("copying", src)
+    print("     to", dst)
     if not okay("okay to copy? ", answer):
         return
     f = open(src, rmode)
@@ -203,7 +203,7 @@
         return 1
     if answer[:1] == 'n':
         return 0
-    print "Yes or No please -- try again:"
+    print("Yes or No please -- try again:")
     return okay(prompt)
 
 if __name__ == '__main__':

Modified: python/branches/py3k-buffer/Tools/scripts/untabify.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/untabify.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/untabify.py	Fri Aug 17 20:48:09 2007
@@ -13,8 +13,8 @@
         if not args:
             raise getopt.error, "At least one file argument required"
     except getopt.error as msg:
-        print msg
-        print "usage:", sys.argv[0], "[-t tabwidth] file ..."
+        print(msg)
+        print("usage:", sys.argv[0], "[-t tabwidth] file ...")
         return
     for optname, optvalue in opts:
         if optname == '-t':
@@ -29,7 +29,7 @@
         text = f.read()
         f.close()
     except IOError as msg:
-        print "%r: I/O error: %s" % (filename, msg)
+        print("%r: I/O error: %s" % (filename, msg))
         return
     newtext = text.expandtabs(tabsize)
     if newtext == text:
@@ -46,7 +46,7 @@
     f = open(filename, "w")
     f.write(newtext)
     f.close()
-    print filename
+    print(filename)
 
 if __name__ == '__main__':
     main()

Modified: python/branches/py3k-buffer/Tools/scripts/which.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/which.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/which.py	Fri Aug 17 20:48:09 2007
@@ -37,7 +37,7 @@
                 mode = S_IMODE(st[ST_MODE])
                 if mode & 0o111:
                     if not ident:
-                        print filename
+                        print(filename)
                         ident = st[:3]
                     else:
                         if st[:3] == ident:

Modified: python/branches/py3k-buffer/Tools/scripts/xxci.py
==============================================================================
--- python/branches/py3k-buffer/Tools/scripts/xxci.py	(original)
+++ python/branches/py3k-buffer/Tools/scripts/xxci.py	Fri Aug 17 20:48:09 2007
@@ -18,14 +18,14 @@
     args = sys.argv[1:]
     if args:
         return args
-    print 'No arguments, checking almost *, in "ls -t" order'
+    print('No arguments, checking almost *, in "ls -t" order')
     list = []
     for file in os.listdir(os.curdir):
         if not skipfile(file):
             list.append((getmtime(file), file))
     list.sort()
     if not list:
-        print 'Nothing to do -- exit 1'
+        print('Nothing to do -- exit 1')
         sys.exit(1)
     list.sort()
     list.reverse()
@@ -89,7 +89,7 @@
 
 def go(args):
     for file in args:
-        print file + ':'
+        print(file + ':')
         if differing(file):
             showdiffs(file)
             if askyesno('Check in ' + file + ' ? '):
@@ -119,4 +119,4 @@
         setup()
         go(getargs())
     except KeyboardInterrupt:
-        print '[Intr]'
+        print('[Intr]')

Modified: python/branches/py3k-buffer/Tools/unicode/comparecodecs.py
==============================================================================
--- python/branches/py3k-buffer/Tools/unicode/comparecodecs.py	(original)
+++ python/branches/py3k-buffer/Tools/unicode/comparecodecs.py	Fri Aug 17 20:48:09 2007
@@ -11,7 +11,7 @@
 
 def compare_codecs(encoding1, encoding2):
 
-    print 'Comparing encoding/decoding of   %r and   %r' % (encoding1, encoding2)
+    print('Comparing encoding/decoding of   %r and   %r' % (encoding1, encoding2))
     mismatch = 0
     # Check encoding
     for i in range(sys.maxunicode):
@@ -25,8 +25,8 @@
         except UnicodeError as reason:
             c2 = '<undefined>'
         if c1 != c2:
-            print ' * encoding mismatch for 0x%04X: %-14r != %r' % \
-                  (i, c1, c2)
+            print(' * encoding mismatch for 0x%04X: %-14r != %r' % \
+                  (i, c1, c2))
             mismatch += 1
     # Check decoding
     for i in range(256):
@@ -40,14 +40,14 @@
         except UnicodeError:
             u2 = u'<undefined>'
         if u1 != u2:
-            print ' * decoding mismatch for 0x%04X: %-14r != %r' % \
-                  (i, u1, u2)
+            print(' * decoding mismatch for 0x%04X: %-14r != %r' % \
+                  (i, u1, u2))
             mismatch += 1
     if mismatch:
-        print
-        print 'Found %i mismatches' % mismatch
+        print()
+        print('Found %i mismatches' % mismatch)
     else:
-        print '-> Codecs are identical.'
+        print('-> Codecs are identical.')
 
 if __name__ == '__main__':
     compare_codecs(sys.argv[1], sys.argv[2])

Modified: python/branches/py3k-buffer/Tools/unicode/gencodec.py
==============================================================================
--- python/branches/py3k-buffer/Tools/unicode/gencodec.py	(original)
+++ python/branches/py3k-buffer/Tools/unicode/gencodec.py	Fri Aug 17 20:48:09 2007
@@ -131,7 +131,7 @@
         return '(' + ', '.join(['0x%0*X' % (precision, item)
                                 for item in t]) + ')'
     except TypeError as why:
-        print '* failed to convert %r: %s' % (t, why)
+        print('* failed to convert %r: %s' % (t, why))
         raise
 
 def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)):
@@ -383,18 +383,18 @@
         name = nameprefix + name
         codefile = name + '.py'
         marshalfile = name + '.mapping'
-        print 'converting %s to %s and %s' % (mapname,
+        print('converting %s to %s and %s' % (mapname,
                                               dirprefix + codefile,
-                                              dirprefix + marshalfile)
+                                              dirprefix + marshalfile))
         try:
             map = readmap(os.path.join(dir,mapname))
             if not map:
-                print '* map is empty; skipping'
+                print('* map is empty; skipping')
             else:
                 pymap(mappathname, map, dirprefix + codefile,name,comments)
                 marshalmap(mappathname, map, dirprefix + marshalfile)
         except ValueError as why:
-            print '* conversion failed: %s' % why
+            print('* conversion failed: %s' % why)
             raise
 
 def rewritepythondir(dir, dirprefix='', comments=1):
@@ -405,17 +405,17 @@
             continue
         name = mapname[:-len('.mapping')]
         codefile = name + '.py'
-        print 'converting %s to %s' % (mapname,
-                                       dirprefix + codefile)
+        print('converting %s to %s' % (mapname,
+                                       dirprefix + codefile))
         try:
             map = marshal.load(open(os.path.join(dir,mapname),
                                'rb'))
             if not map:
-                print '* map is empty; skipping'
+                print('* map is empty; skipping')
             else:
                 pymap(mapname, map, dirprefix + codefile,name,comments)
         except ValueError as why:
-            print '* conversion failed: %s' % why
+            print('* conversion failed: %s' % why)
 
 if __name__ == '__main__':
 

Modified: python/branches/py3k-buffer/Tools/unicode/listcodecs.py
==============================================================================
--- python/branches/py3k-buffer/Tools/unicode/listcodecs.py	(original)
+++ python/branches/py3k-buffer/Tools/unicode/listcodecs.py	Fri Aug 17 20:48:09 2007
@@ -26,8 +26,8 @@
             # Probably an error from importing the codec; still it's
             # a valid code name
             if _debug:
-                print '* problem importing codec %r: %s' % \
-                      (name, reason)
+                print('* problem importing codec %r: %s' % \
+                      (name, reason))
         names.append(name)
     return names
 
@@ -35,7 +35,7 @@
 if __name__ == '__main__':
     names = listcodecs(encodings.__path__[0])
     names.sort()
-    print 'all_codecs = ['
+    print('all_codecs = [')
     for name in names:
-        print '    %r,' % name
-    print ']'
+        print('    %r,' % name)
+    print(']')

Modified: python/branches/py3k-buffer/Tools/unicode/makeunicodedata.py
==============================================================================
--- python/branches/py3k-buffer/Tools/unicode/makeunicodedata.py	(original)
+++ python/branches/py3k-buffer/Tools/unicode/makeunicodedata.py	Fri Aug 17 20:48:09 2007
@@ -60,21 +60,21 @@
 
 def maketables(trace=0):
 
-    print "--- Reading", UNICODE_DATA % "", "..."
+    print("--- Reading", UNICODE_DATA % "", "...")
 
     version = ""
     unicode = UnicodeData(UNICODE_DATA % version,
                           COMPOSITION_EXCLUSIONS % version,
                           EASTASIAN_WIDTH % version)
 
-    print len(filter(None, unicode.table)), "characters"
+    print(len(filter(None, unicode.table)), "characters")
 
     for version in old_versions:
-        print "--- Reading", UNICODE_DATA % ("-"+version), "..."
+        print("--- Reading", UNICODE_DATA % ("-"+version), "...")
         old_unicode = UnicodeData(UNICODE_DATA % ("-"+version),
                                   COMPOSITION_EXCLUSIONS % ("-"+version),
                                   EASTASIAN_WIDTH % ("-"+version))
-        print len(filter(None, old_unicode.table)), "characters"
+        print(len(filter(None, old_unicode.table)), "characters")
         merge_old_version(version, unicode, old_unicode)
 
     makeunicodename(unicode, trace)
@@ -93,7 +93,7 @@
 
     FILE = "Modules/unicodedata_db.h"
 
-    print "--- Preparing", FILE, "..."
+    print("--- Preparing", FILE, "...")
 
     # 1) database properties
 
@@ -203,93 +203,92 @@
         l = comp_last[l]
         comp_data[f*total_last+l] = char
 
-    print len(table), "unique properties"
-    print len(decomp_prefix), "unique decomposition prefixes"
-    print len(decomp_data), "unique decomposition entries:",
-    print decomp_size, "bytes"
-    print total_first, "first characters in NFC"
-    print total_last, "last characters in NFC"
-    print len(comp_pairs), "NFC pairs"
+    print(len(table), "unique properties")
+    print(len(decomp_prefix), "unique decomposition prefixes")
+    print(len(decomp_data), "unique decomposition entries:", end=' ')
+    print(decomp_size, "bytes")
+    print(total_first, "first characters in NFC")
+    print(total_last, "last characters in NFC")
+    print(len(comp_pairs), "NFC pairs")
 
-    print "--- Writing", FILE, "..."
+    print("--- Writing", FILE, "...")
 
     fp = open(FILE, "w")
-    print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
-    print >>fp
-    print >>fp, '#define UNIDATA_VERSION "%s"' % UNIDATA_VERSION
-    print >>fp, "/* a list of unique database records */"
-    print >>fp, \
-          "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {"
+    print("/* this file was generated by %s %s */" % (SCRIPT, VERSION), file=fp)
+    print(file=fp)
+    print('#define UNIDATA_VERSION "%s"' % UNIDATA_VERSION, file=fp)
+    print("/* a list of unique database records */", file=fp)
+    print("const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {", file=fp)
     for item in table:
-        print >>fp, "    {%d, %d, %d, %d, %d}," % item
-    print >>fp, "};"
-    print >>fp
-
-    print >>fp, "/* Reindexing of NFC first characters. */"
-    print >>fp, "#define TOTAL_FIRST",total_first
-    print >>fp, "#define TOTAL_LAST",total_last
-    print >>fp, "struct reindex{int start;short count,index;};"
-    print >>fp, "struct reindex nfc_first[] = {"
+        print("    {%d, %d, %d, %d, %d}," % item, file=fp)
+    print("};", file=fp)
+    print(file=fp)
+
+    print("/* Reindexing of NFC first characters. */", file=fp)
+    print("#define TOTAL_FIRST",total_first, file=fp)
+    print("#define TOTAL_LAST",total_last, file=fp)
+    print("struct reindex{int start;short count,index;};", file=fp)
+    print("struct reindex nfc_first[] = {", file=fp)
     for start,end in comp_first_ranges:
-        print >>fp,"  { %d, %d, %d}," % (start,end-start,comp_first[start])
-    print >>fp,"  {0,0,0}"
-    print >>fp,"};\n"
-    print >>fp, "struct reindex nfc_last[] = {"
+        print("  { %d, %d, %d}," % (start,end-start,comp_first[start]), file=fp)
+    print("  {0,0,0}", file=fp)
+    print("};\n", file=fp)
+    print("struct reindex nfc_last[] = {", file=fp)
     for start,end in comp_last_ranges:
-        print >>fp,"  { %d, %d, %d}," % (start,end-start,comp_last[start])
-    print >>fp,"  {0,0,0}"
-    print >>fp,"};\n"
+        print("  { %d, %d, %d}," % (start,end-start,comp_last[start]), file=fp)
+    print("  {0,0,0}", file=fp)
+    print("};\n", file=fp)
 
     # FIXME: <fl> the following tables could be made static, and
     # the support code moved into unicodedatabase.c
 
-    print >>fp, "/* string literals */"
-    print >>fp, "const char *_PyUnicode_CategoryNames[] = {"
+    print("/* string literals */", file=fp)
+    print("const char *_PyUnicode_CategoryNames[] = {", file=fp)
     for name in CATEGORY_NAMES:
-        print >>fp, "    \"%s\"," % name
-    print >>fp, "    NULL"
-    print >>fp, "};"
+        print("    \"%s\"," % name, file=fp)
+    print("    NULL", file=fp)
+    print("};", file=fp)
 
-    print >>fp, "const char *_PyUnicode_BidirectionalNames[] = {"
+    print("const char *_PyUnicode_BidirectionalNames[] = {", file=fp)
     for name in BIDIRECTIONAL_NAMES:
-        print >>fp, "    \"%s\"," % name
-    print >>fp, "    NULL"
-    print >>fp, "};"
+        print("    \"%s\"," % name, file=fp)
+    print("    NULL", file=fp)
+    print("};", file=fp)
 
-    print >>fp, "const char *_PyUnicode_EastAsianWidthNames[] = {"
+    print("const char *_PyUnicode_EastAsianWidthNames[] = {", file=fp)
     for name in EASTASIANWIDTH_NAMES:
-        print >>fp, "    \"%s\"," % name
-    print >>fp, "    NULL"
-    print >>fp, "};"
+        print("    \"%s\"," % name, file=fp)
+    print("    NULL", file=fp)
+    print("};", file=fp)
 
-    print >>fp, "static const char *decomp_prefix[] = {"
+    print("static const char *decomp_prefix[] = {", file=fp)
     for name in decomp_prefix:
-        print >>fp, "    \"%s\"," % name
-    print >>fp, "    NULL"
-    print >>fp, "};"
+        print("    \"%s\"," % name, file=fp)
+    print("    NULL", file=fp)
+    print("};", file=fp)
 
     # split record index table
     index1, index2, shift = splitbins(index, trace)
 
-    print >>fp, "/* index tables for the database records */"
-    print >>fp, "#define SHIFT", shift
+    print("/* index tables for the database records */", file=fp)
+    print("#define SHIFT", shift, file=fp)
     Array("index1", index1).dump(fp, trace)
     Array("index2", index2).dump(fp, trace)
 
     # split decomposition index table
     index1, index2, shift = splitbins(decomp_index, trace)
 
-    print >>fp, "/* decomposition data */"
+    print("/* decomposition data */", file=fp)
     Array("decomp_data", decomp_data).dump(fp, trace)
 
-    print >>fp, "/* index tables for the decomposition data */"
-    print >>fp, "#define DECOMP_SHIFT", shift
+    print("/* index tables for the decomposition data */", file=fp)
+    print("#define DECOMP_SHIFT", shift, file=fp)
     Array("decomp_index1", index1).dump(fp, trace)
     Array("decomp_index2", index2).dump(fp, trace)
 
     index, index2, shift = splitbins(comp_data, trace)
-    print >>fp, "/* NFC pairs */"
-    print >>fp, "#define COMP_SHIFT", shift
+    print("/* NFC pairs */", file=fp)
+    print("#define COMP_SHIFT", shift, file=fp)
     Array("comp_index", index).dump(fp, trace)
     Array("comp_data", index2).dump(fp, trace)
 
@@ -306,30 +305,30 @@
                 index[i] = cache[record] = len(records)
                 records.append(record)
         index1, index2, shift = splitbins(index, trace)
-        print >>fp, "static const change_record change_records_%s[] = {" % cversion
+        print("static const change_record change_records_%s[] = {" % cversion, file=fp)
         for record in records:
-            print >>fp, "\t{ %s }," % ", ".join(map(str,record))
-        print >>fp, "};"
+            print("\t{ %s }," % ", ".join(map(str,record)), file=fp)
+        print("};", file=fp)
         Array("changes_%s_index" % cversion, index1).dump(fp, trace)
         Array("changes_%s_data" % cversion, index2).dump(fp, trace)
-        print >>fp, "static const change_record* get_change_%s(Py_UCS4 n)" % cversion
-        print >>fp, "{"
-        print >>fp, "\tint index;"
-        print >>fp, "\tif (n >= 0x110000) index = 0;"
-        print >>fp, "\telse {"
-        print >>fp, "\t\tindex = changes_%s_index[n>>%d];" % (cversion, shift)
-        print >>fp, "\t\tindex = changes_%s_data[(index<<%d)+(n & %d)];" % \
-              (cversion, shift, ((1<<shift)-1))
-        print >>fp, "\t}"
-        print >>fp, "\treturn change_records_%s+index;" % cversion
-        print >>fp, "}\n"
-        print >>fp, "static Py_UCS4 normalization_%s(Py_UCS4 n)" % cversion
-        print >>fp, "{"
-        print >>fp, "\tswitch(n) {"
+        print("static const change_record* get_change_%s(Py_UCS4 n)" % cversion, file=fp)
+        print("{", file=fp)
+        print("\tint index;", file=fp)
+        print("\tif (n >= 0x110000) index = 0;", file=fp)
+        print("\telse {", file=fp)
+        print("\t\tindex = changes_%s_index[n>>%d];" % (cversion, shift), file=fp)
+        print("\t\tindex = changes_%s_data[(index<<%d)+(n & %d)];" % \
+              (cversion, shift, ((1<<shift)-1)), file=fp)
+        print("\t}", file=fp)
+        print("\treturn change_records_%s+index;" % cversion, file=fp)
+        print("}\n", file=fp)
+        print("static Py_UCS4 normalization_%s(Py_UCS4 n)" % cversion, file=fp)
+        print("{", file=fp)
+        print("\tswitch(n) {", file=fp)
         for k, v in normalization:
-            print >>fp, "\tcase %s: return 0x%s;" % (hex(k), v)
-        print >>fp, "\tdefault: return 0;"
-        print >>fp, "\t}\n}\n"
+            print("\tcase %s: return 0x%s;" % (hex(k), v), file=fp)
+        print("\tdefault: return 0;", file=fp)
+        print("\t}\n}\n", file=fp)
 
     fp.close()
 
@@ -340,7 +339,7 @@
 
     FILE = "Objects/unicodetype_db.h"
 
-    print "--- Preparing", FILE, "..."
+    print("--- Preparing", FILE, "...")
 
     # extract unicode types
     dummy = (0, 0, 0, 0, 0, 0)
@@ -405,25 +404,25 @@
                 table.append(item)
             index[char] = i
 
-    print len(table), "unique character type entries"
+    print(len(table), "unique character type entries")
 
-    print "--- Writing", FILE, "..."
+    print("--- Writing", FILE, "...")
 
     fp = open(FILE, "w")
-    print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
-    print >>fp
-    print >>fp, "/* a list of unique character type descriptors */"
-    print >>fp, "const _PyUnicode_TypeRecord _PyUnicode_TypeRecords[] = {"
+    print("/* this file was generated by %s %s */" % (SCRIPT, VERSION), file=fp)
+    print(file=fp)
+    print("/* a list of unique character type descriptors */", file=fp)
+    print("const _PyUnicode_TypeRecord _PyUnicode_TypeRecords[] = {", file=fp)
     for item in table:
-        print >>fp, "    {%d, %d, %d, %d, %d, %d}," % item
-    print >>fp, "};"
-    print >>fp
+        print("    {%d, %d, %d, %d, %d, %d}," % item, file=fp)
+    print("};", file=fp)
+    print(file=fp)
 
     # split decomposition index table
     index1, index2, shift = splitbins(index, trace)
 
-    print >>fp, "/* type indexes */"
-    print >>fp, "#define SHIFT", shift
+    print("/* type indexes */", file=fp)
+    print("#define SHIFT", shift, file=fp)
     Array("index1", index1).dump(fp, trace)
     Array("index2", index2).dump(fp, trace)
 
@@ -436,7 +435,7 @@
 
     FILE = "Modules/unicodename_db.h"
 
-    print "--- Preparing", FILE, "..."
+    print("--- Preparing", FILE, "...")
 
     # collect names
     names = [None] * len(unicode.chars)
@@ -448,7 +447,7 @@
             if name and name[0] != "<":
                 names[char] = name + chr(0)
 
-    print len(filter(lambda n: n is not None, names)), "distinct names"
+    print(len(filter(lambda n: n is not None, names)), "distinct names")
 
     # collect unique words from names (note that we differ between
     # words inside a sentence, and words ending a sentence.  the
@@ -469,7 +468,7 @@
                 else:
                     words[w] = [len(words)]
 
-    print n, "words in text;", b, "bytes"
+    print(n, "words in text;", b, "bytes")
 
     wordlist = words.items()
 
@@ -485,19 +484,19 @@
     escapes = 0
     while escapes * 256 < len(wordlist):
         escapes = escapes + 1
-    print escapes, "escapes"
+    print(escapes, "escapes")
 
     short = 256 - escapes
 
     assert short > 0
 
-    print short, "short indexes in lexicon"
+    print(short, "short indexes in lexicon")
 
     # statistics
     n = 0
     for i in range(short):
         n = n + len(wordlist[i][1])
-    print n, "short indexes in phrasebook"
+    print(n, "short indexes in phrasebook")
 
     # pick the most commonly used words, and sort the rest on falling
     # length (to maximize overlap)
@@ -566,29 +565,29 @@
 
     codehash = Hash("code", data, 47)
 
-    print "--- Writing", FILE, "..."
+    print("--- Writing", FILE, "...")
 
     fp = open(FILE, "w")
-    print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
-    print >>fp
-    print >>fp, "#define NAME_MAXLEN", 256
-    print >>fp
-    print >>fp, "/* lexicon */"
+    print("/* this file was generated by %s %s */" % (SCRIPT, VERSION), file=fp)
+    print(file=fp)
+    print("#define NAME_MAXLEN", 256, file=fp)
+    print(file=fp)
+    print("/* lexicon */", file=fp)
     Array("lexicon", lexicon).dump(fp, trace)
     Array("lexicon_offset", lexicon_offset).dump(fp, trace)
 
     # split decomposition index table
     offset1, offset2, shift = splitbins(phrasebook_offset, trace)
 
-    print >>fp, "/* code->name phrasebook */"
-    print >>fp, "#define phrasebook_shift", shift
-    print >>fp, "#define phrasebook_short", short
+    print("/* code->name phrasebook */", file=fp)
+    print("#define phrasebook_shift", shift, file=fp)
+    print("#define phrasebook_short", short, file=fp)
 
     Array("phrasebook", phrasebook).dump(fp, trace)
     Array("phrasebook_offset1", offset1).dump(fp, trace)
     Array("phrasebook_offset2", offset2).dump(fp, trace)
 
-    print >>fp, "/* name->code dictionary */"
+    print("/* name->code dictionary */", file=fp)
     codehash.dump(fp, trace)
 
     fp.close()
@@ -781,7 +780,7 @@
         else:
             raise AssertionError, "ran out of polynominals"
 
-        print size, "slots in hash table"
+        print(size, "slots in hash table")
 
         table = [None] * size
 
@@ -813,7 +812,7 @@
                 if incr > mask:
                     incr = incr ^ poly
 
-        print n, "collisions"
+        print(n, "collisions")
         self.collisions = n
 
         for i in range(len(table)):
@@ -845,7 +844,7 @@
         # write data to file, as a C array
         size = getsize(self.data)
         if trace:
-            print >>sys.stderr, self.name+":", size*len(self.data), "bytes"
+            print(self.name+":", size*len(self.data), "bytes", file=sys.stderr)
         file.write("static ")
         if size == 1:
             file.write("unsigned char")
@@ -895,10 +894,10 @@
     import sys
     if trace:
         def dump(t1, t2, shift, bytes):
-            print >>sys.stderr, "%d+%d bins at shift %d; %d bytes" % (
-                len(t1), len(t2), shift, bytes)
-        print >>sys.stderr, "Size of original table:", len(t)*getsize(t), \
-                            "bytes"
+            print("%d+%d bins at shift %d; %d bytes" % (
+                len(t1), len(t2), shift, bytes), file=sys.stderr)
+        print("Size of original table:", len(t)*getsize(t), \
+                            "bytes", file=sys.stderr)
     n = len(t)-1    # last valid index
     maxshift = 0    # the most we can shift n and still have something left
     if n > 0:
@@ -930,7 +929,7 @@
             bytes = b
     t1, t2, shift = best
     if trace:
-        print >>sys.stderr, "Best:",
+        print("Best:", end=' ', file=sys.stderr)
         dump(t1, t2, shift, bytes)
     if __debug__:
         # exhaustively verify that the decomposition is correct

Modified: python/branches/py3k-buffer/Tools/unicode/mkstringprep.py
==============================================================================
--- python/branches/py3k-buffer/Tools/unicode/mkstringprep.py	(original)
+++ python/branches/py3k-buffer/Tools/unicode/mkstringprep.py	Fri Aug 17 20:48:09 2007
@@ -106,7 +106,7 @@
 
 ########### Generate compact Python versions of the tables #############
 
-print """# This file is generated by mkstringprep.py. DO NOT EDIT.
+print("""# This file is generated by mkstringprep.py. DO NOT EDIT.
 \"\"\"Library that exposes various tables found in the StringPrep RFC 3454.
 
 There are two kinds of tables: sets, for which a member test is provided,
@@ -114,9 +114,9 @@
 \"\"\"
 
 import unicodedata
-"""
+""")
 
-print "assert unicodedata.unidata_version == %s" % repr(unicodedata.unidata_version)
+print("assert unicodedata.unidata_version == %s" % repr(unicodedata.unidata_version))
 
 # A.1 is the table of unassigned characters
 # XXX Plane 15 PUA is listed as unassigned in Python.
@@ -134,13 +134,13 @@
 
 # assert table == Cn
 
-print """
+print("""
 def in_table_a1(code):
     if unicodedata.category(code) != 'Cn': return False
     c = ord(code)
     if 0xFDD0 <= c < 0xFDF0: return False
     return (c & 0xFFFF) not in (0xFFFE, 0xFFFF)
-"""
+""")
 
 # B.1 cannot easily be derived
 name, table = tables[0]
@@ -148,11 +148,11 @@
 assert name == "B.1"
 table = table.keys()
 table.sort()
-print """
+print("""
 b1_set = """ + compact_set(table) + """
 def in_table_b1(code):
     return ord(code) in b1_set
-"""
+""")
 
 # B.2 and B.3 is case folding.
 # It takes CaseFolding.txt into account, which is
@@ -180,20 +180,20 @@
 b3 = b3_exceptions.items()
 b3.sort()
 
-print """
-b3_exceptions = {"""
+print("""
+b3_exceptions = {""")
 for i,(k,v) in enumerate(b3):
-    print "0x%x:%s," % (k, repr(v)),
+    print("0x%x:%s," % (k, repr(v)), end=' ')
     if i % 4 == 3:
-        print
-print "}"
+        print()
+print("}")
 
-print """
+print("""
 def map_table_b3(code):
     r = b3_exceptions.get(ord(code))
     if r is not None: return r
     return code.lower()
-"""
+""")
 
 def map_table_b3(code):
     r = b3_exceptions.get(ord(code))
@@ -222,7 +222,7 @@
 # B.3 should not add any additional special cases
 assert specials == {}
 
-print """
+print("""
 def map_table_b2(a):
     al = map_table_b3(a)
     b = unicodedata.normalize("NFKC", al)
@@ -232,7 +232,7 @@
         return c
     else:
         return al
-"""
+""")
 
 # C.1.1 is a table with a single character
 name, table = tables[0]
@@ -240,10 +240,10 @@
 assert name == "C.1.1"
 assert table == {0x20:0x20}
 
-print """
+print("""
 def in_table_c11(code):
     return code == u" "
-"""
+""")
 
 # C.1.2 is the rest of all space characters
 name, table = tables[0]
@@ -254,13 +254,13 @@
 # Zs = set(gen_category(["Zs"])) - set([0x20])
 # assert Zs == table
 
-print """
+print("""
 def in_table_c12(code):
     return unicodedata.category(code) == "Zs" and code != u" "
 
 def in_table_c11_c12(code):
     return unicodedata.category(code) == "Zs"
-"""
+""")
 
 # C.2.1 ASCII control characters
 name, table_c21 = tables[0]
@@ -272,10 +272,10 @@
 table_c21 = set(table_c21.keys())
 assert Cc_ascii == table_c21
 
-print """
+print("""
 def in_table_c21(code):
     return ord(code) < 128 and unicodedata.category(code) == "Cc"
-"""
+""")
 
 # C.2.2 Non-ASCII control characters. It also includes
 # a number of characters in category Cf.
@@ -290,7 +290,7 @@
 specials = list(table_c22 - Cc_nonascii)
 specials.sort()
 
-print """c22_specials = """ + compact_set(specials) + """
+print("""c22_specials = """ + compact_set(specials) + """
 def in_table_c22(code):
     c = ord(code)
     if c < 128: return False
@@ -300,7 +300,7 @@
 def in_table_c21_c22(code):
     return unicodedata.category(code) == "Cc" or \\
            ord(code) in c22_specials
-"""
+""")
 
 # C.3 Private use
 name, table = tables[0]
@@ -310,10 +310,10 @@
 Co = set(gen_category(["Co"]))
 assert set(table.keys()) == Co
 
-print """
+print("""
 def in_table_c3(code):
     return unicodedata.category(code) == "Co"
-"""
+""")
 
 # C.4 Non-character code points, xFFFE, xFFFF
 # plus process internal codes
@@ -327,13 +327,13 @@
 table = set(table.keys())
 assert table == nonchar
 
-print """
+print("""
 def in_table_c4(code):
     c = ord(code)
     if c < 0xFDD0: return False
     if c < 0xFDF0: return True
     return (ord(code) & 0xFFFF) in (0xFFFE, 0xFFFF)
-"""
+""")
 
 # C.5 Surrogate codes
 name, table = tables[0]
@@ -343,10 +343,10 @@
 Cs = set(gen_category(["Cs"]))
 assert set(table.keys()) == Cs
 
-print """
+print("""
 def in_table_c5(code):
     return unicodedata.category(code) == "Cs"
-"""
+""")
 
 # C.6 Inappropriate for plain text
 name, table = tables[0]
@@ -356,11 +356,11 @@
 table = table.keys()
 table.sort()
 
-print """
+print("""
 c6_set = """ + compact_set(table) + """
 def in_table_c6(code):
     return ord(code) in c6_set
-"""
+""")
 
 # C.7 Inappropriate for canonical representation
 name, table = tables[0]
@@ -370,11 +370,11 @@
 table = table.keys()
 table.sort()
 
-print """
+print("""
 c7_set = """ + compact_set(table) + """
 def in_table_c7(code):
     return ord(code) in c7_set
-"""
+""")
 
 # C.8 Change display properties or are deprecated
 name, table = tables[0]
@@ -384,11 +384,11 @@
 table = table.keys()
 table.sort()
 
-print """
+print("""
 c8_set = """ + compact_set(table) + """
 def in_table_c8(code):
     return ord(code) in c8_set
-"""
+""")
 
 # C.9 Tagging characters
 name, table = tables[0]
@@ -398,11 +398,11 @@
 table = table.keys()
 table.sort()
 
-print """
+print("""
 c9_set = """ + compact_set(table) + """
 def in_table_c9(code):
     return ord(code) in c9_set
-"""
+""")
 
 # D.1 Characters with bidirectional property "R" or "AL"
 name, table = tables[0]
@@ -412,10 +412,10 @@
 RandAL = set(gen_bidirectional(["R","AL"]))
 assert set(table.keys()) == RandAL
 
-print """
+print("""
 def in_table_d1(code):
     return unicodedata.bidirectional(code) in ("R","AL")
-"""
+""")
 
 # D.2 Characters with bidirectional property "L"
 name, table = tables[0]
@@ -425,7 +425,7 @@
 L = set(gen_bidirectional(["L"]))
 assert set(table.keys()) == L
 
-print """
+print("""
 def in_table_d2(code):
     return unicodedata.bidirectional(code) == "L"
-"""
+""")

Modified: python/branches/py3k-buffer/Tools/versioncheck/checkversions.py
==============================================================================
--- python/branches/py3k-buffer/Tools/versioncheck/checkversions.py	(original)
+++ python/branches/py3k-buffer/Tools/versioncheck/checkversions.py	Fri Aug 17 20:48:09 2007
@@ -28,7 +28,7 @@
         try:
             execfile(fullname)
         except:
-            print '** Exception in', fullname
+            print('** Exception in', fullname)
 
 def walk1tree(tree):
     os.path.walk(tree, check1dir, None)
@@ -38,7 +38,7 @@
     try:
         options, arguments = getopt.getopt(sys.argv[1:], 'v:')
     except getopt.error:
-        print USAGE
+        print(USAGE)
         sys.exit(1)
     for o, a in options:
         if o == '-v':

Modified: python/branches/py3k-buffer/Tools/versioncheck/pyversioncheck.py
==============================================================================
--- python/branches/py3k-buffer/Tools/versioncheck/pyversioncheck.py	(original)
+++ python/branches/py3k-buffer/Tools/versioncheck/pyversioncheck.py	Fri Aug 17 20:48:09 2007
@@ -18,12 +18,12 @@
     if verbose > VERBOSE_NORMAL:
         return ok
     if ok < 0:
-        print '%s: No correctly formatted current version file found'%(package)
+        print('%s: No correctly formatted current version file found'%(package))
     elif ok == 1:
-        print '%s: up-to-date (version %s)'%(package, version)
+        print('%s: up-to-date (version %s)'%(package, version))
     else:
-        print '%s: version %s installed, version %s found:' % \
-                        (package, version, newversion)
+        print('%s: version %s installed, version %s found:' % \
+                        (package, version, newversion))
         if verbose > VERBOSE_SILENT:
             while 1:
                 line = fp.readline()
@@ -33,7 +33,7 @@
 
 def checkonly(package, url, version, verbose=0):
     if verbose >= VERBOSE_EACHFILE:
-        print '%s:'%package
+        print('%s:'%package)
     if isinstance(url, str):
         ok, newversion, fp = _check1version(package, url, version, verbose)
     else:
@@ -45,51 +45,51 @@
 
 def _check1version(package, url, version, verbose=0):
     if verbose >= VERBOSE_EACHFILE:
-        print '  Checking %s'%url
+        print('  Checking %s'%url)
     try:
         fp = urllib.urlopen(url)
     except IOError as arg:
         if verbose >= VERBOSE_EACHFILE:
-            print '    Cannot open:', arg
+            print('    Cannot open:', arg)
         return -1, None, None
     msg = rfc822.Message(fp, seekable=0)
     newversion = msg.getheader('current-version')
     if not newversion:
         if verbose >= VERBOSE_EACHFILE:
-            print '    No "Current-Version:" header in URL or URL not found'
+            print('    No "Current-Version:" header in URL or URL not found')
         return -1, None, None
     version = version.lower().strip()
     newversion = newversion.lower().strip()
     if version == newversion:
         if verbose >= VERBOSE_EACHFILE:
-            print '    Version identical (%s)'%newversion
+            print('    Version identical (%s)'%newversion)
         return 1, version, fp
     else:
         if verbose >= VERBOSE_EACHFILE:
-            print '    Versions different (installed: %s, new: %s)'% \
-                        (version, newversion)
+            print('    Versions different (installed: %s, new: %s)'% \
+                        (version, newversion))
         return 0, newversion, fp
 
 
 def _test():
-    print '--- TEST VERBOSE=1'
-    print '--- Testing existing and identical version file'
+    print('--- TEST VERBOSE=1')
+    print('--- Testing existing and identical version file')
     versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=1)
-    print '--- Testing existing package with new version'
+    print('--- Testing existing package with new version')
     versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=1)
-    print '--- Testing package with non-existing version file'
+    print('--- Testing package with non-existing version file')
     versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=1)
-    print '--- Test package with 2 locations, first non-existing second ok'
+    print('--- Test package with 2 locations, first non-existing second ok')
     versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt']
     versioncheck('VersionTestPackage', versfiles, '1.0', verbose=1)
-    print '--- TEST VERBOSE=2'
-    print '--- Testing existing and identical version file'
+    print('--- TEST VERBOSE=2')
+    print('--- Testing existing and identical version file')
     versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=2)
-    print '--- Testing existing package with new version'
+    print('--- Testing existing package with new version')
     versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=2)
-    print '--- Testing package with non-existing version file'
+    print('--- Testing package with non-existing version file')
     versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=2)
-    print '--- Test package with 2 locations, first non-existing second ok'
+    print('--- Test package with 2 locations, first non-existing second ok')
     versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt']
     versioncheck('VersionTestPackage', versfiles, '1.0', verbose=2)
 

Modified: python/branches/py3k-buffer/Tools/webchecker/wcgui.py
==============================================================================
--- python/branches/py3k-buffer/Tools/webchecker/wcgui.py	(original)
+++ python/branches/py3k-buffer/Tools/webchecker/wcgui.py	Fri Aug 17 20:48:09 2007
@@ -76,8 +76,8 @@
         opts, args = getopt.getopt(sys.argv[1:], 't:m:qva')
     except getopt.error as msg:
         sys.stdout = sys.stderr
-        print msg
-        print __doc__%vars(webchecker)
+        print(msg)
+        print(__doc__%vars(webchecker))
         sys.exit(2)
     webchecker.verbose = webchecker.VERBOSE
     webchecker.nonames = webchecker.NONAMES

Modified: python/branches/py3k-buffer/Tools/webchecker/webchecker.py
==============================================================================
--- python/branches/py3k-buffer/Tools/webchecker/webchecker.py	(original)
+++ python/branches/py3k-buffer/Tools/webchecker/webchecker.py	Fri Aug 17 20:48:09 2007
@@ -109,7 +109,7 @@
 import sys
 import os
 from types import *
-import StringIO
+import io
 import getopt
 import pickle
 
@@ -155,8 +155,8 @@
         opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
     except getopt.error as msg:
         sys.stdout = sys.stderr
-        print msg
-        print __doc__%globals()
+        print(msg)
+        print(__doc__%globals())
         sys.exit(2)
 
     # The extra_roots variable collects extra roots.
@@ -186,7 +186,7 @@
             checkext = not checkext
 
     if verbose > 0:
-        print AGENTNAME, "version", __version__
+        print(AGENTNAME, "version", __version__)
 
     if restart:
         c = load_pickle(dumpfile=dumpfile, verbose=verbose)
@@ -222,32 +222,32 @@
                 c.run()
             except KeyboardInterrupt:
                 if verbose > 0:
-                    print "[run interrupted]"
+                    print("[run interrupted]")
 
         try:
             c.report()
         except KeyboardInterrupt:
             if verbose > 0:
-                print "[report interrupted]"
+                print("[report interrupted]")
 
     finally:
         if c.save_pickle(dumpfile):
             if dumpfile == DUMPFILE:
-                print "Use ``%s -R'' to restart." % sys.argv[0]
+                print("Use ``%s -R'' to restart." % sys.argv[0])
             else:
-                print "Use ``%s -R -d %s'' to restart." % (sys.argv[0],
-                                                           dumpfile)
+                print("Use ``%s -R -d %s'' to restart." % (sys.argv[0],
+                                                           dumpfile))
 
 
 def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE):
     if verbose > 0:
-        print "Loading checkpoint from %s ..." % dumpfile
+        print("Loading checkpoint from %s ..." % dumpfile)
     f = open(dumpfile, "rb")
     c = pickle.load(f)
     f.close()
     if verbose > 0:
-        print "Done."
-        print "Root:", "\n      ".join(c.roots)
+        print("Done.")
+        print("Root:", "\n      ".join(c.roots))
     return c
 
 
@@ -297,7 +297,7 @@
     def message(self, format, *args):
         if args:
             format = format%args
-        print format
+        print(format)
 
     def __getstate__(self):
         return (self.roots, self.todo, self.done, self.bad, self.round)
@@ -689,7 +689,7 @@
             if self.verbose >= level:
                 if args:
                     msg = msg%args
-                print msg
+                print(msg)
 
     # Method to retrieve names.
     def getnames(self):
@@ -721,12 +721,12 @@
         return infos
 
 
-class MyStringIO(StringIO.StringIO):
+class MyStringIO(io.StringIO):
 
     def __init__(self, url, info):
         self.__url = url
         self.__info = info
-        StringIO.StringIO.__init__(self)
+        super(MyStringIO, self).__init__(self)
 
     def info(self):
         return self.__info

Modified: python/branches/py3k-buffer/Tools/webchecker/websucker.py
==============================================================================
--- python/branches/py3k-buffer/Tools/webchecker/websucker.py	(original)
+++ python/branches/py3k-buffer/Tools/webchecker/websucker.py	Fri Aug 17 20:48:09 2007
@@ -22,8 +22,8 @@
     try:
         opts, args = getopt.getopt(sys.argv[1:], "qv")
     except getopt.error as msg:
-        print msg
-        print "usage:", sys.argv[0], "[-qv] ... [rooturl] ..."
+        print(msg)
+        print("usage:", sys.argv[0], "[-qv] ... [rooturl] ...")
         return 2
     for o, a in opts:
         if o == "-q":
@@ -36,9 +36,9 @@
             ('User-agent', 'websucker/%s' % __version__),
         ]
     for arg in args:
-        print "Adding root", arg
+        print("Adding root", arg)
         c.addroot(arg)
-    print "Run..."
+    print("Run...")
     c.run()
 
 class Sucker(webchecker.Checker):
@@ -116,7 +116,7 @@
         return
     head, tail = os.path.split(dir)
     if not tail:
-        print "Huh?  Don't know how to make dir", dir
+        print("Huh?  Don't know how to make dir", dir)
         return
     makedirs(head)
     os.mkdir(dir, 0o777)

Modified: python/branches/py3k-buffer/configure
==============================================================================
--- python/branches/py3k-buffer/configure	(original)
+++ python/branches/py3k-buffer/configure	Fri Aug 17 20:48:09 2007
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.in Revision: 54283 .
+# From configure.in Revision: 55739 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.61 for python 3.0.
 #
@@ -1838,6 +1838,14 @@
 _ACEOF
 
 
+# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is
+# also defined. This can be overridden by defining _BSD_SOURCE
+
+cat >>confdefs.h <<\_ACEOF
+#define _BSD_SOURCE 1
+_ACEOF
+
+
 # The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables
 # u_int on Irix 5.3. Defining _BSD_TYPES brings it back.
 

Modified: python/branches/py3k-buffer/configure.in
==============================================================================
--- python/branches/py3k-buffer/configure.in	(original)
+++ python/branches/py3k-buffer/configure.in	Fri Aug 17 20:48:09 2007
@@ -50,6 +50,10 @@
 # them.
 AC_DEFINE(__BSD_VISIBLE, 1, [Define on FreeBSD to activate all library features])
 
+# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is
+# also defined. This can be overridden by defining _BSD_SOURCE
+AC_DEFINE(_BSD_SOURCE, 1, [Define on OpenBSD to activate all library features])
+
 # The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables
 # u_int on Irix 5.3. Defining _BSD_TYPES brings it back.
 AC_DEFINE(_BSD_TYPES, 1, [Define on Irix to enable u_int])

Modified: python/branches/py3k-buffer/pyconfig.h.in
==============================================================================
--- python/branches/py3k-buffer/pyconfig.h.in	(original)
+++ python/branches/py3k-buffer/pyconfig.h.in	Fri Aug 17 20:48:09 2007
@@ -103,6 +103,10 @@
 /* Define if you have the 'resize_term' function. */
 #undef HAVE_CURSES_RESIZE_TERM
 
+/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
+   */
+#undef HAVE_DECL_TZNAME
+
 /* Define to 1 if you have the device macros. */
 #undef HAVE_DEVICE_MACROS
 
@@ -802,22 +806,22 @@
 /* Define if i>>j for signed int i does not extend the sign bit when i < 0 */
 #undef SIGNED_RIGHT_SHIFT_ZERO_FILLS
 
-/* The size of a `double', as computed by sizeof. */
+/* The size of `double', as computed by sizeof. */
 #undef SIZEOF_DOUBLE
 
-/* The size of a `float', as computed by sizeof. */
+/* The size of `float', as computed by sizeof. */
 #undef SIZEOF_FLOAT
 
-/* The size of a `fpos_t', as computed by sizeof. */
+/* The size of `fpos_t', as computed by sizeof. */
 #undef SIZEOF_FPOS_T
 
-/* The size of a `int', as computed by sizeof. */
+/* The size of `int', as computed by sizeof. */
 #undef SIZEOF_INT
 
-/* The size of a `long', as computed by sizeof. */
+/* The size of `long', as computed by sizeof. */
 #undef SIZEOF_LONG
 
-/* The size of a `long long', as computed by sizeof. */
+/* The size of `long long', as computed by sizeof. */
 #undef SIZEOF_LONG_LONG
 
 /* The number of bytes in an off_t. */
@@ -826,25 +830,25 @@
 /* The number of bytes in a pthread_t. */
 #undef SIZEOF_PTHREAD_T
 
-/* The size of a `short', as computed by sizeof. */
+/* The size of `short', as computed by sizeof. */
 #undef SIZEOF_SHORT
 
-/* The size of a `size_t', as computed by sizeof. */
+/* The size of `size_t', as computed by sizeof. */
 #undef SIZEOF_SIZE_T
 
 /* The number of bytes in a time_t. */
 #undef SIZEOF_TIME_T
 
-/* The size of a `uintptr_t', as computed by sizeof. */
+/* The size of `uintptr_t', as computed by sizeof. */
 #undef SIZEOF_UINTPTR_T
 
-/* The size of a `void *', as computed by sizeof. */
+/* The size of `void *', as computed by sizeof. */
 #undef SIZEOF_VOID_P
 
-/* The size of a `wchar_t', as computed by sizeof. */
+/* The size of `wchar_t', as computed by sizeof. */
 #undef SIZEOF_WCHAR_T
 
-/* The size of a `_Bool', as computed by sizeof. */
+/* The size of `_Bool', as computed by sizeof. */
 #undef SIZEOF__BOOL
 
 /* Define to 1 if you have the ANSI C header files. */
@@ -924,6 +928,9 @@
 # undef _ALL_SOURCE
 #endif
 
+/* Define on OpenBSD to activate all library features */
+#undef _BSD_SOURCE
+
 /* Define on Irix to enable u_int */
 #undef _BSD_TYPES
 
@@ -980,7 +987,7 @@
 /* Define to `int' if <sys/types.h> does not define. */
 #undef mode_t
 
-/* Define to `long' if <sys/types.h> does not define. */
+/* Define to `long int' if <sys/types.h> does not define. */
 #undef off_t
 
 /* Define to `int' if <sys/types.h> does not define. */
@@ -989,7 +996,7 @@
 /* Define to empty if the keyword does not work. */
 #undef signed
 
-/* Define to `unsigned' if <sys/types.h> does not define. */
+/* Define to `unsigned int' if <sys/types.h> does not define. */
 #undef size_t
 
 /* Define to `int' if <sys/socket.h> does not define. */

Modified: python/branches/py3k-buffer/runtests.sh
==============================================================================
--- python/branches/py3k-buffer/runtests.sh	(original)
+++ python/branches/py3k-buffer/runtests.sh	Fri Aug 17 20:48:09 2007
@@ -48,7 +48,10 @@
 for T in $TESTS
 do
     echo -n $T
-    if $PYTHON Lib/test/regrtest.py $UFLAG $T >OUT/$T.out 2>&1
+    if   case $T in
+         *curses*) echo; $PYTHON Lib/test/regrtest.py $UFLAG $T 2>OUT/$T.out;;
+         *) $PYTHON Lib/test/regrtest.py $UFLAG $T >OUT/$T.out 2>&1;;
+         esac
     then
 	if grep -q "1 test skipped:" OUT/$T.out
 	then
@@ -61,7 +64,5 @@
     else
 	echo " BAD"
         echo $T >>BAD
-	##echo "--------- Re-running test in verbose mode ---------" >>OUT/$T.out
-	##$PYTHON Lib/test/regrtest.py -v $UFLAG $T >>OUT/$T.out 2>&1
     fi
 done

Modified: python/branches/py3k-buffer/setup.py
==============================================================================
--- python/branches/py3k-buffer/setup.py	(original)
+++ python/branches/py3k-buffer/setup.py	Fri Aug 17 20:48:09 2007
@@ -460,9 +460,6 @@
         # Fred Drake's interface to the Python parser
         exts.append( Extension('parser', ['parsermodule.c']) )
 
-        # cStringIO
-        exts.append( Extension('cStringIO', ['cStringIO.c']) )
-
         # Memory-mapped files (also works on Win32).
         if platform not in ['atheos', 'mac']:
             exts.append( Extension('mmap', ['mmapmodule.c']) )
@@ -1074,24 +1071,12 @@
         exts.append(Extension('_fileio', ['_fileio.c']))
 
         # Platform-specific libraries
-        if platform == 'linux2':
-            # Linux-specific modules
-            exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
-        else:
-            missing.append('linuxaudiodev')
-
         if platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
                         'freebsd7'):
             exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
         else:
             missing.append('ossaudiodev')
 
-        if platform == 'sunos5':
-            # SunOS specific modules
-            exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
-        else:
-            missing.append('sunaudiodev')
-
         if platform == 'darwin' and ("--disable-toolbox-glue" not in
                 sysconfig.get_config_var("CONFIG_ARGS")):
 


More information about the Python-3000-checkins mailing list