[Python-checkins] r63930 - in python/branches/okkoto-sizeof: Demo/pdist/cmptree.py Demo/pdist/server.py Demo/turtle Doc/Makefile Doc/README.txt Doc/c-api/concrete.rst Doc/c-api/file.rst Doc/c-api/string.rst Doc/c-api/type.rst Doc/glossary.rst Doc/includes/noddy2.c Doc/includes/noddy3.c Doc/includes/noddy4.c Doc/includes/run-func.c Doc/library/_winreg.rst Doc/library/anydbm.rst Doc/library/basehttpserver.rst Doc/library/bsddb.rst Doc/library/calendar.rst Doc/library/cgihttpserver.rst Doc/library/cmd.rst Doc/library/codecs.rst Doc/library/collections.rst Doc/library/commands.rst Doc/library/configparser.rst Doc/library/cookie.rst Doc/library/cookielib.rst Doc/library/copy.rst Doc/library/copyreg.rst Doc/library/dbhash.rst Doc/library/dbm.rst Doc/library/docxmlrpcserver.rst Doc/library/dumbdbm.rst Doc/library/dummy_thread.rst Doc/library/easydialogs.rst Doc/library/ftplib.rst Doc/library/future_builtins.rst Doc/library/gdbm.rst Doc/library/htmllib.rst Doc/library/htmlparser.rst Doc/library/httplib.rst Doc/library/idle.rst Doc/library/logging.rst Doc/library/math.rst Doc/library/msilib.rst Doc/library/os.rst Doc/library/persistence.rst Doc/library/pickle.rst Doc/library/poplib.rst Doc/library/queue.rst Doc/library/re.rst Doc/library/reprlib.rst Doc/library/scrolledtext.rst Doc/library/sgmllib.rst Doc/library/shlex.rst Doc/library/shutil.rst Doc/library/simplehttpserver.rst Doc/library/simplexmlrpcserver.rst Doc/library/smtplib.rst Doc/library/socket.rst Doc/library/socketserver.rst Doc/library/stdtypes.rst Doc/library/string.rst Doc/library/struct.rst Doc/library/sys.rst Doc/library/tarfile.rst Doc/library/telnetlib.rst Doc/library/test.rst Doc/library/thread.rst Doc/library/threading.rst Doc/library/tix.rst Doc/library/tkinter.rst Doc/library/turtle.rst Doc/library/urllib2.rst Doc/library/userdict.rst Doc/library/whichdb.rst Doc/library/xmlrpclib.rst Doc/library/zipfile.rst Doc/reference/expressions.rst Doc/reference/simple_stmts.rst Doc/tools/sphinxext/pyspecific.py Doc/tutorial/controlflow.rst Doc/tutorial/datastructures.rst Doc/tutorial/errors.rst Doc/tutorial/floatingpoint.rst Doc/tutorial/inputoutput.rst Doc/tutorial/interpreter.rst Doc/tutorial/introduction.rst Doc/tutorial/stdlib2.rst Doc/using/cmdline.rst Doc/whatsnew/2.6.rst Include/Python.h Include/bytesobject.h Include/fileobject.h Include/floatobject.h Include/formatter_string.h Include/formatter_unicode.h Include/intobject.h Include/longobject.h Include/object.h Include/py_curses.h Include/pyerrors.h Include/pyport.h Include/pythonrun.h Include/stringobject.h Include/unicodeobject.h Include/warnings.h Lib/BaseHTTPServer.py Lib/SimpleXMLRPCServer.py Lib/UserString.py Lib/bdb.py Lib/bsddb/__init__.py Lib/bsddb/db.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_all.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_replication.py Lib/bsddb/test/test_sequence.py Lib/collections.py Lib/commands.py Lib/configparser.py Lib/copy.py Lib/copyreg.py Lib/ctypes/test/__init__.py Lib/ctypes/test/runtests.py Lib/ctypes/test/test_loading.py Lib/ctypes/test/test_pointers.py Lib/ctypes/util.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/upload.py Lib/distutils/command/wininst-6.0.exe Lib/distutils/command/wininst-7.1.exe Lib/distutils/command/wininst-9.0-amd64.exe Lib/distutils/command/wininst-9.0.exe Lib/distutils/config.py Lib/distutils/dist.py Lib/ftplib.py Lib/gzip.py Lib/heapq.py Lib/htmllib.py Lib/httplib.py Lib/idlelib/Debugger.py Lib/idlelib/ObjectBrowser.py Lib/idlelib/configHandler.py Lib/idlelib/rpc.py Lib/idlelib/run.py Lib/lib-old/ConfigParser.py Lib/lib-old/Queue.py Lib/lib-old/SocketServer.py Lib/lib-old/copy_reg.py Lib/lib-old/repr.py Lib/lib-tk/Dialog.py Lib/lib-tk/FileDialog.py Lib/lib-tk/FixTk.py Lib/lib-tk/ScrolledText.py Lib/lib-tk/SimpleDialog.py Lib/lib-tk/Tix.py Lib/lib-tk/Tkconstants.py Lib/lib-tk/Tkdnd.py Lib/lib-tk/Tkinter.py Lib/lib-tk/tkColorChooser.py Lib/lib-tk/tkCommonDialog.py Lib/lib-tk/tkFileDialog.py Lib/lib-tk/tkFont.py Lib/lib-tk/tkMessageBox.py Lib/lib-tk/tkSimpleDialog.py Lib/lib-tk/turtle.py Lib/lib2to3 Lib/lib2to3/fixes/fix_imports.py Lib/lib2to3/pgen2/driver.py Lib/lib2to3/tests/test_fixers.py Lib/locale.py Lib/logging/config.py Lib/logging/handlers.py Lib/os.py Lib/pdb.py Lib/pickle.py Lib/platform.py Lib/poplib.py Lib/pydoc.py Lib/queue.py Lib/re.py Lib/reprlib.py Lib/sgmllib.py Lib/smtplib.py Lib/socket.py Lib/socketserver.py Lib/sqlite3/test/dbapi.py Lib/sre_parse.py Lib/subprocess.py Lib/tarfile.py Lib/telnetlib.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/test___all__.py Lib/test/test_bsddb.py Lib/test/test_bsddb3.py Lib/test/test_cfgparser.py Lib/test/test_collections.py Lib/test/test_copy.py Lib/test/test_copyreg.py Lib/test/test_datetime.py Lib/test/test_descrtut.py Lib/test/test_dummy_thread.py Lib/test/test_enumerate.py Lib/test/test_ftplib.py Lib/test/test_generators.py Lib/test/test_genexps.py Lib/test/test_gzip.py Lib/test/test_htmllib.py Lib/test/test_httplib.py Lib/test/test_ioctl.py Lib/test/test_json.py Lib/test/test_logging.py Lib/test/test_math.py Lib/test/test_minidom.py Lib/test/test_mutex.py Lib/test/test_opcodes.py Lib/test/test_platform.py Lib/test/test_poplib.py Lib/test/test_py3kwarn.py Lib/test/test_pyclbr.py Lib/test/test_pydoc.py Lib/test/test_queue.py Lib/test/test_reprlib.py Lib/test/test_sgmllib.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_socketserver.py Lib/test/test_subprocess.py Lib/test/test_support.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_telnetlib.py Lib/test/test_threading.py Lib/test/test_unicodedata.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urllib2net.py Lib/test/test_userstring.py Lib/test/test_weakref.py Lib/test/test_wsgiref.py Lib/test/test_zipfile.py Lib/threading.py Lib/urllib.py Lib/urllib2.py Lib/xml/dom/minidom.py Lib/xmlrpclib.py Lib/zipfile.py Mac/Modules/MacOS.c Mac/Modules/Nav.c Mac/Modules/ae/_AEmodule.c Mac/Modules/cf/_CFmodule.c Mac/Modules/cf/pycfbridge.c Mac/Modules/file/_Filemodule.c Mac/Modules/gestaltmodule.c Mac/Modules/qd/_Qdmodule.c Mac/Modules/qdoffs/_Qdoffsmodule.c Mac/Modules/res/_Resmodule.c Mac/Modules/scrap/_Scrapmodule.c Mac/Modules/snd/_Sndihooks.c Mac/Modules/win/_Winmodule.c Makefile.pre.in Misc/ACKS Misc/NEWS Misc/build.sh Misc/cheatsheet Misc/developers.txt Modules/_bsddb.c Modules/_bytesio.c Modules/_codecsmodule.c Modules/_collectionsmodule.c Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/libffi/configure Modules/_ctypes/libffi/configure.ac Modules/_ctypes/libffi/fficonfig.py.in Modules/_ctypes/malloc_closure.c Modules/_curses_panel.c Modules/_cursesmodule.c Modules/_elementtree.c Modules/_fileio.c Modules/_hashopenssl.c Modules/_heapqmodule.c Modules/_hotshot.c Modules/_json.c Modules/_localemodule.c Modules/_lsprof.c Modules/_sqlite/cache.c Modules/_sqlite/connection.c Modules/_sqlite/connection.h Modules/_sqlite/cursor.c Modules/_sqlite/cursor.h Modules/_sqlite/module.c Modules/_sqlite/row.c Modules/_sqlite/statement.c Modules/_sre.c Modules/_ssl.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/almodule.c Modules/arraymodule.c Modules/audioop.c Modules/binascii.c Modules/bsddb.h Modules/bsddbmodule.c Modules/bz2module.c Modules/cPickle.c Modules/cStringIO.c Modules/cdmodule.c Modules/cgensupport.c Modules/cjkcodecs/cjkcodecs.h Modules/cjkcodecs/multibytecodec.c Modules/clmodule.c Modules/cmathmodule.c Modules/datetimemodule.c Modules/dbmmodule.c Modules/dlmodule.c Modules/errnomodule.c Modules/fcntlmodule.c Modules/flmodule.c Modules/fmmodule.c Modules/gcmodule.c Modules/gdbmmodule.c Modules/glmodule.c Modules/grpmodule.c Modules/imageop.c Modules/imgfile.c Modules/itertoolsmodule.c Modules/linuxaudiodev.c Modules/main.c Modules/mathmodule.c Modules/md5module.c Modules/mmapmodule.c Modules/nismodule.c Modules/operator.c Modules/ossaudiodev.c Modules/parsermodule.c Modules/posixmodule.c Modules/pwdmodule.c Modules/pyexpat.c Modules/readline.c Modules/selectmodule.c Modules/sha256module.c Modules/sha512module.c Modules/shamodule.c Modules/socketmodule.c Modules/spwdmodule.c Modules/stropmodule.c Modules/sunaudiodev.c Modules/svmodule.c Modules/syslogmodule.c Modules/termios.c Modules/threadmodule.c Modules/timemodule.c Modules/unicodedata.c Modules/zipimport.c Modules/zlibmodule.c Objects/abstract.c Objects/boolobject.c Objects/bufferobject.c Objects/bytes_methods.c Objects/bytesobject.c Objects/cellobject.c Objects/classobject.c Objects/codeobject.c Objects/complexobject.c Objects/descrobject.c Objects/dictobject.c Objects/enumobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/funcobject.c Objects/genobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/moduleobject.c Objects/object.c Objects/rangeobject.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/formatter.h Objects/stringlib/string_format.h Objects/stringlib/stringdefs.h Objects/stringobject.c Objects/structseq.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c Objects/weakrefobject.c PC/VC6/pythoncore.dsp PC/VS7.1/pythoncore.vcproj PC/VS8.0/_bsddb.vcproj PC/VS8.0/_elementtree.vcproj PC/VS8.0/_sqlite3.vcproj PC/VS8.0/_ssl.vcproj PC/VS8.0/_tkinter.vcproj PC/VS8.0/bdist_wininst.vcproj PC/VS8.0/debug.vsprops PC/VS8.0/make_versioninfo.vcproj PC/VS8.0/pcbuild.sln PC/VS8.0/pyd.vsprops PC/VS8.0/pyd_d.vsprops PC/VS8.0/pyproject.vsprops PC/VS8.0/python.vcproj PC/VS8.0/pythoncore.vcproj PC/VS8.0/release.vsprops PC/VS8.0/x64.vsprops PC/_msi.c PC/_subprocess.c PC/_winreg.c PC/bdist_wininst/install.c PC/msvcrtmodule.c PC/winsound.c PCbuild/pyproject.vsprops PCbuild/pythoncore.vcproj Parser/asdl_c.py Parser/tokenizer.c Python/Python-ast.c Python/_warnings.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/codecs.c Python/compile.c Python/errors.c Python/formatter_string.c Python/formatter_unicode.c Python/future.c Python/getargs.c Python/import.c Python/mactoolboxglue.c Python/marshal.c Python/modsupport.c Python/mysnprintf.c Python/peephole.c Python/pystrtod.c Python/pythonrun.c Python/structmember.c Python/symtable.c Python/sysmodule.c Python/traceback.c README RISCOS/Modules/drawfmodule.c RISCOS/Modules/riscosmodule.c RISCOS/Modules/swimodule.c Tools/README Tools/bgen/README Tools/msi/msi.py Tools/msi/msilib.py Tools/webchecker/wsgui.py configure configure.in pyconfig.h.in setup.py

robert.schuppenies python-checkins at python.org
Wed Jun 4 11:24:42 CEST 2008


Author: robert.schuppenies
Date: Wed Jun  4 11:24:23 2008
New Revision: 63930

Log:
merged from trunk to revision 63929.


Added:
   python/branches/okkoto-sizeof/Demo/turtle/
      - copied from r63929, /python/trunk/Demo/turtle/
   python/branches/okkoto-sizeof/Doc/library/scrolledtext.rst
      - copied unchanged from r63929, /python/trunk/Doc/library/scrolledtext.rst
   python/branches/okkoto-sizeof/Doc/library/tix.rst
      - copied unchanged from r63929, /python/trunk/Doc/library/tix.rst
   python/branches/okkoto-sizeof/Doc/library/turtle.rst
      - copied unchanged from r63929, /python/trunk/Doc/library/turtle.rst
   python/branches/okkoto-sizeof/Include/bytesobject.h
      - copied unchanged from r63929, /python/trunk/Include/bytesobject.h
   python/branches/okkoto-sizeof/Include/stringobject.h
      - copied unchanged from r63929, /python/trunk/Include/stringobject.h
   python/branches/okkoto-sizeof/Lib/lib-tk/FileDialog.py
      - copied unchanged from r63929, /python/trunk/Lib/lib-tk/FileDialog.py
   python/branches/okkoto-sizeof/Lib/lib-tk/SimpleDialog.py
      - copied unchanged from r63929, /python/trunk/Lib/lib-tk/SimpleDialog.py
   python/branches/okkoto-sizeof/Lib/lib-tk/tkFileDialog.py
      - copied unchanged from r63929, /python/trunk/Lib/lib-tk/tkFileDialog.py
   python/branches/okkoto-sizeof/Lib/lib-tk/tkSimpleDialog.py
      - copied unchanged from r63929, /python/trunk/Lib/lib-tk/tkSimpleDialog.py
   python/branches/okkoto-sizeof/Objects/bytesobject.c
      - copied unchanged from r63929, /python/trunk/Objects/bytesobject.c
Removed:
   python/branches/okkoto-sizeof/Doc/library/copyreg.rst
   python/branches/okkoto-sizeof/Doc/library/reprlib.rst
   python/branches/okkoto-sizeof/Include/formatter_string.h
   python/branches/okkoto-sizeof/Include/formatter_unicode.h
   python/branches/okkoto-sizeof/Lib/configparser.py
   python/branches/okkoto-sizeof/Lib/copyreg.py
   python/branches/okkoto-sizeof/Lib/lib-old/ConfigParser.py
   python/branches/okkoto-sizeof/Lib/lib-old/Queue.py
   python/branches/okkoto-sizeof/Lib/lib-old/SocketServer.py
   python/branches/okkoto-sizeof/Lib/lib-old/copy_reg.py
   python/branches/okkoto-sizeof/Lib/lib-old/repr.py
   python/branches/okkoto-sizeof/Lib/queue.py
   python/branches/okkoto-sizeof/Lib/reprlib.py
   python/branches/okkoto-sizeof/Lib/socketserver.py
   python/branches/okkoto-sizeof/Lib/test/test_copyreg.py
   python/branches/okkoto-sizeof/Lib/test/test_reprlib.py
   python/branches/okkoto-sizeof/Objects/stringobject.c
Modified:
   python/branches/okkoto-sizeof/Demo/pdist/cmptree.py
   python/branches/okkoto-sizeof/Demo/pdist/server.py
   python/branches/okkoto-sizeof/Doc/Makefile
   python/branches/okkoto-sizeof/Doc/README.txt
   python/branches/okkoto-sizeof/Doc/c-api/concrete.rst
   python/branches/okkoto-sizeof/Doc/c-api/file.rst
   python/branches/okkoto-sizeof/Doc/c-api/string.rst
   python/branches/okkoto-sizeof/Doc/c-api/type.rst
   python/branches/okkoto-sizeof/Doc/glossary.rst
   python/branches/okkoto-sizeof/Doc/includes/noddy2.c
   python/branches/okkoto-sizeof/Doc/includes/noddy3.c
   python/branches/okkoto-sizeof/Doc/includes/noddy4.c
   python/branches/okkoto-sizeof/Doc/includes/run-func.c
   python/branches/okkoto-sizeof/Doc/library/_winreg.rst
   python/branches/okkoto-sizeof/Doc/library/anydbm.rst
   python/branches/okkoto-sizeof/Doc/library/basehttpserver.rst
   python/branches/okkoto-sizeof/Doc/library/bsddb.rst
   python/branches/okkoto-sizeof/Doc/library/calendar.rst
   python/branches/okkoto-sizeof/Doc/library/cgihttpserver.rst
   python/branches/okkoto-sizeof/Doc/library/cmd.rst
   python/branches/okkoto-sizeof/Doc/library/codecs.rst
   python/branches/okkoto-sizeof/Doc/library/collections.rst
   python/branches/okkoto-sizeof/Doc/library/commands.rst
   python/branches/okkoto-sizeof/Doc/library/configparser.rst
   python/branches/okkoto-sizeof/Doc/library/cookie.rst
   python/branches/okkoto-sizeof/Doc/library/cookielib.rst
   python/branches/okkoto-sizeof/Doc/library/copy.rst
   python/branches/okkoto-sizeof/Doc/library/dbhash.rst
   python/branches/okkoto-sizeof/Doc/library/dbm.rst
   python/branches/okkoto-sizeof/Doc/library/docxmlrpcserver.rst
   python/branches/okkoto-sizeof/Doc/library/dumbdbm.rst
   python/branches/okkoto-sizeof/Doc/library/dummy_thread.rst
   python/branches/okkoto-sizeof/Doc/library/easydialogs.rst
   python/branches/okkoto-sizeof/Doc/library/ftplib.rst
   python/branches/okkoto-sizeof/Doc/library/future_builtins.rst
   python/branches/okkoto-sizeof/Doc/library/gdbm.rst
   python/branches/okkoto-sizeof/Doc/library/htmllib.rst
   python/branches/okkoto-sizeof/Doc/library/htmlparser.rst
   python/branches/okkoto-sizeof/Doc/library/httplib.rst
   python/branches/okkoto-sizeof/Doc/library/idle.rst
   python/branches/okkoto-sizeof/Doc/library/logging.rst
   python/branches/okkoto-sizeof/Doc/library/math.rst
   python/branches/okkoto-sizeof/Doc/library/msilib.rst
   python/branches/okkoto-sizeof/Doc/library/os.rst
   python/branches/okkoto-sizeof/Doc/library/persistence.rst
   python/branches/okkoto-sizeof/Doc/library/pickle.rst
   python/branches/okkoto-sizeof/Doc/library/poplib.rst
   python/branches/okkoto-sizeof/Doc/library/queue.rst
   python/branches/okkoto-sizeof/Doc/library/re.rst
   python/branches/okkoto-sizeof/Doc/library/sgmllib.rst
   python/branches/okkoto-sizeof/Doc/library/shlex.rst
   python/branches/okkoto-sizeof/Doc/library/shutil.rst
   python/branches/okkoto-sizeof/Doc/library/simplehttpserver.rst
   python/branches/okkoto-sizeof/Doc/library/simplexmlrpcserver.rst
   python/branches/okkoto-sizeof/Doc/library/smtplib.rst
   python/branches/okkoto-sizeof/Doc/library/socket.rst
   python/branches/okkoto-sizeof/Doc/library/socketserver.rst
   python/branches/okkoto-sizeof/Doc/library/stdtypes.rst
   python/branches/okkoto-sizeof/Doc/library/string.rst
   python/branches/okkoto-sizeof/Doc/library/struct.rst
   python/branches/okkoto-sizeof/Doc/library/sys.rst
   python/branches/okkoto-sizeof/Doc/library/tarfile.rst
   python/branches/okkoto-sizeof/Doc/library/telnetlib.rst
   python/branches/okkoto-sizeof/Doc/library/test.rst
   python/branches/okkoto-sizeof/Doc/library/thread.rst
   python/branches/okkoto-sizeof/Doc/library/threading.rst
   python/branches/okkoto-sizeof/Doc/library/tkinter.rst
   python/branches/okkoto-sizeof/Doc/library/urllib2.rst
   python/branches/okkoto-sizeof/Doc/library/userdict.rst
   python/branches/okkoto-sizeof/Doc/library/whichdb.rst
   python/branches/okkoto-sizeof/Doc/library/xmlrpclib.rst
   python/branches/okkoto-sizeof/Doc/library/zipfile.rst
   python/branches/okkoto-sizeof/Doc/reference/expressions.rst
   python/branches/okkoto-sizeof/Doc/reference/simple_stmts.rst
   python/branches/okkoto-sizeof/Doc/tools/sphinxext/pyspecific.py
   python/branches/okkoto-sizeof/Doc/tutorial/controlflow.rst
   python/branches/okkoto-sizeof/Doc/tutorial/datastructures.rst
   python/branches/okkoto-sizeof/Doc/tutorial/errors.rst
   python/branches/okkoto-sizeof/Doc/tutorial/floatingpoint.rst
   python/branches/okkoto-sizeof/Doc/tutorial/inputoutput.rst
   python/branches/okkoto-sizeof/Doc/tutorial/interpreter.rst
   python/branches/okkoto-sizeof/Doc/tutorial/introduction.rst
   python/branches/okkoto-sizeof/Doc/tutorial/stdlib2.rst
   python/branches/okkoto-sizeof/Doc/using/cmdline.rst
   python/branches/okkoto-sizeof/Doc/whatsnew/2.6.rst
   python/branches/okkoto-sizeof/Include/Python.h
   python/branches/okkoto-sizeof/Include/fileobject.h
   python/branches/okkoto-sizeof/Include/floatobject.h
   python/branches/okkoto-sizeof/Include/intobject.h
   python/branches/okkoto-sizeof/Include/longobject.h
   python/branches/okkoto-sizeof/Include/object.h
   python/branches/okkoto-sizeof/Include/py_curses.h
   python/branches/okkoto-sizeof/Include/pyerrors.h
   python/branches/okkoto-sizeof/Include/pyport.h
   python/branches/okkoto-sizeof/Include/pythonrun.h
   python/branches/okkoto-sizeof/Include/unicodeobject.h
   python/branches/okkoto-sizeof/Include/warnings.h
   python/branches/okkoto-sizeof/Lib/BaseHTTPServer.py
   python/branches/okkoto-sizeof/Lib/SimpleXMLRPCServer.py
   python/branches/okkoto-sizeof/Lib/UserString.py
   python/branches/okkoto-sizeof/Lib/bdb.py
   python/branches/okkoto-sizeof/Lib/bsddb/__init__.py
   python/branches/okkoto-sizeof/Lib/bsddb/db.py
   python/branches/okkoto-sizeof/Lib/bsddb/dbtables.py
   python/branches/okkoto-sizeof/Lib/bsddb/test/test_all.py
   python/branches/okkoto-sizeof/Lib/bsddb/test/test_lock.py
   python/branches/okkoto-sizeof/Lib/bsddb/test/test_replication.py
   python/branches/okkoto-sizeof/Lib/bsddb/test/test_sequence.py
   python/branches/okkoto-sizeof/Lib/collections.py
   python/branches/okkoto-sizeof/Lib/commands.py
   python/branches/okkoto-sizeof/Lib/copy.py
   python/branches/okkoto-sizeof/Lib/ctypes/test/__init__.py
   python/branches/okkoto-sizeof/Lib/ctypes/test/runtests.py
   python/branches/okkoto-sizeof/Lib/ctypes/test/test_loading.py
   python/branches/okkoto-sizeof/Lib/ctypes/test/test_pointers.py
   python/branches/okkoto-sizeof/Lib/ctypes/util.py
   python/branches/okkoto-sizeof/Lib/distutils/command/bdist_wininst.py
   python/branches/okkoto-sizeof/Lib/distutils/command/upload.py
   python/branches/okkoto-sizeof/Lib/distutils/command/wininst-6.0.exe
   python/branches/okkoto-sizeof/Lib/distutils/command/wininst-7.1.exe
   python/branches/okkoto-sizeof/Lib/distutils/command/wininst-9.0-amd64.exe
   python/branches/okkoto-sizeof/Lib/distutils/command/wininst-9.0.exe
   python/branches/okkoto-sizeof/Lib/distutils/config.py
   python/branches/okkoto-sizeof/Lib/distutils/dist.py
   python/branches/okkoto-sizeof/Lib/ftplib.py
   python/branches/okkoto-sizeof/Lib/gzip.py
   python/branches/okkoto-sizeof/Lib/heapq.py
   python/branches/okkoto-sizeof/Lib/htmllib.py
   python/branches/okkoto-sizeof/Lib/httplib.py
   python/branches/okkoto-sizeof/Lib/idlelib/Debugger.py
   python/branches/okkoto-sizeof/Lib/idlelib/ObjectBrowser.py
   python/branches/okkoto-sizeof/Lib/idlelib/configHandler.py
   python/branches/okkoto-sizeof/Lib/idlelib/rpc.py
   python/branches/okkoto-sizeof/Lib/idlelib/run.py
   python/branches/okkoto-sizeof/Lib/lib-tk/Dialog.py   (contents, props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/FixTk.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/ScrolledText.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/Tix.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/Tkconstants.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/Tkdnd.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/Tkinter.py   (contents, props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/tkColorChooser.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/tkCommonDialog.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/tkFont.py   (contents, props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/tkMessageBox.py   (props changed)
   python/branches/okkoto-sizeof/Lib/lib-tk/turtle.py   (contents, props changed)
   python/branches/okkoto-sizeof/Lib/lib2to3/   (props changed)
   python/branches/okkoto-sizeof/Lib/lib2to3/fixes/fix_imports.py
   python/branches/okkoto-sizeof/Lib/lib2to3/pgen2/driver.py
   python/branches/okkoto-sizeof/Lib/lib2to3/tests/test_fixers.py
   python/branches/okkoto-sizeof/Lib/locale.py
   python/branches/okkoto-sizeof/Lib/logging/config.py
   python/branches/okkoto-sizeof/Lib/logging/handlers.py
   python/branches/okkoto-sizeof/Lib/os.py
   python/branches/okkoto-sizeof/Lib/pdb.py
   python/branches/okkoto-sizeof/Lib/pickle.py
   python/branches/okkoto-sizeof/Lib/platform.py
   python/branches/okkoto-sizeof/Lib/poplib.py
   python/branches/okkoto-sizeof/Lib/pydoc.py
   python/branches/okkoto-sizeof/Lib/re.py
   python/branches/okkoto-sizeof/Lib/sgmllib.py
   python/branches/okkoto-sizeof/Lib/smtplib.py
   python/branches/okkoto-sizeof/Lib/socket.py
   python/branches/okkoto-sizeof/Lib/sqlite3/test/dbapi.py
   python/branches/okkoto-sizeof/Lib/sre_parse.py
   python/branches/okkoto-sizeof/Lib/subprocess.py
   python/branches/okkoto-sizeof/Lib/tarfile.py
   python/branches/okkoto-sizeof/Lib/telnetlib.py
   python/branches/okkoto-sizeof/Lib/test/pickletester.py
   python/branches/okkoto-sizeof/Lib/test/regrtest.py
   python/branches/okkoto-sizeof/Lib/test/test___all__.py
   python/branches/okkoto-sizeof/Lib/test/test_bsddb.py
   python/branches/okkoto-sizeof/Lib/test/test_bsddb3.py
   python/branches/okkoto-sizeof/Lib/test/test_cfgparser.py
   python/branches/okkoto-sizeof/Lib/test/test_collections.py
   python/branches/okkoto-sizeof/Lib/test/test_copy.py
   python/branches/okkoto-sizeof/Lib/test/test_datetime.py
   python/branches/okkoto-sizeof/Lib/test/test_descrtut.py
   python/branches/okkoto-sizeof/Lib/test/test_dummy_thread.py
   python/branches/okkoto-sizeof/Lib/test/test_enumerate.py
   python/branches/okkoto-sizeof/Lib/test/test_ftplib.py
   python/branches/okkoto-sizeof/Lib/test/test_generators.py
   python/branches/okkoto-sizeof/Lib/test/test_genexps.py
   python/branches/okkoto-sizeof/Lib/test/test_gzip.py
   python/branches/okkoto-sizeof/Lib/test/test_htmllib.py
   python/branches/okkoto-sizeof/Lib/test/test_httplib.py
   python/branches/okkoto-sizeof/Lib/test/test_ioctl.py
   python/branches/okkoto-sizeof/Lib/test/test_json.py
   python/branches/okkoto-sizeof/Lib/test/test_logging.py
   python/branches/okkoto-sizeof/Lib/test/test_math.py
   python/branches/okkoto-sizeof/Lib/test/test_minidom.py
   python/branches/okkoto-sizeof/Lib/test/test_mutex.py
   python/branches/okkoto-sizeof/Lib/test/test_opcodes.py
   python/branches/okkoto-sizeof/Lib/test/test_platform.py
   python/branches/okkoto-sizeof/Lib/test/test_poplib.py
   python/branches/okkoto-sizeof/Lib/test/test_py3kwarn.py
   python/branches/okkoto-sizeof/Lib/test/test_pyclbr.py
   python/branches/okkoto-sizeof/Lib/test/test_pydoc.py
   python/branches/okkoto-sizeof/Lib/test/test_queue.py
   python/branches/okkoto-sizeof/Lib/test/test_sgmllib.py
   python/branches/okkoto-sizeof/Lib/test/test_smtplib.py
   python/branches/okkoto-sizeof/Lib/test/test_socket.py
   python/branches/okkoto-sizeof/Lib/test/test_socketserver.py
   python/branches/okkoto-sizeof/Lib/test/test_subprocess.py
   python/branches/okkoto-sizeof/Lib/test/test_support.py
   python/branches/okkoto-sizeof/Lib/test/test_sys.py
   python/branches/okkoto-sizeof/Lib/test/test_tarfile.py
   python/branches/okkoto-sizeof/Lib/test/test_telnetlib.py
   python/branches/okkoto-sizeof/Lib/test/test_threading.py
   python/branches/okkoto-sizeof/Lib/test/test_unicodedata.py
   python/branches/okkoto-sizeof/Lib/test/test_urllib.py
   python/branches/okkoto-sizeof/Lib/test/test_urllib2.py
   python/branches/okkoto-sizeof/Lib/test/test_urllib2net.py
   python/branches/okkoto-sizeof/Lib/test/test_userstring.py
   python/branches/okkoto-sizeof/Lib/test/test_weakref.py
   python/branches/okkoto-sizeof/Lib/test/test_wsgiref.py
   python/branches/okkoto-sizeof/Lib/test/test_zipfile.py
   python/branches/okkoto-sizeof/Lib/threading.py
   python/branches/okkoto-sizeof/Lib/urllib.py
   python/branches/okkoto-sizeof/Lib/urllib2.py
   python/branches/okkoto-sizeof/Lib/xml/dom/minidom.py
   python/branches/okkoto-sizeof/Lib/xmlrpclib.py
   python/branches/okkoto-sizeof/Lib/zipfile.py
   python/branches/okkoto-sizeof/Mac/Modules/MacOS.c
   python/branches/okkoto-sizeof/Mac/Modules/Nav.c
   python/branches/okkoto-sizeof/Mac/Modules/ae/_AEmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/cf/_CFmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/cf/pycfbridge.c
   python/branches/okkoto-sizeof/Mac/Modules/file/_Filemodule.c
   python/branches/okkoto-sizeof/Mac/Modules/gestaltmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/qd/_Qdmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/qdoffs/_Qdoffsmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/res/_Resmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/scrap/_Scrapmodule.c
   python/branches/okkoto-sizeof/Mac/Modules/snd/_Sndihooks.c
   python/branches/okkoto-sizeof/Mac/Modules/win/_Winmodule.c
   python/branches/okkoto-sizeof/Makefile.pre.in
   python/branches/okkoto-sizeof/Misc/ACKS
   python/branches/okkoto-sizeof/Misc/NEWS
   python/branches/okkoto-sizeof/Misc/build.sh
   python/branches/okkoto-sizeof/Misc/cheatsheet
   python/branches/okkoto-sizeof/Misc/developers.txt
   python/branches/okkoto-sizeof/Modules/_bsddb.c
   python/branches/okkoto-sizeof/Modules/_bytesio.c
   python/branches/okkoto-sizeof/Modules/_codecsmodule.c
   python/branches/okkoto-sizeof/Modules/_collectionsmodule.c
   python/branches/okkoto-sizeof/Modules/_csv.c
   python/branches/okkoto-sizeof/Modules/_ctypes/_ctypes.c
   python/branches/okkoto-sizeof/Modules/_ctypes/callbacks.c
   python/branches/okkoto-sizeof/Modules/_ctypes/callproc.c
   python/branches/okkoto-sizeof/Modules/_ctypes/cfield.c
   python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure
   python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure.ac
   python/branches/okkoto-sizeof/Modules/_ctypes/libffi/fficonfig.py.in
   python/branches/okkoto-sizeof/Modules/_ctypes/malloc_closure.c
   python/branches/okkoto-sizeof/Modules/_curses_panel.c
   python/branches/okkoto-sizeof/Modules/_cursesmodule.c
   python/branches/okkoto-sizeof/Modules/_elementtree.c
   python/branches/okkoto-sizeof/Modules/_fileio.c
   python/branches/okkoto-sizeof/Modules/_hashopenssl.c
   python/branches/okkoto-sizeof/Modules/_heapqmodule.c
   python/branches/okkoto-sizeof/Modules/_hotshot.c
   python/branches/okkoto-sizeof/Modules/_json.c
   python/branches/okkoto-sizeof/Modules/_localemodule.c
   python/branches/okkoto-sizeof/Modules/_lsprof.c
   python/branches/okkoto-sizeof/Modules/_sqlite/cache.c
   python/branches/okkoto-sizeof/Modules/_sqlite/connection.c
   python/branches/okkoto-sizeof/Modules/_sqlite/connection.h
   python/branches/okkoto-sizeof/Modules/_sqlite/cursor.c
   python/branches/okkoto-sizeof/Modules/_sqlite/cursor.h
   python/branches/okkoto-sizeof/Modules/_sqlite/module.c
   python/branches/okkoto-sizeof/Modules/_sqlite/row.c
   python/branches/okkoto-sizeof/Modules/_sqlite/statement.c
   python/branches/okkoto-sizeof/Modules/_sre.c
   python/branches/okkoto-sizeof/Modules/_ssl.c
   python/branches/okkoto-sizeof/Modules/_struct.c
   python/branches/okkoto-sizeof/Modules/_testcapimodule.c
   python/branches/okkoto-sizeof/Modules/_tkinter.c
   python/branches/okkoto-sizeof/Modules/almodule.c
   python/branches/okkoto-sizeof/Modules/arraymodule.c
   python/branches/okkoto-sizeof/Modules/audioop.c
   python/branches/okkoto-sizeof/Modules/binascii.c
   python/branches/okkoto-sizeof/Modules/bsddb.h
   python/branches/okkoto-sizeof/Modules/bsddbmodule.c
   python/branches/okkoto-sizeof/Modules/bz2module.c
   python/branches/okkoto-sizeof/Modules/cPickle.c
   python/branches/okkoto-sizeof/Modules/cStringIO.c
   python/branches/okkoto-sizeof/Modules/cdmodule.c
   python/branches/okkoto-sizeof/Modules/cgensupport.c
   python/branches/okkoto-sizeof/Modules/cjkcodecs/cjkcodecs.h
   python/branches/okkoto-sizeof/Modules/cjkcodecs/multibytecodec.c
   python/branches/okkoto-sizeof/Modules/clmodule.c
   python/branches/okkoto-sizeof/Modules/cmathmodule.c
   python/branches/okkoto-sizeof/Modules/datetimemodule.c
   python/branches/okkoto-sizeof/Modules/dbmmodule.c
   python/branches/okkoto-sizeof/Modules/dlmodule.c
   python/branches/okkoto-sizeof/Modules/errnomodule.c
   python/branches/okkoto-sizeof/Modules/fcntlmodule.c
   python/branches/okkoto-sizeof/Modules/flmodule.c
   python/branches/okkoto-sizeof/Modules/fmmodule.c
   python/branches/okkoto-sizeof/Modules/gcmodule.c
   python/branches/okkoto-sizeof/Modules/gdbmmodule.c
   python/branches/okkoto-sizeof/Modules/glmodule.c
   python/branches/okkoto-sizeof/Modules/grpmodule.c
   python/branches/okkoto-sizeof/Modules/imageop.c
   python/branches/okkoto-sizeof/Modules/imgfile.c
   python/branches/okkoto-sizeof/Modules/itertoolsmodule.c
   python/branches/okkoto-sizeof/Modules/linuxaudiodev.c
   python/branches/okkoto-sizeof/Modules/main.c
   python/branches/okkoto-sizeof/Modules/mathmodule.c
   python/branches/okkoto-sizeof/Modules/md5module.c
   python/branches/okkoto-sizeof/Modules/mmapmodule.c
   python/branches/okkoto-sizeof/Modules/nismodule.c
   python/branches/okkoto-sizeof/Modules/operator.c
   python/branches/okkoto-sizeof/Modules/ossaudiodev.c
   python/branches/okkoto-sizeof/Modules/parsermodule.c
   python/branches/okkoto-sizeof/Modules/posixmodule.c
   python/branches/okkoto-sizeof/Modules/pwdmodule.c
   python/branches/okkoto-sizeof/Modules/pyexpat.c
   python/branches/okkoto-sizeof/Modules/readline.c
   python/branches/okkoto-sizeof/Modules/selectmodule.c
   python/branches/okkoto-sizeof/Modules/sha256module.c
   python/branches/okkoto-sizeof/Modules/sha512module.c
   python/branches/okkoto-sizeof/Modules/shamodule.c
   python/branches/okkoto-sizeof/Modules/socketmodule.c
   python/branches/okkoto-sizeof/Modules/spwdmodule.c
   python/branches/okkoto-sizeof/Modules/stropmodule.c
   python/branches/okkoto-sizeof/Modules/sunaudiodev.c
   python/branches/okkoto-sizeof/Modules/svmodule.c
   python/branches/okkoto-sizeof/Modules/syslogmodule.c
   python/branches/okkoto-sizeof/Modules/termios.c
   python/branches/okkoto-sizeof/Modules/threadmodule.c
   python/branches/okkoto-sizeof/Modules/timemodule.c
   python/branches/okkoto-sizeof/Modules/unicodedata.c
   python/branches/okkoto-sizeof/Modules/zipimport.c
   python/branches/okkoto-sizeof/Modules/zlibmodule.c
   python/branches/okkoto-sizeof/Objects/abstract.c
   python/branches/okkoto-sizeof/Objects/boolobject.c
   python/branches/okkoto-sizeof/Objects/bufferobject.c
   python/branches/okkoto-sizeof/Objects/bytes_methods.c
   python/branches/okkoto-sizeof/Objects/cellobject.c
   python/branches/okkoto-sizeof/Objects/classobject.c
   python/branches/okkoto-sizeof/Objects/codeobject.c
   python/branches/okkoto-sizeof/Objects/complexobject.c
   python/branches/okkoto-sizeof/Objects/descrobject.c
   python/branches/okkoto-sizeof/Objects/dictobject.c
   python/branches/okkoto-sizeof/Objects/enumobject.c
   python/branches/okkoto-sizeof/Objects/exceptions.c
   python/branches/okkoto-sizeof/Objects/fileobject.c
   python/branches/okkoto-sizeof/Objects/floatobject.c
   python/branches/okkoto-sizeof/Objects/frameobject.c
   python/branches/okkoto-sizeof/Objects/funcobject.c
   python/branches/okkoto-sizeof/Objects/genobject.c
   python/branches/okkoto-sizeof/Objects/intobject.c
   python/branches/okkoto-sizeof/Objects/listobject.c
   python/branches/okkoto-sizeof/Objects/longobject.c
   python/branches/okkoto-sizeof/Objects/methodobject.c
   python/branches/okkoto-sizeof/Objects/moduleobject.c
   python/branches/okkoto-sizeof/Objects/object.c
   python/branches/okkoto-sizeof/Objects/rangeobject.c
   python/branches/okkoto-sizeof/Objects/setobject.c
   python/branches/okkoto-sizeof/Objects/sliceobject.c
   python/branches/okkoto-sizeof/Objects/stringlib/formatter.h
   python/branches/okkoto-sizeof/Objects/stringlib/string_format.h
   python/branches/okkoto-sizeof/Objects/stringlib/stringdefs.h
   python/branches/okkoto-sizeof/Objects/structseq.c
   python/branches/okkoto-sizeof/Objects/tupleobject.c
   python/branches/okkoto-sizeof/Objects/typeobject.c
   python/branches/okkoto-sizeof/Objects/unicodeobject.c
   python/branches/okkoto-sizeof/Objects/weakrefobject.c
   python/branches/okkoto-sizeof/PC/VC6/pythoncore.dsp
   python/branches/okkoto-sizeof/PC/VS7.1/pythoncore.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/_bsddb.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/_elementtree.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/_sqlite3.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/_ssl.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/_tkinter.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/bdist_wininst.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/debug.vsprops
   python/branches/okkoto-sizeof/PC/VS8.0/make_versioninfo.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/pcbuild.sln
   python/branches/okkoto-sizeof/PC/VS8.0/pyd.vsprops
   python/branches/okkoto-sizeof/PC/VS8.0/pyd_d.vsprops
   python/branches/okkoto-sizeof/PC/VS8.0/pyproject.vsprops
   python/branches/okkoto-sizeof/PC/VS8.0/python.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/pythoncore.vcproj
   python/branches/okkoto-sizeof/PC/VS8.0/release.vsprops
   python/branches/okkoto-sizeof/PC/VS8.0/x64.vsprops
   python/branches/okkoto-sizeof/PC/_msi.c
   python/branches/okkoto-sizeof/PC/_subprocess.c
   python/branches/okkoto-sizeof/PC/_winreg.c
   python/branches/okkoto-sizeof/PC/bdist_wininst/install.c
   python/branches/okkoto-sizeof/PC/msvcrtmodule.c
   python/branches/okkoto-sizeof/PC/winsound.c
   python/branches/okkoto-sizeof/PCbuild/pyproject.vsprops
   python/branches/okkoto-sizeof/PCbuild/pythoncore.vcproj
   python/branches/okkoto-sizeof/Parser/asdl_c.py
   python/branches/okkoto-sizeof/Parser/tokenizer.c
   python/branches/okkoto-sizeof/Python/Python-ast.c
   python/branches/okkoto-sizeof/Python/_warnings.c
   python/branches/okkoto-sizeof/Python/ast.c
   python/branches/okkoto-sizeof/Python/bltinmodule.c
   python/branches/okkoto-sizeof/Python/ceval.c
   python/branches/okkoto-sizeof/Python/codecs.c
   python/branches/okkoto-sizeof/Python/compile.c
   python/branches/okkoto-sizeof/Python/errors.c
   python/branches/okkoto-sizeof/Python/formatter_string.c
   python/branches/okkoto-sizeof/Python/formatter_unicode.c
   python/branches/okkoto-sizeof/Python/future.c
   python/branches/okkoto-sizeof/Python/getargs.c
   python/branches/okkoto-sizeof/Python/import.c
   python/branches/okkoto-sizeof/Python/mactoolboxglue.c
   python/branches/okkoto-sizeof/Python/marshal.c
   python/branches/okkoto-sizeof/Python/modsupport.c
   python/branches/okkoto-sizeof/Python/mysnprintf.c
   python/branches/okkoto-sizeof/Python/peephole.c
   python/branches/okkoto-sizeof/Python/pystrtod.c
   python/branches/okkoto-sizeof/Python/pythonrun.c
   python/branches/okkoto-sizeof/Python/structmember.c
   python/branches/okkoto-sizeof/Python/symtable.c
   python/branches/okkoto-sizeof/Python/sysmodule.c
   python/branches/okkoto-sizeof/Python/traceback.c
   python/branches/okkoto-sizeof/README
   python/branches/okkoto-sizeof/RISCOS/Modules/drawfmodule.c
   python/branches/okkoto-sizeof/RISCOS/Modules/riscosmodule.c
   python/branches/okkoto-sizeof/RISCOS/Modules/swimodule.c
   python/branches/okkoto-sizeof/Tools/README
   python/branches/okkoto-sizeof/Tools/bgen/README
   python/branches/okkoto-sizeof/Tools/msi/msi.py
   python/branches/okkoto-sizeof/Tools/msi/msilib.py
   python/branches/okkoto-sizeof/Tools/webchecker/wsgui.py
   python/branches/okkoto-sizeof/configure
   python/branches/okkoto-sizeof/configure.in
   python/branches/okkoto-sizeof/pyconfig.h.in
   python/branches/okkoto-sizeof/setup.py

Modified: python/branches/okkoto-sizeof/Demo/pdist/cmptree.py
==============================================================================
--- python/branches/okkoto-sizeof/Demo/pdist/cmptree.py	(original)
+++ python/branches/okkoto-sizeof/Demo/pdist/cmptree.py	Wed Jun  4 11:24:23 2008
@@ -1,7 +1,7 @@
 """Compare local and remote dictionaries and transfer differing files -- like rdist."""
 
 import sys
-from reprlib import repr
+from repr import repr
 import FSProxy
 import time
 import os

Modified: python/branches/okkoto-sizeof/Demo/pdist/server.py
==============================================================================
--- python/branches/okkoto-sizeof/Demo/pdist/server.py	(original)
+++ python/branches/okkoto-sizeof/Demo/pdist/server.py	Wed Jun  4 11:24:23 2008
@@ -4,7 +4,7 @@
 import socket
 import pickle
 from fnmatch import fnmatch
-from reprlib import repr
+from repr import repr
 
 
 # Default verbosity (0 = silent, 1 = print connections, 2 = print requests too)

Modified: python/branches/okkoto-sizeof/Doc/Makefile
==============================================================================
--- python/branches/okkoto-sizeof/Doc/Makefile	(original)
+++ python/branches/okkoto-sizeof/Doc/Makefile	Wed Jun  4 11:24:23 2008
@@ -21,6 +21,7 @@
 	@echo "  web       to make file usable by Sphinx.web"
 	@echo "  htmlhelp  to make HTML files and a HTML help project"
 	@echo "  latex     to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+	@echo "  text      to make plain text files"
 	@echo "  changes   to make an overview over all changed/added/deprecated items"
 	@echo "  linkcheck to check all external links for integrity"
 	@echo "  coverage  to check documentation coverage for library and C API"
@@ -75,6 +76,10 @@
 	@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
 	      "run these through (pdf)latex."
 
+text: BUILDER = text
+text: build
+	@echo "Build finished; the text files are in build/text."
+
 changes: BUILDER = changes
 changes: build
 	@echo "The overview file is in build/changes."
@@ -93,6 +98,11 @@
 	@echo "Testing of doctests in the sources finished, look at the " \
 	      "results in build/doctest/output.txt"
 
+pydoc-topics: BUILDER = pydoc-topics
+pydoc-topics: build
+	@echo "Building finished; now copy build/pydoc-topics/pydoc_topics.py " \
+	      "into the Lib/ directory"
+
 clean:
 	-rm -rf build/*
 	-rm -rf tools/sphinx

Modified: python/branches/okkoto-sizeof/Doc/README.txt
==============================================================================
--- python/branches/okkoto-sizeof/Doc/README.txt	(original)
+++ python/branches/okkoto-sizeof/Doc/README.txt	Wed Jun  4 11:24:23 2008
@@ -51,6 +51,8 @@
  * "latex", which builds LaTeX source files that can be run with "pdflatex"
    to produce PDF documents.
 
+ * "text", which builds a plain text file for each source file.
+
  * "linkcheck", which checks all external references to see whether they are
    broken, redirected or malformed, and outputs this information to stdout
    as well as a plain-text (.txt) file.
@@ -62,6 +64,11 @@
  * "coverage", which builds a coverage overview for standard library modules
    and C API.
 
+ * "pydoc-topics", which builds a Python module containing a dictionary
+   with plain text documentation for the labels defined in
+   `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic
+   and keyword help.
+
 A "make update" updates the Subversion checkouts in `tools/`.
 
 

Modified: python/branches/okkoto-sizeof/Doc/c-api/concrete.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/c-api/concrete.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/c-api/concrete.rst	Wed Jun  4 11:24:23 2008
@@ -64,6 +64,7 @@
 
 .. toctree::
 
+   bytearray.rst
    string.rst
    unicode.rst
    buffer.rst

Modified: python/branches/okkoto-sizeof/Doc/c-api/file.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/c-api/file.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/c-api/file.rst	Wed Jun  4 11:24:23 2008
@@ -130,6 +130,14 @@
    .. versionadded:: 2.3
 
 
+.. cfunction:: int PyFile_SetEncodingAndErrors(PyFileObject *p, const char *enc, *errors)
+
+   Set the file's encoding for Unicode output to *enc*, and its error
+   mode to *err*. Return 1 on success and 0 on failure.
+
+   .. versionadded:: 2.6
+
+
 .. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag)
 
    .. index:: single: softspace (file attribute)

Modified: python/branches/okkoto-sizeof/Doc/c-api/string.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/c-api/string.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/c-api/string.rst	Wed Jun  4 11:24:23 2008
@@ -2,12 +2,16 @@
 
 .. _stringobjects:
 
-String Objects
---------------
+String/Bytes Objects
+--------------------
 
 These functions raise :exc:`TypeError` when expecting a string parameter and are
 called with a non-string parameter.
 
+.. note::
+   These functions have been renamed to PyBytes_* in Python 3.x. The PyBytes
+   names are also available in 2.6.
+
 .. index:: object: string
 
 
@@ -120,7 +124,7 @@
 
 .. cfunction:: PyObject* PyString_FromFormatV(const char *format, va_list vargs)
 
-   Identical to :func:`PyString_FromFormat` except that it takes exactly two
+   Identical to :cfunc:`PyString_FromFormat` except that it takes exactly two
    arguments.
 
 

Modified: python/branches/okkoto-sizeof/Doc/c-api/type.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/c-api/type.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/c-api/type.rst	Wed Jun  4 11:24:23 2008
@@ -37,7 +37,16 @@
 
 .. cfunction:: unsigned int PyType_ClearCache(void)
 
-   Clears the internal lookup cache. Return the current version tag.
+   Clear the internal lookup cache. Return the current version tag.
+
+   .. versionadded:: 2.6
+
+
+.. cfunction:: void PyType_Modified(PyTypeObject *type)
+
+   Invalidate the internal lookup cache for the type and all of its
+   subtypes.  This function must be called after any manual
+   modification of the attributes or base classes of the type.
 
    .. versionadded:: 2.6
 

Modified: python/branches/okkoto-sizeof/Doc/glossary.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/glossary.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/glossary.rst	Wed Jun  4 11:24:23 2008
@@ -16,6 +16,14 @@
       The typical Python prompt of the interactive shell when entering code for
       an indented code block.
 
+   2to3
+      A tool that tries to convert Python 2.x code to Python 3.x code by
+      handling most of the incompatibilites that can be detected by parsing the
+      source and traversing the parse tree.
+
+      2to3 is available in the standard library as :mod:`lib2to3`; a standalone
+      entry point is provided as :file:`Tools/scripts/2to3`.
+
    argument
       A value passed to a function or method, assigned to a name local to
       the body.  A function or method may have both positional arguments and
@@ -388,9 +396,10 @@
       definition), or pass several arguments as a list to a function.  See
       :term:`argument`.
 
-   Python 3000
-      Nickname for the next major Python version, 3.0 (coined long ago when the
-      release of version 3 was something in the distant future.)
+   Python 3000 
+      Nickname for the next major Python version, 3.0 (coined long ago
+      when the release of version 3 was something in the distant future.)  This
+      is also abbreviated "Py3k".
 
    Pythonic
       An idea or piece of code which closely follows the most common idioms of

Modified: python/branches/okkoto-sizeof/Doc/includes/noddy2.c
==============================================================================
--- python/branches/okkoto-sizeof/Doc/includes/noddy2.c	(original)
+++ python/branches/okkoto-sizeof/Doc/includes/noddy2.c	Wed Jun  4 11:24:23 2008
@@ -23,14 +23,14 @@
 
     self = (Noddy *)type->tp_alloc(type, 0);
     if (self != NULL) {
-        self->first = PyString_FromString("");
+        self->first = PyBytes_FromString("");
         if (self->first == NULL)
           {
             Py_DECREF(self);
             return NULL;
           }
         
-        self->last = PyString_FromString("");
+        self->last = PyBytes_FromString("");
         if (self->last == NULL)
           {
             Py_DECREF(self);
@@ -90,7 +90,7 @@
     PyObject *args, *result;
 
     if (format == NULL) {
-        format = PyString_FromString("%s %s");
+        format = PyBytes_FromString("%s %s");
         if (format == NULL)
             return NULL;
     }
@@ -109,7 +109,7 @@
     if (args == NULL)
         return NULL;
 
-    result = PyString_Format(format, args);
+    result = PyBytes_Format(format, args);
     Py_DECREF(args);
     
     return result;

Modified: python/branches/okkoto-sizeof/Doc/includes/noddy3.c
==============================================================================
--- python/branches/okkoto-sizeof/Doc/includes/noddy3.c	(original)
+++ python/branches/okkoto-sizeof/Doc/includes/noddy3.c	Wed Jun  4 11:24:23 2008
@@ -23,14 +23,14 @@
 
     self = (Noddy *)type->tp_alloc(type, 0);
     if (self != NULL) {
-        self->first = PyString_FromString("");
+        self->first = PyBytes_FromString("");
         if (self->first == NULL)
           {
             Py_DECREF(self);
             return NULL;
           }
         
-        self->last = PyString_FromString("");
+        self->last = PyBytes_FromString("");
         if (self->last == NULL)
           {
             Py_DECREF(self);
@@ -93,7 +93,7 @@
     return -1;
   }
   
-  if (! PyString_Check(value)) {
+  if (! PyBytes_Check(value)) {
     PyErr_SetString(PyExc_TypeError, 
                     "The first attribute value must be a string");
     return -1;
@@ -121,7 +121,7 @@
     return -1;
   }
   
-  if (! PyString_Check(value)) {
+  if (! PyBytes_Check(value)) {
     PyErr_SetString(PyExc_TypeError, 
                     "The last attribute value must be a string");
     return -1;
@@ -153,7 +153,7 @@
     PyObject *args, *result;
 
     if (format == NULL) {
-        format = PyString_FromString("%s %s");
+        format = PyBytes_FromString("%s %s");
         if (format == NULL)
             return NULL;
     }
@@ -162,7 +162,7 @@
     if (args == NULL)
         return NULL;
 
-    result = PyString_Format(format, args);
+    result = PyBytes_Format(format, args);
     Py_DECREF(args);
     
     return result;

Modified: python/branches/okkoto-sizeof/Doc/includes/noddy4.c
==============================================================================
--- python/branches/okkoto-sizeof/Doc/includes/noddy4.c	(original)
+++ python/branches/okkoto-sizeof/Doc/includes/noddy4.c	Wed Jun  4 11:24:23 2008
@@ -57,14 +57,14 @@
 
     self = (Noddy *)type->tp_alloc(type, 0);
     if (self != NULL) {
-        self->first = PyString_FromString("");
+        self->first = PyBytes_FromString("");
         if (self->first == NULL)
           {
             Py_DECREF(self);
             return NULL;
           }
         
-        self->last = PyString_FromString("");
+        self->last = PyBytes_FromString("");
         if (self->last == NULL)
           {
             Py_DECREF(self);
@@ -124,7 +124,7 @@
     PyObject *args, *result;
 
     if (format == NULL) {
-        format = PyString_FromString("%s %s");
+        format = PyBytes_FromString("%s %s");
         if (format == NULL)
             return NULL;
     }
@@ -143,7 +143,7 @@
     if (args == NULL)
         return NULL;
 
-    result = PyString_Format(format, args);
+    result = PyBytes_Format(format, args);
     Py_DECREF(args);
     
     return result;

Modified: python/branches/okkoto-sizeof/Doc/includes/run-func.c
==============================================================================
--- python/branches/okkoto-sizeof/Doc/includes/run-func.c	(original)
+++ python/branches/okkoto-sizeof/Doc/includes/run-func.c	Wed Jun  4 11:24:23 2008
@@ -13,7 +13,7 @@
     }
 
     Py_Initialize();
-    pName = PyString_FromString(argv[1]);
+    pName = PyBytes_FromString(argv[1]);
     /* Error checking of pName left out */
 
     pModule = PyImport_Import(pName);

Modified: python/branches/okkoto-sizeof/Doc/library/_winreg.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/_winreg.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/_winreg.rst	Wed Jun  4 11:24:23 2008
@@ -7,6 +7,11 @@
    :synopsis: Routines and objects for manipulating the Windows registry.
 .. sectionauthor:: Mark Hammond <MarkH at ActiveState.com>
 
+.. note::
+   The :mod:`_winreg` module has been renamed to :mod:`winreg` in Python 3.0.
+   The :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
+
 
 .. versionadded:: 2.0
 

Modified: python/branches/okkoto-sizeof/Doc/library/anydbm.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/anydbm.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/anydbm.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`anydbm` --- Generic access to DBM-style databases
 =======================================================
 
@@ -6,6 +5,11 @@
    :synopsis: Generic interface to DBM-style database modules.
 
 
+.. note::
+   The :mod:`anydbm` module has been renamed to :mod:`dbm` in Python 3.0.  The
+   :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
+
 .. index::
    module: dbhash
    module: bsddb

Modified: python/branches/okkoto-sizeof/Doc/library/basehttpserver.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/basehttpserver.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/basehttpserver.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,14 @@
-
 :mod:`BaseHTTPServer` --- Basic HTTP server
 ===========================================
 
 .. module:: BaseHTTPServer
    :synopsis: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer).
 
+.. note::
+   The :mod:`BaseHTTPServer` module has been merged into :mod:`http.server` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 .. index::
    pair: WWW; server
@@ -21,7 +25,7 @@
 functioning Web servers. See the :mod:`SimpleHTTPServer` and
 :mod:`CGIHTTPServer` modules.
 
-The first class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer`
+The first class, :class:`HTTPServer`, is a :class:`SocketServer.TCPServer`
 subclass.  It creates and listens at the HTTP socket, dispatching the requests
 to a handler.  Code to create and run the server looks like this::
 

Modified: python/branches/okkoto-sizeof/Doc/library/bsddb.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/bsddb.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/bsddb.rst	Wed Jun  4 11:24:23 2008
@@ -15,15 +15,15 @@
 :func:`marshal.dumps` or  :func:`pickle.dumps`.
 
 The :mod:`bsddb` module requires a Berkeley DB library version from 3.3 thru
-4.5.
+4.7.
 
 
 .. seealso::
 
-   http://pybsddb.sourceforge.net/
+   http://www.jcea.es/programacion/pybsddb.htm
       The website with documentation for the :mod:`bsddb.db` Python Berkeley DB
       interface that closely mirrors the object oriented interface provided in
-      Berkeley DB 3 and 4.
+      Berkeley DB 4.x itself.
 
    http://www.oracle.com/database/berkeley-db/
       The Berkeley DB library.

Modified: python/branches/okkoto-sizeof/Doc/library/calendar.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/calendar.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/calendar.rst	Wed Jun  4 11:24:23 2008
@@ -37,7 +37,7 @@
    :class:`Calendar` instances have the following methods:
 
 
-   .. method:: iterweekdays(weekday)
+   .. method:: iterweekdays()
 
       Return an iterator for the week day numbers that will be used for one
       week.  The first value from the iterator will be the same as the value of

Modified: python/branches/okkoto-sizeof/Doc/library/cgihttpserver.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/cgihttpserver.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/cgihttpserver.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`CGIHTTPServer` --- CGI-capable HTTP request handler
 =========================================================
 
@@ -7,6 +6,11 @@
               scripts.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+.. note::
+   The :mod:`CGIHTTPServer` module has been merged into :mod:`http.server` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 The :mod:`CGIHTTPServer` module defines a request-handler class, interface
 compatible with :class:`BaseHTTPServer.BaseHTTPRequestHandler` and inherits

Modified: python/branches/okkoto-sizeof/Doc/library/cmd.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/cmd.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/cmd.rst	Wed Jun  4 11:24:23 2008
@@ -26,7 +26,12 @@
 
    The optional arguments *stdin* and *stdout* specify the  input and output file
    objects that the Cmd instance or subclass  instance will use for input and
-   output. If not specified, they will default to *sys.stdin* and *sys.stdout*.
+   output. If not specified, they will default to :data:`sys.stdin` and
+   :data:`sys.stdout`.
+
+   If you want a given *stdin* to be used, make sure to set the instance's
+   :attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be
+   ignored.
 
    .. versionchanged:: 2.3
       The *stdin* and *stdout* parameters were added.

Modified: python/branches/okkoto-sizeof/Doc/library/codecs.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/codecs.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/codecs.rst	Wed Jun  4 11:24:23 2008
@@ -295,7 +295,8 @@
 ------------------
 
 The :mod:`codecs` module defines a set of base classes which define the
-interface and can also be used to easily write you own codecs for use in Python.
+interface and can also be used to easily write your own codecs for use in
+Python.
 
 Each codec has to define four interfaces to make it usable as codec in Python:
 stateless encoder, stateless decoder, stream reader and stream writer. The

Modified: python/branches/okkoto-sizeof/Doc/library/collections.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/collections.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/collections.rst	Wed Jun  4 11:24:23 2008
@@ -122,7 +122,7 @@
    Since some set operations create new sets, the default mixin methods need
    a way to create new instances from an iterable. The class constructor is
    assumed to have a signature in the form ``ClassName(iterable)``.
-   That assumption is factored-out to a singleinternal classmethod called
+   That assumption is factored-out to an internal classmethod called
    :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
    If the :class:`Set` mixin is being used in a class with a different
    constructor signature, you will need to override :meth:`from_iterable`

Modified: python/branches/okkoto-sizeof/Doc/library/commands.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/commands.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/commands.rst	Wed Jun  4 11:24:23 2008
@@ -16,6 +16,12 @@
 processes and retrieving their results.  Using the :mod:`subprocess` module is
 preferable to using the :mod:`commands` module.
 
+.. warning::
+
+   In 3.x, :func:`getstatus` and two undocumented functions (:func:`mk2arg` and
+   :func:`mkarg`) have been removed.  Also, :func:`getstatusoutput` and
+   :func:`getoutput` have been moved to the :mod:`subprocess` module.
+
 The :mod:`commands` module defines the following functions:
 
 
@@ -44,6 +50,7 @@
       This function is nonobvious and useless, also the name is misleading in the
       presence of :func:`getstatusoutput`.
 
+
 Example::
 
    >>> import commands

Modified: python/branches/okkoto-sizeof/Doc/library/configparser.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/configparser.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/configparser.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,7 @@
-:mod:`configparser` --- Configuration file parser
+:mod:`ConfigParser` --- Configuration file parser
 =================================================
 
 .. module:: ConfigParser
-   :synopsis: Old name for the configparser module.
-
-.. module:: configparser
    :synopsis: Configuration file parser.
 
 .. moduleauthor:: Ken Manheimer <klm at zope.com>
@@ -13,9 +10,10 @@
 .. sectionauthor:: Christopher G. Petrilli <petrilli at amber.org>
 
 .. note::
-   The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
-   Python 3.0.  It is importable under both names in Python 2.6 and the rest of
-   the 2.x series.
+
+   The :mod:`ConfigParser` module has been renamed to `configparser` in Python
+   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
 
 .. index::
    pair: .ini; file
@@ -233,9 +231,9 @@
    load the required file or files using :meth:`readfp` before calling :meth:`read`
    for any optional files::
 
-      import configparser, os
+      import ConfigParser, os
 
-      config = configparser.ConfigParser()
+      config = ConfigParser.ConfigParser()
       config.readfp(open('defaults.cfg'))
       config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
 
@@ -375,10 +373,10 @@
 
 An example of writing to a configuration file::
 
-   import configparser
+   import ConfigParser
+
+   config = ConfigParser.RawConfigParser()
 
-   config = configparser.RawConfigParser()
-   
    # When adding sections or items, add them in the reverse order of
    # how you want them to be displayed in the actual file.
    # In addition, please note that using RawConfigParser's and the raw
@@ -393,16 +391,16 @@
    config.set('Section1', 'baz', 'fun')
    config.set('Section1', 'bar', 'Python')
    config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
-   
+
    # Writing our configuration file to 'example.cfg'
    with open('example.cfg', 'wb') as configfile:
        config.write(configfile)
 
 An example of reading the configuration file again::
 
-   import configparser
+   import ConfigParser
 
-   config = configparser.RawConfigParser()
+   config = ConfigParser.RawConfigParser()
    config.read('example.cfg')
 
    # getfloat() raises an exception if the value is not a float
@@ -419,9 +417,9 @@
 To get interpolation, you will need to use a :class:`ConfigParser` or
 :class:`SafeConfigParser`::
 
-   import configparser
+   import ConfigParser
 
-   config = configparser.ConfigParser()
+   config = ConfigParser.ConfigParser()
    config.read('example.cfg')
 
    # Set the third, optional argument of get to 1 if you wish to use raw mode.
@@ -433,15 +431,15 @@
    print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                            'baz': 'evil'})
 
-Defaults are available in all three types of ConfigParsers. They are used in 
+Defaults are available in all three types of ConfigParsers. They are used in
 interpolation if an option used is not defined elsewhere. ::
 
-   import configparser
+   import ConfigParser
 
    # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
-   config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
+   config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
    config.read('example.cfg')
-   
+
    print config.get('Section1', 'foo') # -> "Python is fun!"
    config.remove_option('Section1', 'bar')
    config.remove_option('Section1', 'baz')
@@ -452,7 +450,7 @@
    def opt_move(config, section1, section2, option):
        try:
            config.set(section2, option, config.get(section1, option, 1))
-       except configparser.NoSectionError:
+       except ConfigParser.NoSectionError:
            # Create non-existent section
            config.add_section(section2)
            opt_move(config, section1, section2, option)

Modified: python/branches/okkoto-sizeof/Doc/library/cookie.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/cookie.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/cookie.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`Cookie` --- HTTP state management
 =======================================
 
@@ -7,6 +6,11 @@
 .. moduleauthor:: Timothy O'Malley <timo at alum.mit.edu>
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+.. note::
+   The :mod:`Cookie` module has been renamed to :mod:`http.cookies` in Python
+   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
+
 
 The :mod:`Cookie` module defines classes for abstracting the concept of
 cookies, an HTTP state management mechanism. It supports both simple string-only
@@ -18,6 +22,12 @@
 MSIE 3.0x doesn't follow the character rules outlined in those specs.  As a
 result, the parsing rules used are a bit less strict.
 
+.. note::
+
+   On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
+   cookie data comes from a browser you should always prepare for invalid data
+   and catch :exc:`CookieError` on parsing.
+
 
 .. exception:: CookieError
 

Modified: python/branches/okkoto-sizeof/Doc/library/cookielib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/cookielib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/cookielib.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`cookielib` --- Cookie handling for HTTP clients
 =====================================================
 
@@ -7,6 +6,11 @@
 .. moduleauthor:: John J. Lee <jjl at pobox.com>
 .. sectionauthor:: John J. Lee <jjl at pobox.com>
 
+.. note::
+   The :mod:`cookielib` module has been renamed to :mod:`http.cookiejar` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 .. versionadded:: 2.4
 

Modified: python/branches/okkoto-sizeof/Doc/library/copy.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/copy.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/copy.rst	Wed Jun  4 11:24:23 2008
@@ -63,7 +63,7 @@
 
 Classes can use the same interfaces to control copying that they use to control
 pickling.  See the description of module :mod:`pickle` for information on these
-methods.  The :mod:`copy` module does not use the :mod:`copyreg` registration
+methods.  The :mod:`copy` module does not use the :mod:`copy_reg` registration
 module.
 
 .. index::

Deleted: python/branches/okkoto-sizeof/Doc/library/copyreg.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/copyreg.rst	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,48 +0,0 @@
-:mod:`copyreg` --- Register :mod:`pickle` support functions
-===========================================================
-
-.. module:: copy_reg
-   :synopsis: Old name for the copyreg module.
-
-.. module:: copyreg
-   :synopsis: Register pickle support functions.
-
-.. note::
-   The :mod:`copy_reg` module has been renamed to :mod:`copyreg` in Python 3.0.
-   It is importable under both names in Python 2.6 and the rest of the 2.x
-   series.
-
-.. index::
-   module: pickle
-   module: cPickle
-   module: copy
-
-The :mod:`copyreg` module provides support for the :mod:`pickle` and
-:mod:`cPickle` modules.  The :mod:`copy` module is likely to use this in the
-future as well.  It provides configuration information about object constructors
-which are not classes.  Such constructors may be factory functions or class
-instances.
-
-
-.. function:: constructor(object)
-
-   Declares *object* to be a valid constructor.  If *object* is not callable (and
-   hence not valid as a constructor), raises :exc:`TypeError`.
-
-
-.. function:: pickle(type, function[, constructor])
-
-   Declares that *function* should be used as a "reduction" function for objects of
-   type *type*; *type* must not be a "classic" class object.  (Classic classes are
-   handled differently; see the documentation for the :mod:`pickle` module for
-   details.)  *function* should return either a string or a tuple containing two or
-   three elements.
-
-   The optional *constructor* parameter, if provided, is a callable object which
-   can be used to reconstruct the object when called with the tuple of arguments
-   returned by *function* at pickling time.  :exc:`TypeError` will be raised if
-   *object* is a class or *constructor* is not callable.
-
-   See the :mod:`pickle` module for more details on the interface expected of
-   *function* and *constructor*.
-

Modified: python/branches/okkoto-sizeof/Doc/library/dbhash.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/dbhash.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/dbhash.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`dbhash` --- DBM-style interface to the BSD database library
 =================================================================
 
@@ -6,6 +5,10 @@
    :synopsis: DBM-style interface to the BSD database library.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+.. note::
+   The :mod:`dbhash` module has been renamed to :mod:`dbm.bsd` in Python 3.0.
+   The :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
 
 .. index:: module: bsddb
 

Modified: python/branches/okkoto-sizeof/Doc/library/dbm.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/dbm.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/dbm.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`dbm` --- Simple "database" interface
 ==========================================
 
@@ -6,6 +5,11 @@
    :platform: Unix
    :synopsis: The standard "database" interface, based on ndbm.
 
+.. note::
+   The :mod:`dbm` module has been renamed to :mod:`dbm.ndbm` in Python 3.0.  The
+   :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
+
 
 The :mod:`dbm` module provides an interface to the Unix "(n)dbm" library.  Dbm
 objects behave like mappings (dictionaries), except that keys and values are

Modified: python/branches/okkoto-sizeof/Doc/library/docxmlrpcserver.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/docxmlrpcserver.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/docxmlrpcserver.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`DocXMLRPCServer` --- Self-documenting XML-RPC server
 ==========================================================
 
@@ -7,6 +6,11 @@
 .. moduleauthor:: Brian Quinlan <brianq at activestate.com>
 .. sectionauthor:: Brian Quinlan <brianq at activestate.com>
 
+.. note::
+   The :mod:`DocXMLRPCServer` module has been merged into :mod:`xmlrpc.server`
+   in Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 .. versionadded:: 2.3
 

Modified: python/branches/okkoto-sizeof/Doc/library/dumbdbm.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/dumbdbm.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/dumbdbm.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,13 @@
-
 :mod:`dumbdbm` --- Portable DBM implementation
 ==============================================
 
 .. module:: dumbdbm
    :synopsis: Portable implementation of the simple DBM interface.
 
+.. note::
+   The :mod:`dumbdbm` module has been renamed to :mod:`dbm.dumb` in Python 3.0.
+   The :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
 
 .. index:: single: databases
 

Modified: python/branches/okkoto-sizeof/Doc/library/dummy_thread.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/dummy_thread.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/dummy_thread.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,15 @@
-
 :mod:`dummy_thread` --- Drop-in replacement for the :mod:`thread` module
 ========================================================================
 
 .. module:: dummy_thread
    :synopsis: Drop-in replacement for the thread module.
 
+.. note::
+   The :mod:`dummy_thread` module has been renamed to :mod:`_dummy_thread` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0; however, you should consider using the
+   high-lever :mod:`dummy_threading` module instead.
+
 
 This module provides a duplicate interface to the :mod:`thread` module.  It is
 meant to be imported when the :mod:`thread` module is not provided on a

Modified: python/branches/okkoto-sizeof/Doc/library/easydialogs.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/easydialogs.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/easydialogs.rst	Wed Jun  4 11:24:23 2008
@@ -9,10 +9,12 @@
 
 
 The :mod:`EasyDialogs` module contains some simple dialogs for the Macintosh.
-All routines take an optional resource ID parameter *id* with which one can
-override the :const:`DLOG` resource used for the dialog, provided that the
-dialog items correspond (both type and item number) to those in the default
-:const:`DLOG` resource. See source code for details.
+The dialogs get launched in a separate application which appears in the dock and
+must be clicked on for the dialogs be displayed.  All routines take an optional
+resource ID parameter *id* with which one can override the :const:`DLOG`
+resource used for the dialog, provided that the dialog items correspond (both
+type and item number) to those in the default :const:`DLOG` resource. See source
+code for details.
 
 .. warning::
 

Modified: python/branches/okkoto-sizeof/Doc/library/ftplib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/ftplib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/ftplib.rst	Wed Jun  4 11:24:23 2008
@@ -44,8 +44,8 @@
    the method call ``login(user, passwd, acct)`` is made (where *passwd* and
    *acct* default to the empty string when not given).  The optional *timeout*
    parameter specifies a timeout in seconds for blocking operations like the
-   connection attempt (if is not specified, or passed as None, the global
-   default timeout setting will be used).
+   connection attempt (if is not specified, the global default timeout setting
+   will be used).
 
    .. versionchanged:: 2.6
       *timeout* was added.
@@ -126,10 +126,8 @@
    made.
 
    The optional *timeout* parameter specifies a timeout in seconds for the
-   connection attempt. If is not specified, or passed as None, the object
-   timeout is used (the timeout that you passed when instantiating the class);
-   if the object timeout is also None, the global default timeout setting will
-   be used.
+   connection attempt. If no *timeout* is passed, the global default timeout
+   setting will be used.
 
    .. versionchanged:: 2.6
       *timeout* was added.

Modified: python/branches/okkoto-sizeof/Doc/library/future_builtins.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/future_builtins.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/future_builtins.rst	Wed Jun  4 11:24:23 2008
@@ -15,7 +15,7 @@
 
    ... code using Python 3-style map and filter ...
 
-The :program:`2to3` tool that ports Python 2 code to Python 3 will recognize
+The :term:`2to3` tool that ports Python 2 code to Python 3 will recognize
 this usage and leave the new builtins alone.
 
 .. note::

Modified: python/branches/okkoto-sizeof/Doc/library/gdbm.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/gdbm.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/gdbm.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`gdbm` --- GNU's reinterpretation of dbm
 =============================================
 
@@ -6,6 +5,11 @@
    :platform: Unix
    :synopsis: GNU's reinterpretation of dbm.
 
+.. note::
+   The :mod:`gdbm` module has been renamed to :mod:`dbm.gnu` in Python 3.0.  The
+   :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
+
 
 .. index:: module: dbm
 

Modified: python/branches/okkoto-sizeof/Doc/library/htmllib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/htmllib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/htmllib.rst	Wed Jun  4 11:24:23 2008
@@ -1,9 +1,12 @@
-
 :mod:`htmllib` --- A parser for HTML documents
 ==============================================
 
 .. module:: htmllib
    :synopsis: A parser for HTML documents.
+   :deprecated:
+   
+.. deprecated:: 2.6
+    The :mod:`htmllib` module has been removed in Python 3.0.
 
 
 .. index::
@@ -156,6 +159,12 @@
    :synopsis: Definitions of HTML general entities.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+.. note::
+
+   The :mod:`htmlentitydefs` module has been renamed to :mod:`html.entities` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``,
 and ``entitydefs``. ``entitydefs`` is used by the :mod:`htmllib` module to

Modified: python/branches/okkoto-sizeof/Doc/library/htmlparser.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/htmlparser.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/htmlparser.rst	Wed Jun  4 11:24:23 2008
@@ -5,6 +5,12 @@
 .. module:: HTMLParser
    :synopsis: A simple parser that can handle HTML and XHTML.
 
+.. note::
+
+   The :mod:`HTMLParser` module has been renamed to :mod:`html.parser` in Python
+   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
+
 
 .. versionadded:: 2.2
 
@@ -22,7 +28,7 @@
 
    The :class:`HTMLParser` class is instantiated without arguments.
 
-   An HTMLParser instance is fed HTML data and calls handler functions when tags
+   An :class:`HTMLParser` instance is fed HTML data and calls handler functions when tags
    begin and end.  The :class:`HTMLParser` class is meant to be overridden by the
    user to provide a desired behavior.
 
@@ -92,7 +98,7 @@
    ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``.
 
    .. versionchanged:: 2.6
-      All entity references from htmlentitydefs are now replaced in the attribute
+      All entity references from :mod:`htmlentitydefs` are now replaced in the attribute
       values.
 
 

Modified: python/branches/okkoto-sizeof/Doc/library/httplib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/httplib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/httplib.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,14 @@
-
 :mod:`httplib` --- HTTP protocol client
 =======================================
 
 .. module:: httplib
    :synopsis: HTTP and HTTPS protocol client (requires sockets).
 
+.. note::
+   The :mod:`httplib` module has been renamed to :mod:`http.client` in Python
+   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
+
 
 .. index::
    pair: HTTP; protocol
@@ -40,7 +44,7 @@
    be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1
    status line.  If the optional *timeout* parameter is given, blocking
    operations (like connection attempts) will timeout after that many seconds
-   (if it is not given or ``None``, the global default timeout setting is used).
+   (if it is not given, the global default timeout setting is used).
 
    For example, the following calls all create instances that connect to the server
    at the same host and port::

Modified: python/branches/okkoto-sizeof/Doc/library/idle.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/idle.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/idle.rst	Wed Jun  4 11:24:23 2008
@@ -10,11 +10,11 @@
    single: Python Editor
    single: Integrated Development Environment
 
-IDLE is the Python IDE built with the :mod:`Tkinter` GUI toolkit.
+IDLE is the Python IDE built with the :mod:`tkinter` GUI toolkit.
 
 IDLE has the following features:
 
-* coded in 100% pure Python, using the :mod:`Tkinter` GUI toolkit
+* coded in 100% pure Python, using the :mod:`tkinter` GUI toolkit
 
 * cross-platform: works on Windows and Unix (on Mac OS, there are currently
   problems with Tcl/Tk)

Modified: python/branches/okkoto-sizeof/Doc/library/logging.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/logging.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/logging.rst	Wed Jun  4 11:24:23 2008
@@ -1299,17 +1299,17 @@
    logger2.warning('Jail zesty vixen who grabbed pay from quack.')
    logger2.error('The five boxing wizards jump quickly.')
 
-At the receiving end, you can set up a receiver using the :mod:`socketserver`
+At the receiving end, you can set up a receiver using the :mod:`SocketServer`
 module. Here is a basic working example::
 
    import cPickle
    import logging
    import logging.handlers
-   import socketserver
+   import SocketServer
    import struct
 
 
-   class LogRecordStreamHandler(socketserver.StreamRequestHandler):
+   class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
        """Handler for a streaming logging request.
 
        This basically logs the record using whatever logging policy is
@@ -1351,7 +1351,7 @@
            # cycles and network bandwidth!
            logger.handle(record)
 
-   class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
+   class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
        """simple TCP socket-based logging receiver suitable for testing.
        """
 
@@ -1360,7 +1360,7 @@
        def __init__(self, host='localhost',
                     port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                     handler=LogRecordStreamHandler):
-           socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
+           SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
            self.abort = 0
            self.timeout = 1
            self.logname = None
@@ -2240,12 +2240,12 @@
 
 .. function:: fileConfig(fname[, defaults])
 
-   Reads the logging configuration from a :mod:`configparser`\-format file named
-   *fname*.  This function can be called several times from an application,
-   allowing an end user the ability to select from various pre-canned
-   configurations (if the developer provides a mechanism to present the choices
-   and load the chosen configuration). Defaults to be passed to the ConfigParser
-   can be specified in the *defaults* argument.
+   Reads the logging configuration from a ConfigParser-format file named *fname*.
+   This function can be called several times from an application, allowing an end
+   user the ability to select from various pre-canned configurations (if the
+   developer provides a mechanism to present the choices and load the chosen
+   configuration). Defaults to be passed to ConfigParser can be specified in the
+   *defaults* argument.
 
 
 .. function:: listen([port])
@@ -2275,20 +2275,18 @@
 Configuration file format
 ^^^^^^^^^^^^^^^^^^^^^^^^^
 
-The configuration file format understood by :func:`fileConfig` is
-based on :mod:`configparser` functionality. The file must contain
-sections called ``[loggers]``, ``[handlers]`` and ``[formatters]``
-which identify by name the entities of each type which are defined in
-the file. For each such entity, there is a separate section which
-identified how that entity is configured. Thus, for a logger named
-``log01`` in the ``[loggers]`` section, the relevant configuration
-details are held in a section ``[logger_log01]``. Similarly, a handler
-called ``hand01`` in the ``[handlers]`` section will have its
-configuration held in a section called ``[handler_hand01]``, while a
-formatter called ``form01`` in the ``[formatters]`` section will have
-its configuration specified in a section called
-``[formatter_form01]``. The root logger configuration must be
-specified in a section called ``[logger_root]``.
+The configuration file format understood by :func:`fileConfig` is based on
+ConfigParser functionality. The file must contain sections called ``[loggers]``,
+``[handlers]`` and ``[formatters]`` which identify by name the entities of each
+type which are defined in the file. For each such entity, there is a separate
+section which identified how that entity is configured. Thus, for a logger named
+``log01`` in the ``[loggers]`` section, the relevant configuration details are
+held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
+the ``[handlers]`` section will have its configuration held in a section called
+``[handler_hand01]``, while a formatter called ``form01`` in the
+``[formatters]`` section will have its configuration specified in a section
+called ``[formatter_form01]``. The root logger configuration must be specified
+in a section called ``[logger_root]``.
 
 Examples of these sections in the file are given below. ::
 

Modified: python/branches/okkoto-sizeof/Doc/library/math.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/math.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/math.rst	Wed Jun  4 11:24:23 2008
@@ -103,6 +103,12 @@
    Return the fractional and integer parts of *x*.  Both results carry the sign of
    *x*, and both are floats.
 
+.. function:: sum(iterable)
+
+   Return an accurate floating point sum of values in the iterable.  Avoids
+   loss of precision by tracking multiple intermediate partial sums.  The
+   algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the
+   typical case where the rounding mode is half-even.
 
 .. function:: trunc(x)
 

Modified: python/branches/okkoto-sizeof/Doc/library/msilib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/msilib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/msilib.rst	Wed Jun  4 11:24:23 2008
@@ -264,6 +264,18 @@
    :cfunc:`MsiRecordGetFieldCount`.
 
 
+.. method:: Record.GetInteger(field)
+
+   Return the value of *field* as an integer where possible.  *field* must
+   be an integer.
+
+
+.. method:: Record.GetString(field)
+
+   Return the value of *field* as a string where possible.  *field* must
+   be an integer.
+
+
 .. method:: Record.SetString(field, value)
 
    Set *field* to *value* through :cfunc:`MsiRecordSetString`. *field* must be an
@@ -543,3 +555,4 @@
    This module contains definitions for the UIText and ActionText tables, for the
    standard installer actions.
 
+

Modified: python/branches/okkoto-sizeof/Doc/library/os.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/os.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/os.rst	Wed Jun  4 11:24:23 2008
@@ -717,7 +717,8 @@
    combined using the bitwise OR operator ``|``. Availability: Windows.
 
 
-.. data:: O_DIRECT
+.. data:: O_ASYNC
+          O_DIRECT
           O_DIRECTORY
           O_NOFOLLOW
           O_NOATIME
@@ -2030,7 +2031,7 @@
 
    Return the number of processes in the system run queue averaged over the last
    1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
-   unobtainable.
+   unobtainable.  Availability: Unix.
 
    .. versionadded:: 2.3
 

Modified: python/branches/okkoto-sizeof/Doc/library/persistence.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/persistence.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/persistence.rst	Wed Jun  4 11:24:23 2008
@@ -19,7 +19,7 @@
 .. toctree::
 
    pickle.rst
-   copyreg.rst
+   copy_reg.rst
    shelve.rst
    marshal.rst
    anydbm.rst

Modified: python/branches/okkoto-sizeof/Doc/library/pickle.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/pickle.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/pickle.rst	Wed Jun  4 11:24:23 2008
@@ -535,7 +535,7 @@
 and calls :meth:`__reduce__`.
 
 An alternative to implementing a :meth:`__reduce__` method on the object to be
-pickled, is to register the callable with the :mod:`copyreg` module.  This
+pickled, is to register the callable with the :mod:`copy_reg` module.  This
 module provides a way for programs to register "reduction functions" and
 constructors for user-defined types.   Reduction functions have the same
 semantics and interface as the :meth:`__reduce__` method described above, except
@@ -786,7 +786,7 @@
 
 .. seealso::
 
-   Module :mod:`copyreg`
+   Module :mod:`copy_reg`
       Pickle interface constructor registration for extension types.
 
    Module :mod:`shelve`

Modified: python/branches/okkoto-sizeof/Doc/library/poplib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/poplib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/poplib.rst	Wed Jun  4 11:24:23 2008
@@ -29,8 +29,8 @@
    This class implements the actual POP3 protocol.  The connection is created when
    the instance is initialized. If *port* is omitted, the standard POP3 port (110)
    is used. The optional *timeout* parameter specifies a timeout in seconds for the
-   connection attempt (if not specified, or passed as None, the global default
-   timeout setting will be used).
+   connection attempt (if not specified, the global default timeout setting will
+   be used).
 
    .. versionchanged:: 2.6
       *timeout* was added.

Modified: python/branches/okkoto-sizeof/Doc/library/queue.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/queue.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/queue.rst	Wed Jun  4 11:24:23 2008
@@ -2,17 +2,15 @@
 ===========================================
 
 .. module:: Queue
-   :synopsis: Old name for the queue module.
-
-.. module:: queue
    :synopsis: A synchronized queue class.
 
 .. note::
-   The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3.0.  It
-   is importable under both names in Python 2.6 and the rest of the 2.x series.
+   The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3.0.  The
+   :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
 
 
-The :mod:`queue` module implements multi-producer, multi-consumer queues.
+The :mod:`Queue` module implements multi-producer, multi-consumer queues.
 It is especially useful in threaded programming when information must be
 exchanged safely between multiple threads.  The :class:`Queue` class in this
 module implements all the required locking semantics.  It depends on the
@@ -26,7 +24,7 @@
 the entries are kept sorted (using the :mod:`heapq` module) and the
 lowest valued entry is retrieved first.
 
-The :mod:`queue` module defines the following classes and exceptions:
+The :mod:`Queue` module defines the following classes and exceptions:
 
 .. class:: Queue(maxsize)
 
@@ -75,7 +73,7 @@
 -------------
 
 Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
-provide the public methods described below.  
+provide the public methods described below.
 
 
 .. method:: Queue.qsize()
@@ -170,20 +168,20 @@
 
 Example of how to wait for enqueued tasks to be completed::
 
-   def worker(): 
-       while True: 
-           item = q.get() 
-           do_work(item) 
-           q.task_done() 
+   def worker():
+       while True:
+           item = q.get()
+           do_work(item)
+           q.task_done()
 
-   q = Queue() 
-   for i in range(num_worker_threads): 
+   q = Queue()
+   for i in range(num_worker_threads):
         t = Thread(target=worker)
         t.setDaemon(True)
-        t.start() 
+        t.start()
 
    for item in source():
-       q.put(item) 
+       q.put(item)
 
    q.join()       # block until all tasks are done
 

Modified: python/branches/okkoto-sizeof/Doc/library/re.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/re.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/re.rst	Wed Jun  4 11:24:23 2008
@@ -181,6 +181,12 @@
    ``[^5]`` will match any character except ``'5'``, and ``[^^]`` will match any
    character except ``'^'``.
 
+   Note that inside ``[]`` the special forms and special characters lose
+   their meanings and only the syntaxes described here are valid. For
+   example, ``+``, ``*``, ``(``, ``)``, and so on are treated as
+   literals inside ``[]``, and backreferences cannot be used inside
+   ``[]``.
+
 ``'|'``
    ``A|B``, where A and B can be arbitrary REs, creates a regular expression that
    will match either A or B.  An arbitrary number of REs can be separated by the

Deleted: python/branches/okkoto-sizeof/Doc/library/reprlib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/reprlib.rst	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,143 +0,0 @@
-
-:mod:`reprlib` --- Alternate :func:`repr` implementation
-=====================================================
-
-.. module:: repr
-   :synopsis: Old name for the reprlib module.
-.. module:: reprlib
-   :synopsis: Alternate repr() implementation with size limits.
-.. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
-
-.. note::
-   The :mod:`repr` module has been renamed to :mod:`reprlib` in
-   Python 3.0.  It is importable under both names in Python 2.6
-   and the rest of the 2.x series.
-
-
-The :mod:`reprlib` module provides a means for producing object representations
-with limits on the size of the resulting strings. This is used in the Python
-debugger and may be useful in other contexts as well.
-
-This module provides a class, an instance, and a function:
-
-
-.. class:: Repr()
-
-   Class which provides formatting services useful in implementing functions
-   similar to the built-in :func:`repr`; size limits for  different object types
-   are added to avoid the generation of representations which are excessively long.
-
-
-.. data:: aRepr
-
-   This is an instance of :class:`Repr` which is used to provide the :func:`repr`
-   function described below.  Changing the attributes of this object will affect
-   the size limits used by :func:`repr` and the Python debugger.
-
-
-.. function:: repr(obj)
-
-   This is the :meth:`repr` method of ``aRepr``.  It returns a string similar to
-   that returned by the built-in function of the same  name, but with limits on
-   most sizes.
-
-
-.. _repr-objects:
-
-Repr Objects
-------------
-
-:class:`Repr` instances provide several members which can be used to provide
-size limits for the representations of different object types,  and methods
-which format specific object types.
-
-
-.. attribute:: Repr.maxlevel
-
-   Depth limit on the creation of recursive representations.  The default is ``6``.
-
-
-.. attribute:: Repr.maxdict
-               Repr.maxlist
-               Repr.maxtuple
-               Repr.maxset
-               Repr.maxfrozenset
-               Repr.maxdeque
-               Repr.maxarray
-
-   Limits on the number of entries represented for the named object type.  The
-   default is ``4`` for :attr:`maxdict`, ``5`` for :attr:`maxarray`, and  ``6`` for
-   the others.
-
-   .. versionadded:: 2.4
-      :attr:`maxset`, :attr:`maxfrozenset`, and :attr:`set`.
-
-
-.. attribute:: Repr.maxlong
-
-   Maximum number of characters in the representation for a long integer.  Digits
-   are dropped from the middle.  The default is ``40``.
-
-
-.. attribute:: Repr.maxstring
-
-   Limit on the number of characters in the representation of the string.  Note
-   that the "normal" representation of the string is used as the character source:
-   if escape sequences are needed in the representation, these may be mangled when
-   the representation is shortened.  The default is ``30``.
-
-
-.. attribute:: Repr.maxother
-
-   This limit is used to control the size of object types for which no specific
-   formatting method is available on the :class:`Repr` object. It is applied in a
-   similar manner as :attr:`maxstring`.  The default is ``20``.
-
-
-.. method:: Repr.repr(obj)
-
-   The equivalent to the built-in :func:`repr` that uses the formatting imposed by
-   the instance.
-
-
-.. method:: Repr.repr1(obj, level)
-
-   Recursive implementation used by :meth:`repr`.  This uses the type of *obj* to
-   determine which formatting method to call, passing it *obj* and *level*.  The
-   type-specific methods should call :meth:`repr1` to perform recursive formatting,
-   with ``level - 1`` for the value of *level* in the recursive  call.
-
-
-.. method:: Repr.repr_TYPE(obj, level)
-   :noindex:
-
-   Formatting methods for specific types are implemented as methods with a name
-   based on the type name.  In the method name, **TYPE** is replaced by
-   ``string.join(string.split(type(obj).__name__, '_'))``. Dispatch to these
-   methods is handled by :meth:`repr1`. Type-specific methods which need to
-   recursively format a value should call ``self.repr1(subobj, level - 1)``.
-
-
-.. _subclassing-reprs:
-
-Subclassing Repr Objects
-------------------------
-
-The use of dynamic dispatching by :meth:`Repr.repr1` allows subclasses of
-:class:`Repr` to add support for additional built-in object types or to modify
-the handling of types already supported. This example shows how special support
-for file objects could be added::
-
-   import repr
-   import sys
-
-   class MyRepr(repr.Repr):
-       def repr_file(self, obj, level):
-           if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
-               return obj.name
-           else:
-               return `obj`
-
-   aRepr = MyRepr()
-   print aRepr.repr(sys.stdin)          # prints '<stdin>'
-

Modified: python/branches/okkoto-sizeof/Doc/library/sgmllib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/sgmllib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/sgmllib.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,12 @@
-
 :mod:`sgmllib` --- Simple SGML parser
 =====================================
 
 .. module:: sgmllib
    :synopsis: Only as much of an SGML parser as needed to parse HTML.
-
+   :deprecated:
+   
+.. deprecated:: 2.6
+    The :mod:`sgmllib` module has been removed in Python 3.0.
 
 .. index:: single: SGML
 

Modified: python/branches/okkoto-sizeof/Doc/library/shlex.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/shlex.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/shlex.rst	Wed Jun  4 11:24:23 2008
@@ -63,7 +63,7 @@
 
 .. seealso::
 
-   Module :mod:`configparser`
+   Module :mod:`ConfigParser`
       Parser for configuration files similar to the Windows :file:`.ini` files.
 
 

Modified: python/branches/okkoto-sizeof/Doc/library/shutil.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/shutil.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/shutil.rst	Wed Jun  4 11:24:23 2008
@@ -73,8 +73,9 @@
 
 .. function:: copy2(src, dst)
 
-   Similar to :func:`copy`, but last access time and last modification time are
-   copied as well.  This is similar to the Unix command :program:`cp -p`.
+   Similar to :func:`copy`, but metadata is copied as well -- in fact, this is just
+   :func:`copy` followed by :func:`copystat`.  This is similar to the
+   Unix command :program:`cp -p`.
 
 
 .. function:: copytree(src, dst[, symlinks])

Modified: python/branches/okkoto-sizeof/Doc/library/simplehttpserver.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/simplehttpserver.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/simplehttpserver.rst	Wed Jun  4 11:24:23 2008
@@ -6,6 +6,11 @@
    :synopsis: This module provides a basic request handler for HTTP servers.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+.. note::
+   The :mod:`SimpleHTTPServer` module has been merged into :mod:`http.server` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 The :mod:`SimpleHTTPServer` module defines a single class,
 :class:`SimpleHTTPRequestHandler`, which is interface-compatible with

Modified: python/branches/okkoto-sizeof/Doc/library/simplexmlrpcserver.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/simplexmlrpcserver.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/simplexmlrpcserver.rst	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,3 @@
-
 :mod:`SimpleXMLRPCServer` --- Basic XML-RPC server
 ==================================================
 
@@ -7,6 +6,11 @@
 .. moduleauthor:: Brian Quinlan <brianq at activestate.com>
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+.. note::
+   The :mod:`SimpleXMLRPCServer` module has been merged into
+   :mod:`xmlrpc.server` in Python 3.0.  The :term:`2to3` tool will automatically
+   adapt imports when converting your sources to 3.0.
+
 
 .. versionadded:: 2.2
 
@@ -22,7 +26,7 @@
    functions that can be called by the XML-RPC protocol.  The *requestHandler*
    parameter should be a factory for request handler instances; it defaults to
    :class:`SimpleXMLRPCRequestHandler`.  The *addr* and *requestHandler* parameters
-   are passed to the :class:`socketserver.TCPServer` constructor.  If *logRequests*
+   are passed to the :class:`SocketServer.TCPServer` constructor.  If *logRequests*
    is true (the default), requests will be logged; setting this parameter to false
    will turn off logging.   The *allow_none* and *encoding* parameters are passed
    on to  :mod:`xmlrpclib` and control the XML-RPC responses that will be returned
@@ -63,7 +67,7 @@
 --------------------------
 
 The :class:`SimpleXMLRPCServer` class is based on
-:class:`socketserver.TCPServer` and provides a means of creating simple, stand
+:class:`SocketServer.TCPServer` and provides a means of creating simple, stand
 alone XML-RPC servers.
 
 

Modified: python/branches/okkoto-sizeof/Doc/library/smtplib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/smtplib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/smtplib.rst	Wed Jun  4 11:24:23 2008
@@ -25,8 +25,8 @@
    with those parameters during initialization.  An :exc:`SMTPConnectError` is
    raised if the specified host doesn't respond correctly. The optional
    *timeout* parameter specifies a timeout in seconds for blocking operations
-   like the connection attempt (if not specified, or passed as None, the global
-   default timeout setting will be used).
+   like the connection attempt (if not specified, the global default timeout
+   setting will be used).
 
    For normal use, you should only require the initialization/connect,
    :meth:`sendmail`, and :meth:`quit` methods.  An example is included below.
@@ -45,8 +45,8 @@
    and *certfile* are also optional, and can contain a PEM formatted private key
    and certificate chain file for the SSL connection. The optional *timeout*
    parameter specifies a timeout in seconds for blocking operations like the
-   connection attempt (if not specified, or passed as None, the global default
-   timeout setting will be used).
+   connection attempt (if not specified, the global default timeout setting
+   will be used).
 
    .. versionchanged:: 2.6
       *timeout* was added.

Modified: python/branches/okkoto-sizeof/Doc/library/socket.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/socket.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/socket.rst	Wed Jun  4 11:24:23 2008
@@ -207,12 +207,11 @@
 
 .. function:: create_connection(address[, timeout])
 
-   Connects to the *address* received (as usual, a ``(host, port)`` pair), with an
-   optional timeout for the connection.  Especially useful for higher-level
-   protocols, it is not normally used directly from application-level code.
-   Passing the optional *timeout* parameter will set the timeout on the socket
-   instance (if it is not given or ``None``, the global default timeout setting is
-   used).
+   Convenience function.  Connect to *address* (a 2-tuple ``(host, port)``),
+   and return the socket object.  Passing the optional *timeout* parameter will
+   set the timeout on the socket instance before attempting to connect.  If no
+   *timeout* is supplied, the global default timeout setting returned by
+   :func:`getdefaulttimeout` is used.
 
    .. versionadded:: 2.6
 
@@ -481,7 +480,7 @@
 
 .. seealso::
 
-   Module :mod:`socketserver`
+   Module :mod:`SocketServer`
       Classes that simplify writing network servers.
 
 

Modified: python/branches/okkoto-sizeof/Doc/library/socketserver.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/socketserver.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/socketserver.rst	Wed Jun  4 11:24:23 2008
@@ -1,19 +1,18 @@
-:mod:`socketserver` --- A framework for network servers
+
+:mod:`SocketServer` --- A framework for network servers
 =======================================================
 
 .. module:: SocketServer
-   :synopsis: Old name for the socketserver module.
-
-.. module:: socketserver
    :synopsis: A framework for network servers.
 
 .. note::
-   The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
-   Python 3.0.  It is importable under both names in Python 2.6 and the rest of
-   the 2.x series.
 
+   The :mod:`SocketServer` module has been renamed to `socketserver` in Python
+   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
+   your sources to 3.0.
 
-The :mod:`socketserver` module simplifies the task of writing network servers.
+
+The :mod:`SocketServer` module simplifies the task of writing network servers.
 
 There are four basic server classes: :class:`TCPServer` uses the Internet TCP
 protocol, which provides for continuous streams of data between the client and
@@ -220,7 +219,7 @@
 users of the server object.
 
 .. XXX should the default implementations of these be documented, or should
-   it be assumed that the user will look at socketserver.py?
+   it be assumed that the user will look at SocketServer.py?
 
 
 .. function:: finish_request()
@@ -244,8 +243,8 @@
 
 .. function:: handle_timeout()
 
-   This function is called when the :attr:`timeout` attribute has been set to a 
-   value other than :const:`None` and the timeout period has passed with no 
+   This function is called when the :attr:`timeout` attribute has been set to a
+   value other than :const:`None` and the timeout period has passed with no
    requests being received.  The default action for forking servers is
    to collect the status of any child processes that have exited, while
    in threading servers this method does nothing.
@@ -292,27 +291,28 @@
 
 .. function:: finish()
 
-   Called after the :meth:`handle` method to perform any clean-up actions required.
-   The default implementation does nothing.  If :meth:`setup` or :meth:`handle`
-   raise an exception, this function will not be called.
+   Called after the :meth:`handle` method to perform any clean-up actions
+   required.  The default implementation does nothing.  If :meth:`setup` or
+   :meth:`handle` raise an exception, this function will not be called.
 
 
 .. function:: handle()
 
-   This function must do all the work required to service a request. The default
-   implementation does nothing. Several instance attributes are available to it;
-   the request is available as :attr:`self.request`; the client address as
-   :attr:`self.client_address`; and the server instance as :attr:`self.server`, in
-   case it needs access to per-server information.
-
-   The type of :attr:`self.request` is different for datagram or stream services.
-   For stream services, :attr:`self.request` is a socket object; for datagram
-   services, :attr:`self.request` is a string. However, this can be hidden by using
-   the  request handler subclasses :class:`StreamRequestHandler` or
-   :class:`DatagramRequestHandler`, which override the :meth:`setup` and
-   :meth:`finish` methods, and provide :attr:`self.rfile` and :attr:`self.wfile`
-   attributes. :attr:`self.rfile` and :attr:`self.wfile` can be read or written,
-   respectively, to get the request data or return data to the client.
+   This function must do all the work required to service a request.  The
+   default implementation does nothing.  Several instance attributes are
+   available to it; the request is available as :attr:`self.request`; the client
+   address as :attr:`self.client_address`; and the server instance as
+   :attr:`self.server`, in case it needs access to per-server information.
+
+   The type of :attr:`self.request` is different for datagram or stream
+   services.  For stream services, :attr:`self.request` is a socket object; for
+   datagram services, :attr:`self.request` is a pair of string and socket.
+   However, this can be hidden by using the request handler subclasses
+   :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which
+   override the :meth:`setup` and :meth:`finish` methods, and provide
+   :attr:`self.rfile` and :attr:`self.wfile` attributes.  :attr:`self.rfile` and
+   :attr:`self.wfile` can be read or written, respectively, to get the request
+   data or return data to the client.
 
 
 .. function:: setup()
@@ -320,3 +320,217 @@
    Called before the :meth:`handle` method to perform any initialization actions
    required.  The default implementation does nothing.
 
+
+Examples
+--------
+
+:class:`SocketServer.TCPServer` Example
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This is the server side::
+
+   import SocketServer
+
+   class MyTCPHandler(SocketServer.BaseRequestHandler):
+       """
+       The RequestHandler class for our server.
+
+       It is instantiated once per connection to the server, and must
+       override the handle() method to implement communication to the
+       client.
+       """
+
+       def handle(self):
+           # self.request is the TCP socket connected to the client
+           self.data = self.request.recv(1024).strip()
+           print "%s wrote:" % self.client_address[0]
+           print self.data
+           # just send back the same data, but upper-cased
+           self.request.send(self.data.upper())
+
+   if __name__ == "__main__":
+       HOST, PORT = "localhost", 9999
+
+       # Create the server, binding to localhost on port 9999
+       server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
+
+       # Activate the server; this will keep running until you
+       # interrupt the program with Ctrl-C
+       server.serve_forever()
+
+An alternative request handler class that makes use of streams (file-like
+objects that simplify communication by providing the standard file interface)::
+
+   class MyTCPHandler(SocketServer.StreamRequestHandler):
+
+       def handle(self):
+           # self.rfile is a file-like object created by the handler;
+           # we can now use e.g. readline() instead of raw recv() calls
+           self.data = self.rfile.readline().strip()
+           print "%s wrote:" % self.client_address[0]
+           print self.data
+           # Likewise, self.wfile is a file-like object used to write back
+           # to the client
+           self.wfile.write(self.data.upper())
+
+The difference is that the ``readline()`` call in the second handler will call
+``recv()`` multiple times until it encounters a newline character, while the
+single ``recv()`` call in the first handler will just return what has been sent
+from the client in one ``send()`` call.
+
+
+This is the client side::
+
+   import socket
+   import sys
+
+   HOST, PORT = "localhost", 9999
+   data = " ".join(sys.argv[1:])
+
+   # Create a socket (SOCK_STREAM means a TCP socket)
+   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+
+   # Connect to server and send data
+   sock.connect((HOST, PORT))
+   sock.send(data + "\n")
+
+   # Receive data from the server and shut down
+   received = sock.recv(1024)
+   sock.close()
+
+   print "Sent:     %s" % data
+   print "Received: %s" % received
+
+
+The output of the example should look something like this:
+
+Server::
+
+   $ python TCPServer.py
+   127.0.0.1 wrote:
+   hello world with TCP
+   127.0.0.1 wrote:
+   python is nice
+
+Client::
+
+   $ python TCPClient.py hello world with TCP
+   Sent:     hello world with TCP
+   Received: HELLO WORLD WITH TCP
+   $ python TCPClient.py python is nice
+   Sent:     python is nice
+   Received: PYTHON IS NICE
+
+
+:class:`SocketServer.UDPServer` Example
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This is the server side::
+
+   import SocketServer
+
+   class MyUDPHandler(SocketServer.BaseRequestHandler):
+       """
+       This class works similar to the TCP handler class, except that
+       self.request consists of a pair of data and client socket, and since
+       there is no connection the client address must be given explicitly
+       when sending data back via sendto().
+       """
+
+       def handle(self):
+           data = self.request[0].strip()
+           socket = self.request[1]
+           print "%s wrote:" % self.client_address[0]
+           print data
+           socket.sendto(data.upper(), self.client_address)
+
+   if __name__ == "__main__":
+      HOST, PORT = "localhost", 9999
+      server = SocketServer.UDPServer((HOST, PORT), BaseUDPRequestHandler)
+      server.serve_forever()
+
+This is the client side::
+
+   import socket
+   import sys
+
+   HOST, PORT = "localhost"
+   data = " ".join(sys.argv[1:])
+
+   # SOCK_DGRAM is the socket type to use for UDP sockets
+   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+
+   # As you can see, there is no connect() call; UDP has no connections.
+   # Instead, data is directly sent to the recipient via sendto().
+   sock.sendto(data + "\n", (HOST, PORT))
+   received = sock.recv(1024)
+
+   print "Sent:     %s" % data
+   print "Received: %s" % received
+
+The output of the example should look exactly like for the TCP server example.
+
+
+Asynchronous Mixins
+~~~~~~~~~~~~~~~~~~~
+
+To build asynchronous handlers, use the :class:`ThreadingMixIn` and
+:class:`ForkingMixIn` classes.
+
+An example for the :class:`ThreadingMixIn` class::
+
+   import socket
+   import threading
+   import SocketServer
+
+   class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
+
+       def handle(self):
+           data = self.request.recv(1024)
+           cur_thread = threading.currentThread()
+           response = "%s: %s" % (cur_thread.getName(), data)
+           self.request.send(response)
+
+   class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
+       pass
+
+   def client(ip, port, message):
+       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+       sock.connect((ip, port))
+       sock.send(message)
+       response = sock.recv(1024)
+       print "Received: %s" % response
+       sock.close()
+
+   if __name__ == "__main__":
+       # Port 0 means to select an arbitrary unused port
+       HOST, PORT = "localhost", 0
+
+       server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
+       ip, port = server.server_address
+
+       # Start a thread with the server -- that thread will then start one
+       # more thread for each request
+       server_thread = threading.Thread(target=server.serve_forever)
+       # Exit the server thread when the main thread terminates
+       server_thread.setDaemon(True)
+       server_thread.start()
+       print "Server loop running in thread:", t.getName()
+
+       client(ip, port, "Hello World 1")
+       client(ip, port, "Hello World 2")
+       client(ip, port, "Hello World 3")
+
+       server.shutdown()
+
+The output of the example should look something like this::
+
+   $ python ThreadedTCPServer.py
+   Server loop running in thread: Thread-1
+   Received: Thread-2: Hello World 1
+   Received: Thread-3: Hello World 2
+   Received: Thread-4: Hello World 3
+
+
+The :class:`ForkingMixIn` class is used in the same way, except that the server
+will spawn a new process for each request.

Modified: python/branches/okkoto-sizeof/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/stdtypes.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/stdtypes.rst	Wed Jun  4 11:24:23 2008
@@ -2165,6 +2165,13 @@
    .. versionadded:: 2.3
 
 
+.. attribute:: file.errors
+
+   The Unicode error handler used to along with the encoding.
+
+   .. versionadded:: 2.6
+
+
 .. attribute:: file.mode
 
    The I/O mode for the file.  If the file was created using the :func:`open`

Modified: python/branches/okkoto-sizeof/Doc/library/string.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/string.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/string.rst	Wed Jun  4 11:24:23 2008
@@ -103,16 +103,16 @@
    :func:`strip` and :func:`split` is undefined.
 
 
-.. _string-formatting:
+.. _new-string-formatting:
 
 String Formatting
 -----------------
 
 Starting in Python 2.6, the built-in str and unicode classes provide the ability
-to do complex variable substitutions and value formatting via the :func:`format`
-method described in :pep:`3101`.  The :class:`Formatter` class in the
-:mod:`string` module allows you to create and customize your own string
-formatting behaviors using the same implementation as the built-in
+to do complex variable substitutions and value formatting via the
+:meth:`str.format` method described in :pep:`3101`.  The :class:`Formatter`
+class in the :mod:`string` module allows you to create and customize your own
+string formatting behaviors using the same implementation as the built-in
 :meth:`format` method.
 
 .. class:: Formatter

Modified: python/branches/okkoto-sizeof/Doc/library/struct.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/struct.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/struct.rst	Wed Jun  4 11:24:23 2008
@@ -233,6 +233,16 @@
 native size and alignment are in effect; standard size and alignment does not
 enforce any alignment.
 
+Unpacked fields can be named by assigning them to variables or by wrapping
+the result in a named tuple::
+
+    >>> record = 'raymond   \x32\x12\x08\x01\x08'
+    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
+
+    >>> from collections import namedtuple
+    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
+    >>> Student._make(unpack('<10sHHb', s))
+    Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)
 
 .. seealso::
 

Modified: python/branches/okkoto-sizeof/Doc/library/sys.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/sys.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/sys.rst	Wed Jun  4 11:24:23 2008
@@ -531,6 +531,11 @@
    is at least 2\*\*31-1.  The largest negative integer is ``-maxint-1`` --- the
    asymmetry results from the use of 2's complement binary arithmetic.
 
+.. data:: maxsize
+
+   The largest positive integer supported by the platform's Py_ssize_t type,
+   and thus the maximum size lists, strings, dicts, and many other containers
+   can have.
 
 .. data:: maxunicode
 

Modified: python/branches/okkoto-sizeof/Doc/library/tarfile.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/tarfile.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/tarfile.rst	Wed Jun  4 11:24:23 2008
@@ -34,10 +34,8 @@
   character devices and block devices and is able to acquire and restore file
   information like timestamp, access permissions and owner.
 
-* can handle tape devices.
 
-
-.. function:: open(name[, mode[, fileobj[, bufsize]]], **kwargs)
+.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)
 
    Return a :class:`TarFile` object for the pathname *name*. For detailed
    information on :class:`TarFile` objects and the keyword arguments that are
@@ -78,7 +76,7 @@
    for *name*. It is supposed to be at position 0.
 
    For special purposes, there is a second format for *mode*:
-   ``'filemode|[compression]'``.  :func:`open` will return a :class:`TarFile`
+   ``'filemode|[compression]'``.  :func:`tarfile.open` will return a :class:`TarFile`
    object that processes its data as a stream of blocks.  No random seeking will
    be done on the file. If given, *fileobj* may be any object that has a
    :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
@@ -116,7 +114,7 @@
 .. class:: TarFile
 
    Class for reading and writing tar archives. Do not use this class directly,
-   better use :func:`open` instead. See :ref:`tarfile-objects`.
+   better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
 
 
 .. function:: is_tarfile(name)
@@ -125,7 +123,7 @@
    module can read.
 
 
-.. class:: TarFileCompat(filename[, mode[, compression]])
+.. class:: TarFileCompat(filename, mode='r', compression=TAR_PLAIN)
 
    Class for limited access to tar archives with a :mod:`zipfile`\ -like interface.
    Please consult the documentation of the :mod:`zipfile` module for more details.
@@ -167,16 +165,17 @@
 
 .. exception:: ExtractError
 
-   Is raised for *non-fatal* errors when using :meth:`extract`, but only if
+   Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if
    :attr:`TarFile.errorlevel`\ ``== 2``.
 
 
 .. exception:: HeaderError
 
-   Is raised by :meth:`frombuf` if the buffer it gets is invalid.
+   Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid.
 
    .. versionadded:: 2.6
 
+
 Each of the following constants defines a tar archive format that the
 :mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
 details.
@@ -202,12 +201,21 @@
    The default format for creating archives. This is currently :const:`GNU_FORMAT`.
 
 
+The following variables are available on module level:
+
+
+.. data:: ENCODING
+
+   The default character encoding i.e. the value from either
+   :func:`sys.getfilesystemencoding` or :func:`sys.getdefaultencoding`.
+
+
 .. seealso::
 
    Module :mod:`zipfile`
       Documentation of the :mod:`zipfile` standard module.
 
-   `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/tar_134.html#SEC134>`_
+   `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
       Documentation for tar archive files, including GNU tar extensions.
 
 
@@ -223,7 +231,7 @@
 object, see :ref:`tarinfo-objects` for details.
 
 
-.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=None, errors=None, pax_headers=None, debug=0, errorlevel=0)
+.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors=None, pax_headers=None, debug=0, errorlevel=0)
 
    All following arguments are optional and can be accessed as instance attributes
    as well.
@@ -254,18 +262,18 @@
 
    .. versionadded:: 2.6
 
-   If *dereference* is ``False``, add symbolic and hard links to the archive. If it
-   is ``True``, add the content of the target files to the archive. This has no
+   If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it
+   is :const:`True`, add the content of the target files to the archive. This has no
    effect on systems that do not support symbolic links.
 
-   If *ignore_zeros* is ``False``, treat an empty block as the end of the archive.
-   If it is *True*, skip empty (and invalid) blocks and try to get as many members
+   If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive.
+   If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members
    as possible. This is only useful for reading concatenated or damaged archives.
 
    *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
    messages). The messages are written to ``sys.stderr``.
 
-   If *errorlevel* is ``0``, all errors are ignored when using :meth:`extract`.
+   If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`.
    Nevertheless, they appear as error messages in the debug output, when debugging
    is enabled.  If ``1``, all *fatal* errors are raised as :exc:`OSError` or
    :exc:`IOError` exceptions. If ``2``, all *non-fatal* errors are raised as
@@ -285,8 +293,8 @@
 
 .. method:: TarFile.open(...)
 
-   Alternative constructor. The :func:`open` function on module level is actually a
-   shortcut to this classmethod. See section :ref:`tarfile-mod` for details.
+   Alternative constructor. The :func:`tarfile.open` function is actually a
+   shortcut to this classmethod.
 
 
 .. method:: TarFile.getmember(name)
@@ -322,11 +330,11 @@
 .. method:: TarFile.next()
 
    Return the next member of the archive as a :class:`TarInfo` object, when
-   :class:`TarFile` is opened for reading. Return ``None`` if there is no more
+   :class:`TarFile` is opened for reading. Return :const:`None` if there is no more
    available.
 
 
-.. method:: TarFile.extractall([path[, members]])
+.. method:: TarFile.extractall(path=".", members=None)
 
    Extract all members from the archive to the current working directory or
    directory *path*. If optional *members* is given, it must be a subset of the
@@ -346,7 +354,7 @@
    .. versionadded:: 2.5
 
 
-.. method:: TarFile.extract(member[, path])
+.. method:: TarFile.extract(member, path="")
 
    Extract a member from the archive to the current working directory, using its
    full name. Its file information is extracted as accurately as possible. *member*
@@ -355,9 +363,8 @@
 
    .. note::
 
-      Because the :meth:`extract` method allows random access to a tar archive there
-      are some issues you must take care of yourself. See the description for
-      :meth:`extractall` above.
+      The :meth:`extract` method does not take care of several extraction issues.
+      In most cases you should consider using the :meth:`extractall` method.
 
    .. warning::
 
@@ -369,7 +376,7 @@
    Extract a member from the archive as a file object. *member* may be a filename
    or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
    is returned. If *member* is a link, a file-like object is constructed from the
-   link's target. If *member* is none of the above, ``None`` is returned.
+   link's target. If *member* is none of the above, :const:`None` is returned.
 
    .. note::
 
@@ -377,7 +384,7 @@
       :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`.
 
 
-.. method:: TarFile.add(name[, arcname[, recursive[, exclude]]])
+.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None)
 
    Add the file *name* to the archive. *name* may be any type of file (directory,
    fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name
@@ -391,7 +398,7 @@
       Added the *exclude* parameter.
 
 
-.. method:: TarFile.addfile(tarinfo[, fileobj])
+.. method:: TarFile.addfile(tarinfo, fileobj=None)
 
    Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
    ``tarinfo.size`` bytes are read from it and added to the archive.  You can
@@ -403,7 +410,7 @@
       avoid irritation about the file size.
 
 
-.. method:: TarFile.gettarinfo([name[, arcname[, fileobj]]])
+.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
 
    Create a :class:`TarInfo` object for either the file *name* or the file object
    *fileobj* (using :func:`os.fstat` on its file descriptor).  You can modify some
@@ -451,7 +458,7 @@
 :meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
 
 
-.. class:: TarInfo([name])
+.. class:: TarInfo(name="")
 
    Create a :class:`TarInfo` object.
 
@@ -472,7 +479,7 @@
    .. versionadded:: 2.6
 
 
-.. method:: TarInfo.tobuf([format[, encoding [, errors]]])
+.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict')
 
    Create a string buffer from a :class:`TarInfo` object. For information on the
    arguments see the constructor of the :class:`TarFile` class.
@@ -604,6 +611,21 @@
    tar.extractall()
    tar.close()
 
+How to extract a subset of a tar archive with :meth:`TarFile.extractall` using
+a generator function instead of a list::
+
+   import os
+   import tarfile
+
+   def py_files(members):
+       for tarinfo in members:
+           if os.path.splitext(tarinfo.name)[1] == ".py":
+               yield tarinfo
+
+   tar = tarfile.open("sample.tar.gz")
+   tar.extractall(members=py_files(tar))
+   tar.close()
+
 How to create an uncompressed tar archive from a list of filenames::
 
    import tarfile
@@ -626,28 +648,6 @@
            print "something else."
    tar.close()
 
-How to create a tar archive with faked information::
-
-   import tarfile
-   tar = tarfile.open("sample.tar.gz", "w:gz")
-   for name in namelist:
-       tarinfo = tar.gettarinfo(name, "fakeproj-1.0/" + name)
-       tarinfo.uid = 123
-       tarinfo.gid = 456
-       tarinfo.uname = "johndoe"
-       tarinfo.gname = "fake"
-       tar.addfile(tarinfo, file(name))
-   tar.close()
-
-The *only* way to extract an uncompressed tar stream from ``sys.stdin``::
-
-   import sys
-   import tarfile
-   tar = tarfile.open(mode="r|", fileobj=sys.stdin)
-   for tarinfo in tar:
-       tar.extract(tarinfo)
-   tar.close()
-
 
 .. _tar-formats:
 

Modified: python/branches/okkoto-sizeof/Doc/library/telnetlib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/telnetlib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/telnetlib.rst	Wed Jun  4 11:24:23 2008
@@ -28,6 +28,11 @@
    :class:`Telnet` represents a connection to a Telnet server. The instance is
    initially not connected by default; the :meth:`open` method must be used to
    establish a connection.  Alternatively, the host name and optional port
+   and timeout can be passed to the constructor, in which case the connection to
+   the server will be established before the constructor returns.  The optional
+   *timeout* parameter specifies a timeout in seconds for the connection attempt (if
+   not specified, the global default timeout setting will be used).
+
    number can be passed to the constructor, to, in which case the connection to
    the server will be established before the constructor returns. The optional
    *timeout* parameter specifies a timeout in seconds for blocking operations
@@ -128,8 +133,7 @@
    Connect to a host. The optional second argument is the port number, which
    defaults to the standard Telnet port (23). The optional *timeout* parameter
    specifies a timeout in seconds for blocking operations like the connection
-   attempt (if not specified, or passed as None, the global default timeout
-   setting will be used).
+   attempt (if not specified, the global default timeout setting will be used).
 
    Do not try to reopen an already connected instance.
 

Modified: python/branches/okkoto-sizeof/Doc/library/test.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/test.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/test.rst	Wed Jun  4 11:24:23 2008
@@ -185,6 +185,14 @@
 .. module:: test.test_support
    :synopsis: Support for Python regression tests.
 
+.. note::
+
+   The :mod:`test.test_support` module has been renamed to :mod:`test.support`
+   in Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
+
+
 
 The :mod:`test.test_support` module provides support for Python's regression
 tests.

Modified: python/branches/okkoto-sizeof/Doc/library/thread.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/thread.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/thread.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,15 @@
-
 :mod:`thread` --- Multiple threads of control
 =============================================
 
 .. module:: thread
    :synopsis: Create multiple threads of control within one interpreter.
 
+.. note::
+   The :mod:`thread` module has been renamed to :mod:`_thread` in Python 3.0.
+   The :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0; however, you should consider using the high-lever
+   :mod:`threading` module instead.
+
 
 .. index::
    single: light-weight processes

Modified: python/branches/okkoto-sizeof/Doc/library/threading.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/threading.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/threading.rst	Wed Jun  4 11:24:23 2008
@@ -8,7 +8,7 @@
 
 This module constructs higher-level threading interfaces on top of the  lower
 level :mod:`thread` module.
-See also the :mod:`mutex` and :mod:`queue` modules.
+See also the :mod:`mutex` and :mod:`Queue` modules.
 
 The :mod:`dummy_threading` module is provided for situations where
 :mod:`threading` cannot be used because :mod:`thread` is missing.
@@ -651,6 +651,17 @@
    constructor.
 
 
+.. method:: Thread.getIdent()
+
+   Return the 'thread identifier' of this thread or None if the thread has not
+   been started.  This is a nonzero integer.  See the :mod:`thread` module's
+   :func:`get_ident()` function.  Thread identifiers may be recycled when a
+   thread exits and another thread is created.  The identifier is returned
+   even after the thread has exited.
+
+   .. versionadded:: 2.6
+
+
 .. method:: Thread.isAlive()
 
    Return whether the thread is alive.

Modified: python/branches/okkoto-sizeof/Doc/library/tkinter.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/tkinter.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/tkinter.rst	Wed Jun  4 11:24:23 2008
@@ -11,6 +11,11 @@
 platforms, as well as on Windows and Macintosh systems.  (Tk itself is not part
 of Python; it is maintained at ActiveState.)
 
+.. note::
+
+   :mod:`Tkinter` has been renamed to :mod:`tkinter` in Python 3.0.  The
+   :term:`2to3` tool will automatically adapt imports when converting your
+   sources to 3.0.
 
 .. seealso::
 
@@ -107,6 +112,9 @@
 :mod:`turtle`
    Turtle graphics in a Tk window.
 
+These have been renamed as well in Python 3.0; they were all made submodules of
+the new ``tkinter`` package.
+
 
 Tkinter Life Preserver
 ----------------------

Modified: python/branches/okkoto-sizeof/Doc/library/urllib2.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/urllib2.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/urllib2.rst	Wed Jun  4 11:24:23 2008
@@ -27,9 +27,9 @@
    returns a string in this format.
 
    The optional *timeout* parameter specifies a timeout in seconds for blocking
-   operations like the connection attempt (if not specified, or passed as
-   ``None``, the global default timeout setting will be used).  This actually
-   only works for HTTP, HTTPS, FTP and FTPS connections.
+   operations like the connection attempt (if not specified, the global default
+   timeout setting will be used).  This actually only works for HTTP, HTTPS,
+   FTP and FTPS connections.
 
    This function returns a file-like object with two additional methods:
 
@@ -411,9 +411,9 @@
    the same as those of :func:`urlopen` (which simply calls the :meth:`open`
    method on the currently installed global :class:`OpenerDirector`).  The
    optional *timeout* parameter specifies a timeout in seconds for blocking
-   operations like the connection attempt (if not specified, or passed as
-   ``None``, the global default timeout setting will be used; this actually only
-   works for HTTP, HTTPS, FTP and FTPS connections).
+   operations like the connection attempt (if not specified, the global default
+   timeout setting will be usedi). The timeout feature actually works only for
+   HTTP, HTTPS, FTP and FTPS connections).
 
    .. versionchanged:: 2.6
       *timeout* was added.

Modified: python/branches/okkoto-sizeof/Doc/library/userdict.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/userdict.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/userdict.rst	Wed Jun  4 11:24:23 2008
@@ -100,6 +100,12 @@
    defaulting to the empty list ``[]``.  *list* can be any iterable, e.g. a
    real Python list or a :class:`UserList` object.
 
+   .. note::
+      The :class:`UserList` class has been moved to the :mod:`collections`
+      module in Python 3.0. The :term:`2to3` tool will automatically adapt
+      imports when converting your sources to 3.0.
+
+
 In addition to supporting the methods and operations of mutable sequences (see
 section :ref:`typesseq`), :class:`UserList` instances provide the following
 attribute:
@@ -167,6 +173,12 @@
    :class:`UserString` (or a subclass) or an arbitrary sequence which can be
    converted into a string using the built-in :func:`str` function.
 
+   .. note::
+      The :class:`UserString` class has been moved to the :mod:`collections`
+      module in Python 3.0. The :term:`2to3` tool will automatically adapt
+      imports when converting your sources to 3.0.
+
+
 
 .. class:: MutableString([sequence])
 
@@ -178,6 +190,9 @@
    mutable object as dictionary key, which would be otherwise very error prone and
    hard to track down.
 
+   .. deprecated:: 2.6
+      The :class:`MutableString` class has been removed in Python 3.0.
+
 In addition to supporting the methods and operations of string and Unicode
 objects (see section :ref:`string-methods`), :class:`UserString` instances
 provide the following attribute:

Modified: python/branches/okkoto-sizeof/Doc/library/whichdb.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/whichdb.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/whichdb.rst	Wed Jun  4 11:24:23 2008
@@ -1,10 +1,14 @@
-
 :mod:`whichdb` --- Guess which DBM module created a database
 ============================================================
 
 .. module:: whichdb
    :synopsis: Guess which DBM-style module created a given database.
 
+.. note::
+   The :mod:`whichdb` module's only function has been put into the :mod:`dbm`
+   module in Python 3.0.  The :term:`2to3` tool will automatically adapt imports
+   when converting your sources to 3.0.
+
 
 The single function in this module attempts to guess which of the several simple
 database modules available--\ :mod:`dbm`, :mod:`gdbm`, or :mod:`dbhash`\

Modified: python/branches/okkoto-sizeof/Doc/library/xmlrpclib.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/xmlrpclib.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/xmlrpclib.rst	Wed Jun  4 11:24:23 2008
@@ -6,6 +6,11 @@
 .. moduleauthor:: Fredrik Lundh <fredrik at pythonware.com>
 .. sectionauthor:: Eric S. Raymond <esr at snark.thyrsus.com>
 
+.. note::
+   The :mod:`xmlrpclib` module has been renamed to :mod:`xmlrpc.client` in
+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
+   converting your sources to 3.0.
+
 
 .. XXX Not everything is documented yet.  It might be good to describe
    Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.

Modified: python/branches/okkoto-sizeof/Doc/library/zipfile.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/library/zipfile.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/library/zipfile.rst	Wed Jun  4 11:24:23 2008
@@ -155,11 +155,11 @@
 .. method:: ZipFile.open(name[, mode[, pwd]])
 
    Extract a member from the archive as a file-like object (ZipExtFile). *name* is
-   the name of the file in the archive. The *mode* parameter, if included, must be
-   one of the following: ``'r'`` (the  default), ``'U'``, or ``'rU'``. Choosing
-   ``'U'`` or  ``'rU'`` will enable universal newline support in the read-only
-   object. *pwd* is the password used for encrypted files.  Calling  :meth:`open`
-   on a closed ZipFile will raise a  :exc:`RuntimeError`.
+   the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
+   parameter, if included, must be one of the following: ``'r'`` (the  default),
+   ``'U'``, or ``'rU'``. Choosing ``'U'`` or  ``'rU'`` will enable universal newline
+   support in the read-only object. *pwd* is the password used for encrypted files.
+   Calling  :meth:`open` on a closed ZipFile will raise a  :exc:`RuntimeError`.
 
    .. note::
 
@@ -178,16 +178,22 @@
       create a new file object that will be held by the ZipExtFile, allowing it to
       operate independently of the  ZipFile.
 
+   .. note::
+
+      The :meth:`open`, :meth:`read` and :meth:`extract` methods can take a filename
+      or a :class:`ZipInfo` object.  You will appreciate this when trying to read a
+      ZIP file that contains members with duplicate names.
+
    .. versionadded:: 2.6
 
 
 .. method:: ZipFile.extract(member[, path[, pwd]])
 
-   Extract a member from the archive to the current working directory, using its
-   full name.  Its file information is extracted as accurately as possible.
-   *path* specifies a different directory to extract to.   *member* can be a
-   filename or a :class:`ZipInfo` object.  *pwd* is the password used for
-   encrypted files.
+   Extract a member from the archive to the current working directory; *member*
+   must be its full name or a :class:`ZipInfo` object).  Its file information is
+   extracted as accurately as possible.  *path* specifies a different directory
+   to extract to.  *member* can be a filename or a :class:`ZipInfo` object.
+   *pwd* is the password used for encrypted files.
 
    .. versionadded:: 2.6
 
@@ -216,13 +222,14 @@
 
 .. method:: ZipFile.read(name[, pwd])
 
-   Return the bytes of the file in the archive.  The archive must be open for read
-   or append. *pwd* is the password used for encrypted  files and, if specified, it
-   will override the default password set with :meth:`setpassword`.  Calling
+   Return the bytes of the file *name* in the archive.  *name* is the name of the
+   file in the archive, or a :class:`ZipInfo` object.  The archive must be open for
+   read or append. *pwd* is the password used for encrypted  files and, if specified,
+   it will override the default password set with :meth:`setpassword`.  Calling
    :meth:`read` on a closed ZipFile  will raise a :exc:`RuntimeError`.
 
    .. versionchanged:: 2.6
-      *pwd* was added.
+      *pwd* was added, and *name* can now be a :class:`ZipInfo` object.
 
 
 .. method:: ZipFile.testzip()

Modified: python/branches/okkoto-sizeof/Doc/reference/expressions.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/reference/expressions.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/reference/expressions.rst	Wed Jun  4 11:24:23 2008
@@ -1318,10 +1318,9 @@
 
 .. rubric:: Footnotes
 
-.. [#] In Python 2.3, a list comprehension "leaks" the control variables of each
-   ``for`` it contains into the containing scope.  However, this behavior is
-   deprecated, and relying on it will not work once this bug is fixed in a future
-   release.
+.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
+   variables of each ``for`` it contains into the containing scope.  However, this 
+   behavior is deprecated, and relying on it will not work in Python 3.0
 
 .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
    true numerically due to roundoff.  For example, and assuming a platform on which

Modified: python/branches/okkoto-sizeof/Doc/reference/simple_stmts.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/reference/simple_stmts.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/reference/simple_stmts.rst	Wed Jun  4 11:24:23 2008
@@ -534,7 +534,7 @@
 If no expressions are present, :keyword:`raise` re-raises the last exception
 that was active in the current scope.  If no exception is active in the current
 scope, a :exc:`TypeError` exception is raised indicating that this is an error
-(if running under IDLE, a :exc:`queue.Empty` exception is raised instead).
+(if running under IDLE, a :exc:`Queue.Empty` exception is raised instead).
 
 Otherwise, :keyword:`raise` evaluates the expressions to get three objects,
 using ``None`` as the value of omitted expressions.  The first two objects are

Modified: python/branches/okkoto-sizeof/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/okkoto-sizeof/Doc/tools/sphinxext/pyspecific.py	Wed Jun  4 11:24:23 2008
@@ -20,5 +20,71 @@
     return [refnode], []
 
 
+# Support for building "topic help" for pydoc
+
+pydoc_topic_labels = [
+    'assert', 'assignment', 'atom-identifiers', 'atom-literals',
+    'attribute-access', 'attribute-references', 'augassign', 'binary',
+    'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
+    'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
+    'break', 'callable-types', 'calls', 'class', 'coercion-rules',
+    'comparisons', 'compound', 'context-managers', 'continue', 'conversions',
+    'customization', 'debugger', 'del', 'dict', 'dynamic-features', 'else',
+    'exceptions', 'exec', 'execmodel', 'exprlists', 'floating', 'for',
+    'formatstrings', 'function', 'global', 'id-classes', 'identifiers', 'if',
+    'imaginary', 'import', 'in', 'integers', 'lambda', 'lists', 'naming',
+    'numbers', 'numeric-types', 'objects', 'operator-summary', 'pass', 'power',
+    'print', 'raise', 'return', 'sequence-methods', 'sequence-types',
+    'shifting', 'slicings', 'specialattrs', 'specialnames',
+    'string-conversions', 'string-methods', 'strings', 'subscriptions', 'truth',
+    'try', 'types', 'typesfunctions', 'typesmapping', 'typesmethods',
+    'typesmodules', 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with',
+    'yield'
+]
+
+from os import path
+from time import asctime
+from pprint import pformat
+from docutils.io import StringOutput
+from docutils.utils import new_document
+from sphinx.builder import Builder
+from sphinx.textwriter import TextWriter
+
+class PydocTopicsBuilder(Builder):
+    name = 'pydoc-topics'
+
+    def init(self):
+        self.topics = {}
+
+    def get_outdated_docs(self):
+        return 'all pydoc topics'
+
+    def get_target_uri(self, docname, typ=None):
+        return ''  # no URIs
+
+    def write(self, *ignored):
+        writer = TextWriter(self)
+        for label in self.status_iterator(pydoc_topic_labels, 'building topics... '):
+            if label not in self.env.labels:
+                self.warn('label %r not in documentation' % label)
+                continue
+            docname, labelid, sectname = self.env.labels[label]
+            doctree = self.env.get_and_resolve_doctree(docname, self)
+            document = new_document('<section node>')
+            document.append(doctree.ids[labelid])
+            destination = StringOutput(encoding='utf-8')
+            writer.write(document, destination)
+            self.topics[label] = writer.output
+
+    def finish(self):
+        f = open(path.join(self.outdir, 'pydoc_topics.py'), 'w')
+        try:
+            f.write('# Autogenerated by Sphinx on %s\n' % asctime())
+            f.write('topics = ' + pformat(self.topics) + '\n')
+        finally:
+            f.close()
+
+
 def setup(app):
     app.add_role('issue', issue_role)
+    app.add_builder(PydocTopicsBuilder)

Modified: python/branches/okkoto-sizeof/Doc/tutorial/controlflow.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/controlflow.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/controlflow.rst	Wed Jun  4 11:24:23 2008
@@ -445,8 +445,8 @@
 up in a tuple.  Before the variable number of arguments, zero or more normal
 arguments may occur. ::
 
-   def fprintf(file, format, *args):
-       file.write(format % args)
+   def write_multiple_items(file, separator, *args):
+       file.write(separator.join(args))
 
 
 .. _tut-unpacking-arguments:

Modified: python/branches/okkoto-sizeof/Doc/tutorial/datastructures.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/datastructures.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/datastructures.rst	Wed Jun  4 11:24:23 2008
@@ -550,7 +550,7 @@
    >>> questions = ['name', 'quest', 'favorite color']
    >>> answers = ['lancelot', 'the holy grail', 'blue']
    >>> for q, a in zip(questions, answers):
-   ...     print 'What is your %s?  It is %s.' % (q, a)
+   ...     print 'What is your {0}?  It is {1}.'.format(q, a)
    ...	
    What is your name?  It is lancelot.
    What is your quest?  It is the holy grail.

Modified: python/branches/okkoto-sizeof/Doc/tutorial/errors.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/errors.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/errors.rst	Wed Jun  4 11:24:23 2008
@@ -132,7 +132,7 @@
        s = f.readline()
        i = int(s.strip())
    except IOError as (errno, strerror):
-       print "I/O error(%s): %s" % (errno, strerror)
+       print "I/O error({0}): {1}".format(errno, strerror)
    except ValueError:
        print "Could not convert data to an integer."
    except:

Modified: python/branches/okkoto-sizeof/Doc/tutorial/floatingpoint.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/floatingpoint.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/floatingpoint.rst	Wed Jun  4 11:24:23 2008
@@ -132,9 +132,8 @@
 While pathological cases do exist, for most casual use of floating-point
 arithmetic you'll see the result you expect in the end if you simply round the
 display of your final results to the number of decimal digits you expect.
-:func:`str` usually suffices, and for finer control see the discussion of
-Python's ``%`` format operator: the ``%g``, ``%f`` and ``%e`` format codes
-supply flexible and easy ways to round float results for display.
+:func:`str` usually suffices, and for finer control see the :meth:`str.format`
+method's format specifiers in :ref:`formatstrings`.
 
 
 .. _tut-fp-error:

Modified: python/branches/okkoto-sizeof/Doc/tutorial/inputoutput.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/inputoutput.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/inputoutput.rst	Wed Jun  4 11:24:23 2008
@@ -27,16 +27,13 @@
 concatenation operations you can create any layout you can imagine.  The
 standard module :mod:`string` contains some useful operations for padding
 strings to a given column width; these will be discussed shortly.  The second
-way is to use the ``%`` operator with a string as the left argument.  The ``%``
-operator interprets the left argument much like a :cfunc:`sprintf`\ -style
-format string to be applied to the right argument, and returns the string
-resulting from this formatting operation.
+way is to use the :meth:`str.format` method.
 
 One question remains, of course: how do you convert values to strings? Luckily,
 Python has ways to convert any value to a string: pass it to the :func:`repr`
 or :func:`str` functions.  Reverse quotes (``````) are equivalent to
-:func:`repr`, but they are no longer used in modern Python code and will likely
-not be in future versions of the language.
+:func:`repr`, but they are no longer used in modern Python code and are removed
+in future versions of the language.
 
 The :func:`str` function is meant to return representations of values which are
 fairly human-readable, while :func:`repr` is meant to generate representations
@@ -94,7 +91,7 @@
    10 100 1000
 
    >>> for x in range(1,11):
-   ...     print '%2d %3d %4d' % (x, x*x, x*x*x)
+   ...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
    ... 
     1   1    1
     2   4    8
@@ -129,42 +126,91 @@
    >>> '3.14159265359'.zfill(5)
    '3.14159265359'
 
-Using the ``%`` operator looks like this::
+Basic usage of the :meth:`str.format` method looks like this::
+
+   >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
+   We are the knights who say "Ni!"
+
+The brackets and characters within them (called format fields) are replaced with
+the objects passed into the format method.  The number in the brackets refers to
+the position of the object passed into the format method. ::
+
+   >>> print '{0} and {1}'.format('spam', 'eggs')
+   spam and eggs
+   >>> print '{1} and {0}'.format('spam', 'eggs')
+   eggs and spam
+
+If keyword arguments are used in the format method, their values are referred to
+by using the name of the argument. ::
+
+   >>> print 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')
+   This spam is absolutely horrible.
+
+Positional and keyword arguments can be arbitrarily combined::
+
+   >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')
+   The story of Bill, Manfred, and Georg.
+
+An optional ``':``` and format specifier can follow the field name. This also
+greater control over how the value is formatted.  The following example
+truncates the Pi to three places after the decimal.
 
    >>> import math
-   >>> print 'The value of PI is approximately %5.3f.' % math.pi
+   >>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
    The value of PI is approximately 3.142.
 
-If there is more than one format in the string, you need to pass a tuple as
-right operand, as in this example::
+Passing an integer after the ``':'`` will cause that field to be a minimum
+number of characters wide.  This is useful for making tables pretty.::
 
    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
    >>> for name, phone in table.items():
-   ...     print '%-10s ==> %10d' % (name, phone)
+   ...     print '{0:10} ==> {1:10d}'.format(name, phone)
    ... 
    Jack       ==>       4098
    Dcab       ==>       7678
    Sjoerd     ==>       4127
 
-Most formats work exactly as in C and require that you pass the proper type;
-however, if you don't you get an exception, not a core dump. The ``%s`` format
-is more relaxed: if the corresponding argument is not a string object, it is
-converted to string using the :func:`str` built-in function.  Using ``*`` to
-pass the width or precision in as a separate (integer) argument is supported.
-The C formats ``%n`` and ``%p`` are not supported.
-
 If you have a really long format string that you don't want to split up, it
 would be nice if you could reference the variables to be formatted by name
-instead of by position.  This can be done by using form ``%(name)format``, as
-shown here::
+instead of by position.  This can be done by simply passing the dict and using
+square brackets ``'[]'`` to access the keys ::
+
+   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
+   >>> print 'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)
+   Jack: 4098; Sjoerd: 4127; Dcab: 8637678
+
+This could also be done by passing the table as keyword arguments with the '**'
+notation.::
 
    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
-   >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
+   >>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)
    Jack: 4098; Sjoerd: 4127; Dcab: 8637678
 
 This is particularly useful in combination with the new built-in :func:`vars`
 function, which returns a dictionary containing all local variables.
 
+For a complete overview of string formating with :meth:`str.format`, see
+:ref:`formatstrings`.
+
+
+Old string formatting
+---------------------
+
+The ``%`` operator can also be used for string formatting. It interprets the
+left argument much like a :cfunc:`sprintf`\ -style format string to be applied
+to the right argument, and returns the string resulting from this formatting
+operation. For example::
+
+   >>> import math
+   >>> print 'The value of PI is approximately %5.3f.' % math.pi
+   The value of PI is approximately 3.142.
+
+Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%``
+operator. However, because this old style of formatting will eventually removed
+from the language :meth:`str.format` should generally be used.
+
+More information can be found in the :ref:`string-formatting` section.
+
 
 .. _tut-files:
 

Modified: python/branches/okkoto-sizeof/Doc/tutorial/interpreter.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/interpreter.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/interpreter.rst	Wed Jun  4 11:24:23 2008
@@ -51,8 +51,8 @@
 A second way of starting the interpreter is ``python -c command [arg] ...``,
 which executes the statement(s) in *command*, analogous to the shell's
 :option:`-c` option.  Since Python statements often contain spaces or other
-characters that are special to the shell, it is best to quote  *command* in its
-entirety with double quotes.
+characters that are special to the shell, it is usually advised to quote
+*command* in its entirety with single quotes.
 
 Some Python modules are also useful as scripts.  These can be invoked using
 ``python -m module [arg] ...``, which executes the source file for *module* as

Modified: python/branches/okkoto-sizeof/Doc/tutorial/introduction.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/introduction.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/introduction.rst	Wed Jun  4 11:24:23 2008
@@ -372,9 +372,13 @@
       Both strings and Unicode strings support a large number of methods for
       basic transformations and searching.
 
+   :ref:`new-string-formatting`
+      Information about string formatting with :meth:`str.format` is described
+      here.
+
    :ref:`string-formatting`
-      The formatting operations invoked when strings and Unicode strings are the
-      left operand of the ``%`` operator are described in more detail here.
+      The old formatting operations invoked when strings and Unicode strings are
+      the left operand of the ``%`` operator are described in more detail here.
 
 
 .. _tut-unicodestrings:

Modified: python/branches/okkoto-sizeof/Doc/tutorial/stdlib2.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/tutorial/stdlib2.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/tutorial/stdlib2.rst	Wed Jun  4 11:24:23 2008
@@ -13,11 +13,11 @@
 Output Formatting
 =================
 
-The :mod:`reprlib` module provides a version of :func:`repr` customized for
+The :mod:`repr` module provides a version of :func:`repr` customized for
 abbreviated displays of large or deeply nested containers::
 
-   >>> import reprlib
-   >>> reprlib.repr(set('supercalifragilisticexpialidocious'))
+   >>> import repr
+   >>> repr.repr(set('supercalifragilisticexpialidocious'))
    "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"
 
 The :mod:`pprint` module offers more sophisticated control over printing both
@@ -116,7 +116,7 @@
    >>> for i, filename in enumerate(photofiles):
    ...     base, ext = os.path.splitext(filename)
    ...     newname = t.substitute(d=date, n=i, f=ext)
-   ...     print '%s --> %s' % (filename, newname)
+   ...     print '{0} --> {1}'.format(filename, newname)
 
    img_1074.jpg --> Ashley_0.jpg
    img_1076.jpg --> Ashley_1.jpg
@@ -174,7 +174,7 @@
 
    class AsyncZip(threading.Thread):
        def __init__(self, infile, outfile):
-           threading.Thread.__init__(self)        
+           threading.Thread.__init__(self)
            self.infile = infile
            self.outfile = outfile
        def run(self):
@@ -198,9 +198,9 @@
 While those tools are powerful, minor design errors can result in problems that
 are difficult to reproduce.  So, the preferred approach to task coordination is
 to concentrate all access to a resource in a single thread and then use the
-:mod:`queue` module to feed that thread with requests from other threads.
-Applications using :class:`Queue` objects for inter-thread communication and
-coordination are easier to design, more readable, and more reliable.
+:mod:`Queue` module to feed that thread with requests from other threads.
+Applications using :class:`Queue.Queue` objects for inter-thread communication
+and coordination are easier to design, more readable, and more reliable.
 
 
 .. _tut-logging:
@@ -358,11 +358,11 @@
 results in decimal floating point and binary floating point. The difference
 becomes significant if the results are rounded to the nearest cent::
 
-   >>> from decimal import *       
+   >>> from decimal import *
    >>> Decimal('0.70') * Decimal('1.05')
    Decimal("0.7350")
    >>> .70 * 1.05
-   0.73499999999999999       
+   0.73499999999999999
 
 The :class:`Decimal` result keeps a trailing zero, automatically inferring four
 place significance from multiplicands with two place significance.  Decimal
@@ -380,7 +380,7 @@
    >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
    True
    >>> sum([0.1]*10) == 1.0
-   False      
+   False
 
 The :mod:`decimal` module provides arithmetic with as much precision as needed::
 

Modified: python/branches/okkoto-sizeof/Doc/using/cmdline.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/using/cmdline.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/using/cmdline.rst	Wed Jun  4 11:24:23 2008
@@ -481,6 +481,13 @@
 
    .. versionadded:: 2.6
 
+.. envvar:: PYTHONIOENCODING
+
+   Overrides the encoding used for stdin/stdout/stderr, in the syntax
+   encodingname:errorhandler, with the :errors part being optional.
+
+   .. versionadded:: 2.6
+
 
 .. envvar:: PYTHONNOUSERSITE
 

Modified: python/branches/okkoto-sizeof/Doc/whatsnew/2.6.rst
==============================================================================
--- python/branches/okkoto-sizeof/Doc/whatsnew/2.6.rst	(original)
+++ python/branches/okkoto-sizeof/Doc/whatsnew/2.6.rst	Wed Jun  4 11:24:23 2008
@@ -1,5 +1,5 @@
 ****************************
-  What's New in Python 2.6  
+  What's New in Python 2.6
 ****************************
 
 .. XXX add trademark info for Apple, Microsoft, SourceForge.
@@ -10,42 +10,42 @@
 
 .. $Id: whatsnew26.tex 55746 2007-06-02 18:33:53Z neal.norwitz $
    Rules for maintenance:
-   
+
    * Anyone can add text to this document.  Do not spend very much time
    on the wording of your changes, because your text will probably
    get rewritten to some degree.
-   
+
    * The maintainer will go through Misc/NEWS periodically and add
    changes; it's therefore more important to add your changes to
    Misc/NEWS than to this file.
-   
+
    * This is not a complete list of every single change; completeness
    is the purpose of Misc/NEWS.  Some changes I consider too small
    or esoteric to include.  If such a change is added to the text,
    I'll just remove it.  (This is another reason you shouldn't spend
    too much time on writing your addition.)
-   
+
    * If you want to draw your new text to the attention of the
    maintainer, add 'XXX' to the beginning of the paragraph or
    section.
-   
+
    * It's OK to just add a fragmentary note about a change.  For
    example: "XXX Describe the transmogrify() function added to the
    socket module."  The maintainer will research the change and
    write the necessary text.
-   
+
    * You can comment out your additions if you like, but it's not
    necessary (especially when a final release is some months away).
-   
+
    * Credit the author of a patch or bugfix.   Just the name is
    sufficient; the e-mail address isn't necessary.
-   
+
    * It's helpful to add the bug/patch number in a parenthetical comment.
-   
+
    XXX Describe the transmogrify() function added to the socket
    module.
    (Contributed by P.Y. Developer; :issue:`12345`.)
-   
+
    This saves the maintainer some effort going through the SVN logs
    when researching a change.
 
@@ -74,7 +74,7 @@
 ================
 
 The development cycle for Python 2.6 also saw the release of the first
-alphas of Python 3.0, and the development of 3.0 has influenced 
+alphas of Python 3.0, and the development of 3.0 has influenced
 a number of features in 2.6.
 
 Python 3.0 is a far-ranging redesign of Python that breaks
@@ -83,7 +83,7 @@
 Python 3.0.  However, not all the changes in 3.0 necessarily break
 compatibility.  In cases where new features won't cause existing code
 to break, they've been backported to 2.6 and are described in this
-document in the appropriate place.  Some of the 3.0-derived features 
+document in the appropriate place.  Some of the 3.0-derived features
 are:
 
 * A :meth:`__complex__` method for converting objects to a complex number.
@@ -94,7 +94,7 @@
 A new command-line switch, :option:`-3`, enables warnings
 about features that will be removed in Python 3.0.  You can run code
 with this switch to see how much work will be necessary to port
-code to 3.0.  The value of this switch is available 
+code to 3.0.  The value of this switch is available
 to Python code as the boolean variable :data:`sys.py3kwarning`,
 and to C extension code as :cdata:`Py_Py3kWarningFlag`.
 
@@ -116,9 +116,9 @@
 Development Changes
 ==================================================
 
-While 2.6 was being developed, the Python development process 
-underwent two significant changes: the developer group 
-switched from SourceForge's issue tracker to a customized 
+While 2.6 was being developed, the Python development process
+underwent two significant changes: the developer group
+switched from SourceForge's issue tracker to a customized
 Roundup installation, and the documentation was converted from
 LaTeX to reStructuredText.
 
@@ -135,34 +135,34 @@
 therefore posted a call for issue trackers, asking volunteers to set
 up different products and import some of the bugs and patches from
 SourceForge.  Four different trackers were examined: Atlassian's `Jira
-<http://www.atlassian.com/software/jira/>`__, 
-`Launchpad <http://www.launchpad.net>`__, 
-`Roundup <http://roundup.sourceforge.net/>`__, and 
-`Trac <http://trac.edgewall.org/>`__.  
+<http://www.atlassian.com/software/jira/>`__,
+`Launchpad <http://www.launchpad.net>`__,
+`Roundup <http://roundup.sourceforge.net/>`__, and
+`Trac <http://trac.edgewall.org/>`__.
 The committee eventually settled on Jira
 and Roundup as the two candidates.  Jira is a commercial product that
-offers a no-cost hosted instance to free-software projects; Roundup 
+offers a no-cost hosted instance to free-software projects; Roundup
 is an open-source project that requires volunteers
 to administer it and a server to host it.
 
 After posting a call for volunteers, a new Roundup installation was
 set up at http://bugs.python.org.  One installation of Roundup can
 host multiple trackers, and this server now also hosts issue trackers
-for Jython and for the Python web site.  It will surely find 
+for Jython and for the Python web site.  It will surely find
 other uses in the future.  Where possible,
 this edition of "What's New in Python" links to the bug/patch
 item for each change.
 
-Hosting is kindly provided by 
-`Upfront Systems <http://www.upfrontsystems.co.za/>`__ 
+Hosting is kindly provided by
+`Upfront Systems <http://www.upfrontsystems.co.za/>`__
 of Stellenbosch, South Africa.  Martin von Loewis put a
 lot of effort into importing existing bugs and patches from
-SourceForge; his scripts for this import operation are at 
+SourceForge; his scripts for this import operation are at
 http://svn.python.org/view/tracker/importer/.
 
 .. seealso::
 
-  http://bugs.python.org 
+  http://bugs.python.org
     The Python bug tracker.
 
   http://bugs.jython.org:
@@ -189,8 +189,8 @@
 Unfortunately, converting LaTeX to HTML is fairly complicated, and
 Fred L. Drake Jr., the Python documentation editor for many years,
 spent a lot of time wrestling the conversion process into shape.
-Occasionally people would suggest converting the documentation into 
-SGML or, later, XML, but performing a good conversion is a major task 
+Occasionally people would suggest converting the documentation into
+SGML or, later, XML, but performing a good conversion is a major task
 and no one pursued the task to completion.
 
 During the 2.6 development cycle, Georg Brandl put a substantial
@@ -222,7 +222,7 @@
 statement an optional feature, to be enabled by a ``from __future__
 import with_statement`` directive.  In 2.6 the statement no longer needs to
 be specially enabled; this means that :keyword:`with` is now always a
-keyword.  The rest of this section is a copy of the corresponding 
+keyword.  The rest of this section is a copy of the corresponding
 section from "What's New in Python 2.5" document; if you read
 it back when Python 2.5 came out, you can skip the rest of this
 section.
@@ -518,7 +518,7 @@
    :pep:`370` - Per-user ``site-packages`` Directory
      PEP written and implemented by Christian Heimes.
 
-  
+
 .. ======================================================================
 
 .. _pep-3101:
@@ -526,9 +526,9 @@
 PEP 3101: Advanced String Formatting
 =====================================================
 
-In Python 3.0, the `%` operator is supplemented by a more powerful
-string formatting method, :meth:`format`.  Support for the
-:meth:`format` method has been backported to Python 2.6.
+In Python 3.0, the `%` operator is supplemented by a more powerful string
+formatting method, :meth:`format`.  Support for the :meth:`str.format` method
+has been backported to Python 2.6.
 
 In 2.6, both 8-bit and Unicode strings have a `.format()` method that
 treats the string as a template and takes the arguments to be formatted.
@@ -539,7 +539,7 @@
 
      # Use the named keyword arguments
      uid = 'root'
-     
+
      'User ID: {uid}   Last seen: {last_login}'.format(uid='root',
             last_login = '5 Mar 2008 07:20') ->
        'User ID: root   Last seen: 5 Mar 2008 07:20'
@@ -548,8 +548,8 @@
 
      format("Empty dict: {{}}") -> "Empty dict: {}"
 
-Field names can be integers indicating positional arguments, such as 
-``{0}``, ``{1}``, etc. or names of keyword arguments.  You can also 
+Field names can be integers indicating positional arguments, such as
+``{0}``, ``{1}``, etc. or names of keyword arguments.  You can also
 supply compound field names that read attributes or access dictionary keys::
 
     import sys
@@ -602,7 +602,7 @@
 =                (For numeric types only) Pad after the sign.
 ================ ============================================
 
-Format specifiers can also include a presentation type, which 
+Format specifiers can also include a presentation type, which
 controls how the value is formatted.  For example, floating-point numbers
 can be formatted as a general number or in exponential notation:
 
@@ -649,8 +649,11 @@
 
 .. seealso::
 
+   :ref:`formatstrings`
+      The reference format fields.
+
    :pep:`3101` - Advanced String Formatting
-      PEP written by Talin.
+      PEP written by Talin. Implemented by Eric Smith.
 
 .. ======================================================================
 
@@ -660,10 +663,10 @@
 =====================================================
 
 The ``print`` statement becomes the :func:`print` function in Python 3.0.
-Making :func:`print` a function makes it easier to change 
-by doing 'def print(...)' or importing a new function from somewhere else. 
+Making :func:`print` a function makes it easier to change
+by doing 'def print(...)' or importing a new function from somewhere else.
 
-Python 2.6 has a ``__future__`` import that removes ``print`` as language 
+Python 2.6 has a ``__future__`` import that removes ``print`` as language
 syntax, letting you use the functional form instead.  For example::
 
     from __future__ import print_function
@@ -677,7 +680,7 @@
 
  * **args**: positional arguments whose values will be printed out.
  * **sep**: the separator, which will be printed between arguments.
- * **end**: the ending text, which will be printed after all of the 
+ * **end**: the ending text, which will be printed after all of the
    arguments have been output.
  * **file**: the file object to which the output will be sent.
 
@@ -693,7 +696,7 @@
 PEP 3110: Exception-Handling Changes
 =====================================================
 
-One error that Python programmers occasionally make 
+One error that Python programmers occasionally make
 is the following::
 
     try:
@@ -701,11 +704,11 @@
     except TypeError, ValueError:
         ...
 
-The author is probably trying to catch both 
+The author is probably trying to catch both
 :exc:`TypeError` and :exc:`ValueError` exceptions, but this code
-actually does something different: it will catch 
+actually does something different: it will catch
 :exc:`TypeError` and bind the resulting exception object
-to the local name ``"ValueError"``.  The correct code 
+to the local name ``"ValueError"``.  The correct code
 would have specified a tuple::
 
     try:
@@ -718,7 +721,7 @@
 node that's a tuple.
 
 Python 3.0 changes the syntax to make this unambiguous by replacing
-the comma with the word "as".  To catch an exception and store the 
+the comma with the word "as".  To catch an exception and store the
 exception object in the variable ``exc``, you must write::
 
     try:
@@ -744,13 +747,13 @@
 =====================================================
 
 Python 3.0 adopts Unicode as the language's fundamental string type, and
-denotes 8-bit literals differently, either as ``b'string'`` 
-or using a :class:`bytes` constructor.  For future compatibility, 
+denotes 8-bit literals differently, either as ``b'string'``
+or using a :class:`bytes` constructor.  For future compatibility,
 Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
 and it also supports the ``b''`` notation.
 
 There's also a ``__future__`` import that causes all string literals
-to become Unicode strings.  This means that ``\u`` escape sequences 
+to become Unicode strings.  This means that ``\u`` escape sequences
 can be used to include Unicode characters::
 
 
@@ -786,7 +789,7 @@
 the :mod:`io` module:
 
 * :class:`RawIOBase`: defines raw I/O operations: :meth:`read`,
-  :meth:`readinto`, 
+  :meth:`readinto`,
   :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
   and :meth:`close`.
   Most of the methods of this class will often map to a single system call.
@@ -799,36 +802,36 @@
 
   .. XXX should 2.6 register them in io.py?
 
-* :class:`BufferedIOBase`: is an abstract base class that 
-  buffers data in memory to reduce the number of 
+* :class:`BufferedIOBase`: is an abstract base class that
+  buffers data in memory to reduce the number of
   system calls used, making I/O processing more efficient.
-  It supports all of the methods of :class:`RawIOBase`, 
+  It supports all of the methods of :class:`RawIOBase`,
   and adds a :attr:`raw` attribute holding the underlying raw object.
 
   There are four concrete classes implementing this ABC:
-  :class:`BufferedWriter` and 
+  :class:`BufferedWriter` and
   :class:`BufferedReader` for objects that only support
   writing or reading and don't support random access,
   :class:`BufferedRandom` for objects that support the :meth:`seek` method
   for random access,
-  and :class:`BufferedRWPair` for objects such as TTYs that have 
+  and :class:`BufferedRWPair` for objects such as TTYs that have
   both read and write operations that act upon unconnected streams of data.
 
 * :class:`TextIOBase`: Provides functions for reading and writing
   strings (remember, strings will be Unicode in Python 3.0),
-  and supporting universal newlines.  :class:`TextIOBase` defines 
-  the :meth:`readline` method and supports iteration upon 
-  objects.   
+  and supporting universal newlines.  :class:`TextIOBase` defines
+  the :meth:`readline` method and supports iteration upon
+  objects.
 
   There are two concrete implementations.  :class:`TextIOWrapper`
   wraps a buffered I/O object, supporting all of the methods for
-  text I/O and adding a :attr:`buffer` attribute for access 
+  text I/O and adding a :attr:`buffer` attribute for access
   to the underlying object.  :class:`StringIO` simply buffers
   everything in memory without ever writing anything to disk.
 
   (In current 2.6 alpha releases, :class:`io.StringIO` is implemented in
-  pure Python, so it's pretty slow.   You should therefore stick with the 
-  existing :mod:`StringIO` module or :mod:`cStringIO` for now.  At some 
+  pure Python, so it's pretty slow.   You should therefore stick with the
+  existing :mod:`StringIO` module or :mod:`cStringIO` for now.  At some
   point Python 3.0's :mod:`io` module will be rewritten into C for speed,
   and perhaps the C implementation will be  backported to the 2.x releases.)
 
@@ -836,7 +839,7 @@
 
 In Python 2.6, the underlying implementations haven't been
 restructured to build on top of the :mod:`io` module's classes.  The
-module is being provided to make it easier to write code that's 
+module is being provided to make it easier to write code that's
 forward-compatible with 3.0, and to save developers the effort of writing
 their own implementations of buffering and text I/O.
 
@@ -855,7 +858,7 @@
 =====================================================
 
 The buffer protocol is a C-level API that lets Python types
-exchange pointers into their internal representations.  A 
+exchange pointers into their internal representations.  A
 memory-mapped file can be viewed as a buffer of characters, for
 example, and this lets another module such as :mod:`re`
 treat memory-mapped files as a string of characters to be searched.
@@ -863,19 +866,19 @@
 The primary users of the buffer protocol are numeric-processing
 packages such as NumPy, which can expose the internal representation
 of arrays so that callers can write data directly into an array instead
-of going through a slower API.  This PEP updates the buffer protocol in light of experience 
+of going through a slower API.  This PEP updates the buffer protocol in light of experience
 from NumPy development, adding a number of new features
-such as indicating the shape of an array, 
+such as indicating the shape of an array,
 locking memory .
 
-The most important new C API function is 
+The most important new C API function is
 ``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which
 takes an object and a set of flags, and fills in the
-``Py_buffer`` structure with information 
+``Py_buffer`` structure with information
 about the object's memory representation.  Objects
-can use this operation to lock memory in place 
+can use this operation to lock memory in place
 while an external caller could be modifying the contents,
-so there's a corresponding 
+so there's a corresponding
 ``PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view)`` to
 indicate that the external caller is done.
 
@@ -883,7 +886,7 @@
 constraints upon the memory returned.  Some examples are:
 
  * :const:`PyBUF_WRITABLE` indicates that the memory must be writable.
- 
+
  * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory.
 
  * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS`
@@ -897,7 +900,7 @@
    :pep:`3118` - Revising the buffer protocol
       PEP written by Travis Oliphant and Carl Banks; implemented by
       Travis Oliphant.
-      
+
 
 .. ======================================================================
 
@@ -909,16 +912,16 @@
 Some object-oriented languages such as Java support interfaces: declarations
 that a class has a given set of methods or supports a given access protocol.
 Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC
-support consists of an :mod:`abc` module containing a metaclass called 
+support consists of an :mod:`abc` module containing a metaclass called
 :class:`ABCMeta`, special handling
 of this metaclass by the :func:`isinstance` and :func:`issubclass` built-ins,
 and a collection of basic ABCs that the Python developers think will be widely
 useful.
 
-Let's say you have a particular class and wish to know whether it supports 
+Let's say you have a particular class and wish to know whether it supports
 dictionary-style access.  The phrase "dictionary-style" is vague, however.
-It probably means that accessing items with ``obj[1]`` works.  
-Does it imply that setting items with ``obj[2] = value`` works?  
+It probably means that accessing items with ``obj[1]`` works.
+Does it imply that setting items with ``obj[2] = value`` works?
 Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items`
 methods?  What about the iterative variants  such as :meth:`iterkeys`?  :meth:`copy`
 and :meth:`update`?  Iterating over the object with :func:`iter`?
@@ -927,7 +930,7 @@
 module.  :class:`Iterable` indicates that a class defines :meth:`__iter__`,
 and :class:`Container` means the class supports  ``x in y`` expressions
 by defining a :meth:`__contains__` method.  The basic dictionary interface of
-getting items, setting items, and 
+getting items, setting items, and
 :meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
 :class:`MutableMapping` ABC.
 
@@ -935,22 +938,22 @@
 to indicate they support that ABC's interface::
 
     import collections
-  
+
     class Storage(collections.MutableMapping):
         ...
 
 
-Alternatively, you could write the class without deriving from 
+Alternatively, you could write the class without deriving from
 the desired ABC and instead register the class by
 calling the ABC's :meth:`register` method::
 
     import collections
-    
+
     class Storage:
         ...
-	
+
     collections.MutableMapping.register(Storage)
-    
+
 For classes that you write, deriving from the ABC is probably clearer.
 The :meth:`register`  method is useful when you've written a new
 ABC that can describe an existing type or class, or if you want
@@ -963,8 +966,8 @@
   PrintableType.register(float)
   PrintableType.register(str)
 
-Classes should obey the semantics specified by an ABC, but 
-Python can't check this; it's up to the class author to  
+Classes should obey the semantics specified by an ABC, but
+Python can't check this; it's up to the class author to
 understand the ABC's requirements and to implement the code accordingly.
 
 To check whether an object supports a particular interface, you can
@@ -972,11 +975,11 @@
 
     def func(d):
 	if not isinstance(d, collections.MutableMapping):
-	    raise ValueError("Mapping object expected, not %r" % d)        
+	    raise ValueError("Mapping object expected, not %r" % d)
 
-(Don't feel that you must now begin writing lots of checks as in the 
-above example.  Python has a strong tradition of duck-typing, where 
-explicit type-checking isn't done and code simply calls methods on 
+(Don't feel that you must now begin writing lots of checks as in the
+above example.  Python has a strong tradition of duck-typing, where
+explicit type-checking isn't done and code simply calls methods on
 an object, trusting that those methods will be there and raising an
 exception if they aren't.  Be judicious in checking for ABCs
 and only do it where it helps.)
@@ -988,46 +991,46 @@
 
   class Drawable():
       __metaclass__ = ABCMeta
-  
+
       def draw(self, x, y, scale=1.0):
 	  pass
 
       def draw_doubled(self, x, y):
 	  self.draw(x, y, scale=2.0)
 
-	
+
   class Square(Drawable):
       def draw(self, x, y, scale):
           ...
 
-	  
+
 In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
 renders the object at twice its size and can be implemented in terms
 of other methods described in :class:`Drawable`.  Classes implementing
-this ABC therefore don't need to provide their own implementation 
+this ABC therefore don't need to provide their own implementation
 of :meth:`draw_doubled`, though they can do so.  An implementation
-of :meth:`draw` is necessary, though; the ABC can't provide 
-a useful generic implementation.  You 
-can apply the ``@abstractmethod`` decorator to methods such as 
-:meth:`draw` that must be implemented; Python will 
-then raise an exception for classes that 
+of :meth:`draw` is necessary, though; the ABC can't provide
+a useful generic implementation.  You
+can apply the ``@abstractmethod`` decorator to methods such as
+:meth:`draw` that must be implemented; Python will
+then raise an exception for classes that
 don't define the method::
 
     class Drawable():
 	__metaclass__ = ABCMeta
-    
+
 	@abstractmethod
 	def draw(self, x, y, scale):
 	    pass
 
-Note that the exception is only raised when you actually 
+Note that the exception is only raised when you actually
 try to create an instance of a subclass without the method::
 
     >>> s=Square()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: Can't instantiate abstract class Square with abstract methods draw
-    >>> 
+    >>>
 
 Abstract data attributes can be declared using the ``@abstractproperty`` decorator::
 
@@ -1035,7 +1038,7 @@
     def readonly(self):
        return self._x
 
-Subclasses must then define a :meth:`readonly` property 
+Subclasses must then define a :meth:`readonly` property
 
 .. seealso::
 
@@ -1056,7 +1059,7 @@
 adds support for binary (base-2) integer literals, signalled by a "0b"
 or "0B" prefix.
 
-Python 2.6 doesn't drop support for a leading 0 signalling 
+Python 2.6 doesn't drop support for a leading 0 signalling
 an octal number, but it does add support for "0o" and "0b"::
 
     >>> 0o21, 2*8 + 1
@@ -1064,8 +1067,8 @@
     >>> 0b101111
     47
 
-The :func:`oct` built-in still returns numbers 
-prefixed with a leading zero, and a new :func:`bin` 
+The :func:`oct` built-in still returns numbers
+prefixed with a leading zero, and a new :func:`bin`
 built-in returns the binary representation for a number::
 
     >>> oct(42)
@@ -1141,36 +1144,36 @@
 round off the results or introduce tiny errors that may break the
 commutativity and associativity properties; inexact numbers may
 perform such rounding or introduce small errors.  Integers, long
-integers, and rational numbers are exact, while floating-point 
+integers, and rational numbers are exact, while floating-point
 and complex numbers are inexact.
 
 :class:`Complex` is a subclass of :class:`Number`.  Complex numbers
 can undergo the basic operations of addition, subtraction,
 multiplication, division, and exponentiation, and you can retrieve the
-real and imaginary parts and obtain a number's conjugate.  Python's built-in 
+real and imaginary parts and obtain a number's conjugate.  Python's built-in
 complex type is an implementation of :class:`Complex`.
 
-:class:`Real` further derives from :class:`Complex`, and adds 
-operations that only work on real numbers: :func:`floor`, :func:`trunc`, 
-rounding, taking the remainder mod N, floor division, 
-and comparisons.  
+:class:`Real` further derives from :class:`Complex`, and adds
+operations that only work on real numbers: :func:`floor`, :func:`trunc`,
+rounding, taking the remainder mod N, floor division,
+and comparisons.
 
 :class:`Rational` numbers derive from :class:`Real`, have
 :attr:`numerator` and :attr:`denominator` properties, and can be
 converted to floats.  Python 2.6 adds a simple rational-number class,
-:class:`Fraction`, in the :mod:`fractions` module.  (It's called 
-:class:`Fraction` instead of :class:`Rational` to avoid 
+:class:`Fraction`, in the :mod:`fractions` module.  (It's called
+:class:`Fraction` instead of :class:`Rational` to avoid
 a name clash with :class:`numbers.Rational`.)
 
 :class:`Integral` numbers derive from :class:`Rational`, and
-can be shifted left and right with ``<<`` and ``>>``, 
-combined using bitwise operations such as ``&`` and ``|``, 
+can be shifted left and right with ``<<`` and ``>>``,
+combined using bitwise operations such as ``&`` and ``|``,
 and can be used as array indexes and slice boundaries.
 
 In Python 3.0, the PEP slightly redefines the existing built-ins
 :func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
-one, :func:`math.trunc`, that's been backported to Python 2.6. 
-:func:`math.trunc` rounds toward zero, returning the closest 
+one, :func:`math.trunc`, that's been backported to Python 2.6.
+:func:`math.trunc` rounds toward zero, returning the closest
 :class:`Integral` that's between the function's argument and zero.
 
 .. seealso::
@@ -1181,7 +1184,7 @@
    `Scheme's numerical tower <http://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.
 
    `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.
-  
+
 
 The :mod:`fractions` Module
 --------------------------------------------------
@@ -1205,8 +1208,8 @@
     >>> a/b
     Fraction(5, 3)
 
-To help in converting floating-point numbers to rationals, 
-the float type now has a :meth:`as_integer_ratio()` method that returns 
+To help in converting floating-point numbers to rationals,
+the float type now has a :meth:`as_integer_ratio()` method that returns
 the numerator and denominator for a fraction that evaluates to the same
 floating-point value::
 
@@ -1239,7 +1242,7 @@
 
     >>> def f(**kw):
     ...    print sorted(kw)
-    ... 
+    ...
     >>> ud=UserDict.UserDict()
     >>> ud['a'] = 1
     >>> ud['b'] = 'string'
@@ -1264,21 +1267,21 @@
 
 * Properties now have three attributes, :attr:`getter`,
   :attr:`setter` and :attr:`deleter`, that are useful shortcuts for
-  adding or modifying a getter, setter or deleter function to an 
+  adding or modifying a getter, setter or deleter function to an
   existing property. You would use them like this::
 
     class C(object):
-	@property                                                              
-	def x(self): 
-	    return self._x                                            
-
-	@x.setter                                                              
-	def x(self, value): 
-	    self._x = value                                    
-
-	@x.deleter                                                             
-	def x(self): 
-	    del self._x             
+	@property
+	def x(self):
+	    return self._x
+
+	@x.setter
+	def x(self, value):
+	    self._x = value
+
+	@x.deleter
+	def x(self):
+	    del self._x
 
     class D(C):
         @C.x.getter
@@ -1290,22 +1293,22 @@
             self._x = value / 2
 
 
-* C functions and methods that use 
-  :cfunc:`PyComplex_AsCComplex` will now accept arguments that 
-  have a :meth:`__complex__` method.  In particular, the functions in the 
+* C functions and methods that use
+  :cfunc:`PyComplex_AsCComplex` will now accept arguments that
+  have a :meth:`__complex__` method.  In particular, the functions in the
   :mod:`cmath` module will now accept objects with this method.
   This is a backport of a Python 3.0 change.
   (Contributed by Mark Dickinson; :issue:`1675423`.)
 
   A numerical nicety: when creating a complex number from two floats
-  on systems that support signed zeros (-0 and +0), the 
-  :func:`complex` constructor will now preserve the sign 
+  on systems that support signed zeros (-0 and +0), the
+  :func:`complex` constructor will now preserve the sign
   of the zero.  (:issue:`1507`)
 
 * More floating-point features were also added.  The :func:`float` function
   will now turn the strings ``+nan`` and ``-nan`` into the corresponding
-  IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into 
-  positive or negative infinity.  This works on any platform with 
+  IEEE 754 Not A Number values, and ``+inf`` and ``-inf`` into
+  positive or negative infinity.  This works on any platform with
   IEEE 754 semantics.  (Contributed by Christian Heimes; :issue:`1635`.)
 
   Other functions in the :mod:`math` module, :func:`isinf` and
@@ -1316,11 +1319,11 @@
   functions have been improved to give more consistent behaviour
   across platforms, especially with respect to handling of
   floating-point exceptions and IEEE 754 special values.
-  The new functions are: 
+  The new functions are:
 
   * :func:`isinf` and :func:`isnan` determine whether a given float is
     a (positive or negative) infinity or a NaN (Not a Number),
-    respectively. 
+    respectively.
 
   * ``copysign(x, y)`` copies the sign bit of an IEEE 754 number,
     returning the absolute value of *x* combined with the sign bit of
@@ -1350,31 +1353,31 @@
   (Contributed by Christian Heimes and Mark Dickinson.)
 
 * Changes to the :class:`Exception` interface
-  as dictated by :pep:`352` continue to be made.  For 2.6, 
+  as dictated by :pep:`352` continue to be made.  For 2.6,
   the :attr:`message` attribute is being deprecated in favor of the
   :attr:`args` attribute.
 
-* The :exc:`GeneratorExit` exception now subclasses 
-  :exc:`BaseException` instead of :exc:`Exception`.  This means 
+* The :exc:`GeneratorExit` exception now subclasses
+  :exc:`BaseException` instead of :exc:`Exception`.  This means
   that an exception handler that does ``except Exception:``
-  will not inadvertently catch :exc:`GeneratorExit`. 
+  will not inadvertently catch :exc:`GeneratorExit`.
   (Contributed by Chad Austin; :issue:`1537`.)
 
-* Generator objects now have a :attr:`gi_code` attribute that refers to 
-  the original code object backing the generator.  
+* Generator objects now have a :attr:`gi_code` attribute that refers to
+  the original code object backing the generator.
   (Contributed by Collin Winter; :issue:`1473257`.)
 
 * The :func:`compile` built-in function now accepts keyword arguments
   as well as positional parameters.  (Contributed by Thomas Wouters;
   :issue:`1444529`.)
 
-* The :func:`complex` constructor now accepts strings containing 
+* The :func:`complex` constructor now accepts strings containing
   parenthesized complex numbers, letting ``complex(repr(cmplx))``
   will now round-trip values.  For example, ``complex('(3+4j)')``
   now returns the value (3+4j).  (:issue:`1491866`)
 
-* The string :meth:`translate` method now accepts ``None`` as the 
-  translation table parameter, which is treated as the identity 
+* The string :meth:`translate` method now accepts ``None`` as the
+  translation table parameter, which is treated as the identity
   transformation.   This makes it easier to carry out operations
   that only delete characters.  (Contributed by Bengt Richter;
   :issue:`1193128`.)
@@ -1383,7 +1386,7 @@
   method on the objects it receives.  This method must return a list
   of strings containing the names of valid attributes for the object,
   and lets the object control the value that :func:`dir` produces.
-  Objects that have :meth:`__getattr__` or :meth:`__getattribute__` 
+  Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
   methods can use this to advertise pseudo-attributes they will honor.
   (:issue:`1591665`)
 
@@ -1411,12 +1414,12 @@
 * Type objects now have a cache of methods that can reduce
   the amount of work required to find the correct method implementation
   for a particular class; once cached, the interpreter doesn't need to
-  traverse base classes to figure out the right method to call.  
-  The cache is cleared if a base class or the class itself is modified, 
-  so the cache should remain correct even in the face of Python's dynamic 
+  traverse base classes to figure out the right method to call.
+  The cache is cleared if a base class or the class itself is modified,
+  so the cache should remain correct even in the face of Python's dynamic
   nature.
-  (Original optimization implemented by Armin Rigo, updated for 
-  Python 2.6 by Kevin Jacobs; :issue:`1700288`.) 
+  (Original optimization implemented by Armin Rigo, updated for
+  Python 2.6 by Kevin Jacobs; :issue:`1700288`.)
 
 * All of the functions in the :mod:`struct` module have been rewritten in
   C, thanks to work at the Need For Speed sprint.
@@ -1427,7 +1430,7 @@
   these types.  (Contributed by Neal Norwitz.)
 
 * Unicode strings now use faster code for detecting
-  whitespace and line breaks; this speeds up the :meth:`split` method 
+  whitespace and line breaks; this speeds up the :meth:`split` method
   by about 25% and :meth:`splitlines` by 35%.
   (Contributed by Antoine Pitrou.)  Memory usage is reduced
   by using pymalloc for the Unicode string's data.
@@ -1468,12 +1471,51 @@
 complete list of changes, or look through the Subversion logs for all the
 details.
 
-* (3.0-warning mode) Python 3.0 will feature a reorganized standard 
+* (3.0-warning mode) Python 3.0 will feature a reorganized standard
   library; many outdated modules are being dropped,
-  and some modules are being renamed or moved into packages. 
-  Python 2.6 running in 3.0-warning mode will warn about these modules 
+  and some modules are being renamed or moved into packages.
+  Python 2.6 running in 3.0-warning mode will warn about these modules
   when they are imported.
+
+  The modules that have been renamed are:
+
+  * :mod:`ConfigParser` has become :mod:`configparser`.
+  * :mod:`copy_reg` has become :mod:`copyreg`.
+  * :mod:`htmlentitydefs` has become :mod:`html.entities`.
+  * :mod:`HTMLParser` has become :mod:`html.parser`.
+  * :mod:`repr` (the module) has become :mod:`reprlib`.
+  * :mod:`SocketServer` has become :mod:`socketserver`.
+  * :mod:`Tkinter` has become the :mod:`tkinter` package.
+  * :mod:`Queue` has become :mod:`queue`.
+
+  .. XXX no warnings anymore for renamed modules!
+
   The list of deprecated modules is:
+  :mod:`audiodev`,
+  :mod:`bgenlocations`,
+  :mod:`buildtools`,
+  :mod:`bundlebuilder`,
+  :mod:`Canvas`,
+  :mod:`compiler`,
+  :mod:`dircache`,
+  :mod:`dl`,
+  :mod:`fpformat`,
+  :mod:`gensuitemodule`,
+  :mod:`ihooks`,
+  :mod:`imageop`,
+  :mod:`imgfile`,
+  :mod:`linuxaudiodev`,
+  :mod:`mhlib`,
+  :mod:`multifile`,
+  :mod:`new`,
+  :mod:`popen2`,
+  :mod:`pure`,
+  :mod:`statvfs`,
+  :mod:`sunaudiodev`,
+  :mod:`test.testall`,
+  :mod:`toaiff`.
+
+  Various MacOS modules have been removed:
   :mod:`_builtinSuites`,
   :mod:`aepack`,
   :mod:`aetools`,
@@ -1483,68 +1525,57 @@
   :mod:`appletrunner`,
   :mod:`argvemulator`,
   :mod:`Audio_mac`,
-  :mod:`audiodev`,
   :mod:`autoGIL`,
-  :mod:`bgenlocations`,
-  :mod:`buildtools`,
-  :mod:`bundlebuilder`,
-  :mod:`Canvas`,
   :mod:`Carbon`,
   :mod:`cfmfile`,
   :mod:`CodeWarrior`,
   :mod:`ColorPicker`,
-  :mod:`compiler`,
-  :mod:`cd`,
-  :mod:`cddb`,
-  :mod:`cdplayer`,
-  :mod:`CL` and :mod:`cl`,
-  :mod:`cd`,
-  :mod:`cd`,
-  :mod:`dircache`,
-  :mod:`dl`,
   :mod:`EasyDialogs`,
   :mod:`Explorer`,
   :mod:`Finder`,
   :mod:`FrameWork`,
   :mod:`findertools`,
-  :mod:`fpformat`,
-  :mod:`gensuitemodule`,
   :mod:`ic`,
   :mod:`icglue`,
   :mod:`icopen`,
-  :mod:`ihooks`,
-  :mod:`imageop`,
-  :mod:`linuxaudiodev`,
   :mod:`macerrors`,
   :mod:`MacOS`,
   :mod:`macostools`,
   :mod:`macresource`,
-  :mod:`mhlib`,
   :mod:`MiniAEFrame`,
-  :mod:`multifile`,
   :mod:`Nav`,
   :mod:`Netscape`,
-  :mod:`new`,
   :mod:`OSATerminology`,
   :mod:`pimp`,
   :mod:`PixMapWrapper`,
-  :mod:`popen2`,
-  :mod:`pure`,
   :mod:`StdSuites`,
-  :mod:`sv`,
   :mod:`SystemEvents`,
   :mod:`Terminal`,
-  :mod:`terminalcommand`,
-  :mod:`test.testall`,
-  :mod:`toaiff`,
-  :mod:`videoreader`.
-
-  The modules that have been renamed are:
+  :mod:`terminalcommand`.
 
-  * :mod:`ConfigParser` has become :mod:`configparser`.
-  * :mod:`copy_reg` has become :mod:`copyreg`.
-  * :mod:`SocketServer` has become :mod:`socketserver`.
-  * :mod:`Queue` has become :mod:`queue`.
+  A number of old IRIX-specific modules were deprecated:
+  :mod:`cd`,
+  :mod:`cddb`,
+  :mod:`cdplayer`,
+  :mod:`CL` and :mod:`cl`,
+  :mod:`DEVICE`,
+  :mod:`ERRNO`,
+  :mod:`FILE`,
+  :mod:`FL` and :mod:`fl`,
+  :mod:`flp`,
+  :mod:`fm`,
+  :mod:`GET`,
+  :mod:`GLWS`,
+  :mod:`GL` and :mod:`gl`,
+  :mod:`IN`,
+  :mod:`IOCTL`,
+  :mod:`jpeg`,
+  :mod:`panelparser`,
+  :mod:`readcd`,
+  :mod:`SV` and :mod:`sv`,
+  :mod:`torgb`,
+  :mod:`videoreader`,
+  :mod:`WAIT`.
 
 * The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
   available, instead of restricting itself to protocol 1.
@@ -1554,18 +1585,18 @@
   thanks to Mark Dickinson and Christian Heimes, that added some new
   features and greatly improved the accuracy of the computations.
 
-  Five new functions were added: 
+  Five new functions were added:
 
   * :func:`polar` converts a complex number to polar form, returning
-    the modulus and argument of that complex number. 
+    the modulus and argument of that complex number.
 
   * :func:`rect` does the opposite, turning a (modulus, argument) pair
     back into the corresponding complex number.
 
-  * :func:`phase` returns the phase or argument of a complex number.  
+  * :func:`phase` returns the phase or argument of a complex number.
 
   * :func:`isnan` returns True if either
-    the real or imaginary part of its argument is a NaN.  
+    the real or imaginary part of its argument is a NaN.
 
   * :func:`isinf` returns True if either the real or imaginary part of
     its argument is infinite.
@@ -1588,7 +1619,7 @@
   fieldnames)` is a factory function that creates subclasses of the standard tuple
   whose fields are accessible by name as well as index.  For example::
 
-     >>> var_type = collections.namedtuple('variable', 
+     >>> var_type = collections.namedtuple('variable',
      ...             'id name type size')
      # Names are separated by spaces or commas.
      # 'id, name, type, size' would also work.
@@ -1607,15 +1638,15 @@
      variable(id=1, name='amplitude', type='int', size=4)
 
   Where the new :class:`namedtuple` type proved suitable, the standard
-  library has been modified to return them.  For example, 
-  the :meth:`Decimal.as_tuple` method now returns a named tuple with 
+  library has been modified to return them.  For example,
+  the :meth:`Decimal.as_tuple` method now returns a named tuple with
   :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
 
   (Contributed by Raymond Hettinger.)
 
-* Another change to the :mod:`collections` module is that the 
+* Another change to the :mod:`collections` module is that the
   :class:`deque` type now supports an optional *maxlen* parameter;
-  if supplied, the deque's size will be restricted to no more 
+  if supplied, the deque's size will be restricted to no more
   than *maxlen* items.  Adding more items to a full deque causes
   old items to be discarded.
 
@@ -1634,7 +1665,7 @@
 
   (Contributed by Raymond Hettinger.)
 
-* The :mod:`ctypes` module now supports a :class:`c_bool` datatype 
+* The :mod:`ctypes` module now supports a :class:`c_bool` datatype
   that represents the C99 ``bool`` type.  (Contributed by David Remahl;
   :issue:`1649190`.)
 
@@ -1650,9 +1681,9 @@
   (Contributed by Fabian Kreutz.)
   ::
 
-     # Boldface text starting at y=0,x=21 
+     # Boldface text starting at y=0,x=21
      # and affecting the rest of the line.
-     stdscr.chgat(0,21, curses.A_BOLD)  
+     stdscr.chgat(0,21, curses.A_BOLD)
 
   The :class:`Textbox` class in the :mod:`curses.textpad` module
   now supports editing in insert mode as well as overwrite mode.
@@ -1664,7 +1695,7 @@
   object, zero-padded on
   the left to six places.  (Contributed by Skip Montanaro; :issue:`1158`.)
 
-* The :mod:`decimal` module was updated to version 1.66 of 
+* The :mod:`decimal` module was updated to version 1.66 of
   `the General Decimal Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`__.  New features
   include some methods for some basic mathematical functions such as
   :meth:`exp` and :meth:`log10`::
@@ -1676,14 +1707,14 @@
     >>> Decimal(1000).log10()
     Decimal("3")
 
-  The :meth:`as_tuple` method of :class:`Decimal` objects now returns a 
+  The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
   named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.
-  
+
   (Implemented by Facundo Batista and Mark Dickinson.  Named tuple
   support added by Raymond Hettinger.)
 
-* The :mod:`difflib` module's :class:`SequenceMatcher` class 
-  now returns named tuples representing matches. 
+* The :mod:`difflib` module's :class:`SequenceMatcher` class
+  now returns named tuples representing matches.
   In addition to behaving like tuples, the returned values
   also have :attr:`a`, :attr:`b`, and :attr:`size` attributes.
   (Contributed by Raymond Hettinger.)
@@ -1691,25 +1722,25 @@
 * An optional ``timeout`` parameter was added to the
   :class:`ftplib.FTP` class constructor as well as the :meth:`connect`
   method, specifying a timeout measured in seconds.  (Added by Facundo
-  Batista.)  Also, the :class:`FTP` class's 
+  Batista.)  Also, the :class:`FTP` class's
   :meth:`storbinary` and :meth:`storlines`
-  now take an optional *callback* parameter that will be called with 
+  now take an optional *callback* parameter that will be called with
   each block of data after the data has been sent.
   (Contributed by Phil Schwartz; :issue:`1221598`.)
 
-* The :func:`reduce` built-in function is also available in the 
+* The :func:`reduce` built-in function is also available in the
   :mod:`functools` module.  In Python 3.0, the built-in is dropped and it's
   only available from :mod:`functools`; currently there are no plans
-  to drop the built-in in the 2.x series.  (Patched by 
+  to drop the built-in in the 2.x series.  (Patched by
   Christian Heimes; :issue:`1739906`.)
 
-* The :func:`glob.glob` function can now return Unicode filenames if 
+* The :func:`glob.glob` function can now return Unicode filenames if
   a Unicode path was used and Unicode filenames are matched within the
   directory.  (:issue:`1001604`)
 
 * The :mod:`gopherlib` module has been removed.
 
-* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)`` 
+* A new function in the :mod:`heapq` module: ``merge(iter1, iter2, ...)``
   takes any number of iterables that return data *in sorted
   order*, and returns a new iterator that returns the contents of all
   the iterators, also in sorted order.  For example::
@@ -1718,25 +1749,25 @@
        [1, 2, 3, 5, 8, 9, 16]
 
   Another new function, ``heappushpop(heap, item)``,
-  pushes *item* onto *heap*, then pops off and returns the smallest item. 
+  pushes *item* onto *heap*, then pops off and returns the smallest item.
   This is more efficient than making a call to :func:`heappush` and then
   :func:`heappop`.
 
   (Contributed by Raymond Hettinger.)
 
 * An optional ``timeout`` parameter was added to the
-  :class:`httplib.HTTPConnection` and :class:`HTTPSConnection` 
+  :class:`httplib.HTTPConnection` and :class:`HTTPSConnection`
   class constructors, specifying a timeout measured in seconds.
   (Added by Facundo Batista.)
 
-* Most of the :mod:`inspect` module's functions, such as 
-  :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.  
+* Most of the :mod:`inspect` module's functions, such as
+  :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
   In addition to behaving like tuples, the elements of the  return value
   can also be accessed as attributes.
   (Contributed by Raymond Hettinger.)
 
-  Some new functions in the module include 
-  :func:`isgenerator`, :func:`isgeneratorfunction`, 
+  Some new functions in the module include
+  :func:`isgenerator`, :func:`isgeneratorfunction`,
   and :func:`isabstract`.
 
 * The :mod:`itertools` module gained several new functions.
@@ -1753,25 +1784,25 @@
   every possible combination of the elements returned from each iterable. ::
 
      itertools.product([1,2,3], [4,5,6]) ->
-       [(1, 4), (1, 5), (1, 6), 
-	(2, 4), (2, 5), (2, 6), 
+       [(1, 4), (1, 5), (1, 6),
+	(2, 4), (2, 5), (2, 6),
 	(3, 4), (3, 5), (3, 6)]
 
   The optional *repeat* keyword argument is used for taking the
-  product of an iterable or a set of iterables with themselves, 
+  product of an iterable or a set of iterables with themselves,
   repeated *N* times.  With a single iterable argument, *N*-tuples
   are returned::
 
      itertools.product([1,2], repeat=3)) ->
-       [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), 
+       [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
         (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
 
   With two iterables, *2N*-tuples are returned. ::
 
      itertools(product([1,2], [3,4], repeat=2) ->
-       [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4), 
-        (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4), 
-        (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4), 
+       [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
+        (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
+        (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
         (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
 
   ``combinations(iterable, r)`` returns sub-sequences of length *r* from
@@ -1784,35 +1815,35 @@
       [('1', '2', '3')]
 
     itertools.combinations('1234', 3) ->
-      [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'), 
+      [('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
        ('2', '3', '4')]
 
   ``permutations(iter[, r])`` returns all the permutations of length *r* of
-  the iterable's elements.  If *r* is not specified, it will default to the 
+  the iterable's elements.  If *r* is not specified, it will default to the
   number of elements produced by the iterable. ::
 
     itertools.permutations([1,2,3,4], 2) ->
-      [(1, 2), (1, 3), (1, 4), 
-       (2, 1), (2, 3), (2, 4), 
-       (3, 1), (3, 2), (3, 4), 
+      [(1, 2), (1, 3), (1, 4),
+       (2, 1), (2, 3), (2, 4),
+       (3, 1), (3, 2), (3, 4),
        (4, 1), (4, 2), (4, 3)]
 
   ``itertools.chain(*iterables)`` is an existing function in
   :mod:`itertools` that gained a new constructor in Python 2.6.
-  ``itertools.chain.from_iterable(iterable)`` takes a single 
+  ``itertools.chain.from_iterable(iterable)`` takes a single
   iterable that should return other iterables.  :func:`chain` will
   then return all the elements of the first iterable, then
   all the elements of the second, and so on. ::
 
     chain.from_iterable([[1,2,3], [4,5,6]]) ->
        [1, 2, 3, 4, 5, 6]
-  
+
   (All contributed by Raymond Hettinger.)
 
-* The :mod:`logging` module's :class:`FileHandler` class 
+* The :mod:`logging` module's :class:`FileHandler` class
   and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
-  and :class:`TimedRotatingFileHandler` now 
-  have an optional *delay* parameter to its constructor.  If *delay* 
+  and :class:`TimedRotatingFileHandler` now
+  have an optional *delay* parameter to its constructor.  If *delay*
   is true, opening of the log file is deferred until the first
   :meth:`emit` call is made.  (Contributed by Vinay Sajip.)
 
@@ -1827,16 +1858,16 @@
   the forward search.
   (Contributed by John Lenton.)
 
-* The :mod:`operator` module gained a 
-  :func:`methodcaller` function that takes a name and an optional 
-  set of arguments, returning a callable that will call 
+* The :mod:`operator` module gained a
+  :func:`methodcaller` function that takes a name and an optional
+  set of arguments, returning a callable that will call
   the named function on any arguments passed to it.  For example::
 
     >>> # Equivalent to lambda s: s.replace('old', 'new')
     >>> replacer = operator.methodcaller('replace', 'old', 'new')
     >>> replacer('old wine in old bottles')
     'new wine in new bottles'
-   
+
   (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)
 
   The :func:`attrgetter` function now accepts dotted names and performs
@@ -1850,8 +1881,8 @@
 
   (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)
 
-* New functions in the :mod:`os` module include 
-  ``fchmod(fd, mode)``,   ``fchown(fd, uid, gid)``,  
+* New functions in the :mod:`os` module include
+  ``fchmod(fd, mode)``,   ``fchown(fd, uid, gid)``,
   and ``lchmod(path, mode)``, on operating systems that support these
   functions. :func:`fchmod` and :func:`fchown` let you change the mode
   and ownership of an opened file, and :func:`lchmod` changes the mode
@@ -1865,8 +1896,8 @@
   parameter's default value is false.  Note that the function can fall
   into an infinite recursion if there's a symlink that points to a
   parent directory.  (:issue:`1273829`)
-       
-* The ``os.environ`` object's :meth:`clear` method will now unset the 
+
+* The ``os.environ`` object's :meth:`clear` method will now unset the
   environment variables using :func:`os.unsetenv` in addition to clearing
   the object's keys.  (Contributed by Martin Horcicka; :issue:`1181`.)
 
@@ -1882,23 +1913,23 @@
   working directory to the destination ``path``.  (Contributed by
   Richard Barran; :issue:`1339796`.)
 
-  On Windows, :func:`os.path.expandvars` will now expand environment variables 
-  in the form "%var%", and "~user" will be expanded into the 
+  On Windows, :func:`os.path.expandvars` will now expand environment variables
+  in the form "%var%", and "~user" will be expanded into the
   user's home directory path.  (Contributed by Josiah Carlson;
   :issue:`957650`.)
 
-* The Python debugger provided by the :mod:`pdb` module 
+* The Python debugger provided by the :mod:`pdb` module
   gained a new command: "run" restarts the Python program being debugged,
   and can optionally take new command-line arguments for the program.
   (Contributed by Rocky Bernstein; :issue:`1393667`.)
 
-  The :func:`post_mortem` function, used to enter debugging of a 
+  The :func:`post_mortem` function, used to enter debugging of a
   traceback, will now use the traceback returned by :func:`sys.exc_info`
   if no traceback is supplied.   (Contributed by Facundo Batista;
   :issue:`1106316`.)
 
-* The :mod:`pickletools` module now has an :func:`optimize` function 
-  that takes a string containing a pickle and removes some unused 
+* The :mod:`pickletools` module now has an :func:`optimize` function
+  that takes a string containing a pickle and removes some unused
   opcodes, returning a shorter pickle that contains the same data structure.
   (Contributed by Raymond Hettinger.)
 
@@ -1916,7 +1947,7 @@
           +-- StopIteration
           +-- StandardError
      ...'
-    >>> 
+    >>>
 
   (Contributed by Paul Moore; :issue:`2439`.)
 
@@ -1933,13 +1964,13 @@
   processes faster.  (Contributed by Georg Brandl; :issue:`1663329`.)
 
 * The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
-  their :attr:`buffer_size` attribute to change the size of the buffer 
+  their :attr:`buffer_size` attribute to change the size of the buffer
   used to hold character data.
   (Contributed by Achim Gaedke; :issue:`1137`.)
 
 * The :mod:`Queue` module now provides queue classes that retrieve entries
-  in different orders.  The :class:`PriorityQueue` class stores 
-  queued items in a heap and retrieves them in priority order, 
+  in different orders.  The :class:`PriorityQueue` class stores
+  queued items in a heap and retrieves them in priority order,
   and :class:`LifoQueue` retrieves the most recently added entries first,
   meaning that it behaves like a stack.
   (Contributed by Raymond Hettinger.)
@@ -1953,8 +1984,8 @@
 
   The new ``triangular(low, high, mode)`` function returns random
   numbers following a triangular distribution.   The returned values
-  are between *low* and *high*, not including *high* itself, and 
-  with *mode* as the mode, the most frequently occurring value 
+  are between *low* and *high*, not including *high* itself, and
+  with *mode* as the mode, the most frequently occurring value
   in the distribution.  (Contributed by Wladmir van der Laan and
   Raymond Hettinger; :issue:`1681432`.)
 
@@ -1965,8 +1996,8 @@
 
 * The :mod:`rgbimg` module has been removed.
 
-* The :mod:`sched` module's :class:`scheduler` instances now 
-  have a read-only :attr:`queue` attribute that returns the 
+* The :mod:`sched` module's :class:`scheduler` instances now
+  have a read-only :attr:`queue` attribute that returns the
   contents of the scheduler's queue, represented as a list of
   named tuples with the fields ``(time, priority, action, argument)``.
   (Contributed by Raymond Hettinger; :issue:`1861`.)
@@ -1975,19 +2006,19 @@
   for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls.
   Also, a :meth:`modify` method was added to the existing :class:`poll`
   objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
-  or file object and an event mask, 
-  
+  or file object and an event mask,
+
   (Contributed by Christian Heimes; :issue:`1657`.)
 
-* The :mod:`sets` module has been deprecated; it's better to 
+* The :mod:`sets` module has been deprecated; it's better to
   use the built-in :class:`set` and :class:`frozenset` types.
 
-* Integrating signal handling with GUI handling event loops 
+* Integrating signal handling with GUI handling event loops
   like those used by Tkinter or GTk+ has long been a problem; most
   software ends up polling, waking up every fraction of a second.
   The :mod:`signal` module can now make this more efficient.
   Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
-  to be used; when a signal is received, a byte is written to that 
+  to be used; when a signal is received, a byte is written to that
   file descriptor.  There's also a C-level function,
   :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor.
 
@@ -1996,7 +2027,7 @@
   will be passed to :func:`set_wakeup_fd`, and the readable descriptor
   will be added to the list of descriptors monitored by the event loop via
   :cfunc:`select` or :cfunc:`poll`.
-  On receiving a signal, a byte will be written and the main event loop 
+  On receiving a signal, a byte will be written and the main event loop
   will be woken up, without the need to poll.
 
   (Contributed by Adam Olsen; :issue:`1583`.)
@@ -2014,7 +2045,7 @@
 
 * The :mod:`smtplib` module now supports SMTP over SSL thanks to the
   addition of the :class:`SMTP_SSL` class. This class supports an
-  interface identical to the existing :class:`SMTP` class.   Both 
+  interface identical to the existing :class:`SMTP` class.   Both
   class constructors also have an optional ``timeout`` parameter
   that specifies a timeout for the initial connection attempt, measured in
   seconds.
@@ -2037,35 +2068,35 @@
   environments.  TIPC addresses are 4- or 5-tuples.
   (Contributed by Alberto Bertogli; :issue:`1646`.)
 
-  A new function, :func:`create_connection`, takes an address 
-  and connects to it using an optional timeout value, returning 
+  A new function, :func:`create_connection`, takes an address
+  and connects to it using an optional timeout value, returning
   the connected socket object.
 
 * The base classes in the :mod:`SocketServer` module now support
-  calling a :meth:`handle_timeout` method after a span of inactivity 
-  specified by the server's :attr:`timeout` attribute.  (Contributed 
-  by Michael Pomraning.)  The :meth:`serve_forever` method 
+  calling a :meth:`handle_timeout` method after a span of inactivity
+  specified by the server's :attr:`timeout` attribute.  (Contributed
+  by Michael Pomraning.)  The :meth:`serve_forever` method
   now takes an optional poll interval measured in seconds,
   controlling how often the server will check for a shutdown request.
-  (Contributed by Pedro Werneck and Jeffrey Yasskin; 
+  (Contributed by Pedro Werneck and Jeffrey Yasskin;
   :issue:`742598`, :issue:`1193577`.)
 
 * The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
-  using the format character ``'?'``. 
+  using the format character ``'?'``.
   (Contributed by David Remahl.)
 
 * The :class:`Popen` objects provided by the :mod:`subprocess` module
   now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods.
   On Windows, :meth:`send_signal` only supports the :const:`SIGTERM`
   signal, and all these methods are aliases for the Win32 API function
-  :cfunc:`TerminateProcess`.  
+  :cfunc:`TerminateProcess`.
   (Contributed by Christian Heimes.)
- 
+
 * A new variable in the :mod:`sys` module,
   :attr:`float_info`, is an object
   containing information about the platform's floating-point support
   derived from the :file:`float.h` file.  Attributes of this object
-  include 
+  include
   :attr:`mant_dig` (number of digits in the mantissa), :attr:`epsilon`
   (smallest difference between 1.0 and the next largest value
   representable), and several others.  (Contributed by Christian Heimes;
@@ -2077,25 +2108,25 @@
   variable is initially set on start-up by supplying the :option:`-B`
   switch to the Python interpreter, or by setting the
   :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
-  running the interpreter.  Python code can subsequently 
+  running the interpreter.  Python code can subsequently
   change the value of this variable to control whether bytecode files
   are written or not.
   (Contributed by Neal Norwitz and Georg Brandl.)
 
-  Information about the command-line arguments supplied to the Python 
-  interpreter are available as attributes of a ``sys.flags`` named 
-  tuple.  For example, the :attr:`verbose` attribute is true if Python 
+  Information about the command-line arguments supplied to the Python
+  interpreter are available as attributes of a ``sys.flags`` named
+  tuple.  For example, the :attr:`verbose` attribute is true if Python
   was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
   These attributes are all read-only.
   (Contributed by Christian Heimes.)
 
   It's now possible to determine the current profiler and tracer functions
-  by calling :func:`sys.getprofile` and :func:`sys.gettrace`.  
+  by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
   (Contributed by Georg Brandl; :issue:`1648`.)
 
 * The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and
   POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar
-  format that was already supported.  The default format 
+  format that was already supported.  The default format
   is GNU tar; specify the ``format`` parameter to open a file
   using a different format::
 
@@ -2110,37 +2141,37 @@
 
   The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's
   a function that can be used to exclude certain filenames from
-  an archive. 
-  The function must take a filename and return true if the file 
+  an archive.
+  The function must take a filename and return true if the file
   should be excluded or false if it should be archived.
   The function is applied to both the name initially passed to :meth:`add`
   and to the names of files in recursively-added directories.
-  
+
   (All changes contributed by Lars Gustäbel).
 
 * An optional ``timeout`` parameter was added to the
   :class:`telnetlib.Telnet` class constructor, specifying a timeout
   measured in seconds.  (Added by Facundo Batista.)
 
-* The :class:`tempfile.NamedTemporaryFile` class usually deletes 
-  the temporary file it created when the file is closed.  This 
-  behaviour can now be changed by passing ``delete=False`` to the 
+* The :class:`tempfile.NamedTemporaryFile` class usually deletes
+  the temporary file it created when the file is closed.  This
+  behaviour can now be changed by passing ``delete=False`` to the
   constructor.  (Contributed by Damien Miller; :issue:`1537850`.)
 
-  A new class, :class:`SpooledTemporaryFile`, behaves like 
-  a temporary file but stores its data in memory until a maximum size is 
-  exceeded.  On reaching that limit, the contents will be written to 
+  A new class, :class:`SpooledTemporaryFile`, behaves like
+  a temporary file but stores its data in memory until a maximum size is
+  exceeded.  On reaching that limit, the contents will be written to
   an on-disk temporary file.  (Contributed by Dustin J. Mitchell.)
 
   The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
-  both work as context managers, so you can write 
+  both work as context managers, so you can write
   ``with tempfile.NamedTemporaryFile() as tmp: ...``.
   (Contributed by Alexander Belopolsky; :issue:`2021`.)
 
 * The :mod:`test.test_support` module now contains a
   :func:`EnvironmentVarGuard`
   context manager that  supports temporarily changing environment variables and
-  automatically restores them to their old values. 
+  automatically restores them to their old values.
 
   Another context manager, :class:`TransientResource`, can surround calls
   to resources that may or may not be available; it will catch and
@@ -2149,12 +2180,12 @@
   external web site::
 
       with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT):
-          f = urllib.urlopen('https://sf.net')                         
+          f = urllib.urlopen('https://sf.net')
           ...
 
   (Contributed by Brett Cannon.)
 
-* The :mod:`textwrap` module can now preserve existing whitespace 
+* The :mod:`textwrap` module can now preserve existing whitespace
   at the beginnings and ends of the newly-created lines
   by specifying ``drop_whitespace=False``
   as an argument::
@@ -2170,22 +2201,22 @@
       has a bunch
        of    extra
        whitespace.
-    >>> 
+    >>>
 
   (Contributed by Dwayne Bailey; :issue:`1581073`.)
 
-* The :mod:`timeit` module now accepts callables as well as strings 
+* The :mod:`timeit` module now accepts callables as well as strings
   for the statement being timed and for the setup code.
-  Two convenience functions were added for creating 
-  :class:`Timer` instances: 
-  ``repeat(stmt, setup, time, repeat, number)`` and 
+  Two convenience functions were added for creating
+  :class:`Timer` instances:
+  ``repeat(stmt, setup, time, repeat, number)`` and
   ``timeit(stmt, setup, time, number)`` create an instance and call
   the corresponding method. (Contributed by Erik Demaine;
   :issue:`1533909`.)
 
 * An optional ``timeout`` parameter was added to the
   :func:`urllib.urlopen` function and the
-  :class:`urllib.ftpwrapper` class constructor, as well as the 
+  :class:`urllib.ftpwrapper` class constructor, as well as the
   :func:`urllib2.urlopen` function.  The parameter specifies a timeout
   measured in seconds.   For example::
 
@@ -2193,11 +2224,11 @@
      Traceback (most recent call last):
        ...
      urllib2.URLError: <urlopen error timed out>
-     >>>   
+     >>>
 
-  (Added by Facundo Batista.) 
+  (Added by Facundo Batista.)
 
-* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning` 
+* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
   gained an optional *line* argument that can be used to supply the
   line of source code.  (Added as part of :issue:`1631171`, which re-implemented
   part of the :mod:`warnings` module in C code.)
@@ -2206,30 +2237,30 @@
   classes can now be prevented from immediately opening and binding to
   their socket by passing True as the ``bind_and_activate``
   constructor parameter.  This can be used to modify the instance's
-  :attr:`allow_reuse_address` attribute before calling the 
-  :meth:`server_bind` and :meth:`server_activate` methods to 
+  :attr:`allow_reuse_address` attribute before calling the
+  :meth:`server_bind` and :meth:`server_activate` methods to
   open the socket and begin listening for connections.
   (Contributed by Peter Parente; :issue:`1599845`.)
 
   :class:`SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
-  attribute; if true, the exception and formatted traceback are returned 
-  as HTTP headers "X-Exception" and "X-Traceback".  This feature is 
+  attribute; if true, the exception and formatted traceback are returned
+  as HTTP headers "X-Exception" and "X-Traceback".  This feature is
   for debugging purposes only and should not be used on production servers
   because the tracebacks could possibly reveal passwords or other sensitive
-  information.  (Contributed by Alan McIntyre as part of his 
+  information.  (Contributed by Alan McIntyre as part of his
   project for Google's Summer of Code 2007.)
 
 * The :mod:`xmlrpclib` module no longer automatically converts
-  :class:`datetime.date` and :class:`datetime.time` to the 
+  :class:`datetime.date` and :class:`datetime.time` to the
   :class:`xmlrpclib.DateTime` type; the conversion semantics were
   not necessarily correct for all applications.  Code using
-  :mod:`xmlrpclib` should convert :class:`date` and :class:`time` 
-  instances. (:issue:`1330538`)  The code can also handle 
+  :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
+  instances. (:issue:`1330538`)  The code can also handle
   dates before 1900.  (Contributed by Ralf Schmitt; :issue:`2014`.)
 
-* The :mod:`zipfile` module's :class:`ZipFile` class now has 
-  :meth:`extract` and :meth:`extractall` methods that will unpack 
-  a single file or all the files in the archive to the current directory, or 
+* The :mod:`zipfile` module's :class:`ZipFile` class now has
+  :meth:`extract` and :meth:`extractall` methods that will unpack
+  a single file or all the files in the archive to the current directory, or
   to a specified directory::
 
     z = zipfile.ZipFile('python-251.zip')
@@ -2300,12 +2331,12 @@
 plistlib: A Property-List Parser
 --------------------------------------------------
 
-A commonly-used format on MacOS X is the ``.plist`` format, 
-which stores basic data types (numbers, strings, lists, 
+A commonly-used format on MacOS X is the ``.plist`` format,
+which stores basic data types (numbers, strings, lists,
 and dictionaries) and serializes them into an XML-based format.
 (It's a lot like the XML-RPC serialization of data types.)
 
-Despite being primarily used on MacOS X, the format 
+Despite being primarily used on MacOS X, the format
 has nothing Mac-specific about it and the Python implementation works
 on any platform that Python supports, so the :mod:`plistlib` module
 has been promoted to the standard library.
@@ -2333,7 +2364,7 @@
 
     # read/writePlist accepts file-like objects as well as paths.
     plistlib.writePlist(data_struct, sys.stdout)
-   
+
 
 .. ======================================================================
 
@@ -2352,25 +2383,25 @@
   own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which
   are in the C89 standard library.
 
-* The BerkeleyDB module now has a C API object, available as 
+* The BerkeleyDB module now has a C API object, available as
   ``bsddb.db.api``.   This object can be used by other C extensions
   that wish to use the :mod:`bsddb` module for their own purposes.
   (Contributed by Duncan Grisby; :issue:`1551895`.)
 
-* The new buffer interface, previously described in 
+* The new buffer interface, previously described in
   `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__,
   adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyObject_ReleaseBuffer`,
   as well as a few other functions.
 
 * Python's use of the C stdio library is now thread-safe, or at least
   as thread-safe as the underlying library is.  A long-standing potential
-  bug occurred if one thread closed a file object while another thread 
-  was reading from or writing to the object.  In 2.6 file objects 
-  have a reference count, manipulated by the 
+  bug occurred if one thread closed a file object while another thread
+  was reading from or writing to the object.  In 2.6 file objects
+  have a reference count, manipulated by the
   :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount`
-  functions.  File objects can't be closed unless the reference count 
-  is zero.  :cfunc:`PyFile_IncUseCount` should be called while the GIL 
-  is still held, before carrying out an I/O operation using the 
+  functions.  File objects can't be closed unless the reference count
+  is zero.  :cfunc:`PyFile_IncUseCount` should be called while the GIL
+  is still held, before carrying out an I/O operation using the
   ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called
   immediately after the GIL is re-acquired.
   (Contributed by Antoine Pitrou and Gregory P. Smith.)
@@ -2383,11 +2414,11 @@
   thread, the :exc:`ImportError` is raised.
   (Contributed by Christian Heimes.)
 
-* Several functions return information about the platform's 
+* Several functions return information about the platform's
   floating-point support.  :cfunc:`PyFloat_GetMax` returns
   the maximum representable floating point value,
-  and :cfunc:`PyFloat_GetMin` returns the minimum 
-  positive value.  :cfunc:`PyFloat_GetInfo` returns a dictionary 
+  and :cfunc:`PyFloat_GetMin` returns the minimum
+  positive value.  :cfunc:`PyFloat_GetInfo` returns a dictionary
   containing more information from the :file:`float.h` file, such as
   ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
   (smallest difference between 1.0 and the next largest value
@@ -2399,23 +2430,23 @@
   and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
   (Contributed by Christian Heimes; :issue:`1635`.)
 
-* Many C extensions define their own little macro for adding 
-  integers and strings to the module's dictionary in the 
-  ``init*`` function.  Python 2.6 finally defines standard macros 
+* Many C extensions define their own little macro for adding
+  integers and strings to the module's dictionary in the
+  ``init*`` function.  Python 2.6 finally defines standard macros
   for adding values to a module, :cmacro:`PyModule_AddStringMacro`
-  and :cmacro:`PyModule_AddIntMacro()`.  (Contributed by 
+  and :cmacro:`PyModule_AddIntMacro()`.  (Contributed by
   Christian Heimes.)
 
 * Some macros were renamed in both 3.0 and 2.6 to make it clearer that
   they are macros,
   not functions.  :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`,
   :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and
-  :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.  
+  :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`.
   The mixed-case macros are still available
   in Python 2.6 for backward compatibility.
   (:issue:`1629`)
 
-* Distutils now places C extensions it builds in a 
+* Distutils now places C extensions it builds in a
   different directory when running on a debug version of Python.
   (Contributed by Collin Winter; :issue:`1530959`.)
 
@@ -2427,7 +2458,7 @@
   always defined.
 
 * A new Makefile target, "make check", prepares the Python source tree
-  for making a patch: it fixes trailing whitespace in all modified 
+  for making a patch: it fixes trailing whitespace in all modified
   ``.py`` files, checks whether the documentation has been changed,
   and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files
   have been updated.
@@ -2449,35 +2480,35 @@
 * The support for Windows 95, 98, ME and NT4 has been dropped.
   Python 2.6 requires at least Windows 2000 SP4.
 
-* The :mod:`msvcrt` module now supports 
+* The :mod:`msvcrt` module now supports
   both the normal and wide char variants of the console I/O
-  API.  The :func:`getwch` function reads a keypress and returns a Unicode 
+  API.  The :func:`getwch` function reads a keypress and returns a Unicode
   value, as does the :func:`getwche` function.  The :func:`putwch` function
   takes a Unicode character and writes it to the console.
   (Contributed by Christian Heimes.)
 
-* :func:`os.path.expandvars` will now expand environment variables 
-  in the form "%var%", and "~user" will be expanded into the 
+* :func:`os.path.expandvars` will now expand environment variables
+  in the form "%var%", and "~user" will be expanded into the
   user's home directory path.  (Contributed by Josiah Carlson.)
 
-* The :mod:`socket` module's socket objects now have an 
-  :meth:`ioctl` method that provides a limited interface to the 
+* The :mod:`socket` module's socket objects now have an
+  :meth:`ioctl` method that provides a limited interface to the
   :cfunc:`WSAIoctl` system interface.
 
-* The :mod:`_winreg` module now has a function, 
-  :func:`ExpandEnvironmentStrings`, 
+* The :mod:`_winreg` module now has a function,
+  :func:`ExpandEnvironmentStrings`,
   that expands environment variable references such as ``%NAME%``
   in an input string.  The handle objects provided by this
-  module now support the context protocol, so they can be used 
+  module now support the context protocol, so they can be used
   in :keyword:`with` statements. (Contributed by Christian Heimes.)
 
-  :mod:`_winreg` also has better support for x64 systems, 
+  :mod:`_winreg` also has better support for x64 systems,
   exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`,
   and :func:`QueryReflectionKey` functions, which enable and disable
   registry reflection for 32-bit processes running on 64-bit systems.
   (:issue:`1753245`)
 
-* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The 
+* The new default compiler on Windows is Visual Studio 2008 (VS 9.0). The
   build directories for Visual Studio 2003 (VS7.1) and 2005 (VS8.0)
   were moved into the PC/ directory. The new PCbuild directory supports
   cross compilation for X64, debug builds and Profile Guided Optimization
@@ -2500,7 +2531,7 @@
 
 Some of the more notable changes are:
 
-* It's now possible to prevent Python from writing any :file:`.pyc` 
+* It's now possible to prevent Python from writing any :file:`.pyc`
   or :file:`.pyo` files by either supplying the :option:`-B` switch
   or setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable
   to any non-empty string when running the Python interpreter.  These
@@ -2521,23 +2552,23 @@
 * The :meth:`__init__` method of :class:`collections.deque`
   now clears any existing contents of the deque
   before adding elements from the iterable.  This change makes the
-  behavior match that of ``list.__init__()``.  
+  behavior match that of ``list.__init__()``.
 
-* The :class:`Decimal` constructor now accepts leading and trailing 
+* The :class:`Decimal` constructor now accepts leading and trailing
   whitespace when passed a string.  Previously it would raise an
   :exc:`InvalidOperation` exception.  On the other hand, the
   :meth:`create_decimal` method of :class:`Context` objects now
-  explicitly disallows extra whitespace, raising a 
+  explicitly disallows extra whitespace, raising a
   :exc:`ConversionSyntax` exception.
 
-* Due to an implementation accident, if you passed a file path to 
+* Due to an implementation accident, if you passed a file path to
   the built-in  :func:`__import__` function, it would actually import
-  the specified file.  This was never intended to work, however, and 
-  the implementation now explicitly checks for this case and raises 
+  the specified file.  This was never intended to work, however, and
+  the implementation now explicitly checks for this case and raises
   an :exc:`ImportError`.
 
 * C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule`
-  functions now default to absolute imports, not relative imports.  
+  functions now default to absolute imports, not relative imports.
   This will affect C extensions that import other modules.
 
 * The :mod:`socket` module exception :exc:`socket.error` now inherits
@@ -2546,21 +2577,21 @@
   (Implemented by Gregory P. Smith; :issue:`1706815`.)
 
 * The :mod:`xmlrpclib` module no longer automatically converts
-  :class:`datetime.date` and :class:`datetime.time` to the 
+  :class:`datetime.date` and :class:`datetime.time` to the
   :class:`xmlrpclib.DateTime` type; the conversion semantics were
   not necessarily correct for all applications.  Code using
-  :mod:`xmlrpclib` should convert :class:`date` and :class:`time` 
+  :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
   instances. (:issue:`1330538`)
 
-* (3.0-warning mode) The :class:`Exception` class now warns 
-  when accessed using slicing or index access; having 
+* (3.0-warning mode) The :class:`Exception` class now warns
+  when accessed using slicing or index access; having
   :class:`Exception` behave like a tuple is being phased out.
 
 * (3.0-warning mode) inequality comparisons between two dictionaries
   or two objects that don't implement comparison methods are reported
   as warnings.  ``dict1 == dict2`` still works, but ``dict1 < dict2``
   is being phased out.
-  
+
   Comparisons between cells, which are an implementation detail of Python's
   scoping rules, also cause warnings because such comparisons are forbidden
   entirely in 3.0.
@@ -2574,6 +2605,6 @@
 ================
 
 The author would like to thank the following people for offering suggestions,
-corrections and assistance with various drafts of this article: 
+corrections and assistance with various drafts of this article:
 Georg Brandl, Jim Jewett.
 

Modified: python/branches/okkoto-sizeof/Include/Python.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/Python.h	(original)
+++ python/branches/okkoto-sizeof/Include/Python.h	Wed Jun  4 11:24:23 2008
@@ -94,6 +94,7 @@
 /* #include "memoryobject.h" */
 #include "bufferobject.h"
 #include "bytesobject.h"
+#include "bytearrayobject.h"
 #include "tupleobject.h"
 #include "listobject.h"
 #include "dictobject.h"

Modified: python/branches/okkoto-sizeof/Include/fileobject.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/fileobject.h	(original)
+++ python/branches/okkoto-sizeof/Include/fileobject.h	Wed Jun  4 11:24:23 2008
@@ -24,6 +24,7 @@
 	int f_newlinetypes;	/* Types of newlines seen */
 	int f_skipnextlf;	/* Skip next \n */
 	PyObject *f_encoding;
+	PyObject *f_errors;
 	PyObject *weakreflist; /* List of weak references */
 	int unlocked_count;	/* Num. currently running sections of code
 				   using f_fp with the GIL released. */
@@ -37,6 +38,7 @@
 PyAPI_FUNC(PyObject *) PyFile_FromString(char *, char *);
 PyAPI_FUNC(void) PyFile_SetBufSize(PyObject *, int);
 PyAPI_FUNC(int) PyFile_SetEncoding(PyObject *, const char *);
+PyAPI_FUNC(int) PyFile_SetEncodingAndErrors(PyObject *, const char *, char *errors);
 PyAPI_FUNC(PyObject *) PyFile_FromFile(FILE *, char *, char *,
                                              int (*)(FILE *));
 PyAPI_FUNC(FILE *) PyFile_AsFile(PyObject *);

Modified: python/branches/okkoto-sizeof/Include/floatobject.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/floatobject.h	(original)
+++ python/branches/okkoto-sizeof/Include/floatobject.h	Wed Jun  4 11:24:23 2008
@@ -115,6 +115,12 @@
 /* free list api */
 PyAPI_FUNC(void) PyFloat_CompactFreeList(size_t *, size_t *, size_t *);
 
+/* Format the object based on the format_spec, as defined in PEP 3101
+   (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyFloat_FormatAdvanced(PyObject *obj,
+					       char *format_spec,
+					       Py_ssize_t format_spec_len);
+
 #ifdef __cplusplus
 }
 #endif

Deleted: python/branches/okkoto-sizeof/Include/formatter_string.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/formatter_string.h	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,12 +0,0 @@
-PyObject *
-string__format__(PyObject *self, PyObject *args);
-
-PyObject *
-string_long__format__(PyObject *self, PyObject *args);
-
-PyObject *
-string_int__format__(PyObject *self, PyObject *args);
-
-PyObject *
-string_float__format__(PyObject *self, PyObject *args);
-

Deleted: python/branches/okkoto-sizeof/Include/formatter_unicode.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/formatter_unicode.h	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,12 +0,0 @@
-PyObject *
-unicode__format__(PyObject *self, PyObject *args);
-
-PyObject *
-unicode_long__format__(PyObject *self, PyObject *args);
-
-PyObject *
-unicode_int__format__(PyObject *self, PyObject *args);
-
-PyObject *
-unicode_float__format__(PyObject *self, PyObject *args);
-

Modified: python/branches/okkoto-sizeof/Include/intobject.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/intobject.h	(original)
+++ python/branches/okkoto-sizeof/Include/intobject.h	Wed Jun  4 11:24:23 2008
@@ -68,6 +68,12 @@
    a leading "0" */
 PyAPI_FUNC(PyObject*) _PyInt_Format(PyIntObject* v, int base, int newstyle);
 
+/* Format the object based on the format_spec, as defined in PEP 3101
+   (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyInt_FormatAdvanced(PyObject *obj,
+					     char *format_spec,
+					     Py_ssize_t format_spec_len);
+
 #ifdef __cplusplus
 }
 #endif

Modified: python/branches/okkoto-sizeof/Include/longobject.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/longobject.h	(original)
+++ python/branches/okkoto-sizeof/Include/longobject.h	Wed Jun  4 11:24:23 2008
@@ -119,6 +119,12 @@
    a leading "0", instead of the prefix "0o" */
 PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *aa, int base, int addL, int newstyle);
 
+/* Format the object based on the format_spec, as defined in PEP 3101
+   (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyLong_FormatAdvanced(PyObject *obj,
+					      char *format_spec,
+					      Py_ssize_t format_spec_len);
+
 #ifdef __cplusplus
 }
 #endif

Modified: python/branches/okkoto-sizeof/Include/object.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/object.h	(original)
+++ python/branches/okkoto-sizeof/Include/object.h	Wed Jun  4 11:24:23 2008
@@ -460,6 +460,7 @@
 					       PyObject *, PyObject *);
 PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
 PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
+PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
 
 /* Generic operations on objects */
 PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
@@ -514,7 +515,7 @@
 PyAPI_FUNC(long) _Py_HashPointer(void*);
 
 /* Helper for passing objects to printf and the like */
-#define PyObject_REPR(obj) PyString_AS_STRING(PyObject_Repr(obj))
+#define PyObject_REPR(obj) PyBytes_AS_STRING(PyObject_Repr(obj))
 
 /* Flag bits for printing: */
 #define Py_PRINT_RAW	1	/* No string quotes etc. */
@@ -608,7 +609,7 @@
 #define Py_TPFLAGS_LONG_SUBCLASS	(1L<<24)
 #define Py_TPFLAGS_LIST_SUBCLASS	(1L<<25)
 #define Py_TPFLAGS_TUPLE_SUBCLASS	(1L<<26)
-#define Py_TPFLAGS_STRING_SUBCLASS	(1L<<27)
+#define Py_TPFLAGS_BYTES_SUBCLASS	(1L<<27)
 #define Py_TPFLAGS_UNICODE_SUBCLASS	(1L<<28)
 #define Py_TPFLAGS_DICT_SUBCLASS	(1L<<29)
 #define Py_TPFLAGS_BASE_EXC_SUBCLASS	(1L<<30)

Modified: python/branches/okkoto-sizeof/Include/py_curses.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/py_curses.h	(original)
+++ python/branches/okkoto-sizeof/Include/py_curses.h	Wed Jun  4 11:24:23 2008
@@ -146,7 +146,7 @@
 static PyObject *PyCurses_ ## X (PyObject *self) \
 { \
   PyCursesInitialised \
-  return PyString_FromString(X()); }
+  return PyBytes_FromString(X()); }
 
 #define NoArgTrueFalseFunction(X) \
 static PyObject *PyCurses_ ## X (PyObject *self) \

Modified: python/branches/okkoto-sizeof/Include/pyerrors.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/pyerrors.h	(original)
+++ python/branches/okkoto-sizeof/Include/pyerrors.h	Wed Jun  4 11:24:23 2008
@@ -104,7 +104,7 @@
 
 #define PyExceptionClass_Name(x)				   \
 	(PyClass_Check((x))					   \
-	 ? PyString_AS_STRING(((PyClassObject*)(x))->cl_name)	   \
+	 ? PyBytes_AS_STRING(((PyClassObject*)(x))->cl_name)	   \
 	 : (char *)(((PyTypeObject*)(x))->tp_name))
 
 #define PyExceptionInstance_Class(x)					\

Modified: python/branches/okkoto-sizeof/Include/pyport.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/pyport.h	(original)
+++ python/branches/okkoto-sizeof/Include/pyport.h	Wed Jun  4 11:24:23 2008
@@ -135,9 +135,9 @@
  * all platforms (Python interprets the format string itself, and does whatever
  * the platform C requires to convert a size_t/Py_ssize_t argument):
  *
- *     PyString_FromFormat
+ *     PyBytes_FromFormat
  *     PyErr_Format
- *     PyString_FromFormatV
+ *     PyBytes_FromFormatV
  *
  * Lower-level uses require that you interpolate the correct format modifier
  * yourself (e.g., calling printf, fprintf, sprintf, PyOS_snprintf); for
@@ -454,6 +454,13 @@
 extern char * _getpty(int *, int, mode_t, int);
 #endif
 
+/* On QNX 6, struct termio must be declared by including sys/termio.h
+   if TCGETA, TCSETA, TCSETAW, or TCSETAF are used.  sys/termio.h must
+   be included before termios.h or it will generate an error. */
+#ifdef HAVE_SYS_TERMIO_H
+#include <sys/termio.h>
+#endif
+
 #if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY)
 #if !defined(HAVE_PTY_H) && !defined(HAVE_LIBUTIL_H)
 /* BSDI does not supply a prototype for the 'openpty' and 'forkpty'

Modified: python/branches/okkoto-sizeof/Include/pythonrun.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/pythonrun.h	(original)
+++ python/branches/okkoto-sizeof/Include/pythonrun.h	Wed Jun  4 11:24:23 2008
@@ -124,7 +124,7 @@
 PyAPI_FUNC(int) _PyFrame_Init(void);
 PyAPI_FUNC(int) _PyInt_Init(void);
 PyAPI_FUNC(void) _PyFloat_Init(void);
-PyAPI_FUNC(int) PyBytes_Init(void);
+PyAPI_FUNC(int) PyByteArray_Init(void);
 
 /* Various internal finalizers */
 PyAPI_FUNC(void) _PyExc_Fini(void);
@@ -136,11 +136,11 @@
 PyAPI_FUNC(void) PyTuple_Fini(void);
 PyAPI_FUNC(void) PyList_Fini(void);
 PyAPI_FUNC(void) PySet_Fini(void);
-PyAPI_FUNC(void) PyString_Fini(void);
+PyAPI_FUNC(void) PyBytes_Fini(void);
 PyAPI_FUNC(void) PyInt_Fini(void);
 PyAPI_FUNC(void) PyFloat_Fini(void);
 PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
-PyAPI_FUNC(void) PyBytes_Fini(void);
+PyAPI_FUNC(void) PyByteArray_Fini(void);
 
 /* Stuff with no proper home (yet) */
 PyAPI_FUNC(char *) PyOS_Readline(FILE *, FILE *, char *);

Modified: python/branches/okkoto-sizeof/Include/unicodeobject.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/unicodeobject.h	(original)
+++ python/branches/okkoto-sizeof/Include/unicodeobject.h	Wed Jun  4 11:24:23 2008
@@ -553,6 +553,12 @@
 PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(const char*, va_list);
 PyAPI_FUNC(PyObject *) PyUnicode_FromFormat(const char*, ...);
 
+/* Format the object based on the format_spec, as defined in PEP 3101
+   (Advanced String Formatting). */
+PyAPI_FUNC(PyObject *) _PyUnicode_FormatAdvanced(PyObject *obj,
+						 Py_UNICODE *format_spec,
+						 Py_ssize_t format_spec_len);
+
 /* --- wchar_t support for platforms which support it --------------------- */
 
 #ifdef HAVE_WCHAR_H

Modified: python/branches/okkoto-sizeof/Include/warnings.h
==============================================================================
--- python/branches/okkoto-sizeof/Include/warnings.h	(original)
+++ python/branches/okkoto-sizeof/Include/warnings.h	Wed Jun  4 11:24:23 2008
@@ -9,7 +9,9 @@
 PyAPI_FUNC(int) PyErr_WarnEx(PyObject *, const char *, Py_ssize_t);
 PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, const char *, int,
                                     const char *, PyObject *);
-PyAPI_FUNC(int) PyErr_WarnPy3k(const char *, Py_ssize_t);
+
+#define PyErr_WarnPy3k(msg, stacklevel) \
+  (Py_Py3kWarningFlag ? PyErr_WarnEx(PyExc_DeprecationWarning, msg, stacklevel) : 0)
 
 /* DEPRECATED: Use PyErr_WarnEx() instead. */
 #define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1)

Modified: python/branches/okkoto-sizeof/Lib/BaseHTTPServer.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/BaseHTTPServer.py	(original)
+++ python/branches/okkoto-sizeof/Lib/BaseHTTPServer.py	Wed Jun  4 11:24:23 2008
@@ -74,7 +74,7 @@
 import time
 import socket # For gethostbyaddr()
 import mimetools
-import socketserver
+import SocketServer
 
 # Default error message template
 DEFAULT_ERROR_MESSAGE = """\
@@ -94,19 +94,19 @@
 def _quote_html(html):
     return html.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
 
-class HTTPServer(socketserver.TCPServer):
+class HTTPServer(SocketServer.TCPServer):
 
     allow_reuse_address = 1    # Seems to make sense in testing environment
 
     def server_bind(self):
         """Override server_bind to store the server name."""
-        socketserver.TCPServer.server_bind(self)
+        SocketServer.TCPServer.server_bind(self)
         host, port = self.socket.getsockname()[:2]
         self.server_name = socket.getfqdn(host)
         self.server_port = port
 
 
-class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
+class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
 
     """HTTP request handler base class.
 
@@ -218,6 +218,12 @@
     # where each string is of the form name[/version].
     server_version = "BaseHTTP/" + __version__
 
+    # The default request version.  This only affects responses up until
+    # the point where the request line is parsed, so it mainly decides what
+    # the client gets back when sending a malformed request line.
+    # Most web servers default to HTTP 0.9, i.e. don't send a status line.
+    default_request_version = "HTTP/0.9"
+
     def parse_request(self):
         """Parse a request (internal).
 
@@ -230,7 +236,7 @@
 
         """
         self.command = None  # set in case of error on the first line
-        self.request_version = version = "HTTP/0.9" # Default
+        self.request_version = version = self.default_request_version
         self.close_connection = 1
         requestline = self.raw_requestline
         if requestline[-2:] == '\r\n':

Modified: python/branches/okkoto-sizeof/Lib/SimpleXMLRPCServer.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/SimpleXMLRPCServer.py	(original)
+++ python/branches/okkoto-sizeof/Lib/SimpleXMLRPCServer.py	Wed Jun  4 11:24:23 2008
@@ -101,7 +101,7 @@
 
 import xmlrpclib
 from xmlrpclib import Fault
-import socketserver
+import SocketServer
 import BaseHTTPServer
 import sys
 import os
@@ -512,7 +512,7 @@
         if self.server.logRequests:
             BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
 
-class SimpleXMLRPCServer(socketserver.TCPServer,
+class SimpleXMLRPCServer(SocketServer.TCPServer,
                          SimpleXMLRPCDispatcher):
     """Simple XML-RPC server.
 
@@ -536,7 +536,7 @@
         self.logRequests = logRequests
 
         SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
-        socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
+        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
 
         # [Bug #1222790] If possible, set close-on-exec flag; if a
         # method spawns a subprocess, the subprocess shouldn't have

Modified: python/branches/okkoto-sizeof/Lib/UserString.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/UserString.py	(original)
+++ python/branches/okkoto-sizeof/Lib/UserString.py	Wed Jun  4 11:24:23 2008
@@ -146,6 +146,9 @@
 
     A faster and better solution is to rewrite your program using lists."""
     def __init__(self, string=""):
+        from warnings import warnpy3k
+        warnpy3k('the class UserString.MutableString has been removed in '
+                    'Python 3.0', stacklevel=2)
         self.data = string
     def __hash__(self):
         raise TypeError, "unhashable type (it is mutable)"

Modified: python/branches/okkoto-sizeof/Lib/bdb.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bdb.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bdb.py	Wed Jun  4 11:24:23 2008
@@ -325,7 +325,7 @@
     #
 
     def format_stack_entry(self, frame_lineno, lprefix=': '):
-        import linecache, reprlib
+        import linecache, repr
         frame, lineno = frame_lineno
         filename = self.canonic(frame.f_code.co_filename)
         s = '%s(%r)' % (filename, lineno)
@@ -338,13 +338,13 @@
         else:
             args = None
         if args:
-            s = s + reprlib.repr(args)
+            s = s + repr.repr(args)
         else:
             s = s + '()'
         if '__return__' in frame.f_locals:
             rv = frame.f_locals['__return__']
             s = s + '->'
-            s = s + reprlib.repr(rv)
+            s = s + repr.repr(rv)
         line = linecache.getline(filename, lineno)
         if line: s = s + lprefix + line.strip()
         return s

Modified: python/branches/okkoto-sizeof/Lib/bsddb/__init__.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/__init__.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/__init__.py	Wed Jun  4 11:24:23 2008
@@ -33,7 +33,7 @@
 #----------------------------------------------------------------------
 
 
-"""Support for Berkeley DB 3.3 through 4.6 with a simple interface.
+"""Support for Berkeley DB 4.x with a simple interface.
 
 For the full featured object oriented interface use the bsddb.db module
 instead.  It mirrors the Oracle Berkeley DB C API.
@@ -66,13 +66,8 @@
 
 import sys, os
 
-# 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 """
+import UserDict
+from weakref import ref
 class _iter_mixin(UserDict.DictMixin):
     def _make_iter_cursor(self):
         cur = _DeadlockWrap(self.db.cursor)
@@ -87,67 +82,80 @@
         return lambda ref: self._cursor_refs.pop(key, None)
 
     def __iter__(self):
+        self._kill_iteration = False
+        self._in_iter += 1
         try:
-            cur = self._make_iter_cursor()
+            try:
+                cur = self._make_iter_cursor()
 
-            # FIXME-20031102-greg: race condition.  cursor could
-            # be closed by another thread before this call.
+                # FIXME-20031102-greg: race condition.  cursor could
+                # be closed by another thread before this call.
 
-            # since we're only returning keys, we call the cursor
-            # methods with flags=0, dlen=0, dofs=0
-            key = _DeadlockWrap(cur.first, 0,0,0)[0]
-            yield key
-
-            next = cur.next
-            while 1:
-                try:
-                    key = _DeadlockWrap(next, 0,0,0)[0]
-                    yield key
-                except _bsddb.DBCursorClosedError:
-                    cur = self._make_iter_cursor()
-                    # FIXME-20031101-greg: race condition.  cursor could
-                    # be closed by another thread before this call.
-                    _DeadlockWrap(cur.set, key,0,0,0)
-                    next = cur.next
-        except _bsddb.DBNotFoundError:
-            return
-        except _bsddb.DBCursorClosedError:
-            # the database was modified during iteration.  abort.
-            return
+                # since we're only returning keys, we call the cursor
+                # methods with flags=0, dlen=0, dofs=0
+                key = _DeadlockWrap(cur.first, 0,0,0)[0]
+                yield key
+
+                next = cur.next
+                while 1:
+                    try:
+                        key = _DeadlockWrap(next, 0,0,0)[0]
+                        yield key
+                    except _bsddb.DBCursorClosedError:
+                        if self._kill_iteration:
+                            raise RuntimeError('Database changed size '
+                                               'during iteration.')
+                        cur = self._make_iter_cursor()
+                        # FIXME-20031101-greg: race condition.  cursor could
+                        # be closed by another thread before this call.
+                        _DeadlockWrap(cur.set, key,0,0,0)
+                        next = cur.next
+            except _bsddb.DBNotFoundError:
+                pass
+            except _bsddb.DBCursorClosedError:
+                # the database was modified during iteration.  abort.
+                pass
+        finally:
+            self._in_iter -= 1
 
     def iteritems(self):
         if not self.db:
             return
+        self._kill_iteration = False
+        self._in_iter += 1
         try:
-            cur = self._make_iter_cursor()
-
-            # FIXME-20031102-greg: race condition.  cursor could
-            # be closed by another thread before this call.
+            try:
+                cur = self._make_iter_cursor()
 
-            kv = _DeadlockWrap(cur.first)
-            key = kv[0]
-            yield kv
+                # FIXME-20031102-greg: race condition.  cursor could
+                # be closed by another thread before this call.
 
-            next = cur.next
-            while 1:
-                try:
-                    kv = _DeadlockWrap(next)
-                    key = kv[0]
-                    yield kv
-                except _bsddb.DBCursorClosedError:
-                    cur = self._make_iter_cursor()
-                    # FIXME-20031101-greg: race condition.  cursor could
-                    # be closed by another thread before this call.
-                    _DeadlockWrap(cur.set, key,0,0,0)
-                    next = cur.next
-        except _bsddb.DBNotFoundError:
-            return
-        except _bsddb.DBCursorClosedError:
-            # the database was modified during iteration.  abort.
-            return
-"""
-else:
-    class _iter_mixin: pass
+                kv = _DeadlockWrap(cur.first)
+                key = kv[0]
+                yield kv
+
+                next = cur.next
+                while 1:
+                    try:
+                        kv = _DeadlockWrap(next)
+                        key = kv[0]
+                        yield kv
+                    except _bsddb.DBCursorClosedError:
+                        if self._kill_iteration:
+                            raise RuntimeError('Database changed size '
+                                               'during iteration.')
+                        cur = self._make_iter_cursor()
+                        # FIXME-20031101-greg: race condition.  cursor could
+                        # be closed by another thread before this call.
+                        _DeadlockWrap(cur.set, key,0,0,0)
+                        next = cur.next
+            except _bsddb.DBNotFoundError:
+                pass
+            except _bsddb.DBCursorClosedError:
+                # the database was modified during iteration.  abort.
+                pass
+        finally:
+            self._in_iter -= 1
 
 
 class _DBWithCursor(_iter_mixin):
@@ -176,6 +184,8 @@
         # a collection of all DBCursor objects currently allocated
         # by the _iter_mixin interface.
         self._cursor_refs = {}
+        self._in_iter = 0
+        self._kill_iteration = False
 
     def __del__(self):
         self.close()
@@ -225,6 +235,8 @@
     def __setitem__(self, key, value):
         self._checkOpen()
         self._closeCursors()
+        if self._in_iter and key not in self:
+            self._kill_iteration = True
         def wrapF():
             self.db[key] = value
         _DeadlockWrap(wrapF)  # self.db[key] = value
@@ -232,6 +244,8 @@
     def __delitem__(self, key):
         self._checkOpen()
         self._closeCursors()
+        if self._in_iter and key in self:
+            self._kill_iteration = True
         def wrapF():
             del self.db[key]
         _DeadlockWrap(wrapF)  # del self.db[key]

Modified: python/branches/okkoto-sizeof/Lib/bsddb/db.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/db.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/db.py	Wed Jun  4 11:24:23 2008
@@ -48,4 +48,4 @@
     from _bsddb import __version__
 
 if version() < (3, 2, 0):
-    raise ImportError, "correct BerkeleyDB symbols not found.  Perhaps python was statically linked with an older version?"
+    raise ImportError, "correct Berkeley DB symbols not found.  Perhaps python was statically linked with an older version?"

Modified: python/branches/okkoto-sizeof/Lib/bsddb/dbtables.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/dbtables.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/dbtables.py	Wed Jun  4 11:24:23 2008
@@ -13,7 +13,7 @@
 #   --  Gregory P. Smith <greg at krypto.org>
 
 # This provides a simple database table interface built on top of
-# the Python BerkeleyDB 3 interface.
+# the Python Berkeley DB 3 interface.
 #
 _cvsid = '$Id$'
 
@@ -139,7 +139,7 @@
                  recover=0, dbflags=0):
         """bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0600)
 
-        Open database name in the dbhome BerkeleyDB directory.
+        Open database name in the dbhome Berkeley DB directory.
         Use keyword arguments when calling this constructor.
         """
         self.db = None

Modified: python/branches/okkoto-sizeof/Lib/bsddb/test/test_all.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/test/test_all.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/test/test_all.py	Wed Jun  4 11:24:23 2008
@@ -67,9 +67,20 @@
     return path
 
 
-get_new_path.prefix="/tmp/z-Berkeley_DB"
+# This path can be overriden via "set_test_path_prefix()".
+import os, os.path
+get_new_path.prefix=os.path.join(os.sep,"tmp","z-Berkeley_DB")
 get_new_path.num=0
 
+def get_test_path_prefix() :
+    return get_new_path.prefix
+
+def set_test_path_prefix(path) :
+    get_new_path.prefix=path
+
+def remove_test_path_directory() :
+    test_support.rmtree(get_new_path.prefix)
+
 try :
     import threading
     get_new_path.mutex=threading.Lock()
@@ -97,24 +108,18 @@
 test_all.verbose = verbose
 
 
-def suite():
-    try:
-        # this is special, it used to segfault the interpreter
-        import test_1413192
-    except:
-        pass
-
+def suite(module_prefix='', timing_check=None):
     test_modules = [
         'test_associate',
         'test_basics',
-        'test_compat',
         'test_compare',
+        'test_compat',
+        'test_cursor_pget_bug',
         'test_dbobj',
         'test_dbshelve',
         'test_dbtables',
-        'test_early_close',
         'test_distributed_transactions',
-        'test_replication',
+        'test_early_close',
         'test_get_none',
         'test_join',
         'test_lock',
@@ -122,15 +127,21 @@
         'test_pickle',
         'test_queue',
         'test_recno',
-        'test_thread',
+        'test_replication',
         'test_sequence',
-        'test_cursor_pget_bug',
+        'test_thread',
         ]
 
     alltests = unittest.TestSuite()
     for name in test_modules:
-        module = __import__(name)
+        #module = __import__(name)
+        # Do it this way so that suite may be called externally via
+        # python's Lib/test/test_bsddb3.
+        module = __import__(module_prefix+name, globals(), locals(), name)
+
         alltests.addTest(module.test_suite())
+        if timing_check:
+            alltests.addTest(unittest.makeSuite(timing_check))
     return alltests
 
 

Modified: python/branches/okkoto-sizeof/Lib/bsddb/test/test_lock.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/test/test_lock.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/test/test_lock.py	Wed Jun  4 11:24:23 2008
@@ -97,11 +97,7 @@
         for t in threads:
             t.join()
 
-    def _DISABLED_test03_lock_timeout(self):
-        # Disabled as this test crashes the python interpreter built in
-        # debug mode with:
-        #  Fatal Python error: UNREF invalid object
-        # the error occurs as marked below.
+    def test03_lock_timeout(self):
         self.env.set_timeout(0, db.DB_SET_LOCK_TIMEOUT)
         self.env.set_timeout(0, db.DB_SET_TXN_TIMEOUT)
         self.env.set_timeout(123456, db.DB_SET_LOCK_TIMEOUT)
@@ -128,8 +124,6 @@
         self.assertNotEqual(anID, anID2)
         lock = self.env.lock_get(anID, "shared lock", db.DB_LOCK_WRITE)
         start_time=time.time()
-        # FIXME: I see the UNREF crash as the interpreter trys to exit
-        # from this call to lock_get.
         self.assertRaises(db.DBLockNotGrantedError,
                 self.env.lock_get,anID2, "shared lock", db.DB_LOCK_READ)
         end_time=time.time()

Modified: python/branches/okkoto-sizeof/Lib/bsddb/test/test_replication.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/test/test_replication.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/test/test_replication.py	Wed Jun  4 11:24:23 2008
@@ -2,6 +2,7 @@
 """
 
 import os
+import time
 import unittest
 
 try:
@@ -57,10 +58,12 @@
         self.dbenvMaster.set_event_notify(confirmed_master)
         self.dbenvClient.set_event_notify(client_startupdone)
 
-        self.dbenvMaster.repmgr_set_local_site("127.0.0.1",46117)
-        self.dbenvClient.repmgr_set_local_site("127.0.0.1",46118)
-        self.dbenvMaster.repmgr_add_remote_site("127.0.0.1",46118)
-        self.dbenvClient.repmgr_add_remote_site("127.0.0.1",46117)
+        master_port = test_support.find_unused_port()
+        self.dbenvMaster.repmgr_set_local_site("127.0.0.1", master_port)
+        client_port = test_support.find_unused_port()
+        self.dbenvClient.repmgr_set_local_site("127.0.0.1", client_port)
+        self.dbenvMaster.repmgr_add_remote_site("127.0.0.1", client_port)
+        self.dbenvClient.repmgr_add_remote_site("127.0.0.1", master_port)
         self.dbenvMaster.rep_set_nsites(2)
         self.dbenvClient.rep_set_nsites(2)
         self.dbenvMaster.rep_set_priority(10)
@@ -91,10 +94,9 @@
         # The timeout is necessary in BDB 4.5, since DB_EVENT_REP_STARTUPDONE
         # is not generated if the master has no new transactions.
         # This is solved in BDB 4.6 (#15542).
-        import time
         timeout = time.time()+2
         while (time.time()<timeout) and not (self.confirmed_master and self.client_startupdone) :
-            time.sleep(0.001)
+            time.sleep(0.02)
         if db.version() >= (4,6) :
             self.assertTrue(time.time()<timeout)
         else :
@@ -103,14 +105,14 @@
         d = self.dbenvMaster.repmgr_site_list()
         self.assertEquals(len(d), 1)
         self.assertEquals(d[0][0], "127.0.0.1")
-        self.assertEquals(d[0][1], 46118)
+        self.assertEquals(d[0][1], client_port)
         self.assertTrue((d[0][2]==db.DB_REPMGR_CONNECTED) or \
                 (d[0][2]==db.DB_REPMGR_DISCONNECTED))
 
         d = self.dbenvClient.repmgr_site_list()
         self.assertEquals(len(d), 1)
         self.assertEquals(d[0][0], "127.0.0.1")
-        self.assertEquals(d[0][1], 46117)
+        self.assertEquals(d[0][1], master_port)
         self.assertTrue((d[0][2]==db.DB_REPMGR_CONNECTED) or \
                 (d[0][2]==db.DB_REPMGR_DISCONNECTED))
 

Modified: python/branches/okkoto-sizeof/Lib/bsddb/test/test_sequence.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/bsddb/test/test_sequence.py	(original)
+++ python/branches/okkoto-sizeof/Lib/bsddb/test/test_sequence.py	Wed Jun  4 11:24:23 2008
@@ -110,20 +110,16 @@
             self.assertRaises(db.DBNotFoundError, seq.open,
                     key='id', txn=None, flags=0)
 
-            self.assertRaises(db.DBNotFoundError, seq.stat)
+            self.assertRaises(db.DBInvalidArgError, seq.stat)
 
             d.close()
 
     def test_64bits(self) :
-        value_plus=(1L<<63)-1
-        self.assertEquals(9223372036854775807L,value_plus)
-        value_minus=-1L<<63  # Two complement
-        self.assertEquals(-9223372036854775808L,value_minus)
-        if db.version() < (4,4):
-            # We don't use both extremes because it is
-            # problematic in Berkeley DB 4.3.
-            value_plus-=1
-            value_minus+=1
+        # We don't use both extremes because they are problematic
+        value_plus=(1L<<63)-2
+        self.assertEquals(9223372036854775806L,value_plus)
+        value_minus=(-1L<<63)+1  # Two complement
+        self.assertEquals(-9223372036854775807L,value_minus)
         self.seq = db.DBSequence(self.d, flags=0)
         self.assertEquals(None, self.seq.init_value(value_plus-1))
         self.assertEquals(None, self.seq.open(key='id', txn=None,

Modified: python/branches/okkoto-sizeof/Lib/collections.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/collections.py	(original)
+++ python/branches/okkoto-sizeof/Lib/collections.py	Wed Jun  4 11:24:23 2008
@@ -88,8 +88,9 @@
     if verbose:
         print template
 
-    # Execute the template string in a temporary namespace
-    namespace = dict(itemgetter=_itemgetter)
+    # Execute the template string in a temporary namespace and
+    # support tracing utilities by setting a value for frame.f_globals['__name__']
+    namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename)
     try:
         exec template in namespace
     except SyntaxError, e:

Modified: python/branches/okkoto-sizeof/Lib/commands.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/commands.py	(original)
+++ python/branches/okkoto-sizeof/Lib/commands.py	Wed Jun  4 11:24:23 2008
@@ -63,6 +63,8 @@
 # Make command argument from directory and pathname (prefix space, add quotes).
 #
 def mk2arg(head, x):
+    from warnings import warnpy3k
+    warnpy3k("In 3.x, mk2arg has been removed.")
     import os
     return mkarg(os.path.join(head, x))
 
@@ -75,6 +77,8 @@
 # with backslash.
 #
 def mkarg(x):
+    from warnings import warnpy3k
+    warnpy3k("in 3.x, mkarg has been removed.")
     if '\'' not in x:
         return ' \'' + x + '\''
     s = ' "'

Deleted: python/branches/okkoto-sizeof/Lib/configparser.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/configparser.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,669 +0,0 @@
-"""Configuration file parser.
-
-A setup file consists of sections, lead by a "[section]" header,
-and followed by "name: value" entries, with continuations and such in
-the style of RFC 822.
-
-The option values can contain format strings which refer to other values in
-the same section, or values in a special [DEFAULT] section.
-
-For example:
-
-    something: %(dir)s/whatever
-
-would resolve the "%(dir)s" to the value of dir.  All reference
-expansions are done late, on demand.
-
-Intrinsic defaults can be specified by passing them into the
-ConfigParser constructor as a dictionary.
-
-class:
-
-ConfigParser -- responsible for parsing a list of
-                configuration files, and managing the parsed database.
-
-    methods:
-
-    __init__(defaults=None)
-        create the parser and specify a dictionary of intrinsic defaults.  The
-        keys must be strings, the values must be appropriate for %()s string
-        interpolation.  Note that `__name__' is always an intrinsic default;
-        its value is the section's name.
-
-    sections()
-        return all the configuration section names, sans DEFAULT
-
-    has_section(section)
-        return whether the given section exists
-
-    has_option(section, option)
-        return whether the given option exists in the given section
-
-    options(section)
-        return list of configuration options for the named section
-
-    read(filenames)
-        read and parse the list of named configuration files, given by
-        name.  A single filename is also allowed.  Non-existing files
-        are ignored.  Return list of successfully read files.
-
-    readfp(fp, filename=None)
-        read and parse one configuration file, given as a file object.
-        The filename defaults to fp.name; it is only used in error
-        messages (if fp has no `name' attribute, the string `<???>' is used).
-
-    get(section, option, raw=False, vars=None)
-        return a string value for the named option.  All % interpolations are
-        expanded in the return values, based on the defaults passed into the
-        constructor and the DEFAULT section.  Additional substitutions may be
-        provided using the `vars' argument, which must be a dictionary whose
-        contents override any pre-existing defaults.
-
-    getint(section, options)
-        like get(), but convert value to an integer
-
-    getfloat(section, options)
-        like get(), but convert value to a float
-
-    getboolean(section, options)
-        like get(), but convert value to a boolean (currently case
-        insensitively defined as 0, false, no, off for False, and 1, true,
-        yes, on for True).  Returns False or True.
-
-    items(section, raw=False, vars=None)
-        return a list of tuples with (name, value) for each option
-        in the section.
-
-    remove_section(section)
-        remove the given file section and all its options
-
-    remove_option(section, option)
-        remove the given option from the given section
-
-    set(section, option, value)
-        set the given option
-
-    write(fp)
-        write the configuration state in .ini format
-"""
-
-import re
-
-__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
-           "InterpolationError", "InterpolationDepthError",
-           "InterpolationSyntaxError", "ParsingError",
-           "MissingSectionHeaderError",
-           "ConfigParser", "SafeConfigParser", "RawConfigParser",
-           "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
-
-DEFAULTSECT = "DEFAULT"
-
-MAX_INTERPOLATION_DEPTH = 10
-
-
-
-# exception classes
-class Error(Exception):
-    """Base class for ConfigParser exceptions."""
-
-    def _get_message(self):
-        """Getter for 'message'; needed only to override deprecation in
-        BaseException."""
-        return self.__message
-
-    def _set_message(self, value):
-        """Setter for 'message'; needed only to override deprecation in
-        BaseException."""
-        self.__message = value
-
-    # BaseException.message has been deprecated since Python 2.6.  To prevent
-    # DeprecationWarning from popping up over this pre-existing attribute, use
-    # a new property that takes lookup precedence.
-    message = property(_get_message, _set_message)
-
-    def __init__(self, msg=''):
-        self.message = msg
-        Exception.__init__(self, msg)
-
-    def __repr__(self):
-        return self.message
-
-    __str__ = __repr__
-
-class NoSectionError(Error):
-    """Raised when no section matches a requested option."""
-
-    def __init__(self, section):
-        Error.__init__(self, 'No section: %r' % (section,))
-        self.section = section
-
-class DuplicateSectionError(Error):
-    """Raised when a section is multiply-created."""
-
-    def __init__(self, section):
-        Error.__init__(self, "Section %r already exists" % section)
-        self.section = section
-
-class NoOptionError(Error):
-    """A requested option was not found."""
-
-    def __init__(self, option, section):
-        Error.__init__(self, "No option %r in section: %r" %
-                       (option, section))
-        self.option = option
-        self.section = section
-
-class InterpolationError(Error):
-    """Base class for interpolation-related exceptions."""
-
-    def __init__(self, option, section, msg):
-        Error.__init__(self, msg)
-        self.option = option
-        self.section = section
-
-class InterpolationMissingOptionError(InterpolationError):
-    """A string substitution required a setting which was not available."""
-
-    def __init__(self, option, section, rawval, reference):
-        msg = ("Bad value substitution:\n"
-               "\tsection: [%s]\n"
-               "\toption : %s\n"
-               "\tkey    : %s\n"
-               "\trawval : %s\n"
-               % (section, option, reference, rawval))
-        InterpolationError.__init__(self, option, section, msg)
-        self.reference = reference
-
-class InterpolationSyntaxError(InterpolationError):
-    """Raised when the source text into which substitutions are made
-    does not conform to the required syntax."""
-
-class InterpolationDepthError(InterpolationError):
-    """Raised when substitutions are nested too deeply."""
-
-    def __init__(self, option, section, rawval):
-        msg = ("Value interpolation too deeply recursive:\n"
-               "\tsection: [%s]\n"
-               "\toption : %s\n"
-               "\trawval : %s\n"
-               % (section, option, rawval))
-        InterpolationError.__init__(self, option, section, msg)
-
-class ParsingError(Error):
-    """Raised when a configuration file does not follow legal syntax."""
-
-    def __init__(self, filename):
-        Error.__init__(self, 'File contains parsing errors: %s' % filename)
-        self.filename = filename
-        self.errors = []
-
-    def append(self, lineno, line):
-        self.errors.append((lineno, line))
-        self.message += '\n\t[line %2d]: %s' % (lineno, line)
-
-class MissingSectionHeaderError(ParsingError):
-    """Raised when a key-value pair is found before any section header."""
-
-    def __init__(self, filename, lineno, line):
-        Error.__init__(
-            self,
-            'File contains no section headers.\nfile: %s, line: %d\n%r' %
-            (filename, lineno, line))
-        self.filename = filename
-        self.lineno = lineno
-        self.line = line
-
-
-class RawConfigParser:
-    def __init__(self, defaults=None, dict_type=dict):
-        self._dict = dict_type
-        self._sections = self._dict()
-        self._defaults = self._dict()
-        if defaults:
-            for key, value in defaults.items():
-                self._defaults[self.optionxform(key)] = value
-
-    def defaults(self):
-        return self._defaults
-
-    def sections(self):
-        """Return a list of section names, excluding [DEFAULT]"""
-        # self._sections will never have [DEFAULT] in it
-        return self._sections.keys()
-
-    def add_section(self, section):
-        """Create a new section in the configuration.
-
-        Raise DuplicateSectionError if a section by the specified name
-        already exists. Raise ValueError if name is DEFAULT or any of it's
-        case-insensitive variants.
-        """
-        if section.lower() == "default":
-            raise ValueError, 'Invalid section name: %s' % section
-
-        if section in self._sections:
-            raise DuplicateSectionError(section)
-        self._sections[section] = self._dict()
-
-    def has_section(self, section):
-        """Indicate whether the named section is present in the configuration.
-
-        The DEFAULT section is not acknowledged.
-        """
-        return section in self._sections
-
-    def options(self, section):
-        """Return a list of option names for the given section name."""
-        try:
-            opts = self._sections[section].copy()
-        except KeyError:
-            raise NoSectionError(section)
-        opts.update(self._defaults)
-        if '__name__' in opts:
-            del opts['__name__']
-        return opts.keys()
-
-    def read(self, filenames):
-        """Read and parse a filename or a list of filenames.
-
-        Files that cannot be opened are silently ignored; this is
-        designed so that you can specify a list of potential
-        configuration file locations (e.g. current directory, user's
-        home directory, systemwide directory), and all existing
-        configuration files in the list will be read.  A single
-        filename may also be given.
-
-        Return list of successfully read files.
-        """
-        if isinstance(filenames, basestring):
-            filenames = [filenames]
-        read_ok = []
-        for filename in filenames:
-            try:
-                fp = open(filename)
-            except IOError:
-                continue
-            self._read(fp, filename)
-            fp.close()
-            read_ok.append(filename)
-        return read_ok
-
-    def readfp(self, fp, filename=None):
-        """Like read() but the argument must be a file-like object.
-
-        The `fp' argument must have a `readline' method.  Optional
-        second argument is the `filename', which if not given, is
-        taken from fp.name.  If fp has no `name' attribute, `<???>' is
-        used.
-
-        """
-        if filename is None:
-            try:
-                filename = fp.name
-            except AttributeError:
-                filename = '<???>'
-        self._read(fp, filename)
-
-    def get(self, section, option):
-        opt = self.optionxform(option)
-        if section not in self._sections:
-            if section != DEFAULTSECT:
-                raise NoSectionError(section)
-            if opt in self._defaults:
-                return self._defaults[opt]
-            else:
-                raise NoOptionError(option, section)
-        elif opt in self._sections[section]:
-            return self._sections[section][opt]
-        elif opt in self._defaults:
-            return self._defaults[opt]
-        else:
-            raise NoOptionError(option, section)
-
-    def items(self, section):
-        try:
-            d2 = self._sections[section]
-        except KeyError:
-            if section != DEFAULTSECT:
-                raise NoSectionError(section)
-            d2 = self._dict()
-        d = self._defaults.copy()
-        d.update(d2)
-        if "__name__" in d:
-            del d["__name__"]
-        return d.items()
-
-    def _get(self, section, conv, option):
-        return conv(self.get(section, option))
-
-    def getint(self, section, option):
-        return self._get(section, int, option)
-
-    def getfloat(self, section, option):
-        return self._get(section, float, option)
-
-    _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
-                       '0': False, 'no': False, 'false': False, 'off': False}
-
-    def getboolean(self, section, option):
-        v = self.get(section, option)
-        if v.lower() not in self._boolean_states:
-            raise ValueError, 'Not a boolean: %s' % v
-        return self._boolean_states[v.lower()]
-
-    def optionxform(self, optionstr):
-        return optionstr.lower()
-
-    def has_option(self, section, option):
-        """Check for the existence of a given option in a given section."""
-        if not section or section == DEFAULTSECT:
-            option = self.optionxform(option)
-            return option in self._defaults
-        elif section not in self._sections:
-            return False
-        else:
-            option = self.optionxform(option)
-            return (option in self._sections[section]
-                    or option in self._defaults)
-
-    def set(self, section, option, value):
-        """Set an option."""
-        if not section or section == DEFAULTSECT:
-            sectdict = self._defaults
-        else:
-            try:
-                sectdict = self._sections[section]
-            except KeyError:
-                raise NoSectionError(section)
-        sectdict[self.optionxform(option)] = value
-
-    def write(self, fp):
-        """Write an .ini-format representation of the configuration state."""
-        if self._defaults:
-            fp.write("[%s]\n" % DEFAULTSECT)
-            for (key, value) in self._defaults.items():
-                fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
-            fp.write("\n")
-        for section in self._sections:
-            fp.write("[%s]\n" % section)
-            for (key, value) in self._sections[section].items():
-                if key != "__name__":
-                    fp.write("%s = %s\n" %
-                             (key, str(value).replace('\n', '\n\t')))
-            fp.write("\n")
-
-    def remove_option(self, section, option):
-        """Remove an option."""
-        if not section or section == DEFAULTSECT:
-            sectdict = self._defaults
-        else:
-            try:
-                sectdict = self._sections[section]
-            except KeyError:
-                raise NoSectionError(section)
-        option = self.optionxform(option)
-        existed = option in sectdict
-        if existed:
-            del sectdict[option]
-        return existed
-
-    def remove_section(self, section):
-        """Remove a file section."""
-        existed = section in self._sections
-        if existed:
-            del self._sections[section]
-        return existed
-
-    #
-    # Regular expressions for parsing section headers and options.
-    #
-    SECTCRE = re.compile(
-        r'\['                                 # [
-        r'(?P<header>[^]]+)'                  # very permissive!
-        r'\]'                                 # ]
-        )
-    OPTCRE = re.compile(
-        r'(?P<option>[^:=\s][^:=]*)'          # very permissive!
-        r'\s*(?P<vi>[:=])\s*'                 # any number of space/tab,
-                                              # followed by separator
-                                              # (either : or =), followed
-                                              # by any # space/tab
-        r'(?P<value>.*)$'                     # everything up to eol
-        )
-
-    def _read(self, fp, fpname):
-        """Parse a sectioned setup file.
-
-        The sections in setup file contains a title line at the top,
-        indicated by a name in square brackets (`[]'), plus key/value
-        options lines, indicated by `name: value' format lines.
-        Continuations are represented by an embedded newline then
-        leading whitespace.  Blank lines, lines beginning with a '#',
-        and just about everything else are ignored.
-        """
-        cursect = None                            # None, or a dictionary
-        optname = None
-        lineno = 0
-        e = None                                  # None, or an exception
-        while True:
-            line = fp.readline()
-            if not line:
-                break
-            lineno = lineno + 1
-            # comment or blank line?
-            if line.strip() == '' or line[0] in '#;':
-                continue
-            if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
-                # no leading whitespace
-                continue
-            # continuation line?
-            if line[0].isspace() and cursect is not None and optname:
-                value = line.strip()
-                if value:
-                    cursect[optname] = "%s\n%s" % (cursect[optname], value)
-            # a section header or option header?
-            else:
-                # is it a section header?
-                mo = self.SECTCRE.match(line)
-                if mo:
-                    sectname = mo.group('header')
-                    if sectname in self._sections:
-                        cursect = self._sections[sectname]
-                    elif sectname == DEFAULTSECT:
-                        cursect = self._defaults
-                    else:
-                        cursect = self._dict()
-                        cursect['__name__'] = sectname
-                        self._sections[sectname] = cursect
-                    # So sections can't start with a continuation line
-                    optname = None
-                # no section header in the file?
-                elif cursect is None:
-                    raise MissingSectionHeaderError(fpname, lineno, line)
-                # an option line?
-                else:
-                    mo = self.OPTCRE.match(line)
-                    if mo:
-                        optname, vi, optval = mo.group('option', 'vi', 'value')
-                        if vi in ('=', ':') and ';' in optval:
-                            # ';' is a comment delimiter only if it follows
-                            # a spacing character
-                            pos = optval.find(';')
-                            if pos != -1 and optval[pos-1].isspace():
-                                optval = optval[:pos]
-                        optval = optval.strip()
-                        # allow empty values
-                        if optval == '""':
-                            optval = ''
-                        optname = self.optionxform(optname.rstrip())
-                        cursect[optname] = optval
-                    else:
-                        # a non-fatal parsing error occurred.  set up the
-                        # exception but keep going. the exception will be
-                        # raised at the end of the file and will contain a
-                        # list of all bogus lines
-                        if not e:
-                            e = ParsingError(fpname)
-                        e.append(lineno, repr(line))
-        # if any parsing errors occurred, raise an exception
-        if e:
-            raise e
-
-
-class ConfigParser(RawConfigParser):
-
-    def get(self, section, option, raw=False, vars=None):
-        """Get an option value for a given section.
-
-        All % interpolations are expanded in the return values, based on the
-        defaults passed into the constructor, unless the optional argument
-        `raw' is true.  Additional substitutions may be provided using the
-        `vars' argument, which must be a dictionary whose contents overrides
-        any pre-existing defaults.
-
-        The section DEFAULT is special.
-        """
-        d = self._defaults.copy()
-        try:
-            d.update(self._sections[section])
-        except KeyError:
-            if section != DEFAULTSECT:
-                raise NoSectionError(section)
-        # Update with the entry specific variables
-        if vars:
-            for key, value in vars.items():
-                d[self.optionxform(key)] = value
-        option = self.optionxform(option)
-        try:
-            value = d[option]
-        except KeyError:
-            raise NoOptionError(option, section)
-
-        if raw:
-            return value
-        else:
-            return self._interpolate(section, option, value, d)
-
-    def items(self, section, raw=False, vars=None):
-        """Return a list of tuples with (name, value) for each option
-        in the section.
-
-        All % interpolations are expanded in the return values, based on the
-        defaults passed into the constructor, unless the optional argument
-        `raw' is true.  Additional substitutions may be provided using the
-        `vars' argument, which must be a dictionary whose contents overrides
-        any pre-existing defaults.
-
-        The section DEFAULT is special.
-        """
-        d = self._defaults.copy()
-        try:
-            d.update(self._sections[section])
-        except KeyError:
-            if section != DEFAULTSECT:
-                raise NoSectionError(section)
-        # Update with the entry specific variables
-        if vars:
-            for key, value in vars.items():
-                d[self.optionxform(key)] = value
-        options = d.keys()
-        if "__name__" in options:
-            options.remove("__name__")
-        if raw:
-            return [(option, d[option])
-                    for option in options]
-        else:
-            return [(option, self._interpolate(section, option, d[option], d))
-                    for option in options]
-
-    def _interpolate(self, section, option, rawval, vars):
-        # do the string interpolation
-        value = rawval
-        depth = MAX_INTERPOLATION_DEPTH
-        while depth:                    # Loop through this until it's done
-            depth -= 1
-            if "%(" in value:
-                value = self._KEYCRE.sub(self._interpolation_replace, value)
-                try:
-                    value = value % vars
-                except KeyError, e:
-                    raise InterpolationMissingOptionError(
-                        option, section, rawval, e[0])
-            else:
-                break
-        if "%(" in value:
-            raise InterpolationDepthError(option, section, rawval)
-        return value
-
-    _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
-
-    def _interpolation_replace(self, match):
-        s = match.group(1)
-        if s is None:
-            return match.group()
-        else:
-            return "%%(%s)s" % self.optionxform(s)
-
-
-class SafeConfigParser(ConfigParser):
-
-    def _interpolate(self, section, option, rawval, vars):
-        # do the string interpolation
-        L = []
-        self._interpolate_some(option, L, rawval, section, vars, 1)
-        return ''.join(L)
-
-    _interpvar_re = re.compile(r"%\(([^)]+)\)s")
-    _badpercent_re = re.compile(r"%[^%]|%$")
-
-    def _interpolate_some(self, option, accum, rest, section, map, depth):
-        if depth > MAX_INTERPOLATION_DEPTH:
-            raise InterpolationDepthError(option, section, rest)
-        while rest:
-            p = rest.find("%")
-            if p < 0:
-                accum.append(rest)
-                return
-            if p > 0:
-                accum.append(rest[:p])
-                rest = rest[p:]
-            # p is no longer used
-            c = rest[1:2]
-            if c == "%":
-                accum.append("%")
-                rest = rest[2:]
-            elif c == "(":
-                m = self._interpvar_re.match(rest)
-                if m is None:
-                    raise InterpolationSyntaxError(option, section,
-                        "bad interpolation variable reference %r" % rest)
-                var = self.optionxform(m.group(1))
-                rest = rest[m.end():]
-                try:
-                    v = map[var]
-                except KeyError:
-                    raise InterpolationMissingOptionError(
-                        option, section, rest, var)
-                if "%" in v:
-                    self._interpolate_some(option, accum, v,
-                                           section, map, depth + 1)
-                else:
-                    accum.append(v)
-            else:
-                raise InterpolationSyntaxError(
-                    option, section,
-                    "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
-
-    def set(self, section, option, value):
-        """Set an option.  Extend ConfigParser.set: check for string values."""
-        if not isinstance(value, basestring):
-            raise TypeError("option values must be strings")
-        # check for bad percent signs:
-        # first, replace all "good" interpolations
-        tmp_value = self._interpvar_re.sub('', value)
-        # then, check if there's a lone percent sign left
-        m = self._badpercent_re.search(tmp_value)
-        if m:
-            raise ValueError("invalid interpolation syntax in %r at "
-                             "position %d" % (value, m.start()))
-        ConfigParser.set(self, section, option, value)

Modified: python/branches/okkoto-sizeof/Lib/copy.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/copy.py	(original)
+++ python/branches/okkoto-sizeof/Lib/copy.py	Wed Jun  4 11:24:23 2008
@@ -49,7 +49,7 @@
 """
 
 import types
-from copyreg import dispatch_table
+from copy_reg import dispatch_table
 
 class Error(Exception):
     pass
@@ -399,16 +399,17 @@
     print l2
     l.append({l[1]: l, 'xyz': l[2]})
     l3 = copy(l)
-    import reprlib
-    print map(reprlib.repr, l)
-    print map(reprlib.repr, l1)
-    print map(reprlib.repr, l2)
-    print map(reprlib.repr, l3)
+    import repr
+    print map(repr.repr, l)
+    print map(repr.repr, l1)
+    print map(repr.repr, l2)
+    print map(repr.repr, l3)
     l3 = deepcopy(l)
-    print map(reprlib.repr, l)
-    print map(reprlib.repr, l1)
-    print map(reprlib.repr, l2)
-    print map(reprlib.repr, l3)
+    import repr
+    print map(repr.repr, l)
+    print map(repr.repr, l1)
+    print map(repr.repr, l2)
+    print map(repr.repr, l3)
 
 if __name__ == '__main__':
     _test()

Deleted: python/branches/okkoto-sizeof/Lib/copyreg.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/copyreg.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,201 +0,0 @@
-"""Helper to provide extensibility for pickle/cPickle.
-
-This is only useful to add pickle support for extension types defined in
-C, not for instances of user-defined classes.
-"""
-
-from types import ClassType as _ClassType
-
-__all__ = ["pickle", "constructor",
-           "add_extension", "remove_extension", "clear_extension_cache"]
-
-dispatch_table = {}
-
-def pickle(ob_type, pickle_function, constructor_ob=None):
-    if type(ob_type) is _ClassType:
-        raise TypeError("copy_reg is not intended for use with classes")
-
-    if not hasattr(pickle_function, '__call__'):
-        raise TypeError("reduction functions must be callable")
-    dispatch_table[ob_type] = pickle_function
-
-    # The constructor_ob function is a vestige of safe for unpickling.
-    # There is no reason for the caller to pass it anymore.
-    if constructor_ob is not None:
-        constructor(constructor_ob)
-
-def constructor(object):
-    if not hasattr(object, '__call__'):
-        raise TypeError("constructors must be callable")
-
-# Example: provide pickling support for complex numbers.
-
-try:
-    complex
-except NameError:
-    pass
-else:
-
-    def pickle_complex(c):
-        return complex, (c.real, c.imag)
-
-    pickle(complex, pickle_complex, complex)
-
-# Support for pickling new-style objects
-
-def _reconstructor(cls, base, state):
-    if base is object:
-        obj = object.__new__(cls)
-    else:
-        obj = base.__new__(cls, state)
-        if base.__init__ != object.__init__:
-            base.__init__(obj, state)
-    return obj
-
-_HEAPTYPE = 1<<9
-
-# Python code for object.__reduce_ex__ for protocols 0 and 1
-
-def _reduce_ex(self, proto):
-    assert proto < 2
-    for base in self.__class__.__mro__:
-        if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
-            break
-    else:
-        base = object # not really reachable
-    if base is object:
-        state = None
-    else:
-        if base is self.__class__:
-            raise TypeError, "can't pickle %s objects" % base.__name__
-        state = base(self)
-    args = (self.__class__, base, state)
-    try:
-        getstate = self.__getstate__
-    except AttributeError:
-        if getattr(self, "__slots__", None):
-            raise TypeError("a class that defines __slots__ without "
-                            "defining __getstate__ cannot be pickled")
-        try:
-            dict = self.__dict__
-        except AttributeError:
-            dict = None
-    else:
-        dict = getstate()
-    if dict:
-        return _reconstructor, args, dict
-    else:
-        return _reconstructor, args
-
-# Helper for __reduce_ex__ protocol 2
-
-def __newobj__(cls, *args):
-    return cls.__new__(cls, *args)
-
-def _slotnames(cls):
-    """Return a list of slot names for a given class.
-
-    This needs to find slots defined by the class and its bases, so we
-    can't simply return the __slots__ attribute.  We must walk down
-    the Method Resolution Order and concatenate the __slots__ of each
-    class found there.  (This assumes classes don't modify their
-    __slots__ attribute to misrepresent their slots after the class is
-    defined.)
-    """
-
-    # Get the value from a cache in the class if possible
-    names = cls.__dict__.get("__slotnames__")
-    if names is not None:
-        return names
-
-    # Not cached -- calculate the value
-    names = []
-    if not hasattr(cls, "__slots__"):
-        # This class has no slots
-        pass
-    else:
-        # Slots found -- gather slot names from all base classes
-        for c in cls.__mro__:
-            if "__slots__" in c.__dict__:
-                slots = c.__dict__['__slots__']
-                # if class has a single slot, it can be given as a string
-                if isinstance(slots, basestring):
-                    slots = (slots,)
-                for name in slots:
-                    # special descriptors
-                    if name in ("__dict__", "__weakref__"):
-                        continue
-                    # mangled names
-                    elif name.startswith('__') and not name.endswith('__'):
-                        names.append('_%s%s' % (c.__name__, name))
-                    else:
-                        names.append(name)
-
-    # Cache the outcome in the class if at all possible
-    try:
-        cls.__slotnames__ = names
-    except:
-        pass # But don't die if we can't
-
-    return names
-
-# A registry of extension codes.  This is an ad-hoc compression
-# mechanism.  Whenever a global reference to <module>, <name> is about
-# to be pickled, the (<module>, <name>) tuple is looked up here to see
-# if it is a registered extension code for it.  Extension codes are
-# universal, so that the meaning of a pickle does not depend on
-# context.  (There are also some codes reserved for local use that
-# don't have this restriction.)  Codes are positive ints; 0 is
-# reserved.
-
-_extension_registry = {}                # key -> code
-_inverted_registry = {}                 # code -> key
-_extension_cache = {}                   # code -> object
-# Don't ever rebind those names:  cPickle grabs a reference to them when
-# it's initialized, and won't see a rebinding.
-
-def add_extension(module, name, code):
-    """Register an extension code."""
-    code = int(code)
-    if not 1 <= code <= 0x7fffffff:
-        raise ValueError, "code out of range"
-    key = (module, name)
-    if (_extension_registry.get(key) == code and
-        _inverted_registry.get(code) == key):
-        return # Redundant registrations are benign
-    if key in _extension_registry:
-        raise ValueError("key %s is already registered with code %s" %
-                         (key, _extension_registry[key]))
-    if code in _inverted_registry:
-        raise ValueError("code %s is already in use for key %s" %
-                         (code, _inverted_registry[code]))
-    _extension_registry[key] = code
-    _inverted_registry[code] = key
-
-def remove_extension(module, name, code):
-    """Unregister an extension code.  For testing only."""
-    key = (module, name)
-    if (_extension_registry.get(key) != code or
-        _inverted_registry.get(code) != key):
-        raise ValueError("key %s is not registered with code %s" %
-                         (key, code))
-    del _extension_registry[key]
-    del _inverted_registry[code]
-    if code in _extension_cache:
-        del _extension_cache[code]
-
-def clear_extension_cache():
-    _extension_cache.clear()
-
-# Standard extension code assignments
-
-# Reserved ranges
-
-# First  Last Count  Purpose
-#     1   127   127  Reserved for Python standard library
-#   128   191    64  Reserved for Zope
-#   192   239    48  Reserved for 3rd parties
-#   240   255    16  Reserved for private use (will never be assigned)
-#   256   Inf   Inf  Reserved for future assignment
-
-# Extension codes are assigned by the Python Software Foundation.

Modified: python/branches/okkoto-sizeof/Lib/ctypes/test/__init__.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/ctypes/test/__init__.py	(original)
+++ python/branches/okkoto-sizeof/Lib/ctypes/test/__init__.py	Wed Jun  4 11:24:23 2008
@@ -50,11 +50,16 @@
             if fnmatch.fnmatchcase(fnm, mask):
                 yield "%s.%s" % (package.__name__, os.path.splitext(fnm)[0])
 
-def get_tests(package, mask, verbosity):
+def get_tests(package, mask, verbosity, exclude=()):
     """Return a list of skipped test modules, and a list of test cases."""
     tests = []
     skipped = []
     for modname in find_package_modules(package, mask):
+        if modname.split(".")[-1] in exclude:
+            skipped.append(modname)
+            if verbosity > 1:
+                print >> sys.stderr, "Skipped %s: excluded" % modname
+            continue
         try:
             mod = __import__(modname, globals(), locals(), ['*'])
         except ResourceDenied, detail:
@@ -151,12 +156,13 @@
 
 def main(*packages):
     try:
-        opts, args = getopt.getopt(sys.argv[1:], "rqvu:")
+        opts, args = getopt.getopt(sys.argv[1:], "rqvu:x:")
     except getopt.error:
         return usage()
 
     verbosity = 1
     search_leaks = False
+    exclude = []
     for flag, value in opts:
         if flag == "-q":
             verbosity -= 1
@@ -171,17 +177,19 @@
             search_leaks = True
         elif flag == "-u":
             use_resources.extend(value.split(","))
+        elif flag == "-x":
+            exclude.extend(value.split(","))
 
     mask = "test_*.py"
     if args:
         mask = args[0]
 
     for package in packages:
-        run_tests(package, mask, verbosity, search_leaks)
+        run_tests(package, mask, verbosity, search_leaks, exclude)
 
 
-def run_tests(package, mask, verbosity, search_leaks):
-    skipped, testcases = get_tests(package, mask, verbosity)
+def run_tests(package, mask, verbosity, search_leaks, exclude):
+    skipped, testcases = get_tests(package, mask, verbosity, exclude)
     runner = TestRunner(verbosity=verbosity)
 
     suites = [unittest.makeSuite(o) for o in testcases]

Modified: python/branches/okkoto-sizeof/Lib/ctypes/test/runtests.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/ctypes/test/runtests.py	(original)
+++ python/branches/okkoto-sizeof/Lib/ctypes/test/runtests.py	Wed Jun  4 11:24:23 2008
@@ -8,6 +8,8 @@
          Add resources to the lits of allowed resources. '*' allows all
          resources.
   -v     verbose mode: print the test currently executed
+  -x<test1[,test2...]>
+         Exclude specified tests.
   mask   mask to select filenames containing testcases, wildcards allowed
 """
 import sys

Modified: python/branches/okkoto-sizeof/Lib/ctypes/test/test_loading.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/ctypes/test/test_loading.py	(original)
+++ python/branches/okkoto-sizeof/Lib/ctypes/test/test_loading.py	Wed Jun  4 11:24:23 2008
@@ -6,7 +6,7 @@
 
 libc_name = None
 if os.name == "nt":
-    libc_name = "msvcrt"
+    libc_name = find_library("c")
 elif os.name == "ce":
     libc_name = "coredll"
 elif sys.platform == "cygwin":
@@ -43,6 +43,7 @@
 
     if os.name in ("nt", "ce"):
         def test_load_library(self):
+            self.failIf(libc_name is None)
             if is_resource_enabled("printing"):
                 print find_library("kernel32")
                 print find_library("user32")

Modified: python/branches/okkoto-sizeof/Lib/ctypes/test/test_pointers.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/ctypes/test/test_pointers.py	(original)
+++ python/branches/okkoto-sizeof/Lib/ctypes/test/test_pointers.py	Wed Jun  4 11:24:23 2008
@@ -175,5 +175,13 @@
         self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted
         self.assertRaises(TypeError, c_void_p, object()) # nor other objects
 
+    def test_pointers_bool(self):
+        # NULL pointers have a boolean False value, non-NULL pointers True.
+        self.failUnlessEqual(bool(POINTER(c_int)()), False)
+        self.failUnlessEqual(bool(pointer(c_int())), True)
+
+        self.failUnlessEqual(bool(CFUNCTYPE(None)(0)), False)
+        self.failUnlessEqual(bool(CFUNCTYPE(None)(42)), True)
+
 if __name__ == '__main__':
     unittest.main()

Modified: python/branches/okkoto-sizeof/Lib/ctypes/util.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/ctypes/util.py	(original)
+++ python/branches/okkoto-sizeof/Lib/ctypes/util.py	Wed Jun  4 11:24:23 2008
@@ -5,7 +5,50 @@
 
 # find_library(name) returns the pathname of a library, or None.
 if os.name == "nt":
+
+    def _get_build_version():
+        """Return the version of MSVC that was used to build Python.
+
+        For Python 2.3 and up, the version number is included in
+        sys.version.  For earlier versions, assume the compiler is MSVC 6.
+        """
+        # This function was copied from Lib/distutils/msvccompiler.py
+        prefix = "MSC v."
+        i = sys.version.find(prefix)
+        if i == -1:
+            return 6
+        i = i + len(prefix)
+        s, rest = sys.version[i:].split(" ", 1)
+        majorVersion = int(s[:-2]) - 6
+        minorVersion = int(s[2:3]) / 10.0
+        # I don't think paths are affected by minor version in version 6
+        if majorVersion == 6:
+            minorVersion = 0
+        if majorVersion >= 6:
+            return majorVersion + minorVersion
+        # else we don't know what version of the compiler this is
+        return None
+
+    def find_msvcrt():
+        """Return the name of the VC runtime dll"""
+        version = _get_build_version()
+        if version is None:
+            # better be safe than sorry
+            return None
+        if version <= 6:
+            clibname = 'msvcrt'
+        else:
+            clibname = 'msvcr%d' % (version * 10)
+
+        # If python was built with in debug mode
+        import imp
+        if imp.get_suffixes()[0][0] == '_d.pyd':
+            clibname += 'd'
+        return clibname+'.dll'
+
     def find_library(name):
+        if name in ('c', 'm'):
+            return find_msvcrt()
         # See MSDN for the REAL search order.
         for directory in os.environ['PATH'].split(os.pathsep):
             fname = os.path.join(directory, name)

Modified: python/branches/okkoto-sizeof/Lib/distutils/command/bdist_wininst.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/distutils/command/bdist_wininst.py	(original)
+++ python/branches/okkoto-sizeof/Lib/distutils/command/bdist_wininst.py	Wed Jun  4 11:24:23 2008
@@ -79,6 +79,12 @@
 
     def finalize_options (self):
         if self.bdist_dir is None:
+            if self.skip_build and self.plat_name:
+                # If build is skipped and plat_name is overridden, bdist will
+                # not see the correct 'plat_name' - so set that up manually.
+                bdist = self.distribution.get_command_obj('bdist')
+                bdist.plat_name = self.plat_name
+                # next the command will be initialized using that name
             bdist_base = self.get_finalized_command('bdist').bdist_base
             self.bdist_dir = os.path.join(bdist_base, 'wininst')
         if not self.target_version:

Modified: python/branches/okkoto-sizeof/Lib/distutils/command/upload.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/distutils/command/upload.py	(original)
+++ python/branches/okkoto-sizeof/Lib/distutils/command/upload.py	Wed Jun  4 11:24:23 2008
@@ -14,11 +14,7 @@
 import base64
 import urlparse
 import cStringIO as StringIO
-try:
-    from configparser import ConfigParser
-except ImportError:
-    # For backward-compatibility with Python versions < 2.6.
-    from ConfigParser import ConfigParser
+from ConfigParser import ConfigParser
 
 
 class upload(PyPIRCCommand):

Modified: python/branches/okkoto-sizeof/Lib/distutils/command/wininst-6.0.exe
==============================================================================
Binary files. No diff available.

Modified: python/branches/okkoto-sizeof/Lib/distutils/command/wininst-7.1.exe
==============================================================================
Binary files. No diff available.

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

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

Modified: python/branches/okkoto-sizeof/Lib/distutils/config.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/distutils/config.py	(original)
+++ python/branches/okkoto-sizeof/Lib/distutils/config.py	Wed Jun  4 11:24:23 2008
@@ -5,11 +5,7 @@
 """
 import os
 import sys
-try:
-    from configparser import ConfigParser
-except ImportError:
-    # For backward-compatibility with Python versions < 2.6.
-    from ConfigParser import ConfigParser
+from ConfigParser import ConfigParser
 
 from distutils.cmd import Command
 
@@ -62,7 +58,7 @@
         """Reads the .pypirc file."""
         rc = self._get_rc_file()
         if os.path.exists(rc):
-            print 'Using PyPI login from %s' % rc
+            self.announce('Using PyPI login from %s' % rc)
             repository = self.repository or self.DEFAULT_REPOSITORY
             realm = self.realm or self.DEFAULT_REALM
 

Modified: python/branches/okkoto-sizeof/Lib/distutils/dist.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/distutils/dist.py	(original)
+++ python/branches/okkoto-sizeof/Lib/distutils/dist.py	Wed Jun  4 11:24:23 2008
@@ -358,11 +358,7 @@
 
 
     def parse_config_files (self, filenames=None):
-        try:
-            from configparser import ConfigParser
-        except ImportError:
-            # For backward-compatibility with Python versions < 2.6.
-            from ConfigParser import ConfigParser
+        from ConfigParser import ConfigParser
 
         if filenames is None:
             filenames = self.find_config_files()

Modified: python/branches/okkoto-sizeof/Lib/ftplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/ftplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/ftplib.py	Wed Jun  4 11:24:23 2008
@@ -44,6 +44,7 @@
     from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn
 except ImportError:
     import socket
+from socket import _GLOBAL_DEFAULT_TIMEOUT
 
 __all__ = ["FTP","Netrc"]
 
@@ -71,7 +72,6 @@
 # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
 CRLF = '\r\n'
 
-
 # The class itself
 class FTP:
 
@@ -109,14 +109,15 @@
     # Initialize host to localhost, port to standard ftp port
     # Optional arguments are host (for connect()),
     # and user, passwd, acct (for login())
-    def __init__(self, host='', user='', passwd='', acct='', timeout=None):
+    def __init__(self, host='', user='', passwd='', acct='',
+                 timeout=_GLOBAL_DEFAULT_TIMEOUT):
         self.timeout = timeout
         if host:
             self.connect(host)
             if user:
                 self.login(user, passwd, acct)
 
-    def connect(self, host='', port=0, timeout=None):
+    def connect(self, host='', port=0, timeout=-999):
         '''Connect to host.  Arguments are:
          - host: hostname to connect to (string, default previous host)
          - port: port to connect to (integer, default previous port)
@@ -125,7 +126,7 @@
             self.host = host
         if port > 0:
             self.port = port
-        if timeout is not None:
+        if timeout != -999:
             self.timeout = timeout
         self.sock = socket.create_connection((self.host, self.port), self.timeout)
         self.af = self.sock.family

Modified: python/branches/okkoto-sizeof/Lib/gzip.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/gzip.py	(original)
+++ python/branches/okkoto-sizeof/Lib/gzip.py	Wed Jun  4 11:24:23 2008
@@ -306,6 +306,8 @@
             raise IOError, "Incorrect length of data produced"
 
     def close(self):
+        if self.fileobj is None:
+            return
         if self.mode == WRITE:
             self.fileobj.write(self.compress.flush())
             write32u(self.fileobj, self.crc)

Modified: python/branches/okkoto-sizeof/Lib/heapq.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/heapq.py	(original)
+++ python/branches/okkoto-sizeof/Lib/heapq.py	Wed Jun  4 11:24:23 2008
@@ -167,7 +167,7 @@
 
 def heappushpop(heap, item):
     """Fast version of a heappush followed by a heappop."""
-    if heap and item > heap[0]:
+    if heap and heap[0] < item:
         item, heap[0] = heap[0], item
         _siftup(heap, 0)
     return item
@@ -240,10 +240,11 @@
     while pos > startpos:
         parentpos = (pos - 1) >> 1
         parent = heap[parentpos]
-        if parent <= newitem:
-            break
-        heap[pos] = parent
-        pos = parentpos
+        if newitem < parent:
+            heap[pos] = parent
+            pos = parentpos
+            continue
+        break
     heap[pos] = newitem
 
 # The child indices of heap index pos are already heaps, and we want to make
@@ -294,7 +295,7 @@
     while childpos < endpos:
         # Set childpos to index of smaller child.
         rightpos = childpos + 1
-        if rightpos < endpos and heap[rightpos] <= heap[childpos]:
+        if rightpos < endpos and not heap[childpos] < heap[rightpos]:
             childpos = rightpos
         # Move the smaller child up.
         heap[pos] = heap[childpos]

Modified: python/branches/okkoto-sizeof/Lib/htmllib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/htmllib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/htmllib.py	Wed Jun  4 11:24:23 2008
@@ -4,6 +4,11 @@
 http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_toc.html
 """
 
+from warnings import warnpy3k
+warnpy3k("the htmllib module has been removed in Python 3.0",
+         stacklevel=2)
+del warnpy3k
+
 import sgmllib
 
 from formatter import AS_IS

Modified: python/branches/okkoto-sizeof/Lib/httplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/httplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/httplib.py	Wed Jun  4 11:24:23 2008
@@ -639,7 +639,8 @@
     debuglevel = 0
     strict = 0
 
-    def __init__(self, host, port=None, strict=None, timeout=None):
+    def __init__(self, host, port=None, strict=None,
+                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         self.timeout = timeout
         self.sock = None
         self._buffer = []
@@ -1055,7 +1056,7 @@
         default_port = HTTPS_PORT
 
         def __init__(self, host, port=None, key_file=None, cert_file=None,
-                     strict=None, timeout=None):
+                     strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
             HTTPConnection.__init__(self, host, port, strict, timeout)
             self.key_file = key_file
             self.cert_file = cert_file

Modified: python/branches/okkoto-sizeof/Lib/idlelib/Debugger.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/idlelib/Debugger.py	(original)
+++ python/branches/okkoto-sizeof/Lib/idlelib/Debugger.py	Wed Jun  4 11:24:23 2008
@@ -413,8 +413,8 @@
             height = 20*len(dict) # XXX 20 == observed height of Entry widget
         self.master = master
         self.title = title
-        import reprlib
-        self.repr = reprlib.Repr()
+        import repr
+        self.repr = repr.Repr()
         self.repr.maxstring = 60
         self.repr.maxother = 60
         self.frame = frame = Frame(master)

Modified: python/branches/okkoto-sizeof/Lib/idlelib/ObjectBrowser.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/idlelib/ObjectBrowser.py	(original)
+++ python/branches/okkoto-sizeof/Lib/idlelib/ObjectBrowser.py	Wed Jun  4 11:24:23 2008
@@ -11,7 +11,7 @@
 
 from TreeWidget import TreeItem, TreeNode, ScrolledCanvas
 
-from reprlib import Repr
+from repr import Repr
 
 myrepr = Repr()
 myrepr.maxstring = 100

Modified: python/branches/okkoto-sizeof/Lib/idlelib/configHandler.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/idlelib/configHandler.py	(original)
+++ python/branches/okkoto-sizeof/Lib/idlelib/configHandler.py	Wed Jun  4 11:24:23 2008
@@ -21,7 +21,7 @@
 import sys
 import string
 import macosxSupport
-from configparser import ConfigParser, NoOptionError, NoSectionError
+from ConfigParser import ConfigParser, NoOptionError, NoSectionError
 
 class InvalidConfigType(Exception): pass
 class InvalidConfigSet(Exception): pass

Modified: python/branches/okkoto-sizeof/Lib/idlelib/rpc.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/idlelib/rpc.py	(original)
+++ python/branches/okkoto-sizeof/Lib/idlelib/rpc.py	Wed Jun  4 11:24:23 2008
@@ -5,7 +5,7 @@
 has only one client per server, this was not a limitation.
 
    +---------------------------------+ +-------------+
-   | socketserver.BaseRequestHandler | | SocketIO    |
+   | SocketServer.BaseRequestHandler | | SocketIO    |
    +---------------------------------+ +-------------+
                    ^                   | register()  |
                    |                   | unregister()|
@@ -31,13 +31,13 @@
 import os
 import socket
 import select
-import socketserver
+import SocketServer
 import struct
 import cPickle as pickle
 import threading
-import queue
+import Queue
 import traceback
-import copyreg
+import copy_reg
 import types
 import marshal
 
@@ -60,18 +60,18 @@
 #      assert isinstance(fn, type.FunctionType)
 #      return repr(fn)
 
-copyreg.pickle(types.CodeType, pickle_code, unpickle_code)
-# copyreg.pickle(types.FunctionType, pickle_function, unpickle_function)
+copy_reg.pickle(types.CodeType, pickle_code, unpickle_code)
+# copy_reg.pickle(types.FunctionType, pickle_function, unpickle_function)
 
 BUFSIZE = 8*1024
 LOCALHOST = '127.0.0.1'
 
-class RPCServer(socketserver.TCPServer):
+class RPCServer(SocketServer.TCPServer):
 
     def __init__(self, addr, handlerclass=None):
         if handlerclass is None:
             handlerclass = RPCHandler
-        socketserver.TCPServer.__init__(self, addr, handlerclass)
+        SocketServer.TCPServer.__init__(self, addr, handlerclass)
 
     def server_bind(self):
         "Override TCPServer method, no bind() phase for connecting entity"
@@ -117,8 +117,8 @@
 #----------------- end class RPCServer --------------------
 
 objecttable = {}
-request_queue = queue.Queue(0)
-response_queue = queue.Queue(0)
+request_queue = Queue.Queue(0)
+response_queue = Queue.Queue(0)
 
 
 class SocketIO(object):
@@ -413,7 +413,7 @@
             # send queued response if there is one available
             try:
                 qmsg = response_queue.get(0)
-            except queue.Empty:
+            except Queue.Empty:
                 pass
             else:
                 seq, response = qmsg
@@ -492,7 +492,7 @@
     def __init__(self, oid):
         self.oid = oid
 
-class RPCHandler(socketserver.BaseRequestHandler, SocketIO):
+class RPCHandler(SocketServer.BaseRequestHandler, SocketIO):
 
     debugging = False
     location = "#S"  # Server
@@ -500,10 +500,10 @@
     def __init__(self, sock, addr, svr):
         svr.current_handler = self ## cgt xxx
         SocketIO.__init__(self, sock)
-        socketserver.BaseRequestHandler.__init__(self, sock, addr, svr)
+        SocketServer.BaseRequestHandler.__init__(self, sock, addr, svr)
 
     def handle(self):
-        "handle() method required by socketserver"
+        "handle() method required by SocketServer"
         self.mainloop()
 
     def get_remote_proxy(self, oid):

Modified: python/branches/okkoto-sizeof/Lib/idlelib/run.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/idlelib/run.py	(original)
+++ python/branches/okkoto-sizeof/Lib/idlelib/run.py	Wed Jun  4 11:24:23 2008
@@ -5,7 +5,7 @@
 import traceback
 import thread
 import threading
-import queue
+import Queue
 
 import CallTips
 import AutoComplete
@@ -85,7 +85,7 @@
                     continue
             try:
                 seq, request = rpc.request_queue.get(block=True, timeout=0.05)
-            except queue.Empty:
+            except Queue.Empty:
                 continue
             method, args, kwargs = request
             ret = method(*args, **kwargs)

Deleted: python/branches/okkoto-sizeof/Lib/lib-old/ConfigParser.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-old/ConfigParser.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,8 +0,0 @@
-import sys
-from warnings import warnpy3k
-
-warnpy3k("the ConfigParser module has been renamed "
-         "to 'configparser' in Python 3.0", stacklevel=2)
-
-import configparser
-sys.modules[__name__] = configparser

Deleted: python/branches/okkoto-sizeof/Lib/lib-old/Queue.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-old/Queue.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,8 +0,0 @@
-import sys
-from warnings import warnpy3k
-
-warnpy3k("the Queue module has been renamed "
-         "to 'queue' in Python 3.0", stacklevel=2)
-
-import queue
-sys.modules[__name__] = queue

Deleted: python/branches/okkoto-sizeof/Lib/lib-old/SocketServer.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-old/SocketServer.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,8 +0,0 @@
-import sys
-from warnings import warnpy3k
-
-warnpy3k("the SocketServer module has been renamed "
-         "to 'socketserver' in Python 3.0", stacklevel=2)
-
-import socketserver
-sys.modules[__name__] = socketserver

Deleted: python/branches/okkoto-sizeof/Lib/lib-old/copy_reg.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-old/copy_reg.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,8 +0,0 @@
-import sys
-from warnings import warnpy3k
-
-warnpy3k("the copy_reg module has been renamed "
-         "to 'copyreg' in Python 3.0", stacklevel=2)
-
-import copyreg
-sys.modules[__name__] = copyreg

Deleted: python/branches/okkoto-sizeof/Lib/lib-old/repr.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-old/repr.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,7 +0,0 @@
-from warnings import warnpy3k
-warnpy3k("The repr module has been renamed to 'reprlib' in Python 3.0",
-         stacklevel=2)
-
-from sys import modules
-import reprlib
-modules[__name__] = repr

Modified: python/branches/okkoto-sizeof/Lib/lib-tk/Dialog.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-tk/Dialog.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib-tk/Dialog.py	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,4 @@
-# Dialog.py -- Tkinter interface to the tk_dialog script.
+# dialog.py -- Tkinter interface to the tk_dialog script.
 
 from Tkinter import *
 from Tkinter import _cnfmerge

Modified: python/branches/okkoto-sizeof/Lib/lib-tk/Tkinter.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-tk/Tkinter.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib-tk/Tkinter.py	Wed Jun  4 11:24:23 2008
@@ -34,7 +34,8 @@
 
 import sys
 if sys.platform == "win32":
-    import FixTk # Attempt to configure Tcl/Tk without requiring PATH
+    # Attempt to configure Tcl/Tk without requiring PATH
+    import FixTk
 import _tkinter # If this fails your Python may not be configured for Tk
 tkinter = _tkinter # b/w compat for export
 TclError = _tkinter.TclError
@@ -1052,6 +1053,18 @@
                 if k[-1] == '_': k = k[:-1]
                 if callable(v):
                     v = self._register(v)
+                elif isinstance(v, (tuple, list)):
+                    nv = []
+                    for item in v:
+                        if not isinstance(item, (basestring, int)):
+                            break
+                        elif isinstance(item, int):
+                            nv.append('%d' % item)
+                        else:
+                            # format it to proper Tcl code if it contains space
+                            nv.append(('{%s}' if ' ' in item else '%s') % item)
+                    else:
+                        v = ' '.join(nv)
                 res = res + ('-'+k, v)
         return res
     def nametowidget(self, name):
@@ -1091,7 +1104,6 @@
             if self._tclCommands is None:
                 self._tclCommands = []
             self._tclCommands.append(name)
-        #print '+ Tkinter created command', name
         return name
     register = _register
     def _root(self):
@@ -1199,6 +1211,8 @@
     __getitem__ = cget
     def __setitem__(self, key, value):
         self.configure({key: value})
+    def __contains__(self, key):
+        raise TypeError("Tkinter objects don't support 'in' tests.")
     def keys(self):
         """Return a list of all resource names of this widget."""
         return map(lambda x: x[0][1:],
@@ -1744,10 +1758,11 @@
         after=widget - pack it after you have packed widget
         anchor=NSEW (or subset) - position widget according to
                                   given direction
-                before=widget - pack it before you will pack widget
+        before=widget - pack it before you will pack widget
         expand=bool - expand widget if parent size grows
         fill=NONE or X or Y or BOTH - fill widget if widget grows
         in=master - use master to contain this widget
+        in_=master - see 'in' option description
         ipadx=amount - add internal padding in x direction
         ipady=amount - add internal padding in y direction
         padx=amount - add padding in x direction
@@ -1785,29 +1800,26 @@
     Base class to use the methods place_* in every widget."""
     def place_configure(self, cnf={}, **kw):
         """Place a widget in the parent widget. Use as options:
-        in=master - master relative to which the widget is placed.
+        in=master - master relative to which the widget is placed
+        in_=master - see 'in' option description
         x=amount - locate anchor of this widget at position x of master
         y=amount - locate anchor of this widget at position y of master
         relx=amount - locate anchor of this widget between 0.0 and 1.0
                       relative to width of master (1.0 is right edge)
-            rely=amount - locate anchor of this widget between 0.0 and 1.0
+        rely=amount - locate anchor of this widget between 0.0 and 1.0
                       relative to height of master (1.0 is bottom edge)
-            anchor=NSEW (or subset) - position anchor according to given direction
+        anchor=NSEW (or subset) - position anchor according to given direction
         width=amount - width of this widget in pixel
         height=amount - height of this widget in pixel
         relwidth=amount - width of this widget between 0.0 and 1.0
                           relative to width of master (1.0 is the same width
-                  as the master)
-            relheight=amount - height of this widget between 0.0 and 1.0
+                          as the master)
+        relheight=amount - height of this widget between 0.0 and 1.0
                            relative to height of master (1.0 is the same
-                   height as the master)
-            bordermode="inside" or "outside" - whether to take border width of master widget
-                                               into account
-            """
-        for k in ['in_']:
-            if kw.has_key(k):
-                kw[k[:-1]] = kw[k]
-                del kw[k]
+                           height as the master)
+        bordermode="inside" or "outside" - whether to take border width of
+                                           master widget into account
+        """
         self.tk.call(
               ('place', 'configure', self._w)
               + self._options(cnf, kw))
@@ -1842,6 +1854,7 @@
         column=number - use cell identified with given column (starting with 0)
         columnspan=number - this widget will span several columns
         in=master - use master to contain this widget
+        in_=master - see 'in' option description
         ipadx=amount - add internal padding in x direction
         ipady=amount - add internal padding in y direction
         padx=amount - add padding in x direction
@@ -2907,8 +2920,7 @@
         and edit_undo
 
         """
-        return self._getints(
-            self.tk.call((self._w, 'edit') + args)) or ()
+        return self.tk.call(self._w, 'edit', *args)
 
     def edit_modified(self, arg=None):
         """Get or Set the modified flag

Modified: python/branches/okkoto-sizeof/Lib/lib-tk/tkFont.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-tk/tkFont.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib-tk/tkFont.py	Wed Jun  4 11:24:23 2008
@@ -31,7 +31,7 @@
     name -- name to use for this font configuration (defaults to a unique name)
     exists -- does a named font by this name already exist?
        Creates a new named font if False, points to the existing font if True.
-       Raises _tkinter.TclError if the assertion is false.
+       Raises _Tkinter.TclError if the assertion is false.
 
        the following are ignored if font is specified:
 

Modified: python/branches/okkoto-sizeof/Lib/lib-tk/turtle.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib-tk/turtle.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib-tk/turtle.py	Wed Jun  4 11:24:23 2008
@@ -1,294 +1,3142 @@
-# LogoMation-like turtle graphics
+#
+# turtle.py: a Tkinter based turtle graphics module for Python
+# Version 1.0b1 - 31. 5. 2008
+#
+# Copyright (C) 2006 - 2008  Gregor Lingl
+# email: glingl at aon.at
+#
+# This software is provided 'as-is', without any express or implied
+# warranty.  In no event will the authors be held liable for any damages
+# arising from the use of this software.
+#
+# Permission is granted to anyone to use this software for any purpose,
+# including commercial applications, and to alter it and redistribute it
+# freely, subject to the following restrictions:
+#
+# 1. The origin of this software must not be misrepresented; you must not
+#    claim that you wrote the original software. If you use this software
+#    in a product, an acknowledgment in the product documentation would be
+#    appreciated but is not required.
+# 2. Altered source versions must be plainly marked as such, and must not be
+#    misrepresented as being the original software.
+# 3. This notice may not be removed or altered from any source distribution.
+
 
 """
 Turtle graphics is a popular way for introducing programming to
 kids. It was part of the original Logo programming language developed
-by Wally Feurzeig and Seymour Papert in 1966.
+by Wally Feurzig and Seymour Papert in 1966.
 
 Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
 the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
 the direction it is facing, drawing a line as it moves. Give it the
 command turtle.left(25), and it rotates in-place 25 degrees clockwise.
 
-By combining together these and similar commands, intricate shapes and
-pictures can easily be drawn.
-"""
+By combining together these and similar commands, intricate shapes and
+pictures can easily be drawn.
+
+----- turtle.py
+
+This module is an extended reimplementation of turtle.py from the
+Python standard distribution up to Python 2.5. (See: http:\\www.python.org)
+
+It tries to keep the merits of turtle.py and to be (nearly) 100%
+compatible with it. This means in the first place to enable the
+learning programmer to use all the commands, classes and methods
+interactively when using the module from within IDLE run with
+the -n switch.
+
+Roughly it has the following features added:
+
+- Better animation of the turtle movements, especially of turning the
+  turtle. So the turtles can more easily be used as a visual feedback
+  instrument by the (beginning) programmer.
+
+- Different turtle shapes, gif-images as turtle shapes, user defined
+  and user controllable turtle shapes, among them compound
+  (multicolored) shapes. Turtle shapes can be stgretched and tilted, which
+  makes turtles zu very versatile geometrical objects.
+
+- Fine control over turtle movement and screen updates via delay(),
+  and enhanced tracer() and speed() methods.
+
+- Aliases for the most commonly used commands, like fd for forward etc.,
+  following the early Logo traditions. This reduces the boring work of
+  typing long sequences of commands, which often occur in a natural way
+  when kids try to program fancy pictures on their first encounter with
+  turtle graphcis.
+
+- Turtles now have an undo()-method with configurable undo-buffer.
+
+- Some simple commands/methods for creating event driven programs
+  (mouse-, key-, timer-events). Especially useful for programming games.
+
+- A scrollable Canvas class. The default scrollable Canvas can be
+  extended interactively as needed while playing around with the turtle(s).
+
+- A TurtleScreen class with methods controlling background color or
+  background image, window and canvas size and other properties of the
+  TurtleScreen.
+
+- There is a method, setworldcoordinates(), to install a user defined
+  coordinate-system for the TurtleScreen.
+
+- The implementation uses a 2-vector class named Vec2D, derived from tuple.
+  This class is public, so it can be imported by the application programmer,
+  which makes certain types of computations very natural and compact.
+
+- Appearance of the TurtleScreen and the Turtles at startup/import can be
+  configured by means of a turtle.cfg configuration file.
+  The default configuration mimics the appearance of the old turtle module.
+
+- If configured appropriately the module reads in docstrings from a docstring
+  dictionary in some different language, supplied separately  and replaces
+  the english ones by those read in. There is a utility function
+  write_docstringdict() to write a dictionary with the original (english)
+  docstrings to disc, so it can serve as a template for translations.
+
+Behind the scenes there are some features included with possible
+extensionsin in mind. These will be commented and documented elsewhere.
+
+"""
+
+_ver = "turtle 1.0b1 - for Python 2.6   -  30. 5. 2008, 18:08"
+
+#print _ver
+
+import Tkinter as TK
+import types
+import math
+import time
+import os
+
+from os.path import isfile, split, join
+from copy import deepcopy
+
+from math import *    ## for compatibility with old turtle module
+
+_tg_classes = ['ScrolledCanvas', 'TurtleScreen', 'Screen',
+               'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D']
+_tg_screen_functions = ['addshape', 'bgcolor', 'bgpic', 'bye',
+        'clearscreen', 'colormode', 'delay', 'exitonclick', 'getcanvas',
+        'getshapes', 'listen', 'mode', 'onkey', 'onscreenclick', 'ontimer',
+        'register_shape', 'resetscreen', 'screensize', 'setup',
+        'setworldcoordinates', 'title', 'tracer', 'turtles', 'update',
+        'window_height', 'window_width']
+_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
+        'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'color',
+        'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd',
+        'fill', 'fillcolor', 'forward', 'get_poly', 'getpen', 'getscreen',
+        'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'isdown',
+        'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease', 'pd',
+        'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position',
+        'pu', 'radians', 'right', 'reset', 'resizemode', 'rt',
+        'seth', 'setheading', 'setpos', 'setposition', 'settiltangle',
+        'setundobuffer', 'setx', 'sety', 'shape', 'shapesize', 'showturtle',
+        'speed', 'st', 'stamp', 'tilt', 'tiltangle', 'towards', 'tracer',
+        'turtlesize', 'undo', 'undobufferentries', 'up', 'width',
+        'window_height', 'window_width', 'write', 'xcor', 'ycor']
+_tg_utilities = ['write_docstringdict', 'done', 'mainloop']
+_math_functions = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
+        'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
+        'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
+
+__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
+           _tg_utilities + _math_functions)
+
+_alias_list = ['addshape', 'backward', 'bk', 'fd', 'ht', 'lt', 'pd', 'pos',
+               'pu', 'rt', 'seth', 'setpos', 'setposition', 'st',
+               'turtlesize', 'up', 'width']
+
+_CFG = {"width" : 0.5,               # Screen
+        "height" : 0.75,
+        "canvwidth" : 400,
+        "canvheight": 300,
+        "leftright": None,
+        "topbottom": None,
+        "mode": "standard",          # TurtleScreen
+        "colormode": 1.0,
+        "delay": 10,
+        "undobuffersize": 1000,      # RawTurtle
+        "shape": "classic",
+        "pencolor" : "black",
+        "fillcolor" : "black",
+        "resizemode" : "noresize",
+        "visible" : True,
+        "language": "english",        # docstrings
+        "exampleturtle": "turtle",
+        "examplescreen": "screen",
+        "title": "Python Turtle Graphics",
+        "using_IDLE": False
+       }
+
+##print "cwd:", os.getcwd()
+##print "__file__:", __file__
+##
+##def show(dictionary):
+##    print "=========================="
+##    for key in sorted(dictionary.keys()):
+##        print key, ":", dictionary[key]
+##    print "=========================="
+##    print
+
+def config_dict(filename):
+    """Convert content of config-file into dictionary."""
+    f = open(filename, "r")
+    cfglines = f.readlines()
+    f.close()
+    cfgdict = {}
+    for line in cfglines:
+        line = line.strip()
+        if not line or line.startswith("#"):
+            continue
+        try:
+            key, value = line.split("=")
+        except:
+            print "Bad line in config-file %s:\n%s" % (filename,line)
+            continue
+        key = key.strip()
+        value = value.strip()
+        if value in ["True", "False", "None", "''", '""']:
+            value = eval(value)
+        else:
+            try:
+                if "." in value:
+                    value = float(value)
+                else:
+                    value = int(value)
+            except:
+                pass # value need not be converted
+        cfgdict[key] = value
+    return cfgdict
+
+def readconfig(cfgdict):
+    """Read config-files, change configuration-dict accordingly.
+
+    If there is a turtle.cfg file in the current working directory,
+    read it from there. If this contains an importconfig-value,
+    say 'myway', construct filename turtle_mayway.cfg else use
+    turtle.cfg and read it from the import-directory, where
+    turtle.py is located.
+    Update configuration dictionary first according to config-file,
+    in the import directory, then according to config-file in the
+    current working directory.
+    If no config-file is found, the default configuration is used.
+    """
+    default_cfg = "turtle.cfg"
+    cfgdict1 = {}
+    cfgdict2 = {}
+    if isfile(default_cfg):
+        cfgdict1 = config_dict(default_cfg)
+        #print "1. Loading config-file %s from: %s" % (default_cfg, os.getcwd())
+    if "importconfig" in cfgdict1:
+        default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"]
+    try:
+        head, tail = split(__file__)
+        cfg_file2 = join(head, default_cfg)
+    except:
+        cfg_file2 = ""
+    if isfile(cfg_file2):
+        #print "2. Loading config-file %s:" % cfg_file2
+        cfgdict2 = config_dict(cfg_file2)
+##    show(_CFG)
+##    show(cfgdict2)
+    _CFG.update(cfgdict2)
+##    show(_CFG)
+##    show(cfgdict1)
+    _CFG.update(cfgdict1)
+##    show(_CFG)
+
+try:
+    readconfig(_CFG)
+except:
+    print "No configfile read, reason unknown"
+
+
+class Vec2D(tuple):
+    """A 2 dimensional vector class, used as a helper class
+    for implementing turtle graphics.
+    May be useful for turtle graphics programs also.
+    Derived from tuple, so a vector is a tuple!
+
+    Provides (for a, b vectors, k number):
+       a+b vector addition
+       a-b vector subtraction
+       a*b inner product
+       k*a and a*k multiplication with scalar
+       |a| absolute value of a
+       a.rotate(angle) rotation
+    """
+    def __new__(cls, x, y):
+        return tuple.__new__(cls, (x, y))
+    def __add__(self, other):
+        return Vec2D(self[0]+other[0], self[1]+other[1])
+    def __mul__(self, other):
+        if isinstance(other, Vec2D):
+            return self[0]*other[0]+self[1]*other[1]
+        return Vec2D(self[0]*other, self[1]*other)
+    def __rmul__(self, other):
+        if isinstance(other, int) or isinstance(other, float):
+            return Vec2D(self[0]*other, self[1]*other)
+    def __sub__(self, other):
+        return Vec2D(self[0]-other[0], self[1]-other[1])
+    def __neg__(self):
+        return Vec2D(-self[0], -self[1])
+    def __abs__(self):
+        return (self[0]**2 + self[1]**2)**0.5
+    def rotate(self, angle):
+        """rotate self counterclockwise by angle
+        """
+        perp = Vec2D(-self[1], self[0])
+        angle = angle * math.pi / 180.0
+        c, s = math.cos(angle), math.sin(angle)
+        return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)
+    def __getnewargs__(self):
+        return (self[0], self[1])
+    def __repr__(self):
+        return "(%.2f,%.2f)" % self
+
+
+##############################################################################
+### From here up to line    : Tkinter - Interface for turtle.py            ###
+### May be replaced by an interface to some different graphcis-toolkit     ###
+##############################################################################
+
+## helper functions for Scrolled Canvas, to forward Canvas-methods
+## to ScrolledCanvas class
+
+def __methodDict(cls, _dict):
+    """helper function for Scrolled Canvas"""
+    baseList = list(cls.__bases__)
+    baseList.reverse()
+    for _super in baseList:
+        __methodDict(_super, _dict)
+    for key, value in cls.__dict__.items():
+        if type(value) == types.FunctionType:
+            _dict[key] = value
+
+def __methods(cls):
+    """helper function for Scrolled Canvas"""
+    _dict = {}
+    __methodDict(cls, _dict)
+    return _dict.keys()
+
+__stringBody = (
+    'def %(method)s(self, *args, **kw): return ' +
+    'self.%(attribute)s.%(method)s(*args, **kw)')
+
+def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
+    """Helper functions for Scrolled Canvas, used to forward
+    ScrolledCanvas-methods to Tkinter.Canvas class.
+    """
+    _dict = {}
+    __methodDict(toClass, _dict)
+    for ex in _dict.keys():
+        if ex[:1] == '_' or ex[-1:] == '_':
+            del _dict[ex]
+    for ex in exclude:
+        if _dict.has_key(ex):
+            del _dict[ex]
+    for ex in __methods(fromClass):
+        if _dict.has_key(ex):
+            del _dict[ex]
+
+    for method, func in _dict.items():
+        d = {'method': method, 'func': func}
+        if type(toPart) == types.StringType:
+            execString = \
+                __stringBody % {'method' : method, 'attribute' : toPart}
+        exec execString in d
+        fromClass.__dict__[method] = d[method]
+
+
+class ScrolledCanvas(TK.Frame):
+    """Modeled after the scrolled canvas class from Grayons's Tkinter book.
+
+    Used as the default canvas, which pops up automatically when
+    using turtle graphics functions or the Turtle class.
+    """
+    def __init__(self, master, width=500, height=350,
+                                          canvwidth=600, canvheight=500):
+        TK.Frame.__init__(self, master, width=width, height=height)
+        self._root = self.winfo_toplevel()
+        self.width, self.height = width, height
+        self.canvwidth, self.canvheight = canvwidth, canvheight
+        self.bg = "white"
+        self._canvas = TK.Canvas(master, width=width, height=height,
+                                 bg=self.bg, relief=TK.SUNKEN, borderwidth=2)
+        self.hscroll = TK.Scrollbar(master, command=self._canvas.xview,
+                                    orient=TK.HORIZONTAL)
+        self.vscroll = TK.Scrollbar(master, command=self._canvas.yview)
+        self._canvas.configure(xscrollcommand=self.hscroll.set,
+                               yscrollcommand=self.vscroll.set)
+        self.rowconfigure(0, weight=1, minsize=0)
+        self.columnconfigure(0, weight=1, minsize=0)
+        self._canvas.grid(padx=1, in_ = self, pady=1, row=0,
+                column=0, rowspan=1, columnspan=1, sticky='news')
+        self.vscroll.grid(padx=1, in_ = self, pady=1, row=0,
+                column=1, rowspan=1, columnspan=1, sticky='news')
+        self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
+                column=0, rowspan=1, columnspan=1, sticky='news')
+        self.reset()
+        self._root.bind('<Configure>', self.onResize)
+
+    def reset(self, canvwidth=None, canvheight=None, bg = None):
+        """Ajust canvas and scrollbars according to given canvas size."""
+        if canvwidth:
+            self.canvwidth = canvwidth
+        if canvheight:
+            self.canvheight = canvheight
+        if bg:
+            self.bg = bg
+        self._canvas.config(bg=bg,
+                        scrollregion=(-self.canvwidth//2, -self.canvheight//2,
+                                       self.canvwidth//2, self.canvheight//2))
+        self._canvas.xview_moveto(0.5*(self.canvwidth - self.width + 30) /
+                                                               self.canvwidth)
+        self._canvas.yview_moveto(0.5*(self.canvheight- self.height + 30) /
+                                                              self.canvheight)
+        self.adjustScrolls()
+
+
+    def adjustScrolls(self):
+        """ Adjust scrollbars according to window- and canvas-size.
+        """
+        cwidth = self._canvas.winfo_width()
+        cheight = self._canvas.winfo_height()
+        self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
+        self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
+        if cwidth < self.canvwidth or cheight < self.canvheight:
+            self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
+                              column=0, rowspan=1, columnspan=1, sticky='news')
+            self.vscroll.grid(padx=1, in_ = self, pady=1, row=0,
+                              column=1, rowspan=1, columnspan=1, sticky='news')
+        else:
+            self.hscroll.grid_forget()
+            self.vscroll.grid_forget()
+
+    def onResize(self, event):
+        """self-explanatory"""
+        self.adjustScrolls()
+
+    def bbox(self, *args):
+        """ 'forward' method, which canvas itself has inherited...
+        """
+        return self._canvas.bbox(*args)
+
+    def cget(self, *args, **kwargs):
+        """ 'forward' method, which canvas itself has inherited...
+        """
+        return self._canvas.cget(*args, **kwargs)
+
+    def config(self, *args, **kwargs):
+        """ 'forward' method, which canvas itself has inherited...
+        """
+        self._canvas.config(*args, **kwargs)
+
+    def bind(self, *args, **kwargs):
+        """ 'forward' method, which canvas itself has inherited...
+        """
+        self._canvas.bind(*args, **kwargs)
+
+    def unbind(self, *args, **kwargs):
+        """ 'forward' method, which canvas itself has inherited...
+        """
+        self._canvas.unbind(*args, **kwargs)
+
+    def focus_force(self):
+        """ 'forward' method, which canvas itself has inherited...
+        """
+        self._canvas.focus_force()
+
+__forwardmethods(ScrolledCanvas, TK.Canvas, '_canvas')
+
+
+class _Root(TK.Tk):
+    """Root class for Screen based on Tkinter."""
+    def __init__(self):
+        TK.Tk.__init__(self)
+
+    def setupcanvas(self, width, height, cwidth, cheight):
+        self._canvas = ScrolledCanvas(self, width, height, cwidth, cheight)
+        self._canvas.pack(expand=1, fill="both")
+
+    def _getcanvas(self):
+        return self._canvas
+
+    def set_geometry(self, width, height, startx, starty):
+        self.geometry("%dx%d%+d%+d"%(width, height, startx, starty))
+
+    def ondestroy(self, destroy):
+        self.wm_protocol("WM_DELETE_WINDOW", destroy)
+
+    def win_width(self):
+        return self.winfo_screenwidth()
+
+    def win_height(self):
+        return self.winfo_screenheight()
+
+Canvas = TK.Canvas
+
+
+class TurtleScreenBase(object):
+    """Provide the basic graphics functionality.
+       Interface between Tkinter and turtle.py.
+
+       To port turtle.py to some different graphics toolkit
+       a corresponding TurtleScreenBase class has to be implemented.
+    """
+
+    @staticmethod
+    def _blankimage():
+        """return a blank image object
+        """
+        img = TK.PhotoImage(width=1, height=1)
+        img.blank()
+        return img
+
+    @staticmethod
+    def _image(filename):
+        """return an image object containing the
+        imagedata from a gif-file named filename.
+        """
+        return TK.PhotoImage(file=filename)
+
+    def __init__(self, cv):
+        self.cv = cv
+        if isinstance(cv, ScrolledCanvas):
+            w = self.cv.canvwidth
+            h = self.cv.canvheight
+        else:  # expected: ordinary TK.Canvas
+            w = int(self.cv.cget("width"))
+            h = int(self.cv.cget("height"))
+            self.cv.config(scrollregion = (-w//2, -h//2, w//2, h//2 ))
+        self.canvwidth = w
+        self.canvheight = h
+        self.xscale = self.yscale = 1.0
+
+    def _createpoly(self):
+        """Create an invisible polygon item on canvas self.cv)
+        """
+        return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
+
+    def _drawpoly(self, polyitem, coordlist, fill=None,
+                  outline=None, width=None, top=False):
+        """Configure polygonitem polyitem according to provided
+        arguments:
+        coordlist is sequence of coordinates
+        fill is filling color
+        outline is outline color
+        top is a boolean value, which specifies if polyitem
+        will be put on top of the canvas' displaylist so it
+        will not be covered by other items.
+        """
+        cl = []
+        for x, y in coordlist:
+            cl.append(x * self.xscale)
+            cl.append(-y * self.yscale)
+        self.cv.coords(polyitem, *cl)
+        if fill is not None:
+            self.cv.itemconfigure(polyitem, fill=fill)
+        if outline is not None:
+            self.cv.itemconfigure(polyitem, outline=outline)
+        if width is not None:
+            self.cv.itemconfigure(polyitem, width=width)
+        if top:
+            self.cv.tag_raise(polyitem)
+
+    def _createline(self):
+        """Create an invisible line item on canvas self.cv)
+        """
+        return self.cv.create_line(0, 0, 0, 0, fill="", width=2,
+                                   capstyle = TK.ROUND)
+
+    def _drawline(self, lineitem, coordlist=None,
+                  fill=None, width=None, top=False):
+        """Configure lineitem according to provided arguments:
+        coordlist is sequence of coordinates
+        fill is drawing color
+        width is width of drawn line.
+        top is a boolean value, which specifies if polyitem
+        will be put on top of the canvas' displaylist so it
+        will not be covered by other items.
+        """
+        if coordlist is not None:
+            cl = []
+            for x, y in coordlist:
+                cl.append(x * self.xscale)
+                cl.append(-y * self.yscale)
+            self.cv.coords(lineitem, *cl)
+        if fill is not None:
+            self.cv.itemconfigure(lineitem, fill=fill)
+        if width is not None:
+            self.cv.itemconfigure(lineitem, width=width)
+        if top:
+            self.cv.tag_raise(lineitem)
+
+    def _delete(self, item):
+        """Delete graphics item from canvas.
+        If item is"all" delete all graphics items.
+        """
+        self.cv.delete(item)
+
+    def _update(self):
+        """Redraw graphics items on canvas
+        """
+        self.cv.update()
+
+    def _delay(self, delay):
+        """Delay subsequent canvas actions for delay ms."""
+        self.cv.after(delay)
+
+    def _iscolorstring(self, color):
+        """Check if the string color is a legal Tkinter color string.
+        """
+        try:
+            rgb = self.cv.winfo_rgb(color)
+            ok = True
+        except TK.TclError:
+            ok = False
+        return ok
+
+    def _bgcolor(self, color=None):
+        """Set canvas' backgroundcolor if color is not None,
+        else return backgroundcolor."""
+        if color is not None:
+            self.cv.config(bg = color)
+            self._update()
+        else:
+            return self.cv.cget("bg")
+
+    def _write(self, pos, txt, align, font, pencolor):
+        """Write txt at pos in canvas with specified font
+        and color.
+        Return text item and x-coord of right bottom corner
+        of text's bounding box."""
+        x, y = pos
+        x = x * self.xscale
+        y = y * self.yscale
+        anchor = {"left":"sw", "center":"s", "right":"se" }
+        item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align],
+                                        fill = pencolor, font = font)
+        x0, y0, x1, y1 = self.cv.bbox(item)
+        self.cv.update()
+        return item, x1-1
+
+##    def _dot(self, pos, size, color):
+##        """may be implemented for some other graphics toolkit"""
+
+    def _onclick(self, item, fun, num=1, add=None):
+        """Bind fun to mouse-click event on turtle.
+        fun must be a function with two arguments, the coordinates
+        of the clicked point on the canvas.
+        num, the number of the mouse-button defaults to 1
+        """
+        if fun is None:
+            self.cv.tag_unbind(item, "<Button-%s>" % num)
+        else:
+            def eventfun(event):
+                x, y = (self.cv.canvasx(event.x)/self.xscale,
+                        -self.cv.canvasy(event.y)/self.yscale)
+                fun(x, y)
+            self.cv.tag_bind(item, "<Button-%s>" % num, eventfun, add)
+
+    def _onrelease(self, item, fun, num=1, add=None):
+        """Bind fun to mouse-button-release event on turtle.
+        fun must be a function with two arguments, the coordinates
+        of the point on the canvas where mouse button is released.
+        num, the number of the mouse-button defaults to 1
+
+        If a turtle is clicked, first _onclick-event will be performed,
+        then _onscreensclick-event.
+        """
+        if fun is None:
+            self.cv.tag_unbind(item, "<Button%s-ButtonRelease>" % num)
+        else:
+            def eventfun(event):
+                x, y = (self.cv.canvasx(event.x)/self.xscale,
+                        -self.cv.canvasy(event.y)/self.yscale)
+                fun(x, y)
+            self.cv.tag_bind(item, "<Button%s-ButtonRelease>" % num,
+                             eventfun, add)
+
+    def _ondrag(self, item, fun, num=1, add=None):
+        """Bind fun to mouse-move-event (with pressed mouse button) on turtle.
+        fun must be a function with two arguments, the coordinates of the
+        actual mouse position on the canvas.
+        num, the number of the mouse-button defaults to 1
+
+        Every sequence of mouse-move-events on a turtle is preceded by a
+        mouse-click event on that turtle.
+        """
+        if fun is None:
+            self.cv.tag_unbind(item, "<Button%s-Motion>" % num)
+        else:
+            def eventfun(event):
+                try:
+                    x, y = (self.cv.canvasx(event.x)/self.xscale,
+                           -self.cv.canvasy(event.y)/self.yscale)
+                    fun(x, y)
+                except:
+                    pass
+            self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add)
+
+    def _onscreenclick(self, fun, num=1, add=None):
+        """Bind fun to mouse-click event on canvas.
+        fun must be a function with two arguments, the coordinates
+        of the clicked point on the canvas.
+        num, the number of the mouse-button defaults to 1
+
+        If a turtle is clicked, first _onclick-event will be performed,
+        then _onscreensclick-event.
+        """
+        if fun is None:
+            self.cv.unbind("<Button-%s>" % num)
+        else:
+            def eventfun(event):
+                x, y = (self.cv.canvasx(event.x)/self.xscale,
+                        -self.cv.canvasy(event.y)/self.yscale)
+                fun(x, y)
+            self.cv.bind("<Button-%s>" % num, eventfun, add)
+
+    def _onkey(self, fun, key):
+        """Bind fun to key-release event of key.
+        Canvas must have focus. See method listen
+        """
+        if fun is None:
+            self.cv.unbind("<KeyRelease-%s>" % key, None)
+        else:
+            def eventfun(event):
+                fun()
+            self.cv.bind("<KeyRelease-%s>" % key, eventfun)
+
+    def _listen(self):
+        """Set focus on canvas (in order to collect key-events)
+        """
+        self.cv.focus_force()
+
+    def _ontimer(self, fun, t):
+        """Install a timer, which calls fun after t milliseconds.
+        """
+        if t == 0:
+            self.cv.after_idle(fun)
+        else:
+            self.cv.after(t, fun)
+
+    def _createimage(self, image):
+        """Create and return image item on canvas.
+        """
+        return self.cv.create_image(0, 0, image=image)
+
+    def _drawimage(self, item, (x, y), image):
+        """Configure image item as to draw image object
+        at position (x,y) on canvas)
+        """
+        self.cv.coords(item, (x, -y))
+        self.cv.itemconfig(item, image=image)
+
+    def _setbgpic(self, item, image):
+        """Configure image item as to draw image object
+        at center of canvas. Set item to the first item
+        in the displaylist, so it will be drawn below
+        any other item ."""
+        self.cv.itemconfig(item, image=image)
+        self.cv.tag_lower(item)
+
+    def _type(self, item):
+        """Return 'line' or 'polygon' or 'image' depending on
+        type of item.
+        """
+        return self.cv.type(item)
+
+    def _pointlist(self, item):
+        """returns list of coordinate-pairs of points of item
+        Example (for insiders):
+        >>> from turtle import *
+        >>> getscreen()._pointlist(getturtle().turtle._item)
+        [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
+        (9.9999999999999982, 0.0)]
+        >>> """
+        cl = self.cv.coords(item)
+        pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)]
+        return  pl
+
+    def _setscrollregion(self, srx1, sry1, srx2, sry2):
+        self.cv.config(scrollregion=(srx1, sry1, srx2, sry2))
+
+    def _rescale(self, xscalefactor, yscalefactor):
+        items = self.cv.find_all()
+        for item in items:
+            coordinates = self.cv.coords(item)
+            newcoordlist = []
+            while coordinates:
+                x, y = coordinates[:2]
+                newcoordlist.append(x * xscalefactor)
+                newcoordlist.append(y * yscalefactor)
+                coordinates = coordinates[2:]
+            self.cv.coords(item, *newcoordlist)
+
+    def _resize(self, canvwidth=None, canvheight=None, bg=None):
+        """Resize the canvas, the turtles are drawing on. Does
+        not alter the drawing window.
+        """
+        # needs amendment
+        if not isinstance(self.cv, ScrolledCanvas):
+            return self.canvwidth, self.canvheight
+        if canvwidth is None and canvheight is None and bg is None:
+            return self.cv.canvwidth, self.cv.canvheight
+        if canvwidth is not None:
+            self.canvwidth = canvwidth
+        if canvheight is not None:
+            self.canvheight = canvheight
+        self.cv.reset(canvwidth, canvheight, bg)
+
+    def _window_size(self):
+        """ Return the width and height of the turtle window.
+        """
+        width = self.cv.winfo_width()
+        if width <= 1:  # the window isn't managed by a geometry manager
+            width = self.cv['width']
+        height = self.cv.winfo_height()
+        if height <= 1: # the window isn't managed by a geometry manager
+            height = self.cv['height']
+        return width, height
+
+
+##############################################################################
+###                  End of Tkinter - interface                            ###
+##############################################################################
+
+
+class Terminator (Exception):
+    """Will be raised in TurtleScreen.update, if _RUNNING becomes False.
+
+    Thus stops execution of turtle graphics script. Main purpose: use in
+    in the Demo-Viewer turtle.Demo.py.
+    """
+    pass
+
+
+class TurtleGraphicsError(Exception):
+    """Some TurtleGraphics Error
+    """
+
+
+class Shape(object):
+    """Data structure modeling shapes.
+
+    attribute _type is one of "polygon", "image", "compound"
+    attribute _data is - depending on _type a poygon-tuple,
+    an image or a list constructed using the addcomponent method.
+    """
+    def __init__(self, type_, data=None):
+        self._type = type_
+        if type_ == "polygon":
+            if isinstance(data, list):
+                data = tuple(data)
+        elif type_ == "image":
+            if isinstance(data, str):
+                if data.lower().endswith(".gif") and isfile(data):
+                    data = TurtleScreen._image(data)
+                # else data assumed to be Photoimage
+        elif type_ == "compound":
+            data = []
+        else:
+            raise TurtleGraphicsError("There is no shape type %s" % type_)
+        self._data = data
+
+    def addcomponent(self, poly, fill, outline=None):
+        """Add component to a shape of type compound.
+
+        Arguments: poly is a polygon, i. e. a tuple of number pairs.
+        fill is the fillcolor of the component,
+        outline is the outline color of the component.
+
+        call (for a Shapeobject namend s):
+        --   s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
+
+        Example:
+        >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
+        >>> s = Shape("compound")
+        >>> s.addcomponent(poly, "red", "blue")
+        ### .. add more components and then use register_shape()
+        """
+        if self._type != "compound":
+            raise TurtleGraphicsError("Cannot add component to %s Shape"
+                                                                % self._type)
+        if outline is None:
+            outline = fill
+        self._data.append([poly, fill, outline])
+
+
+class Tbuffer(object):
+    """Ring buffer used as undobuffer for RawTurtle objects."""
+    def __init__(self, bufsize=10):
+        self.bufsize = bufsize
+        self.buffer = [[None]] * bufsize
+        self.ptr = -1
+        self.cumulate = False
+    def reset(self, bufsize=None):
+        if bufsize is None:
+            for i in range(self.bufsize):
+                self.buffer[i] = [None]
+        else:
+            self.bufsize = bufsize
+            self.buffer = [[None]] * bufsize
+        self.ptr = -1
+    def push(self, item):
+        if self.bufsize > 0:
+            if not self.cumulate:
+                self.ptr = (self.ptr + 1) % self.bufsize
+                self.buffer[self.ptr] = item
+            else:
+                self.buffer[self.ptr].append(item)
+    def pop(self):
+        if self.bufsize > 0:
+            item = self.buffer[self.ptr]
+            if item is None:
+                return None
+            else:
+                self.buffer[self.ptr] = [None]
+                self.ptr = (self.ptr - 1) % self.bufsize
+                return (item)
+    def nr_of_items(self):
+        return self.bufsize - self.buffer.count([None])
+    def __repr__(self):
+        return str(self.buffer) + " " + str(self.ptr)
+
+
+
+class TurtleScreen(TurtleScreenBase):
+    """Provides screen oriented methods like setbg etc.
+
+    Only relies upon the methods of TurtleScreenBase and NOT
+    upon components of the underlying graphics toolkit -
+    which is Tkinter in this case.
+    """
+#    _STANDARD_DELAY = 5
+    _RUNNING = True
+
+    def __init__(self, cv, mode=_CFG["mode"],
+                 colormode=_CFG["colormode"], delay=_CFG["delay"]):
+        self._shapes = {
+                   "arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))),
+                  "turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7),
+                              (-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6),
+                              (-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6),
+                              (5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10),
+                              (2,14))),
+                  "circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88),
+                              (5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51),
+                              (-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0),
+                              (-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09),
+                              (-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51),
+                              (5.88,-8.09), (8.09,-5.88), (9.51,-3.09))),
+                  "square" : Shape("polygon", ((10,-10), (10,10), (-10,10),
+                              (-10,-10))),
+                "triangle" : Shape("polygon", ((10,-5.77), (0,11.55),
+                              (-10,-5.77))),
+                  "classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))),
+                   "blank" : Shape("image", self._blankimage())
+                  }
+
+        self._bgpics = {"nopic" : ""}
+
+        TurtleScreenBase.__init__(self, cv)
+        self._mode = mode
+        self._delayvalue = delay
+        self._colormode = _CFG["colormode"]
+        self._keys = []
+        self.clear()
+
+    def clear(self):
+        """Delete all drawings and all turtles from the TurtleScreen.
+
+        Reset empty TurtleScreen to it's initial state: white background,
+        no backgroundimage, no eventbindings and tracing on.
+
+        No argument.
+
+        Example (for a TurtleScreen instance named screen):
+        screen.clear()
+
+        Note: this method is not available as function.
+        """
+        self._delayvalue = _CFG["delay"]
+        self._colormode = _CFG["colormode"]
+        self._delete("all")
+        self._bgpic = self._createimage("")
+        self._bgpicname = "nopic"
+        self._tracing = 1
+        self._updatecounter = 0
+        self._turtles = []
+        self.bgcolor("white")
+        for btn in 1, 2, 3:
+            self.onclick(None, btn)
+        for key in self._keys[:]:
+            self.onkey(None, key)
+        Turtle._pen = None
+
+    def mode(self, mode=None):
+        """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
+
+        Optional argument:
+        mode -- on of the strings 'standard', 'logo' or 'world'
+
+        Mode 'standard' is compatible with turtle.py.
+        Mode 'logo' is compatible with most Logo-Turtle-Graphics.
+        Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
+        this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
+        If mode is not given, return the current mode.
+
+             Mode      Initial turtle heading     positive angles
+         ------------|-------------------------|-------------------
+          'standard'    to the right (east)       counterclockwise
+            'logo'        upward    (north)         clockwise
+
+        Examples:
+        >>> mode('logo')   # resets turtle heading to north
+        >>> mode()
+        'logo'
+        """
+        if mode == None:
+            return self._mode
+        mode = mode.lower()
+        if mode not in ["standard", "logo", "world"]:
+            raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode)
+        self._mode = mode
+        if mode in ["standard", "logo"]:
+            self._setscrollregion(-self.canvwidth//2, -self.canvheight//2,
+                                       self.canvwidth//2, self.canvheight//2)
+            self.xscale = self.yscale = 1.0
+        self.reset()
+
+    def setworldcoordinates(self, llx, lly, urx, ury):
+        """Set up a user defined coordinate-system.
+
+        Arguments:
+        llx -- a number, x-coordinate of lower left corner of canvas
+        lly -- a number, y-coordinate of lower left corner of canvas
+        urx -- a number, x-coordinate of upper right corner of canvas
+        ury -- a number, y-coordinate of upper right corner of canvas
+
+        Set up user coodinat-system and switch to mode 'world' if necessary.
+        This performs a screen.reset. If mode 'world' is already active,
+        all drawings are redrawn according to the new coordinates.
+
+        But ATTENTION: in user-defined coordinatesystems angles may appear
+        distorted. (see Screen.mode())
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
+        >>> for _ in range(36):
+                left(10)
+                forward(0.5)
+        """
+        if self.mode() != "world":
+            self.mode("world")
+        xspan = float(urx - llx)
+        yspan = float(ury - lly)
+        wx, wy = self._window_size()
+        self.screensize(wx-20, wy-20)
+        oldxscale, oldyscale = self.xscale, self.yscale
+        self.xscale = self.canvwidth / xspan
+        self.yscale = self.canvheight / yspan
+        srx1 = llx * self.xscale
+        sry1 = -ury * self.yscale
+        srx2 = self.canvwidth + srx1
+        sry2 = self.canvheight + sry1
+        self._setscrollregion(srx1, sry1, srx2, sry2)
+        self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
+        self.update()
+
+    def register_shape(self, name, shape=None):
+        """Adds a turtle shape to TurtleScreen's shapelist.
+
+        Arguments:
+        (1) name is the name of a gif-file and shape is None.
+            Installs the corresponding image shape.
+            !! Image-shapes DO NOT rotate when turning the turtle,
+            !! so they do not display the heading of the turtle!
+        (2) name is an arbitrary string and shape is a tuple
+            of pairs of coordinates. Installs the corresponding
+            polygon shape
+        (3) name is an arbitrary string and shape is a
+            (compound) Shape object. Installs the corresponding
+            compound shape.
+        To use a shape, you have to issue the command shape(shapename).
+
+        call: register_shape("turtle.gif")
+        --or: register_shape("tri", ((0,0), (10,10), (-10,10)))
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
+
+        """
+        if shape is None:
+            # image
+            if name.lower().endswith(".gif"):
+                shape = Shape("image", self._image(name))
+            else:
+                raise TurtleGraphicsError("Bad arguments for register_shape.\n"
+                                          + "Use  help(register_shape)" )
+        elif isinstance(shape, tuple):
+            shape = Shape("polygon", shape)
+        ## else shape assumed to be Shape-instance
+        self._shapes[name] = shape
+        # print "shape added:" , self._shapes
+
+    def _colorstr(self, color):
+        """Return color string corresponding to args.
+
+        Argument may be a string or a tuple of three
+        numbers corresponding to actual colormode,
+        i.e. in the range 0<=n<=colormode.
+
+        If the argument doesn't represent a color,
+        an error is raised.
+        """
+        if len(color) == 1:
+            color = color[0]
+        if isinstance(color, str):
+            if self._iscolorstring(color) or color == "":
+                return color
+            else:
+                raise TurtleGraphicsError("bad color string: %s" % str(color))
+        try:
+            r, g, b = color
+        except:
+            raise TurtleGraphicsError("bad color arguments: %s" % str(color))
+        if self._colormode == 1.0:
+            r, g, b = [round(255.0*x) for x in (r, g, b)]
+        if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
+            raise TurtleGraphicsError("bad color sequence: %s" % str(color))
+        return "#%02x%02x%02x" % (r, g, b)
+
+    def _color(self, cstr):
+        if not cstr.startswith("#"):
+            return cstr
+        if len(cstr) == 7:
+            cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)]
+        elif len(cstr) == 4:
+            cl = [16*int(cstr[h], 16) for h in cstr[1:]]
+        else:
+            raise TurtleGraphicsError("bad colorstring: %s" % cstr)
+        return tuple([c * self._colormode/255 for c in cl])
+
+    def colormode(self, cmode=None):
+        """Return the colormode or set it to 1.0 or 255.
+
+        Optional argument:
+        cmode -- one of the values 1.0 or 255
+
+        r, g, b values of colortriples have to be in range 0..cmode.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.colormode()
+        1.0
+        >>> screen.colormode(255)
+        >>> turtle.pencolor(240,160,80)
+        """
+        if cmode is None:
+            return self._colormode
+        if cmode == 1.0:
+            self._colormode = float(cmode)
+        elif cmode == 255:
+            self._colormode = int(cmode)
+
+    def reset(self):
+        """Reset all Turtles on the Screen to their initial state.
+
+        No argument.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.reset()
+        """
+        for turtle in self._turtles:
+            turtle._setmode(self._mode)
+            turtle.reset()
+
+    def turtles(self):
+        """Return the list of turtles on the screen.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.turtles()
+        [<turtle.Turtle object at 0x00E11FB0>]
+        """
+        return self._turtles
+
+    def bgcolor(self, *args):
+        """Set or return backgroundcolor of the TurtleScreen.
+
+        Arguments (if given): a color string or three numbers
+        in the range 0..colormode or a 3-tuple of such numbers.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.bgcolor("orange")
+        >>> screen.bgcolor()
+        'orange'
+        >>> screen.bgcolor(0.5,0,0.5)
+        >>> screen.bgcolor()
+        '#800080'
+        """
+        if args:
+            color = self._colorstr(args)
+        else:
+            color = None
+        color = self._bgcolor(color)
+        if color is not None:
+            color = self._color(color)
+        return color
+
+    def tracer(self, n=None, delay=None):
+        """Turns turtle animation on/off and set delay for update drawings.
+
+        Optional arguments:
+        n -- nonnegative  integer
+        delay -- nonnegative  integer
+
+        If n is given, only each n-th regular screen update is really performed.
+        (Can be used to accelerate the drawing of complex graphics.)
+        Second arguments sets delay value (see RawTurtle.delay())
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.tracer(8, 25)
+        >>> dist = 2
+        >>> for i in range(200):
+                fd(dist)
+                rt(90)
+                dist += 2
+        """
+        if n is None:
+            return self._tracing
+        self._tracing = int(n)
+        self._updatecounter = 0
+        if delay is not None:
+            self._delayvalue = int(delay)
+        if self._tracing:
+            self.update()
+
+    def delay(self, delay=None):
+        """ Return or set the drawing delay in milliseconds.
+
+        Optional argument:
+        delay -- positive integer
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.delay(15)
+        >>> screen.delay()
+        15
+        """
+        if delay is None:
+            return self._delayvalue
+        self._delayvalue = int(delay)
+
+    def _incrementudc(self):
+        "Increment upadate counter."""
+        if not TurtleScreen._RUNNING:
+            TurtleScreen._RUNNNING = True
+            raise Terminator
+        if self._tracing > 0:
+            self._updatecounter += 1
+            self._updatecounter %= self._tracing
+
+    def update(self):
+        """Perform a TurtleScreen update.
+        """
+        for t in self.turtles():
+            t._update_data()
+            t._drawturtle()
+        self._update()
+
+    def window_width(self):
+        """ Return the width of the turtle window.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.window_width()
+        640
+        """
+        return self._window_size()[0]
+
+    def window_height(self):
+        """ Return the height of the turtle window.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.window_height()
+        480
+        """
+        return self._window_size()[1]
+
+    def getcanvas(self):
+        """Return the Canvas of this TurtleScreen.
+
+        No argument.
+
+        Example (for a Screen instance named screen):
+        >>> cv = screen.getcanvas()
+        >>> cv
+        <turtle.ScrolledCanvas instance at 0x010742D8>
+        """
+        return self.cv
+
+    def getshapes(self):
+        """Return a list of names of all currently available turtle shapes.
+
+        No argument.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.getshapes()
+        ['arrow', 'blank', 'circle', ... , 'turtle']
+        """
+        return sorted(self._shapes.keys())
+
+    def onclick(self, fun, btn=1, add=None):
+        """Bind fun to mouse-click event on canvas.
+
+        Arguments:
+        fun -- a function with two arguments, the coordinates of the
+               clicked point on the canvas.
+        num -- the number of the mouse-button, defaults to 1
+
+        Example (for a TurtleScreen instance named screen
+        and a Turtle instance named turtle):
+
+        >>> screen.onclick(turtle.goto)
+
+        ### Subsequently clicking into the TurtleScreen will
+        ### make the turtle move to the clicked point.
+        >>> screen.onclick(None)
+
+        ### event-binding will be removed
+        """
+        self._onscreenclick(fun, btn, add)
+
+    def onkey(self, fun, key):
+        """Bind fun to key-release event of key.
+
+        Arguments:
+        fun -- a function with no arguments
+        key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
+
+        In order ro be able to register key-events, TurtleScreen
+        must have focus. (See method listen.)
+
+        Example (for a TurtleScreen instance named screen
+        and a Turtle instance named turtle):
+
+        >>> def f():
+                fd(50)
+                lt(60)
+
+
+        >>> screen.onkey(f, "Up")
+        >>> screen.listen()
+
+        ### Subsequently the turtle can be moved by
+        ### repeatedly pressing the up-arrow key,
+        ### consequently drawing a hexagon
+        """
+        if fun == None:
+            self._keys.remove(key)
+        elif key not in self._keys:
+            self._keys.append(key)
+        self._onkey(fun, key)
+
+    def listen(self, xdummy=None, ydummy=None):
+        """Set focus on TurtleScreen (in order to collect key-events)
+
+        No arguments.
+        Dummy arguments are provided in order
+        to be able to pass listen to the onclick method.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.listen()
+        """
+        self._listen()
+
+    def ontimer(self, fun, t=0):
+        """Install a timer, which calls fun after t milliseconds.
+
+        Arguments:
+        fun -- a function with no arguments.
+        t -- a number >= 0
+
+        Example (for a TurtleScreen instance named screen):
+
+        >>> running = True
+        >>> def f():
+                if running:
+                        fd(50)
+                        lt(60)
+                        screen.ontimer(f, 250)
+
+        >>> f()   ### makes the turtle marching around
+        >>> running = False
+        """
+        self._ontimer(fun, t)
+
+    def bgpic(self, picname=None):
+        """Set background image or return name of current backgroundimage.
+
+        Optional argument:
+        picname -- a string, name of a gif-file or "nopic".
+
+        If picname is a filename, set the corresponing image as background.
+        If picname is "nopic", delete backgroundimage, if present.
+        If picname is None, return the filename of the current backgroundimage.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.bgpic()
+        'nopic'
+        >>> screen.bgpic("landscape.gif")
+        >>> screen.bgpic()
+        'landscape.gif'
+        """
+        if picname is None:
+            return self._bgpicname
+        if picname not in self._bgpics:
+            self._bgpics[picname] = self._image(picname)
+        self._setbgpic(self._bgpic, self._bgpics[picname])
+        self._bgpicname = picname
+
+    def screensize(self, canvwidth=None, canvheight=None, bg=None):
+        """Resize the canvas, the turtles are drawing on.
+
+        Optional arguments:
+        canvwidth -- positive integer, new width of canvas in pixels
+        canvheight --  positive integer, new height of canvas in pixels
+        bg -- colorstring or color-tupel, new backgroundcolor
+        If no arguments are given, return current (canvaswidth, canvasheight)
+
+        Do not alter the drawing window. To observe hidden parts of
+        the canvas use the scrollbars. (Can make visible those parts
+        of a drawing, which were outside the canvas before!)
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.screensize(2000,1500)
+            ### e. g. to search for an erroneously escaped turtle ;-)
+        """
+        return self._resize(canvwidth, canvheight, bg)
+
+    onscreenclick = onclick
+    resetscreen = reset
+    clearscreen = clear
+    addshape = register_shape
+
+class TNavigator(object):
+    """Navigation part of the RawTurtle.
+    Implements methods for turtle movement.
+    """
+    START_ORIENTATION = {
+        "standard": Vec2D(1.0, 0.0),
+        "world"   : Vec2D(1.0, 0.0),
+        "logo"    : Vec2D(0.0, 1.0)  }
+    DEFAULT_MODE = "standard"
+    DEFAULT_ANGLEOFFSET = 0
+    DEFAULT_ANGLEORIENT = 1
+
+    def __init__(self, mode=DEFAULT_MODE):
+        self._angleOffset = self.DEFAULT_ANGLEOFFSET
+        self._angleOrient = self.DEFAULT_ANGLEORIENT
+        self._mode = mode
+        self.undobuffer = None
+        self.degrees()
+        self._mode = None
+        self._setmode(mode)
+        TNavigator.reset(self)
+
+    def reset(self):
+        """reset turtle to its initial values
+
+        Will be overwritten by parent class
+        """
+        self._position = Vec2D(0.0, 0.0)
+        self._orient =  TNavigator.START_ORIENTATION[self._mode]
+
+    def _setmode(self, mode=None):
+        """Set turtle-mode to 'standard', 'world' or 'logo'.
+        """
+        if mode == None:
+            return self._mode
+        if mode not in ["standard", "logo", "world"]:
+            return
+        self._mode = mode
+        if mode in ["standard", "world"]:
+            self._angleOffset = 0
+            self._angleOrient = 1
+        else: # mode == "logo":
+            self._angleOffset = self._fullcircle/4.
+            self._angleOrient = -1
+
+    def _setDegreesPerAU(self, fullcircle):
+        """Helper function for degrees() and radians()"""
+        self._fullcircle = fullcircle
+        self._degreesPerAU = 360/fullcircle
+        if self._mode == "standard":
+            self._angleOffset = 0
+        else:
+            self._angleOffset = fullcircle/4.
+
+    def degrees(self, fullcircle=360.0):
+        """ Set angle measurement units to degrees.
+
+        Optional argument:
+        fullcircle -  a number
+
+        Set angle measurement units, i. e. set number
+        of 'degrees' for a full circle. Dafault value is
+        360 degrees.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.left(90)
+        >>> turtle.heading()
+        90
+        >>> turtle.degrees(400.0)  # angle measurement in gon
+        >>> turtle.heading()
+        100
+
+        """
+        self._setDegreesPerAU(fullcircle)
+
+    def radians(self):
+        """ Set the angle measurement units to radians.
+
+        No arguments.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.heading()
+        90
+        >>> turtle.radians()
+        >>> turtle.heading()
+        1.5707963267948966
+        """
+        self._setDegreesPerAU(2*math.pi)
+
+    def _go(self, distance):
+        """move turtle forward by specified distance"""
+        ende = self._position + self._orient * distance
+        self._goto(ende)
+
+    def _rotate(self, angle):
+        """Turn turtle counterclockwise by specified angle if angle > 0."""
+        angle *= self._degreesPerAU
+        self._orient = self._orient.rotate(angle)
+
+    def _goto(self, end):
+        """move turtle to position end."""
+        self._position = end
+
+    def forward(self, distance):
+        """Move the turtle forward by the specified distance.
+
+        Aliases: forward | fd
+
+        Argument:
+        distance -- a number (integer or float)
+
+        Move the turtle forward by the specified distance, in the direction
+        the turtle is headed.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.position()
+        (0.00, 0.00)
+        >>> turtle.forward(25)
+        >>> turtle.position()
+        (25.00,0.00)
+        >>> turtle.forward(-75)
+        >>> turtle.position()
+        (-50.00,0.00)
+        """
+        self._go(distance)
+
+    def back(self, distance):
+        """Move the turtle backward by distance.
+
+        Aliases: back | backward | bk
+
+        Argument:
+        distance -- a number
+
+        Move the turtle backward by distance ,opposite to the direction the
+        turtle is headed. Do not change the turtle's heading.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.position()
+        (0.00, 0.00)
+        >>> turtle.backward(30)
+        >>> turtle.position()
+        (-30.00, 0.00)
+        """
+        self._go(-distance)
+
+    def right(self, angle):
+        """Turn turtle right by angle units.
+
+        Aliases: right | rt
+
+        Argument:
+        angle -- a number (integer or float)
+
+        Turn turtle right by angle units. (Units are by default degrees,
+        but can be set via the degrees() and radians() functions.)
+        Angle orientation depends on mode. (See this.)
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.heading()
+        22.0
+        >>> turtle.right(45)
+        >>> turtle.heading()
+        337.0
+        """
+        self._rotate(-angle)
+
+    def left(self, angle):
+        """Turn turtle left by angle units.
+
+        Aliases: left | lt
+
+        Argument:
+        angle -- a number (integer or float)
+
+        Turn turtle left by angle units. (Units are by default degrees,
+        but can be set via the degrees() and radians() functions.)
+        Angle orientation depends on mode. (See this.)
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.heading()
+        22.0
+        >>> turtle.left(45)
+        >>> turtle.heading()
+        67.0
+        """
+        self._rotate(angle)
+
+    def pos(self):
+        """Return the turtle's current location (x,y), as a Vec2D-vector.
+
+        Aliases: pos | position
+
+        No arguments.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.pos()
+        (0.00, 240.00)
+        """
+        return self._position
+
+    def xcor(self):
+        """ Return the turtle's x coordinate.
+
+        No arguments.
+
+        Example (for a Turtle instance named turtle):
+        >>> reset()
+        >>> turtle.left(60)
+        >>> turtle.forward(100)
+        >>> print turtle.xcor()
+        50.0
+        """
+        return self._position[0]
+
+    def ycor(self):
+        """ Return the turtle's y coordinate
+        ---
+        No arguments.
+
+        Example (for a Turtle instance named turtle):
+        >>> reset()
+        >>> turtle.left(60)
+        >>> turtle.forward(100)
+        >>> print turtle.ycor()
+        86.6025403784
+        """
+        return self._position[1]
+
+
+    def goto(self, x, y=None):
+        """Move turtle to an absolute position.
+
+        Aliases: setpos | setposition | goto:
+
+        Arguments:
+        x -- a number      or     a pair/vector of numbers
+        y -- a number             None
+
+        call: goto(x, y)         # two coordinates
+        --or: goto((x, y))       # a pair (tuple) of coordinates
+        --or: goto(vec)          # e.g. as returned by pos()
+
+        Move turtle to an absolute position. If the pen is down,
+        a line will be drawn. The turtle's orientation does not change.
+
+        Example (for a Turtle instance named turtle):
+        >>> tp = turtle.pos()
+        >>> tp
+        (0.00, 0.00)
+        >>> turtle.setpos(60,30)
+        >>> turtle.pos()
+        (60.00,30.00)
+        >>> turtle.setpos((20,80))
+        >>> turtle.pos()
+        (20.00,80.00)
+        >>> turtle.setpos(tp)
+        >>> turtle.pos()
+        (0.00,0.00)
+        """
+        if y is None:
+            self._goto(Vec2D(*x))
+        else:
+            self._goto(Vec2D(x, y))
+
+    def home(self):
+        """Move turtle to the origin - coordinates (0,0).
+
+        No arguments.
+
+        Move turtle to the origin - coordinates (0,0) and set it's
+        heading to it's start-orientation (which depends on mode).
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.home()
+        """
+        self.goto(0, 0)
+        self.setheading(0)
+
+    def setx(self, x):
+        """Set the turtle's first coordinate to x
+
+        Argument:
+        x -- a number (integer or float)
+
+        Set the turtle's first coordinate to x, leave second coordinate
+        unchanged.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.position()
+        (0.00, 240.00)
+        >>> turtle.setx(10)
+        >>> turtle.position()
+        (10.00, 240.00)
+        """
+        self._goto(Vec2D(x, self._position[1]))
+
+    def sety(self, y):
+        """Set the turtle's second coordinate to y
+
+        Argument:
+        y -- a number (integer or float)
+
+        Set the turtle's first coordinate to x, second coordinate remains
+        unchanged.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.position()
+        (0.00, 40.00)
+        >>> turtle.sety(-10)
+        >>> turtle.position()
+        (0.00, -10.00)
+        """
+        self._goto(Vec2D(self._position[0], y))
+
+    def distance(self, x, y=None):
+        """Return the distance from the turtle to (x,y) in turtle step units.
+
+        Arguments:
+        x -- a number   or  a pair/vector of numbers   or   a turtle instance
+        y -- a number       None                            None
+
+        call: distance(x, y)         # two coordinates
+        --or: distance((x, y))       # a pair (tuple) of coordinates
+        --or: distance(vec)          # e.g. as returned by pos()
+        --or: distance(mypen)        # where mypen is another turtle
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.pos()
+        (0.00, 0.00)
+        >>> turtle.distance(30,40)
+        50.0
+        >>> pen = Turtle()
+        >>> pen.forward(77)
+        >>> turtle.distance(pen)
+        77.0
+        """
+        if y is not None:
+            pos = Vec2D(x, y)
+        if isinstance(x, Vec2D):
+            pos = x
+        elif isinstance(x, tuple):
+            pos = Vec2D(*x)
+        elif isinstance(x, TNavigator):
+            pos = x._position
+        return abs(pos - self._position)
+
+    def towards(self, x, y=None):
+        """Return the angle of the line from the turtle's position to (x, y).
+
+        Arguments:
+        x -- a number   or  a pair/vector of numbers   or   a turtle instance
+        y -- a number       None                            None
+
+        call: distance(x, y)         # two coordinates
+        --or: distance((x, y))       # a pair (tuple) of coordinates
+        --or: distance(vec)          # e.g. as returned by pos()
+        --or: distance(mypen)        # where mypen is another turtle
+
+        Return the angle, between the line from turtle-position to position
+        specified by x, y and the turtle's start orientation. (Depends on
+        modes - "standard" or "logo")
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.pos()
+        (10.00, 10.00)
+        >>> turtle.towards(0,0)
+        225.0
+        """
+        if y is not None:
+            pos = Vec2D(x, y)
+        if isinstance(x, Vec2D):
+            pos = x
+        elif isinstance(x, tuple):
+            pos = Vec2D(*x)
+        elif isinstance(x, TNavigator):
+            pos = x._position
+        x, y = pos - self._position
+        result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
+        result /= self._degreesPerAU
+        return (self._angleOffset + self._angleOrient*result) % self._fullcircle
+
+    def heading(self):
+        """ Return the turtle's current heading.
+
+        No arguments.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.left(67)
+        >>> turtle.heading()
+        67.0
+        """
+        x, y = self._orient
+        result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
+        result /= self._degreesPerAU
+        return (self._angleOffset + self._angleOrient*result) % self._fullcircle
+
+    def setheading(self, to_angle):
+        """Set the orientation of the turtle to to_angle.
+
+        Aliases:  setheading | seth
+
+        Argument:
+        to_angle -- a number (integer or float)
+
+        Set the orientation of the turtle to to_angle.
+        Here are some common directions in degrees:
+
+         standard - mode:          logo-mode:
+        -------------------|--------------------
+           0 - east                0 - north
+          90 - north              90 - east
+         180 - west              180 - south
+         270 - south             270 - west
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.setheading(90)
+        >>> turtle.heading()
+        90
+        """
+        angle = (to_angle - self.heading())*self._angleOrient
+        full = self._fullcircle
+        angle = (angle+full/2.)%full - full/2.
+        self._rotate(angle)
+
+    def circle(self, radius, extent = None, steps = None):
+        """ Draw a circle with given radius.
+
+        Arguments:
+        radius -- a number
+        extent (optional) -- a number
+        steps (optional) -- an integer
+
+        Draw a circle with given radius. The center is radius units left
+        of the turtle; extent - an angle - determines which part of the
+        circle is drawn. If extent is not given, draw the entire circle.
+        If extent is not a full circle, one endpoint of the arc is the
+        current pen position. Draw the arc in counterclockwise direction
+        if radius is positive, otherwise in clockwise direction. Finally
+        the direction of the turtle is changed by the amount of extent.
+
+        As the circle is approximated by an inscribed regular polygon,
+        steps determines the number of steps to use. If not given,
+        it will be calculated automatically. Maybe used to draw regular
+        polygons.
+
+        call: circle(radius)                  # full circle
+        --or: circle(radius, extent)          # arc
+        --or: circle(radius, extent, steps)
+        --or: circle(radius, steps=6)         # 6-sided polygon
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.circle(50)
+        >>> turtle.circle(120, 180)  # semicircle
+        """
+        if self.undobuffer:
+            self.undobuffer.push(["seq"])
+            self.undobuffer.cumulate = True
+        speed = self.speed()
+        if extent is None:
+            extent = self._fullcircle
+        if steps is None:
+            frac = abs(extent)/self._fullcircle
+            steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
+        w = 1.0 * extent / steps
+        w2 = 0.5 * w
+        l = 2.0 * radius * math.sin(w2*math.pi/180.0*self._degreesPerAU)
+        if radius < 0:
+            l, w, w2 = -l, -w, -w2
+        tr = self.tracer()
+        dl = self._delay()
+        if speed == 0:
+            self.tracer(0, 0)
+        else:
+            self.speed(0)
+        self._rotate(w2)
+        for i in range(steps):
+            self.speed(speed)
+            self._go(l)
+            self.speed(0)
+            self._rotate(w)
+        self._rotate(-w2)
+        if speed == 0:
+            self.tracer(tr, dl)
+        self.speed(speed)
+        if self.undobuffer:
+            self.undobuffer.cumulate = False
+
+## three dummy methods to be implemented by child class:
+
+    def speed(self, s=0):
+        """dummy method - to be overwritten by child class"""
+    def tracer(self, a=None, b=None):
+        """dummy method - to be overwritten by child class"""
+    def _delay(self, n=None):
+        """dummy method - to be overwritten by child class"""
+
+    fd = forward
+    bk = back
+    backward = back
+    rt = right
+    lt = left
+    position = pos
+    setpos = goto
+    setposition = goto
+    seth = setheading
+
+
+class TPen(object):
+    """Drawing part of the RawTurtle.
+    Implements drawing properties.
+    """
+    def __init__(self, resizemode=_CFG["resizemode"]):
+        self._resizemode = resizemode # or "user" or "noresize"
+        self.undobuffer = None
+        TPen._reset(self)
+
+    def _reset(self, pencolor=_CFG["pencolor"],
+                     fillcolor=_CFG["fillcolor"]):
+        self._pensize = 1
+        self._shown = True
+        self._pencolor = pencolor
+        self._fillcolor = fillcolor
+        self._drawing = True
+        self._speed = 3
+        self._stretchfactor = (1, 1)
+        self._tilt = 0
+        self._outlinewidth = 1
+        ### self.screen = None  # to override by child class
+
+    def resizemode(self, rmode=None):
+        """Set resizemode to one of the values: "auto", "user", "noresize".
+
+        (Optional) Argument:
+        rmode -- one of the strings "auto", "user", "noresize"
+
+        Different resizemodes have the following effects:
+          - "auto" adapts the appearance of the turtle
+                   corresponding to the value of pensize.
+          - "user" adapts the appearance of the turtle according to the
+                   values of stretchfactor and outlinewidth (outline),
+                   which are set by shapesize()
+          - "noresize" no adaption of the turtle's appearance takes place.
+        If no argument is given, return current resizemode.
+        resizemode("user") is called by a call of shapesize with arguments.
+
+
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.resizemode("noresize")
+        >>> turtle.resizemode()
+        'noresize'
+        """
+        if rmode is None:
+            return self._resizemode
+        rmode = rmode.lower()
+        if rmode in ["auto", "user", "noresize"]:
+            self.pen(resizemode=rmode)
+
+    def pensize(self, width=None):
+        """Set or return the line thickness.
+
+        Aliases:  pensize | width
+
+        Argument:
+        width -- positive number
+
+        Set the line thickness to width or return it. If resizemode is set
+        to "auto" and turtleshape is a polygon, that polygon is drawn with
+        the same line thickness. If no argument is given, current pensize
+        is returned.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.pensize()
+        1
+        turtle.pensize(10)   # from here on lines of width 10 are drawn
+        """
+        if width is None:
+            return self._pensize
+        self.pen(pensize=width)
+
+
+    def penup(self):
+        """Pull the pen up -- no drawing when moving.
+
+        Aliases: penup | pu | up
+
+        No argument
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.penup()
+        """
+        if not self._drawing:
+            return
+        self.pen(pendown=False)
+
+    def pendown(self):
+        """Pull the pen down -- drawing when moving.
+
+        Aliases: pendown | pd | down
+
+        No argument.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.pendown()
+        """
+        if self._drawing:
+            return
+        self.pen(pendown=True)
+
+    def isdown(self):
+        """Return True if pen is down, False if it's up.
+
+        No argument.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.penup()
+        >>> turtle.isdown()
+        False
+        >>> turtle.pendown()
+        >>> turtle.isdown()
+        True
+        """
+        return self._drawing
+
+    def speed(self, speed=None):
+        """ Return or set the turtle's speed.
+
+        Optional argument:
+        speed -- an integer in the range 0..10 or a speedstring (see below)
+
+        Set the turtle's speed to an integer value in the range 0 .. 10.
+        If no argument is given: return current speed.
+
+        If input is a number greater than 10 or smaller than 0.5,
+        speed is set to 0.
+        Speedstrings  are mapped to speedvalues in the following way:
+            'fastest' :  0
+            'fast'    :  10
+            'normal'  :  6
+            'slow'    :  3
+            'slowest' :  1
+        speeds from 1 to 10 enforce increasingly faster animation of
+        line drawing and turtle turning.
+
+        Attention:
+        speed = 0 : *no* animation takes place. forward/back makes turtle jump
+        and likewise left/right make the turtle turn instantly.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.speed(3)
+        """
+        speeds = {'fastest':0, 'fast':10, 'normal':6, 'slow':3, 'slowest':1 }
+        if speed is None:
+            return self._speed
+        if speed in speeds:
+            speed = speeds[speed]
+        elif 0.5 < speed < 10.5:
+            speed = int(round(speed))
+        else:
+            speed = 0
+        self.pen(speed=speed)
+
+    def color(self, *args):
+        """Return or set the pencolor and fillcolor.
+
+        Arguments:
+        Several input formats are allowed.
+        They use 0, 1, 2, or 3 arguments as follows:
+
+        color()
+            Return the current pencolor and the current fillcolor
+            as a pair of color specification strings as are returned
+            by pencolor and fillcolor.
+        color(colorstring), color((r,g,b)), color(r,g,b)
+            inputs as in pencolor, set both, fillcolor and pencolor,
+            to the given value.
+        color(colorstring1, colorstring2),
+        color((r1,g1,b1), (r2,g2,b2))
+            equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
+            and analogously, if the other input format is used.
+
+        If turtleshape is a polygon, outline and interior of that polygon
+        is drawn with the newly set colors.
+        For mor info see: pencolor, fillcolor
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.color('red', 'green')
+        >>> turtle.color()
+        ('red', 'green')
+        >>> colormode(255)
+        >>> color((40, 80, 120), (160, 200, 240))
+        >>> color()
+        ('#285078', '#a0c8f0')
+        """
+        if args:
+            l = len(args)
+            if l == 1:
+                pcolor = fcolor = args[0]
+            elif l == 2:
+                pcolor, fcolor = args
+            elif l == 3:
+                pcolor = fcolor = args
+            pcolor = self._colorstr(pcolor)
+            fcolor = self._colorstr(fcolor)
+            self.pen(pencolor=pcolor, fillcolor=fcolor)
+        else:
+            return self._color(self._pencolor), self._color(self._fillcolor)
+
+    def pencolor(self, *args):
+        """ Return or set the pencolor.
+
+        Arguments:
+        Four input formats are allowed:
+          - pencolor()
+            Return the current pencolor as color specification string,
+            possibly in hex-number format (see example).
+            May be used as input to another color/pencolor/fillcolor call.
+          - pencolor(colorstring)
+            s is a Tk color specification string, such as "red" or "yellow"
+          - pencolor((r, g, b))
+            *a tuple* of r, g, and b, which represent, an RGB color,
+            and each of r, g, and b are in the range 0..colormode,
+            where colormode is either 1.0 or 255
+          - pencolor(r, g, b)
+            r, g, and b represent an RGB color, and each of r, g, and b
+            are in the range 0..colormode
+
+        If turtleshape is a polygon, the outline of that polygon is drawn
+        with the newly set pencolor.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.pencolor('brown')
+        >>> tup = (0.2, 0.8, 0.55)
+        >>> turtle.pencolor(tup)
+        >>> turtle.pencolor()
+        '#33cc8c'
+        """
+        if args:
+            color = self._colorstr(args)
+            if color == self._pencolor:
+                return
+            self.pen(pencolor=color)
+        else:
+            return self._color(self._pencolor)
+
+    def fillcolor(self, *args):
+        """ Return or set the fillcolor.
+
+        Arguments:
+        Four input formats are allowed:
+          - fillcolor()
+            Return the current fillcolor as color specification string,
+            possibly in hex-number format (see example).
+            May be used as input to another color/pencolor/fillcolor call.
+          - fillcolor(colorstring)
+            s is a Tk color specification string, such as "red" or "yellow"
+          - fillcolor((r, g, b))
+            *a tuple* of r, g, and b, which represent, an RGB color,
+            and each of r, g, and b are in the range 0..colormode,
+            where colormode is either 1.0 or 255
+          - fillcolor(r, g, b)
+            r, g, and b represent an RGB color, and each of r, g, and b
+            are in the range 0..colormode
+
+        If turtleshape is a polygon, the interior of that polygon is drawn
+        with the newly set fillcolor.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.fillcolor('violet')
+        >>> col = turtle.pencolor()
+        >>> turtle.fillcolor(col)
+        >>> turtle.fillcolor(0, .5, 0)
+        """
+        if args:
+            color = self._colorstr(args)
+            if color == self._fillcolor:
+                return
+            self.pen(fillcolor=color)
+        else:
+            return self._color(self._fillcolor)
+
+    def showturtle(self):
+        """Makes the turtle visible.
+
+        Aliases: showturtle | st
 
-from math import * # Also for export
-from time import sleep
-import Tkinter
+        No argument.
 
-speeds = ['fastest', 'fast', 'normal', 'slow', 'slowest']
+        Example (for a Turtle instance named turtle):
+        >>> turtle.hideturtle()
+        >>> turtle.showturtle()
+        """
+        self.pen(shown=True)
+
+    def hideturtle(self):
+        """Makes the turtle invisible.
+
+        Aliases: hideturtle | ht
+
+        No argument.
+
+        It's a good idea to do this while you're in the
+        middle of a complicated drawing, because hiding
+        the turtle speeds up the drawing observably.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.hideturtle()
+        """
+        self.pen(shown=False)
+
+    def isvisible(self):
+        """Return True if the Turtle is shown, False if it's hidden.
+
+        No argument.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.hideturtle()
+        >>> print turtle.isvisible():
+        False
+        """
+        return self._shown
+
+    def pen(self, pen=None, **pendict):
+        """Return or set the pen's attributes.
+
+        Arguments:
+            pen -- a dictionary with some or all of the below listed keys.
+            **pendict -- one or more keyword-arguments with the below
+                         listed keys as keywords.
+
+        Return or set the pen's attributes in a 'pen-dictionary'
+        with the following key/value pairs:
+           "shown"      :   True/False
+           "pendown"    :   True/False
+           "pencolor"   :   color-string or color-tuple
+           "fillcolor"  :   color-string or color-tuple
+           "pensize"    :   positive number
+           "speed"      :   number in range 0..10
+           "resizemode" :   "auto" or "user" or "noresize"
+           "stretchfactor": (positive number, positive number)
+           "outline"    :   positive number
+           "tilt"       :   number
+
+        This dicionary can be used as argument for a subsequent
+        pen()-call to restore the former pen-state. Moreover one
+        or more of these attributes can be provided as keyword-arguments.
+        This can be used to set several pen attributes in one statement.
+
+
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
+        >>> turtle.pen()
+        {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
+        'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
+        'stretchfactor': (1,1), 'speed': 3}
+        >>> penstate=turtle.pen()
+        >>> turtle.color("yellow","")
+        >>> turtle.penup()
+        >>> turtle.pen()
+        {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
+        'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
+        'stretchfactor': (1,1), 'speed': 3}
+        >>> p.pen(penstate, fillcolor="green")
+        >>> p.pen()
+        {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
+        'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
+        'stretchfactor': (1,1), 'speed': 3}
+        """
+        _pd =  {"shown"         : self._shown,
+                "pendown"       : self._drawing,
+                "pencolor"      : self._pencolor,
+                "fillcolor"     : self._fillcolor,
+                "pensize"       : self._pensize,
+                "speed"         : self._speed,
+                "resizemode"    : self._resizemode,
+                "stretchfactor" : self._stretchfactor,
+                "outline"       : self._outlinewidth,
+                "tilt"          : self._tilt
+               }
 
-class Error(Exception):
-    pass
+        if not (pen or pendict):
+            return _pd
 
-class RawPen:
+        if isinstance(pen, dict):
+            p = pen
+        else:
+            p = {}
+        p.update(pendict)
 
-    def __init__(self, canvas):
-        self._canvas = canvas
-        self._items = []
-        self._tracing = 1
-        self._arrow = 0
-        self._delay = 10     # default delay for drawing
-        self._angle = 0.0
-        self.degrees()
-        self.reset()
+        _p_buf = {}
+        for key in p:
+            _p_buf[key] = _pd[key]
+
+        if self.undobuffer:
+            self.undobuffer.push(("pen", _p_buf))
+
+        newLine = False
+        if "pendown" in p:
+            if self._drawing != p["pendown"]:
+                newLine = True
+        if "pencolor" in p:
+            if isinstance(p["pencolor"], tuple):
+                p["pencolor"] = self._colorstr((p["pencolor"],))
+            if self._pencolor != p["pencolor"]:
+                newLine = True
+        if "pensize" in p:
+            if self._pensize != p["pensize"]:
+                newLine = True
+        if newLine:
+            self._newLine()
+        if "pendown" in p:
+            self._drawing = p["pendown"]
+        if "pencolor" in p:
+            self._pencolor = p["pencolor"]
+        if "pensize" in p:
+            self._pensize = p["pensize"]
+        if "fillcolor" in p:
+            if isinstance(p["fillcolor"], tuple):
+                p["fillcolor"] = self._colorstr((p["fillcolor"],))
+            self._fillcolor = p["fillcolor"]
+        if "speed" in p:
+            self._speed = p["speed"]
+        if "resizemode" in p:
+            self._resizemode = p["resizemode"]
+        if "stretchfactor" in p:
+            sf = p["stretchfactor"]
+            if isinstance(sf, (int, float)):
+                sf = (sf, sf)
+            self._stretchfactor = sf
+        if "outline" in p:
+            self._outlinewidth = p["outline"]
+        if "shown" in p:
+            self._shown = p["shown"]
+        if "tilt" in p:
+            self._tilt = p["tilt"]
+        self._update()
+
+## three dummy methods to be implemented by child class:
+
+    def _newLine(self, usePos = True):
+        """dummy method - to be overwritten by child class"""
+    def _update(self, count=True, forced=False):
+        """dummy method - to be overwritten by child class"""
+    def _color(self, args):
+        """dummy method - to be overwritten by child class"""
+    def _colorstr(self, args):
+        """dummy method - to be overwritten by child class"""
+
+    width = pensize
+    up = penup
+    pu = penup
+    pd = pendown
+    down = pendown
+    st = showturtle
+    ht = hideturtle
 
-    def degrees(self, fullcircle=360.0):
-        """ Set angle measurement units to degrees.
 
-        Example:
-        >>> turtle.degrees()
-        """
-        # Don't try to change _angle if it is 0, because
-        # _fullcircle might not be set, yet
-        if self._angle:
-            self._angle = (self._angle / self._fullcircle) * fullcircle
-        self._fullcircle = fullcircle
-        self._invradian = pi / (fullcircle * 0.5)
+class _TurtleImage(object):
+    """Helper class: Datatype to store Turtle attributes
+    """
 
-    def radians(self):
-        """ Set the angle measurement units to radians.
+    def __init__(self, screen, shapeIndex):
+        self.screen = screen
+        self._type = None
+        self._setshape(shapeIndex)
+
+    def _setshape(self, shapeIndex):
+        screen = self.screen # RawTurtle.screens[self.screenIndex]
+        self.shapeIndex = shapeIndex
+        if self._type == "polygon" == screen._shapes[shapeIndex]._type:
+            return
+        if self._type == "image" == screen._shapes[shapeIndex]._type:
+            return
+        if self._type in ["image", "polygon"]:
+            screen._delete(self._item)
+        elif self._type == "compound":
+            for item in self._item:
+                screen._delete(item)
+        self._type = screen._shapes[shapeIndex]._type
+        if self._type == "polygon":
+            self._item = screen._createpoly()
+        elif self._type == "image":
+            self._item = screen._createimage(screen._shapes["blank"]._data)
+        elif self._type == "compound":
+            self._item = [screen._createpoly() for item in
+                                          screen._shapes[shapeIndex]._data]
+
+
+class RawTurtle(TPen, TNavigator):
+    """Animation part of the RawTurtle.
+    Puts RawTurtle upon a TurtleScreen and provides tools for
+    it's animation.
+    """
+    screens = []
 
-        Example:
-        >>> turtle.radians()
-        """
-        self.degrees(2.0*pi)
+    def __init__(self, canvas=None,
+                 shape=_CFG["shape"],
+                 undobuffersize=_CFG["undobuffersize"],
+                 visible=_CFG["visible"]):
+        if isinstance(canvas, Screen):
+            self.screen = canvas
+        elif isinstance(canvas, TurtleScreen):
+            if canvas not in RawTurtle.screens:
+                RawTurtle.screens.append(canvas)
+            self.screen = canvas
+        elif isinstance(canvas, (ScrolledCanvas, Canvas)):
+            for screen in RawTurtle.screens:
+                if screen.cv == canvas:
+                    self.screen = screen
+                    break
+            else:
+                self.screen = TurtleScreen(canvas)
+                RawTurtle.screens.append(self.screen)
+        else:
+            raise TurtleGraphicsError("bad cavas argument %s" % canvas)
+
+        screen = self.screen
+        TNavigator.__init__(self, screen.mode())
+        TPen.__init__(self)
+        screen._turtles.append(self)
+        self.drawingLineItem = screen._createline()
+        self.turtle = _TurtleImage(screen, shape)
+        self._poly = None
+        self._creatingPoly = False
+        self._fillitem = self._fillpath = None
+        self._shown = visible
+        self._hidden_from_screen = False
+        self.currentLineItem = screen._createline()
+        self.currentLine = [self._position]
+        self.items = [self.currentLineItem]
+        self.stampItems = []
+        self._undobuffersize = undobuffersize
+        self.undobuffer = Tbuffer(undobuffersize)
+        self._update()
 
     def reset(self):
-        """ Clear the screen, re-center the pen, and set variables to
-        the default values.
+        """Delete the turtle's drawings and restore it's default values.
 
-        Example:
+        No argument.
+,
+        Delete the turtle's drawings from the screen, re-center the turtle
+        and set variables to the default values.
+
+        Example (for a Turtle instance named turtle):
         >>> turtle.position()
-        [0.0, -22.0]
+        (0.00,-22.00)
         >>> turtle.heading()
         100.0
         >>> turtle.reset()
         >>> turtle.position()
-        [0.0, 0.0]
+        (0.00,0.00)
         >>> turtle.heading()
         0.0
         """
-        canvas = self._canvas
-        self._canvas.update()
-        width = canvas.winfo_width()
-        height = canvas.winfo_height()
-        if width <= 1:
-            width = canvas['width']
-        if height <= 1:
-            height = canvas['height']
-        self._origin = float(width)/2.0, float(height)/2.0
-        self._position = self._origin
-        self._angle = 0.0
-        self._drawing = 1
-        self._width = 1
-        self._color = "black"
-        self._filling = 0
-        self._path = []
-        self.clear()
-        canvas._root().tkraise()
-
-    def clear(self):
-        """ Clear the screen. The turtle does not move.
-
-        Example:
-        >>> turtle.clear()
-        """
-        self.fill(0)
-        canvas = self._canvas
-        items = self._items
-        self._items = []
-        for item in items:
-            canvas.delete(item)
-        self._delete_turtle()
-        self._draw_turtle()
-
-    def tracer(self, flag):
-        """ Set tracing on if flag is True, and off if it is False.
-        Tracing means line are drawn more slowly, with an
-        animation of an arrow along the line.
-
-        Example:
-        >>> turtle.tracer(False)   # turns off Tracer
-        """
-        self._tracing = flag
-        if not self._tracing:
-            self._delete_turtle()
-        self._draw_turtle()
-
-    def forward(self, distance):
-        """ Go forward distance steps.
-
-        Example:
-        >>> turtle.position()
-        [0.0, 0.0]
-        >>> turtle.forward(25)
-        >>> turtle.position()
-        [25.0, 0.0]
-        >>> turtle.forward(-75)
-        >>> turtle.position()
-        [-50.0, 0.0]
-        """
-        x0, y0 = start = self._position
-        x1 = x0 + distance * cos(self._angle*self._invradian)
-        y1 = y0 - distance * sin(self._angle*self._invradian)
-        self._goto(x1, y1)
+        TNavigator.reset(self)
+        TPen._reset(self)
+        self._clear()
+        self._drawturtle()
+        self._update()
+
+    def setundobuffer(self, size):
+        """Set or disable undobuffer.
+
+        Argument:
+        size -- an integer or None
+
+        If size is an integer an empty undobuffer of given size is installed.
+        Size gives the maximum number of turtle-actions that can be undone
+        by the undo() function.
+        If size is None, no undobuffer is present.
 
-    def backward(self, distance):
-        """ Go backwards distance steps.
-
-        The turtle's heading does not change.
-
-        Example:
-        >>> turtle.position()
-        [0.0, 0.0]
-        >>> turtle.backward(30)
-        >>> turtle.position()
-        [-30.0, 0.0]
+        Example (for a Turtle instance named turtle):
+        >>> turtle.setundobuffer(42)
         """
-        self.forward(-distance)
-
-    def left(self, angle):
-        """ Turn left angle units (units are by default degrees,
-        but can be set via the degrees() and radians() functions.)
-
-        When viewed from above, the turning happens in-place around
-        its front tip.
+        if size is None:
+            self.undobuffer = None
+        else:
+            self.undobuffer = Tbuffer(size)
 
-        Example:
-        >>> turtle.heading()
-        22
-        >>> turtle.left(45)
-        >>> turtle.heading()
-        67.0
-        """
-        self._angle = (self._angle + angle) % self._fullcircle
-        self._draw_turtle()
+    def undobufferentries(self):
+        """Return count of entries in the undobuffer.
 
-    def right(self, angle):
-        """ Turn right angle units (units are by default degrees,
-        but can be set via the degrees() and radians() functions.)
+        No argument.
 
-        When viewed from above, the turning happens in-place around
-        its front tip.
+        Example (for a Turtle instance named turtle):
+        >>> while undobufferentries():
+                undo()
+        """
+        if self.undobuffer is None:
+            return 0
+        return self.undobuffer.nr_of_items()
+
+    def _clear(self):
+        """Delete all of pen's drawings"""
+        self._fillitem = self._fillpath = None
+        for item in self.items:
+            self.screen._delete(item)
+        self.currentLineItem = self.screen._createline()
+        self.currentLine = []
+        if self._drawing:
+            self.currentLine.append(self._position)
+        self.items = [self.currentLineItem]
+        self.clearstamps()
+        self.setundobuffer(self._undobuffersize)
 
-        Example:
-        >>> turtle.heading()
-        22
-        >>> turtle.right(45)
-        >>> turtle.heading()
-        337.0
-        """
-        self.left(-angle)
 
-    def up(self):
-        """ Pull the pen up -- no drawing when moving.
+    def clear(self):
+        """Delete the turtle's drawings from the screen. Do not move turtle.
 
-        Example:
-        >>> turtle.up()
-        """
-        self._drawing = 0
+        No arguments.
 
-    def down(self):
-        """ Put the pen down -- draw when moving.
+        Delete the turtle's drawings from the screen. Do not move turtle.
+        State and position of the turtle as well as drawings of other
+        turtles are not affected.
 
-        Example:
-        >>> turtle.down()
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.clear()
         """
-        self._drawing = 1
+        self._clear()
+        self._update()
 
-    def width(self, width):
-        """ Set the line to thickness to width.
+    def _update_data(self):
+        self.screen._incrementudc()
+        if self.screen._updatecounter != 0:
+            return
+        if len(self.currentLine)>1:
+            self.screen._drawline(self.currentLineItem, self.currentLine,
+                                  self._pencolor, self._pensize)
 
-        Example:
-        >>> turtle.width(10)
+    def _update(self):
+        """Perform a Turtle-data update.
         """
-        self._width = float(width)
-
-    def color(self, *args):
-        """ Set the pen color.
-
-        Three input formats are allowed:
-
-            color(s)
-            s is a Tk specification string, such as "red" or "yellow"
-
-            color((r, g, b))
-            *a tuple* of r, g, and b, which represent, an RGB color,
-            and each of r, g, and b are in the range [0..1]
-
-            color(r, g, b)
-            r, g, and b represent an RGB color, and each of r, g, and b
-            are in the range [0..1]
+        screen = self.screen
+        if screen._tracing == 0:
+            return
+        elif screen._tracing == 1:
+            self._update_data()
+            self._drawturtle()
+            screen._update()                  # TurtleScreenBase
+            screen._delay(screen._delayvalue) # TurtleScreenBase
+        else:
+            self._update_data()
+            if screen._updatecounter == 0:
+                for t in screen.turtles():
+                    t._drawturtle()
+                screen._update()
+
+    def tracer(self, flag=None, delay=None):
+        """Turns turtle animation on/off and set delay for update drawings.
+
+        Optional arguments:
+        n -- nonnegative  integer
+        delay -- nonnegative  integer
+
+        If n is given, only each n-th regular screen update is really performed.
+        (Can be used to accelerate the drawing of complex graphics.)
+        Second arguments sets delay value (see RawTurtle.delay())
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.tracer(8, 25)
+        >>> dist = 2
+        >>> for i in range(200):
+                turtle.fd(dist)
+                turtle.rt(90)
+                dist += 2
+        """
+        return self.screen.tracer(flag, delay)
+
+    def _color(self, args):
+        return self.screen._color(args)
 
-        Example:
+    def _colorstr(self, args):
+        return self.screen._colorstr(args)
 
-        >>> turtle.color('brown')
-        >>> tup = (0.2, 0.8, 0.55)
-        >>> turtle.color(tup)
-        >>> turtle.color(0, .5, 0)
+    def _cc(self, args):
+        """Convert colortriples to hexstrings.
         """
-        if not args:
-            raise Error, "no color arguments"
-        if len(args) == 1:
-            color = args[0]
-            if type(color) == type(""):
-                # Test the color first
-                try:
-                    id = self._canvas.create_line(0, 0, 0, 0, fill=color)
-                except Tkinter.TclError:
-                    raise Error, "bad color string: %r" % (color,)
-                self._set_color(color)
+        if isinstance(args, str):
+            return args
+        try:
+            r, g, b = args
+        except:
+            raise TurtleGraphicsError("bad color arguments: %s" % str(args))
+        if self.screen._colormode == 1.0:
+            r, g, b = [round(255.0*x) for x in (r, g, b)]
+        if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
+            raise TurtleGraphicsError("bad color sequence: %s" % str(args))
+        return "#%02x%02x%02x" % (r, g, b)
+
+    def clone(self):
+        """Create and return a clone of the turtle.
+
+        No argument.
+
+        Create and return a clone of the turtle with same position, heading
+        and turtle properties.
+
+        Example (for a Turtle instance named mick):
+        mick = Turtle()
+        joe = mick.clone()
+        """
+        screen = self.screen
+        self._newLine(self._drawing)
+
+        turtle = self.turtle
+        self.screen = None
+        self.turtle = None  # too make self deepcopy-able
+
+        q = deepcopy(self)
+
+        self.screen = screen
+        self.turtle = turtle
+
+        q.screen = screen
+        q.turtle = _TurtleImage(screen, self.turtle.shapeIndex)
+
+        screen._turtles.append(q)
+        ttype = screen._shapes[self.turtle.shapeIndex]._type
+        if ttype == "polygon":
+            q.turtle._item = screen._createpoly()
+        elif ttype == "image":
+            q.turtle._item = screen._createimage(screen._shapes["blank"]._data)
+        elif ttype == "compound":
+            q.turtle._item = [screen._createpoly() for item in
+                              screen._shapes[self.turtle.shapeIndex]._data]
+        q.currentLineItem = screen._createline()
+        q._update()
+        return q
+
+    def shape(self, name=None):
+        """Set turtle shape to shape with given name / return current shapename.
+
+        Optional argument:
+        name -- a string, which is a valid shapename
+
+        Set turtle shape to shape with given name or, if name is not given,
+        return name of current shape.
+        Shape with name must exist in the TurtleScreen's shape dictionary.
+        Initially there are the following polygon shapes:
+        'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
+        To learn about how to deal with shapes see Screen-method register_shape.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.shape()
+        'arrow'
+        >>> turtle.shape("turtle")
+        >>> turtle.shape()
+        'turtle'
+        """
+        if name is None:
+            return self.turtle.shapeIndex
+        if not name in self.screen.getshapes():
+            raise TurtleGraphicsError("There is no shape named %s" % name)
+        self.turtle._setshape(name)
+        self._update()
+
+    def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
+        """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
+
+        Optinonal arguments:
+           stretch_wid : positive number
+           stretch_len : positive number
+           outline  : positive number
+
+        Return or set the pen's attributes x/y-stretchfactors and/or outline.
+        Set resizemode to "user".
+        If and only if resizemode is set to "user", the turtle will be displayed
+        stretched according to its stretchfactors:
+        stretch_wid is stretchfactor perpendicular to orientation
+        stretch_len is stretchfactor in direction of turtles orientation.
+        outline determines the width of the shapes's outline.
+
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.resizemode("user")
+        >>> turtle.shapesize(5, 5, 12)
+        >>> turtle.shapesize(outline=8)
+        """
+        if stretch_wid is None and stretch_len is None and outline == None:
+            stretch_wid, stretch_len = self._stretchfactor
+            return stretch_wid, stretch_len, self._outlinewidth
+        if stretch_wid is not None:
+            if stretch_len is None:
+                stretchfactor = stretch_wid, stretch_wid
+            else:
+                stretchfactor = stretch_wid, stretch_len
+        elif stretch_len is not None:
+            stretchfactor = self._stretchfactor[0], stretch_len
+        else:
+            stretchfactor = self._stretchfactor
+        if outline is None:
+            outline = self._outlinewidth
+        self.pen(resizemode="user",
+                 stretchfactor=stretchfactor, outline=outline)
+
+    def settiltangle(self, angle):
+        """Rotate the turtleshape to point in the specified direction
+
+        Optional argument:
+        angle -- number
+
+        Rotate the turtleshape to point in the direction specified by angle,
+        regardless of its current tilt-angle. DO NOT change the turtle's
+        heading (direction of movement).
+
+
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.shape("circle")
+        >>> turtle.shapesize(5,2)
+        >>> turtle.settiltangle(45)
+        >>> stamp()
+        >>> turtle.fd(50)
+        >>> turtle.settiltangle(-45)
+        >>> stamp()
+        >>> turtle.fd(50)
+        """
+        tilt = -angle * self._degreesPerAU * self._angleOrient
+        tilt = (tilt * math.pi / 180.0) % (2*math.pi)
+        self.pen(resizemode="user", tilt=tilt)
+
+    def tiltangle(self):
+        """Return the current tilt-angle.
+
+        No argument.
+
+        Return the current tilt-angle, i. e. the angle between the
+        orientation of the turtleshape and the heading of the turtle
+        (it's direction of movement).
+
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.shape("circle")
+        >>> turtle.shapesize(5,2)
+        >>> turtle.tilt(45)
+        >>> turtle.tiltangle()
+        >>>
+        """
+        tilt = -self._tilt * (180.0/math.pi) * self._angleOrient
+        return (tilt / self._degreesPerAU) % self._fullcircle
+
+    def tilt(self, angle):
+        """Rotate the turtleshape by angle.
+
+        Argument:
+        angle - a number
+
+        Rotate the turtleshape by angle from its current tilt-angle,
+        but do NOT change the turtle's heading (direction of movement).
+
+        Examples (for a Turtle instance named turtle):
+        >>> turtle.shape("circle")
+        >>> turtle.shapesize(5,2)
+        >>> turtle.tilt(30)
+        >>> turtle.fd(50)
+        >>> turtle.tilt(30)
+        >>> turtle.fd(50)
+        """
+        self.settiltangle(angle + self.tiltangle())
+
+    def _polytrafo(self, poly):
+        """Computes transformed polygon shapes from a shape
+        according to current position and heading.
+        """
+        screen = self.screen
+        p0, p1 = self._position
+        e0, e1 = self._orient
+        e = Vec2D(e0, e1 * screen.yscale / screen.xscale)
+        e0, e1 = (1.0 / abs(e)) * e
+        return [(p0+(e1*x+e0*y)/screen.xscale, p1+(-e0*x+e1*y)/screen.yscale)
+                                                           for (x, y) in poly]
+
+    def _drawturtle(self):
+        """Manages the correct rendering of the turtle with respect to
+        it's shape, resizemode, strech and tilt etc."""
+        screen = self.screen
+        shape = screen._shapes[self.turtle.shapeIndex]
+        ttype = shape._type
+        titem = self.turtle._item
+        if self._shown and screen._updatecounter == 0 and screen._tracing > 0:
+            self._hidden_from_screen = False
+            tshape = shape._data
+            if ttype == "polygon":
+                if self._resizemode == "noresize":
+                    w = 1
+                    shape = tshape
+                else:
+                    if self._resizemode == "auto":
+                        lx = ly = max(1, self._pensize/5.0)
+                        w = self._pensize
+                        tiltangle = 0
+                    elif self._resizemode == "user":
+                        lx, ly = self._stretchfactor
+                        w = self._outlinewidth
+                        tiltangle = self._tilt
+                    shape = [(lx*x, ly*y) for (x, y) in tshape]
+                    t0, t1 = math.sin(tiltangle), math.cos(tiltangle)
+                    shape = [(t1*x+t0*y, -t0*x+t1*y) for (x, y) in shape]
+                shape = self._polytrafo(shape)
+                fc, oc = self._fillcolor, self._pencolor
+                screen._drawpoly(titem, shape, fill=fc, outline=oc,
+                                                      width=w, top=True)
+            elif ttype == "image":
+                screen._drawimage(titem, self._position, tshape)
+            elif ttype == "compound":
+                lx, ly = self._stretchfactor
+                w = self._outlinewidth
+                for item, (poly, fc, oc) in zip(titem, tshape):
+                    poly = [(lx*x, ly*y) for (x, y) in poly]
+                    poly = self._polytrafo(poly)
+                    screen._drawpoly(item, poly, fill=self._cc(fc),
+                                     outline=self._cc(oc), width=w, top=True)
+        else:
+            if self._hidden_from_screen:
                 return
-            try:
-                r, g, b = color
-            except:
-                raise Error, "bad color sequence: %r" % (color,)
+            if ttype == "polygon":
+                screen._drawpoly(titem, ((0, 0), (0, 0), (0, 0)), "", "")
+            elif ttype == "image":
+                screen._drawimage(titem, self._position,
+                                          screen._shapes["blank"]._data)
+            elif ttype == "compound":
+                for item in titem:
+                    screen._drawpoly(item, ((0, 0), (0, 0), (0, 0)), "", "")
+            self._hidden_from_screen = True
+
+##############################  stamp stuff  ###############################
+
+    def stamp(self):
+        """Stamp a copy of the turtleshape onto the canvas and return it's id.
+
+        No argument.
+
+        Stamp a copy of the turtle shape onto the canvas at the current
+        turtle position. Return a stamp_id for that stamp, which can be
+        used to delete it by calling clearstamp(stamp_id).
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.color("blue")
+        >>> turtle.stamp()
+        13
+        >>> turtle.fd(50)
+        """
+        screen = self.screen
+        shape = screen._shapes[self.turtle.shapeIndex]
+        ttype = shape._type
+        tshape = shape._data
+        if ttype == "polygon":
+            stitem = screen._createpoly()
+            if self._resizemode == "noresize":
+                w = 1
+                shape = tshape
+            else:
+                if self._resizemode == "auto":
+                    lx = ly = max(1, self._pensize/5.0)
+                    w = self._pensize
+                    tiltangle = 0
+                elif self._resizemode == "user":
+                    lx, ly = self._stretchfactor
+                    w = self._outlinewidth
+                    tiltangle = self._tilt
+                shape = [(lx*x, ly*y) for (x, y) in tshape]
+                t0, t1 = math.sin(tiltangle), math.cos(tiltangle)
+                shape = [(t1*x+t0*y, -t0*x+t1*y) for (x, y) in shape]
+            shape = self._polytrafo(shape)
+            fc, oc = self._fillcolor, self._pencolor
+            screen._drawpoly(stitem, shape, fill=fc, outline=oc,
+                                                  width=w, top=True)
+        elif ttype == "image":
+            stitem = screen._createimage("")
+            screen._drawimage(stitem, self._position, tshape)
+        elif ttype == "compound":
+            stitem = []
+            for element in tshape:
+                item = screen._createpoly()
+                stitem.append(item)
+            stitem = tuple(stitem)
+            lx, ly = self._stretchfactor
+            w = self._outlinewidth
+            for item, (poly, fc, oc) in zip(stitem, tshape):
+                poly = [(lx*x, ly*y) for (x, y) in poly]
+                poly = self._polytrafo(poly)
+                screen._drawpoly(item, poly, fill=self._cc(fc),
+                                 outline=self._cc(oc), width=w, top=True)
+        self.stampItems.append(stitem)
+        self.undobuffer.push(("stamp", stitem))
+        return stitem
+
+    def _clearstamp(self, stampid):
+        """does the work for clearstamp() and clearstamps()
+        """
+        if stampid in self.stampItems:
+            if isinstance(stampid, tuple):
+                for subitem in stampid:
+                    self.screen._delete(subitem)
+            else:
+                self.screen._delete(stampid)
+            self.stampItems.remove(stampid)
+        # Delete stampitem from undobuffer if necessary
+        # if clearstamp is called directly.
+        item = ("stamp", stampid)
+        buf = self.undobuffer
+        if item not in buf.buffer:
+            return
+        index = buf.buffer.index(item)
+        buf.buffer.remove(item)
+        if index <= buf.ptr:
+            buf.ptr = (buf.ptr - 1) % buf.bufsize
+        buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None])
+
+    def clearstamp(self, stampid):
+        """Delete stamp with given stampid
+
+        Argument:
+        stampid - an integer, must be return value of previous stamp() call.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.color("blue")
+        >>> astamp = turtle.stamp()
+        >>> turtle.fd(50)
+        >>> turtle.clearstamp(astamp)
+        """
+        self._clearstamp(stampid)
+        self._update()
+
+    def clearstamps(self, n=None):
+        """Delete all or first/last n of turtle's stamps.
+
+        Optional argument:
+        n -- an integer
+
+        If n is None, delete all of pen's stamps,
+        else if n > 0 delete first n stamps
+        else if n < 0 delete last n stamps.
+
+        Example (for a Turtle instance named turtle):
+        >>> for i in range(8):
+                turtle.stamp(); turtle.fd(30)
+        ...
+        >>> turtle.clearstamps(2)
+        >>> turtle.clearstamps(-2)
+        >>> turtle.clearstamps()
+        """
+        if n is None:
+            toDelete = self.stampItems[:]
+        elif n >= 0:
+            toDelete = self.stampItems[:n]
         else:
-            try:
-                r, g, b = args
-            except:
-                raise Error, "bad color arguments: %r" % (args,)
-        assert 0 <= r <= 1
-        assert 0 <= g <= 1
-        assert 0 <= b <= 1
-        x = 255.0
-        y = 0.5
-        self._set_color("#%02x%02x%02x" % (int(r*x+y), int(g*x+y), int(b*x+y)))
-
-    def _set_color(self,color):
-        self._color = color
-        self._draw_turtle()
+            toDelete = self.stampItems[n:]
+        for item in toDelete:
+            self._clearstamp(item)
+        self._update()
+
+    def _goto(self, end):
+        """Move the pen to the point end, thereby drawing a line
+        if pen is down. All other methodes for turtle movement depend
+        on this one.
+        """
+        ## Version mit undo-stuff
+        go_modes = ( self._drawing,
+                     self._pencolor,
+                     self._pensize,
+                     isinstance(self._fillpath, list))
+        screen = self.screen
+        undo_entry = ("go", self._position, end, go_modes,
+                      (self.currentLineItem,
+                      self.currentLine[:],
+                      screen._pointlist(self.currentLineItem),
+                      self.items[:])
+                      )
+        if self.undobuffer:
+            self.undobuffer.push(undo_entry)
+        start = self._position
+        if self._speed and screen._tracing == 1:
+            diff = (end-start)
+            diffsq = (diff[0]*screen.xscale)**2 + (diff[1]*screen.yscale)**2
+            nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
+            delta = diff * (1.0/nhops)
+            for n in range(1, nhops):
+                if n == 1:
+                    top = True
+                else:
+                    top = False
+                self._position = start + delta * n
+                if self._drawing:
+                    screen._drawline(self.drawingLineItem,
+                                     (start, self._position),
+                                     self._pencolor, self._pensize, top)
+                self._update()
+            if self._drawing:
+                screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)),
+                                               fill="", width=self._pensize)
+        # Turtle now at end,
+        if self._drawing: # now update currentLine
+            self.currentLine.append(end)
+        if isinstance(self._fillpath, list):
+            self._fillpath.append(end)
+        ######    vererbung!!!!!!!!!!!!!!!!!!!!!!
+        self._position = end
+        if self._creatingPoly:
+            self._poly.append(end)
+        if len(self.currentLine) > 42: # 42! answer to the ultimate question
+                                       # of life, the universe and everything
+            self._newLine()
+        self._update() #count=True)
+
+    def _undogoto(self, entry):
+        """Reverse a _goto. Used for undo()
+        """
+        old, new, go_modes, coodata = entry
+        drawing, pc, ps, filling = go_modes
+        cLI, cL, pl, items = coodata
+        screen = self.screen
+        if abs(self._position - new) > 0.5:
+            print "undogoto: HALLO-DA-STIMMT-WAS-NICHT!"
+        # restore former situation
+        self.currentLineItem = cLI
+        self.currentLine = cL
 
-    def write(self, text, move=False):
-        """ Write text at the current pen position.
-
-        If move is true, the pen is moved to the bottom-right corner
-        of the text. By default, move is False.
+        if pl == [(0, 0), (0, 0)]:
+            usepc = ""
+        else:
+            usepc = pc
+        screen._drawline(cLI, pl, fill=usepc, width=ps)
 
-        Example:
-        >>> turtle.write('The race is on!')
-        >>> turtle.write('Home = (0, 0)', True)
-        """
-        x, y  = self._position
-        x = x-1 # correction -- calibrated for Windows
-        item = self._canvas.create_text(x, y,
-                                        text=str(text), anchor="sw",
-                                        fill=self._color)
-        self._items.append(item)
-        if move:
-            x0, y0, x1, y1 = self._canvas.bbox(item)
-            self._goto(x1, y1)
-        self._draw_turtle()
-
-    def fill(self, flag):
-        """ Call fill(1) before drawing the shape you
-         want to fill, and fill(0) when done.
+        todelete = [i for i in self.items if (i not in items) and
+                                       (screen._type(i) == "line")]
+        for i in todelete:
+            screen._delete(i)
+            self.items.remove(i)
+
+        start = old
+        if self._speed and screen._tracing == 1:
+            diff = old - new
+            diffsq = (diff[0]*screen.xscale)**2 + (diff[1]*screen.yscale)**2
+            nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
+            delta = diff * (1.0/nhops)
+            for n in range(1, nhops):
+                if n == 1:
+                    top = True
+                else:
+                    top = False
+                self._position = new + delta * n
+                if drawing:
+                    screen._drawline(self.drawingLineItem,
+                                     (start, self._position),
+                                     pc, ps, top)
+                self._update()
+            if drawing:
+                screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)),
+                                               fill="", width=ps)
+        # Turtle now at position old,
+        self._position = old
+        ##  if undo is done during crating a polygon, the last vertex
+        ##  will be deleted. if the polygon is entirel deleted,
+        ##  creatigPoly will be set to False.
+        ##  Polygons created before the last one will not be affected by undo()
+        if self._creatingPoly:
+            if len(self._poly) > 0:
+                self._poly.pop()
+            if self._poly == []:
+                self._creatingPoly = False
+                self._poly = None
+        if filling:
+            if self._fillpath == []:
+                self._fillpath = None
+                print "Unwahrscheinlich in _undogoto!"
+            elif self._fillpath is not None:
+                self._fillpath.pop()
+        self._update() #count=True)
+
+    def _rotate(self, angle):
+        """Turns pen clockwise by angle.
+        """
+        if self.undobuffer:
+            self.undobuffer.push(("rot", angle, self._degreesPerAU))
+        angle *= self._degreesPerAU
+        neworient = self._orient.rotate(angle)
+        tracing = self.screen._tracing
+        if tracing == 1 and self._speed > 0:
+            anglevel = 3.0 * self._speed
+            steps = 1 + int(abs(angle)/anglevel)
+            delta = 1.0*angle/steps
+            for _ in range(steps):
+                self._orient = self._orient.rotate(delta)
+                self._update()
+        self._orient = neworient
+        self._update()
+
+    def _newLine(self, usePos=True):
+        """Closes current line item and starts a new one.
+           Remark: if current line became too long, animation
+           performance (via _drawline) slowed down considerably.
+        """
+        if len(self.currentLine) > 1:
+            self.screen._drawline(self.currentLineItem, self.currentLine,
+                                      self._pencolor, self._pensize)
+            self.currentLineItem = self.screen._createline()
+            self.items.append(self.currentLineItem)
+        else:
+            self.screen._drawline(self.currentLineItem, top=True)
+        self.currentLine = []
+        if usePos:
+            self.currentLine = [self._position]
+
+    def fill(self, flag=None):
+        """Call fill(True) before drawing a shape to fill, fill(False) when done.
+
+        Optional argument:
+        flag -- True/False (or 1/0 respectively)
+
+        Call fill(True) before drawing the shape you want to fill,
+        and  fill(False) when done.
+        When used without argument: return fillstate (True if filling,
+        False else)
 
-        Example:
-        >>> turtle.fill(1)
+        Example (for a Turtle instance named turtle):
+        >>> turtle.fill(True)
         >>> turtle.forward(100)
         >>> turtle.left(90)
         >>> turtle.forward(100)
@@ -296,27 +3144,43 @@
         >>> turtle.forward(100)
         >>> turtle.left(90)
         >>> turtle.forward(100)
-        >>> turtle.fill(0)
+        >>> turtle.fill(False)
         """
-        if self._filling:
-            path = tuple(self._path)
-            smooth = self._filling < 0
-            if len(path) > 2:
-                item = self._canvas._create('polygon', path,
-                                            {'fill': self._color,
-                                             'smooth': smooth})
-                self._items.append(item)
-        self._path = []
-        self._filling = flag
+        filling = isinstance(self._fillpath, list)
+        if flag is None:
+            return filling
+        screen = self.screen
+        entry1 = entry2 = ()
+        if filling:
+            if len(self._fillpath) > 2:
+                self.screen._drawpoly(self._fillitem, self._fillpath,
+                                      fill=self._fillcolor)
+                entry1 = ("dofill", self._fillitem)
         if flag:
-            self._path.append(self._position)
+            self._fillitem = self.screen._createpoly()
+            self.items.append(self._fillitem)
+            self._fillpath = [self._position]
+            entry2 = ("beginfill", self._fillitem) # , self._fillpath)
+            self._newLine()
+        else:
+            self._fillitem = self._fillpath = None
+        if self.undobuffer:
+            if entry1 == ():
+                if entry2 != ():
+                    self.undobuffer.push(entry2)
+            else:
+                if entry2 == ():
+                    self.undobuffer.push(entry1)
+                else:
+                    self.undobuffer.push(["seq", entry1, entry2])
+        self._update()
 
     def begin_fill(self):
-        """ Called just before drawing a shape to be filled.
-            Must eventually be followed by a corresponding end_fill() call.
-            Otherwise it will be ignored.
+        """Called just before drawing a shape to be filled.
 
-        Example:
+        No argument.
+
+        Example (for a Turtle instance named turtle):
         >>> turtle.begin_fill()
         >>> turtle.forward(100)
         >>> turtle.left(90)
@@ -327,13 +3191,14 @@
         >>> turtle.forward(100)
         >>> turtle.end_fill()
         """
-        self._path = [self._position]
-        self._filling = 1
+        self.fill(True)
 
     def end_fill(self):
-        """ Called after drawing a shape to be filled.
+        """Fill the shape drawn after the call begin_fill().
 
-        Example:
+        No argument.
+
+        Example (for a Turtle instance named turtle):
         >>> turtle.begin_fill()
         >>> turtle.forward(100)
         >>> turtle.left(90)
@@ -344,613 +3209,820 @@
         >>> turtle.forward(100)
         >>> turtle.end_fill()
         """
-        self.fill(0)
+        self.fill(False)
 
-    def circle(self, radius, extent = None):
-        """ Draw a circle with given radius.
-        The center is radius units left of the turtle; extent
-        determines which part of the circle is drawn. If not given,
-        the entire circle is drawn.
+    def dot(self, size=None, *color):
+        """Draw a dot with diameter size, using color.
 
-        If extent is not a full circle, one endpoint of the arc is the
-        current pen position. The arc is drawn in a counter clockwise
-        direction if radius is positive, otherwise in a clockwise
-        direction. In the process, the direction of the turtle is
-        changed by the amount of the extent.
+        Optional argumentS:
+        size -- an integer >= 1 (if given)
+        color -- a colorstring or a numeric color tuple
+
+        Draw a circular dot with diameter size, using color.
+        If size is not given, the maximum of pensize+4 and 2*pensize is used.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.dot()
+        >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
+        """
+        #print "dot-1:", size, color
+        if not color:
+            if isinstance(size, (str, tuple)):
+                color = self._colorstr(size)
+                size = self._pensize + max(self._pensize, 4)
+            else:
+                color = self._pencolor
+                if not size:
+                    size = self._pensize + max(self._pensize, 4)
+        else:
+            if size is None:
+                size = self._pensize + max(self._pensize, 4)
+            color = self._colorstr(color)
+        #print "dot-2:", size, color
+        if hasattr(self.screen, "_dot"):
+            item = self.screen._dot(self._position, size, color)
+            #print "dot:", size, color, "item:", item
+            self.items.append(item)
+            if self.undobuffer:
+                self.undobuffer.push(("dot", item))
+        else:
+            pen = self.pen()
+            if self.undobuffer:
+                self.undobuffer.push(["seq"])
+                self.undobuffer.cumulate = True
+            try:
+                if self.resizemode() == 'auto':
+                    self.ht()
+                self.pendown()
+                self.pensize(size)
+                self.pencolor(color)
+                self.forward(0)
+            finally:
+                self.pen(pen)
+            if self.undobuffer:
+                self.undobuffer.cumulate = False
+
+    def _write(self, txt, align, font):
+        """Performs the writing for write()
+        """
+        item, end = self.screen._write(self._position, txt, align, font,
+                                                          self._pencolor)
+        self.items.append(item)
+        if self.undobuffer:
+            self.undobuffer.push(("wri", item))
+        return end
+
+    def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
+        """Write text at the current turtle position.
+
+        Arguments:
+        arg -- info, which is to be written to the TurtleScreen
+        move (optional) -- True/False
+        align (optional) -- one of the strings "left", "center" or right"
+        font (optional) -- a triple (fontname, fontsize, fonttype)
+
+        Write text - the string representation of arg - at the current
+        turtle position according to align ("left", "center" or right")
+        and with the given font.
+        If move is True, the pen is moved to the bottom-right corner
+        of the text. By default, move is False.
 
-        >>> turtle.circle(50)
-        >>> turtle.circle(120, 180)  # half a circle
+        Example (for a Turtle instance named turtle):
+        >>> turtle.write('Home = ', True, align="center")
+        >>> turtle.write((0,0), True)
+        """
+        if self.undobuffer:
+            self.undobuffer.push(["seq"])
+            self.undobuffer.cumulate = True
+        end = self._write(str(arg), align.lower(), font)
+        if move:
+            x, y = self.pos()
+            self.setpos(end, y)
+        if self.undobuffer:
+            self.undobuffer.cumulate = False
+
+    def begin_poly(self):
+        """Start recording the vertices of a polygon.
+
+        No argument.
+
+        Start recording the vertices of a polygon. Current turtle position
+        is first point of polygon.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.begin_poly()
         """
-        if extent is None:
-            extent = self._fullcircle
-        frac = abs(extent)/self._fullcircle
-        steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
-        w = 1.0 * extent / steps
-        w2 = 0.5 * w
-        l = 2.0 * radius * sin(w2*self._invradian)
-        if radius < 0:
-            l, w, w2 = -l, -w, -w2
-        self.left(w2)
-        for i in range(steps):
-            self.forward(l)
-            self.left(w)
-        self.right(w2)
+        self._poly = [self._position]
+        self._creatingPoly = True
 
-    def heading(self):
-        """ Return the turtle's current heading.
+    def end_poly(self):
+        """Stop recording the vertices of a polygon.
 
-        Example:
-        >>> turtle.heading()
-        67.0
+        No argument.
+
+        Stop recording the vertices of a polygon. Current turtle position is
+        last point of polygon. This will be connected with the first point.
+
+        Example (for a Turtle instance named turtle):
+        >>> turtle.end_poly()
         """
-        return self._angle
+        self._creatingPoly = False
 
-    def setheading(self, angle):
-        """ Set the turtle facing the given angle.
+    def get_poly(self):
+        """Return the lastly recorded polygon.
 
-        Here are some common directions in degrees:
+        No argument.
+
+        Example (for a Turtle instance named turtle):
+        >>> p = turtle.get_poly()
+        >>> turtle.register_shape("myFavouriteShape", p)
+        """
+        ## check if there is any poly?  -- 1st solution:
+        if self._poly is not None:
+            return tuple(self._poly)
+
+    def getscreen(self):
+        """Return the TurtleScreen object, the turtle is drawing  on.
+
+        No argument.
 
-           0 - east
-          90 - north
-         180 - west
-         270 - south
+        Return the TurtleScreen object, the turtle is drawing  on.
+        So TurtleScreen-methods can be called for that object.
+
+        Example (for a Turtle instance named turtle):
+        >>> ts = turtle.getscreen()
+        >>> ts
+        <turtle.TurtleScreen object at 0x0106B770>
+        >>> ts.bgcolor("pink")
+        """
+        return self.screen
+
+    def getturtle(self):
+        """Return the Turtleobject itself.
+
+        No argument.
+
+        Only reasonable use: as a function to return the 'anonymous turtle':
 
         Example:
-        >>> turtle.setheading(90)
-        >>> turtle.heading()
-        90
-        >>> turtle.setheading(128)
-        >>> turtle.heading()
-        128
+        >>> pet = getturtle()
+        >>> pet.fd(50)
+        >>> pet
+        <turtle.Turtle object at 0x0187D810>
+        >>> turtles()
+        [<turtle.Turtle object at 0x0187D810>]
         """
-        self._angle = angle
-        self._draw_turtle()
+        return self
+
+    getpen = getturtle
+
+
+    ################################################################
+    ### screen oriented methods recurring to methods of TurtleScreen
+    ################################################################
 
     def window_width(self):
         """ Returns the width of the turtle window.
 
-        Example:
-        >>> turtle.window_width()
+        No argument.
+
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.window_width()
         640
         """
-        width = self._canvas.winfo_width()
-        if width <= 1:  # the window isn't managed by a geometry manager
-            width = self._canvas['width']
-        return width
+        return self.screen._window_size()[0]
 
     def window_height(self):
         """ Return the height of the turtle window.
 
-        Example:
-        >>> turtle.window_height()
-        768
-        """
-        height = self._canvas.winfo_height()
-        if height <= 1: # the window isn't managed by a geometry manager
-            height = self._canvas['height']
-        return height
+        No argument.
 
-    def position(self):
-        """ Return the current (x, y) location of the turtle.
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.window_height()
+        480
+        """
+        return self.screen._window_size()[1]
 
-        Example:
-        >>> turtle.position()
-        [0.0, 240.0]
+    def _delay(self, delay=None):
+        """Set delay value which determines speed of turtle animation.
         """
-        x0, y0 = self._origin
-        x1, y1 = self._position
-        return [x1-x0, -y1+y0]
+        return self.screen.delay(delay)
 
-    def setx(self, xpos):
-        """ Set the turtle's x coordinate to be xpos.
+    #####   event binding methods   #####
 
-        Example:
-        >>> turtle.position()
-        [10.0, 240.0]
-        >>> turtle.setx(10)
-        >>> turtle.position()
-        [10.0, 240.0]
-        """
-        x0, y0 = self._origin
-        x1, y1 = self._position
-        self._goto(x0+xpos, y1)
+    def onclick(self, fun, btn=1, add=None):
+        """Bind fun to mouse-click event on this turtle on canvas.
 
-    def sety(self, ypos):
-        """ Set the turtle's y coordinate to be ypos.
+        Arguments:
+        fun --  a function with two arguments, to which will be assigned
+                the coordinates of the clicked point on the canvas.
+        num --  number of the mouse-button defaults to 1 (left mouse button).
+        add --  True or False. If True, new binding will be added, otherwise
+                it will replace a former binding.
 
-        Example:
-        >>> turtle.position()
-        [0.0, 0.0]
-        >>> turtle.sety(-22)
-        >>> turtle.position()
-        [0.0, -22.0]
+        Example for the anonymous turtle, i. e. the procedural way:
+
+        >>> def turn(x, y):
+                left(360)
+
+        >>> onclick(turn) # Now clicking into the turtle will turn it.
+        >>> onclick(None)  # event-binding will be removed
         """
-        x0, y0 = self._origin
-        x1, y1 = self._position
-        self._goto(x1, y0-ypos)
+        self.screen._onclick(self.turtle._item, fun, btn, add)
+        self._update()
 
-    def towards(self, *args):
-        """Returs the angle, which corresponds to the line
-        from turtle-position to point (x,y).
+    def onrelease(self, fun, btn=1, add=None):
+        """Bind fun to mouse-button-release event on this turtle on canvas.
 
-        Argument can be two coordinates or one pair of coordinates
-        or a RawPen/Pen instance.
+        Arguments:
+        fun -- a function with two arguments, to which will be assigned
+                the coordinates of the clicked point on the canvas.
+        num --  number of the mouse-button defaults to 1 (left mouse button).
 
-        Example:
-        >>> turtle.position()
-        [10.0, 10.0]
-        >>> turtle.towards(0,0)
-        225.0
+        Example (for a MyTurtle instance named joe):
+        >>> class MyTurtle(Turtle):
+                def glow(self,x,y):
+                        self.fillcolor("red")
+                def unglow(self,x,y):
+                        self.fillcolor("")
+
+        >>> joe = MyTurtle()
+        >>> joe.onclick(joe.glow)
+        >>> joe.onrelease(joe.unglow)
+        ### clicking on joe turns fillcolor red,
+        ### unclicking turns it to transparent.
         """
-        if len(args) == 2:
-            x, y = args
-        else:
-            arg = args[0]
-            if isinstance(arg, RawPen):
-                x, y = arg.position()
-            else:
-                x, y = arg
-        x0, y0 = self.position()
-        dx = x - x0
-        dy = y - y0
-        return (atan2(dy,dx) / self._invradian) % self._fullcircle
+        self.screen._onrelease(self.turtle._item, fun, btn, add)
+        self._update()
 
-    def goto(self, *args):
-        """ Go to the given point.
+    def ondrag(self, fun, btn=1, add=None):
+        """Bind fun to mouse-move event on this turtle on canvas.
 
-        If the pen is down, then a line will be drawn. The turtle's
-        orientation does not change.
+        Arguments:
+        fun -- a function with two arguments, to which will be assigned
+               the coordinates of the clicked point on the canvas.
+        num -- number of the mouse-button defaults to 1 (left mouse button).
 
-        Two input formats are accepted:
+        Every sequence of mouse-move-events on a turtle is preceded by a
+        mouse-click event on that turtle.
 
-           goto(x, y)
-           go to point (x, y)
+        Example (for a Turtle instance named turtle):
+        >>> turtle.ondrag(turtle.goto)
 
-           goto((x, y))
-           go to point (x, y)
+        ### Subsequently clicking and dragging a Turtle will
+        ### move it across the screen thereby producing handdrawings
+        ### (if pen is down).
+        """
+        self.screen._ondrag(self.turtle._item, fun, btn, add)
 
-        Example:
-        >>> turtle.position()
-        [0.0, 0.0]
-        >>> turtle.goto(50, -45)
-        >>> turtle.position()
-        [50.0, -45.0]
+
+    def _undo(self, action, data):
+        """Does the main part of the work for undo()
         """
-        if len(args) == 1:
-            try:
-                x, y = args[0]
-            except:
-                raise Error, "bad point argument: %r" % (args[0],)
-        else:
-            try:
-                x, y = args
-            except:
-                raise Error, "bad coordinates: %r" % (args[0],)
-        x0, y0 = self._origin
-        self._goto(x0+x, y0-y)
-
-    def _goto(self, x1, y1):
-        x0, y0 = self._position
-        self._position = map(float, (x1, y1))
-        if self._filling:
-            self._path.append(self._position)
-        if self._drawing:
-            if self._tracing:
-                dx = float(x1 - x0)
-                dy = float(y1 - y0)
-                distance = hypot(dx, dy)
-                nhops = int(distance)
-                item = self._canvas.create_line(x0, y0, x0, y0,
-                                                width=self._width,
-                                                capstyle="round",
-                                                fill=self._color)
-                try:
-                    for i in range(1, 1+nhops):
-                        x, y = x0 + dx*i/nhops, y0 + dy*i/nhops
-                        self._canvas.coords(item, x0, y0, x, y)
-                        self._draw_turtle((x,y))
-                        self._canvas.update()
-                        self._canvas.after(self._delay)
-                    # in case nhops==0
-                    self._canvas.coords(item, x0, y0, x1, y1)
-                    self._canvas.itemconfigure(item, arrow="none")
-                except Tkinter.TclError:
-                    # Probably the window was closed!
-                    return
-            else:
-                item = self._canvas.create_line(x0, y0, x1, y1,
-                                                width=self._width,
-                                                capstyle="round",
-                                                fill=self._color)
-            self._items.append(item)
-        self._draw_turtle()
-
-    def speed(self, speed):
-        """ Set the turtle's speed.
-
-        speed must one of these five strings:
-
-            'fastest' is a 0 ms delay
-            'fast' is a 5 ms delay
-            'normal' is a 10 ms delay
-            'slow' is a 15 ms delay
-            'slowest' is a 20 ms delay
+        if self.undobuffer is None:
+            return
+        if action == "rot":
+            angle, degPAU = data
+            self._rotate(-angle*degPAU/self._degreesPerAU)
+            dummy = self.undobuffer.pop()
+        elif action == "stamp":
+            stitem = data[0]
+            self.clearstamp(stitem)
+        elif action == "go":
+            self._undogoto(data)
+        elif action in ["wri", "dot"]:
+            item = data[0]
+            self.screen._delete(item)
+            self.items.remove(item)
+        elif action == "dofill":
+            item = data[0]
+            self.screen._drawpoly(item, ((0, 0),(0, 0),(0, 0)),
+                                  fill="", outline="")
+        elif action == "beginfill":
+            item = data[0]
+            self._fillitem = self._fillpath = None
+            self.screen._delete(item)
+            self.items.remove(item)
+        elif action == "pen":
+            TPen.pen(self, data[0])
+            self.undobuffer.pop()
+
+    def undo(self):
+        """undo (repeatedly) the last turtle action.
+
+        No argument.
+
+        undo (repeatedly) the last turtle action.
+        Number of available undo actions is determined by the size of
+        the undobuffer.
+
+        Example (for a Turtle instance named turtle):
+        >>> for i in range(4):
+                turtle.fd(50); turtle.lt(80)
 
-         Example:
-         >>> turtle.speed('slow')
+        >>> for i in range(8):
+                turtle.undo()
         """
-        try:
-            speed = speed.strip().lower()
-            self._delay = speeds.index(speed) * 5
-        except:
-            raise ValueError("%r is not a valid speed. speed must be "
-                             "one of %s" % (speed, speeds))
+        if self.undobuffer is None:
+            return
+        item = self.undobuffer.pop()
+        action = item[0]
+        data = item[1:]
+        if action == "seq":
+            while data:
+                item = data.pop()
+                self._undo(item[0], item[1:])
+        else:
+            self._undo(action, data)
 
+    turtlesize = shapesize
 
-    def delay(self, delay):
-        """ Set the drawing delay in milliseconds.
+RawPen = RawTurtle
 
-        This is intended to allow finer control of the drawing speed
-        than the speed() method
+###  Screen - Klasse  ########################
 
-        Example:
-        >>> turtle.delay(15)
-        """
-        if int(delay) < 0:
-            raise ValueError("delay must be greater than or equal to 0")
-        self._delay = int(delay)
-
-    def _draw_turtle(self, position=[]):
-        if not self._tracing:
-            self._canvas.update()
-            return
-        if position == []:
-            position = self._position
-        x,y = position
-        distance = 8
-        dx = distance * cos(self._angle*self._invradian)
-        dy = distance * sin(self._angle*self._invradian)
-        self._delete_turtle()
-        self._arrow = self._canvas.create_line(x-dx,y+dy,x,y,
-                                          width=self._width,
-                                          arrow="last",
-                                          capstyle="round",
-                                          fill=self._color)
-        self._canvas.update()
-
-    def _delete_turtle(self):
-        if self._arrow != 0:
-            self._canvas.delete(self._arrow)
-            self._arrow = 0
-
-
-_root = None
-_canvas = None
-_pen = None
-_width = 0.50                  # 50% of window width
-_height = 0.75                 # 75% of window height
-_startx = None
-_starty = None
-_title = "Turtle Graphics"     # default title
+class Screen(TurtleScreen):
+
+    _root = None
+    _canvas = None
+    _title = _CFG["title"]
+
+    # Borg-Idiom
 
-class Pen(RawPen):
+    _shared_state = {}
+
+    def __new__(cls, *args, **kwargs):
+        obj = object.__new__(cls, *args, **kwargs)
+        obj.__dict__ = cls._shared_state
+        return obj
 
     def __init__(self):
-        global _root, _canvas
-        if _root is None:
-            _root = Tkinter.Tk()
-            _root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
-            _root.title(_title)
-
-        if _canvas is None:
-            # XXX Should have scroll bars
-            _canvas = Tkinter.Canvas(_root, background="white")
-            _canvas.pack(expand=1, fill="both")
+        if Screen._root is None:
+            Screen._root = self._root = _Root()
+            self._root.title(Screen._title)
+            self._root.ondestroy(self._destroy)
+        if Screen._canvas is None:
+            width = _CFG["width"]
+            height = _CFG["height"]
+            canvwidth = _CFG["canvwidth"]
+            canvheight = _CFG["canvheight"]
+            leftright = _CFG["leftright"]
+            topbottom = _CFG["topbottom"]
+            self._root.setupcanvas(width, height, canvwidth, canvheight)
+            Screen._canvas = self._root._getcanvas()
+            self.setup(width, height, leftright, topbottom)
+        TurtleScreen.__init__(self, Screen._canvas)
+        Turtle._screen = self
+
+    def setup(self, width=_CFG["width"], height=_CFG["height"],
+              startx=_CFG["leftright"], starty=_CFG["topbottom"]):
+        """ Set the size and position of the main window.
+
+        Arguments:
+        width: as integer a size in pixels, as float a fraction of the screen.
+          Default is 50% of screen.
+        height: as integer the height in pixels, as float a fraction of the
+          screen. Default is 75% of screen.
+        startx: if positive, starting position in pixels from the left
+          edge of the screen, if negative from the right edge
+          Default, startx=None is to center window horizontally.
+        starty: if positive, starting position in pixels from the top
+          edge of the screen, if negative from the bottom edge
+          Default, starty=None is to center window vertically.
+
+        Examples (for a Screen instance named screen):
+        >>> screen.setup (width=200, height=200, startx=0, starty=0)
+
+        sets window to 200x200 pixels, in upper left of screen
 
-            setup(width=_width, height= _height, startx=_startx, starty=_starty)
+        >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
 
-        RawPen.__init__(self, _canvas)
+        sets window to 75% of screen by 50% of screen and centers
+        """
+        if not hasattr(self._root, "set_geometry"):
+            return
+        sw = self._root.win_width()
+        sh = self._root.win_height()
+        if isinstance(width, float) and 0 <= width <= 1:
+            width = sw*width
+        if startx is None:
+            startx = (sw - width) / 2
+        if isinstance(height, float) and 0 <= height <= 1:
+            height = sh*height
+        if starty is None:
+            starty = (sh - height) / 2
+        self._root.set_geometry(width, height, startx, starty)
+
+    def title(self, titlestring):
+        """Set title of turtle-window
+
+        Argument:
+        titlestring -- a string, to appear in the titlebar of the
+                       turtle graphics window.
+
+        This is a method of Screen-class. Not available for TurtleScreen-
+        objects.
+
+        Example (for a Screen instance named screen):
+        >>> screen.title("Welcome to the turtle-zoo!")
+        """
+        if Screen._root is not None:
+            Screen._root.title(titlestring)
+        Screen._title = titlestring
 
     def _destroy(self):
-        global _root, _canvas, _pen
-        root = self._canvas._root()
-        if root is _root:
-            _pen = None
-            _root = None
-            _canvas = None
+        root = self._root
+        if root is Screen._root:
+            Turtle._pen = None
+            Turtle._screen = None
+            Screen._root = None
+            Screen._canvas = None
+        TurtleScreen._RUNNING = True
         root.destroy()
 
-def _getpen():
-    global _pen
-    if not _pen:
-        _pen = Pen()
-    return _pen
+    def bye(self):
+        """Shut the turtlegraphics window.
 
-class Turtle(Pen):
-    pass
+        Example (for a TurtleScreen instance named screen):
+        >>> screen.bye()
+        """
+        self._destroy()
 
-"""For documentation of the following functions see
-   the RawPen methods with the same names
-"""
+    def exitonclick(self):
+        """Go into mainloop until the mouse is clicked.
 
-def degrees(): _getpen().degrees()
-def radians(): _getpen().radians()
-def reset(): _getpen().reset()
-def clear(): _getpen().clear()
-def tracer(flag): _getpen().tracer(flag)
-def forward(distance): _getpen().forward(distance)
-def backward(distance): _getpen().backward(distance)
-def left(angle): _getpen().left(angle)
-def right(angle): _getpen().right(angle)
-def up(): _getpen().up()
-def down(): _getpen().down()
-def width(width): _getpen().width(width)
-def color(*args): _getpen().color(*args)
-def write(arg, move=0): _getpen().write(arg, move)
-def fill(flag): _getpen().fill(flag)
-def begin_fill(): _getpen().begin_fill()
-def end_fill(): _getpen().end_fill()
-def circle(radius, extent=None): _getpen().circle(radius, extent)
-def goto(*args): _getpen().goto(*args)
-def heading(): return _getpen().heading()
-def setheading(angle): _getpen().setheading(angle)
-def position(): return _getpen().position()
-def window_width(): return _getpen().window_width()
-def window_height(): return _getpen().window_height()
-def setx(xpos): _getpen().setx(xpos)
-def sety(ypos): _getpen().sety(ypos)
-def towards(*args): return _getpen().towards(*args)
-
-def done(): _root.mainloop()
-def delay(delay): return _getpen().delay(delay)
-def speed(speed): return _getpen().speed(speed)
-
-for methodname in dir(RawPen):
-    """ copies RawPen docstrings to module functions of same name """
-    if not methodname.startswith("_"):
-        eval(methodname).__doc__ = RawPen.__dict__[methodname].__doc__
-
-
-def setup(**geometry):
-    """ Sets the size and position of the main window.
-
-    Keywords are width, height, startx and starty:
-
-    width: either a size in pixels or a fraction of the screen.
-      Default is 50% of screen.
-    height: either the height in pixels or a fraction of the screen.
-      Default is 75% of screen.
-
-    Setting either width or height to None before drawing will force
-      use of default geometry as in older versions of turtle.py
-
-    startx: starting position in pixels from the left edge of the screen.
-      Default is to center window. Setting startx to None is the default
-      and centers window horizontally on screen.
-
-    starty: starting position in pixels from the top edge of the screen.
-      Default is to center window. Setting starty to None is the default
-      and centers window vertically on screen.
-
-    Examples:
-    >>> setup (width=200, height=200, startx=0, starty=0)
-
-    sets window to 200x200 pixels, in upper left of screen
-
-    >>> setup(width=.75, height=0.5, startx=None, starty=None)
-
-    sets window to 75% of screen by 50% of screen and centers
-
-    >>> setup(width=None)
-
-    forces use of default geometry as in older versions of turtle.py
-    """
-
-    global _width, _height, _startx, _starty
-
-    width = geometry.get('width',_width)
-    if width >= 0 or width is None:
-        _width = width
-    else:
-        raise ValueError, "width can not be less than 0"
+        No arguments.
 
-    height = geometry.get('height',_height)
-    if height >= 0 or height is None:
-        _height = height
-    else:
-        raise ValueError, "height can not be less than 0"
+        Bind bye() method to mouseclick on TurtleScreen.
+        If "using_IDLE" - value in configuration dictionary is False
+        (default value), enter mainloop.
+        If IDLE with -n switch (no subprocess) is used, this value should be
+        set to True in turtle.cfg. In this case IDLE's mainloop
+        is active also for the client script.
 
-    startx = geometry.get('startx', _startx)
-    if startx >= 0 or startx is None:
-        _startx = _startx
-    else:
-        raise ValueError, "startx can not be less than 0"
+        This is a method of the Screen-class and not available for
+        TurtleScreen instances.
 
-    starty = geometry.get('starty', _starty)
-    if starty >= 0 or starty is None:
-        _starty = starty
-    else:
-        raise ValueError, "startx can not be less than 0"
+        Example (for a Screen instance named screen):
+        >>> screen.exitonclick()
 
+        """
+        def exitGracefully(x, y):
+            """Screen.bye() with two dummy-parameters"""
+            self.bye()
+        self.onclick(exitGracefully)
+        if _CFG["using_IDLE"]:
+            return
+        try:
+            mainloop()
+        except AttributeError:
+            exit(0)
 
-    if _root and _width and _height:
-        if 0 < _width <= 1:
-            _width = _root.winfo_screenwidth() * +width
-        if 0 < _height <= 1:
-            _height = _root.winfo_screenheight() * _height
 
-        # center window on screen
-        if _startx is None:
-            _startx = (_root.winfo_screenwidth() - _width) / 2
+class Turtle(RawTurtle):
+    """RawTurtle auto-crating (scrolled) canvas.
 
-        if _starty is None:
-            _starty = (_root.winfo_screenheight() - _height) / 2
+    When a Turtle object is created or a function derived from some
+    Turtle method is called a TurtleScreen object is automatically created.
+    """
+    _pen = None
+    _screen = None
 
-        _root.geometry("%dx%d+%d+%d" % (_width, _height, _startx, _starty))
+    def __init__(self,
+                 shape=_CFG["shape"],
+                 undobuffersize=_CFG["undobuffersize"],
+                 visible=_CFG["visible"]):
+        if Turtle._screen is None:
+            Turtle._screen = Screen()
+        RawTurtle.__init__(self, Turtle._screen,
+                           shape=shape,
+                           undobuffersize=undobuffersize,
+                           visible=visible)
 
-def title(title):
-    """Set the window title.
+Pen = Turtle
 
-    By default this is set to 'Turtle Graphics'
+def _getpen():
+    """Create the 'anonymous' turtle if not already present."""
+    if Turtle._pen is None:
+        Turtle._pen = Turtle()
+    return Turtle._pen
+
+def _getscreen():
+    """Create a TurtleScreen if not already present."""
+    if Turtle._screen is None:
+        Turtle._screen = Screen()
+    return Turtle._screen
+
+def write_docstringdict(filename="turtle_docstringdict"):
+    """Create and write docstring-dictionary to file.
+
+    Optional argument:
+    filename -- a string, used as filename
+                default value is turtle_docstringdict
+
+    Has to be called explicitely, (not used by the turtle-graphics classes)
+    The docstring dictionary will be written to the Python script <filname>.py
+    It is intended to serve as a template for translation of the docstrings
+    into different languages.
+    """
+    docsdict = {}
 
-    Example:
-    >>> title("My Window")
+    for methodname in _tg_screen_functions:
+        key = "Screen."+methodname
+        docsdict[key] = eval(key).__doc__
+    for methodname in _tg_turtle_functions:
+        key = "Turtle."+methodname
+        docsdict[key] = eval(key).__doc__
+
+    f = open("%s.py" % filename,"w")
+    keys = sorted([x for x in docsdict.keys()
+                        if x.split('.')[1] not in _alias_list])
+    f.write('docsdict = {\n\n')
+    for key in keys[:-1]:
+        f.write('%s :\n' % repr(key))
+        f.write('        """%s\n""",\n\n' % docsdict[key])
+    key = keys[-1]
+    f.write('%s :\n' % repr(key))
+    f.write('        """%s\n"""\n\n' % docsdict[key])
+    f.write("}\n")
+    f.close()
+
+def read_docstrings(lang):
+    """Read in docstrings from lang-specific docstring dictionary.
+
+    Transfer docstrings, translated to lang, from a dictionary-file
+    to the methods of classes Screen and Turtle and - in revised form -
+    to the corresponding functions.
     """
+    modname = "turtle_docstringdict_%(language)s" % {'language':lang.lower()}
+    module = __import__(modname)
+    docsdict = module.docsdict
+    for key in docsdict:
+        #print key
+        try:
+            eval(key).im_func.__doc__ = docsdict[key]
+        except:
+            print "Bad docstring-entry: %s" % key
 
-    global _title
-    _title = title
+_LANGUAGE = _CFG["language"]
 
-def demo():
-    reset()
-    tracer(1)
-    up()
-    backward(100)
-    down()
-    # draw 3 squares; the last filled
-    width(3)
-    for i in range(3):
-        if i == 2:
-            fill(1)
-        for j in range(4):
-            forward(20)
-            left(90)
-        if i == 2:
-            color("maroon")
-            fill(0)
+try:
+    if _LANGUAGE != "english":
+        read_docstrings(_LANGUAGE)
+except ImportError:
+    print "Cannot find docsdict for", _LANGUAGE
+except:
+    print ("Unknown Error when trying to import %s-docstring-dictionary" %
+                                                                  _LANGUAGE)
+
+
+def getmethparlist(ob):
+    "Get strings describing the arguments for the given object"
+    argText1 = argText2 = ""
+    # bit of a hack for methods - turn it into a function
+    # but we drop the "self" param.
+    if type(ob)==types.MethodType:
+        fob = ob.im_func
+        argOffset = 1
+    else:
+        fob = ob
+        argOffset = 0
+    # Try and build one for Python defined functions
+    if type(fob) in [types.FunctionType, types.LambdaType]:
+        try:
+            counter = fob.func_code.co_argcount
+            items2 = list(fob.func_code.co_varnames[argOffset:counter])
+            realArgs = fob.func_code.co_varnames[argOffset:counter]
+            defaults = fob.func_defaults or []
+            defaults = list(map(lambda name: "=%s" % repr(name), defaults))
+            defaults = [""] * (len(realArgs)-len(defaults)) + defaults
+            items1 = map(lambda arg, dflt: arg+dflt, realArgs, defaults)
+            if fob.func_code.co_flags & 0x4:
+                items1.append("*"+fob.func_code.co_varnames[counter])
+                items2.append("*"+fob.func_code.co_varnames[counter])
+                counter += 1
+            if fob.func_code.co_flags & 0x8:
+                items1.append("**"+fob.func_code.co_varnames[counter])
+                items2.append("**"+fob.func_code.co_varnames[counter])
+            argText1 = ", ".join(items1)
+            argText1 = "(%s)" % argText1
+            argText2 = ", ".join(items2)
+            argText2 = "(%s)" % argText2
+        except:
+            pass
+    return argText1, argText2
+
+def _turtle_docrevise(docstr):
+    """To reduce docstrings from RawTurtle class for functions
+    """
+    import re
+    if docstr is None:
+        return None
+    turtlename = _CFG["exampleturtle"]
+    newdocstr = docstr.replace("%s." % turtlename,"")
+    parexp = re.compile(r' \(.+ %s\):' % turtlename)
+    newdocstr = parexp.sub(":", newdocstr)
+    return newdocstr
+
+def _screen_docrevise(docstr):
+    """To reduce docstrings from TurtleScreen class for functions
+    """
+    import re
+    if docstr is None:
+        return None
+    screenname = _CFG["examplescreen"]
+    newdocstr = docstr.replace("%s." % screenname,"")
+    parexp = re.compile(r' \(.+ %s\):' % screenname)
+    newdocstr = parexp.sub(":", newdocstr)
+    return newdocstr
+
+## The following mechanism makes all methods of RawTurtle and Turtle available
+## as functions. So we can enhance, change, add, delete methods to these
+## classes and do not need to change anything here.
+
+
+for methodname in _tg_screen_functions:
+    pl1, pl2 = getmethparlist(eval('Screen.' + methodname))
+    if pl1 == "":
+        print ">>>>>>", pl1, pl2
+        continue
+    defstr = ("def %(key)s%(pl1)s: return _getscreen().%(key)s%(pl2)s" %
+                                   {'key':methodname, 'pl1':pl1, 'pl2':pl2})
+    exec defstr
+    eval(methodname).__doc__ = _screen_docrevise(eval('Screen.'+methodname).__doc__)
+
+for methodname in _tg_turtle_functions:
+    pl1, pl2 = getmethparlist(eval('Turtle.' + methodname))
+    if pl1 == "":
+        print ">>>>>>", pl1, pl2
+        continue
+    defstr = ("def %(key)s%(pl1)s: return _getpen().%(key)s%(pl2)s" %
+                                   {'key':methodname, 'pl1':pl1, 'pl2':pl2})
+    exec defstr
+    eval(methodname).__doc__ = _turtle_docrevise(eval('Turtle.'+methodname).__doc__)
+
+
+done = mainloop = TK.mainloop
+del pl1, pl2, defstr
+
+if __name__ == "__main__":
+    def switchpen():
+        if isdown():
+            pu()
+        else:
+            pd()
+
+    def demo1():
+        """Demo of old turtle.py - module"""
+        reset()
+        tracer(True)
         up()
-        forward(30)
+        backward(100)
         down()
-    width(1)
-    color("black")
-    # move out of the way
-    tracer(0)
-    up()
-    right(90)
-    forward(100)
-    right(90)
-    forward(100)
-    right(180)
-    down()
-    # some text
-    write("startstart", 1)
-    write("start", 1)
-    color("red")
-    # staircase
-    for i in range(5):
-        forward(20)
-        left(90)
-        forward(20)
-        right(90)
-    # filled staircase
-    fill(1)
-    for i in range(5):
-        forward(20)
-        left(90)
-        forward(20)
-        right(90)
-    fill(0)
-    tracer(1)
-    # more text
-    write("end")
-
-def demo2():
-    # exercises some new and improved features
-    speed('fast')
-    width(3)
-
-    # draw a segmented half-circle
-    setheading(towards(0,0))
-    x,y = position()
-    r = (x**2+y**2)**.5/2.0
-    right(90)
-    pendown = True
-    for i in range(18):
-        if pendown:
+        # draw 3 squares; the last filled
+        width(3)
+        for i in range(3):
+            if i == 2:
+                fill(1)
+            for _ in range(4):
+                forward(20)
+                left(90)
+            if i == 2:
+                color("maroon")
+                fill(0)
             up()
-            pendown = False
-        else:
+            forward(30)
             down()
-            pendown = True
-        circle(r,10)
-    sleep(2)
-
-    reset()
-    left(90)
-
-    # draw a series of triangles
-    l = 10
-    color("green")
-    width(3)
-    left(180)
-    sp = 5
-    for i in range(-2,16):
-        if i > 0:
-            color(1.0-0.05*i,0,0.05*i)
-            fill(1)
-            color("green")
-        for j in range(3):
-            forward(l)
-            left(120)
-        l += 10
-        left(15)
-        if sp > 0:
-            sp = sp-1
-            speed(speeds[sp])
-    color(0.25,0,0.75)
-    fill(0)
-
-    # draw and fill a concave shape
-    left(120)
-    up()
-    forward(70)
-    right(30)
-    down()
-    color("red")
-    speed("fastest")
-    fill(1)
-    for i in range(4):
-        circle(50,90)
+        width(1)
+        color("black")
+        # move out of the way
+        tracer(False)
+        up()
         right(90)
-        forward(30)
+        forward(100)
         right(90)
-    color("yellow")
-    fill(0)
-    left(90)
-    up()
-    forward(30)
-    down();
-
-    color("red")
-
-    # create a second turtle and make the original pursue and catch it
-    turtle=Turtle()
-    turtle.reset()
-    turtle.left(90)
-    turtle.speed('normal')
-    turtle.up()
-    turtle.goto(280,40)
-    turtle.left(24)
-    turtle.down()
-    turtle.speed('fast')
-    turtle.color("blue")
-    turtle.width(2)
-    speed('fastest')
-
-    # turn default turtle towards new turtle object
-    setheading(towards(turtle))
-    while ( abs(position()[0]-turtle.position()[0])>4 or
-            abs(position()[1]-turtle.position()[1])>4):
-        turtle.forward(3.5)
-        turtle.left(0.6)
-        # turn default turtle towards new turtle object
+        forward(100)
+        right(180)
+        down()
+        # some text
+        write("startstart", 1)
+        write("start", 1)
+        color("red")
+        # staircase
+        for i in range(5):
+            forward(20)
+            left(90)
+            forward(20)
+            right(90)
+        # filled staircase
+        tracer(True)
+        fill(1)
+        for i in range(5):
+            forward(20)
+            left(90)
+            forward(20)
+            right(90)
+        fill(0)
+        # more text
+
+    def demo2():
+        """Demo of some new features."""
+        speed(1)
+        st()
+        pensize(3)
+        setheading(towards(0, 0))
+        radius = distance(0, 0)/2.0
+        rt(90)
+        for _ in range(18):
+            switchpen()
+            circle(radius, 10)
+        write("wait a moment...")
+        while undobufferentries():
+            undo()
+        reset()
+        lt(90)
+        colormode(255)
+        laenge = 10
+        pencolor("green")
+        pensize(3)
+        lt(180)
+        for i in range(-2, 16):
+            if i > 0:
+                begin_fill()
+                fillcolor(255-15*i, 0, 15*i)
+            for _ in range(3):
+                fd(laenge)
+                lt(120)
+            laenge += 10
+            lt(15)
+            speed((speed()+1)%12)
+        end_fill()
+
+        lt(120)
+        pu()
+        fd(70)
+        rt(30)
+        pd()
+        color("red","yellow")
+        speed(0)
+        fill(1)
+        for _ in range(4):
+            circle(50, 90)
+            rt(90)
+            fd(30)
+            rt(90)
+        fill(0)
+        lt(90)
+        pu()
+        fd(30)
+        pd()
+        shape("turtle")
+
+        tri = getturtle()
+        tri.resizemode("auto")
+        turtle = Turtle()
+        turtle.resizemode("auto")
+        turtle.shape("turtle")
+        turtle.reset()
+        turtle.left(90)
+        turtle.speed(0)
+        turtle.up()
+        turtle.goto(280, 40)
+        turtle.lt(30)
+        turtle.down()
+        turtle.speed(6)
+        turtle.color("blue","orange")
+        turtle.pensize(2)
+        tri.speed(6)
         setheading(towards(turtle))
-        forward(4)
-    write("CAUGHT! ", move=True)
-
-
+        count = 1
+        while tri.distance(turtle) > 4:
+            turtle.fd(3.5)
+            turtle.lt(0.6)
+            tri.setheading(tri.towards(turtle))
+            tri.fd(4)
+            if count % 20 == 0:
+                turtle.stamp()
+                tri.stamp()
+                switchpen()
+            count += 1
+        tri.write("CAUGHT! ", font=("Arial", 16, "bold"), align="right")
+        tri.pencolor("black")
+        tri.pencolor("red")
+
+        def baba(xdummy, ydummy):
+            clearscreen()
+            bye()
+
+        time.sleep(2)
+
+        while undobufferentries():
+            tri.undo()
+            turtle.undo()
+        tri.fd(50)
+        tri.write("  Click me!", font = ("Courier", 12, "bold") )
+        tri.onclick(baba, 1)
 
-if __name__ == '__main__':
-    demo()
-    sleep(3)
+    demo1()
     demo2()
-    done()
+    exitonclick()

Modified: python/branches/okkoto-sizeof/Lib/lib2to3/fixes/fix_imports.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib2to3/fixes/fix_imports.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib2to3/fixes/fix_imports.py	Wed Jun  4 11:24:23 2008
@@ -14,10 +14,143 @@
 builtin_names = [name for name in dir(__builtin__)
                  if name not in ("__name__", "__doc__")]
 
+# XXX(alexandre): It would be possible to get the modules exports by fetching
+# XXX: their __all__ attribute. However, I fear that this would add an additional
+# XXX: overhead to the fixer.
 MAPPING = {"StringIO":  ("io", ["StringIO"]),
            "cStringIO": ("io", ["StringIO"]),
            "__builtin__" : ("builtins", builtin_names),
-          }
+           'copy_reg': ('copyreg', ['pickle',
+                                    'constructor',
+                                    'add_extension',
+                                    'remove_extension',
+                                    'clear_extension_cache']),
+           'Queue': ('queue', ['Empty', 'Full', 'Queue',
+                               'PriorityQueue', 'LifoQueue']),
+           'SocketServer': ('socketserver',
+                            ['TCPServer', 'UDPServer', 'BaseServer',
+                             'ForkingUDPServer', 'ForkingTCPServer',
+                             'ThreadingUDPServer', 'ThreadingTCPServer',
+                             'BaseRequestHandler', 'StreamRequestHandler',
+                             'DatagramRequestHandler', 'ThreadingMixIn',
+                             'ForkingMixIn', 'UnixStreamServer',
+                             'UnixDatagramServer', 'ThreadingUnixStreamServer',
+                             'ThreadingUnixDatagramServer']),
+           'ConfigParser': ('configparser',
+                            ['NoSectionError', 'DuplicateSectionError',
+                             'NoOptionError', 'InterpolationError',
+                             'InterpolationDepthError',
+                             'InterpolationSyntaxError',
+                             'ParsingError', 'MissingSectionHeaderError',
+                             'ConfigParser', 'SafeConfigParser',
+                             'RawConfigParser', 'DEFAULTSECT',
+                             'MAX_INTERPOLATION_DEPTH']),
+           'repr': ('reprlib', ['Repr', 'repr']),
+           'FileDialog': ('tkinter.filedialog',
+                          ['FileDialog', 'LoadFileDialog', 'SaveFileDialog']),
+           'tkFileDialog': ('tkinter.filedialog',
+                            ['Open', 'SaveAs', 'Directory', 'askopenfilename',
+                             'asksaveasfilename', 'askopenfilenames',
+                             'askopenfile', 'askopenfiles', 'asksaveasfile',
+                             'askdirectory']),
+           'SimpleDialog': ('tkinter.simpledialog', ['SimpleDialog']),
+           'tkSimpleDialog': ('tkinter.simpledialog',
+                              ['Dialog', 'askinteger', 'askfloat',
+                               'askstring']),
+           'tkColorChooser': ('tkinter.colorchooser', ['Chooser', 'askcolor']),
+           'tkCommonDialog': ('tkinter.commondialog', ['Dialog']),
+           'Dialog': ('tkinter.dialog', ['Dialog']),
+           'Tkdnd': ('tkinter.dnd', ['DndHandler']),
+           'tkFont': ('tkinter.font',
+                      ['nametofont', 'Font', 'families', 'names']),
+           'tkMessageBox': ('tkinter.messagebox',
+                            ['Message', 'showinfo', 'showwarning', 'showerror',
+                             'askquestion', 'askokcancel', 'askyesno',
+                             'askyesnocancel', 'askretrycancel']),
+           'ScrolledText': ('tkinter.scrolledtext', ['ScrolledText']),
+           'turtle': ('tkinter.turtle',
+                      ['RawPen', 'Pen', 'Turtle', 'degrees', 'radian', 'reset',
+                       'clear', 'tracer', 'forward', 'backward', 'left',
+                       'right', 'up', 'down', 'width', 'color', 'write', 'fill',
+                       'begin_fill', 'end_fill', 'circle', 'goto', 'heading',
+                       'setheading', 'position', 'window_width', 'setx', 'sety',
+                       'towards', 'done', 'delay', 'speed', 'setup', 'title']),
+           'Tkconstants': ('tkinter.constants',
+                           ['NO', 'FALSE', 'OFF', 'YES', 'TRUE', 'ON', 'N', 'S',
+                            'W', 'E', 'NW', 'SW', 'SE', 'NE', 'NS', 'EW',
+                            'NSEW', 'CENTER', 'NONE', 'X', 'Y', 'BOTH', 'LEFT',
+                            'TOP', 'RIGHT', 'BOTTOM', 'RAISED', 'SUNKEN',
+                            'FLAT', 'RIDGE', 'GROOVE', 'SOLID', 'HORIZONTAL',
+                            'VERTICAL', 'NUMERIC', 'CHAR', 'WORD', 'BASELINE',
+                            'INSIDE', 'OUTSIDE', 'SEL', 'SEL_FIRST', 'SEL_LAST',
+                            'END', 'INSERT', 'CURRENT', 'ANCHOR', 'ALL',
+                            'NORMAL', 'DISABLED', 'ACTIVE', 'HIDDEN', 'CASCADE',
+                            'CHECKBUTTON', 'COMMAND', 'RADIOBUTTON',
+                            'SEPARATOR', 'SINGLE', 'BROWSE', 'MULTIPLE',
+                            'EXTENDED', 'DOTBOX', 'UNDERLINE', 'PIESLICE',
+                            'CHORD', 'ARC', 'FIRST', 'LAST', 'BUTT',
+                            'PROJECTING', 'ROUND', 'BEVEL', 'MITTER', 'MOVETO',
+                            'SCROLL', 'UNITS', 'PAGES']),
+           'Tix': ('tkinter.tix',
+                   ['tixCommand', 'Tk', 'Form', 'TixWidget', 'TixSubWidget',
+                    'DisplayStyle', 'Balloon', 'ButtonBox', 'ComboBox',
+                    'Control', 'DirList', 'DirTree', 'DirSelectBox',
+                    'ExFileSelectBox', 'DirSelectDialog', 'ExFileSelectDialog',
+                    'FileSelectBox', 'FileSelectDialog', 'FileEntry', 'HList',
+                    'InputOnly', 'LabelEntry', 'LabelFrame', 'ListNoteBook',
+                    'Meter', 'NoteBook', 'OptionMenu', 'PanedWindow',
+                    'PopupMenu', 'ResizeHandle', 'ScrolledHList',
+                    'ScrolledListBox', 'ScrolledText', 'ScrolledTList',
+                    'ScrolledWindow', 'Select', 'Shell', 'DialogShell',
+                    'StdButtonBox', 'TList', 'Tree', 'CheckList', 'OptionName',
+                    'FileTypeList', 'Grid', 'ScrolledGrid']),
+           'Tkinter': ('tkinter',
+                       ['_flatten', 'TclError', 'TkVersion', 'TclVersion',
+                        'Variable', 'StringVar', 'IntVar', 'DoubleVar',
+                        'BooleanVar','mainloop', 'Tk', 'Tcl', 'Toplevel',
+                        'Button', 'Canvas', 'Checkbutton', 'Entry', 'Frame',
+                        'Label', 'Listbox', 'Menu', 'Menubutton',
+                        'Radiobutton', 'Scale', 'Scrollbar', 'Text',
+                        'OptionMenu', 'Image', 'PhotoImage', 'BitmapImage',
+                        'image_names', 'image_types', 'Spinbox', 'LabelFrame',
+                        'PanedWindow', 'Studbutton', 'Tributton']),
+           'markupbase': ('_markupbase', ['ParserBase']),
+           '_winreg': ('winreg', [
+               'CloseKey', 'ConnectRegistry', 'CreateKey', 'DeleteKey',
+               'DeleteValue', 'DisableReflectionKey', 'EnableReflectionKey',
+               'EnumKey', 'EnumValue', 'ExpandEnvironmentStrings', 'FlushKey',
+               'LoadKey', 'OpenKey', 'OpenKeyEx', 'QueryValue', 'QueryValueEx',
+               'QueryInfoKey', 'QueryReflectionKey', 'SaveKey', 'SetValue',
+               'SetValueEx', 'HKEY_CLASSES_ROOT', 'HKEY_CURRENT_USER',
+               'HKEY_LOCAL_MACHINE', 'HKEY_USERS', 'HKEY_PERFORMANCE_DATA',
+               'HKEY_CURRENT_CONFIG', 'HKEY_DYN_DATA', 'KEY_QUERY_VALUE',
+               'KEY_SET_VALUE', 'KEY_CREATE_SUB_KEY', 'KEY_ENUMERATE_SUB_KEYS',
+               'KEY_NOTIFY', 'KEY_CREATE_LINK', 'KEY_READ', 'KEY_WRITE',
+               'KEY_EXECUTE', 'KEY_ALL_ACCESS', 'KEY_WOW64_64KEY',
+               'KEY_WOW64_32KEY', 'REG_OPTION_RESERVED',
+               'REG_OPTION_NON_VOLATILE', 'REG_OPTION_VOLATILE',
+               'REG_OPTION_CREATE_LINK', 'REG_OPTION_BACKUP_RESTORE',
+               'REG_OPTION_OPEN_LINK', 'REG_LEGAL_OPTION',
+               'REG_CREATED_NEW_KEY', 'REG_OPENED_EXISTING_KEY',
+               'REG_WHOLE_HIVE_VOLATILE', 'REG_REFRESH_HIVE',
+               'REG_NO_LAZY_FLUSH', 'REG_NOTIFY_CHANGE_NAME',
+               'REG_NOTIFY_CHANGE_ATTRIBUTES', 'REG_NOTIFY_CHANGE_LAST_SET',
+               'REG_NOTIFY_CHANGE_SECURITY', 'REG_LEGAL_CHANGE_FILTER',
+               'REG_NONE', 'REG_SZ', 'REG_EXPAND_SZ', 'REG_BINARY', 'REG_DWORD',
+               'REG_DWORD_LITTLE_ENDIAN', 'REG_DWORD_BIG_ENDIAN', 'REG_LINK',
+               'REG_MULTI_SZ', 'REG_RESOURCE_LIST',
+               'REG_FULL_RESOURCE_DESCRIPTOR', 'REG_RESOURCE_REQUIREMENTS_LIST']),
+           'thread': ('_thread',
+                      ['LockType', '_local', 'allocate', 'allocate_lock',
+                       'error', 'exit', 'exit_thread', 'get_ident',
+                       'interrupt_main', 'stack_size', 'start_new',
+                       'start_new_thread']),
+           'dummy_thread': ('_dummy_thread',
+                      ['LockType', '_local', 'allocate', 'allocate_lock',
+                       'error', 'exit', 'exit_thread', 'get_ident',
+                       'interrupt_main', 'stack_size', 'start_new',
+                       'start_new_thread']),
+}
 
 
 def alternates(members):
@@ -34,7 +167,8 @@
                               | dotted_as_names< any* module=%r any* >) >
               """ % (old_module, old_module)
         yield """import_from< 'from' module_name=%r 'import'
-                   ( %s | import_as_name< %s 'as' any >) >
+                   ( %s | import_as_name< %s 'as' any > |
+                     import_as_names< any* >) >
               """ % (old_module, members, members)
         yield """import_from< 'from' module_name=%r 'import' star='*' >
               """ % old_module

Modified: python/branches/okkoto-sizeof/Lib/lib2to3/pgen2/driver.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib2to3/pgen2/driver.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib2to3/pgen2/driver.py	Wed Jun  4 11:24:23 2008
@@ -126,7 +126,10 @@
         g = pgen.generate_grammar(gt)
         if save:
             logger.info("Writing grammar tables to %s", gp)
-            g.dump(gp)
+            try:
+                g.dump(gp)
+            except IOError, e:
+                logger.info("Writing failed:"+str(e))
     else:
         g = grammar.Grammar()
         g.load(gp)

Modified: python/branches/okkoto-sizeof/Lib/lib2to3/tests/test_fixers.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/lib2to3/tests/test_fixers.py	(original)
+++ python/branches/okkoto-sizeof/Lib/lib2to3/tests/test_fixers.py	Wed Jun  4 11:24:23 2008
@@ -1405,14 +1405,12 @@
         s = "foo(xreadlines)"
         self.unchanged(s)
 
-class Test_imports(FixerTestCase):
+# Disable test, as it takes a too long time to run, and also
+# fails in 2.6.
+#class Test_imports(FixerTestCase):
+class Test_imports:
     fixer = "imports"
-
-    modules = {"StringIO":  ("io", ["StringIO"]),
-               "cStringIO": ("io", ["StringIO"]),
-               "__builtin__" : ("builtins", ["open", "Exception",
-                   "__debug__", "str"]),
-              }
+    from ..fixes.fix_imports import MAPPING as modules
 
     def test_import_module(self):
         for old, (new, members) in self.modules.items():
@@ -1434,6 +1432,13 @@
                 s = "from foo import %s" % member
                 self.unchanged(s)
 
+            b = "from %s import %s" % (old, ", ".join(members))
+            a = "from %s import %s" % (new, ", ".join(members))
+            self.check(b, a)
+
+            s = "from foo import %s" % ", ".join(members)
+            self.unchanged(s)
+
     def test_import_module_as(self):
         for old, (new, members) in self.modules.items():
             b = "import %s as foo_bar" % old
@@ -1481,6 +1486,16 @@
                     foo(%s, %s())
                     """ % (new, member, member, member)
                 self.check(b, a)
+            b = """
+                from %s import %s
+                foo(%s)
+                """ % (old, ", ".join(members), ", ".join(members))
+            a = """
+                from %s import %s
+                foo(%s)
+                """ % (new, ", ".join(members), ", ".join(members))
+            self.check(b, a)
+
 
 class Test_input(FixerTestCase):
     fixer = "input"

Modified: python/branches/okkoto-sizeof/Lib/locale.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/locale.py	(original)
+++ python/branches/okkoto-sizeof/Lib/locale.py	Wed Jun  4 11:24:23 2008
@@ -615,6 +615,33 @@
 #    updated 'zh_cn.big5' -> 'zh_TW.eucTW' to 'zh_TW.big5'
 #    updated 'zh_tw' -> 'zh_TW.eucTW' to 'zh_TW.big5'
 #
+# MAL 2008-05-30:
+# Updated alias mapping to most recent locale.alias file
+# from X.org distribution using makelocalealias.py.
+#
+# These are the differences compared to the old mapping (Python 2.5
+# and older):
+#
+#    updated 'cs_cs.iso88592' -> 'cs_CZ.ISO8859-2' to 'cs_CS.ISO8859-2'
+#    updated 'serbocroatian' -> 'sh_YU.ISO8859-2' to 'sr_CS.ISO8859-2'
+#    updated 'sh' -> 'sh_YU.ISO8859-2' to 'sr_CS.ISO8859-2'
+#    updated 'sh_hr.iso88592' -> 'sh_HR.ISO8859-2' to 'hr_HR.ISO8859-2'
+#    updated 'sh_sp' -> 'sh_YU.ISO8859-2' to 'sr_CS.ISO8859-2'
+#    updated 'sh_yu' -> 'sh_YU.ISO8859-2' to 'sr_CS.ISO8859-2'
+#    updated 'sp' -> 'sp_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sp_yu' -> 'sp_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sr' -> 'sr_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sr at cyrillic' -> 'sr_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sr_sp' -> 'sr_SP.ISO8859-2' to 'sr_CS.ISO8859-2'
+#    updated 'sr_yu' -> 'sr_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sr_yu.cp1251 at cyrillic' -> 'sr_YU.CP1251' to 'sr_CS.CP1251'
+#    updated 'sr_yu.iso88592' -> 'sr_YU.ISO8859-2' to 'sr_CS.ISO8859-2'
+#    updated 'sr_yu.iso88595' -> 'sr_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sr_yu.iso88595 at cyrillic' -> 'sr_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+#    updated 'sr_yu.microsoftcp1251 at cyrillic' -> 'sr_YU.CP1251' to 'sr_CS.CP1251'
+#    updated 'sr_yu.utf8 at cyrillic' -> 'sr_YU.UTF-8' to 'sr_CS.UTF-8'
+#    updated 'sr_yu at cyrillic' -> 'sr_YU.ISO8859-5' to 'sr_CS.ISO8859-5'
+
 locale_alias = {
     'a3':                                   'a3_AZ.KOI8-C',
     'a3_az':                                'a3_AZ.KOI8-C',
@@ -623,30 +650,46 @@
     'af_za':                                'af_ZA.ISO8859-1',
     'af_za.iso88591':                       'af_ZA.ISO8859-1',
     'am':                                   'am_ET.UTF-8',
+    'am_et':                                'am_ET.UTF-8',
     'american':                             'en_US.ISO8859-1',
     'american.iso88591':                    'en_US.ISO8859-1',
     'ar':                                   'ar_AA.ISO8859-6',
     'ar_aa':                                'ar_AA.ISO8859-6',
     'ar_aa.iso88596':                       'ar_AA.ISO8859-6',
     'ar_ae':                                'ar_AE.ISO8859-6',
+    'ar_ae.iso88596':                       'ar_AE.ISO8859-6',
     'ar_bh':                                'ar_BH.ISO8859-6',
+    'ar_bh.iso88596':                       'ar_BH.ISO8859-6',
     'ar_dz':                                'ar_DZ.ISO8859-6',
+    'ar_dz.iso88596':                       'ar_DZ.ISO8859-6',
     'ar_eg':                                'ar_EG.ISO8859-6',
     'ar_eg.iso88596':                       'ar_EG.ISO8859-6',
     'ar_iq':                                'ar_IQ.ISO8859-6',
+    'ar_iq.iso88596':                       'ar_IQ.ISO8859-6',
     'ar_jo':                                'ar_JO.ISO8859-6',
+    'ar_jo.iso88596':                       'ar_JO.ISO8859-6',
     'ar_kw':                                'ar_KW.ISO8859-6',
+    'ar_kw.iso88596':                       'ar_KW.ISO8859-6',
     'ar_lb':                                'ar_LB.ISO8859-6',
+    'ar_lb.iso88596':                       'ar_LB.ISO8859-6',
     'ar_ly':                                'ar_LY.ISO8859-6',
+    'ar_ly.iso88596':                       'ar_LY.ISO8859-6',
     'ar_ma':                                'ar_MA.ISO8859-6',
+    'ar_ma.iso88596':                       'ar_MA.ISO8859-6',
     'ar_om':                                'ar_OM.ISO8859-6',
+    'ar_om.iso88596':                       'ar_OM.ISO8859-6',
     'ar_qa':                                'ar_QA.ISO8859-6',
+    'ar_qa.iso88596':                       'ar_QA.ISO8859-6',
     'ar_sa':                                'ar_SA.ISO8859-6',
     'ar_sa.iso88596':                       'ar_SA.ISO8859-6',
     'ar_sd':                                'ar_SD.ISO8859-6',
+    'ar_sd.iso88596':                       'ar_SD.ISO8859-6',
     'ar_sy':                                'ar_SY.ISO8859-6',
+    'ar_sy.iso88596':                       'ar_SY.ISO8859-6',
     'ar_tn':                                'ar_TN.ISO8859-6',
+    'ar_tn.iso88596':                       'ar_TN.ISO8859-6',
     'ar_ye':                                'ar_YE.ISO8859-6',
+    'ar_ye.iso88596':                       'ar_YE.ISO8859-6',
     'arabic':                               'ar_AA.ISO8859-6',
     'arabic.iso88596':                      'ar_AA.ISO8859-6',
     'az':                                   'az_AZ.ISO8859-9E',
@@ -662,6 +705,7 @@
     'bg_bg.iso88595':                       'bg_BG.ISO8859-5',
     'bg_bg.koi8r':                          'bg_BG.KOI8-R',
     'bg_bg.microsoftcp1251':                'bg_BG.CP1251',
+    'bn_in':                                'bn_IN.UTF-8',
     'bokmal':                               'nb_NO.ISO8859-1',
     'bokm\xe5l':                            'nb_NO.ISO8859-1',
     'br':                                   'br_FR.ISO8859-1',
@@ -669,7 +713,12 @@
     'br_fr.iso88591':                       'br_FR.ISO8859-1',
     'br_fr.iso885914':                      'br_FR.ISO8859-14',
     'br_fr.iso885915':                      'br_FR.ISO8859-15',
+    'br_fr.iso885915 at euro':                 'br_FR.ISO8859-15',
+    'br_fr.utf8 at euro':                      'br_FR.UTF-8',
     'br_fr at euro':                           'br_FR.ISO8859-15',
+    'bs':                                   'bs_BA.ISO8859-2',
+    'bs_ba':                                'bs_BA.ISO8859-2',
+    'bs_ba.iso88592':                       'bs_BA.ISO8859-2',
     'bulgarian':                            'bg_BG.CP1251',
     'c':                                    'C',
     'c-french':                             'fr_CA.ISO8859-1',
@@ -682,6 +731,8 @@
     'ca_es':                                'ca_ES.ISO8859-1',
     'ca_es.iso88591':                       'ca_ES.ISO8859-1',
     'ca_es.iso885915':                      'ca_ES.ISO8859-15',
+    'ca_es.iso885915 at euro':                 'ca_ES.ISO8859-15',
+    'ca_es.utf8 at euro':                      'ca_ES.UTF-8',
     'ca_es at euro':                           'ca_ES.ISO8859-15',
     'catalan':                              'ca_ES.ISO8859-1',
     'cextend':                              'en_US.ISO8859-1',
@@ -691,7 +742,7 @@
     'croatian':                             'hr_HR.ISO8859-2',
     'cs':                                   'cs_CZ.ISO8859-2',
     'cs_cs':                                'cs_CZ.ISO8859-2',
-    'cs_cs.iso88592':                       'cs_CZ.ISO8859-2',
+    'cs_cs.iso88592':                       'cs_CS.ISO8859-2',
     'cs_cz':                                'cs_CZ.ISO8859-2',
     'cs_cz.iso88592':                       'cs_CZ.ISO8859-2',
     'cy':                                   'cy_GB.ISO8859-1',
@@ -717,10 +768,14 @@
     'de_at':                                'de_AT.ISO8859-1',
     'de_at.iso88591':                       'de_AT.ISO8859-1',
     'de_at.iso885915':                      'de_AT.ISO8859-15',
+    'de_at.iso885915 at euro':                 'de_AT.ISO8859-15',
+    'de_at.utf8 at euro':                      'de_AT.UTF-8',
     'de_at at euro':                           'de_AT.ISO8859-15',
     'de_be':                                'de_BE.ISO8859-1',
     'de_be.iso88591':                       'de_BE.ISO8859-1',
     'de_be.iso885915':                      'de_BE.ISO8859-15',
+    'de_be.iso885915 at euro':                 'de_BE.ISO8859-15',
+    'de_be.utf8 at euro':                      'de_BE.UTF-8',
     'de_be at euro':                           'de_BE.ISO8859-15',
     'de_ch':                                'de_CH.ISO8859-1',
     'de_ch.iso88591':                       'de_CH.ISO8859-1',
@@ -732,10 +787,14 @@
     'de_de.885915 at euro':                    'de_DE.ISO8859-15',
     'de_de.iso88591':                       'de_DE.ISO8859-1',
     'de_de.iso885915':                      'de_DE.ISO8859-15',
+    'de_de.iso885915 at euro':                 'de_DE.ISO8859-15',
+    'de_de.utf8 at euro':                      'de_DE.UTF-8',
     'de_de at euro':                           'de_DE.ISO8859-15',
     'de_lu':                                'de_LU.ISO8859-1',
     'de_lu.iso88591':                       'de_LU.ISO8859-1',
     'de_lu.iso885915':                      'de_LU.ISO8859-15',
+    'de_lu.iso885915 at euro':                 'de_LU.ISO8859-15',
+    'de_lu.utf8 at euro':                      'de_LU.UTF-8',
     'de_lu at euro':                           'de_LU.ISO8859-15',
     'deutsch':                              'de_DE.ISO8859-1',
     'dutch':                                'nl_NL.ISO8859-1',
@@ -755,6 +814,7 @@
     'en_be':                                'en_BE.ISO8859-1',
     'en_be at euro':                           'en_BE.ISO8859-15',
     'en_bw':                                'en_BW.ISO8859-1',
+    'en_bw.iso88591':                       'en_BW.ISO8859-1',
     'en_ca':                                'en_CA.ISO8859-1',
     'en_ca.iso88591':                       'en_CA.ISO8859-1',
     'en_gb':                                'en_GB.ISO8859-1',
@@ -763,15 +823,20 @@
     'en_gb.iso885915':                      'en_GB.ISO8859-15',
     'en_gb at euro':                           'en_GB.ISO8859-15',
     'en_hk':                                'en_HK.ISO8859-1',
+    'en_hk.iso88591':                       'en_HK.ISO8859-1',
     'en_ie':                                'en_IE.ISO8859-1',
     'en_ie.iso88591':                       'en_IE.ISO8859-1',
     'en_ie.iso885915':                      'en_IE.ISO8859-15',
+    'en_ie.iso885915 at euro':                 'en_IE.ISO8859-15',
+    'en_ie.utf8 at euro':                      'en_IE.UTF-8',
     'en_ie at euro':                           'en_IE.ISO8859-15',
     'en_in':                                'en_IN.ISO8859-1',
     'en_nz':                                'en_NZ.ISO8859-1',
     'en_nz.iso88591':                       'en_NZ.ISO8859-1',
     'en_ph':                                'en_PH.ISO8859-1',
+    'en_ph.iso88591':                       'en_PH.ISO8859-1',
     'en_sg':                                'en_SG.ISO8859-1',
+    'en_sg.iso88591':                       'en_SG.ISO8859-1',
     'en_uk':                                'en_GB.ISO8859-1',
     'en_us':                                'en_US.ISO8859-1',
     'en_us.88591':                          'en_US.ISO8859-1',
@@ -787,6 +852,7 @@
     'en_za.iso885915':                      'en_ZA.ISO8859-15',
     'en_za at euro':                           'en_ZA.ISO8859-15',
     'en_zw':                                'en_ZW.ISO8859-1',
+    'en_zw.iso88591':                       'en_ZW.ISO8859-1',
     'eng_gb':                               'en_GB.ISO8859-1',
     'eng_gb.8859':                          'en_GB.ISO8859-1',
     'english':                              'en_EN.ISO8859-1',
@@ -822,6 +888,8 @@
     'es_es.88591':                          'es_ES.ISO8859-1',
     'es_es.iso88591':                       'es_ES.ISO8859-1',
     'es_es.iso885915':                      'es_ES.ISO8859-15',
+    'es_es.iso885915 at euro':                 'es_ES.ISO8859-15',
+    'es_es.utf8 at euro':                      'es_ES.UTF-8',
     'es_es at euro':                           'es_ES.ISO8859-15',
     'es_gt':                                'es_GT.ISO8859-1',
     'es_gt.iso88591':                       'es_GT.ISO8859-1',
@@ -850,6 +918,7 @@
     'es_sv.iso885915':                      'es_SV.ISO8859-15',
     'es_sv at euro':                           'es_SV.ISO8859-15',
     'es_us':                                'es_US.ISO8859-1',
+    'es_us.iso88591':                       'es_US.ISO8859-1',
     'es_uy':                                'es_UY.ISO8859-1',
     'es_uy.iso88591':                       'es_UY.ISO8859-1',
     'es_uy.iso885915':                      'es_UY.ISO8859-15',
@@ -870,6 +939,8 @@
     'eu_es':                                'eu_ES.ISO8859-1',
     'eu_es.iso88591':                       'eu_ES.ISO8859-1',
     'eu_es.iso885915':                      'eu_ES.ISO8859-15',
+    'eu_es.iso885915 at euro':                 'eu_ES.ISO8859-15',
+    'eu_es.utf8 at euro':                      'eu_ES.UTF-8',
     'eu_es at euro':                           'eu_ES.ISO8859-15',
     'fa':                                   'fa_IR.UTF-8',
     'fa_ir':                                'fa_IR.UTF-8',
@@ -879,6 +950,7 @@
     'fi_fi.88591':                          'fi_FI.ISO8859-1',
     'fi_fi.iso88591':                       'fi_FI.ISO8859-1',
     'fi_fi.iso885915':                      'fi_FI.ISO8859-15',
+    'fi_fi.iso885915 at euro':                 'fi_FI.ISO8859-15',
     'fi_fi.utf8 at euro':                      'fi_FI.UTF-8',
     'fi_fi at euro':                           'fi_FI.ISO8859-15',
     'finnish':                              'fi_FI.ISO8859-1',
@@ -893,6 +965,8 @@
     'fr_be.88591':                          'fr_BE.ISO8859-1',
     'fr_be.iso88591':                       'fr_BE.ISO8859-1',
     'fr_be.iso885915':                      'fr_BE.ISO8859-15',
+    'fr_be.iso885915 at euro':                 'fr_BE.ISO8859-15',
+    'fr_be.utf8 at euro':                      'fr_BE.UTF-8',
     'fr_be at euro':                           'fr_BE.ISO8859-15',
     'fr_ca':                                'fr_CA.ISO8859-1',
     'fr_ca.88591':                          'fr_CA.ISO8859-1',
@@ -908,11 +982,15 @@
     'fr_fr.88591':                          'fr_FR.ISO8859-1',
     'fr_fr.iso88591':                       'fr_FR.ISO8859-1',
     'fr_fr.iso885915':                      'fr_FR.ISO8859-15',
+    'fr_fr.iso885915 at euro':                 'fr_FR.ISO8859-15',
+    'fr_fr.utf8 at euro':                      'fr_FR.UTF-8',
     'fr_fr at euro':                           'fr_FR.ISO8859-15',
     'fr_lu':                                'fr_LU.ISO8859-1',
     'fr_lu.88591':                          'fr_LU.ISO8859-1',
     'fr_lu.iso88591':                       'fr_LU.ISO8859-1',
     'fr_lu.iso885915':                      'fr_LU.ISO8859-15',
+    'fr_lu.iso885915 at euro':                 'fr_LU.ISO8859-15',
+    'fr_lu.utf8 at euro':                      'fr_LU.UTF-8',
     'fr_lu at euro':                           'fr_LU.ISO8859-15',
     'fran\xe7ais':                          'fr_FR.ISO8859-1',
     'fre_fr':                               'fr_FR.ISO8859-1',
@@ -926,6 +1004,8 @@
     'ga_ie.iso88591':                       'ga_IE.ISO8859-1',
     'ga_ie.iso885914':                      'ga_IE.ISO8859-14',
     'ga_ie.iso885915':                      'ga_IE.ISO8859-15',
+    'ga_ie.iso885915 at euro':                 'ga_IE.ISO8859-15',
+    'ga_ie.utf8 at euro':                      'ga_IE.UTF-8',
     'ga_ie at euro':                           'ga_IE.ISO8859-15',
     'galego':                               'gl_ES.ISO8859-1',
     'galician':                             'gl_ES.ISO8859-1',
@@ -945,9 +1025,12 @@
     'gl_es':                                'gl_ES.ISO8859-1',
     'gl_es.iso88591':                       'gl_ES.ISO8859-1',
     'gl_es.iso885915':                      'gl_ES.ISO8859-15',
+    'gl_es.iso885915 at euro':                 'gl_ES.ISO8859-15',
+    'gl_es.utf8 at euro':                      'gl_ES.UTF-8',
     'gl_es at euro':                           'gl_ES.ISO8859-15',
     'greek':                                'el_GR.ISO8859-7',
     'greek.iso88597':                       'el_GR.ISO8859-7',
+    'gu_in':                                'gu_IN.UTF-8',
     'gv':                                   'gv_GB.ISO8859-1',
     'gv_gb':                                'gv_GB.ISO8859-1',
     'gv_gb.iso88591':                       'gv_GB.ISO8859-1',
@@ -998,6 +1081,8 @@
     'it_it.88591':                          'it_IT.ISO8859-1',
     'it_it.iso88591':                       'it_IT.ISO8859-1',
     'it_it.iso885915':                      'it_IT.ISO8859-15',
+    'it_it.iso885915 at euro':                 'it_IT.ISO8859-15',
+    'it_it.utf8 at euro':                      'it_IT.UTF-8',
     'it_it at euro':                           'it_IT.ISO8859-15',
     'italian':                              'it_IT.ISO8859-1',
     'italian.iso88591':                     'it_IT.ISO8859-1',
@@ -1037,6 +1122,8 @@
     'kl_gl.iso88591':                       'kl_GL.ISO8859-1',
     'kl_gl.iso885915':                      'kl_GL.ISO8859-15',
     'kl_gl at euro':                           'kl_GL.ISO8859-15',
+    'km_kh':                                'km_KH.UTF-8',
+    'kn_in':                                'kn_IN.UTF-8',
     'ko':                                   'ko_KR.eucKR',
     'ko_kr':                                'ko_KR.eucKR',
     'ko_kr.euc':                            'ko_KR.eucKR',
@@ -1049,6 +1136,8 @@
     'kw_gb.iso885914':                      'kw_GB.ISO8859-14',
     'kw_gb.iso885915':                      'kw_GB.ISO8859-15',
     'kw_gb at euro':                           'kw_GB.ISO8859-15',
+    'ky':                                   'ky_KG.UTF-8',
+    'ky_kg':                                'ky_KG.UTF-8',
     'lithuanian':                           'lt_LT.ISO8859-13',
     'lo':                                   'lo_LA.MULELAO-1',
     'lo_la':                                'lo_LA.MULELAO-1',
@@ -1071,6 +1160,7 @@
     'mk_mk.cp1251':                         'mk_MK.CP1251',
     'mk_mk.iso88595':                       'mk_MK.ISO8859-5',
     'mk_mk.microsoftcp1251':                'mk_MK.CP1251',
+    'mr_in':                                'mr_IN.UTF-8',
     'ms':                                   'ms_MY.ISO8859-1',
     'ms_my':                                'ms_MY.ISO8859-1',
     'ms_my.iso88591':                       'ms_MY.ISO8859-1',
@@ -1088,11 +1178,15 @@
     'nl_be.88591':                          'nl_BE.ISO8859-1',
     'nl_be.iso88591':                       'nl_BE.ISO8859-1',
     'nl_be.iso885915':                      'nl_BE.ISO8859-15',
+    'nl_be.iso885915 at euro':                 'nl_BE.ISO8859-15',
+    'nl_be.utf8 at euro':                      'nl_BE.UTF-8',
     'nl_be at euro':                           'nl_BE.ISO8859-15',
     'nl_nl':                                'nl_NL.ISO8859-1',
     'nl_nl.88591':                          'nl_NL.ISO8859-1',
     'nl_nl.iso88591':                       'nl_NL.ISO8859-1',
     'nl_nl.iso885915':                      'nl_NL.ISO8859-15',
+    'nl_nl.iso885915 at euro':                 'nl_NL.ISO8859-15',
+    'nl_nl.utf8 at euro':                      'nl_NL.UTF-8',
     'nl_nl at euro':                           'nl_NL.ISO8859-15',
     'nn':                                   'nn_NO.ISO8859-1',
     'nn_no':                                'nn_NO.ISO8859-1',
@@ -1109,6 +1203,12 @@
     'no_no at euro':                           'no_NO.ISO8859-15',
     'norwegian':                            'no_NO.ISO8859-1',
     'norwegian.iso88591':                   'no_NO.ISO8859-1',
+    'nr':                                   'nr_ZA.ISO8859-1',
+    'nr_za':                                'nr_ZA.ISO8859-1',
+    'nr_za.iso88591':                       'nr_ZA.ISO8859-1',
+    'nso':                                  'nso_ZA.ISO8859-15',
+    'nso_za':                               'nso_ZA.ISO8859-15',
+    'nso_za.iso885915':                     'nso_ZA.ISO8859-15',
     'ny':                                   'ny_NO.ISO8859-1',
     'ny_no':                                'ny_NO.ISO8859-1',
     'ny_no.88591':                          'ny_NO.ISO8859-1',
@@ -1121,6 +1221,7 @@
     'oc_fr.iso88591':                       'oc_FR.ISO8859-1',
     'oc_fr.iso885915':                      'oc_FR.ISO8859-15',
     'oc_fr at euro':                           'oc_FR.ISO8859-15',
+    'pa_in':                                'pa_IN.UTF-8',
     'pd':                                   'pd_US.ISO8859-1',
     'pd_de':                                'pd_DE.ISO8859-1',
     'pd_de.iso88591':                       'pd_DE.ISO8859-1',
@@ -1156,6 +1257,7 @@
     'pt_pt.88591':                          'pt_PT.ISO8859-1',
     'pt_pt.iso88591':                       'pt_PT.ISO8859-1',
     'pt_pt.iso885915':                      'pt_PT.ISO8859-15',
+    'pt_pt.iso885915 at euro':                 'pt_PT.ISO8859-15',
     'pt_pt.utf8 at euro':                      'pt_PT.UTF-8',
     'pt_pt at euro':                           'pt_PT.ISO8859-15',
     'ro':                                   'ro_RO.ISO8859-2',
@@ -1174,13 +1276,19 @@
     'ru_ua.microsoftcp1251':                'ru_UA.CP1251',
     'rumanian':                             'ro_RO.ISO8859-2',
     'russian':                              'ru_RU.ISO8859-5',
+    'rw':                                   'rw_RW.ISO8859-1',
+    'rw_rw':                                'rw_RW.ISO8859-1',
+    'rw_rw.iso88591':                       'rw_RW.ISO8859-1',
     'se_no':                                'se_NO.UTF-8',
-    'serbocroatian':                        'sh_YU.ISO8859-2',
-    'sh':                                   'sh_YU.ISO8859-2',
+    'serbocroatian':                        'sr_CS.ISO8859-2',
+    'sh':                                   'sr_CS.ISO8859-2',
     'sh_hr':                                'sh_HR.ISO8859-2',
-    'sh_hr.iso88592':                       'sh_HR.ISO8859-2',
-    'sh_sp':                                'sh_YU.ISO8859-2',
-    'sh_yu':                                'sh_YU.ISO8859-2',
+    'sh_hr.iso88592':                       'hr_HR.ISO8859-2',
+    'sh_sp':                                'sr_CS.ISO8859-2',
+    'sh_yu':                                'sr_CS.ISO8859-2',
+    'si':                                   'si_LK.UTF-8',
+    'si_lk':                                'si_LK.UTF-8',
+    'sinhala':                              'si_LK.UTF-8',
     'sk':                                   'sk_SK.ISO8859-2',
     'sk_sk':                                'sk_SK.ISO8859-2',
     'sk_sk.iso88592':                       'sk_SK.ISO8859-2',
@@ -1191,8 +1299,8 @@
     'slovak':                               'sk_SK.ISO8859-2',
     'slovene':                              'sl_SI.ISO8859-2',
     'slovenian':                            'sl_SI.ISO8859-2',
-    'sp':                                   'sp_YU.ISO8859-5',
-    'sp_yu':                                'sp_YU.ISO8859-5',
+    'sp':                                   'sr_CS.ISO8859-5',
+    'sp_yu':                                'sr_CS.ISO8859-5',
     'spanish':                              'es_ES.ISO8859-1',
     'spanish.iso88591':                     'es_ES.ISO8859-1',
     'spanish_spain':                        'es_ES.ISO8859-1',
@@ -1200,21 +1308,35 @@
     'sq':                                   'sq_AL.ISO8859-2',
     'sq_al':                                'sq_AL.ISO8859-2',
     'sq_al.iso88592':                       'sq_AL.ISO8859-2',
-    'sr':                                   'sr_YU.ISO8859-5',
-    'sr at cyrillic':                          'sr_YU.ISO8859-5',
-    'sr_sp':                                'sr_SP.ISO8859-2',
-    'sr_yu':                                'sr_YU.ISO8859-5',
-    'sr_yu.cp1251 at cyrillic':                'sr_YU.CP1251',
-    'sr_yu.iso88592':                       'sr_YU.ISO8859-2',
-    'sr_yu.iso88595':                       'sr_YU.ISO8859-5',
-    'sr_yu.iso88595 at cyrillic':              'sr_YU.ISO8859-5',
-    'sr_yu.microsoftcp1251 at cyrillic':       'sr_YU.CP1251',
-    'sr_yu.utf8 at cyrillic':                  'sr_YU.UTF-8',
-    'sr_yu at cyrillic':                       'sr_YU.ISO8859-5',
+    'sr':                                   'sr_CS.ISO8859-5',
+    'sr at cyrillic':                          'sr_CS.ISO8859-5',
+    'sr at latn':                              'sr_CS.ISO8859-2',
+    'sr_cs.iso88592':                       'sr_CS.ISO8859-2',
+    'sr_cs.iso88592 at latn':                  'sr_CS.ISO8859-2',
+    'sr_cs.iso88595':                       'sr_CS.ISO8859-5',
+    'sr_cs.utf8 at latn':                      'sr_CS.UTF-8',
+    'sr_cs at latn':                           'sr_CS.ISO8859-2',
+    'sr_sp':                                'sr_CS.ISO8859-2',
+    'sr_yu':                                'sr_CS.ISO8859-5',
+    'sr_yu.cp1251 at cyrillic':                'sr_CS.CP1251',
+    'sr_yu.iso88592':                       'sr_CS.ISO8859-2',
+    'sr_yu.iso88595':                       'sr_CS.ISO8859-5',
+    'sr_yu.iso88595 at cyrillic':              'sr_CS.ISO8859-5',
+    'sr_yu.microsoftcp1251 at cyrillic':       'sr_CS.CP1251',
+    'sr_yu.utf8 at cyrillic':                  'sr_CS.UTF-8',
+    'sr_yu at cyrillic':                       'sr_CS.ISO8859-5',
+    'ss':                                   'ss_ZA.ISO8859-1',
+    'ss_za':                                'ss_ZA.ISO8859-1',
+    'ss_za.iso88591':                       'ss_ZA.ISO8859-1',
+    'st':                                   'st_ZA.ISO8859-1',
+    'st_za':                                'st_ZA.ISO8859-1',
+    'st_za.iso88591':                       'st_ZA.ISO8859-1',
     'sv':                                   'sv_SE.ISO8859-1',
     'sv_fi':                                'sv_FI.ISO8859-1',
     'sv_fi.iso88591':                       'sv_FI.ISO8859-1',
     'sv_fi.iso885915':                      'sv_FI.ISO8859-15',
+    'sv_fi.iso885915 at euro':                 'sv_FI.ISO8859-15',
+    'sv_fi.utf8 at euro':                      'sv_FI.UTF-8',
     'sv_fi at euro':                           'sv_FI.ISO8859-15',
     'sv_se':                                'sv_SE.ISO8859-1',
     'sv_se.88591':                          'sv_SE.ISO8859-1',
@@ -1239,9 +1361,15 @@
     'tl':                                   'tl_PH.ISO8859-1',
     'tl_ph':                                'tl_PH.ISO8859-1',
     'tl_ph.iso88591':                       'tl_PH.ISO8859-1',
+    'tn':                                   'tn_ZA.ISO8859-15',
+    'tn_za':                                'tn_ZA.ISO8859-15',
+    'tn_za.iso885915':                      'tn_ZA.ISO8859-15',
     'tr':                                   'tr_TR.ISO8859-9',
     'tr_tr':                                'tr_TR.ISO8859-9',
     'tr_tr.iso88599':                       'tr_TR.ISO8859-9',
+    'ts':                                   'ts_ZA.ISO8859-1',
+    'ts_za':                                'ts_ZA.ISO8859-1',
+    'ts_za.iso88591':                       'ts_ZA.ISO8859-1',
     'tt':                                   'tt_RU.TATAR-CYR',
     'tt_ru':                                'tt_RU.TATAR-CYR',
     'tt_ru.koi8c':                          'tt_RU.KOI8-C',
@@ -1263,6 +1391,11 @@
     'ur_pk.microsoftcp1256':                'ur_PK.CP1256',
     'uz':                                   'uz_UZ.UTF-8',
     'uz_uz':                                'uz_UZ.UTF-8',
+    'uz_uz.iso88591':                       'uz_UZ.ISO8859-1',
+    'uz_uz.utf8 at cyrillic':                  'uz_UZ.UTF-8',
+    'uz_uz at cyrillic':                       'uz_UZ.UTF-8',
+    've':                                   've_ZA.UTF-8',
+    've_za':                                've_ZA.UTF-8',
     'vi':                                   'vi_VN.TCVN',
     'vi_vn':                                'vi_VN.TCVN',
     'vi_vn.tcvn':                           'vi_VN.TCVN',
@@ -1273,7 +1406,11 @@
     'wa_be':                                'wa_BE.ISO8859-1',
     'wa_be.iso88591':                       'wa_BE.ISO8859-1',
     'wa_be.iso885915':                      'wa_BE.ISO8859-15',
+    'wa_be.iso885915 at euro':                 'wa_BE.ISO8859-15',
     'wa_be at euro':                           'wa_BE.ISO8859-15',
+    'xh':                                   'xh_ZA.ISO8859-1',
+    'xh_za':                                'xh_ZA.ISO8859-1',
+    'xh_za.iso88591':                       'xh_ZA.ISO8859-1',
     'yi':                                   'yi_US.CP1255',
     'yi_us':                                'yi_US.CP1255',
     'yi_us.cp1255':                         'yi_US.CP1255',
@@ -1291,6 +1428,10 @@
     'zh_tw':                                'zh_TW.big5',
     'zh_tw.big5':                           'zh_TW.big5',
     'zh_tw.euc':                            'zh_TW.eucTW',
+    'zh_tw.euctw':                          'zh_TW.eucTW',
+    'zu':                                   'zu_ZA.ISO8859-1',
+    'zu_za':                                'zu_ZA.ISO8859-1',
+    'zu_za.iso88591':                       'zu_ZA.ISO8859-1',
 }
 
 #

Modified: python/branches/okkoto-sizeof/Lib/logging/config.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/logging/config.py	(original)
+++ python/branches/okkoto-sizeof/Lib/logging/config.py	Wed Jun  4 11:24:23 2008
@@ -35,7 +35,7 @@
 except ImportError:
     thread = None
 
-from socketserver import ThreadingTCPServer, StreamRequestHandler
+from SocketServer import ThreadingTCPServer, StreamRequestHandler
 
 
 DEFAULT_LOGGING_CONFIG_PORT = 9030
@@ -65,9 +65,9 @@
     rather than a filename, in which case the file-like object will be read
     using readfp.
     """
-    import configparser
+    import ConfigParser
 
-    cp = configparser.ConfigParser(defaults)
+    cp = ConfigParser.ConfigParser(defaults)
     if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
         cp.readfp(fname)
     else:

Modified: python/branches/okkoto-sizeof/Lib/logging/handlers.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/logging/handlers.py	(original)
+++ python/branches/okkoto-sizeof/Lib/logging/handlers.py	Wed Jun  4 11:24:23 2008
@@ -156,10 +156,11 @@
     If backupCount is > 0, when rollover is done, no more than backupCount
     files are kept - the oldest ones are deleted.
     """
-    def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0):
+    def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0):
         BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
         self.when = string.upper(when)
         self.backupCount = backupCount
+        self.utc = utc
         # Calculate the real rollover interval, which is just the number of
         # seconds between rollovers.  Also set the filename suffix used when
         # a rollover occurs.  Current 'when' events supported:
@@ -214,7 +215,10 @@
         # the rest.  Note that this code doesn't care about leap seconds. :)
         if self.when == 'MIDNIGHT' or self.when.startswith('W'):
             # This could be done with less code, but I wanted it to be clear
-            t = time.localtime(currentTime)
+            if utc:
+                t = time.gmtime(currentTime)
+            else:
+                t = time.localtime(currentTime)
             currentHour = t[3]
             currentMinute = t[4]
             currentSecond = t[5]
@@ -245,13 +249,14 @@
                     else:
                         daysToWait = 6 - day + self.dayOfWeek + 1
                     newRolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
-                    dstNow = t[-1]
-                    dstAtRollover = time.localtime(newRolloverAt)[-1]
-                    if dstNow != dstAtRollover:
-                        if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
-                            newRolloverAt = newRolloverAt - 3600
-                        else:           # DST bows out before next rollover, so we need to add an hour
-                            newRolloverAt = newRolloverAt + 3600
+                    if not utc:
+                        dstNow = t[-1]
+                        dstAtRollover = time.localtime(newRolloverAt)[-1]
+                        if dstNow != dstAtRollover:
+                            if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
+                                newRolloverAt = newRolloverAt - 3600
+                            else:           # DST bows out before next rollover, so we need to add an hour
+                                newRolloverAt = newRolloverAt + 3600
                     self.rolloverAt = newRolloverAt
 
         #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime)
@@ -284,7 +289,7 @@
             if fileName[:plen] == prefix:
                 suffix = fileName[plen:]
                 if self.extMatch.match(suffix):
-                    result.append(fileName)
+                    result.append(os.path.join(dirName, fileName))
         result.sort()
         if len(result) < self.backupCount:
             result = []
@@ -303,7 +308,10 @@
         self.stream.close()
         # get the time that this sequence started at and make it a TimeTuple
         t = self.rolloverAt - self.interval
-        timeTuple = time.localtime(t)
+        if self.utc:
+            timeTuple = time.gmtime(t)
+        else:
+            timeTuple = time.localtime(t)
         dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
         if os.path.exists(dfn):
             os.remove(dfn)
@@ -324,7 +332,7 @@
         while newRolloverAt <= currentTime:
             newRolloverAt = newRolloverAt + self.interval
         #If DST changes and midnight or weekly rollover, adjust for this.
-        if self.when == 'MIDNIGHT' or self.when.startswith('W'):
+        if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
             dstNow = time.localtime(currentTime)[-1]
             dstAtRollover = time.localtime(newRolloverAt)[-1]
             if dstNow != dstAtRollover:

Modified: python/branches/okkoto-sizeof/Lib/os.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/os.py	(original)
+++ python/branches/okkoto-sizeof/Lib/os.py	Wed Jun  4 11:24:23 2008
@@ -715,7 +715,7 @@
             return p.stdin, p.stdout
         __all__.append("popen4")
 
-import copyreg as _copy_reg
+import copy_reg as _copy_reg
 
 def _make_stat_result(tup, dict):
     return stat_result(tup, dict)

Modified: python/branches/okkoto-sizeof/Lib/pdb.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/pdb.py	(original)
+++ python/branches/okkoto-sizeof/Lib/pdb.py	Wed Jun  4 11:24:23 2008
@@ -8,7 +8,7 @@
 import linecache
 import cmd
 import bdb
-from reprlib import Repr
+from repr import Repr
 import os
 import re
 import pprint

Modified: python/branches/okkoto-sizeof/Lib/pickle.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/pickle.py	(original)
+++ python/branches/okkoto-sizeof/Lib/pickle.py	Wed Jun  4 11:24:23 2008
@@ -27,8 +27,8 @@
 __version__ = "$Revision$"       # Code version
 
 from types import *
-from copyreg import dispatch_table
-from copyreg import _extension_registry, _inverted_registry, _extension_cache
+from copy_reg import dispatch_table
+from copy_reg import _extension_registry, _inverted_registry, _extension_cache
 import marshal
 import sys
 import struct
@@ -295,7 +295,7 @@
             self.save_global(obj)
             return
 
-        # Check copyreg.dispatch_table
+        # Check copy_reg.dispatch_table
         reduce = dispatch_table.get(t)
         if reduce:
             rv = reduce(obj)

Modified: python/branches/okkoto-sizeof/Lib/platform.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/platform.py	(original)
+++ python/branches/okkoto-sizeof/Lib/platform.py	Wed Jun  4 11:24:23 2008
@@ -733,7 +733,11 @@
             release = '%i.%i.%i' %(major, minor, patch)
         else:
             release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
+
     if sysu:
+        # NOTE: this block is left as documentation of the
+        # intention of this function, the 'sysu' gestalt is no
+        # longer available and there are no alternatives.
         major =  int((sysu & 0xFF000000L) >> 24)
         minor =  (sysu & 0x00F00000) >> 20
         bugfix = (sysu & 0x000F0000) >> 16
@@ -746,6 +750,8 @@
                  0x60:'beta',
                  0x80:'final'}.get(stage,'')
         versioninfo = (version,stage,nonrel)
+
+
     if sysa:
         machine = {0x1: '68k',
                    0x2: 'PowerPC',

Modified: python/branches/okkoto-sizeof/Lib/poplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/poplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/poplib.py	Wed Jun  4 11:24:23 2008
@@ -76,7 +76,8 @@
     """
 
 
-    def __init__(self, host, port=POP3_PORT, timeout=None):
+    def __init__(self, host, port=POP3_PORT,
+                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         self.host = host
         self.port = port
         self.sock = socket.create_connection((host, port), timeout)
@@ -240,7 +241,7 @@
 
 
     def rset(self):
-        """Not sure what this does."""
+        """Unmark all messages marked for deletion."""
         return self._shortcmd('RSET')
 
 

Modified: python/branches/okkoto-sizeof/Lib/pydoc.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/pydoc.py	(original)
+++ python/branches/okkoto-sizeof/Lib/pydoc.py	Wed Jun  4 11:24:23 2008
@@ -1,5 +1,5 @@
 #!/usr/bin/env python
-# -*- coding: Latin-1 -*-
+# -*- coding: latin-1 -*-
 """Generate Python documentation in HTML or text for interactive use.
 
 In the Python interpreter, do "from pydoc import help" to provide online
@@ -53,7 +53,7 @@
 #     path will be displayed.
 
 import sys, imp, os, re, types, inspect, __builtin__, pkgutil
-from reprlib import Repr
+from repr import Repr
 from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
 try:
     from collections import deque
@@ -1523,142 +1523,149 @@
     return
 
 class Helper:
+
+    # These dictionaries map a topic name to either an alias, or a tuple
+    # (label, seealso-items).  The "label" is the label of the corresponding
+    # section in the .rst file under Doc/ and an index into the dictionary
+    # in pydoc_topics.py.
+    #
+    # CAUTION: if you change one of these dictionaries, be sure to adapt the
+    #          list of needed labels in Doc/tools/sphinxext/pyspecific.py and
+    #          regenerate the pydoc_topics.py file by running
+    #              make pydoc-topics
+    #          in Doc/ and copying the output file into the Lib/ directory.
+
     keywords = {
         'and': 'BOOLEAN',
         'as': 'with',
-        'assert': ('ref/assert', ''),
-        'break': ('ref/break', 'while for'),
-        'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
-        'continue': ('ref/continue', 'while for'),
-        'def': ('ref/function', ''),
-        'del': ('ref/del', 'BASICMETHODS'),
+        'assert': ('assert', ''),
+        'break': ('break', 'while for'),
+        'class': ('class', 'CLASSES SPECIALMETHODS'),
+        'continue': ('continue', 'while for'),
+        'def': ('function', ''),
+        'del': ('del', 'BASICMETHODS'),
         'elif': 'if',
-        'else': ('ref/if', 'while for'),
-        'except': 'try',
-        'exec': ('ref/exec', ''),
-        'finally': 'try',
-        'for': ('ref/for', 'break continue while'),
-        'from': 'import',
-        'global': ('ref/global', 'NAMESPACES'),
-        'if': ('ref/if', 'TRUTHVALUE'),
-        'import': ('ref/import', 'MODULES'),
-        'in': ('ref/comparisons', 'SEQUENCEMETHODS2'),
+        'else': ('else', 'while for'),
+        'except': 'except',
+        'exec': ('exec', ''),
+        'finally': 'finally',
+        'for': ('for', 'break continue while'),
+        'from': 'from',
+        'global': ('global', 'NAMESPACES'),
+        'if': ('if', 'TRUTHVALUE'),
+        'import': ('import', 'MODULES'),
+        'in': ('in', 'SEQUENCEMETHODS2'),
         'is': 'COMPARISON',
-        'lambda': ('ref/lambdas', 'FUNCTIONS'),
+        'lambda': ('lambda', 'FUNCTIONS'),
         'not': 'BOOLEAN',
         'or': 'BOOLEAN',
-        'pass': ('ref/pass', ''),
-        'print': ('ref/print', ''),
-        'raise': ('ref/raise', 'EXCEPTIONS'),
-        'return': ('ref/return', 'FUNCTIONS'),
-        'try': ('ref/try', 'EXCEPTIONS'),
-        'while': ('ref/while', 'break continue if TRUTHVALUE'),
-        'with': ('ref/with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
-        'yield': ('ref/yield', ''),
+        'pass': ('pass', ''),
+        'print': ('print', ''),
+        'raise': ('raise', 'EXCEPTIONS'),
+        'return': ('return', 'FUNCTIONS'),
+        'try': ('try', 'EXCEPTIONS'),
+        'while': ('while', 'break continue if TRUTHVALUE'),
+        'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
+        'yield': ('yield', ''),
     }
 
     topics = {
-        'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
-        'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
-        'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'),
-        'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'),
-        'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
-        'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'),
-        'INTEGER': ('ref/integers', 'int range'),
-        'FLOAT': ('ref/floating', 'float math'),
-        'COMPLEX': ('ref/imaginary', 'complex cmath'),
-        'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
+        'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
+                  'FUNCTIONS CLASSES MODULES FILES inspect'),
+        'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING '
+                    'TYPES'),
+        'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
+        'FORMATTING': ('formatstrings', 'OPERATORS'),
+        'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
+                    'FORMATTING TYPES'),
+        'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
+        'INTEGER': ('integers', 'int range'),
+        'FLOAT': ('floating', 'float math'),
+        'COMPLEX': ('imaginary', 'complex cmath'),
+        'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
         'MAPPINGS': 'DICTIONARIES',
-        'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
-        'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
-        'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'),
-        'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'),
+        'FUNCTIONS': ('typesfunctions', 'def TYPES'),
+        'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
+        'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
+        'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
         'FRAMEOBJECTS': 'TYPES',
         'TRACEBACKS': 'TYPES',
-        'NONE': ('lib/bltin-null-object', ''),
-        'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'),
-        'FILES': ('lib/bltin-file-objects', ''),
-        'SPECIALATTRIBUTES': ('lib/specialattrs', ''),
-        'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'),
-        'MODULES': ('lib/typesmodules', 'import'),
+        'NONE': ('bltin-null-object', ''),
+        'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
+        'FILES': ('bltin-file-objects', ''),
+        'SPECIALATTRIBUTES': ('specialattrs', ''),
+        'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
+        'MODULES': ('typesmodules', 'import'),
         'PACKAGES': 'import',
-        'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
+        'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
+                        'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
+                        'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
+                        'LISTS DICTIONARIES BACKQUOTES'),
         'OPERATORS': 'EXPRESSIONS',
         'PRECEDENCE': 'EXPRESSIONS',
-        'OBJECTS': ('ref/objects', 'TYPES'),
-        'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
-        'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'),
-        'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
-        'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'),
-        'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
-        'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
-        'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'),
-        'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
-        'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
-        'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
-        'DYNAMICFEATURES': ('ref/dynamic-features', ''),
+        'OBJECTS': ('objects', 'TYPES'),
+        'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
+                           'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS '
+                           'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
+        'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'),
+        'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
+        'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
+        'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 '
+                             'SPECIALMETHODS'),
+        'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 '
+                             'SPECIALMETHODS'),
+        'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
+        'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
+                          'SPECIALMETHODS'),
+        'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
+        'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
+        'DYNAMICFEATURES': ('dynamic-features', ''),
         'SCOPING': 'NAMESPACES',
         'FRAMES': 'NAMESPACES',
-        'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'),
-        'COERCIONS': ('ref/coercion-rules','CONVERSIONS'),
-        'CONVERSIONS': ('ref/conversions', 'COERCIONS'),
-        'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'),
-        'SPECIALIDENTIFIERS': ('ref/id-classes', ''),
-        'PRIVATENAMES': ('ref/atom-identifiers', ''),
-        'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
+        'EXCEPTIONS': ('exceptions', 'try except finally raise'),
+        'COERCIONS': ('coercion-rules','CONVERSIONS'),
+        'CONVERSIONS': ('conversions', 'COERCIONS'),
+        'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
+        'SPECIALIDENTIFIERS': ('id-classes', ''),
+        'PRIVATENAMES': ('atom-identifiers', ''),
+        'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS '
+                     'TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
         'TUPLES': 'SEQUENCES',
-        'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'),
-        'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'),
-        'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'),
-        'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'),
-        'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'),
-        'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'),
-        'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
-        'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'),
-        'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'),
-        'CALLS': ('ref/calls', 'EXPRESSIONS'),
-        'POWER': ('ref/power', 'EXPRESSIONS'),
-        'UNARY': ('ref/unary', 'EXPRESSIONS'),
-        'BINARY': ('ref/binary', 'EXPRESSIONS'),
-        'SHIFTING': ('ref/shifting', 'EXPRESSIONS'),
-        'BITWISE': ('ref/bitwise', 'EXPRESSIONS'),
-        'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'),
-        'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'),
+        'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
+        'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
+        'LISTLITERALS': ('lists', 'LISTS LITERALS'),
+        'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
+        'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
+        'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'),
+        'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr '
+                       'ATTRIBUTEMETHODS'),
+        'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'),
+        'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'),
+        'CALLS': ('calls', 'EXPRESSIONS'),
+        'POWER': ('power', 'EXPRESSIONS'),
+        'UNARY': ('unary', 'EXPRESSIONS'),
+        'BINARY': ('binary', 'EXPRESSIONS'),
+        'SHIFTING': ('shifting', 'EXPRESSIONS'),
+        'BITWISE': ('bitwise', 'EXPRESSIONS'),
+        'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
+        'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
         'ASSERTION': 'assert',
-        'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'),
-        'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'),
+        'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
+        'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
         'DELETION': 'del',
         'PRINTING': 'print',
         'RETURNING': 'return',
         'IMPORTING': 'import',
         'CONDITIONAL': 'if',
-        'LOOPING': ('ref/compound', 'for while break continue'),
-        'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'),
-        'DEBUGGING': ('lib/module-pdb', 'pdb'),
-        'CONTEXTMANAGERS': ('ref/context-managers', 'with'),
+        'LOOPING': ('compound', 'for while break continue'),
+        'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
+        'DEBUGGING': ('debugger', 'pdb'),
+        'CONTEXTMANAGERS': ('context-managers', 'with'),
     }
 
     def __init__(self, input, output):
         self.input = input
         self.output = output
-        self.docdir = None
-        execdir = os.path.dirname(sys.executable)
-        homedir = os.environ.get('PYTHONHOME')
-        join = os.path.join
-        for dir in [os.environ.get('PYTHONDOCS'),
-                    homedir and os.path.join(homedir, 'doc'),
-                    join(execdir, 'doc'), # for Windows
-                    join(sys.prefix, 'doc/python-docs-' + split(sys.version)[0]),
-                    join(sys.prefix, 'doc/python-' + split(sys.version)[0]),
-                    join(sys.prefix, 'doc/python-docs-' + sys.version[:3]),
-                    join(sys.prefix, 'doc/python-' + sys.version[:3]),
-                    join(sys.prefix, 'Resources/English.lproj/Documentation')]:
-            if dir and os.path.isdir(join(dir, 'lib')):
-                self.docdir = dir
-                break
-            if dir and os.path.isdir(join(dir, 'html', 'lib')):
-                self.docdir = join(dir, 'html')
-                break
 
     def __repr__(self):
         if inspect.stack()[1][3] == '?':
@@ -1761,14 +1768,12 @@
         self.list(self.topics.keys())
 
     def showtopic(self, topic):
-        if not self.docdir:
+        try:
+            import pydoc_topics
+        except ImportError:
             self.output.write('''
-Sorry, topic and keyword documentation is not available because the Python
-HTML documentation files could not be found.  If you have installed them,
-please set the environment variable PYTHONDOCS to indicate their location.
-
-On the Microsoft Windows operating system, the files can be built by
-running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory.
+Sorry, topic and keyword documentation is not available because the
+module "pydoc_topics" could not be found.
 ''')
             return
         target = self.topics.get(topic, self.keywords.get(topic))
@@ -1778,31 +1783,15 @@
         if type(target) is type(''):
             return self.showtopic(target)
 
-        filename, xrefs = target
-        filename = self.docdir + '/' + filename + '.html'
+        label, xrefs = target
         try:
-            file = open(filename)
-        except:
-            self.output.write('could not read docs from %s\n' % filename)
+            doc = pydoc_topics.topics[label]
+        except KeyError:
+            self.output.write('no documentation found for %s\n' % repr(topic))
             return
-
-        divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S)
-        addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S)
-        document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
-        file.close()
-
-        import htmllib, formatter, StringIO
-        buffer = StringIO.StringIO()
-        parser = htmllib.HTMLParser(
-            formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
-        parser.start_table = parser.do_p
-        parser.end_table = lambda parser=parser: parser.do_p({})
-        parser.start_tr = parser.do_br
-        parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
-        parser.feed(document)
-        buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n  ')
-        pager('  ' + strip(buffer) + '\n')
+        pager(strip(doc) + '\n')
         if xrefs:
+            import StringIO, formatter
             buffer = StringIO.StringIO()
             formatter.DumbWriter(buffer).send_flowing_data(
                 'Related help topics: ' + join(split(xrefs), ', ') + '\n')

Deleted: python/branches/okkoto-sizeof/Lib/queue.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/queue.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,244 +0,0 @@
-"""A multi-producer, multi-consumer queue."""
-
-from time import time as _time
-from collections import deque
-import heapq
-
-__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
-
-class Empty(Exception):
-    "Exception raised by Queue.get(block=0)/get_nowait()."
-    pass
-
-class Full(Exception):
-    "Exception raised by Queue.put(block=0)/put_nowait()."
-    pass
-
-class Queue:
-    """Create a queue object with a given maximum size.
-
-    If maxsize is <= 0, the queue size is infinite.
-    """
-    def __init__(self, maxsize=0):
-        try:
-            import threading
-        except ImportError:
-            import dummy_threading as threading
-        self.maxsize = maxsize
-        self._init(maxsize)
-        # mutex must be held whenever the queue is mutating.  All methods
-        # that acquire mutex must release it before returning.  mutex
-        # is shared between the three conditions, so acquiring and
-        # releasing the conditions also acquires and releases mutex.
-        self.mutex = threading.Lock()
-        # Notify not_empty whenever an item is added to the queue; a
-        # thread waiting to get is notified then.
-        self.not_empty = threading.Condition(self.mutex)
-        # Notify not_full whenever an item is removed from the queue;
-        # a thread waiting to put is notified then.
-        self.not_full = threading.Condition(self.mutex)
-        # Notify all_tasks_done whenever the number of unfinished tasks
-        # drops to zero; thread waiting to join() is notified to resume
-        self.all_tasks_done = threading.Condition(self.mutex)
-        self.unfinished_tasks = 0
-
-    def task_done(self):
-        """Indicate that a formerly enqueued task is complete.
-
-        Used by Queue consumer threads.  For each get() used to fetch a task,
-        a subsequent call to task_done() tells the queue that the processing
-        on the task is complete.
-
-        If a join() is currently blocking, it will resume when all items
-        have been processed (meaning that a task_done() call was received
-        for every item that had been put() into the queue).
-
-        Raises a ValueError if called more times than there were items
-        placed in the queue.
-        """
-        self.all_tasks_done.acquire()
-        try:
-            unfinished = self.unfinished_tasks - 1
-            if unfinished <= 0:
-                if unfinished < 0:
-                    raise ValueError('task_done() called too many times')
-                self.all_tasks_done.notifyAll()
-            self.unfinished_tasks = unfinished
-        finally:
-            self.all_tasks_done.release()
-
-    def join(self):
-        """Blocks until all items in the Queue have been gotten and processed.
-
-        The count of unfinished tasks goes up whenever an item is added to the
-        queue. The count goes down whenever a consumer thread calls task_done()
-        to indicate the item was retrieved and all work on it is complete.
-
-        When the count of unfinished tasks drops to zero, join() unblocks.
-        """
-        self.all_tasks_done.acquire()
-        try:
-            while self.unfinished_tasks:
-                self.all_tasks_done.wait()
-        finally:
-            self.all_tasks_done.release()
-
-    def qsize(self):
-        """Return the approximate size of the queue (not reliable!)."""
-        self.mutex.acquire()
-        n = self._qsize()
-        self.mutex.release()
-        return n
-
-    def empty(self):
-        """Return True if the queue is empty, False otherwise (not reliable!)."""
-        self.mutex.acquire()
-        n = not self._qsize()
-        self.mutex.release()
-        return n
-
-    def full(self):
-        """Return True if the queue is full, False otherwise (not reliable!)."""
-        self.mutex.acquire()
-        n = 0 < self.maxsize == self._qsize()
-        self.mutex.release()
-        return n
-
-    def put(self, item, block=True, timeout=None):
-        """Put an item into the queue.
-
-        If optional args 'block' is true and 'timeout' is None (the default),
-        block if necessary until a free slot is available. If 'timeout' is
-        a positive number, it blocks at most 'timeout' seconds and raises
-        the Full exception if no free slot was available within that time.
-        Otherwise ('block' is false), put an item on the queue if a free slot
-        is immediately available, else raise the Full exception ('timeout'
-        is ignored in that case).
-        """
-        self.not_full.acquire()
-        try:
-            if self.maxsize > 0:
-                if not block:
-                    if self._qsize() == self.maxsize:
-                        raise Full
-                elif timeout is None:
-                    while self._qsize() == self.maxsize:
-                        self.not_full.wait()
-                elif timeout < 0:
-                    raise ValueError("'timeout' must be a positive number")
-                else:
-                    endtime = _time() + timeout
-                    while self._qsize() == self.maxsize:
-                        remaining = endtime - _time()
-                        if remaining <= 0.0:
-                            raise Full
-                        self.not_full.wait(remaining)
-            self._put(item)
-            self.unfinished_tasks += 1
-            self.not_empty.notify()
-        finally:
-            self.not_full.release()
-
-    def put_nowait(self, item):
-        """Put an item into the queue without blocking.
-
-        Only enqueue the item if a free slot is immediately available.
-        Otherwise raise the Full exception.
-        """
-        return self.put(item, False)
-
-    def get(self, block=True, timeout=None):
-        """Remove and return an item from the queue.
-
-        If optional args 'block' is true and 'timeout' is None (the default),
-        block if necessary until an item is available. If 'timeout' is
-        a positive number, it blocks at most 'timeout' seconds and raises
-        the Empty exception if no item was available within that time.
-        Otherwise ('block' is false), return an item if one is immediately
-        available, else raise the Empty exception ('timeout' is ignored
-        in that case).
-        """
-        self.not_empty.acquire()
-        try:
-            if not block:
-                if not self._qsize():
-                    raise Empty
-            elif timeout is None:
-                while not self._qsize():
-                    self.not_empty.wait()
-            elif timeout < 0:
-                raise ValueError("'timeout' must be a positive number")
-            else:
-                endtime = _time() + timeout
-                while not self._qsize():
-                    remaining = endtime - _time()
-                    if remaining <= 0.0:
-                        raise Empty
-                    self.not_empty.wait(remaining)
-            item = self._get()
-            self.not_full.notify()
-            return item
-        finally:
-            self.not_empty.release()
-
-    def get_nowait(self):
-        """Remove and return an item from the queue without blocking.
-
-        Only get an item if one is immediately available. Otherwise
-        raise the Empty exception.
-        """
-        return self.get(False)
-
-    # Override these methods to implement other queue organizations
-    # (e.g. stack or priority queue).
-    # These will only be called with appropriate locks held
-
-    # Initialize the queue representation
-    def _init(self, maxsize):
-        self.queue = deque()
-
-    def _qsize(self, len=len):
-        return len(self.queue)
-
-    # Put a new item in the queue
-    def _put(self, item):
-        self.queue.append(item)
-
-    # Get an item from the queue
-    def _get(self):
-        return self.queue.popleft()
-
-
-class PriorityQueue(Queue):
-    '''Variant of Queue that retrieves open entries in priority order (lowest first).
-
-    Entries are typically tuples of the form:  (priority number, data).
-    '''
-
-    def _init(self, maxsize):
-        self.queue = []
-
-    def _qsize(self, len=len):
-        return len(self.queue)
-
-    def _put(self, item, heappush=heapq.heappush):
-        heappush(self.queue, item)
-
-    def _get(self, heappop=heapq.heappop):
-        return heappop(self.queue)
-
-
-class LifoQueue(Queue):
-    '''Variant of Queue that retrieves most recently added entries first.'''
-
-    def _init(self, maxsize):
-        self.queue = []
-
-    def _qsize(self, len=len):
-        return len(self.queue)
-
-    def _put(self, item):
-        self.queue.append(item)
-
-    def _get(self):
-        return self.queue.pop()

Modified: python/branches/okkoto-sizeof/Lib/re.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/re.py	(original)
+++ python/branches/okkoto-sizeof/Lib/re.py	Wed Jun  4 11:24:23 2008
@@ -278,12 +278,12 @@
 
 # register myself for pickling
 
-import copyreg
+import copy_reg
 
 def _pickle(p):
     return _compile, (p.pattern, p.flags)
 
-copyreg.pickle(_pattern_type, _pickle, _compile)
+copy_reg.pickle(_pattern_type, _pickle, _compile)
 
 # --------------------------------------------------------------------
 # experimental stuff (see python-dev discussions for details)

Deleted: python/branches/okkoto-sizeof/Lib/reprlib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/reprlib.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,132 +0,0 @@
-"""Redo the builtin repr() (representation) but with limits on most sizes."""
-
-__all__ = ["Repr","repr"]
-
-import __builtin__
-from itertools import islice
-
-class Repr:
-
-    def __init__(self):
-        self.maxlevel = 6
-        self.maxtuple = 6
-        self.maxlist = 6
-        self.maxarray = 5
-        self.maxdict = 4
-        self.maxset = 6
-        self.maxfrozenset = 6
-        self.maxdeque = 6
-        self.maxstring = 30
-        self.maxlong = 40
-        self.maxother = 20
-
-    def repr(self, x):
-        return self.repr1(x, self.maxlevel)
-
-    def repr1(self, x, level):
-        typename = type(x).__name__
-        if ' ' in typename:
-            parts = typename.split()
-            typename = '_'.join(parts)
-        if hasattr(self, 'repr_' + typename):
-            return getattr(self, 'repr_' + typename)(x, level)
-        else:
-            s = __builtin__.repr(x)
-            if len(s) > self.maxother:
-                i = max(0, (self.maxother-3)//2)
-                j = max(0, self.maxother-3-i)
-                s = s[:i] + '...' + s[len(s)-j:]
-            return s
-
-    def _repr_iterable(self, x, level, left, right, maxiter, trail=''):
-        n = len(x)
-        if level <= 0 and n:
-            s = '...'
-        else:
-            newlevel = level - 1
-            repr1 = self.repr1
-            pieces = [repr1(elem, newlevel) for elem in islice(x, maxiter)]
-            if n > maxiter:  pieces.append('...')
-            s = ', '.join(pieces)
-            if n == 1 and trail:  right = trail + right
-        return '%s%s%s' % (left, s, right)
-
-    def repr_tuple(self, x, level):
-        return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',')
-
-    def repr_list(self, x, level):
-        return self._repr_iterable(x, level, '[', ']', self.maxlist)
-
-    def repr_array(self, x, level):
-        header = "array('%s', [" % x.typecode
-        return self._repr_iterable(x, level, header, '])', self.maxarray)
-
-    def repr_set(self, x, level):
-        x = _possibly_sorted(x)
-        return self._repr_iterable(x, level, 'set([', '])', self.maxset)
-
-    def repr_frozenset(self, x, level):
-        x = _possibly_sorted(x)
-        return self._repr_iterable(x, level, 'frozenset([', '])',
-                                   self.maxfrozenset)
-
-    def repr_deque(self, x, level):
-        return self._repr_iterable(x, level, 'deque([', '])', self.maxdeque)
-
-    def repr_dict(self, x, level):
-        n = len(x)
-        if n == 0: return '{}'
-        if level <= 0: return '{...}'
-        newlevel = level - 1
-        repr1 = self.repr1
-        pieces = []
-        for key in islice(_possibly_sorted(x), self.maxdict):
-            keyrepr = repr1(key, newlevel)
-            valrepr = repr1(x[key], newlevel)
-            pieces.append('%s: %s' % (keyrepr, valrepr))
-        if n > self.maxdict: pieces.append('...')
-        s = ', '.join(pieces)
-        return '{%s}' % (s,)
-
-    def repr_str(self, x, level):
-        s = __builtin__.repr(x[:self.maxstring])
-        if len(s) > self.maxstring:
-            i = max(0, (self.maxstring-3)//2)
-            j = max(0, self.maxstring-3-i)
-            s = __builtin__.repr(x[:i] + x[len(x)-j:])
-            s = s[:i] + '...' + s[len(s)-j:]
-        return s
-
-    def repr_long(self, x, level):
-        s = __builtin__.repr(x) # XXX Hope this isn't too slow...
-        if len(s) > self.maxlong:
-            i = max(0, (self.maxlong-3)//2)
-            j = max(0, self.maxlong-3-i)
-            s = s[:i] + '...' + s[len(s)-j:]
-        return s
-
-    def repr_instance(self, x, level):
-        try:
-            s = __builtin__.repr(x)
-            # Bugs in x.__repr__() can cause arbitrary
-            # exceptions -- then make up something
-        except Exception:
-            return '<%s instance at %x>' % (x.__class__.__name__, id(x))
-        if len(s) > self.maxstring:
-            i = max(0, (self.maxstring-3)//2)
-            j = max(0, self.maxstring-3-i)
-            s = s[:i] + '...' + s[len(s)-j:]
-        return s
-
-
-def _possibly_sorted(x):
-    # Since not all sequences of items can be sorted and comparison
-    # functions may raise arbitrary exceptions, return an unsorted
-    # sequence in that case.
-    try:
-        return sorted(x)
-    except Exception:
-        return list(x)
-
-aRepr = Repr()
-repr = aRepr.repr

Modified: python/branches/okkoto-sizeof/Lib/sgmllib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/sgmllib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/sgmllib.py	Wed Jun  4 11:24:23 2008
@@ -9,6 +9,11 @@
 # not supported at all.
 
 
+from warnings import warnpy3k
+warnpy3k("the sgmllib module has been removed in Python 3.0",
+         stacklevel=2)
+del warnpy3k
+
 import markupbase
 import re
 

Modified: python/branches/okkoto-sizeof/Lib/smtplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/smtplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/smtplib.py	Wed Jun  4 11:24:23 2008
@@ -220,7 +220,8 @@
     ehlo_resp = None
     does_esmtp = 0
 
-    def __init__(self, host='', port=0, local_hostname=None, timeout=None):
+    def __init__(self, host='', port=0, local_hostname=None,
+                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         """Initialize a new instance.
 
         If specified, `host' is the name of the remote host to which to
@@ -741,7 +742,8 @@
         certificate chain file for the SSL connection.
         """
         def __init__(self, host='', port=0, local_hostname=None,
-                     keyfile=None, certfile=None, timeout=None):
+                     keyfile=None, certfile=None,
+                     timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
             self.keyfile = keyfile
             self.certfile = certfile
             SMTP.__init__(self, host, port, local_hostname, timeout)

Modified: python/branches/okkoto-sizeof/Lib/socket.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/socket.py	(original)
+++ python/branches/okkoto-sizeof/Lib/socket.py	Wed Jun  4 11:24:23 2008
@@ -480,14 +480,17 @@
             raise StopIteration
         return line
 
+_GLOBAL_DEFAULT_TIMEOUT = object()
 
-def create_connection(address, timeout=None):
-    """Connect to address (host, port) with an optional timeout.
+def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
+    """Connect to *address* and return the socket object.
 
-    Provides access to socketobject timeout for higher-level
-    protocols.  Passing a timeout will set the timeout on the
-    socket instance (if not present, or passed as None, the
-    default global timeout setting will be used).
+    Convenience function.  Connect to *address* (a 2-tuple ``(host,
+    port)``) and return the socket object.  Passing the optional
+    *timeout* parameter will set the timeout on the socket instance
+    before attempting to connect.  If no *timeout* is supplied, the
+    global default timeout setting returned by :func:`getdefaulttimeout`
+    is used.
     """
 
     msg = "getaddrinfo returns an empty list"
@@ -497,7 +500,7 @@
         sock = None
         try:
             sock = socket(af, socktype, proto)
-            if timeout is not None:
+            if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
                 sock.settimeout(timeout)
             sock.connect(sa)
             return sock

Deleted: python/branches/okkoto-sizeof/Lib/socketserver.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/socketserver.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,681 +0,0 @@
-"""Generic socket server classes.
-
-This module tries to capture the various aspects of defining a server:
-
-For socket-based servers:
-
-- address family:
-        - AF_INET{,6}: IP (Internet Protocol) sockets (default)
-        - AF_UNIX: Unix domain sockets
-        - others, e.g. AF_DECNET are conceivable (see <socket.h>
-- socket type:
-        - SOCK_STREAM (reliable stream, e.g. TCP)
-        - SOCK_DGRAM (datagrams, e.g. UDP)
-
-For request-based servers (including socket-based):
-
-- client address verification before further looking at the request
-        (This is actually a hook for any processing that needs to look
-         at the request before anything else, e.g. logging)
-- how to handle multiple requests:
-        - synchronous (one request is handled at a time)
-        - forking (each request is handled by a new process)
-        - threading (each request is handled by a new thread)
-
-The classes in this module favor the server type that is simplest to
-write: a synchronous TCP/IP server.  This is bad class design, but
-save some typing.  (There's also the issue that a deep class hierarchy
-slows down method lookups.)
-
-There are five classes in an inheritance diagram, four of which represent
-synchronous servers of four types:
-
-        +------------+
-        | BaseServer |
-        +------------+
-              |
-              v
-        +-----------+        +------------------+
-        | TCPServer |------->| UnixStreamServer |
-        +-----------+        +------------------+
-              |
-              v
-        +-----------+        +--------------------+
-        | UDPServer |------->| UnixDatagramServer |
-        +-----------+        +--------------------+
-
-Note that UnixDatagramServer derives from UDPServer, not from
-UnixStreamServer -- the only difference between an IP and a Unix
-stream server is the address family, which is simply repeated in both
-unix server classes.
-
-Forking and threading versions of each type of server can be created
-using the ForkingMixIn and ThreadingMixIn mix-in classes.  For
-instance, a threading UDP server class is created as follows:
-
-        class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
-
-The Mix-in class must come first, since it overrides a method defined
-in UDPServer! Setting the various member variables also changes
-the behavior of the underlying server mechanism.
-
-To implement a service, you must derive a class from
-BaseRequestHandler and redefine its handle() method.  You can then run
-various versions of the service by combining one of the server classes
-with your request handler class.
-
-The request handler class must be different for datagram or stream
-services.  This can be hidden by using the request handler
-subclasses StreamRequestHandler or DatagramRequestHandler.
-
-Of course, you still have to use your head!
-
-For instance, it makes no sense to use a forking server if the service
-contains state in memory that can be modified by requests (since the
-modifications in the child process would never reach the initial state
-kept in the parent process and passed to each child).  In this case,
-you can use a threading server, but you will probably have to use
-locks to avoid two requests that come in nearly simultaneous to apply
-conflicting changes to the server state.
-
-On the other hand, if you are building e.g. an HTTP server, where all
-data is stored externally (e.g. in the file system), a synchronous
-class will essentially render the service "deaf" while one request is
-being handled -- which may be for a very long time if a client is slow
-to reqd all the data it has requested.  Here a threading or forking
-server is appropriate.
-
-In some cases, it may be appropriate to process part of a request
-synchronously, but to finish processing in a forked child depending on
-the request data.  This can be implemented by using a synchronous
-server and doing an explicit fork in the request handler class
-handle() method.
-
-Another approach to handling multiple simultaneous requests in an
-environment that supports neither threads nor fork (or where these are
-too expensive or inappropriate for the service) is to maintain an
-explicit table of partially finished requests and to use select() to
-decide which request to work on next (or whether to handle a new
-incoming request).  This is particularly important for stream services
-where each client can potentially be connected for a long time (if
-threads or subprocesses cannot be used).
-
-Future work:
-- Standard classes for Sun RPC (which uses either UDP or TCP)
-- Standard mix-in classes to implement various authentication
-  and encryption schemes
-- Standard framework for select-based multiplexing
-
-XXX Open problems:
-- What to do with out-of-band data?
-
-BaseServer:
-- split generic "request" functionality out into BaseServer class.
-  Copyright (C) 2000  Luke Kenneth Casson Leighton <lkcl at samba.org>
-
-  example: read entries from a SQL database (requires overriding
-  get_request() to return a table entry from the database).
-  entry is processed by a RequestHandlerClass.
-
-"""
-
-# Author of the BaseServer patch: Luke Kenneth Casson Leighton
-
-# XXX Warning!
-# There is a test suite for this module, but it cannot be run by the
-# standard regression test.
-# To run it manually, run Lib/test/test_socketserver.py.
-
-__version__ = "0.4"
-
-
-import socket
-import select
-import sys
-import os
-try:
-    import threading
-except ImportError:
-    import dummy_threading as threading
-
-__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
-           "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
-           "StreamRequestHandler","DatagramRequestHandler",
-           "ThreadingMixIn", "ForkingMixIn"]
-if hasattr(socket, "AF_UNIX"):
-    __all__.extend(["UnixStreamServer","UnixDatagramServer",
-                    "ThreadingUnixStreamServer",
-                    "ThreadingUnixDatagramServer"])
-
-class BaseServer:
-
-    """Base class for server classes.
-
-    Methods for the caller:
-
-    - __init__(server_address, RequestHandlerClass)
-    - serve_forever(poll_interval=0.5)
-    - shutdown()
-    - handle_request()  # if you do not use serve_forever()
-    - fileno() -> int   # for select()
-
-    Methods that may be overridden:
-
-    - server_bind()
-    - server_activate()
-    - get_request() -> request, client_address
-    - handle_timeout()
-    - verify_request(request, client_address)
-    - server_close()
-    - process_request(request, client_address)
-    - close_request(request)
-    - handle_error()
-
-    Methods for derived classes:
-
-    - finish_request(request, client_address)
-
-    Class variables that may be overridden by derived classes or
-    instances:
-
-    - timeout
-    - address_family
-    - socket_type
-    - allow_reuse_address
-
-    Instance variables:
-
-    - RequestHandlerClass
-    - socket
-
-    """
-
-    timeout = None
-
-    def __init__(self, server_address, RequestHandlerClass):
-        """Constructor.  May be extended, do not override."""
-        self.server_address = server_address
-        self.RequestHandlerClass = RequestHandlerClass
-        self.__is_shut_down = threading.Event()
-        self.__serving = False
-
-    def server_activate(self):
-        """Called by constructor to activate the server.
-
-        May be overridden.
-
-        """
-        pass
-
-    def serve_forever(self, poll_interval=0.5):
-        """Handle one request at a time until shutdown.
-
-        Polls for shutdown every poll_interval seconds. Ignores
-        self.timeout. If you need to do periodic tasks, do them in
-        another thread.
-        """
-        self.__serving = True
-        self.__is_shut_down.clear()
-        while self.__serving:
-            # XXX: Consider using another file descriptor or
-            # connecting to the socket to wake this up instead of
-            # polling. Polling reduces our responsiveness to a
-            # shutdown request and wastes cpu at all other times.
-            r, w, e = select.select([self], [], [], poll_interval)
-            if r:
-                self._handle_request_noblock()
-        self.__is_shut_down.set()
-
-    def shutdown(self):
-        """Stops the serve_forever loop.
-
-        Blocks until the loop has finished. This must be called while
-        serve_forever() is running in another thread, or it will
-        deadlock.
-        """
-        self.__serving = False
-        self.__is_shut_down.wait()
-
-    # The distinction between handling, getting, processing and
-    # finishing a request is fairly arbitrary.  Remember:
-    #
-    # - handle_request() is the top-level call.  It calls
-    #   select, get_request(), verify_request() and process_request()
-    # - get_request() is different for stream or datagram sockets
-    # - process_request() is the place that may fork a new process
-    #   or create a new thread to finish the request
-    # - finish_request() instantiates the request handler class;
-    #   this constructor will handle the request all by itself
-
-    def handle_request(self):
-        """Handle one request, possibly blocking.
-
-        Respects self.timeout.
-        """
-        # Support people who used socket.settimeout() to escape
-        # handle_request before self.timeout was available.
-        timeout = self.socket.gettimeout()
-        if timeout is None:
-            timeout = self.timeout
-        elif self.timeout is not None:
-            timeout = min(timeout, self.timeout)
-        fd_sets = select.select([self], [], [], timeout)
-        if not fd_sets[0]:
-            self.handle_timeout()
-            return
-        self._handle_request_noblock()
-
-    def _handle_request_noblock(self):
-        """Handle one request, without blocking.
-
-        I assume that select.select has returned that the socket is
-        readable before this function was called, so there should be
-        no risk of blocking in get_request().
-        """
-        try:
-            request, client_address = self.get_request()
-        except socket.error:
-            return
-        if self.verify_request(request, client_address):
-            try:
-                self.process_request(request, client_address)
-            except:
-                self.handle_error(request, client_address)
-                self.close_request(request)
-
-    def handle_timeout(self):
-        """Called if no new request arrives within self.timeout.
-
-        Overridden by ForkingMixIn.
-        """
-        pass
-
-    def verify_request(self, request, client_address):
-        """Verify the request.  May be overridden.
-
-        Return True if we should proceed with this request.
-
-        """
-        return True
-
-    def process_request(self, request, client_address):
-        """Call finish_request.
-
-        Overridden by ForkingMixIn and ThreadingMixIn.
-
-        """
-        self.finish_request(request, client_address)
-        self.close_request(request)
-
-    def server_close(self):
-        """Called to clean-up the server.
-
-        May be overridden.
-
-        """
-        pass
-
-    def finish_request(self, request, client_address):
-        """Finish one request by instantiating RequestHandlerClass."""
-        self.RequestHandlerClass(request, client_address, self)
-
-    def close_request(self, request):
-        """Called to clean up an individual request."""
-        pass
-
-    def handle_error(self, request, client_address):
-        """Handle an error gracefully.  May be overridden.
-
-        The default is to print a traceback and continue.
-
-        """
-        print '-'*40
-        print 'Exception happened during processing of request from',
-        print client_address
-        import traceback
-        traceback.print_exc() # XXX But this goes to stderr!
-        print '-'*40
-
-
-class TCPServer(BaseServer):
-
-    """Base class for various socket-based server classes.
-
-    Defaults to synchronous IP stream (i.e., TCP).
-
-    Methods for the caller:
-
-    - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
-    - serve_forever(poll_interval=0.5)
-    - shutdown()
-    - handle_request()  # if you don't use serve_forever()
-    - fileno() -> int   # for select()
-
-    Methods that may be overridden:
-
-    - server_bind()
-    - server_activate()
-    - get_request() -> request, client_address
-    - handle_timeout()
-    - verify_request(request, client_address)
-    - process_request(request, client_address)
-    - close_request(request)
-    - handle_error()
-
-    Methods for derived classes:
-
-    - finish_request(request, client_address)
-
-    Class variables that may be overridden by derived classes or
-    instances:
-
-    - timeout
-    - address_family
-    - socket_type
-    - request_queue_size (only for stream sockets)
-    - allow_reuse_address
-
-    Instance variables:
-
-    - server_address
-    - RequestHandlerClass
-    - socket
-
-    """
-
-    address_family = socket.AF_INET
-
-    socket_type = socket.SOCK_STREAM
-
-    request_queue_size = 5
-
-    allow_reuse_address = False
-
-    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
-        """Constructor.  May be extended, do not override."""
-        BaseServer.__init__(self, server_address, RequestHandlerClass)
-        self.socket = socket.socket(self.address_family,
-                                    self.socket_type)
-        if bind_and_activate:
-            self.server_bind()
-            self.server_activate()
-
-    def server_bind(self):
-        """Called by constructor to bind the socket.
-
-        May be overridden.
-
-        """
-        if self.allow_reuse_address:
-            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-        self.socket.bind(self.server_address)
-        self.server_address = self.socket.getsockname()
-
-    def server_activate(self):
-        """Called by constructor to activate the server.
-
-        May be overridden.
-
-        """
-        self.socket.listen(self.request_queue_size)
-
-    def server_close(self):
-        """Called to clean-up the server.
-
-        May be overridden.
-
-        """
-        self.socket.close()
-
-    def fileno(self):
-        """Return socket file number.
-
-        Interface required by select().
-
-        """
-        return self.socket.fileno()
-
-    def get_request(self):
-        """Get the request and client address from the socket.
-
-        May be overridden.
-
-        """
-        return self.socket.accept()
-
-    def close_request(self, request):
-        """Called to clean up an individual request."""
-        request.close()
-
-
-class UDPServer(TCPServer):
-
-    """UDP server class."""
-
-    allow_reuse_address = False
-
-    socket_type = socket.SOCK_DGRAM
-
-    max_packet_size = 8192
-
-    def get_request(self):
-        data, client_addr = self.socket.recvfrom(self.max_packet_size)
-        return (data, self.socket), client_addr
-
-    def server_activate(self):
-        # No need to call listen() for UDP.
-        pass
-
-    def close_request(self, request):
-        # No need to close anything.
-        pass
-
-class ForkingMixIn:
-
-    """Mix-in class to handle each request in a new process."""
-
-    timeout = 300
-    active_children = None
-    max_children = 40
-
-    def collect_children(self):
-        """Internal routine to wait for children that have exited."""
-        if self.active_children is None: return
-        while len(self.active_children) >= self.max_children:
-            # XXX: This will wait for any child process, not just ones
-            # spawned by this library. This could confuse other
-            # libraries that expect to be able to wait for their own
-            # children.
-            try:
-                pid, status = os.waitpid(0, options=0)
-            except os.error:
-                pid = None
-            if pid not in self.active_children: continue
-            self.active_children.remove(pid)
-
-        # XXX: This loop runs more system calls than it ought
-        # to. There should be a way to put the active_children into a
-        # process group and then use os.waitpid(-pgid) to wait for any
-        # of that set, but I couldn't find a way to allocate pgids
-        # that couldn't collide.
-        for child in self.active_children:
-            try:
-                pid, status = os.waitpid(child, os.WNOHANG)
-            except os.error:
-                pid = None
-            if not pid: continue
-            try:
-                self.active_children.remove(pid)
-            except ValueError, e:
-                raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
-                                                           self.active_children))
-
-    def handle_timeout(self):
-        """Wait for zombies after self.timeout seconds of inactivity.
-
-        May be extended, do not override.
-        """
-        self.collect_children()
-
-    def process_request(self, request, client_address):
-        """Fork a new subprocess to process the request."""
-        self.collect_children()
-        pid = os.fork()
-        if pid:
-            # Parent process
-            if self.active_children is None:
-                self.active_children = []
-            self.active_children.append(pid)
-            self.close_request(request)
-            return
-        else:
-            # Child process.
-            # This must never return, hence os._exit()!
-            try:
-                self.finish_request(request, client_address)
-                os._exit(0)
-            except:
-                try:
-                    self.handle_error(request, client_address)
-                finally:
-                    os._exit(1)
-
-
-class ThreadingMixIn:
-    """Mix-in class to handle each request in a new thread."""
-
-    # Decides how threads will act upon termination of the
-    # main process
-    daemon_threads = False
-
-    def process_request_thread(self, request, client_address):
-        """Same as in BaseServer but as a thread.
-
-        In addition, exception handling is done here.
-
-        """
-        try:
-            self.finish_request(request, client_address)
-            self.close_request(request)
-        except:
-            self.handle_error(request, client_address)
-            self.close_request(request)
-
-    def process_request(self, request, client_address):
-        """Start a new thread to process the request."""
-        t = threading.Thread(target = self.process_request_thread,
-                             args = (request, client_address))
-        if self.daemon_threads:
-            t.setDaemon (1)
-        t.start()
-
-
-class ForkingUDPServer(ForkingMixIn, UDPServer): pass
-class ForkingTCPServer(ForkingMixIn, TCPServer): pass
-
-class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
-class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
-
-if hasattr(socket, 'AF_UNIX'):
-
-    class UnixStreamServer(TCPServer):
-        address_family = socket.AF_UNIX
-
-    class UnixDatagramServer(UDPServer):
-        address_family = socket.AF_UNIX
-
-    class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
-
-    class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
-
-class BaseRequestHandler:
-
-    """Base class for request handler classes.
-
-    This class is instantiated for each request to be handled.  The
-    constructor sets the instance variables request, client_address
-    and server, and then calls the handle() method.  To implement a
-    specific service, all you need to do is to derive a class which
-    defines a handle() method.
-
-    The handle() method can find the request as self.request, the
-    client address as self.client_address, and the server (in case it
-    needs access to per-server information) as self.server.  Since a
-    separate instance is created for each request, the handle() method
-    can define arbitrary other instance variariables.
-
-    """
-
-    def __init__(self, request, client_address, server):
-        self.request = request
-        self.client_address = client_address
-        self.server = server
-        try:
-            self.setup()
-            self.handle()
-            self.finish()
-        finally:
-            sys.exc_traceback = None    # Help garbage collection
-
-    def setup(self):
-        pass
-
-    def handle(self):
-        pass
-
-    def finish(self):
-        pass
-
-
-# The following two classes make it possible to use the same service
-# class for stream or datagram servers.
-# Each class sets up these instance variables:
-# - rfile: a file object from which receives the request is read
-# - wfile: a file object to which the reply is written
-# When the handle() method returns, wfile is flushed properly
-
-
-class StreamRequestHandler(BaseRequestHandler):
-
-    """Define self.rfile and self.wfile for stream sockets."""
-
-    # Default buffer sizes for rfile, wfile.
-    # We default rfile to buffered because otherwise it could be
-    # really slow for large data (a getc() call per byte); we make
-    # wfile unbuffered because (a) often after a write() we want to
-    # read and we need to flush the line; (b) big writes to unbuffered
-    # files are typically optimized by stdio even when big reads
-    # aren't.
-    rbufsize = -1
-    wbufsize = 0
-
-    def setup(self):
-        self.connection = self.request
-        self.rfile = self.connection.makefile('rb', self.rbufsize)
-        self.wfile = self.connection.makefile('wb', self.wbufsize)
-
-    def finish(self):
-        if not self.wfile.closed:
-            self.wfile.flush()
-        self.wfile.close()
-        self.rfile.close()
-
-
-class DatagramRequestHandler(BaseRequestHandler):
-
-    # XXX Regrettably, I cannot get this working on Linux;
-    # s.recvfrom() doesn't return a meaningful client address.
-
-    """Define self.rfile and self.wfile for datagram sockets."""
-
-    def setup(self):
-        try:
-            from cStringIO import StringIO
-        except ImportError:
-            from StringIO import StringIO
-        self.packet, self.socket = self.request
-        self.rfile = StringIO(self.packet)
-        self.wfile = StringIO()
-
-    def finish(self):
-        self.socket.sendto(self.wfile.getvalue(), self.client_address)

Modified: python/branches/okkoto-sizeof/Lib/sqlite3/test/dbapi.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/sqlite3/test/dbapi.py	(original)
+++ python/branches/okkoto-sizeof/Lib/sqlite3/test/dbapi.py	Wed Jun  4 11:24:23 2008
@@ -297,6 +297,15 @@
         self.cu.execute("update test set name='bar'")
         self.failUnlessEqual(self.cu.rowcount, 2)
 
+    def CheckRowcountSelect(self):
+        """
+        pysqlite does not know the rowcount of SELECT statements, because we
+        don't fetch all rows after executing the select statement. The rowcount
+        has thus to be -1.
+        """
+        self.cu.execute("select 5 union select 6")
+        self.failUnlessEqual(self.cu.rowcount, -1)
+
     def CheckRowcountExecutemany(self):
         self.cu.execute("delete from test")
         self.cu.executemany("insert into test(name) values (?)", [(1,), (2,), (3,)])

Modified: python/branches/okkoto-sizeof/Lib/sre_parse.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/sre_parse.py	(original)
+++ python/branches/okkoto-sizeof/Lib/sre_parse.py	Wed Jun  4 11:24:23 2008
@@ -139,8 +139,6 @@
         return self.data[index]
     def __setitem__(self, index, code):
         self.data[index] = code
-    def __getslice__(self, start, stop):
-        return SubPattern(self.pattern, self.data[start:stop])
     def insert(self, index, code):
         self.data.insert(index, code)
     def append(self, code):

Modified: python/branches/okkoto-sizeof/Lib/subprocess.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/subprocess.py	(original)
+++ python/branches/okkoto-sizeof/Lib/subprocess.py	Wed Jun  4 11:24:23 2008
@@ -661,8 +661,10 @@
                 self.stdin.close()
             elif self.stdout:
                 stdout = self.stdout.read()
+                self.stdout.close()
             elif self.stderr:
                 stderr = self.stderr.read()
+                self.stderr.close()
             self.wait()
             return (stdout, stderr)
 

Modified: python/branches/okkoto-sizeof/Lib/tarfile.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/tarfile.py	(original)
+++ python/branches/okkoto-sizeof/Lib/tarfile.py	Wed Jun  4 11:24:23 2008
@@ -692,7 +692,6 @@
         if self.mode == "w":
             raw = self.bz2obj.flush()
             self.fileobj.write(raw)
-        self.fileobj.close()
 # class _BZ2Proxy
 
 #------------------------

Modified: python/branches/okkoto-sizeof/Lib/telnetlib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/telnetlib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/telnetlib.py	Wed Jun  4 11:24:23 2008
@@ -184,13 +184,13 @@
 
     """
 
-    def __init__(self, host=None, port=0, timeout=None):
+    def __init__(self, host=None, port=0,
+                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         """Constructor.
 
         When called without arguments, create an unconnected instance.
-        With a hostname argument, it connects the instance; a port
-        number is optional.
-
+        With a hostname argument, it connects the instance; port number
+        and timeout are optional.
         """
         self.debuglevel = DEBUGLEVEL
         self.host = host
@@ -208,23 +208,21 @@
         if host is not None:
             self.open(host, port, timeout)
 
-    def open(self, host, port=0, timeout=None):
+    def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         """Connect to a host.
 
         The optional second argument is the port number, which
         defaults to the standard telnet port (23).
 
         Don't try to reopen an already connected instance.
-
         """
         self.eof = 0
         if not port:
             port = TELNET_PORT
         self.host = host
         self.port = port
-        if timeout is not None:
-            self.timeout = timeout
-        self.sock = socket.create_connection((host, port), self.timeout)
+        self.timeout = timeout
+        self.sock = socket.create_connection((host, port), timeout)
 
     def __del__(self):
         """Destructor -- close the connection."""

Modified: python/branches/okkoto-sizeof/Lib/test/pickletester.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/pickletester.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/pickletester.py	Wed Jun  4 11:24:23 2008
@@ -2,7 +2,7 @@
 import pickle
 import cPickle
 import pickletools
-import copyreg
+import copy_reg
 
 from test.test_support import TestFailed, have_unicode, TESTFN, \
                               run_with_locale
@@ -44,21 +44,21 @@
     # there is one).
     def __init__(self, code):
         self.code = code
-        if code in copyreg._inverted_registry:
-            self.pair = copyreg._inverted_registry[code]
-            copyreg.remove_extension(self.pair[0], self.pair[1], code)
+        if code in copy_reg._inverted_registry:
+            self.pair = copy_reg._inverted_registry[code]
+            copy_reg.remove_extension(self.pair[0], self.pair[1], code)
         else:
             self.pair = None
 
     # Restore previous registration for code.
     def restore(self):
         code = self.code
-        curpair = copyreg._inverted_registry.get(code)
+        curpair = copy_reg._inverted_registry.get(code)
         if curpair is not None:
-            copyreg.remove_extension(curpair[0], curpair[1], code)
+            copy_reg.remove_extension(curpair[0], curpair[1], code)
         pair = self.pair
         if pair is not None:
-            copyreg.add_extension(pair[0], pair[1], code)
+            copy_reg.add_extension(pair[0], pair[1], code)
 
 class C:
     def __cmp__(self, other):
@@ -690,14 +690,14 @@
                 self.assertEqual(B(x), B(y), detail)
                 self.assertEqual(x.__dict__, y.__dict__, detail)
 
-    # Register a type with copyreg, with extension code extcode.  Pickle
+    # Register a type with copy_reg, with extension code extcode.  Pickle
     # an object of that type.  Check that the resulting pickle uses opcode
     # (EXT[124]) under proto 2, and not in proto 1.
 
     def produce_global_ext(self, extcode, opcode):
         e = ExtensionSaver(extcode)
         try:
-            copyreg.add_extension(__name__, "MyList", extcode)
+            copy_reg.add_extension(__name__, "MyList", extcode)
             x = MyList([1, 2, 3])
             x.foo = 42
             x.bar = "hello"

Modified: python/branches/okkoto-sizeof/Lib/test/regrtest.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/regrtest.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/regrtest.py	Wed Jun  4 11:24:23 2008
@@ -629,7 +629,7 @@
 
 def dash_R(the_module, test, indirect_test, huntrleaks):
     # This code is hackish and inelegant, but it seems to do the job.
-    import copyreg, _abcoll, io
+    import copy_reg, _abcoll, io
 
     if not hasattr(sys, 'gettotalrefcount'):
         raise Exception("Tracking reference leaks requires a debug build "
@@ -637,7 +637,7 @@
 
     # Save current values for dash_R_cleanup() to restore.
     fs = warnings.filters[:]
-    ps = copyreg.dispatch_table.copy()
+    ps = copy_reg.dispatch_table.copy()
     pic = sys.path_importer_cache.copy()
     abcs = {}
     modules = _abcoll, io
@@ -677,7 +677,7 @@
         refrep.close()
 
 def dash_R_cleanup(fs, ps, pic, abcs):
-    import gc, copyreg
+    import gc, copy_reg
     import _strptime, linecache
     dircache = test_support.import_module('dircache', deprecated=True)
     import urlparse, urllib, urllib2, mimetypes, doctest
@@ -691,8 +691,8 @@
 
     # Restore some original values.
     warnings.filters[:] = fs
-    copyreg.dispatch_table.clear()
-    copyreg.dispatch_table.update(ps)
+    copy_reg.dispatch_table.clear()
+    copy_reg.dispatch_table.update(ps)
     sys.path_importer_cache.clear()
     sys.path_importer_cache.update(pic)
 

Modified: python/branches/okkoto-sizeof/Lib/test/test___all__.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test___all__.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test___all__.py	Wed Jun  4 11:24:23 2008
@@ -37,12 +37,12 @@
         self.check_all("BaseHTTPServer")
         self.check_all("Bastion")
         self.check_all("CGIHTTPServer")
-        self.check_all("configparser")
+        self.check_all("ConfigParser")
         self.check_all("Cookie")
         self.check_all("MimeWriter")
         self.check_all("Queue")
         self.check_all("SimpleHTTPServer")
-        self.check_all("socketserver")
+        self.check_all("SocketServer")
         self.check_all("StringIO")
         self.check_all("UserString")
         self.check_all("aifc")
@@ -61,7 +61,7 @@
         self.check_all("commands")
         self.check_all("compileall")
         self.check_all("copy")
-        self.check_all("copyreg")
+        self.check_all("copy_reg")
         self.check_all("csv")
         self.check_all("dbhash")
         self.check_all("decimal")
@@ -123,7 +123,7 @@
         self.check_all("quopri")
         self.check_all("random")
         self.check_all("re")
-        self.check_all("reprlib")
+        self.check_all("repr")
         self.check_all("rexec")
         self.check_all("rfc822")
         self.check_all("rlcompleter")
@@ -144,6 +144,7 @@
         self.check_all("tarfile")
         self.check_all("telnetlib")
         self.check_all("tempfile")
+        self.check_all("test.test_support")
         self.check_all("textwrap")
         self.check_all("threading")
         self.check_all("timeit")

Modified: python/branches/okkoto-sizeof/Lib/test/test_bsddb.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_bsddb.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_bsddb.py	Wed Jun  4 11:24:23 2008
@@ -66,9 +66,6 @@
         self.assertSetEquals(d.iteritems(), f.iteritems())
 
     def test_iter_while_modifying_values(self):
-        if not hasattr(self.f, '__iter__'):
-            return
-
         di = iter(self.d)
         while 1:
             try:
@@ -80,20 +77,62 @@
         # it should behave the same as a dict.  modifying values
         # of existing keys should not break iteration.  (adding
         # or removing keys should)
+        loops_left = len(self.f)
         fi = iter(self.f)
         while 1:
             try:
                 key = fi.next()
                 self.f[key] = 'modified '+key
+                loops_left -= 1
             except StopIteration:
                 break
+        self.assertEqual(loops_left, 0)
 
         self.test_mapping_iteration_methods()
 
-    def test_iteritems_while_modifying_values(self):
-        if not hasattr(self.f, 'iteritems'):
-            return
+    def test_iter_abort_on_changed_size(self):
+        def DictIterAbort():
+            di = iter(self.d)
+            while 1:
+                try:
+                    di.next()
+                    self.d['newkey'] = 'SPAM'
+                except StopIteration:
+                    break
+        self.assertRaises(RuntimeError, DictIterAbort)
+
+        def DbIterAbort():
+            fi = iter(self.f)
+            while 1:
+                try:
+                    fi.next()
+                    self.f['newkey'] = 'SPAM'
+                except StopIteration:
+                    break
+        self.assertRaises(RuntimeError, DbIterAbort)
 
+    def test_iteritems_abort_on_changed_size(self):
+        def DictIteritemsAbort():
+            di = self.d.iteritems()
+            while 1:
+                try:
+                    di.next()
+                    self.d['newkey'] = 'SPAM'
+                except StopIteration:
+                    break
+        self.assertRaises(RuntimeError, DictIteritemsAbort)
+
+        def DbIteritemsAbort():
+            fi = self.f.iteritems()
+            while 1:
+                try:
+                    key, value = fi.next()
+                    del self.f[key]
+                except StopIteration:
+                    break
+        self.assertRaises(RuntimeError, DbIteritemsAbort)
+
+    def test_iteritems_while_modifying_values(self):
         di = self.d.iteritems()
         while 1:
             try:
@@ -105,13 +144,16 @@
         # it should behave the same as a dict.  modifying values
         # of existing keys should not break iteration.  (adding
         # or removing keys should)
+        loops_left = len(self.f)
         fi = self.f.iteritems()
         while 1:
             try:
                 k, v = fi.next()
                 self.f[k] = 'modified '+v
+                loops_left -= 1
             except StopIteration:
                 break
+        self.assertEqual(loops_left, 0)
 
         self.test_mapping_iteration_methods()
 
@@ -177,8 +219,8 @@
         # the database write and locking+threading support is enabled
         # the cursor's read lock will deadlock the write lock request..
 
-        # test the iterator interface (if present)
-        if hasattr(self.f, 'iteritems'):
+        # test the iterator interface
+        if True:
             if debug: print "D"
             i = self.f.iteritems()
             k,v = i.next()
@@ -213,10 +255,7 @@
         self.assert_(self.f[k], "be gone with ye deadlocks")
 
     def test_for_cursor_memleak(self):
-        if not hasattr(self.f, 'iteritems'):
-            return
-
-        # do the bsddb._DBWithCursor _iter_mixin internals leak cursors?
+        # do the bsddb._DBWithCursor iterator internals leak cursors?
         nc1 = len(self.f._cursor_refs)
         # create iterator
         i = self.f.iteritems()

Modified: python/branches/okkoto-sizeof/Lib/test/test_bsddb3.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_bsddb3.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_bsddb3.py	Wed Jun  4 11:24:23 2008
@@ -48,61 +48,29 @@
             sys.__stdout__.flush()
 
 
-def suite():
-    test_modules = [
-        'test_associate',
-        'test_basics',
-        'test_compare',
-        'test_compat',
-        'test_cursor_pget_bug',
-        'test_dbobj',
-        'test_dbshelve',
-        'test_dbtables',
-        'test_distributed_transactions',
-        'test_early_close',
-        'test_get_none',
-        'test_join',
-        'test_lock',
-        'test_misc',
-        'test_pickle',
-        'test_queue',
-        'test_recno',
-        'test_replication',
-        'test_sequence',
-        'test_thread',
-        ]
-
-    alltests = unittest.TestSuite()
-    for name in test_modules:
-        module = __import__("bsddb.test."+name, globals(), locals(), name)
-        #print module,name
-        alltests.addTest(module.test_suite())
-        alltests.addTest(unittest.makeSuite(TimingCheck))
-    return alltests
-
-
 # For invocation through regrtest
 def test_main():
-    run_unittest(suite())
-    db_home = os.path.join(tempfile.gettempdir(), 'db_home')
-    # The only reason to remove db_home is in case if there is an old
-    # one lying around.  This might be by a different user, so just
-    # ignore errors.  We should always make a unique name now.
+    from bsddb import db
+    from bsddb.test import test_all
+    test_all.set_test_path_prefix(os.path.join(tempfile.gettempdir(),
+                                 'z-test_bsddb3-%s' %
+                                 os.getpid()))
+    # Please leave this print in, having this show up in the buildbots
+    # makes diagnosing problems a lot easier.
+    print >>sys.stderr, db.DB_VERSION_STRING
+    print >>sys.stderr, 'Test path prefix: ', test_all.get_test_path_prefix()
     try:
-        rmtree(db_home)
-    except:
-        pass
-    rmtree('db_home%d' % os.getpid())
+        run_unittest(test_all.suite(module_prefix='bsddb.test.',
+                                    timing_check=TimingCheck))
+    finally:
+        # The only reason to remove db_home is in case if there is an old
+        # one lying around.  This might be by a different user, so just
+        # ignore errors.  We should always make a unique name now.
+        try:
+            test_all.remove_test_path_directory()
+        except:
+            pass
 
-# For invocation as a script
-if __name__ == '__main__':
-    from bsddb import db
-    print '-=' * 38
-    print db.DB_VERSION_STRING
-    print 'bsddb.db.version():   %s' % (db.version(),)
-    print 'bsddb.db.__version__: %s' % db.__version__
-    print 'bsddb.db.cvsid:       %s' % db.cvsid
-    print 'python version:        %s' % sys.version
-    print '-=' * 38
 
+if __name__ == '__main__':
     test_main()

Modified: python/branches/okkoto-sizeof/Lib/test/test_cfgparser.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_cfgparser.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_cfgparser.py	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,4 @@
-import configparser
+import ConfigParser
 import StringIO
 import unittest
 import UserDict
@@ -94,7 +94,7 @@
                     "remove_option() failed to report non-existance of option"
                     " that was removed")
 
-        self.assertRaises(configparser.NoSectionError,
+        self.assertRaises(ConfigParser.NoSectionError,
                           cf.remove_option, 'No Such Section', 'foo')
 
         eq(cf.get('Long Line', 'foo'),
@@ -147,17 +147,17 @@
 
     def test_parse_errors(self):
         self.newconfig()
-        self.parse_error(configparser.ParsingError,
+        self.parse_error(ConfigParser.ParsingError,
                          "[Foo]\n  extra-spaces: splat\n")
-        self.parse_error(configparser.ParsingError,
+        self.parse_error(ConfigParser.ParsingError,
                          "[Foo]\n  extra-spaces= splat\n")
-        self.parse_error(configparser.ParsingError,
+        self.parse_error(ConfigParser.ParsingError,
                          "[Foo]\noption-without-value\n")
-        self.parse_error(configparser.ParsingError,
+        self.parse_error(ConfigParser.ParsingError,
                          "[Foo]\n:value-without-option-name\n")
-        self.parse_error(configparser.ParsingError,
+        self.parse_error(ConfigParser.ParsingError,
                          "[Foo]\n=value-without-option-name\n")
-        self.parse_error(configparser.MissingSectionHeaderError,
+        self.parse_error(ConfigParser.MissingSectionHeaderError,
                          "No Section!\n")
 
     def parse_error(self, exc, src):
@@ -170,13 +170,13 @@
                          "new ConfigParser should have no defined sections")
         self.failIf(cf.has_section("Foo"),
                     "new ConfigParser should have no acknowledged sections")
-        self.assertRaises(configparser.NoSectionError,
+        self.assertRaises(ConfigParser.NoSectionError,
                           cf.options, "Foo")
-        self.assertRaises(configparser.NoSectionError,
+        self.assertRaises(ConfigParser.NoSectionError,
                           cf.set, "foo", "bar", "value")
-        self.get_error(configparser.NoSectionError, "foo", "bar")
+        self.get_error(ConfigParser.NoSectionError, "foo", "bar")
         cf.add_section("foo")
-        self.get_error(configparser.NoOptionError, "foo", "bar")
+        self.get_error(ConfigParser.NoOptionError, "foo", "bar")
 
     def get_error(self, exc, section, option):
         try:
@@ -215,7 +215,7 @@
     def test_weird_errors(self):
         cf = self.newconfig()
         cf.add_section("Foo")
-        self.assertRaises(configparser.DuplicateSectionError,
+        self.assertRaises(ConfigParser.DuplicateSectionError,
                           cf.add_section, "Foo")
 
     def test_write(self):
@@ -324,7 +324,7 @@
 
 
 class ConfigParserTestCase(TestCaseBase):
-    config_class = configparser.ConfigParser
+    config_class = ConfigParser.ConfigParser
 
     def test_interpolation(self):
         cf = self.get_interpolation_config()
@@ -335,11 +335,11 @@
            "something with lots of interpolation (9 steps)")
         eq(cf.get("Foo", "bar10"),
            "something with lots of interpolation (10 steps)")
-        self.get_error(configparser.InterpolationDepthError, "Foo", "bar11")
+        self.get_error(ConfigParser.InterpolationDepthError, "Foo", "bar11")
 
     def test_interpolation_missing_value(self):
         cf = self.get_interpolation_config()
-        e = self.get_error(configparser.InterpolationError,
+        e = self.get_error(ConfigParser.InterpolationError,
                            "Interpolation Error", "name")
         self.assertEqual(e.reference, "reference")
         self.assertEqual(e.section, "Interpolation Error")
@@ -375,7 +375,7 @@
 
 
 class RawConfigParserTestCase(TestCaseBase):
-    config_class = configparser.RawConfigParser
+    config_class = ConfigParser.RawConfigParser
 
     def test_interpolation(self):
         cf = self.get_interpolation_config()
@@ -410,7 +410,7 @@
 
 
 class SafeConfigParserTestCase(ConfigParserTestCase):
-    config_class = configparser.SafeConfigParser
+    config_class = ConfigParser.SafeConfigParser
 
     def test_safe_interpolation(self):
         # See http://www.python.org/sf/511737

Modified: python/branches/okkoto-sizeof/Lib/test/test_collections.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_collections.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_collections.py	Wed Jun  4 11:24:23 2008
@@ -110,7 +110,9 @@
 
         n = 10000
         import string, random
-        names = [''.join([random.choice(string.letters) for j in range(10)]) for i in range(n)]
+        names = list(set(''.join([random.choice(string.ascii_letters)
+                                  for j in range(10)]) for i in range(n)))
+        n = len(names)
         Big = namedtuple('Big', names)
         b = Big(*range(n))
         self.assertEqual(b, tuple(range(n)))

Modified: python/branches/okkoto-sizeof/Lib/test/test_copy.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_copy.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_copy.py	Wed Jun  4 11:24:23 2008
@@ -1,7 +1,7 @@
 """Unit tests for the copy module."""
 
 import copy
-import copyreg
+import copy_reg
 
 import unittest
 from test import test_support
@@ -42,7 +42,7 @@
             return (C, (obj.foo,))
         x = C(42)
         self.assertRaises(TypeError, copy.copy, x)
-        copyreg.pickle(C, pickle_C, C)
+        copy_reg.pickle(C, pickle_C, C)
         y = copy.copy(x)
 
     def test_copy_reduce_ex(self):
@@ -215,7 +215,7 @@
             return (C, (obj.foo,))
         x = C(42)
         self.assertRaises(TypeError, copy.deepcopy, x)
-        copyreg.pickle(C, pickle_C, C)
+        copy_reg.pickle(C, pickle_C, C)
         y = copy.deepcopy(x)
 
     def test_deepcopy_reduce_ex(self):

Deleted: python/branches/okkoto-sizeof/Lib/test/test_copyreg.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_copyreg.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,121 +0,0 @@
-import copyreg
-import unittest
-
-from test import test_support
-from test.pickletester import ExtensionSaver
-
-class C:
-    pass
-
-
-class WithoutSlots(object):
-    pass
-
-class WithWeakref(object):
-    __slots__ = ('__weakref__',)
-
-class WithPrivate(object):
-    __slots__ = ('__spam',)
-
-class WithSingleString(object):
-    __slots__ = 'spam'
-
-class WithInherited(WithSingleString):
-    __slots__ = ('eggs',)
-
-
-class CopyRegTestCase(unittest.TestCase):
-
-    def test_class(self):
-        self.assertRaises(TypeError, copyreg.pickle,
-                          C, None, None)
-
-    def test_noncallable_reduce(self):
-        self.assertRaises(TypeError, copyreg.pickle,
-                          type(1), "not a callable")
-
-    def test_noncallable_constructor(self):
-        self.assertRaises(TypeError, copyreg.pickle,
-                          type(1), int, "not a callable")
-
-    def test_bool(self):
-        import copy
-        self.assertEquals(True, copy.copy(True))
-
-    def test_extension_registry(self):
-        mod, func, code = 'junk1 ', ' junk2', 0xabcd
-        e = ExtensionSaver(code)
-        try:
-            # Shouldn't be in registry now.
-            self.assertRaises(ValueError, copyreg.remove_extension,
-                              mod, func, code)
-            copyreg.add_extension(mod, func, code)
-            # Should be in the registry.
-            self.assert_(copyreg._extension_registry[mod, func] == code)
-            self.assert_(copyreg._inverted_registry[code] == (mod, func))
-            # Shouldn't be in the cache.
-            self.assert_(code not in copyreg._extension_cache)
-            # Redundant registration should be OK.
-            copyreg.add_extension(mod, func, code)  # shouldn't blow up
-            # Conflicting code.
-            self.assertRaises(ValueError, copyreg.add_extension,
-                              mod, func, code + 1)
-            self.assertRaises(ValueError, copyreg.remove_extension,
-                              mod, func, code + 1)
-            # Conflicting module name.
-            self.assertRaises(ValueError, copyreg.add_extension,
-                              mod[1:], func, code )
-            self.assertRaises(ValueError, copyreg.remove_extension,
-                              mod[1:], func, code )
-            # Conflicting function name.
-            self.assertRaises(ValueError, copyreg.add_extension,
-                              mod, func[1:], code)
-            self.assertRaises(ValueError, copyreg.remove_extension,
-                              mod, func[1:], code)
-            # Can't remove one that isn't registered at all.
-            if code + 1 not in copyreg._inverted_registry:
-                self.assertRaises(ValueError, copyreg.remove_extension,
-                                  mod[1:], func[1:], code + 1)
-
-        finally:
-            e.restore()
-
-        # Shouldn't be there anymore.
-        self.assert_((mod, func) not in copyreg._extension_registry)
-        # The code *may* be in copyreg._extension_registry, though, if
-        # we happened to pick on a registered code.  So don't check for
-        # that.
-
-        # Check valid codes at the limits.
-        for code in 1, 0x7fffffff:
-            e = ExtensionSaver(code)
-            try:
-                copyreg.add_extension(mod, func, code)
-                copyreg.remove_extension(mod, func, code)
-            finally:
-                e.restore()
-
-        # Ensure invalid codes blow up.
-        for code in -1, 0, 0x80000000L:
-            self.assertRaises(ValueError, copyreg.add_extension,
-                              mod, func, code)
-
-    def test_slotnames(self):
-        self.assertEquals(copyreg._slotnames(WithoutSlots), [])
-        self.assertEquals(copyreg._slotnames(WithWeakref), [])
-        expected = ['_WithPrivate__spam']
-        self.assertEquals(copyreg._slotnames(WithPrivate), expected)
-        self.assertEquals(copyreg._slotnames(WithSingleString), ['spam'])
-        expected = ['eggs', 'spam']
-        expected.sort()
-        result = copyreg._slotnames(WithInherited)
-        result.sort()
-        self.assertEquals(result, expected)
-
-
-def test_main():
-    test_support.run_unittest(CopyRegTestCase)
-
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/okkoto-sizeof/Lib/test/test_datetime.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_datetime.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_datetime.py	Wed Jun  4 11:24:23 2008
@@ -850,9 +850,13 @@
         self.assertRaises(TypeError, t.strftime, "one", "two") # too many args
         self.assertRaises(TypeError, t.strftime, 42) # arg wrong type
 
+        # test that unicode input is allowed (issue 2782)
+        self.assertEqual(t.strftime(u"%m"), "03")
+
         # A naive object replaces %z and %Z w/ empty strings.
         self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
 
+
     def test_format(self):
         dt = self.theclass(2007, 9, 10)
         self.assertEqual(dt.__format__(''), str(dt))

Modified: python/branches/okkoto-sizeof/Lib/test/test_descrtut.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_descrtut.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_descrtut.py	Wed Jun  4 11:24:23 2008
@@ -208,6 +208,7 @@
      '__setattr__',
      '__setitem__',
      '__setslice__',
+     '__sizeof__',
      '__str__',
      '__subclasshook__',
      'append',

Modified: python/branches/okkoto-sizeof/Lib/test/test_dummy_thread.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_dummy_thread.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_dummy_thread.py	Wed Jun  4 11:24:23 2008
@@ -7,7 +7,7 @@
 """
 import dummy_thread as _thread
 import time
-import queue
+import Queue
 import random
 import unittest
 from test import test_support
@@ -124,7 +124,7 @@
             """Use to test _thread.start_new_thread() passes args properly."""
             queue.put((arg1, arg2))
 
-        testing_queue = queue.Queue(1)
+        testing_queue = Queue.Queue(1)
         _thread.start_new_thread(arg_tester, (testing_queue, True, True))
         result = testing_queue.get()
         self.failUnless(result[0] and result[1],
@@ -148,7 +148,7 @@
             queue.put(_thread.get_ident())
 
         thread_count = 5
-        testing_queue = queue.Queue(thread_count)
+        testing_queue = Queue.Queue(thread_count)
         if test_support.verbose:
             print
             print "*** Testing multiple thread creation "\

Modified: python/branches/okkoto-sizeof/Lib/test/test_enumerate.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_enumerate.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_enumerate.py	Wed Jun  4 11:24:23 2008
@@ -138,6 +138,8 @@
         for data in 'abc', range(5), tuple(enumerate('abc')), A(), xrange(1,17,5):
             self.assertEqual(list(data)[::-1], list(reversed(data)))
         self.assertRaises(TypeError, reversed, {})
+        # don't allow keyword arguments
+        self.assertRaises(TypeError, reversed, [], a=1)
 
     def test_xrange_optimization(self):
         x = xrange(1)

Modified: python/branches/okkoto-sizeof/Lib/test/test_ftplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_ftplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_ftplib.py	Wed Jun  4 11:24:23 2008
@@ -53,35 +53,52 @@
         # connects
         ftp = ftplib.FTP(HOST)
         self.evt.wait()
-        ftp.sock.close()
+        ftp.close()
 
     def testTimeoutDefault(self):
-        # default
-        ftp = ftplib.FTP(HOST)
+        # default -- use global socket timeout
+        self.assert_(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            ftp = ftplib.FTP("localhost")
+        finally:
+            socket.setdefaulttimeout(None)
+        self.assertEqual(ftp.sock.gettimeout(), 30)
+        self.evt.wait()
+        ftp.close()
+
+    def testTimeoutNone(self):
+        # no timeout -- do not use global socket timeout
+        self.assert_(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            ftp = ftplib.FTP("localhost", timeout=None)
+        finally:
+            socket.setdefaulttimeout(None)
         self.assertTrue(ftp.sock.gettimeout() is None)
         self.evt.wait()
-        ftp.sock.close()
+        ftp.close()
 
     def testTimeoutValue(self):
         # a value
         ftp = ftplib.FTP(HOST, timeout=30)
         self.assertEqual(ftp.sock.gettimeout(), 30)
         self.evt.wait()
-        ftp.sock.close()
+        ftp.close()
 
     def testTimeoutConnect(self):
         ftp = ftplib.FTP()
         ftp.connect(HOST, timeout=30)
         self.assertEqual(ftp.sock.gettimeout(), 30)
         self.evt.wait()
-        ftp.sock.close()
+        ftp.close()
 
     def testTimeoutDifferentOrder(self):
         ftp = ftplib.FTP(timeout=30)
         ftp.connect(HOST)
         self.assertEqual(ftp.sock.gettimeout(), 30)
         self.evt.wait()
-        ftp.sock.close()
+        ftp.close()
 
     def testTimeoutDirectAccess(self):
         ftp = ftplib.FTP()
@@ -89,18 +106,6 @@
         ftp.connect(HOST)
         self.assertEqual(ftp.sock.gettimeout(), 30)
         self.evt.wait()
-        ftp.sock.close()
-
-    def testTimeoutNone(self):
-        # None, having other default
-        previous = socket.getdefaulttimeout()
-        socket.setdefaulttimeout(30)
-        try:
-            ftp = ftplib.FTP(HOST, timeout=None)
-        finally:
-            socket.setdefaulttimeout(previous)
-        self.assertEqual(ftp.sock.gettimeout(), 30)
-        self.evt.wait()
         ftp.close()
 
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_generators.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_generators.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_generators.py	Wed Jun  4 11:24:23 2008
@@ -927,7 +927,7 @@
 >>> g.__name__
 'f'
 >>> repr(g)  # doctest: +ELLIPSIS
-'<f generator object at ...>'
+'<generator object f at ...>'
 """
 
 # conjoin is a simple backtracking generator, named in honor of Icon's

Modified: python/branches/okkoto-sizeof/Lib/test/test_genexps.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_genexps.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_genexps.py	Wed Jun  4 11:24:23 2008
@@ -92,7 +92,7 @@
 Verify that parenthesis are required when used as a keyword argument value
 
     >>> dict(a = (i for i in xrange(10))) #doctest: +ELLIPSIS
-    {'a': <<genexpr> generator object at ...>}
+    {'a': <generator object <genexpr> at ...>}
 
 Verify early binding for the outermost for-expression
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_gzip.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_gzip.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_gzip.py	Wed Jun  4 11:24:23 2008
@@ -24,14 +24,14 @@
 class TestGzip(unittest.TestCase):
     filename = test_support.TESTFN
 
-    def setUp (self):
+    def setUp(self):
         test_support.unlink(self.filename)
 
-    def tearDown (self):
+    def tearDown(self):
         test_support.unlink(self.filename)
 
 
-    def test_write (self):
+    def test_write(self):
         f = gzip.GzipFile(self.filename, 'wb') ; f.write(data1 * 50)
 
         # Try flush and fileno.
@@ -41,6 +41,9 @@
             os.fsync(f.fileno())
         f.close()
 
+        # Test multiple close() calls.
+        f.close()
+
     def test_read(self):
         self.test_write()
         # Try reading.

Modified: python/branches/okkoto-sizeof/Lib/test/test_htmllib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_htmllib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_htmllib.py	Wed Jun  4 11:24:23 2008
@@ -1,8 +1,8 @@
 import formatter
-import htmllib
 import unittest
 
 from test import test_support
+htmllib = test_support.import_module('htmllib', deprecated=True)
 
 
 class AnchorCollector(htmllib.HTMLParser):

Modified: python/branches/okkoto-sizeof/Lib/test/test_httplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_httplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_httplib.py	Wed Jun  4 11:24:23 2008
@@ -214,27 +214,32 @@
         '''This will prove that the timeout gets through
         HTTPConnection and into the socket.
         '''
-        # default
-        httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT)
-        httpConn.connect()
-        self.assertTrue(httpConn.sock.gettimeout() is None)
-        httpConn.close()
-
-        # a value
-        httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
-        httpConn.connect()
+        # default -- use global socket timeout
+        self.assert_(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT)
+            httpConn.connect()
+        finally:
+            socket.setdefaulttimeout(None)
         self.assertEqual(httpConn.sock.gettimeout(), 30)
         httpConn.close()
 
-        # None, having other default
-        previous = socket.getdefaulttimeout()
+        # no timeout -- do not use global socket default
+        self.assert_(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(30)
         try:
             httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT,
                                               timeout=None)
             httpConn.connect()
         finally:
-            socket.setdefaulttimeout(previous)
+            socket.setdefaulttimeout(None)
+        self.assertEqual(httpConn.sock.gettimeout(), None)
+        httpConn.close()
+
+        # a value
+        httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
+        httpConn.connect()
         self.assertEqual(httpConn.sock.gettimeout(), 30)
         httpConn.close()
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_ioctl.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_ioctl.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_ioctl.py	Wed Jun  4 11:24:23 2008
@@ -52,13 +52,10 @@
                 set_winsz_opcode_maybe_neg, = struct.unpack("i",
                         struct.pack("I", termios.TIOCSWINSZ))
 
-            # We're just testing that these calls do not raise exceptions.
-            saved_winsz = fcntl.ioctl(mfd, termios.TIOCGWINSZ, "\0"*8)
             our_winsz = struct.pack("HHHH",80,25,0,0)
             # test both with a positive and potentially negative ioctl code
             new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_pos, our_winsz)
             new_winsz = fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, our_winsz)
-            fcntl.ioctl(mfd, set_winsz_opcode_maybe_neg, saved_winsz)
         finally:
             os.close(mfd)
             os.close(sfd)

Modified: python/branches/okkoto-sizeof/Lib/test/test_json.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_json.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_json.py	Wed Jun  4 11:24:23 2008
@@ -11,7 +11,6 @@
 
 def test_main():
     test.test_support.run_unittest(json.tests.test_suite())
-    test.test_support.run_doctest(json)
 
 
 if __name__ == "__main__":

Modified: python/branches/okkoto-sizeof/Lib/test/test_logging.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_logging.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_logging.py	Wed Jun  4 11:24:23 2008
@@ -33,7 +33,7 @@
 import re
 import select
 import socket
-from socketserver import ThreadingTCPServer, StreamRequestHandler
+from SocketServer import ThreadingTCPServer, StreamRequestHandler
 import string
 import struct
 import sys

Modified: python/branches/okkoto-sizeof/Lib/test/test_math.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_math.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_math.py	Wed Jun  4 11:24:23 2008
@@ -630,6 +630,158 @@
         self.assertRaises(ValueError, math.sqrt, NINF)
         self.assert_(math.isnan(math.sqrt(NAN)))
 
+    def testSum(self):
+        # math.sum relies on exact rounding for correct operation.
+        # There's a known problem with IA32 floating-point that causes
+        # inexact rounding in some situations, and will cause the
+        # math.sum tests below to fail; see issue #2937.  On non IEEE
+        # 754 platforms, and on IEEE 754 platforms that exhibit the
+        # problem described in issue #2937, we simply skip the whole
+        # test.
+
+        if not float.__getformat__("double").startswith("IEEE"):
+            return
+
+        # on IEEE 754 compliant machines, both of the expressions
+        # below should round to 10000000000000002.0.
+        if 1e16+2.999 != 1e16+2.9999:
+            return
+
+        # Python version of math.sum algorithm, for comparison
+        def msum(iterable):
+            """Full precision sum of values in iterable.  Returns the value of
+            the sum, rounded to the nearest representable floating-point number
+            using the round-half-to-even rule.
+
+            """
+            # Stage 1: accumulate partials
+            partials = []
+            for x in iterable:
+                i = 0
+                for y in partials:
+                    if abs(x) < abs(y):
+                        x, y = y, x
+                    hi = x + y
+                    lo = y - (hi - x)
+                    if lo:
+                        partials[i] = lo
+                        i += 1
+                    x = hi
+                partials[i:] = [x] if x else []
+
+            # Stage 2: sum partials
+            if not partials:
+                return 0.0
+
+            # sum from the top, stopping as soon as the sum is inexact.
+            total = partials.pop()
+            while partials:
+                x = partials.pop()
+                old_total, total = total, total + x
+                error = x - (total - old_total)
+                if error != 0.0:
+                    # adjust for correct rounding if necessary
+                    if partials and (partials[-1] > 0.0) == (error > 0.0) and \
+                            total + 2*error - total == 2*error:
+                        total += 2*error
+                    break
+            return total
+
+        from sys import float_info
+        maxfloat = float_info.max
+        twopow = 2.**(float_info.max_exp - 1)
+
+        test_values = [
+            ([], 0.0),
+            ([0.0], 0.0),
+            ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
+            ([1e308, 1e308, -1e308], OverflowError),
+            ([-1e308, 1e308, 1e308], 1e308),
+            ([1e308, -1e308, 1e308], 1e308),
+            ([2.0**1023, 2.0**1023, -2.0**1000], OverflowError),
+            ([twopow, twopow, twopow, twopow, -twopow, -twopow, -twopow],
+             OverflowError),
+            ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
+            ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
+            ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
+
+            ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
+            ([2.0**1023-2.0**970, -1.0, 2.0**1023], OverflowError),
+            ([maxfloat, maxfloat*2.**-54], maxfloat),
+            ([maxfloat, maxfloat*2.**-53], OverflowError),
+            ([1./n for n in range(1, 1001)], 7.4854708605503451),
+            ([(-1.)**n/n for n in range(1, 1001)], -0.69264743055982025),
+            ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0),
+            ([INF, -INF, NAN], ValueError),
+            ([NAN, INF, -INF], ValueError),
+            ([INF, NAN, INF], ValueError),
+
+            ([INF, INF], OverflowError),
+            ([INF, -INF], ValueError),
+            ([-INF, 1e308, 1e308, -INF], OverflowError),
+            ([2.0**1023-2.0**970, 0.0, 2.0**1023], OverflowError),
+            ([2.0**1023-2.0**970, 1.0, 2.0**1023], OverflowError),
+            ([2.0**1023, 2.0**1023], OverflowError),
+            ([2.0**1023, 2.0**1023, -1.0], OverflowError),
+            ([twopow, twopow, twopow, twopow, -twopow, -twopow],
+             OverflowError),
+            ([twopow, twopow, twopow, twopow, -twopow, twopow], OverflowError),
+            ([-twopow, -twopow, -twopow, -twopow], OverflowError),
+
+            ([2.**1023, 2.**1023, -2.**971], OverflowError),
+            ([2.**1023, 2.**1023, -2.**970], OverflowError),
+            ([-2.**970,  2.**1023,  2.**1023, -2.**-1074], OverflowError),
+            ([ 2.**1023, 2.**1023, -2.**970,   2.**-1074], OverflowError),
+            ([-2.**1023,  2.**971, -2.**1023], -maxfloat),
+            ([-2.**1023, -2.**1023, 2.**970],   OverflowError),
+            ([-2.**1023,  -2.**1023,  2.**970,  2.**-1074], OverflowError),
+            ([-2.**-1074, -2.**1023, -2.**1023, 2.**970], OverflowError),
+            ([2.**930, -2.**980, 2.**1023, 2.**1023, twopow, -twopow],
+             OverflowError),
+            ([2.**1023, 2.**1023, -1e307], OverflowError),
+            ([1e16, 1., 1e-16], 10000000000000002.0),
+            ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
+        ]
+
+        for i, (vals, s) in enumerate(test_values):
+            if isinstance(s, type) and issubclass(s, Exception):
+                try:
+                    m = math.sum(vals)
+                except s:
+                    pass
+                else:
+                    self.fail("test %d failed: got %r, expected %r "
+                              "for math.sum(%.100r)" %
+                              (i, m, s.__name__, vals))
+            else:
+                try:
+                    self.assertEqual(math.sum(vals), s)
+                except OverflowError:
+                    self.fail("test %d failed: got OverflowError, expected %r "
+                              "for math.sum(%.100r)" % (i, s, vals))
+                except ValueError:
+                    self.fail("test %d failed: got ValueError, expected %r "
+                              "for math.sum(%.100r)" % (i, s, vals))
+
+                # compare with output of msum above, but only when
+                # result isn't an IEEE special or an exception
+                if not math.isinf(s) and not math.isnan(s):
+                    self.assertEqual(msum(vals), s)
+
+        from random import random, gauss, shuffle
+        for j in xrange(1000):
+            vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
+            s = 0
+            for i in xrange(200):
+                v = gauss(0, random()) ** 7 - s
+                s += v
+                vals.append(v)
+            shuffle(vals)
+
+            s = msum(vals)
+            self.assertEqual(msum(vals), math.sum(vals))
+
+
     def testTan(self):
         self.assertRaises(TypeError, math.tan)
         self.ftest('tan(0)', math.tan(0), 0)
@@ -766,6 +918,10 @@
                 message = ("Unexpected ValueError in " +
                            "test %s:%s(%r)\n" % (id, fn, ar))
                 self.fail(message)
+            except OverflowError:
+                message = ("Unexpected OverflowError in " +
+                           "test %s:%s(%r)\n" % (id, fn, ar))
+                self.fail(message)
             self.ftest("%s:%s(%r)" % (id, fn, ar), result, er)
 
 def test_main():

Modified: python/branches/okkoto-sizeof/Lib/test/test_minidom.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_minidom.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_minidom.py	Wed Jun  4 11:24:23 2008
@@ -1314,6 +1314,11 @@
             for i in range(len(n1.childNodes)):
                 stack.append((n1.childNodes[i], n2.childNodes[i]))
 
+    def testSerializeCommentNodeWithDoubleHyphen(self):
+        doc = create_doc_without_doctype()
+        doc.appendChild(doc.createComment("foo--bar"))
+        self.assertRaises(ValueError, doc.toxml)
+
 def test_main():
     run_unittest(MinidomTest)
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_mutex.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_mutex.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_mutex.py	Wed Jun  4 11:24:23 2008
@@ -5,26 +5,28 @@
 
 class MutexTest(unittest.TestCase):
 
-    def setUp(self):
-        self.mutex = mutex.mutex()
-
-    def called_by_mutex(self, some_data):
-        self.assert_(self.mutex.test(), "mutex not held")
-        # Nested locking
-        self.mutex.lock(self.called_by_mutex2, "eggs")
-
-    def called_by_mutex2(self, some_data):
-        self.assert_(self.ready_for_2,
-                     "called_by_mutex2 called too soon")
-
     def test_lock_and_unlock(self):
-        self.read_for_2 = False
-        self.mutex.lock(self.called_by_mutex, "spam")
-        self.ready_for_2 = True
+
+        def called_by_mutex(some_data):
+            self.assertEqual(some_data, "spam")
+            self.assert_(m.test(), "mutex not held")
+            # Nested locking
+            m.lock(called_by_mutex2, "eggs")
+
+        def called_by_mutex2(some_data):
+            self.assertEquals(some_data, "eggs")
+            self.assert_(m.test(), "mutex not held")
+            self.assert_(ready_for_2,
+                         "called_by_mutex2 called too soon")
+
+        m = mutex.mutex()
+        read_for_2 = False
+        m.lock(called_by_mutex, "spam")
+        ready_for_2 = True
         # unlock both locks
-        self.mutex.unlock()
-        self.mutex.unlock()
-        self.failIf(self.mutex.test(), "mutex still held")
+        m.unlock()
+        m.unlock()
+        self.failIf(m.test(), "mutex still held")
 
 def test_main():
     test.test_support.run_unittest(MutexTest)

Modified: python/branches/okkoto-sizeof/Lib/test/test_opcodes.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_opcodes.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_opcodes.py	Wed Jun  4 11:24:23 2008
@@ -48,12 +48,12 @@
 
         try: raise AClass, b
         except BClass, v:
-            if v != b: self.fail("v!=b")
+            self.assertEqual(v, b)
         else: self.fail("no exception")
 
         try: raise b
         except AClass, v:
-            if v != b: self.fail("v!=b AClass")
+            self.assertEqual(v, b)
         else:
             self.fail("no exception")
 
@@ -72,35 +72,35 @@
 
         f = eval('lambda: None')
         g = eval('lambda: None')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda a: a')
         g = eval('lambda a: a')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda a=1: a')
         g = eval('lambda a=1: a')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda: 0')
         g = eval('lambda: 1')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda: None')
         g = eval('lambda a: None')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda a: None')
         g = eval('lambda b: None')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda a: None')
         g = eval('lambda a=None: None')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
         f = eval('lambda a=0: None')
         g = eval('lambda a=1: None')
-        self.failIf(f == g)
+        self.assertNotEquals(f, g)
 
 
 def test_main():

Modified: python/branches/okkoto-sizeof/Lib/test/test_platform.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_platform.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_platform.py	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,5 @@
 import sys
+import os
 import unittest
 import platform
 
@@ -63,12 +64,36 @@
 
     def test_mac_ver(self):
         res = platform.mac_ver()
+
         try:
             import gestalt
-        except ImportError: pass
+        except ImportError:
+            have_toolbox_glue = False
         else:
-            if sys.platform == 'darwin':
-                self.assert_(all(res))
+            have_toolbox_glue = True
+
+        if have_toolbox_glue and os.uname()[0] == 'Darwin':
+            # We're on a MacOSX system, check that
+            # the right version information is returned
+            fd = os.popen('sw_vers', 'r')
+            real_ver = None
+            for ln in fd:
+                if ln.startswith('ProductVersion:'):
+                    real_ver = ln.strip().split()[-1]
+                    break
+            fd.close()
+            self.failIf(real_ver is None)
+            self.assertEquals(res[0], real_ver)
+
+            # res[1] claims to contain
+            # (version, dev_stage, non_release_version)
+            # That information is no longer available
+            self.assertEquals(res[1], ('', '', ''))
+
+            if sys.byteorder == 'little':
+                self.assertEquals(res[2], 'i386')
+            else:
+                self.assertEquals(res[2], 'PowerPC')
 
     def test_dist(self):
         res = platform.dist()

Modified: python/branches/okkoto-sizeof/Lib/test/test_poplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_poplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_poplib.py	Wed Jun  4 11:24:23 2008
@@ -40,28 +40,29 @@
         pop.sock.close()
 
     def testTimeoutDefault(self):
-        # default
-        pop = poplib.POP3(HOST, self.port)
-        self.assertTrue(pop.sock.gettimeout() is None)
-        pop.sock.close()
-
-    def testTimeoutValue(self):
-        # a value
-        pop = poplib.POP3(HOST, self.port, timeout=30)
+        self.assertTrue(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            pop = poplib.POP3("localhost", self.port)
+        finally:
+            socket.setdefaulttimeout(None)
         self.assertEqual(pop.sock.gettimeout(), 30)
         pop.sock.close()
 
     def testTimeoutNone(self):
-        # None, having other default
-        previous = socket.getdefaulttimeout()
+        self.assertTrue(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(30)
         try:
             pop = poplib.POP3(HOST, self.port, timeout=None)
         finally:
-            socket.setdefaulttimeout(previous)
-        self.assertEqual(pop.sock.gettimeout(), 30)
+            socket.setdefaulttimeout(None)
+        self.assertTrue(pop.sock.gettimeout() is None)
         pop.sock.close()
 
+    def testTimeoutValue(self):
+        pop = poplib.POP3("localhost", self.port, timeout=30)
+        self.assertEqual(pop.sock.gettimeout(), 30)
+        pop.sock.close()
 
 
 def test_main(verbose=None):

Modified: python/branches/okkoto-sizeof/Lib/test/test_py3kwarn.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_py3kwarn.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_py3kwarn.py	Wed Jun  4 11:24:23 2008
@@ -123,6 +123,13 @@
         with catch_warning() as w:
             self.assertWarning(buffer('a'), w, expected)
 
+    def test_file_xreadlines(self):
+        expected = ("f.xreadlines() not supported in 3.x, "
+                    "try 'for line in f' instead")
+        with file(__file__) as f:
+            with catch_warning() as w:
+                self.assertWarning(f.xreadlines(), w, expected)
+
 
 class TestStdlibRemovals(unittest.TestCase):
 
@@ -130,7 +137,7 @@
     # import side-effect.
     all_platforms = ('audiodev', 'imputil', 'mutex', 'user', 'new', 'rexec',
                         'Bastion', 'compiler', 'dircache', 'fpformat',
-                        'ihooks', 'mhlib', 'statvfs')
+                        'ihooks', 'mhlib', 'statvfs', 'htmllib', 'sgmllib')
     inclusive_platforms = {'irix' : ('pure', 'AL', 'al', 'CD', 'cd', 'cddb',
                                      'cdplayer', 'CL', 'cl', 'DEVICE', 'GL',
                                      'gl', 'ERRNO', 'FILE', 'FL', 'flp', 'fl',
@@ -155,7 +162,7 @@
                            'sunos5' : ('sunaudiodev', 'SUNAUDIODEV'),
                           }
     optional_modules = ('bsddb185', 'Canvas', 'dl', 'linuxaudiodev', 'imageop',
-                        'sv')
+                        'sv', 'cPickle')
 
     def check_removal(self, module_name, optional=False):
         """Make sure the specified module, when imported, raises a
@@ -200,58 +207,32 @@
         for path_mod in ("ntpath", "macpath", "os2emxpath", "posixpath"):
             mod = __import__(path_mod)
             with catch_warning() as w:
-                # Since os3exmpath just imports it from ntpath
-                warnings.simplefilter("always")
-                mod.walk(".", dumbo, None)
+                mod.walk("crashers", dumbo, None)
             self.assertEquals(str(w.message), msg)
 
-
-class TestStdlibRenames(unittest.TestCase):
-
-    renames = {'copy_reg': 'copyreg', 'Queue': 'queue',
-               'SocketServer': 'socketserver',
-               'ConfigParser': 'configparser',
-               'repr': 'reprlib',
-               }
-
-    def check_rename(self, module_name, new_module_name):
-        """Make sure that:
-        - A DeprecationWarning is raised when importing using the
-          old 2.x module name.
-        - The module can be imported using the new 3.x name.
-        - The warning message specify both names.
-        """
-        with CleanImport(module_name):
-            with catch_warning(record=False) as w:
-                warnings.filterwarnings("error", ".+ renamed to",
-                                        DeprecationWarning)
-                try:
-                    __import__(module_name, level=0)
-                except DeprecationWarning as exc:
-                    self.assert_(module_name in exc.args[0])
-                    self.assert_(new_module_name in exc.args[0])
-                else:
-                    self.fail("DeprecationWarning not raised for %s" %
-                              module_name)
-        with CleanImport(new_module_name):
-            try:
-                __import__(new_module_name, level=0)
-            except ImportError:
-                self.fail("cannot import %s with its 3.x name, %s" %
-                          module_name, new_module_name)
-            except DeprecationWarning:
-                self.fail("unexpected DeprecationWarning raised for %s" %
-                          module_name)
-
-    def test_module_renames(self):
-        for module_name, new_module_name in self.renames.items():
-            self.check_rename(module_name, new_module_name)
+    def test_commands_members(self):
+        import commands
+        members = {"mk2arg" : 2, "mkarg" : 1, "getstatus" : 1}
+        for name, arg_count in members.items():
+            with catch_warning(record=False):
+                warnings.filterwarnings("error")
+                func = getattr(commands, name)
+                self.assertRaises(DeprecationWarning, func, *([None]*arg_count))
+
+    def test_mutablestring_removal(self):
+        # UserString.MutableString has been removed in 3.0.
+        import UserString
+        with catch_warning(record=False):
+            warnings.filterwarnings("error", ".*MutableString",
+                                    DeprecationWarning)
+            self.assertRaises(DeprecationWarning, UserString.MutableString)
 
 
 def test_main():
-    run_unittest(TestPy3KWarnings,
-                 TestStdlibRemovals,
-                 TestStdlibRenames)
+    with catch_warning(record=True):
+        warnings.simplefilter("always")
+        run_unittest(TestPy3KWarnings,
+                     TestStdlibRemovals)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/okkoto-sizeof/Lib/test/test_pyclbr.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_pyclbr.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_pyclbr.py	Wed Jun  4 11:24:23 2008
@@ -166,6 +166,7 @@
         cm('cgi', ignore=('log',))      # set with = in module
         cm('urllib', ignore=('_CFNumberToInt32',
                              '_CStringFromCFString',
+                             '_CFSetup',
                              'getproxies_registry',
                              'proxy_bypass_registry',
                              'proxy_bypass_macosx_sysconf',

Modified: python/branches/okkoto-sizeof/Lib/test/test_pydoc.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_pydoc.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_pydoc.py	Wed Jun  4 11:24:23 2008
@@ -1,33 +1,269 @@
-from test import test_support
-import unittest
-import pydoc
-
-class TestDescriptions(unittest.TestCase):
-    def test_module(self):
-        # Check that pydocfodder module can be described
-        from test import pydocfodder
-        doc = pydoc.render_doc(pydocfodder)
-        assert "pydocfodder" in doc
-
-    def test_classic_class(self):
-        class C: "Classic class"
-        c = C()
-        self.failUnlessEqual(pydoc.describe(C), 'class C')
-        self.failUnlessEqual(pydoc.describe(c), 'instance of C')
-        self.failUnless('instance of C in module test.test_pydoc'
-                        in pydoc.render_doc(c))
-
-    def test_class(self):
-        class C(object): "New-style class"
-        c = C()
-
-        self.failUnlessEqual(pydoc.describe(C), 'class C')
-        self.failUnlessEqual(pydoc.describe(c), 'C')
-        self.failUnless('C in module test.test_pydoc object'
-                        in pydoc.render_doc(c))
-
-def test_main():
-    test_support.run_unittest(TestDescriptions)
-
-if __name__ == "__main__":
-    unittest.main()
+import sys
+import os
+import difflib
+import subprocess
+import re
+import pydoc
+import inspect
+import unittest
+import test.test_support
+
+from test import pydoc_mod
+
+expected_text_pattern = \
+"""
+NAME
+    test.pydoc_mod - This is a test module for test_pydoc
+
+FILE
+    %s
+%s
+CLASSES
+    __builtin__.object
+        B
+    A
+\x20\x20\x20\x20
+    class A
+     |  Hello and goodbye
+     |\x20\x20
+     |  Methods defined here:
+     |\x20\x20
+     |  __init__()
+     |      Wow, I have no function!
+\x20\x20\x20\x20
+    class B(__builtin__.object)
+     |  Data descriptors defined here:
+     |\x20\x20
+     |  __dict__
+     |      dictionary for instance variables (if defined)
+     |\x20\x20
+     |  __weakref__
+     |      list of weak references to the object (if defined)
+     |\x20\x20
+     |  ----------------------------------------------------------------------
+     |  Data and other attributes defined here:
+     |\x20\x20
+     |  NO_MEANING = 'eggs'
+
+FUNCTIONS
+    doc_func()
+        This function solves all of the world's problems:
+        hunger
+        lack of Python
+        war
+\x20\x20\x20\x20
+    nodoc_func()
+
+DATA
+    __author__ = 'Benjamin Peterson'
+    __credits__ = 'Nobody'
+    __package__ = None
+    __version__ = '1.2.3.4'
+
+VERSION
+    1.2.3.4
+
+AUTHOR
+    Benjamin Peterson
+
+CREDITS
+    Nobody
+""".strip()
+
+expected_html_pattern = \
+"""
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
+<tr bgcolor="#7799ee">
+<td valign=bottom>&nbsp;<br>
+<font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong><a href="test.html"><font color="#ffffff">test</font></a>.pydoc_mod</strong></big></big> (version 1.2.3.4)</font></td
+><td align=right valign=bottom
+><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
+    <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
+<p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#ee77aa">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
+\x20\x20\x20\x20
+<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
+<td width="100%%"><dl>
+<dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
+</font></dt><dd>
+<dl>
+<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
+</font></dt></dl>
+</dd>
+<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
+</font></dt></dl>
+ <p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#ffc8d8">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a></font></td></tr>
+\x20\x20\x20\x20
+<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
+<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
+<tr><td>&nbsp;</td>
+<td width="100%%">Methods defined here:<br>
+<dl><dt><a name="A-__init__"><strong>__init__</strong></a>()</dt><dd><tt>Wow,&nbsp;I&nbsp;have&nbsp;no&nbsp;function!</tt></dd></dl>
+
+</td></tr></table> <p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#ffc8d8">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
+\x20\x20\x20\x20
+<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
+<td width="100%%">Data descriptors defined here:<br>
+<dl><dt><strong>__dict__</strong></dt>
+<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
+</dl>
+<dl><dt><strong>__weakref__</strong></dt>
+<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
+</dl>
+<hr>
+Data and other attributes defined here:<br>
+<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
+
+</td></tr></table></td></tr></table><p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#eeaa77">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
+\x20\x20\x20\x20
+<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
+<td width="100%%"><dl><dt><a name="-doc_func"><strong>doc_func</strong></a>()</dt><dd><tt>This&nbsp;function&nbsp;solves&nbsp;all&nbsp;of&nbsp;the&nbsp;world's&nbsp;problems:<br>
+hunger<br>
+lack&nbsp;of&nbsp;Python<br>
+war</tt></dd></dl>
+ <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
+</td></tr></table><p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#55aa55">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
+\x20\x20\x20\x20
+<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
+<td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
+<strong>__credits__</strong> = 'Nobody'<br>
+<strong>__package__</strong> = None<br>
+<strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#7799ee">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
+\x20\x20\x20\x20
+<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
+<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
+<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
+<tr bgcolor="#7799ee">
+<td colspan=3 valign=bottom>&nbsp;<br>
+<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
+\x20\x20\x20\x20
+<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
+<td width="100%%">Nobody</td></tr></table>
+""".strip()
+
+
+# output pattern for missing module
+missing_pattern = "no Python documentation found for '%s'"
+
+def run_pydoc(module_name, *args):
+    """
+    Runs pydoc on the specified module. Returns the stripped
+    output of pydoc.
+    """
+    cmd = [sys.executable, pydoc.__file__, " ".join(args), module_name]
+    output = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()
+    return output.strip()
+
+def get_pydoc_html(module):
+    "Returns pydoc generated output as html"
+    doc = pydoc.HTMLDoc()
+    output = doc.docmodule(module)
+    loc = doc.getdocloc(pydoc_mod) or ""
+    if loc:
+        loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
+    return output.strip(), loc
+
+def get_pydoc_text(module):
+    "Returns pydoc generated output as text"
+    doc = pydoc.TextDoc()
+    loc = doc.getdocloc(pydoc_mod) or ""
+    if loc:
+        loc = "\nMODULE DOCS\n    " + loc + "\n"
+
+    output = doc.docmodule(module)
+
+    # cleanup the extra text formatting that pydoc preforms
+    patt = re.compile('\b.')
+    output = patt.sub('', output)
+    return output.strip(), loc
+
+def print_diffs(text1, text2):
+    "Prints unified diffs for two texts"
+    lines1 = text1.splitlines(True)
+    lines2 = text2.splitlines(True)
+    diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
+                                 tofile='got')
+    print '\n' + ''.join(diffs)
+
+
+class PyDocDocTest(unittest.TestCase):
+
+    def test_html_doc(self):
+        result, doc_loc = get_pydoc_html(pydoc_mod)
+        mod_file = inspect.getabsfile(pydoc_mod)
+        expected_html = expected_html_pattern % (mod_file, mod_file, doc_loc)
+        if result != expected_html:
+            print_diffs(expected_html, result)
+            self.fail("outputs are not equal, see diff above")
+
+    def test_text_doc(self):
+        result, doc_loc = get_pydoc_text(pydoc_mod)
+        expected_text = expected_text_pattern % \
+                        (inspect.getabsfile(pydoc_mod), doc_loc)
+        if result != expected_text:
+            print_diffs(expected_text, result)
+            self.fail("outputs are not equal, see diff above")
+
+    def test_not_here(self):
+        missing_module = "test.i_am_not_here"
+        result = run_pydoc(missing_module)
+        expected = missing_pattern % missing_module
+        self.assertEqual(expected, result,
+            "documentation for missing module found")
+
+
+class TestDescriptions(unittest.TestCase):
+
+    def test_module(self):
+        # Check that pydocfodder module can be described
+        from test import pydocfodder
+        doc = pydoc.render_doc(pydocfodder)
+        self.assert_("pydocfodder" in doc)
+
+    def test_classic_class(self):
+        class C: "Classic class"
+        c = C()
+        self.assertEqual(pydoc.describe(C), 'class C')
+        self.assertEqual(pydoc.describe(c), 'instance of C')
+        expected = 'instance of C in module %s' % __name__
+        self.assert_(expected in pydoc.render_doc(c))
+
+    def test_class(self):
+        class C(object): "New-style class"
+        c = C()
+
+        self.assertEqual(pydoc.describe(C), 'class C')
+        self.assertEqual(pydoc.describe(c), 'C')
+        expected = 'C in module %s object' % __name__
+        self.assert_(expected in pydoc.render_doc(c))
+
+
+def test_main():
+    test.test_support.run_unittest(PyDocDocTest,
+                                   TestDescriptions)
+
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/okkoto-sizeof/Lib/test/test_queue.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_queue.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_queue.py	Wed Jun  4 11:24:23 2008
@@ -1,6 +1,6 @@
 # Some simple queue module tests, plus some failure conditions
 # to ensure the Queue locks remain stable.
-import queue
+import Queue
 import sys
 import threading
 import time
@@ -107,12 +107,12 @@
         try:
             q.put("full", block=0)
             self.fail("Didn't appear to block with a full queue")
-        except queue.Full:
+        except Queue.Full:
             pass
         try:
             q.put("full", timeout=0.01)
             self.fail("Didn't appear to time-out with a full queue")
-        except queue.Full:
+        except Queue.Full:
             pass
         # Test a blocking put
         self.do_blocking_test(q.put, ("full",), q.get, ())
@@ -124,12 +124,12 @@
         try:
             q.get(block=0)
             self.fail("Didn't appear to block with an empty queue")
-        except queue.Empty:
+        except Queue.Empty:
             pass
         try:
             q.get(timeout=0.01)
             self.fail("Didn't appear to time-out with an empty queue")
-        except queue.Empty:
+        except Queue.Empty:
             pass
         # Test a blocking get
         self.do_blocking_test(q.get, (), q.put, ('empty',))
@@ -191,13 +191,13 @@
 
 
 class QueueTest(BaseQueueTest):
-    type2test = queue.Queue
+    type2test = Queue.Queue
 
 class LifoQueueTest(BaseQueueTest):
-    type2test = queue.LifoQueue
+    type2test = Queue.LifoQueue
 
 class PriorityQueueTest(BaseQueueTest):
-    type2test = queue.PriorityQueue
+    type2test = Queue.PriorityQueue
 
 
 
@@ -205,21 +205,21 @@
 class FailingQueueException(Exception):
     pass
 
-class FailingQueue(queue.Queue):
+class FailingQueue(Queue.Queue):
     def __init__(self, *args):
         self.fail_next_put = False
         self.fail_next_get = False
-        queue.Queue.__init__(self, *args)
+        Queue.Queue.__init__(self, *args)
     def _put(self, item):
         if self.fail_next_put:
             self.fail_next_put = False
             raise FailingQueueException, "You Lose"
-        return queue.Queue._put(self, item)
+        return Queue.Queue._put(self, item)
     def _get(self):
         if self.fail_next_get:
             self.fail_next_get = False
             raise FailingQueueException, "You Lose"
-        return queue.Queue._get(self)
+        return Queue.Queue._get(self)
 
 class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
 

Deleted: python/branches/okkoto-sizeof/Lib/test/test_reprlib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_reprlib.py	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,327 +0,0 @@
-"""
-  Test cases for the repr module
-  Nick Mathewson
-"""
-
-import sys
-import os
-import shutil
-import unittest
-
-from test.test_support import run_unittest
-from reprlib import repr as r # Don't shadow builtin repr
-from reprlib import Repr
-
-
-def nestedTuple(nesting):
-    t = ()
-    for i in range(nesting):
-        t = (t,)
-    return t
-
-class ReprTests(unittest.TestCase):
-
-    def test_string(self):
-        eq = self.assertEquals
-        eq(r("abc"), "'abc'")
-        eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
-
-        s = "a"*30+"b"*30
-        expected = repr(s)[:13] + "..." + repr(s)[-14:]
-        eq(r(s), expected)
-
-        eq(r("\"'"), repr("\"'"))
-        s = "\""*30+"'"*100
-        expected = repr(s)[:13] + "..." + repr(s)[-14:]
-        eq(r(s), expected)
-
-    def test_tuple(self):
-        eq = self.assertEquals
-        eq(r((1,)), "(1,)")
-
-        t3 = (1, 2, 3)
-        eq(r(t3), "(1, 2, 3)")
-
-        r2 = Repr()
-        r2.maxtuple = 2
-        expected = repr(t3)[:-2] + "...)"
-        eq(r2.repr(t3), expected)
-
-    def test_container(self):
-        from array import array
-        from collections import deque
-
-        eq = self.assertEquals
-        # Tuples give up after 6 elements
-        eq(r(()), "()")
-        eq(r((1,)), "(1,)")
-        eq(r((1, 2, 3)), "(1, 2, 3)")
-        eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
-        eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
-
-        # Lists give up after 6 as well
-        eq(r([]), "[]")
-        eq(r([1]), "[1]")
-        eq(r([1, 2, 3]), "[1, 2, 3]")
-        eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
-        eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
-
-        # Sets give up after 6 as well
-        eq(r(set([])), "set([])")
-        eq(r(set([1])), "set([1])")
-        eq(r(set([1, 2, 3])), "set([1, 2, 3])")
-        eq(r(set([1, 2, 3, 4, 5, 6])), "set([1, 2, 3, 4, 5, 6])")
-        eq(r(set([1, 2, 3, 4, 5, 6, 7])), "set([1, 2, 3, 4, 5, 6, ...])")
-
-        # Frozensets give up after 6 as well
-        eq(r(frozenset([])), "frozenset([])")
-        eq(r(frozenset([1])), "frozenset([1])")
-        eq(r(frozenset([1, 2, 3])), "frozenset([1, 2, 3])")
-        eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset([1, 2, 3, 4, 5, 6])")
-        eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset([1, 2, 3, 4, 5, 6, ...])")
-
-        # collections.deque after 6
-        eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")
-
-        # Dictionaries give up after 4.
-        eq(r({}), "{}")
-        d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
-        eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
-        d['arthur'] = 1
-        eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
-
-        # array.array after 5.
-        eq(r(array('i')), "array('i', [])")
-        eq(r(array('i', [1])), "array('i', [1])")
-        eq(r(array('i', [1, 2])), "array('i', [1, 2])")
-        eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
-        eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
-        eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
-        eq(r(array('i', [1, 2, 3, 4, 5, 6])),
-                   "array('i', [1, 2, 3, 4, 5, ...])")
-
-    def test_numbers(self):
-        eq = self.assertEquals
-        eq(r(123), repr(123))
-        eq(r(123L), repr(123L))
-        eq(r(1.0/3), repr(1.0/3))
-
-        n = 10L**100
-        expected = repr(n)[:18] + "..." + repr(n)[-19:]
-        eq(r(n), expected)
-
-    def test_instance(self):
-        eq = self.assertEquals
-        i1 = ClassWithRepr("a")
-        eq(r(i1), repr(i1))
-
-        i2 = ClassWithRepr("x"*1000)
-        expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
-        eq(r(i2), expected)
-
-        i3 = ClassWithFailingRepr()
-        eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))
-
-        s = r(ClassWithFailingRepr)
-        self.failUnless(s.startswith("<class "))
-        self.failUnless(s.endswith(">"))
-        self.failUnless(s.find("...") == 8)
-
-    def test_file(self):
-        fp = open(unittest.__file__)
-        self.failUnless(repr(fp).startswith(
-            "<open file '%s', mode 'r' at 0x" % unittest.__file__))
-        fp.close()
-        self.failUnless(repr(fp).startswith(
-            "<closed file '%s', mode 'r' at 0x" % unittest.__file__))
-
-    def test_lambda(self):
-        self.failUnless(repr(lambda x: x).startswith(
-            "<function <lambda"))
-        # XXX anonymous functions?  see func_repr
-
-    def test_builtin_function(self):
-        eq = self.assertEquals
-        # Functions
-        eq(repr(hash), '<built-in function hash>')
-        # Methods
-        self.failUnless(repr(''.split).startswith(
-            '<built-in method split of str object at 0x'))
-
-    def test_xrange(self):
-        eq = self.assertEquals
-        eq(repr(xrange(1)), 'xrange(1)')
-        eq(repr(xrange(1, 2)), 'xrange(1, 2)')
-        eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')
-
-    def test_nesting(self):
-        eq = self.assertEquals
-        # everything is meant to give up after 6 levels.
-        eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
-        eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
-
-        eq(r(nestedTuple(6)), "(((((((),),),),),),)")
-        eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
-
-        eq(r({ nestedTuple(5) : nestedTuple(5) }),
-           "{((((((),),),),),): ((((((),),),),),)}")
-        eq(r({ nestedTuple(6) : nestedTuple(6) }),
-           "{((((((...),),),),),): ((((((...),),),),),)}")
-
-        eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
-        eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
-
-    def test_buffer(self):
-        # XXX doesn't test buffers with no b_base or read-write buffers (see
-        # bufferobject.c).  The test is fairly incomplete too.  Sigh.
-        x = buffer('foo')
-        self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
-
-    def test_cell(self):
-        # XXX Hmm? How to get at a cell object?
-        pass
-
-    def test_descriptors(self):
-        eq = self.assertEquals
-        # method descriptors
-        eq(repr(dict.items), "<method 'items' of 'dict' objects>")
-        # XXX member descriptors
-        # XXX attribute descriptors
-        # XXX slot descriptors
-        # static and class methods
-        class C:
-            def foo(cls): pass
-        x = staticmethod(C.foo)
-        self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
-        x = classmethod(C.foo)
-        self.failUnless(repr(x).startswith('<classmethod object at 0x'))
-
-    def test_unsortable(self):
-        # Repr.repr() used to call sorted() on sets, frozensets and dicts
-        # without taking into account that not all objects are comparable
-        x = set([1j, 2j, 3j])
-        y = frozenset(x)
-        z = {1j: 1, 2j: 2}
-        r(x)
-        r(y)
-        r(z)
-
-def touch(path, text=''):
-    fp = open(path, 'w')
-    fp.write(text)
-    fp.close()
-
-class LongReprTest(unittest.TestCase):
-    def setUp(self):
-        longname = 'areallylongpackageandmodulenametotestreprtruncation'
-        self.pkgname = os.path.join(longname)
-        self.subpkgname = os.path.join(longname, longname)
-        # Make the package and subpackage
-        shutil.rmtree(self.pkgname, ignore_errors=True)
-        os.mkdir(self.pkgname)
-        touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
-        shutil.rmtree(self.subpkgname, ignore_errors=True)
-        os.mkdir(self.subpkgname)
-        touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
-        # Remember where we are
-        self.here = os.getcwd()
-        sys.path.insert(0, self.here)
-
-    def tearDown(self):
-        actions = []
-        for dirpath, dirnames, filenames in os.walk(self.pkgname):
-            for name in dirnames + filenames:
-                actions.append(os.path.join(dirpath, name))
-        actions.append(self.pkgname)
-        actions.sort()
-        actions.reverse()
-        for p in actions:
-            if os.path.isdir(p):
-                os.rmdir(p)
-            else:
-                os.remove(p)
-        del sys.path[0]
-
-    def test_module(self):
-        eq = self.assertEquals
-        touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
-        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
-        eq(repr(areallylongpackageandmodulenametotestreprtruncation),
-           "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
-        eq(repr(sys), "<module 'sys' (built-in)>")
-
-    def test_type(self):
-        eq = self.assertEquals
-        touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
-class foo(object):
-    pass
-''')
-        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
-        eq(repr(foo.foo),
-               "<class '%s.foo'>" % foo.__name__)
-
-    def test_object(self):
-        # XXX Test the repr of a type with a really long tp_name but with no
-        # tp_repr.  WIBNI we had ::Inline? :)
-        pass
-
-    def test_class(self):
-        touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
-class bar:
-    pass
-''')
-        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
-        # Module name may be prefixed with "test.", depending on how run.
-        self.failUnless(repr(bar.bar).startswith(
-            "<class %s.bar at 0x" % bar.__name__))
-
-    def test_instance(self):
-        touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
-class baz:
-    pass
-''')
-        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
-        ibaz = baz.baz()
-        self.failUnless(repr(ibaz).startswith(
-            "<%s.baz instance at 0x" % baz.__name__))
-
-    def test_method(self):
-        eq = self.assertEquals
-        touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
-class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
-    def amethod(self): pass
-''')
-        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
-        # Unbound methods first
-        eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
-        '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
-        # Bound method next
-        iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
-        self.failUnless(repr(iqux.amethod).startswith(
-            '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \
-            % (qux.__name__,) ))
-
-    def test_builtin_function(self):
-        # XXX test built-in functions and methods with really long names
-        pass
-
-class ClassWithRepr:
-    def __init__(self, s):
-        self.s = s
-    def __repr__(self):
-        return "ClassWithLongRepr(%r)" % self.s
-
-
-class ClassWithFailingRepr:
-    def __repr__(self):
-        raise Exception("This should be caught by Repr.repr_instance")
-
-
-def test_main():
-    run_unittest(ReprTests)
-    if os.name != 'mac':
-        run_unittest(LongReprTest)
-
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/okkoto-sizeof/Lib/test/test_sgmllib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_sgmllib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_sgmllib.py	Wed Jun  4 11:24:23 2008
@@ -1,8 +1,8 @@
 import pprint
 import re
-import sgmllib
 import unittest
 from test import test_support
+sgmllib = test_support.import_module('sgmllib', deprecated=True)
 
 
 class EventCollector(sgmllib.SGMLParser):

Modified: python/branches/okkoto-sizeof/Lib/test/test_smtplib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_smtplib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_smtplib.py	Wed Jun  4 11:24:23 2008
@@ -54,41 +54,43 @@
     def testBasic1(self):
         # connects
         smtp = smtplib.SMTP(HOST, self.port)
-        smtp.sock.close()
+        smtp.close()
 
     def testBasic2(self):
         # connects, include port in host name
         smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
-        smtp.sock.close()
+        smtp.close()
 
     def testLocalHostName(self):
         # check that supplied local_hostname is used
         smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
         self.assertEqual(smtp.local_hostname, "testhost")
-        smtp.sock.close()
+        smtp.close()
 
     def testTimeoutDefault(self):
-        # default
-        smtp = smtplib.SMTP(HOST, self.port)
-        self.assertTrue(smtp.sock.gettimeout() is None)
-        smtp.sock.close()
-
-    def testTimeoutValue(self):
-        # a value
-        smtp = smtplib.SMTP(HOST, self.port, timeout=30)
+        self.assertTrue(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            smtp = smtplib.SMTP(HOST, self.port)
+        finally:
+            socket.setdefaulttimeout(None)
         self.assertEqual(smtp.sock.gettimeout(), 30)
-        smtp.sock.close()
+        smtp.close()
 
     def testTimeoutNone(self):
-        # None, having other default
-        previous = socket.getdefaulttimeout()
+        self.assertTrue(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(30)
         try:
             smtp = smtplib.SMTP(HOST, self.port, timeout=None)
         finally:
-            socket.setdefaulttimeout(previous)
+            socket.setdefaulttimeout(None)
+        self.assertTrue(smtp.sock.gettimeout() is None)
+        smtp.close()
+
+    def testTimeoutValue(self):
+        smtp = smtplib.SMTP(HOST, self.port, timeout=30)
         self.assertEqual(smtp.sock.gettimeout(), 30)
-        smtp.sock.close()
+        smtp.close()
 
 
 # Test server thread using the specified SMTP server class

Modified: python/branches/okkoto-sizeof/Lib/test/test_socket.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_socket.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_socket.py	Wed Jun  4 11:24:23 2008
@@ -9,7 +9,7 @@
 import thread, threading
 import time
 import traceback
-import queue
+import Queue
 import sys
 import os
 import array
@@ -96,7 +96,7 @@
         self.server_ready = threading.Event()
         self.client_ready = threading.Event()
         self.done = threading.Event()
-        self.queue = queue.Queue(1)
+        self.queue = Queue.Queue(1)
 
         # Do some munging to start the client test.
         methodname = self.id()
@@ -901,8 +901,25 @@
 
     testTimeoutDefault = _justAccept
     def _testTimeoutDefault(self):
-        self.cli = socket.create_connection((HOST, self.port))
-        self.assertTrue(self.cli.gettimeout() is None)
+        # passing no explicit timeout uses socket's global default
+        self.assert_(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(42)
+        try:
+            self.cli = socket.create_connection((HOST, self.port))
+        finally:
+            socket.setdefaulttimeout(None)
+        self.assertEquals(self.cli.gettimeout(), 42)
+
+    testTimeoutNone = _justAccept
+    def _testTimeoutNone(self):
+        # None timeout means the same as sock.settimeout(None)
+        self.assert_(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            self.cli = socket.create_connection((HOST, self.port), timeout=None)
+        finally:
+            socket.setdefaulttimeout(None)
+        self.assertEqual(self.cli.gettimeout(), None)
 
     testTimeoutValueNamed = _justAccept
     def _testTimeoutValueNamed(self):
@@ -914,17 +931,6 @@
         self.cli = socket.create_connection((HOST, self.port), 30)
         self.assertEqual(self.cli.gettimeout(), 30)
 
-    testTimeoutNone = _justAccept
-    def _testTimeoutNone(self):
-        previous = socket.getdefaulttimeout()
-        socket.setdefaulttimeout(30)
-        try:
-            self.cli = socket.create_connection((HOST, self.port), timeout=None)
-        finally:
-            socket.setdefaulttimeout(previous)
-        self.assertEqual(self.cli.gettimeout(), 30)
-
-
 class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
 
     def __init__(self, methodName='runTest'):

Modified: python/branches/okkoto-sizeof/Lib/test/test_socketserver.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_socketserver.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_socketserver.py	Wed Jun  4 11:24:23 2008
@@ -1,5 +1,5 @@
 """
-Test suite for socketserver.
+Test suite for SocketServer.py.
 """
 
 import contextlib
@@ -13,7 +13,7 @@
 import threading
 import time
 import unittest
-import socketserver
+import SocketServer
 
 import test.test_support
 from test.test_support import reap_children, verbose, TestSkipped
@@ -40,12 +40,12 @@
         raise RuntimeError, "timed out on %r" % (sock,)
 
 if HAVE_UNIX_SOCKETS:
-    class ForkingUnixStreamServer(socketserver.ForkingMixIn,
-                                  socketserver.UnixStreamServer):
+    class ForkingUnixStreamServer(SocketServer.ForkingMixIn,
+                                  SocketServer.UnixStreamServer):
         pass
 
-    class ForkingUnixDatagramServer(socketserver.ForkingMixIn,
-                                    socketserver.UnixDatagramServer):
+    class ForkingUnixDatagramServer(SocketServer.ForkingMixIn,
+                                    SocketServer.UnixDatagramServer):
         pass
 
 
@@ -172,55 +172,55 @@
         s.close()
 
     def test_TCPServer(self):
-        self.run_server(socketserver.TCPServer,
-                        socketserver.StreamRequestHandler,
+        self.run_server(SocketServer.TCPServer,
+                        SocketServer.StreamRequestHandler,
                         self.stream_examine)
 
     def test_ThreadingTCPServer(self):
-        self.run_server(socketserver.ThreadingTCPServer,
-                        socketserver.StreamRequestHandler,
+        self.run_server(SocketServer.ThreadingTCPServer,
+                        SocketServer.StreamRequestHandler,
                         self.stream_examine)
 
     if HAVE_FORKING:
         def test_ForkingTCPServer(self):
             with simple_subprocess(self):
-                self.run_server(socketserver.ForkingTCPServer,
-                                socketserver.StreamRequestHandler,
+                self.run_server(SocketServer.ForkingTCPServer,
+                                SocketServer.StreamRequestHandler,
                                 self.stream_examine)
 
     if HAVE_UNIX_SOCKETS:
         def test_UnixStreamServer(self):
-            self.run_server(socketserver.UnixStreamServer,
-                            socketserver.StreamRequestHandler,
+            self.run_server(SocketServer.UnixStreamServer,
+                            SocketServer.StreamRequestHandler,
                             self.stream_examine)
 
         def test_ThreadingUnixStreamServer(self):
-            self.run_server(socketserver.ThreadingUnixStreamServer,
-                            socketserver.StreamRequestHandler,
+            self.run_server(SocketServer.ThreadingUnixStreamServer,
+                            SocketServer.StreamRequestHandler,
                             self.stream_examine)
 
         if HAVE_FORKING:
             def test_ForkingUnixStreamServer(self):
                 with simple_subprocess(self):
                     self.run_server(ForkingUnixStreamServer,
-                                    socketserver.StreamRequestHandler,
+                                    SocketServer.StreamRequestHandler,
                                     self.stream_examine)
 
     def test_UDPServer(self):
-        self.run_server(socketserver.UDPServer,
-                        socketserver.DatagramRequestHandler,
+        self.run_server(SocketServer.UDPServer,
+                        SocketServer.DatagramRequestHandler,
                         self.dgram_examine)
 
     def test_ThreadingUDPServer(self):
-        self.run_server(socketserver.ThreadingUDPServer,
-                        socketserver.DatagramRequestHandler,
+        self.run_server(SocketServer.ThreadingUDPServer,
+                        SocketServer.DatagramRequestHandler,
                         self.dgram_examine)
 
     if HAVE_FORKING:
         def test_ForkingUDPServer(self):
             with simple_subprocess(self):
-                self.run_server(socketserver.ForkingUDPServer,
-                                socketserver.DatagramRequestHandler,
+                self.run_server(SocketServer.ForkingUDPServer,
+                                SocketServer.DatagramRequestHandler,
                                 self.dgram_examine)
 
     # Alas, on Linux (at least) recvfrom() doesn't return a meaningful
@@ -228,19 +228,19 @@
 
     # if HAVE_UNIX_SOCKETS:
     #     def test_UnixDatagramServer(self):
-    #         self.run_server(socketserver.UnixDatagramServer,
-    #                         socketserver.DatagramRequestHandler,
+    #         self.run_server(SocketServer.UnixDatagramServer,
+    #                         SocketServer.DatagramRequestHandler,
     #                         self.dgram_examine)
     #
     #     def test_ThreadingUnixDatagramServer(self):
-    #         self.run_server(socketserver.ThreadingUnixDatagramServer,
-    #                         socketserver.DatagramRequestHandler,
+    #         self.run_server(SocketServer.ThreadingUnixDatagramServer,
+    #                         SocketServer.DatagramRequestHandler,
     #                         self.dgram_examine)
     #
     #     if HAVE_FORKING:
     #         def test_ForkingUnixDatagramServer(self):
-    #             self.run_server(socketserver.ForkingUnixDatagramServer,
-    #                             socketserver.DatagramRequestHandler,
+    #             self.run_server(SocketServer.ForkingUnixDatagramServer,
+    #                             SocketServer.DatagramRequestHandler,
     #                             self.dgram_examine)
 
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_subprocess.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_subprocess.py	Wed Jun  4 11:24:23 2008
@@ -287,14 +287,12 @@
                              stderr=subprocess.PIPE)
         (stdout, stderr) = p.communicate()
         self.assertEqual(stdout, None)
-        # When running with a pydebug build, the # of references is outputted
-        # to stderr, so just check if stderr at least started with "pinapple"
-        self.assert_(stderr.startswith("pineapple"))
+        self.assertEqual(remove_stderr_debug_decorations(stderr), "pineapple")
 
     def test_communicate(self):
         p = subprocess.Popen([sys.executable, "-c",
-                          'import sys,os;' \
-                          'sys.stderr.write("pineapple");' \
+                          'import sys,os;'
+                          'sys.stderr.write("pineapple");'
                           'sys.stdout.write(sys.stdin.read())'],
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
@@ -304,6 +302,22 @@
         self.assertEqual(remove_stderr_debug_decorations(stderr),
                          "pineapple")
 
+    # This test is Linux specific for simplicity to at least have
+    # some coverage.  It is not a platform specific bug.
+    if os.path.isdir('/proc/%d/fd' % os.getpid()):
+        # Test for the fd leak reported in http://bugs.python.org/issue2791.
+        def test_communicate_pipe_fd_leak(self):
+            fd_directory = '/proc/%d/fd' % os.getpid()
+            num_fds_before_popen = len(os.listdir(fd_directory))
+            p = subprocess.Popen([sys.executable, '-c', 'print()'],
+                                 stdout=subprocess.PIPE)
+            p.communicate()
+            num_fds_after_communicate = len(os.listdir(fd_directory))
+            del p
+            num_fds_after_destruction = len(os.listdir(fd_directory))
+            self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
+            self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
+
     def test_communicate_returns(self):
         # communicate() should return None if no redirection is active
         p = subprocess.Popen([sys.executable, "-c",
@@ -534,7 +548,7 @@
             # args is a string
             f, fname = self.mkstemp()
             os.write(f, "#!/bin/sh\n")
-            os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
+            os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
                         sys.executable)
             os.close(f)
             os.chmod(fname, 0700)
@@ -576,7 +590,7 @@
             # call() function with string argument on UNIX
             f, fname = self.mkstemp()
             os.write(f, "#!/bin/sh\n")
-            os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
+            os.write(f, "exec '%s' -c 'import sys; sys.exit(47)'\n" %
                         sys.executable)
             os.close(f)
             os.chmod(fname, 0700)

Modified: python/branches/okkoto-sizeof/Lib/test/test_support.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_support.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_support.py	Wed Jun  4 11:24:23 2008
@@ -13,6 +13,19 @@
 import warnings
 import unittest
 
+__all__ = ["Error", "TestFailed", "TestSkipped", "ResourceDenied", "import_module",
+           "verbose", "use_resources", "max_memuse", "record_original_stdout",
+           "get_original_stdout", "unload", "unlink", "rmtree", "forget",
+           "is_resource_enabled", "requires", "find_unused_port", "bind_port",
+           "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
+           "findfile", "verify", "vereq", "sortdict", "check_syntax_error",
+           "open_urlresource", "WarningMessage", "catch_warning", "CleanImport",
+           "EnvironmentVarGuard", "TransientResource", "captured_output",
+           "captured_stdout", "TransientResource", "transient_internet",
+           "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
+           "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
+           "threading_cleanup", "reap_children"]
+
 class Error(Exception):
     """Base class for regression test exceptions."""
 
@@ -584,11 +597,7 @@
 _1G = 1024 * _1M
 _2G = 2 * _1G
 
-# Hack to get at the maximum value an internal index can take.
-class _Dummy:
-    def __getslice__(self, i, j):
-        return j
-MAX_Py_ssize_t = _Dummy()[:]
+MAX_Py_ssize_t = sys.maxsize
 
 def set_memlimit(limit):
     import re

Modified: python/branches/okkoto-sizeof/Lib/test/test_sys.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_sys.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_sys.py	Wed Jun  4 11:24:23 2008
@@ -385,6 +385,25 @@
 ##        self.assert_(r[0][2] > 100, r[0][2])
 ##        self.assert_(r[1][2] > 100, r[1][2])
 
+    def test_ioencoding(self):
+        import subprocess,os
+        env = dict(os.environ)
+
+        # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
+        # not representable in ASCII.
+
+        env["PYTHONIOENCODING"] = "cp424"
+        p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
+                             stdout = subprocess.PIPE, env=env)
+        out = p.stdout.read().strip()
+        self.assertEqual(out, unichr(0xa2).encode("cp424"))
+
+        env["PYTHONIOENCODING"] = "ascii:replace"
+        p = subprocess.Popen([sys.executable, "-c", 'print unichr(0xa2)'],
+                             stdout = subprocess.PIPE, env=env)
+        out = p.stdout.read().strip()
+        self.assertEqual(out, '?')
+
 
 class SizeofTest(unittest.TestCase):
 
@@ -400,7 +419,7 @@
 
     def tearDown(self):
         self.file.close()
-        os.remove(test.test_support.TESTFN)
+        test.test_support.unlink(test.test_support.TESTFN)
 
     def check_sizeof(self, o, size):
         result = sys.getsizeof(o)
@@ -416,13 +435,13 @@
             return value
 
     def test_align(self):
-        self.assertTrue( (self.align(0) % self.p) == 0 )
-        self.assertTrue( (self.align(1) % self.p) == 0 )
-        self.assertTrue( (self.align(3) % self.p) == 0 )
-        self.assertTrue( (self.align(4) % self.p) == 0 )
-        self.assertTrue( (self.align(7) % self.p) == 0 )
-        self.assertTrue( (self.align(8) % self.p) == 0 )
-        self.assertTrue( (self.align(9) % self.p) == 0 )
+        self.assertEqual(self.align(0) % self.p, 0)
+        self.assertEqual(self.align(1) % self.p, 0)
+        self.assertEqual(self.align(3) % self.p, 0)
+        self.assertEqual(self.align(4) % self.p, 0)
+        self.assertEqual(self.align(7) % self.p, 0)
+        self.assertEqual(self.align(8) % self.p, 0)
+        self.assertEqual(self.align(9) % self.p, 0)
 
     def test_standardtypes(self):
         i = self.i
@@ -433,8 +452,6 @@
         self.check_sizeof(True, h + l)
         # buffer
         self.check_sizeof(buffer(''), h + 2*p + 2*l + self.align(i) +l)
-        # bytearray
-        self.check_sizeof(bytes(), h + self.align(i) + l + p)
         # cell
         def get_cell():
             x = 42
@@ -462,7 +479,7 @@
         self.check_sizeof(reversed(''), h + l + p )
         # file
         self.check_sizeof(self.file, h + 4*p + self.align(2*i) + 4*p +\
-                            self.align(3*i) + 2*p + self.align(i))
+                            self.align(3*i) + 3*p + self.align(i))
         # float
         self.check_sizeof(float(0), h + 8)
         # function
@@ -488,7 +505,7 @@
         self.check_sizeof(abs, h + 3*p)
         # module
         self.check_sizeof(unittest, h + p)
-        # xange
+        # xrange
         self.check_sizeof(xrange(1), h + 3*p)
         # slice
         self.check_sizeof(slice(0), h + 3*p)
@@ -501,8 +518,8 @@
         # type (PyTypeObject + PyNumberMethods +  PyMappingMethods +
         #       PySequenceMethods +  PyBufferProcs)
         len_typeobject = p + 2*l + 15*p + l + 4*p + l + 9*p + l + 11*p
-        self.check_sizeof(class_newstyle, h + \
-                              len_typeobject + 42*p + 10*p + 3*p + 6*p)
+        self.check_sizeof(class_newstyle,
+                          h + len_typeobject + 42*p + 10*p + 3*p + 6*p)
 
 
     def test_specialtypes(self):

Modified: python/branches/okkoto-sizeof/Lib/test/test_tarfile.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_tarfile.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_tarfile.py	Wed Jun  4 11:24:23 2008
@@ -529,7 +529,19 @@
         self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
 
 
-class WriteTest(unittest.TestCase):
+class WriteTestBase(unittest.TestCase):
+    # Put all write tests in here that are supposed to be tested
+    # in all possible mode combinations.
+
+    def test_fileobj_no_close(self):
+        fobj = StringIO.StringIO()
+        tar = tarfile.open(fileobj=fobj, mode=self.mode)
+        tar.addfile(tarfile.TarInfo("foo"))
+        tar.close()
+        self.assert_(fobj.closed is False, "external fileobjs must never closed")
+
+
+class WriteTest(WriteTestBase):
 
     mode = "w:"
 
@@ -652,7 +664,7 @@
             shutil.rmtree(tempdir)
 
 
-class StreamWriteTest(unittest.TestCase):
+class StreamWriteTest(WriteTestBase):
 
     mode = "w|"
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_telnetlib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_telnetlib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_telnetlib.py	Wed Jun  4 11:24:23 2008
@@ -40,34 +40,36 @@
         telnet.sock.close()
 
     def testTimeoutDefault(self):
-        # default
-        telnet = telnetlib.Telnet(HOST, self.port)
-        self.assertTrue(telnet.sock.gettimeout() is None)
-        telnet.sock.close()
-
-    def testTimeoutValue(self):
-        # a value
-        telnet = telnetlib.Telnet(HOST, self.port, timeout=30)
-        self.assertEqual(telnet.sock.gettimeout(), 30)
-        telnet.sock.close()
-
-    def testTimeoutDifferentOrder(self):
-        telnet = telnetlib.Telnet(timeout=30)
-        telnet.open(HOST, self.port)
+        self.assertTrue(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(30)
+        try:
+            telnet = telnetlib.Telnet("localhost", self.port)
+        finally:
+            socket.setdefaulttimeout(None)
         self.assertEqual(telnet.sock.gettimeout(), 30)
         telnet.sock.close()
 
     def testTimeoutNone(self):
         # None, having other default
-        previous = socket.getdefaulttimeout()
+        self.assertTrue(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(30)
         try:
             telnet = telnetlib.Telnet(HOST, self.port, timeout=None)
         finally:
-            socket.setdefaulttimeout(previous)
+            socket.setdefaulttimeout(None)
+        self.assertTrue(telnet.sock.gettimeout() is None)
+        telnet.sock.close()
+
+    def testTimeoutValue(self):
+        telnet = telnetlib.Telnet("localhost", self.port, timeout=30)
         self.assertEqual(telnet.sock.gettimeout(), 30)
         telnet.sock.close()
 
+    def testTimeoutOpen(self):
+        telnet = telnetlib.Telnet()
+        telnet.open("localhost", self.port, timeout=30)
+        self.assertEqual(telnet.sock.gettimeout(), 30)
+        telnet.sock.close()
 
 
 def test_main(verbose=None):

Modified: python/branches/okkoto-sizeof/Lib/test/test_threading.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_threading.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_threading.py	Wed Jun  4 11:24:23 2008
@@ -3,6 +3,7 @@
 import test.test_support
 from test.test_support import verbose
 import random
+import re
 import sys
 import threading
 import thread
@@ -72,6 +73,8 @@
         for i in range(NUMTASKS):
             t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
             threads.append(t)
+            self.failUnlessEqual(t.getIdent(), None)
+            self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
             t.start()
 
         if verbose:
@@ -79,6 +82,8 @@
         for t in threads:
             t.join(NUMTASKS)
             self.assert_(not t.isAlive())
+            self.failIfEqual(t.getIdent(), 0)
+            self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
         if verbose:
             print 'all tasks done'
         self.assertEqual(numrunning.get(), 0)

Modified: python/branches/okkoto-sizeof/Lib/test/test_unicodedata.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_unicodedata.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_unicodedata.py	Wed Jun  4 11:24:23 2008
@@ -103,6 +103,7 @@
         self.assertEqual(self.db.digit(u'9'), 9)
         self.assertEqual(self.db.digit(u'\u215b', None), None)
         self.assertEqual(self.db.digit(u'\u2468'), 9)
+        self.assertEqual(self.db.digit(u'\U00020000', None), None)
 
         self.assertRaises(TypeError, self.db.digit)
         self.assertRaises(TypeError, self.db.digit, u'xx')
@@ -113,6 +114,7 @@
         self.assertEqual(self.db.numeric(u'9'), 9)
         self.assertEqual(self.db.numeric(u'\u215b'), 0.125)
         self.assertEqual(self.db.numeric(u'\u2468'), 9.0)
+        self.assertEqual(self.db.numeric(u'\U00020000', None), None)
 
         self.assertRaises(TypeError, self.db.numeric)
         self.assertRaises(TypeError, self.db.numeric, u'xx')
@@ -123,6 +125,7 @@
         self.assertEqual(self.db.decimal(u'9'), 9)
         self.assertEqual(self.db.decimal(u'\u215b', None), None)
         self.assertEqual(self.db.decimal(u'\u2468', None), None)
+        self.assertEqual(self.db.decimal(u'\U00020000', None), None)
 
         self.assertRaises(TypeError, self.db.decimal)
         self.assertRaises(TypeError, self.db.decimal, u'xx')
@@ -132,6 +135,7 @@
         self.assertEqual(self.db.category(u'\uFFFE'), 'Cn')
         self.assertEqual(self.db.category(u'a'), 'Ll')
         self.assertEqual(self.db.category(u'A'), 'Lu')
+        self.assertEqual(self.db.category(u'\U00020000'), 'Lo')
 
         self.assertRaises(TypeError, self.db.category)
         self.assertRaises(TypeError, self.db.category, u'xx')
@@ -140,6 +144,7 @@
         self.assertEqual(self.db.bidirectional(u'\uFFFE'), '')
         self.assertEqual(self.db.bidirectional(u' '), 'WS')
         self.assertEqual(self.db.bidirectional(u'A'), 'L')
+        self.assertEqual(self.db.bidirectional(u'\U00020000'), 'L')
 
         self.assertRaises(TypeError, self.db.bidirectional)
         self.assertRaises(TypeError, self.db.bidirectional, u'xx')
@@ -155,6 +160,7 @@
         self.assertEqual(self.db.mirrored(u'\uFFFE'), 0)
         self.assertEqual(self.db.mirrored(u'a'), 0)
         self.assertEqual(self.db.mirrored(u'\u2201'), 1)
+        self.assertEqual(self.db.mirrored(u'\U00020000'), 0)
 
         self.assertRaises(TypeError, self.db.mirrored)
         self.assertRaises(TypeError, self.db.mirrored, u'xx')
@@ -163,6 +169,7 @@
         self.assertEqual(self.db.combining(u'\uFFFE'), 0)
         self.assertEqual(self.db.combining(u'a'), 0)
         self.assertEqual(self.db.combining(u'\u20e1'), 230)
+        self.assertEqual(self.db.combining(u'\U00020000'), 0)
 
         self.assertRaises(TypeError, self.db.combining)
         self.assertRaises(TypeError, self.db.combining, u'xx')
@@ -185,6 +192,7 @@
         self.assertEqual(eaw(u'\uFF66'), 'H')
         self.assertEqual(eaw(u'\uFF1F'), 'F')
         self.assertEqual(eaw(u'\u2010'), 'A')
+        self.assertEqual(eaw(u'\U00020000'), 'W')
 
 class UnicodeMiscTest(UnicodeDatabaseTest):
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_urllib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_urllib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_urllib.py	Wed Jun  4 11:24:23 2008
@@ -568,6 +568,7 @@
 # .   Facundo
 #
 # def server(evt):
+#     import socket, time
 #     serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 #     serv.settimeout(3)
 #     serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -592,6 +593,7 @@
 # class FTPWrapperTests(unittest.TestCase):
 #
 #     def setUp(self):
+#         import ftplib, time, threading
 #         ftplib.FTP.port = 9093
 #         self.evt = threading.Event()
 #         threading.Thread(target=server, args=(self.evt,)).start()
@@ -603,31 +605,37 @@
 #     def testBasic(self):
 #         # connects
 #         ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
-#         ftp.ftp.sock.close()
+#         ftp.close()
 #
-#     def testTimeoutDefault(self):
-#         # default
-#         ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
-#         self.assertTrue(ftp.ftp.sock.gettimeout() is None)
-#         ftp.ftp.sock.close()
-#
-#     def testTimeoutValue(self):
-#         # a value
-#         ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [], timeout=30)
+#     def testTimeoutNone(self):
+#         # global default timeout is ignored
+#         import socket
+#         self.assert_(socket.getdefaulttimeout() is None)
+#         socket.setdefaulttimeout(30)
+#         try:
+#             ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
+#         finally:
+#             socket.setdefaulttimeout(None)
 #         self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
-#         ftp.ftp.sock.close()
+#         ftp.close()
 #
-#     def testTimeoutNone(self):
-#         # None, having other default
-#         previous = socket.getdefaulttimeout()
+#     def testTimeoutDefault(self):
+#         # global default timeout is used
+#         import socket
+#         self.assert_(socket.getdefaulttimeout() is None)
 #         socket.setdefaulttimeout(30)
 #         try:
 #             ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
 #         finally:
-#             socket.setdefaulttimeout(previous)
+#             socket.setdefaulttimeout(None)
 #         self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
-#         ftp.ftp.close()
+#         ftp.close()
 #
+#     def testTimeoutValue(self):
+#         ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
+#                                 timeout=30)
+#         self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
+#         ftp.close()
 
 
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_urllib2.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_urllib2.py	Wed Jun  4 11:24:23 2008
@@ -2,6 +2,7 @@
 from test import test_support
 
 import os
+import socket
 import StringIO
 
 import urllib2
@@ -551,14 +552,15 @@
 
         class NullFTPHandler(urllib2.FTPHandler):
             def __init__(self, data): self.data = data
-            def connect_ftp(self, user, passwd, host, port, dirs, timeout=None):
+            def connect_ftp(self, user, passwd, host, port, dirs,
+                            timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
                 self.user, self.passwd = user, passwd
                 self.host, self.port = host, port
                 self.dirs = dirs
                 self.ftpwrapper = MockFTPWrapper(self.data)
                 return self.ftpwrapper
 
-        import ftplib, socket
+        import ftplib
         data = "rheum rhaponicum"
         h = NullFTPHandler(data)
         o = h.parent = MockOpener()
@@ -691,7 +693,7 @@
                 self.req_headers = []
                 self.data = None
                 self.raise_on_endheaders = False
-            def __call__(self, host, timeout=None):
+            def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
                 self.host = host
                 self.timeout = timeout
                 return self

Modified: python/branches/okkoto-sizeof/Lib/test/test_urllib2net.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_urllib2net.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_urllib2net.py	Wed Jun  4 11:24:23 2008
@@ -189,46 +189,58 @@
 
 class TimeoutTest(unittest.TestCase):
     def test_http_basic(self):
+        self.assertTrue(socket.getdefaulttimeout() is None)
         u = _urlopen_with_retry("http://www.python.org")
         self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
 
-    def test_http_NoneWithdefault(self):
-        prev = socket.getdefaulttimeout()
+    def test_http_default_timeout(self):
+        self.assertTrue(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(60)
+        try:
+            u = _urlopen_with_retry("http://www.python.org")
+        finally:
+            socket.setdefaulttimeout(None)
+        self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60)
+
+    def test_http_no_timeout(self):
+        self.assertTrue(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(60)
         try:
             u = _urlopen_with_retry("http://www.python.org", timeout=None)
-            self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60)
         finally:
-            socket.setdefaulttimeout(prev)
+            socket.setdefaulttimeout(None)
+        self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
 
-    def test_http_Value(self):
+    def test_http_timeout(self):
         u = _urlopen_with_retry("http://www.python.org", timeout=120)
         self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120)
 
-    def test_http_NoneNodefault(self):
-        u = _urlopen_with_retry("http://www.python.org", timeout=None)
-        self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
-
     FTP_HOST = "ftp://ftp.mirror.nl/pub/mirror/gnu/"
 
     def test_ftp_basic(self):
+        self.assertTrue(socket.getdefaulttimeout() is None)
         u = _urlopen_with_retry(self.FTP_HOST)
         self.assertTrue(u.fp.fp._sock.gettimeout() is None)
 
-    def test_ftp_NoneWithdefault(self):
-        prev = socket.getdefaulttimeout()
+    def test_ftp_default_timeout(self):
+        self.assertTrue(socket.getdefaulttimeout() is None)
         socket.setdefaulttimeout(60)
         try:
-            u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
-            self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
+            u = _urlopen_with_retry(self.FTP_HOST)
         finally:
-            socket.setdefaulttimeout(prev)
+            socket.setdefaulttimeout(None)
+        self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
 
-    def test_ftp_NoneNodefault(self):
-        u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
+    def test_ftp_no_timeout(self):
+        self.assertTrue(socket.getdefaulttimeout() is None)
+        socket.setdefaulttimeout(60)
+        try:
+            u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
+        finally:
+            socket.setdefaulttimeout(None)
         self.assertTrue(u.fp.fp._sock.gettimeout() is None)
 
-    def test_ftp_Value(self):
+    def test_ftp_timeout(self):
         u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
         self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
 

Modified: python/branches/okkoto-sizeof/Lib/test/test_userstring.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_userstring.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_userstring.py	Wed Jun  4 11:24:23 2008
@@ -4,8 +4,8 @@
 
 import string
 from test import test_support, string_tests
-
 from UserString import UserString, MutableString
+import warnings
 
 class UserStringTest(
     string_tests.CommonTest,
@@ -135,7 +135,10 @@
         self.assertEqual(s, "")
 
 def test_main():
-    test_support.run_unittest(UserStringTest, MutableStringTest)
+    with test_support.catch_warning(record=False):
+        warnings.filterwarnings("ignore", ".*MutableString",
+                                DeprecationWarning)
+        test_support.run_unittest(UserStringTest, MutableStringTest)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/okkoto-sizeof/Lib/test/test_weakref.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_weakref.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_weakref.py	Wed Jun  4 11:24:23 2008
@@ -3,6 +3,7 @@
 import unittest
 import UserList
 import weakref
+import operator
 
 from test import test_support
 
@@ -187,6 +188,26 @@
         self.assertEqual(L3[:5], p3[:5])
         self.assertEqual(L3[2:5], p3[2:5])
 
+    def test_proxy_index(self):
+        class C:
+            def __index__(self):
+                return 10
+        o = C()
+        p = weakref.proxy(o)
+        self.assertEqual(operator.index(p), 10)
+
+    def test_proxy_div(self):
+        class C:
+            def __floordiv__(self, other):
+                return 42
+            def __ifloordiv__(self, other):
+                return 21
+        o = C()
+        p = weakref.proxy(o)
+        self.assertEqual(p // 5, 42)
+        p //= 5
+        self.assertEqual(p, 21)
+
     # The PyWeakref_* C API is documented as allowing either NULL or
     # None as the value for the callback, where either means "no
     # callback".  The "no callback" ref and proxy objects are supposed
@@ -1059,7 +1080,7 @@
     def _reference(self):
         return self.__ref.copy()
 
-libreftest = """ Doctest for examples in the library reference: libweakref.tex
+libreftest = """ Doctest for examples in the library reference: weakref.rst
 
 >>> import weakref
 >>> class Dict(dict):

Modified: python/branches/okkoto-sizeof/Lib/test/test_wsgiref.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_wsgiref.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_wsgiref.py	Wed Jun  4 11:24:23 2008
@@ -8,7 +8,7 @@
 from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, demo_app
 from wsgiref.simple_server import make_server
 from StringIO import StringIO
-from socketserver import BaseServer
+from SocketServer import BaseServer
 import re, sys
 
 from test import test_support

Modified: python/branches/okkoto-sizeof/Lib/test/test_zipfile.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/test/test_zipfile.py	(original)
+++ python/branches/okkoto-sizeof/Lib/test/test_zipfile.py	Wed Jun  4 11:24:23 2008
@@ -132,6 +132,25 @@
         for f in (TESTFN2, TemporaryFile(), StringIO()):
             self.zipOpenTest(f, zipfile.ZIP_STORED)
 
+    def testOpenViaZipInfo(self):
+        # Create the ZIP archive
+        zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
+        zipfp.writestr("name", "foo")
+        zipfp.writestr("name", "bar")
+        zipfp.close()
+
+        zipfp = zipfile.ZipFile(TESTFN2, "r")
+        infos = zipfp.infolist()
+        data = ""
+        for info in infos:
+            data += zipfp.open(info).read()
+        self.assert_(data == "foobar" or data == "barfoo")
+        data = ""
+        for info in infos:
+            data += zipfp.read(info)
+        self.assert_(data == "foobar" or data == "barfoo")
+        zipfp.close()
+
     def zipRandomOpenTest(self, f, compression):
         self.makeTestArchive(f, compression)
 

Modified: python/branches/okkoto-sizeof/Lib/threading.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/threading.py	(original)
+++ python/branches/okkoto-sizeof/Lib/threading.py	Wed Jun  4 11:24:23 2008
@@ -414,6 +414,7 @@
         self.__args = args
         self.__kwargs = kwargs
         self.__daemonic = self._set_daemon()
+        self.__ident = None
         self.__started = Event()
         self.__stopped = False
         self.__block = Condition(Lock())
@@ -434,7 +435,9 @@
         if self.__stopped:
             status = "stopped"
         if self.__daemonic:
-            status = status + " daemon"
+            status += " daemon"
+        if self.__ident is not None:
+            status += " %s" % self.__ident
         return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
 
     def start(self):
@@ -481,9 +484,10 @@
 
     def __bootstrap_inner(self):
         try:
+            self.__ident = _get_ident()
             self.__started.set()
             _active_limbo_lock.acquire()
-            _active[_get_ident()] = self
+            _active[self.__ident] = self
             del _limbo[self]
             _active_limbo_lock.release()
             if __debug__:
@@ -635,6 +639,10 @@
         assert self.__initialized, "Thread.__init__() not called"
         self.__name = str(name)
 
+    def getIdent(self):
+        assert self.__initialized, "Thread.__init__() not called"
+        return self.__ident
+
     def isAlive(self):
         assert self.__initialized, "Thread.__init__() not called"
         return self.__started.isSet() and not self.__stopped

Modified: python/branches/okkoto-sizeof/Lib/urllib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/urllib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/urllib.py	Wed Jun  4 11:24:23 2008
@@ -832,7 +832,8 @@
 class ftpwrapper:
     """Class used by open_ftp() for cache of open FTP connections."""
 
-    def __init__(self, user, passwd, host, port, dirs, timeout=None):
+    def __init__(self, user, passwd, host, port, dirs,
+                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         self.user = user
         self.passwd = passwd
         self.host = host
@@ -1321,6 +1322,24 @@
 
 
 if sys.platform == 'darwin':
+
+    def _CFSetup(sc):
+        from ctypes import c_int32, c_void_p, c_char_p, c_int
+        sc.CFStringCreateWithCString.argtypes = [ c_void_p, c_char_p, c_int32 ]
+        sc.CFStringCreateWithCString.restype = c_void_p
+        sc.SCDynamicStoreCopyProxies.argtypes = [ c_void_p ]
+        sc.SCDynamicStoreCopyProxies.restype = c_void_p
+        sc.CFDictionaryGetValue.argtypes = [ c_void_p, c_void_p ]
+        sc.CFDictionaryGetValue.restype = c_void_p
+        sc.CFStringGetLength.argtypes = [ c_void_p ]
+        sc.CFStringGetLength.restype = c_int32
+        sc.CFStringGetCString.argtypes = [ c_void_p, c_char_p, c_int32, c_int32 ]
+        sc.CFStringGetCString.restype = c_int32
+        sc.CFNumberGetValue.argtypes = [ c_void_p, c_int, c_void_p ]
+        sc.CFNumberGetValue.restype = c_int32
+        sc.CFRelease.argtypes = [ c_void_p ]
+        sc.CFRelease.restype = None
+
     def _CStringFromCFString(sc, value):
         from ctypes import create_string_buffer
         length = sc.CFStringGetLength(value) + 1
@@ -1357,6 +1376,7 @@
             return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
 
         sc = cdll.LoadLibrary(find_library("SystemConfiguration"))
+        _CFSetup(sc)
 
         hostIP = None
 
@@ -1369,6 +1389,8 @@
 
 
         proxyDict = sc.SCDynamicStoreCopyProxies(None)
+        if proxyDict is None:
+            return False
 
         try:
             # Check for simple host names:
@@ -1422,11 +1444,11 @@
         from ctypes.util import find_library
 
         sc = cdll.LoadLibrary(find_library("SystemConfiguration"))
+        _CFSetup(sc)
 
         if not sc:
             return {}
 
-
         kSCPropNetProxiesHTTPEnable = sc.CFStringCreateWithCString(0, "HTTPEnable", 0)
         kSCPropNetProxiesHTTPProxy = sc.CFStringCreateWithCString(0, "HTTPProxy", 0)
         kSCPropNetProxiesHTTPPort = sc.CFStringCreateWithCString(0, "HTTPPort", 0)

Modified: python/branches/okkoto-sizeof/Lib/urllib2.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/urllib2.py	(original)
+++ python/branches/okkoto-sizeof/Lib/urllib2.py	Wed Jun  4 11:24:23 2008
@@ -117,7 +117,7 @@
 __version__ = sys.version[:3]
 
 _opener = None
-def urlopen(url, data=None, timeout=None):
+def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
     global _opener
     if _opener is None:
         _opener = build_opener()
@@ -359,7 +359,7 @@
             if result is not None:
                 return result
 
-    def open(self, fullurl, data=None, timeout=None):
+    def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
         # accept a URL or a Request object
         if isinstance(fullurl, basestring):
             req = Request(fullurl, data)

Modified: python/branches/okkoto-sizeof/Lib/xml/dom/minidom.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/xml/dom/minidom.py	(original)
+++ python/branches/okkoto-sizeof/Lib/xml/dom/minidom.py	Wed Jun  4 11:24:23 2008
@@ -1128,6 +1128,8 @@
         self.data = self.nodeValue = data
 
     def writexml(self, writer, indent="", addindent="", newl=""):
+        if "--" in self.data:
+            raise ValueError("'--' is not allowed in a comment node")
         writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
 
 

Modified: python/branches/okkoto-sizeof/Lib/xmlrpclib.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/xmlrpclib.py	(original)
+++ python/branches/okkoto-sizeof/Lib/xmlrpclib.py	Wed Jun  4 11:24:23 2008
@@ -897,6 +897,7 @@
         self.append(int(data))
         self._value = 0
     dispatch["i4"] = end_int
+    dispatch["i8"] = end_int
     dispatch["int"] = end_int
 
     def end_double(self, data):

Modified: python/branches/okkoto-sizeof/Lib/zipfile.py
==============================================================================
--- python/branches/okkoto-sizeof/Lib/zipfile.py	(original)
+++ python/branches/okkoto-sizeof/Lib/zipfile.py	Wed Jun  4 11:24:23 2008
@@ -776,10 +776,13 @@
         else:
             zef_file = open(self.filename, 'rb')
 
-        # Get info object for name
-        zinfo = self.getinfo(name)
-
-        filepos = zef_file.tell()
+        # Make sure we have an info object
+        if isinstance(name, ZipInfo):
+            # 'name' is already an info object
+            zinfo = name
+        else:
+            # Get info object for name
+            zinfo = self.getinfo(name)
 
         zef_file.seek(zinfo.header_offset, 0)
 
@@ -884,7 +887,7 @@
         if upperdirs and not os.path.exists(upperdirs):
             os.makedirs(upperdirs)
 
-        source = self.open(member.filename, pwd=pwd)
+        source = self.open(member, pwd=pwd)
         target = file(targetpath, "wb")
         shutil.copyfileobj(source, target)
         source.close()

Modified: python/branches/okkoto-sizeof/Mac/Modules/MacOS.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/MacOS.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/MacOS.c	Wed Jun  4 11:24:23 2008
@@ -77,17 +77,17 @@
 	if (!PyArg_ParseTuple(args, "l", &n))
 		return NULL;
 		
-	v = PyString_FromStringAndSize((char *)NULL, n);
+	v = PyBytes_FromStringAndSize((char *)NULL, n);
 	if (v == NULL)
 		return NULL;
 		
-	err = FSRead(self->fRefNum, &n, PyString_AsString(v));
+	err = FSRead(self->fRefNum, &n, PyBytes_AsString(v));
 	if (err && err != eofErr) {
 		PyMac_Error(err);
 		Py_DECREF(v);
 		return NULL;
 	}
-	_PyString_Resize(&v, n);
+	_PyBytes_Resize(&v, n);
 	return v;
 }
 
@@ -301,8 +301,8 @@
 		return NULL;
 	if ((err = FSpGetFInfo(&fss, &info)) != noErr)
 		return PyErr_Mac(MacOS_Error, err);
-	creator = PyString_FromStringAndSize((char *)&info.fdCreator, 4);
-	type = PyString_FromStringAndSize((char *)&info.fdType, 4);
+	creator = PyBytes_FromStringAndSize((char *)&info.fdCreator, 4);
+	type = PyBytes_FromStringAndSize((char *)&info.fdType, 4);
 	res = Py_BuildValue("OO", creator, type);
 	Py_DECREF(creator);
 	Py_DECREF(type);
@@ -623,7 +623,7 @@
 	** some of the image and sound processing interfaces on the mac:-(
 	*/
 	{
-		PyStringObject *p = 0;
+		PyBytesObject *p = 0;
 		long off = (long)&(p->ob_sval[0]);
 		
 		if( PyDict_SetItemString(d, "string_id_to_buffer", Py_BuildValue("i", off)) != 0)

Modified: python/branches/okkoto-sizeof/Mac/Modules/Nav.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/Nav.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/Nav.c	Wed Jun  4 11:24:23 2008
@@ -139,11 +139,11 @@
 	NavGetDefaultDialogOptions(opt);
 
 	while ( PyDict_Next(d, &pos, &key, &value) ) {
-		if ( !key || !value || !PyString_Check(key) ) {
+		if ( !key || !value || !PyBytes_Check(key) ) {
 			PyErr_SetString(ErrorObject, "DialogOption has non-string key");
 			return 0;
 		}
-		keystr = PyString_AsString(key);
+		keystr = PyBytes_AsString(key);
 		if( strcmp(keystr, "defaultLocation") == 0 ) {
 			if ( (defaultLocation_storage = PyMem_NEW(AEDesc, 1)) == NULL ) {
 				PyErr_NoMemory();
@@ -932,7 +932,7 @@
 
 	/* Add some symbolic constants to the module */
 	d = PyModule_GetDict(m);
-	ErrorObject = PyString_FromString("Nav.error");
+	ErrorObject = PyBytes_FromString("Nav.error");
 	PyDict_SetItemString(d, "error", ErrorObject);
 
 	/* XXXX Add constants here */

Modified: python/branches/okkoto-sizeof/Mac/Modules/ae/_AEmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/ae/_AEmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/ae/_AEmodule.c	Wed Jun  4 11:24:23 2008
@@ -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/okkoto-sizeof/Mac/Modules/cf/_CFmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/cf/_CFmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/cf/_CFmodule.c	Wed Jun  4 11:24:23 2008
@@ -392,7 +392,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFTypeRef type-%d object at 0x%8.8x for 0x%8.8x>", (int)CFGetTypeID(self->ob_itself), (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFTypeRefObj_hash(CFTypeRefObject *self)
@@ -596,7 +596,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFArrayRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFArrayRefObj_hash(CFArrayRefObject *self)
@@ -836,7 +836,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFMutableArrayRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFMutableArrayRefObj_hash(CFMutableArrayRefObject *self)
@@ -1029,7 +1029,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFDictionaryRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFDictionaryRefObj_hash(CFDictionaryRefObject *self)
@@ -1206,7 +1206,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFMutableDictionaryRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFMutableDictionaryRefObj_hash(CFMutableDictionaryRefObject *self)
@@ -1327,10 +1327,10 @@
 {
 
 	if (v == Py_None) { *p_itself = NULL; return 1; }
-	if (PyString_Check(v)) {
+	if (PyBytes_Check(v)) {
 	    char *cStr;
 	    Py_ssize_t cLen;
-	    if( PyString_AsStringAndSize(v, &cStr, &cLen) < 0 ) return 0;
+	    if( PyBytes_AsStringAndSize(v, &cStr, &cLen) < 0 ) return 0;
 	    *p_itself = CFDataCreate((CFAllocatorRef)NULL, (unsigned char *)cStr, cLen);
 	    return 1;
 	}
@@ -1405,7 +1405,7 @@
 	int size = CFDataGetLength(_self->ob_itself);
 	char *data = (char *)CFDataGetBytePtr(_self->ob_itself);
 
-	_res = (PyObject *)PyString_FromStringAndSize(data, size);
+	_res = (PyObject *)PyBytes_FromStringAndSize(data, size);
 	return _res;
 
 }
@@ -1437,7 +1437,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFDataRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFDataRefObj_hash(CFDataRefObject *self)
@@ -1702,7 +1702,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFMutableDataRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFMutableDataRefObj_hash(CFMutableDataRefObject *self)
@@ -1823,7 +1823,7 @@
 {
 
 	if (v == Py_None) { *p_itself = NULL; return 1; }
-	if (PyString_Check(v)) {
+	if (PyBytes_Check(v)) {
 	    char *cStr;
 	    if (!PyArg_Parse(v, "es", "ascii", &cStr))
 	        return 0;
@@ -2344,7 +2344,7 @@
 
 	if( data == NULL ) return PyErr_NoMemory();
 	if ( CFStringGetCString(_self->ob_itself, data, size, 0) ) {
-	        _res = (PyObject *)PyString_FromString(data);
+	        _res = (PyObject *)PyBytes_FromString(data);
 	} else {
 	        PyErr_SetString(PyExc_RuntimeError, "CFStringGetCString could not fit the string");
 	        _res = NULL;
@@ -2445,7 +2445,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFStringRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFStringRefObj_hash(CFStringRefObject *self)
@@ -2833,7 +2833,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFMutableStringRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFMutableStringRefObj_hash(CFMutableStringRefObject *self)
@@ -3485,7 +3485,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<CFURL object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int CFURLRefObj_hash(CFURLRefObject *self)

Modified: python/branches/okkoto-sizeof/Mac/Modules/cf/pycfbridge.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/cf/pycfbridge.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/cf/pycfbridge.c	Wed Jun  4 11:24:23 2008
@@ -146,7 +146,7 @@
 int
 PyCF_Python2CF(PyObject *src, CFTypeRef *dst) {
 
-	if (PyString_Check(src) || PyUnicode_Check(src))
+	if (PyBytes_Check(src) || PyUnicode_Check(src))
 		return PyCF_Python2CF_simple(src, dst);
 	if (PySequence_Check(src))
 		return PyCF_Python2CF_sequence(src, (CFArrayRef *)dst);
@@ -249,7 +249,7 @@
 		return (*dst != NULL);
 	}
 #endif
-	if (PyString_Check(src) || PyUnicode_Check(src)) 
+	if (PyBytes_Check(src) || PyUnicode_Check(src)) 
 		return PyCF_Python2CF_string(src, (CFStringRef *)dst);
 	if (PyBool_Check(src)) {
 		if (src == Py_True)
@@ -281,7 +281,7 @@
 	CFIndex size;
 	UniChar *unichars;
 	
-	if (PyString_Check(src)) {
+	if (PyBytes_Check(src)) {
 		if (!PyArg_Parse(src, "es", "ascii", &chars))
 			return 0; /* This error is more descriptive than the general one below */
 		*dst = CFStringCreateWithCString((CFAllocatorRef)NULL, chars, kCFStringEncodingASCII);

Modified: python/branches/okkoto-sizeof/Mac/Modules/file/_Filemodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/file/_Filemodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/file/_Filemodule.c	Wed Jun  4 11:24:23 2008
@@ -915,7 +915,7 @@
 
 	                    size = GetHandleSize((Handle)self->ob_itself);
 	                    HLock((Handle)self->ob_itself);
-	                    rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size);
+	                    rv = PyBytes_FromStringAndSize(*(Handle)self->ob_itself, size);
 	                    HUnlock((Handle)self->ob_itself);
 	                    return rv;
 	            
@@ -1315,7 +1315,7 @@
 	        PyMac_Error(err);
 	        return NULL;
 	}
-	_res = PyString_FromString(strbuf);
+	_res = PyBytes_FromString(strbuf);
 	return _res;
 
 }
@@ -1372,7 +1372,7 @@
 
 static PyObject *FSSpec_get_data(FSSpecObject *self, void *closure)
 {
-	return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
+	return PyBytes_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
 }
 
 #define FSSpec_set_data NULL
@@ -1393,7 +1393,7 @@
 	        self->ob_itself.vRefNum,
 	        self->ob_itself.parID,
 	        self->ob_itself.name[0], self->ob_itself.name+1);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 #define FSSpec_hash NULL
@@ -1925,7 +1925,7 @@
 
 static PyObject *FSRef_get_data(FSRefObject *self, void *closure)
 {
-	return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
+	return PyBytes_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
 }
 
 #define FSRef_set_data NULL
@@ -3038,7 +3038,7 @@
 
 	if (!PyArg_ParseTuple(_args, "O", &obj))
 	        return NULL;
-	if (PyString_Check(obj)) {
+	if (PyBytes_Check(obj)) {
 	        Py_INCREF(obj);
 	        return obj;
 	}
@@ -3201,7 +3201,7 @@
         }
 
         /* On OSX we now try a pathname */
-        if ( PyString_Check(v) || PyUnicode_Check(v)) {
+        if ( PyBytes_Check(v) || PyUnicode_Check(v)) {
                 char *path = NULL;
                 if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path))
                         return 0;

Modified: python/branches/okkoto-sizeof/Mac/Modules/gestaltmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/gestaltmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/gestaltmodule.c	Wed Jun  4 11:24:23 2008
@@ -34,7 +34,7 @@
 {
 	OSErr iErr;
 	OSType selector;
-	long response;
+	SInt32 response;
 	if (!PyArg_ParseTuple(args, "O&", PyMac_GetOSType, &selector))
 		return NULL;
 	iErr = Gestalt ( selector, &response );

Modified: python/branches/okkoto-sizeof/Mac/Modules/qd/_Qdmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/qd/_Qdmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/qd/_Qdmodule.c	Wed Jun  4 11:24:23 2008
@@ -1457,7 +1457,7 @@
 	if ( !PyArg_ParseTuple(_args, "ii", &from, &length) )
 	        return NULL;
 	cp = _self->ob_itself->baseAddr+from;
-	_res = PyString_FromStringAndSize(cp, length);
+	_res = PyBytes_FromStringAndSize(cp, length);
 	return _res;
 
 }
@@ -1510,14 +1510,14 @@
 
 static PyObject *BMObj_get_bitmap_data(BitMapObject *self, void *closure)
 {
-	return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(BitMap));
+	return PyBytes_FromStringAndSize((char *)self->ob_itself, sizeof(BitMap));
 }
 
 #define BMObj_set_bitmap_data NULL
 
 static PyObject *BMObj_get_pixmap_data(BitMapObject *self, void *closure)
 {
-	return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(PixMap));
+	return PyBytes_FromStringAndSize((char *)self->ob_itself, sizeof(PixMap));
 }
 
 #define BMObj_set_pixmap_data NULL
@@ -6500,10 +6500,10 @@
 	int rowbytes;
 	char *data;
 
-	if ( !PyArg_ParseTuple(_args, "O!iO&", &PyString_Type, &source, &rowbytes, PyMac_GetRect,
+	if ( !PyArg_ParseTuple(_args, "O!iO&", &PyBytes_Type, &source, &rowbytes, PyMac_GetRect,
 	                &bounds) )
 	        return NULL;
-	data = PyString_AsString(source);
+	data = PyBytes_AsString(source);
 	if ((ptr=(BitMap *)malloc(sizeof(BitMap))) == NULL )
 	        return PyErr_NoMemory();
 	ptr->baseAddr = (Ptr)data;
@@ -6527,15 +6527,15 @@
 	BitMap *ptr;
 	PyObject *source;
 
-	if ( !PyArg_ParseTuple(_args, "O!", &PyString_Type, &source) )
+	if ( !PyArg_ParseTuple(_args, "O!", &PyBytes_Type, &source) )
 	        return NULL;
-	if ( PyString_Size(source) != sizeof(BitMap) && PyString_Size(source) != sizeof(PixMap) ) {
+	if ( PyBytes_Size(source) != sizeof(BitMap) && PyBytes_Size(source) != sizeof(PixMap) ) {
 	        PyErr_Format(PyExc_TypeError,
 	                "Argument size was %ld, should be %lu (sizeof BitMap) or %lu (sizeof PixMap)",
-	                PyString_Size(source), sizeof(BitMap), sizeof(PixMap));
+	                PyBytes_Size(source), sizeof(BitMap), sizeof(PixMap));
 	        return NULL;
 	}
-	ptr = (BitMapPtr)PyString_AsString(source);
+	ptr = (BitMapPtr)PyBytes_AsString(source);
 	if ( (_res = BMObj_New(ptr)) == NULL ) {
 	        return NULL;
 	}

Modified: python/branches/okkoto-sizeof/Mac/Modules/qdoffs/_Qdoffsmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/qdoffs/_Qdoffsmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/qdoffs/_Qdoffsmodule.c	Wed Jun  4 11:24:23 2008
@@ -608,7 +608,7 @@
 	if ( !PyArg_ParseTuple(_args, "O&ii", ResObj_Convert, &pm, &from, &length) )
 	        return NULL;
 	cp = GetPixBaseAddr(pm)+from;
-	_res = PyString_FromStringAndSize(cp, length);
+	_res = PyBytes_FromStringAndSize(cp, length);
 	return _res;
 
 }

Modified: python/branches/okkoto-sizeof/Mac/Modules/res/_Resmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/res/_Resmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/res/_Resmodule.c	Wed Jun  4 11:24:23 2008
@@ -520,7 +520,7 @@
 
 	            state = HGetState(self->ob_itself);
 	            HLock(self->ob_itself);
-	            res = PyString_FromStringAndSize(
+	            res = PyBytes_FromStringAndSize(
 	                    *self->ob_itself,
 	                    GetHandleSize(self->ob_itself));
 	            HUnlock(self->ob_itself);
@@ -537,10 +537,10 @@
 
 	            if ( v == NULL )
 	                    return -1;
-	            if ( !PyString_Check(v) )
+	            if ( !PyBytes_Check(v) )
 	                    return -1;
-	            size = PyString_Size(v);
-	            data = PyString_AsString(v);
+	            size = PyBytes_Size(v);
+	            data = PyBytes_AsString(v);
 	            /* XXXX Do I need the GetState/SetState calls? */
 	            SetHandleSize(self->ob_itself, size);
 	            if ( MemError())

Modified: python/branches/okkoto-sizeof/Mac/Modules/scrap/_Scrapmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/scrap/_Scrapmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/scrap/_Scrapmodule.c	Wed Jun  4 11:24:23 2008
@@ -105,12 +105,12 @@
 	                          flavorType,
 	                          &byteCount);
 	if (_err != noErr) return PyMac_Error(_err);
-	_res = PyString_FromStringAndSize(NULL, (int)byteCount);
+	_res = PyBytes_FromStringAndSize(NULL, (int)byteCount);
 	if ( _res == NULL ) return NULL;
 	_err = GetScrapFlavorData(_self->ob_itself,
 	                          flavorType,
 	                          &byteCount,
-	                          PyString_AS_STRING(_res));
+	                          PyBytes_AS_STRING(_res));
 	if (_err != noErr) {
 		Py_XDECREF(_res);
 		return PyMac_Error(_err);

Modified: python/branches/okkoto-sizeof/Mac/Modules/snd/_Sndihooks.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/snd/_Sndihooks.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/snd/_Sndihooks.c	Wed Jun  4 11:24:23 2008
@@ -500,7 +500,7 @@
 
 	/* Add some symbolic constants to the module */
 	d = PyModule_GetDict(m);
-	ErrorObject = PyString_FromString("Sndihooks.error");
+	ErrorObject = PyBytes_FromString("Sndihooks.error");
 	PyDict_SetItemString(d, "error", ErrorObject);
 
 	/* XXXX Add constants here */

Modified: python/branches/okkoto-sizeof/Mac/Modules/win/_Winmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Mac/Modules/win/_Winmodule.c	(original)
+++ python/branches/okkoto-sizeof/Mac/Modules/win/_Winmodule.c	Wed Jun  4 11:24:23 2008
@@ -2580,7 +2580,7 @@
 {
 	char buf[100];
 	sprintf(buf, "<Window object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int WinObj_hash(WindowObject *self)

Modified: python/branches/okkoto-sizeof/Makefile.pre.in
==============================================================================
--- python/branches/okkoto-sizeof/Makefile.pre.in	(original)
+++ python/branches/okkoto-sizeof/Makefile.pre.in	Wed Jun  4 11:24:23 2008
@@ -302,6 +302,7 @@
 		Objects/boolobject.o \
 		Objects/bufferobject.o \
 		Objects/bytes_methods.o \
+		Objects/bytearrayobject.o \
 		Objects/bytesobject.o \
 		Objects/cellobject.o \
 		Objects/classobject.o \
@@ -328,7 +329,6 @@
 		Objects/rangeobject.o \
                 Objects/setobject.o \
 		Objects/sliceobject.o \
-		Objects/stringobject.o \
 		Objects/structseq.o \
 		Objects/tupleobject.o \
 		Objects/typeobject.o \
@@ -375,6 +375,12 @@
 build_all_use_profile:
 	$(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use"
 
+coverage:
+	@echo "Building with support for coverage checking:"
+	$(MAKE) clean
+	$(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov"
+
+
 # Build the interpreter
 $(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY)
 		$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \
@@ -578,6 +584,7 @@
 		Include/bitset.h \
 		Include/boolobject.h \
 		Include/bytes_methods.h \
+		Include/bytearrayobject.h \
 		Include/bytesobject.h \
 		Include/bufferobject.h \
 		Include/cellobject.h \

Modified: python/branches/okkoto-sizeof/Misc/ACKS
==============================================================================
--- python/branches/okkoto-sizeof/Misc/ACKS	(original)
+++ python/branches/okkoto-sizeof/Misc/ACKS	Wed Jun  4 11:24:23 2008
@@ -228,6 +228,7 @@
 Lele Gaifax
 Santiago Gala
 Yitzchak Gale
+Quentin Gallet-Gilles
 Raymund Galvin
 Nitin Ganatra
 Fred Gansevles
@@ -376,6 +377,7 @@
 Joseph Koshy
 Bob Kras
 Holger Krekel
+Michael Kremer
 Fabian Kreutz
 Hannu Krosing
 Andrew Kuchling
@@ -410,6 +412,7 @@
 Bjorn Lindqvist
 Per Lindqvist
 Eric Lindvall
+Gregor Lingl
 Nick Lockwood
 Stephanie Lockwood
 Anne Lord
@@ -497,6 +500,7 @@
 Jason Orendorff
 Douglas Orr
 Denis S. Otkidach
+Michael Otteneder
 Russel Owen
 Ondrej Palkovsky
 Mike Pall
@@ -635,6 +639,7 @@
 Rafal Smotrzyk
 Dirk Soede
 Paul Sokolovsky
+Cody Somerville
 Clay Spence
 Per Spilling
 Joshua Spoerri

Modified: python/branches/okkoto-sizeof/Misc/NEWS
==============================================================================
--- python/branches/okkoto-sizeof/Misc/NEWS	(original)
+++ python/branches/okkoto-sizeof/Misc/NEWS	Wed Jun  4 11:24:23 2008
@@ -12,85 +12,178 @@
 Core and Builtins
 -----------------
 
-- Issue #2863: generators now have a ``gen.__name__`` attribute that equals
-  ``gen.gi_code.co_name``, like ``func.__name___`` that equals
-  ``func.func_code.co_name``.  The repr() of a generator now also contains
-  this name.
+- Issue #2898: Added sys.getsizeof() to retrieve size of objects in bytes.
+
+- New environment variable PYTHONIOENCODING.
+
+- Patch #2488: Add sys.maxsize.
+
+- Issue #2353: file.xreadlines() now emits a Py3k warning.
+
+- Issue #2863: generators now have a ``gen.__name__`` attribute that
+  equals ``gen.gi_code.co_name``, like ``func.__name___`` that equals
+  ``func.func_code.co_name``.  The repr() of a generator now also
+  contains this name.
 
 - Issue #2831: enumerate() now has a ``start`` argument.
 
-- Issue #2801: fix bug in the float.is_integer method where a ValueError
-  was sometimes incorrectly raised.
+- Issue #2801: fix bug in the float.is_integer method where a
+  ValueError was sometimes incorrectly raised.
 
-- Issue #2790: sys.flags was not properly exposing its bytes_warning attribute.
+- Issue #2790: sys.flags was not properly exposing its bytes_warning
+  attribute.
 
-- Issue #2196: hasattr now lets exceptions which do not inherit Exception
-  (KeyboardInterrupt, and SystemExit) propagate instead of ignoring them
+- Issue #2196: hasattr() now lets exceptions which do not inherit
+  Exception (KeyboardInterrupt, and SystemExit) propagate instead of
+  ignoring them.
 
 Extension Modules
 -----------------
 
+- The heapq module does comparisons using LT instead of LE.  This
+  makes its implementation match that used by list.sort().
+
+- Issue #2819: add full-precision summation function to math module,
+  based on Hettinger's ASPN Python Cookbook recipe.
+
+- Issue #2592: delegate nb_index and the floor/truediv slots in
+  weakref.proxy.
+
+- Support os.O_ASYNC and fcntl.FASYNC if the constants exist on the
+  platform.
+
 - Support for Windows 9x has been removed from the winsound module.
 
-- bsddb module updated to version 4.6.4.
+- bsddb module updated to version 4.7.0.
+  http://www.jcea.es/programacion/pybsddb.htm#bsddb3-4.7.0
+
+- Issue #2858: Fix potential memory corruption when
+  bsddb.db.DBEnv.lock_get and other bsddb.db object constructors
+  raised an exception.
+
+- Issue #2669: bsddb/__init__.py iteration no longer silently fails when
+  the database has changed size during iteration.  It now raises a
+  RuntimeError in the same manner as a dictionary.
+
+- Issue #2870: cmathmodule.c compile error.
+
+- Added a threading.Thread.getIdent() method.
 
 Library
 -------
 
-- The repr module has been renamed 'reprlib'.  The old name is now
-  deprecated.
+- Patch #2125: Add GetInteger and GetString methods for 
+  msilib.Record objects.
 
-- The statvfs module has been deprecated for removal in Python 3.0.
+- Issue #2782: The datetime module's strftime methods now accept
+  unicode format strings just as time.strftime always has.
+
+- The sgmllib and htmllib modules have been deprecated for removal
+  in Python 3.0.
+
+- Issue #3011: locale module alias table was updated to the latest
+  version from the X.org locale.alias file.
+
+- Issue #1797 (partial fix): ctypes NULL function pointers have a
+  False boolean value now.
+
+- Issue #2985: Allow 64-bit integer responses (``<i8>``) in XMLRPC
+  transfers.
 
-- The sunaudiodev and SUNAUDIODEV modules have been deprecated for removal in
+- Issue #2877: The UserString.MutableString class has been removed in
   Python 3.0.
 
-- The WAIT module from IRIX has been deprecated for removal in Python 3.0.
+- Do not close external file objects passed to tarfile.open(mode='w:bz2')
+  when the TarFile is closed.
 
-- The torgb module from IRIX has been deprecated for removal in Python 3.0.
+- Issue #2959: For consistency with other file-like objects, gzip's
+  GzipFile.close() can now be called multiple times without raising
+  an exception.
 
-- The SV module from IRIX has been deprecated for removal in Python 3.0.
+- Issue #1390: Raise ValueError in toxml when an invalid comment would
+  otherwise be produced.
 
-- The readcd module from IRIX has been deprecated for removal in Python 3.0.
+- Issue #2914: TimedRotatingFileHandler now takes an optional keyword
+  argument "utc" to use UTC time rather than local time.
 
-- The panelparser module from IRIX has been deprecated for removal in
-  Python 3.0.
+- Issue #2929: TimedRotatingFileHandler was using the wrong path when
+  deleting old log files (filename only instead of full path).
+
+- Issue #1775025: You can now specify zipfile members to open(),
+  read() or extract() via a ZipInfo instance.  This allows handling
+  duplicate filenames in zipfiles.
 
--The panel module from IRIX has been deprecated for removal in Python 3.0.
+- Issue #961805: Fix Text.edit_modified() in Tkinter.
 
-- The jpeg module from IRIX has been deprecated for removal in Python 3.0.
+- Issue #1793: Function ctypes.util.find_msvcrt() added that returns
+  the name of the C runtime library that Python uses.
+  ctypes.util.find_library(name) now call this function when name is
+  'm' or 'c'.
 
-- The IOCTL module from IRIX has been deprecated for removal in Python 3.0.
+- The statvfs module has been deprecated for removal in Python 3.0.
 
-- The IN module from IRIX has been deprecated for removal in Python 3.0.
+- The sunaudiodev and SUNAUDIODEV modules have been deprecated for
+  removal in Python 3.0.
 
-- The imgfile module from IRIX has been deprecated for removal in Python 3.0.
+- The WAIT module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The GLWS module from IRIX has been deprecated for removal in Python 3.0.
+- The torgb module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The GET module from IRIX has been deprecated for removal in Python 3.0.
+- The SV module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The fm module from IRIX has been deprecated for removal in Python 3.0.
+- The readcd module from IRIX has been deprecated for removal in
+  Python 3.0.
 
-- The FL, flp, and fl modules from IRIX have been deprecated for removal in
+- The panelparser module from IRIX has been deprecated for removal in
   Python 3.0.
 
-- The FILE module on IRIX has been deprecated for removal in Python 3.0.
+- The panel module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The ERRNO module on IRIX has been deprecated for removal in Python 3.0.
+- The jpeg module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The DEVICE, GL, gl, and cgen modules (which indirectly includes cgensupport)
-  have been deprecated for removal in Python 3.0.
+- The IOCTL module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The ConfigParser module has been renamed 'configparser'.  The old
-  name is now deprecated.
+- The IN module from IRIX has been deprecated for removal in Python
+  3.0.
 
-- The CL, CL_old, and cl modules for IRIX have been deprecated for removal in
+- The imgfile module from IRIX has been deprecated for removal in
   Python 3.0.
 
-- The cdplayer module for IRIX has been deprecated for removal in Python 3.0.
+- The GLWS module from IRIX has been deprecated for removal in Python
+  3.0.
+
+- The GET module from IRIX has been deprecated for removal in Python
+  3.0.
+
+- The fm module from IRIX has been deprecated for removal in Python
+  3.0.
+
+- The FL, flp, and fl modules from IRIX have been deprecated for
+  removal in Python 3.0.
+
+- The FILE module on IRIX has been deprecated for removal in Python
+  3.0.
+
+- The ERRNO module on IRIX has been deprecated for removal in Python
+  3.0.
+
+- The DEVICE, GL, gl, and cgen modules (which indirectly includes
+  cgensupport) have been deprecated for removal in Python 3.0.
 
-- The cddb module for IRIX has been deprecated for removal in Python 3.0.
+- The CL, CL_old, and cl modules for IRIX have been deprecated for
+  removal in Python 3.0.
+
+- The cdplayer module for IRIX has been deprecated for removal in
+  Python 3.0.
+
+- The cddb module for IRIX has been deprecated for removal in Python
+  3.0.
 
 - The cd and CD modules for IRIX have been deprecated for removal in
   Python 3.0.
@@ -98,7 +191,7 @@
 - The al and AL modules for IRIX have been deprecated for removal in
   Python 3.0.
 
-- #1713041: fix pprint's handling of maximum depth.
+- Issue #1713041: fix pprint's handling of maximum depth.
 
 - The timing module has been deprecated for removal in Python 3.0.
 
@@ -106,19 +199,19 @@
 
 - The multifile module has been deprecated as per PEP 4.
 
-- The SocketServer module has been renamed 'socketserver'.  The old
-  name is now deprecated.
-
 - The imageop module has been deprecated for removal in Python 3.0.
 
-- #2250: Exceptions raised during evaluation of names in rlcompleter's
-  ``Completer.complete()`` method are now caught and ignored.
+- Issue #2250: Exceptions raised during evaluation of names in
+  rlcompleter's ``Completer.complete()`` method are now caught and
+  ignored.
 
-- #2659: Added ``break_on_hyphens`` option to textwrap TextWrapper class.
+- Issue #2659: Added ``break_on_hyphens`` option to textwrap
+  TextWrapper class.
 
 - The mhlib module has been deprecated for removal in Python 3.0.
 
-- The linuxaudiodev module has been deprecated for removal in Python 3.0.
+- The linuxaudiodev module has been deprecated for removal in Python
+  3.0.
 
 - The ihooks module has been deprecated for removal in Python 3.0.
 
@@ -130,7 +223,8 @@
 
 - The compiler package has been deprecated for removal in Python 3.0.
 
-- The Bastion and rexec modules have been deprecated for removal in Python 3.0.
+- The Bastion and rexec modules have been deprecated for removal in
+  Python 3.0.
 
 - The bsddb185 module has been deprecated for removal in Python 3.0.
 
@@ -143,7 +237,8 @@
 
 - The toaiff module has been deprecated for removal in Python 3.0.
 
-- The test.testall module has been deprecated for removal in Python 3.0.
+- The test.testall module has been deprecated for removal in Python
+  3.0.
 
 - The new module has been deprecated for removal in Python 3.0.
 
@@ -161,14 +256,28 @@
 
 - pdb gained the "until" command.
 
-- The Mac Modules (including Carbon) have been deprecated for removal in
-  3.0.
+- The Mac Modules (including Carbon) have been deprecated for removal
+  in Python 3.0.
 
 Build
 -----
 
+- Patch #1722225: Support QNX 6.
+
 - ``Lib/lib-old`` is now added to sys.path.
 
+C API
+-----
+
+- Add ``PyType_Modified()`` as a public API to clear the type cache.
+
+- The PyBytes functions have been renamed to PyByteArray.
+
+- The PyString functions have been renamed to PyBytes. A batch of
+  defines were added so that the linker still sees the original
+  PyString names.
+
+
 What's New in Python 2.6 alpha 3?
 =================================
 
@@ -179,51 +288,52 @@
 
 - Issue #2719: backported the ``next()`` builtin from Python 3.
 
-- Issue #2681: The octal literal ``0o8`` was incorrecly acctepted. Now it
-  properly raises a SyntaxError.
+- Issue #2681: The octal literal ``0o8`` was incorrecly acctepted. Now
+  it properly raises a SyntaxError.
 
-- Patch #2617: Reserved -J and -X arguments for Jython, IronPython and other
-  implementations of Python. 
+- Issue #2617: Reserved -J and -X arguments for Jython, IronPython and
+  other implementations of Python.
 
-- Implemented PEP 370: Per user site-packages directory
+- Implemented PEP 370: Per user site-packages directory.
 
 Extension Modules
 -----------------
 
-- Issue #2670:  Fix a failure in urllib2.build_opener(), when passed two
-  handlers that derive the same default base class.
+- Issue #2670: Fix a failure in urllib2.build_opener(), when passed
+  two handlers that derive the same default base class.
 
 - Added kill, terminate and send_signal(sig) to subprocess.Popen.
 
-- Added phase(z) -> phi, polar(z) -> r, phi and rect(r, phi) -> z to the cmath
-  module.
+- Added phase(z) -> phi, polar(z) -> r, phi and rect(r, phi) -> z to
+  the cmath module.
 
-- Four new methods were added to the math and cmath modules:
-  acosh, asinh, atanh and log1p. 
+- Four new methods were added to the math and cmath modules: acosh,
+  asinh, atanh and log1p.
 
-- zlib.decompressobj().flush(value) no longer crashes the interpreter when
-  passed a value less than or equal to zero.
+- zlib.decompressobj().flush(value) no longer crashes the interpreter
+  when passed a value less than or equal to zero.
 
-- Issue #1631171: Re-implement the 'warnings' module in C (the original Python
-  code has been kept as backup). This will allow for using the 'warning's
-  machinery in such places as the parser where use of pure Python code is not
-  possible.  Both the ``showarning()`` and ``formatwarning()`` gain an
-  optional 'line' argument which is not called by default for
-  backwards-compatibility reasons. Setting ``warnings.showwarning()`` to
-  an implementation that lacks support for the ``line`` argument will raise a
-  DeprecationWarning.
+- Issue #1631171: Re-implement the 'warnings' module in C (the
+  original Python code has been kept as backup). This will allow for
+  using the 'warning's machinery in such places as the parser where
+  use of pure Python code is not possible.  Both the ``showarning()``
+  and ``formatwarning()`` gain an optional 'line' argument which is
+  not called by default for backwards-compatibility reasons. Setting
+  ``warnings.showwarning()`` to an implementation that lacks support
+  for the ``line`` argument will raise a DeprecationWarning.
 
 Library
 -------
 
 - The audiodev module has been deprecated for removal in Python 3.0.
 
-- Issue #2750: Add the 'json' package. Based on simplejson 1.9 and contributed
-  by Bob Ippolito.
+- Issue #2750: Add the 'json' package. Based on simplejson 1.9 and
+  contributed by Bob Ippolito.
 
 - Issue #1734346: Support Unicode file names for zipfiles.
 
-- Issue #2581: distutils: Vista UAC/elevation support for bdist_wininst
+- Issue #2581: distutils: Vista UAC/elevation support for
+  bdist_wininst.
 
 - Issue #2635: Fix bug in 'fix_sentence_endings' textwrap.fill option,
   where an extra space was added after a word containing (but not
@@ -248,11 +358,11 @@
 - Issue #2616: The ctypes.pointer() and ctypes.POINTER() functions are
   now implemented in C for better performance.
 
-- Issue #2408: The ``_types`` module, which was used as in implementation
-  detail of the public ``types`` module, has been removed and replaced by pure
-  python code.
+- Issue #2408: The ``_types`` module, which was used as in
+  implementation detail of the public ``types`` module, has been
+  removed and replaced by pure python code.
 
-- Issue #2513: distutils on Windows is now capable of cross-compiling 
+- Issue #2513: distutils on Windows is now capable of cross-compiling
   extension modules between 32 and 64 bit platforms.  See the distutls
   build documentation for more information.
 
@@ -265,49 +375,55 @@
   libffi3.0.5 version, apart from some small changes to
   Modules/_ctypes/libffi/configure.ac.
 
-- Issue #2385: distutils.core.run_script() makes __file__ available, so the
-  controlled environment will more closely mirror the typical script
-  environment.  This supports setup.py scripts that refer to data files.
+- Issue #2385: distutils.core.run_script() makes __file__ available,
+  so the controlled environment will more closely mirror the typical
+  script environment.  This supports setup.py scripts that refer to
+  data files.
 
 Tests
 -----
-- Issue #2550: The approach used by client/server code for obtaining ports
-  to listen on in network-oriented tests has been refined in an effort to
-  facilitate running multiple instances of the entire regression test suite
-  in parallel without issue.  test_support.bind_port() has been fixed such
-  that it will always return a unique port -- which wasn't always the case
-  with the previous implementation, especially if socket options had been
-  set that affected address reuse (i.e. SO_REUSEADDR, SO_REUSEPORT).  The
-  new implementation of bind_port() will actually raise an exception if it
-  is passed an AF_INET/SOCK_STREAM socket with either the SO_REUSEADDR or 
-  SO_REUSEPORT socket option set.  Furthermore, if available, bind_port()
-  will set the SO_EXCLUSIVEADDRUSE option on the socket it's been passed.
-  This currently only applies to Windows.  This option prevents any other
-  sockets from binding to the host/port we've bound to, thus removing the
-  possibility of the 'non-deterministic' behaviour, as Microsoft puts it,
-  that occurs when a second SOCK_STREAM socket binds and accepts to a 
-  host/port that's already been bound by another socket.  The optional 
-  preferred port parameter to bind_port() has been removed.  Under no
+
+- Issue #2550: The approach used by client/server code for obtaining
+  ports to listen on in network-oriented tests has been refined in an
+  effort to facilitate running multiple instances of the entire
+  regression test suite in parallel without issue.
+  test_support.bind_port() has been fixed such that it will always
+  return a unique port -- which wasn't always the case with the
+  previous implementation, especially if socket options had been set
+  that affected address reuse (i.e. SO_REUSEADDR, SO_REUSEPORT).  The
+  new implementation of bind_port() will actually raise an exception
+  if it is passed an AF_INET/SOCK_STREAM socket with either the
+  SO_REUSEADDR or SO_REUSEPORT socket option set.  Furthermore, if
+  available, bind_port() will set the SO_EXCLUSIVEADDRUSE option on
+  the socket it's been passed.  This currently only applies to
+  Windows.  This option prevents any other sockets from binding to the
+  host/port we've bound to, thus removing the possibility of the
+  'non-deterministic' behaviour, as Microsoft puts it, that occurs
+  when a second SOCK_STREAM socket binds and accepts to a host/port
+  that's already been bound by another socket.  The optional preferred
+  port parameter to bind_port() has been removed.  Under no
   circumstances should tests be hard coding ports!
-  
-  test_support.find_unused_port() has also been introduced, which will pass
-  a temporary socket object to bind_port() in order to obtain an unused port.
-  The temporary socket object is then closed and deleted, and the port is
-  returned.  This method should only be used for obtaining an unused port
-  in order to pass to an external program (i.e. the -accept [port] argument
-  to openssl's s_server mode) or as a parameter to a server-oriented class
-  that doesn't give you direct access to the underlying socket used.
 
-  Finally, test_support.HOST has been introduced, which should be used for
-  the host argument of any relevant socket calls (i.e. bind and connect).
+  test_support.find_unused_port() has also been introduced, which will
+  pass a temporary socket object to bind_port() in order to obtain an
+  unused port.  The temporary socket object is then closed and
+  deleted, and the port is returned.  This method should only be used
+  for obtaining an unused port in order to pass to an external program
+  (i.e. the -accept [port] argument to openssl's s_server mode) or as
+  a parameter to a server-oriented class that doesn't give you direct
+  access to the underlying socket used.
+
+  Finally, test_support.HOST has been introduced, which should be used
+  for the host argument of any relevant socket calls (i.e. bind and
+  connect).
 
   The following tests were updated to following the new conventions:
-    test_socket, test_smtplib, test_asyncore, test_ssl, test_httplib, 
+    test_socket, test_smtplib, test_asyncore, test_ssl, test_httplib,
     test_poplib, test_ftplib, test_telnetlib, test_socketserver,
     test_asynchat and test_socket_ssl.
 
-  It is now possible for multiple instances of the regression test suite to
-  run in parallel without issue.
+  It is now possible for multiple instances of the regression test
+  suite to run in parallel without issue.
 
 Build
 -----
@@ -318,18 +434,17 @@
   gcc is used as compiler.
 
 - Issue #2573: On MacOS X it is now possible to install the framework
-  with a different name using --with-framework-name=NAME. 
+  with a different name using --with-framework-name=NAME.
 
 C API
 -----
 
-- Added implementation of copysign, acosh, asinh, atanh and log1p 
-  to the new files Include/pymath.h and Python/pymath.h for 
-  platforms which provide the functions through their libm. The
-  files also contains several helpers and constants for math.
+- Added implementation of copysign, acosh, asinh, atanh and log1p to
+  the new files Include/pymath.h and Python/pymath.h for platforms
+  which provide the functions through their libm. The files also
+  contains several helpers and constants for math.
 
-- Added a new convenience function, PyErr_WarnPy3k, for issuing Py3k
-  warnings.
+- Added a new convenience macro, PyErr_WarnPy3k, for issuing Py3k warnings.
 
 
 What's New in Python 2.6 alpha 2?
@@ -340,9 +455,9 @@
 Core and builtins
 -----------------
 
-- Issue #1733757: The interpreter would hang on shutdown if the tracing 
-  function set by sys.settrace is still active and happens to call
-  threading.currentThread().
+- Issue #1733757: The interpreter would hang on shutdown if the
+  tracing function set by sys.settrace is still active and happens to
+  call threading.currentThread().
 
 - Patch #1442: properly report exceptions when the PYTHONSTARTUP file
   cannot be executed.
@@ -351,10 +466,10 @@
   reference on the outer class name.
 
 - Patch #1810: compile() can now compile _ast trees as returned by
-  compile(..., PyCF_ONLY_AST).
+  ``compile(..., PyCF_ONLY_AST)``.
 
-- Patch #2426: Added sqlite3.Connection.iterdump method to allow easy dumping
-  of databases.  Contributed by Paul Kippes at PyCon 2008.
+- Patch #2426: Added sqlite3.Connection.iterdump method to allow easy
+  dumping of databases.  Contributed by Paul Kippes at PyCon 2008.
 
 - Patch #2477: Added from __future__ import unicode_literals.
 
@@ -363,52 +478,57 @@
 - Issue #2355: add Py3k warning for buffer().
 
 - Issue #1477: With narrow Unicode builds, the unicode escape sequence
-  \Uxxxxxxxx did not accept values outside the Basic Multilingual Plane.  This
-  affected raw unicode literals and the 'raw-unicode-escape' codec.  Now
-  UTF-16 surrogates are generated in this case, like normal unicode literals
-  and the 'unicode-escape' codec.
+  \Uxxxxxxxx did not accept values outside the Basic Multilingual
+  Plane.  This affected raw unicode literals and the
+  'raw-unicode-escape' codec.  Now UTF-16 surrogates are generated in
+  this case, like normal unicode literals and the 'unicode-escape'
+  codec.
 
 - Issue #2348: add Py3k warning for file.softspace.
 
-- Issue #2346/#2347: add Py3k warnings for __methods__ and __members__.
+- Issue #2346/#2347: add Py3k warnings for __methods__ and
+  __members__.
 
 - Issue #2358: Add a Py3k warning on sys.exc_clear() usage.
 
 - Issue #2400: Allow relative imports to "import *".
 
-- Issue 1745.  Backport print function with:
-   from __future__ import print_function
+- Issue #1745: Backport print function with ``from __future__ import
+  print_function``.
 
-- Issue 2332: add new attribute names for instance method objects.
-  The two changes are:  im_self -> __self__ and im_func -> __func__
+- Issue #2332: add new attribute names for instance method objects.
+  The two changes are: im_self -> __self__ and im_func -> __func__
 
-- Issue 2379: Raise a Py3K warning for __getitem__ or __getslice__ on
+- Issue #2379: Raise a Py3K warning for __getitem__ or __getslice__ on
   exception instances.
 
 - Issue #2371: Add a Py3k warning when catching an exception that
-  doesn't derive from BaseException.  Issue #2341: Add a Py3k warning
-  when raising an exception that doesn't derive from BaseException.
+  doesn't derive from BaseException.
+
+- Issue #2341: Add a Py3k warning when raising an exception that
+  doesn't derive from BaseException.
 
 - Issue #2321: use pymalloc for unicode object string data to reduce
   memory usage in some circumstances.
 
-- PEP 3127: octal literals now start with "0o". Old-style octal literals
-  are still valid. There are binary literals with a prefix of "0b".
-  This also affects int(x, 0).
+- PEP 3127: octal literals now start with "0o". Old-style octal
+  literals are still valid. There are binary literals with a prefix of
+  "0b".  This also affects int(x, 0).
 
 - Issue #2359: Adding deprecation warnings for array.{read,write}.
 
-- Issue #1779871: Gnu gcc can now build Python on OS X because the
+- Issue #1779871: GNU gcc can now build Python on OS X because the
   flags -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd are no
   longer passed.
 
 - Add a warning when asserting a non-empty tuple which is always true.
 
-- Issue #2179: speed up with statement execution by storing the exit method
-  on the stack instead of in a temporary variable (patch by Jeffrey Yaskin)
+- Issue #2179: speed up with statement execution by storing the exit
+  method on the stack instead of in a temporary variable (patch by
+  Jeffrey Yaskin)
 
-- Issue #2238: Some syntax errors in *args and **kwargs expressions could give
-  bogus error messages.
+- Issue #2238: Some syntax errors in *args and **kwargs expressions
+  could give bogus error messages.
 
 - Issue #2143: Fix embedded readline() hang on SSL socket EOF.
 
@@ -420,20 +540,22 @@
 Library
 -------
 
-- Issue #2315: logging.handlers: TimedRotatingFileHandler now accounts for
-  daylight savings time in calculating the next rollover.
-
-- Issue #2316: logging.handlers: TimedRotatingFileHandler  now calculates
-  rollovers correctly even when nothing is logged for a while.
+- Issue #2315: logging.handlers: TimedRotatingFileHandler now accounts
+  for daylight savings time in calculating the next rollover.
 
-- Issue #2317: logging.handlers: TimedRotatingFileHandler now uses improved
-  logic for removing old files.
+- Issue #2316: logging.handlers: TimedRotatingFileHandler now
+  calculates rollovers correctly even when nothing is logged for a
+  while.
+
+- Issue #2317: logging.handlers: TimedRotatingFileHandler now uses
+  improved logic for removing old files.
+
+- Issue #2495: tokenize.untokenize now inserts a space between two
+  consecutive string literals; previously, ["" ""] was rendered as
+  [""""], which is incorrect python code.
 
-- Issue #2495: tokenize.untokenize now inserts a space between two consecutive
-  string literals; previously, ["" ""] was rendered as [""""], which is
-  incorrect python code.
-
-- Issue #2248: return the result of the QUIT command. from SMTP.quit().
+- Issue #2248: return the result of the QUIT command. from
+  SMTP.quit().
 
 - Backport of Python 3.0's io module.
 
@@ -446,58 +568,60 @@
 - Issue #2432: give DictReader the dialect and line_num attributes
   advertised in the docs.
 
-- Issue #2460:  Make Ellipsis object copyable.
+- Issue #2460: Make Ellipsis object copyable.
 
-- Issue #1681432:  Add triangular distribution to the random module
+- Issue #1681432: Add triangular distribution to the random module
 
-- Issue #2136: urllib2's auth handler now allows single-quoted realms in the
-  WWW-Authenticate header.
+- Issue #2136: urllib2's auth handler now allows single-quoted realms
+  in the WWW-Authenticate header.
 
 - Issue #2434: Enhanced platform.win32_ver() to also work on Python
   installation which do not have the win32all package installed.
 
-- Added support to platform.uname() to also report the machine
-  and processor information on Windows XP and later. As a result,
+- Added support to platform.uname() to also report the machine and
+  processor information on Windows XP and later. As a result,
   platform.machine() and platform.processor() will report this
   information as well.
 
-- The library implementing the 2to3 conversion, lib2to3, was added
-  to the standard distribution.
+- The library implementing the 2to3 conversion, lib2to3, was added to
+  the standard distribution.
 
-- Issue #1747858: Fix chown to work with large uid's and gid's on 64-bit
-  platforms.
+- Issue #1747858: Fix chown to work with large uid's and gid's on
+  64-bit platforms.
 
-- Issue #1202: zlib.crc32 and zlib.adler32 no longer return different values
-  on 32-bit vs. 64-bit python interpreters.  Both were correct, but they now
-  both return a signed integer object for consistency.
+- Issue #1202: zlib.crc32 and zlib.adler32 no longer return different
+  values on 32-bit vs. 64-bit python interpreters.  Both were correct,
+  but they now both return a signed integer object for consistency.
 
 - Issue #1158: add %f format (fractions of a second represented as
   microseconds) to datetime objects.  Understood by both strptime and
   strftime.
 
 - Issue #705836: struct.pack(">f", x) now raises OverflowError on all
-  platforms when x is too large to fit into an IEEE 754 float; previously
-  it only raised OverflowError on non IEEE 754 platforms.
+  platforms when x is too large to fit into an IEEE 754 float;
+  previously it only raised OverflowError on non IEEE 754 platforms.
 
 - Issues #2166, #1741 and #1531505: now distutils deals with HOME
   correctly under win32
 
-- #1858: distutils: added multiple server support in .pypirc
+- Patch #1858: distutils: added multiple server support in .pypirc
 
 - Issue #1106316: pdb.post_mortem()'s parameter, "traceback", is now
-  optional: it defaults to the traceback of the exception that is currently
-  being handled (is mandatory to be in the middle of an exception, otherwise
-  it raises ValueError).
+  optional: it defaults to the traceback of the exception that is
+  currently being handled (is mandatory to be in the middle of an
+  exception, otherwise it raises ValueError).
 
 - Issue #1193577: A .shutdown() method has been added to SocketServers
   which terminates the .serve_forever() loop.
 
-- Bug #2220: handle rlcompleter attribute match failure more gracefully.
+- Issue #2220: handle rlcompleter attribute match failure more
+  gracefully.
 
-- Issue #2225: py_compile, when executed as a script, now returns a non-
-  zero status code if not all files could be compiled successfully.
+- Issue #2225: py_compile, when executed as a script, now returns a
+  non- zero status code if not all files could be compiled
+  successfully.
 
-- Bug #1725737: In distutil's sdist, exclude RCS, CVS etc. also in the
+- Bug #1725737: In distutils' sdist, exclude RCS, CVS etc. also in the
   root directory, and also exclude .hg, .git, .bzr, and _darcs.
 
 - Issue #1872: The struct module typecode for _Bool has been changed
@@ -505,19 +629,18 @@
 
 - The bundled libffi copy is now in sync with the recently released
   libffi3.0.4 version, apart from some small changes to
-  Modules/_ctypes/libffi/configure.ac.
-  On OS X, preconfigured libffi files are used.
-  On all linux systems the --with-system-ffi configure option defaults
-  to "yes".
+  Modules/_ctypes/libffi/configure.ac.  On OS X, preconfigured libffi
+  files are used.  On all linux systems the --with-system-ffi
+  configure option defaults to "yes".
 
-- Issue 1577: shutil.move() now calls os.rename() if the destination is a
-  directory instead of copying-then-remove-source.
+- Issue #1577: shutil.move() now calls os.rename() if the destination
+  is a directory instead of copying-then-remove-source.
 
 Tests
 -----
 
-- test_nis no longer fails when test.test_support.verbose is true and NIS is
-  not set up on the testing machine.
+- test_nis no longer fails when test.test_support.verbose is true and
+  NIS is not set up on the testing machine.
 
 - Output comparison tests are no longer supported.
 
@@ -527,13 +650,15 @@
 
 - GHOP 290: Convert test_dbm and test_dummy_threading to unittest.
 
-- GHOP 293: Convert test_strftime, test_getargs, and test_pep247 to unittest.
+- GHOP 293: Convert test_strftime, test_getargs, and test_pep247 to
+  unittest.
 
 - Issue #2055: Convert test_fcntl to unittest.
 
 - Issue 1960: Convert test_gdbm to unittest.
 
-- GHOP 294: Convert test_contains, test_crypt, and test_select to unittest.
+- GHOP 294: Convert test_contains, test_crypt, and test_select to
+  unittest.
 
 - GHOP 238: Convert test_tokenize to use doctest.
 
@@ -547,8 +672,8 @@
 
 - A new script 2to3 is now installed, to run the 2.x to 3.x converter.
 
-- Python/memmove.c and Python/strerror.c have been removed; both functions are
-  in the C89 standard library.
+- Python/memmove.c and Python/strerror.c have been removed; both
+  functions are in the C89 standard library.
 
 - Patch #2284: Add -x64 option to rt.bat.
 
@@ -556,7 +681,8 @@
 -----
 
 - Patch #2477: Added PyParser_ParseFileFlagsEx() and
-  PyParser_ParseStringFlagsFilenameEx()
+  PyParser_ParseStringFlagsFilenameEx().
+
 
 What's New in Python 2.6 alpha 1?
 =================================
@@ -597,56 +723,59 @@
   datetime; the class string.Formatter; and the C API
   PyObject_Format().
 
-- Fixed several potential crashes, all caused by specially crafted __del__
-  methods exploiting objects in temporarily inconsistent state.
+- Fixed several potential crashes, all caused by specially crafted
+  __del__ methods exploiting objects in temporarily inconsistent
+  state.
 
 - Issue #2115: Important speedup in setting __slot__ attributes.  Also
-  prevent a possible crash: an Abstract Base Class would try to access a slot
-  on a registered virtual subclass.
+  prevent a possible crash: an Abstract Base Class would try to access
+  a slot on a registered virtual subclass.
 
-- Fixed repr() and str() of complex numbers with infinity or nan as real or
-  imaginary part.
+- Fixed repr() and str() of complex numbers with infinity or nan as
+  real or imaginary part.
 
-- Clear all free lists during a gc.collect() of the highest generation in order
-  to allow pymalloc to free more arenas. Python may give back memory to the
-  OS earlier.
-
-- Issue #2045: Fix an infinite recursion triggered when printing a subclass of
-  collections.defaultdict, if its default_factory is set to a bound method.
+- Clear all free lists during a gc.collect() of the highest generation
+  in order to allow pymalloc to free more arenas. Python may give back
+  memory to the OS earlier.
+
+- Issue #2045: Fix an infinite recursion triggered when printing a
+  subclass of collections.defaultdict, if its default_factory is set
+  to a bound method.
 
 - Fixed a minor memory leak in dictobject.c. The content of the free
   list was not freed on interpreter shutdown.
 
-- Limit free list of method and builtin function objects to 256 entries
-  each.
+- Limit free list of method and builtin function objects to 256
+  entries each.
 
-- Patch #1953: Added ``sys._compact_freelists()`` and the C API functions
-  ``PyInt_CompactFreeList`` and ``PyFloat_CompactFreeList``
+- Patch #1953: Added ``sys._compact_freelists()`` and the C API
+  functions ``PyInt_CompactFreeList`` and ``PyFloat_CompactFreeList``
   to compact the internal free lists of pre-allocted ints and floats.
 
-- Bug #1983: Fixed return type of fork(), fork1() and forkpty() calls.
-  Python expected the return type int but the fork familie returns pi_t.
-
-- Issue #1678380: Fix a bug that identifies 0j and -0j when they appear
-  in the same code unit.
-
-- Issue #2025 :  Add tuple.count() and tuple.index() methods to comply with
-  the collections.Sequence API.
-
-- Patch #1970 by Antoine Pitrou: Speedup unicode whitespace and linebreak
-  detection
-
-- Added ``PyType_ClearCache()`` and ``sys._clear_type_cache`` to clear the
-  internal lookup cache for ref leak tests.
-
-- Patch #1473257: generator objects gain a gi_code attribute. This is the
-  same object as the func_code attribute of the function that produced the
-  generator.
-
-- Issue #1920: "while 0" statements were completely removed by the compiler,
-  even in the presence of an "else" clause, which is supposed to be run when
-  the condition is false. Now the compiler correctly emits bytecode for the
-  "else" suite.
+- Issue #1983: Fixed return type of fork(), fork1() and forkpty()
+  calls.  Python expected the return type int but the fork familie
+  returns pi_t.
+
+- Issue #1678380: Fix a bug that identifies 0j and -0j when they
+  appear in the same code unit.
+
+- Issue #2025: Add tuple.count() and tuple.index() methods to comply
+  with the collections.Sequence API.
+
+- Patch #1970 by Antoine Pitrou: Speedup unicode whitespace and
+  linebreak detection
+
+- Added ``PyType_ClearCache()`` and ``sys._clear_type_cache`` to clear
+  the internal lookup cache for ref leak tests.
+
+- Patch #1473257: generator objects gain a gi_code attribute. This is
+  the same object as the func_code attribute of the function that
+  produced the generator.
+
+- Issue #1920: "while 0" statements were completely removed by the
+  compiler, even in the presence of an "else" clause, which is
+  supposed to be run when the condition is false. Now the compiler
+  correctly emits bytecode for the "else" suite.
 
 - A few crashers fixed: weakref_in_del.py (issue #1377858);
   loosing_dict_ref.py (issue #1303614, test67.py);
@@ -656,7 +785,7 @@
   suppressed while an extension is loaded by calling SetErrorMode in
   dynload_win.c. The error is still reported properly.
 
-- Bug #1915: Python compiles with --enable-unicode=no again. However
+- Issue #1915: Python compiles with --enable-unicode=no again. However
   several extension methods and modules do not work without unicode
   support.
 
@@ -671,48 +800,50 @@
 - sys.float_info / PyFloat_GetInfo: The floating point information
   object was converted from a dict to a specialized structseq object.
 
-- Patch #1816: Added sys.flags structseq. It exposes the status of most
-  command line arguments and PYTHON* environment variables.
+- Patch #1816: Added sys.flags structseq. It exposes the status of
+  most command line arguments and PYTHON* environment variables.
 
-- Objects/structseq.c: Implemented new structseq representation. The patch
-  makes structseqs (e.g. the return value of os.stat) more readable.
+- Objects/structseq.c: Implemented new structseq representation. The
+  patch makes structseqs (e.g. the return value of os.stat) more
+  readable.
 
-- Patch #1700288: added a type attribute cache that caches method accesses,
-  resulting in speedups in heavily object-oriented code.
+- Patch #1700288: added a type attribute cache that caches method
+  accesses, resulting in speedups in heavily object-oriented code.
 
 - Bug #1776: __import__() no longer accepts filenames on any platform.
   The first parameter to __import__() must be a valid module name.
 
 - Patch #1668: renamed THREADDEBUG envvar to PYTHONTHREADDEBUG.
 
-- Patch #602345: Add -B command line option, PYTHONDONTWRITEBYTECODE envvar
-  and sys.dont_write_bytecode attribute. All these can be set to forbid Python
-  to attempt to write compiled bytecode files.
-
-- Improve some exception messages when Windows fails to load an extension
-  module. Now we get for example '%1 is not a valid Win32 application' instead
-  of 'error code 193'.
+- Patch #602345: Add -B command line option, PYTHONDONTWRITEBYTECODE
+  envvar and sys.dont_write_bytecode attribute. All these can be set
+  to forbid Python to attempt to write compiled bytecode files.
+
+- Improve some exception messages when Windows fails to load an
+  extension module. Now we get for example '%1 is not a valid Win32
+  application' instead of 'error code 193'.
 
-- Bug #1481296: Fixed long(float('nan'))!=0L.
+- Bug #1481296: Fixed long(float('nan')) != 0L.
 
-- Issue #1640: Added math.isinf(x), math.isnan(x) and math.copysign(x, y)
-  functions.
+- Issue #1640: Added math.isinf(x), math.isnan(x) and math.copysign(x,
+  y) functions.
 
 - Issue #1635: Platform independent creation and representation of NaN
-  and INF. float("nan"), float("inf") and float("-inf") now work on every
-  platform with IEEE 754 semantics.
+  and INF. float("nan"), float("inf") and float("-inf") now work on
+  every platform with IEEE 754 semantics.
 
-- Compiler now generates simpler and faster code for dictionary literals.
-  The oparg for BUILD_MAP now indicates an estimated dictionary size.
-  There is a new opcode, STORE_MAP, for adding entries to the dictionary.
+- Compiler now generates simpler and faster code for dictionary
+  literals.  The oparg for BUILD_MAP now indicates an estimated
+  dictionary size.  There is a new opcode, STORE_MAP, for adding
+  entries to the dictionary.
 
-- Issue #1638: %zd configure test fails on Linux
+- Issue #1638: %zd configure test fails on Linux.
 
-- Issue #1620: New property decorator syntax was modifying the decorator
-  in place instead of creating a new decorator object.
+- Issue #1620: New property decorator syntax was modifying the
+  decorator in place instead of creating a new decorator object.
 
-- Issue #1538: Avoid copying string in split/rsplit if the split
-  char is not found.
+- Issue #1538: Avoid copying string in split/rsplit if the split char
+  is not found.
 
 - Issue #1553: An erroneous __length_hint__ can make list() raise a
   SystemError.
@@ -721,25 +852,26 @@
   inside packages with the -m switch via a new module level
   __package__ attribute.
 
-- Issue #1402: Fix a crash on exit, when another thread is still running, and
-  if the deallocation of its frames somehow calls the PyGILState_Ensure() /
-  PyGILState_Release() functions.
+- Issue #1402: Fix a crash on exit, when another thread is still
+  running, and if the deallocation of its frames somehow calls the
+  PyGILState_Ensure() / PyGILState_Release() functions.
 
 - Expose the Py_Py3kWarningFlag as sys.py3kwarning.
 
 - Issue #1445: Fix a SystemError when accessing the ``cell_contents``
   attribute of an empty cell object.
 
-- Issue #1460: The utf-7 incremental decoder did not accept truncated input.
-  It now correctly saves its state between chunks of data.
+- Issue #1460: The utf-7 incremental decoder did not accept truncated
+  input.  It now correctly saves its state between chunks of data.
 
-- Patch #1739468: Directories and zipfiles containing a __main__.py file can
-  now be directly executed by passing their name to the interpreter. The
-  directory/zipfile is automatically inserted as the first entry in sys.path.
-
-- Issue #1265: Fix a problem with sys.settrace, if the tracing function uses a
-  generator expression when at the same time the executed code is closing a
-  paused generator.
+- Patch #1739468: Directories and zipfiles containing a __main__.py
+  file can now be directly executed by passing their name to the
+  interpreter. The directory/zipfile is automatically inserted as the
+  first entry in sys.path.
+
+- Issue #1265: Fix a problem with sys.settrace, if the tracing
+  function uses a generator expression when at the same time the
+  executed code is closing a paused generator.
 
 - sets and frozensets now have an isdisjoint() method.
 
@@ -747,48 +879,53 @@
 
 - Fix warnings found by the new version of the Coverity checker.
 
-- The enumerate() builtin function is no longer bounded to sequences smaller
-  than LONG_MAX.  Formerly, it raised an OverflowError.  Now, automatically
-  shifts from ints to longs.
-
-- Issue #1686386: Tuple's tp_repr did not take into account the possibility of
-  having a self-referential tuple, which is possible from C code.  Nor did
-  object's tp_str consider that a type's tp_str could do something that could
-  lead to an inifinite recursion.  Py_ReprEnter() and Py_EnterRecursiveCall(),
-  respectively, fixed the issues.
-
-- Issue #1164: It was possible to trigger deadlock when using the 'print'
-  statement to write to a file since the GIL was not released as needed.  Now
-  PyObject_Print() does the right thing along with various tp_print
-  implementations of the built-in types and those in the collections module.
-
-- Issue #1147: Exceptions were directly allowing string exceptions in their
-  throw() method even though string exceptions no longer allowed.
+- The enumerate() builtin function is no longer bounded to sequences
+  smaller than LONG_MAX.  Formerly, it raised an OverflowError.  Now,
+  automatically shifts from ints to longs.
+
+- Issue #1686386: Tuple's tp_repr did not take into account the
+  possibility of having a self-referential tuple, which is possible
+  from C code.  Nor did object's tp_str consider that a type's tp_str
+  could do something that could lead to an inifinite recursion.
+  Py_ReprEnter() and Py_EnterRecursiveCall(), respectively, fixed the
+  issues.
+
+- Issue #1164: It was possible to trigger deadlock when using the
+  'print' statement to write to a file since the GIL was not released
+  as needed.  Now PyObject_Print() does the right thing along with
+  various tp_print implementations of the built-in types and those in
+  the collections module.
+
+- Issue #1147: Exceptions were directly allowing string exceptions in
+  their throw() method even though string exceptions no longer
+  allowed.
 
-- Issue #1096: Prevent a segfault from getting the repr of a very deeply nested
-  list by using the recursion counter.
+- Issue #1096: Prevent a segfault from getting the repr of a very
+  deeply nested list by using the recursion counter.
 
 - Issue #1202533: Fix infinite recursion calls triggered by calls to
-  PyObject_Call() never calling back out to Python code to trigger recursion
-  depth updates/checks.  Required the creation of a static RuntimeError
-  instance in case normalizing an exception put the recursion check value past
-  its limit.  Fixes crashers infinite_rec_(1|2|4|5).py.
+  PyObject_Call() never calling back out to Python code to trigger
+  recursion depth updates/checks.  Required the creation of a static
+  RuntimeError instance in case normalizing an exception put the
+  recursion check value past its limit.  Fixes crashers
+  infinite_rec_(1|2|4|5).py.
 
-- Patch #1031213: Decode source line in SyntaxErrors back to its original source
-  encoding.
+- Patch #1031213: Decode source line in SyntaxErrors back to its
+  original source encoding.
 
 - Patch #1673759: add a missing overflow check when formatting floats
   with %G.
 
-- Prevent expandtabs() on string and unicode objects from causing a segfault
-  when a large width is passed on 32-bit platforms.
+- Prevent expandtabs() on string and unicode objects from causing a
+  segfault when a large width is passed on 32-bit platforms.
 
-- Bug #1733488: Fix compilation of bufferobject.c on AIX.
+- Issue #1733488: Fix compilation of bufferobject.c on AIX.
 
-- Bug #1722485: remove docstrings again when running with -OO.
+- Issue #1722485: remove docstrings again when running with -OO.
 
 - Add new attribute names for function objects.  All the func_* become
-  __*__ attributes.  (Some already existed, e.g., __doc__ and __name__.)
+  __*__ attributes.  (Some already existed, e.g., __doc__ and
+  __name__.)
 
 - Add -3 option to the interpreter to warn about features that are
   deprecated and will be changed/removed in Python 3.0.
@@ -797,12 +934,12 @@
   calls.
 
 - except clauses may now be spelled either "except E, target:" or
-  "except E as target:". This is to provide forwards compatibility with
-  Python 3.0.
+  "except E as target:". This is to provide forwards compatibility
+  with Python 3.0.
 
 - Deprecate BaseException.message as per PEP 352.
 
-- Bug #1303614: don't expose object's __dict__ when the dict is
+- Issue #1303614: don't expose object's __dict__ when the dict is
   inherited from a builtin base.
 
 - When __slots__ are set to a unicode string, make it work the same as
@@ -827,22 +964,25 @@
   warning later).  Also, type.__init__() insists on the same signature
   as supported by type.__new__().
 
-- Patch #1675423: PyComplex_AsCComplex() now tries to convert an object
-  to complex using its __complex__() method before falling back to the
-  __float__() method. Therefore, the functions in the cmath module now
-  can operate on objects that define a __complex__() method.
-
-- Patch #1623563: allow __class__ assignment for classes with __slots__.
-  The old and the new class are still required to have the same slot names.
+- Patch #1675423: PyComplex_AsCComplex() now tries to convert an
+  object to complex using its __complex__() method before falling back
+  to the __float__() method. Therefore, the functions in the cmath
+  module now can operate on objects that define a __complex__()
+  method.
+
+- Patch #1623563: allow __class__ assignment for classes with
+  __slots__.  The old and the new class are still required to have the
+  same slot names.
+
+- Patch #1642547: Fix an error/crash when encountering syntax errors
+  in complex if statements.
+
+- Patch #1462488: Python no longer segfaults when
+  ``object.__reduce_ex__()`` is called with an object that is faking
+  its type.
 
-- Patch #1642547: Fix an error/crash when encountering syntax errors in
-  complex if statements.
-
-- Patch #1462488: Python no longer segfaults when ``object.__reduce_ex__()``
-  is called with an object that is faking its type.
-
-- Patch #1680015: Don't modify __slots__ tuple if it contains an unicode
-  name.
+- Patch #1680015: Don't modify __slots__ tuple if it contains an
+  unicode name.
 
 - Patch #1444529: the builtin compile() now accepts keyword arguments.
 
@@ -850,61 +990,69 @@
   case, even when converting the value to a string failed.
 
 - The dir() function has been extended to call the __dir__() method on
-  its argument, if it exists. If not, it will work like before. This allows
-  customizing the output of dir() in the presence of a __getattr__().
+  its argument, if it exists. If not, it will work like before. This
+  allows customizing the output of dir() in the presence of a
+  __getattr__().
 
 - Patch #922167: Python no longer segfaults when faced with infinitely
   self-recursive reload() calls (as reported by bug #742342).
 
-- Patch #1675981: remove unreachable code from ``type.__new__()`` method.
+- Patch #1675981: remove unreachable code from ``type.__new__()``
+  method.
 
-- Patch #1491866: change the complex() constructor to allow parthensized
-  forms. This means complex(repr(x)) now works instead of raising a
-  ValueError.
+- Patch #1491866: change the complex() constructor to allow
+  parthensized forms. This means complex(repr(x)) now works instead of
+  raising a ValueError.
 
 - Patch #703779: unset __file__ in __main__ after running a file. This
-  makes the filenames the warning module prints much more sensible when
-  a PYTHONSTARTUP file is used.
+  makes the filenames the warning module prints much more sensible
+  when a PYTHONSTARTUP file is used.
 
 - Variant of patch #697613: don't exit the interpreter on a SystemExit
   exception if the -i command line option or PYTHONINSPECT environment
-  variable is given, but break into the interactive interpreter just like
-  on other exceptions or normal program exit.
+  variable is given, but break into the interactive interpreter just
+  like on other exceptions or normal program exit.
 
-- Patch #1638879: don't accept strings with embedded NUL bytes in long().
+- Patch #1638879: don't accept strings with embedded NUL bytes in
+  long().
 
-- Bug #1674503: close the file opened by execfile() in an error condition.
+- Bug #1674503: close the file opened by execfile() in an error
+  condition.
 
 - Patch #1674228: when assigning a slice (old-style), check for the
   sq_ass_slice instead of the sq_slice slot.
 
-- When printing an unraisable error, don't print exceptions. before the name.
-  This duplicates the behavior whening normally printing exceptions.
-
-- Bug #1653736: Properly discard third argument to slot_nb_inplace_power.
-
-- PEP 352: Raising a string exception now triggers a TypeError.  Attempting to
-  catch a string exception raises DeprecationWarning.
-
-- Bug #1377858: Fix the segfaulting of the interpreter when an object created
-  a weakref on itself during a __del__ call for new-style classes (classic
-  classes still have the bug).
+- When printing an unraisable error, don't print exceptions. before
+  the name.  This duplicates the behavior whening normally printing
+  exceptions.
+
+- Bug #1653736: Properly discard third argument to
+  slot_nb_inplace_power.
+
+- PEP 352: Raising a string exception now triggers a TypeError.
+  Attempting to catch a string exception raises DeprecationWarning.
+
+- Bug #1377858: Fix the segfaulting of the interpreter when an object
+  created a weakref on itself during a __del__ call for new-style
+  classes (classic classes still have the bug).
 
 - Bug #1579370: Make PyTraceBack_Here use the current thread, not the
   frame's thread state.
 
-- patch #1630975: Fix crash when replacing sys.stdout in sitecustomize.py
+- patch #1630975: Fix crash when replacing sys.stdout in
+  sitecustomize.py.
 
-- Prevent seg fault on shutdown which could occur if an object
-  raised a warning.
+- Prevent seg fault on shutdown which could occur if an object raised
+  a warning.
 
-- Bug #1566280: Explicitly invoke threading._shutdown from Py_Main,
-  to avoid relying on atexit.
+- Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to
+  avoid relying on atexit.
 
-- Bug #1590891: random.randrange don't return correct value for big number
+- Bug #1590891: random.randrange don't return correct value for big
+  number.
 
-- Patch #1586791: Better exception messages for some operations on strings,
-  tuples and lists.
+- Patch #1586791: Better exception messages for some operations on
+  strings, tuples and lists.
 
 - Bug #1067760: Deprecate passing floats to file.seek.
 
@@ -912,10 +1060,10 @@
 
 - Bug #1588287: fix invalid assertion for `1,2` in debug builds.
 
-- Bug #1576657: when setting a KeyError for a tuple key, make sure that
-  the tuple isn't used as the "exception arguments tuple".
+- Bug #1576657: when setting a KeyError for a tuple key, make sure
+  that the tuple isn't used as the "exception arguments tuple".
 
-- Bug #1565514, SystemError not raised on too many nested blocks.
+- Bug #1565514: SystemError not raised on too many nested blocks.
 
 - Bug #1576174: WindowsError now displays the windows error code
   again, no longer the posix error code.
@@ -923,8 +1071,8 @@
 - Patch #1549049: Support long values in structmember, issue warnings
   if the assigned value for structmember fields gets truncated.
 
-- Update the peephole optimizer to remove more dead code (jumps after returns)
-  and inline unconditional jumps to returns.
+- Update the peephole optimizer to remove more dead code (jumps after
+  returns) and inline unconditional jumps to returns.
 
 - Bug #1545497: when given an explicit base, int() did ignore NULs
   embedded in the string to convert.
@@ -942,12 +1090,12 @@
   number of arguments, as was the case in Python 2.4.
 
 - Patch #1567691: super() and new.instancemethod() now don't accept
-  keyword arguments any more (previously they accepted them, but didn't
-  use them).
+  keyword arguments any more (previously they accepted them, but
+  didn't use them).
 
-- Fix a bug in the parser's future statement handling that led to "with"
-  not being recognized as a keyword after, e.g., this statement:
-  from __future__ import division, with_statement
+- Fix a bug in the parser's future statement handling that led to
+  "with" not being recognized as a keyword after, e.g., this
+  statement: from __future__ import division, with_statement
 
 - Bug #1557232: fix seg fault with def f((((x)))) and def f(((x),)).
 
@@ -955,8 +1103,9 @@
 
 - Allow exception instances to be directly sliced again.
 
-- Bug #1551432: Exceptions do not define an explicit __unicode__ method.  This
-  allows calling unicode() on exceptions classes directly to succeed.
+- Bug #1551432: Exceptions do not define an explicit __unicode__
+  method.  This allows calling unicode() on exceptions classes
+  directly to succeed.
 
 - Bug #1542051: Exceptions now correctly call PyObject_GC_UnTrack.
   Also make sure that every exception class has __module__ set to
@@ -976,18 +1125,19 @@
   head is the original string if sep was not found.
 
 - Bug #1520864: unpacking singleton tuples in list comprehensions and
-  generator expressions (x for x, in ... ) works again.  Fixing this problem
-  required changing the .pyc magic number.  This means that .pyc files
-  generated before 2.5c2 will be regenerated.
+  generator expressions (x for x, in ... ) works again.  Fixing this
+  problem required changing the .pyc magic number.  This means that
+  .pyc files generated before 2.5c2 will be regenerated.
 
 - ``with`` and ``as`` are now keywords.
 
-- Bug #1664966: Fix crash in exec if Unicode filename can't be decoded.
+- Bug #1664966: Fix crash in exec if Unicode filename can't be
+  decoded.
 
 - Issue #1537: Changed GeneratorExit's base class from Exception to
   BaseException.
 
-- Fix Issue #1703448: A joined thread could show up in the
+- Issue #1703448: A joined thread could show up in the
   threading.enumerate() list after the join() for a brief period until
   it actually exited.
 
@@ -995,24 +1145,25 @@
 Library
 -------
 
-- #2274 Add heapq.heappushpop().
+- Patch #2274: Add heapq.heappushpop().
 
 - Add inspect.isabstract(object) to fix bug #2223
 
 - Add a __format__ method to Decimal, to support PEP 3101.
 
-- Add a timing parameter when using trace.Trace to print out timestamps.
+- Add a timing parameter when using trace.Trace to print out
+  timestamps.
 
-- #1627: httplib now ignores negative Content-Length headers.
+- Issue #1627: httplib now ignores negative Content-Length headers.
 
-- #900744: If an invalid chunked-encoding header is sent by a server,
-  httplib will now raise IncompleteRead and close the connection instead
-  of raising ValueError.
+- Issue #900744: If an invalid chunked-encoding header is sent by a
+  server, httplib will now raise IncompleteRead and close the
+  connection instead of raising ValueError.
 
-- #1492: The content type of BaseHTTPServer error messages can now be
-  overridden.
+- Issue #1492: The content type of BaseHTTPServer error messages can
+  now be overridden.
 
-- Issue 1781: ConfigParser now does not let you add the "default" section
+- Issue #1781: ConfigParser now does not let you add the "default" section
   (ignore-case)
 
 - Removed uses of dict.has_key() from distutils, and uses of
@@ -1020,9 +1171,11 @@
   without warnings when '-3' is given.  More work like this needs to
   be done in the rest of the stdlib.
 
-- Issue #1916. Added isgenerator() and isgeneratorfunction() to inspect.py.
+- Issue #1916: added isgenerator() and isgeneratorfunction() to
+  inspect.py.
 
-- #1224: Fixed bad url parsing when path begins with double slash.
+- Issue #1224: Fixed bad url parsing when path begins with double
+  slash.
 
 - ctypes instances that are not or do not contain pointers can now be
   pickled.
@@ -1034,89 +1187,93 @@
   to fractions.Fraction, to avoid the name clash with the abstract
   base class numbers.Rational.  See discussion in issue #1682.
 
-- The pickletools module now provides an optimize() function
-  that eliminates unused PUT opcodes from a pickle string.
-
-- #2021: Allow tempfile.NamedTemporaryFile and SpooledTemporaryFile
-  to be used in with statements by correctly supporting the context
-  management protocol.
+- The pickletools module now provides an optimize() function that
+  eliminates unused PUT opcodes from a pickle string.
 
-- #1979: Add rich comparisons to Decimal, and make Decimal comparisons
-  involving a NaN follow the IEEE 754 standard.
+- Patch #2021: Allow tempfile.NamedTemporaryFile and
+  SpooledTemporaryFile to be used in with statements by correctly
+  supporting the context management protocol.
+
+- Patch #1979: Add rich comparisons to Decimal, and make Decimal
+  comparisons involving a NaN follow the IEEE 754 standard.
+
+- Issue #2004: tarfile.py: Use mode 0700 for temporary directories and
+  default permissions for missing directories.
+
+- Issue #175006: The debugger used to skip the condition of a "while"
+  statement after the first iteration. Now it correctly steps on the
+  expression, and breakpoints on the "while" statement are honored on
+  each loop.
 
-- #2004: tarfile.py: Use mode 0700 for temporary directories and default
-  permissions for missing directories.
-
-- #175006: The debugger used to skip the condition of a "while" statement
-  after the first iteration. Now it correctly steps on the expression, and
-  breakpoints on the "while" statement are honored on each loop.
-
-- #1765140: add an optional delay argument to FileHandler and its
-  subclasses. Defaults to false (existing behaviour), but if true,
+- Issue #1765140: add an optional delay argument to FileHandler and
+  its subclasses. Defaults to false (existing behaviour), but if true,
   defers opening the file until the first call to emit().
 
 - The pprint module now supports sets and frozensets.
 
-- #1221598: add optional callbacks to ftplib.FTP's storbinary() and
-  storlines() methods.  (Contributed by Phil Schwartz)
+- Issue #1221598: add optional callbacks to ftplib.FTP's storbinary()
+  and storlines() methods.  (Contributed by Phil Schwartz)
 
-- #1715: include sub-extension modules in pydoc's text output.
+- Issue #1715: include sub-extension modules in pydoc's text output.
 
-- #1836: fix an off-by-one bug in TimedRotatingHandler's rollover
-  time calculation.
+- Issue #1836: fix an off-by-one bug in TimedRotatingHandler's
+  rollover time calculation.
 
-- #1021: fix a bug to allow basicConfig to accept NOTSET as a level.
+- Issue #1021: fix a bug to allow basicConfig to accept NOTSET as a
+  level.
 
-- #932563: add LoggerAdapter convenience class to make it easier to add
-  contextual information in logging output.
+- Issue #932563: add LoggerAdapter convenience class to make it easier
+  to add contextual information in logging output.
 
-- #1760556: fix a bug to avoid FileHandler throwing an exception in
-  flush().
+- Issue #1760556: fix a bug to avoid FileHandler throwing an exception
+  in flush().
 
-- Bug #1530959: distutils' build command now uses different build directory
-  when building extension modules against versions of Python compiled
-  with ``--with-pydebug``.
+- Bug #1530959: distutils' build command now uses different build
+  directory when building extension modules against versions of Python
+  compiled with ``--with-pydebug``.
 
-- #1555501: move plistlib from plat-mac directory to general library.
+- Issue #1555501: move plistlib from plat-mac directory to general
+  library.
 
-- #1269: fix a bug in pstats.add_callers() and add a unit test file for
-  pstats.
+- Issue #1269: fix a bug in pstats.add_callers() and add a unit test
+  file for pstats.
 
-- #1669: don't allow shutil.rmtree() to be called on a symlink to a
-  directory.
+- Issue #1669: don't allow shutil.rmtree() to be called on a symlink
+  to a directory.
 
-- #1664522: in urllib, don't read non-existing directories in ftp mode,
-  returning a 0-byte file -- raise an IOError instead.
+- Issue #1664522: in urllib, don't read non-existing directories in
+  ftp mode, returning a 0-byte file -- raise an IOError instead.
 
-- #856047: respect the ``no_proxy`` environment variable when using the
-  ``http_proxy`` etc. environment variables in urllib.
+- Issue #856047: respect the ``no_proxy`` environment variable when
+  using the ``http_proxy`` etc. environment variables in urllib.
 
-- #1178141: add a getcode() method to the addinfourls that urllib.open()
-  returns so that you can retrieve the HTTP status code.
+- Issue #1178141: add a getcode() method to the addinfourls that
+  urllib.open() returns so that you can retrieve the HTTP status code.
 
 - Issue #1003: Fix zipfile decryption check, it would fail zip files
   with extended local headers.
 
-- #1189216: Fix the zipfile module to work on archives with headers
-  past the 2**31 byte boundary.
+- Issue #1189216: Fix the zipfile module to work on archives with
+  headers past the 2**31 byte boundary.
 
-- #1336: fix a race condition in subprocess.Popen if the garbage
+- Issue #1336: fix a race condition in subprocess.Popen if the garbage
   collector kicked in at the wrong time that would cause the process
   to hang when the child wrote to stderr.
 
-- #1146: fix how textwrap breaks a long word that would start in the
-  last column of a line.
+- Issue #1146: fix how textwrap breaks a long word that would start in
+  the last column of a line.
 
-- #1693149: trace.py --ignore-module - accept multiple comma-separated
-  modules to be given.
+- Issue #1693149: trace.py --ignore-module - accept multiple
+  comma-separated modules to be given.
 
-- #1822: MIMEMultipart.is_multipart() behaves correctly for a just-created
-  (and empty) instance. Thanks Jonathan Share.
+- Issue #1822: MIMEMultipart.is_multipart() behaves correctly for a
+  just-created (and empty) instance. Thanks Jonathan Share.
 
-- #1861: Added an attribute to the sched module which returns an ordered
-  list of upcoming events (displayed as named tuples).
+- Issue #1861: Added an attribute to the sched module which returns an
+  ordered list of upcoming events (displayed as named tuples).
 
-- #1837: The queue module now also supports a LIFO queue and a priority queue.
+- Issue #1837: The queue module now also supports a LIFO queue and a
+  priority queue.
 
 - Patch #1048820: Add insert-mode editing to curses.textpad.Textbox
   (patch by Stefan Wehr).  Also, fix an off-by-one bug in
@@ -1133,24 +1290,25 @@
 - Issue #1786: pdb should use its own stdin/stdout around an exec call
   and when creating a recursive instance.
 
-- Issue #1698398 Zipfile.printdir() crashed because the format string
-  expected a tuple type of length six instead of time.struct_time object.
+- Issue #1698398: ZipFile.printdir() crashed because the format string
+  expected a tuple type of length six instead of time.struct_time
+  object.
 
 - Issue #1780: The Decimal constructor now accepts arbitrary leading
   and trailing whitespace when constructing from a string.
   Context.create_decimal no longer accepts trailing newlines.
 
-- Decimal.as_tuple(), difflib.find_longest_match() and inspect functions
-  that returned a tuple now return a named tuple.
+- Decimal.as_tuple(), difflib.find_longest_match() and inspect
+  functions that returned a tuple now return a named tuple.
 
 - Doctest now returns results as a named tuple for readability:
       (0, 7) --> TestResults(failed=0, attempted=7)
 
-- Issue #846388. re.match is interruptible now, which is particularly
+- Issue #846388:q re.match is interruptible now, which is particularly
   good for long regular expression matches.
 
-- pyexpat, patch #1137: allow setting buffer_size attribute
-  on Parser objects to set the character data buffer size.
+- Patch #1137: allow setting buffer_size attribute on pyexpat Parser
+  objects to set the character data buffer size.
 
 - Issue #1757: The hash of a Decimal instance is no longer affected by
   the current context.
@@ -1160,22 +1318,23 @@
 
 - Issue #1646: Make socket support the TIPC protocol.
 
-- Bug #1742: return os.curdir from os.path.relpath() if both arguments are
-  equal instead of raising an exception.
+- Bug #1742: return os.curdir from os.path.relpath() if both arguments
+  are equal instead of raising an exception.
 
 - Patch #1637: fix urlparse for URLs like 'http://x.com?arg=/foo'.
 
 - Patch #1698: allow '@' in username parsed by urlparse.py.
 
-- Issue #1735: TarFile.extractall() now correctly sets directory permissions
-  and times.
+- Issue #1735: TarFile.extractall() now correctly sets directory
+  permissions and times.
 
 - Bug #1713: posixpath.ismount() claims symlink to a mountpoint is a mountpoint.
 
-- Bug #1687: Fxed plistlib.py restricts <integer> to Python int when writing
+- Bug #1687: Fxed plistlib.py restricts <integer> to Python int when
+  writing
 
-- Issue #1700: Regular expression inline flags incorrectly handle certain
-  unicode characters.
+- Issue #1700: Regular expression inline flags incorrectly handle
+  certain unicode characters.
 
 - Issue #1689: PEP 3141, numeric abstract base classes.
 
@@ -1184,22 +1343,22 @@
 
 - Issue #1642: Fix segfault in ctypes when trying to delete attributes.
 
-- Issue #1727780: Support loading pickles of random.Random objects created
-  on 32-bit systems on 64-bit systems, and vice versa. As a consequence
-  of the change, Random pickles created by Python 2.6 cannot be loaded
-  in Python 2.5.
-
-- Issue #1455: The distutils package now supports VS 2005 and VS 2008 for
-  both the msvccompiler and cygwincompiler.
+- Issue #1727780: Support loading pickles of random.Random objects
+  created on 32-bit systems on 64-bit systems, and vice versa. As a
+  consequence of the change, Random pickles created by Python 2.6
+  cannot be loaded in Python 2.5.
+
+- Issue #1455: The distutils package now supports VS 2005 and VS 2008
+  for both the msvccompiler and cygwincompiler.
 
-- Issue #1531: tarfile.py: Read fileobj from the current offset, do not
-  seek to the start.
+- Issue #1531: tarfile.py: Read fileobj from the current offset, do
+  not seek to the start.
 
-- Issue #1534: Added a dictionary sys.float_info with information about the
-  internal floating point type to the sys module.
+- Issue #1534: Added a dictionary sys.float_info with information
+  about the internal floating point type to the sys module.
 
-- Issue 1429818: patch for trace and doctest modules so they play nicely
-  together.
+- Issue #1429818: patch for trace and doctest modules so they play
+  nicely together.
 
 - doctest made a bad assumption that a package's __loader__.get_data()
   method used universal newlines.
@@ -1213,8 +1372,8 @@
 - IN module for FreeBSD 8 is added and preexisting FreeBSD 6 and 7
   files are updated.
 
-- Issues #1181, #1287: unsetenv() is now called when the os.environ.pop()
-  and os.environ.clear() methods are used.
+- Issues #1181, #1287: unsetenv() is now called when the
+  os.environ.pop() and os.environ.clear() methods are used.
 
 - ctypes will now work correctly on 32-bit systems when Python is
   configured with --with-system-ffi.
@@ -1224,17 +1383,19 @@
 
 - collections.deque() now supports a "maxlen" argument.
 
-- itertools.count() is no longer bounded to LONG_MAX.  Formerly, it raised
-  an OverflowError.  Now, automatically shifts from ints to longs.
+- itertools.count() is no longer bounded to LONG_MAX.  Formerly, it
+  raised an OverflowError.  Now, automatically shifts from ints to
+  longs.
 
-- Added itertools.product() which forms the Cartesian product of
-  the input iterables.
+- Added itertools.product() which forms the Cartesian product of the
+  input iterables.
 
 - Added itertools.combinations() and itertools.permutations().
 
 - Patch #1541463: optimize performance of cgi.FieldStorage operations.
 
-- Decimal is fully updated to the latest Decimal Specification (v1.66).
+- Decimal is fully updated to the latest Decimal Specification
+  (v1.66).
 
 - Bug #1153: repr.repr() now doesn't require set and dictionary items
   to be orderable to properly represent them.
@@ -1243,16 +1404,18 @@
 
 - Bug #1709599: Run test_1565150 only if the file system is NTFS.
 
-- When encountering a password-protected robots.txt file the RobotFileParser
-  no longer prompts interactively for a username and password (bug 813986).
+- When encountering a password-protected robots.txt file the
+  RobotFileParser no longer prompts interactively for a username and
+  password (bug 813986).
 
 - TarFile.__init__() no longer fails if no name argument is passed and
   the fileobj argument has no usable name attribute (e.g. StringIO).
 
-- The functools module now provides 'reduce', for forward compatibility
-  with Python 3000.
+- The functools module now provides 'reduce', for forward
+  compatibility with Python 3000.
 
-- Server-side SSL support and cert verification added, by Bill Janssen.
+- Server-side SSL support and cert verification added, by Bill
+  Janssen.
 
 - socket.ssl deprecated; use new ssl module instead.
 
@@ -1261,8 +1424,8 @@
 - EUC-KR codec now handles the cheot-ga-keut composed make-up hangul
   syllables.
 
-- GB18030 codec now can encode additional two-byte characters that
-  are missing in GBK.
+- GB18030 codec now can encode additional two-byte characters that are
+  missing in GBK.
 
 - Add new codecs for UTF-32, UTF-32-LE and UTF-32-BE.
 
@@ -1279,31 +1442,34 @@
 
 - tarfile.py: Added "exclude" keyword argument to TarFile.add().
 
-- Bug #1734723: Fix repr.Repr() so it doesn't ignore the maxtuple attribute.
-
-- The urlopen function of urllib2 now has an optional timeout parameter (note
-  that it actually works with HTTP, HTTPS, FTP and FTPS connections).
+- Bug #1734723: Fix repr.Repr() so it doesn't ignore the maxtuple
+  attribute.
 
-- In ftplib, the FTP.ntransfercmd method, when in passive mode, now uses
-  the socket.create_connection function, using the timeout specified at
-  connection time.
+- The urlopen function of urllib2 now has an optional timeout
+  parameter (note that it actually works with HTTP, HTTPS, FTP and
+  FTPS connections).
+
+- In ftplib, the FTP.ntransfercmd method, when in passive mode, now
+  uses the socket.create_connection function, using the timeout
+  specified at connection time.
 
 - Bug #1728403: Fix a bug that CJKCodecs StreamReader hangs when it
-  reads a file that ends with incomplete sequence and sizehint argument
-  for .read() is specified.
+  reads a file that ends with incomplete sequence and sizehint
+  argument for .read() is specified.
 
-- Bug #1730389: Change time.strptime() to use ``\s+`` instead of ``\s*`` when
-  matching spaces in the specified format argument.
+- Bug #1730389: Change time.strptime() to use ``\s+`` instead of
+  ``\s*`` when matching spaces in the specified format argument.
 
-- SF 1668596/1720897: distutils now copies data files
-  even if package_dir is empty.
+- Bugs #1668596/#1720897: distutils now copies data files even if
+  package_dir is empty.
 
 - sha now raises a DeprecationWarning upon import.
 
 - md5 now raises a DeprecationWarning upon import.
 
-- Issue1385: The hmac module now computes the correct hmac when using hashes
-  with a block size other than 64 bytes (such as sha384 and sha512).
+- Issue #1385: The hmac module now computes the correct hmac when
+  using hashes with a block size other than 64 bytes (such as sha384
+  and sha512).
 
 - mimify now raises a DeprecationWarning upon import.
 
@@ -1318,11 +1484,11 @@
 
 - The posixfile module now raises a DeprecationWarning.
 
-- Remove the gopherlib module.  This also leads to the removal of gopher
-  support in urllib/urllib2.
+- Remove the gopherlib module.  This also leads to the removal of
+  gopher support in urllib/urllib2.
 
-- Fix bug in marshal where bad data would cause a segfault due to
-  lack of an infinite recursion check.
+- Fix bug in marshal where bad data would cause a segfault due to lack
+  of an infinite recursion check.
 
 - Removed plat-freebsd2 and plat-freebsd3 directories (and IN.py in
   the directories).
@@ -1331,10 +1497,11 @@
   the traceback inadvertently or maliciously closing the comment and
   injecting HTML into the error page.
 
-- The popen2 module and os.popen* are deprecated.  Use the subprocess module.
+- The popen2 module and os.popen* are deprecated.  Use the subprocess
+  module.
 
-- Added an optional credentials argument to SMTPHandler, for use with SMTP
-  servers which require authentication.
+- Added an optional credentials argument to SMTPHandler, for use with
+  SMTP servers which require authentication.
 
 - Patch #1695948: Added optional timeout parameter to SocketHandler.
 
@@ -1349,13 +1516,15 @@
   ".cpp" too.
 
 - As specified in RFC 2616, an HTTP response like 2xx indicates that
-  the client's request was successfully received, understood, and accepted.
-  Now in these cases no error is raised in urllib (issue #1177) and urllib2.
+  the client's request was successfully received, understood, and
+  accepted.  Now in these cases no error is raised in urllib (issue
+  #1177) and urllib2.
 
-- Bug #1290505: time.strptime's internal cache of locale information is now
-  properly recreated when the locale is changed.
+- Bug #1290505: time.strptime's internal cache of locale information
+  is now properly recreated when the locale is changed.
 
-- Patch #1685563: remove (don't add) duplicate paths in distutils.MSVCCompiler.
+- Patch #1685563: remove (don't add) duplicate paths in
+  distutils.MSVCCompiler.
 
 - Added a timeout parameter to the constructor of other protocols
   (telnetlib, ftplib, smtplib and poplib). This is second part of the
@@ -1373,8 +1542,8 @@
 
 - Patch #1630118: add a SpooledTemporaryFile class to tempfile.py.
 
-- Patch #1273829: os.walk() now has a "followlinks" parameter. If set to
-  True (which is not the default), it visits symlinks pointing to
+- Patch #1273829: os.walk() now has a "followlinks" parameter. If set
+  to True (which is not the default), it visits symlinks pointing to
   directories.
 
 - Bug #1681228: the webbrowser module now correctly uses the default
@@ -1388,72 +1557,76 @@
   initialization failed.
 
 - Bug #767111: fix long-standing bug in urllib which caused an
-  AttributeError instead of an IOError when the server's response didn't
-  contain a valid HTTP status line.
+  AttributeError instead of an IOError when the server's response
+  didn't contain a valid HTTP status line.
 
-- Patch #957650: "%var%" environment variable references are now properly
-  expanded in ntpath.expandvars(), also "~user" home directory references
-  are recognized and handled on Windows.
+- Patch #957650: "%var%" environment variable references are now
+  properly expanded in ntpath.expandvars(), also "~user" home
+  directory references are recognized and handled on Windows.
 
-- Patch #1429539: pdb now correctly initializes the __main__ module for
-  the debugged script, which means that imports from __main__ work
+- Patch #1429539: pdb now correctly initializes the __main__ module
+  for the debugged script, which means that imports from __main__ work
   correctly now.
 
 - The nonobvious commands.getstatus() function is now deprecated.
 
-- Patch #1393667: pdb now has a "run" command which restarts the debugged
-  Python program, optionally with different arguments.
+- Patch #1393667: pdb now has a "run" command which restarts the
+  debugged Python program, optionally with different arguments.
 
 - Patch #1649190: Adding support for _Bool to ctypes as c_bool.
 
-- Patch #1530482: add pydoc.render_doc() which returns the documentation
-  for a thing instead of paging it to stdout, which pydoc.doc() does.
-
-- Patch #1533909: the timeit module now accepts callables in addition to
-  strings for the code to time and the setup code. Also added two
-  convenience functions for instantiating a Timer and calling its methods.
-
-- Patch #1537850: tempfile.NamedTemporaryFile now has a "delete" parameter
-  which can be set to False to prevent the default delete-on-close
-  behavior.
+- Patch #1530482: add pydoc.render_doc() which returns the
+  documentation for a thing instead of paging it to stdout, which
+  pydoc.doc() does.
+
+- Patch #1533909: the timeit module now accepts callables in addition
+  to strings for the code to time and the setup code. Also added two
+  convenience functions for instantiating a Timer and calling its
+  methods.
+
+- Patch #1537850: tempfile.NamedTemporaryFile now has a "delete"
+  parameter which can be set to False to prevent the default
+  delete-on-close behavior.
 
 - Patch #1581073: add a flag to textwrap that prevents the dropping of
   whitespace while wrapping.
 
 - Patch #1603688: ConfigParser.SafeConfigParser now checks values that
-  are set for invalid interpolation sequences that would lead to errors
-  on reading back those values.
+  are set for invalid interpolation sequences that would lead to
+  errors on reading back those values.
 
-- Added support for the POSIX.1-2001 (pax) format to tarfile.py. Extended
-  and cleaned up the test suite. Added a new testtar.tar.
+- Added support for the POSIX.1-2001 (pax) format to
+  tarfile.py. Extended and cleaned up the test suite. Added a new
+  testtar.tar.
 
 - Patch #1449244: Support Unicode strings in
   email.message.Message.{set_charset,get_content_charset}.
 
-- Patch #1542681: add entries for "with", "as" and "CONTEXTMANAGERS" to
-  pydoc's help keywords.
+- Patch #1542681: add entries for "with", "as" and "CONTEXTMANAGERS"
+  to pydoc's help keywords.
 
 - Patch #1555098: use str.join() instead of repeated string
   concatenation in robotparser.
 
 - Patch #1635454: the csv.DictWriter class now includes the offending
-  field names in its exception message if you try to write a record with
-  a dictionary containing fields not in the CSV field names list.
+  field names in its exception message if you try to write a record
+  with a dictionary containing fields not in the CSV field names list.
 
 - Patch #1668100: urllib2 now correctly raises URLError instead of
   OSError if accessing a local file via the file:// protocol fails.
 
 - Patch #1677862: Require a space or tab after import in .pth files.
 
-- Patch #1192590: Fix pdb's "ignore" and "condition" commands so they trap
-  the IndexError caused by passing in an invalid breakpoint number.
+- Patch #1192590: Fix pdb's "ignore" and "condition" commands so they
+  trap the IndexError caused by passing in an invalid breakpoint
+  number.
+
+- Patch #1599845: Add an option to disable the implicit calls to
+  server_bind() and server_activate() in the constructors for
+  TCPServer, SimpleXMLRPCServer and DocXMLRPCServer.
 
-- Patch #1599845: Add an option to disable the implicit calls to server_bind()
-  and server_activate() in the constructors for TCPServer, SimpleXMLRPCServer
-  and DocXMLRPCServer.
-
-- Bug #1531963: Make SocketServer.TCPServer's server_address always
-  be equal to calling getsockname() on the server's socket. Fixed by
+- Bug #1531963: Make SocketServer.TCPServer's server_address always be
+  equal to calling getsockname() on the server's socket. Fixed by
   patch #1545011.
 
 - Patch #742598: Add .timeout attribute to SocketServer that calls
@@ -1469,20 +1642,21 @@
 
 - Patch #1481079: add support for HTTP_REFERER to CGIHTTPServer.
 
-- Patch #1675424: Added tests for uncovered code in the zipfile module.
-  The KeyError raised by Zipfile.getinfo for nonexistent names now has
-  a descriptive message.
+- Patch #1675424: Added tests for uncovered code in the zipfile
+  module.  The KeyError raised by Zipfile.getinfo for nonexistent
+  names now has a descriptive message.
 
 - Bug #1115886: os.path.splitext('.cshrc') gives now ('.cshrc', '').
 
-- unittest now verifies more of its assumptions. In particular, TestCase
-  and TestSuite subclasses (not instances) are no longer accepted in
-  TestSuite.addTest(). This should cause no incompatibility since it
-  never made sense with ordinary subclasses -- the failure just occurred
-  later, with a more cumbersome exception.
+- unittest now verifies more of its assumptions. In particular,
+  TestCase and TestSuite subclasses (not instances) are no longer
+  accepted in TestSuite.addTest(). This should cause no
+  incompatibility since it never made sense with ordinary subclasses
+  -- the failure just occurred later, with a more cumbersome
+  exception.
 
-- Patch #787789: allow to pass custom TestRunner instances to unittest's
-  main() function.
+- Patch #787789: allow to pass custom TestRunner instances to
+  unittest's main() function.
 
 - Patches #1550273, #1550272: fix a few bugs in unittest and add a
   comprehensive test suite for the module.
@@ -1490,8 +1664,9 @@
 - Patch #1001604: glob.glob() now returns unicode filenames if it was
   given a unicode argument and os.listdir() returns unicode filenames.
 
-- Patch #1673619: setup.py identifies extension modules it doesn't know how
-  to build and those it knows how to build but that fail to build.
+- Patch #1673619: setup.py identifies extension modules it doesn't
+  know how to build and those it knows how to build but that fail to
+  build.
 
 - Patch #912410: Replace HTML entity references for attribute values
   in HTMLParser.
@@ -1509,8 +1684,8 @@
 
 - Added itertools.izip_longest().
 
-- Have the encoding package's search function dynamically import using absolute
-  import semantics.
+- Have the encoding package's search function dynamically import using
+  absolute import semantics.
 
 - Patch #1647484: Renamed GzipFile's filename attribute to name.
 
@@ -1521,16 +1696,16 @@
 
 - Patch #685268: Consider a package's __path__ in imputil.
 
-- Patch 1463026: Support default namespace in XMLGenerator.
+- Patch #1463026: Support default namespace in XMLGenerator.
 
-- Patch 1571379: Make trace's --ignore-dir facility work in the face of
-  relative directory names.
+- Patch #1571379: Make trace's --ignore-dir facility work in the face
+  of relative directory names.
 
-- Bug #1600860: Search for shared python library in LIBDIR,
-  not lib/python/config, on "linux" and "gnu" systems.
+- Bug #1600860: Search for shared python library in LIBDIR, not
+  lib/python/config, on "linux" and "gnu" systems.
 
-- Patch #1652681: tarfile.py: create nonexistent files in append mode and
-  allow appending to empty files.
+- Patch #1652681: tarfile.py: create nonexistent files in append mode
+  and allow appending to empty files.
 
 - Bug #1124861: Automatically create pipes if GetStdHandle fails in
   subprocess.
@@ -1538,9 +1713,10 @@
 - Patch #1634778: add missing encoding aliases for iso8859_15 and
   iso8859_16.
 
-- Patch #1638243: the compiler package is now able to correctly compile
-  a with statement; previously, executing code containing a with statement
-  compiled by the compiler package crashed the interpreter.
+- Patch #1638243: the compiler package is now able to correctly
+  compile a with statement; previously, executing code containing a
+  with statement compiled by the compiler package crashed the
+  interpreter.
 
 - Bug #1643943: Fix time.strptime's support for the %U directive.
 
@@ -1549,7 +1725,8 @@
 
 - Patch #1627441: close sockets properly in urllib2.
 
-- Bug #494589: make ntpath.expandvars behave according to its docstring.
+- Bug #494589: make ntpath.expandvars behave according to its
+  docstring.
 
 - Changed platform module API python_version_tuple() to actually
   return a tuple (it used to return a list).
@@ -1559,8 +1736,8 @@
 
 - Added support for IronPython and Jython to the platform module.
 
-- The sets module has been deprecated.  Use the built-in set/frozenset types
-  instead.
+- The sets module has been deprecated.  Use the built-in set/frozenset
+  types instead.
 
 - Bug #1610795: make ctypes.util.find_library work on BSD systems.
 
@@ -1580,53 +1757,56 @@
 - Bug #411881: logging.handlers: bare except clause removed from
   SocketHandler.createSocket. Now, only socket.error is trapped.
 
-- Bug #411881: logging: bare except clause removed from LogRecord.__init__.
-  Now, only ValueError, TypeError and AttributeError are trapped.
+- Bug #411881: logging: bare except clause removed from
+  LogRecord.__init__.  Now, only ValueError, TypeError and
+  AttributeError are trapped.
 
-- Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument.
+- Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj
+  argument.
 
 - Patch #1182394 from Shane Holloway: speed up HMAC.hexdigest.
 
-- Patch #1262036: Prevent TarFiles from being added to themselves under
-  certain conditions.
+- Patch #1262036: Prevent TarFiles from being added to themselves
+  under certain conditions.
 
-- Patch #1230446: tarfile.py: fix ExFileObject so that read() and tell()
-  work correctly together with readline().
+- Patch #1230446: tarfile.py: fix ExFileObject so that read() and
+  tell() work correctly together with readline().
 
-- Patch #1484695: The tarfile module now raises a HeaderError exception
-  if a buffer given to frombuf() is invalid.
+- Patch #1484695: The tarfile module now raises a HeaderError
+  exception if a buffer given to frombuf() is invalid.
 
 - Bug #1503765: Fix a problem in logging.config with spaces in comma-
   separated lists read from logging config files.
 
-- Patch #1604907: Fix problems in logging.handlers caused at logging shutdown
-  when syslog handlers fail to initialize because of syslogd problems.
+- Patch #1604907: Fix problems in logging.handlers caused at logging
+  shutdown when syslog handlers fail to initialize because of syslogd
+  problems.
 
-- Patch #1608267: fix a race condition in os.makedirs() if the directory
-  to be created is already there.
+- Patch #1608267: fix a race condition in os.makedirs() if the
+  directory to be created is already there.
 
 - Patch #1610437: fix a tarfile bug with long filename headers.
 
-- Patch #1371075: Make ConfigParser accept optional dict type
-  for ordering, sorting, etc.
+- Patch #1371075: Make ConfigParser accept optional dict type for
+  ordering, sorting, etc.
 
 - Bug #1563807: _ctypes built on AIX fails with ld ffi error.
 
 - Bug #1598620: A ctypes Structure cannot contain itself.
 
-- Patch #1070046: Marshal new-style objects like InstanceType
-  in xmlrpclib.
+- Patch #1070046: Marshal new-style objects like InstanceType in
+  xmlrpclib.
 
 - cStringIO.truncate(-1) now raises an IOError, like StringIO and
   regular files.
 
 - Patch #1472877: Fix Tix subwidget name resolution.
 
-- Patch #1594554: Always close a tkSimpleDialog on ok(), even
-  if an exception occurs.
+- Patch #1594554: Always close a tkSimpleDialog on ok(), even if an
+  exception occurs.
 
-- Patch #1538878: Don't make tkSimpleDialog dialogs transient if
-  the parent window is withdrawn.
+- Patch #1538878: Don't make tkSimpleDialog dialogs transient if the
+  parent window is withdrawn.
 
 - Bug #1597824: return the registered function from atexit.register()
   to facilitate usage as a decorator.
@@ -1634,8 +1814,8 @@
 - Patch #1360200: Use unmangled_version RPM spec field to deal with
   file name mangling.
 
-- Patch #1359217: Process 2xx response in an ftplib transfer
-  that precedes an 1xx response.
+- Patch #1359217: Process 2xx response in an ftplib transfer that
+  precedes an 1xx response.
 
 - Patch #1355023: support whence argument for GzipFile.seek.
 
@@ -1646,13 +1826,13 @@
   weren't passing the message factory on to newly created Maildir/MH
   objects.
 
-- Patch #1514543: mailbox.py: In the Maildir class, report errors if there's
-  a filename clash instead of possibly losing a message.  (Patch by David
-  Watson.)
-
-- Patch #1514544: Try to ensure that messages/indexes have been physically
-  written to disk after calling .flush() or .close(). (Patch by David
-  Watson.)
+- Patch #1514543: mailbox.py: In the Maildir class, report errors if
+  there's a filename clash instead of possibly losing a message.
+  (Patch by David Watson.)
+
+- Patch #1514544: Try to ensure that messages/indexes have been
+  physically written to disk after calling .flush() or
+  .close(). (Patch by David Watson.)
 
 - Patch #1592250: Add elide argument to Tkinter.Text.search.
 
@@ -1681,29 +1861,29 @@
 
 - Patch #1567274: Support SMTP over TLS.
 
-- Patch #1560695: Add .note.GNU-stack to ctypes' sysv.S so that
-  ctypes isn't considered as requiring executable stacks.
+- Patch #1560695: Add .note.GNU-stack to ctypes' sysv.S so that ctypes
+  isn't considered as requiring executable stacks.
 
 - ctypes callback functions only support 'fundamental' data types as
   result type.  Raise an error when something else is used.  This is a
   partial fix for Bug #1574584.
 
-- Fix turtle so that time.sleep is imported for the entire library.  Allows
-  the demo2 function to be executed on its own instead of only when the
-  module is run as a script.
+- Fix turtle so that time.sleep is imported for the entire library.
+  Allows the demo2 function to be executed on its own instead of only
+  when the module is run as a script.
 
-- Bug #813342: Start the IDLE subprocess with -Qnew if the parent
-  is started with that option.
+- Bug #813342: Start the IDLE subprocess with -Qnew if the parent is
+  started with that option.
 
 - Bug #1565150: Fix subsecond processing for os.utime on Windows.
 
 - Support for MSVC 8 was added to bdist_wininst.
 
-- Bug #1446043: correctly raise a LookupError if an encoding name given
-  to encodings.search_function() contains a dot.
+- Bug #1446043: correctly raise a LookupError if an encoding name
+  given to encodings.search_function() contains a dot.
 
-- Bug #1560617: in pyclbr, return full module name not only for classes,
-  but also for functions.
+- Bug #1560617: in pyclbr, return full module name not only for
+  classes, but also for functions.
 
 - Bug #1457823: cgi.(Sv)FormContentDict's constructor now takes
   keep_blank_values and strict_parsing keyword arguments.
@@ -1714,127 +1894,139 @@
 - Bug #1565661: in webbrowser, split() the command for the default
   GNOME browser in case it is a command with args.
 
-- Made the error message for time.strptime when the data data and format do
-  match be more clear.
+- Made the error message for time.strptime when the data data and
+  format do match be more clear.
 
 - Fix a bug in traceback.format_exception_only() that led to an error
   being raised when print_exc() was called without an exception set.
   In version 2.4, this printed "None", restored that behavior.
 
-- Make webbrowser.BackgroundBrowser usable in Windows (it wasn't because
-  the close_fds arg to subprocess.Popen is not supported).
+- Make webbrowser.BackgroundBrowser usable in Windows (it wasn't
+  because the close_fds arg to subprocess.Popen is not supported).
 
-- Reverted patch #1504333 to sgmllib because it introduced an infinite loop.
+- Reverted patch #1504333 to sgmllib because it introduced an infinite
+  loop.
 
-- Patch #1553314: Fix the inspect.py slowdown that was hurting IPython & SAGE
-  by adding smarter caching in inspect.getmodule()
+- Patch #1553314: Fix the inspect.py slowdown that was hurting IPython
+  & SAGE by adding smarter caching in inspect.getmodule()
 
 - Fix missing import of the types module in logging.config.
 
 - Patch #1550886: Fix decimal module context management implementation
   to match the localcontext() example from PEP 343.
 
-- Bug #1545341: The 'classifier' keyword argument to the Distutils setup()
-  function now accepts tuples as well as lists.
+- Bug #1545341: The 'classifier' keyword argument to the Distutils
+  setup() function now accepts tuples as well as lists.
 
-- Bug #1541863: uuid.uuid1 failed to generate unique identifiers
-  on systems with low clock resolution.
+- Bug #1541863: uuid.uuid1 failed to generate unique identifiers on
+  systems with low clock resolution.
 
 - Bug #1531862: Do not close standard file descriptors in subprocess.
 
-- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092).
-
-- Fix utf-8-sig incremental decoder, which didn't recognise a BOM when the
-  first chunk fed to the decoder started with a BOM, but was longer than 3
-  bytes.
-
-- The implementation of UnicodeError objects has been simplified (start and end
-  attributes are now stored directly as Py_ssize_t members).
+- idle: Honor the "Cancel" action in the save dialog (Debian bug
+  #299092).
 
-- Issue829951: In the smtplib module, SMTP.starttls() now complies with
-  RFC 3207 and forgets any knowledge obtained from the server not obtained
-  from the TLS negotiation itself.  Patch contributed by Bill Fenner.
+- Fix utf-8-sig incremental decoder, which didn't recognise a BOM when
+  the first chunk fed to the decoder started with a BOM, but was
+  longer than 3 bytes.
+
+- The implementation of UnicodeError objects has been simplified
+  (start and end attributes are now stored directly as Py_ssize_t
+  members).
+
+- Issue #829951: In the smtplib module, SMTP.starttls() now complies
+  with RFC 3207 and forgets any knowledge obtained from the server not
+  obtained from the TLS negotiation itself.  Patch contributed by Bill
+  Fenner.
 
-- Issue1339: The smtplib.SMTP class has been refactored a bit such
+- Issue #1339: The smtplib.SMTP class has been refactored a bit such
   that the SMTP.starttls() caller no longer needs to call ehlo()
   beforehand.  SMTP.starttls() now raises an exception of the server
-  does not claim to support starttls.  Adds the SMTP.ehlo_or_helo_if_needed()
-  method.  Patch contributed by Bill Fenner.
+  does not claim to support starttls.  Adds the
+  SMTP.ehlo_or_helo_if_needed() method.  Patch contributed by Bill
+  Fenner.
 
-- Patch #1089358: Add signal.siginterrupt, a wrapper around siginterrupt(3).
+- Patch #1089358: Add signal.siginterrupt, a wrapper around
+  siginterrupt(3).
 
 Extension Modules
 -----------------
 
-- Patch #1657: added select.epoll and select.kqueue
+- Patch #1657: added select.epoll and select.kqueue.
 
 - Patch #1506171: added operator.methodcaller().
 
 - Patch #1826: operator.attrgetter() now supports dotted attribute paths.
 
-- Patch #1957: syslogmodule: Release GIL when calling syslog(3)
+- Patch #1957: syslogmodule: Release GIL when calling syslog(3).
 
-- #2112: mmap.error is now a subclass of EnvironmentError and not a
-  direct EnvironmentError
+- Bug #2112: mmap.error is now a subclass of EnvironmentError and not
+  a direct EnvironmentError.
 
-- Bug #2111: mmap segfaults when trying to write a block opened with PROT_READ
+- Bug #2111: mmap segfaults when trying to write a block opened with
+  PROT_READ.
 
-- #2063: correct order of utime and stime in os.times() result on Windows.
+- Bug #2063: correct order of utime and stime in os.times() result on
+  Windows.
 
 - Patch #1736: Fix file name handling of _msi.FCICreate.
 
 - Updated ``big5hkscs`` codec to the HKSCS revision of 2004.
 
-- #1940: make it possible to use curses.filter() before curses.initscr()
-  as the documentation says.
+- Issue #1940: make it possible to use curses.filter() before
+  curses.initscr() as the documentation says.
 
 - Backport of _fileio module from Python 3.0.
 
-- #1087741: mmap.mmap is now a class, not a factory function. It is also
-  subclassable now.
+- Patch #1087741: mmap.mmap is now a class, not a factory function. It
+  is also subclassable now.
 
 - Patch #1648: added ``sys.getprofile()`` and ``sys.gettrace()``.
 
-- Patch #1663329: added ``os.closerange()`` function to quickly close a range
-  of file descriptors without considering errors.
+- Patch #1663329: added ``os.closerange()`` function to quickly close
+  a range of file descriptors without considering errors.
 
-- Patch 976880: ``mmap`` objects now have an ``rfind`` method that
+- Patch #976880: ``mmap`` objects now have an ``rfind`` method that
   works as expected.  ``mmap.find`` also takes an optional ``end``
   parameter.
 
-- _winreg's HKEY object has gained __enter__ and __exit__ methods to support
-  the context manager protocol.  The _winreg module also gained a new function
-  ``ExpandEnvironmentStrings`` to expand REG_EXPAND_SZ keys.
+- _winreg's HKEY object has gained __enter__ and __exit__ methods to
+  support the context manager protocol.  The _winreg module also
+  gained a new function ``ExpandEnvironmentStrings`` to expand
+  REG_EXPAND_SZ keys.
+
+- itertools.starmap() now accepts any iterable input. Previously, it
+  required the function inputs to be tuples.
+
+- itertools.chain() now has an alternate constructor,
+  chain.from_iterable().
+
+- Issue #1646: Make socket support TIPC. The socket module now has
+  support for TIPC under Linux, see http://tipc.sf.net/ for more
+  information.
 
-- itertools.starmap() now accepts any iterable input. Previously, it required
-  the function inputs to be tuples.
-
-- itertools.chain() now has an alternate constructor, chain.from_iterable().
-
-- Issue #1646: Make socket support TIPC. The socket module now has support
-  for TIPC under Linux, see http://tipc.sf.net/ for more information.
-
-- Added interface for Windows' WSAIoctl to socket object and added an example
-  for a simple network sniffer.
+- Added interface for Windows' WSAIoctl to socket object and added an
+  example for a simple network sniffer.
 
 - Bug #1301: Bad assert in _tkinter fixed.
 
 - Added bdist_wininst executable for VS 2008.
 
-- Bug #1604: collections.deque.__init__(iterable) now clears any prior contents
-  before adding elements from the iterable.  This fix brings the behavior into
-  line with that for list.__init__().
+- Bug #1604: collections.deque.__init__(iterable) now clears any prior
+  contents before adding elements from the iterable.  This fix brings
+  the behavior into line with that for list.__init__().
 
-- Added wide char functions to msvcrt module: getwch, getwche, putwch and
-  ungetwch. The functions accept or return unicode.
+- Added wide char functions to msvcrt module: getwch, getwche, putwch
+  and ungetwch. The functions accept or return unicode.
 
 - os.access now returns True on Windows for any existing directory.
 
 - Added warnpy3k function to the warnings module.
 
-- Marshal.dumps() now expects exact type matches for int, long, float, complex,
-  tuple, list, dict, set, and frozenset.  Formerly, it would silently miscode
-  subclasses of those types.  Now, it raises a ValueError instead.
+- Marshal.dumps() now expects exact type matches for int, long, float,
+  complex, tuple, list, dict, set, and frozenset.  Formerly, it would
+  silently miscode subclasses of those types.  Now, it raises a
+  ValueError instead.
 
 - Patch #1388440: Add set_completion_display_matches_hook and
   get_completion_type to readline.
@@ -1850,21 +2042,22 @@
   intended for RECNO databases.
 
 - pybsddb.sf.net Bug #477182: Load the database flags at database open
-  time so that opening a database previously created with the DB_DUP or
-  DB_DUPSORT flag set will keep the proper behavior on subsequent opens.
-  Specifically: dictionary assignment to a DB object will replace all
-  values for a given key when the database allows duplicate values.
-  DB users should use DB.put(k, v) when they want to store duplicates; not
-  DB[k] = v.
+  time so that opening a database previously created with the DB_DUP
+  or DB_DUPSORT flag set will keep the proper behavior on subsequent
+  opens.  Specifically: dictionary assignment to a DB object will
+  replace all values for a given key when the database allows
+  duplicate values.  DB users should use DB.put(k, v) when they want
+  to store duplicates; not DB[k] = v.
 
 - Add the bsddb.db.DBEnv.lock_id_free method.
 
 - Bug #1686475: Support stat'ing open files on Windows again.
 
-- Patch #1185447: binascii.b2a_qp() now correctly quotes binary characters
-  with ASCII value less than 32. Also, it correctly quotes dots only if
-  they occur on a single line, as opposed to the previous behavior of
-  quoting dots if they are the second character of any line.
+- Patch #1185447: binascii.b2a_qp() now correctly quotes binary
+  characters with ASCII value less than 32. Also, it correctly quotes
+  dots only if they occur on a single line, as opposed to the previous
+  behavior of quoting dots if they are the second character of any
+  line.
 
 - Bug #1622896: fix a rare corner case where the bz2 module raised an
   error in spite of a succesful compression.
@@ -1875,8 +2068,9 @@
 - Patch #1646728: datetime.fromtimestamp fails with negative
   fractional times.  With unittest.
 
-- Patch #1490190: posixmodule now includes os.chflags() and os.lchflags()
-  functions on platforms where the underlying system calls are available.
+- Patch #1490190: posixmodule now includes os.chflags() and
+  os.lchflags() functions on platforms where the underlying system
+  calls are available.
 
 - Patch #1494140: Add documentation for the new struct.Struct object.
 
@@ -1886,20 +2080,21 @@
 
 - Bug #1653736: Complain about keyword arguments to time.isoformat.
 
-- Bug #1486663: don't reject keyword arguments for subclasses of builtin
-  types.
+- Bug #1486663: don't reject keyword arguments for subclasses of
+  builtin types.
 
-- Patch #1610575: The struct module now supports the 't' code, for
-  C99 _Bool.
+- Patch #1610575: The struct module now supports the 't' code, for C99
+  _Bool.
 
-- Patch #1635058: ensure that htonl and friends never accept or
-  return negative numbers, per the underlying C implementation.
+- Patch #1635058: ensure that htonl and friends never accept or return
+  negative numbers, per the underlying C implementation.
 
 - Patch #1544279: Improve thread-safety of the socket module by moving
   the sock_addr_t storage out of the socket object.
 
-- Patch #1019808: fix bug that causes an incorrect error to be returned
-  when a socket timeout is set and a connection attempt fails.
+- Patch #1019808: fix bug that causes an incorrect error to be
+  returned when a socket timeout is set and a connection attempt
+  fails.
 
 - Speed up function calls into the math module.
 
@@ -1925,19 +2120,21 @@
 
 - RLIMIT_SBSIZE was added to the resource module where available.
 
-- Bug #1551427: fix a wrong NULL pointer check in the win32 version
-  of os.urandom().
+- Bug #1551427: fix a wrong NULL pointer check in the win32 version of
+  os.urandom().
 
 - Bug #1548092: fix curses.tparm seg fault on invalid input.
 
 - Patch #1114: fix curses module compilation on 64-bit AIX, & possibly
-  other 64-bit LP64 platforms where attr_t is not the same size as a long.
-  (Contributed by Luke Mewburn.)
+  other 64-bit LP64 platforms where attr_t is not the same size as a
+  long.  (Contributed by Luke Mewburn.)
 
-- Bug #1550714: fix SystemError from itertools.tee on negative value for n.
+- Bug #1550714: fix SystemError from itertools.tee on negative value
+  for n.
 
 - Fixed a few bugs on cjkcodecs:
-  - gbk and gb18030 codec now handle U+30FB KATAKANA MIDDLE DOT correctly.
+  - gbk and gb18030 codec now handle U+30FB KATAKANA MIDDLE DOT
+    correctly.
   - iso2022_jp_2 codec now encodes into G0 for KS X 1001, GB2312
     codepoints to conform the standard.
   - iso2022_jp_3 and iso2022_jp_2004 codec can encode JIS X 0213:2
@@ -1954,8 +2151,9 @@
 - Added support for linking the bsddb module against BerkeleyDB 4.5.x
   and 4.6.x.
 
-- Bug #1633621: if curses.resizeterm() or curses.resize_term() is called,
-  update _curses.LINES, _curses.COLS, curses.LINES and curses.COLS.
+- Bug #1633621: if curses.resizeterm() or curses.resize_term() is
+  called, update _curses.LINES, _curses.COLS, curses.LINES and
+  curses.COLS.
 
 - Fix an off-by-one bug in locale.strxfrm().
 
@@ -1975,26 +2173,28 @@
 
 - Refactor test_logging to use unittest.
 
-- Refactor test_profile and test_cprofile to use the same code to profile.
+- Refactor test_profile and test_cprofile to use the same code to
+  profile.
 
-- Make test_runpy reentrant by fixing _check_module to clear out any module
-  being tested.  Was causing an error by __import__ doing a reload on the
-  second run and thus suppressing bytecode recreation.
+- Make test_runpy reentrant by fixing _check_module to clear out any
+  module being tested.  Was causing an error by __import__ doing a
+  reload on the second run and thus suppressing bytecode recreation.
 
 - Capture socket connection resets and timeouts in test_socket_ssl and
   test_urllib2net and raise test.test_support.ResourceDenied.
 
-- Patch #1559413: Fix test_cmd_line if sys.executable contains a space.
+- Patch #1559413: Fix test_cmd_line if sys.executable contains a
+  space.
 
-- Added test.test_support.TransientResource which is a context manager to
-  surround calls to resources that are not guaranteed to work even if
-  test.test_support.requires says that the resource should exist.
+- Added test.test_support.TransientResource which is a context manager
+  to surround calls to resources that are not guaranteed to work even
+  if test.test_support.requires says that the resource should exist.
 
 - Added a test for slicing of an exception.
 
-- Added test.test_support.EnvironmentVarGuard.  It's a class that provides a
-  context manager so that one can temporarily set or unset environment
-  variables.
+- Added test.test_support.EnvironmentVarGuard.  It's a class that
+  provides a context manager so that one can temporarily set or unset
+  environment variables.
 
 - Added some tests for modulefinder.
 
@@ -2003,34 +2203,33 @@
 - Fix bsddb test_basics.test06_Transactions to check the version
   number properly.
 
-- test.test_support.catch_warning is a new context manager that can be used
-  to catch the warnings issued by the warning framework.
-
+- test.test_support.catch_warning is a new context manager that can be
+  used to catch the warnings issued by the warning framework.
 
 Tools
 -----
 
-- Tools/scripts/reindent.py now creates the backup file using shutil.copy
-  to preserve user/group and permissions. Added also a --nobackup option
-  to not create the backup if the user is concerned regarding this.  Check
-  issue 1050828 for more details.
-
-- Tools/scripts/win_add2path.py was added. The simple script modifes the
-  PATH environment var of the HKCU tree and adds the python bin and script
-  directory.
+- Tools/scripts/reindent.py now creates the backup file using
+  shutil.copy to preserve user/group and permissions. Added also a
+  --nobackup option to not create the backup if the user is concerned
+  regarding this.  Check issue 1050828 for more details.
+
+- Tools/scripts/win_add2path.py was added. The simple script modifes
+  the PATH environment var of the HKCU tree and adds the python bin
+  and script directory.
 
 - Tools/18n/pygettext.py was added to the list of scripts installed by
   Tools/scripts/setup.py (tracker item 642309).
 
-- Added IronPython and Jython support to pybench (part of which
-  was patch #1563844)
+- Added IronPython and Jython support to pybench (part of which was
+  patch #1563844).
 
-- Made some minor changes to pybench output to allow the user
-  to see which Python version is running pybench
+- Made some minor changes to pybench output to allow the user to see
+  which Python version is running pybench.
 
 - Added support for the new platform module feature
-  platform.python_implementation(); this will now be saved
-  in the benchmark pickle
+  platform.python_implementation(); this will now be saved in the
+  benchmark pickle.
 
 
 Documentation
@@ -2039,8 +2238,9 @@
 - RFE #1765140: Updated documentation on FileHandler and subclasses to
   include new optional delay argument.
 
-- Bug #932563: Added section on getting contextual information into logging
-  output, and added documentation for the new LoggerAdapter class.
+- Bug #932563: Added section on getting contextual information into
+  logging output, and added documentation for the new LoggerAdapter
+  class.
 
 - Bug #1295: Added information about caching of formatted exception
   information in the LogRecord by Formatter.format().
@@ -2050,8 +2250,8 @@
 
 - Patch #1698768: updated the "using Python on the Mac" intro.
 
-- Bug #1569057: Document that calling file.next() when the file is open for
-  writing is undefined.
+- Bug #1569057: Document that calling file.next() when the file is
+  open for writing is undefined.
 
 - Patch #1489771: the syntax rules in Python Reference Manual were
   updated to reflect the current Python syntax.
@@ -2078,8 +2278,9 @@
 - Bug #1566663: remove obsolete example from datetime docs.
 
 - Bug #1541682: Fix example in the "Refcount details" API docs.
-  Additionally, remove a faulty example showing PySequence_SetItem applied
-  to a newly created list object and add notes that this isn't a good idea.
+  Additionally, remove a faulty example showing PySequence_SetItem
+  applied to a newly created list object and add notes that this isn't
+  a good idea.
 
 
 Tools/Demos
@@ -2088,8 +2289,8 @@
 - Patch #1552024: add decorator support to unparse.py demo script.
 
 - Make auto-generated python.vim file list built-ins and exceptions in
-  alphatbetical order.  Makes output more deterministic and easier to tell if
-  the file is stale or not.
+  alphatbetical order.  Makes output more deterministic and easier to
+  tell if the file is stale or not.
 
 - Bug #1546372: Fixed small bugglet in pybench that caused a missing
   file not to get reported properly.
@@ -2098,23 +2299,24 @@
 Build
 -----
 
-- Have the search path for building extensions follow the declared order in
-  $CPPFLAGS and $LDFLAGS when adding directories from those environment
-  variables.
+- Have the search path for building extensions follow the declared
+  order in $CPPFLAGS and $LDFLAGS when adding directories from those
+  environment variables.
 
 - Bug #1983: Added a check to pyport to verify that sizeof(pid_t) is
   smaller or equal sizeof(long).
 
 - Bug #1234: Fixed semaphore errors on AIX 5.2
 
-- Issue #1726: Remove Python/atof.c from PCBuild/pythoncore.vcproj
+- Issue #1726: Remove Python/atof.c from PCBuild/pythoncore.vcproj.
 
-- Removed PCbuild8/ directory and added a new build directory for VS 2005
-  based on the VS 2008 build directory to PC/VS8.0. The script
-  PCbuild/vs8to9.py was added to sync changes from PCbuild to PC/VS8.0.
+- Removed PCbuild8/ directory and added a new build directory for VS
+  2005 based on the VS 2008 build directory to PC/VS8.0. The script
+  PCbuild/vs8to9.py was added to sync changes from PCbuild to
+  PC/VS8.0.
 
-- Moved PCbuild/ directory for VS 2003 to PC/VS7.1 and renamed PCBuild9/
-  directory to PCBuild/.
+- Moved PCbuild/ directory for VS 2003 to PC/VS7.1 and renamed
+  PCBuild9/ directory to PCBuild/.
 
 - Bug #1699: Define _BSD_SOURCE only on OpenBSD.
 
@@ -2125,20 +2327,22 @@
 - Patch #1418: Make the AC_REPLACE_FUNCS object files actually work.
 
 - Add a FAST_LOOPS build option that speeds-up looping by trading away
-  periodic threadstate and signal checking in tight loops.  By default,
-  this option is turned-off.  It should only be enabled in debugged,
-  performance critical applications.
+  periodic threadstate and signal checking in tight loops.  By
+  default, this option is turned-off.  It should only be enabled in
+  debugged, performance critical applications.
 
-- Patch #786737: Allow building in a tree of symlinks pointing to
-  a readonly source.
+- Patch #786737: Allow building in a tree of symlinks pointing to a
+  readonly source.
 
 - Bug #1737210: Change Manufacturer of Windows installer to PSF.
 
 - Bug #1746880: Correctly install DLLs into system32 folder on Win64.
 
-- Define _BSD_SOURCE, to get access to POSIX extensions on OpenBSD 4.1+.
+- Define _BSD_SOURCE, to get access to POSIX extensions on OpenBSD
+  4.1+.
 
-- Stop supporting AtheOS and cause a build error in configure for the platform.
+- Stop supporting AtheOS and cause a build error in configure for the
+  platform.
 
 - Bug #1655392: don't add -L/usr/lib/pythonX.Y/config to the LDFLAGS
   returned by python-config if Python was built with --enable-shared
@@ -2151,18 +2355,18 @@
 
 - Disable _XOPEN_SOURCE on NetBSD 1.x.
 
-- configure now checks whether gcc supports the PyArg_ParseTuple format
-  attribute.
+- configure now checks whether gcc supports the PyArg_ParseTuple
+  format attribute.
 
 - Bug #1578513: Cross compilation was broken by a change to configure.
   Repair so that it's back to how it was in 2.4.3.
 
-- Patch #1576954: Update VC6 build directory; remove redundant
-  files in VC7.
+- Patch #1576954: Update VC6 build directory; remove redundant files
+  in VC7.
 
 - Bug #1568842: Fix test for uintptr_t.
 
-- Patch #1540470, for OpenBSD 4.0.
+- Patch #1540470: for OpenBSD 4.0.
 
 - Fix build failure on kfreebsd and on the hurd.
 
@@ -2170,45 +2374,48 @@
 
 - Allow Emacs 22 for building the documentation in info format.
 
-- Makefile.pre.in(buildbottest): Run an optional script pybuildbot.identify
-  to include some information about the build environment.
+- Makefile.pre.in(buildbottest): Run an optional script
+  pybuildbot.identify to include some information about the build
+  environment.
 
 
 C API
 -----
 
-- Unified naming convention for free lists and their limits. All free lists
-  in Object/ are named ``free_list``, the counter ``numfree`` and the upper
-  limit is a macro ``PyName_MAXFREELIST`` inside an #ifndef block.
-
-- ``PySet_Add()`` can now modify a newly created frozenset.  Similarly to
-  ``PyTuple_SetItem``, it can be used to populate a brand new frozenset; but
-  it does not steal a reference to the added item.
+- Unified naming convention for free lists and their limits. All free
+  lists in Object/ are named ``free_list``, the counter ``numfree``
+  and the upper limit is a macro ``PyName_MAXFREELIST`` inside an
+  #ifndef block.
+
+- ``PySet_Add()`` can now modify a newly created frozenset.  Similarly
+  to ``PyTuple_SetItem``, it can be used to populate a brand new
+  frozenset; but it does not steal a reference to the added item.
 
 - Added ``PySet_Check()`` and ``PyFrozenSet_Check()`` to the set API.
 
-- Backport of PyUnicode_FromString(), _FromStringAndSize(), _Format and
-  _FormatV from Python 3.0. Made PyLong_AsSsize_t and PyLong_FromSsize_t
-  public functions.
+- Backport of PyUnicode_FromString(), _FromStringAndSize(), _Format
+  and _FormatV from Python 3.0. Made PyLong_AsSsize_t and
+  PyLong_FromSsize_t public functions.
 
 - Patch #1720595: add T_BOOL to the range of structmember types.
 
 - Issue #1534: Added ``PyFloat_GetMax()``, ``PyFloat_GetMin()`` and
   ``PyFloat_GetInfo()`` to the float API.
 
-- Issue #1521: On 64bit platforms, using PyArgs_ParseTuple with the t# of w#
-  format code incorrectly truncated the length to an int, even when
-  PY_SSIZE_T_CLEAN is set.  The str.decode method used to return incorrect
-  results with huge strings.
-
-- Issue #1629: Renamed Py_Size, Py_Type and Py_Refcnt to Py_SIZE, Py_TYPE
-  and Py_REFCNT.
-
-- PEP 3123: Provide forward compatibility with Python 3.0, while keeping
-  backwards compatibility. Add Py_Refcnt, Py_Type, Py_Size, and
-  PyVarObject_HEAD_INIT.
+- Issue #1521: On 64bit platforms, using PyArgs_ParseTuple with the t#
+  of w# format code incorrectly truncated the length to an int, even
+  when PY_SSIZE_T_CLEAN is set.  The str.decode method used to return
+  incorrect results with huge strings.
+
+- Issue #1629: Renamed Py_Size, Py_Type and Py_Refcnt to Py_SIZE,
+  Py_TYPE and Py_REFCNT.
+
+- PEP 3123: Provide forward compatibility with Python 3.0, while
+  keeping backwards compatibility. Add Py_Refcnt, Py_Type, Py_Size,
+  and PyVarObject_HEAD_INIT.
 
-- Py_ssize_t fields work in structmember when HAVE_LONG_LONG is not defined.
+- Py_ssize_t fields work in structmember when HAVE_LONG_LONG is not
+  defined.
 
 - Patch #1733960: Allow T_LONGLONG to accept ints.
 
@@ -2224,26 +2431,27 @@
 - Make _PyGILState_NoteThreadState() static, it was not used anywhere
   outside of pystate.c and should not be necessary.
 
-- ``PyImport_Import`` and ``PyImport_ImportModule`` now always do absolute
-  imports. In earlier versions they might have used relative imports under
-  some conditions.
+- ``PyImport_Import`` and ``PyImport_ImportModule`` now always do
+  absolute imports. In earlier versions they might have used relative
+  imports under some conditions.
 
-- Added case insensitive comparison methods ``PyOS_stricmp(char*, char*)``
-  and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
+- Added case insensitive comparison methods ``PyOS_stricmp(char*,
+  char*)`` and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
 
-- Bug #1542693: remove semi-colon at end of PyImport_ImportModuleEx macro
-  so it can be used as an expression.
+- Bug #1542693: remove semi-colon at end of PyImport_ImportModuleEx
+  macro so it can be used as an expression.
 
 
 Windows
 -------
 
-- Patch #1706: Drop support for Win9x, WinME and NT4. Python now requires
-  Windows 2000 or greater. The _WINVER and NTDDI_VERSION macros are set to
-  Win2k for x86/32bit builds and WinXP for AMD64 builds.
+- Patch #1706: Drop support for Win9x, WinME and NT4. Python now
+  requires Windows 2000 or greater. The _WINVER and NTDDI_VERSION
+  macros are set to Win2k for x86/32bit builds and WinXP for AMD64
+  builds.
 
-- Conditionalize definition of _CRT_SECURE_NO_DEPRECATE
-  and _CRT_NONSTDC_NO_DEPRECATE.
+- Conditionalize definition of _CRT_SECURE_NO_DEPRECATE and
+  _CRT_NONSTDC_NO_DEPRECATE.
 
 - Bug #1216: Restore support for Visual Studio 2002.
 
@@ -2255,9 +2463,9 @@
 
 - buildtools now raises a DeprecationWarning.
 
-- Removed the macfs module.  It had been deprecated since Python 2.5.  This
-  lead to the deprecation of macostools.touched() as it relied solely on macfs
-  and was a no-op under OS X.
+- Removed the macfs module.  It had been deprecated since Python 2.5.
+  This lead to the deprecation of macostools.touched() as it relied
+  solely on macfs and was a no-op under OS X.
 
 ----
 

Modified: python/branches/okkoto-sizeof/Misc/build.sh
==============================================================================
--- python/branches/okkoto-sizeof/Misc/build.sh	(original)
+++ python/branches/okkoto-sizeof/Misc/build.sh	Wed Jun  4 11:24:23 2008
@@ -67,7 +67,7 @@
 # Note: test_XXX (none currently) really leak, but are disabled
 # so we don't send spam.  Any test which really leaks should only 
 # be listed here if there are also test cases under Lib/test/leakers.
-LEAKY_TESTS="test_(asynchat|cmd_line|popen2|socket|smtplib|sys|threadsignals|urllib2_localnet)"
+LEAKY_TESTS="test_(asynchat|cmd_line|popen2|socket|smtplib|sys|threadsignals|urllib2_localnet|httpservers)"
 
 # Skip these tests altogether when looking for leaks.  These tests
 # do not need to be stored above in LEAKY_TESTS too.

Modified: python/branches/okkoto-sizeof/Misc/cheatsheet
==============================================================================
--- python/branches/okkoto-sizeof/Misc/cheatsheet	(original)
+++ python/branches/okkoto-sizeof/Misc/cheatsheet	Wed Jun  4 11:24:23 2008
@@ -1044,7 +1044,7 @@
 super(type)         Create an unbound super object.  Used to call cooperative
                     superclass methods.
 sum(sequence,       Add the values in the sequence and return the sum.
-    [start]) 
+    [start])
 tuple(sequence)     Creates a tuple with same elements as sequence. If already
                     a tuple, return itself (not a copy).
                     Returns a type object [see module types] representing
@@ -1973,7 +1973,7 @@
                  sys.path.
 smtplib          SMTP Client class (RFC 821)
 sndhdr           Several routines that help recognizing sound.
-socketserver     Generic socket server classes.
+SocketServer     Generic socket server classes.
 stat             Constants and functions for interpreting stat/lstat struct.
 statcache        Maintain a cache of file stats.
 statvfs          Constants for interpreting statvfs struct as returned by

Modified: python/branches/okkoto-sizeof/Misc/developers.txt
==============================================================================
--- python/branches/okkoto-sizeof/Misc/developers.txt	(original)
+++ python/branches/okkoto-sizeof/Misc/developers.txt	Wed Jun  4 11:24:23 2008
@@ -17,6 +17,9 @@
 Permissions History
 -------------------
 
+- Robert Schuppenies was given SVN access on 21 May 2008 by MvL,
+  for GSoC contributions.
+
 - Rodrigo Bernardo Pimentel was given SVN access on 29 April 2008 by MvL,
   for GSoC contributions.
 

Modified: python/branches/okkoto-sizeof/Modules/_bsddb.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_bsddb.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_bsddb.c	Wed Jun  4 11:24:23 2008
@@ -50,7 +50,7 @@
  *
  * Gregory P. Smith <greg at krypto.org> was once again the maintainer.
  *
- * Since January 2008, new maintainer is Jesus Cea <jcea at argo.es>.
+ * Since January 2008, new maintainer is Jesus Cea <jcea at jcea.es>.
  * Jesus Cea licenses this code to PSF under a Contributor Agreement.
  *
  * Use the pybsddb-users at lists.sf.net mailing list for all questions.
@@ -104,6 +104,17 @@
 typedef int Py_ssize_t;
 #endif
 
+#if (PY_VERSION_HEX < 0x02060000)  /* really: before python trunk r63675 */
+/* This code now uses PyBytes* API function names instead of PyString*.
+ * These #defines map to their equivalent on earlier python versions.    */
+#define PyBytes_FromStringAndSize PyString_FromStringAndSize
+#define PyBytes_FromString PyString_FromString
+#define PyBytes_AsStringAndSize PyString_AsStringAndSize
+#define PyBytes_Check PyString_Check
+#define PyBytes_GET_SIZE PyString_GET_SIZE
+#define PyBytes_AS_STRING PyString_AS_STRING
+#endif
+
 #ifdef WITH_THREAD
 
 /* These are for when calling Python --> C */
@@ -398,7 +409,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)
@@ -417,15 +428,15 @@
          * the code check for DB_THREAD and forceably set DBT_MALLOC
          * when we otherwise would leave flags 0 to indicate that.
          */
-        key->data = malloc(PyString_GET_SIZE(keyobj));
+        key->data = malloc(PyBytes_GET_SIZE(keyobj));
         if (key->data == NULL) {
             PyErr_SetString(PyExc_MemoryError, "Key memory allocation failed");
             return 0;
         }
-        memcpy(key->data, PyString_AS_STRING(keyobj),
-               PyString_GET_SIZE(keyobj));
+        memcpy(key->data, PyBytes_AS_STRING(keyobj),
+               PyBytes_GET_SIZE(keyobj));
         key->flags = DB_DBT_REALLOC;
-        key->size = PyString_GET_SIZE(keyobj);
+        key->size = PyBytes_GET_SIZE(keyobj);
     }
 
     else if (PyInt_Check(keyobj)) {
@@ -535,7 +546,7 @@
     p=DummyString;
     assert(s==0);
   }
-  return PyString_FromStringAndSize(p,s);
+  return PyBytes_FromStringAndSize(p,s);
 }
 
 static PyObject *BuildValue_S(const void *p,int s)
@@ -903,7 +914,7 @@
             Py_DECREF(self->myenvobj);
             self->myenvobj = NULL;
         }
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
     return self;
@@ -1010,7 +1021,7 @@
     err = db_env_create(&self->db_env, flags);
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
     else {
@@ -1050,20 +1061,27 @@
 newDBTxnObject(DBEnvObject* myenv, DBTxnObject *parent, DB_TXN *txn, int flags)
 {
     int err;
-    DB_TXN *parent_txn=NULL;
+    DB_TXN *parent_txn = NULL;
 
     DBTxnObject* self = PyObject_New(DBTxnObject, &DBTxn_Type);
     if (self == NULL)
         return NULL;
 
     self->in_weakreflist = NULL;
+    self->children_txns = NULL;
+    self->children_dbs = NULL;
+    self->children_cursors = NULL;
+    self->children_sequences = NULL;
+    self->flag_prepare = 0;
+    self->parent_txn = NULL;
+    self->env = NULL;
 
     if (parent && ((PyObject *)parent!=Py_None)) {
-        parent_txn=parent->txn;
+        parent_txn = parent->txn;
     }
 
     if (txn) {
-        self->txn=txn;
+        self->txn = txn;
     } else {
         MYDB_BEGIN_ALLOW_THREADS;
 #if (DBVER >= 40)
@@ -1074,29 +1092,24 @@
         MYDB_END_ALLOW_THREADS;
 
         if (makeDBError(err)) {
-            PyObject_Del(self);
+            Py_DECREF(self);
             return NULL;
         }
     }
 
-    if (parent_txn) { /* Can't use 'parent' because could be 'parent==Py_None' */
-        self->parent_txn=parent;
+    /* Can't use 'parent' because could be 'parent==Py_None' */
+    if (parent_txn) {
+        self->parent_txn = parent;
         Py_INCREF(parent);
         self->env = NULL;
-        INSERT_IN_DOUBLE_LINKED_LIST(parent->children_txns,self);
+        INSERT_IN_DOUBLE_LINKED_LIST(parent->children_txns, self);
     } else {
-        self->parent_txn=NULL;
+        self->parent_txn = NULL;
         Py_INCREF(myenv);
         self->env = myenv;
-        INSERT_IN_DOUBLE_LINKED_LIST(myenv->children_txns,self);
+        INSERT_IN_DOUBLE_LINKED_LIST(myenv->children_txns, self);
     }
 
-    self->children_txns=NULL;
-    self->children_dbs=NULL;
-    self->children_cursors=NULL;
-    self->children_sequences=NULL;
-    self->flag_prepare=0;
-
     return self;
 }
 
@@ -1151,7 +1164,7 @@
 #endif
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
 
@@ -1183,7 +1196,7 @@
     self->mydb = mydb;
 
     INSERT_IN_DOUBLE_LINKED_LIST(self->mydb->children_sequences,self);
-    self->txn=NULL;
+    self->txn = NULL;
 
     self->in_weakreflist = NULL;
 
@@ -1191,8 +1204,7 @@
     err = db_sequence_create(&self->sequence, self->mydb->db, flags);
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        Py_DECREF(self->mydb);
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
 
@@ -1290,12 +1302,12 @@
         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);
-            PyString_AsStringAndSize(result, &data, &size);
+            PyBytes_AsStringAndSize(result, &data, &size);
             secKey->flags = DB_DBT_APPMALLOC;   /* DB will free */
             secKey->data = malloc(size);        /* TODO, check this */
 	    if (secKey->data) {
@@ -4128,6 +4140,26 @@
 }
 
 
+#if (DBVER >= 47)
+static PyObject*
+DBEnv_log_set_config(DBEnvObject* self, PyObject* args)
+{
+    int err, flags, onoff;
+
+    if (!PyArg_ParseTuple(args, "ii:log_set_config",
+                          &flags, &onoff))
+        return NULL;
+    CHECK_ENV_NOT_CLOSED(self);
+
+    MYDB_BEGIN_ALLOW_THREADS;
+    err = self->db_env->log_set_config(self->db_env, flags, onoff);
+    MYDB_END_ALLOW_THREADS;
+    RETURN_IF_ERR();
+    RETURN_NONE();
+}
+#endif /* DBVER >= 47 */
+
+
 static PyObject*
 DBEnv_set_data_dir(DBEnvObject* self, PyObject* args)
 {
@@ -4391,7 +4423,7 @@
         if (!retp) break;
         flags=DB_NEXT;  /* Prepare for next loop pass */
         for (i=0; i<retp; i++) {
-            gid=PyString_FromStringAndSize((char *)(preplist[i].gid),
+            gid=PyBytes_FromStringAndSize((char *)(preplist[i].gid),
                                 DB_XIDDATASIZE);
             if (!gid) {
                 Py_DECREF(list);
@@ -4778,8 +4810,13 @@
     MAKE_ENTRY(objs_nowait);
     MAKE_ENTRY(lockers_wait);
     MAKE_ENTRY(lockers_nowait);
+#if (DBVER >= 47)
+    MAKE_ENTRY(lock_wait);
+    MAKE_ENTRY(lock_nowait);
+#else
     MAKE_ENTRY(locks_wait);
     MAKE_ENTRY(locks_nowait);
+#endif
     MAKE_ENTRY(hash_len);
 #endif
     MAKE_ENTRY(regsize);
@@ -4844,7 +4881,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 = PyBytes_FromString (*log_list);
             if (item == NULL) {
                 Py_DECREF(list);
                 list = NULL;
@@ -4944,6 +4981,30 @@
 
 #if (DBVER >= 40)
 static PyObject*
+DBEnv_set_rpc_server(DBEnvObject* self, PyObject* args, PyObject* kwargs)
+{
+    int err;
+    char *host;
+    long cl_timeout=0, sv_timeout=0;
+
+    static char* kwnames[] = { "host", "cl_timeout", "sv_timeout", NULL};
+
+    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|ll:set_rpc_server", kwnames,
+                                     &host, &cl_timeout, &sv_timeout))
+        return NULL;
+    CHECK_ENV_NOT_CLOSED(self);
+
+    MYDB_BEGIN_ALLOW_THREADS;
+    err = self->db_env->set_rpc_server(self->db_env, NULL, host, cl_timeout,
+            sv_timeout, 0);
+    MYDB_END_ALLOW_THREADS;
+    RETURN_IF_ERR();
+    RETURN_NONE();
+}
+#endif
+
+#if (DBVER >= 40)
+static PyObject*
 DBEnv_set_verbose(DBEnvObject* self, PyObject* args)
 {
     int err;
@@ -5074,7 +5135,11 @@
 DBEnv_rep_get_nsites(DBEnvObject* self, PyObject* args)
 {
     int err;
+#if (DBVER >= 47)
+    u_int32_t nsites;
+#else
     int nsites;
+#endif
 
     if (!PyArg_ParseTuple(args, ":rep_get_nsites")) {
         return NULL;
@@ -5108,7 +5173,11 @@
 DBEnv_rep_get_priority(DBEnvObject* self, PyObject* args)
 {
     int err;
+#if (DBVER >= 47)
+    u_int32_t priority;
+#else
     int priority;
+#endif
 
     if (!PyArg_ParseTuple(args, ":rep_get_priority")) {
         return NULL;
@@ -6093,6 +6162,9 @@
     {"set_cachesize",   (PyCFunction)DBEnv_set_cachesize,    METH_VARARGS},
     {"set_data_dir",    (PyCFunction)DBEnv_set_data_dir,     METH_VARARGS},
     {"set_flags",       (PyCFunction)DBEnv_set_flags,        METH_VARARGS},
+#if (DBVER >= 47)
+    {"log_set_config",  (PyCFunction)DBEnv_log_set_config,   METH_VARARGS},
+#endif
     {"set_lg_bsize",    (PyCFunction)DBEnv_set_lg_bsize,     METH_VARARGS},
     {"set_lg_dir",      (PyCFunction)DBEnv_set_lg_dir,       METH_VARARGS},
     {"set_lg_max",      (PyCFunction)DBEnv_set_lg_max,       METH_VARARGS},
@@ -6139,6 +6211,10 @@
     {"txn_recover",     (PyCFunction)DBEnv_txn_recover,       METH_VARARGS},
 #endif
 #if (DBVER >= 40)
+    {"set_rpc_server",  (PyCFunction)DBEnv_set_rpc_server,
+        METH_VARARGS||METH_KEYWORDS},
+#endif
+#if (DBVER >= 40)
     {"set_verbose",     (PyCFunction)DBEnv_set_verbose,       METH_VARARGS},
 #if (DBVER >= 42)
     {"get_verbose",     (PyCFunction)DBEnv_get_verbose,       METH_VARARGS},
@@ -6231,7 +6307,7 @@
       if (home == NULL) {
           RETURN_NONE();
       }
-      return PyString_FromString(home);
+      return PyBytes_FromString(home);
     }
 
     return Py_FindMethod(DBEnv_methods, (PyObject* )self, name);
@@ -6547,9 +6623,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 = PyBytes_FromString( PY_BSDDB_VERSION );
+    PyObject* db_version_s = PyBytes_FromString( DB_VERSION_STRING );
+    PyObject* cvsid_s = PyBytes_FromString( rcs_id );
     PyObject* py_api;
 
     /* Initialize the type of the new type objects here; doing it here
@@ -6759,6 +6835,7 @@
 #if (DBVER < 45)
     ADD_INT(d, DB_CACHED_COUNTS);
 #endif
+
 #if (DBVER >= 41)
     _addIntToDict(d, "DB_CHECKPOINT", 0);
 #else
@@ -6857,14 +6934,25 @@
     ADD_INT(d, DB_TIME_NOTGRANTED);
     ADD_INT(d, DB_TXN_NOT_DURABLE);
     ADD_INT(d, DB_TXN_WRITE_NOSYNC);
-    ADD_INT(d, DB_LOG_AUTOREMOVE);
-    ADD_INT(d, DB_DIRECT_LOG);
     ADD_INT(d, DB_DIRECT_DB);
     ADD_INT(d, DB_INIT_REP);
     ADD_INT(d, DB_ENCRYPT);
     ADD_INT(d, DB_CHKSUM);
 #endif
 
+#if (DBVER >= 42) && (DBVER < 47)
+    ADD_INT(d, DB_LOG_AUTOREMOVE);
+    ADD_INT(d, DB_DIRECT_LOG);
+#endif
+
+#if (DBVER >= 47)
+    ADD_INT(d, DB_LOG_DIRECT);
+    ADD_INT(d, DB_LOG_DSYNC);
+    ADD_INT(d, DB_LOG_IN_MEMORY);
+    ADD_INT(d, DB_LOG_AUTO_REMOVE);
+    ADD_INT(d, DB_LOG_ZERO);
+#endif
+
 #if (DBVER >= 44)
     ADD_INT(d, DB_DSYNC_DB);
 #endif
@@ -6934,14 +7022,17 @@
 #endif
 
 #if (DBVER >= 43)
-    ADD_INT(d, DB_DSYNC_LOG);
-    ADD_INT(d, DB_LOG_INMEMORY);
     ADD_INT(d, DB_BUFFER_SMALL);
     ADD_INT(d, DB_SEQ_DEC);
     ADD_INT(d, DB_SEQ_INC);
     ADD_INT(d, DB_SEQ_WRAP);
 #endif
 
+#if (DBVER >= 43) && (DBVER < 47)
+    ADD_INT(d, DB_LOG_INMEMORY);
+    ADD_INT(d, DB_DSYNC_LOG);
+#endif
+
 #if (DBVER >= 41)
     ADD_INT(d, DB_ENCRYPT_AES);
     ADD_INT(d, DB_AUTO_COMMIT);

Modified: python/branches/okkoto-sizeof/Modules/_bytesio.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_bytesio.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_bytesio.c	Wed Jun  4 11:24:23 2008
@@ -175,7 +175,7 @@
 bytesio_getvalue(BytesIOObject *self)
 {
     CHECK_CLOSED(self);
-    return PyString_FromStringAndSize(self->buf, self->string_size);
+    return PyBytes_FromStringAndSize(self->buf, self->string_size);
 }
 
 PyDoc_STRVAR(isatty_doc,
@@ -244,7 +244,7 @@
     output = self->buf + self->pos;
     self->pos += size;
 
-    return PyString_FromStringAndSize(output, size);
+    return PyBytes_FromStringAndSize(output, size);
 }
 
 
@@ -307,7 +307,7 @@
         self->pos -= size;
     }
 
-    return PyString_FromStringAndSize(output, n);
+    return PyBytes_FromStringAndSize(output, n);
 }
 
 PyDoc_STRVAR(readlines_doc,
@@ -349,7 +349,7 @@
         return NULL;
 
     while ((n = get_line(self, &output)) != 0) {
-        line = PyString_FromStringAndSize(output, n);
+        line = PyBytes_FromStringAndSize(output, n);
         if (!line)
             goto on_error;
         if (PyList_Append(result, line) == -1) {
@@ -455,7 +455,7 @@
     if (!next || n == 0)
         return NULL;
 
-    return PyString_FromStringAndSize(next, n);
+    return PyBytes_FromStringAndSize(next, n);
 }
 
 PyDoc_STRVAR(seek_doc,

Modified: python/branches/okkoto-sizeof/Modules/_codecsmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_codecsmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_codecsmodule.c	Wed Jun  4 11:24:23 2008
@@ -168,7 +168,7 @@
     if (!PyArg_ParseTuple(args, "s#|z:escape_decode",
 			  &data, &size, &errors))
 	return NULL;
-    return codec_tuple(PyString_DecodeEscape(data, size, errors, 0, NULL),
+    return codec_tuple(PyBytes_DecodeEscape(data, size, errors, 0, NULL),
 		       size);
 }
 
@@ -182,21 +182,21 @@
 	Py_ssize_t len;
 
 	if (!PyArg_ParseTuple(args, "O!|z:escape_encode",
-			      &PyString_Type, &str, &errors))
+			      &PyBytes_Type, &str, &errors))
 		return NULL;
 
-	str = PyString_Repr(str, 0);
+	str = PyBytes_Repr(str, 0);
 	if (!str)
 		return NULL;
 
 	/* The string will be quoted. Unquote, similar to unicode-escape. */
-	buf = PyString_AS_STRING (str);
-	len = PyString_GET_SIZE (str);
+	buf = PyBytes_AS_STRING (str);
+	len = PyBytes_GET_SIZE (str);
 	memmove(buf, buf+1, len-2);
-	if (_PyString_Resize(&str, len-2) < 0)
+	if (_PyBytes_Resize(&str, len-2) < 0)
 		return NULL;
 	
-	return codec_tuple(str, PyString_Size(str));
+	return codec_tuple(str, PyBytes_Size(str));
 }
 
 #ifdef Py_USING_UNICODE
@@ -640,7 +640,7 @@
 			  &data, &size, &errors))
 	return NULL;
 
-    return codec_tuple(PyString_FromStringAndSize(data, size),
+    return codec_tuple(PyBytes_FromStringAndSize(data, size),
 		       size);
 }
 
@@ -656,7 +656,7 @@
 			  &data, &size, &errors))
 	return NULL;
 
-    return codec_tuple(PyString_FromStringAndSize(data, size),
+    return codec_tuple(PyBytes_FromStringAndSize(data, size),
 		       size);
 }
 
@@ -676,13 +676,13 @@
     if (PyUnicode_Check(obj)) {
 	data = PyUnicode_AS_DATA(obj);
 	size = PyUnicode_GET_DATA_SIZE(obj);
-	return codec_tuple(PyString_FromStringAndSize(data, size),
+	return codec_tuple(PyBytes_FromStringAndSize(data, size),
 			   size);
     }
     else {
 	if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
 	    return NULL;
-	return codec_tuple(PyString_FromStringAndSize(data, size),
+	return codec_tuple(PyBytes_FromStringAndSize(data, size),
 			   size);
     }
 }

Modified: python/branches/okkoto-sizeof/Modules/_collectionsmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_collectionsmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_collectionsmodule.c	Wed Jun  4 11:24:23 2008
@@ -668,7 +668,7 @@
 	if (i != 0) {
 		if (i < 0)
 			return NULL;
-		return PyString_FromString("[...]");
+		return PyBytes_FromString("[...]");
 	}
 
 	aslist = PySequence_List(deque);
@@ -677,16 +677,16 @@
 		return NULL;
 	}
 	if (((dequeobject *)deque)->maxlen != -1)
-		fmt = PyString_FromFormat("deque(%%r, maxlen=%i)", 
+		fmt = PyBytes_FromFormat("deque(%%r, maxlen=%i)", 
 					((dequeobject *)deque)->maxlen);
 	else
-		fmt = PyString_FromString("deque(%r)");  
+		fmt = PyBytes_FromString("deque(%r)");  
 	if (fmt == NULL) {
 		Py_DECREF(aslist);
 		Py_ReprLeave(deque);
 		return NULL;
 	}
-	result = PyString_Format(fmt, aslist);
+	result = PyBytes_Format(fmt, aslist);
 	Py_DECREF(fmt);
 	Py_DECREF(aslist);
 	Py_ReprLeave(deque);
@@ -1298,14 +1298,14 @@
 	if (baserepr == NULL)
 		return NULL;
 	if (dd->default_factory == NULL)
-		defrepr = PyString_FromString("None");
+		defrepr = PyBytes_FromString("None");
 	else
 	{
 		int status = Py_ReprEnter(dd->default_factory);
 		if (status != 0) {
 			if (status < 0)
 				return NULL;
-			defrepr = PyString_FromString("...");
+			defrepr = PyBytes_FromString("...");
 		}
 		else
 			defrepr = PyObject_Repr(dd->default_factory);
@@ -1315,9 +1315,9 @@
 		Py_DECREF(baserepr);
 		return NULL;
 	}
-	result = PyString_FromFormat("defaultdict(%s, %s)",
-				     PyString_AS_STRING(defrepr),
-				     PyString_AS_STRING(baserepr));
+	result = PyBytes_FromFormat("defaultdict(%s, %s)",
+				     PyBytes_AS_STRING(defrepr),
+				     PyBytes_AS_STRING(baserepr));
 	Py_DECREF(defrepr);
 	Py_DECREF(baserepr);
 	return result;

Modified: python/branches/okkoto-sizeof/Modules/_csv.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_csv.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_csv.c	Wed Jun  4 11:24:23 2008
@@ -176,7 +176,7 @@
                 return Py_None;
         }
         else
-                return PyString_FromStringAndSize((char*)&c, 1);
+                return PyBytes_FromStringAndSize((char*)&c, 1);
 }
 
 static PyObject *
@@ -235,16 +235,16 @@
 	if (src == NULL)
 		*target = dflt;
 	else {
-		if (src == Py_None || PyString_Size(src) == 0)
+		if (src == Py_None || PyBytes_Size(src) == 0)
 			*target = '\0';
-		else if (!PyString_Check(src) || PyString_Size(src) != 1) {
+		else if (!PyBytes_Check(src) || PyBytes_Size(src) != 1) {
 			PyErr_Format(PyExc_TypeError, 
 				     "\"%s\" must be an 1-character string", 
 				     name);
 			return -1;
 		}
 		else {
-			char *s = PyString_AsString(src);
+			char *s = PyBytes_AsString(src);
 			if (s == NULL)
 				return -1;
 			*target = s[0];
@@ -257,7 +257,7 @@
 _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
 {
 	if (src == NULL)
-		*target = PyString_FromString(dflt);
+		*target = PyBytes_FromString(dflt);
 	else {
 		if (src == Py_None)
 			*target = NULL;
@@ -528,7 +528,7 @@
 {
 	PyObject *field;
 
-	field = PyString_FromStringAndSize(self->field, self->field_len);
+	field = PyBytes_FromStringAndSize(self->field, self->field_len);
 	if (field == NULL)
 		return -1;
 	self->field_len = 0;
@@ -787,8 +787,8 @@
                 }
 		++self->line_num;
 
-                line = PyString_AsString(lineobj);
-		linelen = PyString_Size(lineobj);
+                line = PyBytes_AsString(lineobj);
+		linelen = PyBytes_Size(lineobj);
 
                 if (line == NULL || linelen < 0) {
                         Py_DECREF(lineobj);
@@ -976,7 +976,7 @@
 		rec_len++;\
 	} while(0)
 
-	lineterm = PyString_AsString(dialect->lineterminator);
+	lineterm = PyBytes_AsString(dialect->lineterminator);
 	if (lineterm == NULL)
 		return -1;
 
@@ -1101,7 +1101,7 @@
 	int terminator_len;
 	char *terminator;
 
-	terminator_len = PyString_Size(self->dialect->lineterminator);
+	terminator_len = PyBytes_Size(self->dialect->lineterminator);
 	if (terminator_len == -1)
 		return 0;
 
@@ -1109,7 +1109,7 @@
 	if (!join_check_rec_size(self, self->rec_len + terminator_len))
 		return 0;
 
-	terminator = PyString_AsString(self->dialect->lineterminator); 
+	terminator = PyBytes_AsString(self->dialect->lineterminator); 
 	if (terminator == NULL)
 		return 0;
 	memmove(self->rec + self->rec_len, terminator, terminator_len);
@@ -1161,9 +1161,9 @@
 			break;
 		}
 
-		if (PyString_Check(field)) {
+		if (PyBytes_Check(field)) {
 			append_ok = join_append(self,
-						PyString_AS_STRING(field),
+						PyBytes_AS_STRING(field),
                                                 &quoted, len == 1);
 			Py_DECREF(field);
 		}
@@ -1179,7 +1179,7 @@
 			if (str == NULL)
 				return NULL;
 
-			append_ok = join_append(self, PyString_AS_STRING(str), 
+			append_ok = join_append(self, PyBytes_AS_STRING(str), 
                                                 &quoted, len == 1);
 			Py_DECREF(str);
 		}

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/_ctypes.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/_ctypes.c	Wed Jun  4 11:24:23 2008
@@ -477,7 +477,7 @@
 static PyObject *
 CDataType_from_buffer_copy(PyObject *type, PyObject *args)
 {
-	void *buffer;
+	const void *buffer;
 	Py_ssize_t buffer_len;
 	Py_ssize_t offset = 0;
 	PyObject *obj, *result;
@@ -684,8 +684,8 @@
 	if (-1 == PyType_Type.tp_setattro(self, key, value))
 		return -1;
 	
-	if (value && PyString_Check(key) &&
-	    0 == strcmp(PyString_AS_STRING(key), "_fields_"))
+	if (value && PyBytes_Check(key) &&
+	    0 == strcmp(PyBytes_AS_STRING(key), "_fields_"))
 		return StructUnionType_update_stgdict(self, value, 1);
 	return 0;
 }
@@ -698,8 +698,8 @@
 	if (-1 == PyObject_GenericSetAttr(self, key, value))
 		return -1;
 	
-	if (PyString_Check(key) &&
-	    0 == strcmp(PyString_AS_STRING(key), "_fields_"))
+	if (PyBytes_Check(key) &&
+	    0 == strcmp(PyBytes_AS_STRING(key), "_fields_"))
 		return StructUnionType_update_stgdict(self, value, 0);
 	return 0;
 }
@@ -1025,7 +1025,7 @@
 		size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
 		if (size < 0)
 			return -1;
-	} else if (-1 == PyString_AsStringAndSize(value, &ptr, &size)) {
+	} else if (-1 == PyBytes_AsStringAndSize(value, &ptr, &size)) {
 		return -1;
 	}
 	if (size > self->b_size) {
@@ -1042,7 +1042,7 @@
 static PyObject *
 CharArray_get_raw(CDataObject *self)
 {
-	return PyString_FromStringAndSize(self->b_ptr, self->b_size);
+	return PyBytes_FromStringAndSize(self->b_ptr, self->b_size);
 }
 
 static PyObject *
@@ -1053,7 +1053,7 @@
 	for (i = 0; i < self->b_size; ++i)
 		if (*ptr++ == '\0')
 			break;
-	return PyString_FromStringAndSize(self->b_ptr, i);
+	return PyBytes_FromStringAndSize(self->b_ptr, i);
 }
 
 static int
@@ -1074,14 +1074,14 @@
 						  conversion_mode_errors);
 		if (!value)
 			return -1;
-	} else if (!PyString_Check(value)) {
+	} else if (!PyBytes_Check(value)) {
 		PyErr_Format(PyExc_TypeError,
 			     "string expected instead of %s instance",
 			     Py_TYPE(value)->tp_name);
 		return -1;
 	} else
 		Py_INCREF(value);
-	size = PyString_GET_SIZE(value);
+	size = PyBytes_GET_SIZE(value);
 	if (size > self->b_size) {
 		PyErr_SetString(PyExc_ValueError,
 				"string too long");
@@ -1089,7 +1089,7 @@
 		return -1;
 	}
 
-	ptr = PyString_AS_STRING(value);
+	ptr = PyBytes_AS_STRING(value);
 	memcpy(self->b_ptr, ptr, size);
 	if (size < self->b_size)
 		self->b_ptr[size] = '\0';
@@ -1128,7 +1128,7 @@
 				"can't delete attribute");
 		return -1;
 	}
-	if (PyString_Check(value)) {
+	if (PyBytes_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
 						    conversion_mode_encoding,
 						    conversion_mode_errors);
@@ -1402,7 +1402,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	if (PyUnicode_Check(value) || PyString_Check(value)) {
+	if (PyUnicode_Check(value) || PyBytes_Check(value)) {
 		PyCArgObject *parg;
 		struct fielddesc *fd = getentry("Z");
 
@@ -1466,7 +1466,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	if (PyString_Check(value) || PyUnicode_Check(value)) {
+	if (PyBytes_Check(value) || PyUnicode_Check(value)) {
 		PyCArgObject *parg;
 		struct fielddesc *fd = getentry("z");
 
@@ -1552,7 +1552,7 @@
 		return (PyObject *)parg;
 	}
 /* string */
-	if (PyString_Check(value)) {
+	if (PyBytes_Check(value)) {
 		PyCArgObject *parg;
 		struct fielddesc *fd = getentry("z");
 
@@ -1623,10 +1623,10 @@
 	}
 /* c_char_p, c_wchar_p */
 	stgd = PyObject_stgdict(value);
-	if (stgd && CDataObject_Check(value) && stgd->proto && PyString_Check(stgd->proto)) {
+	if (stgd && CDataObject_Check(value) && stgd->proto && PyBytes_Check(stgd->proto)) {
 		PyCArgObject *parg;
 
-		switch (PyString_AS_STRING(stgd->proto)[0]) {
+		switch (PyBytes_AS_STRING(stgd->proto)[0]) {
 		case 'z': /* c_char_p */
 		case 'Z': /* c_wchar_p */
 			parg = new_CArgObject();
@@ -1683,13 +1683,13 @@
 
 	if (suffix == NULL)
 #ifdef WORDS_BIGENDIAN
-		suffix = PyString_InternFromString("_le");
+		suffix = PyBytes_InternFromString("_le");
 #else
-		suffix = PyString_InternFromString("_be");
+		suffix = PyBytes_InternFromString("_be");
 #endif
 
 	Py_INCREF(name);
-	PyString_Concat(&name, suffix);
+	PyBytes_Concat(&name, suffix);
 	if (name == NULL)
 		return NULL;
 
@@ -1744,7 +1744,7 @@
 	
 	dict = PyObject_stgdict((PyObject *)self);
 	assert(dict); /* Cannot be NULL for CDataObject instances */
-	fmt = PyString_AsString(dict->proto);
+	fmt = PyBytes_AsString(dict->proto);
 	assert(fmt);
 
 	fd = getentry(fmt);
@@ -1779,9 +1779,9 @@
 
 	proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
 	if (!proto
-	    || !PyString_Check(proto)
-	    || 1 != strlen(PyString_AS_STRING(proto))
-	    || !strchr(SIMPLE_TYPE_CHARS, PyString_AS_STRING(proto)[0])) {
+	    || !PyBytes_Check(proto)
+	    || 1 != strlen(PyBytes_AS_STRING(proto))
+	    || !strchr(SIMPLE_TYPE_CHARS, PyBytes_AS_STRING(proto)[0])) {
 		PyErr_Format(PyExc_AttributeError,
 			     "class must define a '_type_' attribute which must be\n"
 			     "a single character string containing one of '%s'.",
@@ -1790,12 +1790,12 @@
 		Py_DECREF(result);
 		return NULL;
 	}
-	fmt = getentry(PyString_AS_STRING(proto));
+	fmt = getentry(PyBytes_AS_STRING(proto));
 	if (fmt == NULL) {
 		Py_DECREF(result);
 		PyErr_Format(PyExc_ValueError,
 			     "_type_ '%s' not supported",
-			     PyString_AS_STRING(proto));
+			     PyBytes_AS_STRING(proto));
 		return NULL;
 	}
 
@@ -1835,7 +1835,7 @@
 	   Overrides the SimpleType_from_param generic method.
 	 */
 	if (result->tp_base == &Simple_Type) {
-		switch (PyString_AS_STRING(proto)[0]) {
+		switch (PyBytes_AS_STRING(proto)[0]) {
 		case 'z': /* c_char_p */
 			ml = &c_char_p_method;
 			stgdict->flags |= TYPEFLAG_ISPOINTER;
@@ -1940,7 +1940,7 @@
 	assert(dict);
 
 	/* I think we can rely on this being a one-character string */
-	fmt = PyString_AsString(dict->proto);
+	fmt = PyBytes_AsString(dict->proto);
 	assert(fmt);
 	
 	fd = getentry(fmt);
@@ -2290,7 +2290,7 @@
 #endif
 		target = target->b_base;
 	}
-	return PyString_FromStringAndSize(string, cp-string);
+	return PyBytes_FromStringAndSize(string, cp-string);
 }
 
 /*
@@ -2435,7 +2435,7 @@
 			     _unpickle,
 			     Py_TYPE(_self),
 			     PyObject_GetAttrString(_self, "__dict__"),
-			     PyString_FromStringAndSize(self->b_ptr, self->b_size));
+			     PyBytes_FromStringAndSize(self->b_ptr, self->b_size));
 }
 
 static PyObject *
@@ -2984,9 +2984,9 @@
 	dict = PyType_stgdict(arg);
 	if (dict
 	    /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
-	    && PyString_Check(dict->proto)
+	    && PyBytes_Check(dict->proto)
 /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
-	    && (strchr("PzZ", PyString_AS_STRING(dict->proto)[0]))) {
+	    && (strchr("PzZ", PyBytes_AS_STRING(dict->proto)[0]))) {
 		return 1;
 	}
 
@@ -3071,8 +3071,8 @@
 		return 1;
 	}
 #endif
-	if (PyString_Check(obj) || PyUnicode_Check(obj)) {
-		*pname = PyString_AsString(obj);
+	if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
+		*pname = PyBytes_AsString(obj);
 		return *pname ? 1 : 0;
 	}
 	PyErr_SetString(PyExc_TypeError,
@@ -3422,7 +3422,7 @@
 		/* We HAVE already checked that the tuple can be parsed with "i|zO", so... */
 		Py_ssize_t tsize = PyTuple_GET_SIZE(item);
 		flag = PyInt_AS_LONG(PyTuple_GET_ITEM(item, 0));
-		name = tsize > 1 ? PyString_AS_STRING(PyTuple_GET_ITEM(item, 1)) : NULL;
+		name = tsize > 1 ? PyBytes_AS_STRING(PyTuple_GET_ITEM(item, 1)) : NULL;
 		defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
 
 		switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
@@ -3476,7 +3476,7 @@
 					     "NULL stgdict unexpected");
 				goto error;
 			}
-			if (PyString_Check(dict->proto)) {
+			if (PyBytes_Check(dict->proto)) {
 				PyErr_Format(
 					PyExc_TypeError,
 					"%s 'out' parameter must be passed as default value",
@@ -3774,16 +3774,36 @@
 {
 #ifdef MS_WIN32
 	if (self->index)
-		return PyString_FromFormat("<COM method offset %d: %s at %p>",
+		return PyBytes_FromFormat("<COM method offset %d: %s at %p>",
 					   self->index - 0x1000,
 					   Py_TYPE(self)->tp_name,
 					   self);
 #endif
-	return PyString_FromFormat("<%s object at %p>",
+	return PyBytes_FromFormat("<%s object at %p>",
 				   Py_TYPE(self)->tp_name,
 				   self);
 }
 
+static int
+Pointer_nonzero(CDataObject *self)
+{
+	return *(void **)self->b_ptr != NULL;
+}
+
+static PyNumberMethods Pointer_as_number = {
+	0, /* nb_add */
+	0, /* nb_subtract */
+	0, /* nb_multiply */
+	0, /* nb_divide */
+	0, /* nb_remainder */
+	0, /* nb_divmod */
+	0, /* nb_power */
+	0, /* nb_negative */
+	0, /* nb_positive */
+	0, /* nb_absolute */
+	(inquiry)Pointer_nonzero, /* nb_nonzero */
+};
+
 PyTypeObject CFuncPtr_Type = {
 	PyVarObject_HEAD_INIT(NULL, 0)
 	"_ctypes.CFuncPtr",
@@ -3795,7 +3815,7 @@
 	0,					/* tp_setattr */
 	0,					/* tp_compare */
 	(reprfunc)CFuncPtr_repr,		/* tp_repr */
-	0,					/* tp_as_number */
+	&Pointer_as_number,			/* tp_as_number */
 	0,					/* tp_as_sequence */
 	0,					/* tp_as_mapping */
 	0,					/* tp_hash */
@@ -3888,7 +3908,7 @@
 			}
 
 			if (kwds && PyDict_GetItem(kwds, name)) {
-				char *field = PyString_AsString(name);
+				char *field = PyBytes_AsString(name);
 				if (field == NULL) {
 					PyErr_Clear();
 					field = "???";
@@ -4090,7 +4110,7 @@
 			     type, so this cannot be NULL */
 	if (itemdict->getfunc == getentry("c")->getfunc) {
 		char *ptr = (char *)self->b_ptr;
-		return PyString_FromStringAndSize(ptr + ilow, len);
+		return PyBytes_FromStringAndSize(ptr + ilow, len);
 #ifdef CTYPES_UNICODE
 	} else if (itemdict->getfunc == getentry("u")->getfunc) {
 		wchar_t *ptr = (wchar_t *)self->b_ptr;
@@ -4147,9 +4167,9 @@
 			char *dest;
 
 			if (slicelen <= 0)
-				return PyString_FromString("");
+				return PyBytes_FromString("");
 			if (step == 1) {
-				return PyString_FromStringAndSize(ptr + start,
+				return PyBytes_FromStringAndSize(ptr + start,
 								  slicelen);
 			}
 			dest = (char *)PyMem_Malloc(slicelen);
@@ -4162,7 +4182,7 @@
 				dest[i] = ptr[cur];
 			}
 
-			np = PyString_FromStringAndSize(dest, slicelen);
+			np = PyBytes_FromStringAndSize(dest, slicelen);
 			PyMem_Free(dest);
 			return np;
 		}
@@ -4572,12 +4592,12 @@
 	static PyObject *format;
 
 	if (Py_TYPE(self)->tp_base != &Simple_Type) {
-		return PyString_FromFormat("<%s object at %p>",
+		return PyBytes_FromFormat("<%s object at %p>",
 					   Py_TYPE(self)->tp_name, self);
 	}
 
 	if (format == NULL) {
-		format = PyString_InternFromString("%s(%r)");
+		format = PyBytes_InternFromString("%s(%r)");
 		if (format == NULL)
 			return NULL;
 	}
@@ -4586,7 +4606,7 @@
 	if (val == NULL)
 		return NULL;
 
-	name = PyString_FromString(Py_TYPE(self)->tp_name);
+	name = PyBytes_FromString(Py_TYPE(self)->tp_name);
 	if (name == NULL) {
 		Py_DECREF(val);
 		return NULL;
@@ -4598,7 +4618,7 @@
 	if (args == NULL)
 		return NULL;
 
-	result = PyString_Format(format, args);
+	result = PyBytes_Format(format, args);
 	Py_DECREF(args);
 	return result;
 }
@@ -4832,7 +4852,7 @@
 	assert(itemdict);
 	if (itemdict->getfunc == getentry("c")->getfunc) {
 		char *ptr = *(char **)self->b_ptr;
-		return PyString_FromStringAndSize(ptr + ilow, len);
+		return PyBytes_FromStringAndSize(ptr + ilow, len);
 #ifdef CTYPES_UNICODE
 	} else if (itemdict->getfunc == getentry("u")->getfunc) {
 		wchar_t *ptr = *(wchar_t **)self->b_ptr;
@@ -4929,9 +4949,9 @@
 			char *dest;
 			
 			if (len <= 0)
-                        	return PyString_FromString("");
+                        	return PyBytes_FromString("");
 			if (step == 1) {
-				return PyString_FromStringAndSize(ptr + start,
+				return PyBytes_FromStringAndSize(ptr + start,
 								  len);
 			}
 			dest = (char *)PyMem_Malloc(len);
@@ -4940,7 +4960,7 @@
 			for (cur = start, i = 0; i < len; cur += step, i++) {
 				dest[i] = ptr[cur];
 			}
-			np = PyString_FromStringAndSize(dest, len);
+			np = PyBytes_FromStringAndSize(dest, len);
 			PyMem_Free(dest);
 			return np;
 		}
@@ -5003,26 +5023,6 @@
 	Pointer_subscript,
 };
 
-static int
-Pointer_nonzero(CDataObject *self)
-{
-	return *(void **)self->b_ptr != NULL;
-}
-
-static PyNumberMethods Pointer_as_number = {
-	0, /* nb_add */
-	0, /* nb_subtract */
-	0, /* nb_multiply */
-	0, /* nb_divide */
-	0, /* nb_remainder */
-	0, /* nb_divmod */
-	0, /* nb_power */
-	0, /* nb_negative */
-	0, /* nb_positive */
-	0, /* nb_absolute */
-	(inquiry)Pointer_nonzero, /* nb_nonzero */
-};
-
 PyTypeObject Pointer_Type = {
 	PyVarObject_HEAD_INIT(NULL, 0)
 	"_ctypes._Pointer",
@@ -5140,7 +5140,7 @@
 		++methods;
 	}
 
-	s = PyString_FromString(comerror_doc);
+	s = PyBytes_FromString(comerror_doc);
 	if (s == NULL)
 		goto error;
 	status = PyDict_SetItemString(dict, "__doc__", s);
@@ -5166,8 +5166,8 @@
 string_at(const char *ptr, int size)
 {
 	if (size == -1)
-		return PyString_FromString(ptr);
-	return PyString_FromStringAndSize(ptr, size);
+		return PyBytes_FromString(ptr);
+	return PyBytes_FromStringAndSize(ptr, size);
 }
 
 static int
@@ -5181,8 +5181,8 @@
 		return 1;
 	dict = PyType_stgdict(arg);
 	if (dict) {
-		if (PyString_Check(dict->proto)
-		    && (strchr("sPzUZXO", PyString_AS_STRING(dict->proto)[0]))) {
+		if (PyBytes_Check(dict->proto)
+		    && (strchr("sPzUZXO", PyBytes_AS_STRING(dict->proto)[0]))) {
 			/* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
 			return 1;
 		}

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/callbacks.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/callbacks.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/callbacks.c	Wed Jun  4 11:24:23 2008
@@ -107,15 +107,15 @@
 	PyCodeObject *py_code = 0;
 	PyFrameObject *py_frame = 0;
     
-	py_srcfile = PyString_FromString(filename);
+	py_srcfile = PyBytes_FromString(filename);
 	if (!py_srcfile) goto bad;
-	py_funcname = PyString_FromString(funcname);
+	py_funcname = PyBytes_FromString(funcname);
 	if (!py_funcname) goto bad;
 	py_globals = PyDict_New();
 	if (!py_globals) goto bad;
 	empty_tuple = PyTuple_New(0);
 	if (!empty_tuple) goto bad;
-	empty_string = PyString_FromString("");
+	empty_string = PyBytes_FromString("");
 	if (!empty_string) goto bad;
 	py_code = PyCode_New(
 		0,            /*int argcount,*/
@@ -460,7 +460,7 @@
 	static PyObject *context;
 
 	if (context == NULL)
-		context = PyString_InternFromString("_ctypes.DllGetClassObject");
+		context = PyBytes_InternFromString("_ctypes.DllGetClassObject");
 
 	mod = PyImport_ImportModuleNoBlock("ctypes");
 	if (!mod) {
@@ -539,7 +539,7 @@
 	static PyObject *context;
 
 	if (context == NULL)
-		context = PyString_InternFromString("_ctypes.DllCanUnloadNow");
+		context = PyBytes_InternFromString("_ctypes.DllCanUnloadNow");
 
 	mod = PyImport_ImportModuleNoBlock("ctypes");
 	if (!mod) {

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/callproc.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/callproc.c	Wed Jun  4 11:24:23 2008
@@ -370,7 +370,7 @@
 			self->tag, self);
 		break;
 	}
-	return PyString_FromString(buffer);
+	return PyBytes_FromString(buffer);
 }
 
 static PyMemberDef PyCArgType_members[] = {
@@ -518,9 +518,9 @@
 		return 0;
 	}
 
-	if (PyString_Check(obj)) {
+	if (PyBytes_Check(obj)) {
 		pa->ffi_type = &ffi_type_pointer;
-		pa->value.p = PyString_AS_STRING(obj);
+		pa->value.p = PyBytes_AS_STRING(obj);
 		Py_INCREF(obj);
 		pa->keep = obj;
 		return 0;
@@ -781,7 +781,7 @@
 	PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
 
 	va_start(vargs, fmt);
-	s = PyString_FromFormatV(fmt, vargs);
+	s = PyBytes_FromFormatV(fmt, vargs);
 	va_end(vargs);
 	if (!s)
 		return;
@@ -790,18 +790,18 @@
 	PyErr_NormalizeException(&tp, &v, &tb);
 	cls_str = PyObject_Str(tp);
 	if (cls_str) {
-		PyString_ConcatAndDel(&s, cls_str);
-		PyString_ConcatAndDel(&s, PyString_FromString(": "));
+		PyBytes_ConcatAndDel(&s, cls_str);
+		PyBytes_ConcatAndDel(&s, PyBytes_FromString(": "));
 		if (s == NULL)
 			goto error;
 	} else
 		PyErr_Clear();
 	msg_str = PyObject_Str(v);
 	if (msg_str)
-		PyString_ConcatAndDel(&s, msg_str);
+		PyBytes_ConcatAndDel(&s, msg_str);
 	else {
 		PyErr_Clear();
-		PyString_ConcatAndDel(&s, PyString_FromString("???"));
+		PyBytes_ConcatAndDel(&s, PyBytes_FromString("???"));
 		if (s == NULL)
 			goto error;
 	}
@@ -1105,7 +1105,7 @@
 	if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
 		return NULL;
 #ifdef _UNICODE
-	name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
+	name = alloca((PyBytes_Size(nameobj) + 1) * sizeof(WCHAR));
 	if (!name) {
 		PyErr_NoMemory();
 		return NULL;
@@ -1113,14 +1113,14 @@
 
 	{
 		int r;
-		char *aname = PyString_AsString(nameobj);
+		char *aname = PyBytes_AsString(nameobj);
 		if(!aname)
 			return NULL;
-		r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyString_Size(nameobj) + 1);
+		r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyBytes_Size(nameobj) + 1);
 		name[r] = 0;
 	}
 #else
-	name = PyString_AsString(nameobj);
+	name = PyBytes_AsString(nameobj);
 	if(!name)
 		return NULL;
 #endif
@@ -1613,9 +1613,9 @@
 		Py_INCREF(result);
 		return result;
 	}
-	if (PyString_CheckExact(cls)) {
-		buf = alloca(strlen(PyString_AS_STRING(cls)) + 3 + 1);
-		sprintf(buf, "LP_%s", PyString_AS_STRING(cls));
+	if (PyBytes_CheckExact(cls)) {
+		buf = alloca(strlen(PyBytes_AS_STRING(cls)) + 3 + 1);
+		sprintf(buf, "LP_%s", PyBytes_AS_STRING(cls));
 		result = PyObject_CallFunction((PyObject *)Py_TYPE(&Pointer_Type),
 					       "s(O){}",
 					       buf,

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/cfield.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/cfield.c	Wed Jun  4 11:24:23 2008
@@ -272,7 +272,7 @@
 	name = ((PyTypeObject *)self->proto)->tp_name;
 
 	if (bits)
-		result = PyString_FromFormat(
+		result = PyBytes_FromFormat(
 #if (PY_VERSION_HEX < 0x02050000)
 			"<Field type=%s, ofs=%d:%d, bits=%d>",
 #else
@@ -280,7 +280,7 @@
 #endif
 			name, self->offset, size, bits);
 	else
-		result = PyString_FromFormat(
+		result = PyBytes_FromFormat(
 #if (PY_VERSION_HEX < 0x02050000)
 			"<Field type=%s, ofs=%d, size=%d>",
 #else
@@ -1164,12 +1164,12 @@
 static PyObject *
 c_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
-	if (!PyString_Check(value) || (1 != PyString_Size(value))) {
+	if (!PyBytes_Check(value) || (1 != PyBytes_Size(value))) {
 		PyErr_Format(PyExc_TypeError,
 			     "one character string expected");
 		return NULL;
 	}
-	*(char *)ptr = PyString_AS_STRING(value)[0];
+	*(char *)ptr = PyBytes_AS_STRING(value)[0];
 	_RET(value);
 }
 
@@ -1177,7 +1177,7 @@
 static PyObject *
 c_get(void *ptr, Py_ssize_t size)
 {
-	return PyString_FromStringAndSize((char *)ptr, 1);
+	return PyBytes_FromStringAndSize((char *)ptr, 1);
 }
 
 #ifdef CTYPES_UNICODE
@@ -1187,7 +1187,7 @@
 {
 	Py_ssize_t len;
 
-	if (PyString_Check(value)) {
+	if (PyBytes_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
 						    conversion_mode_encoding,
 						    conversion_mode_errors);
@@ -1262,7 +1262,7 @@
 	/* It's easier to calculate in characters than in bytes */
 	length /= sizeof(wchar_t);
 
-	if (PyString_Check(value)) {
+	if (PyBytes_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
 						    conversion_mode_encoding,
 						    conversion_mode_errors);
@@ -1301,21 +1301,21 @@
 	PyObject *result;
 	size_t slen;
 
-	result = PyString_FromString((char *)ptr);
+	result = PyBytes_FromString((char *)ptr);
 	if (!result)
 		return NULL;
 	/* chop off at the first NUL character, if any.
 	 * On error, result will be deallocated and set to NULL.
 	 */
-	slen = strlen(PyString_AS_STRING(result));
+	slen = strlen(PyBytes_AS_STRING(result));
 	size = min(size, (Py_ssize_t)slen);
 	if (result->ob_refcnt == 1) {
 		/* shorten the result */
-		_PyString_Resize(&result, size);
+		_PyBytes_Resize(&result, size);
 		return result;
 	} else
 		/* cannot shorten the result */
-		return PyString_FromStringAndSize(ptr, size);
+		return PyBytes_FromStringAndSize(ptr, size);
 }
 
 static PyObject *
@@ -1324,7 +1324,7 @@
 	char *data;
 	Py_ssize_t size;
 
-	data = PyString_AsString(value);
+	data = PyBytes_AsString(value);
 	if (!data)
 		return NULL;
 	size = strlen(data);
@@ -1356,8 +1356,8 @@
 		Py_INCREF(value);
 		return value;
 	}
-	if (PyString_Check(value)) {
-		*(char **)ptr = PyString_AS_STRING(value);
+	if (PyBytes_Check(value)) {
+		*(char **)ptr = PyBytes_AS_STRING(value);
 		Py_INCREF(value);
 		return value;
 	} else if (PyUnicode_Check(value)) {
@@ -1366,7 +1366,7 @@
 							  conversion_mode_errors);
 		if (str == NULL)
 			return NULL;
-		*(char **)ptr = PyString_AS_STRING(str);
+		*(char **)ptr = PyBytes_AS_STRING(str);
 		return str;
 	} else if (PyInt_Check(value) || PyLong_Check(value)) {
 #if SIZEOF_VOID_P == SIZEOF_LONG_LONG
@@ -1395,7 +1395,7 @@
 			return NULL;
 		}
 #endif
-		return PyString_FromString(*(char **)ptr);
+		return PyBytes_FromString(*(char **)ptr);
 	} else {
 		Py_INCREF(Py_None);
 		return Py_None;
@@ -1411,7 +1411,7 @@
 		Py_INCREF(value);
 		return value;
 	}
-	if (PyString_Check(value)) {
+	if (PyBytes_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
 						    conversion_mode_encoding,
 						    conversion_mode_errors);
@@ -1502,7 +1502,7 @@
 	/* convert value into a PyUnicodeObject or NULL */
 	if (Py_None == value) {
 		value = NULL;
-	} else if (PyString_Check(value)) {
+	} else if (PyBytes_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
 						    conversion_mode_encoding,
 						    conversion_mode_errors);

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure	Wed Jun  4 11:24:23 2008
@@ -20406,6 +20406,9 @@
   i?86-*-solaris2.1[0-9]*)
 	TARGET=X86_64; TARGETDIR=x86
 	;;
+  i*86-*-nto-qnx*)
+        TARGET=X86; TARGETDIR=x86
+        ;;
   i?86-*-*)
 	TARGET=X86; TARGETDIR=x86
 	;;

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure.ac
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure.ac	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/libffi/configure.ac	Wed Jun  4 11:24:23 2008
@@ -86,6 +86,9 @@
   i?86-*-solaris2.1[[0-9]]*)
 	TARGET=X86_64; TARGETDIR=x86
 	;;
+  i*86-*-nto-qnx*) 
+        TARGET=X86; TARGETDIR=x86
+        ;;
   i?86-*-*)
 	TARGET=X86; TARGETDIR=x86
 	;;

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/libffi/fficonfig.py.in
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/libffi/fficonfig.py.in	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/libffi/fficonfig.py.in	Wed Jun  4 11:24:23 2008
@@ -25,6 +25,7 @@
     'SH64': ['src/sh64/sysv.S', 'src/sh64/ffi.c'],
     'PA': ['src/pa/linux.S', 'src/pa/ffi.c'],
     'PA_LINUX': ['src/pa/linux.S', 'src/pa/ffi.c'],
+    'PA_HPUX': ['src/pa/hpux32.S', 'src/pa/ffi.c'],
 }
 
 ffi_srcdir = '@srcdir@'

Modified: python/branches/okkoto-sizeof/Modules/_ctypes/malloc_closure.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ctypes/malloc_closure.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_ctypes/malloc_closure.c	Wed Jun  4 11:24:23 2008
@@ -48,7 +48,11 @@
 	}
 #else
 	if (!_pagesize) {
+#ifdef _SC_PAGESIZE
+		_pagesize = sysconf(_SC_PAGESIZE);
+#else
 		_pagesize = getpagesize();
+#endif
 	}
 #endif
 

Modified: python/branches/okkoto-sizeof/Modules/_curses_panel.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_curses_panel.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_curses_panel.c	Wed Jun  4 11:24:23 2008
@@ -472,7 +472,7 @@
     PyDict_SetItemString(d, "error", PyCursesError);
 
     /* Make the version available */
-    v = PyString_FromString(PyCursesVersion);
+    v = PyBytes_FromString(PyCursesVersion);
     PyDict_SetItemString(d, "version", v);
     PyDict_SetItemString(d, "__version__", v);
     Py_DECREF(v);

Modified: python/branches/okkoto-sizeof/Modules/_cursesmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_cursesmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_cursesmodule.c	Wed Jun  4 11:24:23 2008
@@ -198,9 +198,9 @@
 {
   if (PyInt_Check(obj)) {
     *ch = (chtype) PyInt_AsLong(obj);
-  } else if(PyString_Check(obj) 
-	    && (PyString_Size(obj) == 1)) {
-    *ch = (chtype) *PyString_AsString(obj);
+  } else if(PyBytes_Check(obj) 
+	    && (PyBytes_Size(obj) == 1)) {
+    *ch = (chtype) *PyBytes_AsString(obj);
   } else {
     return 0;
   }
@@ -886,9 +886,9 @@
     return Py_BuildValue("c", rtn);
   else
 #if defined(__NetBSD__)
-    return PyString_FromString(unctrl(rtn));
+    return PyBytes_FromString(unctrl(rtn));
 #else
-    return PyString_FromString((char *)keyname(rtn));
+    return PyBytes_FromString((char *)keyname(rtn));
 #endif
 }
 
@@ -943,7 +943,7 @@
   }
   if (rtn2 == ERR)
     rtn[0] = 0;
-  return PyString_FromString(rtn);
+  return PyBytes_FromString(rtn);
 }
 
 static PyObject *
@@ -1095,7 +1095,7 @@
   }
   if (rtn2 == ERR)
     rtn[0] = 0;
-  return PyString_FromString(rtn);
+  return PyBytes_FromString(rtn);
 }
 
 static PyObject *
@@ -1757,7 +1757,7 @@
 
   ch = erasechar();
 
-  return PyString_FromStringAndSize(&ch, 1);
+  return PyBytes_FromStringAndSize(&ch, 1);
 }
 
 static PyObject *
@@ -2114,7 +2114,7 @@
   }
   knp = keyname(ch);
 
-  return PyString_FromString((knp == NULL) ? "" : (char *)knp);
+  return PyBytes_FromString((knp == NULL) ? "" : (char *)knp);
 }
 #endif
 
@@ -2125,7 +2125,7 @@
 
   ch = killchar();  
 
-  return PyString_FromStringAndSize(&ch, 1);  
+  return PyBytes_FromStringAndSize(&ch, 1);  
 }  
 
 static PyObject *
@@ -2496,7 +2496,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString( capname );
+	return PyBytes_FromString( capname );
 }
 
 static PyObject *
@@ -2520,7 +2520,7 @@
   		return NULL;
 	}
 
-	return PyString_FromString(result);
+	return PyBytes_FromString(result);
 }
 
 static PyObject *
@@ -2547,14 +2547,14 @@
 
   if (PyInt_Check(temp))
     ch = (chtype) PyInt_AsLong(temp);
-  else if (PyString_Check(temp))
-    ch = (chtype) *PyString_AsString(temp);
+  else if (PyBytes_Check(temp))
+    ch = (chtype) *PyBytes_AsString(temp);
   else {
     PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int");
     return NULL;
   }
 
-  return PyString_FromString(unctrl(ch));
+  return PyBytes_FromString(unctrl(ch));
 }
 
 static PyObject *
@@ -2569,8 +2569,8 @@
 
   if (PyInt_Check(temp))
     ch = (int) PyInt_AsLong(temp);
-  else if (PyString_Check(temp))
-    ch = (int) *PyString_AsString(temp);
+  else if (PyBytes_Check(temp))
+    ch = (int) *PyBytes_AsString(temp);
   else {
     PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int");
     return NULL;
@@ -2753,7 +2753,7 @@
 	PyDict_SetItemString(d, "error", PyCursesError);
 
 	/* Make the version available */
-	v = PyString_FromString(PyCursesVersion);
+	v = PyBytes_FromString(PyCursesVersion);
 	PyDict_SetItemString(d, "version", v);
 	PyDict_SetItemString(d, "__version__", v);
 	Py_DECREF(v);

Modified: python/branches/okkoto-sizeof/Modules/_elementtree.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_elementtree.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_elementtree.c	Wed Jun  4 11:24:23 2008
@@ -103,7 +103,7 @@
 #define PyDict_CheckExact PyDict_Check
 #if (PY_VERSION_HEX < 0x02020000)
 #define PyList_CheckExact PyList_Check
-#define PyString_CheckExact PyString_Check
+#define PyBytes_CheckExact PyBytes_Check
 #if (PY_VERSION_HEX >= 0x01060000)
 #define Py_USING_UNICODE /* always enabled for 2.0 and 2.1 */
 #endif
@@ -173,7 +173,7 @@
     switch (PyList_GET_SIZE(list)) {
     case 0:
         Py_DECREF(list);
-        return PyString_FromString("");
+        return PyBytes_FromString("");
     case 1:
         result = PyList_GET_ITEM(list, 0);
         Py_INCREF(result);
@@ -748,9 +748,9 @@
         return 0;
     }
 #endif
-    if (PyString_Check(tag)) {
-        char *p = PyString_AS_STRING(tag);
-        for (i = 0; i < PyString_GET_SIZE(tag); i++) {
+    if (PyBytes_Check(tag)) {
+        char *p = PyBytes_AS_STRING(tag);
+        for (i = 0; i < PyBytes_GET_SIZE(tag); i++) {
             if (p[i] == '{')
                 check = 0;
             else if (p[i] == '}')
@@ -818,7 +818,7 @@
         if (Element_CheckExact(item) && !PyObject_Compare(item->tag, tag)) {
             PyObject* text = element_get_text(item);
             if (text == Py_None)
-                return PyString_FromString("");
+                return PyBytes_FromString("");
             Py_XINCREF(text);
             return text;
         }
@@ -1154,12 +1154,12 @@
     PyObject* repr;
     char buffer[100];
     
-    repr = PyString_FromString("<Element ");
+    repr = PyBytes_FromString("<Element ");
 
-    PyString_ConcatAndDel(&repr, PyObject_Repr(self->tag));
+    PyBytes_ConcatAndDel(&repr, PyObject_Repr(self->tag));
 
     sprintf(buffer, " at %p>", self);
-    PyString_ConcatAndDel(&repr, PyString_FromString(buffer));
+    PyBytes_ConcatAndDel(&repr, PyBytes_FromString(buffer));
 
     return repr;
 }
@@ -1617,14 +1617,14 @@
         Py_INCREF(data); self->data = data;
     } else {
         /* more than one item; use a list to collect items */
-        if (PyString_CheckExact(self->data) && Py_REFCNT(self->data) == 1 &&
-            PyString_CheckExact(data) && PyString_GET_SIZE(data) == 1) {
+        if (PyBytes_CheckExact(self->data) && Py_REFCNT(self->data) == 1 &&
+            PyBytes_CheckExact(data) && PyBytes_GET_SIZE(data) == 1) {
             /* expat often generates single character data sections; handle
                the most common case by resizing the existing string... */
-            Py_ssize_t size = PyString_GET_SIZE(self->data);
-            if (_PyString_Resize(&self->data, size + 1) < 0)
+            Py_ssize_t size = PyBytes_GET_SIZE(self->data);
+            if (_PyBytes_Resize(&self->data, size + 1) < 0)
                 return NULL;
-            PyString_AS_STRING(self->data)[size] = PyString_AS_STRING(data)[0];
+            PyBytes_AS_STRING(self->data)[size] = PyBytes_AS_STRING(data)[0];
         } else if (PyList_CheckExact(self->data)) {
             if (PyList_Append(self->data, data) < 0)
                 return NULL;
@@ -1896,7 +1896,7 @@
         return PyUnicode_DecodeUTF8(string, size, "strict");
 #endif
 
-    return PyString_FromStringAndSize(string, size);
+    return PyBytes_FromStringAndSize(string, size);
 }
 
 LOCAL(PyObject*)
@@ -1910,7 +1910,7 @@
     PyObject* value;
 
     /* look the 'raw' name up in the names dictionary */
-    key = PyString_FromStringAndSize(string, size);
+    key = PyBytes_FromStringAndSize(string, size);
     if (!key)
         return NULL;
 
@@ -1932,8 +1932,8 @@
                 break;
         if (i != size) {
             /* convert to universal name */
-            tag = PyString_FromStringAndSize(NULL, size+1);
-            p = PyString_AS_STRING(tag);
+            tag = PyBytes_FromStringAndSize(NULL, size+1);
+            p = PyBytes_AS_STRING(tag);
             p[0] = '{';
             memcpy(p+1, string, size);
             size++;
@@ -1947,7 +1947,7 @@
 #if defined(Py_USING_UNICODE)
         /* inline makestring, to avoid duplicating the source string if
            it's not an utf-8 string */
-        p = PyString_AS_STRING(tag);
+        p = PyBytes_AS_STRING(tag);
         if (checkstring(p, size)) {
             value = PyUnicode_DecodeUTF8(p, size, "strict");
             Py_DECREF(tag);
@@ -2004,7 +2004,7 @@
     } else {
         PyErr_Format(
             PyExc_SyntaxError, "undefined entity &%s;: line %ld, column %ld",
-            PyString_AS_STRING(key),
+            PyBytes_AS_STRING(key),
             EXPAT(GetErrorLineNumber)(self->parser),
             EXPAT(GetErrorColumnNumber)(self->parser)
             );
@@ -2435,13 +2435,13 @@
             return NULL;
         }
 
-        if (!PyString_CheckExact(buffer) || PyString_GET_SIZE(buffer) == 0) {
+        if (!PyBytes_CheckExact(buffer) || PyBytes_GET_SIZE(buffer) == 0) {
             Py_DECREF(buffer);
             break;
         }
 
         res = expat_parse(
-            self, PyString_AS_STRING(buffer), PyString_GET_SIZE(buffer), 0
+            self, PyBytes_AS_STRING(buffer), PyBytes_GET_SIZE(buffer), 0
             );
 
         Py_DECREF(buffer);
@@ -2503,7 +2503,7 @@
 
     if (event_set == Py_None) {
         /* default is "end" only */
-        target->end_event_obj = PyString_FromString("end");
+        target->end_event_obj = PyBytes_FromString("end");
         Py_RETURN_NONE;
     }
 
@@ -2513,9 +2513,9 @@
     for (i = 0; i < PyTuple_GET_SIZE(event_set); i++) {
         PyObject* item = PyTuple_GET_ITEM(event_set, i);
         char* event;
-        if (!PyString_Check(item))
+        if (!PyBytes_Check(item))
             goto error;
-        event = PyString_AS_STRING(item);
+        event = PyBytes_AS_STRING(item);
         if (strcmp(event, "start") == 0) {
             Py_INCREF(item);
             target->start_event_obj = item;
@@ -2587,7 +2587,7 @@
         char buffer[100];
         sprintf(buffer, "Expat %d.%d.%d", XML_MAJOR_VERSION,
                 XML_MINOR_VERSION, XML_MICRO_VERSION);
-        return PyString_FromString(buffer);
+        return PyBytes_FromString(buffer);
     } else {
         PyErr_SetString(PyExc_AttributeError, name);
         return NULL;

Modified: python/branches/okkoto-sizeof/Modules/_fileio.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_fileio.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_fileio.c	Wed Jun  4 11:24:23 2008
@@ -392,14 +392,14 @@
 	Py_ssize_t total = 0;
 	int n;
 
-	result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
+	result = PyBytes_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE);
 	if (result == NULL)
 		return NULL;
 
 	while (1) {
 		Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE;
-		if (PyString_GET_SIZE(result) < newsize) {
-			if (_PyString_Resize(&result, newsize) < 0) {
+		if (PyBytes_GET_SIZE(result) < newsize) {
+			if (_PyBytes_Resize(&result, newsize) < 0) {
 				if (total == 0) {
 					Py_DECREF(result);
 					return NULL;
@@ -411,7 +411,7 @@
 		Py_BEGIN_ALLOW_THREADS
 		errno = 0;
 		n = read(self->fd,
-			 PyString_AS_STRING(result) + total,
+			 PyBytes_AS_STRING(result) + total,
 			 newsize - total);
 		Py_END_ALLOW_THREADS
 		if (n == 0)
@@ -430,8 +430,8 @@
 		total += n;
 	}
 
-	if (PyString_GET_SIZE(result) > total) {
-		if (_PyString_Resize(&result, total) < 0) {
+	if (PyBytes_GET_SIZE(result) > total) {
+		if (_PyBytes_Resize(&result, total) < 0) {
 			/* This should never happen, but just in case */
 			Py_DECREF(result);
 			return NULL;
@@ -460,10 +460,10 @@
 		return fileio_readall(self);
 	}
 
-	bytes = PyString_FromStringAndSize(NULL, size);
+	bytes = PyBytes_FromStringAndSize(NULL, size);
 	if (bytes == NULL)
 		return NULL;
-	ptr = PyString_AS_STRING(bytes);
+	ptr = PyBytes_AS_STRING(bytes);
 
 	Py_BEGIN_ALLOW_THREADS
 	errno = 0;
@@ -478,7 +478,7 @@
 	}
 
 	if (n != size) {
-		if (_PyString_Resize(&bytes, n) < 0) {
+		if (_PyBytes_Resize(&bytes, n) < 0) {
 			Py_DECREF(bytes);
 			return NULL;
 		}
@@ -690,9 +690,9 @@
 fileio_repr(PyFileIOObject *self)
 {
         if (self->fd < 0)
-		return PyString_FromFormat("_fileio._FileIO(-1)");
+		return PyBytes_FromFormat("_fileio._FileIO(-1)");
 
-	return PyString_FromFormat("_fileio._FileIO(%d, '%s')",
+	return PyBytes_FromFormat("_fileio._FileIO(%d, '%s')",
 				   self->fd, mode_string(self));
 }
 
@@ -816,7 +816,7 @@
 static PyObject *
 get_mode(PyFileIOObject *self, void *closure)
 {
-	return PyString_FromString(mode_string(self));
+	return PyBytes_FromString(mode_string(self));
 }
 
 static PyGetSetDef fileio_getsetlist[] = {

Modified: python/branches/okkoto-sizeof/Modules/_hashopenssl.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_hashopenssl.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_hashopenssl.c	Wed Jun  4 11:24:23 2008
@@ -103,7 +103,7 @@
     digest_size = EVP_MD_CTX_size(&temp_ctx);
     EVP_DigestFinal(&temp_ctx, digest, NULL);
 
-    retval = PyString_FromStringAndSize((const char *)digest, digest_size);
+    retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
     EVP_MD_CTX_cleanup(&temp_ctx);
     return retval;
 }
@@ -130,10 +130,10 @@
     /* Create a new string */
     /* NOTE: not thread safe! modifying an already created string object */
     /* (not a problem because we hold the GIL by default) */
-    retval = PyString_FromStringAndSize(NULL, digest_size * 2);
+    retval = PyBytes_FromStringAndSize(NULL, digest_size * 2);
     if (!retval)
 	    return NULL;
-    hex_digest = PyString_AsString(retval);
+    hex_digest = PyBytes_AsString(retval);
     if (!hex_digest) {
 	    Py_DECREF(retval);
 	    return NULL;
@@ -220,8 +220,8 @@
 {
     char buf[100];
     PyOS_snprintf(buf, sizeof(buf), "<%s HASH object @ %p>",
-            PyString_AsString(((EVPobject *)self)->name), self);
-    return PyString_FromString(buf);
+            PyBytes_AsString(((EVPobject *)self)->name), self);
+    return PyBytes_FromString(buf);
 }
 
 #if HASH_OBJ_CONSTRUCTOR
@@ -421,7 +421,7 @@
 
 /* used in the init function to setup a constructor */
 #define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
-    CONST_ ## NAME ## _name_obj = PyString_FromString(#NAME); \
+    CONST_ ## NAME ## _name_obj = PyBytes_FromString(#NAME); \
     if (EVP_get_digestbyname(#NAME)) { \
         CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
         EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \

Modified: python/branches/okkoto-sizeof/Modules/_heapqmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_heapqmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_heapqmodule.c	Wed Jun  4 11:24:23 2008
@@ -28,12 +28,12 @@
 	while (pos > startpos){
 		parentpos = (pos - 1) >> 1;
 		parent = PyList_GET_ITEM(heap, parentpos);
-		cmp = PyObject_RichCompareBool(parent, newitem, Py_LE);
+		cmp = PyObject_RichCompareBool(newitem, parent, Py_LT);
 		if (cmp == -1) {
 			Py_DECREF(newitem);
 			return -1;
 		}
-		if (cmp == 1)
+		if (cmp == 0)
 			break;
 		Py_INCREF(parent);
 		Py_DECREF(PyList_GET_ITEM(heap, pos));
@@ -69,14 +69,14 @@
 		rightpos = childpos + 1;
 		if (rightpos < endpos) {
 			cmp = PyObject_RichCompareBool(
-				PyList_GET_ITEM(heap, rightpos),
 				PyList_GET_ITEM(heap, childpos),
-				Py_LE);
+				PyList_GET_ITEM(heap, rightpos),
+				Py_LT);
 			if (cmp == -1) {
 				Py_DECREF(newitem);
 				return -1;
 			}
-			if (cmp == 1)
+			if (cmp == 0)
 				childpos = rightpos;
 		}
 		/* Move the smaller child up. */
@@ -214,10 +214,10 @@
 		return item;
 	}
 
-	cmp = PyObject_RichCompareBool(item, PyList_GET_ITEM(heap, 0), Py_LE);
+	cmp = PyObject_RichCompareBool(PyList_GET_ITEM(heap, 0), item, Py_LT);
 	if (cmp == -1)
 		return NULL;
-	if (cmp == 1) {
+	if (cmp == 0) {
 		Py_INCREF(item);
 		return item;
 	}
@@ -270,6 +270,7 @@
 {
 	PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
 	Py_ssize_t i, n;
+	int cmp;
 
 	if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
 		return NULL;
@@ -312,7 +313,12 @@
 			else
 				goto sortit;
 		}
-		if (PyObject_RichCompareBool(elem, sol, Py_LE)) {
+		cmp = PyObject_RichCompareBool(sol, elem, Py_LT);
+		if (cmp == -1) {
+			Py_DECREF(elem);
+			goto fail;
+		}
+		if (cmp == 0) {
 			Py_DECREF(elem);
 			continue;
 		}
@@ -362,12 +368,12 @@
 	while (pos > startpos){
 		parentpos = (pos - 1) >> 1;
 		parent = PyList_GET_ITEM(heap, parentpos);
-		cmp = PyObject_RichCompareBool(newitem, parent, Py_LE);
+		cmp = PyObject_RichCompareBool(parent, newitem, Py_LT);
 		if (cmp == -1) {
 			Py_DECREF(newitem);
 			return -1;
 		}
-		if (cmp == 1)
+		if (cmp == 0)
 			break;
 		Py_INCREF(parent);
 		Py_DECREF(PyList_GET_ITEM(heap, pos));
@@ -403,14 +409,14 @@
 		rightpos = childpos + 1;
 		if (rightpos < endpos) {
 			cmp = PyObject_RichCompareBool(
-				PyList_GET_ITEM(heap, childpos),
 				PyList_GET_ITEM(heap, rightpos),
-				Py_LE);
+				PyList_GET_ITEM(heap, childpos),
+				Py_LT);
 			if (cmp == -1) {
 				Py_DECREF(newitem);
 				return -1;
 			}
-			if (cmp == 1)
+			if (cmp == 0)
 				childpos = rightpos;
 		}
 		/* Move the smaller child up. */
@@ -434,6 +440,7 @@
 {
 	PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
 	Py_ssize_t i, n;
+	int cmp;
 
 	if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
 		return NULL;
@@ -477,7 +484,12 @@
 			else
 				goto sortit;
 		}
-		if (PyObject_RichCompareBool(los, elem, Py_LE)) {
+		cmp = PyObject_RichCompareBool(elem, los, Py_LT);
+		if (cmp == -1) {
+			Py_DECREF(elem);
+			goto fail;
+		}
+		if (cmp == 0) {
 			Py_DECREF(elem);
 			continue;
 		}
@@ -658,6 +670,6 @@
 	m = Py_InitModule3("_heapq", heapq_methods, module_doc);
 	if (m == NULL)
     		return;
-	PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
+	PyModule_AddObject(m, "__about__", PyBytes_FromString(__about__));
 }
 

Modified: python/branches/okkoto-sizeof/Modules/_hotshot.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_hotshot.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_hotshot.c	Wed Jun  4 11:24:23 2008
@@ -326,7 +326,7 @@
             return ERR_EOF;
         }
     }
-    *pvalue = PyString_FromStringAndSize(buf, len);
+    *pvalue = PyBytes_FromStringAndSize(buf, len);
     free(buf);
     if (*pvalue == NULL) {
         return ERR_EXCEPTION;
@@ -562,7 +562,7 @@
                 self->index - written);
         self->index -= written;
         if (written == 0) {
-            char *s = PyString_AsString(self->logfilename);
+            char *s = PyBytes_AsString(self->logfilename);
             PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
             do_stop(self);
             return -1;
@@ -570,7 +570,7 @@
     }
     if (written > 0) {
         if (fflush(self->logfp)) {
-            char *s = PyString_AsString(self->logfilename);
+            char *s = PyBytes_AsString(self->logfilename);
             PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
             do_stop(self);
             return -1;
@@ -792,7 +792,7 @@
         self->next_fileno++;
         Py_DECREF(obj);
         if (pack_define_file(self, fileno,
-                             PyString_AS_STRING(fcode->co_filename)) < 0)
+                             PyBytes_AS_STRING(fcode->co_filename)) < 0)
             return -1;
     }
     else {
@@ -810,7 +810,7 @@
         PyObject *name = PyDict_GetItem(dict, obj);
         if (name == NULL) {
             if (pack_define_func(self, fileno, fcode->co_firstlineno,
-                                 PyString_AS_STRING(fcode->co_name)) < 0) {
+                                 PyBytes_AS_STRING(fcode->co_name)) < 0) {
                 Py_DECREF(obj);
                 return -1;
             }
@@ -1471,7 +1471,7 @@
     len = PyList_GET_SIZE(temp);
     for (i = 0; i < len; ++i) {
         PyObject *item = PyList_GET_ITEM(temp, i);
-        buffer = PyString_AsString(item);
+        buffer = PyBytes_AsString(item);
         if (buffer == NULL) {
             pack_add_info(self, "sys-path-entry", "<non-string-path-entry>");
             PyErr_Clear();

Modified: python/branches/okkoto-sizeof/Modules/_json.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_json.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_json.c	Wed Jun  4 11:24:23 2008
@@ -70,11 +70,11 @@
     input_unicode = PyUnicode_AS_UNICODE(pystr);
     /* One char input can be up to 6 chars output, estimate 4 of these */
     output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
-    rval = PyString_FromStringAndSize(NULL, output_size);
+    rval = PyBytes_FromStringAndSize(NULL, output_size);
     if (rval == NULL) {
         return NULL;
     }
-    output = PyString_AS_STRING(rval);
+    output = PyBytes_AS_STRING(rval);
     chars = 0;
     output[chars++] = '"';
     for (i = 0; i < input_chars; i++) {
@@ -92,14 +92,14 @@
             if (output_size > 2 + (input_chars * MAX_EXPANSION)) {
                 output_size = 2 + (input_chars * MAX_EXPANSION);
             }
-            if (_PyString_Resize(&rval, output_size) == -1) {
+            if (_PyBytes_Resize(&rval, output_size) == -1) {
                 return NULL;
             }
-            output = PyString_AS_STRING(rval);
+            output = PyBytes_AS_STRING(rval);
         }
     }
     output[chars++] = '"';
-    if (_PyString_Resize(&rval, chars) == -1) {
+    if (_PyBytes_Resize(&rval, chars) == -1) {
         return NULL;
     }
     return rval;
@@ -116,15 +116,15 @@
     char *output;
     char *input_str;
 
-    input_chars = PyString_GET_SIZE(pystr);
-    input_str = PyString_AS_STRING(pystr);
+    input_chars = PyBytes_GET_SIZE(pystr);
+    input_str = PyBytes_AS_STRING(pystr);
     /* One char input can be up to 6 chars output, estimate 4 of these */
     output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
-    rval = PyString_FromStringAndSize(NULL, output_size);
+    rval = PyBytes_FromStringAndSize(NULL, output_size);
     if (rval == NULL) {
         return NULL;
     }
-    output = PyString_AS_STRING(rval);
+    output = PyBytes_AS_STRING(rval);
     chars = 0;
     output[chars++] = '"';
     for (i = 0; i < input_chars; i++) {
@@ -154,14 +154,14 @@
             if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
                 output_size = 2 + (input_chars * MIN_EXPANSION);
             }
-            if (_PyString_Resize(&rval, output_size) == -1) {
+            if (_PyBytes_Resize(&rval, output_size) == -1) {
                 return NULL;
             }
-            output = PyString_AS_STRING(rval);
+            output = PyBytes_AS_STRING(rval);
         }
     }
     output[chars++] = '"';
-    if (_PyString_Resize(&rval, chars) == -1) {
+    if (_PyBytes_Resize(&rval, chars) == -1) {
         return NULL;
     }
     return rval;
@@ -215,7 +215,7 @@
         ustr = PyUnicode_FromUnicode(&c, 0);
     }
     if (joinstr == NULL) {
-        joinstr = PyString_InternFromString("join");
+        joinstr = PyBytes_InternFromString("join");
     }
     if (joinstr == NULL || ustr == NULL) {
         return NULL;
@@ -227,10 +227,10 @@
 scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict)
 {
     PyObject *rval;
-    Py_ssize_t len = PyString_GET_SIZE(pystr);
+    Py_ssize_t len = PyBytes_GET_SIZE(pystr);
     Py_ssize_t begin = end - 1;
     Py_ssize_t next = begin;
-    char *buf = PyString_AS_STRING(pystr);
+    char *buf = PyBytes_AS_STRING(pystr);
     PyObject *chunks = PyList_New(0);
     if (chunks == NULL) {
         goto bail;
@@ -555,7 +555,7 @@
     if (encoding == NULL) {
         encoding = DEFAULT_ENCODING;
     }
-    if (PyString_Check(pystr)) {
+    if (PyBytes_Check(pystr)) {
         return scanstring_str(pystr, end, encoding, strict);
     }
     else if (PyUnicode_Check(pystr)) {
@@ -576,7 +576,7 @@
 py_encode_basestring_ascii(PyObject* self, PyObject *pystr)
 {
     /* METH_O */
-    if (PyString_Check(pystr)) {
+    if (PyBytes_Check(pystr)) {
         return ascii_escape_str(pystr);
     }
     else if (PyUnicode_Check(pystr)) {

Modified: python/branches/okkoto-sizeof/Modules/_localemodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_localemodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_localemodule.c	Wed Jun  4 11:24:23 2008
@@ -119,7 +119,7 @@
         if (isupper(c))
             ul[n++] = c;
     }
-    ulo = PyString_FromStringAndSize((const char *)ul, n);
+    ulo = PyBytes_FromStringAndSize((const char *)ul, n);
     if (!ulo)
         return;
     if (string)
@@ -134,7 +134,7 @@
         if (islower(c))
             ul[n++] = c;
     }
-    ulo = PyString_FromStringAndSize((const char *)ul, n);
+    ulo = PyBytes_FromStringAndSize((const char *)ul, n);
     if (!ulo)
         return;
     if (string)
@@ -149,7 +149,7 @@
         if (isalpha(c))
             ul[n++] = c;
     }
-    ulo = PyString_FromStringAndSize((const char *)ul, n);
+    ulo = PyBytes_FromStringAndSize((const char *)ul, n);
     if (!ulo)
         return;
     if (string)
@@ -175,7 +175,7 @@
             PyErr_SetString(Error, "unsupported locale setting");
             return NULL;
         }
-        result_object = PyString_FromString(result);
+        result_object = PyBytes_FromString(result);
         if (!result_object)
             return NULL;
         /* record changes to LC_CTYPE */
@@ -190,7 +190,7 @@
             PyErr_SetString(Error, "locale query failed");
             return NULL;
         }
-        result_object = PyString_FromString(result);
+        result_object = PyBytes_FromString(result);
     }
     return result_object;
 }
@@ -216,7 +216,7 @@
        involved herein */
 
 #define RESULT_STRING(s)\
-    x = PyString_FromString(l->s);\
+    x = PyBytes_FromString(l->s);\
     if (!x) goto failed;\
     PyDict_SetItemString(result, #s, x);\
     Py_XDECREF(x)
@@ -284,9 +284,9 @@
     if (!PyArg_UnpackTuple(args, "strcoll", 2, 2, &os1, &os2))
         return NULL;
     /* If both arguments are byte strings, use strcoll.  */
-    if (PyString_Check(os1) && PyString_Check(os2))
-        return PyInt_FromLong(strcoll(PyString_AS_STRING(os1),
-                                      PyString_AS_STRING(os2)));
+    if (PyBytes_Check(os1) && PyBytes_Check(os2))
+        return PyInt_FromLong(strcoll(PyBytes_AS_STRING(os1),
+                                      PyBytes_AS_STRING(os2)));
     /* If neither argument is unicode, it's an error.  */
     if (!PyUnicode_Check(os1) && !PyUnicode_Check(os2)) {
         PyErr_SetString(PyExc_ValueError, "strcoll arguments must be strings");
@@ -368,7 +368,7 @@
             return PyErr_NoMemory();
         strxfrm(buf, s, n2);
     }
-    result = PyString_FromString(buf);
+    result = PyBytes_FromString(buf);
     PyMem_Free(buf);
     return result;
 }
@@ -563,13 +563,13 @@
         return NULL;
     /* Check whether this is a supported constant. GNU libc sometimes
        returns numeric values in the char* return value, which would
-       crash PyString_FromString.  */
+       crash PyBytes_FromString.  */
     for (i = 0; langinfo_constants[i].name; i++)
         if (langinfo_constants[i].value == item) {
             /* Check NULL as a workaround for GNU libc's returning NULL
                instead of an empty string for nl_langinfo(ERA).  */
             const char *result = nl_langinfo(item);
-            return PyString_FromString(result != NULL ? result : "");
+            return PyBytes_FromString(result != NULL ? result : "");
         }
     PyErr_SetString(PyExc_ValueError, "unsupported langinfo constant");
     return NULL;
@@ -588,7 +588,7 @@
 	char *in;
 	if (!PyArg_ParseTuple(args, "z", &in))
 		return 0;
-	return PyString_FromString(gettext(in));
+	return PyBytes_FromString(gettext(in));
 }
 
 PyDoc_STRVAR(dgettext__doc__,
@@ -601,7 +601,7 @@
 	char *domain, *in;
 	if (!PyArg_ParseTuple(args, "zz", &domain, &in))
 		return 0;
-	return PyString_FromString(dgettext(domain, in));
+	return PyBytes_FromString(dgettext(domain, in));
 }
 
 PyDoc_STRVAR(dcgettext__doc__,
@@ -615,7 +615,7 @@
 	int category;
 	if (!PyArg_ParseTuple(args, "zzi", &domain, &msgid, &category))
 		return 0;
-	return PyString_FromString(dcgettext(domain,msgid,category));
+	return PyBytes_FromString(dcgettext(domain,msgid,category));
 }
 
 PyDoc_STRVAR(textdomain__doc__,
@@ -633,7 +633,7 @@
 		PyErr_SetFromErrno(PyExc_OSError);
 		return NULL;
 	}
-	return PyString_FromString(domain);
+	return PyBytes_FromString(domain);
 }
 
 PyDoc_STRVAR(bindtextdomain__doc__,
@@ -651,7 +651,7 @@
 		PyErr_SetFromErrno(PyExc_OSError);
 		return NULL;
 	}
-	return PyString_FromString(dirname);
+	return PyBytes_FromString(dirname);
 }
 
 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
@@ -667,7 +667,7 @@
 		return NULL;
 	codeset = bind_textdomain_codeset(domain, codeset);
 	if (codeset)
-		return PyString_FromString(codeset);
+		return PyBytes_FromString(codeset);
 	Py_RETURN_NONE;
 }
 #endif
@@ -760,7 +760,7 @@
     Error = PyErr_NewException("locale.Error", NULL, NULL);
     PyDict_SetItemString(d, "Error", Error);
 
-    x = PyString_FromString(locale__doc__);
+    x = PyBytes_FromString(locale__doc__);
     PyDict_SetItemString(d, "__doc__", x);
     Py_XDECREF(x);
 

Modified: python/branches/okkoto-sizeof/Modules/_lsprof.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_lsprof.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_lsprof.c	Wed Jun  4 11:24:23 2008
@@ -179,8 +179,8 @@
 		/* built-in function: look up the module name */
 		PyObject *mod = fn->m_module;
 		char *modname;
-		if (mod && PyString_Check(mod)) {
-			modname = PyString_AS_STRING(mod);
+		if (mod && PyBytes_Check(mod)) {
+			modname = PyBytes_AS_STRING(mod);
 		}
 		else if (mod && PyModule_Check(mod)) {
 			modname = PyModule_GetName(mod);
@@ -193,11 +193,11 @@
 			modname = "__builtin__";
 		}
 		if (strcmp(modname, "__builtin__") != 0)
-			return PyString_FromFormat("<%s.%s>",
+			return PyBytes_FromFormat("<%s.%s>",
 						   modname,
 						   fn->m_ml->ml_name);
 		else
-			return PyString_FromFormat("<%s>",
+			return PyBytes_FromFormat("<%s>",
 						   fn->m_ml->ml_name);
 	}
 	else {
@@ -205,7 +205,7 @@
 			repr(getattr(type(__self__), __name__))
 		*/
 		PyObject *self = fn->m_self;
-		PyObject *name = PyString_FromString(fn->m_ml->ml_name);
+		PyObject *name = PyBytes_FromString(fn->m_ml->ml_name);
 		if (name != NULL) {
 			PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
 			Py_XINCREF(mo);
@@ -218,7 +218,7 @@
 			}
 		}
 		PyErr_Clear();
-		return PyString_FromFormat("<built-in method %s>",
+		return PyBytes_FromFormat("<built-in method %s>",
 					   fn->m_ml->ml_name);
 	}
 }

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/cache.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/cache.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/cache.c	Wed Jun  4 11:24:23 2008
@@ -241,12 +241,12 @@
         if (!fmt_args) {
             return NULL;
         }
-        template = PyString_FromString("%s <- %s ->%s\n");
+        template = PyBytes_FromString("%s <- %s ->%s\n");
         if (!template) {
             Py_DECREF(fmt_args);
             return NULL;
         }
-        display_str = PyString_Format(template, fmt_args);
+        display_str = PyBytes_Format(template, fmt_args);
         Py_DECREF(template);
         Py_DECREF(fmt_args);
         if (!display_str) {

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/connection.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/connection.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/connection.c	Wed Jun  4 11:24:23 2008
@@ -84,8 +84,8 @@
     Py_INCREF(&PyUnicode_Type);
     self->text_factory = (PyObject*)&PyUnicode_Type;
 
-    if (PyString_Check(database) || PyUnicode_Check(database)) {
-        if (PyString_Check(database)) {
+    if (PyBytes_Check(database) || PyUnicode_Check(database)) {
+        if (PyBytes_Check(database)) {
             database_utf8 = database;
             Py_INCREF(database_utf8);
         } else {
@@ -96,7 +96,7 @@
         }
 
         Py_BEGIN_ALLOW_THREADS
-        rc = sqlite3_open(PyString_AsString(database_utf8), &self->db);
+        rc = sqlite3_open(PyBytes_AsString(database_utf8), &self->db);
         Py_END_ALLOW_THREADS
 
         Py_DECREF(database_utf8);
@@ -111,7 +111,7 @@
         if (class_attr) {
             class_attr_str = PyObject_Str(class_attr);
             if (class_attr_str) {
-                if (strcmp(PyString_AsString(class_attr_str), "<type 'apsw.Connection'>") == 0) {
+                if (strcmp(PyBytes_AsString(class_attr_str), "<type 'apsw.Connection'>") == 0) {
                     /* In the APSW Connection object, the first entry after
                      * PyObject_HEAD is the sqlite3* we want to get hold of.
                      * Luckily, this is the same layout as we have in our
@@ -134,7 +134,7 @@
     }
 
     if (!isolation_level) {
-        isolation_level = PyString_FromString("");
+        isolation_level = PyBytes_FromString("");
         if (!isolation_level) {
             return -1;
         }
@@ -499,12 +499,12 @@
         } else {
             sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
         }
-    } else if (PyString_Check(py_val)) {
-        sqlite3_result_text(context, PyString_AsString(py_val), -1, SQLITE_TRANSIENT);
+    } else if (PyBytes_Check(py_val)) {
+        sqlite3_result_text(context, PyBytes_AsString(py_val), -1, SQLITE_TRANSIENT);
     } else if (PyUnicode_Check(py_val)) {
         stringval = PyUnicode_AsUTF8String(py_val);
         if (stringval) {
-            sqlite3_result_text(context, PyString_AsString(stringval), -1, SQLITE_TRANSIENT);
+            sqlite3_result_text(context, PyBytes_AsString(stringval), -1, SQLITE_TRANSIENT);
             Py_DECREF(stringval);
         }
     } else {
@@ -963,21 +963,21 @@
         Py_INCREF(isolation_level);
         self->isolation_level = isolation_level;
 
-        begin_statement = PyString_FromString("BEGIN ");
+        begin_statement = PyBytes_FromString("BEGIN ");
         if (!begin_statement) {
             return -1;
         }
-        PyString_Concat(&begin_statement, isolation_level);
+        PyBytes_Concat(&begin_statement, isolation_level);
         if (!begin_statement) {
             return -1;
         }
 
-        self->begin_statement = PyMem_Malloc(PyString_Size(begin_statement) + 2);
+        self->begin_statement = PyMem_Malloc(PyBytes_Size(begin_statement) + 2);
         if (!self->begin_statement) {
             return -1;
         }
 
-        strcpy(self->begin_statement, PyString_AsString(begin_statement));
+        strcpy(self->begin_statement, PyBytes_AsString(begin_statement));
         Py_DECREF(begin_statement);
     }
 
@@ -1152,8 +1152,8 @@
         goto finally;
     }
 
-    string1 = PyString_FromStringAndSize((const char*)text1_data, text1_length);
-    string2 = PyString_FromStringAndSize((const char*)text2_data, text2_length);
+    string1 = PyBytes_FromStringAndSize((const char*)text1_data, text1_length);
+    string2 = PyBytes_FromStringAndSize((const char*)text2_data, text2_length);
 
     if (!string1 || !string2) {
         goto finally; /* failed to allocate strings */
@@ -1259,7 +1259,7 @@
         goto finally;
     }
 
-    if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyString_Type, &name, &callable)) {
+    if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyBytes_Type, &name, &callable)) {
         goto finally;
     }
 
@@ -1268,7 +1268,7 @@
         goto finally;
     }
 
-    chk = PyString_AsString(uppercase_name);
+    chk = PyBytes_AsString(uppercase_name);
     while (*chk) {
         if ((*chk >= '0' && *chk <= '9')
          || (*chk >= 'A' && *chk <= 'Z')
@@ -1293,7 +1293,7 @@
     }
 
     rc = sqlite3_create_collation(self->db,
-                                  PyString_AsString(uppercase_name),
+                                  PyBytes_AsString(uppercase_name),
                                   SQLITE_UTF8,
                                   (callable != Py_None) ? callable : NULL,
                                   (callable != Py_None) ? pysqlite_collation_callback : NULL);

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/connection.h
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/connection.h	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/connection.h	Wed Jun  4 11:24:23 2008
@@ -80,7 +80,7 @@
     /* Determines how bytestrings from SQLite are converted to Python objects:
      * - PyUnicode_Type:        Python Unicode objects are constructed from UTF-8 bytestrings
      * - OptimizedUnicode:      Like before, but for ASCII data, only PyStrings are created.
-     * - PyString_Type:         PyStrings are created as-is.
+     * - PyBytes_Type:         PyStrings are created as-is.
      * - Any custom callable:   Any object returned from the callable called with the bytestring
      *                          as single parameter.
      */

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/cursor.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/cursor.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/cursor.c	Wed Jun  4 11:24:23 2008
@@ -101,10 +101,7 @@
 
     self->arraysize = 1;
 
-    self->rowcount = PyInt_FromLong(-1L);
-    if (!self->rowcount) {
-        return -1;
-    }
+    self->rowcount = -1L;
 
     Py_INCREF(Py_None);
     self->row_factory = Py_None;
@@ -130,7 +127,6 @@
     Py_XDECREF(self->row_cast_map);
     Py_XDECREF(self->description);
     Py_XDECREF(self->lastrowid);
-    Py_XDECREF(self->rowcount);
     Py_XDECREF(self->row_factory);
     Py_XDECREF(self->next_row);
 
@@ -182,7 +178,7 @@
                     if (*pos == '[') {
                         type_start = pos + 1;
                     } else if (*pos == ']' && type_start != (const char*)-1) {
-                        key = PyString_FromStringAndSize(type_start, pos - type_start);
+                        key = PyBytes_FromStringAndSize(type_start, pos - type_start);
                         if (!key) {
                             /* creating a string failed, but it is too complicated
                              * to propagate the error here, we just assume there is
@@ -207,7 +203,7 @@
                      * 'NUMBER(10)' to be treated as 'NUMBER', for example.
                      * In other words, it will work as people expect it to work.*/
                     if (*pos == ' ' || *pos == '(' || *pos == 0) {
-                        py_decltype = PyString_FromStringAndSize(decltype, pos - decltype);
+                        py_decltype = PyBytes_FromStringAndSize(decltype, pos - decltype);
                         if (!py_decltype) {
                             return -1;
                         }
@@ -252,7 +248,7 @@
             if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) {
                 pos--;
             }
-            return PyString_FromStringAndSize(colname, pos - colname);
+            return PyBytes_FromStringAndSize(colname, pos - colname);
         }
     }
 }
@@ -277,7 +273,7 @@
     }
 
     if (is_ascii) {
-        return PyString_FromString(val_str);
+        return PyBytes_FromString(val_str);
     } else {
         return PyUnicode_DecodeUTF8(val_str, strlen(val_str), NULL);
     }
@@ -331,7 +327,7 @@
                 Py_INCREF(Py_None);
                 converted = Py_None;
             } else {
-                item = PyString_FromStringAndSize(val_str, nbytes);
+                item = PyBytes_FromStringAndSize(val_str, nbytes);
                 if (!item) {
                     return NULL;
                 }
@@ -374,8 +370,8 @@
                                      colname , val_str);
                         PyErr_SetString(pysqlite_OperationalError, buf);
                     }
-                } else if (self->connection->text_factory == (PyObject*)&PyString_Type) {
-                    converted = PyString_FromString(val_str);
+                } else if (self->connection->text_factory == (PyObject*)&PyBytes_Type) {
+                    converted = PyBytes_FromString(val_str);
                 } else {
                     converted = PyObject_CallFunction(self->connection->text_factory, "s", val_str);
                 }
@@ -427,12 +423,12 @@
     int statement_type;
     PyObject* descriptor;
     PyObject* second_argument = NULL;
-    long rowcount = 0;
     int allow_8bit_chars;
 
     if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
         return NULL;
     }
+
     /* Make shooting yourself in the foot with not utf-8 decodable 8-bit-strings harder */
     allow_8bit_chars = ((self->connection->text_factory != (PyObject*)&PyUnicode_Type) &&
         (self->connection->text_factory != (PyObject*)&PyUnicode_Type && pysqlite_OptimizedUnicode));
@@ -446,7 +442,7 @@
             return NULL;
         }
 
-        if (!PyString_Check(operation) && !PyUnicode_Check(operation)) {
+        if (!PyBytes_Check(operation) && !PyUnicode_Check(operation)) {
             PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode");
             return NULL;
         }
@@ -468,7 +464,7 @@
             return NULL;
         }
 
-        if (!PyString_Check(operation) && !PyUnicode_Check(operation)) {
+        if (!PyBytes_Check(operation) && !PyUnicode_Check(operation)) {
             PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode");
             return NULL;
         }
@@ -503,21 +499,22 @@
         rc = pysqlite_statement_reset(self->statement);
     }
 
-    if (PyString_Check(operation)) {
-        operation_cstr = PyString_AsString(operation);
+    if (PyBytes_Check(operation)) {
+        operation_cstr = PyBytes_AsString(operation);
     } else {
         operation_bytestr = PyUnicode_AsUTF8String(operation);
         if (!operation_bytestr) {
             goto error;
         }
 
-        operation_cstr = PyString_AsString(operation_bytestr);
+        operation_cstr = PyBytes_AsString(operation_bytestr);
     }
 
-    /* reset description */
+    /* reset description and rowcount */
     Py_DECREF(self->description);
     Py_INCREF(Py_None);
     self->description = Py_None;
+    self->rowcount = -1L;
 
     func_args = PyTuple_New(1);
     if (!func_args) {
@@ -693,7 +690,10 @@
             case STATEMENT_DELETE:
             case STATEMENT_INSERT:
             case STATEMENT_REPLACE:
-                rowcount += (long)sqlite3_changes(self->connection->db);
+                if (self->rowcount == -1L) {
+                    self->rowcount = 0L;
+                }
+                self->rowcount += (long)sqlite3_changes(self->connection->db);
         }
 
         Py_DECREF(self->lastrowid);
@@ -728,13 +728,9 @@
     Py_XDECREF(parameters_list);
 
     if (PyErr_Occurred()) {
-        Py_DECREF(self->rowcount);
-        self->rowcount = PyInt_FromLong(-1L);
+        self->rowcount = -1L;
         return NULL;
     } else {
-        Py_DECREF(self->rowcount);
-        self->rowcount = PyInt_FromLong(rowcount);
-
         Py_INCREF(self);
         return (PyObject*)self;
     }
@@ -768,15 +764,15 @@
         return NULL;
     }
 
-    if (PyString_Check(script_obj)) {
-        script_cstr = PyString_AsString(script_obj);
+    if (PyBytes_Check(script_obj)) {
+        script_cstr = PyBytes_AsString(script_obj);
     } else if (PyUnicode_Check(script_obj)) {
         script_str = PyUnicode_AsUTF8String(script_obj);
         if (!script_str) {
             return NULL;
         }
 
-        script_cstr = PyString_AsString(script_str);
+        script_cstr = PyBytes_AsString(script_str);
     } else {
         PyErr_SetString(PyExc_ValueError, "script argument must be unicode or string.");
         return NULL;
@@ -1028,7 +1024,7 @@
     {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), RO},
     {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
     {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), RO},
-    {"rowcount", T_OBJECT, offsetof(pysqlite_Cursor, rowcount), RO},
+    {"rowcount", T_LONG, offsetof(pysqlite_Cursor, rowcount), RO},
     {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
     {NULL}
 };

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/cursor.h
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/cursor.h	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/cursor.h	Wed Jun  4 11:24:23 2008
@@ -37,7 +37,7 @@
     PyObject* row_cast_map;
     int arraysize;
     PyObject* lastrowid;
-    PyObject* rowcount;
+    long rowcount;
     PyObject* row_factory;
     pysqlite_Statement* statement;
 

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/module.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/module.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/module.c	Wed Jun  4 11:24:23 2008
@@ -137,7 +137,7 @@
     /* a basic type is adapted; there's a performance optimization if that's not the case
      * (99 % of all usages) */
     if (type == &PyInt_Type || type == &PyLong_Type || type == &PyFloat_Type
-            || type == &PyString_Type || type == &PyUnicode_Type || type == &PyBuffer_Type) {
+            || type == &PyBytes_Type || type == &PyUnicode_Type || type == &PyBuffer_Type) {
         pysqlite_BaseTypeAdapted = 1;
     }
 
@@ -367,13 +367,13 @@
         Py_DECREF(tmp_obj);
     }
 
-    if (!(tmp_obj = PyString_FromString(PYSQLITE_VERSION))) {
+    if (!(tmp_obj = PyBytes_FromString(PYSQLITE_VERSION))) {
         goto error;
     }
     PyDict_SetItemString(dict, "version", tmp_obj);
     Py_DECREF(tmp_obj);
 
-    if (!(tmp_obj = PyString_FromString(sqlite3_libversion()))) {
+    if (!(tmp_obj = PyBytes_FromString(sqlite3_libversion()))) {
         goto error;
     }
     PyDict_SetItemString(dict, "sqlite_version", tmp_obj);

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/row.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/row.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/row.c	Wed Jun  4 11:24:23 2008
@@ -86,13 +86,13 @@
         item = PyTuple_GetItem(self->data, _idx);
         Py_XINCREF(item);
         return item;
-    } else if (PyString_Check(idx)) {
-        key = PyString_AsString(idx);
+    } else if (PyBytes_Check(idx)) {
+        key = PyBytes_AsString(idx);
 
         nitems = PyTuple_Size(self->description);
 
         for (i = 0; i < nitems; i++) {
-            compare_key = PyString_AsString(PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0));
+            compare_key = PyBytes_AsString(PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0));
             if (!compare_key) {
                 return NULL;
             }

Modified: python/branches/okkoto-sizeof/Modules/_sqlite/statement.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sqlite/statement.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sqlite/statement.c	Wed Jun  4 11:24:23 2008
@@ -60,7 +60,7 @@
     self->st = NULL;
     self->in_use = 0;
 
-    if (PyString_Check(sql)) {
+    if (PyBytes_Check(sql)) {
         sql_str = sql;
         Py_INCREF(sql_str);
     } else if (PyUnicode_Check(sql)) {
@@ -77,7 +77,7 @@
     self->in_weakreflist = NULL;
     self->sql = sql_str;
 
-    sql_cstr = PyString_AsString(sql_str);
+    sql_cstr = PyBytes_AsString(sql_str);
 
     rc = sqlite3_prepare(connection->db,
                          sql_cstr,
@@ -119,7 +119,7 @@
         paramtype = TYPE_LONG;
     } else if (PyFloat_CheckExact(parameter)) {
         paramtype = TYPE_FLOAT;
-    } else if (PyString_CheckExact(parameter)) {
+    } else if (PyBytes_CheckExact(parameter)) {
         paramtype = TYPE_STRING;
     } else if (PyUnicode_CheckExact(parameter)) {
         paramtype = TYPE_UNICODE;
@@ -131,7 +131,7 @@
         paramtype = TYPE_LONG;
     } else if (PyFloat_Check(parameter)) {
         paramtype = TYPE_FLOAT;
-    } else if (PyString_Check(parameter)) {
+    } else if (PyBytes_Check(parameter)) {
         paramtype = TYPE_STRING;
     } else if (PyUnicode_Check(parameter)) {
         paramtype = TYPE_UNICODE;
@@ -140,7 +140,7 @@
     }
 
     if (paramtype == TYPE_STRING && !allow_8bit_chars) {
-        string = PyString_AS_STRING(parameter);
+        string = PyBytes_AS_STRING(parameter);
         for (c = string; *c != 0; c++) {
             if (*c & 0x80) {
                 PyErr_SetString(pysqlite_ProgrammingError, "You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.");
@@ -164,12 +164,12 @@
             rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
             break;
         case TYPE_STRING:
-            string = PyString_AS_STRING(parameter);
+            string = PyBytes_AS_STRING(parameter);
             rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
             break;
         case TYPE_UNICODE:
             stringval = PyUnicode_AsUTF8String(parameter);
-            string = PyString_AsString(stringval);
+            string = PyBytes_AsString(stringval);
             rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT);
             Py_DECREF(stringval);
             break;
@@ -197,7 +197,7 @@
     }
 
     if (PyInt_CheckExact(obj) || PyLong_CheckExact(obj) 
-            || PyFloat_CheckExact(obj) || PyString_CheckExact(obj)
+            || PyFloat_CheckExact(obj) || PyBytes_CheckExact(obj)
             || PyUnicode_CheckExact(obj) || PyBuffer_Check(obj)) {
         return 0;
     } else {
@@ -326,7 +326,7 @@
     char* sql_cstr;
     sqlite3_stmt* new_st;
 
-    sql_cstr = PyString_AsString(self->sql);
+    sql_cstr = PyBytes_AsString(self->sql);
 
     rc = sqlite3_prepare(self->db,
                          sql_cstr,

Modified: python/branches/okkoto-sizeof/Modules/_sre.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_sre.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_sre.c	Wed Jun  4 11:24:23 2008
@@ -1715,7 +1715,7 @@
     size = PyObject_Length(string);
 #endif
 
-    if (PyString_Check(string) || bytes == size)
+    if (PyBytes_Check(string) || bytes == size)
         charsize = 1;
 #if defined(HAVE_UNICODE)
     else if (bytes == (Py_ssize_t) (size * sizeof(Py_UNICODE)))
@@ -1949,7 +1949,7 @@
 
     if (!args)
         return NULL;
-    name = PyString_FromString(module);
+    name = PyBytes_FromString(module);
     if (!name)
         return NULL;
     mod = PyImport_Import(name);
@@ -3416,7 +3416,7 @@
         Py_DECREF(x);
     }
 
-    x = PyString_FromString(copyright);
+    x = PyBytes_FromString(copyright);
     if (x) {
         PyDict_SetItemString(d, "copyright", x);
         Py_DECREF(x);

Modified: python/branches/okkoto-sizeof/Modules/_ssl.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_ssl.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_ssl.c	Wed Jun  4 11:24:23 2008
@@ -491,13 +491,13 @@
 static PyObject *
 PySSL_server(PySSLObject *self)
 {
-	return PyString_FromString(self->server);
+	return PyBytes_FromString(self->server);
 }
 
 static PyObject *
 PySSL_issuer(PySSLObject *self)
 {
-	return PyString_FromString(self->issuer);
+	return PyBytes_FromString(self->issuer);
 }
 
 static PyObject *
@@ -515,7 +515,7 @@
 		_setSSLError(NULL, 0, __FILE__, __LINE__);
 		goto fail;
 	}
-	name_obj = PyString_FromStringAndSize(namebuf, buflen);
+	name_obj = PyBytes_FromStringAndSize(namebuf, buflen);
 	if (name_obj == NULL)
 		goto fail;
 	
@@ -603,8 +603,8 @@
                 /*
                 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
                         entry->set,
-                        PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
-                        PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));                        
+                        PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
+                        PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));                        
                 */
 		if (attr == NULL)
 			goto fail1;
@@ -711,7 +711,7 @@
 					goto fail;
 				}
 
-				v = PyString_FromString("DirName");
+				v = PyBytes_FromString("DirName");
 				if (v == NULL) {
 					Py_DECREF(t);
 					goto fail;
@@ -742,13 +742,13 @@
 				t = PyTuple_New(2);
 				if (t == NULL)
 					goto fail;
-				v = PyString_FromStringAndSize(buf, (vptr - buf));
+				v = PyBytes_FromStringAndSize(buf, (vptr - buf));
 				if (v == NULL) {
 					Py_DECREF(t);
 					goto fail;
 				}
 				PyTuple_SET_ITEM(t, 0, v);
-				v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
+				v = PyBytes_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
 				if (v == NULL) {
 					Py_DECREF(t);
 					goto fail;
@@ -849,7 +849,7 @@
 			_setSSLError(NULL, 0, __FILE__, __LINE__);
 			goto fail1;
 		}
-		sn_obj = PyString_FromStringAndSize(buf, len);
+		sn_obj = PyBytes_FromStringAndSize(buf, len);
 		if (sn_obj == NULL)
 			goto fail1;
 		if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
@@ -866,7 +866,7 @@
 			_setSSLError(NULL, 0, __FILE__, __LINE__);
 			goto fail1;
 		}
-		pnotBefore = PyString_FromStringAndSize(buf, len);
+		pnotBefore = PyBytes_FromStringAndSize(buf, len);
 		if (pnotBefore == NULL)
 			goto fail1;
 		if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
@@ -884,7 +884,7 @@
 		_setSSLError(NULL, 0, __FILE__, __LINE__);
 		goto fail1;
 	}
-	pnotAfter = PyString_FromStringAndSize(buf, len);
+	pnotAfter = PyBytes_FromStringAndSize(buf, len);
 	if (pnotAfter == NULL)
 		goto fail1;
 	if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
@@ -981,7 +981,7 @@
 			PySSL_SetError(self, len, __FILE__, __LINE__);
 			return NULL;
 		}
-		retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
+		retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
 		OPENSSL_free(bytes_buf);
 		return retval;
 
@@ -1028,7 +1028,7 @@
 	if (cipher_name == NULL) {
 		PyTuple_SET_ITEM(retval, 0, Py_None);
 	} else {
-		v = PyString_FromString(cipher_name);
+		v = PyBytes_FromString(cipher_name);
 		if (v == NULL)
 			goto fail0;
 		PyTuple_SET_ITEM(retval, 0, v);
@@ -1037,7 +1037,7 @@
 	if (cipher_protocol == NULL) {
 		PyTuple_SET_ITEM(retval, 1, Py_None);
 	} else {
-		v = PyString_FromString(cipher_protocol);
+		v = PyBytes_FromString(cipher_protocol);
 		if (v == NULL)
 			goto fail0;
 		PyTuple_SET_ITEM(retval, 1, v);
@@ -1211,7 +1211,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 */
@@ -1233,14 +1233,14 @@
 			return NULL;
 		} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
 			/* should contain a zero-length string */
-			_PyString_Resize(&buf, 0);
+			_PyBytes_Resize(&buf, 0);
 			return buf;
 		}
 	}
 	do {
 		err = 0;
 		PySSL_BEGIN_ALLOW_THREADS
-		count = SSL_read(self->ssl, PyString_AsString(buf), len);
+		count = SSL_read(self->ssl, PyBytes_AsString(buf), len);
 		err = SSL_get_error(self->ssl, count);
 		PySSL_END_ALLOW_THREADS
 		if(PyErr_CheckSignals()) {
@@ -1257,7 +1257,7 @@
 			   (SSL_get_shutdown(self->ssl) ==
 			    SSL_RECEIVED_SHUTDOWN))
 		{
-			_PyString_Resize(&buf, 0);
+			_PyBytes_Resize(&buf, 0);
 			return buf;
 		} else {
 			sockstate = SOCKET_OPERATION_OK;
@@ -1276,7 +1276,7 @@
 		return PySSL_SetError(self, count, __FILE__, __LINE__);
 	}
 	if (count != len)
-		_PyString_Resize(&buf, count);
+		_PyBytes_Resize(&buf, count);
 	return buf;
 }
 
@@ -1362,11 +1362,11 @@
 {
     int bytes;
 
-    if (!PyString_Check(arg))
+    if (!PyBytes_Check(arg))
 	return PyErr_Format(PyExc_TypeError,
 			    "RAND_egd() expected string, found %s",
 			    Py_TYPE(arg)->tp_name);
-    bytes = RAND_egd(PyString_AS_STRING(arg));
+    bytes = RAND_egd(PyBytes_AS_STRING(arg));
     if (bytes == -1) {
 	PyErr_SetString(PySSLErrorObject,
 			"EGD connection failed or EGD did not return "

Modified: python/branches/okkoto-sizeof/Modules/_struct.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_struct.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_struct.c	Wed Jun  4 11:24:23 2008
@@ -413,7 +413,7 @@
 		if (msg == NULL)
 			return -1;
 		rval = PyErr_WarnEx(PyExc_DeprecationWarning,
-				    PyString_AS_STRING(msg), 2);
+				    PyBytes_AS_STRING(msg), 2);
 		Py_DECREF(msg);
 		if (rval == 0)
 			return 0;
@@ -446,7 +446,7 @@
 static PyObject *
 nu_char(const char *p, const formatdef *f)
 {
-	return PyString_FromStringAndSize(p, 1);
+	return PyBytes_FromStringAndSize(p, 1);
 }
 
 static PyObject *
@@ -610,12 +610,12 @@
 static int
 np_char(char *p, PyObject *v, const formatdef *f)
 {
-	if (!PyString_Check(v) || PyString_Size(v) != 1) {
+	if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
 		PyErr_SetString(StructError,
 				"char format require string of length 1");
 		return -1;
 	}
-	*p = *PyString_AsString(v);
+	*p = *PyBytes_AsString(v);
 	return 0;
 }
 
@@ -1335,7 +1335,7 @@
 	char c;
 	Py_ssize_t size, len, num, itemsize, x;
 
-	fmt = PyString_AS_STRING(self->s_format);
+	fmt = PyBytes_AS_STRING(self->s_format);
 
 	f = whichtable((char **)&fmt);
 
@@ -1503,12 +1503,12 @@
 		const formatdef *e = code->fmtdef;
 		const char *res = startfrom + code->offset;
 		if (e->format == 's') {
-			v = PyString_FromStringAndSize(res, code->size);
+			v = PyBytes_FromStringAndSize(res, code->size);
 		} else if (e->format == 'p') {
 			Py_ssize_t n = *(unsigned char*)res;
 			if (n >= code->size)
 				n = code->size - 1;
-			v = PyString_FromStringAndSize(res + 1, n);
+			v = PyBytes_FromStringAndSize(res + 1, n);
 		} else {
 			v = e->unpack(res, e);
 		}
@@ -1542,9 +1542,9 @@
 	assert(soself->s_codes != NULL);
 	if (inputstr == NULL)
 		goto fail;
-	if (PyString_Check(inputstr) &&
-		PyString_GET_SIZE(inputstr) == soself->s_size) {
-			return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
+	if (PyBytes_Check(inputstr) &&
+		PyBytes_GET_SIZE(inputstr) == soself->s_size) {
+			return s_unpack_internal(soself, PyBytes_AS_STRING(inputstr));
 	}
 	args = PyTuple_Pack(1, inputstr);
 	if (args == NULL)
@@ -1637,27 +1637,27 @@
 		const formatdef *e = code->fmtdef;
 		char *res = buf + code->offset;
 		if (e->format == 's') {
-			if (!PyString_Check(v)) {
+			if (!PyBytes_Check(v)) {
 				PyErr_SetString(StructError,
 						"argument for 's' must be a string");
 				return -1;
 			}
-			n = PyString_GET_SIZE(v);
+			n = PyBytes_GET_SIZE(v);
 			if (n > code->size)
 				n = code->size;
 			if (n > 0)
-				memcpy(res, PyString_AS_STRING(v), n);
+				memcpy(res, PyBytes_AS_STRING(v), n);
 		} else if (e->format == 'p') {
-			if (!PyString_Check(v)) {
+			if (!PyBytes_Check(v)) {
 				PyErr_SetString(StructError,
 						"argument for 'p' must be a string");
 				return -1;
 			}
-			n = PyString_GET_SIZE(v);
+			n = PyBytes_GET_SIZE(v);
 			if (n > (code->size - 1))
 				n = code->size - 1;
 			if (n > 0)
-				memcpy(res + 1, PyString_AS_STRING(v), n);
+				memcpy(res + 1, PyBytes_AS_STRING(v), n);
 			if (n > 255)
 				n = 255;
 			*res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
@@ -1700,12 +1700,12 @@
 	}
 
 	/* Allocate a new string */
-	result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
+	result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
 	if (result == NULL)
 		return NULL;
 
 	/* Call the guts */
-	if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
+	if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
 		Py_DECREF(result);
 		return NULL;
 	}
@@ -2061,7 +2061,7 @@
 {
 	PyObject *ver, *m;
 
-	ver = PyString_FromString("0.2");
+	ver = PyBytes_FromString("0.2");
 	if (ver == NULL)
 		return;
 

Modified: python/branches/okkoto-sizeof/Modules/_testcapimodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_testcapimodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_testcapimodule.c	Wed Jun  4 11:24:23 2008
@@ -691,7 +691,7 @@
 }
 #endif
 
-/* Some tests of PyString_FromFormat().  This needs more tests. */
+/* Some tests of PyBytes_FromFormat().  This needs more tests. */
 static PyObject *
 test_string_from_format(PyObject *self, PyObject *args)
 {
@@ -699,10 +699,10 @@
 	char *msg;
 
 #define CHECK_1_FORMAT(FORMAT, TYPE) 			\
-	result = PyString_FromFormat(FORMAT, (TYPE)1);	\
+	result = PyBytes_FromFormat(FORMAT, (TYPE)1);	\
 	if (result == NULL)				\
 		return NULL;				\
-	if (strcmp(PyString_AsString(result), "1")) {	\
+	if (strcmp(PyBytes_AsString(result), "1")) {	\
 		msg = FORMAT " failed at 1";		\
 		goto Fail;				\
 	}						\

Modified: python/branches/okkoto-sizeof/Modules/_tkinter.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/_tkinter.c	(original)
+++ python/branches/okkoto-sizeof/Modules/_tkinter.c	Wed Jun  4 11:24:23 2008
@@ -335,8 +335,8 @@
 static char *
 AsString(PyObject *value, PyObject *tmp)
 {
-	if (PyString_Check(value))
-		return PyString_AsString(value);
+	if (PyBytes_Check(value))
+		return PyBytes_AsString(value);
 #ifdef Py_USING_UNICODE
 	else if (PyUnicode_Check(value)) {
 		PyObject *v = PyUnicode_AsUTF8String(value);
@@ -347,7 +347,7 @@
 			return NULL;
 		}
 		Py_DECREF(v);
-		return PyString_AsString(v);
+		return PyBytes_AsString(v);
 	}
 #endif
 	else {
@@ -359,7 +359,7 @@
 			return NULL;
 		}
 		Py_DECREF(v);
-		return PyString_AsString(v);
+		return PyBytes_AsString(v);
 	}
 }
 
@@ -462,13 +462,13 @@
 		 * Could be a quoted string containing funnies, e.g. {"}.
 		 * Return the string itself.
 		 */
-		return PyString_FromString(list);
+		return PyBytes_FromString(list);
 	}
 
 	if (argc == 0)
-		v = PyString_FromString("");
+		v = PyBytes_FromString("");
 	else if (argc == 1)
-		v = PyString_FromString(argv[0]);
+		v = PyBytes_FromString(argv[0]);
 	else if ((v = PyTuple_New(argc)) != NULL) {
 		int i;
 		PyObject *w;
@@ -530,10 +530,10 @@
 			return result;
 		/* Fall through, returning arg. */
 	}
-	else if (PyString_Check(arg)) {
+	else if (PyBytes_Check(arg)) {
 		int argc;
 		char **argv;
-		char *list = PyString_AsString(arg);
+		char *list = PyBytes_AsString(arg);
 
 		if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
 			Py_INCREF(arg);
@@ -541,7 +541,7 @@
 		}
 		Tcl_Free(FREECAST argv);
 		if (argc > 1)
-			return Split(PyString_AsString(arg));
+			return Split(PyBytes_AsString(arg));
 		/* Fall through, returning arg. */
 	}
 	Py_INCREF(arg);
@@ -747,12 +747,12 @@
 static PyObject *
 PyTclObject_str(PyTclObject *self)
 {
-	if (self->string && PyString_Check(self->string)) {
+	if (self->string && PyBytes_Check(self->string)) {
 		Py_INCREF(self->string);
 		return self->string;
 	}
 	/* XXX Could cache value if it is an ASCII string. */
-	return PyString_FromString(Tcl_GetString(self->value));
+	return PyBytes_FromString(Tcl_GetString(self->value));
 }
 
 static char*
@@ -778,16 +778,16 @@
 #ifdef Py_USING_UNICODE
 		if (i == len)
 			/* It is an ASCII string. */
-			self->string = PyString_FromStringAndSize(s, len);
+			self->string = PyBytes_FromStringAndSize(s, len);
 		else {
 			self->string = PyUnicode_DecodeUTF8(s, len, "strict");
 			if (!self->string) {
 				PyErr_Clear();
-				self->string = PyString_FromStringAndSize(s, len);
+				self->string = PyBytes_FromStringAndSize(s, len);
 			}
 		}
 #else
-		self->string = PyString_FromStringAndSize(s, len);
+		self->string = PyBytes_FromStringAndSize(s, len);
 #endif
 		if (!self->string)
 			return NULL;
@@ -820,7 +820,7 @@
 	char buf[50];
 	PyOS_snprintf(buf, 50, "<%s object at %p>",
 		      self->value->typePtr->name, self->value);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int
@@ -839,7 +839,7 @@
 static PyObject*
 get_typename(PyTclObject* obj, void* ignored)
 {
-	return PyString_FromString(obj->value->typePtr->name);
+	return PyBytes_FromString(obj->value->typePtr->name);
 }
 
 
@@ -908,9 +908,9 @@
 {
 	Tcl_Obj *result;
 
-	if (PyString_Check(value))
-		return Tcl_NewStringObj(PyString_AS_STRING(value),
-					PyString_GET_SIZE(value));
+	if (PyBytes_Check(value))
+		return Tcl_NewStringObj(PyBytes_AS_STRING(value),
+					PyBytes_GET_SIZE(value));
 	else if (PyBool_Check(value))
 		return Tcl_NewBooleanObj(PyObject_IsTrue(value));
 	else if (PyInt_Check(value))
@@ -999,17 +999,17 @@
 		}
 
 		if (i == value->length)
-			result = PyString_FromStringAndSize(s, len);
+			result = PyBytes_FromStringAndSize(s, len);
 		else {
 			/* Convert UTF-8 to Unicode string */
 			result = PyUnicode_DecodeUTF8(s, len, "strict");
 			if (result == NULL) {
 				PyErr_Clear();
-				result = PyString_FromStringAndSize(s, len);
+				result = PyBytes_FromStringAndSize(s, len);
 			}
 		}
 #else
-		result = PyString_FromStringAndSize(value->bytes, value->length);
+		result = PyBytes_FromStringAndSize(value->bytes, value->length);
 #endif
 		return result;
 	}
@@ -1023,7 +1023,7 @@
 	if (value->typePtr == app->ByteArrayType) {
 		int size;
 		char *data = (char*)Tcl_GetByteArrayFromObj(value, &size);
-		return PyString_FromStringAndSize(data, size);
+		return PyBytes_FromStringAndSize(data, size);
 	}
 
 	if (value->typePtr == app->DoubleType) {
@@ -1092,7 +1092,7 @@
 		int size;
 		char *c;
 		c = Tcl_GetStringFromObj(value, &size);
-		return PyString_FromStringAndSize(c, size);
+		return PyBytes_FromStringAndSize(c, size);
 #endif
 	}
 
@@ -1204,19 +1204,19 @@
 		}
 
 		if (*p == '\0')
-			res = PyString_FromStringAndSize(s, (int)(p-s));
+			res = PyBytes_FromStringAndSize(s, (int)(p-s));
 		else {
 			/* Convert UTF-8 to Unicode string */
 			p = strchr(p, '\0');
 			res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
 			if (res == NULL) {
 				PyErr_Clear();
-				res = PyString_FromStringAndSize(s, (int)(p-s));
+				res = PyBytes_FromStringAndSize(s, (int)(p-s));
 			}
 		}
 #else
 		p = strchr(p, '\0');
-		res = PyString_FromStringAndSize(s, (int)(p-s));
+		res = PyBytes_FromStringAndSize(s, (int)(p-s));
 #endif
 	}
 	return res;
@@ -1370,7 +1370,7 @@
 		if (err == TCL_ERROR)
 			res = Tkinter_Error(self);
 		else
-			res = PyString_FromString(Tkapp_Result(self));
+			res = PyBytes_FromString(Tkapp_Result(self));
 		LEAVE_OVERLAP_TCL
 		ckfree(cmd);
 	}
@@ -1396,7 +1396,7 @@
 	if (err == TCL_ERROR)
 		res = Tkinter_Error(self);
 	else
-		res = PyString_FromString(Tkapp_Result(self));
+		res = PyBytes_FromString(Tkapp_Result(self));
 	LEAVE_OVERLAP_TCL
 	return res;
 }
@@ -1419,7 +1419,7 @@
 	if (err == TCL_ERROR)
 		res = Tkinter_Error(self);
 	else
-		res = PyString_FromString(Tkapp_Result(self));
+		res = PyBytes_FromString(Tkapp_Result(self));
 	LEAVE_OVERLAP_TCL
 	return res;
 }
@@ -1443,7 +1443,7 @@
 		res = Tkinter_Error(self);
 
 	else
-		res = PyString_FromString(Tkapp_Result(self));
+		res = PyBytes_FromString(Tkapp_Result(self));
 	LEAVE_OVERLAP_TCL
 	return res;
 }
@@ -1466,7 +1466,7 @@
 	if (err == TCL_ERROR)
 		res = Tkinter_Error(self);
 	else
-		res = PyString_FromString(Tkapp_Result(self));
+		res = PyBytes_FromString(Tkapp_Result(self));
 	LEAVE_OVERLAP_TCL
 	return res;
 }
@@ -1511,8 +1511,8 @@
 varname_converter(PyObject *in, void *_out)
 {
 	char **out = (char**)_out;
-	if (PyString_Check(in)) {
-		*out = PyString_AsString(in);
+	if (PyBytes_Check(in)) {
+		*out = PyBytes_AsString(in);
 		return 1;
 	}
 	if (PyTclObject_Check(in)) {
@@ -1676,7 +1676,7 @@
 			res = FromObj(self, tres);
 		}
 		else {
-			res = PyString_FromString(Tcl_GetString(tres));
+			res = PyBytes_FromString(Tcl_GetString(tres));
 		}
 	}
 	LEAVE_OVERLAP_TCL
@@ -1920,7 +1920,7 @@
 		goto finally;
 
 	for (i = 0; i < argc; i++) {
-		PyObject *s = PyString_FromString(argv[i]);
+		PyObject *s = PyBytes_FromString(argv[i]);
 		if (!s || PyTuple_SetItem(v, i, s)) {
 			Py_DECREF(v);
 			v = NULL;
@@ -1961,7 +1961,7 @@
 	PyObject *res = NULL;
 
 	if (s) {
-		res = PyString_FromString(s);
+		res = PyBytes_FromString(s);
 		ckfree(s);
 	}
 
@@ -2011,7 +2011,7 @@
 		return PythonCmd_Error(interp);
 
 	for (i = 0; i < (argc - 1); i++) {
-		PyObject *s = PyString_FromString(argv[i + 1]);
+		PyObject *s = PyBytes_FromString(argv[i + 1]);
 		if (!s || PyTuple_SetItem(arg, i, s)) {
 			Py_DECREF(arg);
 			return PythonCmd_Error(interp);
@@ -2406,7 +2406,7 @@
 
 	PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
 	                v->func == NULL ? ", handler deleted" : "");
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static PyObject *
@@ -3087,7 +3087,7 @@
 static void
 ins_string(PyObject *d, char *name, char *val)
 {
-	PyObject *v = PyString_FromString(val);
+	PyObject *v = PyBytes_FromString(val);
 	if (v) {
 		PyDict_SetItemString(d, name, v);
 		Py_DECREF(v);

Modified: python/branches/okkoto-sizeof/Modules/almodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/almodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/almodule.c	Wed Jun  4 11:24:23 2008
@@ -84,7 +84,7 @@
 			Py_INCREF(Py_None);
 			return Py_None;
 		}
-		return PyString_FromString((char *) value.ptr);
+		return PyBytes_FromString((char *) value.ptr);
 	default:
 		PyErr_SetString(ErrorObject, "unknown element type");
 		return NULL;
@@ -149,12 +149,12 @@
 			PyErr_SetString(ErrorObject, "unknown element type");
 			return -1;
 		}
-		if (!PyString_Check(value)) {
+		if (!PyBytes_Check(value)) {
 			PyErr_BadArgument();
 			return -1;
 		}
-		param->value.ptr = PyString_AS_STRING(value);
-		param->sizeIn = PyString_GET_SIZE(value)+1; /*account for NUL*/
+		param->value.ptr = PyBytes_AS_STRING(value);
+		param->sizeIn = PyBytes_GET_SIZE(value)+1; /*account for NUL*/
 		break;
 	case AL_SET_VAL:
 	case AL_VECTOR_VAL:
@@ -765,12 +765,12 @@
 		return NULL;
 	}
 	size *= ch;
-	v = PyString_FromStringAndSize((char *) NULL, size * framecount);
+	v = PyBytes_FromStringAndSize((char *) NULL, size * framecount);
 	if (v == NULL)
 		return NULL;
 
 	Py_BEGIN_ALLOW_THREADS
-	alReadFrames(self->port, (void *) PyString_AS_STRING(v), framecount);
+	alReadFrames(self->port, (void *) PyBytes_AS_STRING(v), framecount);
 	Py_END_ALLOW_THREADS
 
 	return v;
@@ -1068,12 +1068,12 @@
 	width = ALgetwidth(c);
 #endif /* AL_405 */
 	ALfreeconfig(c);
-	v = PyString_FromStringAndSize((char *)NULL, width * count);
+	v = PyBytes_FromStringAndSize((char *)NULL, width * count);
 	if (v == NULL)
 		return NULL;
 
 	Py_BEGIN_ALLOW_THREADS
-	ret = ALreadsamps(self->port, (void *) PyString_AsString(v), count);
+	ret = ALreadsamps(self->port, (void *) PyBytes_AsString(v), count);
 	Py_END_ALLOW_THREADS
 	if (ret == -1) {
 		Py_DECREF(v);
@@ -1498,7 +1498,7 @@
 			Py_INCREF(item);
 			break;
 		case AL_STRING_VAL:
-			item = PyString_FromString(pvs[i].value.ptr);
+			item = PyBytes_FromString(pvs[i].value.ptr);
 			PyMem_DEL(pvs[i].value.ptr);
 			break;
 		case AL_MATRIX_VAL:
@@ -1725,7 +1725,7 @@
 	PyDict_SetItemString(v, "elementType", item);
 	Py_DECREF(item);
 
-	item = PyString_FromString(pinfo.name);
+	item = PyBytes_FromString(pinfo.name);
 	PyDict_SetItemString(v, "name", item);
 	Py_DECREF(item);
 
@@ -1920,7 +1920,7 @@
 		return NULL;
 	if ((name = ALgetname(device, descriptor)) == NULL)
 		return NULL;
-	return PyString_FromString(name);
+	return PyBytes_FromString(name);
 }
 
 static PyObject *

Modified: python/branches/okkoto-sizeof/Modules/arraymodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/arraymodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/arraymodule.c	Wed Jun  4 11:24:23 2008
@@ -104,7 +104,7 @@
 static PyObject *
 c_getitem(arrayobject *ap, Py_ssize_t i)
 {
-	return PyString_FromStringAndSize(&((char *)ap->ob_item)[i], 1);
+	return PyBytes_FromStringAndSize(&((char *)ap->ob_item)[i], 1);
 }
 
 static int
@@ -1414,7 +1414,7 @@
 static PyObject *
 array_tostring(arrayobject *self, PyObject *unused)
 {
-	return PyString_FromStringAndSize(self->ob_item,
+	return PyBytes_FromStringAndSize(self->ob_item,
 				    Py_SIZE(self) * self->ob_descr->itemsize);
 }
 
@@ -1494,7 +1494,7 @@
 array_get_typecode(arrayobject *a, void *closure)
 {
 	char tc = a->ob_descr->typecode;
-	return PyString_FromStringAndSize(&tc, 1);
+	return PyBytes_FromStringAndSize(&tc, 1);
 }
 
 static PyObject *
@@ -1578,7 +1578,7 @@
 	typecode = a->ob_descr->typecode;
 	if (len == 0) {
 		PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode);
-		return PyString_FromString(buf);
+		return PyBytes_FromString(buf);
 	}
 		
 	if (typecode == 'c')
@@ -1593,9 +1593,9 @@
 	Py_XDECREF(v);
 
 	PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
-	s = PyString_FromString(buf);
-	PyString_ConcatAndDel(&s, t);
-	PyString_ConcatAndDel(&s, PyString_FromString(")"));
+	s = PyBytes_FromString(buf);
+	PyBytes_ConcatAndDel(&s, t);
+	PyBytes_ConcatAndDel(&s, PyBytes_FromString(")"));
 	return s;
 }
 
@@ -1881,7 +1881,7 @@
 		return NULL;
 
 	if (!(initial == NULL || PyList_Check(initial)
-	      || PyString_Check(initial) || PyTuple_Check(initial)
+	      || PyBytes_Check(initial) || PyTuple_Check(initial)
 	      || (c == 'u' && PyUnicode_Check(initial)))) {
 		it = PyObject_GetIter(initial);
 		if (it == NULL)
@@ -1924,7 +1924,7 @@
 					}
 					Py_DECREF(v);
 				}
-			} else if (initial != NULL && PyString_Check(initial)) {
+			} else if (initial != NULL && PyBytes_Check(initial)) {
 				PyObject *t_initial, *v;
 				t_initial = PyTuple_Pack(1, initial);
 				if (t_initial == NULL) {

Modified: python/branches/okkoto-sizeof/Modules/audioop.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/audioop.c	(original)
+++ python/branches/okkoto-sizeof/Modules/audioop.c	Wed Jun  4 11:24:23 2008
@@ -474,7 +474,7 @@
 
 	/* Passing a short** for an 's' argument is correct only
 	   if the string contents is aligned for interpretation
-	   as short[]. Due to the definition of PyStringObject,
+	   as short[]. Due to the definition of PyBytesObject,
 	   this is currently (Python 2.6) the case. */
         if ( !PyArg_ParseTuple(args, "s#s#:findfit",
 	                       (char**)&cp1, &len1, (char**)&cp2, &len2) )
@@ -759,10 +759,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len);
+        rv = PyBytes_FromStringAndSize(NULL, len);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
     
     
         for ( i=0; i < len; i += size ) {
@@ -801,10 +801,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len/2);
+        rv = PyBytes_FromStringAndSize(NULL, len/2);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
     
     
         for ( i=0; i < len; i += size*2 ) {
@@ -846,10 +846,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len*2);
+        rv = PyBytes_FromStringAndSize(NULL, len*2);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
     
     
         for ( i=0; i < len; i += size ) {
@@ -903,10 +903,10 @@
                 return 0;
         }
 
-        rv = PyString_FromStringAndSize(NULL, len1);
+        rv = PyBytes_FromStringAndSize(NULL, len1);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
 
         for ( i=0; i < len1; i += size ) {
                 if ( size == 1 )      val1 = (int)*CHARP(cp1, i);
@@ -949,10 +949,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len);
+        rv = PyBytes_FromStringAndSize(NULL, len);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
     
     
         for ( i=0; i < len; i += size ) {
@@ -985,10 +985,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len);
+        rv = PyBytes_FromStringAndSize(NULL, len);
         if ( rv == 0 )
                 return 0;
-        ncp = (unsigned char *)PyString_AsString(rv);
+        ncp = (unsigned char *)PyBytes_AsString(rv);
     
         for ( i=0; i < len; i += size ) {
                 if ( size == 1 )      val = ((int)*CHARP(cp, i)) << 8;
@@ -1023,10 +1023,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, (len/size)*size2);
+        rv = PyBytes_FromStringAndSize(NULL, (len/size)*size2);
         if ( rv == 0 )
                 return 0;
-        ncp = (unsigned char *)PyString_AsString(rv);
+        ncp = (unsigned char *)PyBytes_AsString(rv);
     
         for ( i=0, j=0; i < len; i += size, j += size2 ) {
                 if ( size == 1 )      val = ((int)*CHARP(cp, i)) << 8;
@@ -1157,7 +1157,7 @@
                     nbytes / bytes_per_frame != ceiling)
                         str = NULL;
                 else
-                        str = PyString_FromStringAndSize(NULL, nbytes);
+                        str = PyBytes_FromStringAndSize(NULL, nbytes);
 
                 if (str == NULL) {
                         PyErr_SetString(PyExc_MemoryError,
@@ -1165,7 +1165,7 @@
                         goto exit;
                 }
         }
-        ncp = PyString_AsString(str);
+        ncp = PyBytes_AsString(str);
 
         for (;;) {
                 while (d < 0) {
@@ -1182,13 +1182,13 @@
                                         goto exit;
                                 /* We have checked before that the length
                                  * of the string fits into int. */
-                                len = (int)(ncp - PyString_AsString(str));
+                                len = (int)(ncp - PyBytes_AsString(str));
                                 if (len == 0) {
                                         /*don't want to resize to zero length*/
-                                        rv = PyString_FromStringAndSize("", 0);
+                                        rv = PyBytes_FromStringAndSize("", 0);
                                         Py_DECREF(str);
                                         str = rv;
-                                } else if (_PyString_Resize(&str, len) < 0)
+                                } else if (_PyBytes_Resize(&str, len) < 0)
                                         goto exit;
                                 rv = Py_BuildValue("(O(iO))", str, d, samps);
                                 Py_DECREF(samps);
@@ -1255,10 +1255,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len/size);
+        rv = PyBytes_FromStringAndSize(NULL, len/size);
         if ( rv == 0 )
                 return 0;
-        ncp = (unsigned char *)PyString_AsString(rv);
+        ncp = (unsigned char *)PyBytes_AsString(rv);
     
         for ( i=0; i < len; i += size ) {
                 if ( size == 1 )      val = ((int)*CHARP(cp, i)) << 8;
@@ -1289,10 +1289,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len*size);
+        rv = PyBytes_FromStringAndSize(NULL, len*size);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
     
         for ( i=0; i < len*size; i += size ) {
                 cval = *cp++;
@@ -1323,10 +1323,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len/size);
+        rv = PyBytes_FromStringAndSize(NULL, len/size);
         if ( rv == 0 )
                 return 0;
-        ncp = (unsigned char *)PyString_AsString(rv);
+        ncp = (unsigned char *)PyBytes_AsString(rv);
     
         for ( i=0; i < len; i += size ) {
                 if ( size == 1 )      val = ((int)*CHARP(cp, i)) << 8;
@@ -1357,10 +1357,10 @@
                 return 0;
         }
     
-        rv = PyString_FromStringAndSize(NULL, len*size);
+        rv = PyBytes_FromStringAndSize(NULL, len*size);
         if ( rv == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(rv);
+        ncp = (signed char *)PyBytes_AsString(rv);
     
         for ( i=0; i < len*size; i += size ) {
                 cval = *cp++;
@@ -1393,10 +1393,10 @@
                 return 0;
         }
     
-        str = PyString_FromStringAndSize(NULL, len/(size*2));
+        str = PyBytes_FromStringAndSize(NULL, len/(size*2));
         if ( str == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(str);
+        ncp = (signed char *)PyBytes_AsString(str);
 
         /* Decode state, should have (value, step) */
         if ( state == Py_None ) {
@@ -1509,10 +1509,10 @@
         } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
                 return 0;
     
-        str = PyString_FromStringAndSize(NULL, len*size*2);
+        str = PyBytes_FromStringAndSize(NULL, len*size*2);
         if ( str == 0 )
                 return 0;
-        ncp = (signed char *)PyString_AsString(str);
+        ncp = (signed char *)PyBytes_AsString(str);
 
         step = stepsizeTable[index];
         bufferstep = 0;

Modified: python/branches/okkoto-sizeof/Modules/binascii.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/binascii.c	(original)
+++ python/branches/okkoto-sizeof/Modules/binascii.c	Wed Jun  4 11:24:23 2008
@@ -141,7 +141,7 @@
 #define BASE64_PAD '='
 
 /* Max binary chunk size; limited only by available memory */
-#define BASE64_MAXBIN (INT_MAX/2 - sizeof(PyStringObject) - 3)
+#define BASE64_MAXBIN (INT_MAX/2 - sizeof(PyBytesObject) - 3)
 
 static unsigned char table_b2a_base64[] =
 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -203,9 +203,9 @@
 	ascii_len--;
 
 	/* Allocate the buffer */
-	if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL )
 		return NULL;
-	bin_data = (unsigned char *)PyString_AsString(rv);
+	bin_data = (unsigned char *)PyBytes_AsString(rv);
 
 	for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) {
 		/* XXX is it really best to add NULs if there's no more data */
@@ -280,9 +280,9 @@
 	}
 
 	/* We're lazy and allocate to much (fixed up later) */
-	if ( (rv=PyString_FromStringAndSize(NULL, bin_len*2+2)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2+2)) == NULL )
 		return NULL;
-	ascii_data = (unsigned char *)PyString_AsString(rv);
+	ascii_data = (unsigned char *)PyBytes_AsString(rv);
 
 	/* Store the length */
 	*ascii_data++ = ' ' + (bin_len & 077);
@@ -304,8 +304,8 @@
 	}
 	*ascii_data++ = '\n';	/* Append a courtesy newline */
 
-	_PyString_Resize(&rv, (ascii_data -
-			       (unsigned char *)PyString_AsString(rv)));
+	_PyBytes_Resize(&rv, (ascii_data -
+			       (unsigned char *)PyBytes_AsString(rv)));
 	return rv;
 }
 
@@ -354,9 +354,9 @@
 	bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
 
 	/* Allocate the buffer */
-	if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL )
 		return NULL;
-	bin_data = (unsigned char *)PyString_AsString(rv);
+	bin_data = (unsigned char *)PyBytes_AsString(rv);
 	bin_len = 0;
 
 	for( ; ascii_len > 0; ascii_len--, ascii_data++) {
@@ -415,13 +415,13 @@
 
 	/* And set string size correctly. If the result string is empty
 	** (because the input was all invalid) return the shared empty
-	** string instead; _PyString_Resize() won't do this for us.
+	** string instead; _PyBytes_Resize() won't do this for us.
 	*/
 	if (bin_len > 0)
-		_PyString_Resize(&rv, bin_len);
+		_PyBytes_Resize(&rv, bin_len);
 	else {
 		Py_DECREF(rv);
-		rv = PyString_FromString("");
+		rv = PyBytes_FromString("");
 	}
 	return rv;
 }
@@ -448,9 +448,9 @@
 	/* We're lazy and allocate too much (fixed up later).
 	   "+3" leaves room for up to two pad characters and a trailing
 	   newline.  Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */
-	if ( (rv=PyString_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL )
 		return NULL;
-	ascii_data = (unsigned char *)PyString_AsString(rv);
+	ascii_data = (unsigned char *)PyBytes_AsString(rv);
 
 	for( ; bin_len > 0 ; bin_len--, bin_data++ ) {
 		/* Shift the data into our buffer */
@@ -474,8 +474,8 @@
 	}
 	*ascii_data++ = '\n';	/* Append a courtesy newline */
 
-	_PyString_Resize(&rv, (ascii_data -
-			       (unsigned char *)PyString_AsString(rv)));
+	_PyBytes_Resize(&rv, (ascii_data -
+			       (unsigned char *)PyBytes_AsString(rv)));
 	return rv;
 }
 
@@ -498,9 +498,9 @@
 	/* Allocate a string that is too big (fixed later) 
 	   Add two to the initial length to prevent interning which
 	   would preclude subsequent resizing.  */
-	if ( (rv=PyString_FromStringAndSize(NULL, len+2)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL )
 		return NULL;
-	bin_data = (unsigned char *)PyString_AsString(rv);
+	bin_data = (unsigned char *)PyBytes_AsString(rv);
 
 	for( ; len > 0 ; len--, ascii_data++ ) {
 		/* Get the byte and look it up */
@@ -534,8 +534,8 @@
 		Py_DECREF(rv);
 		return NULL;
 	}
-	_PyString_Resize(
-		&rv, (bin_data - (unsigned char *)PyString_AsString(rv)));
+	_PyBytes_Resize(
+		&rv, (bin_data - (unsigned char *)PyBytes_AsString(rv)));
 	if (rv) {
 		PyObject *rrv = Py_BuildValue("Oi", rv, done);
 		Py_DECREF(rv);
@@ -559,9 +559,9 @@
 		return NULL;
 
 	/* Worst case: output is twice as big as input (fixed later) */
-	if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL )
 		return NULL;
-	out_data = (unsigned char *)PyString_AsString(rv);
+	out_data = (unsigned char *)PyBytes_AsString(rv);
 
 	for( in=0; in<len; in++) {
 		ch = in_data[in];
@@ -587,8 +587,8 @@
 			}
 		}
 	}
-	_PyString_Resize(&rv, (out_data -
-			       (unsigned char *)PyString_AsString(rv)));
+	_PyBytes_Resize(&rv, (out_data -
+			       (unsigned char *)PyBytes_AsString(rv)));
 	return rv;
 }
 
@@ -608,9 +608,9 @@
 		return NULL;
 
 	/* Allocate a buffer that is at least large enough */
-	if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL )
 		return NULL;
-	ascii_data = (unsigned char *)PyString_AsString(rv);
+	ascii_data = (unsigned char *)PyBytes_AsString(rv);
 
 	for( ; len > 0 ; len--, bin_data++ ) {
 		/* Shift into our buffer, and output any 6bits ready */
@@ -627,8 +627,8 @@
 		leftchar <<= (6-leftbits);
 		*ascii_data++ = table_b2a_hqx[leftchar & 0x3f];
 	}
-	_PyString_Resize(&rv, (ascii_data -
-			       (unsigned char *)PyString_AsString(rv)));
+	_PyBytes_Resize(&rv, (ascii_data -
+			       (unsigned char *)PyBytes_AsString(rv)));
 	return rv;
 }
 
@@ -647,14 +647,14 @@
 
 	/* Empty string is a special case */
 	if ( in_len == 0 )
-		return PyString_FromString("");
+		return PyBytes_FromString("");
 
 	/* Allocate a buffer of reasonable size. Resized when needed */
 	out_len = in_len*2;
-	if ( (rv=PyString_FromStringAndSize(NULL, out_len)) == NULL )
+	if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL )
 		return NULL;
 	out_len_left = out_len;
-	out_data = (unsigned char *)PyString_AsString(rv);
+	out_data = (unsigned char *)PyBytes_AsString(rv);
 
 	/*
 	** We need two macros here to get/put bytes and handle
@@ -673,9 +673,9 @@
 #define OUTBYTE(b) \
 	do { \
 		 if ( --out_len_left < 0 ) { \
-			  _PyString_Resize(&rv, 2*out_len); \
+			  _PyBytes_Resize(&rv, 2*out_len); \
 			  if ( rv == NULL ) return NULL; \
-			  out_data = (unsigned char *)PyString_AsString(rv) \
+			  out_data = (unsigned char *)PyBytes_AsString(rv) \
 								 + out_len; \
 			  out_len_left = out_len-1; \
 			  out_len = out_len * 2; \
@@ -723,8 +723,8 @@
 			OUTBYTE(in_byte);
 		}
 	}
-	_PyString_Resize(&rv, (out_data -
-			       (unsigned char *)PyString_AsString(rv)));
+	_PyBytes_Resize(&rv, (out_data -
+			       (unsigned char *)PyBytes_AsString(rv)));
 	return rv;
 }
 
@@ -923,10 +923,10 @@
 	if (!PyArg_ParseTuple(args, "s#:b2a_hex", &argbuf, &arglen))
 		return NULL;
 
-	retval = PyString_FromStringAndSize(NULL, arglen*2);
+	retval = PyBytes_FromStringAndSize(NULL, arglen*2);
 	if (!retval)
 		return NULL;
-	retbuf = PyString_AsString(retval);
+	retbuf = PyBytes_AsString(retval);
 	if (!retbuf)
 		goto finally;
 
@@ -989,10 +989,10 @@
 		return NULL;
 	}
 
-	retval = PyString_FromStringAndSize(NULL, (arglen/2));
+	retval = PyBytes_FromStringAndSize(NULL, (arglen/2));
 	if (!retval)
 		return NULL;
-	retbuf = PyString_AsString(retval);
+	retbuf = PyBytes_AsString(retval);
 	if (!retbuf)
 		goto finally;
 
@@ -1106,7 +1106,7 @@
 			out++;
 		}
 	}
-	if ((rv = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
+	if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
 		PyMem_Free(odata);
 		return NULL;
 	}
@@ -1306,7 +1306,7 @@
 			}
 		}
 	}
-	if ((rv = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
+	if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
 		PyMem_Free(odata);
 		return NULL;
 	}
@@ -1354,7 +1354,7 @@
 		return;
 
 	d = PyModule_GetDict(m);
-	x = PyString_FromString(doc_binascii);
+	x = PyBytes_FromString(doc_binascii);
 	PyDict_SetItemString(d, "__doc__", x);
 	Py_XDECREF(x);
 

Modified: python/branches/okkoto-sizeof/Modules/bsddb.h
==============================================================================
--- python/branches/okkoto-sizeof/Modules/bsddb.h	(original)
+++ python/branches/okkoto-sizeof/Modules/bsddb.h	Wed Jun  4 11:24:23 2008
@@ -105,7 +105,7 @@
 #error "eek! DBVER can't handle minor versions > 9"
 #endif
 
-#define PY_BSDDB_VERSION "4.6.5devel2"
+#define PY_BSDDB_VERSION "4.7.0"
 
 /* Python object definitions */
 

Modified: python/branches/okkoto-sizeof/Modules/bsddbmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/bsddbmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/bsddbmodule.c	Wed Jun  4 11:24:23 2008
@@ -312,7 +312,7 @@
 		return NULL;
 	}
 
-	result = PyString_FromStringAndSize(data, (int)drec.size);
+	result = PyBytes_FromStringAndSize(data, (int)drec.size);
 	if (data != buf) free(data);
 	return result;
 }
@@ -424,7 +424,7 @@
 		if (dp->di_type == DB_RECNO)
 			item = PyInt_FromLong(*((int*)data));
 		else
-			item = PyString_FromStringAndSize(data,
+			item = PyBytes_FromStringAndSize(data,
 							  (int)krec.size);
 		if (data != buf) free(data);
 		if (item == NULL) {

Modified: python/branches/okkoto-sizeof/Modules/bz2module.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/bz2module.c	(original)
+++ python/branches/okkoto-sizeof/Modules/bz2module.c	Wed Jun  4 11:24:23 2008
@@ -34,7 +34,7 @@
 #error "Large file support, but neither off_t nor fpos_t is large enough."
 #endif
 
-#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
+#define BUF(v) PyBytes_AS_STRING((PyBytesObject *)v)
 
 #define MODE_CLOSED   0
 #define MODE_READ     1
@@ -241,7 +241,7 @@
 	int univ_newline = f->f_univ_newline;
 
 	total_v_size = n > 0 ? n : 100;
-	v = PyString_FromStringAndSize((char *)NULL, total_v_size);
+	v = PyBytes_FromStringAndSize((char *)NULL, total_v_size);
 	if (v == NULL)
 		return NULL;
 
@@ -307,7 +307,7 @@
 			Py_DECREF(v);
 			return NULL;
 		}
-		if (_PyString_Resize(&v, total_v_size) < 0)
+		if (_PyBytes_Resize(&v, total_v_size) < 0)
 			return NULL;
 		buf = BUF(v) + used_v_size;
 		end = BUF(v) + total_v_size;
@@ -315,7 +315,7 @@
 
 	used_v_size = buf - BUF(v);
 	if (used_v_size != total_v_size)
-		_PyString_Resize(&v, used_v_size);
+		_PyBytes_Resize(&v, used_v_size);
 	return v;
 }
 
@@ -438,10 +438,10 @@
 
 /* This is a hacked version of Python's
  * fileobject.c:readahead_get_line_skip(). */
-static PyStringObject *
+static PyBytesObject *
 Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize)
 {
-	PyStringObject* s;
+	PyBytesObject* s;
 	char *bufptr;
 	char *buf;
 	int len;
@@ -452,17 +452,17 @@
 
 	len = f->f_bufend - f->f_bufptr;
 	if (len == 0)
-		return (PyStringObject *)
-			PyString_FromStringAndSize(NULL, skip);
+		return (PyBytesObject *)
+			PyBytes_FromStringAndSize(NULL, skip);
 	bufptr = memchr(f->f_bufptr, '\n', len);
 	if (bufptr != NULL) {
 		bufptr++;			/* Count the '\n' */
 		len = bufptr - f->f_bufptr;
-		s = (PyStringObject *)
-			PyString_FromStringAndSize(NULL, skip+len);
+		s = (PyBytesObject *)
+			PyBytes_FromStringAndSize(NULL, skip+len);
 		if (s == NULL)
 			return NULL;
-		memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
+		memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len);
 		f->f_bufptr = bufptr;
 		if (bufptr == f->f_bufend)
 			Util_DropReadAhead(f);
@@ -476,7 +476,7 @@
 		        PyMem_Free(buf);
 			return NULL;
 		}
-		memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
+		memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len);
 		PyMem_Free(buf);
 	}
 	return s;
@@ -509,7 +509,7 @@
 		case MODE_READ:
 			break;
 		case MODE_READ_EOF:
-			ret = PyString_FromString("");
+			ret = PyBytes_FromString("");
 			goto cleanup;
 		case MODE_CLOSED:
 			PyErr_SetString(PyExc_ValueError,
@@ -531,7 +531,7 @@
 				"more than a Python string can hold");
 		goto cleanup;
 	}
-	ret = PyString_FromStringAndSize((char *)NULL, buffersize);
+	ret = PyBytes_FromStringAndSize((char *)NULL, buffersize);
 	if (ret == NULL)
 		goto cleanup;
 	bytesread = 0;
@@ -557,14 +557,14 @@
 		}
 		if (bytesrequested < 0) {
 			buffersize = Util_NewBufferSize(buffersize);
-			if (_PyString_Resize(&ret, buffersize) < 0)
+			if (_PyBytes_Resize(&ret, buffersize) < 0)
 				goto cleanup;
 		} else {
 			break;
 		}
 	}
 	if (bytesread != buffersize)
-		_PyString_Resize(&ret, bytesread);
+		_PyBytes_Resize(&ret, bytesread);
 
 cleanup:
 	RELEASE_LOCK(self);
@@ -594,7 +594,7 @@
 		case MODE_READ:
 			break;
 		case MODE_READ_EOF:
-			ret = PyString_FromString("");
+			ret = PyBytes_FromString("");
 			goto cleanup;
 		case MODE_CLOSED:
 			PyErr_SetString(PyExc_ValueError,
@@ -607,7 +607,7 @@
 	}
 
 	if (sizehint == 0)
-		ret = PyString_FromString("");
+		ret = PyBytes_FromString("");
 	else
 		ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint);
 
@@ -701,17 +701,17 @@
 			}
 			if (big_buffer == NULL) {
 				/* Create the big buffer */
-				big_buffer = PyString_FromStringAndSize(
+				big_buffer = PyBytes_FromStringAndSize(
 					NULL, buffersize);
 				if (big_buffer == NULL)
 					goto error;
-				buffer = PyString_AS_STRING(big_buffer);
+				buffer = PyBytes_AS_STRING(big_buffer);
 				memcpy(buffer, small_buffer, nfilled);
 			}
 			else {
 				/* Grow the big buffer */
-				_PyString_Resize(&big_buffer, buffersize);
-				buffer = PyString_AS_STRING(big_buffer);
+				_PyBytes_Resize(&big_buffer, buffersize);
+				buffer = PyBytes_AS_STRING(big_buffer);
 			}
 			continue;			
 		}
@@ -720,7 +720,7 @@
 		while (p != NULL) {
 			/* Process complete lines */
 			p++;
-			line = PyString_FromStringAndSize(q, p-q);
+			line = PyBytes_FromStringAndSize(q, p-q);
 			if (line == NULL)
 				goto error;
 			err = PyList_Append(list, line);
@@ -743,7 +743,7 @@
 	}
 	if (nfilled != 0) {
 		/* Partial last line */
-		line = PyString_FromStringAndSize(buffer, nfilled);
+		line = PyBytes_FromStringAndSize(buffer, nfilled);
 		if (line == NULL)
 			goto error;
 		if (sizehint > 0) {
@@ -753,7 +753,7 @@
 				Py_DECREF(line);
 				goto error;
 			}
-			PyString_Concat(&line, rest);
+			PyBytes_Concat(&line, rest);
 			Py_DECREF(rest);
 			if (line == NULL)
 				goto error;
@@ -915,7 +915,7 @@
 		   could potentially execute Python code. */
 		for (i = 0; i < j; i++) {
 			PyObject *v = PyList_GET_ITEM(list, i);
-			if (!PyString_Check(v)) {
+			if (!PyBytes_Check(v)) {
 			    	const char *buffer;
 			    	Py_ssize_t len;
 				if (PyObject_AsCharBuffer(v, &buffer, &len)) {
@@ -926,7 +926,7 @@
 							"strings");
 					goto error;
 				}
-				line = PyString_FromStringAndSize(buffer,
+				line = PyBytes_FromStringAndSize(buffer,
 								  len);
 				if (line == NULL)
 					goto error;
@@ -942,9 +942,9 @@
 		Py_BEGIN_ALLOW_THREADS
 		for (i = 0; i < j; i++) {
 		    	line = PyList_GET_ITEM(list, i);
-			len = PyString_GET_SIZE(line);
+			len = PyBytes_GET_SIZE(line);
 			BZ2_bzWrite (&bzerror, self->fp,
-				     PyString_AS_STRING(line), len);
+				     PyBytes_AS_STRING(line), len);
 			if (bzerror != BZ_OK) {
 				Py_BLOCK_THREADS
 				Util_CatchBZ2Error(bzerror);
@@ -1224,13 +1224,13 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	case NEWLINE_CR:
-		return PyString_FromString("\r");
+		return PyBytes_FromString("\r");
 	case NEWLINE_LF:
-		return PyString_FromString("\n");
+		return PyBytes_FromString("\n");
 	case NEWLINE_CR|NEWLINE_LF:
 		return Py_BuildValue("(ss)", "\r", "\n");
 	case NEWLINE_CRLF:
-		return PyString_FromString("\r\n");
+		return PyBytes_FromString("\r\n");
 	case NEWLINE_CR|NEWLINE_CRLF:
 		return Py_BuildValue("(ss)", "\r", "\r\n");
 	case NEWLINE_LF|NEWLINE_CRLF:
@@ -1448,7 +1448,7 @@
 static PyObject *
 BZ2File_iternext(BZ2FileObject *self)
 {
-	PyStringObject* ret;
+	PyBytesObject* ret;
 	ACQUIRE_LOCK(self);
 	if (self->mode == MODE_CLOSED) {
 		PyErr_SetString(PyExc_ValueError,
@@ -1457,7 +1457,7 @@
 	}
 	ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE);
 	RELEASE_LOCK(self);
-	if (ret == NULL || PyString_GET_SIZE(ret) == 0) {
+	if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) {
 		Py_XDECREF(ret);
 		return NULL;
 	}
@@ -1559,7 +1559,7 @@
 		return NULL;
 
 	if (datasize == 0)
-		return PyString_FromString("");
+		return PyBytes_FromString("");
 
 	ACQUIRE_LOCK(self);
 	if (!self->running) {
@@ -1568,7 +1568,7 @@
 		goto error;
 	}
 
-	ret = PyString_FromStringAndSize(NULL, bufsize);
+	ret = PyBytes_FromStringAndSize(NULL, bufsize);
 	if (!ret)
 		goto error;
 
@@ -1591,7 +1591,7 @@
 			break; /* no more input data */
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
-			if (_PyString_Resize(&ret, bufsize) < 0) {
+			if (_PyBytes_Resize(&ret, bufsize) < 0) {
 				BZ2_bzCompressEnd(bzs);
 				goto error;
 			}
@@ -1601,7 +1601,7 @@
 		}
 	}
 
-	_PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+	_PyBytes_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
 
 	RELEASE_LOCK(self);
 	return ret;
@@ -1636,7 +1636,7 @@
 	}
 	self->running = 0;
 
-	ret = PyString_FromStringAndSize(NULL, bufsize);
+	ret = PyBytes_FromStringAndSize(NULL, bufsize);
 	if (!ret)
 		goto error;
 
@@ -1657,7 +1657,7 @@
 		}
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
-			if (_PyString_Resize(&ret, bufsize) < 0)
+			if (_PyBytes_Resize(&ret, bufsize) < 0)
 				goto error;
 			bzs->next_out = BUF(ret);
 			bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
@@ -1667,7 +1667,7 @@
 	}
 
 	if (bzs->avail_out != 0)
-		_PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+		_PyBytes_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
 
 	RELEASE_LOCK(self);
 	return ret;
@@ -1849,7 +1849,7 @@
 		goto error;
 	}
 
-	ret = PyString_FromStringAndSize(NULL, bufsize);
+	ret = PyBytes_FromStringAndSize(NULL, bufsize);
 	if (!ret)
 		goto error;
 
@@ -1868,7 +1868,7 @@
 			if (bzs->avail_in != 0) {
 				Py_DECREF(self->unused_data);
 				self->unused_data =
-				    PyString_FromStringAndSize(bzs->next_in,
+				    PyBytes_FromStringAndSize(bzs->next_in,
 							       bzs->avail_in);
 			}
 			self->running = 0;
@@ -1882,7 +1882,7 @@
 			break; /* no more input data */
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
-			if (_PyString_Resize(&ret, bufsize) < 0) {
+			if (_PyBytes_Resize(&ret, bufsize) < 0) {
 				BZ2_bzDecompressEnd(bzs);
 				goto error;
 			}
@@ -1894,7 +1894,7 @@
 	}
 
 	if (bzs->avail_out != 0)
-		_PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+		_PyBytes_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
 
 	RELEASE_LOCK(self);
 	return ret;
@@ -1930,7 +1930,7 @@
 	}
 #endif
 
-	self->unused_data = PyString_FromString("");
+	self->unused_data = PyBytes_FromString("");
 	if (!self->unused_data)
 		goto error;
 
@@ -2063,7 +2063,7 @@
 	 * data in one shot. We will check it later anyway. */
 	bufsize = datasize + (datasize/100+1) + 600;
 
-	ret = PyString_FromStringAndSize(NULL, bufsize);
+	ret = PyBytes_FromStringAndSize(NULL, bufsize);
 	if (!ret)
 		return NULL;
 
@@ -2095,7 +2095,7 @@
 		}
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
-			if (_PyString_Resize(&ret, bufsize) < 0) {
+			if (_PyBytes_Resize(&ret, bufsize) < 0) {
 				BZ2_bzCompressEnd(bzs);
 				Py_DECREF(ret);
 				return NULL;
@@ -2106,7 +2106,7 @@
 	}
 
 	if (bzs->avail_out != 0)
-		_PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
+		_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
 	BZ2_bzCompressEnd(bzs);
 
 	return ret;
@@ -2134,9 +2134,9 @@
 		return NULL;
 
 	if (datasize == 0)
-		return PyString_FromString("");
+		return PyBytes_FromString("");
 
-	ret = PyString_FromStringAndSize(NULL, bufsize);
+	ret = PyBytes_FromStringAndSize(NULL, bufsize);
 	if (!ret)
 		return NULL;
 
@@ -2175,7 +2175,7 @@
 		}
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
-			if (_PyString_Resize(&ret, bufsize) < 0) {
+			if (_PyBytes_Resize(&ret, bufsize) < 0) {
 				BZ2_bzDecompressEnd(bzs);
 				Py_DECREF(ret);
 				return NULL;
@@ -2186,7 +2186,7 @@
 	}
 
 	if (bzs->avail_out != 0)
-		_PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
+		_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
 	BZ2_bzDecompressEnd(bzs);
 
 	return ret;
@@ -2223,7 +2223,7 @@
 	if (m == NULL)
 		return;
 
-	PyModule_AddObject(m, "__author__", PyString_FromString(__author__));
+	PyModule_AddObject(m, "__author__", PyBytes_FromString(__author__));
 
 	Py_INCREF(&BZ2File_Type);
 	PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type);

Modified: python/branches/okkoto-sizeof/Modules/cPickle.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cPickle.c	(original)
+++ python/branches/okkoto-sizeof/Modules/cPickle.c	Wed Jun  4 11:24:23 2008
@@ -105,18 +105,18 @@
 /* As the name says, an empty tuple. */
 static PyObject *empty_tuple;
 
-/* copyreg.dispatch_table, {type_object: pickling_function} */
+/* copy_reg.dispatch_table, {type_object: pickling_function} */
 static PyObject *dispatch_table;
 
 /* For EXT[124] opcodes. */
-/* copyreg._extension_registry, {(module_name, function_name): code} */
+/* copy_reg._extension_registry, {(module_name, function_name): code} */
 static PyObject *extension_registry;
-/* copyreg._inverted_registry, {code: (module_name, function_name)} */
+/* copy_reg._inverted_registry, {code: (module_name, function_name)} */
 static PyObject *inverted_registry;
-/* copyreg._extension_cache, {code: object} */
+/* copy_reg._extension_cache, {code: object} */
 static PyObject *extension_cache;
 
-/* For looking up name pairs in copyreg._extension_registry. */
+/* For looking up name pairs in copy_reg._extension_registry. */
 static PyObject *two_tuple;
 
 static PyObject *__class___str, *__getinitargs___str, *__dict___str,
@@ -393,13 +393,13 @@
 	if (format) args = Py_VaBuildValue(format, va);
 	va_end(va);
 	if (format && ! args) return NULL;
-	if (stringformat && !(retval=PyString_FromString(stringformat)))
+	if (stringformat && !(retval=PyBytes_FromString(stringformat)))
 		return NULL;
 
 	if (retval) {
 		if (args) {
 			PyObject *v;
-			v=PyString_Format(retval, args);
+			v=PyBytes_Format(retval, args);
 			Py_DECREF(retval);
 			Py_DECREF(args);
 			if (! v) return NULL;
@@ -477,7 +477,7 @@
 	n = (int)_n;
 	if (s == NULL) {
 		if (!( self->buf_size ))  return 0;
-		py_str = PyString_FromStringAndSize(self->write_buf,
+		py_str = PyBytes_FromStringAndSize(self->write_buf,
 						    self->buf_size);
 		if (!py_str)
 			return -1;
@@ -490,7 +490,7 @@
 
 		if (n > WRITE_BUF_SIZE) {
 			if (!( py_str =
-			       PyString_FromStringAndSize(s, n)))
+			       PyBytes_FromStringAndSize(s, n)))
 				return -1;
 		}
 		else {
@@ -655,7 +655,7 @@
 	Py_XDECREF(self->last_string);
 	self->last_string = str;
 
-	if (! (*s = PyString_AsString(str))) return -1;
+	if (! (*s = PyBytes_AsString(str))) return -1;
 	return n;
 }
 
@@ -670,13 +670,13 @@
 		return -1;
 	}
 
-	if ((str_size = PyString_Size(str)) < 0)
+	if ((str_size = PyBytes_Size(str)) < 0)
 		return -1;
 
 	Py_XDECREF(self->last_string);
 	self->last_string = str;
 
-	if (! (*s = PyString_AsString(str)))
+	if (! (*s = PyBytes_AsString(str)))
 		return -1;
 
 	return str_size;
@@ -1078,9 +1078,9 @@
 				"to pickle");
 			goto finally;
 		}
-		repr = PyString_FromStringAndSize(NULL, (int)nbytes);
+		repr = PyBytes_FromStringAndSize(NULL, (int)nbytes);
 		if (repr == NULL) goto finally;
-		pdata = (unsigned char *)PyString_AS_STRING(repr);
+		pdata = (unsigned char *)PyBytes_AS_STRING(repr);
 		i = _PyLong_AsByteArray((PyLongObject *)args,
 	 			pdata, nbytes,
 				1 /* little endian */, 1 /* signed */);
@@ -1121,14 +1121,14 @@
 	if (!( repr = PyObject_Repr(args)))
 		goto finally;
 
-	if ((size = PyString_Size(repr)) < 0)
+	if ((size = PyBytes_Size(repr)) < 0)
 		goto finally;
 
 	if (self->write_func(self, &l, 1) < 0)
 		goto finally;
 
 	if (self->write_func(self,
-			     PyString_AS_STRING((PyStringObject *)repr),
+			     PyBytes_AS_STRING((PyBytesObject *)repr),
 			     			size) < 0)
 		goto finally;
 
@@ -1177,7 +1177,7 @@
 	int size, len;
 	PyObject *repr=0;
 
-	if ((size = PyString_Size(args)) < 0)
+	if ((size = PyBytes_Size(args)) < 0)
 		return -1;
 
 	if (!self->bin) {
@@ -1188,9 +1188,9 @@
 		if (!( repr = PyObject_Repr(args)))
 			return -1;
 
-		if ((len = PyString_Size(repr)) < 0)
+		if ((len = PyBytes_Size(repr)) < 0)
 			goto err;
-		repr_str = PyString_AS_STRING((PyStringObject *)repr);
+		repr_str = PyBytes_AS_STRING((PyBytesObject *)repr);
 
 		if (self->write_func(self, &string, 1) < 0)
 			goto err;
@@ -1207,7 +1207,7 @@
 		int i;
 		char c_str[5];
 
-		if ((size = PyString_Size(args)) < 0)
+		if ((size = PyBytes_Size(args)) < 0)
 			return -1;
 
 		if (size < 256) {
@@ -1233,8 +1233,8 @@
 		}
 		else {
 			if (self->write_func(self,
-					     PyString_AS_STRING(
-					     	(PyStringObject *)args),
+					     PyBytes_AS_STRING(
+					     	(PyBytesObject *)args),
 					     size) < 0)
 				return -1;
 		}
@@ -1264,13 +1264,13 @@
 
 	static const char *hexdigit = "0123456789ABCDEF";
 
-	repr = PyString_FromStringAndSize(NULL, 6 * size);
+	repr = PyBytes_FromStringAndSize(NULL, 6 * size);
 	if (repr == NULL)
 		return NULL;
 	if (size == 0)
 		return repr;
 
-	p = q = PyString_AS_STRING(repr);
+	p = q = PyBytes_AS_STRING(repr);
 	while (size-- > 0) {
 		Py_UNICODE ch = *s++;
 		/* Map 16-bit characters to '\uxxxx' */
@@ -1287,7 +1287,7 @@
 			*p++ = (char) ch;
 	}
 	*p = '\0';
-	_PyString_Resize(&repr, p - q);
+	_PyBytes_Resize(&repr, p - q);
 	return repr;
 }
 
@@ -1310,9 +1310,9 @@
 		if (!repr)
 			return -1;
 
-		if ((len = PyString_Size(repr)) < 0)
+		if ((len = PyBytes_Size(repr)) < 0)
 			goto err;
-		repr_str = PyString_AS_STRING((PyStringObject *)repr);
+		repr_str = PyBytes_AS_STRING((PyBytesObject *)repr);
 
 		if (self->write_func(self, &string, 1) < 0)
 			goto err;
@@ -1332,7 +1332,7 @@
 		if (!( repr = PyUnicode_AsUTF8String(args)))
 			return -1;
 
-		if ((size = PyString_Size(repr)) < 0)
+		if ((size = PyBytes_Size(repr)) < 0)
 			goto err;
 		if (size > INT_MAX)
 			return -1;   /* string too large */
@@ -1351,7 +1351,7 @@
 			PDATA_APPEND(self->file, repr, -1);
 		}
 		else {
-			if (self->write_func(self, PyString_AS_STRING(repr),
+			if (self->write_func(self, PyBytes_AS_STRING(repr),
 					     size) < 0)
 				goto err;
 		}
@@ -1861,12 +1861,12 @@
 			goto finally;
 
 
-		if ((module_size = PyString_Size(module)) < 0 ||
-		    (name_size = PyString_Size(name)) < 0)
+		if ((module_size = PyBytes_Size(module)) < 0 ||
+		    (name_size = PyBytes_Size(name)) < 0)
 			goto finally;
 
-		module_str = PyString_AS_STRING((PyStringObject *)module);
-		name_str   = PyString_AS_STRING((PyStringObject *)name);
+		module_str = PyBytes_AS_STRING((PyBytesObject *)module);
+		name_str   = PyBytes_AS_STRING((PyBytesObject *)name);
 
 		if (self->write_func(self, &inst, 1) < 0)
 			goto finally;
@@ -1961,12 +1961,12 @@
 	if (!( module = whichmodule(args, global_name)))
 		goto finally;
 
-	if ((module_size = PyString_Size(module)) < 0 ||
-	    (name_size = PyString_Size(global_name)) < 0)
+	if ((module_size = PyBytes_Size(module)) < 0 ||
+	    (name_size = PyBytes_Size(global_name)) < 0)
 		goto finally;
 
-	module_str = PyString_AS_STRING((PyStringObject *)module);
-	name_str   = PyString_AS_STRING((PyStringObject *)global_name);
+	module_str = PyBytes_AS_STRING((PyBytesObject *)module);
+	name_str   = PyBytes_AS_STRING((PyBytesObject *)global_name);
 
 	/* XXX This can be doing a relative import.  Clearly it shouldn't,
 	   but I don't know how to stop it. :-( */
@@ -2099,7 +2099,7 @@
 
 	if (pid != Py_None) {
 		if (!self->bin) {
-			if (!PyString_Check(pid)) {
+			if (!PyBytes_Check(pid)) {
 				PyErr_SetString(PicklingError,
 						"persistent id must be string");
 				goto finally;
@@ -2108,12 +2108,12 @@
 			if (self->write_func(self, &persid, 1) < 0)
 				goto finally;
 
-			if ((size = PyString_Size(pid)) < 0)
+			if ((size = PyBytes_Size(pid)) < 0)
 				goto finally;
 
 			if (self->write_func(self,
-					     PyString_AS_STRING(
-					     	(PyStringObject *)pid),
+					     PyBytes_AS_STRING(
+					     	(PyBytesObject *)pid),
 					     size) < 0)
 				goto finally;
 
@@ -2194,8 +2194,8 @@
 			use_newobj = 0;
 		}
 		else {
-			use_newobj = PyString_Check(temp) &&
-				     strcmp(PyString_AS_STRING(temp),
+			use_newobj = PyBytes_Check(temp) &&
+				     strcmp(PyBytes_AS_STRING(temp),
 				     	    "__newobj__") == 0;
 			Py_DECREF(temp);
 		}
@@ -2362,14 +2362,14 @@
 		break;
 
         case 's':
-		if ((type == &PyString_Type) && (PyString_GET_SIZE(args) < 2)) {
+		if ((type == &PyBytes_Type) && (PyBytes_GET_SIZE(args) < 2)) {
 			res = save_string(self, args, 0);
 			goto finally;
 		}
 
 #ifdef Py_USING_UNICODE
         case 'u':
-		if ((type == &PyUnicode_Type) && (PyString_GET_SIZE(args) < 2)) {
+		if ((type == &PyUnicode_Type) && (PyBytes_GET_SIZE(args) < 2)) {
 			res = save_unicode(self, args, 0);
 			goto finally;
 		}
@@ -2391,7 +2391,7 @@
 
 	switch (type->tp_name[0]) {
         case 's':
-		if (type == &PyString_Type) {
+		if (type == &PyBytes_Type) {
 			res = save_string(self, args, 1);
 			goto finally;
 		}
@@ -2477,7 +2477,7 @@
 	}
 
 	/* Get a reduction callable, and call it.  This may come from
-	 * copyreg.dispatch_table, the object's __reduce_ex__ method,
+	 * copy_reg.dispatch_table, the object's __reduce_ex__ method,
 	 * or the object's __reduce__ method.
 	 */
 	__reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type);
@@ -2526,7 +2526,7 @@
 	if (t == NULL)
 		goto finally;
 
-	if (PyString_Check(t)) {
+	if (PyBytes_Check(t)) {
 		res = save_global(self, args, t);
 		goto finally;
 	}
@@ -2640,8 +2640,8 @@
 	for (rsize = 0, i = l; --i >= 0; ) {
 		k = data->data[i];
 
-		if (PyString_Check(k))
-			rsize += PyString_GET_SIZE(k);
+		if (PyBytes_Check(k))
+			rsize += PyBytes_GET_SIZE(k);
 
 		else if (PyInt_Check(k)) { /* put */
 			ik = PyInt_AS_LONG((PyIntObject*)k);
@@ -2676,17 +2676,17 @@
 	}
 
 	/* Now generate the result */
-	r = PyString_FromStringAndSize(NULL, rsize);
+	r = PyBytes_FromStringAndSize(NULL, rsize);
 	if (r == NULL) goto err;
-	s = PyString_AS_STRING((PyStringObject *)r);
+	s = PyBytes_AS_STRING((PyBytesObject *)r);
 
 	for (i = 0; i < l; i++) {
 		k = data->data[i];
 
-		if (PyString_Check(k)) {
-			ssize = PyString_GET_SIZE(k);
+		if (PyBytes_Check(k)) {
+			ssize = PyBytes_GET_SIZE(k);
 			if (ssize) {
-				p=PyString_AS_STRING((PyStringObject *)k);
+				p=PyBytes_AS_STRING((PyBytesObject *)k);
 				while (--ssize >= 0)
 					*s++ = *p++;
 			}
@@ -3410,7 +3410,7 @@
 		goto insecure;
 	/********************************************/
 
-	str = PyString_DecodeEscape(p, len, NULL, 0, NULL);
+	str = PyBytes_DecodeEscape(p, len, NULL, 0, NULL);
 	free(s);
 	if (str) {
 		PDATA_PUSH(self->stack, str, -1);
@@ -3439,7 +3439,7 @@
 	if (self->read_func(self, &s, l) < 0)
 		return -1;
 
-	if (!( py_string = PyString_FromStringAndSize(s, l)))
+	if (!( py_string = PyBytes_FromStringAndSize(s, l)))
 		return -1;
 
 	PDATA_PUSH(self->stack, py_string, -1);
@@ -3461,7 +3461,7 @@
 
 	if (self->read_func(self, &s, l) < 0) return -1;
 
-	if (!( py_string = PyString_FromStringAndSize(s, l)))  return -1;
+	if (!( py_string = PyBytes_FromStringAndSize(s, l)))  return -1;
 
 	PDATA_PUSH(self->stack, py_string, -1);
 	return 0;
@@ -3688,12 +3688,12 @@
 
 	if ((len = self->readline_func(self, &s)) < 0) return -1;
 	if (len < 2) return bad_readline();
-	module_name = PyString_FromStringAndSize(s, len - 1);
+	module_name = PyBytes_FromStringAndSize(s, len - 1);
 	if (!module_name)  return -1;
 
 	if ((len = self->readline_func(self, &s)) >= 0) {
 		if (len < 2) return bad_readline();
-		if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
+		if ((class_name = PyBytes_FromStringAndSize(s, len - 1))) {
 			class = find_class(module_name, class_name,
 					   self->find_class);
 			Py_DECREF(class_name);
@@ -3772,7 +3772,7 @@
 
 	if ((len = self->readline_func(self, &s)) < 0) return -1;
 	if (len < 2) return bad_readline();
-	module_name = PyString_FromStringAndSize(s, len - 1);
+	module_name = PyBytes_FromStringAndSize(s, len - 1);
 	if (!module_name)  return -1;
 
 	if ((len = self->readline_func(self, &s)) >= 0) {
@@ -3780,7 +3780,7 @@
 			Py_DECREF(module_name);
 			return bad_readline();
 		}
-		if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
+		if ((class_name = PyBytes_FromStringAndSize(s, len - 1))) {
 			class = find_class(module_name, class_name,
 					   self->find_class);
 			Py_DECREF(class_name);
@@ -3805,7 +3805,7 @@
 		if ((len = self->readline_func(self, &s)) < 0) return -1;
 		if (len < 2) return bad_readline();
 
-		pid = PyString_FromStringAndSize(s, len - 1);
+		pid = PyBytes_FromStringAndSize(s, len - 1);
 		if (!pid)  return -1;
 
 		if (PyList_Check(self->pers_func)) {
@@ -3938,7 +3938,7 @@
 	if ((len = self->readline_func(self, &s)) < 0) return -1;
 	if (len < 2) return bad_readline();
 
-	if (!( py_str = PyString_FromStringAndSize(s, len - 1)))  return -1;
+	if (!( py_str = PyBytes_FromStringAndSize(s, len - 1)))  return -1;
 
 	value = PyDict_GetItem(self->memo, py_str);
 	if (! value) {
@@ -4064,8 +4064,8 @@
 	 * confirm that pair is really a 2-tuple of strings.
 	 */
 	if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 ||
-	    !PyString_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
-	    !PyString_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
+	    !PyBytes_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
+	    !PyBytes_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
 		Py_DECREF(py_code);
 		PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
 			     "isn't a 2-tuple of strings", code);
@@ -4098,7 +4098,7 @@
 	if ((l = self->readline_func(self, &s)) < 0) return -1;
 	if (l < 2) return bad_readline();
 	if (!( len=self->stack->length ))  return stackUnderflow();
-	if (!( py_str = PyString_FromStringAndSize(s, l - 1)))  return -1;
+	if (!( py_str = PyBytes_FromStringAndSize(s, l - 1)))  return -1;
 	value=self->stack->data[len-1];
 	l=PyDict_SetItem(self->memo, py_str, value);
 	Py_DECREF(py_str);
@@ -5568,7 +5568,7 @@
 {
 	PyObject *copyreg, *t, *r;
 
-#define INIT_STR(S) if (!( S ## _str=PyString_InternFromString(#S)))  return -1;
+#define INIT_STR(S) if (!( S ## _str=PyBytes_InternFromString(#S)))  return -1;
 
 	if (PyType_Ready(&Unpicklertype) < 0)
 		return -1;
@@ -5591,7 +5591,7 @@
 	INIT_STR(copyreg);
 	INIT_STR(dispatch_table);
 
-	if (!( copyreg = PyImport_ImportModule("copyreg")))
+	if (!( copyreg = PyImport_ImportModule("copy_reg")))
 		return -1;
 
 	/* This is special because we want to use a different
@@ -5710,6 +5710,12 @@
 	PyObject *format_version;
 	PyObject *compatible_formats;
 
+	/* XXX: Should mention that the pickle module will include the C
+	   XXX: optimized implementation automatically. */
+	if (PyErr_WarnPy3k("the cPickle module has been removed in "
+			   "Python 3.0", 2) < 0)
+		return;
+
 	Py_TYPE(&Picklertype) = &PyType_Type;
 	Py_TYPE(&Unpicklertype) = &PyType_Type;
 	Py_TYPE(&PdataType) = &PyType_Type;
@@ -5730,7 +5736,7 @@
 
 	/* Add some symbolic constants to the module */
 	d = PyModule_GetDict(m);
-	v = PyString_FromString(rev);
+	v = PyBytes_FromString(rev);
 	PyDict_SetItemString(d, "__version__", v);
 	Py_XDECREF(v);
 
@@ -5749,7 +5755,7 @@
 
 	/* These are purely informational; no code uses them. */
 	/* File format version we write. */
-	format_version = PyString_FromString("2.0");
+	format_version = PyBytes_FromString("2.0");
 	/* Format versions we can read. */
 	compatible_formats = Py_BuildValue("[sssss]",
 		"1.0",	/* Original protocol 0 */

Modified: python/branches/okkoto-sizeof/Modules/cStringIO.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cStringIO.c	(original)
+++ python/branches/okkoto-sizeof/Modules/cStringIO.c	Wed Jun  4 11:24:23 2008
@@ -119,7 +119,7 @@
 static PyObject *
 IO_cgetval(PyObject *self) {
         if (!IO__opencheck(IOOOBJECT(self))) return NULL;
-        return PyString_FromStringAndSize(((IOobject*)self)->buf,
+        return PyBytes_FromStringAndSize(((IOobject*)self)->buf,
                                           ((IOobject*)self)->pos);
 }
 
@@ -137,7 +137,7 @@
         }
         else
                   s=self->string_size;
-        return PyString_FromStringAndSize(self->buf, s);
+        return PyBytes_FromStringAndSize(self->buf, s);
 }
 
 PyDoc_STRVAR(IO_isatty__doc__, "isatty(): always returns 0");
@@ -177,7 +177,7 @@
 
         if ( (n=IO_cread((PyObject*)self,&output,n)) < 0) return NULL;
 
-        return PyString_FromStringAndSize(output, n);
+        return PyBytes_FromStringAndSize(output, n);
 }
 
 PyDoc_STRVAR(IO_readline__doc__, "readline() -- Read one line");
@@ -215,7 +215,7 @@
                 n -= m;
                 self->pos -= m;
         }
-        return PyString_FromStringAndSize(output, n);
+        return PyBytes_FromStringAndSize(output, n);
 }
 
 PyDoc_STRVAR(IO_readlines__doc__, "readlines() -- Read all lines");
@@ -238,7 +238,7 @@
                         goto err;
 		if (n == 0)
 			break;
-		line = PyString_FromStringAndSize (output, n);
+		line = PyBytes_FromStringAndSize (output, n);
 		if (!line) 
                         goto err;
 		if (PyList_Append (result, line) == -1) {
@@ -315,7 +315,7 @@
 	next = IO_readline((IOobject *)self, NULL);
 	if (!next)
 		return NULL;
-	if (!PyString_GET_SIZE(next)) {
+	if (!PyBytes_GET_SIZE(next)) {
 		Py_DECREF(next);
 		PyErr_SetNone(PyExc_StopIteration);
 		return NULL;
@@ -456,7 +456,7 @@
 	while ((s = PyIter_Next(it)) != NULL) {
 		Py_ssize_t n;
 		char *c;
-		if (PyString_AsStringAndSize(s, &c, &n) == -1) {
+		if (PyBytes_AsStringAndSize(s, &c, &n) == -1) {
 			Py_DECREF(it);
 			Py_DECREF(s);
 			return NULL;

Modified: python/branches/okkoto-sizeof/Modules/cdmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cdmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/cdmodule.c	Wed Jun  4 11:24:23 2008
@@ -239,19 +239,19 @@
 	if (!PyArg_ParseTuple(args, "i:readda", &numframes))
 		return NULL;
 
-	result = PyString_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
+	result = PyBytes_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
 	if (result == NULL)
 		return NULL;
 
 	n = CDreadda(self->ob_cdplayer,
-		       (CDFRAME *) PyString_AsString(result), numframes);
+		       (CDFRAME *) PyBytes_AsString(result), numframes);
 	if (n == -1) {
 		Py_DECREF(result);
 		PyErr_SetFromErrno(CdError);
 		return NULL;
 	}
 	if (n < numframes)
-		_PyString_Resize(&result, n * sizeof(CDFRAME));
+		_PyBytes_Resize(&result, n * sizeof(CDFRAME));
 
 	return result;
 }
@@ -468,7 +468,7 @@
 	PyTuple_SetItem(args, 1, PyInt_FromLong((long) type));
 	switch (type) {
 	case cd_audio:
-		v = PyString_FromStringAndSize(data, CDDA_DATASIZE);
+		v = PyBytes_FromStringAndSize(data, CDDA_DATASIZE);
 		break;
 	case cd_pnum:
 	case cd_index:
@@ -484,15 +484,15 @@
 #undef ptr
 		break;
 	case cd_catalog:
-		v = PyString_FromStringAndSize(NULL, 13);
-		p = PyString_AsString(v);
+		v = PyBytes_FromStringAndSize(NULL, 13);
+		p = PyBytes_AsString(v);
 		for (i = 0; i < 13; i++)
 			*p++ = ((char *) data)[i] + '0';
 		break;
 	case cd_ident:
 #define ptr ((struct cdident *) data)
-		v = PyString_FromStringAndSize(NULL, 12);
-		p = PyString_AsString(v);
+		v = PyBytes_FromStringAndSize(NULL, 12);
+		p = PyBytes_AsString(v);
 		CDsbtoa(p, ptr->country, 2);
 		p += 2;
 		CDsbtoa(p, ptr->owner, 3);

Modified: python/branches/okkoto-sizeof/Modules/cgensupport.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cgensupport.c	(original)
+++ python/branches/okkoto-sizeof/Modules/cgensupport.c	Wed Jun  4 11:24:23 2008
@@ -119,10 +119,10 @@
 	PyObject *v;
 	if (!PyArg_GetObject(args, nargs, i, &v))
 		return 0;
-	if (!PyString_Check(v)) {
+	if (!PyBytes_Check(v)) {
 		return PyErr_BadArgument();
 	}
-	*p_arg = PyString_AsString(v);
+	*p_arg = PyBytes_AsString(v);
 	return 1;
 }
 

Modified: python/branches/okkoto-sizeof/Modules/cjkcodecs/cjkcodecs.h
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cjkcodecs/cjkcodecs.h	(original)
+++ python/branches/okkoto-sizeof/Modules/cjkcodecs/cjkcodecs.h	Wed Jun  4 11:24:23 2008
@@ -261,7 +261,7 @@
 	const MultibyteCodec *codec;
 	const char *enc;
 
-	if (!PyString_Check(encoding)) {
+	if (!PyBytes_Check(encoding)) {
 		PyErr_SetString(PyExc_TypeError,
 				"encoding name must be a string.");
 		return NULL;
@@ -271,7 +271,7 @@
 	if (cofunc == NULL)
 		return NULL;
 
-	enc = PyString_AS_STRING(encoding);
+	enc = PyBytes_AS_STRING(encoding);
 	for (codec = codec_list; codec->encoding[0]; codec++)
 		if (strcmp(codec->encoding, enc) == 0)
 			break;

Modified: python/branches/okkoto-sizeof/Modules/cjkcodecs/multibytecodec.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cjkcodecs/multibytecodec.c	(original)
+++ python/branches/okkoto-sizeof/Modules/cjkcodecs/multibytecodec.c	Wed Jun  4 11:24:23 2008
@@ -85,7 +85,7 @@
 	else if (strcmp(errors, "replace") == 0)
 		return ERROR_REPLACE;
 	else
-		return PyString_FromString(errors);
+		return PyBytes_FromString(errors);
 }
 
 static PyObject *
@@ -93,8 +93,8 @@
 {
 	PyObject *args, *cb, *r;
 
-	assert(PyString_Check(errors));
-	cb = PyCodec_LookupError(PyString_AS_STRING(errors));
+	assert(PyBytes_Check(errors));
+	cb = PyCodec_LookupError(PyBytes_AS_STRING(errors));
 	if (cb == NULL)
 		return NULL;
 
@@ -129,7 +129,7 @@
 		return self->errors;
 	}
 
-	return PyString_FromString(errors);
+	return PyBytes_FromString(errors);
 }
 
 static int
@@ -138,12 +138,12 @@
 {
 	PyObject *cb;
 
-	if (!PyString_Check(value)) {
+	if (!PyBytes_Check(value)) {
 		PyErr_SetString(PyExc_TypeError, "errors must be a string");
 		return -1;
 	}
 
-	cb = internal_error_callback(PyString_AS_STRING(value));
+	cb = internal_error_callback(PyBytes_AS_STRING(value));
 	if (cb == NULL)
 		return -1;
 
@@ -166,15 +166,15 @@
 	Py_ssize_t orgpos, orgsize;
 
 	orgpos = (Py_ssize_t)((char *)buf->outbuf -
-				PyString_AS_STRING(buf->outobj));
-	orgsize = PyString_GET_SIZE(buf->outobj);
-	if (_PyString_Resize(&buf->outobj, orgsize + (
+				PyBytes_AS_STRING(buf->outobj));
+	orgsize = PyBytes_GET_SIZE(buf->outobj);
+	if (_PyBytes_Resize(&buf->outobj, orgsize + (
 	    esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1)
 		return -1;
 
-	buf->outbuf = (unsigned char *)PyString_AS_STRING(buf->outobj) +orgpos;
-	buf->outbuf_end = (unsigned char *)PyString_AS_STRING(buf->outobj)
-		+ PyString_GET_SIZE(buf->outobj);
+	buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos;
+	buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj)
+		+ PyBytes_GET_SIZE(buf->outobj);
 
 	return 0;
 }
@@ -322,10 +322,10 @@
 			goto errorexit;
 	}
 
-	retstrsize = PyString_GET_SIZE(retstr);
+	retstrsize = PyBytes_GET_SIZE(retstr);
 	REQUIRE_ENCODEBUFFER(buf, retstrsize);
 
-	memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
+	memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize);
 	buf->outbuf += retstrsize;
 
 	newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
@@ -468,16 +468,16 @@
 	Py_ssize_t finalsize, r = 0;
 
 	if (datalen == 0)
-		return PyString_FromString("");
+		return PyBytes_FromString("");
 
 	buf.excobj = NULL;
 	buf.inbuf = buf.inbuf_top = *data;
 	buf.inbuf_end = buf.inbuf_top + datalen;
-	buf.outobj = PyString_FromStringAndSize(NULL, datalen * 2 + 16);
+	buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16);
 	if (buf.outobj == NULL)
 		goto errorexit;
-	buf.outbuf = (unsigned char *)PyString_AS_STRING(buf.outobj);
-	buf.outbuf_end = buf.outbuf + PyString_GET_SIZE(buf.outobj);
+	buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj);
+	buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj);
 
 	while (buf.inbuf < buf.inbuf_end) {
 		Py_ssize_t inleft, outleft;
@@ -512,10 +512,10 @@
 		}
 
 	finalsize = (Py_ssize_t)((char *)buf.outbuf -
-				 PyString_AS_STRING(buf.outobj));
+				 PyBytes_AS_STRING(buf.outobj));
 
-	if (finalsize != PyString_GET_SIZE(buf.outobj))
-		if (_PyString_Resize(&buf.outobj, finalsize) == -1)
+	if (finalsize != PyBytes_GET_SIZE(buf.outobj))
+		if (_PyBytes_Resize(&buf.outobj, finalsize) == -1)
 			goto errorexit;
 
 	Py_XDECREF(buf.excobj);
@@ -1222,35 +1222,35 @@
 		if (cres == NULL)
 			goto errorexit;
 
-		if (!PyString_Check(cres)) {
+		if (!PyBytes_Check(cres)) {
 			PyErr_SetString(PyExc_TypeError,
 					"stream function returned a "
 					"non-string object");
 			goto errorexit;
 		}
 
-		endoffile = (PyString_GET_SIZE(cres) == 0);
+		endoffile = (PyBytes_GET_SIZE(cres) == 0);
 
 		if (self->pendingsize > 0) {
 			PyObject *ctr;
 			char *ctrdata;
 
-			rsize = PyString_GET_SIZE(cres) + self->pendingsize;
-			ctr = PyString_FromStringAndSize(NULL, rsize);
+			rsize = PyBytes_GET_SIZE(cres) + self->pendingsize;
+			ctr = PyBytes_FromStringAndSize(NULL, rsize);
 			if (ctr == NULL)
 				goto errorexit;
-			ctrdata = PyString_AS_STRING(ctr);
+			ctrdata = PyBytes_AS_STRING(ctr);
 			memcpy(ctrdata, self->pending, self->pendingsize);
 			memcpy(ctrdata + self->pendingsize,
-				PyString_AS_STRING(cres),
-				PyString_GET_SIZE(cres));
+				PyBytes_AS_STRING(cres),
+				PyBytes_GET_SIZE(cres));
 			Py_DECREF(cres);
 			cres = ctr;
 			self->pendingsize = 0;
 		}
 
-		rsize = PyString_GET_SIZE(cres);
-		if (decoder_prepare_buffer(&buf, PyString_AS_STRING(cres),
+		rsize = PyBytes_GET_SIZE(cres);
+		if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres),
 					   rsize) != 0)
 			goto errorexit;
 
@@ -1585,7 +1585,7 @@
 	if (pwrt == NULL)
 		return NULL;
 
-	if (PyString_Size(pwrt) > 0) {
+	if (PyBytes_Size(pwrt) > 0) {
 		PyObject *wr;
 		wr = PyObject_CallMethod(self->stream, "write", "O", pwrt);
 		if (wr == NULL) {

Modified: python/branches/okkoto-sizeof/Modules/clmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/clmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/clmodule.c	Wed Jun  4 11:24:23 2008
@@ -111,7 +111,7 @@
 		return NULL;
 
   retry:
-	compressedBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
+	compressedBuffer = PyBytes_FromStringAndSize(NULL, frameBufferSize);
 	if (compressedBuffer == NULL)
 		return NULL;
 
@@ -120,7 +120,7 @@
 	if (clCompressImage(compressionScheme, width, height, originalFormat,
 			    compressionRatio, (void *) frameBuffer,
 			    &compressedBufferSize,
-			    (void *) PyString_AsString(compressedBuffer))
+			    (void *) PyBytes_AsString(compressedBuffer))
 	    == FAILURE || error_handler_called) {
 		Py_DECREF(compressedBuffer);
 		if (!error_handler_called)
@@ -135,7 +135,7 @@
 	}
 
 	if (compressedBufferSize < frameBufferSize)
-		_PyString_Resize(&compressedBuffer, compressedBufferSize);
+		_PyBytes_Resize(&compressedBuffer, compressedBufferSize);
 
 	return compressedBuffer;
 }
@@ -155,14 +155,14 @@
 
 	frameBufferSize = width * height * CL_BytesPerPixel(originalFormat);
 
-	frameBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
+	frameBuffer = PyBytes_FromStringAndSize(NULL, frameBufferSize);
 	if (frameBuffer == NULL)
 		return NULL;
 
 	error_handler_called = 0;
 	if (clDecompressImage(compressionScheme, width, height, originalFormat,
 			      compressedBufferSize, compressedBuffer,
-			      (void *) PyString_AsString(frameBuffer))
+			      (void *) PyBytes_AsString(frameBuffer))
 	    == FAILURE || error_handler_called) {
 		Py_DECREF(frameBuffer);
 		if (!error_handler_called)
@@ -236,14 +236,14 @@
 	if (error_handler_called)
 		return NULL;
 
-	data = PyString_FromStringAndSize(NULL, size);
+	data = PyBytes_FromStringAndSize(NULL, size);
 	if (data == NULL)
 		return NULL;
 
 	error_handler_called = 0;
 	if (clCompress(SELF->ob_compressorHdl, numberOfFrames,
 		       (void *) frameBuffer, &compressedBufferSize,
-		       (void *) PyString_AsString(data)) == FAILURE ||
+		       (void *) PyBytes_AsString(data)) == FAILURE ||
 	    error_handler_called) {
 		Py_DECREF(data);
 		if (!error_handler_called)
@@ -252,7 +252,7 @@
 	}
 
 	if (compressedBufferSize < size)
-		if (_PyString_Resize(&data, compressedBufferSize))
+		if (_PyBytes_Resize(&data, compressedBufferSize))
 			return NULL;
 
 	if (compressedBufferSize > size) {
@@ -285,14 +285,14 @@
 	if (error_handler_called)
 		return NULL;
 
-	data = PyString_FromStringAndSize(NULL, dataSize);
+	data = PyBytes_FromStringAndSize(NULL, dataSize);
 	if (data == NULL)
 		return NULL;
 
 	error_handler_called = 0;
 	if (clDecompress(SELF->ob_compressorHdl, numberOfFrames,
 			 compressedDataSize, (void *) compressedData,
-			 (void *) PyString_AsString(data)) == FAILURE ||
+			 (void *) PyBytes_AsString(data)) == FAILURE ||
 	    error_handler_called) {
 		Py_DECREF(data);
 		if (!error_handler_called)
@@ -514,7 +514,7 @@
 			PyList_SetItem(list, i, Py_None);
 		} else
 			PyList_SetItem(list, i,
-				   PyString_FromString((char *) PVbuffer[i]));
+				   PyBytes_FromString((char *) PVbuffer[i]));
 	}
 
 	PyMem_DEL(PVbuffer);
@@ -563,7 +563,7 @@
 		return NULL;
 	}
 
-	return PyString_FromString(name);
+	return PyBytes_FromString(name);
 }
 
 static PyObject *
@@ -775,7 +775,7 @@
 			PyList_SetItem(list, i, Py_None);
 		} else
 			PyList_SetItem(list, i,
-				   PyString_FromString((char *) PVbuffer[i]));
+				   PyBytes_FromString((char *) PVbuffer[i]));
 	}
 
 	PyMem_DEL(PVbuffer);
@@ -818,7 +818,7 @@
 		return NULL;
 	}
 
-	return PyString_FromString(name);
+	return PyBytes_FromString(name);
 }
 
 static PyObject *

Modified: python/branches/okkoto-sizeof/Modules/cmathmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/cmathmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/cmathmodule.c	Wed Jun  4 11:24:23 2008
@@ -920,7 +920,7 @@
 	errno = 0;
 	PyFPE_START_PROTECT("arg function", return 0)
 	phi = c_atan2(z);
-	PyFPE_END_PROTECT(r)
+	PyFPE_END_PROTECT(phi)
 	if (errno != 0)
 		return math_error();
 	else

Modified: python/branches/okkoto-sizeof/Modules/datetimemodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/datetimemodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/datetimemodule.c	Wed Jun  4 11:24:23 2008
@@ -2,6 +2,8 @@
  *  http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
  */
 
+#define PY_SSIZE_T_CLEAN
+
 #include "Python.h"
 #include "modsupport.h"
 #include "structmember.h"
@@ -945,7 +947,7 @@
 	else
 		result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
 
-	if (result != NULL && result != Py_None && ! PyString_Check(result)) {
+	if (result != NULL && result != Py_None && ! PyBytes_Check(result)) {
 		PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
 			     "return None or a string, not '%s'",
 			     Py_TYPE(result)->tp_name);
@@ -1044,27 +1046,27 @@
 {
 	PyObject *temp;
 
-	assert(PyString_Check(repr));
+	assert(PyBytes_Check(repr));
 	assert(tzinfo);
 	if (tzinfo == Py_None)
 		return repr;
 	/* Get rid of the trailing ')'. */
-	assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
-	temp = PyString_FromStringAndSize(PyString_AsString(repr),
-					  PyString_Size(repr) - 1);
+	assert(PyBytes_AsString(repr)[PyBytes_Size(repr)-1] == ')');
+	temp = PyBytes_FromStringAndSize(PyBytes_AsString(repr),
+					  PyBytes_Size(repr) - 1);
 	Py_DECREF(repr);
 	if (temp == NULL)
 		return NULL;
 	repr = temp;
 
 	/* Append ", tzinfo=". */
-	PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
+	PyBytes_ConcatAndDel(&repr, PyBytes_FromString(", tzinfo="));
 
 	/* Append repr(tzinfo). */
-	PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
+	PyBytes_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
 
 	/* Add a closing paren. */
-	PyString_ConcatAndDel(&repr, PyString_FromString(")"));
+	PyBytes_ConcatAndDel(&repr, PyBytes_FromString(")"));
 	return repr;
 }
 
@@ -1090,7 +1092,7 @@
 		      DayNames[wday], MonthNames[GET_MONTH(date) - 1],
 		      GET_DAY(date), hours, minutes, seconds,
 		      GET_YEAR(date));
-	return PyString_FromString(buffer);
+	return PyBytes_FromString(buffer);
 }
 
 /* Add an hours & minutes UTC offset string to buf.  buf has no more than
@@ -1141,7 +1143,7 @@
 	else
 	    sprintf(freplacement, "%06d", 0);
 
-	return PyString_FromStringAndSize(freplacement, strlen(freplacement));
+	return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
 }
 
 /* I sure don't want to reproduce the strftime code from the time module,
@@ -1152,8 +1154,8 @@
  * needed.
  */
 static PyObject *
-wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
-	      PyObject *tzinfoarg)
+wrap_strftime(PyObject *object, const char *format, size_t format_len,
+		PyObject *timetuple, PyObject *tzinfoarg)
 {
 	PyObject *result = NULL;	/* guilty until proved innocent */
 
@@ -1161,20 +1163,19 @@
 	PyObject *Zreplacement = NULL;	/* py string, replacement for %Z */
 	PyObject *freplacement = NULL;	/* py string, replacement for %f */
 
-	char *pin;	/* pointer to next char in input format */
-	char ch;	/* next char in input format */
+	const char *pin;	/* pointer to next char in input format */
+	char ch;		/* next char in input format */
 
 	PyObject *newfmt = NULL;	/* py string, the output format */
 	char *pnew;	/* pointer to available byte in output format */
-	int totalnew;	/* number bytes total in output format buffer,
-			   exclusive of trailing \0 */
-	int usednew;	/* number bytes used so far in output format buffer */
+	size_t totalnew;	/* number bytes total in output format buffer,
+				   exclusive of trailing \0 */
+	size_t usednew;	/* number bytes used so far in output format buffer */
 
-	char *ptoappend; /* pointer to string to append to output buffer */
-	int ntoappend;	/* # of bytes to append to output buffer */
+	const char *ptoappend;	/* ptr to string to append to output buffer */
+	size_t ntoappend;	/* # of bytes to append to output buffer */
 
 	assert(object && format && timetuple);
-	assert(PyString_Check(format));
 
 	/* Give up if the year is before 1900.
 	 * Python strftime() plays games with the year, and different
@@ -1205,13 +1206,13 @@
 	 * a new format.  Since computing the replacements for those codes
 	 * is expensive, don't unless they're actually used.
 	 */
-	totalnew = PyString_Size(format) + 1;	/* realistic if no %z/%Z/%f */
-	newfmt = PyString_FromStringAndSize(NULL, totalnew);
+	totalnew = format_len + 1;	/* realistic if no %z/%Z/%f */
+	newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
 	if (newfmt == NULL) goto Done;
-	pnew = PyString_AsString(newfmt);
+	pnew = PyBytes_AsString(newfmt);
 	usednew = 0;
 
-	pin = PyString_AsString(format);
+	pin = format;
 	while ((ch = *pin++) != '\0') {
 		if (ch != '%') {
 			ptoappend = pin - 1;
@@ -1229,7 +1230,7 @@
 				/* format utcoffset */
 				char buf[100];
 				PyObject *tzinfo = get_tzinfo_member(object);
-				zreplacement = PyString_FromString("");
+				zreplacement = PyBytes_FromString("");
 				if (zreplacement == NULL) goto Done;
 				if (tzinfo != Py_None && tzinfo != NULL) {
 					assert(tzinfoarg != NULL);
@@ -1240,19 +1241,19 @@
 							     tzinfoarg) < 0)
 						goto Done;
 					Py_DECREF(zreplacement);
-					zreplacement = PyString_FromString(buf);
+					zreplacement = PyBytes_FromString(buf);
 					if (zreplacement == NULL) goto Done;
 				}
 			}
 			assert(zreplacement != NULL);
-			ptoappend = PyString_AS_STRING(zreplacement);
-			ntoappend = PyString_GET_SIZE(zreplacement);
+			ptoappend = PyBytes_AS_STRING(zreplacement);
+			ntoappend = PyBytes_GET_SIZE(zreplacement);
 		}
 		else if (ch == 'Z') {
 			/* format tzname */
 			if (Zreplacement == NULL) {
 				PyObject *tzinfo = get_tzinfo_member(object);
-				Zreplacement = PyString_FromString("");
+				Zreplacement = PyBytes_FromString("");
 				if (Zreplacement == NULL) goto Done;
 				if (tzinfo != Py_None && tzinfo != NULL) {
 					PyObject *temp;
@@ -1260,7 +1261,7 @@
 					temp = call_tzname(tzinfo, tzinfoarg);
 					if (temp == NULL) goto Done;
 					if (temp != Py_None) {
-						assert(PyString_Check(temp));
+						assert(PyBytes_Check(temp));
 						/* Since the tzname is getting
 						 * stuffed into the format, we
 						 * have to double any % signs
@@ -1274,7 +1275,7 @@
 						Py_DECREF(temp);
 						if (Zreplacement == NULL)
 							goto Done;
-						if (!PyString_Check(Zreplacement)) {
+						if (!PyBytes_Check(Zreplacement)) {
 							PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
 							goto Done;
 						}
@@ -1284,8 +1285,8 @@
 				}
 			}
 			assert(Zreplacement != NULL);
-			ptoappend = PyString_AS_STRING(Zreplacement);
-			ntoappend = PyString_GET_SIZE(Zreplacement);
+			ptoappend = PyBytes_AS_STRING(Zreplacement);
+			ntoappend = PyBytes_GET_SIZE(Zreplacement);
 		}
 		else if (ch == 'f') {
 			/* format microseconds */
@@ -1295,9 +1296,9 @@
 					goto Done;
 			}
 			assert(freplacement != NULL);
-			assert(PyString_Check(freplacement));
-			ptoappend = PyString_AS_STRING(freplacement);
-			ntoappend = PyString_GET_SIZE(freplacement);
+			assert(PyBytes_Check(freplacement));
+			ptoappend = PyBytes_AS_STRING(freplacement);
+			ntoappend = PyBytes_GET_SIZE(freplacement);
 		}
 		else {
 			/* percent followed by neither z nor Z */
@@ -1313,15 +1314,15 @@
  		if (ntoappend == 0)
  			continue;
  		while (usednew + ntoappend > totalnew) {
- 			int bigger = totalnew << 1;
+ 			size_t bigger = totalnew << 1;
  			if ((bigger >> 1) != totalnew) { /* overflow */
  				PyErr_NoMemory();
  				goto Done;
  			}
- 			if (_PyString_Resize(&newfmt, bigger) < 0)
+ 			if (_PyBytes_Resize(&newfmt, bigger) < 0)
  				goto Done;
  			totalnew = bigger;
- 			pnew = PyString_AsString(newfmt) + usednew;
+ 			pnew = PyBytes_AsString(newfmt) + usednew;
  		}
 		memcpy(pnew, ptoappend, ntoappend);
 		pnew += ntoappend;
@@ -1329,7 +1330,7 @@
 		assert(usednew <= totalnew);
 	}  /* end while() */
 
-	if (_PyString_Resize(&newfmt, usednew) < 0)
+	if (_PyBytes_Resize(&newfmt, usednew) < 0)
 		goto Done;
 	{
 		PyObject *time = PyImport_ImportModuleNoBlock("time");
@@ -2007,18 +2008,18 @@
 delta_repr(PyDateTime_Delta *self)
 {
 	if (GET_TD_MICROSECONDS(self) != 0)
-		return PyString_FromFormat("%s(%d, %d, %d)",
+		return PyBytes_FromFormat("%s(%d, %d, %d)",
 					   Py_TYPE(self)->tp_name,
 					   GET_TD_DAYS(self),
 					   GET_TD_SECONDS(self),
 					   GET_TD_MICROSECONDS(self));
 	if (GET_TD_SECONDS(self) != 0)
-		return PyString_FromFormat("%s(%d, %d)",
+		return PyBytes_FromFormat("%s(%d, %d)",
 					   Py_TYPE(self)->tp_name,
 					   GET_TD_DAYS(self),
 					   GET_TD_SECONDS(self));
 
-	return PyString_FromFormat("%s(%d)",
+	return PyBytes_FromFormat("%s(%d)",
 				   Py_TYPE(self)->tp_name,
 				   GET_TD_DAYS(self));
 }
@@ -2062,7 +2063,7 @@
 		pbuf += n;
 	}
 
-	return PyString_FromStringAndSize(buf, pbuf - buf);
+	return PyBytes_FromStringAndSize(buf, pbuf - buf);
 
  Fail:
 	PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
@@ -2241,15 +2242,15 @@
 
 	/* Check for invocation from pickle with __getstate__ state */
 	if (PyTuple_GET_SIZE(args) == 1 &&
-	    PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-	    PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
-	    MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
+	    PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+	    PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
+	    MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
 	{
 	    	PyDateTime_Date *me;
 
 		me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
 		if (me != NULL) {
-			char *pdata = PyString_AS_STRING(state);
+			char *pdata = PyBytes_AS_STRING(state);
 			memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
 			me->hashcode = -1;
 		}
@@ -2447,7 +2448,7 @@
 		      type_name,
 		      GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
 
-	return PyString_FromString(buffer);
+	return PyBytes_FromString(buffer);
 }
 
 static PyObject *
@@ -2456,7 +2457,7 @@
 	char buffer[128];
 
 	isoformat_date(self, buffer, sizeof(buffer));
-	return PyString_FromString(buffer);
+	return PyBytes_FromString(buffer);
 }
 
 /* str() calls the appropriate isoformat() method. */
@@ -2480,18 +2481,19 @@
 	 * timetuple() method appropriate to self's class.
 	 */
 	PyObject *result;
-	PyObject *format;
 	PyObject *tuple;
+	const char *format;
+	Py_ssize_t format_len;
 	static char *keywords[] = {"format", NULL};
 
-	if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
-					  &PyString_Type, &format))
+	if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
+					  &format, &format_len))
 		return NULL;
 
 	tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
 	if (tuple == NULL)
 		return NULL;
-	result = wrap_strftime((PyObject *)self, format, tuple,
+	result = wrap_strftime((PyObject *)self, format, format_len, tuple,
 			       (PyObject *)self);
 	Py_DECREF(tuple);
 	return result;
@@ -2506,9 +2508,9 @@
 		return NULL;
 
 	/* Check for str or unicode */
-	if (PyString_Check(format)) {
+	if (PyBytes_Check(format)) {
                 /* If format is zero length, return str(self) */
-		if (PyString_GET_SIZE(format) == 0)
+		if (PyBytes_GET_SIZE(format) == 0)
 			return PyObject_Str((PyObject *)self);
 	} else if (PyUnicode_Check(format)) {
                 /* If format is zero length, return str(self) */
@@ -2651,7 +2653,7 @@
 {
 	return Py_BuildValue(
 		"(N)",
-		PyString_FromStringAndSize((char *)self->data,
+		PyBytes_FromStringAndSize((char *)self->data,
 					   _PyDateTime_DATE_DATASIZE));
 }
 
@@ -3107,9 +3109,9 @@
 	/* Check for invocation from pickle with __getstate__ state */
 	if (PyTuple_GET_SIZE(args) >= 1 &&
 	    PyTuple_GET_SIZE(args) <= 2 &&
-	    PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-	    PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
-	    ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
+	    PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+	    PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
+	    ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
 	{
 		PyDateTime_Time *me;
 		char aware;
@@ -3125,7 +3127,7 @@
 		aware = (char)(tzinfo != Py_None);
 		me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
 		if (me != NULL) {
-			char *pdata = PyString_AS_STRING(state);
+			char *pdata = PyBytes_AS_STRING(state);
 
 			memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
 			me->hashcode = -1;
@@ -3211,7 +3213,7 @@
 	else
 		PyOS_snprintf(buffer, sizeof(buffer),
 			      "%s(%d, %d)", type_name, h, m);
-	result = PyString_FromString(buffer);
+	result = PyBytes_FromString(buffer);
 	if (result != NULL && HASTZINFO(self))
 		result = append_keyword_tzinfo(result, self->tzinfo);
 	return result;
@@ -3238,7 +3240,7 @@
 	       _PyDateTime_TIME_DATASIZE);
 
 	isoformat_time(pdatetime, buf, sizeof(buf));
-	result = PyString_FromString(buf);
+	result = PyBytes_FromString(buf);
 	if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
 		return result;
 
@@ -3248,7 +3250,7 @@
 		Py_DECREF(result);
 		return NULL;
 	}
-	PyString_ConcatAndDel(&result, PyString_FromString(buf));
+	PyBytes_ConcatAndDel(&result, PyBytes_FromString(buf));
 	return result;
 }
 
@@ -3256,12 +3258,13 @@
 time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
 {
 	PyObject *result;
-	PyObject *format;
 	PyObject *tuple;
+	const char *format;
+	Py_ssize_t format_len;
 	static char *keywords[] = {"format", NULL};
 
-	if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
-					  &PyString_Type, &format))
+	if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
+					  &format, &format_len))
 		return NULL;
 
 	/* Python's strftime does insane things with the year part of the
@@ -3277,7 +3280,8 @@
 	if (tuple == NULL)
 		return NULL;
 	assert(PyTuple_Size(tuple) == 9);
-	result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
+	result = wrap_strftime((PyObject *)self, format, format_len, tuple,
+			       Py_None);
 	Py_DECREF(tuple);
 	return result;
 }
@@ -3360,7 +3364,7 @@
 
 		/* Reduce this to a hash of another object. */
 		if (offset == 0)
-			temp = PyString_FromStringAndSize((char *)self->data,
+			temp = PyBytes_FromStringAndSize((char *)self->data,
 						_PyDateTime_TIME_DATASIZE);
 		else {
 			int hour;
@@ -3448,7 +3452,7 @@
 	PyObject *basestate;
 	PyObject *result = NULL;
 
-	basestate =  PyString_FromStringAndSize((char *)self->data,
+	basestate =  PyBytes_FromStringAndSize((char *)self->data,
 						_PyDateTime_TIME_DATASIZE);
 	if (basestate != NULL) {
 		if (! HASTZINFO(self) || self->tzinfo == Py_None)
@@ -3635,9 +3639,9 @@
 	/* Check for invocation from pickle with __getstate__ state */
 	if (PyTuple_GET_SIZE(args) >= 1 &&
 	    PyTuple_GET_SIZE(args) <= 2 &&
-	    PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
-	    PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
-	    MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
+	    PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+	    PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
+	    MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
 	{
 		PyDateTime_DateTime *me;
 		char aware;
@@ -3653,7 +3657,7 @@
 		aware = (char)(tzinfo != Py_None);
 		me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
 		if (me != NULL) {
-			char *pdata = PyString_AS_STRING(state);
+			char *pdata = PyBytes_AS_STRING(state);
 
 			memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
 			me->hashcode = -1;
@@ -4162,7 +4166,7 @@
 			      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
 			      DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
 	}
-	baserepr = PyString_FromString(buffer);
+	baserepr = PyBytes_FromString(buffer);
 	if (baserepr == NULL || ! HASTZINFO(self))
 		return baserepr;
 	return append_keyword_tzinfo(baserepr, self->tzinfo);
@@ -4190,7 +4194,7 @@
 	assert(cp != NULL);
 	*cp++ = sep;
 	isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
-	result = PyString_FromString(buffer);
+	result = PyBytes_FromString(buffer);
 	if (result == NULL || ! HASTZINFO(self))
 		return result;
 
@@ -4200,7 +4204,7 @@
 		Py_DECREF(result);
 		return NULL;
 	}
-	PyString_ConcatAndDel(&result, PyString_FromString(buffer));
+	PyBytes_ConcatAndDel(&result, PyBytes_FromString(buffer));
 	return result;
 }
 
@@ -4306,7 +4310,7 @@
 
 		/* Reduce this to a hash of another object. */
 		if (n == OFFSET_NAIVE)
-			temp = PyString_FromStringAndSize(
+			temp = PyBytes_FromStringAndSize(
 					(char *)self->data,
 					_PyDateTime_DATETIME_DATASIZE);
 		else {
@@ -4529,7 +4533,7 @@
 	PyObject *basestate;
 	PyObject *result = NULL;
 
-	basestate = PyString_FromStringAndSize((char *)self->data,
+	basestate = PyBytes_FromStringAndSize((char *)self->data,
 					  _PyDateTime_DATETIME_DATASIZE);
 	if (basestate != NULL) {
 		if (! HASTZINFO(self) || self->tzinfo == Py_None)

Modified: python/branches/okkoto-sizeof/Modules/dbmmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/dbmmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/dbmmodule.c	Wed Jun  4 11:24:23 2008
@@ -104,7 +104,7 @@
 	drec = dbm_fetch(dp->di_dbm, krec);
 	if ( drec.dptr == 0 ) {
 		PyErr_SetString(PyExc_KeyError,
-				PyString_AS_STRING((PyStringObject *)key));
+				PyBytes_AS_STRING((PyBytesObject *)key));
 		return NULL;
 	}
 	if ( dbm_error(dp->di_dbm) ) {
@@ -112,7 +112,7 @@
 		PyErr_SetString(DbmError, "");
 		return NULL;
 	}
-	return PyString_FromStringAndSize(drec.dptr, drec.dsize);
+	return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
 }
 
 static int
@@ -136,7 +136,7 @@
 		if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
 			dbm_clearerr(dp->di_dbm);
 			PyErr_SetString(PyExc_KeyError,
-				      PyString_AS_STRING((PyStringObject *)v));
+				      PyBytes_AS_STRING((PyBytesObject *)v));
 			return -1;
 		}
 	} else {
@@ -166,7 +166,7 @@
 {
 	datum key, val;
 
-	if (PyString_AsStringAndSize(v, (char **)&key.dptr,
+	if (PyBytes_AsStringAndSize(v, (char **)&key.dptr,
 	                             (Py_ssize_t *)&key.dsize)) {
 		return -1;
 	}
@@ -222,7 +222,7 @@
 		return NULL;
 	for (key = dbm_firstkey(dp->di_dbm); key.dptr;
 	     key = dbm_nextkey(dp->di_dbm)) {
-		item = PyString_FromStringAndSize(key.dptr, key.dsize);
+		item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
 		if (item == NULL) {
 			Py_DECREF(v);
 			return NULL;
@@ -269,7 +269,7 @@
         check_dbmobject_open(dp);
 	val = dbm_fetch(dp->di_dbm, key);
 	if (val.dptr != NULL)
-		return PyString_FromStringAndSize(val.dptr, val.dsize);
+		return PyBytes_FromStringAndSize(val.dptr, val.dsize);
 	else {
 		Py_INCREF(defvalue);
 		return defvalue;
@@ -292,16 +292,16 @@
         check_dbmobject_open(dp);
 	val = dbm_fetch(dp->di_dbm, key);
 	if (val.dptr != NULL)
-		return PyString_FromStringAndSize(val.dptr, val.dsize);
+		return PyBytes_FromStringAndSize(val.dptr, val.dsize);
 	if (defvalue == NULL) {
-		defvalue = PyString_FromStringAndSize(NULL, 0);
+		defvalue = PyBytes_FromStringAndSize(NULL, 0);
 		if (defvalue == NULL)
 			return NULL;
 	}
 	else
 		Py_INCREF(defvalue);
-	val.dptr = PyString_AS_STRING(defvalue);
-	val.dsize = PyString_GET_SIZE(defvalue);
+	val.dptr = PyBytes_AS_STRING(defvalue);
+	val.dsize = PyBytes_GET_SIZE(defvalue);
 	if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
 		dbm_clearerr(dp->di_dbm);
 		PyErr_SetString(DbmError, "cannot add item to database");
@@ -404,7 +404,7 @@
 	d = PyModule_GetDict(m);
 	if (DbmError == NULL)
 		DbmError = PyErr_NewException("dbm.error", NULL, NULL);
-	s = PyString_FromString(which_dbm);
+	s = PyBytes_FromString(which_dbm);
 	if (s != NULL) {
 		PyDict_SetItemString(d, "library", s);
 		Py_DECREF(s);

Modified: python/branches/okkoto-sizeof/Modules/dlmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/dlmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/dlmodule.c	Wed Jun  4 11:24:23 2008
@@ -58,8 +58,8 @@
 {
 	char *name;
 	PyUnivPtr *func;
-	if (PyString_Check(args)) {
-		name = PyString_AS_STRING(args);
+	if (PyBytes_Check(args)) {
+		name = PyBytes_AS_STRING(args);
 	} else {
 		PyErr_Format(PyExc_TypeError, "expected string, found %.200s",
 			     Py_TYPE(args)->tp_name);
@@ -88,14 +88,14 @@
 		return NULL;
 	}
 	name = PyTuple_GetItem(args, 0);
-	if (!PyString_Check(name)) {
+	if (!PyBytes_Check(name)) {
 		PyErr_SetString(PyExc_TypeError,
 				"function name must be a string");
 		return NULL;
 	}
 	func = (long (*)(long, long, long, long, long, 
                          long, long, long, long, long)) 
-          dlsym(xp->dl_handle, PyString_AsString(name));
+          dlsym(xp->dl_handle, PyBytes_AsString(name));
 	if (func == NULL) {
 		PyErr_SetString(PyExc_ValueError, dlerror());
 		return NULL;
@@ -109,8 +109,8 @@
 		PyObject *v = PyTuple_GetItem(args, i);
 		if (PyInt_Check(v))
 			alist[i-1] = PyInt_AsLong(v);
-		else if (PyString_Check(v))
-			alist[i-1] = (long)PyString_AsString(v);
+		else if (PyBytes_Check(v))
+			alist[i-1] = (long)PyBytes_AsString(v);
 		else if (v == Py_None)
 			alist[i-1] = (long) ((char *)NULL);
 		else {

Modified: python/branches/okkoto-sizeof/Modules/errnomodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/errnomodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/errnomodule.c	Wed Jun  4 11:24:23 2008
@@ -21,7 +21,7 @@
 static void
 _inscode(PyObject *d, PyObject *de, char *name, int code)
 {
-	PyObject *u = PyString_FromString(name);
+	PyObject *u = PyBytes_FromString(name);
 	PyObject *v = PyInt_FromLong((long) code);
 
 	/* Don't bother checking for errors; they'll be caught at the end

Modified: python/branches/okkoto-sizeof/Modules/fcntlmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/fcntlmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/fcntlmodule.c	Wed Jun  4 11:24:23 2008
@@ -55,7 +55,7 @@
 			PyErr_SetFromErrno(PyExc_IOError);
 			return NULL;
 		}
-		return PyString_FromStringAndSize(buf, len);
+		return PyBytes_FromStringAndSize(buf, len);
 	}
 
 	PyErr_Clear();
@@ -164,7 +164,7 @@
 			return PyInt_FromLong(ret);
 		}
 		else {
-			return PyString_FromStringAndSize(buf, len);
+			return PyBytes_FromStringAndSize(buf, len);
 		}
 	}
 
@@ -185,7 +185,7 @@
 			PyErr_SetFromErrno(PyExc_IOError);
 			return NULL;
 		}
-		return PyString_FromStringAndSize(buf, len);
+		return PyBytes_FromStringAndSize(buf, len);
 	}
 
 	PyErr_Clear();
@@ -510,6 +510,9 @@
         if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
 #endif
 /* GNU extensions, as of glibc 2.2.4. */
+#ifdef FASYNC
+        if (ins(d, "FASYNC", (long)FASYNC)) return -1;
+#endif
 #ifdef F_SETLEASE
         if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
 #endif

Modified: python/branches/okkoto-sizeof/Modules/flmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/flmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/flmodule.c	Wed Jun  4 11:24:23 2008
@@ -324,7 +324,7 @@
 	/* "label" is an exception, getmember only works for char pointers,
 	   not for char arrays */
 	if (strcmp(name, "label") == 0)
-		return PyString_FromString(g->ob_generic->label);
+		return PyBytes_FromString(g->ob_generic->label);
 
 	return PyMember_Get((char *)g->ob_generic, generic_memberlist, name);
 }
@@ -343,12 +343,12 @@
 	/* "label" is an exception: setmember doesn't set strings;
 	   and FORMS wants you to call a function to set the label */
 	if (strcmp(name, "label") == 0) {
-		if (!PyString_Check(v)) {
+		if (!PyBytes_Check(v)) {
 			PyErr_SetString(PyExc_TypeError,
 					"label attr must be string");
 			return -1;
 		}
-		fl_set_object_label(g->ob_generic, PyString_AsString(v));
+		fl_set_object_label(g->ob_generic, PyBytes_AsString(v));
 		return 0;
 	}
 
@@ -369,7 +369,7 @@
 	char buf[100];
 	PyOS_snprintf(buf, sizeof(buf), "<FORMS_object at %p, objclass=%d>",
 		      g, g->ob_generic->objclass);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static PyTypeObject GenericObjecttype = {
@@ -530,7 +530,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString (str);
+	return PyBytes_FromString (str);
 }
 
 /* int func (object) */
@@ -628,7 +628,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString (str);
+	return PyBytes_FromString (str);
 }
 
 static PyObject *
@@ -1594,7 +1594,7 @@
 	char buf[100];
 	PyOS_snprintf(buf, sizeof(buf), "<FORMS_form at %p, window=%ld>",
 		      f, f->ob_form->window);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static PyTypeObject Formtype = {
@@ -2027,7 +2027,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(str);
+	return PyBytes_FromString(str);
 }
 
 static PyObject *
@@ -2046,7 +2046,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(str);
+	return PyBytes_FromString(str);
 }
 
 
@@ -2061,7 +2061,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(str);
+	return PyBytes_FromString(str);
 }
 
 static PyObject *

Modified: python/branches/okkoto-sizeof/Modules/fmmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/fmmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/fmmodule.c	Wed Jun  4 11:24:23 2008
@@ -66,7 +66,7 @@
 		PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontname");
 		return NULL;
 	}
-	return PyString_FromStringAndSize(fontname, len);
+	return PyBytes_FromStringAndSize(fontname, len);
 }
 
 static PyObject *
@@ -79,7 +79,7 @@
 		PyErr_SetString(PyExc_RuntimeError, "error in fmgetcomment");
 		return NULL;
 	}
-	return PyString_FromStringAndSize(comment, len);
+	return PyBytes_FromStringAndSize(comment, len);
 }
 
 static PyObject *
@@ -200,7 +200,7 @@
 	PyObject *v;
 	if (fontlist == NULL)
 		return;
-	v = PyString_FromString(fontname);
+	v = PyBytes_FromString(fontname);
 	if (v == NULL)
 		err = -1;
 	else {
@@ -240,7 +240,7 @@
 static PyObject *
 fm_fontpath(PyObject *self)
 {
-	return PyString_FromString(fmfontpath());
+	return PyBytes_FromString(fmfontpath());
 }
 
 static PyMethodDef fm_methods[] = {

Modified: python/branches/okkoto-sizeof/Modules/gcmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/gcmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/gcmodule.c	Wed Jun  4 11:24:23 2008
@@ -639,8 +639,8 @@
 	char *cname;
 	/* simple version of instance_repr */
 	PyObject *classname = inst->in_class->cl_name;
-	if (classname != NULL && PyString_Check(classname))
-		cname = PyString_AsString(classname);
+	if (classname != NULL && PyBytes_Check(classname))
+		cname = PyBytes_AsString(classname);
 	else
 		cname = "?";
 	PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
@@ -754,7 +754,7 @@
 	double t1 = 0.0;
 
 	if (delstr == NULL) {
-		delstr = PyString_InternFromString("__del__");
+		delstr = PyBytes_InternFromString("__del__");
 		if (delstr == NULL)
 			Py_FatalError("gc couldn't allocate \"__del__\"");
 	}
@@ -898,7 +898,7 @@
 
 	if (PyErr_Occurred()) {
 		if (gc_str == NULL)
-			gc_str = PyString_FromString("garbage collection");
+			gc_str = PyBytes_FromString("garbage collection");
 		PyErr_WriteUnraisable(gc_str);
 		Py_FatalError("unexpected exception during garbage collection");
 	}

Modified: python/branches/okkoto-sizeof/Modules/gdbmmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/gdbmmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/gdbmmodule.c	Wed Jun  4 11:24:23 2008
@@ -128,10 +128,10 @@
     drec = gdbm_fetch(dp->di_dbm, krec);
     if (drec.dptr == 0) {
         PyErr_SetString(PyExc_KeyError,
-                        PyString_AS_STRING((PyStringObject *)key));
+                        PyBytes_AS_STRING((PyBytesObject *)key));
         return NULL;
     }
-    v = PyString_FromStringAndSize(drec.dptr, drec.dsize);
+    v = PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
     free(drec.dptr);
     return v;
 }
@@ -155,7 +155,7 @@
     if (w == NULL) {
         if (gdbm_delete(dp->di_dbm, krec) < 0) {
             PyErr_SetString(PyExc_KeyError,
-                            PyString_AS_STRING((PyStringObject *)v));
+                            PyBytes_AS_STRING((PyBytesObject *)v));
             return -1;
         }
     }
@@ -188,14 +188,14 @@
                         "GDBM object has already been closed");
         return -1;
     }
-    if (!PyString_Check(arg)) {
+    if (!PyBytes_Check(arg)) {
         PyErr_Format(PyExc_TypeError,
                      "gdbm key must be string, not %.100s",
                      arg->ob_type->tp_name);
         return -1;
     }
-    key.dptr = PyString_AS_STRING(arg);
-    key.dsize = PyString_GET_SIZE(arg);
+    key.dptr = PyBytes_AS_STRING(arg);
+    key.dsize = PyBytes_GET_SIZE(arg);
     return gdbm_exists(dp->di_dbm, key);
 }
 
@@ -255,7 +255,7 @@
 
     key = gdbm_firstkey(dp->di_dbm);
     while (key.dptr) {
-        item = PyString_FromStringAndSize(key.dptr, key.dsize);
+        item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
         if (item == NULL) {
             free(key.dptr);
             Py_DECREF(v);
@@ -306,7 +306,7 @@
     check_dbmobject_open(dp);
     key = gdbm_firstkey(dp->di_dbm);
     if (key.dptr) {
-        v = PyString_FromStringAndSize(key.dptr, key.dsize);
+        v = PyBytes_FromStringAndSize(key.dptr, key.dsize);
         free(key.dptr);
         return v;
     }
@@ -338,7 +338,7 @@
     check_dbmobject_open(dp);
     nextkey = gdbm_nextkey(dp->di_dbm, key);
     if (nextkey.dptr) {
-        v = PyString_FromStringAndSize(nextkey.dptr, nextkey.dsize);
+        v = PyBytes_FromStringAndSize(nextkey.dptr, nextkey.dsize);
         free(nextkey.dptr);
         return v;
     }
@@ -541,7 +541,7 @@
     DbmError = PyErr_NewException("gdbm.error", NULL, NULL);
     if (DbmError != NULL) {
         PyDict_SetItemString(d, "error", DbmError);
-        s = PyString_FromString(dbmmodule_open_flags);
+        s = PyBytes_FromString(dbmmodule_open_flags);
         PyDict_SetItemString(d, "open_flags", s);
         Py_DECREF(s);
     }

Modified: python/branches/okkoto-sizeof/Modules/glmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/glmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/glmodule.c	Wed Jun  4 11:24:23 2008
@@ -593,7 +593,7 @@
 #if 0
 /* Don't check this, it breaks experiments with pixmode(PM_SIZE, ...) */
 	pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
-	if (!PyString_Check(s) || PyString_Size(s) != pixcount*sizeof(long)) {
+	if (!PyBytes_Check(s) || PyBytes_Size(s) != pixcount*sizeof(long)) {
 		PyErr_SetString(PyExc_RuntimeError,
 			   "string arg to lrectwrite has wrong size");
 		return NULL;
@@ -623,10 +623,10 @@
 	if (!PyArg_GetShort(args, 4, 3, &y2))
 		return NULL;
 	pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
-	parray = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
+	parray = PyBytes_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
 	if (parray == NULL)
 		return NULL; /* No memory */
-	lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
+	lrectread(x1, y1, x2, y2, (unsigned long *) PyBytes_AsString(parray));
 	return parray;
 }
 
@@ -642,10 +642,10 @@
 	if ( !PyArg_Parse(args, "hhhhl", &x1, &y1, &x2, &y2, &hints) )
 	  return 0;
 	size = (long)(x2+1-x1) * (long)(y2+1-y1);
-	rv = PyString_FromStringAndSize((char *)NULL, size*sizeof(long));
+	rv = PyBytes_FromStringAndSize((char *)NULL, size*sizeof(long));
 	if ( rv == NULL )
 	  return NULL;
-	parray = (unsigned long *)PyString_AsString(rv);
+	parray = (unsigned long *)PyBytes_AsString(rv);
 	size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
 	if ( size_ret != size ) {
 	    printf("gl_readdisplay: got %ld pixels, expected %ld\n",
@@ -700,16 +700,16 @@
 	pixcount = width*height;
 	packedcount = ((width+packfactor-1)/packfactor) *
 		((height+packfactor-1)/packfactor);
-	if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
+	if (PyBytes_Size(unpacked) != pixcount*sizeof(long)) {
 		PyErr_SetString(PyExc_RuntimeError,
 			   "string arg to packrect has wrong size");
 		return NULL;
 	}
-	packed = PyString_FromStringAndSize((char *)NULL, packedcount);
+	packed = PyBytes_FromStringAndSize((char *)NULL, packedcount);
 	if (packed == NULL)
 		return NULL;
-	parray = (unsigned long *) PyString_AsString(unpacked);
-	p = (unsigned char *) PyString_AsString(packed);
+	parray = (unsigned long *) PyBytes_AsString(unpacked);
+	p = (unsigned char *) PyBytes_AsString(packed);
 	for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
 		for (x = 0; x < width; x += packfactor) {
 			pixel = parray[x];
@@ -758,16 +758,16 @@
 	pixcount = width*height;
 	packedcount = ((width+packfactor-1)/packfactor) *
 		((height+packfactor-1)/packfactor);
-	if (PyString_Size(packed) != packedcount) {
+	if (PyBytes_Size(packed) != packedcount) {
 		PyErr_SetString(PyExc_RuntimeError,
 			   "string arg to unpackrect has wrong size");
 		return NULL;
 	}
-	unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
+	unpacked = PyBytes_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
 	if (unpacked == NULL)
 		return NULL;
-	parray = (unsigned long *) PyString_AsString(unpacked);
-	p = (unsigned char *) PyString_AsString(packed);
+	parray = (unsigned long *) PyBytes_AsString(unpacked);
+	p = (unsigned char *) PyBytes_AsString(packed);
 	if (packfactor == 1 && width*height > 0) {
 		/* Just expand bytes to longs */
 		register int x = width * height;
@@ -799,7 +799,7 @@
 {
 	char buf[20];
 	gversion(buf);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 

Modified: python/branches/okkoto-sizeof/Modules/grpmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/grpmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/grpmodule.c	Wed Jun  4 11:24:23 2008
@@ -47,7 +47,7 @@
         return NULL;
     }
     for (member = p->gr_mem; *member != NULL; member++) {
-        PyObject *x = PyString_FromString(*member);
+        PyObject *x = PyBytes_FromString(*member);
         if (x == NULL || PyList_Append(w, x) != 0) {
             Py_XDECREF(x);
             Py_DECREF(w);
@@ -58,13 +58,13 @@
     }
 
 #define SET(i,val) PyStructSequence_SET_ITEM(v, i, val)
-    SET(setIndex++, PyString_FromString(p->gr_name));
+    SET(setIndex++, PyBytes_FromString(p->gr_name));
 #ifdef __VMS
     SET(setIndex++, Py_None);
     Py_INCREF(Py_None);
 #else
     if (p->gr_passwd)
-	    SET(setIndex++, PyString_FromString(p->gr_passwd));
+	    SET(setIndex++, PyBytes_FromString(p->gr_passwd));
     else {
 	    SET(setIndex++, Py_None);
 	    Py_INCREF(Py_None);
@@ -113,7 +113,7 @@
     py_str_name = PyObject_Str(pyo_name);
     if (!py_str_name)
 	    return NULL;
-    name = PyString_AS_STRING(py_str_name);
+    name = PyBytes_AS_STRING(py_str_name);
     
     if ((p = getgrnam(name)) == NULL) {
 	PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name);

Modified: python/branches/okkoto-sizeof/Modules/imageop.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/imageop.c	(original)
+++ python/branches/okkoto-sizeof/Modules/imageop.c	Wed Jun  4 11:24:23 2008
@@ -54,7 +54,7 @@
 		return 1;
 	if (bcos == NULL) {
 		/* cache string object for future use */
-		bcos = PyString_FromString("backward_compatible");
+		bcos = PyBytes_FromString("backward_compatible");
 		if (bcos == NULL)
 			return 1;
 	}
@@ -97,11 +97,11 @@
 	xstep = (newx1 < newx2)? 1 : -1;
 	ystep = (newy1 < newy2)? 1 : -1;
     
-	rv = PyString_FromStringAndSize(NULL,
+	rv = PyBytes_FromStringAndSize(NULL,
 			     (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size);
 	if ( rv == 0 )
 		return 0;
-	ncp = (char *)PyString_AsString(rv);
+	ncp = (char *)PyBytes_AsString(rv);
 	nsp = (short *)ncp;
 	nlp = (Py_Int32 *)ncp;
 	newy2 += ystep;
@@ -150,10 +150,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, newx*newy*size);
+	rv = PyBytes_FromStringAndSize(NULL, newx*newy*size);
 	if ( rv == 0 )
 		return 0;
-	ncp = (char *)PyString_AsString(rv);
+	ncp = (char *)PyBytes_AsString(rv);
 	nsp = (short *)ncp;
 	nlp = (Py_Int32 *)ncp;
 	for( iy = 0; iy < newy; iy++ ) {
@@ -195,10 +195,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, len);
+	rv = PyBytes_FromStringAndSize(NULL, len);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	if ( width == 1 ) {
 		memcpy(ncp, cp, maxx);		/* Copy first line */
@@ -245,10 +245,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, (len+7)/8);
+	rv = PyBytes_FromStringAndSize(NULL, (len+7)/8);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	bit = 0x80;
 	ovalue = 0;
@@ -286,10 +286,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, (len+1)/2);
+	rv = PyBytes_FromStringAndSize(NULL, (len+1)/2);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 	pos = 0;
 	ovalue = 0;
 	for ( i=0; i < len; i++ ) {
@@ -325,10 +325,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, (len+3)/4);
+	rv = PyBytes_FromStringAndSize(NULL, (len+3)/4);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 	pos = 0;
 	ovalue = 0;
 	for ( i=0; i < len; i++ ) {
@@ -363,10 +363,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, (len+7)/8);
+	rv = PyBytes_FromStringAndSize(NULL, (len+7)/8);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	bit = 0x80;
 	ovalue = 0;
@@ -409,10 +409,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, (len+3)/4);
+	rv = PyBytes_FromStringAndSize(NULL, (len+3)/4);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 	pos = 1;
 	ovalue = 0;
 	for ( i=0; i < len; i++ ) {
@@ -449,10 +449,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen);
+	rv = PyBytes_FromStringAndSize(NULL, nlen);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	bit = 0x80;
 	for ( i=0; i < nlen; i++ ) {
@@ -486,10 +486,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen);
+	rv = PyBytes_FromStringAndSize(NULL, nlen);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	pos = 0;
 	for ( i=0; i < nlen; i++ ) {
@@ -522,10 +522,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen);
+	rv = PyBytes_FromStringAndSize(NULL, nlen);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	pos = 0;
 	for ( i=0; i < nlen; i++ ) {
@@ -559,10 +559,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen);
+	rv = PyBytes_FromStringAndSize(NULL, nlen);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	for ( i=0; i < nlen; i++ ) {
 		/* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
@@ -603,10 +603,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen*4);
+	rv = PyBytes_FromStringAndSize(NULL, nlen*4);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	for ( i=0; i < nlen; i++ ) {
 		/* Bits in source: RRRBBGGG
@@ -653,10 +653,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen);
+	rv = PyBytes_FromStringAndSize(NULL, nlen);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	for ( i=0; i < nlen; i++ ) {
 		if (backward_compatible) {
@@ -698,10 +698,10 @@
 		return 0;
 	}
     
-	rv = PyString_FromStringAndSize(NULL, nlen*4);
+	rv = PyBytes_FromStringAndSize(NULL, nlen*4);
 	if ( rv == 0 )
 		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
+	ncp = (unsigned char *)PyBytes_AsString(rv);
 
 	for ( i=0; i < nlen; i++ ) {
 		value = *cp++;

Modified: python/branches/okkoto-sizeof/Modules/imgfile.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/imgfile.c	(original)
+++ python/branches/okkoto-sizeof/Modules/imgfile.c	Wed Jun  4 11:24:23 2008
@@ -130,12 +130,12 @@
 	}
 
 	if ( zsize == 3 ) zsize = 4;
-	rv = PyString_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
+	rv = PyBytes_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
 	if ( rv == NULL ) {
 		iclose(image);
 		return NULL;
 	}
-	cdatap = PyString_AsString(rv);
+	cdatap = PyBytes_AsString(rv);
 	idatap = (long *)cdatap;
 
 	if (top_to_bottom) {
@@ -319,7 +319,7 @@
 	}
 
 	if ( zsize == 3 ) zsize = 4;
-	rv = PyString_FromStringAndSize(NULL, xwtd*ywtd*zsize);
+	rv = PyBytes_FromStringAndSize(NULL, xwtd*ywtd*zsize);
 	if ( rv == NULL ) {
 		iclose(image);
 		return NULL;
@@ -328,7 +328,7 @@
 	xfac = (float)xsize/(float)xwtd;
 	yfac = (float)ysize/(float)ywtd;
 	PyFPE_END_PROTECT(yfac)
-	cdatap = PyString_AsString(rv);
+	cdatap = PyBytes_AsString(rv);
 	idatap = (long *)cdatap;
 
 	if ( extended ) {

Modified: python/branches/okkoto-sizeof/Modules/itertoolsmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/itertoolsmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/itertoolsmodule.c	Wed Jun  4 11:24:23 2008
@@ -2904,12 +2904,12 @@
 	PyObject *result;
 
         if (lz->cnt != PY_SSIZE_T_MAX)
-		return PyString_FromFormat("count(%zd)", lz->cnt);
+		return PyBytes_FromFormat("count(%zd)", lz->cnt);
 
 	cnt_repr = PyObject_Repr(lz->long_cnt);
 	if (cnt_repr == NULL)
 		return NULL;
-	result = PyString_FromFormat("count(%s)", PyString_AS_STRING(cnt_repr));
+	result = PyBytes_FromFormat("count(%s)", PyBytes_AS_STRING(cnt_repr));
 	Py_DECREF(cnt_repr);
 	return result;
 }
@@ -3221,11 +3221,11 @@
 		return NULL;
 
 	if (ro->cnt == -1)
-		result = PyString_FromFormat("repeat(%s)",
-			PyString_AS_STRING(objrepr));
+		result = PyBytes_FromFormat("repeat(%s)",
+			PyBytes_AS_STRING(objrepr));
 	else
-		result = PyString_FromFormat("repeat(%s, %zd)",
-			PyString_AS_STRING(objrepr), ro->cnt);
+		result = PyBytes_FromFormat("repeat(%s, %zd)",
+			PyBytes_AS_STRING(objrepr), ro->cnt);
 	Py_DECREF(objrepr);
 	return result;
 }	

Modified: python/branches/okkoto-sizeof/Modules/linuxaudiodev.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/linuxaudiodev.c	(original)
+++ python/branches/okkoto-sizeof/Modules/linuxaudiodev.c	Wed Jun  4 11:24:23 2008
@@ -162,17 +162,17 @@
 	
     if (!PyArg_ParseTuple(args, "i:read", &size))
         return NULL;
-    rv = PyString_FromStringAndSize(NULL, size);
+    rv = PyBytes_FromStringAndSize(NULL, size);
     if (rv == NULL)
         return NULL;
-    cp = PyString_AS_STRING(rv);
+    cp = PyBytes_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);
+    _PyBytes_Resize(&rv, count);
     return rv;
 }
 

Modified: python/branches/okkoto-sizeof/Modules/main.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/main.c	(original)
+++ python/branches/okkoto-sizeof/Modules/main.c	Wed Jun  4 11:24:23 2008
@@ -99,6 +99,7 @@
 PYTHONHOME   : alternate <prefix> directory (or <prefix>%c<exec_prefix>).\n\
                The default module search path uses %s.\n\
 PYTHONCASEOK : ignore case in 'import' statements (Windows).\n\
+PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
 ";
 
 
@@ -195,7 +196,7 @@
 {
 	PyObject *argv0 = NULL, *importer = NULL;
 
-	if ((argv0 = PyString_FromString(filename)) && 
+	if ((argv0 = PyBytes_FromString(filename)) && 
 	    (importer = PyImport_GetImporter(argv0)) &&
 	    (importer->ob_type != &PyNullImporter_Type))
 	{

Modified: python/branches/okkoto-sizeof/Modules/mathmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/mathmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/mathmodule.c	Wed Jun  4 11:24:23 2008
@@ -307,6 +307,211 @@
 FUNC1(tanh, tanh, 0,
       "tanh(x)\n\nReturn the hyperbolic tangent of x.")
 
+/* Precision summation function as msum() by Raymond Hettinger in
+   <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
+   enhanced with the exact partials sum and roundoff from Mark
+   Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
+   See those links for more details, proofs and other references.
+
+   Note 1: IEEE 754R floating point semantics are assumed,
+   but the current implementation does not re-establish special
+   value semantics across iterations (i.e. handling -Inf + Inf).
+
+   Note 2:  No provision is made for intermediate overflow handling;
+   therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
+   sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
+   overflow of the first partial sum.
+
+   Note 3: The itermediate values lo, yr, and hi are declared volatile so
+   aggressive compilers won't algebraicly reduce lo to always be exactly 0.0.
+   Also, the volatile declaration forces the values to be stored in memory as
+   regular doubles instead of extended long precision (80-bit) values.  This
+   prevents double rounding because any addition or substraction of two doubles
+   can be resolved exactly into double-sized hi and lo values.  As long as the 
+   hi value gets forced into a double before yr and lo are computed, the extra
+   bits in downstream extended precision operations (x87 for example) will be
+   exactly zero and therefore can be losslessly stored back into a double,
+   thereby preventing double rounding.
+
+   Note 4: A similar implementation is in Modules/cmathmodule.c.
+   Be sure to update both when making changes.
+
+   Note 5: The signature of math.sum() differs from __builtin__.sum()
+   because the start argument doesn't make sense in the context of
+   accurate summation.  Since the partials table is collapsed before
+   returning a result, sum(seq2, start=sum(seq1)) may not equal the
+   accurate result returned by sum(itertools.chain(seq1, seq2)).
+*/
+
+#define NUM_PARTIALS  32  /* initial partials array size, on stack */
+
+/* Extend the partials array p[] by doubling its size. */
+static int                          /* non-zero on error */
+_sum_realloc(double **p_ptr, Py_ssize_t  n,
+             double  *ps,    Py_ssize_t *m_ptr)
+{
+	void *v = NULL;
+	Py_ssize_t m = *m_ptr;
+
+	m += m;  /* double */
+	if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
+		double *p = *p_ptr;
+		if (p == ps) {
+			v = PyMem_Malloc(sizeof(double) * m);
+			if (v != NULL)
+				memcpy(v, ps, sizeof(double) * n);
+		}
+		else
+			v = PyMem_Realloc(p, sizeof(double) * m);
+	}
+	if (v == NULL) {        /* size overflow or no memory */
+		PyErr_SetString(PyExc_MemoryError, "math sum partials");
+		return 1;
+	}
+	*p_ptr = (double*) v;
+	*m_ptr = m;
+	return 0;
+}
+
+/* Full precision summation of a sequence of floats.
+
+   def msum(iterable):
+       partials = []  # sorted, non-overlapping partial sums
+       for x in iterable:
+           i = 0
+           for y in partials:
+               if abs(x) < abs(y):
+                   x, y = y, x
+               hi = x + y
+               lo = y - (hi - x)
+               if lo:
+                   partials[i] = lo
+                   i += 1
+               x = hi
+           partials[i:] = [x]
+       return sum_exact(partials)
+
+   Rounded x+y stored in hi with the roundoff stored in lo.  Together hi+lo
+   are exactly equal to x+y.  The inner loop applies hi/lo summation to each
+   partial so that the list of partial sums remains exact.
+
+   Sum_exact() adds the partial sums exactly and correctly rounds the final
+   result (using the round-half-to-even rule).  The items in partials remain
+   non-zero, non-special, non-overlapping and strictly increasing in
+   magnitude, but possibly not all having the same sign.
+
+   Depends on IEEE 754 arithmetic guarantees and half-even rounding.
+*/
+
+static PyObject*
+math_sum(PyObject *self, PyObject *seq)
+{
+	PyObject *item, *iter, *sum = NULL;
+	Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
+	double x, y, t, ps[NUM_PARTIALS], *p = ps;
+	volatile double hi, yr, lo;
+
+	iter = PyObject_GetIter(seq);
+	if (iter == NULL)
+		return NULL;
+
+	PyFPE_START_PROTECT("sum", Py_DECREF(iter); return NULL)
+
+	for(;;) {           /* for x in iterable */
+		assert(0 <= n && n <= m);
+		assert((m == NUM_PARTIALS && p == ps) ||
+		       (m >  NUM_PARTIALS && p != NULL));
+
+		item = PyIter_Next(iter);
+		if (item == NULL) {
+			if (PyErr_Occurred())
+				goto _sum_error;
+			break;
+		}
+		x = PyFloat_AsDouble(item);
+		Py_DECREF(item);
+		if (PyErr_Occurred())
+			goto _sum_error;
+
+		for (i = j = 0; j < n; j++) {       /* for y in partials */
+			y = p[j];
+			if (fabs(x) < fabs(y)) {
+					t = x; x = y; y = t;
+			}
+			hi = x + y;
+			yr = hi - x;
+			lo = y - yr;
+			if (lo != 0.0)
+				p[i++] = lo;
+			x = hi;
+		}
+		
+		n = i;                              /* ps[i:] = [x] */                   
+		if (x != 0.0) {
+			/* If non-finite, reset partials, effectively
+			   adding subsequent items without roundoff
+			   and yielding correct non-finite results,
+			   provided IEEE 754 rules are observed */
+			if (! Py_IS_FINITE(x))
+				n = 0;
+			else if (n >= m && _sum_realloc(&p, n, ps, &m))
+				goto _sum_error;
+			p[n++] = x;
+		}
+	}
+
+	hi = 0.0;
+	if (n > 0) {
+		hi = p[--n];
+		if (Py_IS_FINITE(hi)) {
+			/* sum_exact(ps, hi) from the top, stop when the sum becomes inexact. */
+			while (n > 0) {
+				x = hi;
+				y = p[--n];
+				assert(fabs(y) < fabs(x));
+				hi = x + y;
+				yr = hi - x;
+				lo = y - yr;
+				if (lo != 0.0)
+					break;
+			}
+			/* Make half-even rounding work across multiple partials.  Needed 
+			   so that sum([1e-16, 1, 1e16]) will round-up the last digit to 
+			   two instead of down to zero (the 1e-16 makes the 1 slightly 
+			   closer to two).  With a potential 1 ULP rounding error fixed-up,
+			   math.sum() can guarantee commutativity. */
+			if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
+			              (lo > 0.0 && p[n-1] > 0.0))) {
+				y = lo * 2.0;
+				x = hi + y;
+				yr = x - hi;
+				if (y == yr)
+					hi = x;
+			}
+		}
+		else {  /* raise exception corresponding to a special value */
+			errno = Py_IS_NAN(hi) ? EDOM : ERANGE;
+			if (is_error(hi))
+				goto _sum_error;
+		}
+	}
+	sum = PyFloat_FromDouble(hi);
+
+_sum_error:
+	PyFPE_END_PROTECT(hi)
+	Py_DECREF(iter);
+	if (p != ps)
+		PyMem_Free(p);
+	return sum;
+}
+
+#undef NUM_PARTIALS
+
+PyDoc_STRVAR(math_sum_doc,
+"sum(iterable)\n\n\
+Return an accurate floating point sum of values in the iterable.\n\
+Assumes IEEE-754 floating point arithmetic.");
+
 static PyObject *
 math_trunc(PyObject *self, PyObject *number)
 {
@@ -760,6 +965,7 @@
 	{"sin",		math_sin,	METH_O,		math_sin_doc},
 	{"sinh",	math_sinh,	METH_O,		math_sinh_doc},
 	{"sqrt",	math_sqrt,	METH_O,		math_sqrt_doc},
+	{"sum",		math_sum,	METH_O,		math_sum_doc},
 	{"tan",		math_tan,	METH_O,		math_tan_doc},
 	{"tanh",	math_tanh,	METH_O,		math_tanh_doc},
  	{"trunc",	math_trunc,	METH_O,		math_trunc_doc},

Modified: python/branches/okkoto-sizeof/Modules/md5module.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/md5module.c	(original)
+++ python/branches/okkoto-sizeof/Modules/md5module.c	Wed Jun  4 11:24:23 2008
@@ -80,7 +80,7 @@
 	mdContext = self->md5;
 	md5_finish(&mdContext, aDigest);
 
-	return PyString_FromStringAndSize((char *)aDigest, 16);
+	return PyBytes_FromStringAndSize((char *)aDigest, 16);
 }
 
 PyDoc_STRVAR(digest_doc,
@@ -113,7 +113,7 @@
 		c = (c>9) ? c+'a'-10 : c + '0';
 		hexdigest[j++] = c;
 	}
-	return PyString_FromStringAndSize((char*)hexdigest, 32);
+	return PyBytes_FromStringAndSize((char*)hexdigest, 32);
 }
 
 
@@ -165,7 +165,7 @@
 static PyObject *
 md5_get_name(PyObject *self, void *closure)
 {
-    return PyString_FromStringAndSize("MD5", 3);
+    return PyBytes_FromStringAndSize("MD5", 3);
 }
 
 static PyGetSetDef md5_getseters[] = {

Modified: python/branches/okkoto-sizeof/Modules/mmapmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/mmapmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/mmapmodule.c	Wed Jun  4 11:24:23 2008
@@ -222,7 +222,7 @@
 	else
 		++eol;		/* we're interested in the position after the
 				   newline. */
-	result = PyString_FromStringAndSize(start, (eol - start));
+	result = PyBytes_FromStringAndSize(start, (eol - start));
 	self->pos += (eol - start);
 	return result;
 }
@@ -700,7 +700,7 @@
 		PyErr_SetString(PyExc_IndexError, "mmap index out of range");
 		return NULL;
 	}
-	return PyString_FromStringAndSize(self->data + i, 1);
+	return PyBytes_FromStringAndSize(self->data + i, 1);
 }
 
 static PyObject *
@@ -718,7 +718,7 @@
 	else if ((size_t)ihigh > self->size)
 		ihigh = self->size;
 
-	return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
+	return PyBytes_FromStringAndSize(self->data + ilow, ihigh-ilow);
 }
 
 static PyObject *
@@ -736,7 +736,7 @@
 				"mmap index out of range");
 			return NULL;
 		}
-		return PyString_FromStringAndSize(self->data + i, 1);
+		return PyBytes_FromStringAndSize(self->data + i, 1);
 	}
 	else if (PySlice_Check(item)) {
 		Py_ssize_t start, stop, step, slicelen;
@@ -747,9 +747,9 @@
 		}
 		
 		if (slicelen <= 0)
-			return PyString_FromStringAndSize("", 0);
+			return PyBytes_FromStringAndSize("", 0);
 		else if (step == 1)
-			return PyString_FromStringAndSize(self->data + start,
+			return PyBytes_FromStringAndSize(self->data + start,
 							  slicelen);
 		else {
 			char *result_buf = (char *)PyMem_Malloc(slicelen);
@@ -762,7 +762,7 @@
 			     cur += step, i++) {
 			     	result_buf[i] = self->data[cur];
 			}
-			result = PyString_FromStringAndSize(result_buf,
+			result = PyBytes_FromStringAndSize(result_buf,
 							    slicelen);
 			PyMem_Free(result_buf);
 			return result;
@@ -815,19 +815,19 @@
 				"mmap object doesn't support slice deletion");
 		return -1;
 	}
-	if (! (PyString_Check(v)) ) {
+	if (! (PyBytes_Check(v)) ) {
 		PyErr_SetString(PyExc_IndexError,
 				"mmap slice assignment must be a string");
 		return -1;
 	}
-	if (PyString_Size(v) != (ihigh - ilow)) {
+	if (PyBytes_Size(v) != (ihigh - ilow)) {
 		PyErr_SetString(PyExc_IndexError,
 				"mmap slice assignment is wrong size");
 		return -1;
 	}
 	if (!is_writeable(self))
 		return -1;
-	buf = PyString_AsString(v);
+	buf = PyBytes_AsString(v);
 	memcpy(self->data + ilow, buf, ihigh-ilow);
 	return 0;
 }
@@ -847,14 +847,14 @@
 				"mmap object doesn't support item deletion");
 		return -1;
 	}
-	if (! (PyString_Check(v) && PyString_Size(v)==1) ) {
+	if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) {
 		PyErr_SetString(PyExc_IndexError,
 				"mmap assignment must be single-character string");
 		return -1;
 	}
 	if (!is_writeable(self))
 		return -1;
-	buf = PyString_AsString(v);
+	buf = PyBytes_AsString(v);
 	self->data[i] = buf[0];
 	return 0;
 }
@@ -882,14 +882,14 @@
 				"mmap object doesn't support item deletion");
 			return -1;
 		}
-		if (!PyString_Check(value) || PyString_Size(value) != 1) {
+		if (!PyBytes_Check(value) || PyBytes_Size(value) != 1) {
 			PyErr_SetString(PyExc_IndexError,
 		          "mmap assignment must be single-character string");
 			return -1;
 		}
 		if (!is_writeable(self))
 			return -1;
-		buf = PyString_AsString(value);
+		buf = PyBytes_AsString(value);
 		self->data[i] = buf[0];
 		return 0;
 	}
@@ -906,12 +906,12 @@
 				"mmap object doesn't support slice deletion");
 			return -1;
 		}
-		if (!PyString_Check(value)) {
+		if (!PyBytes_Check(value)) {
 			PyErr_SetString(PyExc_IndexError,
 				"mmap slice assignment must be a string");
 			return -1;
 		}
-		if (PyString_Size(value) != slicelen) {
+		if (PyBytes_Size(value) != slicelen) {
 			PyErr_SetString(PyExc_IndexError,
 				"mmap slice assignment is wrong size");
 			return -1;
@@ -922,7 +922,7 @@
 		if (slicelen == 0)
 			return 0;
 		else if (step == 1) {
-			const char *buf = PyString_AsString(value);
+			const char *buf = PyBytes_AsString(value);
 
 			if (buf == NULL)
 				return -1;
@@ -931,7 +931,7 @@
 		}
 		else {
 			Py_ssize_t cur, i;
-			const char *buf = PyString_AsString(value);
+			const char *buf = PyBytes_AsString(value);
 			
 			if (buf == NULL)
 				return -1;

Modified: python/branches/okkoto-sizeof/Modules/nismodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/nismodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/nismodule.c	Wed Jun  4 11:24:23 2008
@@ -115,8 +115,8 @@
 		    if (invallen > 0 && inval[invallen-1] == '\0')
 			invallen--;
 		}
-		key = PyString_FromStringAndSize(inkey, inkeylen);
-		val = PyString_FromStringAndSize(inval, invallen);
+		key = PyBytes_FromStringAndSize(inkey, inkeylen);
+		val = PyBytes_FromStringAndSize(inval, invallen);
 		if (key == NULL || val == NULL) {
 			/* XXX error -- don't know how to handle */
 			PyErr_Clear();
@@ -146,7 +146,7 @@
 	if ((err = yp_get_default_domain(&domain)) != 0)
 		return nis_error(err);
 
-	res = PyString_FromStringAndSize (domain, strlen(domain));
+	res = PyBytes_FromStringAndSize (domain, strlen(domain));
 	return res;
 }
 
@@ -178,7 +178,7 @@
 	    len--;
 	if (err != 0)
 		return nis_error(err);
-	res = PyString_FromStringAndSize (match, len);
+	res = PyBytes_FromStringAndSize (match, len);
 	free (match);
 	return res;
 }
@@ -398,7 +398,7 @@
 	if ((list = PyList_New(0)) == NULL)
 		return NULL;
 	for (maps = maps; maps; maps = maps->next) {
-		PyObject *str = PyString_FromString(maps->map);
+		PyObject *str = PyBytes_FromString(maps->map);
 		if (!str || PyList_Append(list, str) < 0)
 		{
 			Py_DECREF(list);

Modified: python/branches/okkoto-sizeof/Modules/operator.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/operator.c	(original)
+++ python/branches/okkoto-sizeof/Modules/operator.c	Wed Jun  4 11:24:23 2008
@@ -508,19 +508,19 @@
 	}
 #endif
 	
-	if (!PyString_Check(attr)) {
+	if (!PyBytes_Check(attr)) {
 		PyErr_SetString(PyExc_TypeError,
 				"attribute name must be a string");
 		return NULL;
 	}
 
-	s = PyString_AS_STRING(attr);
+	s = PyBytes_AS_STRING(attr);
 	Py_INCREF(obj);
 	for (;;) {
 		PyObject *newobj, *str;
 		p = strchr(s, '.');
-		str = p ? PyString_FromStringAndSize(s, (p-s)) : 
-			  PyString_FromString(s);
+		str = p ? PyBytes_FromStringAndSize(s, (p-s)) : 
+			  PyBytes_FromString(s);
 		if (str == NULL) {
 			Py_DECREF(obj);
 			return NULL;

Modified: python/branches/okkoto-sizeof/Modules/ossaudiodev.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/ossaudiodev.c	(original)
+++ python/branches/okkoto-sizeof/Modules/ossaudiodev.c	Wed Jun  4 11:24:23 2008
@@ -366,10 +366,10 @@
 
     if (!PyArg_ParseTuple(args, "i:read", &size))
         return NULL;
-    rv = PyString_FromStringAndSize(NULL, size);
+    rv = PyBytes_FromStringAndSize(NULL, size);
     if (rv == NULL)
         return NULL;
-    cp = PyString_AS_STRING(rv);
+    cp = PyBytes_AS_STRING(rv);
 
     Py_BEGIN_ALLOW_THREADS
     count = read(self->fd, cp, size);
@@ -381,7 +381,7 @@
         return NULL;
     }
     self->icount += count;
-    _PyString_Resize(&rv, count);
+    _PyBytes_Resize(&rv, count);
     return rv;
 }
 
@@ -811,20 +811,20 @@
         Py_INCREF(rval);
     }
     else if (strcmp(name, "name") == 0) {
-        rval = PyString_FromString(self->devicename);
+        rval = PyBytes_FromString(self->devicename);
     }
     else if (strcmp(name, "mode") == 0) {
         /* No need for a "default" in this switch: from newossobject(),
            self->mode can only be one of these three values. */
         switch(self->mode) {
             case O_RDONLY:
-                rval = PyString_FromString("r");
+                rval = PyBytes_FromString("r");
                 break;
             case O_RDWR:
-                rval = PyString_FromString("rw");
+                rval = PyBytes_FromString("rw");
                 break;
             case O_WRONLY:
-                rval = PyString_FromString("w");
+                rval = PyBytes_FromString("w");
                 break;
         }
     }
@@ -913,12 +913,12 @@
     if (labels == NULL || names == NULL)
         goto error2;
     for (i = 0; i < num_controls; i++) {
-        s = PyString_FromString(control_labels[i]);
+        s = PyBytes_FromString(control_labels[i]);
         if (s == NULL)
             goto error2;
         PyList_SET_ITEM(labels, i, s);
 
-        s = PyString_FromString(control_names[i]);
+        s = PyBytes_FromString(control_names[i]);
         if (s == NULL)
             goto error2;
         PyList_SET_ITEM(names, i, s);

Modified: python/branches/okkoto-sizeof/Modules/parsermodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/parsermodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/parsermodule.c	Wed Jun  4 11:24:23 2008
@@ -105,14 +105,14 @@
         }
 
         if (TYPE(n) == encoding_decl)
-            (void) addelem(v, i+1, PyString_FromString(STR(n)));
+            (void) addelem(v, i+1, PyBytes_FromString(STR(n)));
         return (v);
     }
     else if (ISTERMINAL(TYPE(n))) {
         PyObject *result = mkseq(2 + lineno + col_offset);
         if (result != NULL) {
             (void) addelem(result, 0, PyInt_FromLong(TYPE(n)));
-            (void) addelem(result, 1, PyString_FromString(STR(n)));
+            (void) addelem(result, 1, PyBytes_FromString(STR(n)));
             if (lineno == 1)
                 (void) addelem(result, 2, PyInt_FromLong(n->n_lineno));
             if (col_offset == 1)
@@ -689,7 +689,7 @@
             temp = PySequence_GetItem(elem, 1);
             if (temp == NULL)
                 return 0;
-            if (!PyString_Check(temp)) {
+            if (!PyBytes_Check(temp)) {
                 PyErr_Format(parser_error,
                              "second item in terminal node must be a string,"
                              " found %s",
@@ -714,10 +714,10 @@
                     Py_DECREF(o);
                 }
             }
-            len = PyString_GET_SIZE(temp) + 1;
+            len = PyBytes_GET_SIZE(temp) + 1;
             strn = (char *)PyObject_MALLOC(len);
             if (strn != NULL)
-                (void) memcpy(strn, PyString_AS_STRING(temp), len);
+                (void) memcpy(strn, PyBytes_AS_STRING(temp), len);
             Py_DECREF(temp);
         }
         else if (!ISNONTERMINAL(type)) {
@@ -800,10 +800,10 @@
             }
             if (res && encoding) {
                 Py_ssize_t len;
-                len = PyString_GET_SIZE(encoding) + 1;
+                len = PyBytes_GET_SIZE(encoding) + 1;
                 res->n_str = (char *)PyObject_MALLOC(len);
                 if (res->n_str != NULL)
-                    (void) memcpy(res->n_str, PyString_AS_STRING(encoding), len);
+                    (void) memcpy(res->n_str, PyBytes_AS_STRING(encoding), len);
                 Py_DECREF(encoding);
                 Py_DECREF(tuple);
             }
@@ -3284,7 +3284,7 @@
      * If this fails, the import of this module will fail because an
      * exception will be raised here; should we clear the exception?
      */
-    copyreg = PyImport_ImportModuleNoBlock("copyreg");
+    copyreg = PyImport_ImportModuleNoBlock("copy_reg");
     if (copyreg != NULL) {
         PyObject *func, *pickler;
 

Modified: python/branches/okkoto-sizeof/Modules/posixmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/posixmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/posixmodule.c	Wed Jun  4 11:24:23 2008
@@ -375,12 +375,12 @@
 		char *p = strchr(*e, '=');
 		if (p == NULL)
 			continue;
-		k = PyString_FromStringAndSize(*e, (int)(p-*e));
+		k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
 		if (k == NULL) {
 			PyErr_Clear();
 			continue;
 		}
-		v = PyString_FromString(p+1);
+		v = PyBytes_FromString(p+1);
 		if (v == NULL) {
 			PyErr_Clear();
 			Py_DECREF(k);
@@ -400,13 +400,13 @@
 
         rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH);
 	if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
-            PyObject *v = PyString_FromString(buffer);
+            PyObject *v = PyBytes_FromString(buffer);
 		    PyDict_SetItemString(d, "BEGINLIBPATH", v);
             Py_DECREF(v);
         }
         rc = DosQueryExtLIBPATH(buffer, END_LIBPATH);
         if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */
-            PyObject *v = PyString_FromString(buffer);
+            PyObject *v = PyBytes_FromString(buffer);
 		    PyDict_SetItemString(d, "ENDLIBPATH", v);
             Py_DECREF(v);
         }
@@ -1598,7 +1598,7 @@
 #endif
 	if (ret == NULL)
 		return posix_error();
-	return PyString_FromString(ret);
+	return PyBytes_FromString(ret);
 }
 #endif
 
@@ -1620,7 +1620,7 @@
 #endif
 	if (ret == NULL)
 		return posix_error();
-	return PyString_FromString(buffer);
+	return PyBytes_FromString(buffer);
 }
 #endif
 
@@ -1968,7 +1968,7 @@
 	Py_END_ALLOW_THREADS
 	if (res == NULL)
 		return posix_error();
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 #ifdef Py_USING_UNICODE
@@ -2174,7 +2174,7 @@
 		/* Skip over . and .. */
 		if (strcmp(FileData.cFileName, ".") != 0 &&
 		    strcmp(FileData.cFileName, "..") != 0) {
-			v = PyString_FromString(FileData.cFileName);
+			v = PyBytes_FromString(FileData.cFileName);
 			if (v == NULL) {
 				Py_DECREF(d);
 				d = NULL;
@@ -2262,7 +2262,7 @@
             /* Leave Case of Name Alone -- In Native Form */
             /* (Removed Forced Lowercasing Code) */
 
-            v = PyString_FromString(namebuf);
+            v = PyBytes_FromString(namebuf);
             if (v == NULL) {
                 Py_DECREF(d);
                 d = NULL;
@@ -2312,7 +2312,7 @@
 		    (NAMLEN(ep) == 1 ||
 		     (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
 			continue;
-		v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep));
+		v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
 		if (v == NULL) {
 			Py_DECREF(d);
 			d = NULL;
@@ -2397,7 +2397,7 @@
 		return PyUnicode_Decode(outbuf, strlen(outbuf),
 			Py_FileSystemDefaultEncoding, NULL);
 	}
-	return PyString_FromString(outbuf);
+	return PyBytes_FromString(outbuf);
 } /* end of posix__getfullpathname */
 #endif /* MS_WINDOWS */
 
@@ -3062,7 +3062,7 @@
         /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */
         if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) {
 #endif
-		len = PyString_Size(key) + PyString_Size(val) + 2;
+		len = PyBytes_Size(key) + PyBytes_Size(val) + 2;
 		p = PyMem_NEW(char, len);
 		if (p == NULL) {
 			PyErr_NoMemory();
@@ -3292,7 +3292,7 @@
 		{
 			goto fail_2;
 		}
-		len = PyString_Size(key) + PyString_Size(val) + 2;
+		len = PyBytes_Size(key) + PyBytes_Size(val) + 2;
 		p = PyMem_NEW(char, len);
 		if (p == NULL) {
 			PyErr_NoMemory();
@@ -3525,7 +3525,7 @@
 		{
 			goto fail_2;
 		}
-		len = PyString_Size(key) + PyString_Size(val) + 2;
+		len = PyBytes_Size(key) + PyBytes_Size(val) + 2;
 		p = PyMem_NEW(char, len);
 		if (p == NULL) {
 			PyErr_NoMemory();
@@ -3895,7 +3895,7 @@
                                 "unable to determine login name");
         }
         else
-            result = PyString_FromString(name);
+            result = PyBytes_FromString(name);
         errno = old_errno;
 
     return result;
@@ -5884,7 +5884,7 @@
 		return posix_error_with_allocated_filename(path);
 
 	PyMem_Free(path);
-	v = PyString_FromStringAndSize(buf, n);
+	v = PyBytes_FromStringAndSize(buf, n);
 #ifdef Py_USING_UNICODE
 	if (arg_is_unicode) {
 		PyObject *w;
@@ -6289,18 +6289,18 @@
 		errno = EINVAL;
 		return posix_error();
 	}
-	buffer = PyString_FromStringAndSize((char *)NULL, size);
+	buffer = PyBytes_FromStringAndSize((char *)NULL, size);
 	if (buffer == NULL)
 		return NULL;
 	Py_BEGIN_ALLOW_THREADS
-	n = read(fd, PyString_AsString(buffer), size);
+	n = read(fd, PyBytes_AsString(buffer), size);
 	Py_END_ALLOW_THREADS
 	if (n < 0) {
 		Py_DECREF(buffer);
 		return posix_error();
 	}
 	if (n != size)
-		_PyString_Resize(&buffer, n);
+		_PyBytes_Resize(&buffer, n);
 	return buffer;
 }
 
@@ -6647,11 +6647,11 @@
 	/* XXX This can leak memory -- not easy to fix :-( */
 	len = strlen(s1) + strlen(s2) + 2;
 	/* len includes space for a trailing \0; the size arg to
-	   PyString_FromStringAndSize does not count that */
-	newstr = PyString_FromStringAndSize(NULL, (int)len - 1);
+	   PyBytes_FromStringAndSize does not count that */
+	newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1);
 	if (newstr == NULL)
 		return PyErr_NoMemory();
-	newenv = PyString_AS_STRING(newstr);
+	newenv = PyBytes_AS_STRING(newstr);
 	PyOS_snprintf(newenv, len, "%s=%s", s1, s2);
 	if (putenv(newenv)) {
                 Py_DECREF(newstr);
@@ -6727,7 +6727,7 @@
 				"strerror() argument out of range");
 		return NULL;
 	}
-	return PyString_FromString(message);
+	return PyBytes_FromString(message);
 }
 
 
@@ -7009,7 +7009,7 @@
 #endif
     if (name == NULL)
         return PyErr_NoMemory();
-    result = PyString_FromString(name);
+    result = PyBytes_FromString(name);
     free(name);
     return result;
 }
@@ -7066,7 +7066,7 @@
 	Py_XDECREF(err);
 	return NULL;
     }
-    return PyString_FromString(buffer);
+    return PyBytes_FromString(buffer);
 }
 #endif
 
@@ -7095,13 +7095,13 @@
         *valuep = PyInt_AS_LONG(arg);
         return 1;
     }
-    if (PyString_Check(arg)) {
+    if (PyBytes_Check(arg)) {
         /* look up the value in the table using a binary search */
         size_t lo = 0;
 		size_t mid;
         size_t hi = tablesize;
         int cmp;
-        char *confname = PyString_AS_STRING(arg);
+        char *confname = PyBytes_AS_STRING(arg);
         while (lo < hi) {
             mid = (lo + hi) / 2;
             cmp = strcmp(confname, table[mid].name);
@@ -7431,12 +7431,12 @@
         }
         else {
 	    if ((unsigned int)len >= sizeof(buffer)) {
-                result = PyString_FromStringAndSize(NULL, len-1);
+                result = PyBytes_FromStringAndSize(NULL, len-1);
                 if (result != NULL)
-                    confstr(name, PyString_AS_STRING(result), len);
+                    confstr(name, PyBytes_AS_STRING(result), len);
             }
             else
-                result = PyString_FromStringAndSize(buffer, len-1);
+                result = PyBytes_FromStringAndSize(buffer, len-1);
         }
     }
     return result;
@@ -8225,11 +8225,11 @@
 	}
 
 	/* Allocate bytes */
-	result = PyString_FromStringAndSize(NULL, howMany);
+	result = PyBytes_FromStringAndSize(NULL, howMany);
 	if (result != NULL) {
 		/* Get random data */
 		if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*)
-				      PyString_AS_STRING(result))) {
+				      PyBytes_AS_STRING(result))) {
 			Py_DECREF(result);
 			return win32_error("CryptGenRandom", NULL);
 		}
@@ -8259,11 +8259,11 @@
 				    "negative argument not allowed");
 
 	/* Allocate bytes */
-	result = PyString_FromStringAndSize(NULL, howMany);
+	result = PyBytes_FromStringAndSize(NULL, howMany);
 	if (result != NULL) {
 		/* Get random data */
 		if (RAND_pseudo_bytes((unsigned char*)
-				      PyString_AS_STRING(result),
+				      PyBytes_AS_STRING(result),
 				      howMany) < 0) {
 			Py_DECREF(result);
 			return PyErr_Format(PyExc_ValueError,
@@ -8756,6 +8756,11 @@
 #endif
 
 /* GNU extensions. */
+#ifdef O_ASYNC
+        /* Send a SIGIO signal whenever input or output 
+           becomes available on file descriptor */
+        if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1;
+#endif
 #ifdef O_DIRECT
         /* Direct disk access. */
         if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;

Modified: python/branches/okkoto-sizeof/Modules/pwdmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/pwdmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/pwdmodule.c	Wed Jun  4 11:24:23 2008
@@ -49,7 +49,7 @@
 sets(PyObject *v, int i, char* val)
 {
   if (val)
-	  PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
+	  PyStructSequence_SET_ITEM(v, i, PyBytes_FromString(val));
   else {
 	  PyStructSequence_SET_ITEM(v, i, Py_None);
 	  Py_INCREF(Py_None);

Modified: python/branches/okkoto-sizeof/Modules/pyexpat.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/pyexpat.c	(original)
+++ python/branches/okkoto-sizeof/Modules/pyexpat.c	Wed Jun  4 11:24:23 2008
@@ -153,7 +153,7 @@
 {
     PyObject *name = hinfo->nameobj;
     if (name == NULL) {
-        name = PyString_FromString(hinfo->name);
+        name = PyBytes_FromString(hinfo->name);
         hinfo->nameobj = name;
     }
     Py_XINCREF(name);
@@ -205,7 +205,7 @@
         Py_INCREF(Py_None);
         return Py_None;
     }
-    return PyString_FromString(str);
+    return PyBytes_FromString(str);
 }
 
 static PyObject *
@@ -218,7 +218,7 @@
         Py_INCREF(Py_None);
         return Py_None;
     }
-    return PyString_FromStringAndSize((const char *)str, len);
+    return PyBytes_FromStringAndSize((const char *)str, len);
 }
 
 /* Callback routines */
@@ -267,16 +267,16 @@
     PyObject *filename = NULL;
 
     if (handler_info[slot].tb_code == NULL) {
-        code = PyString_FromString("");
+        code = PyBytes_FromString("");
         if (code == NULL)
             goto failed;
-        name = PyString_FromString(func_name);
+        name = PyBytes_FromString(func_name);
         if (name == NULL)
             goto failed;
         nulltuple = PyTuple_New(0);
         if (nulltuple == NULL)
             goto failed;
-        filename = PyString_FromString(__FILE__);
+        filename = PyBytes_FromString(__FILE__);
         handler_info[slot].tb_code =
             PyCode_New(0,		/* argcount */
                        0,		/* nlocals */
@@ -971,13 +971,13 @@
         goto finally;
 
     /* XXX what to do if it returns a Unicode string? */
-    if (!PyString_Check(str)) {
+    if (!PyBytes_Check(str)) {
         PyErr_Format(PyExc_TypeError,
                      "read() did not return a string object (type=%.400s)",
                      Py_TYPE(str)->tp_name);
         goto finally;
     }
-    len = PyString_GET_SIZE(str);
+    len = PyBytes_GET_SIZE(str);
     if (len > buf_size) {
         PyErr_Format(PyExc_ValueError,
                      "read() returned too much data: "
@@ -985,7 +985,7 @@
                      buf_size, len);
         goto finally;
     }
-    memcpy(buf, PyString_AsString(str), len);
+    memcpy(buf, PyBytes_AsString(str), len);
 finally:
     Py_XDECREF(arg);
     Py_XDECREF(str);
@@ -1094,7 +1094,7 @@
             = XML_GetInputContext(self->itself, &offset, &size);
 
         if (buffer != NULL)
-            return PyString_FromStringAndSize(buffer + offset,
+            return PyBytes_FromStringAndSize(buffer + offset,
                                               size - offset);
         else
             Py_RETURN_NONE;
@@ -1511,7 +1511,7 @@
 
 #define APPEND(list, str)				\
         do {						\
-                PyObject *o = PyString_FromString(str);	\
+                PyObject *o = PyBytes_FromString(str);	\
                 if (o != NULL)				\
         	        PyList_Append(list, o);		\
                 Py_XDECREF(o);				\
@@ -1862,7 +1862,7 @@
     while (rev[i] != ' ' && rev[i] != '\0')
         ++i;
 
-    return PyString_FromStringAndSize(rev, i);
+    return PyBytes_FromStringAndSize(rev, i);
 }
 
 /* Initialization function for the module */
@@ -1889,7 +1889,7 @@
 MODULE_INITFUNC(void)
 {
     PyObject *m, *d;
-    PyObject *errmod_name = PyString_FromString(MODULE_NAME ".errors");
+    PyObject *errmod_name = PyBytes_FromString(MODULE_NAME ".errors");
     PyObject *errors_module;
     PyObject *modelmod_name;
     PyObject *model_module;
@@ -1899,7 +1899,7 @@
 
     if (errmod_name == NULL)
         return;
-    modelmod_name = PyString_FromString(MODULE_NAME ".model");
+    modelmod_name = PyBytes_FromString(MODULE_NAME ".model");
     if (modelmod_name == NULL)
         return;
 

Modified: python/branches/okkoto-sizeof/Modules/readline.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/readline.c	(original)
+++ python/branches/okkoto-sizeof/Modules/readline.c	Wed Jun  4 11:24:23 2008
@@ -421,7 +421,7 @@
 static PyObject *
 get_completer_delims(PyObject *self, PyObject *noarg)
 {
-	return PyString_FromString(rl_completer_word_break_characters);
+	return PyBytes_FromString(rl_completer_word_break_characters);
 }
 
 PyDoc_STRVAR(doc_get_completer_delims,
@@ -471,7 +471,7 @@
 	if (!PyArg_ParseTuple(args, "i:index", &idx))
 		return NULL;
 	if ((hist_ent = history_get(idx)))
-		return PyString_FromString(hist_ent->line);
+		return PyBytes_FromString(hist_ent->line);
 	else {
 		Py_RETURN_NONE;
 	}
@@ -503,7 +503,7 @@
 static PyObject *
 get_line_buffer(PyObject *self, PyObject *noarg)
 {
-	return PyString_FromString(rl_line_buffer);
+	return PyBytes_FromString(rl_line_buffer);
 }
 
 PyDoc_STRVAR(doc_get_line_buffer,
@@ -676,7 +676,7 @@
 	if (m == NULL)
 		goto error;
 	for (i = 0; i < num_matches; i++) {
-		s = PyString_FromString(matches[i+1]);
+		s = PyBytes_FromString(matches[i+1]);
 		if (s == NULL)
 			goto error;
 		if (PyList_SetItem(m, i, s) == -1)
@@ -725,7 +725,7 @@
 			result = NULL;
 		}
 		else {
-			char *s = PyString_AsString(r);
+			char *s = PyBytes_AsString(r);
 			if (s == NULL)
 				goto error;
 			result = strdup(s);

Modified: python/branches/okkoto-sizeof/Modules/selectmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/selectmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/selectmodule.c	Wed Jun  4 11:24:23 2008
@@ -1219,7 +1219,7 @@
 		"data=0x%lx udata=%p>",
 		(unsigned long)(s->e.ident), s->e.filter, s->e.flags,
 		s->e.fflags, (long)(s->e.data), s->e.udata);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int

Modified: python/branches/okkoto-sizeof/Modules/sha256module.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/sha256module.c	(original)
+++ python/branches/okkoto-sizeof/Modules/sha256module.c	Wed Jun  4 11:24:23 2008
@@ -432,7 +432,7 @@
 
     SHAcopy(self, &temp);
     sha_final(digest, &temp);
-    return PyString_FromStringAndSize((const char *)digest, self->digestsize);
+    return PyBytes_FromStringAndSize((const char *)digest, self->digestsize);
 }
 
 PyDoc_STRVAR(SHA256_hexdigest__doc__,
@@ -452,10 +452,10 @@
     sha_final(digest, &temp);
 
     /* Create a new string */
-    retval = PyString_FromStringAndSize(NULL, self->digestsize * 2);
+    retval = PyBytes_FromStringAndSize(NULL, self->digestsize * 2);
     if (!retval)
 	    return NULL;
-    hex_digest = PyString_AsString(retval);
+    hex_digest = PyBytes_AsString(retval);
     if (!hex_digest) {
 	    Py_DECREF(retval);
 	    return NULL;
@@ -510,9 +510,9 @@
 SHA256_get_name(PyObject *self, void *closure)
 {
     if (((SHAobject *)self)->digestsize == 32)
-        return PyString_FromStringAndSize("SHA256", 6);
+        return PyBytes_FromStringAndSize("SHA256", 6);
     else
-        return PyString_FromStringAndSize("SHA224", 6);
+        return PyBytes_FromStringAndSize("SHA224", 6);
 }
 
 static PyGetSetDef SHA_getseters[] = {

Modified: python/branches/okkoto-sizeof/Modules/sha512module.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/sha512module.c	(original)
+++ python/branches/okkoto-sizeof/Modules/sha512module.c	Wed Jun  4 11:24:23 2008
@@ -498,7 +498,7 @@
 
     SHAcopy(self, &temp);
     sha512_final(digest, &temp);
-    return PyString_FromStringAndSize((const char *)digest, self->digestsize);
+    return PyBytes_FromStringAndSize((const char *)digest, self->digestsize);
 }
 
 PyDoc_STRVAR(SHA512_hexdigest__doc__,
@@ -518,10 +518,10 @@
     sha512_final(digest, &temp);
 
     /* Create a new string */
-    retval = PyString_FromStringAndSize(NULL, self->digestsize * 2);
+    retval = PyBytes_FromStringAndSize(NULL, self->digestsize * 2);
     if (!retval)
 	    return NULL;
-    hex_digest = PyString_AsString(retval);
+    hex_digest = PyBytes_AsString(retval);
     if (!hex_digest) {
 	    Py_DECREF(retval);
 	    return NULL;
@@ -576,9 +576,9 @@
 SHA512_get_name(PyObject *self, void *closure)
 {
     if (((SHAobject *)self)->digestsize == 64)
-        return PyString_FromStringAndSize("SHA512", 6);
+        return PyBytes_FromStringAndSize("SHA512", 6);
     else
-        return PyString_FromStringAndSize("SHA384", 6);
+        return PyBytes_FromStringAndSize("SHA384", 6);
 }
 
 static PyGetSetDef SHA_getseters[] = {

Modified: python/branches/okkoto-sizeof/Modules/shamodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/shamodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/shamodule.c	Wed Jun  4 11:24:23 2008
@@ -380,7 +380,7 @@
 
     SHAcopy(self, &temp);
     sha_final(digest, &temp);
-    return PyString_FromStringAndSize((const char *)digest, sizeof(digest));
+    return PyBytes_FromStringAndSize((const char *)digest, sizeof(digest));
 }
 
 PyDoc_STRVAR(SHA_hexdigest__doc__,
@@ -400,10 +400,10 @@
     sha_final(digest, &temp);
 
     /* Create a new string */
-    retval = PyString_FromStringAndSize(NULL, sizeof(digest) * 2);
+    retval = PyBytes_FromStringAndSize(NULL, sizeof(digest) * 2);
     if (!retval)
 	    return NULL;
-    hex_digest = PyString_AsString(retval);
+    hex_digest = PyBytes_AsString(retval);
     if (!hex_digest) {
 	    Py_DECREF(retval);
 	    return NULL;
@@ -463,7 +463,7 @@
 static PyObject *
 SHA_get_name(PyObject *self, void *closure)
 {
-    return PyString_FromStringAndSize("SHA1", 4);
+    return PyBytes_FromStringAndSize("SHA1", 4);
 }
 
 static PyGetSetDef SHA_getseters[] = {

Modified: python/branches/okkoto-sizeof/Modules/socketmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/socketmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/socketmodule.c	Wed Jun  4 11:24:23 2008
@@ -911,7 +911,7 @@
 		set_gaierror(error);
 		return NULL;
 	}
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 
@@ -955,7 +955,7 @@
 	sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
 		bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
 		bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 #endif
 
@@ -1002,14 +1002,14 @@
 #ifdef linux
 		if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
 			addrlen -= offsetof(struct sockaddr_un, sun_path);
-			return PyString_FromStringAndSize(a->sun_path,
+			return PyBytes_FromStringAndSize(a->sun_path,
 							  addrlen);
 		}
 		else
 #endif /* linux */
 		{
 			/* regular NULL-terminated string */
-			return PyString_FromString(a->sun_path);
+			return PyBytes_FromString(a->sun_path);
 		}
 	}
 #endif /* AF_UNIX */
@@ -1362,7 +1362,7 @@
 
 			addr = (struct sockaddr_sco *)addr_ret;
 			_BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
-			straddr = PyString_AsString(args);
+			straddr = PyBytes_AsString(args);
 			if (straddr == NULL) {
 				PyErr_SetString(socket_error, "getsockaddrarg: "
 						"wrong format");
@@ -1854,16 +1854,16 @@
 				"getsockopt buflen out of range");
 		return NULL;
 	}
-	buf = PyString_FromStringAndSize((char *)NULL, buflen);
+	buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
 	if (buf == NULL)
 		return NULL;
 	res = getsockopt(s->sock_fd, level, optname,
-			 (void *)PyString_AS_STRING(buf), &buflen);
+			 (void *)PyBytes_AS_STRING(buf), &buflen);
 	if (res < 0) {
 		Py_DECREF(buf);
 		return s->errorhandler();
 	}
-	_PyString_Resize(&buf, buflen);
+	_PyBytes_Resize(&buf, buflen);
 	return buf;
 #endif /* __BEOS__ */
 }
@@ -2386,12 +2386,12 @@
 	}
 
 	/* Allocate a new string. */
-	buf = PyString_FromStringAndSize((char *) 0, recvlen);
+	buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
 	if (buf == NULL)
 		return NULL;
 
 	/* Call the guts */
-	outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
+	outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
 	if (outlen < 0) {
 		/* An error occurred, release the string and return an
 		   error. */
@@ -2401,7 +2401,7 @@
 	if (outlen != recvlen) {
 		/* We did not read as many bytes as we anticipated, resize the
 		   string if possible and be succesful. */
-		if (_PyString_Resize(&buf, outlen) < 0)
+		if (_PyBytes_Resize(&buf, outlen) < 0)
 			/* Oopsy, not so succesful after all. */
 			return NULL;
 	}
@@ -2560,11 +2560,11 @@
 		return NULL;
 	}
 
-	buf = PyString_FromStringAndSize((char *) 0, recvlen);
+	buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
 	if (buf == NULL)
 		return NULL;
 
-	outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
+	outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
 				    recvlen, flags, &addr);
 	if (outlen < 0) {
 		goto finally;
@@ -2573,7 +2573,7 @@
 	if (outlen != recvlen) {
 		/* We did not read as many bytes as we anticipated, resize the
 		   string if possible and be succesful. */
-		if (_PyString_Resize(&buf, outlen) < 0)
+		if (_PyBytes_Resize(&buf, outlen) < 0)
 			/* Oopsy, not so succesful after all. */
 			goto finally;
 	}
@@ -2941,7 +2941,7 @@
 		(long)s->sock_fd, s->sock_family,
 		s->sock_type,
 		s->sock_proto);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 
@@ -3057,7 +3057,7 @@
 	if (res < 0)
 		return set_error();
 	buf[sizeof buf - 1] = '\0';
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 PyDoc_STRVAR(gethostname_doc,
@@ -3143,7 +3143,7 @@
 	if (h->h_aliases) {
 		for (pch = h->h_aliases; *pch != NULL; pch++) {
 			int status;
-			tmp = PyString_FromString(*pch);
+			tmp = PyBytes_FromString(*pch);
 			if (tmp == NULL)
 				goto err;
 
@@ -3432,7 +3432,7 @@
 		PyErr_SetString(socket_error, "port/proto not found");
 		return NULL;
 	}
-	return PyString_FromString(sp->s_name);
+	return PyBytes_FromString(sp->s_name);
 }
 
 PyDoc_STRVAR(getservbyport_doc,
@@ -3734,7 +3734,7 @@
     if (inet_aton != NULL) {
 #endif
 	if (inet_aton(ip_addr, &buf))
-		return PyString_FromStringAndSize((char *)(&buf),
+		return PyBytes_FromStringAndSize((char *)(&buf),
 						  sizeof(buf));
 
 	PyErr_SetString(socket_error,
@@ -3763,7 +3763,7 @@
 			return NULL;
 		}
 	}
-	return PyString_FromStringAndSize((char *) &packed_addr,
+	return PyBytes_FromStringAndSize((char *) &packed_addr,
 					  sizeof(packed_addr));
 
 #ifdef USE_INET_ATON_WEAKLINK
@@ -3797,7 +3797,7 @@
 
 	memcpy(&packed_addr, packed_str, addr_len);
 
-	return PyString_FromString(inet_ntoa(packed_addr));
+	return PyBytes_FromString(inet_ntoa(packed_addr));
 }
 
 #ifdef HAVE_INET_PTON
@@ -3840,11 +3840,11 @@
 			"illegal IP address string passed to inet_pton");
 		return NULL;
 	} else if (af == AF_INET) {
-		return PyString_FromStringAndSize(packed,
+		return PyBytes_FromStringAndSize(packed,
 			sizeof(struct in_addr));
 #ifdef ENABLE_IPV6
 	} else if (af == AF_INET6) {
-		return PyString_FromStringAndSize(packed,
+		return PyBytes_FromStringAndSize(packed,
 			sizeof(struct in6_addr));
 #endif
 	} else {
@@ -3871,7 +3871,7 @@
 	char ip[INET_ADDRSTRLEN + 1];
 #endif
 
-	/* Guarantee NUL-termination for PyString_FromString() below */
+	/* Guarantee NUL-termination for PyBytes_FromString() below */
 	memset((void *) &ip[0], '\0', sizeof(ip));
 
 	if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
@@ -3903,7 +3903,7 @@
 		PyErr_SetFromErrno(socket_error);
 		return NULL;
 	} else {
-		return PyString_FromString(retval);
+		return PyBytes_FromString(retval);
 	}
 
 	/* NOTREACHED */
@@ -3944,9 +3944,9 @@
 		idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
 		if (!idna)
 			return NULL;
-		hptr = PyString_AsString(idna);
-	} else if (PyString_Check(hobj)) {
-		hptr = PyString_AsString(hobj);
+		hptr = PyBytes_AsString(idna);
+	} else if (PyBytes_Check(hobj)) {
+		hptr = PyBytes_AsString(hobj);
 	} else {
 		PyErr_SetString(PyExc_TypeError,
 				"getaddrinfo() argument 1 must be string or None");
@@ -3955,8 +3955,8 @@
 	if (PyInt_Check(pobj)) {
 		PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
 		pptr = pbuf;
-	} else if (PyString_Check(pobj)) {
-		pptr = PyString_AsString(pobj);
+	} else if (PyBytes_Check(pobj)) {
+		pptr = PyBytes_AsString(pobj);
 	} else if (pobj == Py_None) {
 		pptr = (char *)NULL;
 	} else {

Modified: python/branches/okkoto-sizeof/Modules/spwdmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/spwdmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/spwdmodule.c	Wed Jun  4 11:24:23 2008
@@ -60,7 +60,7 @@
 sets(PyObject *v, int i, char* val)
 {
   if (val)
-	  PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
+	  PyStructSequence_SET_ITEM(v, i, PyBytes_FromString(val));
   else {
 	  PyStructSequence_SET_ITEM(v, i, Py_None);
 	  Py_INCREF(Py_None);

Modified: python/branches/okkoto-sizeof/Modules/stropmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/stropmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/stropmodule.c	Wed Jun  4 11:24:23 2008
@@ -47,7 +47,7 @@
 			i = i+1;
 		}
 		if (j < i) {
-			item = PyString_FromStringAndSize(s+j, i-j);
+			item = PyBytes_FromStringAndSize(s+j, i-j);
 			if (item == NULL)
 				goto finally;
 
@@ -61,7 +61,7 @@
 				i = i+1;
 			}
 			if (maxsplit && (countsplit >= maxsplit) && i < len) {
-				item = PyString_FromStringAndSize(
+				item = PyBytes_FromStringAndSize(
                                         s+i, len - i);
 				if (item == NULL)
 					goto finally;
@@ -122,7 +122,7 @@
 	i = j = 0;
 	while (i+n <= len) {
 		if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
-			item = PyString_FromStringAndSize(s+j, i-j);
+			item = PyBytes_FromStringAndSize(s+j, i-j);
 			if (item == NULL)
 				goto fail;
 			err = PyList_Append(list, item);
@@ -137,7 +137,7 @@
 		else
 			i++;
 	}
-	item = PyString_FromStringAndSize(s+j, len-j);
+	item = PyBytes_FromStringAndSize(s+j, len-j);
 	if (item == NULL)
 		goto fail;
 	err = PyList_Append(list, item);
@@ -189,7 +189,7 @@
 	if (seqlen == 1) {
 		/* Optimization if there's only one item */
 		PyObject *item = PySequence_GetItem(seq, 0);
-		if (item && !PyString_Check(item)) {
+		if (item && !PyBytes_Check(item)) {
 			PyErr_SetString(PyExc_TypeError,
 				 "first argument must be sequence of strings");
 			Py_DECREF(item);
@@ -198,9 +198,9 @@
 		return item;
 	}
 
-	if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
+	if (!(res = PyBytes_FromStringAndSize((char*)NULL, sz)))
 		return NULL;
-	p = PyString_AsString(res);
+	p = PyBytes_AsString(res);
 
 	/* optimize for lists, since it's the most common case.  all others
 	 * (tuples and arbitrary sequences) just use the sequence abstract
@@ -209,29 +209,29 @@
 	if (PyList_Check(seq)) {
 		for (i = 0; i < seqlen; i++) {
 			PyObject *item = PyList_GET_ITEM(seq, i);
-			if (!PyString_Check(item)) {
+			if (!PyBytes_Check(item)) {
 				PyErr_SetString(PyExc_TypeError,
 				"first argument must be sequence of strings");
 				Py_DECREF(res);
 				return NULL;
 			}
-			slen = PyString_GET_SIZE(item);
+			slen = PyBytes_GET_SIZE(item);
 			while (reslen + slen + seplen >= sz) {
-				if (_PyString_Resize(&res, sz * 2) < 0)
+				if (_PyBytes_Resize(&res, sz * 2) < 0)
 					return NULL;
 				sz *= 2;
-				p = PyString_AsString(res) + reslen;
+				p = PyBytes_AsString(res) + reslen;
 			}
 			if (i > 0) {
 				memcpy(p, sep, seplen);
 				p += seplen;
 				reslen += seplen;
 			}
-			memcpy(p, PyString_AS_STRING(item), slen);
+			memcpy(p, PyBytes_AS_STRING(item), slen);
 			p += slen;
 			reslen += slen;
 		}
-		_PyString_Resize(&res, reslen);
+		_PyBytes_Resize(&res, reslen);
 		return res;
 	}
 
@@ -245,33 +245,33 @@
 	/* This is now type safe */
 	for (i = 0; i < seqlen; i++) {
 		PyObject *item = getitemfunc(seq, i);
-		if (!item || !PyString_Check(item)) {
+		if (!item || !PyBytes_Check(item)) {
 			PyErr_SetString(PyExc_TypeError,
 				 "first argument must be sequence of strings");
 			Py_DECREF(res);
 			Py_XDECREF(item);
 			return NULL;
 		}
-		slen = PyString_GET_SIZE(item);
+		slen = PyBytes_GET_SIZE(item);
 		while (reslen + slen + seplen >= sz) {
-			if (_PyString_Resize(&res, sz * 2) < 0) {
+			if (_PyBytes_Resize(&res, sz * 2) < 0) {
 				Py_DECREF(item);
 				return NULL;
 			}
 			sz *= 2;
-			p = PyString_AsString(res) + reslen;
+			p = PyBytes_AsString(res) + reslen;
 		}
 		if (i > 0) {
 			memcpy(p, sep, seplen);
 			p += seplen;
 			reslen += seplen;
 		}
-		memcpy(p, PyString_AS_STRING(item), slen);
+		memcpy(p, PyBytes_AS_STRING(item), slen);
 		p += slen;
 		reslen += slen;
 		Py_DECREF(item);
 	}
-	_PyString_Resize(&res, reslen);
+	_PyBytes_Resize(&res, reslen);
 	return res;
 }
 
@@ -369,7 +369,7 @@
 	Py_ssize_t len, i, j;
 
 
-	if (PyString_AsStringAndSize(args, &s, &len))
+	if (PyBytes_AsStringAndSize(args, &s, &len))
 		return NULL;
 
 	i = 0;
@@ -392,7 +392,7 @@
 		return args;
 	}
 	else
-		return PyString_FromStringAndSize(s+i, j-i);
+		return PyBytes_FromStringAndSize(s+i, j-i);
 }
 
 
@@ -450,12 +450,12 @@
 	int changed;
 
 	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
+	if (PyBytes_AsStringAndSize(args, &s, &n))
 		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
+	newstr = PyBytes_FromStringAndSize(NULL, n);
 	if (newstr == NULL)
 		return NULL;
-	s_new = PyString_AsString(newstr);
+	s_new = PyBytes_AsString(newstr);
 	changed = 0;
 	for (i = 0; i < n; i++) {
 		int c = Py_CHARMASK(*s++);
@@ -489,12 +489,12 @@
 	int changed;
 
 	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
+	if (PyBytes_AsStringAndSize(args, &s, &n))
 		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
+	newstr = PyBytes_FromStringAndSize(NULL, n);
 	if (newstr == NULL)
 		return NULL;
-	s_new = PyString_AsString(newstr);
+	s_new = PyBytes_AsString(newstr);
 	changed = 0;
 	for (i = 0; i < n; i++) {
 		int c = Py_CHARMASK(*s++);
@@ -529,12 +529,12 @@
 	int changed;
 
 	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
+	if (PyBytes_AsStringAndSize(args, &s, &n))
 		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
+	newstr = PyBytes_FromStringAndSize(NULL, n);
 	if (newstr == NULL)
 		return NULL;
-	s_new = PyString_AsString(newstr);
+	s_new = PyBytes_AsString(newstr);
 	changed = 0;
 	if (0 < n) {
 		int c = Py_CHARMASK(*s++);
@@ -610,12 +610,12 @@
 	}
 
 	/* Second pass: create output string and fill it */
-	out = PyString_FromStringAndSize(NULL, i+j);
+	out = PyBytes_FromStringAndSize(NULL, i+j);
 	if (out == NULL)
 		return NULL;
 
 	i = 0;
-	q = PyString_AS_STRING(out);
+	q = PyBytes_AS_STRING(out);
 
 	for (p = string; p < e; p++) {
 		if (*p == '\t') {
@@ -695,12 +695,12 @@
 	int changed;
 
 	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
+	if (PyBytes_AsStringAndSize(args, &s, &n))
 		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
+	newstr = PyBytes_FromStringAndSize(NULL, n);
 	if (newstr == NULL)
 		return NULL;
-	s_new = PyString_AsString(newstr);
+	s_new = PyBytes_AsString(newstr);
 	changed = 0;
 	for (i = 0; i < n; i++) {
 		int c = Py_CHARMASK(*s++);
@@ -898,10 +898,10 @@
 		return NULL;
 	}
 
-	result = PyString_FromStringAndSize((char *)NULL, 256);
+	result = PyBytes_FromStringAndSize((char *)NULL, 256);
 	if (result == NULL)
 		return NULL;
-	c = (unsigned char *) PyString_AS_STRING((PyStringObject *)result);
+	c = (unsigned char *) PyBytes_AS_STRING((PyBytesObject *)result);
 	for (i = 0; i < 256; i++)
 		c[i]=(unsigned char)i;
 	for (i = 0; i < fromlen; i++)
@@ -942,12 +942,12 @@
 	}
 
 	table = table1;
-	inlen = PyString_GET_SIZE(input_obj);
-	result = PyString_FromStringAndSize((char *)NULL, inlen);
+	inlen = PyBytes_GET_SIZE(input_obj);
+	result = PyBytes_FromStringAndSize((char *)NULL, inlen);
 	if (result == NULL)
 		return NULL;
-	output_start = output = PyString_AsString(result);
-	input = PyString_AsString(input_obj);
+	output_start = output = PyBytes_AsString(result);
+	input = PyBytes_AsString(input_obj);
 
 	if (dellen == 0) {
 		/* If no deletions are required, use faster code */
@@ -983,7 +983,7 @@
 	}
 	/* Fix the size of the resulting string */
 	if (inlen > 0)
-		_PyString_Resize(&result, output - output_start);
+		_PyBytes_Resize(&result, output - output_start);
 	return result;
 }
 
@@ -1169,7 +1169,7 @@
 		Py_XINCREF(newstr);
 	}
 	else {
-		newstr = PyString_FromStringAndSize(new_s, out_len);
+		newstr = PyBytes_FromStringAndSize(new_s, out_len);
 		PyMem_FREE(new_s);
 	}
 	return newstr;
@@ -1222,7 +1222,7 @@
 		if (isspace(c))
 			buf[n++] = c;
 	}
-	s = PyString_FromStringAndSize(buf, n);
+	s = PyBytes_FromStringAndSize(buf, n);
 	if (s)
 		PyModule_AddObject(m, "whitespace", s);
 
@@ -1232,7 +1232,7 @@
 		if (islower(c))
 			buf[n++] = c;
 	}
-	s = PyString_FromStringAndSize(buf, n);
+	s = PyBytes_FromStringAndSize(buf, n);
 	if (s)
 		PyModule_AddObject(m, "lowercase", s);
 
@@ -1242,7 +1242,7 @@
 		if (isupper(c))
 			buf[n++] = c;
 	}
-	s = PyString_FromStringAndSize(buf, n);
+	s = PyBytes_FromStringAndSize(buf, n);
 	if (s)
 		PyModule_AddObject(m, "uppercase", s);
 }

Modified: python/branches/okkoto-sizeof/Modules/sunaudiodev.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/sunaudiodev.c	(original)
+++ python/branches/okkoto-sizeof/Modules/sunaudiodev.c	Wed Jun  4 11:24:23 2008
@@ -135,11 +135,11 @@
 	
         if (!PyArg_ParseTuple(args, "i:read", &size))
 		return NULL;
-	rv = PyString_FromStringAndSize(NULL, size);
+	rv = PyBytes_FromStringAndSize(NULL, size);
 	if (rv == NULL)
 		return NULL;
 
-	if (!(cp = PyString_AsString(rv)))
+	if (!(cp = PyBytes_AsString(rv)))
 		goto finally;
 
 	count = read(self->x_fd, cp, size);

Modified: python/branches/okkoto-sizeof/Modules/svmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/svmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/svmodule.c	Wed Jun  4 11:24:23 2008
@@ -47,13 +47,13 @@
 	if (!PyArg_Parse(args, "i", &invert))
 		return NULL;
 
-	if (!(output = PyString_FromStringAndSize(
+	if (!(output = PyBytes_FromStringAndSize(
 		NULL,
 		(int)(self->ob_info.width * self->ob_info.height * factor))))
 	{
 		return NULL;
 	}
-	if (!(outstr = PyString_AsString(output))) {
+	if (!(outstr = PyBytes_AsString(output))) {
 		Py_DECREF(output);
 		return NULL;
 	}
@@ -152,9 +152,9 @@
 	fieldsize = self->ob_info.width * self->ob_info.height / 2;
 	obcapture = (char*)self->ob_capture;
 	
-	if (!(f1 = PyString_FromStringAndSize(obcapture, fieldsize)))
+	if (!(f1 = PyBytes_FromStringAndSize(obcapture, fieldsize)))
 		goto finally;
-	if (!(f2 = PyString_FromStringAndSize(obcapture + fieldsize,
+	if (!(f2 = PyBytes_FromStringAndSize(obcapture + fieldsize,
 					      fieldsize)))
 		goto finally;
 	ret = PyTuple_Pack(2, f1, f2);
@@ -535,12 +535,12 @@
 		goto finally;
 	}
 
-	if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
+	if (!(videodata = PyBytes_FromStringAndSize(NULL, bytes)))
 		goto finally;
 
 	/* XXX -- need to do something about the bitvector */
 	{
-		char* str = PyString_AsString(videodata);
+		char* str = PyBytes_AsString(videodata);
 		if (!str)
 			goto finally;
 		
@@ -615,10 +615,10 @@
 	if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes))
 		return sv_error();
 
-	if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
+	if (!(videodata = PyBytes_FromStringAndSize(NULL, bytes)))
 		return NULL;
 	
-	str = PyString_AsString(videodata);
+	str = PyBytes_AsString(videodata);
 	if (!str)
 		goto finally;
 
@@ -849,11 +849,11 @@
 		return NULL;
 	}
 
-	if (!(output = PyString_FromStringAndSize(NULL,
+	if (!(output = PyBytes_FromStringAndSize(NULL,
 					      (int)(width * height * factor))))
 		return NULL;
 
-	str = PyString_AsString(output);
+	str = PyBytes_AsString(output);
 	if (!str) {
 		Py_DECREF(output);
 		return NULL;

Modified: python/branches/okkoto-sizeof/Modules/syslogmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/syslogmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/syslogmodule.c	Wed Jun  4 11:24:23 2008
@@ -71,7 +71,7 @@
 	S_ident_o = new_S_ident_o;
 	Py_INCREF(S_ident_o);
 
-	openlog(PyString_AsString(S_ident_o), logopt, facility);
+	openlog(PyBytes_AsString(S_ident_o), logopt, facility);
 
 	Py_INCREF(Py_None);
 	return Py_None;

Modified: python/branches/okkoto-sizeof/Modules/termios.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/termios.c	(original)
+++ python/branches/okkoto-sizeof/Modules/termios.c	Wed Jun  4 11:24:23 2008
@@ -91,7 +91,7 @@
 		return NULL;
 	for (i = 0; i < NCCS; i++) {
 		ch = (char)mode.c_cc[i];
-		v = PyString_FromStringAndSize(&ch, 1);
+		v = PyBytes_FromStringAndSize(&ch, 1);
 		if (v == NULL)
 			goto err;
 		PyList_SetItem(cc, i, v);
@@ -183,8 +183,8 @@
 	for (i = 0; i < NCCS; i++) {
 		v = PyList_GetItem(cc, i);
 
-		if (PyString_Check(v) && PyString_Size(v) == 1)
-			mode.c_cc[i] = (cc_t) * PyString_AsString(v);
+		if (PyBytes_Check(v) && PyBytes_Size(v) == 1)
+			mode.c_cc[i] = (cc_t) * PyBytes_AsString(v);
 		else if (PyInt_Check(v))
 			mode.c_cc[i] = (cc_t) PyInt_AsLong(v);
 		else {

Modified: python/branches/okkoto-sizeof/Modules/threadmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/threadmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/threadmodule.c	Wed Jun  4 11:24:23 2008
@@ -190,7 +190,7 @@
 	Py_XINCREF(kw);
 	self->kw = kw;
 	self->dict = NULL;	/* making sure */
-	self->key = PyString_FromFormat("thread.local.%p", self);
+	self->key = PyBytes_FromFormat("thread.local.%p", self);
 	if (self->key == NULL) 
 		goto err;
 

Modified: python/branches/okkoto-sizeof/Modules/timemodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/timemodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/timemodule.c	Wed Jun  4 11:24:23 2008
@@ -488,7 +488,7 @@
 			   e.g. an empty format, or %Z when the timezone
 			   is unknown. */
 			PyObject *ret;
-			ret = PyString_FromStringAndSize(outbuf, buflen);
+			ret = PyBytes_FromStringAndSize(outbuf, buflen);
 			free(outbuf);
 			return ret;
 		}
@@ -548,7 +548,7 @@
 	p = asctime(&buf);
 	if (p[24] == '\n')
 		p[24] = '\0';
-	return PyString_FromString(p);
+	return PyBytes_FromString(p);
 }
 
 PyDoc_STRVAR(asctime_doc,
@@ -584,7 +584,7 @@
 	}
 	if (p[24] == '\n')
 		p[24] = '\0';
-	return PyString_FromString(p);
+	return PyBytes_FromString(p);
 }
 
 PyDoc_STRVAR(ctime_doc,

Modified: python/branches/okkoto-sizeof/Modules/unicodedata.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/unicodedata.c	(original)
+++ python/branches/okkoto-sizeof/Modules/unicodedata.c	Wed Jun  4 11:24:23 2008
@@ -54,12 +54,6 @@
     return &_PyUnicode_Database_Records[index];
 }
 
-static const _PyUnicode_DatabaseRecord*
-_getrecord(PyUnicodeObject* v)
-{
-    return _getrecord_ex(*PyUnicode_AS_UNICODE(v));
-}
-
 /* ------------- Previous-version API ------------------------------------- */
 typedef struct previous_version {
     PyObject_HEAD
@@ -92,6 +86,24 @@
 	return (PyObject*)self;
 }
 
+
+static Py_UCS4 getuchar(PyUnicodeObject *obj)
+{
+    Py_UNICODE *v = PyUnicode_AS_UNICODE(obj);
+
+    if (PyUnicode_GET_SIZE(obj) == 1)
+	return *v;
+#ifndef Py_UNICODE_WIDE
+    else if ((PyUnicode_GET_SIZE(obj) == 2) &&
+             (0xD800 <= v[0] && v[0] <= 0xDBFF) &&
+             (0xDC00 <= v[1] && v[1] <= 0xDFFF))
+	return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000;
+#endif
+    PyErr_SetString(PyExc_TypeError,
+                    "need a single Unicode character as parameter");
+    return (Py_UCS4)-1;
+}
+
 /* --- Module API --------------------------------------------------------- */
 
 PyDoc_STRVAR(unicodedata_decimal__doc__,
@@ -108,17 +120,16 @@
     PyObject *defobj = NULL;
     int have_old = 0;
     long rc;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!|O:decimal", &PyUnicode_Type, &v, &defobj))
         return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
         return NULL;
-    }
 
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0) {
             /* unassigned */
             have_old = 1;
@@ -131,7 +142,7 @@
     }
 
     if (!have_old)
-        rc = Py_UNICODE_TODECIMAL(*PyUnicode_AS_UNICODE(v));
+        rc = Py_UNICODE_TODECIMAL(c);
     if (rc < 0) {
 	if (defobj == NULL) {
 	    PyErr_SetString(PyExc_ValueError,
@@ -159,15 +170,14 @@
     PyUnicodeObject *v;
     PyObject *defobj = NULL;
     long rc;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!|O:digit", &PyUnicode_Type, &v, &defobj))
         return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
         return NULL;
-    }
-    rc = Py_UNICODE_TODIGIT(*PyUnicode_AS_UNICODE(v));
+    rc = Py_UNICODE_TODIGIT(c);
     if (rc < 0) {
 	if (defobj == NULL) {
 	    PyErr_SetString(PyExc_ValueError, "not a digit");
@@ -195,17 +205,16 @@
     PyObject *defobj = NULL;
     int have_old = 0;
     double rc;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!|O:numeric", &PyUnicode_Type, &v, &defobj))
         return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
 
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0) {
             /* unassigned */
             have_old = 1;
@@ -218,7 +227,7 @@
     }
 
     if (!have_old)
-        rc = Py_UNICODE_TONUMERIC(*PyUnicode_AS_UNICODE(v));
+        rc = Py_UNICODE_TONUMERIC(c);
     if (rc == -1.0) {
 	if (defobj == NULL) {
 	    PyErr_SetString(PyExc_ValueError, "not a numeric character");
@@ -243,22 +252,21 @@
 {
     PyUnicodeObject *v;
     int index;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!:category",
 			  &PyUnicode_Type, &v))
 	return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
-    index = (int) _getrecord(v)->category;
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
+    index = (int) _getrecord_ex(c)->category;
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed != 0xFF)
             index = old->category_changed;
     }
-    return PyString_FromString(_PyUnicode_CategoryNames[index]);
+    return PyBytes_FromString(_PyUnicode_CategoryNames[index]);
 }
 
 PyDoc_STRVAR(unicodedata_bidirectional__doc__,
@@ -273,24 +281,23 @@
 {
     PyUnicodeObject *v;
     int index;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!:bidirectional",
 			  &PyUnicode_Type, &v))
 	return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
-    index = (int) _getrecord(v)->bidirectional;
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
+    index = (int) _getrecord_ex(c)->bidirectional;
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0)
             index = 0; /* unassigned */
         else if (old->bidir_changed != 0xFF)
             index = old->bidir_changed;
     }
-    return PyString_FromString(_PyUnicode_BidirectionalNames[index]);
+    return PyBytes_FromString(_PyUnicode_BidirectionalNames[index]);
 }
 
 PyDoc_STRVAR(unicodedata_combining__doc__,
@@ -305,18 +312,17 @@
 {
     PyUnicodeObject *v;
     int index;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!:combining",
 			  &PyUnicode_Type, &v))
 	return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
-    index = (int) _getrecord(v)->combining;
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
+    index = (int) _getrecord_ex(c)->combining;
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0)
             index = 0; /* unassigned */
     }
@@ -335,18 +341,17 @@
 {
     PyUnicodeObject *v;
     int index;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!:mirrored",
 			  &PyUnicode_Type, &v))
 	return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
-    index = (int) _getrecord(v)->mirrored;
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
+    index = (int) _getrecord_ex(c)->mirrored;
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0)
             index = 0; /* unassigned */
     }
@@ -364,22 +369,21 @@
 {
     PyUnicodeObject *v;
     int index;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!:east_asian_width",
 			  &PyUnicode_Type, &v))
 	return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
-    index = (int) _getrecord(v)->east_asian_width;
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
+    index = (int) _getrecord_ex(c)->east_asian_width;
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0)
             index = 0; /* unassigned */
     }
-    return PyString_FromString(_PyUnicode_EastAsianWidthNames[index]);
+    return PyBytes_FromString(_PyUnicode_EastAsianWidthNames[index]);
 }
 
 PyDoc_STRVAR(unicodedata_decomposition__doc__,
@@ -396,22 +400,21 @@
     char decomp[256];
     int code, index, count, i;
     unsigned int prefix_index;
+    Py_UCS4 c;
 
     if (!PyArg_ParseTuple(args, "O!:decomposition",
 			  &PyUnicode_Type, &v))
 	return NULL;
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
 
-    code = (int) *PyUnicode_AS_UNICODE(v);
+    code = (int)c;
 
     if (self) {
-        const change_record *old = get_old_record(self, *PyUnicode_AS_UNICODE(v));
+        const change_record *old = get_old_record(self, c);
         if (old->category_changed == 0)
-            return PyString_FromString(""); /* unassigned */
+            return PyBytes_FromString(""); /* unassigned */
     }
 
     if (code < 0 || code >= 0x110000)
@@ -450,7 +453,7 @@
     
     decomp[i] = '\0';
 
-    return PyString_FromString(decomp);
+    return PyBytes_FromString(decomp);
 }
 
 static void
@@ -515,7 +518,7 @@
             /* Hangul Decomposition adds three characters in
                a single step, so we need atleast that much room. */
             if (space < 3) {
-                Py_ssize_t newsize = PyString_GET_SIZE(result) + 10;
+                Py_ssize_t newsize = PyBytes_GET_SIZE(result) + 10;
                 space += 10;
                 if (PyUnicode_Resize(&result, newsize) == -1)
                     return NULL;
@@ -1039,20 +1042,18 @@
 unicodedata_name(PyObject* self, PyObject* args)
 {
     char name[NAME_MAXLEN];
+    Py_UCS4 c;
 
     PyUnicodeObject* v;
     PyObject* defobj = NULL;
     if (!PyArg_ParseTuple(args, "O!|O:name", &PyUnicode_Type, &v, &defobj))
         return NULL;
 
-    if (PyUnicode_GET_SIZE(v) != 1) {
-	PyErr_SetString(PyExc_TypeError,
-			"need a single Unicode character as parameter");
-	return NULL;
-    }
+    c = getuchar(v);
+    if (c == (Py_UCS4)-1)
+        return NULL;
 
-    if (!_getucname(self, (Py_UCS4) *PyUnicode_AS_UNICODE(v),
-                    name, sizeof(name))) {
+    if (!_getucname(self, c, name, sizeof(name))) {
 	if (defobj == NULL) {
 	    PyErr_SetString(PyExc_ValueError, "no such name");
             return NULL;

Modified: python/branches/okkoto-sizeof/Modules/zipimport.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/zipimport.c	(original)
+++ python/branches/okkoto-sizeof/Modules/zipimport.c	Wed Jun  4 11:24:23 2008
@@ -154,11 +154,11 @@
 		}
 	}
 
-	self->archive = PyString_FromString(buf);
+	self->archive = PyBytes_FromString(buf);
 	if (self->archive == NULL)
 		return -1;
 
-	self->prefix = PyString_FromString(prefix);
+	self->prefix = PyBytes_FromString(prefix);
 	if (self->prefix == NULL)
 		return -1;
 
@@ -191,10 +191,10 @@
 	char *archive = "???";
 	char *prefix = "";
 
-	if (self->archive != NULL && PyString_Check(self->archive))
-		archive = PyString_AsString(self->archive);
-	if (self->prefix != NULL && PyString_Check(self->prefix))
-		prefix = PyString_AsString(self->prefix);
+	if (self->archive != NULL && PyBytes_Check(self->archive))
+		archive = PyBytes_AsString(self->archive);
+	if (self->prefix != NULL && PyBytes_Check(self->prefix))
+		prefix = PyBytes_AsString(self->prefix);
 	if (prefix != NULL && *prefix)
 		PyOS_snprintf(buf, sizeof(buf),
 			      "<zipimporter object \"%.300s%c%.150s\">",
@@ -203,7 +203,7 @@
 		PyOS_snprintf(buf, sizeof(buf),
 			      "<zipimporter object \"%.300s\">",
 			      archive);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 /* return fullname.split(".")[-1] */
@@ -263,7 +263,7 @@
 
 	subname = get_subname(fullname);
 
-	len = make_filename(PyString_AsString(self->prefix), subname, path);
+	len = make_filename(PyBytes_AsString(self->prefix), subname, path);
 	if (len < 0)
 		return MI_ERROR;
 
@@ -336,12 +336,12 @@
 		/* add __path__ to the module *before* the code gets
 		   executed */
 		PyObject *pkgpath, *fullpath;
-		char *prefix = PyString_AsString(self->prefix);
+		char *prefix = PyBytes_AsString(self->prefix);
 		char *subname = get_subname(fullname);
 		int err;
 
-		fullpath = PyString_FromFormat("%s%c%s%s",
-					PyString_AsString(self->archive),
+		fullpath = PyBytes_FromFormat("%s%c%s%s",
+					PyBytes_AsString(self->archive),
 					SEP,
 					*prefix ? prefix : "",
 					subname);
@@ -418,9 +418,9 @@
 	}
 	path = buf;
 #endif
-	len = PyString_Size(self->archive);
+	len = PyBytes_Size(self->archive);
 	if ((size_t)len < strlen(path) &&
-	    strncmp(path, PyString_AsString(self->archive), len) == 0 &&
+	    strncmp(path, PyBytes_AsString(self->archive), len) == 0 &&
 	    path[len] == SEP) {
 		path = path + len + 1;
 	}
@@ -430,7 +430,7 @@
 		PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
 		return NULL;
 	}
-	return get_data(PyString_AsString(self->archive), toc_entry);
+	return get_data(PyBytes_AsString(self->archive), toc_entry);
 }
 
 static PyObject *
@@ -467,7 +467,7 @@
 	}
 	subname = get_subname(fullname);
 
-	len = make_filename(PyString_AsString(self->prefix), subname, path);
+	len = make_filename(PyBytes_AsString(self->prefix), subname, path);
 	if (len < 0)
 		return NULL;
 
@@ -480,7 +480,7 @@
 
 	toc_entry = PyDict_GetItemString(self->files, path);
 	if (toc_entry != NULL)
-		return get_data(PyString_AsString(self->archive), toc_entry);
+		return get_data(PyBytes_AsString(self->archive), toc_entry);
 
 	/* we have the module, but no source */
 	Py_INCREF(Py_None);
@@ -843,13 +843,13 @@
 	    PyMarshal_ReadShortFromFile(fp);	/* local header size */
 	file_offset += l;	/* Start of file data */
 
-	raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?
+	raw_data = PyBytes_FromStringAndSize((char *)NULL, compress == 0 ?
 					      data_size : data_size + 1);
 	if (raw_data == NULL) {
 		fclose(fp);
 		return NULL;
 	}
-	buf = PyString_AsString(raw_data);
+	buf = PyBytes_AsString(raw_data);
 
 	err = fseek(fp, file_offset, 0);
 	if (err == 0)
@@ -907,8 +907,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,
@@ -953,14 +953,14 @@
 static PyObject *
 normalize_line_endings(PyObject *source)
 {
-	char *buf, *q, *p = PyString_AsString(source);
+	char *buf, *q, *p = PyBytes_AsString(source);
 	PyObject *fixed_source;
 
 	if (!p)
 		return NULL;
 
 	/* 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 "
@@ -979,7 +979,7 @@
 	}
 	*q++ = '\n';  /* add trailing \n */
 	*q = '\0';
-	fixed_source = PyString_FromString(buf);
+	fixed_source = PyBytes_FromString(buf);
 	PyMem_Free(buf);
 	return fixed_source;
 }
@@ -995,7 +995,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;
@@ -1054,7 +1054,7 @@
 {
 	PyObject *data, *code;
 	char *modpath;
-	char *archive = PyString_AsString(self->archive);
+	char *archive = PyBytes_AsString(self->archive);
 
 	if (archive == NULL)
 		return NULL;
@@ -1063,7 +1063,7 @@
 	if (data == NULL)
 		return NULL;
 
-	modpath = PyString_AsString(PyTuple_GetItem(toc_entry, 0));
+	modpath = PyBytes_AsString(PyTuple_GetItem(toc_entry, 0));
 
 	if (isbytecode) {
 		code = unmarshal_code(modpath, data, mtime);
@@ -1088,7 +1088,7 @@
 
 	subname = get_subname(fullname);
 
-	len = make_filename(PyString_AsString(self->prefix), subname, path);
+	len = make_filename(PyBytes_AsString(self->prefix), subname, path);
 	if (len < 0)
 		return NULL;
 
@@ -1098,7 +1098,7 @@
 		strcpy(path + len, zso->suffix);
 		if (Py_VerboseFlag > 1)
 			PySys_WriteStderr("# trying %s%c%s\n",
-					  PyString_AsString(self->archive),
+					  PyBytes_AsString(self->archive),
 					  SEP, path);
 		toc_entry = PyDict_GetItemString(self->files, path);
 		if (toc_entry != NULL) {
@@ -1120,7 +1120,7 @@
 				continue;
 			}
 			if (code != NULL && p_modpath != NULL)
-				*p_modpath = PyString_AsString(
+				*p_modpath = PyBytes_AsString(
 					PyTuple_GetItem(toc_entry, 0));
 			return code;
 		}

Modified: python/branches/okkoto-sizeof/Modules/zlibmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Modules/zlibmodule.c	(original)
+++ python/branches/okkoto-sizeof/Modules/zlibmodule.c	Wed Jun  4 11:24:23 2008
@@ -96,12 +96,12 @@
     if (self == NULL)
 	return NULL;
     self->is_initialised = 0;
-    self->unused_data = PyString_FromString("");
+    self->unused_data = PyBytes_FromString("");
     if (self->unused_data == NULL) {
 	Py_DECREF(self);
 	return NULL;
     }
-    self->unconsumed_tail = PyString_FromString("");
+    self->unconsumed_tail = PyBytes_FromString("");
     if (self->unconsumed_tail == NULL) {
 	Py_DECREF(self);
 	return NULL;
@@ -174,7 +174,7 @@
 
     err=deflateEnd(&zst);
     if (err == Z_OK)
-	ReturnVal = PyString_FromStringAndSize((char *)output,
+	ReturnVal = PyBytes_FromStringAndSize((char *)output,
 					       zst.total_out);
     else
 	zlib_error(zst, err, "while finishing compression");
@@ -211,12 +211,12 @@
     zst.avail_in = length;
     zst.avail_out = r_strlen;
 
-    if (!(result_str = PyString_FromStringAndSize(NULL, r_strlen)))
+    if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen)))
 	return NULL;
 
     zst.zalloc = (alloc_func)NULL;
     zst.zfree = (free_func)Z_NULL;
-    zst.next_out = (Byte *)PyString_AS_STRING(result_str);
+    zst.next_out = (Byte *)PyBytes_AS_STRING(result_str);
     zst.next_in = (Byte *)input;
     err = inflateInit2(&zst, wsize);
 
@@ -256,11 +256,11 @@
 	    /* fall through */
 	case(Z_OK):
 	    /* need more memory */
-	    if (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
+	    if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) {
 		inflateEnd(&zst);
 		goto error;
 	    }
-	    zst.next_out = (unsigned char *)PyString_AS_STRING(result_str) \
+	    zst.next_out = (unsigned char *)PyBytes_AS_STRING(result_str) \
 		+ r_strlen;
 	    zst.avail_out = r_strlen;
 	    r_strlen = r_strlen << 1;
@@ -278,7 +278,7 @@
 	goto error;
     }
 
-    _PyString_Resize(&result_str, zst.total_out);
+    _PyBytes_Resize(&result_str, zst.total_out);
     return result_str;
 
  error:
@@ -400,7 +400,7 @@
     if (!PyArg_ParseTuple(args, "s#:compress", &input, &inplen))
 	return NULL;
 
-    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
+    if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
 	return NULL;
 
     ENTER_ZLIB
@@ -409,7 +409,7 @@
     self->zst.avail_in = inplen;
     self->zst.next_in = input;
     self->zst.avail_out = length;
-    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);
+    self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal);
 
     Py_BEGIN_ALLOW_THREADS
     err = deflate(&(self->zst), Z_NO_FLUSH);
@@ -418,9 +418,9 @@
     /* while Z_OK and the output buffer is full, there might be more output,
        so extend the output buffer and try again */
     while (err == Z_OK && self->zst.avail_out == 0) {
-	if (_PyString_Resize(&RetVal, length << 1) < 0)
+	if (_PyBytes_Resize(&RetVal, length << 1) < 0)
 	    goto error;
-	self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+	self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) \
 	    + length;
 	self->zst.avail_out = length;
 	length = length << 1;
@@ -440,7 +440,7 @@
 	RetVal = NULL;
 	goto error;
     }
-    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
+    _PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out);
 
  error:
     LEAVE_ZLIB
@@ -479,7 +479,7 @@
     /* limit amount of data allocated to max_length */
     if (max_length && length > max_length)
 	length = max_length;
-    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
+    if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
 	return NULL;
 
     ENTER_ZLIB
@@ -488,7 +488,7 @@
     self->zst.avail_in = inplen;
     self->zst.next_in = input;
     self->zst.avail_out = length;
-    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);
+    self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal);
 
     Py_BEGIN_ALLOW_THREADS
     err = inflate(&(self->zst), Z_SYNC_FLUSH);
@@ -510,9 +510,9 @@
 	if (max_length && length > max_length)
 	    length = max_length;
 
-	if (_PyString_Resize(&RetVal, length) < 0)
+	if (_PyBytes_Resize(&RetVal, length) < 0)
 	    goto error;
-	self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+	self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) \
 	    + old_length;
 	self->zst.avail_out = length - old_length;
 
@@ -525,7 +525,7 @@
        of specified size. Return the unconsumed tail in an attribute.*/
     if(max_length) {
 	Py_DECREF(self->unconsumed_tail);
-	self->unconsumed_tail = PyString_FromStringAndSize((char *)self->zst.next_in,
+	self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in,
 							   self->zst.avail_in);
 	if(!self->unconsumed_tail) {
 	    Py_DECREF(RetVal);
@@ -542,7 +542,7 @@
     */
     if (err == Z_STREAM_END) {
 	Py_XDECREF(self->unused_data);  /* Free original empty string */
-	self->unused_data = PyString_FromStringAndSize(
+	self->unused_data = PyBytes_FromStringAndSize(
 	    (char *)self->zst.next_in, self->zst.avail_in);
 	if (self->unused_data == NULL) {
 	    Py_DECREF(RetVal);
@@ -559,7 +559,7 @@
 	goto error;
     }
 
-    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
+    _PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out);
 
  error:
     LEAVE_ZLIB
@@ -589,10 +589,10 @@
     /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
        doing any work at all; just return an empty string. */
     if (flushmode == Z_NO_FLUSH) {
-	return PyString_FromStringAndSize(NULL, 0);
+	return PyBytes_FromStringAndSize(NULL, 0);
     }
 
-    if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
+    if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
 	return NULL;
 
     ENTER_ZLIB
@@ -600,7 +600,7 @@
     start_total_out = self->zst.total_out;
     self->zst.avail_in = 0;
     self->zst.avail_out = length;
-    self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal);
+    self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal);
 
     Py_BEGIN_ALLOW_THREADS
     err = deflate(&(self->zst), flushmode);
@@ -609,9 +609,9 @@
     /* while Z_OK and the output buffer is full, there might be more output,
        so extend the output buffer and try again */
     while (err == Z_OK && self->zst.avail_out == 0) {
-	if (_PyString_Resize(&RetVal, length << 1) < 0)
+	if (_PyBytes_Resize(&RetVal, length << 1) < 0)
 	    goto error;
-	self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+	self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) \
 	    + length;
 	self->zst.avail_out = length;
 	length = length << 1;
@@ -646,7 +646,7 @@
 	goto error;
     }
 
-    _PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
+    _PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out);
 
  error:
     LEAVE_ZLIB
@@ -778,7 +778,7 @@
 	PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
 	return NULL;
     }
-    if (!(retval = PyString_FromStringAndSize(NULL, length)))
+    if (!(retval = PyBytes_FromStringAndSize(NULL, length)))
 	return NULL;
 
 
@@ -786,7 +786,7 @@
 
     start_total_out = self->zst.total_out;
     self->zst.avail_out = length;
-    self->zst.next_out = (Byte *)PyString_AS_STRING(retval);
+    self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval);
 
     Py_BEGIN_ALLOW_THREADS
     err = inflate(&(self->zst), Z_FINISH);
@@ -795,9 +795,9 @@
     /* while Z_OK and the output buffer is full, there might be more output,
        so extend the output buffer and try again */
     while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) {
-	if (_PyString_Resize(&retval, length << 1) < 0)
+	if (_PyBytes_Resize(&retval, length << 1) < 0)
 	    goto error;
-	self->zst.next_out = (Byte *)PyString_AS_STRING(retval) + length;
+	self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length;
 	self->zst.avail_out = length;
 	length = length << 1;
 
@@ -819,7 +819,7 @@
 	    goto error;
 	}
     }
-    _PyString_Resize(&retval, self->zst.total_out - start_total_out);
+    _PyBytes_Resize(&retval, self->zst.total_out - start_total_out);
 
 error:
 
@@ -1027,7 +1027,7 @@
     PyModule_AddIntConstant(m, "Z_SYNC_FLUSH", Z_SYNC_FLUSH);
     PyModule_AddIntConstant(m, "Z_FULL_FLUSH", Z_FULL_FLUSH);
 
-    ver = PyString_FromString(ZLIB_VERSION);
+    ver = PyBytes_FromString(ZLIB_VERSION);
     if (ver != NULL)
 	PyModule_AddObject(m, "ZLIB_VERSION", ver);
 

Modified: python/branches/okkoto-sizeof/Objects/abstract.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/abstract.c	(original)
+++ python/branches/okkoto-sizeof/Objects/abstract.c	Wed Jun  4 11:24:23 2008
@@ -105,7 +105,7 @@
 
 	/* cache a hashed version of the attribute string */
 	if (hintstrobj == NULL) {
-		hintstrobj = PyString_InternFromString("__length_hint__");
+		hintstrobj = PyBytes_InternFromString("__length_hint__");
 		if (hintstrobj == NULL)
 			goto defaultcase;
 	}
@@ -227,7 +227,7 @@
 		null_error();
 		return -1;
 	}
-	okey = PyString_FromString(key);
+	okey = PyBytes_FromString(key);
 	if (okey == NULL)
 		return -1;
 	ret = PyObject_DelItem(o, okey);
@@ -729,21 +729,21 @@
 	/* Initialize cached value */
 	if (str__format__ == NULL) {
 		/* Initialize static variable needed by _PyType_Lookup */
-		str__format__ = PyString_InternFromString("__format__");
+		str__format__ = PyBytes_InternFromString("__format__");
 		if (str__format__ == NULL)
 			goto done;
 	}
 
 	/* If no format_spec is provided, use an empty string */
 	if (format_spec == NULL) {
-		empty = PyString_FromStringAndSize(NULL, 0);
+		empty = PyBytes_FromStringAndSize(NULL, 0);
 		format_spec = empty;
 	}
 
 	/* Check the format_spec type, and make sure it's str or unicode */
 	if (PyUnicode_Check(format_spec))
 		spec_is_unicode = 1;
-	else if (PyString_Check(format_spec))
+	else if (PyBytes_Check(format_spec))
 		spec_is_unicode = 0;
 	else {
 		PyErr_Format(PyExc_TypeError,
@@ -823,7 +823,7 @@
 	/* Check the result type, and make sure it's str or unicode */
 	if (PyUnicode_Check(result))
 		result_is_unicode = 1;
-	else if (PyString_Check(result))
+	else if (PyBytes_Check(result))
 		result_is_unicode = 0;
 	else {
 		PyErr_Format(PyExc_TypeError,
@@ -1541,7 +1541,7 @@
 	const char *type_name;
 	static PyObject *int_name = NULL;
 	if (int_name == NULL) {
-		int_name = PyString_InternFromString("__int__");
+		int_name = PyBytes_InternFromString("__int__");
 		if (int_name == NULL)
 			return NULL;
 	}
@@ -1567,7 +1567,7 @@
 
 non_integral_error:
 	if (PyInstance_Check(integral)) {
-		type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
+		type_name = PyBytes_AS_STRING(((PyInstanceObject *)integral)
 					       ->in_class->cl_name);
 	}
 	else {
@@ -1589,7 +1589,7 @@
 	Py_ssize_t buffer_len;
 
 	if (trunc_name == NULL) {
-		trunc_name = PyString_InternFromString("__trunc__");
+		trunc_name = PyBytes_InternFromString("__trunc__");
 		if (trunc_name == NULL)
 			return NULL;
 	}
@@ -1629,9 +1629,9 @@
 	}
 	PyErr_Clear();  /* It's not an error if  o.__trunc__ doesn't exist. */
 
-	if (PyString_Check(o))
-		return int_from_string(PyString_AS_STRING(o),
-				       PyString_GET_SIZE(o));
+	if (PyBytes_Check(o))
+		return int_from_string(PyBytes_AS_STRING(o),
+				       PyBytes_GET_SIZE(o));
 #ifdef Py_USING_UNICODE
 	if (PyUnicode_Check(o))
 		return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
@@ -1674,7 +1674,7 @@
 	Py_ssize_t buffer_len;
 
 	if (trunc_name == NULL) {
-		trunc_name = PyString_InternFromString("__trunc__");
+		trunc_name = PyBytes_InternFromString("__trunc__");
 		if (trunc_name == NULL)
 			return NULL;
 	}
@@ -1716,13 +1716,13 @@
 	}
 	PyErr_Clear();  /* It's not an error if  o.__trunc__ doesn't exist. */
 
-	if (PyString_Check(o))
+	if (PyBytes_Check(o))
 		/* need to do extra error checking that PyLong_FromString()
 		 * doesn't do.  In particular long('9.5') must raise an
 		 * exception, not truncate the float.
 		 */
-		return long_from_string(PyString_AS_STRING(o),
-					PyString_GET_SIZE(o));
+		return long_from_string(PyBytes_AS_STRING(o),
+					PyBytes_GET_SIZE(o));
 #ifdef Py_USING_UNICODE
 	if (PyUnicode_Check(o))
 		/* The above check is done in PyLong_FromUnicode(). */
@@ -2413,7 +2413,7 @@
 	if (key == NULL)
 		return null_error();
 
-	okey = PyString_FromString(key);
+	okey = PyBytes_FromString(key);
 	if (okey == NULL)
 		return NULL;
 	r = PyObject_GetItem(o, okey);
@@ -2432,7 +2432,7 @@
 		return -1;
 	}
 
-	okey = PyString_FromString(key);
+	okey = PyBytes_FromString(key);
 	if (okey == NULL)
 		return -1;
 	r = PyObject_SetItem(o, okey, value);
@@ -2760,7 +2760,7 @@
 	PyObject *bases;
 
 	if (__bases__ == NULL) {
-		__bases__ = PyString_InternFromString("__bases__");
+		__bases__ = PyBytes_InternFromString("__bases__");
 		if (__bases__ == NULL)
 			return NULL;
 	}
@@ -2838,7 +2838,7 @@
 	int retval = 0;
 
 	if (__class__ == NULL) {
-		__class__ = PyString_InternFromString("__class__");
+		__class__ = PyBytes_InternFromString("__class__");
 		if (__class__ == NULL)
 			return -1;
 	}
@@ -2914,7 +2914,7 @@
 		return 1;
 
 	if (name == NULL) {
-		name = PyString_InternFromString("__instancecheck__");
+		name = PyBytes_InternFromString("__instancecheck__");
 		if (name == NULL)
 			return -1;
 	}
@@ -2998,7 +2998,7 @@
 	PyErr_Fetch(&t, &v, &tb);
 	
 	if (name == NULL) {
-		name = PyString_InternFromString("__subclasscheck__");
+		name = PyBytes_InternFromString("__subclasscheck__");
 		if (name == NULL)
 			return -1;
 	}

Modified: python/branches/okkoto-sizeof/Objects/boolobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/boolobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/boolobject.c	Wed Jun  4 11:24:23 2008
@@ -25,10 +25,10 @@
 
 	if (self->ob_ival)
 		s = true_str ? true_str :
-			(true_str = PyString_InternFromString("True"));
+			(true_str = PyBytes_InternFromString("True"));
 	else
 		s = false_str ? false_str :
-			(false_str = PyString_InternFromString("False"));
+			(false_str = PyBytes_InternFromString("False"));
 	Py_XINCREF(s);
 	return s;
 }

Modified: python/branches/okkoto-sizeof/Objects/bufferobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/bufferobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/bufferobject.c	Wed Jun  4 11:24:23 2008
@@ -287,13 +287,13 @@
 	const char *status = self->b_readonly ? "read-only" : "read-write";
 
 	if ( self->b_base == NULL )
-		return PyString_FromFormat("<%s buffer ptr %p, size %zd at %p>",
+		return PyBytes_FromFormat("<%s buffer ptr %p, size %zd at %p>",
 					   status,
 					   self->b_ptr,
 					   self->b_size,
 					   self);
 	else
-		return PyString_FromFormat(
+		return PyBytes_FromFormat(
 			"<%s buffer for %p, size %zd, offset %zd at %p>",
 			status,
 			self->b_base,
@@ -318,7 +318,7 @@
 	 * underlying memory is immutable.  b_readonly is a necessary but not
 	 * sufficient condition for a buffer to be hashable.  Perhaps it would
 	 * be better to only allow hashing if the underlying object is known to
-	 * be immutable (e.g. PyString_Check() is true).  Another idea would
+	 * be immutable (e.g. PyBytes_Check() is true).  Another idea would
 	 * be to call tp_hash on the underlying object and see if it raises
 	 * an error. */
 	if ( !self->b_readonly )
@@ -349,7 +349,7 @@
 	Py_ssize_t size;
 	if (!get_buf(self, &ptr, &size, ANY_BUFFER))
 		return NULL;
-	return PyString_FromStringAndSize((const char *)ptr, size);
+	return PyBytes_FromStringAndSize((const char *)ptr, size);
 }
 
 /* Sequence methods */
@@ -401,10 +401,10 @@
 	if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
 		return NULL;
 
- 	ob = PyString_FromStringAndSize(NULL, size + count);
+ 	ob = PyBytes_FromStringAndSize(NULL, size + count);
 	if ( ob == NULL )
 		return NULL;
- 	p = PyString_AS_STRING(ob);
+ 	p = PyBytes_AS_STRING(ob);
  	memcpy(p, ptr1, size);
  	memcpy(p + size, ptr2, count);
 
@@ -426,11 +426,11 @@
 		count = 0;
 	if (!get_buf(self, &ptr, &size, ANY_BUFFER))
 		return NULL;
-	ob = PyString_FromStringAndSize(NULL, size * count);
+	ob = PyBytes_FromStringAndSize(NULL, size * count);
 	if ( ob == NULL )
 		return NULL;
 
-	p = PyString_AS_STRING(ob);
+	p = PyBytes_AS_STRING(ob);
 	while ( count-- )
 	{
 	    memcpy(p, ptr, size);
@@ -454,7 +454,7 @@
 		PyErr_SetString(PyExc_IndexError, "buffer index out of range");
 		return NULL;
 	}
-	return PyString_FromStringAndSize((char *)ptr + idx, 1);
+	return PyBytes_FromStringAndSize((char *)ptr + idx, 1);
 }
 
 static PyObject *
@@ -472,7 +472,7 @@
 		right = size;
 	if ( right < left )
 		right = left;
-	return PyString_FromStringAndSize((char *)ptr + left,
+	return PyBytes_FromStringAndSize((char *)ptr + left,
 					  right - left);
 }
 
@@ -501,9 +501,9 @@
 		}
 
 		if (slicelength <= 0)
-			return PyString_FromStringAndSize("", 0);
+			return PyBytes_FromStringAndSize("", 0);
 		else if (step == 1)
-			return PyString_FromStringAndSize((char *)p + start,
+			return PyBytes_FromStringAndSize((char *)p + start,
 							  stop - start);
 		else {
 			PyObject *result;
@@ -518,7 +518,7 @@
 				result_buf[i] = source_buf[cur];
 			}
 
-			result = PyString_FromStringAndSize(result_buf,
+			result = PyBytes_FromStringAndSize(result_buf,
 							    slicelength);
 			PyMem_Free(result_buf);
 			return result;

Modified: python/branches/okkoto-sizeof/Objects/bytes_methods.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/bytes_methods.c	(original)
+++ python/branches/okkoto-sizeof/Objects/bytes_methods.c	Wed Jun  4 11:24:23 2008
@@ -462,11 +462,11 @@
 	Py_ssize_t i;
 
         /*
-	newobj = PyString_FromStringAndSize(NULL, len);
+	newobj = PyBytes_FromStringAndSize(NULL, len);
 	if (!newobj)
 		return NULL;
 
-	s = PyString_AS_STRING(newobj);
+	s = PyBytes_AS_STRING(newobj);
         */
 
 	Py_MEMCPY(result, cptr, len);
@@ -490,11 +490,11 @@
 	Py_ssize_t i;
 
         /*
-	newobj = PyString_FromStringAndSize(NULL, len);
+	newobj = PyBytes_FromStringAndSize(NULL, len);
 	if (!newobj)
 		return NULL;
 
-	s = PyString_AS_STRING(newobj);
+	s = PyBytes_AS_STRING(newobj);
         */
 
 	Py_MEMCPY(result, cptr, len);
@@ -520,10 +520,10 @@
 	int previous_is_cased = 0;
 
         /*
-	newobj = PyString_FromStringAndSize(NULL, len);
+	newobj = PyBytes_FromStringAndSize(NULL, len);
 	if (newobj == NULL)
 		return NULL;
-	s_new = PyString_AsString(newobj);
+	s_new = PyBytes_AsString(newobj);
         */
 	for (i = 0; i < len; i++) {
 		int c = Py_CHARMASK(*s++);
@@ -553,10 +553,10 @@
 	Py_ssize_t i;
 
         /*
-	newobj = PyString_FromStringAndSize(NULL, len);
+	newobj = PyBytes_FromStringAndSize(NULL, len);
 	if (newobj == NULL)
 		return NULL;
-	s_new = PyString_AsString(newobj);
+	s_new = PyBytes_AsString(newobj);
         */
 	if (0 < len) {
 		int c = Py_CHARMASK(*s++);
@@ -589,10 +589,10 @@
 	Py_ssize_t i;
 
         /*
-	newobj = PyString_FromStringAndSize(NULL, len);
+	newobj = PyBytes_FromStringAndSize(NULL, len);
 	if (newobj == NULL)
 		return NULL;
-	s_new = PyString_AsString(newobj);
+	s_new = PyBytes_AsString(newobj);
         */
 	for (i = 0; i < len; i++) {
 		int c = Py_CHARMASK(*s++);

Modified: python/branches/okkoto-sizeof/Objects/cellobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/cellobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/cellobject.c	Wed Jun  4 11:24:23 2008
@@ -73,9 +73,9 @@
 cell_repr(PyCellObject *op)
 {
 	if (op->ob_ref == NULL)
-		return PyString_FromFormat("<cell at %p: empty>", op);
+		return PyBytes_FromFormat("<cell at %p: empty>", op);
 
-	return PyString_FromFormat("<cell at %p: %.80s object at %p>",
+	return PyBytes_FromFormat("<cell at %p: %.80s object at %p>",
 				   op, op->ob_ref->ob_type->tp_name,
 				   op->ob_ref);
 }

Modified: python/branches/okkoto-sizeof/Objects/classobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/classobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/classobject.c	Wed Jun  4 11:24:23 2008
@@ -32,21 +32,21 @@
 	PyClassObject *op, *dummy;
 	static PyObject *docstr, *modstr, *namestr;
 	if (docstr == NULL) {
-		docstr= PyString_InternFromString("__doc__");
+		docstr= PyBytes_InternFromString("__doc__");
 		if (docstr == NULL)
 			return NULL;
 	}
 	if (modstr == NULL) {
-		modstr= PyString_InternFromString("__module__");
+		modstr= PyBytes_InternFromString("__module__");
 		if (modstr == NULL)
 			return NULL;
 	}
 	if (namestr == NULL) {
-		namestr= PyString_InternFromString("__name__");
+		namestr= PyBytes_InternFromString("__name__");
 		if (namestr == NULL)
 			return NULL;
 	}
-	if (name == NULL || !PyString_Check(name)) {
+	if (name == NULL || !PyBytes_Check(name)) {
 		PyErr_SetString(PyExc_TypeError,
 				"PyClass_New: name must be a string");
 		return NULL;
@@ -101,13 +101,13 @@
 	}
 
 	if (getattrstr == NULL) {
-		getattrstr = PyString_InternFromString("__getattr__");
+		getattrstr = PyBytes_InternFromString("__getattr__");
 		if (getattrstr == NULL)
 			goto alloc_error;
-		setattrstr = PyString_InternFromString("__setattr__");
+		setattrstr = PyBytes_InternFromString("__setattr__");
 		if (setattrstr == NULL)
 			goto alloc_error;
-		delattrstr = PyString_InternFromString("__delattr__");
+		delattrstr = PyBytes_InternFromString("__delattr__");
 		if (delattrstr == NULL)
 			goto alloc_error;
 	}
@@ -222,7 +222,7 @@
 class_getattr(register PyClassObject *op, PyObject *name)
 {
 	register PyObject *v;
-	register char *sname = PyString_AsString(name);
+	register char *sname = PyBytes_AsString(name);
 	PyClassObject *klass;
 	descrgetfunc f;
 
@@ -253,7 +253,7 @@
 	if (v == NULL) {
 		PyErr_Format(PyExc_AttributeError,
 			     "class %.50s has no attribute '%.400s'",
-			     PyString_AS_STRING(op->cl_name), sname);
+			     PyBytes_AS_STRING(op->cl_name), sname);
 		return NULL;
 	}
 	f = TP_DESCR_GET(v->ob_type);
@@ -316,9 +316,9 @@
 static char *
 set_name(PyClassObject *c, PyObject *v)
 {
-	if (v == NULL || !PyString_Check(v))
+	if (v == NULL || !PyBytes_Check(v))
 		return "__name__ must be a string object";
-	if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
+	if (strlen(PyBytes_AS_STRING(v)) != (size_t)PyBytes_GET_SIZE(v))
 		return "__name__ must not contain null bytes";
 	set_slot(&c->cl_name, v);
 	return "";
@@ -333,9 +333,9 @@
 			   "classes are read-only in restricted mode");
 		return -1;
 	}
-	sname = PyString_AsString(name);
+	sname = PyBytes_AsString(name);
 	if (sname[0] == '_' && sname[1] == '_') {
-		Py_ssize_t n = PyString_Size(name);
+		Py_ssize_t n = PyBytes_Size(name);
 		if (sname[n-1] == '_' && sname[n-2] == '_') {
 			char *err = NULL;
 			if (strcmp(sname, "__dict__") == 0)
@@ -365,7 +365,7 @@
 		if (rv < 0)
 			PyErr_Format(PyExc_AttributeError,
 				     "class %.50s has no attribute '%.400s'",
-				     PyString_AS_STRING(op->cl_name), sname);
+				     PyBytes_AS_STRING(op->cl_name), sname);
 		return rv;
 	}
 	else
@@ -377,15 +377,15 @@
 {
 	PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
 	char *name;
-	if (op->cl_name == NULL || !PyString_Check(op->cl_name))
+	if (op->cl_name == NULL || !PyBytes_Check(op->cl_name))
 		name = "?";
 	else
-		name = PyString_AsString(op->cl_name);
-	if (mod == NULL || !PyString_Check(mod))
-		return PyString_FromFormat("<class ?.%s at %p>", name, op);
+		name = PyBytes_AsString(op->cl_name);
+	if (mod == NULL || !PyBytes_Check(mod))
+		return PyBytes_FromFormat("<class ?.%s at %p>", name, op);
 	else
-		return PyString_FromFormat("<class %s.%s at %p>",
-					   PyString_AsString(mod),
+		return PyBytes_FromFormat("<class %s.%s at %p>",
+					   PyBytes_AsString(mod),
 					   name, op);
 }
 
@@ -397,21 +397,21 @@
 	PyObject *res;
 	Py_ssize_t m, n;
 
-	if (name == NULL || !PyString_Check(name))
+	if (name == NULL || !PyBytes_Check(name))
 		return class_repr(op);
-	if (mod == NULL || !PyString_Check(mod)) {
+	if (mod == NULL || !PyBytes_Check(mod)) {
 		Py_INCREF(name);
 		return name;
 	}
-	m = PyString_GET_SIZE(mod);
-	n = PyString_GET_SIZE(name);
-	res = PyString_FromStringAndSize((char *)NULL, m+1+n);
+	m = PyBytes_GET_SIZE(mod);
+	n = PyBytes_GET_SIZE(name);
+	res = PyBytes_FromStringAndSize((char *)NULL, m+1+n);
 	if (res != NULL) {
-		char *s = PyString_AS_STRING(res);
-		memcpy(s, PyString_AS_STRING(mod), m);
+		char *s = PyBytes_AS_STRING(res);
+		memcpy(s, PyBytes_AS_STRING(mod), m);
 		s += m;
 		*s++ = '.';
-		memcpy(s, PyString_AS_STRING(name), n);
+		memcpy(s, PyBytes_AS_STRING(name), n);
 	}
 	return res;
 }
@@ -541,7 +541,7 @@
 	static PyObject *initstr;
 
 	if (initstr == NULL) {
-		initstr = PyString_InternFromString("__init__");
+		initstr = PyBytes_InternFromString("__init__");
 		if (initstr == NULL)
 			return NULL;
 	}
@@ -634,7 +634,7 @@
 	PyErr_Fetch(&error_type, &error_value, &error_traceback);
 	/* Execute __del__ method, if any. */
 	if (delstr == NULL) {
-		delstr = PyString_InternFromString("__del__");
+		delstr = PyBytes_InternFromString("__del__");
 		if (delstr == NULL)
 			PyErr_WriteUnraisable((PyObject*)inst);
 	}
@@ -696,7 +696,7 @@
 instance_getattr1(register PyInstanceObject *inst, PyObject *name)
 {
 	register PyObject *v;
-	register char *sname = PyString_AsString(name);
+	register char *sname = PyBytes_AsString(name);
 	if (sname[0] == '_' && sname[1] == '_') {
 		if (strcmp(sname, "__dict__") == 0) {
 			if (PyEval_GetRestricted()) {
@@ -716,7 +716,7 @@
 	if (v == NULL && !PyErr_Occurred()) {
 		PyErr_Format(PyExc_AttributeError,
 			     "%.50s instance has no attribute '%.400s'",
-			     PyString_AS_STRING(inst->in_class->cl_name), sname);
+			     PyBytes_AS_STRING(inst->in_class->cl_name), sname);
 	}
 	return v;
 }
@@ -779,7 +779,7 @@
 	assert(PyInstance_Check(pinst));
 	inst = (PyInstanceObject *)pinst;
 
-	assert(PyString_Check(name));
+	assert(PyBytes_Check(name));
 
  	v = PyDict_GetItem(inst->in_dict, name);
 	if (v == NULL)
@@ -795,8 +795,8 @@
 		if (rv < 0)
 			PyErr_Format(PyExc_AttributeError,
 				     "%.50s instance has no attribute '%.400s'",
-				     PyString_AS_STRING(inst->in_class->cl_name),
-				     PyString_AS_STRING(name));
+				     PyBytes_AS_STRING(inst->in_class->cl_name),
+				     PyBytes_AS_STRING(name));
 		return rv;
 	}
 	else
@@ -807,9 +807,9 @@
 instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
 {
 	PyObject *func, *args, *res, *tmp;
-	char *sname = PyString_AsString(name);
+	char *sname = PyBytes_AsString(name);
 	if (sname[0] == '_' && sname[1] == '_') {
-		Py_ssize_t n = PyString_Size(name);
+		Py_ssize_t n = PyBytes_Size(name);
 		if (sname[n-1] == '_' && sname[n-2] == '_') {
 			if (strcmp(sname, "__dict__") == 0) {
 				if (PyEval_GetRestricted()) {
@@ -875,7 +875,7 @@
 	static PyObject *reprstr;
 
 	if (reprstr == NULL) {
-		reprstr = PyString_InternFromString("__repr__");
+		reprstr = PyBytes_InternFromString("__repr__");
 		if (reprstr == NULL)
 			return NULL;
 	}
@@ -889,16 +889,16 @@
 		classname = inst->in_class->cl_name;
 		mod = PyDict_GetItemString(inst->in_class->cl_dict,
 					   "__module__");
-		if (classname != NULL && PyString_Check(classname))
-			cname = PyString_AsString(classname);
+		if (classname != NULL && PyBytes_Check(classname))
+			cname = PyBytes_AsString(classname);
 		else
 			cname = "?";
-		if (mod == NULL || !PyString_Check(mod))
-			return PyString_FromFormat("<?.%s instance at %p>",
+		if (mod == NULL || !PyBytes_Check(mod))
+			return PyBytes_FromFormat("<?.%s instance at %p>",
 						   cname, inst);
 		else
-			return PyString_FromFormat("<%s.%s instance at %p>",
-						   PyString_AsString(mod),
+			return PyBytes_FromFormat("<%s.%s instance at %p>",
+						   PyBytes_AsString(mod),
 						   cname, inst);
 	}
 	res = PyEval_CallObject(func, (PyObject *)NULL);
@@ -914,7 +914,7 @@
 	static PyObject *strstr;
 
 	if (strstr == NULL) {
-		strstr = PyString_InternFromString("__str__");
+		strstr = PyBytes_InternFromString("__str__");
 		if (strstr == NULL)
 			return NULL;
 	}
@@ -939,7 +939,7 @@
 	static PyObject *hashstr, *eqstr, *cmpstr;
 
 	if (hashstr == NULL) {
-		hashstr = PyString_InternFromString("__hash__");
+		hashstr = PyBytes_InternFromString("__hash__");
 		if (hashstr == NULL)
 			return -1;
 	}
@@ -952,7 +952,7 @@
 		   address.  If an __eq__ or __cmp__ method exists, there must
 		   be a __hash__. */
 		if (eqstr == NULL) {
-			eqstr = PyString_InternFromString("__eq__");
+			eqstr = PyBytes_InternFromString("__eq__");
 			if (eqstr == NULL)
 				return -1;
 		}
@@ -962,7 +962,7 @@
 				return -1;
 			PyErr_Clear();
 			if (cmpstr == NULL) {
-				cmpstr = PyString_InternFromString("__cmp__");
+				cmpstr = PyBytes_InternFromString("__cmp__");
 				if (cmpstr == NULL)
 					return -1;
 			}
@@ -1014,7 +1014,7 @@
 	Py_ssize_t outcome;
 
 	if (lenstr == NULL) {
-		lenstr = PyString_InternFromString("__len__");
+		lenstr = PyBytes_InternFromString("__len__");
 		if (lenstr == NULL)
 			return -1;
 	}
@@ -1063,7 +1063,7 @@
 	PyObject *res;
 
 	if (getitemstr == NULL) {
-		getitemstr = PyString_InternFromString("__getitem__");
+		getitemstr = PyBytes_InternFromString("__getitem__");
 		if (getitemstr == NULL)
 			return NULL;
 	}
@@ -1090,7 +1090,7 @@
 
 	if (value == NULL) {
 		if (delitemstr == NULL) {
-			delitemstr = PyString_InternFromString("__delitem__");
+			delitemstr = PyBytes_InternFromString("__delitem__");
 			if (delitemstr == NULL)
 				return -1;
 		}
@@ -1098,7 +1098,7 @@
 	}
 	else {
 		if (setitemstr == NULL) {
-			setitemstr = PyString_InternFromString("__setitem__");
+			setitemstr = PyBytes_InternFromString("__setitem__");
 			if (setitemstr == NULL)
 				return -1;
 		}
@@ -1135,7 +1135,7 @@
 	PyObject *func, *res;
 
 	if (getitemstr == NULL) {
-		getitemstr = PyString_InternFromString("__getitem__");
+		getitemstr = PyBytes_InternFromString("__getitem__");
 		if (getitemstr == NULL)
 			return NULL;
 	}
@@ -1154,7 +1154,7 @@
 	static PyObject *getslicestr;
 
 	if (getslicestr == NULL) {
-		getslicestr = PyString_InternFromString("__getslice__");
+		getslicestr = PyBytes_InternFromString("__getslice__");
 		if (getslicestr == NULL)
 			return NULL;
 	}
@@ -1166,7 +1166,7 @@
 		PyErr_Clear();
 
 		if (getitemstr == NULL) {
-			getitemstr = PyString_InternFromString("__getitem__");
+			getitemstr = PyBytes_InternFromString("__getitem__");
 			if (getitemstr == NULL)
 				return NULL;
 		}
@@ -1194,7 +1194,7 @@
 
 	if (item == NULL) {
 		if (delitemstr == NULL) {
-			delitemstr = PyString_InternFromString("__delitem__");
+			delitemstr = PyBytes_InternFromString("__delitem__");
 			if (delitemstr == NULL)
 				return -1;
 		}
@@ -1202,7 +1202,7 @@
 	}
 	else {
 		if (setitemstr == NULL) {
-			setitemstr = PyString_InternFromString("__setitem__");
+			setitemstr = PyBytes_InternFromString("__setitem__");
 			if (setitemstr == NULL)
 				return -1;
 		}
@@ -1236,7 +1236,7 @@
 	if (value == NULL) {
 		if (delslicestr == NULL) {
 			delslicestr =
-				PyString_InternFromString("__delslice__");
+				PyBytes_InternFromString("__delslice__");
 			if (delslicestr == NULL)
 				return -1;
 		}
@@ -1247,7 +1247,7 @@
 			PyErr_Clear();
 			if (delitemstr == NULL) {
 				delitemstr =
-				    PyString_InternFromString("__delitem__");
+				    PyBytes_InternFromString("__delitem__");
 				if (delitemstr == NULL)
 					return -1;
 			}
@@ -1263,7 +1263,7 @@
 	else {
 		if (setslicestr == NULL) {
 			setslicestr =
-				PyString_InternFromString("__setslice__");
+				PyBytes_InternFromString("__setslice__");
 			if (setslicestr == NULL)
 				return -1;
 		}
@@ -1274,7 +1274,7 @@
 			PyErr_Clear();
 			if (setitemstr == NULL) {
 				setitemstr =
-				    PyString_InternFromString("__setitem__");
+				    PyBytes_InternFromString("__setitem__");
 				if (setitemstr == NULL)
 					return -1;
 			}
@@ -1311,7 +1311,7 @@
 	 */
 
 	if(__contains__ == NULL) {
-		__contains__ = PyString_InternFromString("__contains__");
+		__contains__ = PyBytes_InternFromString("__contains__");
 		if(__contains__ == NULL)
 			return -1;
 	}
@@ -1417,7 +1417,7 @@
 	}
 
 	if (coerce_obj == NULL) {
-		coerce_obj = PyString_InternFromString("__coerce__");
+		coerce_obj = PyBytes_InternFromString("__coerce__");
 		if (coerce_obj == NULL)
 			return NULL;
 	}
@@ -1504,7 +1504,7 @@
 	PyObject *coerced;
 
 	if (coerce_obj == NULL) {
-		coerce_obj = PyString_InternFromString("__coerce__");
+		coerce_obj = PyBytes_InternFromString("__coerce__");
 		if (coerce_obj == NULL)
 			return -1;
 	}
@@ -1552,7 +1552,7 @@
 #define UNARY(funcname, methodname) \
 static PyObject *funcname(PyInstanceObject *self) { \
 	static PyObject *o; \
-	if (o == NULL) { o = PyString_InternFromString(methodname); \
+	if (o == NULL) { o = PyBytes_InternFromString(methodname); \
 			 if (o == NULL) return NULL; } \
 	return generic_unary_op(self, o); \
 }
@@ -1561,7 +1561,7 @@
 #define UNARY_FB(funcname, methodname, funcname_fb) \
 static PyObject *funcname(PyInstanceObject *self) { \
 	static PyObject *o; \
-	if (o == NULL) { o = PyString_InternFromString(methodname); \
+	if (o == NULL) { o = PyBytes_InternFromString(methodname); \
 			 if (o == NULL) return NULL; } \
 	if (PyObject_HasAttr((PyObject*)self, o)) \
 		return generic_unary_op(self, o); \
@@ -1630,7 +1630,7 @@
 	assert(PyInstance_Check(v));
 
 	if (cmp_obj == NULL) {
-		cmp_obj = PyString_InternFromString("__cmp__");
+		cmp_obj = PyBytes_InternFromString("__cmp__");
 		if (cmp_obj == NULL)
 			return -2;
 	}
@@ -1738,7 +1738,7 @@
 	static PyObject *nonzerostr;
 
 	if (nonzerostr == NULL) {
-		nonzerostr = PyString_InternFromString("__nonzero__");
+		nonzerostr = PyBytes_InternFromString("__nonzero__");
 		if (nonzerostr == NULL)
 			return -1;
 	}
@@ -1747,7 +1747,7 @@
 			return -1;
 		PyErr_Clear();
 		if (lenstr == NULL) {
-			lenstr = PyString_InternFromString("__len__");
+			lenstr = PyBytes_InternFromString("__len__");
 			if (lenstr == NULL)
 				return -1;
 		}
@@ -1787,7 +1787,7 @@
 	static PyObject *indexstr = NULL;
 
 	if (indexstr == NULL) {
-		indexstr = PyString_InternFromString("__index__");
+		indexstr = PyBytes_InternFromString("__index__");
 		if (indexstr == NULL)
 			return NULL;
 	}	
@@ -1814,7 +1814,7 @@
 	PyObject *truncated;
 	static PyObject *int_name;
 	if (int_name == NULL) {
-		int_name = PyString_InternFromString("__int__");
+		int_name = PyBytes_InternFromString("__int__");
 		if (int_name == NULL)
 			return NULL;
 	}
@@ -1929,7 +1929,7 @@
 	if (name_op == NULL)
 		return -1;
 	for (i = 0; i < NAME_OPS; ++i) {
-		name_op[i] = PyString_InternFromString(_name_op[i]);
+		name_op[i] = PyBytes_InternFromString(_name_op[i]);
 		if (name_op[i] == NULL)
 			return -1;
 	}
@@ -2012,12 +2012,12 @@
 	PyObject *func;
 
 	if (iterstr == NULL) {
-		iterstr = PyString_InternFromString("__iter__");
+		iterstr = PyBytes_InternFromString("__iter__");
 		if (iterstr == NULL)
 			return NULL;
 	}
 	if (getitemstr == NULL) {
-		getitemstr = PyString_InternFromString("__getitem__");
+		getitemstr = PyBytes_InternFromString("__getitem__");
 		if (getitemstr == NULL)
 			return NULL;
 	}
@@ -2055,7 +2055,7 @@
 	PyObject *func;
 
 	if (nextstr == NULL) {
-		nextstr = PyString_InternFromString("next");
+		nextstr = PyBytes_InternFromString("next");
 		if (nextstr == NULL)
 			return NULL;
 	}
@@ -2087,7 +2087,7 @@
 		PyErr_Clear();
 		PyErr_Format(PyExc_AttributeError,
 			     "%.200s instance has no __call__ method",
-			     PyString_AsString(inst->in_class->cl_name));
+			     PyBytes_AsString(inst->in_class->cl_name));
 		return NULL;
 	}
 	/* We must check and increment the recursion depth here. Scenario:
@@ -2261,7 +2261,7 @@
 {
 	static PyObject *docstr;
 	if (docstr == NULL) {
-		docstr= PyString_InternFromString("__doc__");
+		docstr= PyBytes_InternFromString("__doc__");
 		if (docstr == NULL)
 			return NULL;
 	}
@@ -2384,12 +2384,12 @@
 			return NULL;
 		PyErr_Clear();
 	}
-	else if (!PyString_Check(funcname)) {
+	else if (!PyBytes_Check(funcname)) {
 		Py_DECREF(funcname);
 		funcname = NULL;
 	}
 	else
-		sfuncname = PyString_AS_STRING(funcname);
+		sfuncname = PyBytes_AS_STRING(funcname);
 	if (klass == NULL)
 		klassname = NULL;
 	else {
@@ -2399,28 +2399,28 @@
 				return NULL;
 			PyErr_Clear();
 		}
-		else if (!PyString_Check(klassname)) {
+		else if (!PyBytes_Check(klassname)) {
 			Py_DECREF(klassname);
 			klassname = NULL;
 		}
 		else
-			sklassname = PyString_AS_STRING(klassname);
+			sklassname = PyBytes_AS_STRING(klassname);
 	}
 	if (self == NULL)
-		result = PyString_FromFormat("<unbound method %s.%s>",
+		result = PyBytes_FromFormat("<unbound method %s.%s>",
 					     sklassname, sfuncname);
 	else {
 		/* XXX Shouldn't use repr() here! */
 		PyObject *selfrepr = PyObject_Repr(self);
 		if (selfrepr == NULL)
 			goto fail;
-		if (!PyString_Check(selfrepr)) {
+		if (!PyBytes_Check(selfrepr)) {
 			Py_DECREF(selfrepr);
 			goto fail;
 		}
-		result = PyString_FromFormat("<bound method %s.%s of %s>",
+		result = PyBytes_FromFormat("<bound method %s.%s of %s>",
 					     sklassname, sfuncname,
-					     PyString_AS_STRING(selfrepr));
+					     PyBytes_AS_STRING(selfrepr));
 		Py_DECREF(selfrepr);
 	}
   fail:
@@ -2472,8 +2472,8 @@
 		PyErr_Clear();
 		return;
 	}
-	if (PyString_Check(name)) {
-		strncpy(buf, PyString_AS_STRING(name), bufsize);
+	if (PyBytes_Check(name)) {
+		strncpy(buf, PyBytes_AS_STRING(name), bufsize);
 		buf[bufsize-1] = '\0';
 	}
 	Py_DECREF(name);

Modified: python/branches/okkoto-sizeof/Objects/codeobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/codeobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/codeobject.c	Wed Jun  4 11:24:23 2008
@@ -32,10 +32,10 @@
 
 	for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
 		PyObject *v = PyTuple_GET_ITEM(tuple, i);
-		if (v == NULL || !PyString_CheckExact(v)) {
+		if (v == NULL || !PyBytes_CheckExact(v)) {
 			Py_FatalError("non-string found in code slot");
 		}
-		PyString_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
+		PyBytes_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
 	}
 }
 
@@ -57,9 +57,9 @@
 	    varnames == NULL || !PyTuple_Check(varnames) ||
 	    freevars == NULL || !PyTuple_Check(freevars) ||
 	    cellvars == NULL || !PyTuple_Check(cellvars) ||
-	    name == NULL || !PyString_Check(name) ||
-	    filename == NULL || !PyString_Check(filename) ||
-	    lnotab == NULL || !PyString_Check(lnotab) ||
+	    name == NULL || !PyBytes_Check(name) ||
+	    filename == NULL || !PyBytes_Check(filename) ||
+	    lnotab == NULL || !PyBytes_Check(lnotab) ||
 	    !PyObject_CheckReadBuffer(code)) {
 		PyErr_BadInternalCall();
 		return NULL;
@@ -71,11 +71,11 @@
 	/* Intern selected string constants */
 	for (i = PyTuple_Size(consts); --i >= 0; ) {
 		PyObject *v = PyTuple_GetItem(consts, i);
-		if (!PyString_Check(v))
+		if (!PyBytes_Check(v))
 			continue;
-		if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
+		if (!all_name_chars((unsigned char *)PyBytes_AS_STRING(v)))
 			continue;
-		PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
+		PyBytes_InternInPlace(&PyTuple_GET_ITEM(consts, i));
 	}
 	co = PyObject_NEW(PyCodeObject, &PyCode_Type);
 	if (co != NULL) {
@@ -145,10 +145,10 @@
 
 	for (i = 0; i < len; i++) {
 		item = PyTuple_GET_ITEM(tup, i);
-		if (PyString_CheckExact(item)) {
+		if (PyBytes_CheckExact(item)) {
 			Py_INCREF(item);
 		}
-		else if (!PyString_Check(item)) {
+		else if (!PyBytes_Check(item)) {
 			PyErr_Format(
 				PyExc_TypeError,
 				"name tuples must contain only "
@@ -158,9 +158,9 @@
 			return NULL;
 		}
 		else {
-			item = PyString_FromStringAndSize(
-				PyString_AS_STRING(item),
-				PyString_GET_SIZE(item));
+			item = PyBytes_FromStringAndSize(
+				PyBytes_AS_STRING(item),
+				PyBytes_GET_SIZE(item));
 			if (item == NULL) {
 				Py_DECREF(newtuple);
 				return NULL;
@@ -281,14 +281,14 @@
 
 	if (co->co_firstlineno != 0)
 		lineno = co->co_firstlineno;
-	if (co->co_filename && PyString_Check(co->co_filename))
-		filename = PyString_AS_STRING(co->co_filename);
-	if (co->co_name && PyString_Check(co->co_name))
-		name = PyString_AS_STRING(co->co_name);
+	if (co->co_filename && PyBytes_Check(co->co_filename))
+		filename = PyBytes_AS_STRING(co->co_filename);
+	if (co->co_name && PyBytes_Check(co->co_name))
+		name = PyBytes_AS_STRING(co->co_name);
 	PyOS_snprintf(buf, sizeof(buf),
 		      "<code object %.100s at %p, file \"%.300s\", line %d>",
 		      name, co, filename, lineno);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static int
@@ -508,8 +508,8 @@
 int
 PyCode_Addr2Line(PyCodeObject *co, int addrq)
 {
-	int size = PyString_Size(co->co_lnotab) / 2;
-	unsigned char *p = (unsigned char*)PyString_AsString(co->co_lnotab);
+	int size = PyBytes_Size(co->co_lnotab) / 2;
+	unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
 	int line = co->co_firstlineno;
 	int addr = 0;
 	while (--size >= 0) {
@@ -604,8 +604,8 @@
         int size, addr, line;
         unsigned char* p;
 
-        p = (unsigned char*)PyString_AS_STRING(co->co_lnotab);
-        size = PyString_GET_SIZE(co->co_lnotab) / 2;
+        p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
+        size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
 
         addr = 0;
         line = co->co_firstlineno;

Modified: python/branches/okkoto-sizeof/Objects/complexobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/complexobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/complexobject.c	Wed Jun  4 11:24:23 2008
@@ -303,7 +303,7 @@
 	cv.imag = 0.;
 
 	if (complex_str == NULL) {
-		if (!(complex_str = PyString_InternFromString("__complex__")))
+		if (!(complex_str = PyBytes_InternFromString("__complex__")))
 			return cv;
 	}
 	
@@ -421,7 +421,7 @@
 {
 	char buf[100];
 	complex_to_buf(buf, sizeof(buf), v, PREC_REPR);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static PyObject *
@@ -429,7 +429,7 @@
 {
 	char buf[100];
 	complex_to_buf(buf, sizeof(buf), v, PREC_STR);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static long
@@ -876,9 +876,9 @@
 #endif
 	Py_ssize_t len;
 
-	if (PyString_Check(v)) {
-		s = PyString_AS_STRING(v);
-		len = PyString_GET_SIZE(v);
+	if (PyBytes_Check(v)) {
+		s = PyBytes_AS_STRING(v);
+		len = PyBytes_GET_SIZE(v);
 	}
 #ifdef Py_USING_UNICODE
 	else if (PyUnicode_Check(v)) {
@@ -1064,7 +1064,7 @@
 		Py_INCREF(r);
 		return r;
 	}
-	if (PyString_Check(r) || PyUnicode_Check(r)) {
+	if (PyBytes_Check(r) || PyUnicode_Check(r)) {
 		if (i != NULL) {
 			PyErr_SetString(PyExc_TypeError,
 					"complex() can't take second arg"
@@ -1073,7 +1073,7 @@
 		}
 		return complex_subtype_from_string(type, r);
 	}
-	if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
+	if (i != NULL && (PyBytes_Check(i) || PyUnicode_Check(i))) {
 		PyErr_SetString(PyExc_TypeError,
 				"complex() second arg can't be a string");
 		return NULL;
@@ -1081,7 +1081,7 @@
 
 	/* XXX Hack to support classes with __complex__ method */
 	if (complexstr == NULL) {
-		complexstr = PyString_InternFromString("__complex__");
+		complexstr = PyBytes_InternFromString("__complex__");
 		if (complexstr == NULL)
 			return NULL;
 	}

Modified: python/branches/okkoto-sizeof/Objects/descrobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/descrobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/descrobject.c	Wed Jun  4 11:24:23 2008
@@ -15,8 +15,8 @@
 static char *
 descr_name(PyDescrObject *descr)
 {
-	if (descr->d_name != NULL && PyString_Check(descr->d_name))
-		return PyString_AS_STRING(descr->d_name);
+	if (descr->d_name != NULL && PyBytes_Check(descr->d_name))
+		return PyBytes_AS_STRING(descr->d_name);
 	else
 		return "?";
 }
@@ -24,7 +24,7 @@
 static PyObject *
 descr_repr(PyDescrObject *descr, char *format)
 {
-	return PyString_FromFormat(format, descr_name(descr),
+	return PyBytes_FromFormat(format, descr_name(descr),
 				   descr->d_type->tp_name);
 }
 
@@ -314,7 +314,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(descr->d_method->ml_doc);
+	return PyBytes_FromString(descr->d_method->ml_doc);
 }
 
 static PyMemberDef descr_members[] = {
@@ -335,7 +335,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(descr->d_member->doc);
+	return PyBytes_FromString(descr->d_member->doc);
 }
 
 static PyGetSetDef member_getset[] = {
@@ -350,7 +350,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(descr->d_getset->doc);
+	return PyBytes_FromString(descr->d_getset->doc);
 }
 
 static PyGetSetDef getset_getset[] = {
@@ -365,7 +365,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromString(descr->d_base->doc);
+	return PyBytes_FromString(descr->d_base->doc);
 }
 
 static PyGetSetDef wrapperdescr_getset[] = {
@@ -576,7 +576,7 @@
 	if (descr != NULL) {
 		Py_XINCREF(type);
 		descr->d_type = type;
-		descr->d_name = PyString_InternFromString(name);
+		descr->d_name = PyBytes_InternFromString(name);
 		if (descr->d_name == NULL) {
 			Py_DECREF(descr);
 			descr = NULL;
@@ -922,7 +922,7 @@
 static PyObject *
 wrapper_repr(wrapperobject *wp)
 {
-	return PyString_FromFormat("<method-wrapper '%s' of %s object at %p>",
+	return PyBytes_FromFormat("<method-wrapper '%s' of %s object at %p>",
 				   wp->descr->d_base->name,
 				   wp->self->ob_type->tp_name,
 				   wp->self);
@@ -947,7 +947,7 @@
 {
 	char *s = wp->descr->d_base->name;
 
-	return PyString_FromString(s);
+	return PyBytes_FromString(s);
 }
 
 static PyObject *
@@ -960,7 +960,7 @@
 		return Py_None;
 	}
 	else {
-		return PyString_FromString(s);
+		return PyBytes_FromString(s);
 	}
 }
 

Modified: python/branches/okkoto-sizeof/Objects/dictobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/dictobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/dictobject.c	Wed Jun  4 11:24:23 2008
@@ -224,7 +224,7 @@
 {
 	register PyDictObject *mp;
 	if (dummy == NULL) { /* Auto-initialize dummy */
-		dummy = PyString_FromString("<dummy key>");
+		dummy = PyBytes_FromString("<dummy key>");
 		if (dummy == NULL)
 			return NULL;
 #ifdef SHOW_CONVERSION_COUNTS
@@ -373,7 +373,7 @@
  * this assumption allows testing for errors during PyObject_RichCompareBool()
  * to be dropped; string-string comparisons never raise exceptions.  This also
  * means we don't need to go through PyObject_RichCompareBool(); we can always
- * use _PyString_Eq() directly.
+ * use _PyBytes_Eq() directly.
  *
  * This is valuable because dicts with only string keys are very common.
  */
@@ -391,7 +391,7 @@
 	   including subclasses of str; e.g., one reason to subclass
 	   strings is to override __eq__, and for speed we don't cater to
 	   that here. */
-	if (!PyString_CheckExact(key)) {
+	if (!PyBytes_CheckExact(key)) {
 #ifdef SHOW_CONVERSION_COUNTS
 		++converted;
 #endif
@@ -405,7 +405,7 @@
 	if (ep->me_key == dummy)
 		freeslot = ep;
 	else {
-		if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key))
+		if (ep->me_hash == hash && _PyBytes_Eq(ep->me_key, key))
 			return ep;
 		freeslot = NULL;
 	}
@@ -420,7 +420,7 @@
 		if (ep->me_key == key
 		    || (ep->me_hash == hash
 		        && ep->me_key != dummy
-			&& _PyString_Eq(ep->me_key, key)))
+			&& _PyBytes_Eq(ep->me_key, key)))
 			return ep;
 		if (ep->me_key == dummy && freeslot == NULL)
 			freeslot = ep;
@@ -626,8 +626,8 @@
 	PyThreadState *tstate;
 	if (!PyDict_Check(op))
 		return NULL;
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1)
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1)
 	{
 		hash = PyObject_Hash(key);
 		if (hash == -1) {
@@ -680,8 +680,8 @@
 	assert(key);
 	assert(value);
 	mp = (PyDictObject *)op;
-	if (PyString_CheckExact(key)) {
-		hash = ((PyStringObject *)key)->ob_shash;
+	if (PyBytes_CheckExact(key)) {
+		hash = ((PyBytesObject *)key)->ob_shash;
 		if (hash == -1)
 			hash = PyObject_Hash(key);
 	}
@@ -728,8 +728,8 @@
 		return -1;
 	}
 	assert(key);
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return -1;
@@ -982,11 +982,11 @@
 
 	i = Py_ReprEnter((PyObject *)mp);
 	if (i != 0) {
-		return i > 0 ? PyString_FromString("{...}") : NULL;
+		return i > 0 ? PyBytes_FromString("{...}") : NULL;
 	}
 
 	if (mp->ma_used == 0) {
-		result = PyString_FromString("{}");
+		result = PyBytes_FromString("{}");
 		goto Done;
 	}
 
@@ -994,7 +994,7 @@
 	if (pieces == NULL)
 		goto Done;
 
-	colon = PyString_FromString(": ");
+	colon = PyBytes_FromString(": ");
 	if (colon == NULL)
 		goto Done;
 
@@ -1006,8 +1006,8 @@
 		/* Prevent repr from deleting value during key format. */
 		Py_INCREF(value);
 		s = PyObject_Repr(key);
-		PyString_Concat(&s, colon);
-		PyString_ConcatAndDel(&s, PyObject_Repr(value));
+		PyBytes_Concat(&s, colon);
+		PyBytes_ConcatAndDel(&s, PyObject_Repr(value));
 		Py_DECREF(value);
 		if (s == NULL)
 			goto Done;
@@ -1019,29 +1019,29 @@
 
 	/* Add "{}" decorations to the first and last items. */
 	assert(PyList_GET_SIZE(pieces) > 0);
-	s = PyString_FromString("{");
+	s = PyBytes_FromString("{");
 	if (s == NULL)
 		goto Done;
 	temp = PyList_GET_ITEM(pieces, 0);
-	PyString_ConcatAndDel(&s, temp);
+	PyBytes_ConcatAndDel(&s, temp);
 	PyList_SET_ITEM(pieces, 0, s);
 	if (s == NULL)
 		goto Done;
 
-	s = PyString_FromString("}");
+	s = PyBytes_FromString("}");
 	if (s == NULL)
 		goto Done;
 	temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
-	PyString_ConcatAndDel(&temp, s);
+	PyBytes_ConcatAndDel(&temp, s);
 	PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
 	if (temp == NULL)
 		goto Done;
 
 	/* Paste them all together with ", " between. */
-	s = PyString_FromString(", ");
+	s = PyBytes_FromString(", ");
 	if (s == NULL)
 		goto Done;
-	result = _PyString_Join(s, pieces);
+	result = _PyBytes_Join(s, pieces);
 	Py_DECREF(s);
 
 Done:
@@ -1064,8 +1064,8 @@
 	long hash;
 	PyDictEntry *ep;
 	assert(mp->ma_table != NULL);
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return NULL;
@@ -1081,7 +1081,7 @@
 			static PyObject *missing_str = NULL;
 			if (missing_str == NULL)
 				missing_str =
-				  PyString_InternFromString("__missing__");
+				  PyBytes_InternFromString("__missing__");
 			missing = _PyType_Lookup(Py_TYPE(mp), missing_str);
 			if (missing != NULL)
 				return PyObject_CallFunctionObjArgs(missing,
@@ -1794,8 +1794,8 @@
 	long hash;
 	PyDictEntry *ep;
 
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return NULL;
@@ -1827,8 +1827,8 @@
 	if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
 		return NULL;
 
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return NULL;
@@ -1856,8 +1856,8 @@
 	if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
 		return NULL;
 
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return NULL;
@@ -1902,8 +1902,8 @@
 				"pop(): dictionary is empty");
 		return NULL;
 	}
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return NULL;
@@ -2052,7 +2052,7 @@
 PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");
 
 PyDoc_STRVAR(sizeof__doc__,
-"D.__sizeof__() -> size of D in bytes");
+"D.__sizeof__() -> size of D in memory, in bytes");
 
 PyDoc_STRVAR(get__doc__,
 "D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.");
@@ -2148,8 +2148,8 @@
 	PyDictObject *mp = (PyDictObject *)op;
 	PyDictEntry *ep;
 
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return -1;
@@ -2275,7 +2275,7 @@
 PyDict_GetItemString(PyObject *v, const char *key)
 {
 	PyObject *kv, *rv;
-	kv = PyString_FromString(key);
+	kv = PyBytes_FromString(key);
 	if (kv == NULL)
 		return NULL;
 	rv = PyDict_GetItem(v, kv);
@@ -2288,10 +2288,10 @@
 {
 	PyObject *kv;
 	int err;
-	kv = PyString_FromString(key);
+	kv = PyBytes_FromString(key);
 	if (kv == NULL)
 		return -1;
-	PyString_InternInPlace(&kv); /* XXX Should we really? */
+	PyBytes_InternInPlace(&kv); /* XXX Should we really? */
 	err = PyDict_SetItem(v, kv, item);
 	Py_DECREF(kv);
 	return err;
@@ -2302,7 +2302,7 @@
 {
 	PyObject *kv;
 	int err;
-	kv = PyString_FromString(key);
+	kv = PyBytes_FromString(key);
 	if (kv == NULL)
 		return -1;
 	err = PyDict_DelItem(v, kv);

Modified: python/branches/okkoto-sizeof/Objects/enumobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/enumobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/enumobject.c	Wed Jun  4 11:24:23 2008
@@ -224,7 +224,10 @@
 	PyObject *seq;
 	reversedobject *ro;
 
-	if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq))
+	if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds))
+		return NULL;
+
+	if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) )
 		return NULL;
 
 	if (PyObject_HasAttrString(seq, "__reversed__"))

Modified: python/branches/okkoto-sizeof/Objects/exceptions.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/exceptions.c	(original)
+++ python/branches/okkoto-sizeof/Objects/exceptions.c	Wed Jun  4 11:24:23 2008
@@ -44,7 +44,7 @@
         return NULL;
     }
 
-    self->message = PyString_FromString("");
+    self->message = PyBytes_FromString("");
     if (!self->message) {
         Py_DECREF(self);
         return NULL;
@@ -104,7 +104,7 @@
 
     switch (PyTuple_GET_SIZE(self->args)) {
     case 0:
-        out = PyString_FromString("");
+        out = PyBytes_FromString("");
         break;
     case 1:
         out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
@@ -133,13 +133,13 @@
     dot = strrchr(name, '.');
     if (dot != NULL) name = dot+1;
 
-    repr = PyString_FromString(name);
+    repr = PyBytes_FromString(name);
     if (!repr) {
         Py_DECREF(repr_suffix);
         return NULL;
     }
 
-    PyString_ConcatAndDel(&repr, repr_suffix);
+    PyBytes_ConcatAndDel(&repr, repr_suffix);
     return repr;
 }
 
@@ -610,7 +610,7 @@
         PyObject *repr;
         PyObject *tuple;
 
-        fmt = PyString_FromString("[Errno %s] %s: %s");
+        fmt = PyBytes_FromString("[Errno %s] %s: %s");
         if (!fmt)
             return NULL;
 
@@ -645,7 +645,7 @@
 
         PyTuple_SET_ITEM(tuple, 2, repr);
 
-        rtnval = PyString_Format(fmt, tuple);
+        rtnval = PyBytes_Format(fmt, tuple);
 
         Py_DECREF(fmt);
         Py_DECREF(tuple);
@@ -654,7 +654,7 @@
         PyObject *fmt;
         PyObject *tuple;
 
-        fmt = PyString_FromString("[Errno %s] %s");
+        fmt = PyBytes_FromString("[Errno %s] %s");
         if (!fmt)
             return NULL;
 
@@ -681,7 +681,7 @@
             PyTuple_SET_ITEM(tuple, 1, Py_None);
         }
 
-        rtnval = PyString_Format(fmt, tuple);
+        rtnval = PyBytes_Format(fmt, tuple);
 
         Py_DECREF(fmt);
         Py_DECREF(tuple);
@@ -841,7 +841,7 @@
         PyObject *repr;
         PyObject *tuple;
 
-        fmt = PyString_FromString("[Error %s] %s: %s");
+        fmt = PyBytes_FromString("[Error %s] %s: %s");
         if (!fmt)
             return NULL;
 
@@ -876,7 +876,7 @@
 
         PyTuple_SET_ITEM(tuple, 2, repr);
 
-        rtnval = PyString_Format(fmt, tuple);
+        rtnval = PyBytes_Format(fmt, tuple);
 
         Py_DECREF(fmt);
         Py_DECREF(tuple);
@@ -885,7 +885,7 @@
         PyObject *fmt;
         PyObject *tuple;
 
-        fmt = PyString_FromString("[Error %s] %s");
+        fmt = PyBytes_FromString("[Error %s] %s");
         if (!fmt)
             return NULL;
 
@@ -912,7 +912,7 @@
             PyTuple_SET_ITEM(tuple, 1, Py_None);
         }
 
-        rtnval = PyString_Format(fmt, tuple);
+        rtnval = PyBytes_Format(fmt, tuple);
 
         Py_DECREF(fmt);
         Py_DECREF(tuple);
@@ -1109,21 +1109,21 @@
         str = PyObject_Str(Py_None);
     if (!str) return NULL;
     /* Don't fiddle with non-string return (shouldn't happen anyway) */
-    if (!PyString_Check(str)) return str;
+    if (!PyBytes_Check(str)) return str;
 
     /* XXX -- do all the additional formatting with filename and
        lineno here */
 
     have_filename = (self->filename != NULL) &&
-        PyString_Check(self->filename);
+        PyBytes_Check(self->filename);
     have_lineno = (self->lineno != NULL) && PyInt_Check(self->lineno);
 
     if (!have_filename && !have_lineno)
         return str;
 
-    bufsize = PyString_GET_SIZE(str) + 64;
+    bufsize = PyBytes_GET_SIZE(str) + 64;
     if (have_filename)
-        bufsize += PyString_GET_SIZE(self->filename);
+        bufsize += PyBytes_GET_SIZE(self->filename);
 
     buffer = PyMem_MALLOC(bufsize);
     if (buffer == NULL)
@@ -1131,19 +1131,19 @@
 
     if (have_filename && have_lineno)
         PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)",
-            PyString_AS_STRING(str),
-            my_basename(PyString_AS_STRING(self->filename)),
+            PyBytes_AS_STRING(str),
+            my_basename(PyBytes_AS_STRING(self->filename)),
             PyInt_AsLong(self->lineno));
     else if (have_filename)
         PyOS_snprintf(buffer, bufsize, "%s (%s)",
-            PyString_AS_STRING(str),
-            my_basename(PyString_AS_STRING(self->filename)));
+            PyBytes_AS_STRING(str),
+            my_basename(PyBytes_AS_STRING(self->filename)));
     else /* only have_lineno */
         PyOS_snprintf(buffer, bufsize, "%s (line %ld)",
-            PyString_AS_STRING(str),
+            PyBytes_AS_STRING(str),
             PyInt_AsLong(self->lineno));
 
-    result = PyString_FromString(buffer);
+    result = PyBytes_FromString(buffer);
     PyMem_FREE(buffer);
 
     if (result == NULL)
@@ -1250,7 +1250,7 @@
         return NULL;
     }
 
-    if (!PyString_Check(attr)) {
+    if (!PyBytes_Check(attr)) {
         PyErr_Format(PyExc_TypeError, "%.200s attribute must be str", name);
         return NULL;
     }
@@ -1262,7 +1262,7 @@
 static int
 set_string(PyObject **attr, const char *value)
 {
-    PyObject *obj = PyString_FromString(value);
+    PyObject *obj = PyBytes_FromString(value);
     if (!obj)
         return -1;
     Py_CLEAR(*attr);
@@ -1345,7 +1345,7 @@
                                "object");
     if (!obj)
         return -1;
-    size = PyString_GET_SIZE(obj);
+    size = PyBytes_GET_SIZE(obj);
     *start = ((PyUnicodeErrorObject *)exc)->start;
     if (*start<0)
         *start = 0;
@@ -1415,7 +1415,7 @@
     if (!obj)
         return -1;
     *end = ((PyUnicodeErrorObject *)exc)->end;
-    size = PyString_GET_SIZE(obj);
+    size = PyBytes_GET_SIZE(obj);
     if (*end<1)
         *end = 1;
     if (*end>size)
@@ -1506,11 +1506,11 @@
     Py_CLEAR(self->reason);
 
     if (!PyArg_ParseTuple(args, "O!O!nnO!",
-        &PyString_Type, &self->encoding,
+        &PyBytes_Type, &self->encoding,
         objecttype, &self->object,
         &self->start,
         &self->end,
-        &PyString_Type, &self->reason)) {
+        &PyBytes_Type, &self->reason)) {
         self->encoding = self->object = self->reason = NULL;
         return -1;
     }
@@ -1590,20 +1590,20 @@
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
         else
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
-        return PyString_FromFormat(
+        return PyBytes_FromFormat(
             "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
-            PyString_AS_STRING(uself->encoding),
+            PyBytes_AS_STRING(uself->encoding),
             badchar_str,
             uself->start,
-            PyString_AS_STRING(uself->reason)
+            PyBytes_AS_STRING(uself->reason)
         );
     }
-    return PyString_FromFormat(
+    return PyBytes_FromFormat(
         "'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
-        PyString_AS_STRING(uself->encoding),
+        PyBytes_AS_STRING(uself->encoding),
         uself->start,
         uself->end-1,
-        PyString_AS_STRING(uself->reason)
+        PyBytes_AS_STRING(uself->reason)
     );
 }
 
@@ -1642,7 +1642,7 @@
     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
         return -1;
     return UnicodeError_init((PyUnicodeErrorObject *)self, args,
-                             kwds, &PyString_Type);
+                             kwds, &PyBytes_Type);
 }
 
 static PyObject *
@@ -1654,21 +1654,21 @@
         /* FromFormat does not support %02x, so format that separately */
         char byte[4];
         PyOS_snprintf(byte, sizeof(byte), "%02x",
-                      ((int)PyString_AS_STRING(uself->object)[uself->start])&0xff);
-        return PyString_FromFormat(
+                      ((int)PyBytes_AS_STRING(uself->object)[uself->start])&0xff);
+        return PyBytes_FromFormat(
             "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
-            PyString_AS_STRING(uself->encoding),
+            PyBytes_AS_STRING(uself->encoding),
             byte,
             uself->start,
-            PyString_AS_STRING(uself->reason)
+            PyBytes_AS_STRING(uself->reason)
         );
     }
-    return PyString_FromFormat(
+    return PyBytes_FromFormat(
         "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
-        PyString_AS_STRING(uself->encoding),
+        PyBytes_AS_STRING(uself->encoding),
         uself->start,
         uself->end-1,
-        PyString_AS_STRING(uself->reason)
+        PyBytes_AS_STRING(uself->reason)
     );
 }
 
@@ -1718,7 +1718,7 @@
         &PyUnicode_Type, &self->object,
         &self->start,
         &self->end,
-        &PyString_Type, &self->reason)) {
+        &PyBytes_Type, &self->reason)) {
         self->object = self->reason = NULL;
         return -1;
     }
@@ -1744,18 +1744,18 @@
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
         else
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
-        return PyString_FromFormat(
+        return PyBytes_FromFormat(
             "can't translate character u'\\%s' in position %zd: %.400s",
             badchar_str,
             uself->start,
-            PyString_AS_STRING(uself->reason)
+            PyBytes_AS_STRING(uself->reason)
         );
     }
-    return PyString_FromFormat(
+    return PyBytes_FromFormat(
         "can't translate characters in position %zd-%zd: %.400s",
         uself->start,
         uself->end-1,
-        PyString_AS_STRING(uself->reason)
+        PyBytes_AS_STRING(uself->reason)
     );
 }
 
@@ -2111,7 +2111,7 @@
 	    (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
 	PyObject *args_tuple;
 	PyObject *exc_message;
-	exc_message = PyString_FromString("maximum recursion depth exceeded");
+	exc_message = PyBytes_FromString("maximum recursion depth exceeded");
 	if (!exc_message)
 	    Py_FatalError("cannot allocate argument for RuntimeError "
 			    "pre-allocation");

Modified: python/branches/okkoto-sizeof/Objects/fileobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/fileobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/fileobject.c	Wed Jun  4 11:24:23 2008
@@ -26,7 +26,7 @@
 #include <io.h>
 #endif
 
-#define BUF(v) PyString_AS_STRING((PyStringObject *)v)
+#define BUF(v) PyBytes_AS_STRING((PyBytesObject *)v)
 
 #ifndef DONT_HAVE_ERRNO_H
 #include <errno.h>
@@ -155,11 +155,12 @@
 	Py_DECREF(f->f_name);
 	Py_DECREF(f->f_mode);
 	Py_DECREF(f->f_encoding);
+	Py_DECREF(f->f_errors);
 
         Py_INCREF(name);
         f->f_name = name;
 
-	f->f_mode = PyString_FromString(mode);
+	f->f_mode = PyBytes_FromString(mode);
 
 	f->f_close = close;
 	f->f_softspace = 0;
@@ -170,6 +171,8 @@
 	f->f_skipnextlf = 0;
 	Py_INCREF(Py_None);
 	f->f_encoding = Py_None;
+	Py_INCREF(Py_None);
+	f->f_errors = Py_None;
 
 	if (f->f_mode == NULL)
 		return NULL;
@@ -367,7 +370,7 @@
 	PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
 							     NULL, NULL);
 	if (f != NULL) {
-		PyObject *o_name = PyString_FromString(name);
+		PyObject *o_name = PyBytes_FromString(name);
 		if (o_name == NULL)
 			return NULL;
 		if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
@@ -435,19 +438,38 @@
 }
 
 /* Set the encoding used to output Unicode strings.
-   Returh 1 on success, 0 on failure. */
+   Return 1 on success, 0 on failure. */
 
 int
 PyFile_SetEncoding(PyObject *f, const char *enc)
 {
+	return PyFile_SetEncodingAndErrors(f, enc, NULL);
+}
+
+int
+PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
+{
 	PyFileObject *file = (PyFileObject*)f;
-	PyObject *str = PyString_FromString(enc);
+	PyObject *str, *oerrors;
 
 	assert(PyFile_Check(f));
+	str = PyBytes_FromString(enc);
 	if (!str)
 		return 0;
+	if (errors) {
+		oerrors = PyString_FromString(errors);
+		if (!oerrors) {
+			Py_DECREF(str);
+			return 0;
+		}
+	} else {
+		oerrors = Py_None;
+		Py_INCREF(Py_None);
+	}
 	Py_DECREF(file->f_encoding);
 	file->f_encoding = str;
+	Py_DECREF(file->f_errors);
+	file->f_errors = oerrors;
 	return 1;
 }
 
@@ -491,6 +513,7 @@
 	Py_XDECREF(f->f_name);
 	Py_XDECREF(f->f_mode);
 	Py_XDECREF(f->f_encoding);
+	Py_XDECREF(f->f_errors);
 	drop_readahead(f);
 	Py_TYPE(f)->tp_free((PyObject *)f);
 }
@@ -502,20 +525,20 @@
 #ifdef Py_USING_UNICODE
 		PyObject *ret = NULL;
 		PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
-		const char *name_str = name ? PyString_AsString(name) : "?";
-		ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
+		const char *name_str = name ? PyBytes_AsString(name) : "?";
+		ret = PyBytes_FromFormat("<%s file u'%s', mode '%s' at %p>",
 				   f->f_fp == NULL ? "closed" : "open",
 				   name_str,
-				   PyString_AsString(f->f_mode),
+				   PyBytes_AsString(f->f_mode),
 				   f);
 		Py_XDECREF(name);
 		return ret;
 #endif
 	} else {
-		return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
+		return PyBytes_FromFormat("<%s file '%s', mode '%s' at %p>",
 				   f->f_fp == NULL ? "closed" : "open",
-				   PyString_AsString(f->f_name),
-				   PyString_AsString(f->f_mode),
+				   PyBytes_AsString(f->f_name),
+				   PyBytes_AsString(f->f_mode),
 				   f);
 	}
 }
@@ -935,7 +958,7 @@
 	"requested number of bytes is more than a Python string can hold");
 		return NULL;
 	}
-	v = PyString_FromStringAndSize((char *)NULL, buffersize);
+	v = PyBytes_FromStringAndSize((char *)NULL, buffersize);
 	if (v == NULL)
 		return NULL;
 	bytesread = 0;
@@ -966,7 +989,7 @@
 		}
 		if (bytesrequested < 0) {
 			buffersize = new_buffersize(f, buffersize);
-			if (_PyString_Resize(&v, buffersize) < 0)
+			if (_PyBytes_Resize(&v, buffersize) < 0)
 				return NULL;
 		} else {
 			/* Got what was requested. */
@@ -974,7 +997,7 @@
 		}
 	}
 	if (bytesread != buffersize)
-		_PyString_Resize(&v, bytesread);
+		_PyBytes_Resize(&v, bytesread);
 	return v;
 }
 
@@ -1092,7 +1115,7 @@
 	size_t increment;	/* amount to increment the buffer */
 	size_t prev_v_size;
 
-	/* Optimize for normal case:  avoid _PyString_Resize if at all
+	/* Optimize for normal case:  avoid _PyBytes_Resize if at all
 	 * possible via first reading into stack buffer "buf".
 	 */
 	total_v_size = INITBUFSIZE;	/* start small and pray */
@@ -1110,7 +1133,7 @@
 			clearerr(fp);
 			if (PyErr_CheckSignals())
 				return NULL;
-			v = PyString_FromStringAndSize(buf, pvfree - buf);
+			v = PyBytes_FromStringAndSize(buf, pvfree - buf);
 			return v;
 		}
 		/* fgets read *something* */
@@ -1139,7 +1162,7 @@
 				assert(p > pvfree && *(p-1) == '\0');
 				--p;	/* don't include \0 from fgets */
 			}
-			v = PyString_FromStringAndSize(buf, p - buf);
+			v = PyBytes_FromStringAndSize(buf, p - buf);
 			return v;
 		}
 		/* yuck:  fgets overwrote all the newlines, i.e. the entire
@@ -1160,7 +1183,7 @@
 	 * into its buffer.
 	 */
 	total_v_size = MAXBUFSIZE << 1;
-	v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
+	v = PyBytes_FromStringAndSize((char*)NULL, (int)total_v_size);
 	if (v == NULL)
 		return v;
 	/* copy over everything except the last null byte */
@@ -1215,13 +1238,13 @@
 			Py_DECREF(v);
 			return NULL;
 		}
-		if (_PyString_Resize(&v, (int)total_v_size) < 0)
+		if (_PyBytes_Resize(&v, (int)total_v_size) < 0)
 			return NULL;
 		/* overwrite the trailing null byte */
 		pvfree = BUF(v) + (prev_v_size - 1);
 	}
 	if (BUF(v) + total_v_size != p)
-		_PyString_Resize(&v, p - BUF(v));
+		_PyBytes_Resize(&v, p - BUF(v));
 	return v;
 #undef INITBUFSIZE
 #undef MAXBUFSIZE
@@ -1253,7 +1276,7 @@
 		return getline_via_fgets(f, fp);
 #endif
 	total_v_size = n > 0 ? n : 100;
-	v = PyString_FromStringAndSize((char *)NULL, total_v_size);
+	v = PyBytes_FromStringAndSize((char *)NULL, total_v_size);
 	if (v == NULL)
 		return NULL;
 	buf = BUF(v);
@@ -1326,7 +1349,7 @@
 			Py_DECREF(v);
 			return NULL;
 		}
-		if (_PyString_Resize(&v, total_v_size) < 0)
+		if (_PyBytes_Resize(&v, total_v_size) < 0)
 			return NULL;
 		buf = BUF(v) + used_v_size;
 		end = BUF(v) + total_v_size;
@@ -1334,7 +1357,7 @@
 
 	used_v_size = buf - BUF(v);
 	if (used_v_size != total_v_size)
-		_PyString_Resize(&v, used_v_size);
+		_PyBytes_Resize(&v, used_v_size);
 	return v;
 }
 
@@ -1379,7 +1402,7 @@
 		result = PyEval_CallObject(reader, args);
 		Py_DECREF(reader);
 		Py_DECREF(args);
-		if (result != NULL && !PyString_Check(result) &&
+		if (result != NULL && !PyBytes_Check(result) &&
 		    !PyUnicode_Check(result)) {
 			Py_DECREF(result);
 			result = NULL;
@@ -1388,9 +1411,9 @@
 		}
 	}
 
-	if (n < 0 && result != NULL && PyString_Check(result)) {
-		char *s = PyString_AS_STRING(result);
-		Py_ssize_t len = PyString_GET_SIZE(result);
+	if (n < 0 && result != NULL && PyBytes_Check(result)) {
+		char *s = PyBytes_AS_STRING(result);
+		Py_ssize_t len = PyBytes_GET_SIZE(result);
 		if (len == 0) {
 			Py_DECREF(result);
 			result = NULL;
@@ -1399,10 +1422,10 @@
 		}
 		else if (s[len-1] == '\n') {
 			if (result->ob_refcnt == 1)
-				_PyString_Resize(&result, len-1);
+				_PyBytes_Resize(&result, len-1);
 			else {
 				PyObject *v;
-				v = PyString_FromStringAndSize(s, len-1);
+				v = PyBytes_FromStringAndSize(s, len-1);
 				Py_DECREF(result);
 				result = v;
 			}
@@ -1450,7 +1473,7 @@
 	if (!PyArg_ParseTuple(args, "|i:readline", &n))
 		return NULL;
 	if (n == 0)
-		return PyString_FromString("");
+		return PyBytes_FromString("");
 	if (n < 0)
 		n = 0;
 	return get_line(f, n);
@@ -1516,18 +1539,18 @@
 			}
 			if (big_buffer == NULL) {
 				/* Create the big buffer */
-				big_buffer = PyString_FromStringAndSize(
+				big_buffer = PyBytes_FromStringAndSize(
 					NULL, buffersize);
 				if (big_buffer == NULL)
 					goto error;
-				buffer = PyString_AS_STRING(big_buffer);
+				buffer = PyBytes_AS_STRING(big_buffer);
 				memcpy(buffer, small_buffer, nfilled);
 			}
 			else {
 				/* Grow the big buffer */
-				if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
+				if ( _PyBytes_Resize(&big_buffer, buffersize) < 0 )
 					goto error;
-				buffer = PyString_AS_STRING(big_buffer);
+				buffer = PyBytes_AS_STRING(big_buffer);
 			}
 			continue;
 		}
@@ -1536,7 +1559,7 @@
 		do {
 			/* Process complete lines */
 			p++;
-			line = PyString_FromStringAndSize(q, p-q);
+			line = PyBytes_FromStringAndSize(q, p-q);
 			if (line == NULL)
 				goto error;
 			err = PyList_Append(list, line);
@@ -1555,7 +1578,7 @@
 	}
 	if (nfilled != 0) {
 		/* Partial last line */
-		line = PyString_FromStringAndSize(buffer, nfilled);
+		line = PyBytes_FromStringAndSize(buffer, nfilled);
 		if (line == NULL)
 			goto error;
 		if (sizehint > 0) {
@@ -1565,7 +1588,7 @@
 				Py_DECREF(line);
 				goto error;
 			}
-			PyString_Concat(&line, rest);
+			PyBytes_Concat(&line, rest);
 			Py_DECREF(rest);
 			if (line == NULL)
 				goto error;
@@ -1672,7 +1695,7 @@
 		   could potentially execute Python code. */
 		for (i = 0; i < j; i++) {
 			PyObject *v = PyList_GET_ITEM(list, i);
-			if (!PyString_Check(v)) {
+			if (!PyBytes_Check(v)) {
 			    	const char *buffer;
 				if (((f->f_binary &&
 				      PyObject_AsReadBuffer(v,
@@ -1685,7 +1708,7 @@
 			"writelines() argument must be a sequence of strings");
 					goto error;
 				}
-				line = PyString_FromStringAndSize(buffer,
+				line = PyBytes_FromStringAndSize(buffer,
 								  len);
 				if (line == NULL)
 					goto error;
@@ -1701,8 +1724,8 @@
 		errno = 0;
 		for (i = 0; i < j; i++) {
 		    	line = PyList_GET_ITEM(list, i);
-			len = PyString_GET_SIZE(line);
-			nwritten = fwrite(PyString_AS_STRING(line),
+			len = PyBytes_GET_SIZE(line);
+			nwritten = fwrite(PyBytes_AS_STRING(line),
 					  1, len, f->f_fp);
 			if (nwritten != len) {
 				FILE_ABORT_ALLOW_THREADS(f)
@@ -1736,6 +1759,15 @@
 }
 
 static PyObject *
+file_xreadlines(PyFileObject *f)
+{
+	if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
+			   "try 'for line in f' instead", 1) < 0)
+	       return NULL;
+	return file_self(f);
+}
+
+static PyObject *
 file_exit(PyObject *f, PyObject *args)
 {
 	PyObject *ret = PyObject_CallMethod(f, "close", NULL);
@@ -1850,9 +1882,9 @@
 #endif
 	{"tell",      (PyCFunction)file_tell,     METH_NOARGS,  tell_doc},
 	{"readinto",  (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
-	{"readlines", (PyCFunction)file_readlines,METH_VARARGS, readlines_doc},
-	{"xreadlines",(PyCFunction)file_self,     METH_NOARGS, xreadlines_doc},
-	{"writelines",(PyCFunction)file_writelines, METH_O,    writelines_doc},
+	{"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
+	{"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
+	{"writelines",(PyCFunction)file_writelines, METH_O,     writelines_doc},
 	{"flush",     (PyCFunction)file_flush,    METH_NOARGS,  flush_doc},
 	{"close",     (PyCFunction)file_close,    METH_NOARGS,  close_doc},
 	{"isatty",    (PyCFunction)file_isatty,   METH_NOARGS,  isatty_doc},
@@ -1870,6 +1902,8 @@
 	 "file name"},
 	{"encoding",	T_OBJECT,	OFF(f_encoding),	RO,
 	 "file encoding"},
+	{"errors",	T_OBJECT,	OFF(f_errors),	RO,
+	 "Unicode error handler"},
 	/* getattr(f, "closed") is implemented without this table */
 	{NULL}	/* Sentinel */
 };
@@ -1887,13 +1921,13 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	case NEWLINE_CR:
-		return PyString_FromString("\r");
+		return PyBytes_FromString("\r");
 	case NEWLINE_LF:
-		return PyString_FromString("\n");
+		return PyBytes_FromString("\n");
 	case NEWLINE_CR|NEWLINE_LF:
 		return Py_BuildValue("(ss)", "\r", "\n");
 	case NEWLINE_CRLF:
-		return PyString_FromString("\r\n");
+		return PyBytes_FromString("\r\n");
 	case NEWLINE_CR|NEWLINE_CRLF:
 		return Py_BuildValue("(ss)", "\r", "\r\n");
 	case NEWLINE_LF|NEWLINE_CRLF:
@@ -1995,10 +2029,10 @@
    horrified by the recursive call: maximum recursion depth is limited by
    logarithmic buffer growth to about 50 even when reading a 1gb line. */
 
-static PyStringObject *
+static PyBytesObject *
 readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
 {
-	PyStringObject* s;
+	PyBytesObject* s;
 	char *bufptr;
 	char *buf;
 	Py_ssize_t len;
@@ -2009,17 +2043,17 @@
 
 	len = f->f_bufend - f->f_bufptr;
 	if (len == 0)
-		return (PyStringObject *)
-			PyString_FromStringAndSize(NULL, skip);
+		return (PyBytesObject *)
+			PyBytes_FromStringAndSize(NULL, skip);
 	bufptr = (char *)memchr(f->f_bufptr, '\n', len);
 	if (bufptr != NULL) {
 		bufptr++;			/* Count the '\n' */
 		len = bufptr - f->f_bufptr;
-		s = (PyStringObject *)
-			PyString_FromStringAndSize(NULL, skip+len);
+		s = (PyBytesObject *)
+			PyBytes_FromStringAndSize(NULL, skip+len);
 		if (s == NULL)
 			return NULL;
-		memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
+		memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len);
 		f->f_bufptr = bufptr;
 		if (bufptr == f->f_bufend)
 			drop_readahead(f);
@@ -2034,7 +2068,7 @@
 		        PyMem_Free(buf);
 			return NULL;
 		}
-		memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
+		memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len);
 		PyMem_Free(buf);
 	}
 	return s;
@@ -2046,13 +2080,13 @@
 static PyObject *
 file_iternext(PyFileObject *f)
 {
-	PyStringObject* l;
+	PyBytesObject* l;
 
 	if (f->f_fp == NULL)
 		return err_closed();
 
 	l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
-	if (l == NULL || PyString_GET_SIZE(l) == 0) {
+	if (l == NULL || PyBytes_GET_SIZE(l) == 0) {
 		Py_XDECREF(l);
 		return NULL;
 	}
@@ -2069,7 +2103,7 @@
 	assert(type != NULL && type->tp_alloc != NULL);
 
 	if (not_yet_string == NULL) {
-		not_yet_string = PyString_InternFromString("<uninitialized file>");
+		not_yet_string = PyBytes_InternFromString("<uninitialized file>");
 		if (not_yet_string == NULL)
 			return NULL;
 	}
@@ -2084,6 +2118,8 @@
 		((PyFileObject *)self)->f_mode = not_yet_string;
 		Py_INCREF(Py_None);
 		((PyFileObject *)self)->f_encoding = Py_None;
+		Py_INCREF(Py_None);
+		((PyFileObject *)self)->f_errors = Py_None;
 		((PyFileObject *)self)->weakreflist = NULL;
 		((PyFileObject *)self)->unlocked_count = 0;
 	}
@@ -2285,8 +2321,10 @@
 #ifdef Py_USING_UNICODE
                 if ((flags & Py_PRINT_RAW) &&
 		    PyUnicode_Check(v) && enc != Py_None) {
-			char *cenc = PyString_AS_STRING(enc);
-			value = PyUnicode_AsEncodedString(v, cenc, "strict");
+			char *cenc = PyBytes_AS_STRING(enc);
+			char *errors = fobj->f_errors == Py_None ? 
+			  "strict" : PyBytes_AS_STRING(fobj->f_errors);
+			value = PyUnicode_AsEncodedString(v, cenc, errors);
 			if (value == NULL)
 				return -1;
 		} else {
@@ -2356,7 +2394,7 @@
 		return 0;
 	}
 	else if (!PyErr_Occurred()) {
-		PyObject *v = PyString_FromString(s);
+		PyObject *v = PyBytes_FromString(s);
 		int err;
 		if (v == NULL)
 			return -1;

Modified: python/branches/okkoto-sizeof/Objects/floatobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/floatobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/floatobject.c	Wed Jun  4 11:24:23 2008
@@ -14,9 +14,6 @@
 #include <ieeefp.h>
 #endif
 
-#include "formatter_string.h"
-
-
 #ifdef _OSF_SOURCE
 /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
 extern int finite(double);
@@ -185,9 +182,9 @@
 
 	if (pend)
 		*pend = NULL;
-	if (PyString_Check(v)) {
-		s = PyString_AS_STRING(v);
-		len = PyString_GET_SIZE(v);
+	if (PyBytes_Check(v)) {
+		s = PyBytes_AS_STRING(v);
+		len = PyBytes_GET_SIZE(v);
 	}
 #ifdef Py_USING_UNICODE
 	else if (PyUnicode_Check(v)) {
@@ -488,7 +485,7 @@
 	char buf[100];
 	format_float(buf, sizeof(buf), v, PREC_REPR);
 
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static PyObject *
@@ -496,7 +493,7 @@
 {
 	char buf[100];
 	format_float(buf, sizeof(buf), v, PREC_STR);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 /* Comparison is pretty much a nightmare.  When comparing float to float,
@@ -1221,7 +1218,7 @@
 		return float_subtype_new(type, args, kwds); /* Wimp out */
 	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
 		return NULL;
-	if (PyString_Check(x))
+	if (PyBytes_Check(x))
 		return PyFloat_FromString(x, NULL);
 	return PyNumber_Float(x);
 }
@@ -1272,13 +1269,13 @@
 	char* s;
 	float_format_type r;
 
-	if (!PyString_Check(arg)) {
+	if (!PyBytes_Check(arg)) {
 		PyErr_Format(PyExc_TypeError,
 	     "__getformat__() argument must be string, not %.500s",
 			     Py_TYPE(arg)->tp_name);
 		return NULL;
 	}
-	s = PyString_AS_STRING(arg);
+	s = PyBytes_AS_STRING(arg);
 	if (strcmp(s, "double") == 0) {
 		r = double_format;
 	}
@@ -1294,11 +1291,11 @@
 	
 	switch (r) {
 	case unknown_format:
-		return PyString_FromString("unknown");
+		return PyBytes_FromString("unknown");
 	case ieee_little_endian_format:
-		return PyString_FromString("IEEE, little-endian");
+		return PyBytes_FromString("IEEE, little-endian");
 	case ieee_big_endian_format:
-		return PyString_FromString("IEEE, big-endian");
+		return PyBytes_FromString("IEEE, big-endian");
 	default:
 		Py_FatalError("insane float_format or double_format");
 		return NULL;
@@ -1397,27 +1394,23 @@
 
 	if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
 		return NULL;
-	if (PyString_Check(format_spec))
-		return string_float__format__(self, args);
+	if (PyBytes_Check(format_spec))
+		return _PyFloat_FormatAdvanced(self,
+					       PyBytes_AS_STRING(format_spec),
+					       PyBytes_GET_SIZE(format_spec));
 	if (PyUnicode_Check(format_spec)) {
 		/* Convert format_spec to a str */
-		PyObject *result = NULL;
-		PyObject *newargs = NULL;
-		PyObject *string_format_spec = NULL;
-
-		string_format_spec = PyObject_Str(format_spec);
-		if (string_format_spec == NULL)
-			goto done;
-
-		newargs = Py_BuildValue("(O)", string_format_spec);
-		if (newargs == NULL)
-			goto done;
-
-		result = string_float__format__(self, newargs);
-
-		done:
-		Py_XDECREF(string_format_spec);
-		Py_XDECREF(newargs);
+		PyObject *result;
+		PyObject *str_spec = PyObject_Str(format_spec);
+
+		if (str_spec == NULL)
+			return NULL;
+
+		result = _PyFloat_FormatAdvanced(self,
+						 PyBytes_AS_STRING(str_spec),
+						 PyBytes_GET_SIZE(str_spec));
+
+		Py_DECREF(str_spec);
 		return result;
 	}
 	PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");

Modified: python/branches/okkoto-sizeof/Objects/frameobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/frameobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/frameobject.c	Wed Jun  4 11:24:23 2008
@@ -114,7 +114,7 @@
 
 	/* Find the bytecode offset for the start of the given line, or the
 	 * first code-owning line after it. */
-	PyString_AsStringAndSize(f->f_code->co_lnotab, &lnotab, &lnotab_len);
+	PyBytes_AsStringAndSize(f->f_code->co_lnotab, &lnotab, &lnotab_len);
 	addr = 0;
 	line = f->f_code->co_firstlineno;
 	new_lasti = -1;
@@ -137,7 +137,7 @@
 	}
 
 	/* We're now ready to look at the bytecode. */
-	PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
+	PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
 	min_addr = MIN(new_lasti, f->f_lasti);
 	max_addr = MAX(new_lasti, f->f_lasti);
 
@@ -548,7 +548,7 @@
 
 int _PyFrame_Init()
 {
-	builtin_object = PyString_InternFromString("__builtins__");
+	builtin_object = PyBytes_InternFromString("__builtins__");
 	return (builtin_object != NULL);
 }
 
@@ -728,7 +728,7 @@
 	for (j = nmap; --j >= 0; ) {
 		PyObject *key = PyTuple_GET_ITEM(map, j);
 		PyObject *value = values[j];
-		assert(PyString_Check(key));
+		assert(PyBytes_Check(key));
 		if (deref) {
 			assert(PyCell_Check(value));
 			value = PyCell_GET(value);
@@ -776,7 +776,7 @@
 	for (j = nmap; --j >= 0; ) {
 		PyObject *key = PyTuple_GET_ITEM(map, j);
 		PyObject *value = PyObject_GetItem(dict, key);
-		assert(PyString_Check(key));
+		assert(PyBytes_Check(key));
 		/* We only care about NULLs if clear is true. */
 		if (value == NULL) {
 			PyErr_Clear();

Modified: python/branches/okkoto-sizeof/Objects/funcobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/funcobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/funcobject.c	Wed Jun  4 11:24:23 2008
@@ -28,7 +28,7 @@
 		consts = ((PyCodeObject *)code)->co_consts;
 		if (PyTuple_Size(consts) >= 1) {
 			doc = PyTuple_GetItem(consts, 0);
-			if (!PyString_Check(doc) && !PyUnicode_Check(doc))
+			if (!PyBytes_Check(doc) && !PyUnicode_Check(doc))
 				doc = Py_None;
 		}
 		else
@@ -42,7 +42,7 @@
 		   Otherwise, use None.
 		*/
 		if (!__name__) {
-			__name__ = PyString_InternFromString("__name__");
+			__name__ = PyBytes_InternFromString("__name__");
 			if (!__name__) {
 				Py_DECREF(op);
 				return NULL;
@@ -254,7 +254,7 @@
 		PyErr_Format(PyExc_ValueError,
 			     "%s() requires a code object with %zd free vars,"
 			     " not %zd",
-			     PyString_AsString(op->func_name),
+			     PyBytes_AsString(op->func_name),
 			     nclosure, nfree);
 		return -1;
 	}
@@ -281,7 +281,7 @@
 		return -1;
 	/* Not legal to del f.func_name or to set it to anything
 	 * other than a string object. */
-	if (value == NULL || !PyString_Check(value)) {
+	if (value == NULL || !PyBytes_Check(value)) {
 		PyErr_SetString(PyExc_TypeError,
 				"__name__ must be set to a string object");
 		return -1;
@@ -380,7 +380,7 @@
 			      &PyDict_Type, &globals,
 			      &name, &defaults, &closure))
 		return NULL;
-	if (name != Py_None && !PyString_Check(name)) {
+	if (name != Py_None && !PyBytes_Check(name)) {
 		PyErr_SetString(PyExc_TypeError,
 				"arg 3 (name) must be None or string");
 		return NULL;
@@ -409,7 +409,7 @@
 	if (nfree != nclosure)
 		return PyErr_Format(PyExc_ValueError,
 				    "%s requires closure of length %zd, not %zd",
-				    PyString_AS_STRING(code->co_name),
+				    PyBytes_AS_STRING(code->co_name),
 				    nfree, nclosure);
 	if (nclosure) {
 		Py_ssize_t i;
@@ -465,8 +465,8 @@
 static PyObject*
 func_repr(PyFunctionObject *op)
 {
-	return PyString_FromFormat("<function %s at %p>",
-				   PyString_AsString(op->func_name),
+	return PyBytes_FromFormat("<function %s at %p>",
+				   PyBytes_AsString(op->func_name),
 				   op);
 }
 

Modified: python/branches/okkoto-sizeof/Objects/genobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/genobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/genobject.c	Wed Jun  4 11:24:23 2008
@@ -285,10 +285,10 @@
 gen_repr(PyGenObject *gen)
 {
 	char *code_name;
-	code_name = PyString_AsString(((PyCodeObject *)gen->gi_code)->co_name);
+	code_name = PyBytes_AsString(((PyCodeObject *)gen->gi_code)->co_name);
 	if (code_name == NULL)
 		return NULL;
-	return PyString_FromFormat("<%.200s generator object at %p>",
+	return PyBytes_FromFormat("<generator object %.200s at %p>",
 				   code_name, gen);
 }
 

Modified: python/branches/okkoto-sizeof/Objects/intobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/intobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/intobject.c	Wed Jun  4 11:24:23 2008
@@ -3,7 +3,6 @@
 
 #include "Python.h"
 #include <ctype.h>
-#include "formatter_string.h"
 
 static PyObject *int_int(PyIntObject *v);
 
@@ -368,7 +367,7 @@
 	if (*end != '\0') {
   bad:
 		slen = strlen(s) < 200 ? strlen(s) : 200;
-		sobj = PyString_FromStringAndSize(s, slen);
+		sobj = PyBytes_FromStringAndSize(s, slen);
 		if (sobj == NULL)
 			return NULL;
 		srepr = PyObject_Repr(sobj);
@@ -377,7 +376,7 @@
 			return NULL;
 		PyErr_Format(PyExc_ValueError,
 			     "invalid literal for int() with base %d: %s",
-			     base, PyString_AS_STRING(srepr));
+			     base, PyBytes_AS_STRING(srepr));
 		Py_DECREF(srepr);
 		return NULL;
 	}
@@ -965,11 +964,11 @@
 		return PyInt_FromLong(0L);
 	if (base == -909)
 		return PyNumber_Int(x);
-	if (PyString_Check(x)) {
+	if (PyBytes_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)) {
+		char *string = PyBytes_AS_STRING(x);
+		if (strlen(string) != PyBytes_Size(x)) {
 			/* create a repr() of the input string,
 			 * just like PyInt_FromString does */
 			PyObject *srepr;
@@ -978,7 +977,7 @@
 				return NULL;
 			PyErr_Format(PyExc_ValueError,
 			     "invalid literal for int() with base %d: %s",
-			     base, PyString_AS_STRING(srepr));
+			     base, PyBytes_AS_STRING(srepr));
 			Py_DECREF(srepr);
 			return NULL;
 		}
@@ -1106,7 +1105,7 @@
 	if (negative)
 		*--p = '-';
 
-	return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
+	return PyBytes_FromStringAndSize(p, &buf[sizeof(buf)] - p);
 }
 
 static PyObject *
@@ -1116,27 +1115,23 @@
 
 	if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
 		return NULL;
-	if (PyString_Check(format_spec))
-		return string_int__format__(self, args);
+	if (PyBytes_Check(format_spec))
+		return _PyInt_FormatAdvanced(self,
+					     PyBytes_AS_STRING(format_spec),
+					     PyBytes_GET_SIZE(format_spec));
 	if (PyUnicode_Check(format_spec)) {
 		/* Convert format_spec to a str */
-		PyObject *result = NULL;
-		PyObject *newargs = NULL;
-		PyObject *string_format_spec = NULL;
-
-		string_format_spec = PyObject_Str(format_spec);
-		if (string_format_spec == NULL)
-			goto done;
-
-		newargs = Py_BuildValue("(O)", string_format_spec);
-		if (newargs == NULL)
-			goto done;
-
-		result = string_int__format__(self, newargs);
-
-		done:
-		Py_XDECREF(string_format_spec);
-		Py_XDECREF(newargs);
+		PyObject *result;
+		PyObject *str_spec = PyObject_Str(format_spec);
+
+		if (str_spec == NULL)
+			return NULL;
+
+		result = _PyInt_FormatAdvanced(self,
+					       PyBytes_AS_STRING(str_spec),
+					       PyBytes_GET_SIZE(str_spec));
+
+		Py_DECREF(str_spec);
 		return result;
 	}
 	PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");

Modified: python/branches/okkoto-sizeof/Objects/listobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/listobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/listobject.c	Wed Jun  4 11:24:23 2008
@@ -174,7 +174,7 @@
 	}
 	if (i < 0 || i >= Py_SIZE(op)) {
 		if (indexerr == NULL)
-			indexerr = PyString_FromString(
+			indexerr = PyBytes_FromString(
 				"list index out of range");
 		PyErr_SetObject(PyExc_IndexError, indexerr);
 		return NULL;
@@ -349,11 +349,11 @@
 
 	i = Py_ReprEnter((PyObject*)v);
 	if (i != 0) {
-		return i > 0 ? PyString_FromString("[...]") : NULL;
+		return i > 0 ? PyBytes_FromString("[...]") : NULL;
 	}
 
 	if (Py_SIZE(v) == 0) {
-		result = PyString_FromString("[]");
+		result = PyBytes_FromString("[]");
 		goto Done;
 	}
 
@@ -379,29 +379,29 @@
 
 	/* Add "[]" decorations to the first and last items. */
 	assert(PyList_GET_SIZE(pieces) > 0);
-	s = PyString_FromString("[");
+	s = PyBytes_FromString("[");
 	if (s == NULL)
 		goto Done;
 	temp = PyList_GET_ITEM(pieces, 0);
-	PyString_ConcatAndDel(&s, temp);
+	PyBytes_ConcatAndDel(&s, temp);
 	PyList_SET_ITEM(pieces, 0, s);
 	if (s == NULL)
 		goto Done;
 
-	s = PyString_FromString("]");
+	s = PyBytes_FromString("]");
 	if (s == NULL)
 		goto Done;
 	temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
-	PyString_ConcatAndDel(&temp, s);
+	PyBytes_ConcatAndDel(&temp, s);
 	PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
 	if (temp == NULL)
 		goto Done;
 
 	/* Paste them all together with ", " between. */
-	s = PyString_FromString(", ");
+	s = PyBytes_FromString(", ");
 	if (s == NULL)
 		goto Done;
-	result = _PyString_Join(s, pieces);
+	result = _PyBytes_Join(s, pieces);
 	Py_DECREF(s);
 
 Done:
@@ -433,7 +433,7 @@
 {
 	if (i < 0 || i >= Py_SIZE(a)) {
 		if (indexerr == NULL)
-			indexerr = PyString_FromString(
+			indexerr = PyBytes_FromString(
 				"list index out of range");
 		PyErr_SetObject(PyExc_IndexError, indexerr);
 		return NULL;
@@ -2437,7 +2437,7 @@
 PyDoc_STRVAR(reversed_doc,
 "L.__reversed__() -- return a reverse iterator over the list");
 PyDoc_STRVAR(sizeof_doc,
-"L.__sizeof__() -- size of L in bytes");
+"L.__sizeof__() -- size of L in memory, in bytes");
 PyDoc_STRVAR(append_doc,
 "L.append(object) -- append object to end");
 PyDoc_STRVAR(extend_doc,

Modified: python/branches/okkoto-sizeof/Objects/longobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/longobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/longobject.c	Wed Jun  4 11:24:23 2008
@@ -6,7 +6,6 @@
 
 #include "Python.h"
 #include "longintrepr.h"
-#include "formatter_string.h"
 
 #include <ctype.h>
 
@@ -1200,7 +1199,7 @@
 _PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
 {
 	register PyLongObject *a = (PyLongObject *)aa;
-	PyStringObject *str;
+	PyBytesObject *str;
 	Py_ssize_t i, j, sz;
 	Py_ssize_t size_a;
 	char *p;
@@ -1229,10 +1228,10 @@
 				"long is too large to format");
 		return NULL;
 	}
-	str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
+	str = (PyBytesObject *) PyBytes_FromStringAndSize((char *)0, sz);
 	if (str == NULL)
 		return NULL;
-	p = PyString_AS_STRING(str) + sz;
+	p = PyBytes_AS_STRING(str) + sz;
 	*p = '\0';
         if (addL)
                 *--p = 'L';
@@ -1258,7 +1257,7 @@
 			do {
 				char cdigit = (char)(accum & (base - 1));
 				cdigit += (cdigit < 10) ? '0' : 'a'-10;
-				assert(p > PyString_AS_STRING(str));
+				assert(p > PyBytes_AS_STRING(str));
 				*--p = cdigit;
 				accumbits -= basebits;
 				accum >>= basebits;
@@ -1310,7 +1309,7 @@
 			do {
 				digit nextrem = (digit)(rem / base);
 				char c = (char)(rem - nextrem * base);
-				assert(p > PyString_AS_STRING(str));
+				assert(p > PyBytes_AS_STRING(str));
 				c += (c < 10) ? '0' : 'a'-10;
 				*--p = c;
 				rem = nextrem;
@@ -1348,14 +1347,14 @@
 	}
 	if (sign)
 		*--p = sign;
-	if (p != PyString_AS_STRING(str)) {
-		char *q = PyString_AS_STRING(str);
+	if (p != PyBytes_AS_STRING(str)) {
+		char *q = PyBytes_AS_STRING(str);
 		assert(p > q);
 		do {
 		} while ((*q++ = *p++) != '\0');
 		q--;
-		_PyString_Resize((PyObject **)&str,
-				 (Py_ssize_t) (q - PyString_AS_STRING(str)));
+		_PyBytes_Resize((PyObject **)&str,
+				 (Py_ssize_t) (q - PyBytes_AS_STRING(str)));
 	}
 	return (PyObject *)str;
 }
@@ -1719,7 +1718,7 @@
  onError:
 	Py_XDECREF(z);
 	slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
-	strobj = PyString_FromStringAndSize(orig_str, slen);
+	strobj = PyBytes_FromStringAndSize(orig_str, slen);
 	if (strobj == NULL)
 		return NULL;
 	strrepr = PyObject_Repr(strobj);
@@ -1728,7 +1727,7 @@
 		return NULL;
 	PyErr_Format(PyExc_ValueError,
 		     "invalid literal for long() with base %d: %s",
-		     base, PyString_AS_STRING(strrepr));
+		     base, PyBytes_AS_STRING(strrepr));
 	Py_DECREF(strrepr);
 	return NULL;
 }
@@ -3332,11 +3331,11 @@
 		return PyLong_FromLong(0L);
 	if (base == -909)
 		return PyNumber_Long(x);
-	else if (PyString_Check(x)) {
+	else if (PyBytes_Check(x)) {
 		/* Since PyLong_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)) {
+		char *string = PyBytes_AS_STRING(x);
+		if (strlen(string) != PyBytes_Size(x)) {
 			/* create a repr() of the input string,
 			 * just like PyLong_FromString does. */
 			PyObject *srepr;
@@ -3345,11 +3344,11 @@
 				return NULL;
 			PyErr_Format(PyExc_ValueError,
 			     "invalid literal for long() with base %d: %s",
-			     base, PyString_AS_STRING(srepr));
+			     base, PyBytes_AS_STRING(srepr));
 			Py_DECREF(srepr);
 			return NULL;
 		}
-		return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
+		return PyLong_FromString(PyBytes_AS_STRING(x), NULL, base);
 	}
 #ifdef Py_USING_UNICODE
 	else if (PyUnicode_Check(x))
@@ -3414,27 +3413,23 @@
 
 	if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
 		return NULL;
-	if (PyString_Check(format_spec))
-		return string_long__format__(self, args);
+	if (PyBytes_Check(format_spec))
+		return _PyLong_FormatAdvanced(self,
+					      PyBytes_AS_STRING(format_spec),
+					      PyBytes_GET_SIZE(format_spec));
 	if (PyUnicode_Check(format_spec)) {
 		/* Convert format_spec to a str */
-		PyObject *result = NULL;
-		PyObject *newargs = NULL;
-		PyObject *string_format_spec = NULL;
-
-		string_format_spec = PyObject_Str(format_spec);
-		if (string_format_spec == NULL)
-			goto done;
-
-		newargs = Py_BuildValue("(O)", string_format_spec);
-		if (newargs == NULL)
-			goto done;
-
-		result = string_long__format__(self, newargs);
-
-		done:
-		Py_XDECREF(string_format_spec);
-		Py_XDECREF(newargs);
+		PyObject *result;
+		PyObject *str_spec = PyObject_Str(format_spec);
+
+		if (str_spec == NULL)
+			return NULL;
+
+		result = _PyLong_FormatAdvanced(self,
+						PyBytes_AS_STRING(str_spec),
+						PyBytes_GET_SIZE(str_spec));
+
+		Py_DECREF(str_spec);
 		return result;
 	}
 	PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
@@ -3472,7 +3467,7 @@
 	{"__getnewargs__",	(PyCFunction)long_getnewargs,	METH_NOARGS},
         {"__format__", (PyCFunction)long__format__, METH_VARARGS},
 	{"__sizeof__",	(PyCFunction)long_sizeof, METH_NOARGS,
-	 "Returns size in bytes"},
+	 "Returns size in memory, in bytes"},
 	{NULL,		NULL}		/* sentinel */
 };
 

Modified: python/branches/okkoto-sizeof/Objects/methodobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/methodobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/methodobject.c	Wed Jun  4 11:24:23 2008
@@ -149,7 +149,7 @@
 	const char *doc = m->m_ml->ml_doc;
 
 	if (doc != NULL)
-		return PyString_FromString(doc);
+		return PyBytes_FromString(doc);
 	Py_INCREF(Py_None);
 	return Py_None;
 }
@@ -157,7 +157,7 @@
 static PyObject *
 meth_get__name__(PyCFunctionObject *m, void *closure)
 {
-	return PyString_FromString(m->m_ml->ml_name);
+	return PyBytes_FromString(m->m_ml->ml_name);
 }
 
 static int
@@ -202,9 +202,9 @@
 meth_repr(PyCFunctionObject *m)
 {
 	if (m->m_self == NULL)
-		return PyString_FromFormat("<built-in function %s>",
+		return PyBytes_FromFormat("<built-in function %s>",
 					   m->m_ml->ml_name);
-	return PyString_FromFormat("<built-in method %s of %s object at %p>",
+	return PyBytes_FromFormat("<built-in method %s of %s object at %p>",
 				   m->m_ml->ml_name,
 				   m->m_self->ob_type->tp_name,
 				   m->m_self);
@@ -333,7 +333,7 @@
 	i = 0;
 	for (c = chain; c != NULL; c = c->link) {
 		for (ml = c->methods; ml->ml_name != NULL; ml++) {
-			PyList_SetItem(v, i, PyString_FromString(ml->ml_name));
+			PyList_SetItem(v, i, PyBytes_FromString(ml->ml_name));
 			i++;
 		}
 	}
@@ -360,7 +360,7 @@
 		if (strcmp(name, "__doc__") == 0) {
 			const char *doc = self->ob_type->tp_doc;
 			if (doc != NULL)
-				return PyString_FromString(doc);
+				return PyBytes_FromString(doc);
 		}
 	}
 	while (chain != NULL) {

Modified: python/branches/okkoto-sizeof/Objects/moduleobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/moduleobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/moduleobject.c	Wed Jun  4 11:24:23 2008
@@ -22,7 +22,7 @@
 	m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
 	if (m == NULL)
 		return NULL;
-	nameobj = PyString_FromString(name);
+	nameobj = PyBytes_FromString(name);
 	m->md_dict = PyDict_New();
 	if (m->md_dict == NULL || nameobj == NULL)
 		goto fail;
@@ -68,12 +68,12 @@
 	d = ((PyModuleObject *)m)->md_dict;
 	if (d == NULL ||
 	    (nameobj = PyDict_GetItemString(d, "__name__")) == NULL ||
-	    !PyString_Check(nameobj))
+	    !PyBytes_Check(nameobj))
 	{
 		PyErr_SetString(PyExc_SystemError, "nameless module");
 		return NULL;
 	}
-	return PyString_AsString(nameobj);
+	return PyBytes_AsString(nameobj);
 }
 
 char *
@@ -88,12 +88,12 @@
 	d = ((PyModuleObject *)m)->md_dict;
 	if (d == NULL ||
 	    (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
-	    !PyString_Check(fileobj))
+	    !PyBytes_Check(fileobj))
 	{
 		PyErr_SetString(PyExc_SystemError, "module filename missing");
 		return NULL;
 	}
-	return PyString_AsString(fileobj);
+	return PyBytes_AsString(fileobj);
 }
 
 void
@@ -117,8 +117,8 @@
 	/* First, clear only names starting with a single underscore */
 	pos = 0;
 	while (PyDict_Next(d, &pos, &key, &value)) {
-		if (value != Py_None && PyString_Check(key)) {
-			char *s = PyString_AsString(key);
+		if (value != Py_None && PyBytes_Check(key)) {
+			char *s = PyBytes_AsString(key);
 			if (s[0] == '_' && s[1] != '_') {
 				if (Py_VerboseFlag > 1)
 				    PySys_WriteStderr("#   clear[1] %s\n", s);
@@ -130,8 +130,8 @@
 	/* Next, clear all names except for __builtins__ */
 	pos = 0;
 	while (PyDict_Next(d, &pos, &key, &value)) {
-		if (value != Py_None && PyString_Check(key)) {
-			char *s = PyString_AsString(key);
+		if (value != Py_None && PyBytes_Check(key)) {
+			char *s = PyBytes_AsString(key);
 			if (s[0] != '_' || strcmp(s, "__builtins__") != 0) {
 				if (Py_VerboseFlag > 1)
 				    PySys_WriteStderr("#   clear[2] %s\n", s);
@@ -195,9 +195,9 @@
 	filename = PyModule_GetFilename((PyObject *)m);
 	if (filename == NULL) {
 		PyErr_Clear();
-		return PyString_FromFormat("<module '%s' (built-in)>", name);
+		return PyBytes_FromFormat("<module '%s' (built-in)>", name);
 	}
-	return PyString_FromFormat("<module '%s' from '%s'>", name, filename);
+	return PyBytes_FromFormat("<module '%s' from '%s'>", name, filename);
 }
 
 /* We only need a traverse function, no clear function: If the module

Modified: python/branches/okkoto-sizeof/Objects/object.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/object.c	(original)
+++ python/branches/okkoto-sizeof/Objects/object.c	Wed Jun  4 11:24:23 2008
@@ -357,9 +357,9 @@
 	}
 #endif
 	if (v == NULL)
-		return PyString_FromString("<NULL>");
+		return PyBytes_FromString("<NULL>");
 	else if (Py_TYPE(v)->tp_repr == NULL)
-		return PyString_FromFormat("<%s object at %p>",
+		return PyBytes_FromFormat("<%s object at %p>",
 					   Py_TYPE(v)->tp_name, v);
 	else {
 		PyObject *res;
@@ -377,7 +377,7 @@
 				return NULL;
 		}
 #endif
-		if (!PyString_Check(res)) {
+		if (!PyBytes_Check(res)) {
 			PyErr_Format(PyExc_TypeError,
 				     "__repr__ returned non-string (type %.200s)",
 				     Py_TYPE(res)->tp_name);
@@ -394,8 +394,8 @@
 	PyObject *res;
 	int type_ok;
 	if (v == NULL)
-		return PyString_FromString("<NULL>");
-	if (PyString_CheckExact(v)) {
+		return PyBytes_FromString("<NULL>");
+	if (PyBytes_CheckExact(v)) {
 		Py_INCREF(v);
 		return v;
 	}
@@ -416,7 +416,7 @@
 	Py_LeaveRecursiveCall();
 	if (res == NULL)
 		return NULL;
-	type_ok = PyString_Check(res);
+	type_ok = PyBytes_Check(res);
 #ifdef Py_USING_UNICODE
 	type_ok = type_ok || PyUnicode_Check(res);
 #endif
@@ -447,7 +447,7 @@
 		    	return NULL;
 	}
 #endif
-	assert(PyString_Check(res));
+	assert(PyBytes_Check(res));
 	return res;
 }
 
@@ -461,7 +461,7 @@
 	static PyObject *unicodestr;
 
 	if (v == NULL) {
-		res = PyString_FromString("<NULL>");
+		res = PyBytes_FromString("<NULL>");
 		if (res == NULL)
 			return NULL;
 		str = PyUnicode_FromEncodedObject(res, NULL, "strict");
@@ -475,7 +475,7 @@
 	   check this before trying the __unicode__
 	   method. */
 	if (unicodestr == NULL) {
-		unicodestr= PyString_InternFromString("__unicode__");
+		unicodestr= PyBytes_InternFromString("__unicode__");
 		if (unicodestr == NULL)
 			return NULL;
 	}
@@ -492,7 +492,7 @@
 			return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
 			                             PyUnicode_GET_SIZE(v));
 		}
-		if (PyString_CheckExact(v)) {
+		if (PyBytes_CheckExact(v)) {
 			Py_INCREF(v);
 			res = v;
 		}
@@ -1084,7 +1084,7 @@
 
 	if (Py_TYPE(v)->tp_getattr != NULL)
 		return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
-	w = PyString_InternFromString(name);
+	w = PyBytes_InternFromString(name);
 	if (w == NULL)
 		return NULL;
 	res = PyObject_GetAttr(v, w);
@@ -1112,7 +1112,7 @@
 
 	if (Py_TYPE(v)->tp_setattr != NULL)
 		return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
-	s = PyString_InternFromString(name);
+	s = PyBytes_InternFromString(name);
 	if (s == NULL)
 		return -1;
 	res = PyObject_SetAttr(v, s, w);
@@ -1125,7 +1125,7 @@
 {
 	PyTypeObject *tp = Py_TYPE(v);
 
-	if (!PyString_Check(name)) {
+	if (!PyBytes_Check(name)) {
 #ifdef Py_USING_UNICODE
 		/* The Unicode to string conversion is done here because the
 		   existing tp_getattro slots expect a string object as name
@@ -1147,10 +1147,10 @@
 	if (tp->tp_getattro != NULL)
 		return (*tp->tp_getattro)(v, name);
 	if (tp->tp_getattr != NULL)
-		return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
+		return (*tp->tp_getattr)(v, PyBytes_AS_STRING(name));
 	PyErr_Format(PyExc_AttributeError,
 		     "'%.50s' object has no attribute '%.400s'",
-		     tp->tp_name, PyString_AS_STRING(name));
+		     tp->tp_name, PyBytes_AS_STRING(name));
 	return NULL;
 }
 
@@ -1172,7 +1172,7 @@
 	PyTypeObject *tp = Py_TYPE(v);
 	int err;
 
-	if (!PyString_Check(name)){
+	if (!PyBytes_Check(name)){
 #ifdef Py_USING_UNICODE
 		/* The Unicode to string conversion is done here because the
 		   existing tp_setattro slots expect a string object as name
@@ -1194,14 +1194,14 @@
 	else
 		Py_INCREF(name);
 
-	PyString_InternInPlace(&name);
+	PyBytes_InternInPlace(&name);
 	if (tp->tp_setattro != NULL) {
 		err = (*tp->tp_setattro)(v, name, value);
 		Py_DECREF(name);
 		return err;
 	}
 	if (tp->tp_setattr != NULL) {
-		err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
+		err = (*tp->tp_setattr)(v, PyBytes_AS_STRING(name), value);
 		Py_DECREF(name);
 		return err;
 	}
@@ -1212,14 +1212,14 @@
 			     "(%s .%.100s)",
 			     tp->tp_name,
 			     value==NULL ? "del" : "assign to",
-			     PyString_AS_STRING(name));
+			     PyBytes_AS_STRING(name));
 	else
 		PyErr_Format(PyExc_TypeError,
 			     "'%.100s' object has only read-only attributes "
 			     "(%s .%.100s)",
 			     tp->tp_name,
 			     value==NULL ? "del" : "assign to",
-			     PyString_AS_STRING(name));
+			     PyBytes_AS_STRING(name));
 	return -1;
 }
 
@@ -1271,7 +1271,7 @@
 	Py_ssize_t dictoffset;
 	PyObject **dictptr;
 
-	if (!PyString_Check(name)){
+	if (!PyBytes_Check(name)){
 #ifdef Py_USING_UNICODE
 		/* The Unicode to string conversion is done here because the
 		   existing tp_setattro slots expect a string object as name
@@ -1386,7 +1386,7 @@
 
 	PyErr_Format(PyExc_AttributeError,
 		     "'%.50s' object has no attribute '%.400s'",
-		     tp->tp_name, PyString_AS_STRING(name));
+		     tp->tp_name, PyBytes_AS_STRING(name));
   done:
 	Py_DECREF(name);
 	return res;
@@ -1401,7 +1401,7 @@
 	PyObject **dictptr;
 	int res = -1;
 
-	if (!PyString_Check(name)){
+	if (!PyBytes_Check(name)){
 #ifdef Py_USING_UNICODE
 		/* The Unicode to string conversion is done here because the
 		   existing tp_setattro slots expect a string object as name
@@ -1469,13 +1469,13 @@
 	if (descr == NULL) {
 		PyErr_Format(PyExc_AttributeError,
 			     "'%.100s' object has no attribute '%.200s'",
-			     tp->tp_name, PyString_AS_STRING(name));
+			     tp->tp_name, PyBytes_AS_STRING(name));
 		goto done;
 	}
 
 	PyErr_Format(PyExc_AttributeError,
 		     "'%.50s' object attribute '%.400s' is read-only",
-		     tp->tp_name, PyString_AS_STRING(name));
+		     tp->tp_name, PyBytes_AS_STRING(name));
   done:
 	Py_DECREF(name);
 	return res;
@@ -1682,7 +1682,7 @@
 		int i;
 		for (i = 0; i < PyList_GET_SIZE(list); ++i) {
 			PyObject *item = PyList_GET_ITEM(list, i);
-			if (PyString_Check(item)) {
+			if (PyBytes_Check(item)) {
 				result = PyDict_SetItem(dict, item, Py_None);
 				if (result < 0)
 					break;
@@ -1904,7 +1904,7 @@
 static PyObject *
 none_repr(PyObject *op)
 {
-	return PyString_FromString("None");
+	return PyBytes_FromString("None");
 }
 
 /* ARGUSED */
@@ -1946,7 +1946,7 @@
 static PyObject *
 NotImplemented_repr(PyObject *op)
 {
-	return PyString_FromString("NotImplemented");
+	return PyBytes_FromString("NotImplemented");
 }
 
 static PyTypeObject PyNotImplemented_Type = {
@@ -1983,10 +1983,10 @@
 	if (PyType_Ready(&PyBool_Type) < 0)
 		Py_FatalError("Can't initialize 'bool'");
 
-	if (PyType_Ready(&PyString_Type) < 0)
+	if (PyType_Ready(&PyBytes_Type) < 0)
 		Py_FatalError("Can't initialize 'str'");
 
-	if (PyType_Ready(&PyBytes_Type) < 0)
+	if (PyType_Ready(&PyByteArray_Type) < 0)
 		Py_FatalError("Can't initialize 'bytes'");
 
 	if (PyType_Ready(&PyList_Type) < 0)

Modified: python/branches/okkoto-sizeof/Objects/rangeobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/rangeobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/rangeobject.c	Wed Jun  4 11:24:23 2008
@@ -113,16 +113,16 @@
 	PyObject *rtn;
 
 	if (r->start == 0 && r->step == 1)
-		rtn = PyString_FromFormat("xrange(%ld)",
+		rtn = PyBytes_FromFormat("xrange(%ld)",
 					  r->start + r->len * r->step);
 
 	else if (r->step == 1)
-		rtn = PyString_FromFormat("xrange(%ld, %ld)",
+		rtn = PyBytes_FromFormat("xrange(%ld, %ld)",
 					  r->start,
 					  r->start + r->len * r->step);
 
 	else
-		rtn = PyString_FromFormat("xrange(%ld, %ld, %ld)",
+		rtn = PyBytes_FromFormat("xrange(%ld, %ld, %ld)",
 					  r->start,
 					  r->start + r->len * r->step,
 					  r->step);

Modified: python/branches/okkoto-sizeof/Objects/setobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/setobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/setobject.c	Wed Jun  4 11:24:23 2008
@@ -94,7 +94,9 @@
 	else {
 		if (entry->hash == hash) {
 			startkey = entry->key;
+			Py_INCREF(startkey);
 			cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
+			Py_DECREF(startkey);
 			if (cmp < 0)
 				return NULL;
 			if (table == so->table && entry->key == startkey) {
@@ -125,7 +127,9 @@
 			break;
 		if (entry->hash == hash && entry->key != dummy) {
 			startkey = entry->key;
+			Py_INCREF(startkey);
 			cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
+			Py_DECREF(startkey);
 			if (cmp < 0)
 				return NULL;
 			if (table == so->table && entry->key == startkey) {
@@ -147,7 +151,7 @@
 
 /*
  * Hacked up version of set_lookkey which can assume keys are always strings;
- * This means we can always use _PyString_Eq directly and not have to check to
+ * This means we can always use _PyBytes_Eq directly and not have to check to
  * see if the comparison altered the table.
  */
 static setentry *
@@ -164,7 +168,7 @@
 	   including subclasses of str; e.g., one reason to subclass
 	   strings is to override __eq__, and for speed we don't cater to
 	   that here. */
-	if (!PyString_CheckExact(key)) {
+	if (!PyBytes_CheckExact(key)) {
 		so->lookup = set_lookkey;
 		return set_lookkey(so, key, hash);
 	}
@@ -175,7 +179,7 @@
 	if (entry->key == dummy)
 		freeslot = entry;
 	else {
-		if (entry->hash == hash && _PyString_Eq(entry->key, key))
+		if (entry->hash == hash && _PyBytes_Eq(entry->key, key))
 			return entry;
 		freeslot = NULL;
 	}
@@ -190,7 +194,7 @@
 		if (entry->key == key
 		    || (entry->hash == hash
 			&& entry->key != dummy
-			&& _PyString_Eq(entry->key, key)))
+			&& _PyBytes_Eq(entry->key, key)))
 			return entry;
 		if (entry->key == dummy && freeslot == NULL)
 			freeslot = entry;
@@ -377,8 +381,8 @@
 	register long hash;
 	register Py_ssize_t n_used;
 
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return -1;
@@ -424,8 +428,8 @@
 	PyObject *old_key;
 
 	assert (PyAnySet_Check(so));
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return -1;
@@ -614,7 +618,7 @@
 	if (status != 0) {
 		if (status < 0)
 			return NULL;
-		return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
+		return PyBytes_FromFormat("%s(...)", so->ob_type->tp_name);
 	}
 
 	keys = PySequence_List((PyObject *)so);
@@ -625,8 +629,8 @@
 	if (listrepr == NULL)
 		goto done;
 
-	result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
-		PyString_AS_STRING(listrepr));
+	result = PyBytes_FromFormat("%s(%s)", so->ob_type->tp_name,
+		PyBytes_AS_STRING(listrepr));
 	Py_DECREF(listrepr);
 done:
 	Py_ReprLeave((PyObject*)so);
@@ -681,8 +685,8 @@
 	long hash;
 	setentry *entry;
 
-	if (!PyString_CheckExact(key) ||
-	    (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+	if (!PyBytes_CheckExact(key) ||
+	    (hash = ((PyBytesObject *) key)->ob_shash) == -1) {
 		hash = PyObject_Hash(key);
 		if (hash == -1)
 			return -1;
@@ -979,7 +983,7 @@
 	register PySetObject *so = NULL;
 
 	if (dummy == NULL) { /* Auto-initialize dummy */
-		dummy = PyString_FromString("<dummy key>");
+		dummy = PyBytes_FromString("<dummy key>");
 		if (dummy == NULL)
 			return NULL;
 	}
@@ -2318,7 +2322,7 @@
 	/* Exercise direct iteration */
 	i = 0, count = 0;
 	while (_PySet_Next((PyObject *)dup, &i, &x)) {
-		s = PyString_AsString(x);
+		s = PyBytes_AsString(x);
 		assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
 		count++;
 	}

Modified: python/branches/okkoto-sizeof/Objects/sliceobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/sliceobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/sliceobject.c	Wed Jun  4 11:24:23 2008
@@ -19,7 +19,7 @@
 static PyObject *
 ellipsis_repr(PyObject *op)
 {
-	return PyString_FromString("Ellipsis");
+	return PyBytes_FromString("Ellipsis");
 }
 
 static PyTypeObject PyEllipsis_Type = {
@@ -228,14 +228,14 @@
 {
 	PyObject *s, *comma;
 
-	s = PyString_FromString("slice(");
-	comma = PyString_FromString(", ");
-	PyString_ConcatAndDel(&s, PyObject_Repr(r->start));
-	PyString_Concat(&s, comma);
-	PyString_ConcatAndDel(&s, PyObject_Repr(r->stop));
-	PyString_Concat(&s, comma);
-	PyString_ConcatAndDel(&s, PyObject_Repr(r->step));
-	PyString_ConcatAndDel(&s, PyString_FromString(")"));
+	s = PyBytes_FromString("slice(");
+	comma = PyBytes_FromString(", ");
+	PyBytes_ConcatAndDel(&s, PyObject_Repr(r->start));
+	PyBytes_Concat(&s, comma);
+	PyBytes_ConcatAndDel(&s, PyObject_Repr(r->stop));
+	PyBytes_Concat(&s, comma);
+	PyBytes_ConcatAndDel(&s, PyObject_Repr(r->step));
+	PyBytes_ConcatAndDel(&s, PyBytes_FromString(")"));
 	Py_DECREF(comma);
 	return s;
 }

Modified: python/branches/okkoto-sizeof/Objects/stringlib/formatter.h
==============================================================================
--- python/branches/okkoto-sizeof/Objects/stringlib/formatter.h	(original)
+++ python/branches/okkoto-sizeof/Objects/stringlib/formatter.h	Wed Jun  4 11:24:23 2008
@@ -102,12 +102,13 @@
   if failure, sets the exception
 */
 static int
-parse_internal_render_format_spec(PyObject *format_spec,
+parse_internal_render_format_spec(STRINGLIB_CHAR *format_spec,
+				  Py_ssize_t format_spec_len,
                                   InternalFormatSpec *format,
                                   char default_type)
 {
-    STRINGLIB_CHAR *ptr = STRINGLIB_STR(format_spec);
-    STRINGLIB_CHAR *end = ptr + STRINGLIB_LEN(format_spec);
+    STRINGLIB_CHAR *ptr = format_spec;
+    STRINGLIB_CHAR *end = format_spec + format_spec_len;
 
     /* end-ptr is used throughout this code to specify the length of
        the input string */
@@ -756,56 +757,31 @@
 /************************************************************************/
 /*********** built in formatters ****************************************/
 /************************************************************************/
-#ifdef FORMAT_STRING
 PyObject *
-FORMAT_STRING(PyObject* value, PyObject* args)
+FORMAT_STRING(PyObject *obj,
+	      STRINGLIB_CHAR *format_spec,
+	      Py_ssize_t format_spec_len)
 {
-    PyObject *format_spec;
-    PyObject *result = NULL;
-#if PY_VERSION_HEX < 0x03000000
-    PyObject *tmp = NULL;
-#endif
     InternalFormatSpec format;
-
-    /* If 2.x, we accept either str or unicode, and try to convert it
-       to the right type.  In 3.x, we insist on only unicode */
-#if PY_VERSION_HEX >= 0x03000000
-    if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__",
-			  &format_spec))
-        goto done;
-#else
-    /* If 2.x, convert format_spec to the same type as value */
-    /* This is to allow things like u''.format('') */
-    if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
-        goto done;
-    if (!(PyString_Check(format_spec) || PyUnicode_Check(format_spec))) {
-        PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
-		     "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
-	goto done;
-    }
-    tmp = STRINGLIB_TOSTR(format_spec);
-    if (tmp == NULL)
-        goto done;
-    format_spec = tmp;
-#endif
+    PyObject *result = NULL;
 
     /* check for the special case of zero length format spec, make
-       it equivalent to str(value) */
-    if (STRINGLIB_LEN(format_spec) == 0) {
-        result = STRINGLIB_TOSTR(value);
+       it equivalent to str(obj) */
+    if (format_spec_len == 0) {
+        result = STRINGLIB_TOSTR(obj);
         goto done;
     }
 
-
     /* parse the format_spec */
-    if (!parse_internal_render_format_spec(format_spec, &format, 's'))
+    if (!parse_internal_render_format_spec(format_spec, format_spec_len,
+					   &format, 's'))
         goto done;
 
     /* type conversion? */
     switch (format.type) {
     case 's':
         /* no type conversion needed, already a string.  do the formatting */
-        result = format_string_internal(value, &format);
+        result = format_string_internal(obj, &format);
         break;
     default:
         /* unknown */
@@ -826,35 +802,31 @@
     }
 
 done:
-#if PY_VERSION_HEX < 0x03000000
-    Py_XDECREF(tmp);
-#endif
     return result;
 }
-#endif /* FORMAT_STRING */
 
 #if defined FORMAT_LONG || defined FORMAT_INT
 static PyObject*
-format_int_or_long(PyObject* value, PyObject* args, IntOrLongToString tostring)
+format_int_or_long(PyObject* obj,
+		   STRINGLIB_CHAR *format_spec,
+		   Py_ssize_t format_spec_len,
+		   IntOrLongToString tostring)
 {
-    PyObject *format_spec;
     PyObject *result = NULL;
     PyObject *tmp = NULL;
     InternalFormatSpec format;
 
-    if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__",
-			  &format_spec))
-        goto done;
-
     /* check for the special case of zero length format spec, make
-       it equivalent to str(value) */
-    if (STRINGLIB_LEN(format_spec) == 0) {
-        result = STRINGLIB_TOSTR(value);
+       it equivalent to str(obj) */
+    if (format_spec_len == 0) {
+        result = STRINGLIB_TOSTR(obj);
         goto done;
     }
 
     /* parse the format_spec */
-    if (!parse_internal_render_format_spec(format_spec, &format, 'd'))
+    if (!parse_internal_render_format_spec(format_spec,
+					   format_spec_len,
+					   &format, 'd'))
         goto done;
 
     /* type conversion? */
@@ -868,7 +840,7 @@
     case 'n':
         /* no type conversion needed, already an int (or long).  do
 	   the formatting */
-	    result = format_int_or_long_internal(value, &format, tostring);
+	    result = format_int_or_long_internal(obj, &format, tostring);
         break;
 
     case 'e':
@@ -879,10 +851,10 @@
     case 'G':
     case '%':
         /* convert to float */
-        tmp = PyNumber_Float(value);
+        tmp = PyNumber_Float(obj);
         if (tmp == NULL)
             goto done;
-        result = format_float_internal(value, &format);
+        result = format_float_internal(obj, &format);
         break;
 
     default:
@@ -917,9 +889,12 @@
 #endif
 
 PyObject *
-FORMAT_LONG(PyObject* value, PyObject* args)
+FORMAT_LONG(PyObject *obj,
+	    STRINGLIB_CHAR *format_spec,
+	    Py_ssize_t format_spec_len)
 {
-    return format_int_or_long(value, args, long_format);
+    return format_int_or_long(obj, format_spec, format_spec_len,
+			      long_format);
 }
 #endif /* FORMAT_LONG */
 
@@ -935,32 +910,35 @@
 }
 
 PyObject *
-FORMAT_INT(PyObject* value, PyObject* args)
+FORMAT_INT(PyObject *obj,
+	   STRINGLIB_CHAR *format_spec,
+	   Py_ssize_t format_spec_len)
 {
-    return format_int_or_long(value, args, int_format);
+    return format_int_or_long(obj, format_spec, format_spec_len,
+			      int_format);
 }
 #endif /* FORMAT_INT */
 
 #ifdef FORMAT_FLOAT
 PyObject *
-FORMAT_FLOAT(PyObject *value, PyObject *args)
+FORMAT_FLOAT(PyObject *obj,
+	     STRINGLIB_CHAR *format_spec,
+	     Py_ssize_t format_spec_len)
 {
-    PyObject *format_spec;
     PyObject *result = NULL;
     InternalFormatSpec format;
 
-    if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec))
-        goto done;
-
     /* check for the special case of zero length format spec, make
-       it equivalent to str(value) */
-    if (STRINGLIB_LEN(format_spec) == 0) {
-        result = STRINGLIB_TOSTR(value);
+       it equivalent to str(obj) */
+    if (format_spec_len == 0) {
+        result = STRINGLIB_TOSTR(obj);
         goto done;
     }
 
     /* parse the format_spec */
-    if (!parse_internal_render_format_spec(format_spec, &format, '\0'))
+    if (!parse_internal_render_format_spec(format_spec,
+					   format_spec_len,
+					   &format, '\0'))
         goto done;
 
     /* type conversion? */
@@ -979,7 +957,7 @@
     case 'n':
     case '%':
         /* no conversion, already a float.  do the formatting */
-        result = format_float_internal(value, &format);
+        result = format_float_internal(obj, &format);
         break;
 
     default:

Modified: python/branches/okkoto-sizeof/Objects/stringlib/string_format.h
==============================================================================
--- python/branches/okkoto-sizeof/Objects/stringlib/string_format.h	(original)
+++ python/branches/okkoto-sizeof/Objects/stringlib/string_format.h	Wed Jun  4 11:24:23 2008
@@ -496,7 +496,7 @@
 #if PY_VERSION_HEX >= 0x03000000
     assert(PyUnicode_Check(result));
 #else
-    assert(PyString_Check(result) || PyUnicode_Check(result));
+    assert(PyBytes_Check(result) || PyUnicode_Check(result));
 
     /* Convert result to our type.  We could be str, and result could
        be unicode */

Modified: python/branches/okkoto-sizeof/Objects/stringlib/stringdefs.h
==============================================================================
--- python/branches/okkoto-sizeof/Objects/stringlib/stringdefs.h	(original)
+++ python/branches/okkoto-sizeof/Objects/stringlib/stringdefs.h	Wed Jun  4 11:24:23 2008
@@ -6,7 +6,7 @@
    compiled as unicode. */
 #define STRINGLIB_IS_UNICODE     0
 
-#define STRINGLIB_OBJECT         PyStringObject
+#define STRINGLIB_OBJECT         PyBytesObject
 #define STRINGLIB_CHAR           char
 #define STRINGLIB_TYPE_NAME      "string"
 #define STRINGLIB_PARSE_CODE     "S"
@@ -16,13 +16,13 @@
 #define STRINGLIB_TOUPPER        toupper
 #define STRINGLIB_TOLOWER        tolower
 #define STRINGLIB_FILL           memset
-#define STRINGLIB_STR            PyString_AS_STRING
-#define STRINGLIB_LEN            PyString_GET_SIZE
-#define STRINGLIB_NEW            PyString_FromStringAndSize
-#define STRINGLIB_RESIZE         _PyString_Resize
-#define STRINGLIB_CHECK          PyString_Check
+#define STRINGLIB_STR            PyBytes_AS_STRING
+#define STRINGLIB_LEN            PyBytes_GET_SIZE
+#define STRINGLIB_NEW            PyBytes_FromStringAndSize
+#define STRINGLIB_RESIZE         _PyBytes_Resize
+#define STRINGLIB_CHECK          PyBytes_Check
 #define STRINGLIB_CMP            memcmp
 #define STRINGLIB_TOSTR          PyObject_Str
-#define STRINGLIB_GROUPING       _PyString_InsertThousandsGrouping
+#define STRINGLIB_GROUPING       _PyBytes_InsertThousandsGrouping
 
 #endif /* !STRINGLIB_STRINGDEFS_H */

Deleted: python/branches/okkoto-sizeof/Objects/stringobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/stringobject.c	Wed Jun  4 11:24:23 2008
+++ (empty file)
@@ -1,5189 +0,0 @@
-/* String object implementation */
-
-#define PY_SSIZE_T_CLEAN
-
-#include "Python.h"
-
-#include "formatter_string.h"
-
-#include <ctype.h>
-
-#ifdef COUNT_ALLOCS
-int null_strings, one_strings;
-#endif
-
-static PyStringObject *characters[UCHAR_MAX + 1];
-static PyStringObject *nullstring;
-
-/* This dictionary holds all interned strings.  Note that references to
-   strings in this dictionary are *not* counted in the string's ob_refcnt.
-   When the interned string reaches a refcnt of 0 the string deallocation
-   function will delete the reference from this dictionary.
-
-   Another way to look at this is that to say that the actual reference
-   count of a string is:  s->ob_refcnt + (s->ob_sstate?2:0)
-*/
-static PyObject *interned;
-
-/*
-   For both PyString_FromString() and PyString_FromStringAndSize(), the
-   parameter `size' denotes number of characters to allocate, not counting any
-   null terminating character.
-
-   For PyString_FromString(), the parameter `str' points to a null-terminated
-   string containing exactly `size' bytes.
-
-   For PyString_FromStringAndSize(), the parameter the parameter `str' is
-   either NULL or else points to a string containing at least `size' bytes.
-   For PyString_FromStringAndSize(), the string in the `str' parameter does
-   not have to be null-terminated.  (Therefore it is safe to construct a
-   substring by calling `PyString_FromStringAndSize(origstring, substrlen)'.)
-   If `str' is NULL then PyString_FromStringAndSize() will allocate `size+1'
-   bytes (setting the last byte to the null terminating character) and you can
-   fill in the data yourself.  If `str' is non-NULL then the resulting
-   PyString object must be treated as immutable and you must not fill in nor
-   alter the data yourself, since the strings may be shared.
-
-   The PyObject member `op->ob_size', which denotes the number of "extra
-   items" in a variable-size object, will contain the number of bytes
-   allocated for string data, not counting the null terminating character.  It
-   is therefore equal to the equal to the `size' parameter (for
-   PyString_FromStringAndSize()) or the length of the string in the `str'
-   parameter (for PyString_FromString()).
-*/
-PyObject *
-PyString_FromStringAndSize(const char *str, Py_ssize_t size)
-{
-	register PyStringObject *op;
-	if (size < 0) {
-		PyErr_SetString(PyExc_SystemError,
-		    "Negative size passed to PyString_FromStringAndSize");
-		return NULL;
-	}
-	if (size == 0 && (op = nullstring) != NULL) {
-#ifdef COUNT_ALLOCS
-		null_strings++;
-#endif
-		Py_INCREF(op);
-		return (PyObject *)op;
-	}
-	if (size == 1 && str != NULL &&
-	    (op = characters[*str & UCHAR_MAX]) != NULL)
-	{
-#ifdef COUNT_ALLOCS
-		one_strings++;
-#endif
-		Py_INCREF(op);
-		return (PyObject *)op;
-	}
-
-	/* Inline PyObject_NewVar */
-	op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
-	if (op == NULL)
-		return PyErr_NoMemory();
-	PyObject_INIT_VAR(op, &PyString_Type, size);
-	op->ob_shash = -1;
-	op->ob_sstate = SSTATE_NOT_INTERNED;
-	if (str != NULL)
-		Py_MEMCPY(op->ob_sval, str, size);
-	op->ob_sval[size] = '\0';
-	/* share short strings */
-	if (size == 0) {
-		PyObject *t = (PyObject *)op;
-		PyString_InternInPlace(&t);
-		op = (PyStringObject *)t;
-		nullstring = op;
-		Py_INCREF(op);
-	} else if (size == 1 && str != NULL) {
-		PyObject *t = (PyObject *)op;
-		PyString_InternInPlace(&t);
-		op = (PyStringObject *)t;
-		characters[*str & UCHAR_MAX] = op;
-		Py_INCREF(op);
-	}
-	return (PyObject *) op;
-}
-
-PyObject *
-PyString_FromString(const char *str)
-{
-	register size_t size;
-	register PyStringObject *op;
-
-	assert(str != NULL);
-	size = strlen(str);
-	if (size > PY_SSIZE_T_MAX) {
-		PyErr_SetString(PyExc_OverflowError,
-			"string is too long for a Python string");
-		return NULL;
-	}
-	if (size == 0 && (op = nullstring) != NULL) {
-#ifdef COUNT_ALLOCS
-		null_strings++;
-#endif
-		Py_INCREF(op);
-		return (PyObject *)op;
-	}
-	if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
-#ifdef COUNT_ALLOCS
-		one_strings++;
-#endif
-		Py_INCREF(op);
-		return (PyObject *)op;
-	}
-
-	/* Inline PyObject_NewVar */
-	op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
-	if (op == NULL)
-		return PyErr_NoMemory();
-	PyObject_INIT_VAR(op, &PyString_Type, size);
-	op->ob_shash = -1;
-	op->ob_sstate = SSTATE_NOT_INTERNED;
-	Py_MEMCPY(op->ob_sval, str, size+1);
-	/* share short strings */
-	if (size == 0) {
-		PyObject *t = (PyObject *)op;
-		PyString_InternInPlace(&t);
-		op = (PyStringObject *)t;
-		nullstring = op;
-		Py_INCREF(op);
-	} else if (size == 1) {
-		PyObject *t = (PyObject *)op;
-		PyString_InternInPlace(&t);
-		op = (PyStringObject *)t;
-		characters[*str & UCHAR_MAX] = op;
-		Py_INCREF(op);
-	}
-	return (PyObject *) op;
-}
-
-PyObject *
-PyString_FromFormatV(const char *format, va_list vargs)
-{
-	va_list count;
-	Py_ssize_t n = 0;
-	const char* f;
-	char *s;
-	PyObject* string;
-
-#ifdef VA_LIST_IS_ARRAY
-	Py_MEMCPY(count, vargs, sizeof(va_list));
-#else
-#ifdef  __va_copy
-	__va_copy(count, vargs);
-#else
-	count = vargs;
-#endif
-#endif
-	/* step 1: figure out how large a buffer we need */
-	for (f = format; *f; f++) {
-		if (*f == '%') {
-			const char* p = f;
-			while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
-				;
-
-			/* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
-			 * they don't affect the amount of space we reserve.
-			 */
-			if ((*f == 'l' || *f == 'z') &&
-					(f[1] == 'd' || f[1] == 'u'))
-				++f;
-
-			switch (*f) {
-			case 'c':
-				(void)va_arg(count, int);
-				/* fall through... */
-			case '%':
-				n++;
-				break;
-			case 'd': case 'u': case 'i': case 'x':
-				(void) va_arg(count, int);
-				/* 20 bytes is enough to hold a 64-bit
-				   integer.  Decimal takes the most space.
-				   This isn't enough for octal. */
-				n += 20;
-				break;
-			case 's':
-				s = va_arg(count, char*);
-				n += strlen(s);
-				break;
-			case 'p':
-				(void) va_arg(count, int);
-				/* maximum 64-bit pointer representation:
-				 * 0xffffffffffffffff
-				 * so 19 characters is enough.
-				 * XXX I count 18 -- what's the extra for?
-				 */
-				n += 19;
-				break;
-			default:
-				/* if we stumble upon an unknown
-				   formatting code, copy the rest of
-				   the format string to the output
-				   string. (we cannot just skip the
-				   code, since there's no way to know
-				   what's in the argument list) */
-				n += strlen(p);
-				goto expand;
-			}
-		} else
-			n++;
-	}
- expand:
-	/* step 2: fill the buffer */
-	/* Since we've analyzed how much space we need for the worst case,
-	   use sprintf directly instead of the slower PyOS_snprintf. */
-	string = PyString_FromStringAndSize(NULL, n);
-	if (!string)
-		return NULL;
-
-	s = PyString_AsString(string);
-
-	for (f = format; *f; f++) {
-		if (*f == '%') {
-			const char* p = f++;
-			Py_ssize_t i;
-			int longflag = 0;
-			int size_tflag = 0;
-			/* parse the width.precision part (we're only
-			   interested in the precision value, if any) */
-			n = 0;
-			while (isdigit(Py_CHARMASK(*f)))
-				n = (n*10) + *f++ - '0';
-			if (*f == '.') {
-				f++;
-				n = 0;
-				while (isdigit(Py_CHARMASK(*f)))
-					n = (n*10) + *f++ - '0';
-			}
-			while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
-				f++;
-			/* handle the long flag, but only for %ld and %lu.
-			   others can be added when necessary. */
-			if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
-				longflag = 1;
-				++f;
-			}
-			/* handle the size_t flag. */
-			if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
-				size_tflag = 1;
-				++f;
-			}
-
-			switch (*f) {
-			case 'c':
-				*s++ = va_arg(vargs, int);
-				break;
-			case 'd':
-				if (longflag)
-					sprintf(s, "%ld", va_arg(vargs, long));
-				else if (size_tflag)
-					sprintf(s, "%" PY_FORMAT_SIZE_T "d",
-					        va_arg(vargs, Py_ssize_t));
-				else
-					sprintf(s, "%d", va_arg(vargs, int));
-				s += strlen(s);
-				break;
-			case 'u':
-				if (longflag)
-					sprintf(s, "%lu",
-						va_arg(vargs, unsigned long));
-				else if (size_tflag)
-					sprintf(s, "%" PY_FORMAT_SIZE_T "u",
-					        va_arg(vargs, size_t));
-				else
-					sprintf(s, "%u",
-						va_arg(vargs, unsigned int));
-				s += strlen(s);
-				break;
-			case 'i':
-				sprintf(s, "%i", va_arg(vargs, int));
-				s += strlen(s);
-				break;
-			case 'x':
-				sprintf(s, "%x", va_arg(vargs, int));
-				s += strlen(s);
-				break;
-			case 's':
-				p = va_arg(vargs, char*);
-				i = strlen(p);
-				if (n > 0 && i > n)
-					i = n;
-				Py_MEMCPY(s, p, i);
-				s += i;
-				break;
-			case 'p':
-				sprintf(s, "%p", va_arg(vargs, void*));
-				/* %p is ill-defined:  ensure leading 0x. */
-				if (s[1] == 'X')
-					s[1] = 'x';
-				else if (s[1] != 'x') {
-					memmove(s+2, s, strlen(s)+1);
-					s[0] = '0';
-					s[1] = 'x';
-				}
-				s += strlen(s);
-				break;
-			case '%':
-				*s++ = '%';
-				break;
-			default:
-				strcpy(s, p);
-				s += strlen(s);
-				goto end;
-			}
-		} else
-			*s++ = *f;
-	}
-
- end:
-	_PyString_Resize(&string, s - PyString_AS_STRING(string));
-	return string;
-}
-
-PyObject *
-PyString_FromFormat(const char *format, ...)
-{
-	PyObject* ret;
-	va_list vargs;
-
-#ifdef HAVE_STDARG_PROTOTYPES
-	va_start(vargs, format);
-#else
-	va_start(vargs);
-#endif
-	ret = PyString_FromFormatV(format, vargs);
-	va_end(vargs);
-	return ret;
-}
-
-
-PyObject *PyString_Decode(const char *s,
-			  Py_ssize_t size,
-			  const char *encoding,
-			  const char *errors)
-{
-    PyObject *v, *str;
-
-    str = PyString_FromStringAndSize(s, size);
-    if (str == NULL)
-	return NULL;
-    v = PyString_AsDecodedString(str, encoding, errors);
-    Py_DECREF(str);
-    return v;
-}
-
-PyObject *PyString_AsDecodedObject(PyObject *str,
-				   const char *encoding,
-				   const char *errors)
-{
-    PyObject *v;
-
-    if (!PyString_Check(str)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-
-    if (encoding == NULL) {
-#ifdef Py_USING_UNICODE
-	encoding = PyUnicode_GetDefaultEncoding();
-#else
-	PyErr_SetString(PyExc_ValueError, "no encoding specified");
-	goto onError;
-#endif
-    }
-
-    /* Decode via the codec registry */
-    v = PyCodec_Decode(str, encoding, errors);
-    if (v == NULL)
-        goto onError;
-
-    return v;
-
- onError:
-    return NULL;
-}
-
-PyObject *PyString_AsDecodedString(PyObject *str,
-				   const char *encoding,
-				   const char *errors)
-{
-    PyObject *v;
-
-    v = PyString_AsDecodedObject(str, encoding, errors);
-    if (v == NULL)
-        goto onError;
-
-#ifdef Py_USING_UNICODE
-    /* Convert Unicode to a string using the default encoding */
-    if (PyUnicode_Check(v)) {
-	PyObject *temp = v;
-	v = PyUnicode_AsEncodedString(v, NULL, NULL);
-	Py_DECREF(temp);
-	if (v == NULL)
-	    goto onError;
-    }
-#endif
-    if (!PyString_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "decoder did not return a string object (type=%.400s)",
-                     Py_TYPE(v)->tp_name);
-        Py_DECREF(v);
-        goto onError;
-    }
-
-    return v;
-
- onError:
-    return NULL;
-}
-
-PyObject *PyString_Encode(const char *s,
-			  Py_ssize_t size,
-			  const char *encoding,
-			  const char *errors)
-{
-    PyObject *v, *str;
-
-    str = PyString_FromStringAndSize(s, size);
-    if (str == NULL)
-	return NULL;
-    v = PyString_AsEncodedString(str, encoding, errors);
-    Py_DECREF(str);
-    return v;
-}
-
-PyObject *PyString_AsEncodedObject(PyObject *str,
-				   const char *encoding,
-				   const char *errors)
-{
-    PyObject *v;
-
-    if (!PyString_Check(str)) {
-        PyErr_BadArgument();
-        goto onError;
-    }
-
-    if (encoding == NULL) {
-#ifdef Py_USING_UNICODE
-	encoding = PyUnicode_GetDefaultEncoding();
-#else
-	PyErr_SetString(PyExc_ValueError, "no encoding specified");
-	goto onError;
-#endif
-    }
-
-    /* Encode via the codec registry */
-    v = PyCodec_Encode(str, encoding, errors);
-    if (v == NULL)
-        goto onError;
-
-    return v;
-
- onError:
-    return NULL;
-}
-
-PyObject *PyString_AsEncodedString(PyObject *str,
-				   const char *encoding,
-				   const char *errors)
-{
-    PyObject *v;
-
-    v = PyString_AsEncodedObject(str, encoding, errors);
-    if (v == NULL)
-        goto onError;
-
-#ifdef Py_USING_UNICODE
-    /* Convert Unicode to a string using the default encoding */
-    if (PyUnicode_Check(v)) {
-	PyObject *temp = v;
-	v = PyUnicode_AsEncodedString(v, NULL, NULL);
-	Py_DECREF(temp);
-	if (v == NULL)
-	    goto onError;
-    }
-#endif
-    if (!PyString_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "encoder did not return a string object (type=%.400s)",
-                     Py_TYPE(v)->tp_name);
-        Py_DECREF(v);
-        goto onError;
-    }
-
-    return v;
-
- onError:
-    return NULL;
-}
-
-static void
-string_dealloc(PyObject *op)
-{
-	switch (PyString_CHECK_INTERNED(op)) {
-		case SSTATE_NOT_INTERNED:
-			break;
-
-		case SSTATE_INTERNED_MORTAL:
-			/* revive dead object temporarily for DelItem */
-			Py_REFCNT(op) = 3;
-			if (PyDict_DelItem(interned, op) != 0)
-				Py_FatalError(
-					"deletion of interned string failed");
-			break;
-
-		case SSTATE_INTERNED_IMMORTAL:
-			Py_FatalError("Immortal interned string died.");
-
-		default:
-			Py_FatalError("Inconsistent interned string state.");
-	}
-	Py_TYPE(op)->tp_free(op);
-}
-
-/* Unescape a backslash-escaped string. If unicode is non-zero,
-   the string is a u-literal. If recode_encoding is non-zero,
-   the string is UTF-8 encoded and should be re-encoded in the
-   specified encoding.  */
-
-PyObject *PyString_DecodeEscape(const char *s,
-				Py_ssize_t len,
-				const char *errors,
-				Py_ssize_t unicode,
-				const char *recode_encoding)
-{
-	int c;
-	char *p, *buf;
-	const char *end;
-	PyObject *v;
-	Py_ssize_t newlen = recode_encoding ? 4*len:len;
-	v = PyString_FromStringAndSize((char *)NULL, newlen);
-	if (v == NULL)
-		return NULL;
-	p = buf = PyString_AsString(v);
-	end = s + len;
-	while (s < end) {
-		if (*s != '\\') {
-		  non_esc:
-#ifdef Py_USING_UNICODE
-			if (recode_encoding && (*s & 0x80)) {
-				PyObject *u, *w;
-				char *r;
-				const char* t;
-				Py_ssize_t rn;
-				t = s;
-				/* Decode non-ASCII bytes as UTF-8. */
-				while (t < end && (*t & 0x80)) t++;
-				u = PyUnicode_DecodeUTF8(s, t - s, errors);
-				if(!u) goto failed;
-
-				/* Recode them in target encoding. */
-				w = PyUnicode_AsEncodedString(
-					u, recode_encoding, errors);
-				Py_DECREF(u);
-				if (!w)	goto failed;
-
-				/* Append bytes to output buffer. */
-				assert(PyString_Check(w));
-				r = PyString_AS_STRING(w);
-				rn = PyString_GET_SIZE(w);
-				Py_MEMCPY(p, r, rn);
-				p += rn;
-				Py_DECREF(w);
-				s = t;
-			} else {
-				*p++ = *s++;
-			}
-#else
-			*p++ = *s++;
-#endif
-			continue;
-		}
-		s++;
-                if (s==end) {
-			PyErr_SetString(PyExc_ValueError,
-					"Trailing \\ in string");
-			goto failed;
-		}
-		switch (*s++) {
-		/* XXX This assumes ASCII! */
-		case '\n': break;
-		case '\\': *p++ = '\\'; break;
-		case '\'': *p++ = '\''; break;
-		case '\"': *p++ = '\"'; break;
-		case 'b': *p++ = '\b'; break;
-		case 'f': *p++ = '\014'; break; /* FF */
-		case 't': *p++ = '\t'; break;
-		case 'n': *p++ = '\n'; break;
-		case 'r': *p++ = '\r'; break;
-		case 'v': *p++ = '\013'; break; /* VT */
-		case 'a': *p++ = '\007'; break; /* BEL, not classic C */
-		case '0': case '1': case '2': case '3':
-		case '4': case '5': case '6': case '7':
-			c = s[-1] - '0';
-			if (s < end && '0' <= *s && *s <= '7') {
-				c = (c<<3) + *s++ - '0';
-				if (s < end && '0' <= *s && *s <= '7')
-					c = (c<<3) + *s++ - '0';
-			}
-			*p++ = c;
-			break;
-		case 'x':
-			if (s+1 < end &&
-                            isxdigit(Py_CHARMASK(s[0])) &&
-			    isxdigit(Py_CHARMASK(s[1])))
-                        {
-				unsigned int x = 0;
-				c = Py_CHARMASK(*s);
-				s++;
-				if (isdigit(c))
-					x = c - '0';
-				else if (islower(c))
-					x = 10 + c - 'a';
-				else
-					x = 10 + c - 'A';
-				x = x << 4;
-				c = Py_CHARMASK(*s);
-				s++;
-				if (isdigit(c))
-					x += c - '0';
-				else if (islower(c))
-					x += 10 + c - 'a';
-				else
-					x += 10 + c - 'A';
-				*p++ = x;
-				break;
-			}
-			if (!errors || strcmp(errors, "strict") == 0) {
-				PyErr_SetString(PyExc_ValueError,
-						"invalid \\x escape");
-				goto failed;
-			}
-			if (strcmp(errors, "replace") == 0) {
-				*p++ = '?';
-			} else if (strcmp(errors, "ignore") == 0)
-				/* do nothing */;
-			else {
-				PyErr_Format(PyExc_ValueError,
-					     "decoding error; "
-					     "unknown error handling code: %.400s",
-					     errors);
-				goto failed;
-			}
-#ifndef Py_USING_UNICODE
-		case 'u':
-		case 'U':
-		case 'N':
-			if (unicode) {
-				PyErr_SetString(PyExc_ValueError,
-					  "Unicode escapes not legal "
-					  "when Unicode disabled");
-				goto failed;
-			}
-#endif
-		default:
-			*p++ = '\\';
-			s--;
-			goto non_esc; /* an arbitry number of unescaped
-					 UTF-8 bytes may follow. */
-		}
-	}
-	if (p-buf < newlen)
-		_PyString_Resize(&v, p - buf);
-	return v;
-  failed:
-	Py_DECREF(v);
-	return NULL;
-}
-
-/* -------------------------------------------------------------------- */
-/* object api */
-
-static Py_ssize_t
-string_getsize(register PyObject *op)
-{
-    	char *s;
-    	Py_ssize_t len;
-	if (PyString_AsStringAndSize(op, &s, &len))
-		return -1;
-	return len;
-}
-
-static /*const*/ char *
-string_getbuffer(register PyObject *op)
-{
-    	char *s;
-    	Py_ssize_t len;
-	if (PyString_AsStringAndSize(op, &s, &len))
-		return NULL;
-	return s;
-}
-
-Py_ssize_t
-PyString_Size(register PyObject *op)
-{
-	if (!PyString_Check(op))
-		return string_getsize(op);
-	return Py_SIZE(op);
-}
-
-/*const*/ char *
-PyString_AsString(register PyObject *op)
-{
-	if (!PyString_Check(op))
-		return string_getbuffer(op);
-	return ((PyStringObject *)op) -> ob_sval;
-}
-
-int
-PyString_AsStringAndSize(register PyObject *obj,
-			 register char **s,
-			 register Py_ssize_t *len)
-{
-	if (s == NULL) {
-		PyErr_BadInternalCall();
-		return -1;
-	}
-
-	if (!PyString_Check(obj)) {
-#ifdef Py_USING_UNICODE
-		if (PyUnicode_Check(obj)) {
-			obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
-			if (obj == NULL)
-				return -1;
-		}
-		else
-#endif
-		{
-			PyErr_Format(PyExc_TypeError,
-				     "expected string or Unicode object, "
-				     "%.200s found", Py_TYPE(obj)->tp_name);
-			return -1;
-		}
-	}
-
-	*s = PyString_AS_STRING(obj);
-	if (len != NULL)
-		*len = PyString_GET_SIZE(obj);
-	else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
-		PyErr_SetString(PyExc_TypeError,
-				"expected string without null bytes");
-		return -1;
-	}
-	return 0;
-}
-
-/* -------------------------------------------------------------------- */
-/* Methods */
-
-#include "stringlib/stringdefs.h"
-#include "stringlib/fastsearch.h"
-
-#include "stringlib/count.h"
-#include "stringlib/find.h"
-#include "stringlib/partition.h"
-
-#define _Py_InsertThousandsGrouping _PyString_InsertThousandsGrouping
-#include "stringlib/localeutil.h"
-
-
-
-static int
-string_print(PyStringObject *op, FILE *fp, int flags)
-{
-	Py_ssize_t i, str_len;
-	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);
-		Py_BEGIN_ALLOW_THREADS
-		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
-		Py_END_ALLOW_THREADS
-		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 = '"';
-
-	str_len = Py_SIZE(op);
-	Py_BEGIN_ALLOW_THREADS
-	fputc(quote, fp);
-	for (i = 0; i < str_len; i++) {
-		/* Since strings are immutable and the caller should have a
-		reference, accessing the interal buffer should not be an issue
-		with the GIL released. */
-		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);
-	Py_END_ALLOW_THREADS
-	return 0;
-}
-
-PyObject *
-PyString_Repr(PyObject *obj, int smartquotes)
-{
-	register PyStringObject* op = (PyStringObject*) obj;
-	size_t newsize = 2 + 4 * Py_SIZE(op);
-	PyObject *v;
-	if (newsize > PY_SSIZE_T_MAX || newsize / 4 != Py_SIZE(op)) {
-		PyErr_SetString(PyExc_OverflowError,
-			"string is too large to make repr");
-                return NULL;
-	}
-	v = PyString_FromStringAndSize((char *)NULL, newsize);
-	if (v == NULL) {
-		return NULL;
-	}
-	else {
-		register Py_ssize_t i;
-		register char c;
-		register char *p;
-		int quote;
-
-		/* figure out which quote to use; single is preferred */
-		quote = '\'';
-		if (smartquotes &&
-		    memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
-		    !memchr(op->ob_sval, '"', Py_SIZE(op)))
-			quote = '"';
-
-		p = PyString_AS_STRING(v);
-		*p++ = quote;
-		for (i = 0; i < Py_SIZE(op); i++) {
-			/* There's at least enough room for a hex escape
-			   and a closing quote. */
-			assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
-			c = op->ob_sval[i];
-			if (c == quote || c == '\\')
-				*p++ = '\\', *p++ = c;
-			else if (c == '\t')
-				*p++ = '\\', *p++ = 't';
-			else if (c == '\n')
-				*p++ = '\\', *p++ = 'n';
-			else if (c == '\r')
-				*p++ = '\\', *p++ = 'r';
-			else if (c < ' ' || c >= 0x7f) {
-				/* For performance, we don't want to call
-				   PyOS_snprintf here (extra layers of
-				   function call). */
-				sprintf(p, "\\x%02x", c & 0xff);
-                                p += 4;
-			}
-			else
-				*p++ = c;
-		}
-		assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
-		*p++ = quote;
-		*p = '\0';
-		_PyString_Resize(
-			&v, (p - PyString_AS_STRING(v)));
-		return v;
-	}
-}
-
-static PyObject *
-string_repr(PyObject *op)
-{
-	return PyString_Repr(op, 1);
-}
-
-static PyObject *
-string_str(PyObject *s)
-{
-	assert(PyString_Check(s));
-	if (PyString_CheckExact(s)) {
-		Py_INCREF(s);
-		return s;
-	}
-	else {
-		/* Subtype -- return genuine string with the same value. */
-		PyStringObject *t = (PyStringObject *) s;
-		return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
-	}
-}
-
-static Py_ssize_t
-string_length(PyStringObject *a)
-{
-	return Py_SIZE(a);
-}
-
-static PyObject *
-string_concat(register PyStringObject *a, register PyObject *bb)
-{
-	register Py_ssize_t size;
-	register PyStringObject *op;
-	if (!PyString_Check(bb)) {
-#ifdef Py_USING_UNICODE
-		if (PyUnicode_Check(bb))
-		    return PyUnicode_Concat((PyObject *)a, bb);
-#endif
-		if (PyBytes_Check(bb))
-		    return PyBytes_Concat((PyObject *)a, bb);
-		PyErr_Format(PyExc_TypeError,
-			     "cannot concatenate 'str' and '%.200s' objects",
-			     Py_TYPE(bb)->tp_name);
-		return NULL;
-	}
-#define b ((PyStringObject *)bb)
-	/* Optimize cases with empty left or right operand */
-	if ((Py_SIZE(a) == 0 || Py_SIZE(b) == 0) &&
-	    PyString_CheckExact(a) && PyString_CheckExact(b)) {
-		if (Py_SIZE(a) == 0) {
-			Py_INCREF(bb);
-			return bb;
-		}
-		Py_INCREF(a);
-		return (PyObject *)a;
-	}
-	size = Py_SIZE(a) + Py_SIZE(b);
-	if (size < 0) {
-		PyErr_SetString(PyExc_OverflowError,
-				"strings are too large to concat");
-		return NULL;
-	}
-	  
-	/* Inline PyObject_NewVar */
-	op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
-	if (op == NULL)
-		return PyErr_NoMemory();
-	PyObject_INIT_VAR(op, &PyString_Type, size);
-	op->ob_shash = -1;
-	op->ob_sstate = SSTATE_NOT_INTERNED;
-	Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
-	Py_MEMCPY(op->ob_sval + Py_SIZE(a), b->ob_sval, Py_SIZE(b));
-	op->ob_sval[size] = '\0';
-	return (PyObject *) op;
-#undef b
-}
-
-static PyObject *
-string_repeat(register PyStringObject *a, register Py_ssize_t n)
-{
-	register Py_ssize_t i;
-	register Py_ssize_t j;
-	register Py_ssize_t size;
-	register PyStringObject *op;
-	size_t nbytes;
-	if (n < 0)
-		n = 0;
-	/* watch out for overflows:  the size can overflow int,
-	 * and the # of bytes needed can overflow size_t
-	 */
-	size = Py_SIZE(a) * n;
-	if (n && size / n != Py_SIZE(a)) {
-		PyErr_SetString(PyExc_OverflowError,
-			"repeated string is too long");
-		return NULL;
-	}
-	if (size == Py_SIZE(a) && PyString_CheckExact(a)) {
-		Py_INCREF(a);
-		return (PyObject *)a;
-	}
-	nbytes = (size_t)size;
-	if (nbytes + sizeof(PyStringObject) <= nbytes) {
-		PyErr_SetString(PyExc_OverflowError,
-			"repeated string is too long");
-		return NULL;
-	}
-	op = (PyStringObject *)
-		PyObject_MALLOC(sizeof(PyStringObject) + nbytes);
-	if (op == NULL)
-		return PyErr_NoMemory();
-	PyObject_INIT_VAR(op, &PyString_Type, size);
-	op->ob_shash = -1;
-	op->ob_sstate = SSTATE_NOT_INTERNED;
-	op->ob_sval[size] = '\0';
-	if (Py_SIZE(a) == 1 && n > 0) {
-		memset(op->ob_sval, a->ob_sval[0] , n);
-		return (PyObject *) op;
-	}
-	i = 0;
-	if (i < size) {
-		Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
-		i = Py_SIZE(a);
-	}
-	while (i < size) {
-		j = (i <= size-i)  ?  i  :  size-i;
-		Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
-		i += j;
-	}
-	return (PyObject *) op;
-}
-
-/* String slice a[i:j] consists of characters a[i] ... a[j-1] */
-
-static PyObject *
-string_slice(register PyStringObject *a, register Py_ssize_t i,
-	     register Py_ssize_t j)
-     /* j -- may be negative! */
-{
-	if (i < 0)
-		i = 0;
-	if (j < 0)
-		j = 0; /* Avoid signed/unsigned bug in next line */
-	if (j > Py_SIZE(a))
-		j = Py_SIZE(a);
-	if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
-		/* It's the same as a */
-		Py_INCREF(a);
-		return (PyObject *)a;
-	}
-	if (j < i)
-		j = i;
-	return PyString_FromStringAndSize(a->ob_sval + i, j-i);
-}
-
-static int
-string_contains(PyObject *str_obj, PyObject *sub_obj)
-{
-	if (!PyString_CheckExact(sub_obj)) {
-#ifdef Py_USING_UNICODE
-		if (PyUnicode_Check(sub_obj))
-			return PyUnicode_Contains(str_obj, sub_obj);
-#endif
-		if (!PyString_Check(sub_obj)) {
-			PyErr_Format(PyExc_TypeError,
-			    "'in <string>' requires string as left operand, "
-			    "not %.200s", Py_TYPE(sub_obj)->tp_name);
-			return -1;
-		}
-	}
-
-	return stringlib_contains_obj(str_obj, sub_obj);
-}
-
-static PyObject *
-string_item(PyStringObject *a, register Py_ssize_t i)
-{
-	char pchar;
-	PyObject *v;
-	if (i < 0 || i >= Py_SIZE(a)) {
-		PyErr_SetString(PyExc_IndexError, "string index out of range");
-		return NULL;
-	}
-	pchar = a->ob_sval[i];
-	v = (PyObject *)characters[pchar & UCHAR_MAX];
-	if (v == NULL)
-		v = PyString_FromStringAndSize(&pchar, 1);
-	else {
-#ifdef COUNT_ALLOCS
-		one_strings++;
-#endif
-		Py_INCREF(v);
-	}
-	return v;
-}
-
-static PyObject*
-string_richcompare(PyStringObject *a, PyStringObject *b, int op)
-{
-	int c;
-	Py_ssize_t len_a, len_b;
-	Py_ssize_t min_len;
-	PyObject *result;
-
-	/* Make sure both arguments are strings. */
-	if (!(PyString_Check(a) && PyString_Check(b))) {
-		result = Py_NotImplemented;
-		goto out;
-	}
-	if (a == b) {
-		switch (op) {
-		case Py_EQ:case Py_LE:case Py_GE:
-			result = Py_True;
-			goto out;
-		case Py_NE:case Py_LT:case Py_GT:
-			result = Py_False;
-			goto out;
-		}
-	}
-	if (op == Py_EQ) {
-		/* Supporting Py_NE here as well does not save
-		   much time, since Py_NE is rarely used.  */
-		if (Py_SIZE(a) == Py_SIZE(b)
-		    && (a->ob_sval[0] == b->ob_sval[0]
-			&& memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
-			result = Py_True;
-		} else {
-			result = Py_False;
-		}
-		goto out;
-	}
-	len_a = Py_SIZE(a); len_b = Py_SIZE(b);
-	min_len = (len_a < len_b) ? len_a : len_b;
-	if (min_len > 0) {
-		c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
-		if (c==0)
-			c = memcmp(a->ob_sval, b->ob_sval, min_len);
-	} else
-		c = 0;
-	if (c == 0)
-		c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
-	switch (op) {
-	case Py_LT: c = c <  0; break;
-	case Py_LE: c = c <= 0; break;
-	case Py_EQ: assert(0);  break; /* unreachable */
-	case Py_NE: c = c != 0; break;
-	case Py_GT: c = c >  0; break;
-	case Py_GE: c = c >= 0; break;
-	default:
-		result = Py_NotImplemented;
-		goto out;
-	}
-	result = c ? Py_True : Py_False;
-  out:
-	Py_INCREF(result);
-	return result;
-}
-
-int
-_PyString_Eq(PyObject *o1, PyObject *o2)
-{
-	PyStringObject *a = (PyStringObject*) o1;
-	PyStringObject *b = (PyStringObject*) o2;
-        return Py_SIZE(a) == Py_SIZE(b)
-          && *a->ob_sval == *b->ob_sval
-          && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0;
-}
-
-static long
-string_hash(PyStringObject *a)
-{
-	register Py_ssize_t len;
-	register unsigned char *p;
-	register long x;
-
-	if (a->ob_shash != -1)
-		return a->ob_shash;
-	len = Py_SIZE(a);
-	p = (unsigned char *) a->ob_sval;
-	x = *p << 7;
-	while (--len >= 0)
-		x = (1000003*x) ^ *p++;
-	x ^= Py_SIZE(a);
-	if (x == -1)
-		x = -2;
-	a->ob_shash = x;
-	return x;
-}
-
-static PyObject*
-string_subscript(PyStringObject* self, PyObject* item)
-{
-	if (PyIndex_Check(item)) {
-		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-		if (i == -1 && PyErr_Occurred())
-			return NULL;
-		if (i < 0)
-			i += PyString_GET_SIZE(self);
-		return string_item(self, i);
-	}
-	else if (PySlice_Check(item)) {
-		Py_ssize_t start, stop, step, slicelength, cur, i;
-		char* source_buf;
-		char* result_buf;
-		PyObject* result;
-
-		if (PySlice_GetIndicesEx((PySliceObject*)item,
-				 PyString_GET_SIZE(self),
-				 &start, &stop, &step, &slicelength) < 0) {
-			return NULL;
-		}
-
-		if (slicelength <= 0) {
-			return PyString_FromStringAndSize("", 0);
-		}
-		else if (start == 0 && step == 1 &&
-			 slicelength == PyString_GET_SIZE(self) &&
-			 PyString_CheckExact(self)) {
-			Py_INCREF(self);
-			return (PyObject *)self;
-		}
-		else if (step == 1) {
-			return PyString_FromStringAndSize(
-				PyString_AS_STRING(self) + start,
-				slicelength);
-		}
-		else {
-			source_buf = PyString_AsString((PyObject*)self);
-			result_buf = (char *)PyMem_Malloc(slicelength);
-			if (result_buf == NULL)
-				return PyErr_NoMemory();
-
-			for (cur = start, i = 0; i < slicelength;
-			     cur += step, i++) {
-				result_buf[i] = source_buf[cur];
-			}
-
-			result = PyString_FromStringAndSize(result_buf,
-							    slicelength);
-			PyMem_Free(result_buf);
-			return result;
-		}
-	}
-	else {
-		PyErr_Format(PyExc_TypeError,
-			     "string indices must be integers, not %.200s",
-			     Py_TYPE(item)->tp_name);
-		return NULL;
-	}
-}
-
-static Py_ssize_t
-string_buffer_getreadbuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
-{
-	if ( index != 0 ) {
-		PyErr_SetString(PyExc_SystemError,
-				"accessing non-existent string segment");
-		return -1;
-	}
-	*ptr = (void *)self->ob_sval;
-	return Py_SIZE(self);
-}
-
-static Py_ssize_t
-string_buffer_getwritebuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
-{
-	PyErr_SetString(PyExc_TypeError,
-			"Cannot use string as modifiable buffer");
-	return -1;
-}
-
-static Py_ssize_t
-string_buffer_getsegcount(PyStringObject *self, Py_ssize_t *lenp)
-{
-	if ( lenp )
-		*lenp = Py_SIZE(self);
-	return 1;
-}
-
-static Py_ssize_t
-string_buffer_getcharbuf(PyStringObject *self, Py_ssize_t index, const char **ptr)
-{
-	if ( index != 0 ) {
-		PyErr_SetString(PyExc_SystemError,
-				"accessing non-existent string segment");
-		return -1;
-	}
-	*ptr = self->ob_sval;
-	return Py_SIZE(self);
-}
-
-static int
-string_buffer_getbuffer(PyStringObject *self, Py_buffer *view, int flags)
-{
-	return PyBuffer_FillInfo(view, (void *)self->ob_sval, Py_SIZE(self),
-				 0, flags);
-}
-
-static PySequenceMethods string_as_sequence = {
-	(lenfunc)string_length, /*sq_length*/
-	(binaryfunc)string_concat, /*sq_concat*/
-	(ssizeargfunc)string_repeat, /*sq_repeat*/
-	(ssizeargfunc)string_item, /*sq_item*/
-	(ssizessizeargfunc)string_slice, /*sq_slice*/
-	0,		/*sq_ass_item*/
-	0,		/*sq_ass_slice*/
-	(objobjproc)string_contains /*sq_contains*/
-};
-
-static PyMappingMethods string_as_mapping = {
-	(lenfunc)string_length,
-	(binaryfunc)string_subscript,
-	0,
-};
-
-static PyBufferProcs string_as_buffer = {
-	(readbufferproc)string_buffer_getreadbuf,
-	(writebufferproc)string_buffer_getwritebuf,
-	(segcountproc)string_buffer_getsegcount,
-	(charbufferproc)string_buffer_getcharbuf,
-	(getbufferproc)string_buffer_getbuffer,
-	0, /* XXX */
-};
-
-
-
-#define LEFTSTRIP 0
-#define RIGHTSTRIP 1
-#define BOTHSTRIP 2
-
-/* Arrays indexed by above */
-static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
-
-#define STRIPNAME(i) (stripformat[i]+3)
-
-
-/* Don't call if length < 2 */
-#define Py_STRING_MATCH(target, offset, pattern, length)	\
-  (target[offset] == pattern[0] &&				\
-   target[offset+length-1] == pattern[length-1] &&		\
-   !memcmp(target+offset+1, pattern+1, length-2) )
-
-
-/* Overallocate the initial list to reduce the number of reallocs for small
-   split sizes.  Eg, "A A A A A A A A A A".split() (10 elements) has three
-   resizes, to sizes 4, 8, then 16.  Most observed string splits are for human
-   text (roughly 11 words per line) and field delimited data (usually 1-10
-   fields).  For large strings the split algorithms are bandwidth limited
-   so increasing the preallocation likely will not improve things.*/
-
-#define MAX_PREALLOC 12
-
-/* 5 splits gives 6 elements */
-#define PREALLOC_SIZE(maxsplit) \
-	(maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
-
-#define SPLIT_APPEND(data, left, right)				\
-	str = PyString_FromStringAndSize((data) + (left),	\
-					 (right) - (left));	\
-	if (str == NULL)					\
-		goto onError;					\
-	if (PyList_Append(list, str)) {				\
-		Py_DECREF(str);					\
-		goto onError;					\
-	}							\
-	else							\
-		Py_DECREF(str);
-
-#define SPLIT_ADD(data, left, right) {				\
-	str = PyString_FromStringAndSize((data) + (left),	\
-					 (right) - (left));	\
-	if (str == NULL)					\
-		goto onError;					\
-	if (count < MAX_PREALLOC) {				\
-		PyList_SET_ITEM(list, count, str);		\
-	} else {						\
-		if (PyList_Append(list, str)) {			\
-			Py_DECREF(str);				\
-			goto onError;				\
-		}						\
-		else						\
-			Py_DECREF(str);				\
-	}							\
-	count++; }
-
-/* Always force the list to the expected size. */
-#define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
-
-#define SKIP_SPACE(s, i, len)    { while (i<len &&  isspace(Py_CHARMASK(s[i]))) i++; }
-#define SKIP_NONSPACE(s, i, len) { while (i<len && !isspace(Py_CHARMASK(s[i]))) i++; }
-#define RSKIP_SPACE(s, i)        { while (i>=0  &&  isspace(Py_CHARMASK(s[i]))) i--; }
-#define RSKIP_NONSPACE(s, i)     { while (i>=0  && !isspace(Py_CHARMASK(s[i]))) i--; }
-
-Py_LOCAL_INLINE(PyObject *)
-split_whitespace(PyStringObject *self, Py_ssize_t len, Py_ssize_t maxsplit)
-{
-	const char *s = PyString_AS_STRING(self);
-	Py_ssize_t i, j, count=0;
-	PyObject *str;
-	PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit));
-
-	if (list == NULL)
-		return NULL;
-
-	i = j = 0;
-
-	while (maxsplit-- > 0) {
-		SKIP_SPACE(s, i, len);
-		if (i==len) break;
-		j = i; i++;
-		SKIP_NONSPACE(s, i, len);
-		if (j == 0 && i == len && PyString_CheckExact(self)) {
-			/* No whitespace in self, so just use it as list[0] */
-			Py_INCREF(self);
-			PyList_SET_ITEM(list, 0, (PyObject *)self);
-			count++;
-			break;
-		}
-		SPLIT_ADD(s, j, i);
-	}
-
-	if (i < len) {
-		/* Only occurs when maxsplit was reached */
-		/* Skip any remaining whitespace and copy to end of string */
-		SKIP_SPACE(s, i, len);
-		if (i != len)
-			SPLIT_ADD(s, i, len);
-	}
-	FIX_PREALLOC_SIZE(list);
-	return list;
-  onError:
-	Py_DECREF(list);
-	return NULL;
-}
-
-Py_LOCAL_INLINE(PyObject *)
-split_char(PyStringObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount)
-{
-	const char *s = PyString_AS_STRING(self);
-	register Py_ssize_t i, j, count=0;
-	PyObject *str;
-	PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
-
-	if (list == NULL)
-		return NULL;
-
-	i = j = 0;
-	while ((j < len) && (maxcount-- > 0)) {
-		for(; j<len; j++) {
-			/* I found that using memchr makes no difference */
-			if (s[j] == ch) {
-				SPLIT_ADD(s, i, j);
-				i = j = j + 1;
-				break;
-			}
-		}
-	}
-	if (i == 0 && count == 0 && PyString_CheckExact(self)) {
-		/* ch not in self, so just use self as list[0] */
-		Py_INCREF(self);
-		PyList_SET_ITEM(list, 0, (PyObject *)self);
-		count++;
-	}
-	else if (i <= len) {
-		SPLIT_ADD(s, i, len);
-	}
-	FIX_PREALLOC_SIZE(list);
-	return list;
-
-  onError:
-	Py_DECREF(list);
-	return NULL;
-}
-
-PyDoc_STRVAR(split__doc__,
-"S.split([sep [,maxsplit]]) -> list of strings\n\
-\n\
-Return a list of the words in the string S, using sep as the\n\
-delimiter string.  If maxsplit is given, at most maxsplit\n\
-splits are done. If sep is not specified or is None, any\n\
-whitespace string is a separator and empty strings are removed\n\
-from the result.");
-
-static PyObject *
-string_split(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
-	Py_ssize_t maxsplit = -1, count=0;
-	const char *s = PyString_AS_STRING(self), *sub;
-	PyObject *list, *str, *subobj = Py_None;
-#ifdef USE_FAST
-	Py_ssize_t pos;
-#endif
-
-	if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
-		return NULL;
-	if (maxsplit < 0)
-		maxsplit = PY_SSIZE_T_MAX;
-	if (subobj == Py_None)
-		return split_whitespace(self, len, maxsplit);
-	if (PyString_Check(subobj)) {
-		sub = PyString_AS_STRING(subobj);
-		n = PyString_GET_SIZE(subobj);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(subobj))
-		return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
-#endif
-	else if (PyObject_AsCharBuffer(subobj, &sub, &n))
-		return NULL;
-
-	if (n == 0) {
-		PyErr_SetString(PyExc_ValueError, "empty separator");
-		return NULL;
-	}
-	else if (n == 1)
-		return split_char(self, len, sub[0], maxsplit);
-
-	list = PyList_New(PREALLOC_SIZE(maxsplit));
-	if (list == NULL)
-		return NULL;
-
-#ifdef USE_FAST
-	i = j = 0;
-	while (maxsplit-- > 0) {
-		pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
-		if (pos < 0)
-			break;
-		j = i+pos;
-		SPLIT_ADD(s, i, j);
-		i = j + n;
-	}
-#else
-	i = j = 0;
-	while ((j+n <= len) && (maxsplit-- > 0)) {
-		for (; j+n <= len; j++) {
-			if (Py_STRING_MATCH(s, j, sub, n)) {
-				SPLIT_ADD(s, i, j);
-				i = j = j + n;
-				break;
-			}
-		}
-	}
-#endif
-	SPLIT_ADD(s, i, len);
-	FIX_PREALLOC_SIZE(list);
-	return list;
-
- onError:
-	Py_DECREF(list);
-	return NULL;
-}
-
-PyDoc_STRVAR(partition__doc__,
-"S.partition(sep) -> (head, sep, tail)\n\
-\n\
-Searches for the separator sep in S, and returns the part before it,\n\
-the separator itself, and the part after it.  If the separator is not\n\
-found, returns S and two empty strings.");
-
-static PyObject *
-string_partition(PyStringObject *self, PyObject *sep_obj)
-{
-	const char *sep;
-	Py_ssize_t sep_len;
-
-	if (PyString_Check(sep_obj)) {
-		sep = PyString_AS_STRING(sep_obj);
-		sep_len = PyString_GET_SIZE(sep_obj);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(sep_obj))
-		return PyUnicode_Partition((PyObject *) self, sep_obj);
-#endif
-	else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
-		return NULL;
-
-	return stringlib_partition(
-		(PyObject*) self,
-		PyString_AS_STRING(self), PyString_GET_SIZE(self),
-		sep_obj, sep, sep_len
-		);
-}
-
-PyDoc_STRVAR(rpartition__doc__,
-"S.rpartition(sep) -> (tail, sep, head)\n\
-\n\
-Searches for the separator sep in S, starting at the end of S, and returns\n\
-the part before it, the separator itself, and the part after it.  If the\n\
-separator is not found, returns two empty strings and S.");
-
-static PyObject *
-string_rpartition(PyStringObject *self, PyObject *sep_obj)
-{
-	const char *sep;
-	Py_ssize_t sep_len;
-
-	if (PyString_Check(sep_obj)) {
-		sep = PyString_AS_STRING(sep_obj);
-		sep_len = PyString_GET_SIZE(sep_obj);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(sep_obj))
-		return PyUnicode_Partition((PyObject *) self, sep_obj);
-#endif
-	else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
-		return NULL;
-
-	return stringlib_rpartition(
-		(PyObject*) self,
-		PyString_AS_STRING(self), PyString_GET_SIZE(self),
-		sep_obj, sep, sep_len
-		);
-}
-
-Py_LOCAL_INLINE(PyObject *)
-rsplit_whitespace(PyStringObject *self, Py_ssize_t len, Py_ssize_t maxsplit)
-{
-	const char *s = PyString_AS_STRING(self);
-	Py_ssize_t i, j, count=0;
-	PyObject *str;
-	PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit));
-
-	if (list == NULL)
-		return NULL;
-
-	i = j = len-1;
-
-	while (maxsplit-- > 0) {
-		RSKIP_SPACE(s, i);
-		if (i<0) break;
-		j = i; i--;
-		RSKIP_NONSPACE(s, i);
-		if (j == len-1 && i < 0 && PyString_CheckExact(self)) {
-			/* No whitespace in self, so just use it as list[0] */
-			Py_INCREF(self);
-			PyList_SET_ITEM(list, 0, (PyObject *)self);
-			count++;
-			break;
-		}
-		SPLIT_ADD(s, i + 1, j + 1);
-	}
-	if (i >= 0) {
-		/* Only occurs when maxsplit was reached */
-		/* Skip any remaining whitespace and copy to beginning of string */
-		RSKIP_SPACE(s, i);
-		if (i >= 0)
-			SPLIT_ADD(s, 0, i + 1);
-
-	}
-	FIX_PREALLOC_SIZE(list);
-	if (PyList_Reverse(list) < 0)
-		goto onError;
-	return list;
-  onError:
-	Py_DECREF(list);
-	return NULL;
-}
-
-Py_LOCAL_INLINE(PyObject *)
-rsplit_char(PyStringObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount)
-{
-	const char *s = PyString_AS_STRING(self);
-	register Py_ssize_t i, j, count=0;
-	PyObject *str;
-	PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
-
-	if (list == NULL)
-		return NULL;
-
-	i = j = len - 1;
-	while ((i >= 0) && (maxcount-- > 0)) {
-		for (; i >= 0; i--) {
-			if (s[i] == ch) {
-				SPLIT_ADD(s, i + 1, j + 1);
-				j = i = i - 1;
-				break;
-			}
-		}
-	}
-	if (i < 0 && count == 0 && PyString_CheckExact(self)) {
-		/* ch not in self, so just use self as list[0] */
-		Py_INCREF(self);
-		PyList_SET_ITEM(list, 0, (PyObject *)self);
-		count++;
-	}
-	else if (j >= -1) {
-		SPLIT_ADD(s, 0, j + 1);
-	}
-	FIX_PREALLOC_SIZE(list);
-	if (PyList_Reverse(list) < 0)
-		goto onError;
-	return list;
-
- onError:
-	Py_DECREF(list);
-	return NULL;
-}
-
-PyDoc_STRVAR(rsplit__doc__,
-"S.rsplit([sep [,maxsplit]]) -> list of strings\n\
-\n\
-Return a list of the words in the string S, using sep as the\n\
-delimiter string, starting at the end of the string and working\n\
-to the front.  If maxsplit is given, at most maxsplit splits are\n\
-done. If sep is not specified or is None, any whitespace string\n\
-is a separator.");
-
-static PyObject *
-string_rsplit(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
-	Py_ssize_t maxsplit = -1, count=0;
-	const char *s, *sub;
-	PyObject *list, *str, *subobj = Py_None;
-
-	if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
-		return NULL;
-	if (maxsplit < 0)
-		maxsplit = PY_SSIZE_T_MAX;
-	if (subobj == Py_None)
-		return rsplit_whitespace(self, len, maxsplit);
-	if (PyString_Check(subobj)) {
-		sub = PyString_AS_STRING(subobj);
-		n = PyString_GET_SIZE(subobj);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(subobj))
-		return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
-#endif
-	else if (PyObject_AsCharBuffer(subobj, &sub, &n))
-		return NULL;
-
-	if (n == 0) {
-		PyErr_SetString(PyExc_ValueError, "empty separator");
-		return NULL;
-	}
-	else if (n == 1)
-		return rsplit_char(self, len, sub[0], maxsplit);
-
-	list = PyList_New(PREALLOC_SIZE(maxsplit));
-	if (list == NULL)
-		return NULL;
-
-	j = len;
-	i = j - n;
-
-	s = PyString_AS_STRING(self);
-	while ( (i >= 0) && (maxsplit-- > 0) ) {
-		for (; i>=0; i--) {
-			if (Py_STRING_MATCH(s, i, sub, n)) {
-				SPLIT_ADD(s, i + n, j);
-				j = i;
-				i -= n;
-				break;
-			}
-		}
-	}
-	SPLIT_ADD(s, 0, j);
-	FIX_PREALLOC_SIZE(list);
-	if (PyList_Reverse(list) < 0)
-		goto onError;
-	return list;
-
-onError:
-	Py_DECREF(list);
-	return NULL;
-}
-
-
-PyDoc_STRVAR(join__doc__,
-"S.join(sequence) -> string\n\
-\n\
-Return a string which is the concatenation of the strings in the\n\
-sequence.  The separator between elements is S.");
-
-static PyObject *
-string_join(PyStringObject *self, PyObject *orig)
-{
-	char *sep = PyString_AS_STRING(self);
-	const Py_ssize_t seplen = PyString_GET_SIZE(self);
-	PyObject *res = NULL;
-	char *p;
-	Py_ssize_t seqlen = 0;
-	size_t sz = 0;
-	Py_ssize_t i;
-	PyObject *seq, *item;
-
-	seq = PySequence_Fast(orig, "");
-	if (seq == NULL) {
-		return NULL;
-	}
-
-	seqlen = PySequence_Size(seq);
-	if (seqlen == 0) {
-		Py_DECREF(seq);
-		return PyString_FromString("");
-	}
-	if (seqlen == 1) {
-		item = PySequence_Fast_GET_ITEM(seq, 0);
-		if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
-			Py_INCREF(item);
-			Py_DECREF(seq);
-			return item;
-		}
-	}
-
-	/* There are at least two things to join, or else we have a subclass
-	 * of the builtin types in the sequence.
-	 * Do a pre-pass to figure out the total amount of space we'll
-	 * need (sz), see whether any argument is absurd, and defer to
-	 * the Unicode join if appropriate.
-	 */
-	for (i = 0; i < seqlen; i++) {
-		const size_t old_sz = sz;
-		item = PySequence_Fast_GET_ITEM(seq, i);
-		if (!PyString_Check(item)){
-#ifdef Py_USING_UNICODE
-			if (PyUnicode_Check(item)) {
-				/* Defer to Unicode join.
-				 * CAUTION:  There's no gurantee that the
-				 * original sequence can be iterated over
-				 * again, so we must pass seq here.
-				 */
-				PyObject *result;
-				result = PyUnicode_Join((PyObject *)self, seq);
-				Py_DECREF(seq);
-				return result;
-			}
-#endif
-			PyErr_Format(PyExc_TypeError,
-				     "sequence item %zd: expected string,"
-				     " %.80s found",
-				     i, Py_TYPE(item)->tp_name);
-			Py_DECREF(seq);
-			return NULL;
-		}
-		sz += PyString_GET_SIZE(item);
-		if (i != 0)
-			sz += seplen;
-		if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
-			PyErr_SetString(PyExc_OverflowError,
-				"join() result is too long for a Python string");
-			Py_DECREF(seq);
-			return NULL;
-		}
-	}
-
-	/* Allocate result space. */
-	res = PyString_FromStringAndSize((char*)NULL, sz);
-	if (res == NULL) {
-		Py_DECREF(seq);
-		return NULL;
-	}
-
-	/* Catenate everything. */
-	p = PyString_AS_STRING(res);
-	for (i = 0; i < seqlen; ++i) {
-		size_t n;
-		item = PySequence_Fast_GET_ITEM(seq, i);
-		n = PyString_GET_SIZE(item);
-		Py_MEMCPY(p, PyString_AS_STRING(item), n);
-		p += n;
-		if (i < seqlen - 1) {
-			Py_MEMCPY(p, sep, seplen);
-			p += seplen;
-		}
-	}
-
-	Py_DECREF(seq);
-	return res;
-}
-
-PyObject *
-_PyString_Join(PyObject *sep, PyObject *x)
-{
-	assert(sep != NULL && PyString_Check(sep));
-	assert(x != NULL);
-	return string_join((PyStringObject *)sep, x);
-}
-
-Py_LOCAL_INLINE(void)
-string_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
-{
-	if (*end > len)
-		*end = len;
-	else if (*end < 0)
-		*end += len;
-	if (*end < 0)
-		*end = 0;
-	if (*start < 0)
-		*start += len;
-	if (*start < 0)
-		*start = 0;
-}
-
-Py_LOCAL_INLINE(Py_ssize_t)
-string_find_internal(PyStringObject *self, PyObject *args, int dir)
-{
-	PyObject *subobj;
-	const char *sub;
-	Py_ssize_t sub_len;
-	Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
-	PyObject *obj_start=Py_None, *obj_end=Py_None;
-
-	if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj,
-		&obj_start, &obj_end))
-		return -2;
-	/* To support None in "start" and "end" arguments, meaning
-	   the same as if they were not passed.
-	*/
-	if (obj_start != Py_None)
-		if (!_PyEval_SliceIndex(obj_start, &start))
-	        return -2;
-	if (obj_end != Py_None)
-		if (!_PyEval_SliceIndex(obj_end, &end))
-	        return -2;
-
-	if (PyString_Check(subobj)) {
-		sub = PyString_AS_STRING(subobj);
-		sub_len = PyString_GET_SIZE(subobj);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(subobj))
-		return PyUnicode_Find(
-			(PyObject *)self, subobj, start, end, dir);
-#endif
-	else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
-		/* XXX - the "expected a character buffer object" is pretty
-		   confusing for a non-expert.  remap to something else ? */
-		return -2;
-
-	if (dir > 0)
-		return stringlib_find_slice(
-			PyString_AS_STRING(self), PyString_GET_SIZE(self),
-			sub, sub_len, start, end);
-	else
-		return stringlib_rfind_slice(
-			PyString_AS_STRING(self), PyString_GET_SIZE(self),
-			sub, sub_len, start, end);
-}
-
-
-PyDoc_STRVAR(find__doc__,
-"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\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-string_find(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t result = string_find_internal(self, args, +1);
-	if (result == -2)
-		return NULL;
-	return PyInt_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(index__doc__,
-"S.index(sub [,start [,end]]) -> int\n\
-\n\
-Like S.find() but raise ValueError when the substring is not found.");
-
-static PyObject *
-string_index(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t result = string_find_internal(self, args, +1);
-	if (result == -2)
-		return NULL;
-	if (result == -1) {
-		PyErr_SetString(PyExc_ValueError,
-				"substring not found");
-		return NULL;
-	}
-	return PyInt_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(rfind__doc__,
-"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\
-arguments start and end are interpreted as in slice notation.\n\
-\n\
-Return -1 on failure.");
-
-static PyObject *
-string_rfind(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t result = string_find_internal(self, args, -1);
-	if (result == -2)
-		return NULL;
-	return PyInt_FromSsize_t(result);
-}
-
-
-PyDoc_STRVAR(rindex__doc__,
-"S.rindex(sub [,start [,end]]) -> int\n\
-\n\
-Like S.rfind() but raise ValueError when the substring is not found.");
-
-static PyObject *
-string_rindex(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t result = string_find_internal(self, args, -1);
-	if (result == -2)
-		return NULL;
-	if (result == -1) {
-		PyErr_SetString(PyExc_ValueError,
-				"substring not found");
-		return NULL;
-	}
-	return PyInt_FromSsize_t(result);
-}
-
-
-Py_LOCAL_INLINE(PyObject *)
-do_xstrip(PyStringObject *self, int striptype, PyObject *sepobj)
-{
-	char *s = PyString_AS_STRING(self);
-	Py_ssize_t len = PyString_GET_SIZE(self);
-	char *sep = PyString_AS_STRING(sepobj);
-	Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
-	Py_ssize_t i, j;
-
-	i = 0;
-	if (striptype != RIGHTSTRIP) {
-		while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
-			i++;
-		}
-	}
-
-	j = len;
-	if (striptype != LEFTSTRIP) {
-		do {
-			j--;
-		} while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
-		j++;
-	}
-
-	if (i == 0 && j == len && PyString_CheckExact(self)) {
-		Py_INCREF(self);
-		return (PyObject*)self;
-	}
-	else
-		return PyString_FromStringAndSize(s+i, j-i);
-}
-
-
-Py_LOCAL_INLINE(PyObject *)
-do_strip(PyStringObject *self, int striptype)
-{
-	char *s = PyString_AS_STRING(self);
-	Py_ssize_t len = PyString_GET_SIZE(self), i, j;
-
-	i = 0;
-	if (striptype != RIGHTSTRIP) {
-		while (i < len && isspace(Py_CHARMASK(s[i]))) {
-			i++;
-		}
-	}
-
-	j = len;
-	if (striptype != LEFTSTRIP) {
-		do {
-			j--;
-		} while (j >= i && isspace(Py_CHARMASK(s[j])));
-		j++;
-	}
-
-	if (i == 0 && j == len && PyString_CheckExact(self)) {
-		Py_INCREF(self);
-		return (PyObject*)self;
-	}
-	else
-		return PyString_FromStringAndSize(s+i, j-i);
-}
-
-
-Py_LOCAL_INLINE(PyObject *)
-do_argstrip(PyStringObject *self, int striptype, PyObject *args)
-{
-	PyObject *sep = NULL;
-
-	if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
-		return NULL;
-
-	if (sep != NULL && sep != Py_None) {
-		if (PyString_Check(sep))
-			return do_xstrip(self, striptype, sep);
-#ifdef Py_USING_UNICODE
-		else if (PyUnicode_Check(sep)) {
-			PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
-			PyObject *res;
-			if (uniself==NULL)
-				return NULL;
-			res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
-				striptype, sep);
-			Py_DECREF(uniself);
-			return res;
-		}
-#endif
-		PyErr_Format(PyExc_TypeError,
-#ifdef Py_USING_UNICODE
-			     "%s arg must be None, str or unicode",
-#else
-			     "%s arg must be None or str",
-#endif
-			     STRIPNAME(striptype));
-		return NULL;
-	}
-
-	return do_strip(self, striptype);
-}
-
-
-PyDoc_STRVAR(strip__doc__,
-"S.strip([chars]) -> string or unicode\n\
-\n\
-Return a copy of the string S with leading and trailing\n\
-whitespace removed.\n\
-If chars is given and not None, remove characters in chars instead.\n\
-If chars is unicode, S will be converted to unicode before stripping");
-
-static PyObject *
-string_strip(PyStringObject *self, PyObject *args)
-{
-	if (PyTuple_GET_SIZE(args) == 0)
-		return do_strip(self, BOTHSTRIP); /* Common case */
-	else
-		return do_argstrip(self, BOTHSTRIP, args);
-}
-
-
-PyDoc_STRVAR(lstrip__doc__,
-"S.lstrip([chars]) -> string or unicode\n\
-\n\
-Return a copy of the string S with leading whitespace removed.\n\
-If chars is given and not None, remove characters in chars instead.\n\
-If chars is unicode, S will be converted to unicode before stripping");
-
-static PyObject *
-string_lstrip(PyStringObject *self, PyObject *args)
-{
-	if (PyTuple_GET_SIZE(args) == 0)
-		return do_strip(self, LEFTSTRIP); /* Common case */
-	else
-		return do_argstrip(self, LEFTSTRIP, args);
-}
-
-
-PyDoc_STRVAR(rstrip__doc__,
-"S.rstrip([chars]) -> string or unicode\n\
-\n\
-Return a copy of the string S with trailing whitespace removed.\n\
-If chars is given and not None, remove characters in chars instead.\n\
-If chars is unicode, S will be converted to unicode before stripping");
-
-static PyObject *
-string_rstrip(PyStringObject *self, PyObject *args)
-{
-	if (PyTuple_GET_SIZE(args) == 0)
-		return do_strip(self, RIGHTSTRIP); /* Common case */
-	else
-		return do_argstrip(self, RIGHTSTRIP, args);
-}
-
-
-PyDoc_STRVAR(lower__doc__,
-"S.lower() -> string\n\
-\n\
-Return a copy of the string S converted to lowercase.");
-
-/* _tolower and _toupper are defined by SUSv2, but they're not ISO C */
-#ifndef _tolower
-#define _tolower tolower
-#endif
-
-static PyObject *
-string_lower(PyStringObject *self)
-{
-	char *s;
-	Py_ssize_t i, n = PyString_GET_SIZE(self);
-	PyObject *newobj;
-
-	newobj = PyString_FromStringAndSize(NULL, n);
-	if (!newobj)
-		return NULL;
-
-	s = PyString_AS_STRING(newobj);
-
-	Py_MEMCPY(s, PyString_AS_STRING(self), n);
-
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(s[i]);
-		if (isupper(c))
-			s[i] = _tolower(c);
-	}
-
-	return newobj;
-}
-
-PyDoc_STRVAR(upper__doc__,
-"S.upper() -> string\n\
-\n\
-Return a copy of the string S converted to uppercase.");
-
-#ifndef _toupper
-#define _toupper toupper
-#endif
-
-static PyObject *
-string_upper(PyStringObject *self)
-{
-	char *s;
-	Py_ssize_t i, n = PyString_GET_SIZE(self);
-	PyObject *newobj;
-
-	newobj = PyString_FromStringAndSize(NULL, n);
-	if (!newobj)
-		return NULL;
-
-	s = PyString_AS_STRING(newobj);
-
-	Py_MEMCPY(s, PyString_AS_STRING(self), n);
-
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(s[i]);
-		if (islower(c))
-			s[i] = _toupper(c);
-	}
-
-	return newobj;
-}
-
-PyDoc_STRVAR(title__doc__,
-"S.title() -> string\n\
-\n\
-Return a titlecased version of S, i.e. words start with uppercase\n\
-characters, all remaining cased characters have lowercase.");
-
-static PyObject*
-string_title(PyStringObject *self)
-{
-	char *s = PyString_AS_STRING(self), *s_new;
-	Py_ssize_t i, n = PyString_GET_SIZE(self);
-	int previous_is_cased = 0;
-	PyObject *newobj;
-
-	newobj = PyString_FromStringAndSize(NULL, n);
-	if (newobj == NULL)
-		return NULL;
-	s_new = PyString_AsString(newobj);
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (islower(c)) {
-			if (!previous_is_cased)
-			    c = toupper(c);
-			previous_is_cased = 1;
-		} else if (isupper(c)) {
-			if (previous_is_cased)
-			    c = tolower(c);
-			previous_is_cased = 1;
-		} else
-			previous_is_cased = 0;
-		*s_new++ = c;
-	}
-	return newobj;
-}
-
-PyDoc_STRVAR(capitalize__doc__,
-"S.capitalize() -> string\n\
-\n\
-Return a copy of the string S with only its first character\n\
-capitalized.");
-
-static PyObject *
-string_capitalize(PyStringObject *self)
-{
-	char *s = PyString_AS_STRING(self), *s_new;
-	Py_ssize_t i, n = PyString_GET_SIZE(self);
-	PyObject *newobj;
-
-	newobj = PyString_FromStringAndSize(NULL, n);
-	if (newobj == NULL)
-		return NULL;
-	s_new = PyString_AsString(newobj);
-	if (0 < n) {
-		int c = Py_CHARMASK(*s++);
-		if (islower(c))
-			*s_new = toupper(c);
-		else
-			*s_new = c;
-		s_new++;
-	}
-	for (i = 1; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (isupper(c))
-			*s_new = tolower(c);
-		else
-			*s_new = c;
-		s_new++;
-	}
-	return newobj;
-}
-
-
-PyDoc_STRVAR(count__doc__,
-"S.count(sub[, start[, end]]) -> int\n\
-\n\
-Return the number of non-overlapping occurrences of substring sub in\n\
-string S[start:end].  Optional arguments start and end are interpreted\n\
-as in slice notation.");
-
-static PyObject *
-string_count(PyStringObject *self, PyObject *args)
-{
-	PyObject *sub_obj;
-	const char *str = PyString_AS_STRING(self), *sub;
-	Py_ssize_t sub_len;
-	Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
-
-	if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
-		_PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
-		return NULL;
-
-	if (PyString_Check(sub_obj)) {
-		sub = PyString_AS_STRING(sub_obj);
-		sub_len = PyString_GET_SIZE(sub_obj);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(sub_obj)) {
-		Py_ssize_t count;
-		count = PyUnicode_Count((PyObject *)self, sub_obj, start, end);
-		if (count == -1)
-			return NULL;
-		else
-		    	return PyInt_FromSsize_t(count);
-	}
-#endif
-	else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
-		return NULL;
-
-	string_adjust_indices(&start, &end, PyString_GET_SIZE(self));
-
-	return PyInt_FromSsize_t(
-		stringlib_count(str + start, end - start, sub, sub_len)
-		);
-}
-
-PyDoc_STRVAR(swapcase__doc__,
-"S.swapcase() -> string\n\
-\n\
-Return a copy of the string S with uppercase characters\n\
-converted to lowercase and vice versa.");
-
-static PyObject *
-string_swapcase(PyStringObject *self)
-{
-	char *s = PyString_AS_STRING(self), *s_new;
-	Py_ssize_t i, n = PyString_GET_SIZE(self);
-	PyObject *newobj;
-
-	newobj = PyString_FromStringAndSize(NULL, n);
-	if (newobj == NULL)
-		return NULL;
-	s_new = PyString_AsString(newobj);
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (islower(c)) {
-			*s_new = toupper(c);
-		}
-		else if (isupper(c)) {
-			*s_new = tolower(c);
-		}
-		else
-			*s_new = c;
-		s_new++;
-	}
-	return newobj;
-}
-
-
-PyDoc_STRVAR(translate__doc__,
-"S.translate(table [,deletechars]) -> string\n\
-\n\
-Return a copy of the string S, where all characters occurring\n\
-in the optional argument deletechars are removed, and the\n\
-remaining characters have been mapped through the given\n\
-translation table, which must be a string of length 256.");
-
-static PyObject *
-string_translate(PyStringObject *self, PyObject *args)
-{
-	register char *input, *output;
-	const char *table;
-	register Py_ssize_t i, c, changed = 0;
-	PyObject *input_obj = (PyObject*)self;
-	const char *output_start, *del_table=NULL;
-	Py_ssize_t inlen, tablen, dellen = 0;
-	PyObject *result;
-	int trans_table[256];
-	PyObject *tableobj, *delobj = NULL;
-
-	if (!PyArg_UnpackTuple(args, "translate", 1, 2,
-			      &tableobj, &delobj))
-		return NULL;
-
-	if (PyString_Check(tableobj)) {
-		table = PyString_AS_STRING(tableobj);
-		tablen = PyString_GET_SIZE(tableobj);
-	}
-	else if (tableobj == Py_None) {
-		table = NULL;
-		tablen = 256;
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(tableobj)) {
-		/* Unicode .translate() does not support the deletechars
-		   parameter; instead a mapping to None will cause characters
-		   to be deleted. */
-		if (delobj != NULL) {
-			PyErr_SetString(PyExc_TypeError,
-			"deletions are implemented differently for unicode");
-			return NULL;
-		}
-		return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
-	}
-#endif
-	else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
-		return NULL;
-
-	if (tablen != 256) {
-		PyErr_SetString(PyExc_ValueError,
-		  "translation table must be 256 characters long");
-		return NULL;
-	}
-
-	if (delobj != NULL) {
-		if (PyString_Check(delobj)) {
-			del_table = PyString_AS_STRING(delobj);
-			dellen = PyString_GET_SIZE(delobj);
-		}
-#ifdef Py_USING_UNICODE
-		else if (PyUnicode_Check(delobj)) {
-			PyErr_SetString(PyExc_TypeError,
-			"deletions are implemented differently for unicode");
-			return NULL;
-		}
-#endif
-		else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
-			return NULL;
-	}
-	else {
-		del_table = NULL;
-		dellen = 0;
-	}
-
-	inlen = PyString_GET_SIZE(input_obj);
-	result = PyString_FromStringAndSize((char *)NULL, inlen);
-	if (result == NULL)
-		return NULL;
-	output_start = output = PyString_AsString(result);
-	input = PyString_AS_STRING(input_obj);
-
-	if (dellen == 0 && table != NULL) {
-		/* If no deletions are required, use faster code */
-		for (i = inlen; --i >= 0; ) {
-			c = Py_CHARMASK(*input++);
-			if (Py_CHARMASK((*output++ = table[c])) != c)
-				changed = 1;
-		}
-		if (changed || !PyString_CheckExact(input_obj))
-			return result;
-		Py_DECREF(result);
-		Py_INCREF(input_obj);
-		return input_obj;
-	}
-
-	if (table == NULL) {
-		for (i = 0; i < 256; i++)
-			trans_table[i] = Py_CHARMASK(i);
-	} else {
-		for (i = 0; i < 256; i++)
-			trans_table[i] = Py_CHARMASK(table[i]);
-	}
-
-	for (i = 0; i < dellen; i++)
-		trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
-
-	for (i = inlen; --i >= 0; ) {
-		c = Py_CHARMASK(*input++);
-		if (trans_table[c] != -1)
-			if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
-				continue;
-		changed = 1;
-	}
-	if (!changed && PyString_CheckExact(input_obj)) {
-		Py_DECREF(result);
-		Py_INCREF(input_obj);
-		return input_obj;
-	}
-	/* Fix the size of the resulting string */
-	if (inlen > 0)
-		_PyString_Resize(&result, output - output_start);
-	return result;
-}
-
-
-#define FORWARD 1
-#define REVERSE -1
-
-/* find and count characters and substrings */
-
-#define findchar(target, target_len, c)				\
-  ((char *)memchr((const void *)(target), c, target_len))
-
-/* String ops must return a string.  */
-/* If the object is subclass of string, create a copy */
-Py_LOCAL(PyStringObject *)
-return_self(PyStringObject *self)
-{
-	if (PyString_CheckExact(self)) {
-		Py_INCREF(self);
-		return self;
-	}
-	return (PyStringObject *)PyString_FromStringAndSize(
-		PyString_AS_STRING(self),
-		PyString_GET_SIZE(self));
-}
-
-Py_LOCAL_INLINE(Py_ssize_t)
-countchar(const char *target, int target_len, char c, Py_ssize_t maxcount)
-{
-	Py_ssize_t count=0;
-	const char *start=target;
-	const char *end=target+target_len;
-
-	while ( (start=findchar(start, end-start, c)) != NULL ) {
-		count++;
-		if (count >= maxcount)
-			break;
-		start += 1;
-	}
-	return count;
-}
-
-Py_LOCAL(Py_ssize_t)
-findstring(const char *target, Py_ssize_t target_len,
-	   const char *pattern, Py_ssize_t pattern_len,
-	   Py_ssize_t start,
-	   Py_ssize_t end,
-	   int direction)
-{
-	if (start < 0) {
-		start += target_len;
-		if (start < 0)
-			start = 0;
-	}
-	if (end > target_len) {
-		end = target_len;
-	} else if (end < 0) {
-		end += target_len;
-		if (end < 0)
-			end = 0;
-	}
-
-	/* zero-length substrings always match at the first attempt */
-	if (pattern_len == 0)
-		return (direction > 0) ? start : end;
-
-	end -= pattern_len;
-
-	if (direction < 0) {
-		for (; end >= start; end--)
-			if (Py_STRING_MATCH(target, end, pattern, pattern_len))
-				return end;
-	} else {
-		for (; start <= end; start++)
-			if (Py_STRING_MATCH(target, start, pattern, pattern_len))
-				return start;
-	}
-	return -1;
-}
-
-Py_LOCAL_INLINE(Py_ssize_t)
-countstring(const char *target, Py_ssize_t target_len,
-	    const char *pattern, Py_ssize_t pattern_len,
-	    Py_ssize_t start,
-	    Py_ssize_t end,
-	    int direction, Py_ssize_t maxcount)
-{
-	Py_ssize_t count=0;
-
-	if (start < 0) {
-		start += target_len;
-		if (start < 0)
-			start = 0;
-	}
-	if (end > target_len) {
-		end = target_len;
-	} else if (end < 0) {
-		end += target_len;
-		if (end < 0)
-			end = 0;
-	}
-
-	/* zero-length substrings match everywhere */
-	if (pattern_len == 0 || maxcount == 0) {
-		if (target_len+1 < maxcount)
-			return target_len+1;
-		return maxcount;
-	}
-
-	end -= pattern_len;
-	if (direction < 0) {
-		for (; (end >= start); end--)
-			if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
-				count++;
-				if (--maxcount <= 0) break;
-				end -= pattern_len-1;
-			}
-	} else {
-		for (; (start <= end); start++)
-			if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
-				count++;
-				if (--maxcount <= 0)
-					break;
-				start += pattern_len-1;
-			}
-	}
-	return count;
-}
-
-
-/* Algorithms for different cases of string replacement */
-
-/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
-Py_LOCAL(PyStringObject *)
-replace_interleave(PyStringObject *self,
-		   const char *to_s, Py_ssize_t to_len,
-		   Py_ssize_t maxcount)
-{
-	char *self_s, *result_s;
-	Py_ssize_t self_len, result_len;
-	Py_ssize_t count, i, product;
-	PyStringObject *result;
-
-	self_len = PyString_GET_SIZE(self);
-
-	/* 1 at the end plus 1 after every character */
-	count = self_len+1;
-	if (maxcount < count) 
-		count = maxcount;
-
-	/* Check for overflow */
-	/*   result_len = count * to_len + self_len; */
-	product = count * to_len;
-	if (product / to_len != count) {
-		PyErr_SetString(PyExc_OverflowError,
-				"replace string is too long");
-		return NULL;
-	}
-	result_len = product + self_len;
-	if (result_len < 0) {
-		PyErr_SetString(PyExc_OverflowError,
-				"replace string is too long");
-		return NULL;
-	}
-  
-	if (! (result = (PyStringObject *)
-	                 PyString_FromStringAndSize(NULL, result_len)) )
-		return NULL;
-
-	self_s = PyString_AS_STRING(self);
-	result_s = PyString_AS_STRING(result);
-
-	/* TODO: special case single character, which doesn't need memcpy */
-
-	/* Lay the first one down (guaranteed this will occur) */
-	Py_MEMCPY(result_s, to_s, to_len);
-	result_s += to_len;
-	count -= 1;
-  
-	for (i=0; i<count; i++) {
-		*result_s++ = *self_s++;
-		Py_MEMCPY(result_s, to_s, to_len);
-		result_s += to_len;
-	}
-
-	/* Copy the rest of the original string */
-	Py_MEMCPY(result_s, self_s, self_len-i);
-
-	return result;
-}
-
-/* Special case for deleting a single character */
-/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
-Py_LOCAL(PyStringObject *)
-replace_delete_single_character(PyStringObject *self,
-				char from_c, Py_ssize_t maxcount)
-{
-	char *self_s, *result_s;
-	char *start, *next, *end;
-	Py_ssize_t self_len, result_len;
-	Py_ssize_t count;
-	PyStringObject *result;
-
-	self_len = PyString_GET_SIZE(self);
-	self_s = PyString_AS_STRING(self);
-
-	count = countchar(self_s, self_len, from_c, maxcount);
-	if (count == 0) {
-		return return_self(self);
-	}
-  
-	result_len = self_len - count;  /* from_len == 1 */
-	assert(result_len>=0);
-
-	if ( (result = (PyStringObject *)
-	                PyString_FromStringAndSize(NULL, result_len)) == NULL)
-		return NULL;
-	result_s = PyString_AS_STRING(result);
-
-	start = self_s;
-	end = self_s + self_len;
-	while (count-- > 0) {
-		next = findchar(start, end-start, from_c);
-		if (next == NULL)
-			break;
-		Py_MEMCPY(result_s, start, next-start);
-		result_s += (next-start);
-		start = next+1;
-	}
-	Py_MEMCPY(result_s, start, end-start);
-
-	return result;
-}
-
-/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
-
-Py_LOCAL(PyStringObject *)
-replace_delete_substring(PyStringObject *self,
-			 const char *from_s, Py_ssize_t from_len,
-			 Py_ssize_t maxcount) {
-	char *self_s, *result_s;
-	char *start, *next, *end;
-	Py_ssize_t self_len, result_len;
-	Py_ssize_t count, offset;
-	PyStringObject *result;
-
-	self_len = PyString_GET_SIZE(self);
-	self_s = PyString_AS_STRING(self);
-
-	count = countstring(self_s, self_len,
-			    from_s, from_len,
-			    0, self_len, 1,
-			    maxcount);
-
-	if (count == 0) {
-		/* no matches */
-		return return_self(self);
-	}
-
-	result_len = self_len - (count * from_len);
-	assert (result_len>=0);
-
-	if ( (result = (PyStringObject *)
-	      PyString_FromStringAndSize(NULL, result_len)) == NULL )
-		return NULL;
-
-	result_s = PyString_AS_STRING(result);
-
-	start = self_s;
-	end = self_s + self_len;
-	while (count-- > 0) {
-		offset = findstring(start, end-start,
-				    from_s, from_len,
-				    0, end-start, FORWARD);
-		if (offset == -1)
-			break;
-		next = start + offset;
-
-		Py_MEMCPY(result_s, start, next-start);
-
-		result_s += (next-start);
-		start = next+from_len;
-	}
-	Py_MEMCPY(result_s, start, end-start);
-	return result;
-}
-
-/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
-Py_LOCAL(PyStringObject *)
-replace_single_character_in_place(PyStringObject *self,
-				  char from_c, char to_c,
-				  Py_ssize_t maxcount)
-{
-	char *self_s, *result_s, *start, *end, *next;
-	Py_ssize_t self_len;
-	PyStringObject *result;
-
-	/* The result string will be the same size */
-	self_s = PyString_AS_STRING(self);
-	self_len = PyString_GET_SIZE(self);
-
-	next = findchar(self_s, self_len, from_c);
-
-	if (next == NULL) {
-		/* No matches; return the original string */
-		return return_self(self);
-	}
-
-	/* Need to make a new string */
-	result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
-	if (result == NULL)
-		return NULL;
-	result_s = PyString_AS_STRING(result);
-	Py_MEMCPY(result_s, self_s, self_len);
-
-	/* change everything in-place, starting with this one */
-	start =  result_s + (next-self_s);
-	*start = to_c;
-	start++;
-	end = result_s + self_len;
-
-	while (--maxcount > 0) {
-		next = findchar(start, end-start, from_c);
-		if (next == NULL)
-			break;
-		*next = to_c;
-		start = next+1;
-	}
-
-	return result;
-}
-
-/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyStringObject *)
-replace_substring_in_place(PyStringObject *self,
-			   const char *from_s, Py_ssize_t from_len,
-			   const char *to_s, Py_ssize_t to_len,
-			   Py_ssize_t maxcount)
-{
-	char *result_s, *start, *end;
-	char *self_s;
-	Py_ssize_t self_len, offset;
-	PyStringObject *result;
-
-	/* The result string will be the same size */
-
-	self_s = PyString_AS_STRING(self);
-	self_len = PyString_GET_SIZE(self);
-
-	offset = findstring(self_s, self_len,
-			    from_s, from_len,
-			    0, self_len, FORWARD);
-	if (offset == -1) {
-		/* No matches; return the original string */
-		return return_self(self);
-	}
-
-	/* Need to make a new string */
-	result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
-	if (result == NULL)
-		return NULL;
-	result_s = PyString_AS_STRING(result);
-	Py_MEMCPY(result_s, self_s, self_len);
-
-	/* change everything in-place, starting with this one */
-	start =  result_s + offset;
-	Py_MEMCPY(start, to_s, from_len);
-	start += from_len;
-	end = result_s + self_len;
-
-	while ( --maxcount > 0) {
-		offset = findstring(start, end-start,
-				    from_s, from_len,
-				    0, end-start, FORWARD);
-		if (offset==-1)
-			break;
-		Py_MEMCPY(start+offset, to_s, from_len);
-		start += offset+from_len;
-	}
-
-	return result;
-}
-
-/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyStringObject *)
-replace_single_character(PyStringObject *self,
-			 char from_c,
-			 const char *to_s, Py_ssize_t to_len,
-			 Py_ssize_t maxcount)
-{
-	char *self_s, *result_s;
-	char *start, *next, *end;
-	Py_ssize_t self_len, result_len;
-	Py_ssize_t count, product;
-	PyStringObject *result;
-
-	self_s = PyString_AS_STRING(self);
-	self_len = PyString_GET_SIZE(self);
-
-	count = countchar(self_s, self_len, from_c, maxcount);
-	if (count == 0) {
-		/* no matches, return unchanged */
-		return return_self(self);
-	}
-
-	/* use the difference between current and new, hence the "-1" */
-	/*   result_len = self_len + count * (to_len-1)  */
-	product = count * (to_len-1);
-	if (product / (to_len-1) != count) {
-		PyErr_SetString(PyExc_OverflowError, "replace string is too long");
-		return NULL;
-	}
-	result_len = self_len + product;
-	if (result_len < 0) {
-		PyErr_SetString(PyExc_OverflowError, "replace string is too long");
-		return NULL;
-	}
-
-	if ( (result = (PyStringObject *)
-	      PyString_FromStringAndSize(NULL, result_len)) == NULL)
-		return NULL;
-	result_s = PyString_AS_STRING(result);
-
-	start = self_s;
-	end = self_s + self_len;
-	while (count-- > 0) {
-		next = findchar(start, end-start, from_c);
-		if (next == NULL) 
-			break;
-
-		if (next == start) {
-			/* replace with the 'to' */
-			Py_MEMCPY(result_s, to_s, to_len);
-			result_s += to_len;
-			start += 1;
-		} else {
-			/* copy the unchanged old then the 'to' */
-			Py_MEMCPY(result_s, start, next-start);
-			result_s += (next-start);
-			Py_MEMCPY(result_s, to_s, to_len);
-			result_s += to_len;
-			start = next+1;
-		}
-	}
-	/* Copy the remainder of the remaining string */
-	Py_MEMCPY(result_s, start, end-start);
-
-	return result;
-}
-
-/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
-Py_LOCAL(PyStringObject *)
-replace_substring(PyStringObject *self,
-		  const char *from_s, Py_ssize_t from_len,
-		  const char *to_s, Py_ssize_t to_len,
-		  Py_ssize_t maxcount) {
-	char *self_s, *result_s;
-	char *start, *next, *end;
-	Py_ssize_t self_len, result_len;
-	Py_ssize_t count, offset, product;
-	PyStringObject *result;
-
-	self_s = PyString_AS_STRING(self);
-	self_len = PyString_GET_SIZE(self);
-
-	count = countstring(self_s, self_len,
-			    from_s, from_len,
-			    0, self_len, FORWARD, maxcount);
-	if (count == 0) {
-		/* no matches, return unchanged */
-		return return_self(self);
-	}
-
-	/* Check for overflow */
-	/*    result_len = self_len + count * (to_len-from_len) */
-	product = count * (to_len-from_len);
-	if (product / (to_len-from_len) != count) {
-		PyErr_SetString(PyExc_OverflowError, "replace string is too long");
-		return NULL;
-	}
-	result_len = self_len + product;
-	if (result_len < 0) {
-		PyErr_SetString(PyExc_OverflowError, "replace string is too long");
-		return NULL;
-	}
-
-	if ( (result = (PyStringObject *)
-	      PyString_FromStringAndSize(NULL, result_len)) == NULL)
-		return NULL;
-	result_s = PyString_AS_STRING(result);
-
-	start = self_s;
-	end = self_s + self_len;
-	while (count-- > 0) {
-		offset = findstring(start, end-start,
-				    from_s, from_len,
-				    0, end-start, FORWARD);
-		if (offset == -1)
-			break;
-		next = start+offset;
-		if (next == start) {
-			/* replace with the 'to' */
-			Py_MEMCPY(result_s, to_s, to_len);
-			result_s += to_len;
-			start += from_len;
-		} else {
-			/* copy the unchanged old then the 'to' */
-			Py_MEMCPY(result_s, start, next-start);
-			result_s += (next-start);
-			Py_MEMCPY(result_s, to_s, to_len);
-			result_s += to_len;
-			start = next+from_len;
-		}
-	}
-	/* Copy the remainder of the remaining string */
-	Py_MEMCPY(result_s, start, end-start);
-
-	return result;
-}
-
-
-Py_LOCAL(PyStringObject *)
-replace(PyStringObject *self,
-	const char *from_s, Py_ssize_t from_len,
-	const char *to_s, Py_ssize_t to_len,
-	Py_ssize_t maxcount)
-{
-	if (maxcount < 0) {
-		maxcount = PY_SSIZE_T_MAX;
-	} else if (maxcount == 0 || PyString_GET_SIZE(self) == 0) {
-		/* nothing to do; return the original string */
-		return return_self(self);
-	}
-
-	if (maxcount == 0 ||
-	    (from_len == 0 && to_len == 0)) {
-		/* nothing to do; return the original string */
-		return return_self(self);
-	}
-
-	/* Handle zero-length special cases */
-
-	if (from_len == 0) {
-		/* insert the 'to' string everywhere.   */
-		/*    >>> "Python".replace("", ".")     */
-		/*    '.P.y.t.h.o.n.'                   */
-		return replace_interleave(self, to_s, to_len, maxcount);
-	}
-
-	/* Except for "".replace("", "A") == "A" there is no way beyond this */
-	/* point for an empty self string to generate a non-empty string */
-	/* Special case so the remaining code always gets a non-empty string */
-	if (PyString_GET_SIZE(self) == 0) {
-		return return_self(self);
-	}
-
-	if (to_len == 0) {
-		/* delete all occurances of 'from' string */
-		if (from_len == 1) {
-			return replace_delete_single_character(
-				self, from_s[0], maxcount);
-		} else {
-			return replace_delete_substring(self, from_s, from_len, maxcount);
-		}
-	}
-
-	/* Handle special case where both strings have the same length */
-
-	if (from_len == to_len) {
-		if (from_len == 1) {
-			return replace_single_character_in_place(
-				self,
-				from_s[0],
-				to_s[0],
-				maxcount);
-		} else {
-			return replace_substring_in_place(
-				self, from_s, from_len, to_s, to_len, maxcount);
-		}
-	}
-
-	/* Otherwise use the more generic algorithms */
-	if (from_len == 1) {
-		return replace_single_character(self, from_s[0],
-						to_s, to_len, maxcount);
-	} else {
-		/* len('from')>=2, len('to')>=1 */
-		return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
-	}
-}
-
-PyDoc_STRVAR(replace__doc__,
-"S.replace (old, new[, count]) -> string\n\
-\n\
-Return a copy of string S with all occurrences of substring\n\
-old replaced by new.  If the optional argument count is\n\
-given, only the first count occurrences are replaced.");
-
-static PyObject *
-string_replace(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t count = -1;
-	PyObject *from, *to;
-	const char *from_s, *to_s;
-	Py_ssize_t from_len, to_len;
-
-	if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
-		return NULL;
-
-	if (PyString_Check(from)) {
-		from_s = PyString_AS_STRING(from);
-		from_len = PyString_GET_SIZE(from);
-	}
-#ifdef Py_USING_UNICODE
-	if (PyUnicode_Check(from))
-		return PyUnicode_Replace((PyObject *)self,
-					 from, to, count);
-#endif
-	else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
-		return NULL;
-
-	if (PyString_Check(to)) {
-		to_s = PyString_AS_STRING(to);
-		to_len = PyString_GET_SIZE(to);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(to))
-		return PyUnicode_Replace((PyObject *)self,
-					 from, to, count);
-#endif
-	else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
-		return NULL;
-
-	return (PyObject *)replace((PyStringObject *) self,
-				   from_s, from_len,
-				   to_s, to_len, count);
-}
-
-/** End DALKE **/
-
-/* Matches the end (direction >= 0) or start (direction < 0) of self
- * against substr, using the start and end arguments. Returns
- * -1 on error, 0 if not found and 1 if found.
- */
-Py_LOCAL(int)
-_string_tailmatch(PyStringObject *self, PyObject *substr, Py_ssize_t start,
-		  Py_ssize_t end, int direction)
-{
-	Py_ssize_t len = PyString_GET_SIZE(self);
-	Py_ssize_t slen;
-	const char* sub;
-	const char* str;
-
-	if (PyString_Check(substr)) {
-		sub = PyString_AS_STRING(substr);
-		slen = PyString_GET_SIZE(substr);
-	}
-#ifdef Py_USING_UNICODE
-	else if (PyUnicode_Check(substr))
-		return PyUnicode_Tailmatch((PyObject *)self,
-					   substr, start, end, direction);
-#endif
-	else if (PyObject_AsCharBuffer(substr, &sub, &slen))
-		return -1;
-	str = PyString_AS_STRING(self);
-
-	string_adjust_indices(&start, &end, len);
-
-	if (direction < 0) {
-		/* startswith */
-		if (start+slen > len)
-			return 0;
-	} else {
-		/* endswith */
-		if (end-start < slen || start > len)
-			return 0;
-
-		if (end-slen > start)
-			start = end - slen;
-	}
-	if (end-start >= slen)
-		return ! memcmp(str+start, sub, slen);
-	return 0;
-}
-
-
-PyDoc_STRVAR(startswith__doc__,
-"S.startswith(prefix[, start[, end]]) -> bool\n\
-\n\
-Return True if S starts with the specified prefix, False otherwise.\n\
-With optional start, test S beginning at that position.\n\
-With optional end, stop comparing S at that position.\n\
-prefix can also be a tuple of strings to try.");
-
-static PyObject *
-string_startswith(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t start = 0;
-	Py_ssize_t end = PY_SSIZE_T_MAX;
-	PyObject *subobj;
-	int result;
-
-	if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
-		_PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
-		return NULL;
-	if (PyTuple_Check(subobj)) {
-		Py_ssize_t i;
-		for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-			result = _string_tailmatch(self,
-					PyTuple_GET_ITEM(subobj, i),
-					start, end, -1);
-			if (result == -1)
-				return NULL;
-			else if (result) {
-				Py_RETURN_TRUE;
-			}
-		}
-		Py_RETURN_FALSE;
-	}
-	result = _string_tailmatch(self, subobj, start, end, -1);
-	if (result == -1)
-		return NULL;
-	else
-		return PyBool_FromLong(result);
-}
-
-
-PyDoc_STRVAR(endswith__doc__,
-"S.endswith(suffix[, start[, end]]) -> bool\n\
-\n\
-Return True if S ends with the specified suffix, False otherwise.\n\
-With optional start, test S beginning at that position.\n\
-With optional end, stop comparing S at that position.\n\
-suffix can also be a tuple of strings to try.");
-
-static PyObject *
-string_endswith(PyStringObject *self, PyObject *args)
-{
-	Py_ssize_t start = 0;
-	Py_ssize_t end = PY_SSIZE_T_MAX;
-	PyObject *subobj;
-	int result;
-
-	if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
-		_PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
-		return NULL;
-	if (PyTuple_Check(subobj)) {
-		Py_ssize_t i;
-		for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
-			result = _string_tailmatch(self,
-					PyTuple_GET_ITEM(subobj, i),
-					start, end, +1);
-			if (result == -1)
-				return NULL;
-			else if (result) {
-				Py_RETURN_TRUE;
-			}
-		}
-		Py_RETURN_FALSE;
-	}
-	result = _string_tailmatch(self, subobj, start, end, +1);
-	if (result == -1)
-		return NULL;
-	else
-		return PyBool_FromLong(result);
-}
-
-
-PyDoc_STRVAR(encode__doc__,
-"S.encode([encoding[,errors]]) -> object\n\
-\n\
-Encodes S using the codec registered for encoding. encoding defaults\n\
-to the default encoding. errors may be given to set a different error\n\
-handling scheme. Default is 'strict' meaning that encoding errors raise\n\
-a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
-'xmlcharrefreplace' as well as any other name registered with\n\
-codecs.register_error that is able to handle UnicodeEncodeErrors.");
-
-static PyObject *
-string_encode(PyStringObject *self, PyObject *args)
-{
-    char *encoding = NULL;
-    char *errors = NULL;
-    PyObject *v;
-
-    if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
-        return NULL;
-    v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    if (!PyString_Check(v) && !PyUnicode_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "encoder did not return a string/unicode object "
-                     "(type=%.400s)",
-                     Py_TYPE(v)->tp_name);
-        Py_DECREF(v);
-        return NULL;
-    }
-    return v;
-
- onError:
-    return NULL;
-}
-
-
-PyDoc_STRVAR(decode__doc__,
-"S.decode([encoding[,errors]]) -> object\n\
-\n\
-Decodes S using the codec registered for encoding. encoding defaults\n\
-to the default encoding. errors may be given to set a different error\n\
-handling scheme. Default is 'strict' meaning that encoding errors raise\n\
-a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
-as well as any other name registerd with codecs.register_error that is\n\
-able to handle UnicodeDecodeErrors.");
-
-static PyObject *
-string_decode(PyStringObject *self, PyObject *args)
-{
-    char *encoding = NULL;
-    char *errors = NULL;
-    PyObject *v;
-
-    if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
-        return NULL;
-    v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    if (!PyString_Check(v) && !PyUnicode_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "decoder did not return a string/unicode object "
-                     "(type=%.400s)",
-                     Py_TYPE(v)->tp_name);
-        Py_DECREF(v);
-        return NULL;
-    }
-    return v;
-
- onError:
-    return NULL;
-}
-
-
-PyDoc_STRVAR(expandtabs__doc__,
-"S.expandtabs([tabsize]) -> string\n\
-\n\
-Return a copy of S where all tab characters are expanded using spaces.\n\
-If tabsize is not given, a tab size of 8 characters is assumed.");
-
-static PyObject*
-string_expandtabs(PyStringObject *self, PyObject *args)
-{
-    const char *e, *p, *qe;
-    char *q;
-    Py_ssize_t i, j, incr;
-    PyObject *u;
-    int tabsize = 8;
-
-    if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
-	return NULL;
-
-    /* First pass: determine size of output string */
-    i = 0; /* chars up to and including most recent \n or \r */
-    j = 0; /* chars since most recent \n or \r (use in tab calculations) */
-    e = PyString_AS_STRING(self) + PyString_GET_SIZE(self); /* end of input */
-    for (p = PyString_AS_STRING(self); p < e; p++)
-        if (*p == '\t') {
-	    if (tabsize > 0) {
-		incr = tabsize - (j % tabsize);
-		if (j > PY_SSIZE_T_MAX - incr)
-		    goto overflow1;
-		j += incr;
-            }
-	}
-        else {
-	    if (j > PY_SSIZE_T_MAX - 1)
-		goto overflow1;
-            j++;
-            if (*p == '\n' || *p == '\r') {
-		if (i > PY_SSIZE_T_MAX - j)
-		    goto overflow1;
-                i += j;
-                j = 0;
-            }
-        }
-
-    if (i > PY_SSIZE_T_MAX - j)
-	goto overflow1;
-
-    /* Second pass: create output string and fill it */
-    u = PyString_FromStringAndSize(NULL, i + j);
-    if (!u)
-        return NULL;
-
-    j = 0; /* same as in first pass */
-    q = PyString_AS_STRING(u); /* next output char */
-    qe = PyString_AS_STRING(u) + PyString_GET_SIZE(u); /* end of output */
-
-    for (p = PyString_AS_STRING(self); p < e; p++)
-        if (*p == '\t') {
-	    if (tabsize > 0) {
-		i = tabsize - (j % tabsize);
-		j += i;
-		while (i--) {
-		    if (q >= qe)
-			goto overflow2;
-		    *q++ = ' ';
-		}
-	    }
-	}
-	else {
-	    if (q >= qe)
-		goto overflow2;
-	    *q++ = *p;
-            j++;
-            if (*p == '\n' || *p == '\r')
-                j = 0;
-        }
-
-    return u;
-
-  overflow2:
-    Py_DECREF(u);
-  overflow1:
-    PyErr_SetString(PyExc_OverflowError, "new string is too long");
-    return NULL;
-}
-
-Py_LOCAL_INLINE(PyObject *)
-pad(PyStringObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
-{
-    PyObject *u;
-
-    if (left < 0)
-        left = 0;
-    if (right < 0)
-        right = 0;
-
-    if (left == 0 && right == 0 && PyString_CheckExact(self)) {
-        Py_INCREF(self);
-        return (PyObject *)self;
-    }
-
-    u = PyString_FromStringAndSize(NULL,
-				   left + PyString_GET_SIZE(self) + right);
-    if (u) {
-        if (left)
-            memset(PyString_AS_STRING(u), fill, left);
-        Py_MEMCPY(PyString_AS_STRING(u) + left,
-	       PyString_AS_STRING(self),
-	       PyString_GET_SIZE(self));
-        if (right)
-            memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
-		   fill, right);
-    }
-
-    return u;
-}
-
-PyDoc_STRVAR(ljust__doc__,
-"S.ljust(width[, fillchar]) -> string\n"
-"\n"
-"Return S left justified in a string of length width. Padding is\n"
-"done using the specified fill character (default is a space).");
-
-static PyObject *
-string_ljust(PyStringObject *self, PyObject *args)
-{
-    Py_ssize_t width;
-    char fillchar = ' ';
-
-    if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar))
-        return NULL;
-
-    if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
-        Py_INCREF(self);
-        return (PyObject*) self;
-    }
-
-    return pad(self, 0, width - PyString_GET_SIZE(self), fillchar);
-}
-
-
-PyDoc_STRVAR(rjust__doc__,
-"S.rjust(width[, fillchar]) -> string\n"
-"\n"
-"Return S right justified in a string of length width. Padding is\n"
-"done using the specified fill character (default is a space)");
-
-static PyObject *
-string_rjust(PyStringObject *self, PyObject *args)
-{
-    Py_ssize_t width;
-    char fillchar = ' ';
-
-    if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar))
-        return NULL;
-
-    if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
-        Py_INCREF(self);
-        return (PyObject*) self;
-    }
-
-    return pad(self, width - PyString_GET_SIZE(self), 0, fillchar);
-}
-
-
-PyDoc_STRVAR(center__doc__,
-"S.center(width[, fillchar]) -> string\n"
-"\n"
-"Return S centered in a string of length width. Padding is\n"
-"done using the specified fill character (default is a space)");
-
-static PyObject *
-string_center(PyStringObject *self, PyObject *args)
-{
-    Py_ssize_t marg, left;
-    Py_ssize_t width;
-    char fillchar = ' ';
-
-    if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar))
-        return NULL;
-
-    if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
-        Py_INCREF(self);
-        return (PyObject*) self;
-    }
-
-    marg = width - PyString_GET_SIZE(self);
-    left = marg / 2 + (marg & width & 1);
-
-    return pad(self, left, marg - left, fillchar);
-}
-
-PyDoc_STRVAR(zfill__doc__,
-"S.zfill(width) -> string\n"
-"\n"
-"Pad a numeric string S with zeros on the left, to fill a field\n"
-"of the specified width.  The string S is never truncated.");
-
-static PyObject *
-string_zfill(PyStringObject *self, PyObject *args)
-{
-    Py_ssize_t fill;
-    PyObject *s;
-    char *p;
-    Py_ssize_t width;
-
-    if (!PyArg_ParseTuple(args, "n:zfill", &width))
-        return NULL;
-
-    if (PyString_GET_SIZE(self) >= width) {
-        if (PyString_CheckExact(self)) {
-            Py_INCREF(self);
-            return (PyObject*) self;
-        }
-        else
-            return PyString_FromStringAndSize(
-                PyString_AS_STRING(self),
-                PyString_GET_SIZE(self)
-            );
-    }
-
-    fill = width - PyString_GET_SIZE(self);
-
-    s = pad(self, fill, 0, '0');
-
-    if (s == NULL)
-        return NULL;
-
-    p = PyString_AS_STRING(s);
-    if (p[fill] == '+' || p[fill] == '-') {
-        /* move sign to beginning of string */
-        p[0] = p[fill];
-        p[fill] = '0';
-    }
-
-    return (PyObject*) s;
-}
-
-PyDoc_STRVAR(isspace__doc__,
-"S.isspace() -> bool\n\
-\n\
-Return True if all characters in S are whitespace\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-string_isspace(PyStringObject *self)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1 &&
-	isspace(*p))
-	return PyBool_FromLong(1);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    for (; p < e; p++) {
-	if (!isspace(*p))
-	    return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-
-PyDoc_STRVAR(isalpha__doc__,
-"S.isalpha() -> bool\n\
-\n\
-Return True if all characters in S are alphabetic\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-string_isalpha(PyStringObject *self)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1 &&
-	isalpha(*p))
-	return PyBool_FromLong(1);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    for (; p < e; p++) {
-	if (!isalpha(*p))
-	    return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-
-PyDoc_STRVAR(isalnum__doc__,
-"S.isalnum() -> bool\n\
-\n\
-Return True if all characters in S are alphanumeric\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-string_isalnum(PyStringObject *self)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1 &&
-	isalnum(*p))
-	return PyBool_FromLong(1);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    for (; p < e; p++) {
-	if (!isalnum(*p))
-	    return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-
-PyDoc_STRVAR(isdigit__doc__,
-"S.isdigit() -> bool\n\
-\n\
-Return True if all characters in S are digits\n\
-and there is at least one character in S, False otherwise.");
-
-static PyObject*
-string_isdigit(PyStringObject *self)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1 &&
-	isdigit(*p))
-	return PyBool_FromLong(1);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    for (; p < e; p++) {
-	if (!isdigit(*p))
-	    return PyBool_FromLong(0);
-    }
-    return PyBool_FromLong(1);
-}
-
-
-PyDoc_STRVAR(islower__doc__,
-"S.islower() -> bool\n\
-\n\
-Return True if all cased characters in S are lowercase and there is\n\
-at least one cased character in S, False otherwise.");
-
-static PyObject*
-string_islower(PyStringObject *self)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-    int cased;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1)
-	return PyBool_FromLong(islower(*p) != 0);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    cased = 0;
-    for (; p < e; p++) {
-	if (isupper(*p))
-	    return PyBool_FromLong(0);
-	else if (!cased && islower(*p))
-	    cased = 1;
-    }
-    return PyBool_FromLong(cased);
-}
-
-
-PyDoc_STRVAR(isupper__doc__,
-"S.isupper() -> bool\n\
-\n\
-Return True if all cased characters in S are uppercase and there is\n\
-at least one cased character in S, False otherwise.");
-
-static PyObject*
-string_isupper(PyStringObject *self)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-    int cased;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1)
-	return PyBool_FromLong(isupper(*p) != 0);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    cased = 0;
-    for (; p < e; p++) {
-	if (islower(*p))
-	    return PyBool_FromLong(0);
-	else if (!cased && isupper(*p))
-	    cased = 1;
-    }
-    return PyBool_FromLong(cased);
-}
-
-
-PyDoc_STRVAR(istitle__doc__,
-"S.istitle() -> bool\n\
-\n\
-Return True if S is a titlecased string and there is at least one\n\
-character in S, i.e. uppercase characters may only follow uncased\n\
-characters and lowercase characters only cased ones. Return False\n\
-otherwise.");
-
-static PyObject*
-string_istitle(PyStringObject *self, PyObject *uncased)
-{
-    register const unsigned char *p
-        = (unsigned char *) PyString_AS_STRING(self);
-    register const unsigned char *e;
-    int cased, previous_is_cased;
-
-    /* Shortcut for single character strings */
-    if (PyString_GET_SIZE(self) == 1)
-	return PyBool_FromLong(isupper(*p) != 0);
-
-    /* Special case for empty strings */
-    if (PyString_GET_SIZE(self) == 0)
-	return PyBool_FromLong(0);
-
-    e = p + PyString_GET_SIZE(self);
-    cased = 0;
-    previous_is_cased = 0;
-    for (; p < e; p++) {
-	register const unsigned char ch = *p;
-
-	if (isupper(ch)) {
-	    if (previous_is_cased)
-		return PyBool_FromLong(0);
-	    previous_is_cased = 1;
-	    cased = 1;
-	}
-	else if (islower(ch)) {
-	    if (!previous_is_cased)
-		return PyBool_FromLong(0);
-	    previous_is_cased = 1;
-	    cased = 1;
-	}
-	else
-	    previous_is_cased = 0;
-    }
-    return PyBool_FromLong(cased);
-}
-
-
-PyDoc_STRVAR(splitlines__doc__,
-"S.splitlines([keepends]) -> list of strings\n\
-\n\
-Return a list of the lines in S, breaking at line boundaries.\n\
-Line breaks are not included in the resulting list unless keepends\n\
-is given and true.");
-
-static PyObject*
-string_splitlines(PyStringObject *self, PyObject *args)
-{
-    register Py_ssize_t i;
-    register Py_ssize_t j;
-    Py_ssize_t len;
-    int keepends = 0;
-    PyObject *list;
-    PyObject *str;
-    char *data;
-
-    if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
-        return NULL;
-
-    data = PyString_AS_STRING(self);
-    len = PyString_GET_SIZE(self);
-
-    /* This does not use the preallocated list because splitlines is
-       usually run with hundreds of newlines.  The overhead of
-       switching between PyList_SET_ITEM and append causes about a
-       2-3% slowdown for that common case.  A smarter implementation
-       could move the if check out, so the SET_ITEMs are done first
-       and the appends only done when the prealloc buffer is full.
-       That's too much work for little gain.*/
-
-    list = PyList_New(0);
-    if (!list)
-        goto onError;
-
-    for (i = j = 0; i < len; ) {
-	Py_ssize_t eol;
-
-	/* Find a line and append it */
-	while (i < len && data[i] != '\n' && data[i] != '\r')
-	    i++;
-
-	/* Skip the line break reading CRLF as one line break */
-	eol = i;
-	if (i < len) {
-	    if (data[i] == '\r' && i + 1 < len &&
-		data[i+1] == '\n')
-		i += 2;
-	    else
-		i++;
-	    if (keepends)
-		eol = i;
-	}
-	SPLIT_APPEND(data, j, eol);
-	j = i;
-    }
-    if (j < len) {
-	SPLIT_APPEND(data, j, len);
-    }
-
-    return list;
-
- onError:
-    Py_XDECREF(list);
-    return NULL;
-}
-
-PyDoc_STRVAR(sizeof__doc__,
-"S.__sizeof__() -> size of S in bytes");
-
-static PyObject *
-string_sizeof(PyStringObject *v)
-{
-	Py_ssize_t res;
-	res = sizeof(PyStringObject) + v->ob_size * v->ob_type->tp_itemsize;
-	return PyInt_FromSsize_t(res);
-}
-
-#undef SPLIT_APPEND
-#undef SPLIT_ADD
-#undef MAX_PREALLOC
-#undef PREALLOC_SIZE
-
-static PyObject *
-string_getnewargs(PyStringObject *v)
-{
-	return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v));
-}
-
-
-#include "stringlib/string_format.h"
-
-PyDoc_STRVAR(format__doc__,
-"S.format(*args, **kwargs) -> unicode\n\
-\n\
-");
-
-PyDoc_STRVAR(p_format__doc__,
-"S.__format__(format_spec) -> unicode\n\
-\n\
-");
-
-
-static PyMethodDef
-string_methods[] = {
-	/* Counterparts of the obsolete stropmodule functions; except
-	   string.maketrans(). */
-	{"join", (PyCFunction)string_join, METH_O, join__doc__},
-	{"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
-	{"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
-	{"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
-	{"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
-	{"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
-	{"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
-	{"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
-	{"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
-	{"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
-	{"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
-	{"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
-	{"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
-	 capitalize__doc__},
-	{"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
-	{"endswith", (PyCFunction)string_endswith, METH_VARARGS,
-	 endswith__doc__},
-	{"partition", (PyCFunction)string_partition, METH_O, partition__doc__},
-	{"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
-	{"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
-	{"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
-	{"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
-	{"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
-	{"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
-	{"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
-	{"rpartition", (PyCFunction)string_rpartition, METH_O,
-	 rpartition__doc__},
-	{"startswith", (PyCFunction)string_startswith, METH_VARARGS,
-	 startswith__doc__},
-	{"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
-	{"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
-	 swapcase__doc__},
-	{"translate", (PyCFunction)string_translate, METH_VARARGS,
-	 translate__doc__},
-	{"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
-	{"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
-	{"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
-	{"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
-	{"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
-	{"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
-	{"__format__", (PyCFunction) string__format__, METH_VARARGS, p_format__doc__},
-	{"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
-	{"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
-	{"encode", (PyCFunction)string_encode, METH_VARARGS, encode__doc__},
-	{"decode", (PyCFunction)string_decode, METH_VARARGS, decode__doc__},
-	{"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
-	 expandtabs__doc__},
-	{"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
-	 splitlines__doc__},
-	{"__sizeof__", (PyCFunction)string_sizeof, METH_NOARGS,
-	 sizeof__doc__},
-	{"__getnewargs__",	(PyCFunction)string_getnewargs,	METH_NOARGS},
-	{NULL,     NULL}		     /* sentinel */
-};
-
-static PyObject *
-str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
-
-static PyObject *
-string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-	PyObject *x = NULL;
-	static char *kwlist[] = {"object", 0};
-
-	if (type != &PyString_Type)
-		return str_subtype_new(type, args, kwds);
-	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
-		return NULL;
-	if (x == NULL)
-		return PyString_FromString("");
-	return PyObject_Str(x);
-}
-
-static PyObject *
-str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-	PyObject *tmp, *pnew;
-	Py_ssize_t n;
-
-	assert(PyType_IsSubtype(type, &PyString_Type));
-	tmp = string_new(&PyString_Type, args, kwds);
-	if (tmp == NULL)
-		return NULL;
-	assert(PyString_CheckExact(tmp));
-	n = PyString_GET_SIZE(tmp);
-	pnew = type->tp_alloc(type, n);
-	if (pnew != NULL) {
-		Py_MEMCPY(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
-		((PyStringObject *)pnew)->ob_shash =
-			((PyStringObject *)tmp)->ob_shash;
-		((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
-	}
-	Py_DECREF(tmp);
-	return pnew;
-}
-
-static PyObject *
-basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-	PyErr_SetString(PyExc_TypeError,
-			"The basestring type cannot be instantiated");
-	return NULL;
-}
-
-static PyObject *
-string_mod(PyObject *v, PyObject *w)
-{
-	if (!PyString_Check(v)) {
-		Py_INCREF(Py_NotImplemented);
-		return Py_NotImplemented;
-	}
-	return PyString_Format(v, w);
-}
-
-PyDoc_STRVAR(basestring_doc,
-"Type basestring cannot be instantiated; it is the base for str and unicode.");
-
-static PyNumberMethods string_as_number = {
-	0,			/*nb_add*/
-	0,			/*nb_subtract*/
-	0,			/*nb_multiply*/
-	0, 			/*nb_divide*/
-	string_mod,		/*nb_remainder*/
-};
-
-
-PyTypeObject PyBaseString_Type = {
-	PyVarObject_HEAD_INIT(&PyType_Type, 0)
-	"basestring",
-	0,
-	0,
- 	0,			 		/* tp_dealloc */
-	0,			 		/* tp_print */
-	0,					/* tp_getattr */
-	0,					/* tp_setattr */
-	0,					/* tp_compare */
-	0,		 			/* tp_repr */
-	0,					/* tp_as_number */
-	0,					/* tp_as_sequence */
-	0,					/* tp_as_mapping */
-	0,		 			/* tp_hash */
-	0,					/* tp_call */
-	0,					/* tp_str */
-	0,					/* tp_getattro */
-	0,					/* tp_setattro */
-	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
-	basestring_doc,				/* tp_doc */
-	0,					/* tp_traverse */
-	0,					/* tp_clear */
-	0,					/* tp_richcompare */
-	0,					/* tp_weaklistoffset */
-	0,					/* tp_iter */
-	0,					/* tp_iternext */
-	0,					/* tp_methods */
-	0,					/* tp_members */
-	0,					/* tp_getset */
-	&PyBaseObject_Type,			/* tp_base */
-	0,					/* tp_dict */
-	0,					/* tp_descr_get */
-	0,					/* tp_descr_set */
-	0,					/* tp_dictoffset */
-	0,					/* tp_init */
-	0,					/* tp_alloc */
-	basestring_new,				/* tp_new */
-	0,		                	/* tp_free */
-};
-
-PyDoc_STRVAR(string_doc,
-"str(object) -> string\n\
-\n\
-Return a nice string representation of the object.\n\
-If the argument is a string, the return value is the same object.");
-
-PyTypeObject PyString_Type = {
-	PyVarObject_HEAD_INIT(&PyType_Type, 0)
-	"str",
-	sizeof(PyStringObject),
-	sizeof(char),
- 	string_dealloc, 			/* tp_dealloc */
-	(printfunc)string_print, 		/* tp_print */
-	0,					/* tp_getattr */
-	0,					/* tp_setattr */
-	0,					/* tp_compare */
-	string_repr, 				/* tp_repr */
-	&string_as_number,			/* tp_as_number */
-	&string_as_sequence,			/* tp_as_sequence */
-	&string_as_mapping,			/* tp_as_mapping */
-	(hashfunc)string_hash, 			/* tp_hash */
-	0,					/* tp_call */
-	string_str,				/* tp_str */
-	PyObject_GenericGetAttr,		/* tp_getattro */
-	0,					/* tp_setattro */
-	&string_as_buffer,			/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
-		Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS |
-		Py_TPFLAGS_HAVE_NEWBUFFER,	/* tp_flags */
-	string_doc,				/* tp_doc */
-	0,					/* tp_traverse */
-	0,					/* tp_clear */
-	(richcmpfunc)string_richcompare,	/* tp_richcompare */
-	0,					/* tp_weaklistoffset */
-	0,					/* tp_iter */
-	0,					/* tp_iternext */
-	string_methods,				/* tp_methods */
-	0,					/* tp_members */
-	0,					/* tp_getset */
-	&PyBaseString_Type,			/* tp_base */
-	0,					/* tp_dict */
-	0,					/* tp_descr_get */
-	0,					/* tp_descr_set */
-	0,					/* tp_dictoffset */
-	0,					/* tp_init */
-	0,					/* tp_alloc */
-	string_new,				/* tp_new */
-	PyObject_Del,	                	/* tp_free */
-};
-
-void
-PyString_Concat(register PyObject **pv, register PyObject *w)
-{
-	register PyObject *v;
-	if (*pv == NULL)
-		return;
-	if (w == NULL || !PyString_Check(*pv)) {
-		Py_DECREF(*pv);
-		*pv = NULL;
-		return;
-	}
-	v = string_concat((PyStringObject *) *pv, w);
-	Py_DECREF(*pv);
-	*pv = v;
-}
-
-void
-PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
-{
-	PyString_Concat(pv, w);
-	Py_XDECREF(w);
-}
-
-
-/* The following function breaks the notion that strings are immutable:
-   it changes the size of a string.  We get away with this only if there
-   is only one module referencing the object.  You can also think of it
-   as creating a new string object and destroying the old one, only
-   more efficiently.  In any case, don't use this if the string may
-   already be known to some other part of the code...
-   Note that if there's not enough memory to resize the string, the original
-   string object at *pv is deallocated, *pv is set to NULL, an "out of
-   memory" exception is set, and -1 is returned.  Else (on success) 0 is
-   returned, and the value in *pv may or may not be the same as on input.
-   As always, an extra byte is allocated for a trailing \0 byte (newsize
-   does *not* include that), and a trailing \0 byte is stored.
-*/
-
-int
-_PyString_Resize(PyObject **pv, Py_ssize_t newsize)
-{
-	register PyObject *v;
-	register PyStringObject *sv;
-	v = *pv;
-	if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
-	    PyString_CHECK_INTERNED(v)) {
-		*pv = 0;
-		Py_DECREF(v);
-		PyErr_BadInternalCall();
-		return -1;
-	}
-	/* XXX UNREF/NEWREF interface should be more symmetrical */
-	_Py_DEC_REFTOTAL;
-	_Py_ForgetReference(v);
-	*pv = (PyObject *)
-		PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
-	if (*pv == NULL) {
-		PyObject_Del(v);
-		PyErr_NoMemory();
-		return -1;
-	}
-	_Py_NewReference(*pv);
-	sv = (PyStringObject *) *pv;
-	Py_SIZE(sv) = newsize;
-	sv->ob_sval[newsize] = '\0';
-	sv->ob_shash = -1;	/* invalidate cached hash value */
-	return 0;
-}
-
-/* Helpers for formatstring */
-
-Py_LOCAL_INLINE(PyObject *)
-getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
-{
-	Py_ssize_t argidx = *p_argidx;
-	if (argidx < arglen) {
-		(*p_argidx)++;
-		if (arglen < 0)
-			return args;
-		else
-			return PyTuple_GetItem(args, argidx);
-	}
-	PyErr_SetString(PyExc_TypeError,
-			"not enough arguments for format string");
-	return NULL;
-}
-
-/* Format codes
- * F_LJUST	'-'
- * F_SIGN	'+'
- * F_BLANK	' '
- * F_ALT	'#'
- * F_ZERO	'0'
- */
-#define F_LJUST (1<<0)
-#define F_SIGN	(1<<1)
-#define F_BLANK (1<<2)
-#define F_ALT	(1<<3)
-#define F_ZERO	(1<<4)
-
-Py_LOCAL_INLINE(int)
-formatfloat(char *buf, size_t buflen, int flags,
-            int prec, int type, PyObject *v)
-{
-	/* fmt = '%#.' + `prec` + `type`
-	   worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
-	char fmt[20];
-	double x;
-	x = PyFloat_AsDouble(v);
-	if (x == -1.0 && PyErr_Occurred()) {
-		PyErr_Format(PyExc_TypeError, "float argument required, "
-			     "not %.200s", Py_TYPE(v)->tp_name);
-		return -1;
-	}
-	if (prec < 0)
-		prec = 6;
-	if (type == 'f' && fabs(x)/1e25 >= 1e25)
-		type = 'g';
-	/* Worst case length calc to ensure no buffer overrun:
-
-	   'g' formats:
-	     fmt = %#.<prec>g
-	     buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
-	        for any double rep.)
-	     len = 1 + prec + 1 + 2 + 5 = 9 + prec
-
-	   'f' formats:
-	     buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
-	     len = 1 + 50 + 1 + prec = 52 + prec
-
-	   If prec=0 the effective precision is 1 (the leading digit is
-	   always given), therefore increase the length by one.
-
-	*/
-	if (((type == 'g' || type == 'G') &&
-              buflen <= (size_t)10 + (size_t)prec) ||
-	    (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
-		PyErr_SetString(PyExc_OverflowError,
-			"formatted float is too long (precision too large?)");
-		return -1;
-	}
-	PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
-		      (flags&F_ALT) ? "#" : "",
-		      prec, type);
-        PyOS_ascii_formatd(buf, buflen, fmt, x);
-	return (int)strlen(buf);
-}
-
-/* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
- * the F_ALT flag, for Python's long (unbounded) ints.  It's not used for
- * Python's regular ints.
- * Return value:  a new PyString*, or NULL if error.
- *  .  *pbuf is set to point into it,
- *     *plen set to the # of chars following that.
- *     Caller must decref it when done using pbuf.
- *     The string starting at *pbuf is of the form
- *         "-"? ("0x" | "0X")? digit+
- *     "0x"/"0X" are present only for x and X conversions, with F_ALT
- *         set in flags.  The case of hex digits will be correct,
- *     There will be at least prec digits, zero-filled on the left if
- *         necessary to get that many.
- * val		object to be converted
- * flags	bitmask of format flags; only F_ALT is looked at
- * prec		minimum number of digits; 0-fill on left if needed
- * type		a character in [duoxX]; u acts the same as d
- *
- * CAUTION:  o, x and X conversions on regular ints can never
- * produce a '-' sign, but can for Python's unbounded ints.
- */
-PyObject*
-_PyString_FormatLong(PyObject *val, int flags, int prec, int type,
-		     char **pbuf, int *plen)
-{
-	PyObject *result = NULL;
-	char *buf;
-	Py_ssize_t i;
-	int sign;	/* 1 if '-', else 0 */
-	int len;	/* number of characters */
-	Py_ssize_t llen;
-	int numdigits;	/* len == numnondigits + numdigits */
-	int numnondigits = 0;
-
-	switch (type) {
-	case 'd':
-	case 'u':
-		result = Py_TYPE(val)->tp_str(val);
-		break;
-	case 'o':
-		result = Py_TYPE(val)->tp_as_number->nb_oct(val);
-		break;
-	case 'x':
-	case 'X':
-		numnondigits = 2;
-		result = Py_TYPE(val)->tp_as_number->nb_hex(val);
-		break;
-	default:
-		assert(!"'type' not in [duoxX]");
-	}
-	if (!result)
-		return NULL;
-
-	buf = PyString_AsString(result);
-	if (!buf) {
-		Py_DECREF(result);
-		return NULL;
-	}
-
-	/* To modify the string in-place, there can only be one reference. */
-	if (Py_REFCNT(result) != 1) {
-		PyErr_BadInternalCall();
-		return NULL;
-	}
-	llen = PyString_Size(result);
-	if (llen > INT_MAX) {
-		PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
-		return NULL;
-	}
-	len = (int)llen;
-	if (buf[len-1] == 'L') {
-		--len;
-		buf[len] = '\0';
-	}
-	sign = buf[0] == '-';
-	numnondigits += sign;
-	numdigits = len - numnondigits;
-	assert(numdigits > 0);
-
-	/* Get rid of base marker unless F_ALT */
-	if ((flags & F_ALT) == 0) {
-		/* Need to skip 0x, 0X or 0. */
-		int skipped = 0;
-		switch (type) {
-		case 'o':
-			assert(buf[sign] == '0');
-			/* If 0 is only digit, leave it alone. */
-			if (numdigits > 1) {
-				skipped = 1;
-				--numdigits;
-			}
-			break;
-		case 'x':
-		case 'X':
-			assert(buf[sign] == '0');
-			assert(buf[sign + 1] == 'x');
-			skipped = 2;
-			numnondigits -= 2;
-			break;
-		}
-		if (skipped) {
-			buf += skipped;
-			len -= skipped;
-			if (sign)
-				buf[0] = '-';
-		}
-		assert(len == numnondigits + numdigits);
-		assert(numdigits > 0);
-	}
-
-	/* Fill with leading zeroes to meet minimum width. */
-	if (prec > numdigits) {
-		PyObject *r1 = PyString_FromStringAndSize(NULL,
-					numnondigits + prec);
-		char *b1;
-		if (!r1) {
-			Py_DECREF(result);
-			return NULL;
-		}
-		b1 = PyString_AS_STRING(r1);
-		for (i = 0; i < numnondigits; ++i)
-			*b1++ = *buf++;
-		for (i = 0; i < prec - numdigits; i++)
-			*b1++ = '0';
-		for (i = 0; i < numdigits; i++)
-			*b1++ = *buf++;
-		*b1 = '\0';
-		Py_DECREF(result);
-		result = r1;
-		buf = PyString_AS_STRING(result);
-		len = numnondigits + prec;
-	}
-
-	/* Fix up case for hex conversions. */
-	if (type == 'X') {
-		/* Need to convert all lower case letters to upper case.
-		   and need to convert 0x to 0X (and -0x to -0X). */
-		for (i = 0; i < len; i++)
-			if (buf[i] >= 'a' && buf[i] <= 'x')
-				buf[i] -= 'a'-'A';
-	}
-	*pbuf = buf;
-	*plen = len;
-	return result;
-}
-
-Py_LOCAL_INLINE(int)
-formatint(char *buf, size_t buflen, int flags,
-          int prec, int type, PyObject *v)
-{
-	/* fmt = '%#.' + `prec` + 'l' + `type`
-	   worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
-	   + 1 + 1 = 24 */
-	char fmt[64];	/* plenty big enough! */
-	char *sign;
-	long x;
-
-	x = PyInt_AsLong(v);
-	if (x == -1 && PyErr_Occurred()) {
-		PyErr_Format(PyExc_TypeError, "int argument required, not %.200s",
-			     Py_TYPE(v)->tp_name);
-		return -1;
-	}
-	if (x < 0 && type == 'u') {
-		type = 'd';
-	}
-	if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
-		sign = "-";
-	else
-		sign = "";
-	if (prec < 0)
-		prec = 1;
-
-	if ((flags & F_ALT) &&
-	    (type == 'x' || type == 'X')) {
-		/* When converting under %#x or %#X, there are a number
-		 * of issues that cause pain:
-		 * - when 0 is being converted, the C standard leaves off
-		 *   the '0x' or '0X', which is inconsistent with other
-		 *   %#x/%#X conversions and inconsistent with Python's
-		 *   hex() function
-		 * - there are platforms that violate the standard and
-		 *   convert 0 with the '0x' or '0X'
-		 *   (Metrowerks, Compaq Tru64)
-		 * - there are platforms that give '0x' when converting
-		 *   under %#X, but convert 0 in accordance with the
-		 *   standard (OS/2 EMX)
-		 *
-		 * We can achieve the desired consistency by inserting our
-		 * own '0x' or '0X' prefix, and substituting %x/%X in place
-		 * of %#x/%#X.
-		 *
-		 * Note that this is the same approach as used in
-		 * formatint() in unicodeobject.c
-		 */
-		PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
-			      sign, type, prec, type);
-	}
-	else {
-		PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
-			      sign, (flags&F_ALT) ? "#" : "",
-			      prec, type);
-	}
-
-	/* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
-	 * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
-	 */
-	if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
-		PyErr_SetString(PyExc_OverflowError,
-		    "formatted integer is too long (precision too large?)");
-		return -1;
-	}
-	if (sign[0])
-		PyOS_snprintf(buf, buflen, fmt, -x);
-	else
-		PyOS_snprintf(buf, buflen, fmt, x);
-	return (int)strlen(buf);
-}
-
-Py_LOCAL_INLINE(int)
-formatchar(char *buf, size_t buflen, PyObject *v)
-{
-	/* presume that the buffer is at least 2 characters long */
-	if (PyString_Check(v)) {
-		if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
-			return -1;
-	}
-	else {
-		if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
-			return -1;
-	}
-	buf[1] = '\0';
-	return 1;
-}
-
-/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
-
-   FORMATBUFLEN is the length of the buffer in which the floats, ints, &
-   chars are formatted. XXX This is a magic number. Each formatting
-   routine does bounds checking to ensure no overflow, but a better
-   solution may be to malloc a buffer of appropriate size for each
-   format. For now, the current solution is sufficient.
-*/
-#define FORMATBUFLEN (size_t)120
-
-PyObject *
-PyString_Format(PyObject *format, PyObject *args)
-{
-	char *fmt, *res;
-	Py_ssize_t arglen, argidx;
-	Py_ssize_t reslen, rescnt, fmtcnt;
-	int args_owned = 0;
-	PyObject *result, *orig_args;
-#ifdef Py_USING_UNICODE
-	PyObject *v, *w;
-#endif
-	PyObject *dict = NULL;
-	if (format == NULL || !PyString_Check(format) || args == NULL) {
-		PyErr_BadInternalCall();
-		return NULL;
-	}
-	orig_args = args;
-	fmt = PyString_AS_STRING(format);
-	fmtcnt = PyString_GET_SIZE(format);
-	reslen = rescnt = fmtcnt + 100;
-	result = PyString_FromStringAndSize((char *)NULL, reslen);
-	if (result == NULL)
-		return NULL;
-	res = PyString_AsString(result);
-	if (PyTuple_Check(args)) {
-		arglen = PyTuple_GET_SIZE(args);
-		argidx = 0;
-	}
-	else {
-		arglen = -1;
-		argidx = -2;
-	}
-	if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
-	    !PyObject_TypeCheck(args, &PyBaseString_Type))
-		dict = args;
-	while (--fmtcnt >= 0) {
-		if (*fmt != '%') {
-			if (--rescnt < 0) {
-				rescnt = fmtcnt + 100;
-				reslen += rescnt;
-				if (_PyString_Resize(&result, reslen) < 0)
-					return NULL;
-				res = PyString_AS_STRING(result)
-					+ reslen - rescnt;
-				--rescnt;
-			}
-			*res++ = *fmt++;
-		}
-		else {
-			/* Got a format specifier */
-			int flags = 0;
-			Py_ssize_t width = -1;
-			int prec = -1;
-			int c = '\0';
-			int fill;
-			int isnumok;
-			PyObject *v = NULL;
-			PyObject *temp = NULL;
-			char *pbuf;
-			int sign;
-			Py_ssize_t len;
-			char formatbuf[FORMATBUFLEN];
-			     /* For format{float,int,char}() */
-#ifdef Py_USING_UNICODE
-			char *fmt_start = fmt;
-			Py_ssize_t argidx_start = argidx;
-#endif
-
-			fmt++;
-			if (*fmt == '(') {
-				char *keystart;
-				Py_ssize_t keylen;
-				PyObject *key;
-				int pcount = 1;
-
-				if (dict == NULL) {
-					PyErr_SetString(PyExc_TypeError,
-						 "format requires a mapping");
-					goto error;
-				}
-				++fmt;
-				--fmtcnt;
-				keystart = fmt;
-				/* Skip over balanced parentheses */
-				while (pcount > 0 && --fmtcnt >= 0) {
-					if (*fmt == ')')
-						--pcount;
-					else if (*fmt == '(')
-						++pcount;
-					fmt++;
-				}
-				keylen = fmt - keystart - 1;
-				if (fmtcnt < 0 || pcount > 0) {
-					PyErr_SetString(PyExc_ValueError,
-						   "incomplete format key");
-					goto error;
-				}
-				key = PyString_FromStringAndSize(keystart,
-								 keylen);
-				if (key == NULL)
-					goto error;
-				if (args_owned) {
-					Py_DECREF(args);
-					args_owned = 0;
-				}
-				args = PyObject_GetItem(dict, key);
-				Py_DECREF(key);
-				if (args == NULL) {
-					goto error;
-				}
-				args_owned = 1;
-				arglen = -1;
-				argidx = -2;
-			}
-			while (--fmtcnt >= 0) {
-				switch (c = *fmt++) {
-				case '-': flags |= F_LJUST; continue;
-				case '+': flags |= F_SIGN; continue;
-				case ' ': flags |= F_BLANK; continue;
-				case '#': flags |= F_ALT; continue;
-				case '0': flags |= F_ZERO; continue;
-				}
-				break;
-			}
-			if (c == '*') {
-				v = getnextarg(args, arglen, &argidx);
-				if (v == NULL)
-					goto error;
-				if (!PyInt_Check(v)) {
-					PyErr_SetString(PyExc_TypeError,
-							"* wants int");
-					goto error;
-				}
-				width = PyInt_AsLong(v);
-				if (width < 0) {
-					flags |= F_LJUST;
-					width = -width;
-				}
-				if (--fmtcnt >= 0)
-					c = *fmt++;
-			}
-			else if (c >= 0 && isdigit(c)) {
-				width = c - '0';
-				while (--fmtcnt >= 0) {
-					c = Py_CHARMASK(*fmt++);
-					if (!isdigit(c))
-						break;
-					if ((width*10) / 10 != width) {
-						PyErr_SetString(
-							PyExc_ValueError,
-							"width too big");
-						goto error;
-					}
-					width = width*10 + (c - '0');
-				}
-			}
-			if (c == '.') {
-				prec = 0;
-				if (--fmtcnt >= 0)
-					c = *fmt++;
-				if (c == '*') {
-					v = getnextarg(args, arglen, &argidx);
-					if (v == NULL)
-						goto error;
-					if (!PyInt_Check(v)) {
-						PyErr_SetString(
-							PyExc_TypeError,
-							"* wants int");
-						goto error;
-					}
-					prec = PyInt_AsLong(v);
-					if (prec < 0)
-						prec = 0;
-					if (--fmtcnt >= 0)
-						c = *fmt++;
-				}
-				else if (c >= 0 && isdigit(c)) {
-					prec = c - '0';
-					while (--fmtcnt >= 0) {
-						c = Py_CHARMASK(*fmt++);
-						if (!isdigit(c))
-							break;
-						if ((prec*10) / 10 != prec) {
-							PyErr_SetString(
-							    PyExc_ValueError,
-							    "prec too big");
-							goto error;
-						}
-						prec = prec*10 + (c - '0');
-					}
-				}
-			} /* prec */
-			if (fmtcnt >= 0) {
-				if (c == 'h' || c == 'l' || c == 'L') {
-					if (--fmtcnt >= 0)
-						c = *fmt++;
-				}
-			}
-			if (fmtcnt < 0) {
-				PyErr_SetString(PyExc_ValueError,
-						"incomplete format");
-				goto error;
-			}
-			if (c != '%') {
-				v = getnextarg(args, arglen, &argidx);
-				if (v == NULL)
-					goto error;
-			}
-			sign = 0;
-			fill = ' ';
-			switch (c) {
-			case '%':
-				pbuf = "%";
-				len = 1;
-				break;
-			case 's':
-#ifdef Py_USING_UNICODE
-				if (PyUnicode_Check(v)) {
-					fmt = fmt_start;
-					argidx = argidx_start;
-					goto unicode;
-				}
-#endif
-				temp = _PyObject_Str(v);
-#ifdef Py_USING_UNICODE
-				if (temp != NULL && PyUnicode_Check(temp)) {
-					Py_DECREF(temp);
-					fmt = fmt_start;
-					argidx = argidx_start;
-					goto unicode;
-				}
-#endif
-				/* Fall through */
-			case 'r':
-				if (c == 'r')
-					temp = PyObject_Repr(v);
-				if (temp == NULL)
-					goto error;
-				if (!PyString_Check(temp)) {
-					PyErr_SetString(PyExc_TypeError,
-					  "%s argument has non-string str()");
-					Py_DECREF(temp);
-					goto error;
-				}
-				pbuf = PyString_AS_STRING(temp);
-				len = PyString_GET_SIZE(temp);
-				if (prec >= 0 && len > prec)
-					len = prec;
-				break;
-			case 'i':
-			case 'd':
-			case 'u':
-			case 'o':
-			case 'x':
-			case 'X':
-				if (c == 'i')
-					c = 'd';
-				isnumok = 0;
-				if (PyNumber_Check(v)) {
-					PyObject *iobj=NULL;
-
-					if (PyInt_Check(v) || (PyLong_Check(v))) {
-						iobj = v;
-						Py_INCREF(iobj);
-					}
-					else {
-						iobj = PyNumber_Int(v);
-						if (iobj==NULL) iobj = PyNumber_Long(v);
-					}
-					if (iobj!=NULL) {
-						if (PyInt_Check(iobj)) {
-							isnumok = 1;
-							pbuf = formatbuf;
-							len = formatint(pbuf,
-									sizeof(formatbuf),
-									flags, prec, c, iobj);
-							Py_DECREF(iobj);
-							if (len < 0)
-								goto error;
-							sign = 1;
-						}
-						else if (PyLong_Check(iobj)) {
-							int ilen;
-							
-							isnumok = 1;
-							temp = _PyString_FormatLong(iobj, flags,
-								prec, c, &pbuf, &ilen);
-							Py_DECREF(iobj);
-							len = ilen;
-							if (!temp)
-								goto error;
-							sign = 1;
-						}
-						else {
-							Py_DECREF(iobj);
-						}
-					}
-				}
-				if (!isnumok) {
-					PyErr_Format(PyExc_TypeError, 
-					    "%%%c format: a number is required, "
-					    "not %.200s", c, Py_TYPE(v)->tp_name);
-					goto error;
-				}
-				if (flags & F_ZERO)
-					fill = '0';
-				break;
-			case 'e':
-			case 'E':
-			case 'f':
-			case 'F':
-			case 'g':
-			case 'G':
-				if (c == 'F')
-					c = 'f';
-				pbuf = formatbuf;
-				len = formatfloat(pbuf, sizeof(formatbuf),
-						  flags, prec, c, v);
-				if (len < 0)
-					goto error;
-				sign = 1;
-				if (flags & F_ZERO)
-					fill = '0';
-				break;
-			case 'c':
-#ifdef Py_USING_UNICODE
-				if (PyUnicode_Check(v)) {
-					fmt = fmt_start;
-					argidx = argidx_start;
-					goto unicode;
-				}
-#endif
-				pbuf = formatbuf;
-				len = formatchar(pbuf, sizeof(formatbuf), v);
-				if (len < 0)
-					goto error;
-				break;
-			default:
-				PyErr_Format(PyExc_ValueError,
-				  "unsupported format character '%c' (0x%x) "
-				  "at index %zd",
-				  c, c,
-				  (Py_ssize_t)(fmt - 1 -
-					       PyString_AsString(format)));
-				goto error;
-			}
-			if (sign) {
-				if (*pbuf == '-' || *pbuf == '+') {
-					sign = *pbuf++;
-					len--;
-				}
-				else if (flags & F_SIGN)
-					sign = '+';
-				else if (flags & F_BLANK)
-					sign = ' ';
-				else
-					sign = 0;
-			}
-			if (width < len)
-				width = len;
-			if (rescnt - (sign != 0) < width) {
-				reslen -= rescnt;
-				rescnt = width + fmtcnt + 100;
-				reslen += rescnt;
-				if (reslen < 0) {
-					Py_DECREF(result);
-					Py_XDECREF(temp);
-					return PyErr_NoMemory();
-				}
-				if (_PyString_Resize(&result, reslen) < 0) {
-					Py_XDECREF(temp);
-					return NULL;
-				}
-				res = PyString_AS_STRING(result)
-					+ reslen - rescnt;
-			}
-			if (sign) {
-				if (fill != ' ')
-					*res++ = sign;
-				rescnt--;
-				if (width > len)
-					width--;
-			}
-			if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
-				assert(pbuf[0] == '0');
-				assert(pbuf[1] == c);
-				if (fill != ' ') {
-					*res++ = *pbuf++;
-					*res++ = *pbuf++;
-				}
-				rescnt -= 2;
-				width -= 2;
-				if (width < 0)
-					width = 0;
-				len -= 2;
-			}
-			if (width > len && !(flags & F_LJUST)) {
-				do {
-					--rescnt;
-					*res++ = fill;
-				} while (--width > len);
-			}
-			if (fill == ' ') {
-				if (sign)
-					*res++ = sign;
-				if ((flags & F_ALT) &&
-				    (c == 'x' || c == 'X')) {
-					assert(pbuf[0] == '0');
-					assert(pbuf[1] == c);
-					*res++ = *pbuf++;
-					*res++ = *pbuf++;
-				}
-			}
-			Py_MEMCPY(res, pbuf, len);
-			res += len;
-			rescnt -= len;
-			while (--width >= len) {
-				--rescnt;
-				*res++ = ' ';
-			}
-                        if (dict && (argidx < arglen) && c != '%') {
-                                PyErr_SetString(PyExc_TypeError,
-                                           "not all arguments converted during string formatting");
-                                Py_XDECREF(temp);
-                                goto error;
-                        }
-			Py_XDECREF(temp);
-		} /* '%' */
-	} /* until end */
-	if (argidx < arglen && !dict) {
-		PyErr_SetString(PyExc_TypeError,
-				"not all arguments converted during string formatting");
-		goto error;
-	}
-	if (args_owned) {
-		Py_DECREF(args);
-	}
-	_PyString_Resize(&result, reslen - rescnt);
-	return result;
-
-#ifdef Py_USING_UNICODE
- unicode:
-	if (args_owned) {
-		Py_DECREF(args);
-		args_owned = 0;
-	}
-	/* Fiddle args right (remove the first argidx arguments) */
-	if (PyTuple_Check(orig_args) && argidx > 0) {
-		PyObject *v;
-		Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
-		v = PyTuple_New(n);
-		if (v == NULL)
-			goto error;
-		while (--n >= 0) {
-			PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
-			Py_INCREF(w);
-			PyTuple_SET_ITEM(v, n, w);
-		}
-		args = v;
-	} else {
-		Py_INCREF(orig_args);
-		args = orig_args;
-	}
-	args_owned = 1;
-	/* Take what we have of the result and let the Unicode formatting
-	   function format the rest of the input. */
-	rescnt = res - PyString_AS_STRING(result);
-	if (_PyString_Resize(&result, rescnt))
-		goto error;
-	fmtcnt = PyString_GET_SIZE(format) - \
-		 (fmt - PyString_AS_STRING(format));
-	format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
-	if (format == NULL)
-		goto error;
-	v = PyUnicode_Format(format, args);
-	Py_DECREF(format);
-	if (v == NULL)
-		goto error;
-	/* Paste what we have (result) to what the Unicode formatting
-	   function returned (v) and return the result (or error) */
-	w = PyUnicode_Concat(result, v);
-	Py_DECREF(result);
-	Py_DECREF(v);
-	Py_DECREF(args);
-	return w;
-#endif /* Py_USING_UNICODE */
-
- error:
-	Py_DECREF(result);
-	if (args_owned) {
-		Py_DECREF(args);
-	}
-	return NULL;
-}
-
-void
-PyString_InternInPlace(PyObject **p)
-{
-	register PyStringObject *s = (PyStringObject *)(*p);
-	PyObject *t;
-	if (s == NULL || !PyString_Check(s))
-		Py_FatalError("PyString_InternInPlace: strings only please!");
-	/* If it's a string subclass, we don't really know what putting
-	   it in the interned dict might do. */
-	if (!PyString_CheckExact(s))
-		return;
-	if (PyString_CHECK_INTERNED(s))
-		return;
-	if (interned == NULL) {
-		interned = PyDict_New();
-		if (interned == NULL) {
-			PyErr_Clear(); /* Don't leave an exception */
-			return;
-		}
-	}
-	t = PyDict_GetItem(interned, (PyObject *)s);
-	if (t) {
-		Py_INCREF(t);
-		Py_DECREF(*p);
-		*p = t;
-		return;
-	}
-
-	if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
-		PyErr_Clear();
-		return;
-	}
-	/* The two references in interned are not counted by refcnt.
-	   The string deallocator will take care of this */
-	Py_REFCNT(s) -= 2;
-	PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
-}
-
-void
-PyString_InternImmortal(PyObject **p)
-{
-	PyString_InternInPlace(p);
-	if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
-		PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
-		Py_INCREF(*p);
-	}
-}
-
-
-PyObject *
-PyString_InternFromString(const char *cp)
-{
-	PyObject *s = PyString_FromString(cp);
-	if (s == NULL)
-		return NULL;
-	PyString_InternInPlace(&s);
-	return s;
-}
-
-void
-PyString_Fini(void)
-{
-	int i;
-	for (i = 0; i < UCHAR_MAX + 1; i++) {
-		Py_XDECREF(characters[i]);
-		characters[i] = NULL;
-	}
-	Py_XDECREF(nullstring);
-	nullstring = NULL;
-}
-
-void _Py_ReleaseInternedStrings(void)
-{
-	PyObject *keys;
-	PyStringObject *s;
-	Py_ssize_t i, n;
-	Py_ssize_t immortal_size = 0, mortal_size = 0;
-
-	if (interned == NULL || !PyDict_Check(interned))
-		return;
-	keys = PyDict_Keys(interned);
-	if (keys == NULL || !PyList_Check(keys)) {
-		PyErr_Clear();
-		return;
-	}
-
-	/* Since _Py_ReleaseInternedStrings() is intended to help a leak
-	   detector, interned strings are not forcibly deallocated; rather, we
-	   give them their stolen references back, and then clear and DECREF
-	   the interned dict. */
-
-	n = PyList_GET_SIZE(keys);
-	fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
-		n);
-	for (i = 0; i < n; i++) {
-		s = (PyStringObject *) PyList_GET_ITEM(keys, i);
-		switch (s->ob_sstate) {
-		case SSTATE_NOT_INTERNED:
-			/* XXX Shouldn't happen */
-			break;
-		case SSTATE_INTERNED_IMMORTAL:
-			Py_REFCNT(s) += 1;
-			immortal_size += Py_SIZE(s);
-			break;
-		case SSTATE_INTERNED_MORTAL:
-			Py_REFCNT(s) += 2;
-			mortal_size += Py_SIZE(s);
-			break;
-		default:
-			Py_FatalError("Inconsistent interned string state.");
-		}
-		s->ob_sstate = SSTATE_NOT_INTERNED;
-	}
-	fprintf(stderr, "total size of all interned strings: "
-			"%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
-			"mortal/immortal\n", mortal_size, immortal_size);
-	Py_DECREF(keys);
-	PyDict_Clear(interned);
-	Py_DECREF(interned);
-	interned = NULL;
-}

Modified: python/branches/okkoto-sizeof/Objects/structseq.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/structseq.c	(original)
+++ python/branches/okkoto-sizeof/Objects/structseq.c	Wed Jun  4 11:24:23 2008
@@ -270,7 +270,7 @@
 			Py_DECREF(tup);
 			return NULL;
 		}
-		crepr = PyString_AsString(repr);
+		crepr = PyBytes_AsString(repr);
 		if (crepr == NULL) {
 			Py_DECREF(tup);
 			Py_DECREF(repr);
@@ -306,7 +306,7 @@
 	*pbuf++ = ')';
 	*pbuf = '\0';
 
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static PyObject *

Modified: python/branches/okkoto-sizeof/Objects/tupleobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/tupleobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/tupleobject.c	Wed Jun  4 11:24:23 2008
@@ -218,7 +218,7 @@
 
 	n = Py_SIZE(v);
 	if (n == 0)
-		return PyString_FromString("()");
+		return PyBytes_FromString("()");
 
 	/* While not mutable, it is still possible to end up with a cycle in a
 	   tuple through an object that stores itself within a tuple (and thus
@@ -226,7 +226,7 @@
 	   possible within a type. */
 	i = Py_ReprEnter((PyObject *)v);
 	if (i != 0) {
-		return i > 0 ? PyString_FromString("(...)") : NULL;
+		return i > 0 ? PyBytes_FromString("(...)") : NULL;
 	}
 
 	pieces = PyTuple_New(n);
@@ -246,29 +246,29 @@
 
 	/* Add "()" decorations to the first and last items. */
 	assert(n > 0);
-	s = PyString_FromString("(");
+	s = PyBytes_FromString("(");
 	if (s == NULL)
 		goto Done;
 	temp = PyTuple_GET_ITEM(pieces, 0);
-	PyString_ConcatAndDel(&s, temp);
+	PyBytes_ConcatAndDel(&s, temp);
 	PyTuple_SET_ITEM(pieces, 0, s);
 	if (s == NULL)
 		goto Done;
 
-	s = PyString_FromString(n == 1 ? ",)" : ")");
+	s = PyBytes_FromString(n == 1 ? ",)" : ")");
 	if (s == NULL)
 		goto Done;
 	temp = PyTuple_GET_ITEM(pieces, n-1);
-	PyString_ConcatAndDel(&temp, s);
+	PyBytes_ConcatAndDel(&temp, s);
 	PyTuple_SET_ITEM(pieces, n-1, temp);
 	if (temp == NULL)
 		goto Done;
 
 	/* Paste them all together with ", " between. */
-	s = PyString_FromString(", ");
+	s = PyBytes_FromString(", ");
 	if (s == NULL)
 		goto Done;
-	result = _PyString_Join(s, pieces);
+	result = _PyBytes_Join(s, pieces);
 	Py_DECREF(s);	
 
 Done:

Modified: python/branches/okkoto-sizeof/Objects/typeobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/typeobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/typeobject.c	Wed Jun  4 11:24:23 2008
@@ -19,10 +19,10 @@
 		 >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
 #define MCACHE_HASH_METHOD(type, name)                                  \
 		MCACHE_HASH((type)->tp_version_tag,                     \
-		            ((PyStringObject *)(name))->ob_shash)
+		            ((PyBytesObject *)(name))->ob_shash)
 #define MCACHE_CACHEABLE_NAME(name)                                     \
-		PyString_CheckExact(name) &&                            \
-		PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
+		PyBytes_CheckExact(name) &&                            \
+		PyBytes_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
 
 struct method_cache_entry {
 	unsigned int version;
@@ -32,7 +32,6 @@
 
 static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
 static unsigned int next_version_tag = 0;
-static void type_modified(PyTypeObject *);
 
 unsigned int
 PyType_ClearCache(void)
@@ -47,12 +46,12 @@
 	}
 	next_version_tag = 0;
 	/* mark all version tags as invalid */
-	type_modified(&PyBaseObject_Type);
+	PyType_Modified(&PyBaseObject_Type);
 	return cur_version_tag;
 }
 
-static void
-type_modified(PyTypeObject *type)
+void
+PyType_Modified(PyTypeObject *type)
 {
 	/* Invalidate any cached data for the specified type and all
 	   subclasses.  This function is called after the base
@@ -86,7 +85,7 @@
 			ref = PyList_GET_ITEM(raw, i);
 			ref = PyWeakref_GET_OBJECT(ref);
 			if (ref != Py_None) {
-				type_modified((PyTypeObject *)ref);
+				PyType_Modified((PyTypeObject *)ref);
 			}
 		}
 	}
@@ -172,7 +171,7 @@
 			Py_INCREF(Py_None);
 		}
 		/* mark all version tags as invalid */
-		type_modified(&PyBaseObject_Type);
+		PyType_Modified(&PyBaseObject_Type);
 		return 1;
 	}
 	bases = type->tp_bases;
@@ -218,7 +217,7 @@
 			s = type->tp_name;
 		else
 			s++;
-		return PyString_FromString(s);
+		return PyBytes_FromString(s);
 	}
 }
 
@@ -237,14 +236,14 @@
 			     "can't delete %s.__name__", type->tp_name);
 		return -1;
 	}
-	if (!PyString_Check(value)) {
+	if (!PyBytes_Check(value)) {
 		PyErr_Format(PyExc_TypeError,
 			     "can only assign string to %s.__name__, not '%s'",
 			     type->tp_name, Py_TYPE(value)->tp_name);
 		return -1;
 	}
-	if (strlen(PyString_AS_STRING(value))
-	    != (size_t)PyString_GET_SIZE(value)) {
+	if (strlen(PyBytes_AS_STRING(value))
+	    != (size_t)PyBytes_GET_SIZE(value)) {
 		PyErr_Format(PyExc_ValueError,
 			     "__name__ must not contain null bytes");
 		return -1;
@@ -257,7 +256,7 @@
 	Py_DECREF(et->ht_name);
 	et->ht_name = value;
 
-	type->tp_name = PyString_AS_STRING(value);
+	type->tp_name = PyBytes_AS_STRING(value);
 
 	return 0;
 }
@@ -280,9 +279,9 @@
 	else {
 		s = strrchr(type->tp_name, '.');
 		if (s != NULL)
-			return PyString_FromStringAndSize(
+			return PyBytes_FromStringAndSize(
 			    type->tp_name, (Py_ssize_t)(s - type->tp_name));
-		return PyString_FromString("__builtin__");
+		return PyBytes_FromString("__builtin__");
 	}
 }
 
@@ -300,7 +299,7 @@
 		return -1;
 	}
 
-	type_modified(type);
+	PyType_Modified(type);
 
 	return PyDict_SetItemString(type->tp_dict, "__module__", value);
 }
@@ -328,7 +327,7 @@
 	int res = PyDict_SetItemString(type->tp_dict,
 				       "__abstractmethods__", value);
 	if (res == 0) {
-		type_modified(type);
+		PyType_Modified(type);
 		if (value && PyObject_IsTrue(value)) {
 			type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
 		}
@@ -556,7 +555,7 @@
 {
 	PyObject *result;
 	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
-		return PyString_FromString(type->tp_doc);
+		return PyBytes_FromString(type->tp_doc);
 	result = PyDict_GetItemString(type->tp_dict, "__doc__");
 	if (result == NULL) {
 		result = Py_None;
@@ -645,7 +644,7 @@
 	mod = type_module(type, NULL);
 	if (mod == NULL)
 		PyErr_Clear();
-	else if (!PyString_Check(mod)) {
+	else if (!PyBytes_Check(mod)) {
 		Py_DECREF(mod);
 		mod = NULL;
 	}
@@ -658,14 +657,14 @@
 	else
 		kind = "type";
 
-	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
-		rtn = PyString_FromFormat("<%s '%s.%s'>",
+	if (mod != NULL && strcmp(PyBytes_AS_STRING(mod), "__builtin__")) {
+		rtn = PyBytes_FromFormat("<%s '%s.%s'>",
 					  kind,
-					  PyString_AS_STRING(mod),
-					  PyString_AS_STRING(name));
+					  PyBytes_AS_STRING(mod),
+					  PyBytes_AS_STRING(name));
 	}
 	else
-		rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
+		rtn = PyBytes_FromFormat("<%s '%s'>", kind, type->tp_name);
 
 	Py_XDECREF(mod);
 	Py_DECREF(name);
@@ -1137,7 +1136,7 @@
 	PyObject *res;
 
 	if (*attrobj == NULL) {
-		*attrobj = PyString_InternFromString(attrstr);
+		*attrobj = PyBytes_InternFromString(attrstr);
 		if (*attrobj == NULL)
 			return NULL;
 	}
@@ -1329,7 +1328,7 @@
 	}
 	if (name == NULL)
 		return NULL;
-	if (!PyString_Check(name)) {
+	if (!PyBytes_Check(name)) {
 		Py_DECREF(name);
 		return NULL;
 	}
@@ -1351,7 +1350,7 @@
 				o = class_name(o);
 				PyErr_Format(PyExc_TypeError,
 					     "duplicate base class %s",
-					     o ? PyString_AS_STRING(o) : "?");
+					     o ? PyBytes_AS_STRING(o) : "?");
 				Py_XDECREF(o);
 				return -1;
 			}
@@ -1397,7 +1396,7 @@
 	while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
 		PyObject *name = class_name(k);
 		off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
-				     name ? PyString_AS_STRING(name) : "?");
+				     name ? PyBytes_AS_STRING(name) : "?");
 		Py_XDECREF(name);
 		if (--n && (size_t)(off+1) < sizeof(buf)) {
 			buf[off++] = ',';
@@ -1621,7 +1620,7 @@
 	   from the custom MRO */
 	type_mro_modified(type, type->tp_bases);
 
-	type_modified(type);
+	PyType_Modified(type);
 
 	return 0;
 }
@@ -1750,7 +1749,7 @@
 	PyObject *descr;
 
 	if (dict_str == NULL) {
-		dict_str = PyString_InternFromString("__dict__");
+		dict_str = PyBytes_InternFromString("__dict__");
 		if (dict_str == NULL)
 			return NULL;
 	}
@@ -1899,14 +1898,14 @@
 	unsigned char *p;
 	Py_ssize_t i, n;
 
-	if (!PyString_Check(s)) {
+	if (!PyBytes_Check(s)) {
 		PyErr_Format(PyExc_TypeError,
 			     "__slots__ items must be strings, not '%.200s'",
 			     Py_TYPE(s)->tp_name);
 		return 0;
 	}
-	p = (unsigned char *) PyString_AS_STRING(s);
-	n = PyString_GET_SIZE(s);
+	p = (unsigned char *) PyBytes_AS_STRING(s);
+	n = PyBytes_GET_SIZE(s);
 	/* We must reject an empty name.  As a hack, we bump the
 	   length to 1 so that the loop will balk on the trailing \0. */
 	if (n == 0)
@@ -2108,7 +2107,7 @@
 		/* Have slots */
 
 		/* Make it into a tuple */
-		if (PyString_Check(slots) || PyUnicode_Check(slots))
+		if (PyBytes_Check(slots) || PyUnicode_Check(slots))
 			slots = PyTuple_Pack(1, slots);
 		else
 			slots = PySequence_Tuple(slots);
@@ -2146,8 +2145,8 @@
 			char *s;
 			if (!valid_identifier(tmp))
 				goto bad_slots;
-			assert(PyString_Check(tmp));
-			s = PyString_AS_STRING(tmp);
+			assert(PyBytes_Check(tmp));
+			s = PyBytes_AS_STRING(tmp);
 			if (strcmp(s, "__dict__") == 0) {
 				if (!may_add_dict || add_dict) {
 					PyErr_SetString(PyExc_TypeError,
@@ -2179,7 +2178,7 @@
 		for (i = j = 0; i < nslots; i++) {
 			char *s;
 			tmp = PyTuple_GET_ITEM(slots, i);
-			s = PyString_AS_STRING(tmp);
+			s = PyBytes_AS_STRING(tmp);
 			if ((add_dict && strcmp(s, "__dict__") == 0) ||
 			    (add_weak && strcmp(s, "__weakref__") == 0))
 				continue;
@@ -2272,7 +2271,7 @@
 	type->tp_as_sequence = &et->as_sequence;
 	type->tp_as_mapping = &et->as_mapping;
 	type->tp_as_buffer = &et->as_buffer;
-	type->tp_name = PyString_AS_STRING(name);
+	type->tp_name = PyBytes_AS_STRING(name);
 
 	/* Set tp_base and tp_bases */
 	type->tp_bases = bases;
@@ -2305,14 +2304,14 @@
 	*/
 	{
 		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
-		if (doc != NULL && PyString_Check(doc)) {
-			const size_t n = (size_t)PyString_GET_SIZE(doc);
+		if (doc != NULL && PyBytes_Check(doc)) {
+			const size_t n = (size_t)PyBytes_GET_SIZE(doc);
 			char *tp_doc = (char *)PyObject_MALLOC(n+1);
 			if (tp_doc == NULL) {
 				Py_DECREF(type);
 				return NULL;
 			}
-			memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
+			memcpy(tp_doc, PyBytes_AS_STRING(doc), n+1);
 			type->tp_doc = tp_doc;
 		}
 	}
@@ -2335,7 +2334,7 @@
 	slotoffset = base->tp_basicsize;
 	if (slots != NULL) {
 		for (i = 0; i < nslots; i++, mp++) {
-			mp->name = PyString_AS_STRING(
+			mp->name = PyBytes_AS_STRING(
 				PyTuple_GET_ITEM(slots, i));
 			mp->type = T_OBJECT_EX;
 			mp->offset = slotoffset;
@@ -2536,7 +2535,7 @@
 	/* Give up */
 	PyErr_Format(PyExc_AttributeError,
 			 "type object '%.50s' has no attribute '%.400s'",
-			 type->tp_name, PyString_AS_STRING(name));
+			 type->tp_name, PyBytes_AS_STRING(name));
 	return NULL;
 }
 
@@ -2855,7 +2854,7 @@
 		if (sorted_methods == NULL)
 			goto error;
 		if (comma == NULL) {
-			comma = PyString_InternFromString(", ");
+			comma = PyBytes_InternFromString(", ");
 			if (comma == NULL)
 				goto error;
 		}
@@ -2863,7 +2862,7 @@
 					     "O",  sorted_methods);
 		if (joined == NULL)
 			goto error;
-		joined_str = PyString_AsString(joined);
+		joined_str = PyBytes_AsString(joined);
 		if (joined_str == NULL)
 			goto error;
 
@@ -2897,20 +2896,20 @@
 	mod = type_module(type, NULL);
 	if (mod == NULL)
 		PyErr_Clear();
-	else if (!PyString_Check(mod)) {
+	else if (!PyBytes_Check(mod)) {
 		Py_DECREF(mod);
 		mod = NULL;
 	}
 	name = type_name(type, NULL);
 	if (name == NULL)
 		return NULL;
-	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
-		rtn = PyString_FromFormat("<%s.%s object at %p>",
-					  PyString_AS_STRING(mod),
-					  PyString_AS_STRING(name),
+	if (mod != NULL && strcmp(PyBytes_AS_STRING(mod), "__builtin__"))
+		rtn = PyBytes_FromFormat("<%s.%s object at %p>",
+					  PyBytes_AS_STRING(mod),
+					  PyBytes_AS_STRING(name),
 					  self);
 	else
-		rtn = PyString_FromFormat("<%s object at %p>",
+		rtn = PyBytes_FromFormat("<%s object at %p>",
 					  type->tp_name, self);
 	Py_XDECREF(mod);
 	Py_DECREF(name);
@@ -3058,7 +3057,7 @@
 
 
 /* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
-   We fall back to helpers in copyreg for:
+   We fall back to helpers in copy_reg for:
    - pickle protocols < 2
    - calculating the list of slot names (done only once per class)
    - the __newobj__ function (which is used as a token but never called)
@@ -3070,7 +3069,7 @@
 	static PyObject *copyreg_str;
 
 	if (!copyreg_str) {
-		copyreg_str = PyString_InternFromString("copyreg");
+		copyreg_str = PyBytes_InternFromString("copy_reg");
 		if (copyreg_str == NULL)
 			return NULL;
 	}
@@ -3376,7 +3375,7 @@
                 return NULL;
 	if (PyUnicode_Check(format_spec)) {
 	        self_as_str = PyObject_Unicode(self);
-	} else if (PyString_Check(format_spec)) {
+	} else if (PyBytes_Check(format_spec)) {
 	        self_as_str = PyObject_Str(self);
 	} else {
 	        PyErr_SetString(PyExc_TypeError, "argument to __format__ must be unicode or str");
@@ -3422,7 +3421,7 @@
         {"__format__", object_format, METH_VARARGS,
          PyDoc_STR("default object formatter")},
         {"__sizeof__", object_sizeof, METH_NOARGS,
-         PyDoc_STR("__sizeof__() -> size of object in bytes")},
+         PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
 	{0}
 };
 
@@ -3635,7 +3634,7 @@
 		type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
 	else if (PyType_IsSubtype(base, &PyLong_Type))
 		type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
-	else if (PyType_IsSubtype(base, &PyString_Type))
+	else if (PyType_IsSubtype(base, &PyBytes_Type))
 		type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
 #ifdef Py_USING_UNICODE
 	else if (PyType_IsSubtype(base, &PyUnicode_Type))
@@ -3974,7 +3973,7 @@
 	 */
 	if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
 		if (type->tp_doc != NULL) {
-			PyObject *doc = PyString_FromString(type->tp_doc);
+			PyObject *doc = PyBytes_FromString(type->tp_doc);
 			if (doc == NULL)
 				goto error;
 			PyDict_SetItemString(type->tp_dict, "__doc__", doc);
@@ -4862,7 +4861,7 @@
 	descrgetfunc f;
 
 	if (getitem_str == NULL) {
-		getitem_str = PyString_InternFromString("__getitem__");
+		getitem_str = PyBytes_InternFromString("__getitem__");
 		if (getitem_str == NULL)
 			return NULL;
 	}
@@ -5230,7 +5229,7 @@
 		return res;
 	}
 	PyErr_Clear();
-	return PyString_FromFormat("<%s object at %p>",
+	return PyBytes_FromFormat("<%s object at %p>",
 				   Py_TYPE(self)->tp_name, self);
 }
 
@@ -5338,13 +5337,13 @@
 	static PyObject *getattr_str = NULL;
 
 	if (getattr_str == NULL) {
-		getattr_str = PyString_InternFromString("__getattr__");
+		getattr_str = PyBytes_InternFromString("__getattr__");
 		if (getattr_str == NULL)
 			return NULL;
 	}
 	if (getattribute_str == NULL) {
 		getattribute_str =
-			PyString_InternFromString("__getattribute__");
+			PyBytes_InternFromString("__getattribute__");
 		if (getattribute_str == NULL)
 			return NULL;
 	}
@@ -5485,7 +5484,7 @@
 	static PyObject *get_str = NULL;
 
 	if (get_str == NULL) {
-		get_str = PyString_InternFromString("__get__");
+		get_str = PyBytes_InternFromString("__get__");
 		if (get_str == NULL)
 			return NULL;
 	}
@@ -5555,7 +5554,7 @@
 	Py_ssize_t i, n;
 
 	if (new_str == NULL) {
-		new_str = PyString_InternFromString("__new__");
+		new_str = PyBytes_InternFromString("__new__");
 		if (new_str == NULL)
 			return NULL;
 	}
@@ -6085,7 +6084,7 @@
 	if (initialized)
 		return;
 	for (p = slotdefs; p->name; p++) {
-		p->name_strobj = PyString_InternFromString(p->name);
+		p->name_strobj = PyBytes_InternFromString(p->name);
 		if (!p->name_strobj)
 			Py_FatalError("Out of memory interning slotdef names");
 	}
@@ -6108,7 +6107,7 @@
 	   update_subclasses() recursion below, but carefully:
 	   they each have their own conditions on which to stop
 	   recursing into subclasses. */
-	type_modified(type);
+	PyType_Modified(type);
 
 	init_slotdefs();
 	pp = ptrs;
@@ -6300,12 +6299,12 @@
 	superobject *su = (superobject *)self;
 
 	if (su->obj_type)
-		return PyString_FromFormat(
+		return PyBytes_FromFormat(
 			"<super: <class '%s'>, <%s object>>",
 			su->type ? su->type->tp_name : "NULL",
 			su->obj_type->tp_name);
 	else
-		return PyString_FromFormat(
+		return PyBytes_FromFormat(
 			"<super: <class '%s'>, NULL>",
 			su->type ? su->type->tp_name : "NULL");
 }
@@ -6319,9 +6318,9 @@
 	if (!skip) {
 		/* We want __class__ to return the class of the super object
 		   (i.e. super, or a subclass), not the class of su->obj. */
-		skip = (PyString_Check(name) &&
-			PyString_GET_SIZE(name) == 9 &&
-			strcmp(PyString_AS_STRING(name), "__class__") == 0);
+		skip = (PyBytes_Check(name) &&
+			PyBytes_GET_SIZE(name) == 9 &&
+			strcmp(PyBytes_AS_STRING(name), "__class__") == 0);
 	}
 
 	if (!skip) {
@@ -6413,7 +6412,7 @@
 		PyObject *class_attr;
 
 		if (class_str == NULL) {
-			class_str = PyString_FromString("__class__");
+			class_str = PyBytes_FromString("__class__");
 			if (class_str == NULL)
 				return NULL;
 		}

Modified: python/branches/okkoto-sizeof/Objects/unicodeobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/unicodeobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/unicodeobject.c	Wed Jun  4 11:24:23 2008
@@ -42,8 +42,6 @@
 #define PY_SSIZE_T_CLEAN
 #include "Python.h"
 
-#include "formatter_unicode.h"
-
 #include "unicodeobject.h"
 #include "ucnhash.h"
 
@@ -1080,11 +1078,11 @@
 #endif
 
     /* Coerce object */
-    if (PyString_Check(obj)) {
-	    s = PyString_AS_STRING(obj);
-	    len = PyString_GET_SIZE(obj);
+    if (PyBytes_Check(obj)) {
+	    s = PyBytes_AS_STRING(obj);
+	    len = PyBytes_GET_SIZE(obj);
     }
-    else if (PyBytes_Check(obj)) {
+    else if (PyByteArray_Check(obj)) {
         /* Python 2.x specific */
         PyErr_Format(PyExc_TypeError,
                      "decoding bytearray is not supported");
@@ -1254,7 +1252,7 @@
     v = PyCodec_Encode(unicode, encoding, errors);
     if (v == NULL)
         goto onError;
-    if (!PyString_Check(v)) {
+    if (!PyBytes_Check(v)) {
         PyErr_Format(PyExc_TypeError,
                      "encoder did not return a string object (type=%.400s)",
                      Py_TYPE(v)->tp_name);
@@ -1654,13 +1652,13 @@
     char * start;
 
     if (size == 0)
-		return PyString_FromStringAndSize(NULL, 0);
+		return PyBytes_FromStringAndSize(NULL, 0);
 
-    v = PyString_FromStringAndSize(NULL, cbAllocated);
+    v = PyBytes_FromStringAndSize(NULL, cbAllocated);
     if (v == NULL)
         return NULL;
 
-    start = out = PyString_AS_STRING(v);
+    start = out = PyBytes_AS_STRING(v);
     for (;i < size; ++i) {
         Py_UNICODE ch = s[i];
 
@@ -1726,7 +1724,7 @@
         *out++ = '-';
     }
 
-    _PyString_Resize(&v, out - start);
+    _PyBytes_Resize(&v, out - start);
     return v;
 }
 
@@ -1991,10 +1989,10 @@
         nallocated = size * 4;
         if (nallocated / 4 != size)  /* overflow! */
             return PyErr_NoMemory();
-        v = PyString_FromStringAndSize(NULL, nallocated);
+        v = PyBytes_FromStringAndSize(NULL, nallocated);
         if (v == NULL)
             return NULL;
-        p = PyString_AS_STRING(v);
+        p = PyBytes_AS_STRING(v);
     }
 
     for (i = 0; i < size;) {
@@ -2042,13 +2040,13 @@
         /* This was stack allocated. */
         nneeded = p - stackbuf;
         assert(nneeded <= nallocated);
-        v = PyString_FromStringAndSize(stackbuf, nneeded);
+        v = PyBytes_FromStringAndSize(stackbuf, nneeded);
     }
     else {
     	/* Cut back to size actually needed. */
-        nneeded = p - PyString_AS_STRING(v);
+        nneeded = p - PyBytes_AS_STRING(v);
         assert(nneeded <= nallocated);
-        _PyString_Resize(&v, nneeded);
+        _PyBytes_Resize(&v, nneeded);
     }
     return v;
 
@@ -2276,12 +2274,12 @@
 	    0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
 	    pairs++;
 #endif
-    v = PyString_FromStringAndSize(NULL,
+    v = PyBytes_FromStringAndSize(NULL,
 		  4 * (size - pairs + (byteorder == 0)));
     if (v == NULL)
         return NULL;
 
-    p = (unsigned char *)PyString_AS_STRING(v);
+    p = (unsigned char *)PyBytes_AS_STRING(v);
     if (byteorder == 0)
 	STORECHAR(0xFEFF);
     if (size == 0)
@@ -2541,12 +2539,12 @@
 	if (s[i] >= 0x10000)
 	    pairs++;
 #endif
-    v = PyString_FromStringAndSize(NULL,
+    v = PyBytes_FromStringAndSize(NULL,
 		  2 * (size + pairs + (byteorder == 0)));
     if (v == NULL)
         return NULL;
 
-    p = (unsigned char *)PyString_AS_STRING(v);
+    p = (unsigned char *)PyBytes_AS_STRING(v);
     if (byteorder == 0)
 	STORECHAR(0xFEFF);
     if (size == 0)
@@ -2889,7 +2887,7 @@
        escape.
     */
 
-    repr = PyString_FromStringAndSize(NULL,
+    repr = PyBytes_FromStringAndSize(NULL,
         2
 #ifdef Py_UNICODE_WIDE
         + 10*size
@@ -2900,7 +2898,7 @@
     if (repr == NULL)
         return NULL;
 
-    p = PyString_AS_STRING(repr);
+    p = PyBytes_AS_STRING(repr);
 
     if (quotes) {
         *p++ = 'u';
@@ -2912,7 +2910,7 @@
 
         /* Escape quotes and backslashes */
         if ((quotes &&
-	     ch == (Py_UNICODE) PyString_AS_STRING(repr)[1]) || ch == '\\') {
+	     ch == (Py_UNICODE) PyBytes_AS_STRING(repr)[1]) || ch == '\\') {
             *p++ = '\\';
             *p++ = (char) ch;
 	    continue;
@@ -2998,10 +2996,10 @@
             *p++ = (char) ch;
     }
     if (quotes)
-        *p++ = PyString_AS_STRING(repr)[1];
+        *p++ = PyBytes_AS_STRING(repr)[1];
 
     *p = '\0';
-    _PyString_Resize(&repr, p - PyString_AS_STRING(repr));
+    _PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr));
     return repr;
 }
 
@@ -3150,16 +3148,16 @@
     static const char *hexdigit = "0123456789abcdef";
 
 #ifdef Py_UNICODE_WIDE
-    repr = PyString_FromStringAndSize(NULL, 10 * size);
+    repr = PyBytes_FromStringAndSize(NULL, 10 * size);
 #else
-    repr = PyString_FromStringAndSize(NULL, 6 * size);
+    repr = PyBytes_FromStringAndSize(NULL, 6 * size);
 #endif
     if (repr == NULL)
         return NULL;
     if (size == 0)
 	return repr;
 
-    p = q = PyString_AS_STRING(repr);
+    p = q = PyBytes_AS_STRING(repr);
     while (size-- > 0) {
         Py_UNICODE ch = *s++;
 #ifdef Py_UNICODE_WIDE
@@ -3218,7 +3216,7 @@
             *p++ = (char) ch;
     }
     *p = '\0';
-    _PyString_Resize(&repr, p - q);
+    _PyBytes_Resize(&repr, p - q);
     return repr;
 }
 
@@ -3458,12 +3456,12 @@
 
     /* allocate enough for a simple encoding without
        replacements, if we need more, we'll resize */
-    res = PyString_FromStringAndSize(NULL, size);
+    res = PyBytes_FromStringAndSize(NULL, size);
     if (res == NULL)
         goto onError;
     if (size == 0)
 	return res;
-    str = PyString_AS_STRING(res);
+    str = PyBytes_AS_STRING(res);
     ressize = size;
 
     while (p<endp) {
@@ -3513,7 +3511,7 @@
 		    p = collend;
 		    break;
 		case 4: /* xmlcharrefreplace */
-		    respos = str-PyString_AS_STRING(res);
+		    respos = str-PyBytes_AS_STRING(res);
 		    /* determine replacement size (temporarily (mis)uses p) */
 		    for (p = collstart, repsize = 0; p < collend; ++p) {
 			if (*p<10)
@@ -3540,9 +3538,9 @@
 		    if (requiredsize > ressize) {
 			if (requiredsize<2*ressize)
 			    requiredsize = 2*ressize;
-			if (_PyString_Resize(&res, requiredsize))
+			if (_PyBytes_Resize(&res, requiredsize))
 			    goto onError;
-			str = PyString_AS_STRING(res) + respos;
+			str = PyBytes_AS_STRING(res) + respos;
 			ressize = requiredsize;
 		    }
 		    /* generate replacement (temporarily (mis)uses p) */
@@ -3560,17 +3558,17 @@
 		    /* need more space? (at least enough for what we
 		       have+the replacement+the rest of the string, so
 		       we won't have to check space for encodable characters) */
-		    respos = str-PyString_AS_STRING(res);
+		    respos = str-PyBytes_AS_STRING(res);
 		    repsize = PyUnicode_GET_SIZE(repunicode);
 		    requiredsize = respos+repsize+(endp-collend);
 		    if (requiredsize > ressize) {
 			if (requiredsize<2*ressize)
 			    requiredsize = 2*ressize;
-			if (_PyString_Resize(&res, requiredsize)) {
+			if (_PyBytes_Resize(&res, requiredsize)) {
 			    Py_DECREF(repunicode);
 			    goto onError;
 			}
-			str = PyString_AS_STRING(res) + respos;
+			str = PyBytes_AS_STRING(res) + respos;
 			ressize = requiredsize;
 		    }
 		    /* check if there is anything unencodable in the replacement
@@ -3591,10 +3589,10 @@
 	}
     }
     /* Resize if we allocated to much */
-    respos = str-PyString_AS_STRING(res);
+    respos = str-PyBytes_AS_STRING(res);
     if (respos<ressize)
        /* If this falls res will be NULL */
-	_PyString_Resize(&res, respos);
+	_PyBytes_Resize(&res, respos);
     Py_XDECREF(errorHandler);
     Py_XDECREF(exc);
     return res;
@@ -3671,7 +3669,7 @@
 		goto onError;
 	}
     }
-    if (p - PyUnicode_AS_UNICODE(v) < PyString_GET_SIZE(v))
+    if (p - PyUnicode_AS_UNICODE(v) < PyBytes_GET_SIZE(v))
 	if (_PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
 	    goto onError;
     Py_XDECREF(errorHandler);
@@ -3849,20 +3847,20 @@
 
     if (*repr == NULL) {
 	/* Create string object */
-	*repr = PyString_FromStringAndSize(NULL, mbcssize);
+	*repr = PyBytes_FromStringAndSize(NULL, mbcssize);
 	if (*repr == NULL)
 	    return -1;
     }
     else {
 	/* Extend string object */
-	n = PyString_Size(*repr);
-	if (_PyString_Resize(repr, n + mbcssize) < 0)
+	n = PyBytes_Size(*repr);
+	if (_PyBytes_Resize(repr, n + mbcssize) < 0)
 	    return -1;
     }
 
     /* Do the conversion */
     if (size > 0) {
-	char *s = PyString_AS_STRING(*repr) + n;
+	char *s = PyBytes_AS_STRING(*repr) + n;
 	if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
 	    PyErr_SetFromWindowsErrWithFilename(0, NULL);
 	    return -1;
@@ -4329,7 +4327,7 @@
 	}
 	return x;
     }
-    else if (PyString_Check(x))
+    else if (PyBytes_Check(x))
 	return x;
     else {
 	/* wrong return value */
@@ -4343,11 +4341,11 @@
 static int
 charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
 {
-	Py_ssize_t outsize = PyString_GET_SIZE(*outobj);
+	Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
 	/* exponentially overallocate to minimize reallocations */
 	if (requiredsize < 2*outsize)
 	    requiredsize = 2*outsize;
-	if (_PyString_Resize(outobj, requiredsize)) {
+	if (_PyBytes_Resize(outobj, requiredsize)) {
 	    return 0;
 	}
 	return 1;
@@ -4368,7 +4366,7 @@
 {
     PyObject *rep;
     char *outstart;
-    Py_ssize_t outsize = PyString_GET_SIZE(*outobj);
+    Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
 
     if (Py_TYPE(mapping) == &EncodingMapType) {
         int res = encoding_map_lookup(c, mapping);
@@ -4378,7 +4376,7 @@
 	if (outsize<requiredsize) 
 	    if (!charmapencode_resize(outobj, outpos, requiredsize))
 		return enc_EXCEPTION;
-        outstart = PyString_AS_STRING(*outobj);
+        outstart = PyBytes_AS_STRING(*outobj);
 	outstart[(*outpos)++] = (char)res;
 	return enc_SUCCESS;
     }
@@ -4397,19 +4395,19 @@
 		    Py_DECREF(rep);
 		    return enc_EXCEPTION;
 		}
-            outstart = PyString_AS_STRING(*outobj);
+            outstart = PyBytes_AS_STRING(*outobj);
 	    outstart[(*outpos)++] = (char)PyInt_AS_LONG(rep);
 	}
 	else {
-	    const char *repchars = PyString_AS_STRING(rep);
-	    Py_ssize_t repsize = PyString_GET_SIZE(rep);
+	    const char *repchars = PyBytes_AS_STRING(rep);
+	    Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
 	    Py_ssize_t requiredsize = *outpos+repsize;
 	    if (outsize<requiredsize)
 		if (!charmapencode_resize(outobj, outpos, requiredsize)) {
 		    Py_DECREF(rep);
 		    return enc_EXCEPTION;
 		}
-            outstart = PyString_AS_STRING(*outobj);
+            outstart = PyBytes_AS_STRING(*outobj);
 	    memcpy(outstart + *outpos, repchars, repsize);
 	    *outpos += repsize;
 	}
@@ -4560,7 +4558,7 @@
 
     /* allocate enough for a simple encoding without
        replacements, if we need more, we'll resize */
-    res = PyString_FromStringAndSize(NULL, size);
+    res = PyBytes_FromStringAndSize(NULL, size);
     if (res == NULL)
         goto onError;
     if (size == 0)
@@ -4585,8 +4583,8 @@
     }
 
     /* Resize if we allocated to much */
-    if (respos<PyString_GET_SIZE(res)) {
-	if (_PyString_Resize(&res, respos))
+    if (respos<PyBytes_GET_SIZE(res)) {
+	if (_PyBytes_Resize(&res, respos))
 	    goto onError;
     }
     Py_XDECREF(exc);
@@ -5484,7 +5482,7 @@
 
 	item = PySequence_Fast_GET_ITEM(fseq, i);
 	/* Convert item to Unicode. */
-	if (! PyUnicode_Check(item) && ! PyString_Check(item)) {
+	if (! PyUnicode_Check(item) && ! PyBytes_Check(item)) {
 	    PyErr_Format(PyExc_TypeError,
 			 "sequence item %zd: expected string or Unicode,"
 			 " %.80s found",
@@ -6488,7 +6486,7 @@
     v = PyUnicode_AsEncodedObject((PyObject *)self, encoding, errors);
     if (v == NULL)
         goto onError;
-    if (!PyString_Check(v) && !PyUnicode_Check(v)) {
+    if (!PyBytes_Check(v) && !PyUnicode_Check(v)) {
         PyErr_Format(PyExc_TypeError,
                      "encoder did not return a string/unicode object "
                      "(type=%.400s)",
@@ -6524,7 +6522,7 @@
     v = PyUnicode_AsDecodedObject((PyObject *)self, encoding, errors);
     if (v == NULL)
         goto onError;
-    if (!PyString_Check(v) && !PyUnicode_Check(v)) {
+    if (!PyBytes_Check(v) && !PyUnicode_Check(v)) {
         PyErr_Format(PyExc_TypeError,
                      "decoder did not return a string/unicode object "
                      "(type=%.400s)",
@@ -7154,7 +7152,7 @@
 	if (sep != NULL && sep != Py_None) {
 		if (PyUnicode_Check(sep))
 			return _PyUnicode_XStrip(self, striptype, sep);
-		else if (PyString_Check(sep)) {
+		else if (PyBytes_Check(sep)) {
 			PyObject *res;
 			sep = PyUnicode_FromObject(sep);
 			if (sep==NULL)
@@ -7318,11 +7316,11 @@
 }
 
 PyDoc_STRVAR(replace__doc__,
-"S.replace (old, new[, maxsplit]) -> unicode\n\
+"S.replace (old, new[, count]) -> unicode\n\
 \n\
 Return a copy of S with all occurrences of substring\n\
-old replaced by new.  If the optional argument maxsplit is\n\
-given, only the first maxsplit occurrences are replaced.");
+old replaced by new.  If the optional argument count is\n\
+given, only the first count occurrences are replaced.");
 
 static PyObject*
 unicode_replace(PyUnicodeObject *self, PyObject *args)
@@ -7863,6 +7861,35 @@
 \n\
 ");
 
+static PyObject *
+unicode__format__(PyObject *self, PyObject *args)
+{
+    PyObject *format_spec;
+    PyObject *result = NULL;
+    PyObject *tmp = NULL;
+
+    /* If 2.x, convert format_spec to the same type as value */
+    /* This is to allow things like u''.format('') */
+    if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
+        goto done;
+    if (!(PyBytes_Check(format_spec) || PyUnicode_Check(format_spec))) {
+        PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
+		     "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
+        goto done;
+    }
+    tmp = PyObject_Unicode(format_spec);
+    if (tmp == NULL)
+        goto done;
+    format_spec = tmp;
+
+    result = _PyUnicode_FormatAdvanced(self,
+                                       PyUnicode_AS_UNICODE(format_spec),
+                                       PyUnicode_GET_SIZE(format_spec));
+done:
+    Py_XDECREF(tmp);
+    return result;
+}
+
 PyDoc_STRVAR(p_format__doc__,
 "S.__format__(format_spec) -> unicode\n\
 \n\
@@ -8071,8 +8098,8 @@
     str = _PyUnicode_AsDefaultEncodedString((PyObject *)self, NULL);
     if (str == NULL)
 	return -1;
-    *ptr = (void *) PyString_AS_STRING(str);
-    return PyString_GET_SIZE(str);
+    *ptr = (void *) PyBytes_AS_STRING(str);
+    return PyBytes_GET_SIZE(str);
 }
 
 /* Helpers for PyUnicode_Format() */
@@ -8191,7 +8218,7 @@
 	PyObject *str; /* temporary string object. */
 	PyUnicodeObject *result;
 
-	str = _PyString_FormatLong(val, flags, prec, type, &buf, &len);
+	str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
 	if (!str)
 		return NULL;
 	result = _PyUnicode_New(len);
@@ -8293,10 +8320,10 @@
 	buf[0] = PyUnicode_AS_UNICODE(v)[0];
     }
 
-    else if (PyString_Check(v)) {
-	if (PyString_GET_SIZE(v) != 1)
+    else if (PyBytes_Check(v)) {
+	if (PyBytes_GET_SIZE(v) != 1)
 	    goto onError;
-	buf[0] = (Py_UNICODE)PyString_AS_STRING(v)[0];
+	buf[0] = (Py_UNICODE)PyBytes_AS_STRING(v)[0];
     }
 
     else {
@@ -8579,10 +8606,10 @@
 			goto onError;
                     if (PyUnicode_Check(temp))
                         /* nothing to do */;
-                    else if (PyString_Check(temp)) {
+                    else if (PyBytes_Check(temp)) {
                         /* convert to string to Unicode */
-		        unicode = PyUnicode_Decode(PyString_AS_STRING(temp),
-						   PyString_GET_SIZE(temp),
+		        unicode = PyUnicode_Decode(PyBytes_AS_STRING(temp),
+						   PyBytes_GET_SIZE(temp),
 						   NULL,
 						   "strict");
 		        Py_DECREF(temp);

Modified: python/branches/okkoto-sizeof/Objects/weakrefobject.c
==============================================================================
--- python/branches/okkoto-sizeof/Objects/weakrefobject.c	(original)
+++ python/branches/okkoto-sizeof/Objects/weakrefobject.c	Wed Jun  4 11:24:23 2008
@@ -166,8 +166,8 @@
 						   "__name__");
 	if (nameobj == NULL)
 		PyErr_Clear();
-	else if (PyString_Check(nameobj))
-		name = PyString_AS_STRING(nameobj);
+	else if (PyBytes_Check(nameobj))
+		name = PyBytes_AS_STRING(nameobj);
         PyOS_snprintf(buffer, sizeof(buffer),
 		      name ? "<weakref at %p; to '%.50s' at %p (%s)>"
 		           : "<weakref at %p; to '%.50s' at %p>",
@@ -177,7 +177,7 @@
 		      name);
 	Py_XDECREF(nameobj);
     }
-    return PyString_FromString(buffer);
+    return PyBytes_FromString(buffer);
 }
 
 /* Weak references only support equality, not ordering. Two weak references
@@ -448,7 +448,7 @@
 		  "<weakproxy at %p to %.100s at %p>", proxy,
 		  Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name,
 		  PyWeakref_GET_OBJECT(proxy));
-    return PyString_FromString(buf);
+    return PyBytes_FromString(buf);
 }
 
 
@@ -473,6 +473,8 @@
 WRAP_BINARY(proxy_sub, PyNumber_Subtract)
 WRAP_BINARY(proxy_mul, PyNumber_Multiply)
 WRAP_BINARY(proxy_div, PyNumber_Divide)
+WRAP_BINARY(proxy_floor_div, PyNumber_FloorDivide)
+WRAP_BINARY(proxy_true_div, PyNumber_TrueDivide)
 WRAP_BINARY(proxy_mod, PyNumber_Remainder)
 WRAP_BINARY(proxy_divmod, PyNumber_Divmod)
 WRAP_TERNARY(proxy_pow, PyNumber_Power)
@@ -492,6 +494,8 @@
 WRAP_BINARY(proxy_isub, PyNumber_InPlaceSubtract)
 WRAP_BINARY(proxy_imul, PyNumber_InPlaceMultiply)
 WRAP_BINARY(proxy_idiv, PyNumber_InPlaceDivide)
+WRAP_BINARY(proxy_ifloor_div, PyNumber_InPlaceFloorDivide)
+WRAP_BINARY(proxy_itrue_div, PyNumber_InPlaceTrueDivide)
 WRAP_BINARY(proxy_imod, PyNumber_InPlaceRemainder)
 WRAP_TERNARY(proxy_ipow, PyNumber_InPlacePower)
 WRAP_BINARY(proxy_ilshift, PyNumber_InPlaceLshift)
@@ -499,6 +503,7 @@
 WRAP_BINARY(proxy_iand, PyNumber_InPlaceAnd)
 WRAP_BINARY(proxy_ixor, PyNumber_InPlaceXor)
 WRAP_BINARY(proxy_ior, PyNumber_InPlaceOr)
+WRAP_UNARY(proxy_index, PyNumber_Index)
 
 static int
 proxy_nonzero(PyWeakReference *proxy)
@@ -623,6 +628,11 @@
     proxy_iand,             /*nb_inplace_and*/
     proxy_ixor,             /*nb_inplace_xor*/
     proxy_ior,              /*nb_inplace_or*/
+    proxy_floor_div,        /*nb_floor_divide*/
+    proxy_true_div,         /*nb_true_divide*/
+    proxy_ifloor_div,       /*nb_inplace_floor_divide*/
+    proxy_itrue_div,        /*nb_inplace_true_divide*/
+    proxy_index,            /*nb_index*/
 };
 
 static PySequenceMethods proxy_as_sequence = {

Modified: python/branches/okkoto-sizeof/PC/VC6/pythoncore.dsp
==============================================================================
--- python/branches/okkoto-sizeof/PC/VC6/pythoncore.dsp	(original)
+++ python/branches/okkoto-sizeof/PC/VC6/pythoncore.dsp	Wed Jun  4 11:24:23 2008
@@ -237,6 +237,10 @@
 # End Source File
 # Begin Source File
 
+SOURCE=..\..\Objects\bytearrayobject.c
+# End Source File
+# Begin Source File
+
 SOURCE=..\..\Objects\bytesobject.c
 # End Source File
 # Begin Source File
@@ -643,10 +647,6 @@
 # End Source File
 # Begin Source File
 
-SOURCE=..\..\Objects\stringobject.c
-# End Source File
-# Begin Source File
-
 SOURCE=..\..\Modules\stropmodule.c
 # End Source File
 # Begin Source File

Modified: python/branches/okkoto-sizeof/PC/VS7.1/pythoncore.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS7.1/pythoncore.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS7.1/pythoncore.vcproj	Wed Jun  4 11:24:23 2008
@@ -443,6 +443,9 @@
 			RelativePath="..\..\Objects\bufferobject.c">
 		</File>
 		<File
+			RelativePath="..\..\Objects\bytearrayobject.c">
+		</File>
+		<File
 			RelativePath="..\..\Objects\bytesobject.c">
 		</File>
 		<File
@@ -764,9 +767,6 @@
 			RelativePath="..\..\Objects\sliceobject.c">
 		</File>
 		<File
-			RelativePath="..\..\Objects\stringobject.c">
-		</File>
-		<File
 			RelativePath="..\..\Modules\stropmodule.c">
 		</File>
 		<File

Modified: python/branches/okkoto-sizeof/PC/VS8.0/_bsddb.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/_bsddb.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/_bsddb.vcproj	Wed Jun  4 11:24:23 2008
@@ -42,7 +42,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -52,11 +52,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Debug\libdb44sd.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build Debug /project db_static&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Debug\libdb44sd.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -105,7 +103,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -115,11 +113,11 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Debug_AMD64\libdb44sd.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build &quot;Debug AMD64&quot; /project db_static /useenv&#x0D;&#x0A;"
+				CommandLine=""
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Debug_AMD64\libdb44sd.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -168,7 +166,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -178,11 +176,10 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Release\libdb44s.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build Release /project db_static&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Release\libdb44s.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -232,7 +229,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -242,11 +239,11 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Release_AMD64\libdb44s.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build &quot;Release AMD64&quot; /project db_static /useenv&#x0D;&#x0A;"
+				CommandLine=""
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Release_AMD64\libdb44s.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -295,7 +292,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -305,11 +302,10 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Release\libdb44s.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build Release /project db_static&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Release\libdb44s.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -359,7 +355,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -369,11 +365,10 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Release_AMD64\libdb44s.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build &quot;Release AMD64&quot; /project db_static /useenv&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Release_AMD64\libdb44s.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 				TargetMachine="17"
 			/>
@@ -423,7 +418,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -433,11 +428,10 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Release\libdb44s.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build Release /project db_static&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Release\libdb44s.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -487,7 +481,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="$(bsddbDir)"
+				AdditionalIncludeDirectories="$(bsddbDir),$(bsddbDir)\.."
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -497,11 +491,10 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				CommandLine="cd $(bsddbDir)&#x0D;&#x0A;if exist Release_AMD64\libdb44s.lib exit 0&#x0D;&#x0A;devenv Berkeley_DB.sln /build &quot;Release AMD64&quot; /project db_static /useenv&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(bsddbDir)\Release_AMD64\libdb44s.lib"
+				AdditionalDependencies="$(bsddbDepLibs)"
 				BaseAddress="0x1e180000"
 				TargetMachine="17"
 			/>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/_elementtree.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/_elementtree.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/_elementtree.vcproj	Wed Jun  4 11:24:23 2008
@@ -56,6 +56,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 			/>
 			<Tool
@@ -118,6 +119,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 			/>
 			<Tool
@@ -180,6 +182,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 			/>
 			<Tool
@@ -243,6 +246,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 			/>
 			<Tool
@@ -305,6 +309,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 			/>
 			<Tool
@@ -368,6 +373,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 				TargetMachine="17"
 			/>
@@ -431,6 +437,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 			/>
 			<Tool
@@ -494,6 +501,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				BaseAddress="0x1D100000"
 				TargetMachine="17"
 			/>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/_sqlite3.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/_sqlite3.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/_sqlite3.vcproj	Wed Jun  4 11:24:23 2008
@@ -53,12 +53,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -118,12 +115,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -183,12 +177,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -249,12 +240,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -314,12 +302,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -380,12 +365,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 				TargetMachine="17"
 			/>
@@ -446,12 +428,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 			/>
 			<Tool
@@ -512,12 +491,9 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="Build sqlite3 libs and dll"
-				CommandLine="cd &quot;$(sqlite3Dir)&quot;&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; if exist $(PlatformName)\sqlite3.dll copy $(PlatformName)\sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;if exist $(PlatformName)\sqlite3.lib exit 0&#x0D;&#x0A;if not exist $(PlatformName) mkdir $(PlatformName)&#x0D;&#x0A;cd $(PlatformName)&#x0D;&#x0A;cl /DNO_TCL /Ox /Ob1 /Oi /GL /GF /FD /MD /Gy ..\..\*.c&#x0D;&#x0A;link /INCREMENTAL:NO /NOLOGO /DLL /OPT:REF /OPT:ICF /def:..\..\sqlite3.def  /dll /out:sqlite3.dll *.obj&#x0D;&#x0A;if not exist &quot;$(OutDir)\sqlite3.dll&quot; copy sqlite3.dll &quot;$(OutDir)&quot;&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(sqlite3Dir)\$(PlatformName)\sqlite3.lib"
 				BaseAddress="0x1e180000"
 				TargetMachine="17"
 			/>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/_ssl.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/_ssl.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/_ssl.vcproj	Wed Jun  4 11:24:23 2008
@@ -27,7 +27,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -89,7 +89,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -153,7 +153,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -216,7 +216,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -280,7 +280,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -343,7 +343,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -408,7 +408,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -471,7 +471,7 @@
 			>
 			<Tool
 				Name="VCPreBuildEventTool"
-				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a"
+				CommandLine="cd &quot;$(SolutionDir)&quot;&#x0D;&#x0A;&quot;$(PythonExe)&quot; build_ssl.py Release $(PlatformName) -a&#x0D;&#x0A;"
 			/>
 			<Tool
 				Name="VCCustomBuildTool"
@@ -535,10 +535,6 @@
 			Name="Source Files"
 			>
 			<File
-				RelativePath="..\..\Modules\_hashopenssl.c"
-				>
-			</File>
-			<File
 				RelativePath="..\..\Modules\_ssl.c"
 				>
 			</File>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/_tkinter.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/_tkinter.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/_tkinter.vcproj	Wed Jun  4 11:24:23 2008
@@ -56,7 +56,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(tcltkLib)"
+				AdditionalDependencies="$(tcltkLibDebug)"
 			/>
 			<Tool
 				Name="VCALinkTool"
@@ -104,7 +104,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="&quot;$(tcltk64Dir)\include&quot;"
+				AdditionalIncludeDirectories="$(tcltk64Dir)\include"
 				PreprocessorDefinitions="WITH_APPINIT"
 			/>
 			<Tool
@@ -118,7 +118,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(tcltk64Lib)"
+				AdditionalDependencies="$(tcltk64LibDebug)"
 			/>
 			<Tool
 				Name="VCALinkTool"
@@ -229,7 +229,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="&quot;$(tcltk64Dir)\include&quot;"
+				AdditionalIncludeDirectories="$(tcltk64Dir)\include"
 				PreprocessorDefinitions="WITH_APPINIT"
 			/>
 			<Tool
@@ -354,7 +354,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="&quot;$(tcltk64Dir)\include&quot;"
+				AdditionalIncludeDirectories="$(tcltk64Dir)\include"
 				PreprocessorDefinitions="WITH_APPINIT"
 			/>
 			<Tool
@@ -480,7 +480,7 @@
 			/>
 			<Tool
 				Name="VCCLCompilerTool"
-				AdditionalIncludeDirectories="&quot;$(tcltk64Dir)\include&quot;"
+				AdditionalIncludeDirectories="$(tcltk64Dir)\include"
 				PreprocessorDefinitions="WITH_APPINIT"
 			/>
 			<Tool

Modified: python/branches/okkoto-sizeof/PC/VS8.0/bdist_wininst.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/bdist_wininst.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/bdist_wininst.vcproj	Wed Jun  4 11:24:23 2008
@@ -11,6 +11,9 @@
 		<Platform
 			Name="Win32"
 		/>
+		<Platform
+			Name="x64"
+		/>
 	</Platforms>
 	<ToolFiles>
 	</ToolFiles>
@@ -104,6 +107,96 @@
 				Name="VCPostBuildEventTool"
 			/>
 		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(PlatformName)\$(ConfigurationName)"
+			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
+			ConfigurationType="1"
+			InheritedPropertySheets=".\pyproject.vsprops;.\release.vsprops"
+			UseOfMFC="0"
+			ATLMinimizesCRunTimeLibraryUsage="false"
+			CharacterSet="0"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				PreprocessorDefinitions="NDEBUG"
+				MkTypLibCompatible="true"
+				SuppressStartupBanner="true"
+				TargetEnvironment="3"
+				TypeLibraryName=".\..\..\lib\distutils\command\wininst.tlb"
+				HeaderFileName=""
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="1"
+				InlineFunctionExpansion="1"
+				AdditionalIncludeDirectories="..\..\PC\bdist_wininst;..\..\Include;..\..\Modules\zlib"
+				PreprocessorDefinitions="_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE"
+				StringPooling="true"
+				RuntimeLibrary="2"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				SuppressStartupBanner="true"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+				PreprocessorDefinitions="NDEBUG"
+				Culture="0"
+				AdditionalIncludeDirectories="..\..\PC;..\..\PC\bdist_wininst;..\..\Include"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="comctl32.lib imagehlp.lib"
+				OutputFile="..\..\lib\distutils\command\wininst-8.0-amd64.exe"
+				LinkIncremental="1"
+				SuppressStartupBanner="true"
+				IgnoreDefaultLibraryNames="LIBC"
+				ProgramDatabaseFile="..\..\lib\distutils\command\wininst-8.0-amd64.pdb"
+				SubSystem="2"
+				RandomizedBaseAddress="1"
+				DataExecutionPrevention="0"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
 	</Configurations>
 	<References>
 	</References>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/debug.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/debug.vsprops	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/debug.vsprops	Wed Jun  4 11:24:23 2008
@@ -8,4 +8,8 @@
 		Name="VCCLCompilerTool"
 		PreprocessorDefinitions="_DEBUG"
 	/>
-</VisualStudioPropertySheet>
\ No newline at end of file
+	<UserMacro
+		Name="KillPythonExe"
+		Value="$(OutDir)\kill_python_d.exe"
+	/>
+</VisualStudioPropertySheet>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/make_versioninfo.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/make_versioninfo.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/make_versioninfo.vcproj	Wed Jun  4 11:24:23 2008
@@ -67,6 +67,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(SolutionDir)make_versioninfo.exe"
 				ProgramDatabaseFile="$(TargetDir)$(TargetName).pdb"
 				SubSystem="1"
@@ -210,6 +211,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(SolutionDir)make_versioninfo_d.exe"
 				ProgramDatabaseFile="$(TargetDir)$(TargetName).pdb"
 				SubSystem="1"

Modified: python/branches/okkoto-sizeof/PC/VS8.0/pcbuild.sln
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/pcbuild.sln	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/pcbuild.sln	Wed Jun  4 11:24:23 2008
@@ -11,6 +11,7 @@
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythoncore", "pythoncore.vcproj", "{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}"
 	ProjectSection(ProjectDependencies) = postProject
 		{F0E0541E-F17D-430B-97C4-93ADF0DD284E} = {F0E0541E-F17D-430B-97C4-93ADF0DD284E}
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}
 		{C73F0EC1-358B-4177-940F-0846AC8B04CD} = {C73F0EC1-358B-4177-940F-0846AC8B04CD}
 	EndProjectSection
 EndProject
@@ -20,6 +21,9 @@
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "w9xpopen", "w9xpopen.vcproj", "{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}"
+	ProjectSection(ProjectDependencies) = postProject
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}
+	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_buildinfo", "make_buildinfo.vcproj", "{C73F0EC1-358B-4177-940F-0846AC8B04CD}"
 EndProject
@@ -36,6 +40,8 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb", "_bsddb.vcproj", "{B4D38F3F-68FB-42EC-A45D-E00657BB3627}"
 	ProjectSection(ProjectDependencies) = postProject
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}
+		{62172C7D-B39E-409A-B352-370FF5098C19} = {62172C7D-B39E-409A-B352-370FF5098C19}
 		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
 	EndProjectSection
 EndProject
@@ -67,6 +73,7 @@
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_sqlite3", "_sqlite3.vcproj", "{13CECB97-4119-4316-9D42-8534019A5A44}"
 	ProjectSection(ProjectDependencies) = postProject
 		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{A1A295E5-463C-437F-81CA-1F32367685DA} = {A1A295E5-463C-437F-81CA-1F32367685DA}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_ssl", "_ssl.vcproj", "{C6E20F84-3247-4AD6-B051-B073268F73BA}"
@@ -108,6 +115,24 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bdist_wininst", "bdist_wininst.vcproj", "{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}"
 EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_hashlib", "_hashlib.vcproj", "{447F05A8-F581-4CAC-A466-5AC7936E207E}"
+	ProjectSection(ProjectDependencies) = postProject
+		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9} = {B11D750F-CD1F-4A96-85CE-E69A5C5259F9}
+		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb44", "_bsddb44.vcproj", "{62172C7D-B39E-409A-B352-370FF5098C19}"
+	ProjectSection(ProjectDependencies) = postProject
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sqlite3", "sqlite3.vcproj", "{A1A295E5-463C-437F-81CA-1F32367685DA}"
+	ProjectSection(ProjectDependencies) = postProject
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31} = {6DE10744-E396-40A5-B4E2-1B69AA7C8D31}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kill_python", "kill_python.vcproj", "{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
@@ -457,13 +482,77 @@
 		{D06B6426-4762-44CC-8BAD-D79052507F2F}.Release|x64.ActiveCfg = Release|x64
 		{D06B6426-4762-44CC-8BAD-D79052507F2F}.Release|x64.Build.0 = Release|x64
 		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|Win32.ActiveCfg = Release|Win32
-		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|x64.ActiveCfg = Release|Win32
+		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Debug|x64.ActiveCfg = Release|x64
 		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|Win32.ActiveCfg = Release|Win32
-		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|x64.ActiveCfg = Release|Win32
+		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGInstrument|x64.ActiveCfg = Release|x64
 		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|Win32.ActiveCfg = Release|Win32
-		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|x64.ActiveCfg = Release|Win32
+		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.PGUpdate|x64.ActiveCfg = Release|x64
 		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|Win32.ActiveCfg = Release|Win32
-		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|x64.ActiveCfg = Release|Win32
+		{EB1C19C1-1F18-421E-9735-CAEE69DC6A3C}.Release|x64.ActiveCfg = Release|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|Win32.ActiveCfg = Debug|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|Win32.Build.0 = Debug|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|x64.ActiveCfg = Debug|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Debug|x64.Build.0 = Debug|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|Win32.ActiveCfg = Release|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|Win32.Build.0 = Release|Win32
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|x64.ActiveCfg = Release|x64
+		{447F05A8-F581-4CAC-A466-5AC7936E207E}.Release|x64.Build.0 = Release|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Debug|Win32.ActiveCfg = Debug|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Debug|Win32.Build.0 = Debug|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Debug|x64.ActiveCfg = Debug|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Debug|x64.Build.0 = Debug|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Release|Win32.ActiveCfg = Release|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Release|Win32.Build.0 = Release|Win32
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Release|x64.ActiveCfg = Release|x64
+		{62172C7D-B39E-409A-B352-370FF5098C19}.Release|x64.Build.0 = Release|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|Win32.Build.0 = Debug|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|x64.ActiveCfg = Debug|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Debug|x64.Build.0 = Debug|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Release|Win32.ActiveCfg = Release|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Release|Win32.Build.0 = Release|Win32
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Release|x64.ActiveCfg = Release|x64
+		{A1A295E5-463C-437F-81CA-1F32367685DA}.Release|x64.Build.0 = Release|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|Win32.ActiveCfg = Debug|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|Win32.Build.0 = Debug|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|x64.ActiveCfg = Debug|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Debug|x64.Build.0 = Debug|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|Win32.ActiveCfg = Release|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|Win32.Build.0 = Release|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|x64.ActiveCfg = Release|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGInstrument|x64.Build.0 = Release|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|Win32.ActiveCfg = Release|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|Win32.Build.0 = Release|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|x64.ActiveCfg = Release|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.PGUpdate|x64.Build.0 = Release|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.ActiveCfg = Release|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.Build.0 = Release|Win32
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.ActiveCfg = Release|x64
+		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.Build.0 = Release|x64
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

Modified: python/branches/okkoto-sizeof/PC/VS8.0/pyd.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/pyd.vsprops	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/pyd.vsprops	Wed Jun  4 11:24:23 2008
@@ -7,6 +7,7 @@
 	>
 	<Tool
 		Name="VCCLCompilerTool"
+		PreprocessorDefinitions="Py_BUILD_CORE_MODULE"
 		RuntimeLibrary="2"
 	/>
 	<Tool

Modified: python/branches/okkoto-sizeof/PC/VS8.0/pyd_d.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/pyd_d.vsprops	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/pyd_d.vsprops	Wed Jun  4 11:24:23 2008
@@ -10,6 +10,7 @@
 		Optimization="0"
 		InlineFunctionExpansion="0"
 		EnableIntrinsicFunctions="false"
+		PreprocessorDefinitions="Py_BUILD_CORE_MODULE"
 		RuntimeLibrary="3"
 	/>
 	<Tool

Modified: python/branches/okkoto-sizeof/PC/VS8.0/pyproject.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/pyproject.vsprops	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/pyproject.vsprops	Wed Jun  4 11:24:23 2008
@@ -45,35 +45,67 @@
 		Value="$(SolutionDir)\python.exe"
 	/>
 	<UserMacro
+		Name="externalsDir"
+		Value="..\..\.."
+	/>
+	<UserMacro
 		Name="bsddbDir"
-		Value="..\..\..\db-4.4.20\build_win32\"
+		Value="$(bsddb44Dir)"
+	/>
+	<UserMacro
+		Name="bsddbDepLibs"
+		Value="$(bsddb44DepLibs)"
+	/>
+	<UserMacro
+		Name="bsddb44Dir"
+		Value="$(externalsDir)\db-4.4.20\build_win32"
+	/>
+	<UserMacro
+		Name="bsddb44DepLibs"
+		Value=""
+	/>
+	<UserMacro
+		Name="bsddb45Dir"
+		Value="$(externalsDir)\db-4.5.20.x\build_windows"
+	/>
+	<UserMacro
+		Name="bsddb45DepLibs"
+		Value="ws2_32.lib"
 	/>
 	<UserMacro
 		Name="sqlite3Dir"
-		Value="..\..\..\sqlite-source-3.3.4\"
+		Value="$(externalsDir)\sqlite-source-3.3.4"
 	/>
 	<UserMacro
 		Name="bz2Dir"
-		Value="..\..\..\bzip2-1.0.3\"
+		Value="$(externalsDir)\bzip2-1.0.3"
 	/>
 	<UserMacro
 		Name="opensslDir"
-		Value="..\..\..\openssl-0.9.8g\"
+		Value="$(externalsDir)\openssl-0.9.8g"
 	/>
 	<UserMacro
 		Name="tcltkDir"
-		Value="..\..\..\tcltk\"
+		Value="$(externalsDir)\tcltk"
 	/>
 	<UserMacro
 		Name="tcltk64Dir"
-		Value="..\..\..\tcltk64"
+		Value="$(externalsDir)\tcltk64"
 	/>
 	<UserMacro
 		Name="tcltkLib"
 		Value="$(tcltkDir)\lib\tcl84.lib $(tcltkDir)\lib\tk84.lib"
 	/>
 	<UserMacro
+		Name="tcltkLibDebug"
+		Value="$(tcltkDir)\lib\tcl84g.lib $(tcltkDir)\lib\tk84g.lib"
+	/>
+	<UserMacro
 		Name="tcltk64Lib"
 		Value="$(tcltk64Dir)\lib\tcl84.lib $(tcltk64Dir)\lib\tk84.lib"
 	/>
+	<UserMacro
+		Name="tcltk64LibDebug"
+		Value="$(tcltk64Dir)\lib\tcl84g.lib $(tcltk64Dir)\lib\tk84g.lib"
+	/>
 </VisualStudioPropertySheet>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/python.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/python.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/python.vcproj	Wed Jun  4 11:24:23 2008
@@ -62,6 +62,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"
@@ -135,6 +136,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"
@@ -209,6 +211,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python_d.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"
@@ -284,9 +287,10 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python_d.exe"
 				SubSystem="1"
-				StackReserveSize="2000000"
+				StackReserveSize="2100000"
 				BaseAddress="0x1d000000"
 			/>
 			<Tool
@@ -356,6 +360,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"
@@ -430,6 +435,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"
@@ -504,6 +510,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"
@@ -578,6 +585,7 @@
 			/>
 			<Tool
 				Name="VCLinkerTool"
+				AdditionalDependencies="odbccp32.lib"
 				OutputFile="$(OutDir)\python.exe"
 				SubSystem="1"
 				StackReserveSize="2000000"

Modified: python/branches/okkoto-sizeof/PC/VS8.0/pythoncore.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/pythoncore.vcproj	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/pythoncore.vcproj	Wed Jun  4 11:24:23 2008
@@ -58,8 +58,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; $(ConfigurationName)"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -133,8 +133,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="$(SolutionDir)make_buildinfo.exe $(ConfigurationName)"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -211,8 +211,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; $(ConfigurationName)"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Debug"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -289,8 +289,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="$(SolutionDir)make_buildinfo.exe $(ConfigurationName)"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Debug"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -363,8 +363,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="$(SolutionDir)make_buildinfo.exe Release"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -438,8 +438,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="$(SolutionDir)make_buildinfo.exe $(ConfigurationName)"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -513,8 +513,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="$(SolutionDir)make_buildinfo.exe Release"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -588,8 +588,8 @@
 			/>
 			<Tool
 				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="$(SolutionDir)make_buildinfo.exe $(ConfigurationName)"
+				Description="Generate build information..."
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release"
 			/>
 			<Tool
 				Name="VCLinkerTool"
@@ -655,11 +655,15 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Include\bytesobject.h"
+				RelativePath="..\..\Include\bytes_methods.h"
 				>
 			</File>
 			<File
-				RelativePath="..\..\Include\bytes_methods.h"
+				RelativePath="..\..\Include\bytearrayobject.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\Include\bytesobject.h"
 				>
 			</File>
 			<File
@@ -871,6 +875,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\Include\pymath.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\Include\pymem.h"
 				>
 			</File>
@@ -1363,11 +1371,15 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Objects\bytesobject.c"
+				RelativePath="..\..\Objects\bytes_methods.c"
 				>
 			</File>
 			<File
-				RelativePath="..\..\Objects\bytes_methods.c"
+				RelativePath="..\..\Objects\bytearrayobject.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\Objects\bytesobject.c"
 				>
 			</File>
 			<File
@@ -1487,10 +1499,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\Objects\stringobject.c"
-				>
-			</File>
-			<File
 				RelativePath="..\..\Objects\structseq.c"
 				>
 			</File>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/release.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/release.vsprops	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/release.vsprops	Wed Jun  4 11:24:23 2008
@@ -8,4 +8,8 @@
 		Name="VCCLCompilerTool"
 		PreprocessorDefinitions="NDEBUG"
 	/>
+	<UserMacro
+		Name="KillPythonExe"
+		Value="$(OutDir)\kill_python.exe"
+	/>	
 </VisualStudioPropertySheet>

Modified: python/branches/okkoto-sizeof/PC/VS8.0/x64.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PC/VS8.0/x64.vsprops	(original)
+++ python/branches/okkoto-sizeof/PC/VS8.0/x64.vsprops	Wed Jun  4 11:24:23 2008
@@ -15,4 +15,8 @@
 		Name="VCLinkerTool"
 		TargetMachine="17"
 	/>
+	<UserMacro
+		Name="PythonExe"
+		Value="$(HOST_PYTHON)"
+	/>
 </VisualStudioPropertySheet>

Modified: python/branches/okkoto-sizeof/PC/_msi.c
==============================================================================
--- python/branches/okkoto-sizeof/PC/_msi.c	(original)
+++ python/branches/okkoto-sizeof/PC/_msi.c	Wed Jun  4 11:24:23 2008
@@ -35,7 +35,7 @@
 	return NULL;
     }
 
-    oresult = PyString_FromString(cresult);
+    oresult = PyBytes_FromString(cresult);
     RpcStringFree(&cresult);
     return oresult;
 
@@ -136,14 +136,14 @@
 	PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab);
 	if (result == NULL)
 	    return -1;
-	if (!PyString_Check(result)) {
+	if (!PyBytes_Check(result)) {
 	    PyErr_Format(PyExc_TypeError, 
 		"Incorrect return type %s from getnextcabinet",
 		result->ob_type->tp_name);
 	    Py_DECREF(result);
 	    return FALSE;
 	}
-	strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab));
+	strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab));
 	return TRUE;
     }
     return FALSE;
@@ -339,6 +339,49 @@
 }
 
 static PyObject*
+record_getinteger(msiobj* record, PyObject* args)
+{
+    unsigned int field;
+    int status;
+    
+    if (!PyArg_ParseTuple(args, "I:GetInteger", &field))
+        return NULL;
+    status = MsiRecordGetInteger(record->h, field);
+    if (status == MSI_NULL_INTEGER){
+        PyErr_SetString(MSIError, "could not convert record field to integer");
+        return NULL;
+    }
+    return PyInt_FromLong((long) status);
+}
+
+static PyObject*
+record_getstring(msiobj* record, PyObject* args)
+{
+    unsigned int field;
+    unsigned int status;
+    char buf[2000];
+    char *res = buf;
+    DWORD size = sizeof(buf);
+    PyObject* string;
+    
+    if (!PyArg_ParseTuple(args, "I:GetString", &field))
+        return NULL;
+    status = MsiRecordGetString(record->h, field, res, &size);
+    if (status == ERROR_MORE_DATA) {
+        res = (char*) malloc(size + 1);
+        if (res == NULL)
+            return PyErr_NoMemory();
+        status = MsiRecordGetString(record->h, field, res, &size);
+    }
+    if (status != ERROR_SUCCESS)
+        return msierror((int) status);
+    string = PyString_FromString(res);
+    if (buf != res)
+        free(res);
+    return string;
+}
+
+static PyObject*
 record_cleardata(msiobj* record, PyObject *args)
 {
     int status = MsiRecordClearData(record->h);
@@ -405,6 +448,10 @@
 static PyMethodDef record_methods[] = {
     { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, 
 	PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")},
+    { "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS,
+    PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")},
+    { "GetString", (PyCFunction)record_getstring, METH_VARARGS,
+    PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")},
     { "SetString", (PyCFunction)record_setstring, METH_VARARGS, 
 	PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")},
     { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, 
@@ -507,7 +554,7 @@
 	    PyErr_SetString(PyExc_NotImplementedError, "FILETIME result");
 	    return NULL;
 	case VT_LPSTR:
-	    result = PyString_FromStringAndSize(sval, ssize);
+	    result = PyBytes_FromStringAndSize(sval, ssize);
 	    if (sval != sbuf)
 		free(sval);
 	    return result;
@@ -539,9 +586,9 @@
     if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data))
 	return NULL;
 
-    if (PyString_Check(data)) {
+    if (PyBytes_Check(data)) {
 	status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR,
-	    0, NULL, PyString_AsString(data));
+	    0, NULL, PyBytes_AsString(data));
     } else if (PyInt_Check(data)) {
 	status = MsiSummaryInfoSetProperty(si->h, field, VT_I4,
 	    PyInt_AsLong(data), NULL, NULL);

Modified: python/branches/okkoto-sizeof/PC/_subprocess.c
==============================================================================
--- python/branches/okkoto-sizeof/PC/_subprocess.c	(original)
+++ python/branches/okkoto-sizeof/PC/_subprocess.c	Wed Jun  4 11:24:23 2008
@@ -304,42 +304,42 @@
 	if (!keys || !values)
 		goto error;
 
-	out = PyString_FromStringAndSize(NULL, 2048);
+	out = PyBytes_FromStringAndSize(NULL, 2048);
 	if (! out)
 		goto error;
 
-	p = PyString_AS_STRING(out);
+	p = PyBytes_AS_STRING(out);
 
 	for (i = 0; i < envsize; i++) {
 		int ksize, vsize, totalsize;
 		PyObject* key = PyList_GET_ITEM(keys, i);
 		PyObject* value = PyList_GET_ITEM(values, i);
 
-		if (! PyString_Check(key) || ! PyString_Check(value)) {
+		if (! PyBytes_Check(key) || ! PyBytes_Check(value)) {
 			PyErr_SetString(PyExc_TypeError,
 				"environment can only contain strings");
 			goto error;
 		}
-		ksize = PyString_GET_SIZE(key);
-		vsize = PyString_GET_SIZE(value);
-		totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 +
+		ksize = PyBytes_GET_SIZE(key);
+		vsize = PyBytes_GET_SIZE(value);
+		totalsize = (p - PyBytes_AS_STRING(out)) + ksize + 1 +
 							     vsize + 1 + 1;
-		if (totalsize > PyString_GET_SIZE(out)) {
-			int offset = p - PyString_AS_STRING(out);
-			_PyString_Resize(&out, totalsize + 1024);
-			p = PyString_AS_STRING(out) + offset;
+		if (totalsize > PyBytes_GET_SIZE(out)) {
+			int offset = p - PyBytes_AS_STRING(out);
+			_PyBytes_Resize(&out, totalsize + 1024);
+			p = PyBytes_AS_STRING(out) + offset;
 		}
-		memcpy(p, PyString_AS_STRING(key), ksize);
+		memcpy(p, PyBytes_AS_STRING(key), ksize);
 		p += ksize;
 		*p++ = '=';
-		memcpy(p, PyString_AS_STRING(value), vsize);
+		memcpy(p, PyBytes_AS_STRING(value), vsize);
 		p += vsize;
 		*p++ = '\0';
 	}
 
 	/* add trailing null byte */
 	*p++ = '\0';
-	_PyString_Resize(&out, p - PyString_AS_STRING(out));
+	_PyBytes_Resize(&out, p - PyBytes_AS_STRING(out));
 
 	/* PyObject_Print(out, stdout, 0); */
 
@@ -413,7 +413,7 @@
 			       NULL,
 			       inherit_handles,
 			       creation_flags,
-			       environment ? PyString_AS_STRING(environment) : NULL,
+			       environment ? PyBytes_AS_STRING(environment) : NULL,
 			       current_directory,
 			       &si,
 			       &pi);
@@ -516,7 +516,7 @@
 	if (! result)
 		return PyErr_SetFromWindowsErr(GetLastError());
 
-	return PyString_FromString(filename);
+	return PyBytes_FromString(filename);
 }
 
 static PyMethodDef sp_functions[] = {

Modified: python/branches/okkoto-sizeof/PC/_winreg.c
==============================================================================
--- python/branches/okkoto-sizeof/PC/_winreg.c	(original)
+++ python/branches/okkoto-sizeof/PC/_winreg.c	Wed Jun  4 11:24:23 2008
@@ -424,7 +424,7 @@
 	PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
 	char resBuf[160];
 	wsprintf(resBuf, "<PyHKEY:%p>", pyhkey->hkey);
-	return PyString_FromString(resBuf);
+	return PyBytes_FromString(resBuf);
 }
 
 static int
@@ -767,11 +767,11 @@
 						return FALSE;
 					need_decref = 1;
 				}
-				if (!PyString_Check(value))
+				if (!PyBytes_Check(value))
 					return FALSE;
 				*retDataSize = 1 + strlen(
-					PyString_AS_STRING(
-						(PyStringObject *)value));
+					PyBytes_AS_STRING(
+						(PyBytesObject *)value));
 			}
 			*retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
 			if (*retDataBuf==NULL){
@@ -782,8 +782,8 @@
 				strcpy((char *)*retDataBuf, "");
 			else
 				strcpy((char *)*retDataBuf,
-				       PyString_AS_STRING(
-				       		(PyStringObject *)value));
+				       PyBytes_AS_STRING(
+				       		(PyBytesObject *)value));
 			if (need_decref)
 				Py_DECREF(value);
 			break;
@@ -808,7 +808,7 @@
 					PyObject *t;
 					t = PyList_GET_ITEM(
 						(PyListObject *)value,j);
-					if (PyString_Check(t)) {
+					if (PyBytes_Check(t)) {
 						obs[j] = t;
 						Py_INCREF(t);
 					} else if (PyUnicode_Check(t)) {
@@ -821,8 +821,8 @@
 					} else
 						goto reg_multi_fail;
 					size += 1 + strlen(
-						PyString_AS_STRING(
-							(PyStringObject *)obs[j]));
+						PyBytes_AS_STRING(
+							(PyBytesObject *)obs[j]));
 				}
 
 				*retDataSize = size + 1;
@@ -839,11 +839,11 @@
 					PyObject *t;
 					t = obs[j];
 					strcpy(P,
-					       PyString_AS_STRING(
-					       		(PyStringObject *)t));
+					       PyBytes_AS_STRING(
+					       		(PyBytesObject *)t));
 					P += 1 + strlen(
-						PyString_AS_STRING(
-							(PyStringObject *)t));
+						PyBytes_AS_STRING(
+							(PyBytesObject *)t));
 					Py_DECREF(obs[j]);
 				}
 				/* And doubly-terminate the list... */
@@ -1085,7 +1085,7 @@
 	if (rc != ERROR_SUCCESS)
 		return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx");
 
-	retStr = PyString_FromStringAndSize(tmpbuf, len);
+	retStr = PyBytes_FromStringAndSize(tmpbuf, len);
 	return retStr;  /* can be NULL */
 }
 
@@ -1303,17 +1303,17 @@
 	    != ERROR_SUCCESS)
 		return PyErr_SetFromWindowsErrWithFunction(rc,
 							   "RegQueryValue");
-	retStr = PyString_FromStringAndSize(NULL, bufSize);
+	retStr = PyBytes_FromStringAndSize(NULL, bufSize);
 	if (retStr == NULL)
 		return NULL;
-	retBuf = PyString_AS_STRING(retStr);
+	retBuf = PyBytes_AS_STRING(retStr);
 	if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize))
 	    != ERROR_SUCCESS) {
 		Py_DECREF(retStr);
 		return PyErr_SetFromWindowsErrWithFunction(rc,
 							   "RegQueryValue");
 	}
-	_PyString_Resize(&retStr, strlen(retBuf));
+	_PyBytes_Resize(&retStr, strlen(retBuf));
 	return retStr;
 }
 
@@ -1414,14 +1414,14 @@
 		return NULL;
 	}
 	/* XXX - need Unicode support */
-	str = PyString_AsString(obStrVal);
+	str = PyBytes_AsString(obStrVal);
 	if (str == NULL)
 		return NULL;
-	len = PyString_Size(obStrVal);
+	len = PyBytes_Size(obStrVal);
 	if (obSubKey == Py_None)
 		subKey = NULL;
 	else {
-		subKey = PyString_AsString(obSubKey);
+		subKey = PyBytes_AsString(obSubKey);
 		if (subKey == NULL)
 			return NULL;
 	}

Modified: python/branches/okkoto-sizeof/PC/bdist_wininst/install.c
==============================================================================
--- python/branches/okkoto-sizeof/PC/bdist_wininst/install.c	(original)
+++ python/branches/okkoto-sizeof/PC/bdist_wininst/install.c	Wed Jun  4 11:24:23 2008
@@ -2115,11 +2115,6 @@
 {
 	HKEY hk;
 	char key_name[80];
-	OSVERSIONINFO winverinfo;
-	winverinfo.dwOSVersionInfoSize = sizeof(winverinfo);
-	// If less than XP, then we can't do it (and its not necessary).
-	if (!GetVersionEx(&winverinfo) || winverinfo.dwMajorVersion < 5)
-		return FALSE;
 	// no Python version info == we can't know yet.
 	if (target_version[0] == '\0')
 		return FALSE;
@@ -2135,6 +2130,23 @@
 	return TRUE;
 }
 
+// Returns TRUE if the platform supports UAC.
+BOOL PlatformSupportsUAC()
+{
+	// Note that win2k does seem to support ShellExecute with 'runas',
+	// but does *not* support IsUserAnAdmin - so we just pretend things
+	// only work on XP and later.
+	BOOL bIsWindowsXPorLater;
+	OSVERSIONINFO winverinfo;
+	winverinfo.dwOSVersionInfoSize = sizeof(winverinfo);
+	if (!GetVersionEx(&winverinfo))
+		return FALSE; // something bad has gone wrong
+	bIsWindowsXPorLater = 
+       ( (winverinfo.dwMajorVersion > 5) ||
+       ( (winverinfo.dwMajorVersion == 5) && (winverinfo.dwMinorVersion >= 1) ));
+	return bIsWindowsXPorLater;
+}
+
 // Spawn ourself as an elevated application.  On failure, a message is
 // displayed to the user - but this app will always terminate, even
 // on error.
@@ -2190,7 +2202,7 @@
 
 	// See if we need to do the Vista UAC magic.
 	if (strcmp(user_access_control, "force")==0) {
-		if (!MyIsUserAnAdmin()) {
+		if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) {
 			SpawnUAC();
 			return 0;
 		}
@@ -2198,7 +2210,7 @@
 	} else if (strcmp(user_access_control, "auto")==0) {
 		// Check if it looks like we need UAC control, based
 		// on how Python itself was installed.
-		if (!MyIsUserAnAdmin() && NeedAutoUAC()) {
+		if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) {
 			SpawnUAC();
 			return 0;
 		}

Modified: python/branches/okkoto-sizeof/PC/msvcrtmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/PC/msvcrtmodule.c	(original)
+++ python/branches/okkoto-sizeof/PC/msvcrtmodule.c	Wed Jun  4 11:24:23 2008
@@ -140,7 +140,7 @@
 	ch = _getch();
 	Py_END_ALLOW_THREADS
 	s[0] = ch;
-	return PyString_FromStringAndSize(s, 1);
+	return PyBytes_FromStringAndSize(s, 1);
 }
 
 static PyObject *
@@ -172,7 +172,7 @@
 	ch = _getche();
 	Py_END_ALLOW_THREADS
 	s[0] = ch;
-	return PyString_FromStringAndSize(s, 1);
+	return PyBytes_FromStringAndSize(s, 1);
 }
 
 static PyObject *

Modified: python/branches/okkoto-sizeof/PC/winsound.c
==============================================================================
--- python/branches/okkoto-sizeof/PC/winsound.c	(original)
+++ python/branches/okkoto-sizeof/PC/winsound.c	Wed Jun  4 11:24:23 2008
@@ -151,7 +151,7 @@
 static void
 add_define(PyObject *dict, const char *key, long value)
 {
-    PyObject *k=PyString_FromString(key);
+    PyObject *k=PyBytes_FromString(key);
     PyObject *v=PyLong_FromLong(value);
     if(v&&k)
     {

Modified: python/branches/okkoto-sizeof/PCbuild/pyproject.vsprops
==============================================================================
--- python/branches/okkoto-sizeof/PCbuild/pyproject.vsprops	(original)
+++ python/branches/okkoto-sizeof/PCbuild/pyproject.vsprops	Wed Jun  4 11:24:23 2008
@@ -45,6 +45,10 @@
 		Value="$(SolutionDir)\python.exe"
 	/>
 	<UserMacro
+		Name="externalsDir"
+		Value="..\.."
+	/>
+	<UserMacro
 		Name="bsddbDir"
 		Value="$(bsddb44Dir)"
 	/>
@@ -54,7 +58,7 @@
 	/>
 	<UserMacro
 		Name="bsddb44Dir"
-		Value="..\..\db-4.4.20\build_win32"
+		Value="$(externalsDir)\db-4.4.20\build_win32"
 	/>
 	<UserMacro
 		Name="bsddb44DepLibs"
@@ -62,7 +66,7 @@
 	/>
 	<UserMacro
 		Name="bsddb45Dir"
-		Value="..\..\db-4.5.20.x\build_windows"
+		Value="$(externalsDir)\db-4.5.20.x\build_windows"
 	/>
 	<UserMacro
 		Name="bsddb45DepLibs"
@@ -70,23 +74,23 @@
 	/>
 	<UserMacro
 		Name="sqlite3Dir"
-		Value="..\..\sqlite-source-3.3.4"
+		Value="$(externalsDir)\sqlite-source-3.3.4"
 	/>
 	<UserMacro
 		Name="bz2Dir"
-		Value="..\..\bzip2-1.0.3"
+		Value="$(externalsDir)\bzip2-1.0.3"
 	/>
 	<UserMacro
 		Name="opensslDir"
-		Value="..\..\openssl-0.9.8g"
+		Value="$(externalsDir)\openssl-0.9.8g"
 	/>
 	<UserMacro
 		Name="tcltkDir"
-		Value="..\..\tcltk"
+		Value="$(externalsDir)\tcltk"
 	/>
 	<UserMacro
 		Name="tcltk64Dir"
-		Value="..\..\tcltk64"
+		Value="$(externalsDir)\tcltk64"
 	/>
 	<UserMacro
 		Name="tcltkLib"

Modified: python/branches/okkoto-sizeof/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/okkoto-sizeof/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/okkoto-sizeof/PCbuild/pythoncore.vcproj	Wed Jun  4 11:24:23 2008
@@ -659,6 +659,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\Include\bytearrayobject.h"
+				>
+			</File>
+			<File
 				RelativePath="..\Include\bytesobject.h"
 				>
 			</File>
@@ -1371,6 +1375,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\Objects\bytearrayobject.c"
+				>
+			</File>
+			<File
 				RelativePath="..\Objects\bytesobject.c"
 				>
 			</File>
@@ -1491,10 +1499,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\Objects\stringobject.c"
-				>
-			</File>
-			<File
 				RelativePath="..\Objects\structseq.c"
 				>
 			</File>

Modified: python/branches/okkoto-sizeof/Parser/asdl_c.py
==============================================================================
--- python/branches/okkoto-sizeof/Parser/asdl_c.py	(original)
+++ python/branches/okkoto-sizeof/Parser/asdl_c.py	Wed Jun  4 11:24:23 2008
@@ -375,7 +375,7 @@
         # there's really nothing more we can do if this fails ...
         self.emit("if (tmp == NULL) goto failed;", 1)
         error = "expected some sort of %s, but got %%.400s" % name
-        format = "PyErr_Format(PyExc_TypeError, \"%s\", PyString_AS_STRING(tmp));"
+        format = "PyErr_Format(PyExc_TypeError, \"%s\", PyBytes_AS_STRING(tmp));"
         self.emit(format % error, 1, reflow=False)
         self.emit("failed:", 0)
         self.emit("Py_XDECREF(tmp);", 1)
@@ -704,7 +704,7 @@
     fnames = PyTuple_New(num_fields);
     if (!fnames) return NULL;
     for (i = 0; i < num_fields; i++) {
-        PyObject *field = PyString_FromString(fields[i]);
+        PyObject *field = PyBytes_FromString(fields[i]);
         if (!field) {
             Py_DECREF(fnames);
             return NULL;
@@ -723,7 +723,7 @@
     PyObject *s, *l = PyTuple_New(num_fields);
     if (!l) return 0;
     for(i = 0; i < num_fields; i++) {
-        s = PyString_FromString(attrs[i]);
+        s = PyBytes_FromString(attrs[i]);
         if (!s) {
             Py_DECREF(l);
             return 0;
@@ -797,7 +797,7 @@
         PyObject *s = PyObject_Repr(obj);
         if (s == NULL) return 1;
         PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s",
-                     PyString_AS_STRING(s));
+                     PyBytes_AS_STRING(s));
         Py_DECREF(s);
         return 1;
     }
@@ -815,7 +815,7 @@
         PyObject *s = PyObject_Repr(obj);
         if (s == NULL) return 1;
         PyErr_Format(PyExc_ValueError, "invalid boolean value: %.400s",
-                     PyString_AS_STRING(s));
+                     PyBytes_AS_STRING(s));
         Py_DECREF(s);
         return 1;
     }

Modified: python/branches/okkoto-sizeof/Parser/tokenizer.c
==============================================================================
--- python/branches/okkoto-sizeof/Parser/tokenizer.c	(original)
+++ python/branches/okkoto-sizeof/Parser/tokenizer.c	Wed Jun  4 11:24:23 2008
@@ -12,7 +12,7 @@
 
 #ifndef PGEN
 #include "unicodeobject.h"
-#include "stringobject.h"
+#include "bytesobject.h"
 #include "fileobject.h"
 #include "codecs.h"
 #include "abstract.h"
@@ -344,7 +344,7 @@
      1) NULL: need to call tok->decoding_readline to get a new line
      2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and
            stored the result in tok->decoding_buffer
-     3) PyStringObject *: previous call to fp_readl did not have enough room
+     3) PyBytesObject *: previous call to fp_readl did not have enough room
            (in the s buffer) to copy entire contents of the line read
            by tok->decoding_readline.  tok->decoding_buffer has the overflow.
            In this case, fp_readl is called in a loop (with an expanded buffer)
@@ -375,7 +375,7 @@
 			return error_ret(tok);
 	} else {
 		tok->decoding_buffer = NULL;
-		if (PyString_CheckExact(buf))
+		if (PyBytes_CheckExact(buf))
 			utf8 = buf;
 	}
 	if (utf8 == NULL) {
@@ -384,10 +384,10 @@
 		if (utf8 == NULL)
 			return error_ret(tok);
 	}
-	str = PyString_AsString(utf8);
-	utf8len = PyString_GET_SIZE(utf8);
+	str = PyBytes_AsString(utf8);
+	utf8len = PyBytes_GET_SIZE(utf8);
 	if (utf8len > size) {
-		tok->decoding_buffer = PyString_FromStringAndSize(str+size, utf8len-size);
+		tok->decoding_buffer = PyBytes_FromStringAndSize(str+size, utf8len-size);
 		if (tok->decoding_buffer == NULL) {
 			Py_DECREF(utf8);
 			return error_ret(tok);
@@ -591,7 +591,7 @@
 		utf8 = translate_into_utf8(str, tok->enc);
 		if (utf8 == NULL)
 			return error_ret(tok);
-		str = PyString_AsString(utf8);
+		str = PyBytes_AsString(utf8);
 	}
 #endif
 	for (s = str;; s++) {
@@ -624,7 +624,7 @@
 				"unknown encoding: %s", tok->enc);
 			return error_ret(tok);
 		}
-		str = PyString_AsString(utf8);
+		str = PyBytes_AsString(utf8);
 	}
 #endif
 	assert(tok->decoding_buffer == NULL);
@@ -706,11 +706,11 @@
 		return 0;
 
 	enc = ((PyFileObject *)sysstdin)->f_encoding;
-	if (enc == NULL || !PyString_Check(enc))
+	if (enc == NULL || !PyBytes_Check(enc))
 		return 0;
 	Py_INCREF(enc);
 
-	encoding = PyString_AsString(enc);
+	encoding = PyBytes_AsString(enc);
 	decoded = PyUnicode_Decode(*inp, strlen(*inp), encoding, NULL);
 	if (decoded == NULL)
 		goto error_clear;
@@ -720,9 +720,9 @@
 	if (utf8 == NULL)
 		goto error_clear;
 
-	assert(PyString_Check(utf8));
-	converted = new_string(PyString_AS_STRING(utf8),
-			       PyString_GET_SIZE(utf8));
+	assert(PyBytes_Check(utf8));
+	converted = new_string(PyBytes_AS_STRING(utf8),
+			       PyBytes_GET_SIZE(utf8));
 	Py_DECREF(utf8);
 	if (converted == NULL)
 		goto error_nomem;
@@ -1609,8 +1609,8 @@
 		/* convert source to original encondig */
 		PyObject *lineobj = dec_utf8(tok->encoding, tok->buf, len);
 		if (lineobj != NULL) {
-			int linelen = PyString_Size(lineobj);
-			const char *line = PyString_AsString(lineobj);
+			int linelen = PyBytes_Size(lineobj);
+			const char *line = PyBytes_AsString(lineobj);
 			text = PyObject_MALLOC(linelen + 1);
 			if (text != NULL && line != NULL) {
 				if (linelen)
@@ -1624,7 +1624,7 @@
 				PyObject *offsetobj = dec_utf8(tok->encoding, 
 							       tok->buf, *offset-1);
 				if (offsetobj) {
-					*offset = PyString_Size(offsetobj) + 1;
+					*offset = PyBytes_Size(offsetobj) + 1;
 					Py_DECREF(offsetobj);
 				}
 			}

Modified: python/branches/okkoto-sizeof/Python/Python-ast.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/Python-ast.c	(original)
+++ python/branches/okkoto-sizeof/Python/Python-ast.c	Wed Jun  4 11:24:23 2008
@@ -495,7 +495,7 @@
     fnames = PyTuple_New(num_fields);
     if (!fnames) return NULL;
     for (i = 0; i < num_fields; i++) {
-        PyObject *field = PyString_FromString(fields[i]);
+        PyObject *field = PyBytes_FromString(fields[i]);
         if (!field) {
             Py_DECREF(fnames);
             return NULL;
@@ -514,7 +514,7 @@
     PyObject *s, *l = PyTuple_New(num_fields);
     if (!l) return 0;
     for(i = 0; i < num_fields; i++) {
-        s = PyString_FromString(attrs[i]);
+        s = PyBytes_FromString(attrs[i]);
         if (!s) {
             Py_DECREF(l);
             return 0;
@@ -588,7 +588,7 @@
         PyObject *s = PyObject_Repr(obj);
         if (s == NULL) return 1;
         PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s",
-                     PyString_AS_STRING(s));
+                     PyBytes_AS_STRING(s));
         Py_DECREF(s);
         return 1;
     }
@@ -606,7 +606,7 @@
         PyObject *s = PyObject_Repr(obj);
         if (s == NULL) return 1;
         PyErr_Format(PyExc_ValueError, "invalid boolean value: %.400s",
-                     PyString_AS_STRING(s));
+                     PyBytes_AS_STRING(s));
         Py_DECREF(s);
         return 1;
     }
@@ -3286,7 +3286,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of mod, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of mod, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -4414,7 +4414,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5261,7 +5261,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of expr, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of expr, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5299,7 +5299,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of expr_context, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of expr_context, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5417,7 +5417,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of slice, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of slice, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5439,7 +5439,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of boolop, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of boolop, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5501,7 +5501,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of operator, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of operator, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5531,7 +5531,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5585,7 +5585,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of cmpop, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of cmpop, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;
@@ -5751,7 +5751,7 @@
 
         tmp = PyObject_Repr(obj);
         if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of excepthandler, but got %.400s", PyString_AS_STRING(tmp));
+        PyErr_Format(PyExc_TypeError, "expected some sort of excepthandler, but got %.400s", PyBytes_AS_STRING(tmp));
 failed:
         Py_XDECREF(tmp);
         return 1;

Modified: python/branches/okkoto-sizeof/Python/_warnings.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/_warnings.c	(original)
+++ python/branches/okkoto-sizeof/Python/_warnings.c	Wed Jun  4 11:24:23 2008
@@ -44,7 +44,7 @@
     int result;
 
     if (warnings_str == NULL) {
-        warnings_str = PyString_InternFromString("warnings");
+        warnings_str = PyBytes_InternFromString("warnings");
         if (warnings_str == NULL)
             return NULL;
     }
@@ -132,7 +132,7 @@
             return NULL;
 
         if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln))
-            return PyString_AsString(action);
+            return PyBytes_AsString(action);
     }
 
     m = PyImport_ImportModule(MODULE_NAME);
@@ -144,7 +144,7 @@
         return NULL;
     action = PyDict_GetItemString(d, DEFAULT_ACTION_NAME);
     if (action != NULL)
-        return PyString_AsString(action);
+        return PyBytes_AsString(action);
 
     PyErr_SetString(PyExc_ValueError,
                     MODULE_NAME "." DEFAULT_ACTION_NAME " not found");
@@ -184,17 +184,17 @@
     if (rc == -1)
         return NULL;
     else if (rc == 0)
-        return PyString_FromString("<unknown>");
+        return PyBytes_FromString("<unknown>");
 
-    mod_str = PyString_AsString(filename);
+    mod_str = PyBytes_AsString(filename);
     if (mod_str == NULL)
 	    return NULL;
-    len = PyString_Size(filename);
+    len = PyBytes_Size(filename);
     if (len < 0)
         return NULL;
     if (len >= 3 &&
 	strncmp(mod_str + (len - 3), ".py", 3) == 0) {
-        module = PyString_FromStringAndSize(mod_str, len-3);
+        module = PyBytes_FromStringAndSize(mod_str, len-3);
     }
     else {
         module = filename;
@@ -258,7 +258,7 @@
     /* Print "  source_line\n" */
     PyFile_WriteString("  ", f_stderr);
     if (sourceline) {
-        char *source_line_str = PyString_AS_STRING(sourceline);
+        char *source_line_str = PyBytes_AS_STRING(sourceline);
         while (*source_line_str == ' ' || *source_line_str == '\t' ||
                 *source_line_str == '\014')
             source_line_str++;
@@ -267,7 +267,7 @@
         PyFile_WriteString("\n", f_stderr);
     }
     else
-        Py_DisplaySourceLine(f_stderr, PyString_AS_STRING(filename), lineno);
+        Py_DisplaySourceLine(f_stderr, PyBytes_AS_STRING(filename), lineno);
     PyErr_Clear();
 }
 
@@ -359,7 +359,7 @@
             const char *err_str = "???";
 
             if (to_str != NULL)
-                err_str = PyString_AS_STRING(to_str);
+                err_str = PyBytes_AS_STRING(to_str);
             PyErr_Format(PyExc_RuntimeError,
                         "Unrecognized action (%s) in warnings.filters:\n %s",
                         action, err_str);
@@ -380,7 +380,7 @@
         else {
             const char *msg = "functions overriding warnings.showwarning() "
                                 "must support the 'line' argument";
-            const char *text_char = PyString_AS_STRING(text);
+            const char *text_char = PyBytes_AS_STRING(text);
 
             if (strcmp(msg, text_char) == 0) {
                 /* Prevent infinite recursion by using built-in implementation
@@ -484,7 +484,7 @@
     /* Setup module. */
     *module = PyDict_GetItemString(globals, "__name__");
     if (*module == NULL) {
-        *module = PyString_FromString("<string>");
+        *module = PyBytes_FromString("<string>");
         if (*module == NULL)
             goto handle_error;
     }
@@ -494,8 +494,8 @@
     /* Setup filename. */
     *filename = PyDict_GetItemString(globals, "__file__");
     if (*filename != NULL) {
-	    Py_ssize_t len = PyString_Size(*filename);
-        const char *file_str = PyString_AsString(*filename);
+	    Py_ssize_t len = PyBytes_Size(*filename);
+        const char *file_str = PyBytes_AsString(*filename);
 	    if (file_str == NULL || (len < 0 && PyErr_Occurred()))
             goto handle_error;
 
@@ -507,7 +507,7 @@
             (tolower(file_str[len-1]) == 'c' ||
                 tolower(file_str[len-1]) == 'o'))
         {
-            *filename = PyString_FromStringAndSize(file_str, len-1);
+            *filename = PyBytes_FromStringAndSize(file_str, len-1);
 	        if (*filename == NULL)
 		        goto handle_error;
 	    }
@@ -515,7 +515,7 @@
             Py_INCREF(*filename);
     }
     else {
-        const char *module_str = PyString_AsString(*module);
+        const char *module_str = PyBytes_AsString(*module);
         if (module_str && strcmp(module_str, "__main__") == 0) {
             PyObject *argv = PySys_GetObject("argv");
             if (argv != NULL && PyList_Size(argv) > 0) {
@@ -530,14 +530,14 @@
                 }
                 else if (!is_true) {
                     Py_DECREF(*filename);
-                    *filename = PyString_FromString("__main__");
+                    *filename = PyBytes_FromString("__main__");
                     if (*filename == NULL)
                         goto handle_error;
                 }
             }
             else {
                 /* embedded interpreters don't have sys.argv, see bug #839151 */
-                *filename = PyString_FromString("__main__");
+                *filename = PyBytes_FromString("__main__");
 	            if (*filename == NULL)
 	                goto handle_error;
             }
@@ -649,12 +649,12 @@
         PyObject *returned;
 
         if (get_source_name == NULL) {
-            get_source_name = PyString_InternFromString("get_source");
+            get_source_name = PyBytes_InternFromString("get_source");
             if (!get_source_name)
                 return NULL;
         }
         if (splitlines_name == NULL) {
-            splitlines_name = PyString_InternFromString("splitlines");
+            splitlines_name = PyBytes_InternFromString("splitlines");
             if (!splitlines_name)
                 return NULL;
         }
@@ -711,7 +711,7 @@
 PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
 {
     PyObject *res;
-    PyObject *message = PyString_FromString(text);
+    PyObject *message = PyBytes_FromString(text);
     if (message == NULL)
         return -1;
 
@@ -745,15 +745,15 @@
                    const char *module_str, PyObject *registry)
 {
     PyObject *res;
-    PyObject *message = PyString_FromString(text);
-    PyObject *filename = PyString_FromString(filename_str);
+    PyObject *message = PyBytes_FromString(text);
+    PyObject *filename = PyBytes_FromString(filename_str);
     PyObject *module = NULL;
     int ret = -1;
 
     if (message == NULL || filename == NULL)
         goto exit;
     if (module_str != NULL) {
-        module = PyString_FromString(module_str);
+        module = PyBytes_FromString(module_str);
             if (module == NULL)
                 goto exit;
     }
@@ -775,15 +775,6 @@
 }
 
 
-int
-PyErr_WarnPy3k(const char *text, Py_ssize_t stacklevel)
-{
-    if (Py_Py3kWarningFlag)
-        return PyErr_WarnEx(PyExc_DeprecationWarning, text, stacklevel);
-    return 0;
-}
-
-
 PyDoc_STRVAR(warn_doc,
 "Issue a warning, or maybe ignore it or raise an exception.");
 
@@ -812,7 +803,7 @@
 
     if (!strcmp(action, "ignore")) {
         if (ignore_str == NULL) {
-            ignore_str = PyString_InternFromString("ignore");
+            ignore_str = PyBytes_InternFromString("ignore");
             if (ignore_str == NULL)
                 return NULL;
         }
@@ -820,7 +811,7 @@
     }
     else if (!strcmp(action, "error")) {
         if (error_str == NULL) {
-            error_str = PyString_InternFromString("error");
+            error_str = PyBytes_InternFromString("error");
             if (error_str == NULL)
                 return NULL;
         }
@@ -828,7 +819,7 @@
     }
     else if (!strcmp(action, "default")) {
         if (default_str == NULL) {
-            default_str = PyString_InternFromString("default");
+            default_str = PyBytes_InternFromString("default");
             if (default_str == NULL)
                 return NULL;
         }
@@ -901,7 +892,7 @@
     if (PyModule_AddObject(m, "once_registry", _once_registry) < 0)
         return;
 
-    default_action = PyString_InternFromString("default");
+    default_action = PyBytes_InternFromString("default");
     if (default_action == NULL)
         return;
     if (PyModule_AddObject(m, DEFAULT_ACTION_NAME, default_action) < 0)

Modified: python/branches/okkoto-sizeof/Python/ast.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/ast.c	(original)
+++ python/branches/okkoto-sizeof/Python/ast.c	Wed Jun  4 11:24:23 2008
@@ -46,7 +46,7 @@
 
 static identifier
 new_identifier(const char* n, PyArena *arena) {
-    PyObject* id = PyString_InternFromString(n);
+    PyObject* id = PyBytes_InternFromString(n);
     PyArena_AddPyObject(arena, id);
     return id;
 }
@@ -352,7 +352,7 @@
     switch (e->kind) {
         case Attribute_kind:
             if (ctx == Store &&
-                !strcmp(PyString_AS_STRING(e->v.Attribute.attr), "None")) {
+                !strcmp(PyBytes_AS_STRING(e->v.Attribute.attr), "None")) {
                 return ast_error(n, "assignment to None");
             }
             e->v.Attribute.ctx = ctx;
@@ -362,7 +362,7 @@
             break;
         case Name_kind:
             if (ctx == Store &&
-                !strcmp(PyString_AS_STRING(e->v.Name.id), "None")) {
+                !strcmp(PyBytes_AS_STRING(e->v.Name.id), "None")) {
                     return ast_error(n, "assignment to None");
             }
             e->v.Name.ctx = ctx;
@@ -1276,7 +1276,7 @@
                 if (errstr) {
                     char *s = "";
                     char buf[128];
-                    s = PyString_AsString(errstr);
+                    s = PyBytes_AsString(errstr);
                     PyOS_snprintf(buf, sizeof(buf), "(unicode error) %s", s);
                     ast_error(n, buf);
                 } else {
@@ -1921,7 +1921,7 @@
                     return NULL;
                 }
                 key = e->v.Name.id;
-                if (!strcmp(PyString_AS_STRING(key), "None")) {
+                if (!strcmp(PyBytes_AS_STRING(key), "None")) {
                     ast_error(CHILD(ch, 0), "assignment to None");
                     return NULL;
                 }
@@ -2050,7 +2050,7 @@
                           "expression not possible");
                 return NULL;
             case Name_kind: {
-                const char *var_name = PyString_AS_STRING(expr1->v.Name.id);
+                const char *var_name = PyBytes_AS_STRING(expr1->v.Name.id);
                 if (var_name[0] == 'N' && !strcmp(var_name, "None")) {
                     ast_error(ch, "assignment to None");
                     return NULL;
@@ -2326,10 +2326,10 @@
                     /* length of string plus one for the dot */
                     len += strlen(STR(CHILD(n, i))) + 1;
                 len--; /* the last name doesn't have a dot */
-                str = PyString_FromStringAndSize(NULL, len);
+                str = PyBytes_FromStringAndSize(NULL, len);
                 if (!str)
                     return NULL;
-                s = PyString_AS_STRING(str);
+                s = PyBytes_AS_STRING(str);
                 if (!s)
                     return NULL;
                 for (i = 0; i < NCH(n); i += 2) {
@@ -2340,13 +2340,13 @@
                 }
                 --s;
                 *s = '\0';
-                PyString_InternInPlace(&str);
+                PyBytes_InternInPlace(&str);
                 PyArena_AddPyObject(c->c_arena, str);
                 return alias(str, NULL, c->c_arena);
             }
             break;
         case STAR:
-            str = PyString_InternFromString("*");
+            str = PyBytes_InternFromString("*");
             PyArena_AddPyObject(c->c_arena, str);
             return alias(str, NULL, c->c_arena);
         default:
@@ -3196,10 +3196,10 @@
                 u = NULL;
         } else {
                 /* "\XX" may become "\u005c\uHHLL" (12 bytes) */
-                u = PyString_FromStringAndSize((char *)NULL, len * 4);
+                u = PyBytes_FromStringAndSize((char *)NULL, len * 4);
                 if (u == NULL)
                         return NULL;
-                p = buf = PyString_AsString(u);
+                p = buf = PyBytes_AsString(u);
                 end = s + len;
                 while (s < end) {
                         if (*s == '\\') {
@@ -3218,8 +3218,8 @@
                                         Py_DECREF(u);
                                         return NULL;
                                 }
-                                r = PyString_AsString(w);
-                                rn = PyString_Size(w);
+                                r = PyBytes_AsString(w);
+                                rn = PyBytes_Size(w);
                                 assert(rn % 2 == 0);
                                 for (i = 0; i < rn; i += 2) {
                                         sprintf(p, "\\u%02x%02x",
@@ -3318,11 +3318,11 @@
                         return v;
 #endif
                 } else {
-                        return PyString_FromStringAndSize(s, len);
+                        return PyBytes_FromStringAndSize(s, len);
                 }
         }
 
-        return PyString_DecodeEscape(s, len, NULL, unicode,
+        return PyBytes_DecodeEscape(s, len, NULL, unicode,
                                      need_encoding ? c->c_encoding : NULL);
 }
 
@@ -3343,8 +3343,8 @@
                         s = parsestr(c, STR(CHILD(n, i)));
                         if (s == NULL)
                                 goto onError;
-                        if (PyString_Check(v) && PyString_Check(s)) {
-                                PyString_ConcatAndDel(&v, s);
+                        if (PyBytes_Check(v) && PyBytes_Check(s)) {
+                                PyBytes_ConcatAndDel(&v, s);
                                 if (v == NULL)
                                     goto onError;
                         }

Modified: python/branches/okkoto-sizeof/Python/bltinmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/bltinmodule.c	(original)
+++ python/branches/okkoto-sizeof/Python/bltinmodule.c	Wed Jun  4 11:24:23 2008
@@ -247,7 +247,7 @@
 		return NULL;
 
 	/* Strings and tuples return a result of the same type. */
-	if (PyString_Check(seq))
+	if (PyBytes_Check(seq))
 		return filterstring(func, seq);
 #ifdef Py_USING_UNICODE
 	if (PyUnicode_Check(seq))
@@ -381,7 +381,7 @@
 		return NULL;
 	}
 	s[0] = (char)x;
-	return PyString_FromStringAndSize(s, 1);
+	return PyBytes_FromStringAndSize(s, 1);
 }
 
 PyDoc_STRVAR(chr_doc,
@@ -652,7 +652,7 @@
 		return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
 	}
 
-	if (!PyString_Check(cmd) &&
+	if (!PyBytes_Check(cmd) &&
 	    !PyUnicode_Check(cmd)) {
 		PyErr_SetString(PyExc_TypeError,
 			   "eval() arg 1 must be a string or code object");
@@ -669,7 +669,7 @@
 		cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
 	}
 #endif
-	if (PyString_AsStringAndSize(cmd, &str, NULL)) {
+	if (PyBytes_AsStringAndSize(cmd, &str, NULL)) {
 		Py_XDECREF(tmp);
 		return NULL;
 	}
@@ -814,7 +814,7 @@
 	}
 #endif
 
-	if (!PyString_Check(name)) {
+	if (!PyBytes_Check(name)) {
 		PyErr_SetString(PyExc_TypeError,
 				"getattr(): attribute name must be string");
 		return NULL;
@@ -870,7 +870,7 @@
 	}
 #endif
 
-	if (!PyString_Check(name)) {
+	if (!PyBytes_Check(name)) {
 		PyErr_SetString(PyExc_TypeError,
 				"hasattr(): attribute name must be string");
 		return NULL;
@@ -1189,7 +1189,7 @@
 		return NULL;
 	}
 	res = (*nb->nb_hex)(v);
-	if (res && !PyString_Check(res)) {
+	if (res && !PyBytes_Check(res)) {
 		PyErr_Format(PyExc_TypeError,
 			     "__hex__ returned non-string (type %.200s)",
 			     res->ob_type->tp_name);
@@ -1249,13 +1249,13 @@
 	PyObject *s;
 	if (!PyArg_ParseTuple(args, "S:intern", &s))
 		return NULL;
-	if (!PyString_CheckExact(s)) {
+	if (!PyBytes_CheckExact(s)) {
 		PyErr_SetString(PyExc_TypeError,
 				"can't intern subclass of string");
 		return NULL;
 	}
 	Py_INCREF(s);
-	PyString_InternInPlace(&s);
+	PyBytes_InternInPlace(&s);
 	return s;
 }
 
@@ -1457,7 +1457,7 @@
 		return NULL;
 	}
 	res = (*nb->nb_oct)(v);
-	if (res && !PyString_Check(res)) {
+	if (res && !PyBytes_Check(res)) {
 		PyErr_Format(PyExc_TypeError,
 			     "__oct__ returned non-string (type %.200s)",
 			     res->ob_type->tp_name);
@@ -1492,16 +1492,16 @@
 	long ord;
 	Py_ssize_t size;
 
-	if (PyString_Check(obj)) {
-		size = PyString_GET_SIZE(obj);
+	if (PyBytes_Check(obj)) {
+		size = PyBytes_GET_SIZE(obj);
 		if (size == 1) {
-			ord = (long)((unsigned char)*PyString_AS_STRING(obj));
+			ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
 			return PyInt_FromLong(ord);
 		}
-	} else if (PyBytes_Check(obj)) {
-		size = PyBytes_GET_SIZE(obj);
+	} else if (PyByteArray_Check(obj)) {
+		size = PyByteArray_GET_SIZE(obj);
 		if (size == 1) {
-			ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
+			ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
 			return PyInt_FromLong(ord);
 		}
 
@@ -1572,14 +1572,14 @@
 			Py_RETURN_NONE;
 	}
 
-	if (sep && sep != Py_None && !PyString_Check(sep) &&
+	if (sep && sep != Py_None && !PyBytes_Check(sep) &&
             !PyUnicode_Check(sep)) {
 		PyErr_Format(PyExc_TypeError,
 			     "sep must be None, str or unicode, not %.200s",
 			     sep->ob_type->tp_name);
 		return NULL;
 	}
-	if (end && end != Py_None && !PyString_Check(end) &&
+	if (end && end != Py_None && !PyBytes_Check(end) &&
 	    !PyUnicode_Check(end)) {
 		PyErr_Format(PyExc_TypeError,
 			     "end must be None, str or unicode, not %.200s",
@@ -1948,7 +1948,7 @@
 			po = PyObject_Str(v);
 			if (po == NULL)
 				return NULL;
-			prompt = PyString_AsString(po);
+			prompt = PyBytes_AsString(po);
 			if (prompt == NULL)
 				return NULL;
 		}
@@ -1976,7 +1976,7 @@
 				result = NULL;
 			}
 			else {
-				result = PyString_FromStringAndSize(s, len-1);
+				result = PyBytes_FromStringAndSize(s, len-1);
 			}
 		}
 		PyMem_FREE(s);
@@ -2305,14 +2305,14 @@
     				return PyFloat_FromDouble(f_result);
 			}
         		if (PyFloat_CheckExact(item)) {
-				PyFPE_START_PROTECT("add", return 0)
+				PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
 				f_result += PyFloat_AS_DOUBLE(item);
 				PyFPE_END_PROTECT(f_result)
 				Py_DECREF(item);
 				continue;
 			}
         		if (PyInt_CheckExact(item)) {
-				PyFPE_START_PROTECT("add", return 0)
+				PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
 				f_result += (double)PyInt_AS_LONG(item);
 				PyFPE_END_PROTECT(f_result)
 				Py_DECREF(item);
@@ -2618,8 +2618,8 @@
 	SETBUILTIN("basestring",	&PyBaseString_Type);
 	SETBUILTIN("bool",		&PyBool_Type);
 	/*	SETBUILTIN("memoryview",        &PyMemoryView_Type); */
-	SETBUILTIN("bytearray",		&PyBytes_Type);
-	SETBUILTIN("bytes",		&PyString_Type);
+	SETBUILTIN("bytearray",		&PyByteArray_Type);
+	SETBUILTIN("bytes",		&PyBytes_Type);
 	SETBUILTIN("buffer",		&PyBuffer_Type);
 	SETBUILTIN("classmethod",	&PyClassMethod_Type);
 #ifndef WITHOUT_COMPLEX
@@ -2639,7 +2639,7 @@
 	SETBUILTIN("set",		&PySet_Type);
 	SETBUILTIN("slice",		&PySlice_Type);
 	SETBUILTIN("staticmethod",	&PyStaticMethod_Type);
-	SETBUILTIN("str",		&PyString_Type);
+	SETBUILTIN("str",		&PyBytes_Type);
 	SETBUILTIN("super",		&PySuper_Type);
 	SETBUILTIN("tuple",		&PyTuple_Type);
 	SETBUILTIN("type",		&PyType_Type);
@@ -2737,7 +2737,7 @@
 {
 	PyObject *result;
 	Py_ssize_t i, j;
-	Py_ssize_t len = PyString_Size(strobj);
+	Py_ssize_t len = PyBytes_Size(strobj);
 	Py_ssize_t outlen = len;
 
 	if (func == Py_None) {
@@ -2745,12 +2745,12 @@
 		 * as no character is ever false and __getitem__
 		 * does return this character. If it's a subclass
 		 * we must go through the __getitem__ loop */
-		if (PyString_CheckExact(strobj)) {
+		if (PyBytes_CheckExact(strobj)) {
 			Py_INCREF(strobj);
 			return strobj;
 		}
 	}
-	if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
+	if ((result = PyBytes_FromStringAndSize(NULL, len)) == NULL)
 		return NULL;
 
 	for (i = j = 0; i < len; ++i) {
@@ -2780,16 +2780,16 @@
 		}
 		if (ok) {
 			Py_ssize_t reslen;
-			if (!PyString_Check(item)) {
+			if (!PyBytes_Check(item)) {
 				PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
 					" __getitem__ returned different type");
 				Py_DECREF(item);
 				goto Fail_1;
 			}
-			reslen = PyString_GET_SIZE(item);
+			reslen = PyBytes_GET_SIZE(item);
 			if (reslen == 1) {
-				PyString_AS_STRING(result)[j++] =
-					PyString_AS_STRING(item)[0];
+				PyBytes_AS_STRING(result)[j++] =
+					PyBytes_AS_STRING(item)[0];
 			} else {
 				/* do we need more space? */
 				Py_ssize_t need = j + reslen + len-i-1;
@@ -2797,15 +2797,15 @@
 					/* overallocate, to avoid reallocations */
 					if (need<2*outlen)
 						need = 2*outlen;
-					if (_PyString_Resize(&result, need)) {
+					if (_PyBytes_Resize(&result, need)) {
 						Py_DECREF(item);
 						return NULL;
 					}
 					outlen = need;
 				}
 				memcpy(
-					PyString_AS_STRING(result) + j,
-					PyString_AS_STRING(item),
+					PyBytes_AS_STRING(result) + j,
+					PyBytes_AS_STRING(item),
 					reslen
 				);
 				j += reslen;
@@ -2815,7 +2815,7 @@
 	}
 
 	if (j < outlen)
-		_PyString_Resize(&result, j);
+		_PyBytes_Resize(&result, j);
 
 	return result;
 

Modified: python/branches/okkoto-sizeof/Python/ceval.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/ceval.c	(original)
+++ python/branches/okkoto-sizeof/Python/ceval.c	Wed Jun  4 11:24:23 2008
@@ -739,7 +739,7 @@
 	consts = co->co_consts;
 	fastlocals = f->f_localsplus;
 	freevars = f->f_localsplus + co->co_nlocals;
-	first_instr = (unsigned char*) PyString_AS_STRING(co->co_code);
+	first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code);
 	/* An explanation is in order for the next line.
 
 	   f->f_lasti now refers to the index of the last instruction
@@ -766,7 +766,7 @@
 	lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
 #endif
 #if defined(Py_DEBUG) || defined(LLTRACE)
-	filename = PyString_AsString(co->co_filename);
+	filename = PyBytes_AsString(co->co_filename);
 #endif
 
 	why = WHY_NOT;
@@ -1147,8 +1147,8 @@
 					goto slow_add;
 				x = PyInt_FromLong(i);
 			}
-			else if (PyString_CheckExact(v) &&
-				 PyString_CheckExact(w)) {
+			else if (PyBytes_CheckExact(v) &&
+				 PyBytes_CheckExact(w)) {
 				x = string_concatenate(v, w, f, next_instr);
 				/* string_concatenate consumed the ref to v */
 				goto skip_decref_vx;
@@ -1349,8 +1349,8 @@
 					goto slow_iadd;
 				x = PyInt_FromLong(i);
 			}
-			else if (PyString_CheckExact(v) &&
-				 PyString_CheckExact(w)) {
+			else if (PyBytes_CheckExact(v) &&
+				 PyBytes_CheckExact(w)) {
 				x = string_concatenate(v, w, f, next_instr);
 				/* string_concatenate consumed the ref to v */
 				goto skip_decref_v;
@@ -1576,9 +1576,9 @@
 				err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
 			if (err == 0) {
 			    /* XXX move into writeobject() ? */
-			    if (PyString_Check(v)) {
-				char *s = PyString_AS_STRING(v);
-				Py_ssize_t len = PyString_GET_SIZE(v);
+			    if (PyBytes_Check(v)) {
+				char *s = PyBytes_AS_STRING(v);
+				Py_ssize_t len = PyBytes_GET_SIZE(v);
 				if (len == 0 ||
 				    !isspace(Py_CHARMASK(s[len-1])) ||
 				    s[len-1] == ' ')
@@ -1705,7 +1705,7 @@
 					retval = POP();
 			}
 			else if (PyExceptionClass_Check(v) ||
-			         PyString_Check(v)) {
+			         PyBytes_Check(v)) {
 				w = POP();
 				u = POP();
 				PyErr_Restore(v, w, u);
@@ -1869,11 +1869,11 @@
 
 		case LOAD_GLOBAL:
 			w = GETITEM(names, oparg);
-			if (PyString_CheckExact(w)) {
+			if (PyBytes_CheckExact(w)) {
 				/* Inline the PyDict_GetItem() calls.
 				   WARNING: this is an extreme speed hack.
 				   Do not try this at home. */
-				long hash = ((PyStringObject *)w)->ob_shash;
+				long hash = ((PyBytesObject *)w)->ob_shash;
 				if (hash != -1) {
 					PyDictObject *d;
 					PyDictEntry *e;
@@ -2726,7 +2726,7 @@
 				PyErr_Format(PyExc_TypeError,
 				    "%.200s() takes %s %d "
 				    "%sargument%s (%d given)",
-				    PyString_AsString(co->co_name),
+				    PyBytes_AsString(co->co_name),
 				    defcount ? "at most" : "exactly",
 				    co->co_argcount,
 				    kwcount ? "non-keyword " : "",
@@ -2756,10 +2756,10 @@
 			PyObject *keyword = kws[2*i];
 			PyObject *value = kws[2*i + 1];
 			int j;
-			if (keyword == NULL || !PyString_Check(keyword)) {
+			if (keyword == NULL || !PyBytes_Check(keyword)) {
 				PyErr_Format(PyExc_TypeError,
 				    "%.200s() keywords must be strings",
-				    PyString_AsString(co->co_name));
+				    PyBytes_AsString(co->co_name));
 				goto fail;
 			}
 			/* XXX slow -- speed up using dictionary? */
@@ -2781,8 +2781,8 @@
 					PyErr_Format(PyExc_TypeError,
 					    "%.200s() got an unexpected "
 					    "keyword argument '%.400s'",
-					    PyString_AsString(co->co_name),
-					    PyString_AsString(keyword));
+					    PyBytes_AsString(co->co_name),
+					    PyBytes_AsString(keyword));
 					goto fail;
 				}
 				PyDict_SetItem(kwdict, keyword, value);
@@ -2793,8 +2793,8 @@
 					     "%.200s() got multiple "
 					     "values for keyword "
 					     "argument '%.400s'",
-					     PyString_AsString(co->co_name),
-					     PyString_AsString(keyword));
+					     PyBytes_AsString(co->co_name),
+					     PyBytes_AsString(keyword));
 					goto fail;
 				}
 				Py_INCREF(value);
@@ -2808,7 +2808,7 @@
 					PyErr_Format(PyExc_TypeError,
 					    "%.200s() takes %s %d "
 					    "%sargument%s (%d given)",
-					    PyString_AsString(co->co_name),
+					    PyBytes_AsString(co->co_name),
 					    ((co->co_flags & CO_VARARGS) ||
 					     defcount) ? "at least"
 						       : "exactly",
@@ -2834,7 +2834,7 @@
 		if (argcount > 0 || kwcount > 0) {
 			PyErr_Format(PyExc_TypeError,
 				     "%.200s() takes no arguments (%d given)",
-				     PyString_AsString(co->co_name),
+				     PyBytes_AsString(co->co_name),
 				     argcount + kwcount);
 			goto fail;
 		}
@@ -2860,11 +2860,11 @@
 		   list so that we can march over it more efficiently?
 		*/
 		for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
-			cellname = PyString_AS_STRING(
+			cellname = PyBytes_AS_STRING(
 				PyTuple_GET_ITEM(co->co_cellvars, i));
 			found = 0;
 			for (j = 0; j < nargs; j++) {
-				argname = PyString_AS_STRING(
+				argname = PyBytes_AS_STRING(
 					PyTuple_GET_ITEM(co->co_varnames, j));
 				if (strcmp(cellname, argname) == 0) {
 					c = PyCell_New(GETLOCAL(j));
@@ -3522,13 +3522,13 @@
 	if (PyMethod_Check(func))
 		return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
 	else if (PyFunction_Check(func))
-		return PyString_AsString(((PyFunctionObject*)func)->func_name);
+		return PyBytes_AsString(((PyFunctionObject*)func)->func_name);
 	else if (PyCFunction_Check(func))
 		return ((PyCFunctionObject*)func)->m_ml->ml_name;
 	else if (PyClass_Check(func))
-		return PyString_AsString(((PyClassObject*)func)->cl_name);
+		return PyBytes_AsString(((PyClassObject*)func)->cl_name);
 	else if (PyInstance_Check(func)) {
-		return PyString_AsString(
+		return PyBytes_AsString(
 			((PyInstanceObject*)func)->in_class->cl_name);
 	} else {
 		return func->ob_type->tp_name;
@@ -3767,7 +3767,7 @@
 				     "for keyword argument '%.200s'",
 				     PyEval_GetFuncName(func),
 				     PyEval_GetFuncDesc(func),
-				     PyString_AsString(key));
+				     PyBytes_AsString(key));
 			Py_DECREF(key);
 			Py_DECREF(value);
 			Py_DECREF(kwdict);
@@ -4086,7 +4086,7 @@
 			length = PyTuple_Size(w);
 			for (i = 0; i < length; i += 1) {
 				PyObject *exc = PyTuple_GET_ITEM(w, i);
-				if (PyString_Check(exc)) {
+				if (PyBytes_Check(exc)) {
 					int ret_val;
 					ret_val = PyErr_WarnEx(
 						PyExc_DeprecationWarning,
@@ -4109,7 +4109,7 @@
 			}
 		}
 		else {
-			if (PyString_Check(w)) {
+			if (PyBytes_Check(w)) {
 				int ret_val;
 				ret_val = PyErr_WarnEx(
 						PyExc_DeprecationWarning,
@@ -4149,7 +4149,7 @@
 	if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
 		PyErr_Format(PyExc_ImportError,
 			     "cannot import name %.230s",
-			     PyString_AsString(name));
+			     PyBytes_AsString(name));
 	}
 	return x;
 }
@@ -4191,8 +4191,8 @@
 			break;
 		}
 		if (skip_leading_underscores &&
-		    PyString_Check(name) &&
-		    PyString_AS_STRING(name)[0] == '_')
+		    PyBytes_Check(name) &&
+		    PyBytes_AS_STRING(name)[0] == '_')
 		{
 			Py_DECREF(name);
 			continue;
@@ -4251,12 +4251,12 @@
 		PyObject *ptype, *pvalue, *ptraceback;
 
 		PyErr_Fetch(&ptype, &pvalue, &ptraceback);
-		if (PyString_Check(pvalue)) {
+		if (PyBytes_Check(pvalue)) {
 			PyObject *newmsg;
-			newmsg = PyString_FromFormat(
+			newmsg = PyBytes_FromFormat(
 				"Error when calling the metaclass bases\n"
 				"    %s",
-				PyString_AS_STRING(pvalue));
+				PyBytes_AS_STRING(pvalue));
 			if (newmsg != NULL) {
 				Py_DECREF(pvalue);
 				pvalue = newmsg;
@@ -4297,7 +4297,7 @@
 	}
 	else if (locals == Py_None)
 		locals = globals;
-	if (!PyString_Check(prog) &&
+	if (!PyBytes_Check(prog) &&
 	    !PyUnicode_Check(prog) &&
 	    !PyCode_Check(prog) &&
 	    !PyFile_Check(prog)) {
@@ -4327,7 +4327,7 @@
 	}
 	else if (PyFile_Check(prog)) {
 		FILE *fp = PyFile_AsFile(prog);
-		char *name = PyString_AsString(PyFile_Name(prog));
+		char *name = PyBytes_AsString(PyFile_Name(prog));
 		PyCompilerFlags cf;
 		if (name == NULL)
 			return -1;
@@ -4353,7 +4353,7 @@
 			cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
 		}
 #endif
-		if (PyString_AsStringAndSize(prog, &str, NULL))
+		if (PyBytes_AsStringAndSize(prog, &str, NULL))
 			return -1;
 		if (PyEval_MergeCompilerFlags(&cf))
 			v = PyRun_StringFlags(str, Py_file_input, globals,
@@ -4378,7 +4378,7 @@
 	if (!obj)
 		return;
 
-	obj_str = PyString_AsString(obj);
+	obj_str = PyBytes_AsString(obj);
 	if (!obj_str)
 		return;
 
@@ -4391,8 +4391,8 @@
 {
 	/* This function implements 'variable += expr' when both arguments
 	   are strings. */
-	Py_ssize_t v_len = PyString_GET_SIZE(v);
-	Py_ssize_t w_len = PyString_GET_SIZE(w);
+	Py_ssize_t v_len = PyBytes_GET_SIZE(v);
+	Py_ssize_t w_len = PyBytes_GET_SIZE(w);
 	Py_ssize_t new_len = v_len + w_len;
 	if (new_len < 0) {
 		PyErr_SetString(PyExc_OverflowError,
@@ -4441,12 +4441,12 @@
 		}
 	}
 
-	if (v->ob_refcnt == 1 && !PyString_CHECK_INTERNED(v)) {
+	if (v->ob_refcnt == 1 && !PyBytes_CHECK_INTERNED(v)) {
 		/* Now we own the last reference to 'v', so we can resize it
 		 * in-place.
 		 */
-		if (_PyString_Resize(&v, new_len) != 0) {
-			/* XXX if _PyString_Resize() fails, 'v' has been
+		if (_PyBytes_Resize(&v, new_len) != 0) {
+			/* XXX if _PyBytes_Resize() fails, 'v' has been
 			 * deallocated so it cannot be put back into
 			 * 'variable'.  The MemoryError is raised when there
 			 * is no value in 'variable', which might (very
@@ -4455,13 +4455,13 @@
 			return NULL;
 		}
 		/* copy 'w' into the newly allocated area of 'v' */
-		memcpy(PyString_AS_STRING(v) + v_len,
-		       PyString_AS_STRING(w), w_len);
+		memcpy(PyBytes_AS_STRING(v) + v_len,
+		       PyBytes_AS_STRING(w), w_len);
 		return v;
 	}
 	else {
 		/* When in-place resizing is not an option. */
-		PyString_Concat(&v, w);
+		PyBytes_Concat(&v, w);
 		return v;
 	}
 }

Modified: python/branches/okkoto-sizeof/Python/codecs.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/codecs.c	(original)
+++ python/branches/okkoto-sizeof/Python/codecs.c	Wed Jun  4 11:24:23 2008
@@ -61,10 +61,10 @@
 	return NULL;
     }
 	
-    v = PyString_FromStringAndSize(NULL, len);
+    v = PyBytes_FromStringAndSize(NULL, len);
     if (v == NULL)
 	return NULL;
-    p = PyString_AS_STRING(v);
+    p = PyBytes_AS_STRING(v);
     for (i = 0; i < len; i++) {
         register char ch = string[i];
         if (ch == ' ')
@@ -112,7 +112,7 @@
     v = normalizestring(encoding);
     if (v == NULL)
 	goto onError;
-    PyString_InternInPlace(&v);
+    PyBytes_InternInPlace(&v);
 
     /* First, try to lookup the name in the registry dictionary */
     result = PyDict_GetItem(interp->codec_search_cache, v);
@@ -190,7 +190,7 @@
     if (errors) {
 	PyObject *v;
 	
-	v = PyString_FromString(errors);
+	v = PyBytes_FromString(errors);
 	if (v == NULL) {
 	    Py_DECREF(args);
 	    return NULL;
@@ -451,7 +451,7 @@
 	    if (string != NULL) {
 	        PyErr_Format(PyExc_TypeError,
 		    "don't know how to handle %.400s in error callback",
-		    PyString_AS_STRING(string));
+		    PyBytes_AS_STRING(string));
 	        Py_DECREF(string);
 	    }
 	}

Modified: python/branches/okkoto-sizeof/Python/compile.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/compile.c	(original)
+++ python/branches/okkoto-sizeof/Python/compile.c	Wed Jun  4 11:24:23 2008
@@ -184,15 +184,15 @@
 {
 	/* Name mangling: __private becomes _classname__private.
 	   This is independent from how the name is used. */
-	const char *p, *name = PyString_AsString(ident);
+	const char *p, *name = PyBytes_AsString(ident);
 	char *buffer;
 	size_t nlen, plen;
-	if (privateobj == NULL || !PyString_Check(privateobj) ||
+	if (privateobj == NULL || !PyBytes_Check(privateobj) ||
 	    name == NULL || name[0] != '_' || name[1] != '_') {
 		Py_INCREF(ident);
 		return ident;
 	}
-	p = PyString_AsString(privateobj);
+	p = PyBytes_AsString(privateobj);
 	nlen = strlen(name);
 	/* Don't mangle __id__ or names with dots.
 
@@ -216,11 +216,11 @@
 		return ident; /* Don't mangle if class is just underscores */
 	}
 	plen = strlen(p);
-	ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
+	ident = PyBytes_FromStringAndSize(NULL, 1 + nlen + plen);
 	if (!ident)
 		return 0;
 	/* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
-	buffer = PyString_AS_STRING(ident);
+	buffer = PyBytes_AS_STRING(ident);
 	buffer[0] = '_';
 	strncpy(buffer+1, p, plen);
 	strcpy(buffer+1+plen, name);
@@ -249,7 +249,7 @@
 	int merged;
 
 	if (!__doc__) {
-		__doc__ = PyString_InternFromString("__doc__");
+		__doc__ = PyBytes_InternFromString("__doc__");
 		if (!__doc__)
 			return NULL;
 	}
@@ -540,7 +540,7 @@
 {
 	char tmpname[256];
 	PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
-	return PyString_FromString(tmpname);
+	return PyBytes_FromString(tmpname);
 }
 
 /* Allocate a new block and return a pointer to it.
@@ -1193,7 +1193,7 @@
 	int addNone = 1;
 	static PyObject *module;
 	if (!module) {
-		module = PyString_InternFromString("<module>");
+		module = PyBytes_InternFromString("<module>");
 		if (!module)
 			return NULL;
 	}
@@ -1245,8 +1245,8 @@
 	    PyOS_snprintf(buf, sizeof(buf),
 			  "unknown scope for %.100s in %.100s(%s) in %s\n"
 			  "symbols: %s\nlocals: %s\nglobals: %s\n",
-			  PyString_AS_STRING(name), 
-			  PyString_AS_STRING(c->u->u_name), 
+			  PyBytes_AS_STRING(name), 
+			  PyBytes_AS_STRING(c->u->u_name), 
 			  PyObject_REPR(c->u->u_ste->ste_id),
 			  c->c_filename,
 			  PyObject_REPR(c->u->u_ste->ste_symbols),
@@ -1304,9 +1304,9 @@
 			printf("lookup %s in %s %d %d\n"
 				"freevars of %s: %s\n",
 				PyObject_REPR(name), 
-				PyString_AS_STRING(c->u->u_name), 
+				PyBytes_AS_STRING(c->u->u_name), 
 				reftype, arg,
-				PyString_AS_STRING(co->co_name),
+				PyBytes_AS_STRING(co->co_name),
 				PyObject_REPR(co->co_freevars));
 			Py_FatalError("compiler_make_closure()");
 		}
@@ -1341,7 +1341,7 @@
 	for (i = 0; i < n; i++) {
 		expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
 		if (arg->kind == Tuple_kind) {
-			PyObject *id = PyString_FromFormat(".%d", i);
+			PyObject *id = PyBytes_FromFormat(".%d", i);
 			if (id == NULL) {
 				return 0;
 			}
@@ -1434,7 +1434,7 @@
 	Py_XDECREF(c->u->u_private);
 	c->u->u_private = s->v.ClassDef.name;
 	Py_INCREF(c->u->u_private);
-	str = PyString_InternFromString("__name__");
+	str = PyBytes_InternFromString("__name__");
 	if (!str || !compiler_nameop(c, str, Load)) {
 		Py_XDECREF(str);
 		compiler_exit_scope(c);
@@ -1442,7 +1442,7 @@
 	}
 	
 	Py_DECREF(str);
-	str = PyString_InternFromString("__module__");
+	str = PyBytes_InternFromString("__module__");
 	if (!str || !compiler_nameop(c, str, Store)) {
 		Py_XDECREF(str);
 		compiler_exit_scope(c);
@@ -1509,7 +1509,7 @@
 	assert(e->kind == Lambda_kind);
 
 	if (!name) {
-		name = PyString_InternFromString("<lambda>");
+		name = PyBytes_InternFromString("<lambda>");
 		if (!name)
 			return 0;
 	}
@@ -1899,7 +1899,7 @@
 	   If there is a dot in name, we need to split it and emit a 
 	   LOAD_ATTR for each name.
 	*/
-	const char *src = PyString_AS_STRING(name);
+	const char *src = PyBytes_AS_STRING(name);
 	const char *dot = strchr(src, '.');
 	if (dot) {
 		/* Consume the base module name to get the first attribute */
@@ -1908,7 +1908,7 @@
 			/* NB src is only defined when dot != NULL */
 			PyObject *attr;
 			dot = strchr(src, '.');
-			attr = PyString_FromStringAndSize(src, 
+			attr = PyBytes_FromStringAndSize(src, 
 					    dot ? dot - src : strlen(src));
 			if (!attr)
 				return -1;
@@ -1957,10 +1957,10 @@
 		}
 		else {
 			identifier tmp = alias->name;
-			const char *base = PyString_AS_STRING(alias->name);
+			const char *base = PyBytes_AS_STRING(alias->name);
 			char *dot = strchr(base, '.');
 			if (dot)
-				tmp = PyString_FromStringAndSize(base, 
+				tmp = PyBytes_FromStringAndSize(base, 
 								 dot - base);
 			r = compiler_nameop(c, tmp, Store);
 			if (dot) {
@@ -2003,7 +2003,7 @@
 	}
 
 	if (s->lineno > c->c_future->ff_lineno) {
-		if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
+		if (!strcmp(PyBytes_AS_STRING(s->v.ImportFrom.module),
 			    "__future__")) {
 			Py_DECREF(level);
 			Py_DECREF(names);
@@ -2023,7 +2023,7 @@
 		alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
 		identifier store_name;
 
-		if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
+		if (i == 0 && *PyBytes_AS_STRING(alias->name) == '*') {
 			assert(n == 1);
 			ADDOP(c, IMPORT_STAR);
 			return 1;
@@ -2053,7 +2053,7 @@
 	if (Py_OptimizeFlag)
 		return 1;
 	if (assertion_error == NULL) {
-		assertion_error = PyString_InternFromString("AssertionError");
+		assertion_error = PyBytes_InternFromString("AssertionError");
 		if (assertion_error == NULL)
 			return 0;
 	}
@@ -2336,7 +2336,7 @@
 
 	/* First check for assignment to __debug__. Param? */
 	if ((ctx == Store || ctx == AugStore || ctx == Del)
-	    && !strcmp(PyString_AS_STRING(name), "__debug__")) {
+	    && !strcmp(PyBytes_AS_STRING(name), "__debug__")) {
 		return compiler_error(c, "can not assign to __debug__");
 	}
 
@@ -2374,7 +2374,7 @@
 	}
 
 	/* XXX Leave assert here, but handle __doc__ and the like better */
-	assert(scope || PyString_AS_STRING(name)[0] == '_');
+	assert(scope || PyBytes_AS_STRING(name)[0] == '_');
 
 	switch (optype) {
 	case OP_DEREF:
@@ -2388,7 +2388,7 @@
 			PyErr_Format(PyExc_SyntaxError,
 				     "can not delete variable '%s' referenced "
 				     "in nested scope",
-				     PyString_AS_STRING(name));
+				     PyBytes_AS_STRING(name));
 			Py_DECREF(mangled);
 			return 0;
 		case Param:
@@ -2773,7 +2773,7 @@
 					       0)))->iter;
 
 	if (!name) {
-		name = PyString_FromString("<genexpr>");
+		name = PyBytes_FromString("<genexpr>");
 		if (!name)
 			return 0;
 	}
@@ -2822,7 +2822,7 @@
 	case Name_kind:
 		/* __debug__ is not assignable, so we can optimize
 		 * it away in if and while statements */
-		if (strcmp(PyString_AS_STRING(e->v.Name.id),
+		if (strcmp(PyBytes_AS_STRING(e->v.Name.id),
 			   "__debug__") == 0)
 			   return ! Py_OptimizeFlag;
 		/* fall through */
@@ -2864,12 +2864,12 @@
     assert(s->kind == With_kind);
 
     if (!enter_attr) {
-	enter_attr = PyString_InternFromString("__enter__");
+	enter_attr = PyBytes_InternFromString("__enter__");
 	if (!enter_attr)
 	    return 0;
     }
     if (!exit_attr) {
-	exit_attr = PyString_InternFromString("__exit__");
+	exit_attr = PyBytes_InternFromString("__exit__");
 	if (!exit_attr)
 	    return 0;
     }
@@ -3472,10 +3472,10 @@
 {
 	memset(a, 0, sizeof(struct assembler));
 	a->a_lineno = firstlineno;
-	a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
+	a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
 	if (!a->a_bytecode)
 		return 0;
-	a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
+	a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
 	if (!a->a_lnotab)
 		return 0;
 	a->a_postorder = (basicblock **)PyObject_Malloc(
@@ -3584,17 +3584,17 @@
 	if (d_bytecode > 255) {
 		int j, nbytes, ncodes = d_bytecode / 255;
 		nbytes = a->a_lnotab_off + 2 * ncodes;
-		len = PyString_GET_SIZE(a->a_lnotab);
+		len = PyBytes_GET_SIZE(a->a_lnotab);
 		if (nbytes >= len) {
 			if (len * 2 < nbytes)
 				len = nbytes;
 			else
 				len *= 2;
-			if (_PyString_Resize(&a->a_lnotab, len) < 0)
+			if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
 				return 0;
 		}
 		lnotab = (unsigned char *)
-			   PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
+			   PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
 		for (j = 0; j < ncodes; j++) {
 			*lnotab++ = 255;
 			*lnotab++ = 0;
@@ -3606,17 +3606,17 @@
 	if (d_lineno > 255) {
 		int j, nbytes, ncodes = d_lineno / 255;
 		nbytes = a->a_lnotab_off + 2 * ncodes;
-		len = PyString_GET_SIZE(a->a_lnotab);
+		len = PyBytes_GET_SIZE(a->a_lnotab);
 		if (nbytes >= len) {
 			if (len * 2 < nbytes)
 				len = nbytes;
 			else
 				len *= 2;
-			if (_PyString_Resize(&a->a_lnotab, len) < 0)
+			if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
 				return 0;
 		}
 		lnotab = (unsigned char *)
-			   PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
+			   PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
 		*lnotab++ = d_bytecode;
 		*lnotab++ = 255;
 		d_bytecode = 0;
@@ -3628,13 +3628,13 @@
 		a->a_lnotab_off += ncodes * 2;
 	}
 
-	len = PyString_GET_SIZE(a->a_lnotab);
+	len = PyBytes_GET_SIZE(a->a_lnotab);
 	if (a->a_lnotab_off + 2 >= len) {
-		if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
+		if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
 			return 0;
 	}
 	lnotab = (unsigned char *)
-			PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
+			PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
 
 	a->a_lnotab_off += 2;
 	if (d_bytecode) {
@@ -3659,7 +3659,7 @@
 assemble_emit(struct assembler *a, struct instr *i)
 {
 	int size, arg = 0, ext = 0;
-	Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
+	Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
 	char *code;
 
 	size = instrsize(i);
@@ -3670,10 +3670,10 @@
 	if (i->i_lineno && !assemble_lnotab(a, i))
 		return 0;
 	if (a->a_offset + size >= len) {
-		if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
+		if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
 		    return 0;
 	}
-	code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
+	code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
 	a->a_offset += size;
 	if (size == 6) {
 		assert(i->i_hasarg);
@@ -3846,7 +3846,7 @@
 	freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
 	if (!freevars)
 	    goto error;
-	filename = PyString_FromString(c->c_filename);
+	filename = PyBytes_FromString(c->c_filename);
 	if (!filename)
 		goto error;
 
@@ -3966,9 +3966,9 @@
 				goto error;
 	}
 
-	if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
+	if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
 		goto error;
-	if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
+	if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
 		goto error;
 
 	co = makecode(c, &a);

Modified: python/branches/okkoto-sizeof/Python/errors.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/errors.c	(original)
+++ python/branches/okkoto-sizeof/Python/errors.c	Wed Jun  4 11:24:23 2008
@@ -66,7 +66,7 @@
 void
 PyErr_SetString(PyObject *exception, const char *string)
 {
-	PyObject *value = PyString_FromString(string);
+	PyObject *value = PyBytes_FromString(string);
 	PyErr_SetObject(exception, value);
 	Py_XDECREF(value);
 }
@@ -351,7 +351,7 @@
 PyObject *
 PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
 {
-	PyObject *name = filename ? PyString_FromString(filename) : NULL;
+	PyObject *name = filename ? PyBytes_FromString(filename) : NULL;
 	PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
 	Py_XDECREF(name);
 	return result;
@@ -430,7 +430,7 @@
 	int ierr,
 	const char *filename)
 {
-	PyObject *name = filename ? PyString_FromString(filename) : NULL;
+	PyObject *name = filename ? PyBytes_FromString(filename) : NULL;
 	PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
 	                                                             ierr,
 	                                                             name);
@@ -469,7 +469,7 @@
 	int ierr,
 	const char *filename)
 {
-	PyObject *name = filename ? PyString_FromString(filename) : NULL;
+	PyObject *name = filename ? PyBytes_FromString(filename) : NULL;
 	PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
 						      PyExc_WindowsError,
 						      ierr, name);
@@ -527,7 +527,7 @@
 	va_start(vargs);
 #endif
 
-	string = PyString_FromFormatV(format, vargs);
+	string = PyBytes_FromFormatV(format, vargs);
 	PyErr_SetObject(exception, string);
 	Py_XDECREF(string);
 	va_end(vargs);
@@ -559,7 +559,7 @@
 			goto failure;
 	}
 	if (PyDict_GetItemString(dict, "__module__") == NULL) {
-		modulename = PyString_FromStringAndSize(name,
+		modulename = PyBytes_FromStringAndSize(name,
 						     (Py_ssize_t)(dot-name));
 		if (modulename == NULL)
 			goto failure;
@@ -611,7 +611,7 @@
 			if (moduleName == NULL)
 				PyFile_WriteString("<unknown>", f);
 			else {
-				char* modstr = PyString_AsString(moduleName);
+				char* modstr = PyBytes_AsString(moduleName);
 				if (modstr &&
 				    strcmp(modstr, "exceptions") != 0)
 				{
@@ -665,7 +665,7 @@
 		Py_DECREF(tmp);
 	}
 	if (filename != NULL) {
-		tmp = PyString_FromString(filename);
+		tmp = PyBytes_FromString(filename);
 		if (tmp == NULL)
 			PyErr_Clear();
 		else {
@@ -742,7 +742,7 @@
 		char *p = linebuf;
 		while (*p == ' ' || *p == '\t' || *p == '\014')
 			p++;
-		return PyString_FromString(p);
+		return PyBytes_FromString(p);
 	}
 	return NULL;
 }

Modified: python/branches/okkoto-sizeof/Python/formatter_string.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/formatter_string.c	(original)
+++ python/branches/okkoto-sizeof/Python/formatter_string.c	Wed Jun  4 11:24:23 2008
@@ -4,12 +4,11 @@
    of int.__float__, etc., that take and return string objects */
 
 #include "Python.h"
-#include "formatter_string.h"
-
 #include "../Objects/stringlib/stringdefs.h"
 
-#define FORMAT_STRING string__format__
-#define FORMAT_LONG   string_long__format__
-#define FORMAT_INT    string_int__format__
-#define FORMAT_FLOAT  string_float__format__
+#define FORMAT_STRING _PyBytes_FormatAdvanced
+#define FORMAT_LONG   _PyLong_FormatAdvanced
+#define FORMAT_INT    _PyInt_FormatAdvanced
+#define FORMAT_FLOAT  _PyFloat_FormatAdvanced
+
 #include "../Objects/stringlib/formatter.h"

Modified: python/branches/okkoto-sizeof/Python/formatter_unicode.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/formatter_unicode.c	(original)
+++ python/branches/okkoto-sizeof/Python/formatter_unicode.c	Wed Jun  4 11:24:23 2008
@@ -2,12 +2,12 @@
    built-in formatter for unicode.  That is, unicode.__format__(). */
 
 #include "Python.h"
-#include "formatter_unicode.h"
-
 #include "../Objects/stringlib/unicodedefs.h"
 
-#define FORMAT_STRING unicode__format__
+#define FORMAT_STRING _PyUnicode_FormatAdvanced
+
 /* don't define FORMAT_LONG and FORMAT_FLOAT, since we can live
    with only the string versions of those.  The builtin format()
    will convert them to unicode. */
+
 #include "../Objects/stringlib/formatter.h"

Modified: python/branches/okkoto-sizeof/Python/future.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/future.c	(original)
+++ python/branches/okkoto-sizeof/Python/future.c	Wed Jun  4 11:24:23 2008
@@ -20,7 +20,7 @@
 	names = s->v.ImportFrom.names;
 	for (i = 0; i < asdl_seq_LEN(names); i++) {
                 alias_ty name = (alias_ty)asdl_seq_GET(names, i);
-		const char *feature = PyString_AsString(name->name);
+		const char *feature = PyBytes_AsString(name->name);
 		if (!feature)
 			return 0;
 		if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) {
@@ -59,7 +59,7 @@
 
 	static PyObject *future;
 	if (!future) {
-		future = PyString_InternFromString("__future__");
+		future = PyBytes_InternFromString("__future__");
 		if (!future)
 			return 0;
 	}

Modified: python/branches/okkoto-sizeof/Python/getargs.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/getargs.c	(original)
+++ python/branches/okkoto-sizeof/Python/getargs.c	Wed Jun  4 11:24:23 2008
@@ -418,7 +418,7 @@
 			n++;
 	}
 	
-	if (!PySequence_Check(arg) || PyString_Check(arg)) {
+	if (!PySequence_Check(arg) || PyBytes_Check(arg)) {
 		levels[0] = 0;
 		PyOS_snprintf(msgbuf, bufsize,
 			      toplevel ? "expected %d arguments, not %.50s" :
@@ -765,8 +765,8 @@
 	
 	case 'c': {/* char */
 		char *p = va_arg(*p_va, char *);
-		if (PyString_Check(arg) && PyString_Size(arg) == 1)
-			*p = PyString_AS_STRING(arg)[0];
+		if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1)
+			*p = PyBytes_AS_STRING(arg)[0];
 		else
 			return converterr("char", arg, msgbuf, bufsize);
 		break;
@@ -777,9 +777,9 @@
 			void **p = (void **)va_arg(*p_va, char **);
 			FETCH_SIZE;
 			
-			if (PyString_Check(arg)) {
-				*p = PyString_AS_STRING(arg);
-				STORE_SIZE(PyString_GET_SIZE(arg));
+			if (PyBytes_Check(arg)) {
+				*p = PyBytes_AS_STRING(arg);
+				STORE_SIZE(PyBytes_GET_SIZE(arg));
 			}
 #ifdef Py_USING_UNICODE
 			else if (PyUnicode_Check(arg)) {
@@ -787,8 +787,8 @@
 				if (uarg == NULL)
 					return converterr(CONV_UNICODE,
 							  arg, msgbuf, bufsize);
-				*p = PyString_AS_STRING(uarg);
-				STORE_SIZE(PyString_GET_SIZE(uarg));
+				*p = PyBytes_AS_STRING(uarg);
+				STORE_SIZE(PyBytes_GET_SIZE(uarg));
 			}
 #endif
 			else { /* any buffer-like object */
@@ -802,20 +802,20 @@
 		} else {
 			char **p = va_arg(*p_va, char **);
 			
-			if (PyString_Check(arg))
-				*p = PyString_AS_STRING(arg);
+			if (PyBytes_Check(arg))
+				*p = PyBytes_AS_STRING(arg);
 #ifdef Py_USING_UNICODE
 			else if (PyUnicode_Check(arg)) {
 				uarg = UNICODE_DEFAULT_ENCODING(arg);
 				if (uarg == NULL)
 					return converterr(CONV_UNICODE,
 							  arg, msgbuf, bufsize);
-				*p = PyString_AS_STRING(uarg);
+				*p = PyBytes_AS_STRING(uarg);
 			}
 #endif
 			else
 				return converterr("string", arg, msgbuf, bufsize);
-			if ((Py_ssize_t)strlen(*p) != PyString_Size(arg))
+			if ((Py_ssize_t)strlen(*p) != PyBytes_Size(arg))
 				return converterr("string without null bytes",
 						  arg, msgbuf, bufsize);
 		}
@@ -831,9 +831,9 @@
 				*p = 0;
 				STORE_SIZE(0);
 			}
-			else if (PyString_Check(arg)) {
-				*p = PyString_AS_STRING(arg);
-				STORE_SIZE(PyString_GET_SIZE(arg));
+			else if (PyBytes_Check(arg)) {
+				*p = PyBytes_AS_STRING(arg);
+				STORE_SIZE(PyBytes_GET_SIZE(arg));
 			}
 #ifdef Py_USING_UNICODE
 			else if (PyUnicode_Check(arg)) {
@@ -841,8 +841,8 @@
 				if (uarg == NULL)
 					return converterr(CONV_UNICODE,
 							  arg, msgbuf, bufsize);
-				*p = PyString_AS_STRING(uarg);
-				STORE_SIZE(PyString_GET_SIZE(uarg));
+				*p = PyBytes_AS_STRING(uarg);
+				STORE_SIZE(PyBytes_GET_SIZE(uarg));
 			}
 #endif
 			else { /* any buffer-like object */
@@ -858,15 +858,15 @@
 			
 			if (arg == Py_None)
 				*p = 0;
-			else if (PyString_Check(arg))
-				*p = PyString_AS_STRING(arg);
+			else if (PyBytes_Check(arg))
+				*p = PyBytes_AS_STRING(arg);
 #ifdef Py_USING_UNICODE
 			else if (PyUnicode_Check(arg)) {
 				uarg = UNICODE_DEFAULT_ENCODING(arg);
 				if (uarg == NULL)
 					return converterr(CONV_UNICODE,
 							  arg, msgbuf, bufsize);
-				*p = PyString_AS_STRING(uarg);
+				*p = PyBytes_AS_STRING(uarg);
 			}
 #endif
 			else
@@ -878,11 +878,11 @@
 				if (arg == Py_None)
 					*q = 0;
 				else
-					*q = PyString_Size(arg);
+					*q = PyBytes_Size(arg);
 				format++;
 			}
 			else if (*p != NULL &&
-				 (Py_ssize_t)strlen(*p) != PyString_Size(arg))
+				 (Py_ssize_t)strlen(*p) != PyBytes_Size(arg))
 				return converterr(
 					"string without null bytes or None", 
 					arg, msgbuf, bufsize);
@@ -923,7 +923,7 @@
 					  arg, msgbuf, bufsize);
 			
 		/* Encode object */
-		if (!recode_strings && PyString_Check(arg)) {
+		if (!recode_strings && PyBytes_Check(arg)) {
 			s = arg;
 			Py_INCREF(s);
 		}
@@ -946,7 +946,7 @@
 			if (s == NULL)
 				return converterr("(encoding failed)",
 						  arg, msgbuf, bufsize);
-			if (!PyString_Check(s)) {
+			if (!PyBytes_Check(s)) {
 				Py_DECREF(s);
 				return converterr(
 					"(encoder failed to return a string)",
@@ -956,7 +956,7 @@
 			return converterr("string<e>", arg, msgbuf, bufsize);
 #endif
 		}
-		size = PyString_GET_SIZE(s);
+		size = PyBytes_GET_SIZE(s);
 
 		/* Write output; output is guaranteed to be 0-terminated */
 		if (*format == '#') { 
@@ -1013,7 +1013,7 @@
 				}
 			}
 			memcpy(*buffer,
-			       PyString_AS_STRING(s),
+			       PyBytes_AS_STRING(s),
 			       size + 1);
 			STORE_SIZE(size);
 		} else {
@@ -1030,7 +1030,7 @@
 			   PyMem_Free()ing it after usage
 
 			*/
-			if ((Py_ssize_t)strlen(PyString_AS_STRING(s))
+			if ((Py_ssize_t)strlen(PyBytes_AS_STRING(s))
 								!= size) {
 				Py_DECREF(s);
 				return converterr(
@@ -1049,7 +1049,7 @@
 						arg, msgbuf, bufsize);
 			}
 			memcpy(*buffer,
-			       PyString_AS_STRING(s),
+			       PyBytes_AS_STRING(s),
 			       size + 1);
 		}
 		Py_DECREF(s);
@@ -1083,7 +1083,7 @@
 
 	case 'S': { /* string object */
 		PyObject **p = va_arg(*p_va, PyObject **);
-		if (PyString_Check(arg))
+		if (PyBytes_Check(arg))
 			*p = arg;
 		else
 			return converterr("string", arg, msgbuf, bufsize);
@@ -1473,12 +1473,12 @@
 		while (PyDict_Next(keywords, &pos, &key, &value)) {
 			int match = 0;
 			char *ks;
-			if (!PyString_Check(key)) {
+			if (!PyBytes_Check(key)) {
 				PyErr_SetString(PyExc_TypeError, 
 					        "keywords must be strings");
 				return cleanreturn(0, freelist);
 			}
-			ks = PyString_AsString(key);
+			ks = PyBytes_AsString(key);
 			for (i = 0; i < len; i++) {
 				if (!strcmp(ks, kwlist[i])) {
 					match = 1;

Modified: python/branches/okkoto-sizeof/Python/import.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/import.c	(original)
+++ python/branches/okkoto-sizeof/Python/import.c	Wed Jun  4 11:24:23 2008
@@ -467,8 +467,8 @@
 		while (PyDict_Next(modules, &pos, &key, &value)) {
 			if (value->ob_refcnt != 1)
 				continue;
-			if (PyString_Check(key) && PyModule_Check(value)) {
-				name = PyString_AS_STRING(key);
+			if (PyBytes_Check(key) && PyModule_Check(value)) {
+				name = PyBytes_AS_STRING(key);
 				if (strcmp(name, "__builtin__") == 0)
 					continue;
 				if (strcmp(name, "sys") == 0)
@@ -486,8 +486,8 @@
 	/* Next, delete all modules (still skipping __builtin__ and sys) */
 	pos = 0;
 	while (PyDict_Next(modules, &pos, &key, &value)) {
-		if (PyString_Check(key) && PyModule_Check(value)) {
-			name = PyString_AS_STRING(key);
+		if (PyBytes_Check(key) && PyModule_Check(value)) {
+			name = PyBytes_AS_STRING(key);
 			if (strcmp(name, "__builtin__") == 0)
 				continue;
 			if (strcmp(name, "sys") == 0)
@@ -665,7 +665,7 @@
 	/* Remember the filename as the __file__ attribute */
 	v = NULL;
 	if (pathname != NULL) {
-		v = PyString_FromString(pathname);
+		v = PyBytes_FromString(pathname);
 		if (v == NULL)
 			PyErr_Clear();
 	}
@@ -1002,7 +1002,7 @@
 		PySys_WriteStderr("import %s # directory %s\n",
 			name, pathname);
 	d = PyModule_GetDict(m);
-	file = PyString_FromString(pathname);
+	file = PyBytes_FromString(pathname);
 	if (file == NULL)
 		goto error;
 	path = Py_BuildValue("[O]", file);
@@ -1214,15 +1214,15 @@
 		Py_DECREF(meta_path);
 	}
 
-	if (path != NULL && PyString_Check(path)) {
+	if (path != NULL && PyBytes_Check(path)) {
 		/* The only type of submodule allowed inside a "frozen"
 		   package are other frozen modules or packages. */
-		if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
+		if (PyBytes_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
 			PyErr_SetString(PyExc_ImportError,
 					"full frozen module name too long");
 			return NULL;
 		}
-		strcpy(buf, PyString_AsString(path));
+		strcpy(buf, PyBytes_AsString(path));
 		strcat(buf, ".");
 		strcat(buf, name);
 		strcpy(name, buf);
@@ -1291,14 +1291,14 @@
 		}
 		else
 #endif
-		if (!PyString_Check(v))
+		if (!PyBytes_Check(v))
 			continue;
-		len = PyString_GET_SIZE(v);
+		len = PyBytes_GET_SIZE(v);
 		if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
 			Py_XDECREF(copy);
 			continue; /* Too long */
 		}
-		strcpy(buf, PyString_AS_STRING(v));
+		strcpy(buf, PyBytes_AS_STRING(v));
 		if (strlen(buf) != len) {
 			Py_XDECREF(copy);
 			continue; /* v contains '\0' */
@@ -1963,7 +1963,7 @@
 		if (m == NULL)
 			goto err_return;
 		d = PyModule_GetDict(m);
-		s = PyString_InternFromString(name);
+		s = PyBytes_InternFromString(name);
 		if (s == NULL)
 			goto err_return;
 		err = PyDict_SetItemString(d, "__path__", s);
@@ -1992,7 +1992,7 @@
 	PyObject *pname;
 	PyObject *result;
 
-	pname = PyString_FromString(name);
+	pname = PyBytes_FromString(name);
 	if (pname == NULL)
 		return NULL;
 	result = PyImport_Import(pname);
@@ -2165,17 +2165,17 @@
 		return Py_None;
 
 	if (namestr == NULL) {
-		namestr = PyString_InternFromString("__name__");
+		namestr = PyBytes_InternFromString("__name__");
 		if (namestr == NULL)
 			return NULL;
 	}
 	if (pathstr == NULL) {
-		pathstr = PyString_InternFromString("__path__");
+		pathstr = PyBytes_InternFromString("__path__");
 		if (pathstr == NULL)
 			return NULL;
 	}
 	if (pkgstr == NULL) {
-		pkgstr = PyString_InternFromString("__package__");
+		pkgstr = PyBytes_InternFromString("__package__");
 		if (pkgstr == NULL)
 			return NULL;
 	}
@@ -2187,12 +2187,12 @@
 	if ((pkgname != NULL) && (pkgname != Py_None)) {
 		/* __package__ is set, so use it */
 		Py_ssize_t len;
-		if (!PyString_Check(pkgname)) {
+		if (!PyBytes_Check(pkgname)) {
 			PyErr_SetString(PyExc_ValueError,
 					"__package__ set to non-string");
 			return NULL;
 		}
-		len = PyString_GET_SIZE(pkgname);
+		len = PyBytes_GET_SIZE(pkgname);
 		if (len == 0) {
 			if (level > 0) {
 				PyErr_SetString(PyExc_ValueError,
@@ -2206,24 +2206,24 @@
 					"Package name too long");
 			return NULL;
 		}
-		strcpy(buf, PyString_AS_STRING(pkgname));
+		strcpy(buf, PyBytes_AS_STRING(pkgname));
 	} else {
 		/* __package__ not set, so figure it out and set it */
 		modname = PyDict_GetItem(globals, namestr);
-		if (modname == NULL || !PyString_Check(modname))
+		if (modname == NULL || !PyBytes_Check(modname))
 			return Py_None;
 	
 		modpath = PyDict_GetItem(globals, pathstr);
 		if (modpath != NULL) {
 			/* __path__ is set, so modname is already the package name */
-			Py_ssize_t len = PyString_GET_SIZE(modname);
+			Py_ssize_t len = PyBytes_GET_SIZE(modname);
 			int error;
 			if (len > MAXPATHLEN) {
 				PyErr_SetString(PyExc_ValueError,
 						"Module name too long");
 				return NULL;
 			}
-			strcpy(buf, PyString_AS_STRING(modname));
+			strcpy(buf, PyBytes_AS_STRING(modname));
 			error = PyDict_SetItem(globals, pkgstr, modname);
 			if (error) {
 				PyErr_SetString(PyExc_ValueError,
@@ -2232,7 +2232,7 @@
 			}
 		} else {
 			/* Normal module, so work out the package name if any */
-			char *start = PyString_AS_STRING(modname);
+			char *start = PyBytes_AS_STRING(modname);
 			char *lastdot = strrchr(start, '.');
 			size_t len;
 			int error;
@@ -2258,7 +2258,7 @@
 			}
 			strncpy(buf, start, len);
 			buf[len] = '\0';
-			pkgname = PyString_FromString(buf);
+			pkgname = PyBytes_FromString(buf);
 			if (pkgname == NULL) {
 				return NULL;
 			}
@@ -2394,13 +2394,13 @@
 			}
 			return 0;
 		}
-		if (!PyString_Check(item)) {
+		if (!PyBytes_Check(item)) {
 			PyErr_SetString(PyExc_TypeError,
 					"Item in ``from list'' not a string");
 			Py_DECREF(item);
 			return 0;
 		}
-		if (PyString_AS_STRING(item)[0] == '*') {
+		if (PyBytes_AS_STRING(item)[0] == '*') {
 			PyObject *all;
 			Py_DECREF(item);
 			/* See if the package defines __all__ */
@@ -2419,7 +2419,7 @@
 		}
 		hasit = PyObject_HasAttr(mod, item);
 		if (!hasit) {
-			char *subname = PyString_AS_STRING(item);
+			char *subname = PyBytes_AS_STRING(item);
 			PyObject *submod;
 			char *p;
 			if (buflen + strlen(subname) >= MAXPATHLEN) {
@@ -2585,7 +2585,7 @@
 		subname = name;
 	else {
 		PyObject *parentname, *parent;
-		parentname = PyString_FromStringAndSize(name, (subname-name));
+		parentname = PyBytes_FromStringAndSize(name, (subname-name));
 		if (parentname == NULL) {
 			imp_modules_reloading_clear();
 			return NULL;
@@ -2594,7 +2594,7 @@
 		if (parent == NULL) {
 			PyErr_Format(PyExc_ImportError,
 			    "reload(): parent %.200s not in sys.modules",
-			    PyString_AS_STRING(parentname));
+			    PyBytes_AS_STRING(parentname));
 			Py_DECREF(parentname);
 			imp_modules_reloading_clear();
 			return NULL;
@@ -2639,7 +2639,7 @@
    done using whatever import hooks are installed in the current
    environment, e.g. by "rexec".
    A dummy list ["__doc__"] is passed as the 4th argument so that
-   e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
+   e.g. PyImport_Import(PyBytes_FromString("win32com.client.gencache"))
    will return <module "gencache"> instead of <module "win32com">. */
 
 PyObject *
@@ -2655,10 +2655,10 @@
 
 	/* Initialize constant string objects */
 	if (silly_list == NULL) {
-		import_str = PyString_InternFromString("__import__");
+		import_str = PyBytes_InternFromString("__import__");
 		if (import_str == NULL)
 			return NULL;
-		builtins_str = PyString_InternFromString("__builtins__");
+		builtins_str = PyBytes_InternFromString("__builtins__");
 		if (builtins_str == NULL)
 			return NULL;
 		silly_list = Py_BuildValue("[s]", "__doc__");
@@ -2726,7 +2726,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/okkoto-sizeof/Python/mactoolboxglue.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/mactoolboxglue.c	(original)
+++ python/branches/okkoto-sizeof/Python/mactoolboxglue.c	Wed Jun  4 11:24:23 2008
@@ -52,7 +52,7 @@
 		buf[0] = '\0';
 	}
 	else {
-		char *input = PyString_AsString(rv);
+		char *input = PyBytes_AsString(rv);
 		if (!input) {
 			PyErr_Clear();
 			buf[0] = '\0';
@@ -124,7 +124,7 @@
 	if (!rv)
 		goto error;
 
-	input = PyString_AsString(rv);
+	input = PyBytes_AsString(rv);
 	if (!input)
 		goto error;
 
@@ -159,12 +159,12 @@
 PyMac_GetOSType(PyObject *v, OSType *pr)
 {
 	uint32_t tmp;
-	if (!PyString_Check(v) || PyString_Size(v) != 4) {
+	if (!PyBytes_Check(v) || PyBytes_Size(v) != 4) {
 		PyErr_SetString(PyExc_TypeError,
 			"OSType arg must be string of 4 chars");
 		return 0;
 	}
-	memcpy((char *)&tmp, PyString_AsString(v), 4);
+	memcpy((char *)&tmp, PyBytes_AsString(v), 4);
 	*pr = (OSType)ntohl(tmp);
 	return 1;
 }
@@ -174,7 +174,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 */
@@ -190,13 +190,13 @@
 PyMac_GetStr255(PyObject *v, Str255 pbuf)
 {
 	int len;
-	if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
+	if (!PyBytes_Check(v) || (len = PyBytes_Size(v)) > 255) {
 		PyErr_SetString(PyExc_TypeError,
 			"Str255 arg must be string of at most 255 chars");
 		return 0;
 	}
 	pbuf[0] = len;
-	memcpy((char *)(pbuf+1), PyString_AsString(v), len);
+	memcpy((char *)(pbuf+1), PyBytes_AsString(v), len);
 	return 1;
 }
 
@@ -208,7 +208,7 @@
 		PyErr_SetString(PyExc_SystemError, "Str255 pointer is NULL");
 		return NULL;
 	}
-	return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
+	return PyBytes_FromStringAndSize((char *)&s[1], (int)s[0]);
 }
 
 PyObject *
@@ -218,7 +218,7 @@
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
-	return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
+	return PyBytes_FromStringAndSize((char *)&s[1], (int)s[0]);
 }
 
 

Modified: python/branches/okkoto-sizeof/Python/marshal.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/marshal.c	(original)
+++ python/branches/okkoto-sizeof/Python/marshal.c	Wed Jun  4 11:24:23 2008
@@ -64,18 +64,18 @@
 	Py_ssize_t size, newsize;
 	if (p->str == NULL)
 		return; /* An error already occurred */
-	size = PyString_Size(p->str);
+	size = PyBytes_Size(p->str);
 	newsize = size + size + 1024;
 	if (newsize > 32*1024*1024) {
 		newsize = size + 1024*1024;
 	}
-	if (_PyString_Resize(&p->str, newsize) != 0) {
+	if (_PyBytes_Resize(&p->str, newsize) != 0) {
 		p->ptr = p->end = NULL;
 	}
 	else {
-		p->ptr = PyString_AS_STRING((PyStringObject *)p->str) + size;
+		p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size;
 		p->end =
-			PyString_AS_STRING((PyStringObject *)p->str) + newsize;
+			PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize;
 		*p->ptr++ = Py_SAFE_DOWNCAST(c, int, char);
 	}
 }
@@ -239,8 +239,8 @@
 		}
 	}
 #endif
-	else if (PyString_CheckExact(v)) {
-		if (p->strings && PyString_CHECK_INTERNED(v)) {
+	else if (PyBytes_CheckExact(v)) {
+		if (p->strings && PyBytes_CHECK_INTERNED(v)) {
 			PyObject *o = PyDict_GetItem(p->strings, v);
 			if (o) {
 				long w = PyInt_AsLong(o);
@@ -265,7 +265,7 @@
 		else {
 			w_byte(TYPE_STRING, p);
 		}
-		n = PyString_GET_SIZE(v);
+		n = PyBytes_GET_SIZE(v);
 		if (n > INT_MAX) {
 			/* huge strings are not supported */
 			p->depth--;
@@ -273,7 +273,7 @@
 			return;
 		}
 		w_long((long)n, p);
-		w_string(PyString_AS_STRING(v), (int)n, p);
+		w_string(PyBytes_AS_STRING(v), (int)n, p);
 	}
 #ifdef Py_USING_UNICODE
 	else if (PyUnicode_CheckExact(v)) {
@@ -285,14 +285,14 @@
 			return;
 		}
 		w_byte(TYPE_UNICODE, p);
-		n = PyString_GET_SIZE(utf8);
+		n = PyBytes_GET_SIZE(utf8);
 		if (n > INT_MAX) {
 			p->depth--;
 			p->error = 1;
 			return;
 		}
 		w_long((long)n, p);
-		w_string(PyString_AS_STRING(utf8), (int)n, p);
+		w_string(PyBytes_AS_STRING(utf8), (int)n, p);
 		Py_DECREF(utf8);
 	}
 #endif
@@ -713,12 +713,12 @@
 			retval = NULL;
 			break;
 		}
-		v = PyString_FromStringAndSize((char *)NULL, n);
+		v = PyBytes_FromStringAndSize((char *)NULL, n);
 		if (v == NULL) {
 			retval = NULL;
 			break;
 		}
-		if (r_string(PyString_AS_STRING(v), (int)n, p) != n) {
+		if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) {
 			Py_DECREF(v);
 			PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
@@ -726,7 +726,7 @@
 			break;
 		}
 		if (type == TYPE_INTERNED) {
-			PyString_InternInPlace(&v);
+			PyBytes_InternInPlace(&v);
 			if (PyList_Append(p->strings, v) < 0) {
 				retval = NULL;
 				break;
@@ -1113,11 +1113,11 @@
 {
 	WFILE wf;
 	wf.fp = NULL;
-	wf.str = PyString_FromStringAndSize((char *)NULL, 50);
+	wf.str = PyBytes_FromStringAndSize((char *)NULL, 50);
 	if (wf.str == NULL)
 		return NULL;
-	wf.ptr = PyString_AS_STRING((PyStringObject *)wf.str);
-	wf.end = wf.ptr + PyString_Size(wf.str);
+	wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str);
+	wf.end = wf.ptr + PyBytes_Size(wf.str);
 	wf.error = 0;
 	wf.depth = 0;
 	wf.version = version;
@@ -1125,14 +1125,14 @@
 	w_object(x, &wf);
 	Py_XDECREF(wf.strings);
 	if (wf.str != NULL) {
-		char *base = PyString_AS_STRING((PyStringObject *)wf.str);
+		char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str);
 		if (wf.ptr - base > PY_SSIZE_T_MAX) {
 			Py_DECREF(wf.str);
 			PyErr_SetString(PyExc_OverflowError,
 					"too much marshall data for a string");
 			return NULL;
 		}
-		_PyString_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base));
+		_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base));
 	}
 	if (wf.error) {
 		Py_XDECREF(wf.str);

Modified: python/branches/okkoto-sizeof/Python/modsupport.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/modsupport.c	(original)
+++ python/branches/okkoto-sizeof/Python/modsupport.c	Wed Jun  4 11:24:23 2008
@@ -65,7 +65,7 @@
 		return NULL;
 	d = PyModule_GetDict(m);
 	if (methods != NULL) {
-		n = PyString_FromString(name);
+		n = PyBytes_FromString(name);
 		if (n == NULL)
 			return NULL;
 		for (ml = methods; ml->ml_name != NULL; ml++) {
@@ -92,7 +92,7 @@
 		Py_DECREF(n);
 	}
 	if (doc != NULL) {
-		v = PyString_FromString(doc);
+		v = PyBytes_FromString(doc);
 		if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
 			Py_XDECREF(v);
 			return NULL;
@@ -391,7 +391,7 @@
 		{
 			char p[1];
 			p[0] = (char)va_arg(*p_va, int);
-			return PyString_FromStringAndSize(p, 1);
+			return PyBytes_FromStringAndSize(p, 1);
 		}
 
 		case 's':
@@ -423,7 +423,7 @@
 					}
 					n = (Py_ssize_t)m;
 				}
-				v = PyString_FromStringAndSize(str, n);
+				v = PyBytes_FromStringAndSize(str, n);
 			}
 			return v;
 		}
@@ -633,7 +633,7 @@
 int 
 PyModule_AddStringConstant(PyObject *m, const char *name, const char *value)
 {
-	PyObject *o = PyString_FromString(value);
+	PyObject *o = PyBytes_FromString(value);
 	if (!o)
 		return -1;
 	if (PyModule_AddObject(m, name, o) == 0)

Modified: python/branches/okkoto-sizeof/Python/mysnprintf.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/mysnprintf.c	(original)
+++ python/branches/okkoto-sizeof/Python/mysnprintf.c	Wed Jun  4 11:24:23 2008
@@ -54,18 +54,28 @@
 PyOS_vsnprintf(char *str, size_t size, const char  *format, va_list va)
 {
 	int len;  /* # bytes written, excluding \0 */
-#ifndef HAVE_SNPRINTF
+#ifdef HAVE_SNPRINTF
+#define _PyOS_vsnprintf_EXTRA_SPACE 1
+#else
+#define _PyOS_vsnprintf_EXTRA_SPACE 512
 	char *buffer;
 #endif
 	assert(str != NULL);
 	assert(size > 0);
 	assert(format != NULL);
+	/* We take a size_t as input but return an int.  Sanity check
+	 * our input so that it won't cause an overflow in the
+         * vsnprintf return value or the buffer malloc size.  */
+	if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) {
+		len = -666;
+		goto Done;
+	}
 
 #ifdef HAVE_SNPRINTF
 	len = vsnprintf(str, size, format, va);
 #else
 	/* Emulate it. */
-	buffer = PyMem_MALLOC(size + 512);
+	buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE);
 	if (buffer == NULL) {
 		len = -666;
 		goto Done;
@@ -75,7 +85,7 @@
 	if (len < 0)
 		/* ignore the error */;
 
-	else if ((size_t)len >= size + 512)
+	else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE)
 		Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
 
 	else {
@@ -86,8 +96,10 @@
 		str[to_copy] = '\0';
 	}
 	PyMem_FREE(buffer);
-Done:
 #endif
-	str[size-1] = '\0';
+Done:
+	if (size > 0)
+		str[size-1] = '\0';
 	return len;
+#undef _PyOS_vsnprintf_EXTRA_SPACE
 }

Modified: python/branches/okkoto-sizeof/Python/peephole.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/peephole.c	(original)
+++ python/branches/okkoto-sizeof/Python/peephole.c	Wed Jun  4 11:24:23 2008
@@ -300,15 +300,15 @@
 		goto exitUnchanged;
 
 	/* Bypass optimization when the lineno table is too complex */
-	assert(PyString_Check(lineno_obj));
-	lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
-	tabsiz = PyString_GET_SIZE(lineno_obj);
+	assert(PyBytes_Check(lineno_obj));
+	lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj);
+	tabsiz = PyBytes_GET_SIZE(lineno_obj);
 	if (memchr(lineno, 255, tabsiz) != NULL)
 		goto exitUnchanged;
 
 	/* Avoid situations where jump retargeting could overflow */
-	assert(PyString_Check(code));
-	codelen = PyString_GET_SIZE(code);
+	assert(PyBytes_Check(code));
+	codelen = PyBytes_GET_SIZE(code);
 	if (codelen > 32700)
 		goto exitUnchanged;
 
@@ -317,7 +317,7 @@
 	if (codestr == NULL)
 		goto exitUnchanged;
 	codestr = (unsigned char *)memcpy(codestr, 
-					  PyString_AS_STRING(code), codelen);
+					  PyBytes_AS_STRING(code), codelen);
 
 	/* Verify that RETURN_VALUE terminates the codestring.	This allows
 	   the various transformation patterns to look ahead several
@@ -382,7 +382,7 @@
 			case LOAD_NAME:
 			case LOAD_GLOBAL:
 				j = GETARG(codestr, i);
-				name = PyString_AsString(PyTuple_GET_ITEM(names, j));
+				name = PyBytes_AsString(PyTuple_GET_ITEM(names, j));
 				if (name == NULL  ||  strcmp(name, "None") != 0)
 					continue;
 				for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
@@ -612,7 +612,7 @@
 	}
 	assert(h + nops == codelen);
 
-	code = PyString_FromStringAndSize((char *)codestr, h);
+	code = PyBytes_FromStringAndSize((char *)codestr, h);
 	PyMem_Free(addrmap);
 	PyMem_Free(codestr);
 	PyMem_Free(blocks);

Modified: python/branches/okkoto-sizeof/Python/pystrtod.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/pystrtod.c	(original)
+++ python/branches/okkoto-sizeof/Python/pystrtod.c	Wed Jun  4 11:24:23 2008
@@ -364,7 +364,7 @@
 	/* At this point, p points just past the right-most character we
 	   want to format.  We need to add the grouping string for the
 	   characters between buffer and p. */
-	return _PyString_InsertThousandsGrouping(buffer, len, p,
+	return _PyBytes_InsertThousandsGrouping(buffer, len, p,
 						 buf_size, NULL, 1);
 }
 

Modified: python/branches/okkoto-sizeof/Python/pythonrun.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/pythonrun.c	(original)
+++ python/branches/okkoto-sizeof/Python/pythonrun.c	Wed Jun  4 11:24:23 2008
@@ -132,10 +132,19 @@
 	PyThreadState *tstate;
 	PyObject *bimod, *sysmod;
 	char *p;
-#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
-	char *codeset;
-	char *saved_locale;
+	char *icodeset; /* On Windows, input codeset may theoretically 
+			   differ from output codeset. */
+	char *codeset = NULL;
+	char *errors = NULL;
+	int free_codeset = 0;
+	int overridden = 0;
 	PyObject *sys_stream, *sys_isatty;
+#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
+	char *saved_locale, *loc_codeset;
+#endif
+#ifdef MS_WINDOWS
+	char ibuf[128];
+	char buf[128];
 #endif
 	extern void _Py_ReadyTypes(void);
 
@@ -169,7 +178,7 @@
 	if (!_PyInt_Init())
 		Py_FatalError("Py_Initialize: can't init ints");
 
-	if (!PyBytes_Init())
+	if (!PyByteArray_Init())
 		Py_FatalError("Py_Initialize: can't init bytearray");
 
 	_PyFloat_Init();
@@ -238,38 +247,75 @@
 	_PyGILState_Init(interp, tstate);
 #endif /* WITH_THREAD */
 
+	if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
+		p = icodeset = codeset = strdup(p);
+		free_codeset = 1;
+		errors = strchr(p, ':');
+		if (errors) {
+			*errors = '\0';
+			errors++;
+		}
+		overridden = 1;
+	}
+
 #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
 	/* On Unix, set the file system encoding according to the
 	   user's preference, if the CODESET names a well-known
 	   Python codec, and Py_FileSystemDefaultEncoding isn't
 	   initialized by other means. Also set the encoding of
-	   stdin and stdout if these are terminals.  */
+	   stdin and stdout if these are terminals, unless overridden.  */
 
-	saved_locale = strdup(setlocale(LC_CTYPE, NULL));
-	setlocale(LC_CTYPE, "");
-	codeset = nl_langinfo(CODESET);
-	if (codeset && *codeset) {
-		PyObject *enc = PyCodec_Encoder(codeset);
-		if (enc) {
-			codeset = strdup(codeset);
-			Py_DECREF(enc);
-		} else {
-			codeset = NULL;
-			PyErr_Clear();
+	if (!overridden || !Py_FileSystemDefaultEncoding) {
+		saved_locale = strdup(setlocale(LC_CTYPE, NULL));
+		setlocale(LC_CTYPE, "");
+		loc_codeset = nl_langinfo(CODESET);
+		if (loc_codeset && *loc_codeset) {
+			PyObject *enc = PyCodec_Encoder(loc_codeset);
+			if (enc) {
+				loc_codeset = strdup(loc_codeset);
+				Py_DECREF(enc);
+			} else {
+				loc_codeset = NULL;
+				PyErr_Clear();
+			}
+		} else
+			loc_codeset = NULL;
+		setlocale(LC_CTYPE, saved_locale);
+		free(saved_locale);
+
+		if (!overridden) {
+			codeset = icodeset = loc_codeset;
+			free_codeset = 1;
+		}
+
+		/* Initialize Py_FileSystemDefaultEncoding from
+		   locale even if PYTHONIOENCODING is set. */
+		if (!Py_FileSystemDefaultEncoding) {
+			Py_FileSystemDefaultEncoding = loc_codeset;
+			if (!overridden)
+				free_codeset = 0;
 		}
-	} else
-		codeset = NULL;
-	setlocale(LC_CTYPE, saved_locale);
-	free(saved_locale);
+	}
+#endif
+
+#ifdef MS_WINDOWS
+	if (!overridden) {
+		icodeset = ibuf;
+		codeset = buf;
+		sprintf(ibuf, "cp%d", GetConsoleCP());
+		sprintf(buf, "cp%d", GetConsoleOutputCP());
+	}
+#endif
 
 	if (codeset) {
 		sys_stream = PySys_GetObject("stdin");
 		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
 		if (!sys_isatty)
 			PyErr_Clear();
-		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
+		if ((overridden ||
+		     (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
 		   PyFile_Check(sys_stream)) {
-			if (!PyFile_SetEncoding(sys_stream, codeset))
+			if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
 				Py_FatalError("Cannot set codeset of stdin");
 		}
 		Py_XDECREF(sys_isatty);
@@ -278,9 +324,10 @@
 		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
 		if (!sys_isatty)
 			PyErr_Clear();
-		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
+		if ((overridden || 
+		     (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
 		   PyFile_Check(sys_stream)) {
-			if (!PyFile_SetEncoding(sys_stream, codeset))
+			if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
 				Py_FatalError("Cannot set codeset of stdout");
 		}
 		Py_XDECREF(sys_isatty);
@@ -289,19 +336,17 @@
 		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
 		if (!sys_isatty)
 			PyErr_Clear();
-		if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
+		if((overridden || 
+		    (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
 		   PyFile_Check(sys_stream)) {
-			if (!PyFile_SetEncoding(sys_stream, codeset))
+			if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
 				Py_FatalError("Cannot set codeset of stderr");
 		}
 		Py_XDECREF(sys_isatty);
 
-		if (!Py_FileSystemDefaultEncoding)
-			Py_FileSystemDefaultEncoding = codeset;
-		else
+		if (free_codeset)
 			free(codeset);
 	}
-#endif
 }
 
 void
@@ -450,8 +495,8 @@
 	PyTuple_Fini();
 	PyList_Fini();
 	PySet_Fini();
-	PyString_Fini();
 	PyBytes_Fini();
+	PyByteArray_Fini();
 	PyInt_Fini();
 	PyFloat_Fini();
 	PyDict_Fini();
@@ -699,12 +744,12 @@
 	}
 	v = PySys_GetObject("ps1");
 	if (v == NULL) {
-		PySys_SetObject("ps1", v = PyString_FromString(">>> "));
+		PySys_SetObject("ps1", v = PyBytes_FromString(">>> "));
 		Py_XDECREF(v);
 	}
 	v = PySys_GetObject("ps2");
 	if (v == NULL) {
-		PySys_SetObject("ps2", v = PyString_FromString("... "));
+		PySys_SetObject("ps2", v = PyBytes_FromString("... "));
 		Py_XDECREF(v);
 	}
 	for (;;) {
@@ -751,16 +796,16 @@
 		v = PyObject_Str(v);
 		if (v == NULL)
 			PyErr_Clear();
-		else if (PyString_Check(v))
-			ps1 = PyString_AsString(v);
+		else if (PyBytes_Check(v))
+			ps1 = PyBytes_AsString(v);
 	}
 	w = PySys_GetObject("ps2");
 	if (w != NULL) {
 		w = PyObject_Str(w);
 		if (w == NULL)
 			PyErr_Clear();
-		else if (PyString_Check(w))
-			ps2 = PyString_AsString(w);
+		else if (PyBytes_Check(w))
+			ps2 = PyBytes_AsString(w);
 	}
 	arena = PyArena_New();
 	if (arena == NULL) {
@@ -853,7 +898,7 @@
 		return -1;
 	d = PyModule_GetDict(m);
 	if (PyDict_GetItemString(d, "__file__") == NULL) {
-		PyObject *f = PyString_FromString(filename);
+		PyObject *f = PyBytes_FromString(filename);
 		if (f == NULL)
 			return -1;
 		if (PyDict_SetItemString(d, "__file__", f) < 0) {
@@ -937,7 +982,7 @@
 		goto finally;
 	if (v == Py_None)
 		*filename = NULL;
-	else if (! (*filename = PyString_AsString(v)))
+	else if (! (*filename = PyBytes_AsString(v)))
 		goto finally;
 
 	Py_DECREF(v);
@@ -969,7 +1014,7 @@
 		goto finally;
 	if (v == Py_None)
 		*text = NULL;
-	else if (! (*text = PyString_AsString(v)))
+	else if (! (*text = PyBytes_AsString(v)))
 		goto finally;
 	Py_DECREF(v);
 	return 1;
@@ -1192,7 +1237,7 @@
 			if (moduleName == NULL)
 				err = PyFile_WriteString("<unknown>", f);
 			else {
-				char* modstr = PyString_AsString(moduleName);
+				char* modstr = PyBytes_AsString(moduleName);
 				if (modstr && strcmp(modstr, "exceptions"))
 				{
 					err = PyFile_WriteString(modstr, f);
@@ -1216,8 +1261,8 @@
 			*/
 			if (s == NULL)
 				err = -1;
-			else if (!PyString_Check(s) ||
-				 PyString_GET_SIZE(s) != 0)
+			else if (!PyBytes_Check(s) ||
+				 PyBytes_GET_SIZE(s) != 0)
 				err = PyFile_WriteString(": ", f);
 			if (err == 0)
 			  err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
@@ -1536,7 +1581,7 @@
 		if (value != NULL) {
 			u = PyObject_Str(value);
 			if (u != NULL) {
-				msg = PyString_AsString(u);
+				msg = PyBytes_AsString(u);
 			}
 		}
 		if (msg == NULL)

Modified: python/branches/okkoto-sizeof/Python/structmember.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/structmember.c	(original)
+++ python/branches/okkoto-sizeof/Python/structmember.c	Wed Jun  4 11:24:23 2008
@@ -16,7 +16,7 @@
 	if (v != NULL) {
 		for (i = 0; i < n; i++)
 			PyList_SetItem(v, i,
-				       PyString_FromString(mlist[i].name));
+				       PyBytes_FromString(mlist[i].name));
 		if (PyErr_Occurred()) {
 			Py_DECREF(v);
 			v = NULL;
@@ -103,13 +103,13 @@
 			v = Py_None;
 		}
 		else
-			v = PyString_FromString(*(char**)addr);
+			v = PyBytes_FromString(*(char**)addr);
 		break;
 	case T_STRING_INPLACE:
-		v = PyString_FromString((char*)addr);
+		v = PyBytes_FromString((char*)addr);
 		break;
 	case T_CHAR:
-		v = PyString_FromStringAndSize((char*)addr, 1);
+		v = PyBytes_FromStringAndSize((char*)addr, 1);
 		break;
 	case T_OBJECT:
 		v = *(PyObject **)addr;
@@ -310,8 +310,8 @@
 		Py_XDECREF(oldv);
 		break;
 	case T_CHAR:
-		if (PyString_Check(v) && PyString_Size(v) == 1) {
-			*(char*)addr = PyString_AsString(v)[0];
+		if (PyBytes_Check(v) && PyBytes_Size(v) == 1) {
+			*(char*)addr = PyBytes_AsString(v)[0];
 		}
 		else {
 			PyErr_BadArgument();

Modified: python/branches/okkoto-sizeof/Python/symtable.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/symtable.c	(original)
+++ python/branches/okkoto-sizeof/Python/symtable.c	Wed Jun  4 11:24:23 2008
@@ -87,9 +87,9 @@
 
 	PyOS_snprintf(buf, sizeof(buf),
 		      "<symtable entry %.100s(%ld), line %d>",
-		      PyString_AS_STRING(ste->ste_name),
+		      PyBytes_AS_STRING(ste->ste_name),
 		      PyInt_AS_LONG(ste->ste_id), ste->ste_lineno);
-	return PyString_FromString(buf);
+	return PyBytes_FromString(buf);
 }
 
 static void
@@ -180,7 +180,7 @@
 static identifier top = NULL, lambda = NULL, genexpr = NULL;
 
 #define GET_IDENTIFIER(VAR) \
-	((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
+	((VAR) ? (VAR) : ((VAR) = PyBytes_InternFromString(# VAR)))
 
 #define DUPLICATE_ARGUMENT \
 "duplicate argument '%s' in function definition"
@@ -372,7 +372,7 @@
 		if (flags & DEF_PARAM) {
 			PyErr_Format(PyExc_SyntaxError,
 				     "name '%s' is local and global",
-				     PyString_AS_STRING(name));
+				     PyBytes_AS_STRING(name));
 			return 0;
 		}
 		SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
@@ -487,19 +487,19 @@
 		PyOS_snprintf(buf, sizeof(buf), 
 			      "import * is not allowed in function '%.100s' "
 			      "because it is %s",
-			      PyString_AS_STRING(ste->ste_name), trailer);
+			      PyBytes_AS_STRING(ste->ste_name), trailer);
 		break;
 	case OPT_BARE_EXEC:
 		PyOS_snprintf(buf, sizeof(buf),
 			      "unqualified exec is not allowed in function "
 			      "'%.100s' it %s",
-			      PyString_AS_STRING(ste->ste_name), trailer);
+			      PyBytes_AS_STRING(ste->ste_name), trailer);
 		break;
 	default:
 		PyOS_snprintf(buf, sizeof(buf), 
 			      "function '%.100s' uses import * and bare exec, "
 			      "which are illegal because it %s",
-			      PyString_AS_STRING(ste->ste_name), trailer);
+			      PyBytes_AS_STRING(ste->ste_name), trailer);
 		break;
 	}
 
@@ -800,7 +800,7 @@
 	    if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
 		    /* Is it better to use 'mangled' or 'name' here? */
 		    PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
-				 PyString_AsString(name));
+				 PyBytes_AsString(name));
 		    PyErr_SyntaxLocation(st->st_filename,
 				       st->st_cur->ste_lineno);
 		    goto error;
@@ -914,7 +914,7 @@
 
 	PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
 		      ++st->st_cur->ste_tmpname);
-	tmp = PyString_InternFromString(tmpname);
+	tmp = PyBytes_InternFromString(tmpname);
 	if (!tmp)
 		return 0;
 	if (!symtable_add_def(st, tmp, DEF_LOCAL))
@@ -1065,7 +1065,7 @@
 		asdl_seq *seq = s->v.Global.names;
 		for (i = 0; i < asdl_seq_LEN(seq); i++) {
 			identifier name = (identifier)asdl_seq_GET(seq, i);
-			char *c_name = PyString_AS_STRING(name);
+			char *c_name = PyBytes_AS_STRING(name);
 			long cur = symtable_lookup(st, name);
 			if (cur < 0)
 				return 0;
@@ -1218,7 +1218,7 @@
 static int
 symtable_implicit_arg(struct symtable *st, int pos)
 {
-	PyObject *id = PyString_FromFormat(".%d", pos);
+	PyObject *id = PyBytes_FromFormat(".%d", pos);
 	if (id == NULL)
 		return 0;
 	if (!symtable_add_def(st, id, DEF_PARAM)) {
@@ -1326,10 +1326,10 @@
 	*/
 	PyObject *store_name;
 	PyObject *name = (a->asname == NULL) ? a->name : a->asname;
-	const char *base = PyString_AS_STRING(name);
+	const char *base = PyBytes_AS_STRING(name);
 	char *dot = strchr(base, '.');
 	if (dot) {
-		store_name = PyString_FromStringAndSize(base, dot - base);
+		store_name = PyBytes_FromStringAndSize(base, dot - base);
 		if (!store_name)
 			return 0;
 	}
@@ -1337,7 +1337,7 @@
 		store_name = name;
 		Py_INCREF(store_name);
 	}
-	if (strcmp(PyString_AS_STRING(name), "*")) {
+	if (strcmp(PyBytes_AS_STRING(name), "*")) {
 		int r = symtable_add_def(st, store_name, DEF_IMPORT); 
 		Py_DECREF(store_name);
 		return r;

Modified: python/branches/okkoto-sizeof/Python/sysmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/sysmodule.c	(original)
+++ python/branches/okkoto-sizeof/Python/sysmodule.c	Wed Jun  4 11:24:23 2008
@@ -229,7 +229,7 @@
 static PyObject *
 sys_getdefaultencoding(PyObject *self)
 {
-	return PyString_FromString(PyUnicode_GetDefaultEncoding());
+	return PyBytes_FromString(PyUnicode_GetDefaultEncoding());
 }
 
 PyDoc_STRVAR(getdefaultencoding_doc,
@@ -261,7 +261,7 @@
 sys_getfilesystemencoding(PyObject *self)
 {
 	if (Py_FileSystemDefaultEncoding)
-		return PyString_FromString(Py_FileSystemDefaultEncoding);
+		return PyBytes_FromString(Py_FileSystemDefaultEncoding);
 	Py_INCREF(Py_None);
 	return Py_None;
 }
@@ -290,7 +290,7 @@
 	int i;
 	for (i = 0; i < 7; ++i) {
 		if (whatstrings[i] == NULL) {
-			name = PyString_InternFromString(whatnames[i]);
+			name = PyBytes_InternFromString(whatnames[i]);
 			if (name == NULL)
 				return -1;
 			whatstrings[i] = name;
@@ -661,13 +661,12 @@
 				     Py_TYPE(args)->tp_name);
 			return NULL;
 		}
-		/* And call it, binding it to the value */
 		return PyObject_CallFunctionObjArgs(method, args, NULL);
 	} 
 	/* Instance of old-style classes */
-	else if(PyInstance_Check(args))
+	else if (PyInstance_Check(args))
 		return PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);
-	/* Old-style class */
+	/* Old-style classes */
 	else if (PyClass_Check(args))
 		return PyInt_FromSsize_t(PyClass_Type.tp_basicsize);
 	else
@@ -932,7 +931,7 @@
 	if (list == NULL)
 		return NULL;
 	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
-		PyObject *name = PyString_FromString(
+		PyObject *name = PyBytes_FromString(
 			PyImport_Inittab[i].name);
 		if (name == NULL)
 			break;
@@ -972,7 +971,7 @@
 		if (warnoptions == NULL)
 			return;
 	}
-	str = PyString_FromString(s);
+	str = PyBytes_FromString(s);
 	if (str != NULL) {
 		PyList_Append(warnoptions, str);
 		Py_DECREF(str);
@@ -1033,6 +1032,7 @@
 Static objects:\n\
 \n\
 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
+maxsize -- the largest supported length of containers.\n\
 maxunicode -- the largest supported character\n\
 builtin_module_names -- tuple of module names built into this interpreter\n\
 version -- the version of this interpreter as a string\n\
@@ -1273,9 +1273,6 @@
 	PyObject *m, *v, *sysdict;
 	PyObject *sysin, *sysout, *syserr;
 	char *s;
-#ifdef MS_WINDOWS
-	char buf[128];
-#endif
 
 	m = Py_InitModule3("sys", sys_methods, sys_doc);
 	if (m == NULL)
@@ -1313,23 +1310,6 @@
 	syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);
 	if (PyErr_Occurred())
 		return NULL;
-#ifdef MS_WINDOWS
-	if(isatty(_fileno(stdin)) && PyFile_Check(sysin)) {
-		sprintf(buf, "cp%d", GetConsoleCP());
-		if (!PyFile_SetEncoding(sysin, buf))
-			return NULL;
-	}
-	if(isatty(_fileno(stdout)) && PyFile_Check(sysout)) {
-		sprintf(buf, "cp%d", GetConsoleOutputCP());
-		if (!PyFile_SetEncoding(sysout, buf))
-			return NULL;
-	}
-	if(isatty(_fileno(stderr)) && PyFile_Check(syserr)) {
-		sprintf(buf, "cp%d", GetConsoleOutputCP());
-		if (!PyFile_SetEncoding(syserr, buf))
-			return NULL;
-	}
-#endif
 
 	PyDict_SetItemString(sysdict, "stdin", sysin);
 	PyDict_SetItemString(sysdict, "stdout", sysout);
@@ -1347,7 +1327,7 @@
 	Py_XDECREF(syserr);
 
 	SET_SYS_FROM_STRING("version",
-			     PyString_FromString(Py_GetVersion()));
+			     PyBytes_FromString(Py_GetVersion()));
 	SET_SYS_FROM_STRING("hexversion",
 			     PyInt_FromLong(PY_VERSION_HEX));
 	svnversion_init();
@@ -1378,15 +1358,17 @@
 	SET_SYS_FROM_STRING("api_version",
 			    PyInt_FromLong(PYTHON_API_VERSION));
 	SET_SYS_FROM_STRING("copyright",
-			    PyString_FromString(Py_GetCopyright()));
+			    PyBytes_FromString(Py_GetCopyright()));
 	SET_SYS_FROM_STRING("platform",
-			    PyString_FromString(Py_GetPlatform()));
+			    PyBytes_FromString(Py_GetPlatform()));
 	SET_SYS_FROM_STRING("executable",
-			    PyString_FromString(Py_GetProgramFullPath()));
+			    PyBytes_FromString(Py_GetProgramFullPath()));
 	SET_SYS_FROM_STRING("prefix",
-			    PyString_FromString(Py_GetPrefix()));
+			    PyBytes_FromString(Py_GetPrefix()));
 	SET_SYS_FROM_STRING("exec_prefix",
-		   	    PyString_FromString(Py_GetExecPrefix()));
+		   	    PyBytes_FromString(Py_GetExecPrefix()));
+	SET_SYS_FROM_STRING("maxsize",
+			    PyInt_FromSsize_t(PY_SSIZE_T_MAX));
 	SET_SYS_FROM_STRING("maxint",
 			    PyInt_FromLong(PyInt_GetMax()));
 	SET_SYS_FROM_STRING("py3kwarning",
@@ -1411,13 +1393,13 @@
 		else
 			value = "little";
 		SET_SYS_FROM_STRING("byteorder",
-				    PyString_FromString(value));
+				    PyBytes_FromString(value));
 	}
 #ifdef MS_COREDLL
 	SET_SYS_FROM_STRING("dllhandle",
 			    PyLong_FromVoidPtr(PyWin_DLLhModule));
 	SET_SYS_FROM_STRING("winver",
-			    PyString_FromString(PyWin_DLLVersionString));
+			    PyBytes_FromString(PyWin_DLLVersionString));
 #endif
 	if (warnoptions == NULL) {
 		warnoptions = PyList_New(0);
@@ -1462,7 +1444,7 @@
 		p = strchr(path, delim);
 		if (p == NULL)
 			p = strchr(path, '\0'); /* End of string */
-		w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));
+		w = PyBytes_FromStringAndSize(path, (Py_ssize_t) (p - path));
 		if (w == NULL) {
 			Py_DECREF(v);
 			return NULL;
@@ -1507,14 +1489,14 @@
 			if (i == 0) {
 				char* fn = decc$translate_vms(argv[0]);
 				if ((fn == (char *)0) || fn == (char *)-1)
-					v = PyString_FromString(argv[0]);
+					v = PyBytes_FromString(argv[0]);
 				else
-					v = PyString_FromString(
+					v = PyBytes_FromString(
 						decc$translate_vms(argv[0]));
 			} else
-				v = PyString_FromString(argv[i]);
+				v = PyBytes_FromString(argv[i]);
 #else
-			PyObject *v = PyString_FromString(argv[i]);
+			PyObject *v = PyBytes_FromString(argv[i]);
 #endif
 			if (v == NULL) {
 				Py_DECREF(av);
@@ -1618,7 +1600,7 @@
 #endif /* Unix */
 		}
 #endif /* All others */
-		a = PyString_FromStringAndSize(argv0, n);
+		a = PyBytes_FromStringAndSize(argv0, n);
 		if (a == NULL)
 			Py_FatalError("no mem for sys.path insertion");
 		if (PyList_Insert(path, 0, a) < 0)

Modified: python/branches/okkoto-sizeof/Python/traceback.c
==============================================================================
--- python/branches/okkoto-sizeof/Python/traceback.c	(original)
+++ python/branches/okkoto-sizeof/Python/traceback.c	Wed Jun  4 11:24:23 2008
@@ -155,12 +155,12 @@
 					PyErr_Clear();
 					break;
 				}
-				if (PyString_Check(v)) {
+				if (PyBytes_Check(v)) {
 					size_t len;
-					len = PyString_GET_SIZE(v);
+					len = PyBytes_GET_SIZE(v);
 					if (len + 1 + taillen >= MAXPATHLEN)
 						continue; /* Too long */
-					strcpy(namebuf, PyString_AsString(v));
+					strcpy(namebuf, PyBytes_AsString(v));
 					if (strlen(namebuf) != len)
 						continue; /* v contains '\0' */
 					if (len > 0 && namebuf[len-1] != SEP)
@@ -238,10 +238,10 @@
 	while (tb != NULL && err == 0) {
 		if (depth <= limit) {
 			err = tb_displayline(f,
-			    PyString_AsString(
+			    PyBytes_AsString(
 				    tb->tb_frame->f_code->co_filename),
 			    tb->tb_lineno,
-			    PyString_AsString(tb->tb_frame->f_code->co_name));
+			    PyBytes_AsString(tb->tb_frame->f_code->co_name));
 		}
 		depth--;
 		tb = tb->tb_next;

Modified: python/branches/okkoto-sizeof/README
==============================================================================
--- python/branches/okkoto-sizeof/README	(original)
+++ python/branches/okkoto-sizeof/README	Wed Jun  4 11:24:23 2008
@@ -917,6 +917,26 @@
 link most extension modules statically.
 
 
+Coverage checking
+-----------------
+
+For C coverage checking using gcov, run "make coverage".  This will
+build a Python binary with profiling activated, and a ".gcno" and
+".gcda" file for every source file compiled with that option.  With
+the built binary, now run the code whose coverage you want to check.
+Then, you can see coverage statistics for each individual source file
+by running gcov, e.g.
+
+    gcov -o Modules zlibmodule
+
+This will create a "zlibmodule.c.gcov" file in the current directory
+containing coverage info for that source file.
+
+This works only for source files statically compiled into the
+executable; use the Makefile/Setup mechanism to compile and link
+extension modules you want to coverage-check statically.
+
+
 Testing
 -------
 

Modified: python/branches/okkoto-sizeof/RISCOS/Modules/drawfmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/RISCOS/Modules/drawfmodule.c	(original)
+++ python/branches/okkoto-sizeof/RISCOS/Modules/drawfmodule.c	Wed Jun  4 11:24:23 2008
@@ -333,7 +333,7 @@
   char *dtable;
   if(!PyArg_ParseTuple(arg,"O!",&PyDict_Type,&d)) return NULL;
   while(PyDict_Next(d,&n,&key,&value))
-  { int m=PyString_Size(value);
+  { int m=PyBytes_Size(value);
     if(m<0||!PyInt_Check(key)) return NULL;
     size+=m+2;
   }
@@ -350,9 +350,9 @@
   memset(dtable,0,size-8);
   n=0;
   while(PyDict_Next(d,&n,&key,&value))
-  { int m=PyString_Size(value);
+  { int m=PyBytes_Size(value);
     *dtable=(char)PyInt_AsLong(key);
-    strcpy(dtable+1,PyString_AsString(value));
+    strcpy(dtable+1,PyBytes_AsString(value));
     dtable+=m+2;
   }
   Py_INCREF(Py_None);return Py_None;
@@ -609,8 +609,8 @@
   if (!strcmp(name, "__members__"))
   { PyObject *list = PyList_New(2);
     if (list)
-    { PyList_SetItem(list, 0, PyString_FromString("size"));
-      PyList_SetItem(list, 1, PyString_FromString("start"));
+    { PyList_SetItem(list, 0, PyBytes_FromString("size"));
+      PyList_SetItem(list, 1, PyBytes_FromString("start"));
       if (PyErr_Occurred()) { Py_DECREF(list);list = NULL;}
     }
     return list;
@@ -659,6 +659,6 @@
 { PyObject *m, *d;
   m = Py_InitModule("drawf", DrawFMethods);
   d = PyModule_GetDict(m);
-  DrawFError=PyString_FromString("drawf.error");
+  DrawFError=PyBytes_FromString("drawf.error");
   PyDict_SetItemString(d,"error",DrawFError);
 }

Modified: python/branches/okkoto-sizeof/RISCOS/Modules/riscosmodule.c
==============================================================================
--- python/branches/okkoto-sizeof/RISCOS/Modules/riscosmodule.c	(original)
+++ python/branches/okkoto-sizeof/RISCOS/Modules/riscosmodule.c	Wed Jun  4 11:24:23 2008
@@ -79,9 +79,9 @@
   char *buf;
   e=xosfscontrol_canonicalise_path(path,0,0,0,0,&len);
   if(e) return riscos_oserror();
-  obj=PyString_FromStringAndSize(NULL,-len);
+  obj=PyBytes_FromStringAndSize(NULL,-len);
   if(obj==NULL) return NULL;
-  buf=PyString_AsString(obj);
+  buf=PyBytes_AsString(obj);
   e=xosfscontrol_canonicalise_path(path,buf,0,0,1-len,&len);
   if(len!=1) return riscos_error("Error expanding path");
   if(!e) return obj;
@@ -131,7 +131,7 @@
 	  { Py_DECREF(d);return riscos_oserror();
 	  }
 	  if(count)
-	  { v=PyString_FromString(buf);
+	  { v=PyBytes_FromString(buf);
 	    if(!v) { Py_DECREF(d);return 0;}
 	    if(PyList_Append(d,v)) {Py_DECREF(d);Py_DECREF(v);return 0;}
 	  }
@@ -320,7 +320,7 @@
   char *name,*value;
   if(!PyArg_ParseTuple(args,"s:getenv",&name)) return NULL;
   value=getenv(name);
-  if(value) return PyString_FromString(value);
+  if(value) return PyBytes_FromString(value);
   Py_INCREF(Py_None);
   return Py_None;
 }
@@ -371,7 +371,7 @@
          os_VARTYPE_EXPANDED,&size,(int *)&context,0))
   { PyObject *v;
     value[size]='\0';
-    v = PyString_FromString(value);
+    v = PyBytes_FromString(value);
     if (v == NULL) continue;
     PyDict_SetItemString(dict, context, v);
     Py_DECREF(v);

Modified: python/branches/okkoto-sizeof/RISCOS/Modules/swimodule.c
==============================================================================
--- python/branches/okkoto-sizeof/RISCOS/Modules/swimodule.c	(original)
+++ python/branches/okkoto-sizeof/RISCOS/Modules/swimodule.c	Wed Jun  4 11:24:23 2008
@@ -66,10 +66,10 @@
   b->length=4*size;
   b->heap=1;
   if(init)
-  { if(PyString_Check(init))
-    { int n=PyString_Size(init);
+  { if(PyBytes_Check(init))
+    { int n=PyBytes_Size(init);
       if (n>4*size) n=4*size;
-      memcpy(b->block,PyString_AsString(init),n);
+      memcpy(b->block,PyBytes_AsString(init),n);
       memset((char*)b->block+n,0,4*size-n);
     }
     else
@@ -113,7 +113,7 @@
   { PyErr_SetString(PyExc_IndexError,"block index out of range");
     return NULL;
   }
-  return PyString_FromStringAndSize((char*)self->block+s,e-s);
+  return PyBytes_FromStringAndSize((char*)self->block+s,e-s);
 }
 
 static PyObject *PyBlock_NullString(PyBlockObject *self,PyObject *arg)
@@ -125,7 +125,7 @@
     return NULL;
   }
   for(i=s;i<e;i++) if(p[i]==0) break;
-  return PyString_FromStringAndSize((char*)self->block+s,i-s);
+  return PyBytes_FromStringAndSize((char*)self->block+s,i-s);
 }
 
 static PyObject *PyBlock_CtrlString(PyBlockObject *self,PyObject *arg)
@@ -137,7 +137,7 @@
     return NULL;
   }
   for(i=s;i<e;i++) if(p[i]<32) break;
-  return PyString_FromStringAndSize((char*)self->block+s,i-s);
+  return PyBytes_FromStringAndSize((char*)self->block+s,i-s);
 }
 
 static PyObject *PyBlock_PadString(PyBlockObject *self,PyObject *arg)
@@ -296,9 +296,9 @@
   if (!strcmp(name, "__members__"))
   { PyObject *list = PyList_New(3);
     if (list)
-    { PyList_SetItem(list, 0, PyString_FromString("length"));
-      PyList_SetItem(list, 1, PyString_FromString("start"));
-      PyList_SetItem(list, 2, PyString_FromString("end"));
+    { PyList_SetItem(list, 0, PyBytes_FromString("length"));
+      PyList_SetItem(list, 1, PyBytes_FromString("start"));
+      PyList_SetItem(list, 2, PyBytes_FromString("end"));
       if (PyErr_Occurred()) { Py_DECREF(list);list = NULL;}
     }
     return list;
@@ -402,7 +402,7 @@
   for(;*fmt;fmt++)
   {  switch(*fmt)
     { case 'i':v=PyInt_FromLong((long)r.r[rno++]); break;
-      case 's':v=PyString_FromString((char*)(r.r[rno++])); break;
+      case 's':v=PyBytes_FromString((char*)(r.r[rno++])); break;
       case '.':rno++; continue;
       case '*':v=PyInt_FromLong((long)carry); break;
     }
@@ -421,7 +421,7 @@
   if(!PyArg_ParseTuple(arg,"i|i",(unsigned int *)&s, &l)) return NULL;
   if (l==-1)
     l = strlen(s);
-  return PyString_FromStringAndSize((char*)s, l);
+  return PyBytes_FromStringAndSize((char*)s, l);
 }
 
 static char swi_string__doc__[] =

Modified: python/branches/okkoto-sizeof/Tools/README
==============================================================================
--- python/branches/okkoto-sizeof/Tools/README	(original)
+++ python/branches/okkoto-sizeof/Tools/README	Wed Jun  4 11:24:23 2008
@@ -9,6 +9,7 @@
 
 bgen		Generate complete extension modules from a
 		description.  Still under development!
+		WARNING: bgen has been removed in 3.0.
 
 compiler	Tools used to maintain the compiler package in the
 		standard library.

Modified: python/branches/okkoto-sizeof/Tools/bgen/README
==============================================================================
--- python/branches/okkoto-sizeof/Tools/bgen/README	(original)
+++ python/branches/okkoto-sizeof/Tools/bgen/README	Wed Jun  4 11:24:23 2008
@@ -5,3 +5,5 @@
 complete source code for Python extension module.  For examples of its
 use, see the Mac Python source distribution (available separately
 from the Python ftp archives).  Note that BGEN is not Mac specific!
+
+WARNING: bgen has been removed in 3.0.

Modified: python/branches/okkoto-sizeof/Tools/msi/msi.py
==============================================================================
--- python/branches/okkoto-sizeof/Tools/msi/msi.py	(original)
+++ python/branches/okkoto-sizeof/Tools/msi/msi.py	Wed Jun  4 11:24:23 2008
@@ -382,6 +382,7 @@
              ])
 
     compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x bad_coding|badsyntax|site-packages|py3_ "[TARGETDIR]Lib"'
+    lib2to3args = r'-c "import lib2to3.pygram, lib2to3.patcomp;lib2to3.patcomp.PatternCompiler()"'
     # See "CustomAction Table"
     add_data(db, "CustomAction", [
         # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty
@@ -395,6 +396,7 @@
         # See "Custom Action Type 18"
         ("CompilePyc", 18, "python.exe", compileargs),
         ("CompilePyo", 18, "python.exe", "-O "+compileargs),
+        ("CompileGrammar", 18, "python.exe", lib2to3args),
         ])
 
     # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table"
@@ -424,12 +426,14 @@
              ("UpdateEditIDLE", None, 1050),
              ("CompilePyc", "COMPILEALL", 6800),
              ("CompilePyo", "COMPILEALL", 6801),
+             ("CompileGrammar", "COMPILEALL", 6802),
             ])
     add_data(db, "AdminExecuteSequence",
             [("InitialTargetDir", 'TARGETDIR=""', 750),
              ("SetDLLDirToTarget", 'DLLDIR=""', 751),
              ("CompilePyc", "COMPILEALL", 6800),
              ("CompilePyo", "COMPILEALL", 6801),
+             ("CompileGrammar", "COMPILEALL", 6802),
             ])
 
     #####################################################################
@@ -840,6 +844,26 @@
         result.append((f, kw))
     return result
 
+def generate_license():
+    import shutil, glob
+    out = open("LICENSE.txt", "w")
+    shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out)
+    for dir, file in (("bzip2","LICENSE"),
+                      ("db", "LICENSE"),
+                      ("openssl", "LICENSE"),
+                      ("tcl", "license.terms"),
+                      ("tk", "license.terms")):
+        out.write("\nThis copy of Python includes a copy of %s, which is licensed under the following terms:\n\n" % dir)
+        dirs = glob.glob(srcdir+"/../"+dir+"-*")
+        if not dirs:
+            raise ValueError, "Could not find "+srcdir+"/../"+dir+"-*"
+        if len(dirs) > 2:
+            raise ValueError, "Multiple copies of "+dir
+        dir = dirs[0]
+        shutil.copyfileobj(open(os.path.join(dir, file)), out)
+    out.close()
+
+
 class PyDirectory(Directory):
     """By default, all components in the Python installer
     can run from source."""
@@ -860,7 +884,8 @@
         root.add_file("%s/w9xpopen.exe" % PCBUILD)
     root.add_file("README.txt", src="README")
     root.add_file("NEWS.txt", src="Misc/NEWS")
-    root.add_file("LICENSE.txt", src="LICENSE")
+    generate_license()
+    root.add_file("LICENSE.txt", src=os.path.abspath("LICENSE.txt"))
     root.start_component("python.exe", keyfile="python.exe")
     root.add_file("%s/python.exe" % PCBUILD)
     root.start_component("pythonw.exe", keyfile="pythonw.exe")
@@ -978,6 +1003,8 @@
         if dir=="setuptools":
             lib.add_file("cli.exe")
             lib.add_file("gui.exe")
+        if dir=="lib2to3":
+            lib.removefile("pickle", "*.pickle")
         if dir=="data" and parent.physical=="test" and parent.basedir.physical=="email":
             # This should contain all non-.svn files listed in subversion
             for f in os.listdir(lib.absolute):

Modified: python/branches/okkoto-sizeof/Tools/msi/msilib.py
==============================================================================
--- python/branches/okkoto-sizeof/Tools/msi/msilib.py	(original)
+++ python/branches/okkoto-sizeof/Tools/msi/msilib.py	Wed Jun  4 11:24:23 2008
@@ -571,6 +571,11 @@
                  [(self.component+"c", self.component, "*.pyc", self.logical, 2),
                   (self.component+"o", self.component, "*.pyo", self.logical, 2)])
 
+    def removefile(self, key, pattern):
+        "Add a RemoveFile entry"
+        add_data(self.db, "RemoveFile", [(self.component+key, self.component, pattern, self.logical, 2)])
+
+
 class Feature:
     def __init__(self, db, id, title, desc, display, level = 1,
                  parent=None, directory = None, attributes=0):

Modified: python/branches/okkoto-sizeof/Tools/webchecker/wsgui.py
==============================================================================
--- python/branches/okkoto-sizeof/Tools/webchecker/wsgui.py	(original)
+++ python/branches/okkoto-sizeof/Tools/webchecker/wsgui.py	Wed Jun  4 11:24:23 2008
@@ -10,7 +10,7 @@
 import websucker
 import os
 import threading
-import queue
+import Queue
 import time
 
 VERBOSE = 2
@@ -139,7 +139,7 @@
 
     def go(self, event=None):
         if not self.msgq:
-            self.msgq = queue.Queue(0)
+            self.msgq = Queue.Queue(0)
             self.check_msgq()
         if not self.sucker:
             self.sucker = SuckerThread(self.msgq)

Modified: python/branches/okkoto-sizeof/configure
==============================================================================
--- python/branches/okkoto-sizeof/configure	(original)
+++ python/branches/okkoto-sizeof/configure	Wed Jun  4 11:24:23 2008
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.in Revision: 62499 .
+# From configure.in Revision: 63545 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.61 for python 2.6.
 #
@@ -2078,6 +2078,11 @@
   Darwin/[789].*)
     define_xopen_source=no
     ;;
+  # On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from
+  # defining NI_NUMERICHOST.
+  QNX/6.3.2)
+    define_xopen_source=no
+    ;;
 
 esac
 
@@ -3920,6 +3925,10 @@
 	   LINKCC="\$(srcdir)/Modules/makexp_aix Modules/python.exp $exp_extra \$(LIBRARY); $LINKCC";;
 	Monterey64*)
 	   LINKCC="$LINKCC -L/usr/lib/ia64l64";;
+	QNX*)
+	   # qcc must be used because the other compilers do not
+	   # support -N.
+	   LINKCC=qcc;;
 	esac
 fi
 { echo "$as_me:$LINENO: result: $LINKCC" >&5
@@ -5461,6 +5470,7 @@
 
 
 
+
 for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \
 fcntl.h grp.h \
 ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \
@@ -5469,7 +5479,7 @@
 sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \
 sys/lock.h sys/mkdev.h sys/modem.h \
 sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \
-sys/time.h \
+sys/termio.h sys/time.h \
 sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \
 sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
 bluetooth/bluetooth.h linux/tipc.h
@@ -12520,7 +12530,7 @@
 			fi
 		fi
 		;;
-	Linux*|GNU*) LDSHARED='$(CC) -shared';;
+	Linux*|GNU*|QNX*) LDSHARED='$(CC) -shared';;
 	BSD/OS*/4*) LDSHARED="gcc -shared";;
 	FreeBSD*)
 		if [ "`$CC -dM -E - </dev/null | grep __ELF__`" != "" ]
@@ -12648,6 +12658,13 @@
 		then
 			LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)'
 		fi;;
+	QNX*)
+		# -Wl,-E causes the symbols to be added to the dynamic
+		# symbol table so that they can be found when a module
+		# is loaded.  -N 2048K causes the stack size to be set
+		# to 2048 kilobytes so that the stack doesn't overflow
+		# when running test_compile.py.
+		LINKFORSHARED='-Wl,-E -N 2048K';;
 	esac
 fi
 { echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5

Modified: python/branches/okkoto-sizeof/configure.in
==============================================================================
--- python/branches/okkoto-sizeof/configure.in	(original)
+++ python/branches/okkoto-sizeof/configure.in	Wed Jun  4 11:24:23 2008
@@ -1,4 +1,7 @@
-dnl Process this file with autoconf 2.0 or later to make a configure script.
+dnl ***********************************************
+dnl * Please run autoreconf to test your changes! *
+dnl ***********************************************
+dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.63).
 
 # Set VERSION so we only need to edit in one place (i.e., here)
 m4_define(PYTHON_VERSION, 2.6)
@@ -262,6 +265,11 @@
   Darwin/@<:@789@:>@.*)
     define_xopen_source=no
     ;;
+  # On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from
+  # defining NI_NUMERICHOST.
+  QNX/6.3.2)
+    define_xopen_source=no
+    ;;
 
 esac
 
@@ -586,6 +594,10 @@
 	   LINKCC="\$(srcdir)/Modules/makexp_aix Modules/python.exp $exp_extra \$(LIBRARY); $LINKCC";;
 	Monterey64*)
 	   LINKCC="$LINKCC -L/usr/lib/ia64l64";;
+	QNX*)
+	   # qcc must be used because the other compilers do not
+	   # support -N.
+	   LINKCC=qcc;;
 	esac
 fi
 AC_MSG_RESULT($LINKCC)
@@ -1132,7 +1144,7 @@
 sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \
 sys/lock.h sys/mkdev.h sys/modem.h \
 sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \
-sys/time.h \
+sys/termio.h sys/time.h \
 sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \
 sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
 bluetooth/bluetooth.h linux/tipc.h)
@@ -1576,7 +1588,7 @@
 			fi
 		fi
 		;;
-	Linux*|GNU*) LDSHARED='$(CC) -shared';;
+	Linux*|GNU*|QNX*) LDSHARED='$(CC) -shared';;
 	BSD/OS*/4*) LDSHARED="gcc -shared";;
 	FreeBSD*)
 		if [[ "`$CC -dM -E - </dev/null | grep __ELF__`" != "" ]]
@@ -1700,6 +1712,13 @@
 		then
 			LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)'
 		fi;;
+	QNX*)
+		# -Wl,-E causes the symbols to be added to the dynamic
+		# symbol table so that they can be found when a module
+		# is loaded.  -N 2048K causes the stack size to be set
+		# to 2048 kilobytes so that the stack doesn't overflow
+		# when running test_compile.py.
+		LINKFORSHARED='-Wl,-E -N 2048K';;
 	esac
 fi
 AC_MSG_RESULT($LINKFORSHARED)

Modified: python/branches/okkoto-sizeof/pyconfig.h.in
==============================================================================
--- python/branches/okkoto-sizeof/pyconfig.h.in	(original)
+++ python/branches/okkoto-sizeof/pyconfig.h.in	Wed Jun  4 11:24:23 2008
@@ -688,6 +688,9 @@
 /* Define to 1 if you have the <sys/stat.h> header file. */
 #undef HAVE_SYS_STAT_H
 
+/* Define to 1 if you have the <sys/termio.h> header file. */
+#undef HAVE_SYS_TERMIO_H
+
 /* Define to 1 if you have the <sys/times.h> header file. */
 #undef HAVE_SYS_TIMES_H
 

Modified: python/branches/okkoto-sizeof/setup.py
==============================================================================
--- python/branches/okkoto-sizeof/setup.py	(original)
+++ python/branches/okkoto-sizeof/setup.py	Wed Jun  4 11:24:23 2008
@@ -5,6 +5,7 @@
 
 import sys, os, imp, re, optparse
 from glob import glob
+from platform import machine as platform_machine
 
 from distutils import log
 from distutils import sysconfig
@@ -687,13 +688,39 @@
         # a release.  Most open source OSes come with one or more
         # versions of BerkeleyDB already installed.
 
-        max_db_ver = (4, 5)  # XXX(gregory.p.smith): 4.6 "works" but seems to
-                             # have issues on many platforms.  I've temporarily
-                             # disabled 4.6 to see what the odd platform
-                             # buildbots say.
+        max_db_ver = (4, 7)
         min_db_ver = (3, 3)
         db_setup_debug = False   # verbose debug prints from this script?
 
+        def allow_db_ver(db_ver):
+            """Returns a boolean if the given BerkeleyDB version is acceptable.
+
+            Args:
+              db_ver: A tuple of the version to verify.
+            """
+            if not (min_db_ver <= db_ver <= max_db_ver):
+                return False
+            # Use this function to filter out known bad configurations.
+            if (4, 6) == db_ver[:2]:
+                # BerkeleyDB 4.6.x is not stable on many architectures.
+                arch = platform_machine()
+                if arch not in ('i386', 'i486', 'i586', 'i686',
+                                'x86_64', 'ia64'):
+                    return False
+            return True
+
+        def gen_db_minor_ver_nums(major):
+            if major == 4:
+                for x in range(max_db_ver[1]+1):
+                    if allow_db_ver((4, x)):
+                        yield x
+            elif major == 3:
+                for x in (3,):
+                    if allow_db_ver((3, x)):
+                        yield x
+            else:
+                raise ValueError("unknown major BerkeleyDB version", major)
+
         # construct a list of paths to look for the header file in on
         # top of the normal inc_dirs.
         db_inc_paths = [
@@ -708,7 +735,7 @@
             '/sw/include/db3',
         ]
         # 4.x minor number specific paths
-        for x in range(max_db_ver[1]+1):
+        for x in gen_db_minor_ver_nums(4):
             db_inc_paths.append('/usr/include/db4%d' % x)
             db_inc_paths.append('/usr/include/db4.%d' % x)
             db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x)
@@ -718,7 +745,7 @@
             # MacPorts default (http://www.macports.org/)
             db_inc_paths.append('/opt/local/include/db4%d' % x)
         # 3.x minor number specific paths
-        for x in (3,):
+        for x in gen_db_minor_ver_nums(3):
             db_inc_paths.append('/usr/include/db3%d' % x)
             db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x)
             db_inc_paths.append('/usr/local/include/db3%d' % x)
@@ -733,10 +760,10 @@
         for dn in inc_dirs:
             std_variants.append(os.path.join(dn, 'db3'))
             std_variants.append(os.path.join(dn, 'db4'))
-            for x in range(max_db_ver[1]+1):
+            for x in gen_db_minor_ver_nums(4):
                 std_variants.append(os.path.join(dn, "db4%d"%x))
                 std_variants.append(os.path.join(dn, "db4.%d"%x))
-            for x in (3,):
+            for x in gen_db_minor_ver_nums(3):
                 std_variants.append(os.path.join(dn, "db3%d"%x))
                 std_variants.append(os.path.join(dn, "db3.%d"%x))
 
@@ -771,7 +798,7 @@
                                 continue
 
                         if ( (not db_ver_inc_map.has_key(db_ver)) and
-                           (db_ver <= max_db_ver and db_ver >= min_db_ver) ):
+                            allow_db_ver(db_ver) ):
                             # save the include directory with the db.h version
                             # (first occurrence only)
                             db_ver_inc_map[db_ver] = d
@@ -816,8 +843,8 @@
 
         except db_found:
             if db_setup_debug:
-                print "db lib: using", db_ver, dblib
-                print "db: lib dir", dblib_dir, "inc dir", db_incdir
+                print "bsddb using BerkeleyDB lib:", db_ver, dblib
+                print "bsddb lib dir:", dblib_dir, " inc dir:", db_incdir
             db_incs = [db_incdir]
             dblibs = [dblib]
             # We add the runtime_library_dirs argument because the
@@ -1009,7 +1036,7 @@
                 missing.append('resource')
 
             # Sun yellow pages. Some systems have the functions in libc.
-            if platform not in ['cygwin', 'atheos']:
+            if platform not in ['cygwin', 'atheos', 'qnx6']:
                 if (self.compiler.find_library_file(lib_dirs, 'nsl')):
                     libs = ['nsl']
                 else:
@@ -1580,6 +1607,9 @@
             # finding some -z option for the Sun compiler.
             extra_link_args.append('-mimpure-text')
 
+        elif sys.platform.startswith('hp-ux'):
+            extra_link_args.append('-fPIC')
+
         ext = Extension('_ctypes',
                         include_dirs=include_dirs,
                         extra_compile_args=extra_compile_args,


More information about the Python-checkins mailing list