[Python-3000-checkins] r56267 - in python/branches/p3yk-noslice: Demo/imputil/knee.py Demo/parser/unparse.py Demo/pdist/RCSProxy.py Demo/pdist/cvslock.py Demo/threads/README Demo/tix/grid.py Doc/Makefile Doc/Makefile.deps Doc/api/abstract.tex Doc/api/concrete.tex Doc/api/exceptions.tex Doc/api/init.tex Doc/api/memory.tex Doc/api/newtypes.tex Doc/api/refcounts.dat Doc/api/utilities.tex Doc/commontex/copyright.tex Doc/commontex/license.tex Doc/dist/dist.tex Doc/ext/extending.tex Doc/ext/newtypes.tex Doc/ext/shoddy.c Doc/howto/functional.rst Doc/howto/regex.tex Doc/howto/unicode.rst Doc/inst/inst.tex Doc/lib/compiler.tex Doc/lib/email.tex Doc/lib/emailutil.tex Doc/lib/lib.tex Doc/lib/libal.tex Doc/lib/libamoeba.tex Doc/lib/libasyncore.tex Doc/lib/libatexit.tex Doc/lib/libbase64.tex Doc/lib/libbastion.tex Doc/lib/libbsddb.tex Doc/lib/libcd.tex Doc/lib/libcfgparser.tex Doc/lib/libcgitb.tex Doc/lib/libcmath.tex Doc/lib/libcmd.tex Doc/lib/libcode.tex Doc/lib/libcodecs.tex Doc/lib/libcollections.tex Doc/lib/libcommands.tex Doc/lib/libconsts.tex Doc/lib/libcontextlib.tex Doc/lib/libcookielib.tex Doc/lib/libcsv.tex Doc/lib/libctypes.tex Doc/lib/libcurses.tex Doc/lib/libcursespanel.tex Doc/lib/libdatetime.tex Doc/lib/libdbhash.tex Doc/lib/libdecimal.tex Doc/lib/libdifflib.tex Doc/lib/libdis.tex Doc/lib/libdl.tex Doc/lib/libdoctest.tex Doc/lib/libdocxmlrpc.tex Doc/lib/libdumbdbm.tex Doc/lib/libetree.tex Doc/lib/libexcs.tex Doc/lib/libfl.tex Doc/lib/libfm.tex Doc/lib/libfnmatch.tex Doc/lib/libftplib.tex Doc/lib/libfuncs.tex Doc/lib/libgettext.tex Doc/lib/libgl.tex Doc/lib/libgopherlib.tex Doc/lib/libhmac.tex Doc/lib/libhotshot.tex Doc/lib/libhtmllib.tex Doc/lib/libhtmlparser.tex Doc/lib/libhttplib.tex Doc/lib/libimageop.tex Doc/lib/libimaplib.tex Doc/lib/libimgfile.tex Doc/lib/libimp.tex Doc/lib/libinspect.tex Doc/lib/libitertools.tex Doc/lib/libjpeg.tex Doc/lib/liblogging.tex Doc/lib/libmailbox.tex Doc/lib/libmd5.tex Doc/lib/libmimetools.tex Doc/lib/libmimetypes.tex Doc/lib/libmimewriter.tex Doc/lib/libmimify.tex Doc/lib/libmmap.tex Doc/lib/libmsilib.tex Doc/lib/libmultifile.tex Doc/lib/libmutex.tex Doc/lib/libnetrc.tex Doc/lib/libnntplib.tex Doc/lib/liboptparse.tex Doc/lib/libos.tex Doc/lib/libpanel.tex Doc/lib/libpdb.tex Doc/lib/libpickle.tex Doc/lib/libpipes.tex Doc/lib/libplatform.tex Doc/lib/libpopen2.tex Doc/lib/libpoplib.tex Doc/lib/libposixfile.tex Doc/lib/libposixpath.tex Doc/lib/libpprint.tex Doc/lib/libqueue.tex Doc/lib/librandom.tex Doc/lib/libre.tex Doc/lib/librepr.tex Doc/lib/librestricted.tex Doc/lib/librexec.tex Doc/lib/librfc822.tex Doc/lib/librgbimg.tex Doc/lib/libsched.tex Doc/lib/libselect.tex Doc/lib/libsets.tex Doc/lib/libsgi.tex Doc/lib/libsha.tex Doc/lib/libshlex.tex Doc/lib/libshutil.tex Doc/lib/libsignal.tex Doc/lib/libsimplexmlrpc.tex Doc/lib/libsite.tex Doc/lib/libsmtplib.tex Doc/lib/libsocket.tex Doc/lib/libsqlite3.tex Doc/lib/libstdtypes.tex Doc/lib/libstdwin.tex Doc/lib/libstring.tex Doc/lib/libsubprocess.tex Doc/lib/libsun.tex Doc/lib/libsys.tex Doc/lib/libtarfile.tex Doc/lib/libtelnetlib.tex Doc/lib/libtempfile.tex Doc/lib/libtest.tex Doc/lib/libtextwrap.tex Doc/lib/libthreading.tex Doc/lib/libtimeit.tex Doc/lib/libturtle.tex Doc/lib/libtypes.tex Doc/lib/libundoc.tex Doc/lib/libunittest.tex Doc/lib/liburllib.tex Doc/lib/liburllib2.tex Doc/lib/liburlparse.tex Doc/lib/libwebbrowser.tex Doc/lib/libwinreg.tex Doc/lib/libxmllib.tex Doc/lib/libxmlrpclib.tex Doc/lib/libzipfile.tex Doc/lib/libzipimport.tex Doc/lib/libzlib.tex Doc/lib/sqlite3/executemany_1.py Doc/mac/libframework.tex Doc/mac/libmacfs.tex Doc/mac/libmacic.tex Doc/mac/libmacostools.tex Doc/mac/mac.tex Doc/mac/undoc.tex Doc/mac/using.tex Doc/ref/ref1.tex Doc/ref/ref2.tex Doc/ref/ref3.tex Doc/ref/ref5.tex Doc/ref/ref6.tex Doc/ref/ref7.tex Doc/texinputs/python.sty Doc/tools/buildindex.py Doc/tools/custlib.py Doc/tools/getversioninfo Doc/tools/keywords.py Doc/tools/listmodules Doc/tools/listmodules.py Doc/tools/mkackshtml Doc/tools/mkhowto Doc/tools/mkmodindex Doc/tools/prechm.py Doc/tools/refcounts.py Doc/tools/sgmlconv/docfixer.py Doc/tools/sgmlconv/esis2sgml.py Doc/tools/sgmlconv/esistools.py Doc/tools/sgmlconv/latex2esis.py Doc/tools/undoc_symbols.py Doc/tut/glossary.tex Doc/tut/tut.tex Doc/whatsnew/Makefile Doc/whatsnew/whatsnew23.tex Doc/whatsnew/whatsnew24.tex Doc/whatsnew/whatsnew25.tex Doc/whatsnew/whatsnew26.tex Doc/whatsnew/whatsnew30.tex Grammar/Grammar Include/Python-ast.h Include/abstract.h Include/asdl.h Include/bytesobject.h Include/ceval.h Include/dictobject.h Include/fileobject.h Include/floatobject.h Include/frameobject.h Include/graminit.h Include/intobject.h Include/listobject.h Include/longobject.h Include/object.h Include/opcode.h Include/pydebug.h Include/pyerrors.h Include/pymem.h Include/pyport.h Include/pystate.h Include/pythonrun.h Include/setobject.h Include/stringobject.h Include/structmember.h Include/symtable.h Include/token.h Include/tupleobject.h Include/unicodeobject.h LICENSE Lib/Bastion.py Lib/CGIHTTPServer.py Lib/ConfigParser.py Lib/Cookie.py Lib/DocXMLRPCServer.py Lib/HTMLParser.py Lib/MimeWriter.py Lib/SimpleXMLRPCServer.py Lib/SocketServer.py Lib/StringIO.py Lib/UserDict.py Lib/_abcoll.py Lib/_strptime.py Lib/abc.py Lib/aifc.py Lib/anydbm.py Lib/atexit.py Lib/bdb.py Lib/binhex.py Lib/bisect.py Lib/bsddb/__init__.py Lib/bsddb/dbrecio.py Lib/bsddb/dbshelve.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_1413192.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compat.py Lib/bsddb/test/test_dbobj.py Lib/bsddb/test/test_env_close.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_pickle.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_sequence.py Lib/bsddb/test/test_thread.py Lib/build_class.py Lib/calendar.py Lib/cgi.py Lib/cgitb.py Lib/chunk.py Lib/cmd.py Lib/codecs.py Lib/collections.py Lib/commands.py Lib/compiler Lib/contextlib.py Lib/copy.py Lib/copy_reg.py Lib/csv.py Lib/ctypes/__init__.py Lib/ctypes/_endian.py Lib/ctypes/test/test_arrays.py Lib/ctypes/test/test_checkretval.py Lib/ctypes/test/test_functions.py Lib/ctypes/test/test_init.py Lib/ctypes/test/test_loading.py Lib/ctypes/test/test_memfunctions.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_python_api.py Lib/ctypes/test/test_random_things.py Lib/ctypes/test/test_repr.py Lib/ctypes/test/test_slicing.py Lib/ctypes/test/test_structures.py Lib/ctypes/wintypes.py Lib/dbhash.py Lib/decimal.py Lib/difflib.py Lib/dis.py Lib/distutils/__init__.py Lib/distutils/ccompiler.py Lib/distutils/cmd.py Lib/distutils/command/bdist.py Lib/distutils/command/bdist_msi.py Lib/distutils/command/bdist_rpm.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/build_clib.py Lib/distutils/command/build_ext.py Lib/distutils/command/build_py.py Lib/distutils/command/build_scripts.py Lib/distutils/command/config.py Lib/distutils/command/install.py Lib/distutils/command/install_lib.py Lib/distutils/command/install_scripts.py Lib/distutils/command/register.py Lib/distutils/command/sdist.py Lib/distutils/cygwinccompiler.py Lib/distutils/dir_util.py Lib/distutils/dist.py Lib/distutils/emxccompiler.py Lib/distutils/extension.py Lib/distutils/fancy_getopt.py Lib/distutils/filelist.py Lib/distutils/msvccompiler.py Lib/distutils/mwerkscompiler.py Lib/distutils/spawn.py Lib/distutils/sysconfig.py Lib/distutils/tests/support.py Lib/distutils/tests/test_build_py.py Lib/distutils/text_file.py Lib/distutils/unixccompiler.py Lib/distutils/util.py Lib/distutils/version.py Lib/doctest.py Lib/dumbdbm.py Lib/email/_parseaddr.py Lib/email/feedparser.py Lib/email/header.py Lib/email/message.py Lib/email/test/test_email.py Lib/email/test/test_email_renamed.py Lib/encodings/__init__.py Lib/encodings/idna.py Lib/encodings/utf_16.py Lib/encodings/utf_8_sig.py Lib/encodings/uu_codec.py Lib/filecmp.py Lib/fileinput.py Lib/formatter.py Lib/ftplib.py Lib/genericpath.py Lib/gettext.py Lib/glob.py Lib/gopherlib.py Lib/gzip.py Lib/heapq.py Lib/hmac.py Lib/hotshot/log.py Lib/httplib.py Lib/idlelib/CallTips.py Lib/idlelib/CodeContext.py Lib/idlelib/Debugger.py Lib/idlelib/MultiCall.py Lib/idlelib/ObjectBrowser.py Lib/idlelib/PyShell.py Lib/idlelib/StackViewer.py Lib/idlelib/aboutDialog.py Lib/idlelib/configDialog.py Lib/idlelib/configHandler.py Lib/idlelib/keybindingDialog.py Lib/idlelib/rpc.py Lib/ihooks.py Lib/imaplib.py Lib/imputil.py Lib/inspect.py Lib/io.py Lib/keyword.py Lib/lib-old Lib/lib-tk/ScrolledText.py Lib/lib-tk/Tix.py Lib/lib-tk/Tkinter.py Lib/linecache.py Lib/locale.py Lib/logging/__init__.py Lib/logging/config.py Lib/logging/handlers.py Lib/macpath.py Lib/mailbox.py Lib/md5.py Lib/mhlib.py Lib/mimetypes.py Lib/mimify.py Lib/modulefinder.py Lib/new.py Lib/ntpath.py Lib/opcode.py Lib/optparse.py Lib/os.py Lib/pdb.doc Lib/pdb.py Lib/pickle.py Lib/pickletools.py Lib/plat-aix3 Lib/plat-atheos/IN.py Lib/plat-freebsd2 Lib/plat-freebsd3 Lib/plat-irix5 Lib/plat-irix6 Lib/plat-mac/EasyDialogs.py Lib/plat-mac/aepack.py Lib/plat-mac/aetypes.py Lib/plat-mac/applesingle.py Lib/plat-mac/buildtools.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/cfmfile.py Lib/plat-mac/findertools.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/ic.py Lib/plat-mac/macfs.py Lib/plat-mac/macostools.py Lib/plat-mac/pimp.py Lib/plat-mac/plistlib.py Lib/plat-riscos/riscospath.py Lib/plat-riscos/rourl2path.py Lib/plat-sunos5/IN.py Lib/plat-sunos5/STROPTS.py Lib/plat-unixware7/IN.py Lib/plat-unixware7/STROPTS.py Lib/platform.py Lib/popen2.py Lib/poplib.py Lib/posixfile.py Lib/posixpath.py Lib/pprint.py Lib/pstats.py Lib/pty.py Lib/pyclbr.py Lib/pydoc.py Lib/random.py Lib/re.py Lib/repr.py Lib/rexec.py Lib/robotparser.py Lib/sched.py Lib/sha.py Lib/shelve.py Lib/shlex.py Lib/site.py Lib/smtplib.py Lib/socket.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/regression.py Lib/sre.py Lib/sre_compile.py Lib/sre_parse.py Lib/stat.py Lib/string.py Lib/stringold.py Lib/stringprep.py Lib/subprocess.py Lib/sunau.py Lib/symbol.py Lib/tarfile.py Lib/telnetlib.py Lib/tempfile.py Lib/test/README Lib/test/bad_coding2.py Lib/test/crashers/dangerous_subclassing.py Lib/test/crashers/infinite_rec_5.py Lib/test/crashers/modify_dict_attr.py Lib/test/dis_module.py Lib/test/exception_hierarchy.txt Lib/test/fork_wait.py Lib/test/inspect_fodder.py Lib/test/inspect_fodder2.py Lib/test/leakers/test_selftype.py Lib/test/list_tests.py Lib/test/mapping_tests.py Lib/test/output/test_cProfile Lib/test/output/test_class Lib/test/output/test_extcall Lib/test/output/test_logging Lib/test/output/test_operations Lib/test/output/test_pkg Lib/test/output/test_popen2 Lib/test/output/test_profile Lib/test/output/test_pty Lib/test/output/test_pyexpat Lib/test/output/test_threadedtempfile Lib/test/output/test_tokenize Lib/test/output/xmltests Lib/test/outstanding_bugs.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/seq_tests.py Lib/test/sortperf.py Lib/test/ssl_cert.pem Lib/test/ssl_key.pem Lib/test/string_tests.py Lib/test/test_MimeWriter.py Lib/test/test_StringIO.py Lib/test/test___all__.py Lib/test/test_abc.py Lib/test/test_al.py Lib/test/test_anydbm.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_atexit.py Lib/test/test_base64.py Lib/test/test_bastion.py Lib/test/test_binascii.py Lib/test/test_bisect.py Lib/test/test_bool.py Lib/test/test_bsddb.py Lib/test/test_bsddb185.py Lib/test/test_bsddb3.py Lib/test/test_bufio.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_bz2.py Lib/test/test_calendar.py Lib/test/test_cd.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_cl.py Lib/test/test_class.py Lib/test/test_cmath.py Lib/test/test_cmd_line.py Lib/test/test_code.py Lib/test/test_codeccallbacks.py Lib/test/test_codecencodings_cn.py Lib/test/test_codecencodings_hk.py Lib/test/test_codecencodings_jp.py Lib/test/test_codecencodings_kr.py Lib/test/test_codecencodings_tw.py Lib/test/test_codecmaps_cn.py Lib/test/test_codecmaps_hk.py Lib/test/test_codecmaps_jp.py Lib/test/test_codecmaps_kr.py Lib/test/test_codecmaps_tw.py Lib/test/test_codecs.py Lib/test/test_codeop.py Lib/test/test_collections.py Lib/test/test_commands.py Lib/test/test_compare.py Lib/test/test_compile.py Lib/test/test_compiler.py Lib/test/test_complex.py Lib/test/test_complex_args.py Lib/test/test_contains.py Lib/test/test_contextlib.py Lib/test/test_copy.py Lib/test/test_crypt.py Lib/test/test_csv.py Lib/test/test_ctypes.py Lib/test/test_curses.py Lib/test/test_datetime.py Lib/test/test_dbm.py Lib/test/test_decimal.py Lib/test/test_decorators.py Lib/test/test_defaultdict.py Lib/test/test_deque.py Lib/test/test_descr.py Lib/test/test_descrtut.py Lib/test/test_dict.py Lib/test/test_difflib.py Lib/test/test_dis.py Lib/test/test_doctest.py Lib/test/test_dumbdbm.py Lib/test/test_dummy_thread.py Lib/test/test_email.py Lib/test/test_email_codecs.py Lib/test/test_email_renamed.py Lib/test/test_enumerate.py Lib/test/test_exceptions.py Lib/test/test_extcall.py Lib/test/test_file.py Lib/test/test_fileinput.py Lib/test/test_fileio.py Lib/test/test_format.py Lib/test/test_ftplib.py Lib/test/test_funcattrs.py Lib/test/test_functools.py Lib/test/test_future2.py Lib/test/test_gc.py Lib/test/test_generators.py Lib/test/test_genexps.py Lib/test/test_getopt.py Lib/test/test_gettext.py Lib/test/test_gl.py Lib/test/test_glob.py Lib/test/test_grammar.py Lib/test/test_grp.py Lib/test/test_hash.py Lib/test/test_heapq.py Lib/test/test_hexoct.py Lib/test/test_hmac.py Lib/test/test_hotshot.py Lib/test/test_htmlparser.py Lib/test/test_httplib.py Lib/test/test_imageop.py Lib/test/test_imgfile.py Lib/test/test_import.py Lib/test/test_importhooks.py Lib/test/test_index.py Lib/test/test_inspect.py Lib/test/test_io.py Lib/test/test_isinstance.py Lib/test/test_iter.py Lib/test/test_iterlen.py Lib/test/test_itertools.py Lib/test/test_keywordonlyarg.py Lib/test/test_linuxaudiodev.py Lib/test/test_list.py Lib/test/test_listcomps.py Lib/test/test_locale.py Lib/test/test_logging.py Lib/test/test_long.py Lib/test/test_long_future.py Lib/test/test_macfs.py Lib/test/test_macostools.py Lib/test/test_macpath.py Lib/test/test_mailbox.py Lib/test/test_marshal.py Lib/test/test_math.py Lib/test/test_md5.py Lib/test/test_metaclass.py Lib/test/test_mhlib.py Lib/test/test_mimetools.py Lib/test/test_minidom.py Lib/test/test_mmap.py Lib/test/test_module.py Lib/test/test_modulefinder.py Lib/test/test_multibytecodec.py Lib/test/test_multibytecodec_support.py Lib/test/test_mutants.py Lib/test/test_new.py Lib/test/test_normalization.py Lib/test/test_ntpath.py Lib/test/test_old_mailbox.py Lib/test/test_operations.py Lib/test/test_operator.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_ossaudiodev.py Lib/test/test_peepholer.py Lib/test/test_pep247.py Lib/test/test_pep352.py Lib/test/test_pkg.py Lib/test/test_popen2.py Lib/test/test_poplib.py Lib/test/test_posixpath.py Lib/test/test_pow.py Lib/test/test_pprint.py Lib/test/test_profilehooks.py Lib/test/test_pty.py Lib/test/test_pwd.py Lib/test/test_pyclbr.py Lib/test/test_pyexpat.py Lib/test/test_queue.py Lib/test/test_random.py Lib/test/test_re.py Lib/test/test_repr.py Lib/test/test_rgbimg.py Lib/test/test_richcmp.py Lib/test/test_robotparser.py Lib/test/test_sax.py Lib/test/test_scope.py Lib/test/test_set.py Lib/test/test_setcomps.py Lib/test/test_sha.py Lib/test/test_slice.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_socket_ssl.py Lib/test/test_socketserver.py Lib/test/test_sort.py Lib/test/test_str.py Lib/test/test_string.py Lib/test/test_stringprep.py Lib/test/test_strop.py Lib/test/test_strptime.py Lib/test/test_struct.py Lib/test/test_structmembers.py Lib/test/test_structseq.py Lib/test/test_subprocess.py Lib/test/test_sundry.py Lib/test/test_super.py Lib/test/test_support.py Lib/test/test_syntax.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_telnetlib.py Lib/test/test_tempfile.py Lib/test/test_textwrap.py Lib/test/test_threadedtempfile.py Lib/test/test_threading.py Lib/test/test_threading_local.py Lib/test/test_threadsignals.py Lib/test/test_tokenize.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_transformer.py Lib/test/test_tuple.py Lib/test/test_typechecks.py Lib/test/test_ucn.py Lib/test/test_unicode.py Lib/test/test_unicode_file.py Lib/test/test_unicodedata.py Lib/test/test_unittest.py Lib/test/test_univnewlines.py Lib/test/test_unpack.py Lib/test/test_unpack_ex.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urllib2_localnet.py Lib/test/test_urllib2net.py Lib/test/test_userdict.py Lib/test/test_userlist.py Lib/test/test_uu.py Lib/test/test_warnings.py Lib/test/test_weakref.py Lib/test/test_winsound.py Lib/test/test_wsgiref.py Lib/test/test_xdrlib.py Lib/test/test_xml_etree.py Lib/test/test_xml_etree_c.py Lib/test/test_xmllib.py Lib/test/test_xmlrpc.py Lib/test/test_xrange.py Lib/test/test_zipfile.py Lib/test/test_zipfile64.py Lib/test/test_zipimport.py Lib/test/test_zlib.py Lib/test/testtar.tar Lib/test/tf_inherit_check.py Lib/test/time_hashlib.py Lib/test/tokenize_tests.txt Lib/test/warning_tests.py Lib/test/xmltests.py Lib/textwrap.py Lib/threading.py Lib/timeit.py Lib/token.py Lib/tokenize.py Lib/trace.py Lib/traceback.py Lib/types.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/urlparse.py Lib/uu.py Lib/uuid.py Lib/warnings.py Lib/wave.py Lib/weakref.py Lib/webbrowser.py Lib/wsgiref/handlers.py Lib/wsgiref/headers.py Lib/wsgiref/util.py Lib/wsgiref/validate.py Lib/xml/dom/domreg.py Lib/xml/dom/pulldom.py Lib/xml/etree/ElementTree.py Lib/xml/sax/saxutils.py Lib/xmllib.py Lib/xmlrpclib.py Lib/zipfile.py Makefile.pre.in Misc/ACKS Misc/BeOS-NOTES Misc/BeOS-setup.py Misc/NEWS Misc/Vim/python.vim Misc/Vim/vim_syntax.py Misc/build.sh Misc/cheatsheet Misc/developers.txt Misc/python-config.in Misc/python-mode.el Misc/valgrind-python.supp Modules/Setup.dist Modules/_bsddb.c Modules/_collectionsmodule.c Modules/_ctypes/_ctypes.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/libffi/configure Modules/_ctypes/libffi/configure.ac Modules/_ctypes/libffi/fficonfig.h.in Modules/_ctypes/libffi/src/x86/ffi.c Modules/_ctypes/libffi/src/x86/ffi64.c Modules/_ctypes/libffi_msvc/ffitarget.h Modules/_ctypes/stgdict.c Modules/_cursesmodule.c Modules/_fileio.c Modules/_localemodule.c Modules/_sqlite/cache.c Modules/_sqlite/module.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/almodule.c Modules/arraymodule.c Modules/atexitmodule.c Modules/binascii.c Modules/bsddbmodule.c Modules/bz2module.c Modules/cPickle.c Modules/cStringIO.c Modules/cdmodule.c Modules/cgen.py Modules/cgensupport.c Modules/cgensupport.h Modules/cjkcodecs/multibytecodec.c Modules/clmodule.c Modules/collectionsmodule.c Modules/config.c.in Modules/cstubs Modules/datetimemodule.c Modules/flmodule.c Modules/fmmodule.c Modules/getaddrinfo.c Modules/getbuildinfo.c Modules/getnameinfo.c Modules/getpath.c Modules/glmodule.c Modules/imageop.c Modules/imgfile.c Modules/itertoolsmodule.c Modules/main.c Modules/md5.c Modules/md5.h Modules/md5module.c Modules/operator.c Modules/parsermodule.c Modules/posixmodule.c Modules/puremodule.c Modules/readline.c Modules/rgbimgmodule.c Modules/sgimodule.c Modules/shamodule.c Modules/socketmodule.c Modules/stropmodule.c Modules/svmodule.c Modules/symtablemodule.c Modules/timemodule.c Modules/timing.h Modules/timingmodule.c Objects/abstract.c Objects/bufferobject.c Objects/bytesobject.c Objects/complexobject.c Objects/dictobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/funcobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/object.c Objects/rangeobject.c Objects/setobject.c Objects/sliceobject.c Objects/stringobject.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodeobject.c PC/VC6/pcbuild.dsw PC/VC6/pythoncore.dsp PC/WinMain.c PC/_winreg.c PC/config.c PC/dl_nt.c PC/getpathp.c PC/make_versioninfo.c PC/os2emx/Makefile PC/os2emx/config.c PC/os2emx/python25.def PC/os2vacpp/config.c PC/os2vacpp/makefile PC/os2vacpp/makefile.omk PC/os2vacpp/python.def PC/pyconfig.h PC/winsound.c PCbuild/_bsddb.vcproj PCbuild/_ssl.mak PCbuild/build_ssl.bat PCbuild/build_ssl.py PCbuild/pcbuild.sln PCbuild/python.iss PCbuild/pythoncore.vcproj PCbuild8/PGInstrument.vsprops PCbuild8/PGUpdate.vsprops PCbuild8/Uninstal.wse PCbuild8/_bsddb PCbuild8/_bsddb.vcproj PCbuild8/_ctypes PCbuild8/_ctypes.vcproj PCbuild8/_ctypes_test PCbuild8/_ctypes_test.vcproj PCbuild8/_elementtree PCbuild8/_elementtree.vcproj PCbuild8/_msi PCbuild8/_msi.vcproj PCbuild8/_socket PCbuild8/_socket.vcproj PCbuild8/_sqlite3 PCbuild8/_sqlite3.vcproj PCbuild8/_ssl.mak PCbuild8/_ssl.vcproj PCbuild8/_testcapi PCbuild8/_testcapi.vcproj PCbuild8/_tkinter PCbuild8/_tkinter.vcproj PCbuild8/build.bat PCbuild8/build_pgo.bat PCbuild8/build_ssl.py PCbuild8/bz2 PCbuild8/bz2.vcproj PCbuild8/db.build PCbuild8/field3.py PCbuild8/make_buildinfo PCbuild8/make_buildinfo.c PCbuild8/make_buildinfo.vcproj PCbuild8/make_versioninfo PCbuild8/make_versioninfo.vcproj PCbuild8/pcbuild.sln PCbuild8/pyd.vsprops PCbuild8/pyd_d.vsprops PCbuild8/pyexpat PCbuild8/pyexpat.vcproj PCbuild8/pyproject.vsprops PCbuild8/python PCbuild8/python.build PCbuild8/python.iss PCbuild8/python.vcproj PCbuild8/python20.wse PCbuild8/pythoncore PCbuild8/pythoncore.vcproj PCbuild8/pythonw PCbuild8/pythonw.vcproj PCbuild8/readme.txt PCbuild8/rmpyc.py PCbuild8/rt.bat PCbuild8/select PCbuild8/select.vcproj PCbuild8/unicodedata PCbuild8/unicodedata.vcproj PCbuild8/w9xpopen.vcproj PCbuild8/winsound PCbuild8/winsound.vcproj Parser/Python.asdl Parser/asdl.py Parser/asdl_c.py Parser/spark.py Parser/tokenizer.c Python/Python-ast.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/dynload_win.c Python/errors.c Python/fmod.c Python/graminit.c Python/import.c Python/marshal.c Python/mystrtoul.c Python/peephole.c Python/pystate.c Python/pythonrun.c Python/structmember.c Python/symtable.c Python/sysmodule.c Python/thread_nt.h README RISCOS/Makefile RISCOS/Modules/config.c Tools/buildbot/README.tcltk-AMD64 Tools/buildbot/build-amd64.bat Tools/buildbot/clean-amd64.bat Tools/buildbot/external-amd64.bat Tools/buildbot/test-amd64.bat Tools/compiler Tools/i18n/msgfmt.py Tools/msi/msilib.py Tools/pybench/Arithmetic.py Tools/pybench/Calls.py Tools/pybench/CommandLine.py Tools/pybench/Constructs.py Tools/pybench/Dict.py Tools/pybench/Exceptions.py Tools/pybench/Imports.py Tools/pybench/Instances.py Tools/pybench/Lists.py Tools/pybench/Lookups.py Tools/pybench/NewInstances.py Tools/pybench/Numbers.py Tools/pybench/Strings.py Tools/pybench/Tuples.py Tools/pybench/Unicode.py Tools/pybench/clockres.py Tools/pybench/pybench.py Tools/pybench/systimes.py Tools/scripts/classfix.py Tools/scripts/cleanfuture.py Tools/scripts/fixcid.py Tools/scripts/ftpmirror.py Tools/scripts/linktree.py Tools/scripts/methfix.py Tools/scripts/pathfix.py Tools/scripts/reindent.py Tools/scripts/which.py Tools/unicode/makeunicodedata.py Tools/unicode/mkstringprep.py Tools/versioncheck/pyversioncheck.py Tools/webchecker/websucker.py configure configure.in setup.py

thomas.wouters python-3000-checkins at python.org
Wed Jul 11 15:41:41 CEST 2007


Author: thomas.wouters
Date: Wed Jul 11 15:40:56 2007
New Revision: 56267

Added:
   python/branches/p3yk-noslice/Doc/ext/shoddy.c
      - copied unchanged from r56202, python/branches/p3yk/Doc/ext/shoddy.c
   python/branches/p3yk-noslice/Doc/whatsnew/whatsnew30.tex
      - copied unchanged from r56202, python/branches/p3yk/Doc/whatsnew/whatsnew30.tex
   python/branches/p3yk-noslice/Lib/_abcoll.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/_abcoll.py
   python/branches/p3yk-noslice/Lib/abc.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/abc.py
   python/branches/p3yk-noslice/Lib/build_class.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/build_class.py
   python/branches/p3yk-noslice/Lib/collections.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/collections.py
   python/branches/p3yk-noslice/Lib/io.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/io.py
   python/branches/p3yk-noslice/Lib/test/dis_module.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/dis_module.py
   python/branches/p3yk-noslice/Lib/test/ssl_cert.pem
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/ssl_cert.pem
   python/branches/p3yk-noslice/Lib/test/ssl_key.pem
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/ssl_key.pem
   python/branches/p3yk-noslice/Lib/test/test_abc.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_abc.py
   python/branches/p3yk-noslice/Lib/test/test_collections.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_collections.py
   python/branches/p3yk-noslice/Lib/test/test_fileio.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_fileio.py
   python/branches/p3yk-noslice/Lib/test/test_ftplib.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_ftplib.py
   python/branches/p3yk-noslice/Lib/test/test_io.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_io.py
   python/branches/p3yk-noslice/Lib/test/test_listcomps.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_listcomps.py
   python/branches/p3yk-noslice/Lib/test/test_metaclass.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_metaclass.py
   python/branches/p3yk-noslice/Lib/test/test_poplib.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_poplib.py
   python/branches/p3yk-noslice/Lib/test/test_setcomps.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_setcomps.py
   python/branches/p3yk-noslice/Lib/test/test_smtplib.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_smtplib.py
   python/branches/p3yk-noslice/Lib/test/test_super.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_super.py
   python/branches/p3yk-noslice/Lib/test/test_telnetlib.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_telnetlib.py
   python/branches/p3yk-noslice/Lib/test/test_typechecks.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_typechecks.py
   python/branches/p3yk-noslice/Lib/test/test_unpack_ex.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_unpack_ex.py
   python/branches/p3yk-noslice/Lib/test/test_urllib2_localnet.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/test_urllib2_localnet.py
   python/branches/p3yk-noslice/Lib/test/warning_tests.py
      - copied unchanged from r56202, python/branches/p3yk/Lib/test/warning_tests.py
   python/branches/p3yk-noslice/Modules/_collectionsmodule.c
      - copied unchanged from r56202, python/branches/p3yk/Modules/_collectionsmodule.c
   python/branches/p3yk-noslice/Modules/_fileio.c
      - copied unchanged from r56202, python/branches/p3yk/Modules/_fileio.c
   python/branches/p3yk-noslice/Modules/atexitmodule.c
      - copied unchanged from r56202, python/branches/p3yk/Modules/atexitmodule.c
   python/branches/p3yk-noslice/PCbuild8/PGInstrument.vsprops
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/PGInstrument.vsprops
   python/branches/p3yk-noslice/PCbuild8/PGUpdate.vsprops
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/PGUpdate.vsprops
   python/branches/p3yk-noslice/PCbuild8/_bsddb/
      - copied from r56202, python/branches/p3yk/PCbuild8/_bsddb/
   python/branches/p3yk-noslice/PCbuild8/_ctypes/
      - copied from r56202, python/branches/p3yk/PCbuild8/_ctypes/
   python/branches/p3yk-noslice/PCbuild8/_ctypes_test/
      - copied from r56202, python/branches/p3yk/PCbuild8/_ctypes_test/
   python/branches/p3yk-noslice/PCbuild8/_elementtree/
      - copied from r56202, python/branches/p3yk/PCbuild8/_elementtree/
   python/branches/p3yk-noslice/PCbuild8/_msi/
      - copied from r56202, python/branches/p3yk/PCbuild8/_msi/
   python/branches/p3yk-noslice/PCbuild8/_socket/
      - copied from r56202, python/branches/p3yk/PCbuild8/_socket/
   python/branches/p3yk-noslice/PCbuild8/_sqlite3/
      - copied from r56202, python/branches/p3yk/PCbuild8/_sqlite3/
   python/branches/p3yk-noslice/PCbuild8/_testcapi/
      - copied from r56202, python/branches/p3yk/PCbuild8/_testcapi/
   python/branches/p3yk-noslice/PCbuild8/_tkinter/
      - copied from r56202, python/branches/p3yk/PCbuild8/_tkinter/
   python/branches/p3yk-noslice/PCbuild8/build.bat
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/build.bat
   python/branches/p3yk-noslice/PCbuild8/build_pgo.bat
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/build_pgo.bat
   python/branches/p3yk-noslice/PCbuild8/bz2/
      - copied from r56202, python/branches/p3yk/PCbuild8/bz2/
   python/branches/p3yk-noslice/PCbuild8/make_buildinfo/
      - copied from r56202, python/branches/p3yk/PCbuild8/make_buildinfo/
   python/branches/p3yk-noslice/PCbuild8/make_versioninfo/
      - copied from r56202, python/branches/p3yk/PCbuild8/make_versioninfo/
   python/branches/p3yk-noslice/PCbuild8/pyd.vsprops
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/pyd.vsprops
   python/branches/p3yk-noslice/PCbuild8/pyd_d.vsprops
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/pyd_d.vsprops
   python/branches/p3yk-noslice/PCbuild8/pyexpat/
      - copied from r56202, python/branches/p3yk/PCbuild8/pyexpat/
   python/branches/p3yk-noslice/PCbuild8/pyproject.vsprops
      - copied unchanged from r56202, python/branches/p3yk/PCbuild8/pyproject.vsprops
   python/branches/p3yk-noslice/PCbuild8/python/
      - copied from r56202, python/branches/p3yk/PCbuild8/python/
   python/branches/p3yk-noslice/PCbuild8/pythoncore/
      - copied from r56202, python/branches/p3yk/PCbuild8/pythoncore/
   python/branches/p3yk-noslice/PCbuild8/pythonw/
      - copied from r56202, python/branches/p3yk/PCbuild8/pythonw/
   python/branches/p3yk-noslice/PCbuild8/select/
      - copied from r56202, python/branches/p3yk/PCbuild8/select/
   python/branches/p3yk-noslice/PCbuild8/unicodedata/
      - copied from r56202, python/branches/p3yk/PCbuild8/unicodedata/
   python/branches/p3yk-noslice/PCbuild8/winsound/
      - copied from r56202, python/branches/p3yk/PCbuild8/winsound/
   python/branches/p3yk-noslice/Tools/buildbot/README.tcltk-AMD64
      - copied unchanged from r56202, python/branches/p3yk/Tools/buildbot/README.tcltk-AMD64
   python/branches/p3yk-noslice/Tools/buildbot/build-amd64.bat
      - copied unchanged from r56202, python/branches/p3yk/Tools/buildbot/build-amd64.bat
   python/branches/p3yk-noslice/Tools/buildbot/clean-amd64.bat
      - copied unchanged from r56202, python/branches/p3yk/Tools/buildbot/clean-amd64.bat
   python/branches/p3yk-noslice/Tools/buildbot/external-amd64.bat
      - copied unchanged from r56202, python/branches/p3yk/Tools/buildbot/external-amd64.bat
   python/branches/p3yk-noslice/Tools/buildbot/test-amd64.bat
      - copied unchanged from r56202, python/branches/p3yk/Tools/buildbot/test-amd64.bat
Removed:
   python/branches/p3yk-noslice/Doc/lib/compiler.tex
   python/branches/p3yk-noslice/Doc/lib/libal.tex
   python/branches/p3yk-noslice/Doc/lib/libamoeba.tex
   python/branches/p3yk-noslice/Doc/lib/libbastion.tex
   python/branches/p3yk-noslice/Doc/lib/libcd.tex
   python/branches/p3yk-noslice/Doc/lib/libfl.tex
   python/branches/p3yk-noslice/Doc/lib/libfm.tex
   python/branches/p3yk-noslice/Doc/lib/libgl.tex
   python/branches/p3yk-noslice/Doc/lib/libgopherlib.tex
   python/branches/p3yk-noslice/Doc/lib/libimageop.tex
   python/branches/p3yk-noslice/Doc/lib/libimgfile.tex
   python/branches/p3yk-noslice/Doc/lib/libjpeg.tex
   python/branches/p3yk-noslice/Doc/lib/libmd5.tex
   python/branches/p3yk-noslice/Doc/lib/libmimewriter.tex
   python/branches/p3yk-noslice/Doc/lib/libmimify.tex
   python/branches/p3yk-noslice/Doc/lib/libpanel.tex
   python/branches/p3yk-noslice/Doc/lib/libpopen2.tex
   python/branches/p3yk-noslice/Doc/lib/libposixfile.tex
   python/branches/p3yk-noslice/Doc/lib/librestricted.tex
   python/branches/p3yk-noslice/Doc/lib/librexec.tex
   python/branches/p3yk-noslice/Doc/lib/librgbimg.tex
   python/branches/p3yk-noslice/Doc/lib/libsets.tex
   python/branches/p3yk-noslice/Doc/lib/libsgi.tex
   python/branches/p3yk-noslice/Doc/lib/libsha.tex
   python/branches/p3yk-noslice/Doc/lib/libstdwin.tex
   python/branches/p3yk-noslice/Doc/lib/libxmllib.tex
   python/branches/p3yk-noslice/Doc/mac/libmacfs.tex
   python/branches/p3yk-noslice/Doc/whatsnew/Makefile
   python/branches/p3yk-noslice/Lib/Bastion.py
   python/branches/p3yk-noslice/Lib/MimeWriter.py
   python/branches/p3yk-noslice/Lib/atexit.py
   python/branches/p3yk-noslice/Lib/compiler/
   python/branches/p3yk-noslice/Lib/gopherlib.py
   python/branches/p3yk-noslice/Lib/lib-old/
   python/branches/p3yk-noslice/Lib/md5.py
   python/branches/p3yk-noslice/Lib/mimify.py
   python/branches/p3yk-noslice/Lib/plat-aix3/
   python/branches/p3yk-noslice/Lib/plat-freebsd2/
   python/branches/p3yk-noslice/Lib/plat-freebsd3/
   python/branches/p3yk-noslice/Lib/plat-irix5/
   python/branches/p3yk-noslice/Lib/plat-irix6/
   python/branches/p3yk-noslice/Lib/plat-mac/cfmfile.py
   python/branches/p3yk-noslice/Lib/plat-mac/macfs.py
   python/branches/p3yk-noslice/Lib/popen2.py
   python/branches/p3yk-noslice/Lib/posixfile.py
   python/branches/p3yk-noslice/Lib/rexec.py
   python/branches/p3yk-noslice/Lib/sha.py
   python/branches/p3yk-noslice/Lib/stringold.py
   python/branches/p3yk-noslice/Lib/test/crashers/dangerous_subclassing.py
   python/branches/p3yk-noslice/Lib/test/crashers/infinite_rec_5.py
   python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py
   python/branches/p3yk-noslice/Lib/test/output/test_operations
   python/branches/p3yk-noslice/Lib/test/output/test_popen2
   python/branches/p3yk-noslice/Lib/test/output/test_pty
   python/branches/p3yk-noslice/Lib/test/output/test_pyexpat
   python/branches/p3yk-noslice/Lib/test/output/test_threadedtempfile
   python/branches/p3yk-noslice/Lib/test/output/xmltests
   python/branches/p3yk-noslice/Lib/test/test_MimeWriter.py
   python/branches/p3yk-noslice/Lib/test/test_al.py
   python/branches/p3yk-noslice/Lib/test/test_bastion.py
   python/branches/p3yk-noslice/Lib/test/test_bsddb185.py
   python/branches/p3yk-noslice/Lib/test/test_cd.py
   python/branches/p3yk-noslice/Lib/test/test_cl.py
   python/branches/p3yk-noslice/Lib/test/test_compiler.py
   python/branches/p3yk-noslice/Lib/test/test_complex_args.py
   python/branches/p3yk-noslice/Lib/test/test_gl.py
   python/branches/p3yk-noslice/Lib/test/test_imageop.py
   python/branches/p3yk-noslice/Lib/test/test_imgfile.py
   python/branches/p3yk-noslice/Lib/test/test_macfs.py
   python/branches/p3yk-noslice/Lib/test/test_md5.py
   python/branches/p3yk-noslice/Lib/test/test_operations.py
   python/branches/p3yk-noslice/Lib/test/test_popen2.py
   python/branches/p3yk-noslice/Lib/test/test_rgbimg.py
   python/branches/p3yk-noslice/Lib/test/test_sha.py
   python/branches/p3yk-noslice/Lib/test/test_strop.py
   python/branches/p3yk-noslice/Lib/test/test_transformer.py
   python/branches/p3yk-noslice/Lib/test/test_xmllib.py
   python/branches/p3yk-noslice/Lib/xmllib.py
   python/branches/p3yk-noslice/Modules/almodule.c
   python/branches/p3yk-noslice/Modules/bsddbmodule.c
   python/branches/p3yk-noslice/Modules/cdmodule.c
   python/branches/p3yk-noslice/Modules/cgen.py
   python/branches/p3yk-noslice/Modules/cgensupport.c
   python/branches/p3yk-noslice/Modules/cgensupport.h
   python/branches/p3yk-noslice/Modules/clmodule.c
   python/branches/p3yk-noslice/Modules/collectionsmodule.c
   python/branches/p3yk-noslice/Modules/cstubs
   python/branches/p3yk-noslice/Modules/flmodule.c
   python/branches/p3yk-noslice/Modules/fmmodule.c
   python/branches/p3yk-noslice/Modules/glmodule.c
   python/branches/p3yk-noslice/Modules/imageop.c
   python/branches/p3yk-noslice/Modules/imgfile.c
   python/branches/p3yk-noslice/Modules/md5.c
   python/branches/p3yk-noslice/Modules/md5.h
   python/branches/p3yk-noslice/Modules/md5module.c
   python/branches/p3yk-noslice/Modules/puremodule.c
   python/branches/p3yk-noslice/Modules/rgbimgmodule.c
   python/branches/p3yk-noslice/Modules/sgimodule.c
   python/branches/p3yk-noslice/Modules/shamodule.c
   python/branches/p3yk-noslice/Modules/stropmodule.c
   python/branches/p3yk-noslice/Modules/svmodule.c
   python/branches/p3yk-noslice/Modules/timing.h
   python/branches/p3yk-noslice/Modules/timingmodule.c
   python/branches/p3yk-noslice/PCbuild8/Uninstal.wse
   python/branches/p3yk-noslice/PCbuild8/_bsddb.vcproj
   python/branches/p3yk-noslice/PCbuild8/_ctypes.vcproj
   python/branches/p3yk-noslice/PCbuild8/_ctypes_test.vcproj
   python/branches/p3yk-noslice/PCbuild8/_elementtree.vcproj
   python/branches/p3yk-noslice/PCbuild8/_msi.vcproj
   python/branches/p3yk-noslice/PCbuild8/_socket.vcproj
   python/branches/p3yk-noslice/PCbuild8/_sqlite3.vcproj
   python/branches/p3yk-noslice/PCbuild8/_ssl.mak
   python/branches/p3yk-noslice/PCbuild8/_ssl.vcproj
   python/branches/p3yk-noslice/PCbuild8/_testcapi.vcproj
   python/branches/p3yk-noslice/PCbuild8/_tkinter.vcproj
   python/branches/p3yk-noslice/PCbuild8/build_ssl.py
   python/branches/p3yk-noslice/PCbuild8/bz2.vcproj
   python/branches/p3yk-noslice/PCbuild8/db.build
   python/branches/p3yk-noslice/PCbuild8/field3.py
   python/branches/p3yk-noslice/PCbuild8/make_buildinfo.c
   python/branches/p3yk-noslice/PCbuild8/make_buildinfo.vcproj
   python/branches/p3yk-noslice/PCbuild8/make_versioninfo.vcproj
   python/branches/p3yk-noslice/PCbuild8/pyexpat.vcproj
   python/branches/p3yk-noslice/PCbuild8/python.build
   python/branches/p3yk-noslice/PCbuild8/python.iss
   python/branches/p3yk-noslice/PCbuild8/python.vcproj
   python/branches/p3yk-noslice/PCbuild8/python20.wse
   python/branches/p3yk-noslice/PCbuild8/pythoncore.vcproj
   python/branches/p3yk-noslice/PCbuild8/pythonw.vcproj
   python/branches/p3yk-noslice/PCbuild8/select.vcproj
   python/branches/p3yk-noslice/PCbuild8/unicodedata.vcproj
   python/branches/p3yk-noslice/PCbuild8/w9xpopen.vcproj
   python/branches/p3yk-noslice/PCbuild8/winsound.vcproj
   python/branches/p3yk-noslice/Python/fmod.c
   python/branches/p3yk-noslice/Tools/compiler/
Modified:
   python/branches/p3yk-noslice/   (props changed)
   python/branches/p3yk-noslice/Demo/imputil/knee.py
   python/branches/p3yk-noslice/Demo/parser/unparse.py
   python/branches/p3yk-noslice/Demo/pdist/RCSProxy.py
   python/branches/p3yk-noslice/Demo/pdist/cvslock.py
   python/branches/p3yk-noslice/Demo/threads/README
   python/branches/p3yk-noslice/Demo/tix/grid.py
   python/branches/p3yk-noslice/Doc/Makefile
   python/branches/p3yk-noslice/Doc/Makefile.deps
   python/branches/p3yk-noslice/Doc/api/abstract.tex
   python/branches/p3yk-noslice/Doc/api/concrete.tex
   python/branches/p3yk-noslice/Doc/api/exceptions.tex
   python/branches/p3yk-noslice/Doc/api/init.tex
   python/branches/p3yk-noslice/Doc/api/memory.tex
   python/branches/p3yk-noslice/Doc/api/newtypes.tex
   python/branches/p3yk-noslice/Doc/api/refcounts.dat
   python/branches/p3yk-noslice/Doc/api/utilities.tex
   python/branches/p3yk-noslice/Doc/commontex/copyright.tex
   python/branches/p3yk-noslice/Doc/commontex/license.tex
   python/branches/p3yk-noslice/Doc/dist/dist.tex
   python/branches/p3yk-noslice/Doc/ext/extending.tex
   python/branches/p3yk-noslice/Doc/ext/newtypes.tex
   python/branches/p3yk-noslice/Doc/howto/functional.rst
   python/branches/p3yk-noslice/Doc/howto/regex.tex
   python/branches/p3yk-noslice/Doc/howto/unicode.rst
   python/branches/p3yk-noslice/Doc/inst/inst.tex
   python/branches/p3yk-noslice/Doc/lib/email.tex
   python/branches/p3yk-noslice/Doc/lib/emailutil.tex
   python/branches/p3yk-noslice/Doc/lib/lib.tex
   python/branches/p3yk-noslice/Doc/lib/libasyncore.tex
   python/branches/p3yk-noslice/Doc/lib/libatexit.tex
   python/branches/p3yk-noslice/Doc/lib/libbase64.tex
   python/branches/p3yk-noslice/Doc/lib/libbsddb.tex
   python/branches/p3yk-noslice/Doc/lib/libcfgparser.tex
   python/branches/p3yk-noslice/Doc/lib/libcgitb.tex
   python/branches/p3yk-noslice/Doc/lib/libcmath.tex
   python/branches/p3yk-noslice/Doc/lib/libcmd.tex
   python/branches/p3yk-noslice/Doc/lib/libcode.tex
   python/branches/p3yk-noslice/Doc/lib/libcodecs.tex
   python/branches/p3yk-noslice/Doc/lib/libcollections.tex
   python/branches/p3yk-noslice/Doc/lib/libcommands.tex
   python/branches/p3yk-noslice/Doc/lib/libconsts.tex
   python/branches/p3yk-noslice/Doc/lib/libcontextlib.tex
   python/branches/p3yk-noslice/Doc/lib/libcookielib.tex
   python/branches/p3yk-noslice/Doc/lib/libcsv.tex
   python/branches/p3yk-noslice/Doc/lib/libctypes.tex
   python/branches/p3yk-noslice/Doc/lib/libcurses.tex
   python/branches/p3yk-noslice/Doc/lib/libcursespanel.tex
   python/branches/p3yk-noslice/Doc/lib/libdatetime.tex
   python/branches/p3yk-noslice/Doc/lib/libdbhash.tex
   python/branches/p3yk-noslice/Doc/lib/libdecimal.tex
   python/branches/p3yk-noslice/Doc/lib/libdifflib.tex
   python/branches/p3yk-noslice/Doc/lib/libdis.tex
   python/branches/p3yk-noslice/Doc/lib/libdl.tex
   python/branches/p3yk-noslice/Doc/lib/libdoctest.tex
   python/branches/p3yk-noslice/Doc/lib/libdocxmlrpc.tex
   python/branches/p3yk-noslice/Doc/lib/libdumbdbm.tex
   python/branches/p3yk-noslice/Doc/lib/libetree.tex
   python/branches/p3yk-noslice/Doc/lib/libexcs.tex
   python/branches/p3yk-noslice/Doc/lib/libfnmatch.tex
   python/branches/p3yk-noslice/Doc/lib/libftplib.tex
   python/branches/p3yk-noslice/Doc/lib/libfuncs.tex
   python/branches/p3yk-noslice/Doc/lib/libgettext.tex
   python/branches/p3yk-noslice/Doc/lib/libhmac.tex
   python/branches/p3yk-noslice/Doc/lib/libhotshot.tex
   python/branches/p3yk-noslice/Doc/lib/libhtmllib.tex
   python/branches/p3yk-noslice/Doc/lib/libhtmlparser.tex
   python/branches/p3yk-noslice/Doc/lib/libhttplib.tex
   python/branches/p3yk-noslice/Doc/lib/libimaplib.tex
   python/branches/p3yk-noslice/Doc/lib/libimp.tex
   python/branches/p3yk-noslice/Doc/lib/libinspect.tex
   python/branches/p3yk-noslice/Doc/lib/libitertools.tex
   python/branches/p3yk-noslice/Doc/lib/liblogging.tex
   python/branches/p3yk-noslice/Doc/lib/libmailbox.tex
   python/branches/p3yk-noslice/Doc/lib/libmimetools.tex
   python/branches/p3yk-noslice/Doc/lib/libmimetypes.tex
   python/branches/p3yk-noslice/Doc/lib/libmmap.tex
   python/branches/p3yk-noslice/Doc/lib/libmsilib.tex
   python/branches/p3yk-noslice/Doc/lib/libmultifile.tex
   python/branches/p3yk-noslice/Doc/lib/libmutex.tex
   python/branches/p3yk-noslice/Doc/lib/libnetrc.tex
   python/branches/p3yk-noslice/Doc/lib/libnntplib.tex
   python/branches/p3yk-noslice/Doc/lib/liboptparse.tex
   python/branches/p3yk-noslice/Doc/lib/libos.tex
   python/branches/p3yk-noslice/Doc/lib/libpdb.tex
   python/branches/p3yk-noslice/Doc/lib/libpickle.tex
   python/branches/p3yk-noslice/Doc/lib/libpipes.tex
   python/branches/p3yk-noslice/Doc/lib/libplatform.tex
   python/branches/p3yk-noslice/Doc/lib/libpoplib.tex
   python/branches/p3yk-noslice/Doc/lib/libposixpath.tex
   python/branches/p3yk-noslice/Doc/lib/libpprint.tex
   python/branches/p3yk-noslice/Doc/lib/libqueue.tex
   python/branches/p3yk-noslice/Doc/lib/librandom.tex
   python/branches/p3yk-noslice/Doc/lib/libre.tex
   python/branches/p3yk-noslice/Doc/lib/librepr.tex
   python/branches/p3yk-noslice/Doc/lib/librfc822.tex
   python/branches/p3yk-noslice/Doc/lib/libsched.tex
   python/branches/p3yk-noslice/Doc/lib/libselect.tex
   python/branches/p3yk-noslice/Doc/lib/libshlex.tex
   python/branches/p3yk-noslice/Doc/lib/libshutil.tex
   python/branches/p3yk-noslice/Doc/lib/libsignal.tex
   python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex
   python/branches/p3yk-noslice/Doc/lib/libsite.tex
   python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex
   python/branches/p3yk-noslice/Doc/lib/libsocket.tex
   python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex
   python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex
   python/branches/p3yk-noslice/Doc/lib/libstring.tex
   python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex
   python/branches/p3yk-noslice/Doc/lib/libsun.tex
   python/branches/p3yk-noslice/Doc/lib/libsys.tex
   python/branches/p3yk-noslice/Doc/lib/libtarfile.tex
   python/branches/p3yk-noslice/Doc/lib/libtelnetlib.tex
   python/branches/p3yk-noslice/Doc/lib/libtempfile.tex
   python/branches/p3yk-noslice/Doc/lib/libtest.tex
   python/branches/p3yk-noslice/Doc/lib/libtextwrap.tex
   python/branches/p3yk-noslice/Doc/lib/libthreading.tex
   python/branches/p3yk-noslice/Doc/lib/libtimeit.tex
   python/branches/p3yk-noslice/Doc/lib/libturtle.tex
   python/branches/p3yk-noslice/Doc/lib/libtypes.tex
   python/branches/p3yk-noslice/Doc/lib/libundoc.tex
   python/branches/p3yk-noslice/Doc/lib/libunittest.tex
   python/branches/p3yk-noslice/Doc/lib/liburllib.tex
   python/branches/p3yk-noslice/Doc/lib/liburllib2.tex
   python/branches/p3yk-noslice/Doc/lib/liburlparse.tex
   python/branches/p3yk-noslice/Doc/lib/libwebbrowser.tex
   python/branches/p3yk-noslice/Doc/lib/libwinreg.tex
   python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex
   python/branches/p3yk-noslice/Doc/lib/libzipfile.tex
   python/branches/p3yk-noslice/Doc/lib/libzipimport.tex
   python/branches/p3yk-noslice/Doc/lib/libzlib.tex
   python/branches/p3yk-noslice/Doc/lib/sqlite3/executemany_1.py
   python/branches/p3yk-noslice/Doc/mac/libframework.tex
   python/branches/p3yk-noslice/Doc/mac/libmacic.tex
   python/branches/p3yk-noslice/Doc/mac/libmacostools.tex
   python/branches/p3yk-noslice/Doc/mac/mac.tex
   python/branches/p3yk-noslice/Doc/mac/undoc.tex
   python/branches/p3yk-noslice/Doc/mac/using.tex
   python/branches/p3yk-noslice/Doc/ref/ref1.tex
   python/branches/p3yk-noslice/Doc/ref/ref2.tex
   python/branches/p3yk-noslice/Doc/ref/ref3.tex
   python/branches/p3yk-noslice/Doc/ref/ref5.tex
   python/branches/p3yk-noslice/Doc/ref/ref6.tex
   python/branches/p3yk-noslice/Doc/ref/ref7.tex
   python/branches/p3yk-noslice/Doc/texinputs/python.sty
   python/branches/p3yk-noslice/Doc/tools/buildindex.py
   python/branches/p3yk-noslice/Doc/tools/custlib.py
   python/branches/p3yk-noslice/Doc/tools/getversioninfo
   python/branches/p3yk-noslice/Doc/tools/keywords.py
   python/branches/p3yk-noslice/Doc/tools/listmodules
   python/branches/p3yk-noslice/Doc/tools/listmodules.py
   python/branches/p3yk-noslice/Doc/tools/mkackshtml
   python/branches/p3yk-noslice/Doc/tools/mkhowto
   python/branches/p3yk-noslice/Doc/tools/mkmodindex
   python/branches/p3yk-noslice/Doc/tools/prechm.py
   python/branches/p3yk-noslice/Doc/tools/refcounts.py
   python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py
   python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py
   python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py
   python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py
   python/branches/p3yk-noslice/Doc/tools/undoc_symbols.py
   python/branches/p3yk-noslice/Doc/tut/glossary.tex
   python/branches/p3yk-noslice/Doc/tut/tut.tex
   python/branches/p3yk-noslice/Doc/whatsnew/whatsnew23.tex
   python/branches/p3yk-noslice/Doc/whatsnew/whatsnew24.tex
   python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex
   python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex
   python/branches/p3yk-noslice/Grammar/Grammar
   python/branches/p3yk-noslice/Include/Python-ast.h
   python/branches/p3yk-noslice/Include/abstract.h
   python/branches/p3yk-noslice/Include/asdl.h
   python/branches/p3yk-noslice/Include/bytesobject.h
   python/branches/p3yk-noslice/Include/ceval.h
   python/branches/p3yk-noslice/Include/dictobject.h
   python/branches/p3yk-noslice/Include/fileobject.h
   python/branches/p3yk-noslice/Include/floatobject.h
   python/branches/p3yk-noslice/Include/frameobject.h
   python/branches/p3yk-noslice/Include/graminit.h
   python/branches/p3yk-noslice/Include/intobject.h
   python/branches/p3yk-noslice/Include/listobject.h
   python/branches/p3yk-noslice/Include/longobject.h
   python/branches/p3yk-noslice/Include/object.h
   python/branches/p3yk-noslice/Include/opcode.h
   python/branches/p3yk-noslice/Include/pydebug.h
   python/branches/p3yk-noslice/Include/pyerrors.h
   python/branches/p3yk-noslice/Include/pymem.h
   python/branches/p3yk-noslice/Include/pyport.h
   python/branches/p3yk-noslice/Include/pystate.h
   python/branches/p3yk-noslice/Include/pythonrun.h
   python/branches/p3yk-noslice/Include/setobject.h
   python/branches/p3yk-noslice/Include/stringobject.h
   python/branches/p3yk-noslice/Include/structmember.h
   python/branches/p3yk-noslice/Include/symtable.h
   python/branches/p3yk-noslice/Include/token.h
   python/branches/p3yk-noslice/Include/tupleobject.h
   python/branches/p3yk-noslice/Include/unicodeobject.h
   python/branches/p3yk-noslice/LICENSE
   python/branches/p3yk-noslice/Lib/CGIHTTPServer.py
   python/branches/p3yk-noslice/Lib/ConfigParser.py
   python/branches/p3yk-noslice/Lib/Cookie.py
   python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py
   python/branches/p3yk-noslice/Lib/HTMLParser.py
   python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py
   python/branches/p3yk-noslice/Lib/SocketServer.py
   python/branches/p3yk-noslice/Lib/StringIO.py
   python/branches/p3yk-noslice/Lib/UserDict.py
   python/branches/p3yk-noslice/Lib/_strptime.py
   python/branches/p3yk-noslice/Lib/aifc.py
   python/branches/p3yk-noslice/Lib/anydbm.py
   python/branches/p3yk-noslice/Lib/bdb.py
   python/branches/p3yk-noslice/Lib/binhex.py
   python/branches/p3yk-noslice/Lib/bisect.py
   python/branches/p3yk-noslice/Lib/bsddb/__init__.py
   python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py
   python/branches/p3yk-noslice/Lib/bsddb/dbshelve.py
   python/branches/p3yk-noslice/Lib/bsddb/dbtables.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_sequence.py
   python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py
   python/branches/p3yk-noslice/Lib/calendar.py
   python/branches/p3yk-noslice/Lib/cgi.py
   python/branches/p3yk-noslice/Lib/cgitb.py
   python/branches/p3yk-noslice/Lib/chunk.py
   python/branches/p3yk-noslice/Lib/cmd.py
   python/branches/p3yk-noslice/Lib/codecs.py
   python/branches/p3yk-noslice/Lib/commands.py
   python/branches/p3yk-noslice/Lib/contextlib.py
   python/branches/p3yk-noslice/Lib/copy.py
   python/branches/p3yk-noslice/Lib/copy_reg.py
   python/branches/p3yk-noslice/Lib/csv.py
   python/branches/p3yk-noslice/Lib/ctypes/__init__.py
   python/branches/p3yk-noslice/Lib/ctypes/_endian.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_arrays.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_checkretval.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_init.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_memfunctions.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_python_api.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_random_things.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_repr.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_slicing.py
   python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py
   python/branches/p3yk-noslice/Lib/ctypes/wintypes.py
   python/branches/p3yk-noslice/Lib/dbhash.py
   python/branches/p3yk-noslice/Lib/decimal.py
   python/branches/p3yk-noslice/Lib/difflib.py
   python/branches/p3yk-noslice/Lib/dis.py
   python/branches/p3yk-noslice/Lib/distutils/__init__.py
   python/branches/p3yk-noslice/Lib/distutils/ccompiler.py
   python/branches/p3yk-noslice/Lib/distutils/cmd.py
   python/branches/p3yk-noslice/Lib/distutils/command/bdist.py
   python/branches/p3yk-noslice/Lib/distutils/command/bdist_msi.py
   python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py
   python/branches/p3yk-noslice/Lib/distutils/command/bdist_wininst.py
   python/branches/p3yk-noslice/Lib/distutils/command/build_clib.py
   python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py
   python/branches/p3yk-noslice/Lib/distutils/command/build_py.py
   python/branches/p3yk-noslice/Lib/distutils/command/build_scripts.py
   python/branches/p3yk-noslice/Lib/distutils/command/config.py
   python/branches/p3yk-noslice/Lib/distutils/command/install.py
   python/branches/p3yk-noslice/Lib/distutils/command/install_lib.py
   python/branches/p3yk-noslice/Lib/distutils/command/install_scripts.py
   python/branches/p3yk-noslice/Lib/distutils/command/register.py
   python/branches/p3yk-noslice/Lib/distutils/command/sdist.py
   python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py
   python/branches/p3yk-noslice/Lib/distutils/dir_util.py
   python/branches/p3yk-noslice/Lib/distutils/dist.py
   python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py
   python/branches/p3yk-noslice/Lib/distutils/extension.py
   python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py
   python/branches/p3yk-noslice/Lib/distutils/filelist.py
   python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py
   python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py
   python/branches/p3yk-noslice/Lib/distutils/spawn.py
   python/branches/p3yk-noslice/Lib/distutils/sysconfig.py
   python/branches/p3yk-noslice/Lib/distutils/tests/support.py
   python/branches/p3yk-noslice/Lib/distutils/tests/test_build_py.py
   python/branches/p3yk-noslice/Lib/distutils/text_file.py
   python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py
   python/branches/p3yk-noslice/Lib/distutils/util.py
   python/branches/p3yk-noslice/Lib/distutils/version.py
   python/branches/p3yk-noslice/Lib/doctest.py
   python/branches/p3yk-noslice/Lib/dumbdbm.py
   python/branches/p3yk-noslice/Lib/email/_parseaddr.py
   python/branches/p3yk-noslice/Lib/email/feedparser.py
   python/branches/p3yk-noslice/Lib/email/header.py
   python/branches/p3yk-noslice/Lib/email/message.py
   python/branches/p3yk-noslice/Lib/email/test/test_email.py
   python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py
   python/branches/p3yk-noslice/Lib/encodings/__init__.py
   python/branches/p3yk-noslice/Lib/encodings/idna.py
   python/branches/p3yk-noslice/Lib/encodings/utf_16.py
   python/branches/p3yk-noslice/Lib/encodings/utf_8_sig.py
   python/branches/p3yk-noslice/Lib/encodings/uu_codec.py
   python/branches/p3yk-noslice/Lib/filecmp.py
   python/branches/p3yk-noslice/Lib/fileinput.py
   python/branches/p3yk-noslice/Lib/formatter.py
   python/branches/p3yk-noslice/Lib/ftplib.py
   python/branches/p3yk-noslice/Lib/genericpath.py
   python/branches/p3yk-noslice/Lib/gettext.py
   python/branches/p3yk-noslice/Lib/glob.py
   python/branches/p3yk-noslice/Lib/gzip.py
   python/branches/p3yk-noslice/Lib/heapq.py
   python/branches/p3yk-noslice/Lib/hmac.py
   python/branches/p3yk-noslice/Lib/hotshot/log.py
   python/branches/p3yk-noslice/Lib/httplib.py
   python/branches/p3yk-noslice/Lib/idlelib/CallTips.py
   python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py
   python/branches/p3yk-noslice/Lib/idlelib/Debugger.py
   python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py
   python/branches/p3yk-noslice/Lib/idlelib/ObjectBrowser.py
   python/branches/p3yk-noslice/Lib/idlelib/PyShell.py
   python/branches/p3yk-noslice/Lib/idlelib/StackViewer.py
   python/branches/p3yk-noslice/Lib/idlelib/aboutDialog.py
   python/branches/p3yk-noslice/Lib/idlelib/configDialog.py
   python/branches/p3yk-noslice/Lib/idlelib/configHandler.py
   python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py
   python/branches/p3yk-noslice/Lib/idlelib/rpc.py
   python/branches/p3yk-noslice/Lib/ihooks.py
   python/branches/p3yk-noslice/Lib/imaplib.py
   python/branches/p3yk-noslice/Lib/imputil.py
   python/branches/p3yk-noslice/Lib/inspect.py
   python/branches/p3yk-noslice/Lib/keyword.py
   python/branches/p3yk-noslice/Lib/lib-tk/ScrolledText.py
   python/branches/p3yk-noslice/Lib/lib-tk/Tix.py
   python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py
   python/branches/p3yk-noslice/Lib/linecache.py
   python/branches/p3yk-noslice/Lib/locale.py
   python/branches/p3yk-noslice/Lib/logging/__init__.py
   python/branches/p3yk-noslice/Lib/logging/config.py
   python/branches/p3yk-noslice/Lib/logging/handlers.py
   python/branches/p3yk-noslice/Lib/macpath.py
   python/branches/p3yk-noslice/Lib/mailbox.py
   python/branches/p3yk-noslice/Lib/mhlib.py
   python/branches/p3yk-noslice/Lib/mimetypes.py
   python/branches/p3yk-noslice/Lib/modulefinder.py
   python/branches/p3yk-noslice/Lib/new.py
   python/branches/p3yk-noslice/Lib/ntpath.py
   python/branches/p3yk-noslice/Lib/opcode.py
   python/branches/p3yk-noslice/Lib/optparse.py
   python/branches/p3yk-noslice/Lib/os.py
   python/branches/p3yk-noslice/Lib/pdb.doc
   python/branches/p3yk-noslice/Lib/pdb.py
   python/branches/p3yk-noslice/Lib/pickle.py
   python/branches/p3yk-noslice/Lib/pickletools.py
   python/branches/p3yk-noslice/Lib/plat-atheos/IN.py
   python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py
   python/branches/p3yk-noslice/Lib/plat-mac/aepack.py
   python/branches/p3yk-noslice/Lib/plat-mac/aetypes.py
   python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py
   python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py
   python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py
   python/branches/p3yk-noslice/Lib/plat-mac/findertools.py
   python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py
   python/branches/p3yk-noslice/Lib/plat-mac/ic.py
   python/branches/p3yk-noslice/Lib/plat-mac/macostools.py
   python/branches/p3yk-noslice/Lib/plat-mac/pimp.py
   python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py
   python/branches/p3yk-noslice/Lib/plat-riscos/riscospath.py
   python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py
   python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py
   python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py
   python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py
   python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py
   python/branches/p3yk-noslice/Lib/platform.py
   python/branches/p3yk-noslice/Lib/poplib.py
   python/branches/p3yk-noslice/Lib/posixpath.py
   python/branches/p3yk-noslice/Lib/pprint.py
   python/branches/p3yk-noslice/Lib/pstats.py
   python/branches/p3yk-noslice/Lib/pty.py
   python/branches/p3yk-noslice/Lib/pyclbr.py
   python/branches/p3yk-noslice/Lib/pydoc.py
   python/branches/p3yk-noslice/Lib/random.py
   python/branches/p3yk-noslice/Lib/re.py
   python/branches/p3yk-noslice/Lib/repr.py
   python/branches/p3yk-noslice/Lib/robotparser.py
   python/branches/p3yk-noslice/Lib/sched.py
   python/branches/p3yk-noslice/Lib/shelve.py
   python/branches/p3yk-noslice/Lib/shlex.py
   python/branches/p3yk-noslice/Lib/site.py
   python/branches/p3yk-noslice/Lib/smtplib.py
   python/branches/p3yk-noslice/Lib/socket.py
   python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py
   python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py
   python/branches/p3yk-noslice/Lib/sre.py
   python/branches/p3yk-noslice/Lib/sre_compile.py
   python/branches/p3yk-noslice/Lib/sre_parse.py
   python/branches/p3yk-noslice/Lib/stat.py
   python/branches/p3yk-noslice/Lib/string.py
   python/branches/p3yk-noslice/Lib/stringprep.py
   python/branches/p3yk-noslice/Lib/subprocess.py
   python/branches/p3yk-noslice/Lib/sunau.py
   python/branches/p3yk-noslice/Lib/symbol.py
   python/branches/p3yk-noslice/Lib/tarfile.py
   python/branches/p3yk-noslice/Lib/telnetlib.py
   python/branches/p3yk-noslice/Lib/tempfile.py
   python/branches/p3yk-noslice/Lib/test/README
   python/branches/p3yk-noslice/Lib/test/bad_coding2.py
   python/branches/p3yk-noslice/Lib/test/exception_hierarchy.txt
   python/branches/p3yk-noslice/Lib/test/fork_wait.py
   python/branches/p3yk-noslice/Lib/test/inspect_fodder.py
   python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py
   python/branches/p3yk-noslice/Lib/test/leakers/test_selftype.py
   python/branches/p3yk-noslice/Lib/test/list_tests.py
   python/branches/p3yk-noslice/Lib/test/mapping_tests.py
   python/branches/p3yk-noslice/Lib/test/output/test_cProfile
   python/branches/p3yk-noslice/Lib/test/output/test_class
   python/branches/p3yk-noslice/Lib/test/output/test_extcall
   python/branches/p3yk-noslice/Lib/test/output/test_logging
   python/branches/p3yk-noslice/Lib/test/output/test_pkg
   python/branches/p3yk-noslice/Lib/test/output/test_profile
   python/branches/p3yk-noslice/Lib/test/output/test_tokenize
   python/branches/p3yk-noslice/Lib/test/outstanding_bugs.py
   python/branches/p3yk-noslice/Lib/test/pickletester.py
   python/branches/p3yk-noslice/Lib/test/regrtest.py
   python/branches/p3yk-noslice/Lib/test/seq_tests.py
   python/branches/p3yk-noslice/Lib/test/sortperf.py
   python/branches/p3yk-noslice/Lib/test/string_tests.py
   python/branches/p3yk-noslice/Lib/test/test_StringIO.py
   python/branches/p3yk-noslice/Lib/test/test___all__.py
   python/branches/p3yk-noslice/Lib/test/test_anydbm.py
   python/branches/p3yk-noslice/Lib/test/test_array.py
   python/branches/p3yk-noslice/Lib/test/test_ast.py
   python/branches/p3yk-noslice/Lib/test/test_atexit.py
   python/branches/p3yk-noslice/Lib/test/test_base64.py
   python/branches/p3yk-noslice/Lib/test/test_binascii.py
   python/branches/p3yk-noslice/Lib/test/test_bisect.py
   python/branches/p3yk-noslice/Lib/test/test_bool.py
   python/branches/p3yk-noslice/Lib/test/test_bsddb.py
   python/branches/p3yk-noslice/Lib/test/test_bsddb3.py
   python/branches/p3yk-noslice/Lib/test/test_bufio.py
   python/branches/p3yk-noslice/Lib/test/test_builtin.py
   python/branches/p3yk-noslice/Lib/test/test_bytes.py
   python/branches/p3yk-noslice/Lib/test/test_bz2.py
   python/branches/p3yk-noslice/Lib/test/test_calendar.py
   python/branches/p3yk-noslice/Lib/test/test_cfgparser.py
   python/branches/p3yk-noslice/Lib/test/test_cgi.py
   python/branches/p3yk-noslice/Lib/test/test_class.py
   python/branches/p3yk-noslice/Lib/test/test_cmath.py
   python/branches/p3yk-noslice/Lib/test/test_cmd_line.py
   python/branches/p3yk-noslice/Lib/test/test_code.py
   python/branches/p3yk-noslice/Lib/test/test_codeccallbacks.py
   python/branches/p3yk-noslice/Lib/test/test_codecencodings_cn.py
   python/branches/p3yk-noslice/Lib/test/test_codecencodings_hk.py
   python/branches/p3yk-noslice/Lib/test/test_codecencodings_jp.py
   python/branches/p3yk-noslice/Lib/test/test_codecencodings_kr.py
   python/branches/p3yk-noslice/Lib/test/test_codecencodings_tw.py
   python/branches/p3yk-noslice/Lib/test/test_codecmaps_cn.py
   python/branches/p3yk-noslice/Lib/test/test_codecmaps_hk.py
   python/branches/p3yk-noslice/Lib/test/test_codecmaps_jp.py
   python/branches/p3yk-noslice/Lib/test/test_codecmaps_kr.py
   python/branches/p3yk-noslice/Lib/test/test_codecmaps_tw.py
   python/branches/p3yk-noslice/Lib/test/test_codecs.py
   python/branches/p3yk-noslice/Lib/test/test_codeop.py
   python/branches/p3yk-noslice/Lib/test/test_commands.py
   python/branches/p3yk-noslice/Lib/test/test_compare.py
   python/branches/p3yk-noslice/Lib/test/test_compile.py
   python/branches/p3yk-noslice/Lib/test/test_complex.py
   python/branches/p3yk-noslice/Lib/test/test_contains.py
   python/branches/p3yk-noslice/Lib/test/test_contextlib.py
   python/branches/p3yk-noslice/Lib/test/test_copy.py
   python/branches/p3yk-noslice/Lib/test/test_crypt.py
   python/branches/p3yk-noslice/Lib/test/test_csv.py
   python/branches/p3yk-noslice/Lib/test/test_ctypes.py
   python/branches/p3yk-noslice/Lib/test/test_curses.py
   python/branches/p3yk-noslice/Lib/test/test_datetime.py
   python/branches/p3yk-noslice/Lib/test/test_dbm.py
   python/branches/p3yk-noslice/Lib/test/test_decimal.py
   python/branches/p3yk-noslice/Lib/test/test_decorators.py
   python/branches/p3yk-noslice/Lib/test/test_defaultdict.py
   python/branches/p3yk-noslice/Lib/test/test_deque.py
   python/branches/p3yk-noslice/Lib/test/test_descr.py
   python/branches/p3yk-noslice/Lib/test/test_descrtut.py
   python/branches/p3yk-noslice/Lib/test/test_dict.py
   python/branches/p3yk-noslice/Lib/test/test_difflib.py
   python/branches/p3yk-noslice/Lib/test/test_dis.py
   python/branches/p3yk-noslice/Lib/test/test_doctest.py
   python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py
   python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py
   python/branches/p3yk-noslice/Lib/test/test_email.py
   python/branches/p3yk-noslice/Lib/test/test_email_codecs.py
   python/branches/p3yk-noslice/Lib/test/test_email_renamed.py
   python/branches/p3yk-noslice/Lib/test/test_enumerate.py
   python/branches/p3yk-noslice/Lib/test/test_exceptions.py
   python/branches/p3yk-noslice/Lib/test/test_extcall.py
   python/branches/p3yk-noslice/Lib/test/test_file.py
   python/branches/p3yk-noslice/Lib/test/test_fileinput.py
   python/branches/p3yk-noslice/Lib/test/test_format.py
   python/branches/p3yk-noslice/Lib/test/test_funcattrs.py
   python/branches/p3yk-noslice/Lib/test/test_functools.py
   python/branches/p3yk-noslice/Lib/test/test_future2.py
   python/branches/p3yk-noslice/Lib/test/test_gc.py
   python/branches/p3yk-noslice/Lib/test/test_generators.py
   python/branches/p3yk-noslice/Lib/test/test_genexps.py
   python/branches/p3yk-noslice/Lib/test/test_getopt.py
   python/branches/p3yk-noslice/Lib/test/test_gettext.py
   python/branches/p3yk-noslice/Lib/test/test_glob.py
   python/branches/p3yk-noslice/Lib/test/test_grammar.py
   python/branches/p3yk-noslice/Lib/test/test_grp.py
   python/branches/p3yk-noslice/Lib/test/test_hash.py
   python/branches/p3yk-noslice/Lib/test/test_heapq.py
   python/branches/p3yk-noslice/Lib/test/test_hexoct.py
   python/branches/p3yk-noslice/Lib/test/test_hmac.py
   python/branches/p3yk-noslice/Lib/test/test_hotshot.py
   python/branches/p3yk-noslice/Lib/test/test_htmlparser.py
   python/branches/p3yk-noslice/Lib/test/test_httplib.py
   python/branches/p3yk-noslice/Lib/test/test_import.py
   python/branches/p3yk-noslice/Lib/test/test_importhooks.py
   python/branches/p3yk-noslice/Lib/test/test_index.py
   python/branches/p3yk-noslice/Lib/test/test_inspect.py
   python/branches/p3yk-noslice/Lib/test/test_isinstance.py
   python/branches/p3yk-noslice/Lib/test/test_iter.py
   python/branches/p3yk-noslice/Lib/test/test_iterlen.py
   python/branches/p3yk-noslice/Lib/test/test_itertools.py
   python/branches/p3yk-noslice/Lib/test/test_keywordonlyarg.py
   python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py
   python/branches/p3yk-noslice/Lib/test/test_list.py
   python/branches/p3yk-noslice/Lib/test/test_locale.py
   python/branches/p3yk-noslice/Lib/test/test_logging.py
   python/branches/p3yk-noslice/Lib/test/test_long.py
   python/branches/p3yk-noslice/Lib/test/test_long_future.py
   python/branches/p3yk-noslice/Lib/test/test_macostools.py
   python/branches/p3yk-noslice/Lib/test/test_macpath.py
   python/branches/p3yk-noslice/Lib/test/test_mailbox.py
   python/branches/p3yk-noslice/Lib/test/test_marshal.py
   python/branches/p3yk-noslice/Lib/test/test_math.py
   python/branches/p3yk-noslice/Lib/test/test_mhlib.py
   python/branches/p3yk-noslice/Lib/test/test_mimetools.py
   python/branches/p3yk-noslice/Lib/test/test_minidom.py
   python/branches/p3yk-noslice/Lib/test/test_mmap.py
   python/branches/p3yk-noslice/Lib/test/test_module.py
   python/branches/p3yk-noslice/Lib/test/test_modulefinder.py
   python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py
   python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py
   python/branches/p3yk-noslice/Lib/test/test_mutants.py
   python/branches/p3yk-noslice/Lib/test/test_new.py
   python/branches/p3yk-noslice/Lib/test/test_normalization.py
   python/branches/p3yk-noslice/Lib/test/test_ntpath.py
   python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py
   python/branches/p3yk-noslice/Lib/test/test_operator.py
   python/branches/p3yk-noslice/Lib/test/test_optparse.py
   python/branches/p3yk-noslice/Lib/test/test_os.py
   python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py
   python/branches/p3yk-noslice/Lib/test/test_peepholer.py
   python/branches/p3yk-noslice/Lib/test/test_pep247.py
   python/branches/p3yk-noslice/Lib/test/test_pep352.py
   python/branches/p3yk-noslice/Lib/test/test_pkg.py
   python/branches/p3yk-noslice/Lib/test/test_posixpath.py
   python/branches/p3yk-noslice/Lib/test/test_pow.py
   python/branches/p3yk-noslice/Lib/test/test_pprint.py
   python/branches/p3yk-noslice/Lib/test/test_profilehooks.py
   python/branches/p3yk-noslice/Lib/test/test_pty.py
   python/branches/p3yk-noslice/Lib/test/test_pwd.py
   python/branches/p3yk-noslice/Lib/test/test_pyclbr.py
   python/branches/p3yk-noslice/Lib/test/test_pyexpat.py
   python/branches/p3yk-noslice/Lib/test/test_queue.py
   python/branches/p3yk-noslice/Lib/test/test_random.py
   python/branches/p3yk-noslice/Lib/test/test_re.py
   python/branches/p3yk-noslice/Lib/test/test_repr.py
   python/branches/p3yk-noslice/Lib/test/test_richcmp.py
   python/branches/p3yk-noslice/Lib/test/test_robotparser.py
   python/branches/p3yk-noslice/Lib/test/test_sax.py
   python/branches/p3yk-noslice/Lib/test/test_scope.py
   python/branches/p3yk-noslice/Lib/test/test_set.py
   python/branches/p3yk-noslice/Lib/test/test_slice.py
   python/branches/p3yk-noslice/Lib/test/test_socket.py
   python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py
   python/branches/p3yk-noslice/Lib/test/test_socketserver.py
   python/branches/p3yk-noslice/Lib/test/test_sort.py
   python/branches/p3yk-noslice/Lib/test/test_str.py
   python/branches/p3yk-noslice/Lib/test/test_string.py
   python/branches/p3yk-noslice/Lib/test/test_stringprep.py
   python/branches/p3yk-noslice/Lib/test/test_strptime.py
   python/branches/p3yk-noslice/Lib/test/test_struct.py
   python/branches/p3yk-noslice/Lib/test/test_structmembers.py
   python/branches/p3yk-noslice/Lib/test/test_structseq.py
   python/branches/p3yk-noslice/Lib/test/test_subprocess.py
   python/branches/p3yk-noslice/Lib/test/test_sundry.py
   python/branches/p3yk-noslice/Lib/test/test_support.py
   python/branches/p3yk-noslice/Lib/test/test_syntax.py
   python/branches/p3yk-noslice/Lib/test/test_sys.py
   python/branches/p3yk-noslice/Lib/test/test_tarfile.py
   python/branches/p3yk-noslice/Lib/test/test_tempfile.py
   python/branches/p3yk-noslice/Lib/test/test_textwrap.py
   python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py
   python/branches/p3yk-noslice/Lib/test/test_threading.py
   python/branches/p3yk-noslice/Lib/test/test_threading_local.py
   python/branches/p3yk-noslice/Lib/test/test_threadsignals.py
   python/branches/p3yk-noslice/Lib/test/test_tokenize.py
   python/branches/p3yk-noslice/Lib/test/test_trace.py
   python/branches/p3yk-noslice/Lib/test/test_traceback.py
   python/branches/p3yk-noslice/Lib/test/test_tuple.py
   python/branches/p3yk-noslice/Lib/test/test_ucn.py
   python/branches/p3yk-noslice/Lib/test/test_unicode.py
   python/branches/p3yk-noslice/Lib/test/test_unicode_file.py
   python/branches/p3yk-noslice/Lib/test/test_unicodedata.py
   python/branches/p3yk-noslice/Lib/test/test_unittest.py
   python/branches/p3yk-noslice/Lib/test/test_univnewlines.py
   python/branches/p3yk-noslice/Lib/test/test_unpack.py
   python/branches/p3yk-noslice/Lib/test/test_urllib.py
   python/branches/p3yk-noslice/Lib/test/test_urllib2.py
   python/branches/p3yk-noslice/Lib/test/test_urllib2net.py
   python/branches/p3yk-noslice/Lib/test/test_userdict.py
   python/branches/p3yk-noslice/Lib/test/test_userlist.py
   python/branches/p3yk-noslice/Lib/test/test_uu.py
   python/branches/p3yk-noslice/Lib/test/test_warnings.py
   python/branches/p3yk-noslice/Lib/test/test_weakref.py
   python/branches/p3yk-noslice/Lib/test/test_winsound.py
   python/branches/p3yk-noslice/Lib/test/test_wsgiref.py
   python/branches/p3yk-noslice/Lib/test/test_xdrlib.py
   python/branches/p3yk-noslice/Lib/test/test_xml_etree.py
   python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py
   python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py
   python/branches/p3yk-noslice/Lib/test/test_xrange.py
   python/branches/p3yk-noslice/Lib/test/test_zipfile.py
   python/branches/p3yk-noslice/Lib/test/test_zipfile64.py
   python/branches/p3yk-noslice/Lib/test/test_zipimport.py
   python/branches/p3yk-noslice/Lib/test/test_zlib.py
   python/branches/p3yk-noslice/Lib/test/testtar.tar
   python/branches/p3yk-noslice/Lib/test/tf_inherit_check.py
   python/branches/p3yk-noslice/Lib/test/time_hashlib.py
   python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt
   python/branches/p3yk-noslice/Lib/test/xmltests.py
   python/branches/p3yk-noslice/Lib/textwrap.py
   python/branches/p3yk-noslice/Lib/threading.py
   python/branches/p3yk-noslice/Lib/timeit.py
   python/branches/p3yk-noslice/Lib/token.py
   python/branches/p3yk-noslice/Lib/tokenize.py
   python/branches/p3yk-noslice/Lib/trace.py
   python/branches/p3yk-noslice/Lib/traceback.py
   python/branches/p3yk-noslice/Lib/types.py
   python/branches/p3yk-noslice/Lib/unittest.py
   python/branches/p3yk-noslice/Lib/urllib.py
   python/branches/p3yk-noslice/Lib/urllib2.py
   python/branches/p3yk-noslice/Lib/urlparse.py
   python/branches/p3yk-noslice/Lib/uu.py
   python/branches/p3yk-noslice/Lib/uuid.py
   python/branches/p3yk-noslice/Lib/warnings.py
   python/branches/p3yk-noslice/Lib/wave.py
   python/branches/p3yk-noslice/Lib/weakref.py
   python/branches/p3yk-noslice/Lib/webbrowser.py
   python/branches/p3yk-noslice/Lib/wsgiref/handlers.py
   python/branches/p3yk-noslice/Lib/wsgiref/headers.py
   python/branches/p3yk-noslice/Lib/wsgiref/util.py
   python/branches/p3yk-noslice/Lib/wsgiref/validate.py
   python/branches/p3yk-noslice/Lib/xml/dom/domreg.py
   python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py
   python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py
   python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py
   python/branches/p3yk-noslice/Lib/xmlrpclib.py
   python/branches/p3yk-noslice/Lib/zipfile.py
   python/branches/p3yk-noslice/Makefile.pre.in
   python/branches/p3yk-noslice/Misc/ACKS
   python/branches/p3yk-noslice/Misc/BeOS-NOTES
   python/branches/p3yk-noslice/Misc/BeOS-setup.py
   python/branches/p3yk-noslice/Misc/NEWS
   python/branches/p3yk-noslice/Misc/Vim/python.vim
   python/branches/p3yk-noslice/Misc/Vim/vim_syntax.py
   python/branches/p3yk-noslice/Misc/build.sh
   python/branches/p3yk-noslice/Misc/cheatsheet
   python/branches/p3yk-noslice/Misc/developers.txt
   python/branches/p3yk-noslice/Misc/python-config.in
   python/branches/p3yk-noslice/Misc/python-mode.el
   python/branches/p3yk-noslice/Misc/valgrind-python.supp
   python/branches/p3yk-noslice/Modules/Setup.dist
   python/branches/p3yk-noslice/Modules/_bsddb.c
   python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c
   python/branches/p3yk-noslice/Modules/_ctypes/callbacks.c
   python/branches/p3yk-noslice/Modules/_ctypes/callproc.c
   python/branches/p3yk-noslice/Modules/_ctypes/cfield.c
   python/branches/p3yk-noslice/Modules/_ctypes/ctypes.h
   python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure
   python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure.ac
   python/branches/p3yk-noslice/Modules/_ctypes/libffi/fficonfig.h.in
   python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi.c
   python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi64.c
   python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffitarget.h
   python/branches/p3yk-noslice/Modules/_ctypes/stgdict.c
   python/branches/p3yk-noslice/Modules/_cursesmodule.c
   python/branches/p3yk-noslice/Modules/_localemodule.c
   python/branches/p3yk-noslice/Modules/_sqlite/cache.c
   python/branches/p3yk-noslice/Modules/_sqlite/module.c
   python/branches/p3yk-noslice/Modules/_struct.c
   python/branches/p3yk-noslice/Modules/_testcapimodule.c
   python/branches/p3yk-noslice/Modules/_tkinter.c
   python/branches/p3yk-noslice/Modules/arraymodule.c
   python/branches/p3yk-noslice/Modules/binascii.c
   python/branches/p3yk-noslice/Modules/bz2module.c
   python/branches/p3yk-noslice/Modules/cPickle.c
   python/branches/p3yk-noslice/Modules/cStringIO.c
   python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c
   python/branches/p3yk-noslice/Modules/config.c.in
   python/branches/p3yk-noslice/Modules/datetimemodule.c
   python/branches/p3yk-noslice/Modules/getaddrinfo.c
   python/branches/p3yk-noslice/Modules/getbuildinfo.c
   python/branches/p3yk-noslice/Modules/getnameinfo.c
   python/branches/p3yk-noslice/Modules/getpath.c
   python/branches/p3yk-noslice/Modules/itertoolsmodule.c
   python/branches/p3yk-noslice/Modules/main.c
   python/branches/p3yk-noslice/Modules/operator.c
   python/branches/p3yk-noslice/Modules/parsermodule.c
   python/branches/p3yk-noslice/Modules/posixmodule.c
   python/branches/p3yk-noslice/Modules/readline.c
   python/branches/p3yk-noslice/Modules/socketmodule.c
   python/branches/p3yk-noslice/Modules/symtablemodule.c
   python/branches/p3yk-noslice/Modules/timemodule.c
   python/branches/p3yk-noslice/Objects/abstract.c
   python/branches/p3yk-noslice/Objects/bufferobject.c
   python/branches/p3yk-noslice/Objects/bytesobject.c
   python/branches/p3yk-noslice/Objects/complexobject.c
   python/branches/p3yk-noslice/Objects/dictobject.c
   python/branches/p3yk-noslice/Objects/exceptions.c
   python/branches/p3yk-noslice/Objects/fileobject.c
   python/branches/p3yk-noslice/Objects/floatobject.c
   python/branches/p3yk-noslice/Objects/frameobject.c
   python/branches/p3yk-noslice/Objects/funcobject.c
   python/branches/p3yk-noslice/Objects/intobject.c
   python/branches/p3yk-noslice/Objects/listobject.c
   python/branches/p3yk-noslice/Objects/longobject.c
   python/branches/p3yk-noslice/Objects/methodobject.c
   python/branches/p3yk-noslice/Objects/object.c
   python/branches/p3yk-noslice/Objects/rangeobject.c
   python/branches/p3yk-noslice/Objects/setobject.c
   python/branches/p3yk-noslice/Objects/sliceobject.c
   python/branches/p3yk-noslice/Objects/stringobject.c
   python/branches/p3yk-noslice/Objects/tupleobject.c
   python/branches/p3yk-noslice/Objects/typeobject.c
   python/branches/p3yk-noslice/Objects/unicodeobject.c
   python/branches/p3yk-noslice/PC/VC6/pcbuild.dsw
   python/branches/p3yk-noslice/PC/VC6/pythoncore.dsp
   python/branches/p3yk-noslice/PC/WinMain.c
   python/branches/p3yk-noslice/PC/_winreg.c
   python/branches/p3yk-noslice/PC/config.c
   python/branches/p3yk-noslice/PC/dl_nt.c
   python/branches/p3yk-noslice/PC/getpathp.c
   python/branches/p3yk-noslice/PC/make_versioninfo.c
   python/branches/p3yk-noslice/PC/os2emx/Makefile
   python/branches/p3yk-noslice/PC/os2emx/config.c
   python/branches/p3yk-noslice/PC/os2emx/python25.def
   python/branches/p3yk-noslice/PC/os2vacpp/config.c
   python/branches/p3yk-noslice/PC/os2vacpp/makefile
   python/branches/p3yk-noslice/PC/os2vacpp/makefile.omk
   python/branches/p3yk-noslice/PC/os2vacpp/python.def
   python/branches/p3yk-noslice/PC/pyconfig.h
   python/branches/p3yk-noslice/PC/winsound.c
   python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj
   python/branches/p3yk-noslice/PCbuild/_ssl.mak
   python/branches/p3yk-noslice/PCbuild/build_ssl.bat
   python/branches/p3yk-noslice/PCbuild/build_ssl.py
   python/branches/p3yk-noslice/PCbuild/pcbuild.sln
   python/branches/p3yk-noslice/PCbuild/python.iss
   python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj
   python/branches/p3yk-noslice/PCbuild8/pcbuild.sln
   python/branches/p3yk-noslice/PCbuild8/readme.txt
   python/branches/p3yk-noslice/PCbuild8/rmpyc.py
   python/branches/p3yk-noslice/PCbuild8/rt.bat
   python/branches/p3yk-noslice/Parser/Python.asdl
   python/branches/p3yk-noslice/Parser/asdl.py
   python/branches/p3yk-noslice/Parser/asdl_c.py
   python/branches/p3yk-noslice/Parser/spark.py
   python/branches/p3yk-noslice/Parser/tokenizer.c
   python/branches/p3yk-noslice/Python/Python-ast.c
   python/branches/p3yk-noslice/Python/ast.c
   python/branches/p3yk-noslice/Python/bltinmodule.c
   python/branches/p3yk-noslice/Python/ceval.c
   python/branches/p3yk-noslice/Python/compile.c
   python/branches/p3yk-noslice/Python/dynload_win.c
   python/branches/p3yk-noslice/Python/errors.c
   python/branches/p3yk-noslice/Python/graminit.c
   python/branches/p3yk-noslice/Python/import.c
   python/branches/p3yk-noslice/Python/marshal.c
   python/branches/p3yk-noslice/Python/mystrtoul.c
   python/branches/p3yk-noslice/Python/peephole.c
   python/branches/p3yk-noslice/Python/pystate.c
   python/branches/p3yk-noslice/Python/pythonrun.c
   python/branches/p3yk-noslice/Python/structmember.c
   python/branches/p3yk-noslice/Python/symtable.c
   python/branches/p3yk-noslice/Python/sysmodule.c
   python/branches/p3yk-noslice/Python/thread_nt.h
   python/branches/p3yk-noslice/README
   python/branches/p3yk-noslice/RISCOS/Makefile
   python/branches/p3yk-noslice/RISCOS/Modules/config.c
   python/branches/p3yk-noslice/Tools/i18n/msgfmt.py
   python/branches/p3yk-noslice/Tools/msi/msilib.py
   python/branches/p3yk-noslice/Tools/pybench/Arithmetic.py
   python/branches/p3yk-noslice/Tools/pybench/Calls.py
   python/branches/p3yk-noslice/Tools/pybench/CommandLine.py
   python/branches/p3yk-noslice/Tools/pybench/Constructs.py
   python/branches/p3yk-noslice/Tools/pybench/Dict.py
   python/branches/p3yk-noslice/Tools/pybench/Exceptions.py
   python/branches/p3yk-noslice/Tools/pybench/Imports.py
   python/branches/p3yk-noslice/Tools/pybench/Instances.py
   python/branches/p3yk-noslice/Tools/pybench/Lists.py
   python/branches/p3yk-noslice/Tools/pybench/Lookups.py
   python/branches/p3yk-noslice/Tools/pybench/NewInstances.py
   python/branches/p3yk-noslice/Tools/pybench/Numbers.py
   python/branches/p3yk-noslice/Tools/pybench/Strings.py
   python/branches/p3yk-noslice/Tools/pybench/Tuples.py
   python/branches/p3yk-noslice/Tools/pybench/Unicode.py
   python/branches/p3yk-noslice/Tools/pybench/clockres.py
   python/branches/p3yk-noslice/Tools/pybench/pybench.py
   python/branches/p3yk-noslice/Tools/pybench/systimes.py
   python/branches/p3yk-noslice/Tools/scripts/classfix.py
   python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py
   python/branches/p3yk-noslice/Tools/scripts/fixcid.py
   python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py
   python/branches/p3yk-noslice/Tools/scripts/linktree.py
   python/branches/p3yk-noslice/Tools/scripts/methfix.py
   python/branches/p3yk-noslice/Tools/scripts/pathfix.py
   python/branches/p3yk-noslice/Tools/scripts/reindent.py   (contents, props changed)
   python/branches/p3yk-noslice/Tools/scripts/which.py
   python/branches/p3yk-noslice/Tools/unicode/makeunicodedata.py
   python/branches/p3yk-noslice/Tools/unicode/mkstringprep.py
   python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py
   python/branches/p3yk-noslice/Tools/webchecker/websucker.py
   python/branches/p3yk-noslice/configure
   python/branches/p3yk-noslice/configure.in
   python/branches/p3yk-noslice/setup.py
Log:
Merged revisions 53867-56212 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/branches/p3yk



Modified: python/branches/p3yk-noslice/Demo/imputil/knee.py
==============================================================================
--- python/branches/p3yk-noslice/Demo/imputil/knee.py	(original)
+++ python/branches/p3yk-noslice/Demo/imputil/knee.py	Wed Jul 11 15:40:56 2007
@@ -106,8 +106,7 @@
     return m
 
 
-# Replacement for reload()
-def reload_hook(module):
+def reload(module):
     name = module.__name__
     if '.' not in name:
         return import_module(name, name, None)
@@ -119,8 +118,6 @@
 
 # Save the original hooks
 original_import = __builtin__.__import__
-original_reload = __builtin__.reload
 
 # Now install our hooks
 __builtin__.__import__ = import_hook
-__builtin__.reload = reload_hook

Modified: python/branches/p3yk-noslice/Demo/parser/unparse.py
==============================================================================
--- python/branches/p3yk-noslice/Demo/parser/unparse.py	(original)
+++ python/branches/p3yk-noslice/Demo/parser/unparse.py	Wed Jul 11 15:40:56 2007
@@ -4,6 +4,19 @@
 import cStringIO
 import os
 
+def interleave(inter, f, seq):
+    """Call f on each item in seq, calling inter() in between.
+    """
+    seq = iter(seq)
+    try:
+        f(seq.next())
+    except StopIteration:
+        pass
+    else:
+        for x in seq:
+            inter()
+            f(x)
+
 class Unparser:
     """Methods in this class recursively traverse an AST and
     output source code for the abstract syntax; original formatting
@@ -63,26 +76,13 @@
 
     def _Import(self, t):
         self.fill("import ")
-        first = True
-        for a in t.names:
-            if first:
-                first = False
-            else:
-                self.write(", ")
-            self.write(a.name)
-            if a.asname:
-                self.write(" as "+a.asname)
+        interleave(lambda: self.write(", "), self.dispatch, t.names)
 
     def _ImportFrom(self, t):
         self.fill("from ")
         self.write(t.module)
         self.write(" import ")
-        for i, a in enumerate(t.names):
-            if i == 0:
-                self.write(", ")
-            self.write(a.name)
-            if a.asname:
-                self.write(" as "+a.asname)
+        interleave(lambda: self.write(", "), self.dispatch, t.names)
         # XXX(jpe) what is level for?
 
     def _Assign(self, t):
@@ -99,8 +99,9 @@
         self.dispatch(t.value)
 
     def _Return(self, t):
-        self.fill("return ")
+        self.fill("return")
         if t.value:
+            self.write(" ")
             self.dispatch(t.value)
 
     def _Pass(self, t):
@@ -138,18 +139,16 @@
             self.write(",")
 
     def _Global(self, t):
-        self.fill("global")
-        for i, n in enumerate(t.names):
-            if i != 0:
-                self.write(",")
-            self.write(" " + n)
+        self.fill("global ")
+        interleave(lambda: self.write(", "), self.write, t.names)
 
     def _Yield(self, t):
-        self.fill("yield")
+        self.write("(")
+        self.write("yield")
         if t.value:
-            self.write(" (")
+            self.write(" ")
             self.dispatch(t.value)
-            self.write(")")
+        self.write(")")
 
     def _Raise(self, t):
         self.fill('raise ')
@@ -188,8 +187,9 @@
         self.leave()
 
     def _excepthandler(self, t):
-        self.fill("except ")
+        self.fill("except")
         if t.type:
+            self.write(" ")
             self.dispatch(t.type)
         if t.name:
             self.write(", ")
@@ -289,9 +289,7 @@
 
     def _List(self, t):
         self.write("[")
-        for e in t.elts:
-            self.dispatch(e)
-            self.write(", ")
+        interleave(lambda: self.write(", "), self.dispatch, t.elts)
         self.write("]")
 
     def _ListComp(self, t):
@@ -318,30 +316,31 @@
             self.dispatch(if_clause)
 
     def _IfExp(self, t):
+        self.write("(")
         self.dispatch(t.body)
         self.write(" if ")
         self.dispatch(t.test)
-        if t.orelse:
-            self.write(" else ")
-            self.dispatch(t.orelse)
+        self.write(" else ")
+        self.dispatch(t.orelse)
+        self.write(")")
 
     def _Dict(self, t):
         self.write("{")
-        for k,v in zip(t.keys, t.values):
+        def writem((k, v)):
             self.dispatch(k)
-            self.write(" : ")
+            self.write(": ")
             self.dispatch(v)
-            self.write(", ")
+        interleave(lambda: self.write(", "), writem, zip(t.keys, t.values))
         self.write("}")
 
     def _Tuple(self, t):
-        if not t.elts:
-            self.write("()")
-            return
         self.write("(")
-        for e in t.elts:
-            self.dispatch(e)
-            self.write(", ")
+        if len(t.elts) == 1:
+            (elt,) = t.elts
+            self.dispatch(elt)
+            self.write(",")
+        else:
+            interleave(lambda: self.write(", "), self.dispatch, t.elts)
         self.write(")")
 
     unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
@@ -357,7 +356,7 @@
     def _BinOp(self, t):
         self.write("(")
         self.dispatch(t.left)
-        self.write(")" + self.binop[t.op.__class__.__name__] + "(")
+        self.write(" " + self.binop[t.op.__class__.__name__] + " ")
         self.dispatch(t.right)
         self.write(")")
 
@@ -367,17 +366,15 @@
         self.write("(")
         self.dispatch(t.left)
         for o, e in zip(t.ops, t.comparators):
-            self.write(") " +self.cmpops[o.__class__.__name__] + " (")
+            self.write(" " + self.cmpops[o.__class__.__name__] + " ")
             self.dispatch(e)
             self.write(")")
 
     boolops = {_ast.And: 'and', _ast.Or: 'or'}
     def _BoolOp(self, t):
         self.write("(")
-        self.dispatch(t.values[0])
-        for v in t.values[1:]:
-            self.write(" %s " % self.boolops[t.op.__class__])
-            self.dispatch(v)
+        s = " %s " % self.boolops[t.op.__class__]
+        interleave(lambda: self.write(s), self.dispatch, t.values)
         self.write(")")
 
     def _Attribute(self,t):
@@ -433,10 +430,7 @@
             self.dispatch(t.step)
 
     def _ExtSlice(self, t):
-        for i, d in enumerate(t.dims):
-            if i != 0:
-                self.write(': ')
-            self.dispatch(d)
+        interleave(lambda: self.write(', '), self.dispatch, t.dims)
 
     # others
     def _arguments(self, t):
@@ -472,9 +466,14 @@
         self.write(": ")
         self.dispatch(t.body)
 
+    def _alias(self, t):
+        self.write(t.name)
+        if t.asname:
+            self.write(" as "+t.asname)
+
 def roundtrip(filename, output=sys.stdout):
     source = open(filename).read()
-    tree = compile(source, filename, "exec", 0x400)
+    tree = compile(source, filename, "exec", _ast.PyCF_ONLY_AST)
     Unparser(tree, output)
 
 

Modified: python/branches/p3yk-noslice/Demo/pdist/RCSProxy.py
==============================================================================
--- python/branches/p3yk-noslice/Demo/pdist/RCSProxy.py	(original)
+++ python/branches/p3yk-noslice/Demo/pdist/RCSProxy.py	Wed Jul 11 15:40:56 2007
@@ -185,7 +185,7 @@
     what = sys.argv[1]
     if hasattr(proxy, what):
         attr = getattr(proxy, what)
-        if callable(attr):
+        if hasattr(attr, '__call__'):
             print attr(*sys.argv[2:])
         else:
             print repr(attr)

Modified: python/branches/p3yk-noslice/Demo/pdist/cvslock.py
==============================================================================
--- python/branches/p3yk-noslice/Demo/pdist/cvslock.py	(original)
+++ python/branches/p3yk-noslice/Demo/pdist/cvslock.py	Wed Jul 11 15:40:56 2007
@@ -262,7 +262,6 @@
         rl.unlock()
     finally:
         print [1]
-        sys.exc_traceback = None
         print [2]
         if rl:
             rl.unlock()

Modified: python/branches/p3yk-noslice/Demo/threads/README
==============================================================================
--- python/branches/p3yk-noslice/Demo/threads/README	(original)
+++ python/branches/p3yk-noslice/Demo/threads/README	Wed Jul 11 15:40:56 2007
@@ -3,10 +3,8 @@
 These are mostly "proof of concept" type applications:
 
 Generator.py	Generator class implemented with threads.
-find.py		Parallelized "find(1)" (looks for directories).
 sync.py		Condition variables primitives by Tim Peters.
 telnet.py	Version of ../sockets/telnet.py using threads.
-wpi.py		Version of ../scripts/pi.py using threads (needs stdwin).
 
 Coroutine.py	Coroutines using threads, by Tim Peters (22 May 94)
 fcmp.py		Example of above, by Tim

Modified: python/branches/p3yk-noslice/Demo/tix/grid.py
==============================================================================
--- python/branches/p3yk-noslice/Demo/tix/grid.py	(original)
+++ python/branches/p3yk-noslice/Demo/tix/grid.py	Wed Jul 11 15:40:56 2007
@@ -18,8 +18,8 @@
 g = MyGrid(r, name="a_grid",
 selectunit="cell")
 g.pack(fill=tk.BOTH)
-for x in xrange(5):
-    for y in xrange(5):
+for x in range(5):
+    for y in range(5):
         g.set(x,y,text=str((x,y)))
 
 c = tk.Button(r, text="Close", command=r.destroy)

Modified: python/branches/p3yk-noslice/Doc/Makefile
==============================================================================
--- python/branches/p3yk-noslice/Doc/Makefile	(original)
+++ python/branches/p3yk-noslice/Doc/Makefile	Wed Jul 11 15:40:56 2007
@@ -73,7 +73,7 @@
 # commontex/patchlevel.tex in their dependencies.
 RELEASE=$(shell $(PYTHON) tools/getversioninfo)
 
-PYTHON=	   python
+PYTHON=	   $(PWD)/../python
 DVIPS=	   dvips -N0 -t $(PAPER)
 
 # This is ugly!  The issue here is that there are two different levels
@@ -122,7 +122,7 @@
 
 # The end of this should reflect the major/minor version numbers of
 # the release:
-WHATSNEW=whatsnew26
+WHATSNEW=whatsnew30
 
 # what's what
 MANDVIFILES=	paper-$(PAPER)/api.dvi paper-$(PAPER)/ext.dvi \

Modified: python/branches/p3yk-noslice/Doc/Makefile.deps
==============================================================================
--- python/branches/p3yk-noslice/Doc/Makefile.deps	(original)
+++ python/branches/p3yk-noslice/Doc/Makefile.deps	Wed Jul 11 15:40:56 2007
@@ -88,7 +88,6 @@
 	commontex/reportingbugs.tex \
 	lib/lib.tex \
 	lib/asttable.tex \
-	lib/compiler.tex \
 	lib/distutils.tex \
 	lib/email.tex \
 	lib/emailencoders.tex \
@@ -172,7 +171,6 @@
 	lib/libgdbm.tex \
 	lib/libtermios.tex \
 	lib/libfcntl.tex \
-	lib/libposixfile.tex \
 	lib/libsyslog.tex \
 	lib/liblogging.tex \
 	lib/libpdb.tex \
@@ -186,7 +184,6 @@
 	lib/liburllib2.tex \
 	lib/libhttplib.tex \
 	lib/libftplib.tex \
-	lib/libgopherlib.tex \
 	lib/libnntplib.tex \
 	lib/liburlparse.tex \
 	lib/libhtmlparser.tex \
@@ -194,34 +191,17 @@
 	lib/libsgmllib.tex \
 	lib/librfc822.tex \
 	lib/libmimetools.tex \
-	lib/libmimewriter.tex \
 	lib/libbinascii.tex \
 	lib/libmm.tex \
 	lib/libaudioop.tex \
-	lib/libimageop.tex \
 	lib/libaifc.tex \
-	lib/libjpeg.tex \
-	lib/librgbimg.tex \
 	lib/libossaudiodev.tex \
 	lib/libcrypto.tex \
 	lib/libhashlib.tex \
-	lib/libmd5.tex \
-	lib/libsha.tex \
 	lib/libhmac.tex \
-	lib/libstdwin.tex \
-	lib/libsgi.tex \
-	lib/libal.tex \
-	lib/libcd.tex \
-	lib/libfl.tex \
-	lib/libfm.tex \
-	lib/libgl.tex \
-	lib/libimgfile.tex \
 	lib/libsun.tex \
 	lib/libxdrlib.tex \
 	lib/libimghdr.tex \
-	lib/librestricted.tex \
-	lib/librexec.tex \
-	lib/libbastion.tex \
 	lib/libformatter.tex \
 	lib/liboperator.tex \
 	lib/libresource.tex \
@@ -253,7 +233,6 @@
 	lib/libzipfile.tex \
 	lib/libpprint.tex \
 	lib/libcode.tex \
-	lib/libmimify.tex \
 	lib/libre.tex \
 	lib/libuserdict.tex \
 	lib/libdis.tex \
@@ -285,7 +264,6 @@
 	lib/libimaplib.tex \
 	lib/libpoplib.tex \
 	lib/libcalendar.tex \
-	lib/libpopen2.tex \
 	lib/libbisect.tex \
 	lib/libcollections.tex \
 	lib/libheapq.tex \
@@ -368,7 +346,6 @@
 	mac/libaetools.tex \
 	mac/libaepack.tex \
 	mac/libaetypes.tex \
-	mac/libmacfs.tex \
 	mac/libmacos.tex \
 	mac/libmacostools.tex \
 	mac/libmacui.tex \

Modified: python/branches/p3yk-noslice/Doc/api/abstract.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/abstract.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/abstract.tex	Wed Jul 11 15:40:56 2007
@@ -790,7 +790,7 @@
   the Python statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
 \end{cfuncdesc}
 
-\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Count}{PyObject *o, PyObject *value}
   Return the number of occurrences of \var{value} in \var{o}, that is,
   return the number of keys for which \code{\var{o}[\var{key}] ==
   \var{value}}.  On failure, return \code{-1}.  This is equivalent to
@@ -804,7 +804,7 @@
   expression \samp{\var{value} in \var{o}}.
 \end{cfuncdesc}
 
-\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Index}{PyObject *o, PyObject *value}
   Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
   \var{value}}.  On error, return \code{-1}.    This is equivalent to
   the Python expression \samp{\var{o}.index(\var{value})}.
@@ -854,7 +854,7 @@
   \versionadded{2.3}
 \end{cfuncdesc}
 
-\begin{cfuncdesc}{int}{PySequence_Fast_GET_SIZE}{PyObject *o}
+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Fast_GET_SIZE}{PyObject *o}
   Returns the length of \var{o}, assuming that \var{o} was
   returned by \cfunction{PySequence_Fast()} and that \var{o} is
   not \NULL.  The size can also be gotten by calling

Modified: python/branches/p3yk-noslice/Doc/api/concrete.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/concrete.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/concrete.tex	Wed Jul 11 15:40:56 2007
@@ -99,6 +99,7 @@
 
 \begin{csimplemacrodesc}{Py_RETURN_NONE}
   Properly handle returning \cdata{Py_None} from within a C function.
+  \versionadded{2.4}
 \end{csimplemacrodesc}
 
 
@@ -430,10 +431,9 @@
   \versionadded{2.2}
 \end{cfuncdesc}
 
-\begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str, char **pend}
+\begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str}
   Create a \ctype{PyFloatObject} object based on the string value in
-  \var{str}, or \NULL{} on failure.  The \var{pend} argument is ignored.  It
-  remains only for backward compatibility.
+  \var{str}, or \NULL{} on failure.
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
@@ -443,7 +443,9 @@
 
 \begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
   Return a C \ctype{double} representation of the contents of
-  \var{pyfloat}.
+  \var{pyfloat}.  If \var{pyfloat} is not a Python floating point
+  object but has a \method{__float__} method, this method will first
+  be called to convert \var{pyfloat} into a float.
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
@@ -558,8 +560,11 @@
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
-  Return the \ctype{Py_complex} value of the complex number
-  \var{op}.
+  Return the \ctype{Py_complex} value of the complex number \var{op}.
+  \versionchanged[If \var{op} is not a Python complex number object
+                  but has a \method{__complex__} method, this method
+		  will first be called to convert \var{op} to a Python
+		  complex number object]{2.6}
 \end{cfuncdesc}
 
 
@@ -1173,10 +1178,10 @@
    *byteorder == 1:  big endian
 \end{verbatim}
 
-  and then switches according to all byte order marks (BOM) it finds
-  in the input data.  BOMs are not copied into the resulting Unicode
-  string.  After completion, \var{*byteorder} is set to the current
-  byte order at the end of input data.
+  and then switches if the first two bytes of the input data are a byte order
+  mark (BOM) and the specified byte order is native order.  This BOM is not
+  copied into the resulting Unicode string.  After completion, \var{*byteorder}
+  is set to the current byte order at the.
 
   If \var{byteorder} is \NULL{}, the codec starts in native order mode.
 
@@ -2157,6 +2162,35 @@
 
 \section{Other Objects \label{otherObjects}}
 
+\subsection{Class Objects \label{classObjects}}
+
+\obindex{class}
+Note that the class objects described here represent old-style classes,
+which will go away in Python 3. When creating new types for extension
+modules, you will want to work with type objects (section
+\ref{typeObjects}).
+
+\begin{ctypedesc}{PyClassObject}
+  The C structure of the objects used to describe built-in classes.
+\end{ctypedesc}
+
+\begin{cvardesc}{PyObject*}{PyClass_Type}
+  This is the type object for class objects; it is the same object as
+  \code{types.ClassType} in the Python layer.
+  \withsubitem{(in module types)}{\ttindex{ClassType}}
+\end{cvardesc}
+
+\begin{cfuncdesc}{int}{PyClass_Check}{PyObject *o}
+  Return true if the object \var{o} is a class object, including
+  instances of types derived from the standard class object.  Return
+  false in all other cases.
+\end{cfuncdesc}
+
+\begin{cfuncdesc}{int}{PyClass_IsSubclass}{PyObject *klass, PyObject *base}
+  Return true if \var{klass} is a subclass of \var{base}. Return false in
+  all other cases.
+\end{cfuncdesc}
+
 \subsection{File Objects \label{fileObjects}}
 
 \obindex{file}

Modified: python/branches/p3yk-noslice/Doc/api/exceptions.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/exceptions.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/exceptions.tex	Wed Jul 11 15:40:56 2007
@@ -381,7 +381,6 @@
 \begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
   \lineiii{PyExc_BaseException\ttindex{PyExc_BaseException}}{\exception{BaseException}}{(1), (4)}
   \lineiii{PyExc_Exception\ttindex{PyExc_Exception}}{\exception{Exception}}{(1)}
-  \lineiii{PyExc_StandardError\ttindex{PyExc_StandardError}}{\exception{StandardError}}{(1)}
   \lineiii{PyExc_ArithmeticError\ttindex{PyExc_ArithmeticError}}{\exception{ArithmeticError}}{(1)}
   \lineiii{PyExc_LookupError\ttindex{PyExc_LookupError}}{\exception{LookupError}}{(1)}
   \lineiii{PyExc_AssertionError\ttindex{PyExc_AssertionError}}{\exception{AssertionError}}{}

Modified: python/branches/p3yk-noslice/Doc/api/init.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/init.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/init.tex	Wed Jul 11 15:40:56 2007
@@ -245,7 +245,7 @@
   program name (set by \cfunction{Py_SetProgramName()} above) and some
   environment variables.  The returned string consists of a series of
   directory names separated by a platform dependent delimiter
-  character.  The delimiter character is \character{:} on \UNIX and Mac OS X,
+  character.  The delimiter character is \character{:} on \UNIX{} and Mac OS X,
   \character{;} on Windows.  The returned string points into
   static storage; the caller should not modify its value.  The value
   is available to Python code as the list

Modified: python/branches/p3yk-noslice/Doc/api/memory.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/memory.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/memory.tex	Wed Jul 11 15:40:56 2007
@@ -100,7 +100,9 @@
   memory block is resized but is not freed, and the returned pointer
   is non-\NULL.  Unless \var{p} is \NULL, it must have been
   returned by a previous call to \cfunction{PyMem_Malloc()} or
-  \cfunction{PyMem_Realloc()}.
+  \cfunction{PyMem_Realloc()}. If the request fails,
+  \cfunction{PyMem_Realloc()} returns \NULL{} and \var{p} remains a
+  valid pointer to the previous memory area.
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{void}{PyMem_Free}{void *p}
@@ -124,7 +126,8 @@
 \begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
   Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
   to \code{(\var{n} * sizeof(\var{TYPE}))} bytes.  Returns a pointer
-  cast to \ctype{\var{TYPE}*}.
+  cast to \ctype{\var{TYPE}*}. On return, \var{p} will be a pointer to
+  the new memory area, or \NULL{} in the event of failure.
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{void}{PyMem_Del}{void *p}

Modified: python/branches/p3yk-noslice/Doc/api/newtypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/newtypes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/newtypes.tex	Wed Jul 11 15:40:56 2007
@@ -1071,7 +1071,7 @@
   iterator, or raises \exception{StopIteration} when the iterator is
   exhausted.  Its presence normally signals that the instances of this
   type are iterators (although classic instances always have this
-  function, even if they don't define a \method{next()} method).
+  function, even if they don't define a \method{__next__()} method).
 
   Iterator types should also define the \member{tp_iter} function, and
   that function should return the iterator instance itself (not a new
@@ -1316,7 +1316,7 @@
 
   This field is inherited by static subtypes, but not by dynamic
   subtypes (subtypes created by a class statement); in the latter,
-  this field is always set to \cfunction{PyType_GenericAlloc()}, to
+  this field is always set to \cfunction{PyType_GenericAlloc}, to
   force a standard heap allocation strategy.  That is also the
   recommended value for statically defined types.
 \end{cmemberdesc}

Modified: python/branches/p3yk-noslice/Doc/api/refcounts.dat
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/refcounts.dat	(original)
+++ python/branches/p3yk-noslice/Doc/api/refcounts.dat	Wed Jul 11 15:40:56 2007
@@ -385,7 +385,6 @@
 
 PyFloat_FromString:PyObject*::+1:
 PyFloat_FromString:PyObject*:str:0:
-PyFloat_FromString:char**:pend:0:ignored
 
 PyFrozenSet_New:PyObject*::+1:
 PyFrozenSet_New:PyObject*:iterable:0:

Modified: python/branches/p3yk-noslice/Doc/api/utilities.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/utilities.tex	(original)
+++ python/branches/p3yk-noslice/Doc/api/utilities.tex	Wed Jul 11 15:40:56 2007
@@ -140,10 +140,7 @@
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
-  Reload a module.  This is best described by referring to the
-  built-in Python function \function{reload()}\bifuncindex{reload}, as
-  the standard \function{reload()} function calls this function
-  directly.  Return a new reference to the reloaded module, or \NULL{}
+  Reload a module.  Return a new reference to the reloaded module, or \NULL{}
   with an exception set on failure (the module still exists in this
   case).
 \end{cfuncdesc}
@@ -930,3 +927,94 @@
   If there is an error in the format string, the
   \exception{SystemError} exception is set and \NULL{} returned.
 \end{cfuncdesc}
+
+\section{String conversion and formatting \label{string-formatting}}
+
+Functions for number conversion and formatted string output.
+
+\begin{cfuncdesc}{int}{PyOS_snprintf}{char *str, size_t size, 
+                                      const char *format, \moreargs}
+Output not more than \var{size} bytes to \var{str} according to the format
+string \var{format} and the extra arguments. See the \UNIX{} man
+page \manpage{snprintf}{2}.
+\end{cfuncdesc}
+
+\begin{cfuncdesc}{int}{PyOS_vsnprintf}{char *str, size_t size,
+                                       const char *format, va_list va}
+Output not more than \var{size} bytes to \var{str} according to the format
+string \var{format} and the variable argument list \var{va}. \UNIX{}
+man page \manpage{vsnprintf}{2}.
+\end{cfuncdesc}
+
+\cfunction{PyOS_snprintf} and \cfunction{PyOS_vsnprintf} wrap the
+Standard C library functions \cfunction{snprintf()} and
+\cfunction{vsnprintf()}. Their purpose is to guarantee consistent
+behavior in corner cases, which the Standard C functions do not.
+
+The wrappers ensure that \var{str}[\var{size}-1] is always
+\character{\textbackslash0} upon return. They never write more than
+\var{size} bytes (including the trailing \character{\textbackslash0}
+into str. Both functions require that \code{\var{str} != NULL},
+\code{\var{size} > 0} and \code{\var{format} != NULL}.
+
+If the platform doesn't have \cfunction{vsnprintf()} and the buffer
+size needed to avoid truncation exceeds \var{size} by more than 512
+bytes, Python aborts with a \var{Py_FatalError}.
+
+The return value (\var{rv}) for these functions should be interpreted
+as follows:
+
+\begin{itemize}
+
+\item When \code{0 <= \var{rv} < \var{size}}, the output conversion
+  was successful and \var{rv} characters were written to \var{str}
+  (excluding the trailing \character{\textbackslash0} byte at
+  \var{str}[\var{rv}]).
+
+\item When \code{\var{rv} >= \var{size}}, the output conversion was
+  truncated and a buffer with \code{\var{rv} + 1} bytes would have
+  been needed to succeed. \var{str}[\var{size}-1] is
+  \character{\textbackslash0} in this case.
+
+\item When \code{\var{rv} < 0}, ``something bad happened.''
+  \var{str}[\var{size}-1] is \character{\textbackslash0} in this case
+  too, but the rest of \var{str} is undefined. The exact cause of the
+  error depends on the underlying platform.
+
+\end{itemize}
+
+The following functions provide locale-independent string to number
+conversions.
+
+\begin{cfuncdesc}{double}{PyOS_ascii_strtod}{const char *nptr, char **endptr}
+Convert a string to a \ctype{double}. This function behaves like the
+Standard C function \cfunction{strtod()} does in the C locale. It does
+this without changing the current locale, since that would not be
+thread-safe.
+
+\cfunction{PyOS_ascii_strtod} should typically be used for reading
+configuration files or other non-user input that should be locale
+independent. \versionadded{2.4}
+
+See the \UNIX{} man page \manpage{strtod}{2} for details.
+
+\end{cfuncdesc}
+
+\begin{cfuncdesc}{char *}{PyOS_ascii_formatd}{char *buffer, size_t buf_len,
+                                              const char *format, double d}
+Convert a \ctype{double} to a string using the \character{.} as the
+decimal separator. \var{format} is a \cfunction{printf()}-style format
+string specifying the number format. Allowed conversion characters are
+\character{e}, \character{E}, \character{f}, \character{F},
+\character{g} and \character{G}.
+
+The return value is a pointer to \var{buffer} with the converted
+string or NULL if the conversion failed. \versionadded{2.4}
+\end{cfuncdesc}
+
+\begin{cfuncdesc}{double}{PyOS_ascii_atof}{const char *nptr}
+Convert a string to a \ctype{double} in a locale-independent
+way. \versionadded{2.4}
+
+See the \UNIX{} man page \manpage{atof}{2} for details.
+\end{cfuncdesc}

Modified: python/branches/p3yk-noslice/Doc/commontex/copyright.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/commontex/copyright.tex	(original)
+++ python/branches/p3yk-noslice/Doc/commontex/copyright.tex	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
-Copyright \copyright{} 2001-2006 Python Software Foundation.
+Copyright \copyright{} 2001-2007 Python Software Foundation.
 All rights reserved.
 
 Copyright \copyright{} 2000 BeOpen.com.

Modified: python/branches/p3yk-noslice/Doc/commontex/license.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/commontex/license.tex	(original)
+++ python/branches/p3yk-noslice/Doc/commontex/license.tex	Wed Jul 11 15:40:56 2007
@@ -52,6 +52,7 @@
   \linev{2.4.3}{2.4.2}{2006}{PSF}{yes}
   \linev{2.4.4}{2.4.3}{2006}{PSF}{yes}
   \linev{2.5}{2.4}{2006}{PSF}{yes}
+  \linev{2.5.1}{2.5}{2007}{PSF}{yes}
 \end{tablev}
 
 \note{GPL-compatible doesn't mean that we're distributing
@@ -82,7 +83,7 @@
 prepare derivative works, distribute, and otherwise use Python
 \version{} alone or in any derivative version, provided, however, that
 PSF's License Agreement and PSF's notice of copyright, i.e.,
-``Copyright \copyright{} 2001-2006 Python Software Foundation; All
+``Copyright \copyright{} 2001-2007 Python Software Foundation; All
 Rights Reserved'' are retained in Python \version{} alone or in any
 derivative version prepared by Licensee.
 

Modified: python/branches/p3yk-noslice/Doc/dist/dist.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/dist/dist.tex	(original)
+++ python/branches/p3yk-noslice/Doc/dist/dist.tex	Wed Jul 11 15:40:56 2007
@@ -486,9 +486,24 @@
 extensions: it will run SWIG on the interface file and compile the
 resulting C/\Cpp{} file into your extension.
 
-\XXX{SWIG support is rough around the edges and largely untested;
-  especially SWIG support for \Cpp{} extensions!  Explain in more detail
-  here when the interface firms up.}
+\XXX{SWIG support is rough around the edges and largely untested!}
+
+This warning notwithstanding, options to SWIG can be currently passed
+like this:
+
+\begin{verbatim}
+setup(...
+      ext_modules=[Extension('_foo', ['foo.i'], 
+                             swig_opts=['-modern', '-I../include'])],
+      py_modules=['foo'],
+     )
+\end{verbatim}
+
+Or on the commandline like this:
+
+\begin{verbatim}
+> python setup.py build_ext --swig-opts="-modern -I../include"
+\end{verbatim}
 
 On some platforms, you can include non-source files that are processed
 by the compiler and included in your extension.  Currently, this just
@@ -1017,6 +1032,7 @@
   --include-dirs (-I)  list of directories to search for header files
   --define (-D)        C preprocessor macros to define
   --undef (-U)         C preprocessor macros to undefine
+  --swig-opts          list of SWIG command line options        
 [...]
 \end{verbatim}
 
@@ -1802,9 +1818,9 @@
         setup.py
         foo.py
 \end{verbatim}
-(In all diagrams in this section, \verb|<root>| will refer to the
-distribution root directory.)  A minimal setup script to describe this
-situation would be:
+(In all diagrams in this section, \var{\textless root\textgreater}
+will refer to the distribution root directory.)  A minimal setup script
+to describe this situation would be:
 \begin{verbatim}
 from distutils.core import setup
 setup(name='foo',
@@ -3179,7 +3195,7 @@
 
 Note that this is not a fully-fledged string interpolation function. A
 valid \code{\$variable} can consist only of upper and lower case letters,
-numbers and an underscore. No \{ \} or \( \) style quoting is available.
+numbers and an underscore. No \{ \} or ( ) style quoting is available.
 \end{funcdesc}
 
 \begin{funcdesc}{grok_environment_error}{exc\optional{, prefix=\samp{'error: '}}}
@@ -3733,7 +3749,7 @@
 
 Subclasses of \class{Command} must define the following methods.
 
-\begin{methoddesc}{initialize_options()}
+\begin{methoddesc}[Command]{initialize_options()}
 Set default values for all the options that this command
 supports.  Note that these defaults may be overridden by other
 commands, by the setup script, by config files, or by the
@@ -3742,7 +3758,7 @@
 are just a bunch of \samp{self.foo = None} assignments.
 \end{methoddesc}
 
-\begin{methoddesc}{finalize_options}{}
+\begin{methoddesc}[Command]{finalize_options}{}
 Set final values for all the options that this command supports.
 This is always called as late as possible, ie.  after any option
 assignments from the command-line or from other commands have been
@@ -3751,7 +3767,7 @@
 \var{bar} as long as \var{foo} still has the same value it was assigned in
 \method{initialize_options()}.
 \end{methoddesc}
-\begin{methoddesc}{run}{}
+\begin{methoddesc}[Command]{run}{}
 A command's raison d'etre: carry out the action it exists to
 perform, controlled by the options initialized in
 \method{initialize_options()}, customized by other commands, the setup

Modified: python/branches/p3yk-noslice/Doc/ext/extending.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ext/extending.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ext/extending.tex	Wed Jul 11 15:40:56 2007
@@ -399,12 +399,7 @@
 following a \cfunction{fork()} without an intervening
 \cfunction{exec()}) can create problems for some extension modules.
 Extension module authors should exercise caution when initializing
-internal data structures.
-Note also that the \function{reload()} function can be used with
-extension modules, and will call the module initialization function
-(\cfunction{initspam()} in the example), but will not load the module
-again if it was loaded from a dynamically loadable object file
-(\file{.so} on \UNIX, \file{.dll} on Windows).}
+internal data structures.}
 
 A more substantial example module is included in the Python source
 distribution as \file{Modules/xxmodule.c}.  This file may be used as a 

Modified: python/branches/p3yk-noslice/Doc/ext/newtypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ext/newtypes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ext/newtypes.tex	Wed Jul 11 15:40:56 2007
@@ -489,7 +489,6 @@
   garbage collection, there are calls that can be made to ``untrack''
   the object from garbage collection, however, these calls are
   advanced and not covered here.}
-\item
 \end{itemize}
 
 
@@ -930,6 +929,102 @@
 collection. Most extensions will use the versions automatically
 provided.
 
+\subsection{Subclassing other types}
+
+It is possible to create new extension types that are derived from existing
+types. It is easiest to inherit from the built in types, since an extension
+can easily use the \class{PyTypeObject} it needs. It can be difficult to
+share these \class{PyTypeObject} structures between extension modules.
+
+In this example we will create a \class{Shoddy} type that inherits from
+the builtin \class{list} type. The new type will be completely compatible
+with regular lists, but will have an additional \method{increment()} method
+that increases an internal counter.
+
+\begin{verbatim}
+>>> import shoddy
+>>> s = shoddy.Shoddy(range(3))
+>>> s.extend(s)
+>>> print len(s)
+6
+>>> print s.increment()
+1
+>>> print s.increment()
+2
+\end{verbatim}
+
+\verbatiminput{shoddy.c}
+
+As you can see, the source code closely resembles the \class{Noddy} examples in previous
+sections. We will break down the main differences between them.
+
+\begin{verbatim}
+typedef struct {
+	PyListObject list;
+	int state;
+} Shoddy;
+\end{verbatim}
+
+The primary difference for derived type objects is that the base type's
+object structure must be the first value. The base type will already
+include the \cfunction{PyObject_HEAD} at the beginning of its structure.
+
+When a Python object is a \class{Shoddy} instance, its \var{PyObject*} pointer
+can be safely cast to both \var{PyListObject*} and \var{Shoddy*}.
+
+\begin{verbatim}
+static int
+Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
+{
+	if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
+		return -1;
+	self->state = 0;
+	return 0;
+}
+\end{verbatim}
+
+In the \member{__init__} method for our type, we can see how to call through
+to the \member{__init__} method of the base type.
+
+This pattern is important when writing a type with custom \member{new} and
+\member{dealloc} methods. The \member{new} method should not actually create the
+memory for the object with \member{tp_alloc}, that will be handled by
+the base class when calling its \member{tp_new}.
+
+When filling out the \cfunction{PyTypeObject} for the \class{Shoddy} type,
+you see a slot for \cfunction{tp_base}. Due to cross platform compiler
+issues, you can't fill that field directly with the \cfunction{PyList_Type};
+it can be done later in the module's \cfunction{init} function.
+
+\begin{verbatim}
+PyMODINIT_FUNC
+initshoddy(void)
+{
+	PyObject *m;
+
+	ShoddyType.tp_base = &PyList_Type;
+	if (PyType_Ready(&ShoddyType) < 0)
+		return;
+
+	m = Py_InitModule3("shoddy", NULL, "Shoddy module");
+	if (m == NULL)
+		return;
+
+	Py_INCREF(&ShoddyType);
+	PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
+}
+\end{verbatim}
+
+Before calling \cfunction{PyType_Ready}, the type structure must have the
+\member{tp_base} slot filled in. When we are deriving a new type, it is
+not necessary to fill out the \member{tp_alloc} slot with
+\cfunction{PyType_GenericNew} -- the allocate function from the base type
+will be inherited.
+
+After that, calling \cfunction{PyType_Ready} and adding the type object
+to the module is the same as with the basic \class{Noddy} examples.
+
+
 \section{Type Methods
          \label{dnt-type-methods}}
 

Modified: python/branches/p3yk-noslice/Doc/howto/functional.rst
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/functional.rst	(original)
+++ python/branches/p3yk-noslice/Doc/howto/functional.rst	Wed Jul 11 15:40:56 2007
@@ -199,11 +199,13 @@
 
 An iterator is an object representing a stream of data; this object
 returns the data one element at a time.  A Python iterator must
-support a method called ``next()`` that takes no arguments and always
+support a method called ``__next__()`` that takes no arguments and always
 returns the next element of the stream.  If there are no more elements
-in the stream, ``next()`` must raise the ``StopIteration`` exception.
+in the stream, ``__next__()`` must raise the ``StopIteration`` exception.
 Iterators don't have to be finite, though; it's perfectly reasonable
 to write an iterator that produces an infinite stream of data.
+The built-in ``next()`` function is normally used to call the iterator's
+``__next__()`` method.
 
 The built-in ``iter()`` function takes an arbitrary object and tries
 to return an iterator that will return the object's contents or
@@ -218,13 +220,13 @@
     >>> it = iter(L)
     >>> print it
     <iterator object at 0x8116870>
-    >>> it.next()
+    >>> next(it)
     1
-    >>> it.next()
+    >>> next(it)
     2
-    >>> it.next()
+    >>> next(it)
     3
-    >>> it.next()
+    >>> next(it)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
@@ -271,7 +273,7 @@
 Note that you can only go forward in an iterator; there's no way to
 get the previous element, reset the iterator, or make a copy of it.
 Iterator objects can optionally provide these additional capabilities,
-but the iterator protocol only specifies the ``next()`` method.
+but the iterator protocol only specifies the ``__next__()`` method.
 Functions may therefore consume all of the iterator's output, and if
 you need to do something different with the same stream, you'll have
 to create a new iterator.
@@ -485,7 +487,7 @@
 statement.  The big difference between ``yield`` and a
 ``return`` statement is that on reaching a ``yield`` the
 generator's state of execution is suspended and local variables are
-preserved.  On the next call to the generator's ``.next()`` method,
+preserved.  On the next call ``next(generator)``,
 the function will resume executing.  
 
 Here's a sample usage of the ``generate_ints()`` generator::
@@ -493,13 +495,13 @@
     >>> gen = generate_ints(3)
     >>> gen
     <generator object at 0x8117f90>
-    >>> gen.next()
+    >>> next(gen)
     0
-    >>> gen.next()
+    >>> next(gen)
     1
-    >>> gen.next()
+    >>> next(gen)
     2
-    >>> gen.next()
+    >>> next(gen)
     Traceback (most recent call last):
       File "stdin", line 1, in ?
       File "stdin", line 2, in generate_ints
@@ -521,7 +523,7 @@
 own class and storing all the local variables of the generator as
 instance variables.  For example, returning a list of integers could
 be done by setting ``self.count`` to 0, and having the
-``next()`` method increment ``self.count`` and return it.
+``__next__()`` method increment ``self.count`` and return it.
 However, for a moderately complicated generator, writing a
 corresponding class can be much messier.
 
@@ -583,7 +585,7 @@
 Values are sent into a generator by calling its
 ``send(value)`` method.  This method resumes the 
 generator's code and the ``yield`` expression returns the specified
-value.  If the regular ``next()`` method is called, the
+value.  If the regular ``__next__()`` method is called, the
 ``yield`` returns ``None``.
 
 Here's a simple counter that increments by 1 and allows changing the
@@ -604,18 +606,18 @@
 And here's an example of changing the counter:
 
     >>> it = counter(10)
-    >>> print it.next()
+    >>> print next(it)
     0
-    >>> print it.next()
+    >>> print next(it)
     1
     >>> print it.send(8)
     8
-    >>> print it.next()
+    >>> print next(it)
     9
-    >>> print it.next()
+    >>> print next(it)
     Traceback (most recent call last):
       File ``t.py'', line 15, in ?
-        print it.next()
+        print next(it)
     StopIteration
 
 Because ``yield`` will often be returning ``None``, you
@@ -978,7 +980,7 @@
 that's a slice of the iterator.  With a single ``stop`` argument, 
 it will return the first ``stop``
 elements.  If you supply a starting index, you'll get ``stop-start``
-elements, and if you supply a value for ``step`, elements will be
+elements, and if you supply a value for ``step``, elements will be
 skipped accordingly.  Unlike Python's string and list slicing, you
 can't use negative values for ``start``, ``stop``, or ``step``.
 

Modified: python/branches/p3yk-noslice/Doc/howto/regex.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/regex.tex	(original)
+++ python/branches/p3yk-noslice/Doc/howto/regex.tex	Wed Jul 11 15:40:56 2007
@@ -522,8 +522,7 @@
 contains a lot of regular expressions, or re-uses the same ones in
 several locations, then it might be worthwhile to collect all the
 definitions in one place, in a section of code that compiles all the
-REs ahead of time.  To take an example from the standard library,
-here's an extract from \file{xmllib.py}:
+REs ahead of time.  To take an example from the standard library:
 
 \begin{verbatim}
 ref = re.compile( ... )

Modified: python/branches/p3yk-noslice/Doc/howto/unicode.rst
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/unicode.rst	(original)
+++ python/branches/p3yk-noslice/Doc/howto/unicode.rst	Wed Jul 11 15:40:56 2007
@@ -152,7 +152,7 @@
 4. Many Internet standards are defined in terms of textual data, and 
    can't handle content with embedded zero bytes.
 
-Generally people don't use this encoding, choosing other encodings
+Generally people don't use this encoding, instead choosing other encodings
 that are more efficient and convenient.
 
 Encodings don't have to handle every possible Unicode character, and

Modified: python/branches/p3yk-noslice/Doc/inst/inst.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/inst/inst.tex	(original)
+++ python/branches/p3yk-noslice/Doc/inst/inst.tex	Wed Jul 11 15:40:56 2007
@@ -296,7 +296,7 @@
 \filevar{prefix} and \filevar{exec-prefix} stand for the directories
 that Python is installed to, and where it finds its libraries at
 run-time.  They are always the same under Windows, and very
-often the same under \UNIX and Mac OS X.  You can find out what your Python
+often the same under \UNIX{} and Mac OS X.  You can find out what your Python
 installation uses for \filevar{prefix} and \filevar{exec-prefix} by
 running Python in interactive mode and typing a few simple commands.
 Under \UNIX, just type \code{python} at the shell prompt.  Under

Deleted: /python/branches/p3yk-noslice/Doc/lib/compiler.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/compiler.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,354 +0,0 @@
-\chapter{Python compiler package \label{compiler}}
-
-\sectionauthor{Jeremy Hylton}{jeremy at zope.com}
-
-
-The Python compiler package is a tool for analyzing Python source code
-and generating Python bytecode.  The compiler contains libraries to
-generate an abstract syntax tree from Python source code and to
-generate Python bytecode from the tree.
-
-The \refmodule{compiler} package is a Python source to bytecode
-translator written in Python.  It uses the built-in parser and
-standard \refmodule{parser} module to generated a concrete syntax
-tree.  This tree is used to generate an abstract syntax tree (AST) and
-then Python bytecode.
-
-The full functionality of the package duplicates the builtin compiler
-provided with the Python interpreter.  It is intended to match its
-behavior almost exactly.  Why implement another compiler that does the
-same thing?  The package is useful for a variety of purposes.  It can
-be modified more easily than the builtin compiler.  The AST it
-generates is useful for analyzing Python source code.
-
-This chapter explains how the various components of the
-\refmodule{compiler} package work.  It blends reference material with
-a tutorial.
-
-The following modules are part of the \refmodule{compiler} package:
-
-\localmoduletable
-
-
-\section{The basic interface}
-
-\declaremodule{}{compiler}
-
-The top-level of the package defines four functions.  If you import
-\module{compiler}, you will get these functions and a collection of
-modules contained in the package.
-
-\begin{funcdesc}{parse}{buf}
-Returns an abstract syntax tree for the Python source code in \var{buf}.
-The function raises \exception{SyntaxError} if there is an error in the
-source code.  The return value is a \class{compiler.ast.Module} instance
-that contains the tree.  
-\end{funcdesc}
-
-\begin{funcdesc}{parseFile}{path}
-Return an abstract syntax tree for the Python source code in the file
-specified by \var{path}.  It is equivalent to
-\code{parse(open(\var{path}).read())}.
-\end{funcdesc}
-
-\begin{funcdesc}{walk}{ast, visitor\optional{, verbose}}
-Do a pre-order walk over the abstract syntax tree \var{ast}.  Call the
-appropriate method on the \var{visitor} instance for each node
-encountered.
-\end{funcdesc}
-
-\begin{funcdesc}{compile}{source, filename, mode, flags=None, 
-			dont_inherit=None}
-Compile the string \var{source}, a Python module, statement or
-expression, into a code object that can be executed by the exec
-statement or \function{eval()}. This function is a replacement for the
-built-in \function{compile()} function.
-
-The \var{filename} will be used for run-time error messages.
-
-The \var{mode} must be 'exec' to compile a module, 'single' to compile a
-single (interactive) statement, or 'eval' to compile an expression.
-
-The \var{flags} and \var{dont_inherit} arguments affect future-related
-statements, but are not supported yet.
-\end{funcdesc}
-
-\begin{funcdesc}{compileFile}{source}
-Compiles the file \var{source} and generates a .pyc file.
-\end{funcdesc}
-
-The \module{compiler} package contains the following modules:
-\refmodule[compiler.ast]{ast}, \module{consts}, \module{future},
-\module{misc}, \module{pyassem}, \module{pycodegen}, \module{symbols},
-\module{transformer}, and \refmodule[compiler.visitor]{visitor}.
-
-\section{Limitations}
-
-There are some problems with the error checking of the compiler
-package.  The interpreter detects syntax errors in two distinct
-phases.  One set of errors is detected by the interpreter's parser,
-the other set by the compiler.  The compiler package relies on the
-interpreter's parser, so it get the first phases of error checking for
-free.  It implements the second phase itself, and that implementation is
-incomplete.  For example, the compiler package does not raise an error
-if a name appears more than once in an argument list: 
-\code{def f(x, x): ...}
-
-A future version of the compiler should fix these problems.
-
-\section{Python Abstract Syntax}
-
-The \module{compiler.ast} module defines an abstract syntax for
-Python.  In the abstract syntax tree, each node represents a syntactic
-construct.  The root of the tree is \class{Module} object.
-
-The abstract syntax offers a higher level interface to parsed Python
-source code.  The \ulink{\module{parser}}
-{http://www.python.org/doc/current/lib/module-parser.html}
-module and the compiler written in C for the Python interpreter use a
-concrete syntax tree.  The concrete syntax is tied closely to the
-grammar description used for the Python parser.  Instead of a single
-node for a construct, there are often several levels of nested nodes
-that are introduced by Python's precedence rules.
-
-The abstract syntax tree is created by the
-\module{compiler.transformer} module.  The transformer relies on the
-builtin Python parser to generate a concrete syntax tree.  It
-generates an abstract syntax tree from the concrete tree.  
-
-The \module{transformer} module was created by Greg
-Stein\index{Stein, Greg} and Bill Tutt\index{Tutt, Bill} for an
-experimental Python-to-C compiler.  The current version contains a
-number of modifications and improvements, but the basic form of the
-abstract syntax and of the transformer are due to Stein and Tutt.
-
-\subsection{AST Nodes}
-
-\declaremodule{}{compiler.ast}
-
-The \module{compiler.ast} module is generated from a text file that
-describes each node type and its elements.  Each node type is
-represented as a class that inherits from the abstract base class
-\class{compiler.ast.Node} and defines a set of named attributes for
-child nodes.
-
-\begin{classdesc}{Node}{}
-  
-  The \class{Node} instances are created automatically by the parser
-  generator.  The recommended interface for specific \class{Node}
-  instances is to use the public attributes to access child nodes.  A
-  public attribute may be bound to a single node or to a sequence of
-  nodes, depending on the \class{Node} type.  For example, the
-  \member{bases} attribute of the \class{Class} node, is bound to a
-  list of base class nodes, and the \member{doc} attribute is bound to
-  a single node.
-  
-  Each \class{Node} instance has a \member{lineno} attribute which may
-  be \code{None}.  XXX Not sure what the rules are for which nodes
-  will have a useful lineno.
-\end{classdesc}
-
-All \class{Node} objects offer the following methods:
-
-\begin{methoddesc}{getChildren}{}
-  Returns a flattened list of the child nodes and objects in the
-  order they occur.  Specifically, the order of the nodes is the
-  order in which they appear in the Python grammar.  Not all of the
-  children are \class{Node} instances.  The names of functions and
-  classes, for example, are plain strings.
-\end{methoddesc}
-
-\begin{methoddesc}{getChildNodes}{}
-  Returns a flattened list of the child nodes in the order they
-  occur.  This method is like \method{getChildren()}, except that it
-  only returns those children that are \class{Node} instances.
-\end{methoddesc}
-
-Two examples illustrate the general structure of \class{Node}
-classes.  The \keyword{while} statement is defined by the following
-grammar production: 
-
-\begin{verbatim}
-while_stmt:     "while" expression ":" suite
-               ["else" ":" suite]
-\end{verbatim}
-
-The \class{While} node has three attributes: \member{test},
-\member{body}, and \member{else_}.  (If the natural name for an
-attribute is also a Python reserved word, it can't be used as an
-attribute name.  An underscore is appended to the word to make it a
-legal identifier, hence \member{else_} instead of \keyword{else}.)
-
-The \keyword{if} statement is more complicated because it can include
-several tests.  
-
-\begin{verbatim}
-if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
-\end{verbatim}
-
-The \class{If} node only defines two attributes: \member{tests} and
-\member{else_}.  The \member{tests} attribute is a sequence of test
-expression, consequent body pairs.  There is one pair for each
-\keyword{if}/\keyword{elif} clause.  The first element of the pair is
-the test expression.  The second elements is a \class{Stmt} node that
-contains the code to execute if the test is true.
-
-The \method{getChildren()} method of \class{If} returns a flat list of
-child nodes.  If there are three \keyword{if}/\keyword{elif} clauses
-and no \keyword{else} clause, then \method{getChildren()} will return
-a list of six elements: the first test expression, the first
-\class{Stmt}, the second text expression, etc.
-
-The following table lists each of the \class{Node} subclasses defined
-in \module{compiler.ast} and each of the public attributes available
-on their instances.  The values of most of the attributes are
-themselves \class{Node} instances or sequences of instances.  When the
-value is something other than an instance, the type is noted in the
-comment.  The attributes are listed in the order in which they are
-returned by \method{getChildren()} and \method{getChildNodes()}.
-
-\input{asttable}
-
-
-\subsection{Assignment nodes}
-
-There is a collection of nodes used to represent assignments.  Each
-assignment statement in the source code becomes a single
-\class{Assign} node in the AST.  The \member{nodes} attribute is a
-list that contains a node for each assignment target.  This is
-necessary because assignment can be chained, e.g. \code{a = b = 2}.
-Each \class{Node} in the list will be one of the following classes: 
-\class{AssAttr}, \class{AssList}, \class{AssName}, or
-\class{AssTuple}. 
-
-Each target assignment node will describe the kind of object being
-assigned to:  \class{AssName} for a simple name, e.g. \code{a = 1}.
-\class{AssAttr} for an attribute assigned, e.g. \code{a.x = 1}.
-\class{AssList} and \class{AssTuple} for list and tuple expansion
-respectively, e.g. \code{a, b, c = a_tuple}.
-
-The target assignment nodes also have a \member{flags} attribute that
-indicates whether the node is being used for assignment or in a delete
-statement.  The \class{AssName} is also used to represent a delete
-statement, e.g. \class{del x}.
-
-When an expression contains several attribute references, an
-assignment or delete statement will contain only one \class{AssAttr}
-node -- for the final attribute reference.  The other attribute
-references will be represented as \class{Getattr} nodes in the
-\member{expr} attribute of the \class{AssAttr} instance.
-
-\subsection{Examples}
-
-This section shows several simple examples of ASTs for Python source
-code.  The examples demonstrate how to use the \function{parse()}
-function, what the repr of an AST looks like, and how to access
-attributes of an AST node.
-
-The first module defines a single function.  Assume it is stored in
-\file{/tmp/doublelib.py}. 
-
-\begin{verbatim}
-"""This is an example module.
-
-This is the docstring.
-"""
-
-def double(x):
-    "Return twice the argument"
-    return x * 2
-\end{verbatim}
-
-In the interactive interpreter session below, I have reformatted the
-long AST reprs for readability.  The AST reprs use unqualified class
-names.  If you want to create an instance from a repr, you must import
-the class names from the \module{compiler.ast} module.
-
-\begin{verbatim}
->>> import compiler
->>> mod = compiler.parseFile("/tmp/doublelib.py")
->>> mod
-Module('This is an example module.\n\nThis is the docstring.\n', 
-       Stmt([Function(None, 'double', ['x'], [], 0,
-                      'Return twice the argument', 
-                      Stmt([Return(Mul((Name('x'), Const(2))))]))]))
->>> from compiler.ast import *
->>> Module('This is an example module.\n\nThis is the docstring.\n', 
-...    Stmt([Function(None, 'double', ['x'], [], 0,
-...                   'Return twice the argument', 
-...                   Stmt([Return(Mul((Name('x'), Const(2))))]))]))
-Module('This is an example module.\n\nThis is the docstring.\n', 
-       Stmt([Function(None, 'double', ['x'], [], 0,
-                      'Return twice the argument', 
-                      Stmt([Return(Mul((Name('x'), Const(2))))]))]))
->>> mod.doc
-'This is an example module.\n\nThis is the docstring.\n'
->>> for node in mod.node.nodes:
-...     print node
-... 
-Function(None, 'double', ['x'], [], 0, 'Return twice the argument',
-         Stmt([Return(Mul((Name('x'), Const(2))))]))
->>> func = mod.node.nodes[0]
->>> func.code
-Stmt([Return(Mul((Name('x'), Const(2))))])
-\end{verbatim}
-
-\section{Using Visitors to Walk ASTs}
-
-\declaremodule{}{compiler.visitor}
-
-The visitor pattern is ...  The \refmodule{compiler} package uses a
-variant on the visitor pattern that takes advantage of Python's
-introspection features to eliminate the need for much of the visitor's
-infrastructure.
-
-The classes being visited do not need to be programmed to accept
-visitors.  The visitor need only define visit methods for classes it
-is specifically interested in; a default visit method can handle the
-rest. 
-
-XXX The magic \method{visit()} method for visitors.
-
-\begin{funcdesc}{walk}{tree, visitor\optional{, verbose}}
-\end{funcdesc}
-
-\begin{classdesc}{ASTVisitor}{}
-
-The \class{ASTVisitor} is responsible for walking over the tree in the
-correct order.  A walk begins with a call to \method{preorder()}.  For
-each node, it checks the \var{visitor} argument to \method{preorder()}
-for a method named `visitNodeType,' where NodeType is the name of the
-node's class, e.g. for a \class{While} node a \method{visitWhile()}
-would be called.  If the method exists, it is called with the node as
-its first argument.
-
-The visitor method for a particular node type can control how child
-nodes are visited during the walk.  The \class{ASTVisitor} modifies
-the visitor argument by adding a visit method to the visitor; this
-method can be used to visit a particular child node.  If no visitor is
-found for a particular node type, the \method{default()} method is
-called. 
-\end{classdesc}
-
-\class{ASTVisitor} objects have the following methods:
-
-XXX describe extra arguments
-
-\begin{methoddesc}{default}{node\optional{, \moreargs}}
-\end{methoddesc}
-
-\begin{methoddesc}{dispatch}{node\optional{, \moreargs}}
-\end{methoddesc}
-
-\begin{methoddesc}{preorder}{tree, visitor}
-\end{methoddesc}
-
-
-\section{Bytecode Generation}
-
-The code generator is a visitor that emits bytecodes.  Each visit method
-can call the \method{emit()} method to emit a new bytecode.  The basic
-code generator is specialized for modules, classes, and functions.  An
-assembler converts that emitted instructions to the low-level bytecode
-format.  It handles things like generator of constant lists of code
-objects and calculation of jump offsets.

Modified: python/branches/p3yk-noslice/Doc/lib/email.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/email.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/email.tex	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
-% Copyright (C) 2001-2006 Python Software Foundation
+% Copyright (C) 2001-2007 Python Software Foundation
 % Author: barry at python.org (Barry Warsaw)
 
 \section{\module{email} ---
@@ -239,7 +239,7 @@
 
 The \module{email} package was originally prototyped as a separate
 library called
-\ulink{\module{mimelib}}{http://mimelib.sf.net/}.
+\ulink{\texttt{mimelib}}{http://mimelib.sf.net/}.
 Changes have been made so that
 method names are more consistent, and some methods or modules have
 either been added or removed.  The semantics of some of the methods

Modified: python/branches/p3yk-noslice/Doc/lib/emailutil.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/emailutil.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/emailutil.tex	Wed Jul 11 15:40:56 2007
@@ -56,7 +56,7 @@
 \code{"Mon, 20 Nov 1995 19:12:08 -0500"}.  If it succeeds in parsing
 the date, \function{parsedate()} returns a 9-tuple that can be passed
 directly to \function{time.mktime()}; otherwise \code{None} will be
-returned.  Note that fields 6, 7, and 8 of the result tuple are not
+returned.  Note that indexes 6, 7, and 8 of the result tuple are not
 usable.
 \end{funcdesc}
 
@@ -70,7 +70,7 @@
 variable for the same timezone; the latter variable follows the
 \POSIX{} standard while this module follows \rfc{2822}.}.  If the input
 string has no timezone, the last element of the tuple returned is
-\code{None}.  Note that fields 6, 7, and 8 of the result tuple are not
+\code{None}.  Note that indexes 6, 7, and 8 of the result tuple are not
 usable.
 \end{funcdesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/lib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/lib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/lib.tex	Wed Jul 11 15:40:56 2007
@@ -146,8 +146,6 @@
 \input{libmhlib}
 \input{libmimetools}
 \input{libmimetypes}
-\input{libmimewriter}
-\input{libmimify}
 \input{libmultifile}
 \input{librfc822}
 
@@ -171,7 +169,6 @@
 \input{xmlsaxutils}
 \input{xmlsaxreader}
 \input{libetree}
-% \input{libxmllib}
 
 \input{fileformats}		% Miscellaneous file formats
 \input{libcsv}
@@ -183,8 +180,6 @@
 \input{libcrypto}               % Cryptographic Services
 \input{libhashlib}
 \input{libhmac}
-\input{libmd5}
-\input{libsha}
 
 % =============
 % FILE & DATABASE STORAGE
@@ -268,7 +263,6 @@
 \input{libpty}
 \input{libfcntl}
 \input{libpipes}
-\input{libposixfile}
 \input{libresource}
 \input{libnis}
 \input{libsyslog}
@@ -283,7 +277,6 @@
 \input{libsubprocess}
 \input{libsocket}
 \input{libsignal}
-\input{libpopen2}
 \input{libasyncore}
 \input{libasynchat}
 
@@ -296,7 +289,6 @@
 \input{liburllib2}
 \input{libhttplib}
 \input{libftplib}
-\input{libgopherlib}
 \input{libpoplib}
 \input{libimaplib}
 \input{libnntplib}
@@ -321,13 +313,11 @@
 
 \input{libmm}                   % Multimedia Services
 \input{libaudioop}
-\input{libimageop}
 \input{libaifc}
 \input{libsunau}
 \input{libwave}
 \input{libchunk}
 \input{libcolorsys}
-\input{librgbimg}
 \input{libimghdr}
 \input{libsndhdr}
 \input{libossaudiodev}
@@ -389,9 +379,6 @@
 \input{custominterp}		% Custom interpreter
 \input{libcode}
 \input{libcodeop}
-\input{librestricted}           % Restricted Execution
-\input{librexec}
-\input{libbastion}
 
 
 \input{modules}			% Importing Modules
@@ -420,7 +407,6 @@
 \input{libpickletools}
 \input{distutils}
 
-\input{compiler}                % compiler package
 \input{libast}
 
 \input{libmisc}                 % Miscellaneous Services
@@ -430,22 +416,9 @@
 % OTHER PLATFORM-SPECIFIC STUFF
 % =============
 
-%\input{libamoeba}              % AMOEBA ONLY
-
-%\input{libstdwin}              % STDWIN ONLY
-
-\input{libsgi}                  % SGI IRIX ONLY
-\input{libal}
-\input{libcd}
-\input{libfl}
-\input{libfm}
-\input{libgl}
-\input{libimgfile}
-\input{libjpeg}
-%\input{libpanel}
-
 \input{libsun}                  % SUNOS ONLY
 \input{libsunaudio}
+% XXX(nnorwitz): the modules below this comment should be kept.
 
 \input{windows}                 % MS Windows ONLY
 \input{libmsilib}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libal.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libal.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,181 +0,0 @@
-\section{\module{al} ---
-         Audio functions on the SGI}
-
-\declaremodule{builtin}{al}
-  \platform{IRIX}
-\modulesynopsis{Audio functions on the SGI.}
-
-
-This module provides access to the audio facilities of the SGI Indy
-and Indigo workstations.  See section 3A of the IRIX man pages for
-details.  You'll need to read those man pages to understand what these
-functions do!  Some of the functions are not available in IRIX
-releases before 4.0.5.  Again, see the manual to check whether a
-specific function is available on your platform.
-
-All functions and methods defined in this module are equivalent to
-the C functions with \samp{AL} prefixed to their name.
-
-Symbolic constants from the C header file \code{<audio.h>} are
-defined in the standard module
-\refmodule[al-constants]{AL}\refstmodindex{AL}, see below.
-
-\warning{The current version of the audio library may dump core
-when bad argument values are passed rather than returning an error
-status.  Unfortunately, since the precise circumstances under which
-this may happen are undocumented and hard to check, the Python
-interface can provide no protection against this kind of problems.
-(One example is specifying an excessive queue size --- there is no
-documented upper limit.)}
-
-The module defines the following functions:
-
-
-\begin{funcdesc}{openport}{name, direction\optional{, config}}
-The name and direction arguments are strings.  The optional
-\var{config} argument is a configuration object as returned by
-\function{newconfig()}.  The return value is an \dfn{audio port
-object}; methods of audio port objects are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{newconfig}{}
-The return value is a new \dfn{audio configuration object}; methods of
-audio configuration objects are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{queryparams}{device}
-The device argument is an integer.  The return value is a list of
-integers containing the data returned by \cfunction{ALqueryparams()}.
-\end{funcdesc}
-
-\begin{funcdesc}{getparams}{device, list}
-The \var{device} argument is an integer.  The list argument is a list
-such as returned by \function{queryparams()}; it is modified in place
-(!).
-\end{funcdesc}
-
-\begin{funcdesc}{setparams}{device, list}
-The \var{device} argument is an integer.  The \var{list} argument is a
-list such as returned by \function{queryparams()}.
-\end{funcdesc}
-
-
-\subsection{Configuration Objects \label{al-config-objects}}
-
-Configuration objects returned by \function{newconfig()} have the
-following methods:
-
-\begin{methoddesc}[audio configuration]{getqueuesize}{}
-Return the queue size.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setqueuesize}{size}
-Set the queue size.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getwidth}{}
-Get the sample width.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setwidth}{width}
-Set the sample width.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getchannels}{}
-Get the channel count.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setchannels}{nchannels}
-Set the channel count.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getsampfmt}{}
-Get the sample format.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setsampfmt}{sampfmt}
-Set the sample format.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getfloatmax}{}
-Get the maximum value for floating sample formats.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setfloatmax}{floatmax}
-Set the maximum value for floating sample formats.
-\end{methoddesc}
-
-
-\subsection{Port Objects \label{al-port-objects}}
-
-Port objects, as returned by \function{openport()}, have the following
-methods:
-
-\begin{methoddesc}[audio port]{closeport}{}
-Close the port.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfd}{}
-Return the file descriptor as an int.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfilled}{}
-Return the number of filled samples.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfillable}{}
-Return the number of fillable samples.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{readsamps}{nsamples}
-Read a number of samples from the queue, blocking if necessary.
-Return the data as a string containing the raw data, (e.g., 2 bytes per
-sample in big-endian byte order (high byte, low byte) if you have set
-the sample width to 2 bytes).
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{writesamps}{samples}
-Write samples into the queue, blocking if necessary.  The samples are
-encoded as described for the \method{readsamps()} return value.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfillpoint}{}
-Return the `fill point'.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{setfillpoint}{fillpoint}
-Set the `fill point'.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getconfig}{}
-Return a configuration object containing the current configuration of
-the port.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{setconfig}{config}
-Set the configuration from the argument, a configuration object.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getstatus}{list}
-Get status information on last error.
-\end{methoddesc}
-
-
-\section{\module{AL} ---
-         Constants used with the \module{al} module}
-
-\declaremodule[al-constants]{standard}{AL}
-  \platform{IRIX}
-\modulesynopsis{Constants used with the \module{al} module.}
-
-
-This module defines symbolic constants needed to use the built-in
-module \refmodule{al} (see above); they are equivalent to those defined
-in the C header file \code{<audio.h>} except that the name prefix
-\samp{AL_} is omitted.  Read the module source for a complete list of
-the defined names.  Suggested use:
-
-\begin{verbatim}
-import al
-from AL import *
-\end{verbatim}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libamoeba.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libamoeba.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,132 +0,0 @@
-\chapter{Amoeba Specific Services}
-
-\section{\module{amoeba} ---
-         Amoeba system support}
-
-\declaremodule{builtin}{amoeba}
-  \platform{Amoeba}
-\modulesynopsis{Functions for the Amoeba operating system.}
-
-
-This module provides some object types and operations useful for
-Amoeba applications.  It is only available on systems that support
-Amoeba operations.  RPC errors and other Amoeba errors are reported as
-the exception \code{amoeba.error = 'amoeba.error'}.
-
-The module \module{amoeba} defines the following items:
-
-\begin{funcdesc}{name_append}{path, cap}
-Stores a capability in the Amoeba directory tree.
-Arguments are the pathname (a string) and the capability (a capability
-object as returned by
-\function{name_lookup()}).
-\end{funcdesc}
-
-\begin{funcdesc}{name_delete}{path}
-Deletes a capability from the Amoeba directory tree.
-Argument is the pathname.
-\end{funcdesc}
-
-\begin{funcdesc}{name_lookup}{path}
-Looks up a capability.
-Argument is the pathname.
-Returns a
-\dfn{capability}
-object, to which various interesting operations apply, described below.
-\end{funcdesc}
-
-\begin{funcdesc}{name_replace}{path, cap}
-Replaces a capability in the Amoeba directory tree.
-Arguments are the pathname and the new capability.
-(This differs from
-\function{name_append()}
-in the behavior when the pathname already exists:
-\function{name_append()}
-finds this an error while
-\function{name_replace()}
-allows it, as its name suggests.)
-\end{funcdesc}
-
-\begin{datadesc}{capv}
-A table representing the capability environment at the time the
-interpreter was started.
-(Alas, modifying this table does not affect the capability environment
-of the interpreter.)
-For example,
-\code{amoeba.capv['ROOT']}
-is the capability of your root directory, similar to
-\code{getcap("ROOT")}
-in C.
-\end{datadesc}
-
-\begin{excdesc}{error}
-The exception raised when an Amoeba function returns an error.
-The value accompanying this exception is a pair containing the numeric
-error code and the corresponding string, as returned by the C function
-\cfunction{err_why()}.
-\end{excdesc}
-
-\begin{funcdesc}{timeout}{msecs}
-Sets the transaction timeout, in milliseconds.
-Returns the previous timeout.
-Initially, the timeout is set to 2 seconds by the Python interpreter.
-\end{funcdesc}
-
-\subsection{Capability Operations}
-
-Capabilities are written in a convenient \ASCII{} format, also used by the
-Amoeba utilities
-\emph{c2a}(U)
-and
-\emph{a2c}(U).
-For example:
-
-\begin{verbatim}
->>> amoeba.name_lookup('/profile/cap')
-aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
->>> 
-\end{verbatim}
-%
-The following methods are defined for capability objects.
-
-\setindexsubitem{(capability method)}
-\begin{funcdesc}{dir_list}{}
-Returns a list of the names of the entries in an Amoeba directory.
-\end{funcdesc}
-
-\begin{funcdesc}{b_read}{offset, maxsize}
-Reads (at most)
-\var{maxsize}
-bytes from a bullet file at offset
-\var{offset.}
-The data is returned as a string.
-EOF is reported as an empty string.
-\end{funcdesc}
-
-\begin{funcdesc}{b_size}{}
-Returns the size of a bullet file.
-\end{funcdesc}
-
-\begin{funcdesc}{dir_append}{}
-\funcline{dir_delete}{}
-\funcline{dir_lookup}{}
-\funcline{dir_replace}{}
-Like the corresponding
-\samp{name_}*
-functions, but with a path relative to the capability.
-(For paths beginning with a slash the capability is ignored, since this
-is the defined semantics for Amoeba.)
-\end{funcdesc}
-
-\begin{funcdesc}{std_info}{}
-Returns the standard info string of the object.
-\end{funcdesc}
-
-\begin{funcdesc}{tod_gettime}{}
-Returns the time (in seconds since the Epoch, in UCT, as for \POSIX) from
-a time server.
-\end{funcdesc}
-
-\begin{funcdesc}{tod_settime}{t}
-Sets the time kept by a time server.
-\end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libasyncore.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libasyncore.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libasyncore.tex	Wed Jul 11 15:40:56 2007
@@ -46,7 +46,7 @@
 \begin{funcdesc}{loop}{\optional{timeout\optional{, use_poll\optional{,
                        map\optional{,count}}}}}
   Enter a polling loop that terminates after count passes or all open
-  channels have been closed.  All arguments are optional.  The \var(count)
+  channels have been closed.  All arguments are optional.  The \var{count}
   parameter defaults to None, resulting in the loop terminating only
   when all channels have been closed.  The \var{timeout} argument sets the
   timeout parameter for the appropriate \function{select()} or

Modified: python/branches/p3yk-noslice/Doc/lib/libatexit.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libatexit.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libatexit.tex	Wed Jul 11 15:40:56 2007
@@ -1,32 +1,21 @@
 \section{\module{atexit} ---
          Exit handlers}
 
-\declaremodule{standard}{atexit}
+\declaremodule{builtin}{atexit}
 \moduleauthor{Skip Montanaro}{skip at mojam.com}
 \sectionauthor{Skip Montanaro}{skip at mojam.com}
 \modulesynopsis{Register and execute cleanup functions.}
 
 \versionadded{2.0}
 
-The \module{atexit} module defines a single function to register
-cleanup functions.  Functions thus registered are automatically
-executed upon normal interpreter termination.
-
-Note: the functions registered via this module are not called when the program is killed by a
-signal, when a Python fatal internal error is detected, or when
-\function{os._exit()} is called.
-
-This is an alternate interface to the functionality provided by the
-\code{sys.exitfunc} variable.
-\withsubitem{(in sys)}{\ttindex{exitfunc}}
-
-Note: This module is unlikely to work correctly when used with other code
-that sets \code{sys.exitfunc}.  In particular, other core Python modules are
-free to use \module{atexit} without the programmer's knowledge.  Authors who
-use \code{sys.exitfunc} should convert their code to use
-\module{atexit} instead.  The simplest way to convert code that sets
-\code{sys.exitfunc} is to import \module{atexit} and register the function
-that had been bound to \code{sys.exitfunc}.
+
+The \module{atexit} module defines functions to register and
+unregister cleanup functions.  Functions thus registered are
+automatically executed upon normal interpreter termination.
+
+Note: the functions registered via this module are not called when
+the program is killed by a signal, when a Python fatal internal
+error is detected, or when \function{os._exit()} is called.
 
 \begin{funcdesc}{register}{func\optional{, *args\optional{, **kargs}}}
 Register \var{func} as a function to be executed at termination.  Any
@@ -47,7 +36,16 @@
 
 \versionchanged[This function now returns \var{func} which makes it
                 possible to use it as a decorator without binding the
-		original name to \code{None}]{2.6}
+                original name to \code{None}]{2.6}
+\end{funcdesc}
+
+\begin{funcdesc}{unregister}{func}
+Remove a function \var{func} from the list of functions to be run at
+interpreter-shutdown.  After calling \function{unregister()},
+\var{func} is guaranteed not to be called when the interpreter
+shuts down.
+
+\versionadded{3.0}
 \end{funcdesc}
 
 

Modified: python/branches/p3yk-noslice/Doc/lib/libbase64.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libbase64.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libbase64.tex	Wed Jul 11 15:40:56 2007
@@ -85,7 +85,7 @@
 letter O (oh), and for optional mapping of the digit 1 (one) to either
 the letter I (eye) or letter L (el).  The optional argument
 \var{map01} when not \code{None}, specifies which letter the digit 1 should
-be mapped to (when map01 is not \var{None}, the digit 0 is always
+be mapped to (when \var{map01} is not \code{None}, the digit 0 is always
 mapped to the letter O).  For security purposes the default is
 \code{None}, so that 0 and 1 are not allowed in the input.
 

Deleted: /python/branches/p3yk-noslice/Doc/lib/libbastion.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libbastion.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,57 +0,0 @@
-\section{\module{Bastion} ---
-         Restricting access to objects}
-
-\declaremodule{standard}{Bastion}
-\modulesynopsis{Providing restricted access to objects.}
-\moduleauthor{Barry Warsaw}{bwarsaw at python.org}
-\versionchanged[Disabled module]{2.3}
-
-\begin{notice}[warning]
-  The documentation has been left in place to help in reading old code
-  that uses the module.
-\end{notice}
-
-% I'm concerned that the word 'bastion' won't be understood by people
-% for whom English is a second language, making the module name
-% somewhat mysterious.  Thus, the brief definition... --amk
-
-According to the dictionary, a bastion is ``a fortified area or
-position'', or ``something that is considered a stronghold.''  It's a
-suitable name for this module, which provides a way to forbid access
-to certain attributes of an object.  It must always be used with the
-\refmodule{rexec} module, in order to allow restricted-mode programs
-access to certain safe attributes of an object, while denying access
-to other, unsafe attributes.
-
-% I've punted on the issue of documenting keyword arguments for now.
-
-\begin{funcdesc}{Bastion}{object\optional{, filter\optional{,
-                          name\optional{, class}}}}
-Protect the object \var{object}, returning a bastion for the
-object.  Any attempt to access one of the object's attributes will
-have to be approved by the \var{filter} function; if the access is
-denied an \exception{AttributeError} exception will be raised.
-
-If present, \var{filter} must be a function that accepts a string
-containing an attribute name, and returns true if access to that
-attribute will be permitted; if \var{filter} returns false, the access
-is denied.  The default filter denies access to any function beginning
-with an underscore (\character{_}).  The bastion's string representation
-will be \samp{<Bastion for \var{name}>} if a value for
-\var{name} is provided; otherwise, \samp{repr(\var{object})} will be
-used.
-
-\var{class}, if present, should be a subclass of \class{BastionClass}; 
-see the code in \file{bastion.py} for the details.  Overriding the
-default \class{BastionClass} will rarely be required.
-\end{funcdesc}
-
-
-\begin{classdesc}{BastionClass}{getfunc, name}
-Class which actually implements bastion objects.  This is the default
-class used by \function{Bastion()}.  The \var{getfunc} parameter is a
-function which returns the value of an attribute which should be
-exposed to the restricted execution environment when called with the
-name of the attribute as the only parameter.  \var{name} is used to
-construct the \function{repr()} of the \class{BastionClass} instance.
-\end{classdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libbsddb.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libbsddb.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libbsddb.tex	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,6 @@
          Interface to Berkeley DB library}
 
 \declaremodule{extension}{bsddb}
-  \platform{Unix, Windows}
 \modulesynopsis{Interface to Berkeley DB database library}
 \sectionauthor{Skip Montanaro}{skip at mojam.com}
 
@@ -46,10 +45,10 @@
 instances.
 
 \begin{funcdesc}{hashopen}{filename\optional{, flag\optional{,
-                           mode\optional{, bsize\optional{,
+                           mode\optional{, pgsize\optional{,
                            ffactor\optional{, nelem\optional{,
-                           cachesize\optional{, hash\optional{,
-                           lorder}}}}}}}}}
+                           cachesize\optional{, lorder\optional{,
+                           hflags}}}}}}}}}
 Open the hash format file named \var{filename}.  Files never intended
 to be preserved on disk may be created by passing \code{None} as the 
 \var{filename}.  The optional
@@ -80,7 +79,7 @@
 
 \begin{funcdesc}{rnopen}{filename\optional{, flag\optional{, mode\optional{,
 rnflags\optional{, cachesize\optional{, pgsize\optional{, lorder\optional{,
-reclen\optional{, bval\optional{, bfname}}}}}}}}}}
+rlen\optional{, delim\optional{, source\optional{, pad}}}}}}}}}}}
 
 Open a DB record format file named \var{filename}.  Files never intended 
 to be preserved on disk may be created by passing \code{None} as the 
@@ -95,14 +94,6 @@
 \end{funcdesc}
 
 
-\begin{notice}
-Beginning in 2.3 some \UNIX{} versions of Python may have a \module{bsddb185}
-module.  This is present \emph{only} to allow backwards compatibility with
-systems which ship with the old Berkeley DB 1.85 database library.  The
-\module{bsddb185} module should never be used directly in new code.
-\end{notice}
-
-
 \begin{seealso}
   \seemodule{dbhash}{DBM-style interface to the \module{bsddb}}
 \end{seealso}
@@ -114,23 +105,23 @@
 the methods listed below.
 \versionchanged[Added dictionary methods]{2.3.1}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[bsddbobject]{close}{}
 Close the underlying file.  The object can no longer be accessed.  Since
 there is no open \method{open} method for these objects, to open the file
 again a new \module{bsddb} module open function must be called.
 \end{methoddesc}
 
-\begin{methoddesc}{keys}{}
+\begin{methoddesc}[bsddbobject]{keys}{}
 Return the list of keys contained in the DB file.  The order of the list is
 unspecified and should not be relied on.  In particular, the order of the
 list returned is different for different file formats.
 \end{methoddesc}
 
-\begin{methoddesc}{has_key}{key}
+\begin{methoddesc}[bsddbobject]{has_key}{key}
 Return \code{1} if the DB file contains the argument as a key.
 \end{methoddesc}
 
-\begin{methoddesc}{set_location}{key}
+\begin{methoddesc}[bsddbobject]{set_location}{key}
 Set the cursor to the item indicated by \var{key} and return a tuple
 containing the key and its value.  For binary tree databases (opened
 using \function{btopen()}), if \var{key} does not actually exist in
@@ -140,32 +131,32 @@
 database.
 \end{methoddesc}
 
-\begin{methoddesc}{first}{}
+\begin{methoddesc}[bsddbobject]{first}{}
 Set the cursor to the first item in the DB file and return it.  The order of 
 keys in the file is unspecified, except in the case of B-Tree databases.
 This method raises \exception{bsddb.error} if the database is empty.
 \end{methoddesc}
 
-\begin{methoddesc}{next}{}
+\begin{methoddesc}[bsddbobject]{next}{}
 Set the cursor to the next item in the DB file and return it.  The order of 
 keys in the file is unspecified, except in the case of B-Tree databases.
 \end{methoddesc}
 
-\begin{methoddesc}{previous}{}
+\begin{methoddesc}[bsddbobject]{previous}{}
 Set the cursor to the previous item in the DB file and return it.  The
 order of keys in the file is unspecified, except in the case of B-Tree
 databases.  This is not supported on hashtable databases (those opened
 with \function{hashopen()}).
 \end{methoddesc}
 
-\begin{methoddesc}{last}{}
+\begin{methoddesc}[bsddbobject]{last}{}
 Set the cursor to the last item in the DB file and return it.  The
 order of keys in the file is unspecified.  This is not supported on
 hashtable databases (those opened with \function{hashopen()}).
 This method raises \exception{bsddb.error} if the database is empty.
 \end{methoddesc}
 
-\begin{methoddesc}{sync}{}
+\begin{methoddesc}[bsddbobject]{sync}{}
 Synchronize the database on disk.
 \end{methoddesc}
 

Deleted: /python/branches/p3yk-noslice/Doc/lib/libcd.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libcd.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,304 +0,0 @@
-\section{\module{cd} ---
-         CD-ROM access on SGI systems}
-
-\declaremodule{builtin}{cd}
-  \platform{IRIX}
-\modulesynopsis{Interface to the CD-ROM on Silicon Graphics systems.}
-
-
-This module provides an interface to the Silicon Graphics CD library.
-It is available only on Silicon Graphics systems.
-
-The way the library works is as follows.  A program opens the CD-ROM
-device with \function{open()} and creates a parser to parse the data
-from the CD with \function{createparser()}.  The object returned by
-\function{open()} can be used to read data from the CD, but also to get
-status information for the CD-ROM device, and to get information about
-the CD, such as the table of contents.  Data from the CD is passed to
-the parser, which parses the frames, and calls any callback
-functions that have previously been added.
-
-An audio CD is divided into \dfn{tracks} or \dfn{programs} (the terms
-are used interchangeably).  Tracks can be subdivided into
-\dfn{indices}.  An audio CD contains a \dfn{table of contents} which
-gives the starts of the tracks on the CD.  Index 0 is usually the
-pause before the start of a track.  The start of the track as given by
-the table of contents is normally the start of index 1.
-
-Positions on a CD can be represented in two ways.  Either a frame
-number or a tuple of three values, minutes, seconds and frames.  Most
-functions use the latter representation.  Positions can be both
-relative to the beginning of the CD, and to the beginning of the
-track.
-
-Module \module{cd} defines the following functions and constants:
-
-
-\begin{funcdesc}{createparser}{}
-Create and return an opaque parser object.  The methods of the parser
-object are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{msftoframe}{minutes, seconds, frames}
-Converts a \code{(\var{minutes}, \var{seconds}, \var{frames})} triple
-representing time in absolute time code into the corresponding CD
-frame number.
-\end{funcdesc}
-
-\begin{funcdesc}{open}{\optional{device\optional{, mode}}}
-Open the CD-ROM device.  The return value is an opaque player object;
-methods of the player object are described below.  The device is the
-name of the SCSI device file, e.g. \code{'/dev/scsi/sc0d4l0'}, or
-\code{None}.  If omitted or \code{None}, the hardware inventory is
-consulted to locate a CD-ROM drive.  The \var{mode}, if not omitted,
-should be the string \code{'r'}.
-\end{funcdesc}
-
-The module defines the following variables:
-
-\begin{excdesc}{error}
-Exception raised on various errors.
-\end{excdesc}
-
-\begin{datadesc}{DATASIZE}
-The size of one frame's worth of audio data.  This is the size of the
-audio data as passed to the callback of type \code{audio}.
-\end{datadesc}
-
-\begin{datadesc}{BLOCKSIZE}
-The size of one uninterpreted frame of audio data.
-\end{datadesc}
-
-The following variables are states as returned by
-\function{getstatus()}:
-
-\begin{datadesc}{READY}
-The drive is ready for operation loaded with an audio CD.
-\end{datadesc}
-
-\begin{datadesc}{NODISC}
-The drive does not have a CD loaded.
-\end{datadesc}
-
-\begin{datadesc}{CDROM}
-The drive is loaded with a CD-ROM.  Subsequent play or read operations
-will return I/O errors.
-\end{datadesc}
-
-\begin{datadesc}{ERROR}
-An error occurred while trying to read the disc or its table of
-contents.
-\end{datadesc}
-
-\begin{datadesc}{PLAYING}
-The drive is in CD player mode playing an audio CD through its audio
-jacks.
-\end{datadesc}
-
-\begin{datadesc}{PAUSED}
-The drive is in CD layer mode with play paused.
-\end{datadesc}
-
-\begin{datadesc}{STILL}
-The equivalent of \constant{PAUSED} on older (non 3301) model Toshiba
-CD-ROM drives.  Such drives have never been shipped by SGI.
-\end{datadesc}
-
-\begin{datadesc}{audio}
-\dataline{pnum}
-\dataline{index}
-\dataline{ptime}
-\dataline{atime}
-\dataline{catalog}
-\dataline{ident}
-\dataline{control}
-Integer constants describing the various types of parser callbacks
-that can be set by the \method{addcallback()} method of CD parser
-objects (see below).
-\end{datadesc}
-
-
-\subsection{Player Objects}
-\label{player-objects}
-
-Player objects (returned by \function{open()}) have the following
-methods:
-
-\begin{methoddesc}[CD player]{allowremoval}{}
-Unlocks the eject button on the CD-ROM drive permitting the user to
-eject the caddy if desired.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{bestreadsize}{}
-Returns the best value to use for the \var{num_frames} parameter of
-the \method{readda()} method.  Best is defined as the value that
-permits a continuous flow of data from the CD-ROM drive.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{close}{}
-Frees the resources associated with the player object.  After calling
-\method{close()}, the methods of the object should no longer be used.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{eject}{}
-Ejects the caddy from the CD-ROM drive.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{getstatus}{}
-Returns information pertaining to the current state of the CD-ROM
-drive.  The returned information is a tuple with the following values:
-\var{state}, \var{track}, \var{rtime}, \var{atime}, \var{ttime},
-\var{first}, \var{last}, \var{scsi_audio}, \var{cur_block}.
-\var{rtime} is the time relative to the start of the current track;
-\var{atime} is the time relative to the beginning of the disc;
-\var{ttime} is the total time on the disc.  For more information on
-the meaning of the values, see the man page \manpage{CDgetstatus}{3dm}.
-The value of \var{state} is one of the following: \constant{ERROR},
-\constant{NODISC}, \constant{READY}, \constant{PLAYING},
-\constant{PAUSED}, \constant{STILL}, or \constant{CDROM}.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{gettrackinfo}{track}
-Returns information about the specified track.  The returned
-information is a tuple consisting of two elements, the start time of
-the track and the duration of the track.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{msftoblock}{min, sec, frame}
-Converts a minutes, seconds, frames triple representing a time in
-absolute time code into the corresponding logical block number for the
-given CD-ROM drive.  You should use \function{msftoframe()} rather than
-\method{msftoblock()} for comparing times.  The logical block number
-differs from the frame number by an offset required by certain CD-ROM
-drives.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{play}{start, play}
-Starts playback of an audio CD in the CD-ROM drive at the specified
-track.  The audio output appears on the CD-ROM drive's headphone and
-audio jacks (if fitted).  Play stops at the end of the disc.
-\var{start} is the number of the track at which to start playing the
-CD; if \var{play} is 0, the CD will be set to an initial paused
-state.  The method \method{togglepause()} can then be used to commence
-play.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{playabs}{minutes, seconds, frames, play}
-Like \method{play()}, except that the start is given in minutes,
-seconds, and frames instead of a track number.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{playtrack}{start, play}
-Like \method{play()}, except that playing stops at the end of the
-track.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{playtrackabs}{track, minutes, seconds, frames, play}
-Like \method{play()}, except that playing begins at the specified
-absolute time and ends at the end of the specified track.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{preventremoval}{}
-Locks the eject button on the CD-ROM drive thus preventing the user
-from arbitrarily ejecting the caddy.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{readda}{num_frames}
-Reads the specified number of frames from an audio CD mounted in the
-CD-ROM drive.  The return value is a string representing the audio
-frames.  This string can be passed unaltered to the
-\method{parseframe()} method of the parser object.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{seek}{minutes, seconds, frames}
-Sets the pointer that indicates the starting point of the next read of
-digital audio data from a CD-ROM.  The pointer is set to an absolute
-time code location specified in \var{minutes}, \var{seconds}, and
-\var{frames}.  The return value is the logical block number to which
-the pointer has been set.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{seekblock}{block}
-Sets the pointer that indicates the starting point of the next read of
-digital audio data from a CD-ROM.  The pointer is set to the specified
-logical block number.  The return value is the logical block number to
-which the pointer has been set.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{seektrack}{track}
-Sets the pointer that indicates the starting point of the next read of
-digital audio data from a CD-ROM.  The pointer is set to the specified
-track.  The return value is the logical block number to which the
-pointer has been set.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{stop}{}
-Stops the current playing operation.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{togglepause}{}
-Pauses the CD if it is playing, and makes it play if it is paused.
-\end{methoddesc}
-
-
-\subsection{Parser Objects}
-\label{cd-parser-objects}
-
-Parser objects (returned by \function{createparser()}) have the
-following methods:
-
-\begin{methoddesc}[CD parser]{addcallback}{type, func, arg}
-Adds a callback for the parser.  The parser has callbacks for eight
-different types of data in the digital audio data stream.  Constants
-for these types are defined at the \module{cd} module level (see above).
-The callback is called as follows: \code{\var{func}(\var{arg}, type,
-data)}, where \var{arg} is the user supplied argument, \var{type} is
-the particular type of callback, and \var{data} is the data returned
-for this \var{type} of callback.  The type of the data depends on the
-\var{type} of callback as follows:
-
-\begin{tableii}{l|p{4in}}{code}{Type}{Value}
-  \lineii{audio}{String which can be passed unmodified to
-\function{al.writesamps()}.}
-  \lineii{pnum}{Integer giving the program (track) number.}
-  \lineii{index}{Integer giving the index number.}
-  \lineii{ptime}{Tuple consisting of the program time in minutes,
-seconds, and frames.}
-  \lineii{atime}{Tuple consisting of the absolute time in minutes,
-seconds, and frames.}
-  \lineii{catalog}{String of 13 characters, giving the catalog number
-of the CD.}
-  \lineii{ident}{String of 12 characters, giving the ISRC
-identification number of the recording.  The string consists of two
-characters country code, three characters owner code, two characters
-giving the year, and five characters giving a serial number.}
-  \lineii{control}{Integer giving the control bits from the CD
-subcode data}
-\end{tableii}
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{deleteparser}{}
-Deletes the parser and frees the memory it was using.  The object
-should not be used after this call.  This call is done automatically
-when the last reference to the object is removed.
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{parseframe}{frame}
-Parses one or more frames of digital audio data from a CD such as
-returned by \method{readda()}.  It determines which subcodes are
-present in the data.  If these subcodes have changed since the last
-frame, then \method{parseframe()} executes a callback of the
-appropriate type passing to it the subcode data found in the frame.
-Unlike the \C{} function, more than one frame of digital audio data
-can be passed to this method.
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{removecallback}{type}
-Removes the callback for the given \var{type}.
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{resetparser}{}
-Resets the fields of the parser used for tracking subcodes to an
-initial state.  \method{resetparser()} should be called after the disc
-has been changed.
-\end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libcfgparser.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcfgparser.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcfgparser.tex	Wed Jul 11 15:40:56 2007
@@ -155,37 +155,37 @@
 
 \class{RawConfigParser} instances have the following methods:
 
-\begin{methoddesc}{defaults}{}
+\begin{methoddesc}[RawConfigParser]{defaults}{}
 Return a dictionary containing the instance-wide defaults.
 \end{methoddesc}
 
-\begin{methoddesc}{sections}{}
+\begin{methoddesc}[RawConfigParser]{sections}{}
 Return a list of the sections available; \code{DEFAULT} is not
 included in the list.
 \end{methoddesc}
 
-\begin{methoddesc}{add_section}{section}
+\begin{methoddesc}[RawConfigParser]{add_section}{section}
 Add a section named \var{section} to the instance.  If a section by
 the given name already exists, \exception{DuplicateSectionError} is
 raised.
 \end{methoddesc}
 
-\begin{methoddesc}{has_section}{section}
+\begin{methoddesc}[RawConfigParser]{has_section}{section}
 Indicates whether the named section is present in the
 configuration. The \code{DEFAULT} section is not acknowledged.
 \end{methoddesc}
 
-\begin{methoddesc}{options}{section}
+\begin{methoddesc}[RawConfigParser]{options}{section}
 Returns a list of options available in the specified \var{section}.
 \end{methoddesc}
 
-\begin{methoddesc}{has_option}{section, option}
+\begin{methoddesc}[RawConfigParser]{has_option}{section, option}
 If the given section exists, and contains the given option,
 return \constant{True}; otherwise return \constant{False}.
 \versionadded{1.6}
 \end{methoddesc}
 
-\begin{methoddesc}{read}{filenames}
+\begin{methoddesc}[RawConfigParser]{read}{filenames}
 Attempt to read and parse a list of filenames, returning a list of filenames
 which were successfully parsed.  If \var{filenames} is a string or
 Unicode string, it is treated as a single filename.
@@ -210,28 +210,28 @@
 \versionchanged[Returns list of successfully parsed filenames]{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{readfp}{fp\optional{, filename}}
+\begin{methoddesc}[RawConfigParser]{readfp}{fp\optional{, filename}}
 Read and parse configuration data from the file or file-like object in
 \var{fp} (only the \method{readline()} method is used).  If
 \var{filename} is omitted and \var{fp} has a \member{name} attribute,
 that is used for \var{filename}; the default is \samp{<???>}.
 \end{methoddesc}
 
-\begin{methoddesc}{get}{section, option}
+\begin{methoddesc}[RawConfigParser]{get}{section, option}
 Get an \var{option} value for the named \var{section}.
 \end{methoddesc}
 
-\begin{methoddesc}{getint}{section, option}
+\begin{methoddesc}[RawConfigParser]{getint}{section, option}
 A convenience method which coerces the \var{option} in the specified
 \var{section} to an integer.
 \end{methoddesc}
 
-\begin{methoddesc}{getfloat}{section, option}
+\begin{methoddesc}[RawConfigParser]{getfloat}{section, option}
 A convenience method which coerces the \var{option} in the specified
 \var{section} to a floating point number.
 \end{methoddesc}
 
-\begin{methoddesc}{getboolean}{section, option}
+\begin{methoddesc}[RawConfigParser]{getboolean}{section, option}
 A convenience method which coerces the \var{option} in the specified
 \var{section} to a Boolean value.  Note that the accepted values
 for the option are \code{"1"}, \code{"yes"}, \code{"true"}, and \code{"on"},
@@ -241,12 +241,12 @@
 cause it to raise \exception{ValueError}.
 \end{methoddesc}
 
-\begin{methoddesc}{items}{section}
+\begin{methoddesc}[RawConfigParser]{items}{section}
 Return a list of \code{(\var{name}, \var{value})} pairs for each
 option in the given \var{section}.
 \end{methoddesc}
 
-\begin{methoddesc}{set}{section, option, value}
+\begin{methoddesc}[RawConfigParser]{set}{section, option, value}
 If the given section exists, set the given option to the specified
 value; otherwise raise \exception{NoSectionError}.  While it is
 possible to use \class{RawConfigParser} (or \class{ConfigParser} with
@@ -256,14 +256,14 @@
 \versionadded{1.6}
 \end{methoddesc}
 
-\begin{methoddesc}{write}{fileobject}
+\begin{methoddesc}[RawConfigParser]{write}{fileobject}
 Write a representation of the configuration to the specified file
 object.  This representation can be parsed by a future \method{read()}
 call.
 \versionadded{1.6}
 \end{methoddesc}
 
-\begin{methoddesc}{remove_option}{section, option}
+\begin{methoddesc}[RawConfigParser]{remove_option}{section, option}
 Remove the specified \var{option} from the specified \var{section}.
 If the section does not exist, raise \exception{NoSectionError}. 
 If the option existed to be removed, return \constant{True};
@@ -271,13 +271,13 @@
 \versionadded{1.6}
 \end{methoddesc}
 
-\begin{methoddesc}{remove_section}{section}
+\begin{methoddesc}[RawConfigParser]{remove_section}{section}
 Remove the specified \var{section} from the configuration.
 If the section in fact existed, return \code{True}.
 Otherwise return \code{False}.
 \end{methoddesc}
 
-\begin{methoddesc}{optionxform}{option}
+\begin{methoddesc}[RawConfigParser]{optionxform}{option}
 Transforms the option name \var{option} as found in an input file or
 as passed in by  client code to the form that should be used in the
 internal structures.  The default implementation returns a lower-case
@@ -293,14 +293,14 @@
 The \class{ConfigParser} class extends some methods of the
 \class{RawConfigParser} interface, adding some optional arguments.
 
-\begin{methoddesc}{get}{section, option\optional{, raw\optional{, vars}}}
+\begin{methoddesc}[ConfigParser]{get}{section, option\optional{, raw\optional{, vars}}}
 Get an \var{option} value for the named \var{section}.  All the
 \character{\%} interpolations are expanded in the return values, based
 on the defaults passed into the constructor, as well as the options
 \var{vars} provided, unless the \var{raw} argument is true.
 \end{methoddesc}
 
-\begin{methoddesc}{items}{section\optional{, raw\optional{, vars}}}
+\begin{methoddesc}[ConfigParser]{items}{section\optional{, raw\optional{, vars}}}
 Return a list of \code{(\var{name}, \var{value})} pairs for each
 option in the given \var{section}. Optional arguments have the
 same meaning as for the \method{get()} method.
@@ -313,7 +313,7 @@
 The \class{SafeConfigParser} class implements the same extended
 interface as \class{ConfigParser}, with the following addition:
 
-\begin{methoddesc}{set}{section, option, value}
+\begin{methoddesc}[SafeConfigParser]{set}{section, option, value}
 If the given section exists, set the given option to the specified
 value; otherwise raise \exception{NoSectionError}.  \var{value} must
 be a string (\class{str} or \class{unicode}); if not,

Modified: python/branches/p3yk-noslice/Doc/lib/libcgitb.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcgitb.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcgitb.tex	Wed Jul 11 15:40:56 2007
@@ -38,7 +38,7 @@
                          context\optional{, format}}}}}
   This function causes the \module{cgitb} module to take over the
   interpreter's default handling for exceptions by setting the
-  value of \code{\refmodule{sys}.excepthook}.
+  value of \member{\refmodule{sys}.excepthook}.
   \withsubitem{(in module sys)}{\ttindex{excepthook()}}
 
   The optional argument \var{display} defaults to \code{1} and can be set
@@ -61,7 +61,7 @@
   report it using \module{cgitb}.  The optional \var{info} argument
   should be a 3-tuple containing an exception type, exception
   value, and traceback object, exactly like the tuple returned by
-  \code{\refmodule{sys}.exc_info()}.  If the \var{info} argument
+  \function{\refmodule{sys}.exc_info()}.  If the \var{info} argument
   is not supplied, the current exception is obtained from
-  \code{\refmodule{sys}.exc_info()}.
+  \function{\refmodule{sys}.exc_info()}.
 \end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libcmath.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcmath.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcmath.tex	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,14 @@
 \modulesynopsis{Mathematical functions for complex numbers.}
 
 This module is always available.  It provides access to mathematical
-functions for complex numbers.  The functions are:
+functions for complex numbers.  The functions in this module accept
+integers, floating-point numbers or complex numbers as arguments.
+They will also accept any Python object that has either a
+\method{__complex__} or a \method{__float__} method: these methods are
+used to convert the object to a complex or floating-point number, respectively, and
+the function is then applied to the result of the conversion.
+
+The functions are:
 
 \begin{funcdesc}{acos}{x}
 Return the arc cosine of \var{x}.

Modified: python/branches/p3yk-noslice/Doc/lib/libcmd.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcmd.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcmd.tex	Wed Jul 11 15:40:56 2007
@@ -37,7 +37,7 @@
 
 A \class{Cmd} instance has the following methods:
 
-\begin{methoddesc}{cmdloop}{\optional{intro}}
+\begin{methoddesc}[Cmd]{cmdloop}{\optional{intro}}
 Repeatedly issue a prompt, accept input, parse an initial prefix off
 the received input, and dispatch to action methods, passing them the
 remainder of the line as argument.
@@ -82,7 +82,7 @@
 any undocumented commands.
 \end{methoddesc}
 
-\begin{methoddesc}{onecmd}{str}
+\begin{methoddesc}[Cmd]{onecmd}{str}
 Interpret the argument as though it had been typed in response to the
 prompt.  This may be overridden, but should not normally need to be;
 see the \method{precmd()} and \method{postcmd()} methods for useful
@@ -93,25 +93,25 @@
 \method{default()} method is returned.
 \end{methoddesc}
 
-\begin{methoddesc}{emptyline}{}
+\begin{methoddesc}[Cmd]{emptyline}{}
 Method called when an empty line is entered in response to the prompt.
 If this method is not overridden, it repeats the last nonempty command
 entered.  
 \end{methoddesc}
 
-\begin{methoddesc}{default}{line}
+\begin{methoddesc}[Cmd]{default}{line}
 Method called on an input line when the command prefix is not
 recognized. If this method is not overridden, it prints an
 error message and returns.
 \end{methoddesc}
 
-\begin{methoddesc}{completedefault}{text, line, begidx, endidx}
+\begin{methoddesc}[Cmd]{completedefault}{text, line, begidx, endidx}
 Method called to complete an input line when no command-specific
 \method{complete_*()} method is available.  By default, it returns an
 empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{precmd}{line}
+\begin{methoddesc}[Cmd]{precmd}{line}
 Hook method executed just before the command line \var{line} is
 interpreted, but after the input prompt is generated and issued.  This
 method is a stub in \class{Cmd}; it exists to be overridden by
@@ -121,7 +121,7 @@
 unchanged.
 \end{methoddesc}
 
-\begin{methoddesc}{postcmd}{stop, line}
+\begin{methoddesc}[Cmd]{postcmd}{stop, line}
 Hook method executed just after a command dispatch is finished.  This
 method is a stub in \class{Cmd}; it exists to be overridden by
 subclasses.  \var{line} is the command line which was executed, and
@@ -133,13 +133,13 @@
 to continue.
 \end{methoddesc}
 
-\begin{methoddesc}{preloop}{}
+\begin{methoddesc}[Cmd]{preloop}{}
 Hook method executed once when \method{cmdloop()} is called.  This
 method is a stub in \class{Cmd}; it exists to be overridden by
 subclasses.
 \end{methoddesc}
 
-\begin{methoddesc}{postloop}{}
+\begin{methoddesc}[Cmd]{postloop}{}
 Hook method executed once when \method{cmdloop()} is about to return.
 This method is a stub in \class{Cmd}; it exists to be overridden by
 subclasses.
@@ -147,42 +147,52 @@
 
 Instances of \class{Cmd} subclasses have some public instance variables:
 
-\begin{memberdesc}{prompt}
+\begin{memberdesc}[Cmd]{prompt}
 The prompt issued to solicit input.
 \end{memberdesc}
 
-\begin{memberdesc}{identchars}
+\begin{memberdesc}[Cmd]{identchars}
 The string of characters accepted for the command prefix.
 \end{memberdesc}
 
-\begin{memberdesc}{lastcmd}
+\begin{memberdesc}[Cmd]{lastcmd}
 The last nonempty command prefix seen. 
 \end{memberdesc}
 
-\begin{memberdesc}{intro}
+\begin{memberdesc}[Cmd]{intro}
 A string to issue as an intro or banner.  May be overridden by giving
 the \method{cmdloop()} method an argument.
 \end{memberdesc}
 
-\begin{memberdesc}{doc_header}
+\begin{memberdesc}[Cmd]{doc_header}
 The header to issue if the help output has a section for documented
 commands.
 \end{memberdesc}
 
-\begin{memberdesc}{misc_header}
+\begin{memberdesc}[Cmd]{misc_header}
 The header to issue if the help output has a section for miscellaneous 
 help topics (that is, there are \method{help_*()} methods without
 corresponding \method{do_*()} methods).
 \end{memberdesc}
 
-\begin{memberdesc}{undoc_header}
+\begin{memberdesc}[Cmd]{undoc_header}
 The header to issue if the help output has a section for undocumented 
 commands (that is, there are \method{do_*()} methods without
 corresponding \method{help_*()} methods).
 \end{memberdesc}
 
-\begin{memberdesc}{ruler}
+\begin{memberdesc}[Cmd]{ruler}
 The character used to draw separator lines under the help-message
 headers.  If empty, no ruler line is drawn.  It defaults to
 \character{=}.
 \end{memberdesc}
+
+\begin{memberdesc}[Cmd]{use_rawinput}
+A flag, defaulting to true.  If true, \method{cmdloop()} uses
+\function{input()} to display a prompt and read the next command;
+if false, \method{sys.stdout.write()} and
+\method{sys.stdin.readline()} are used. (This means that by
+importing \refmodule{readline}, on systems that support it, the
+interpreter will automatically support \program{Emacs}-like line editing 
+and command-history keystrokes.)
+\end{memberdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libcode.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcode.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcode.tex	Wed Jul 11 15:40:56 2007
@@ -68,7 +68,7 @@
 \subsection{Interactive Interpreter Objects
             \label{interpreter-objects}}
 
-\begin{methoddesc}{runsource}{source\optional{, filename\optional{, symbol}}}
+\begin{methoddesc}[InteractiveInterpreter]{runsource}{source\optional{, filename\optional{, symbol}}}
 Compile and run some source in the interpreter.
 Arguments are the same as for \function{compile_command()}; the
 default for \var{filename} is \code{'<input>'}, and for
@@ -98,7 +98,7 @@
 \code{sys.ps1} or \code{sys.ps2} to prompt the next line.
 \end{methoddesc}
 
-\begin{methoddesc}{runcode}{code}
+\begin{methoddesc}[InteractiveInterpreter]{runcode}{code}
 Execute a code object.
 When an exception occurs, \method{showtraceback()} is called to
 display a traceback.  All exceptions are caught except
@@ -109,7 +109,7 @@
 should be prepared to deal with it.
 \end{methoddesc}
 
-\begin{methoddesc}{showsyntaxerror}{\optional{filename}}
+\begin{methoddesc}[InteractiveInterpreter]{showsyntaxerror}{\optional{filename}}
 Display the syntax error that just occurred.  This does not display
 a stack trace because there isn't one for syntax errors.
 If \var{filename} is given, it is stuffed into the exception instead
@@ -118,13 +118,13 @@
 The output is written by the \method{write()} method.
 \end{methoddesc}
 
-\begin{methoddesc}{showtraceback}{}
+\begin{methoddesc}[InteractiveInterpreter]{showtraceback}{}
 Display the exception that just occurred.  We remove the first stack
 item because it is within the interpreter object implementation.
 The output is written by the \method{write()} method.
 \end{methoddesc}
 
-\begin{methoddesc}{write}{data}
+\begin{methoddesc}[InteractiveInterpreter]{write}{data}
 Write a string to the standard error stream (\code{sys.stderr}).
 Derived classes should override this to provide the appropriate output
 handling as needed.
@@ -138,7 +138,7 @@
 \class{InteractiveInterpreter}, and so offers all the methods of the
 interpreter objects as well as the following additions.
 
-\begin{methoddesc}{interact}{\optional{banner}}
+\begin{methoddesc}[InteractiveConsole]{interact}{\optional{banner}}
 Closely emulate the interactive Python console.
 The optional banner argument specify the banner to print before the
 first interaction; by default it prints a banner similar to the one
@@ -147,7 +147,7 @@
 with the real interpreter -- since it's so close!).
 \end{methoddesc}
 
-\begin{methoddesc}{push}{line}
+\begin{methoddesc}[InteractiveConsole]{push}{line}
 Push a line of source text to the interpreter.
 The line should not have a trailing newline; it may have internal
 newlines.  The line is appended to a buffer and the interpreter's
@@ -160,11 +160,11 @@
 \method{runsource()}).
 \end{methoddesc}
 
-\begin{methoddesc}{resetbuffer}{}
+\begin{methoddesc}[InteractiveConsole]{resetbuffer}{}
 Remove any unhandled source text from the input buffer.
 \end{methoddesc}
 
-\begin{methoddesc}{raw_input}{\optional{prompt}}
+\begin{methoddesc}[InteractiveConsole]{raw_input}{\optional{prompt}}
 Write a prompt and read a line.  The returned line does not include
 the trailing newline.  When the user enters the \EOF{} key sequence,
 \exception{EOFError} is raised.  The base implementation reads from

Modified: python/branches/p3yk-noslice/Doc/lib/libcodecs.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcodecs.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcodecs.tex	Wed Jul 11 15:40:56 2007
@@ -237,7 +237,7 @@
 \begin{funcdesc}{iterdecode}{iterable, encoding\optional{, errors}}
 Uses an incremental decoder to iteratively decode the input provided by
 \var{iterable}. This function is a generator. \var{errors} (as well as
-any other keyword argument) is passed through to the incremental encoder.
+any other keyword argument) is passed through to the incremental decoder.
 \versionadded{2.5}
 \end{funcdesc}
 
@@ -307,7 +307,7 @@
 The \class{Codec} class defines these methods which also define the
 function interfaces of the stateless encoder and decoder:
 
-\begin{methoddesc}{encode}{input\optional{, errors}}
+\begin{methoddesc}[Codec]{encode}{input\optional{, errors}}
   Encodes the object \var{input} and returns a tuple (output object,
   length consumed).  While codecs are not restricted to use with Unicode, in
   a Unicode context, encoding converts a Unicode object to a plain string
@@ -325,7 +325,7 @@
   empty object of the output object type in this situation.
 \end{methoddesc}
 
-\begin{methoddesc}{decode}{input\optional{, errors}}
+\begin{methoddesc}[Codec]{decode}{input\optional{, errors}}
   Decodes the object \var{input} and returns a tuple (output object,
   length consumed).  In a Unicode context, decoding converts a plain string
   encoded using a particular character set encoding to a Unicode object.
@@ -405,6 +405,21 @@
   Reset the encoder to the initial state.
 \end{methoddesc}
 
+\begin{methoddesc}{getstate}{}
+  Return the current state of the encoder which must be an integer.
+  The implementation should make sure that \code{0} is the most common state.
+  (States that are more complicated than integers can be converted into an
+  integer by marshaling/pickling the state and encoding the bytes of the
+  resulting string into an integer).
+  \versionadded{3.0}
+\end{methoddesc}
+
+\begin{methoddesc}{setstate}{state}
+  Set the state of the encoder to \var{state}. \var{state} must be an
+  encoder state returned by \method{getstate}.
+  \versionadded{3.0}
+\end{methoddesc}
+
 
 \subsubsection{IncrementalDecoder Objects \label{incremental-decoder-objects}}
 
@@ -453,6 +468,27 @@
   Reset the decoder to the initial state.
 \end{methoddesc}
 
+\begin{methoddesc}{getstate}{}
+  Return the current state of the decoder. This must be a tuple with two
+  items, the first must be the buffer containing the still undecoded input.
+  The second must be an integer and can be additional state info.
+  (The implementation should make sure that \code{0} is the most common
+  additional state info.) If this additional state info is \code{0} it must
+  be possible to set the decoder to the state which has no input buffered
+  and \code{0} as the additional state info, so that feeding the previously
+  buffered input to the decoder returns it to the previous state without
+  producing any output. (Additional state info that is more complicated
+  than integers can be converted into an integer by marshaling/pickling
+  the info and encoding the bytes of the resulting string into an integer.)
+  \versionadded{3.0}
+\end{methoddesc}
+
+\begin{methoddesc}{setstate}{state}
+  Set the state of the encoder to \var{state}. \var{state} must be a
+  decoder state returned by \method{getstate}.
+  \versionadded{3.0}
+\end{methoddesc}
+
 
 The \class{StreamWriter} and \class{StreamReader} classes provide
 generic working interfaces which can be used to implement new
@@ -1197,9 +1233,8 @@
 \lineiv{idna}
          {}
          {Unicode string}
-         {Implements \rfc{3490}.
-          \versionadded{2.3}
-          See also \refmodule{encodings.idna}}
+         {Implements \rfc{3490},
+          see also \refmodule{encodings.idna}}
 
 \lineiv{mbcs}
          {dbcs}
@@ -1214,8 +1249,7 @@
 \lineiv{punycode}
          {}
          {Unicode string}
-         {Implements \rfc{3492}.
-          \versionadded{2.3}}
+         {Implements \rfc{3492}}
 
 \lineiv{quopri_codec}
          {quopri, quoted-printable, quotedprintable}
@@ -1269,6 +1303,8 @@
 
 \end{tableiv}
 
+\versionadded[The \code{idna} and \code{punycode} encodings]{2.3}
+
 \subsection{\module{encodings.idna} ---
             Internationalized Domain Names in Applications}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libcollections.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcollections.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcollections.tex	Wed Jul 11 15:40:56 2007
@@ -9,14 +9,16 @@
 
 
 This module implements high-performance container datatypes.  Currently,
-there are two datatypes, deque and defaultdict.
+there are two datatypes, deque and defaultdict, and one datatype factory
+function, \function{NamedTuple}.
 Future additions may include balanced trees and ordered dictionaries.
 \versionchanged[Added defaultdict]{2.5}
+\versionchanged[Added NamedTuple]{2.6}
 
 \subsection{\class{deque} objects \label{deque-objects}}
 
-\begin{funcdesc}{deque}{\optional{iterable}}
-  Returns a new deque objected initialized left-to-right (using
+\begin{classdesc}{deque}{\optional{iterable}}
+  Returns a new deque object initialized left-to-right (using
   \method{append()}) with data from \var{iterable}.  If \var{iterable}
   is not specified, the new deque is empty.
 
@@ -30,7 +32,7 @@
   for \samp{pop(0)} and \samp{insert(0, v)} operations which change both the
   size and position of the underlying data representation.
   \versionadded{2.4}
-\end{funcdesc}
+\end{classdesc}
 
 Deque objects support the following methods:
 
@@ -174,7 +176,7 @@
     while pending:
         task = pending.popleft()
         try:
-            yield task.next()
+            yield next(task)
         except StopIteration:
             continue
         pending.append(task)
@@ -219,7 +221,7 @@
 
 \subsection{\class{defaultdict} objects \label{defaultdict-objects}}
 
-\begin{funcdesc}{defaultdict}{\optional{default_factory\optional{, ...}}}
+\begin{classdesc}{defaultdict}{\optional{default_factory\optional{, ...}}}
   Returns a new dictionary-like object.  \class{defaultdict} is a subclass
   of the builtin \class{dict} class.  It overrides one method and adds one
   writable instance variable.  The remaining functionality is the same as
@@ -231,7 +233,7 @@
   passed to the \class{dict} constructor, including keyword arguments.
 
  \versionadded{2.5}
-\end{funcdesc}
+\end{classdesc}
 
 \class{defaultdict} objects support the following method in addition to
 the standard \class{dict} operations:
@@ -254,11 +256,11 @@
 
 \class{defaultdict} objects support the following instance variable:
 
-\begin{datadesc}{default_factory}
+\begin{memberdesc}{default_factory}
   This attribute is used by the \method{__missing__} method; it is initialized
   from the first argument to the constructor, if present, or to \code{None}, 
   if absent.
-\end{datadesc}
+\end{memberdesc}
 
 
 \subsubsection{\class{defaultdict} Examples \label{defaultdict-examples}}
@@ -315,12 +317,12 @@
 
 The function \function{int()} which always returns zero is just a special
 case of constant functions.  A faster and more flexible way to create
-constant functions is to use \function{itertools.repeat()} which can supply
+constant functions is to use a lambda function which can supply
 any constant value (not just zero):
 
 \begin{verbatim}
 >>> def constant_factory(value):
-...     return itertools.repeat(value).next
+...     return lambda: value
 >>> d = defaultdict(constant_factory('<missing>'))
 >>> d.update(name='John', action='ran')
 >>> '%(name)s %(action)s to %(object)s' % d
@@ -339,3 +341,62 @@
 >>> d.items()
 [('blue', set([2, 4])), ('red', set([1, 3]))]
 \end{verbatim}
+
+
+
+\subsection{\function{NamedTuple} datatype factory function \label{named-tuple-factory}}
+
+\begin{funcdesc}{NamedTuple}{typename, fieldnames}
+  Returns a new tuple subclass named \var{typename}.  The new subclass is used
+  to create tuple-like objects that have fields accessable by attribute
+  lookup as well as being indexable and iterable.  Instances of the subclass
+  also have a helpful docstring (with typename and fieldnames) and a helpful
+  \method{__repr__()} method which lists the tuple contents in a \code{name=value}
+  format.
+  \versionadded{2.6}
+
+  The \var{fieldnames} are specified in a single string and are separated by spaces.
+  Any valid Python identifier may be used for a field name.
+
+  Example:
+  \begin{verbatim}
+>>> Point = NamedTuple('Point', 'x y')
+>>> Point.__doc__           # docstring for the new datatype
+'Point(x, y)'
+>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
+>>> p[0] + p[1]             # works just like the tuple (11, 22)
+33
+>>> x, y = p                # unpacks just like a tuple
+>>> x, y
+(11, 22)
+>>> p.x + p.y               # fields also accessable by name
+33
+>>> p                       # readable __repr__ with name=value style
+Point(x=11, y=22)  
+\end{verbatim}
+
+  The use cases are the same as those for tuples.  The named factories
+  assign meaning to each tuple position and allow for more readable,
+  self-documenting code.  Named tuples can also be used to assign field names 
+  to tuples returned by the \module{csv} or \module{sqlite3} modules.
+  For example:
+
+  \begin{verbatim}
+from itertools import starmap
+import csv
+EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade')
+for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
+    print record
+\end{verbatim}
+
+  To cast an individual record stored as \class{list}, \class{tuple}, or some other
+  iterable type, use the star-operator to unpack the values:
+
+  \begin{verbatim}
+>>> Color = NamedTuple('Color', 'name code')
+>>> m = dict(red=1, green=2, blue=3)
+>>> print Color(*m.popitem())
+Color(name='blue', code=3)
+\end{verbatim}
+
+\end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libcommands.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcommands.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcommands.tex	Wed Jul 11 15:40:56 2007
@@ -35,12 +35,6 @@
 and the return value is a string containing the command's output.  
 \end{funcdesc}
 
-\begin{funcdesc}{getstatus}{file}
-Return the output of \samp{ls -ld \var{file}} as a string.  This
-function uses the \function{getoutput()} function, and properly
-escapes backslashes and dollar signs in the argument.
-\end{funcdesc}
-
 Example:
 
 \begin{verbatim}
@@ -53,8 +47,6 @@
 (256, 'sh: /bin/junk: not found')
 >>> commands.getoutput('ls /bin/ls')
 '/bin/ls'
->>> commands.getstatus('/bin/ls')
-'-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls'
 \end{verbatim}
 
 \begin{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/libconsts.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libconsts.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libconsts.tex	Wed Jul 11 15:40:56 2007
@@ -13,7 +13,7 @@
 \end{datadesc}
 
 \begin{datadesc}{None}
-  The sole value of \code{\refmodule{types}.NoneType}.  \code{None} is
+  The sole value of \member{\refmodule{types}.NoneType}.  \code{None} is
   frequently used to represent the absence of a value, as when default
   arguments are not passed to a function.
 \end{datadesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libcontextlib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcontextlib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcontextlib.tex	Wed Jul 11 15:40:56 2007
@@ -111,7 +111,7 @@
 \begin{verbatim}
 from __future__ import with_statement
 from contextlib import closing
-import codecs
+import urllib
 
 with closing(urllib.urlopen('http://www.python.org')) as page:
     for line in page:

Modified: python/branches/p3yk-noslice/Doc/lib/libcookielib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcookielib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcookielib.tex	Wed Jul 11 15:40:56 2007
@@ -292,12 +292,12 @@
 
 \class{FileCookieJar} instances have the following public attributes:
 
-\begin{memberdesc}{filename}
+\begin{memberdesc}[FileCookieJar]{filename}
 Filename of default file in which to keep cookies.  This attribute may
 be assigned to.
 \end{memberdesc}
 
-\begin{memberdesc}{delayload}
+\begin{memberdesc}[FileCookieJar]{delayload}
 If true, load cookies lazily from disk.  This attribute should not be
 assigned to.  This is only a hint, since this only affects
 performance, not behaviour (unless the cookies on disk are changing).
@@ -400,13 +400,13 @@
 attributes, indicating which protocols should be used, and how.  All
 of these attributes may be assigned to.
 
-\begin{memberdesc}{netscape}
+\begin{memberdesc}[CookiePolicy]{netscape}
 Implement Netscape protocol.
 \end{memberdesc}
-\begin{memberdesc}{rfc2965}
+\begin{memberdesc}[CookiePolicy]{rfc2965}
 Implement RFC 2965 protocol.
 \end{memberdesc}
-\begin{memberdesc}{hide_cookie2}
+\begin{memberdesc}[CookiePolicy]{hide_cookie2}
 Don't add \mailheader{Cookie2} header to requests (the presence of
 this header indicates to the server that we understand RFC 2965
 cookies).
@@ -504,7 +504,7 @@
 which are all initialised from the constructor arguments of the same
 name, and which may all be assigned to.
 
-\begin{memberdesc}{rfc2109_as_netscape}
+\begin{memberdesc}[DefaultCookiePolicy]{rfc2109_as_netscape}
 If true, request that the \class{CookieJar} instance downgrade RFC
 2109 cookies (ie. cookies received in a \mailheader{Set-Cookie} header
 with a version cookie-attribute of 1) to Netscape cookies by setting
@@ -517,7 +517,7 @@
 
 General strictness switches:
 
-\begin{memberdesc}{strict_domain}
+\begin{memberdesc}[DefaultCookiePolicy]{strict_domain}
 Don't allow sites to set two-component domains with country-code
 top-level domains like \code{.co.uk}, \code{.gov.uk},
 \code{.co.nz}.etc.  This is far from perfect and isn't guaranteed to
@@ -526,7 +526,7 @@
 
 RFC 2965 protocol strictness switches:
 
-\begin{memberdesc}{strict_rfc2965_unverifiable}
+\begin{memberdesc}[DefaultCookiePolicy]{strict_rfc2965_unverifiable}
 Follow RFC 2965 rules on unverifiable transactions (usually, an
 unverifiable transaction is one resulting from a redirect or a request
 for an image hosted on another site).  If this is false, cookies are
@@ -535,19 +535,19 @@
 
 Netscape protocol strictness switches:
 
-\begin{memberdesc}{strict_ns_unverifiable}
+\begin{memberdesc}[DefaultCookiePolicy]{strict_ns_unverifiable}
 apply RFC 2965 rules on unverifiable transactions even to Netscape
 cookies
 \end{memberdesc}
-\begin{memberdesc}{strict_ns_domain}
+\begin{memberdesc}[DefaultCookiePolicy]{strict_ns_domain}
 Flags indicating how strict to be with domain-matching rules for
 Netscape cookies.  See below for acceptable values.
 \end{memberdesc}
-\begin{memberdesc}{strict_ns_set_initial_dollar}
+\begin{memberdesc}[DefaultCookiePolicy]{strict_ns_set_initial_dollar}
 Ignore cookies in Set-Cookie: headers that have names starting with
 \code{'\$'}.
 \end{memberdesc}
-\begin{memberdesc}{strict_ns_set_path}
+\begin{memberdesc}[DefaultCookiePolicy]{strict_ns_set_path}
 Don't allow setting cookies whose path doesn't path-match request URI.
 \end{memberdesc}
 
@@ -556,30 +556,30 @@
 \code{DomainStrictNoDots|DomainStrictNonDomain} means both flags are
 set).
 
-\begin{memberdesc}{DomainStrictNoDots}
+\begin{memberdesc}[DefaultCookiePolicy]{DomainStrictNoDots}
 When setting cookies, the 'host prefix' must not contain a dot
 (eg. \code{www.foo.bar.com} can't set a cookie for \code{.bar.com},
 because \code{www.foo} contains a dot).
 \end{memberdesc}
-\begin{memberdesc}{DomainStrictNonDomain}
+\begin{memberdesc}[DefaultCookiePolicy]{DomainStrictNonDomain}
 Cookies that did not explicitly specify a \code{domain}
 cookie-attribute can only be returned to a domain equal to the domain
 that set the cookie (eg. \code{spam.example.com} won't be returned
 cookies from \code{example.com} that had no \code{domain}
 cookie-attribute).
 \end{memberdesc}
-\begin{memberdesc}{DomainRFC2965Match}
+\begin{memberdesc}[DefaultCookiePolicy]{DomainRFC2965Match}
 When setting cookies, require a full RFC 2965 domain-match.
 \end{memberdesc}
 
 The following attributes are provided for convenience, and are the
 most useful combinations of the above flags:
 
-\begin{memberdesc}{DomainLiberal}
+\begin{memberdesc}[DefaultCookiePolicy]{DomainLiberal}
 Equivalent to 0 (ie. all of the above Netscape domain strictness flags
 switched off).
 \end{memberdesc}
-\begin{memberdesc}{DomainStrict}
+\begin{memberdesc}[DefaultCookiePolicy]{DomainStrict}
 Equivalent to \code{DomainStrictNoDots|DomainStrictNonDomain}.
 \end{memberdesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libcsv.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcsv.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcsv.tex	Wed Jul 11 15:40:56 2007
@@ -487,8 +487,8 @@
     def __iter__(self):
         return self
 
-    def next(self):
-        return self.reader.next().encode("utf-8")
+    def __next__(self):
+        return next(self.reader).encode("utf-8")
 
 class UnicodeReader:
     """
@@ -500,8 +500,8 @@
         f = UTF8Recoder(f, encoding)
         self.reader = csv.reader(f, dialect=dialect, **kwds)
 
-    def next(self):
-        row = self.reader.next()
+    def __next__(self):
+        row = next(self.reader)
         return [unicode(s, "utf-8") for s in row]
 
     def __iter__(self):

Modified: python/branches/p3yk-noslice/Doc/lib/libctypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libctypes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libctypes.tex	Wed Jul 11 15:40:56 2007
@@ -7,21 +7,21 @@
 \versionadded{2.5}
 
 \code{ctypes} is a foreign function library for Python.  It provides C
-compatible data types, and allows to call functions in dlls/shared
+compatible data types, and allows calling functions in dlls/shared
 libraries.  It can be used to wrap these libraries in pure Python.
 
 
 \subsection{ctypes tutorial\label{ctypes-ctypes-tutorial}}
 
-Note: The code samples in this tutorial uses \code{doctest} to make sure
+Note: The code samples in this tutorial use \code{doctest} to make sure
 that they actually work.  Since some code samples behave differently
 under Linux, Windows, or Mac OS X, they contain doctest directives in
 comments.
 
-Note: Quite some code samples references the ctypes \class{c{\_}int} type.
+Note: Some code sample references the ctypes \class{c{\_}int} type.
 This type is an alias to the \class{c{\_}long} type on 32-bit systems.  So,
 you should not be confused if \class{c{\_}long} is printed if you would
-expect \class{c{\_}int} - they are actually the same type.
+expect \class{c{\_}int} --- they are actually the same type.
 
 
 \subsubsection{Loading dynamic link libraries\label{ctypes-loading-dynamic-link-libraries}}
@@ -38,7 +38,7 @@
 automatically raise \class{WindowsError} Python exceptions when the
 function call fails.
 
-Here are some examples for Windows, note that \code{msvcrt} is the MS
+Here are some examples for Windows. Note that \code{msvcrt} is the MS
 standard C library containing most standard C functions, and uses the
 cdecl calling convention:
 \begin{verbatim}
@@ -437,8 +437,8 @@
 expecting pointers to mutable memory. If you need mutable memory
 blocks, ctypes has a \code{create{\_}string{\_}buffer} function which creates
 these in various ways.  The current memory block contents can be
-accessed (or changed) with the \code{raw} property, if you want to access
-it as NUL terminated string, use the \code{string} property:
+accessed (or changed) with the \code{raw} property; if you want to access
+it as NUL terminated string, use the \code{value} property:
 \begin{verbatim}
 >>> from ctypes import *
 >>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
@@ -1219,7 +1219,7 @@
 It is quite interesting to see that the Windows \function{qsort} function
 needs more comparisons than the linux version!
 
-As we can easily check, our array sorted now:
+As we can easily check, our array is sorted now:
 \begin{verbatim}
 >>> for i in ia: print i,
 ...
@@ -1242,7 +1242,7 @@
 \programopt{-O} or \programopt{-OO} flag given on startup.
 
 \code{ctypes} can access values like this with the \method{in{\_}dll} class
-methods of the type.  \var{pythonapi} ìs a predefined symbol giving
+methods of the type.  \var{pythonapi} is a predefined symbol giving
 access to the Python C api:
 \begin{verbatim}
 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
@@ -2113,7 +2113,7 @@
 \end{memberdesc}
 
 
-\subsubsection{Fundamental data types\label{ctypes-fundamental-data-types}}
+\subsubsection{Fundamental data types\label{ctypes-fundamental-data-types-2}}
 
 \begin{classdesc*}{_SimpleCData}
 This non-public class is the base class of all fundamental ctypes
@@ -2294,6 +2294,13 @@
 an integer address, or a string.
 \end{classdesc*}
 
+\begin{classdesc*}{c_bool}
+Represent the C \code{bool} datatype (more accurately, _Bool from C99).
+Its value can be True or False, and the constructor accepts any object that
+has a truth value.
+\versionadded{2.6}
+\end{classdesc*}
+
 \begin{classdesc*}{HRESULT}
 Windows only: Represents a \class{HRESULT} value, which contains success
 or error information for a function or method call.

Modified: python/branches/p3yk-noslice/Doc/lib/libcurses.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcurses.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcurses.tex	Wed Jul 11 15:40:56 2007
@@ -646,6 +646,16 @@
 corner characters are always used by this function.
 \end{methoddesc}
 
+\begin{methoddesc}[window]{chgat}{\optional{y, x, } \optional{num,} attr}
+Sets the attributes of \var{num} characters at the current cursor
+position, or at position \code{(\var{y}, \var{x})} if supplied. If no
+value of \var{num} is given or \var{num} = -1, the attribute will 
+be set on all the characters to the end of the line. 
+This function does not move the cursor. The changed line
+will be touched using the \method{touchline} method so that the
+contents will be redisplayed by the next window refresh.
+\end{methoddesc}
+
 \begin{methoddesc}[window]{clear}{}
 Like \method{erase()}, but also causes the whole window to be repainted
 upon next call to \method{refresh()}.
@@ -1014,9 +1024,11 @@
 input at the end of that time.
 \end{methoddesc}
 
-\begin{methoddesc}[window]{touchline}{start, count}
+\begin{methoddesc}[window]{touchline}{start, count\optional{, changed}}
 Pretend \var{count} lines have been changed, starting with line
-\var{start}.
+\var{start}.  If \var{changed} is supplied, it specifies
+whether the affected lines are marked as 
+having been changed (\var{changed}=1) or unchanged (\var{changed}=0).
 \end{methoddesc}
 
 \begin{methoddesc}[window]{touchwin}{}

Modified: python/branches/p3yk-noslice/Doc/lib/libcursespanel.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcursespanel.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libcursespanel.tex	Wed Jul 11 15:40:56 2007
@@ -45,52 +45,52 @@
 
 Panel objects have the following methods:
 
-\begin{methoddesc}{above}{}
+\begin{methoddesc}[Panel]{above}{}
 Returns the panel above the current panel.
 \end{methoddesc}
 
-\begin{methoddesc}{below}{}
+\begin{methoddesc}[Panel]{below}{}
 Returns the panel below the current panel.
 \end{methoddesc}
 
-\begin{methoddesc}{bottom}{}
+\begin{methoddesc}[Panel]{bottom}{}
 Push the panel to the bottom of the stack.
 \end{methoddesc}
 
-\begin{methoddesc}{hidden}{}
+\begin{methoddesc}[Panel]{hidden}{}
 Returns true if the panel is hidden (not visible), false otherwise.
 \end{methoddesc}
 
-\begin{methoddesc}{hide}{}
+\begin{methoddesc}[Panel]{hide}{}
 Hide the panel. This does not delete the object, it just makes the
 window on screen invisible.
 \end{methoddesc}
 
-\begin{methoddesc}{move}{y, x}
+\begin{methoddesc}[Panel]{move}{y, x}
 Move the panel to the screen coordinates \code{(\var{y}, \var{x})}.
 \end{methoddesc}
 
-\begin{methoddesc}{replace}{win}
+\begin{methoddesc}[Panel]{replace}{win}
 Change the window associated with the panel to the window \var{win}.
 \end{methoddesc}
 
-\begin{methoddesc}{set_userptr}{obj}
+\begin{methoddesc}[Panel]{set_userptr}{obj}
 Set the panel's user pointer to \var{obj}. This is used to associate an
 arbitrary piece of data with the panel, and can be any Python object.
 \end{methoddesc}
 
-\begin{methoddesc}{show}{}
+\begin{methoddesc}[Panel]{show}{}
 Display the panel (which might have been hidden).
 \end{methoddesc}
 
-\begin{methoddesc}{top}{}
+\begin{methoddesc}[Panel]{top}{}
 Push panel to the top of the stack.
 \end{methoddesc}
 
-\begin{methoddesc}{userptr}{}
+\begin{methoddesc}[Panel]{userptr}{}
 Returns the user pointer for the panel.  This might be any Python object.
 \end{methoddesc}
 
-\begin{methoddesc}{window}{}
+\begin{methoddesc}[Panel]{window}{}
 Returns the window object associated with the panel.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libdatetime.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdatetime.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdatetime.tex	Wed Jul 11 15:40:56 2007
@@ -1154,7 +1154,7 @@
 uses made of aware \module{datetime} objects.  If in doubt, simply
 implement all of them.
 
-\begin{methoddesc}{utcoffset}{self, dt}
+\begin{methoddesc}[tzinfo]{utcoffset}{self, dt}
   Return offset of local time from UTC, in minutes east of UTC.  If
   local time is west of UTC, this should be negative.  Note that this
   is intended to be the total offset from UTC; for example, if a
@@ -1178,7 +1178,7 @@
     \exception{NotImplementedError}.
 \end{methoddesc}
 
-\begin{methoddesc}{dst}{self, dt}
+\begin{methoddesc}[tzinfo]{dst}{self, dt}
   Return the daylight saving time (DST) adjustment, in minutes east of
   UTC, or \code{None} if DST information isn't known.  Return
   \code{timedelta(0)} if DST is not in effect.
@@ -1237,7 +1237,7 @@
   \exception{NotImplementedError}.
 \end{methoddesc}
 
-\begin{methoddesc}{tzname}{self, dt}
+\begin{methoddesc}[tzinfo]{tzname}{self, dt}
   Return the time zone name corresponding to the \class{datetime}
   object \var{dt}, as a string.
   Nothing about string names is defined by the
@@ -1278,7 +1278,7 @@
 There is one more \class{tzinfo} method that a subclass may wish to
 override:
 
-\begin{methoddesc}{fromutc}{self, dt}
+\begin{methoddesc}[tzinfo]{fromutc}{self, dt}
   This is called from the default \class{datetime.astimezone()}
   implementation.  When called from that, \code{\var{dt}.tzinfo} is
   \var{self}, and \var{dt}'s date and time members are to be viewed as

Modified: python/branches/p3yk-noslice/Doc/lib/libdbhash.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdbhash.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdbhash.tex	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,6 @@
          DBM-style interface to the BSD database library}
 
 \declaremodule{standard}{dbhash}
-  \platform{Unix, Windows}
 \modulesynopsis{DBM-style interface to the BSD database library.}
 \sectionauthor{Fred L. Drake, Jr.}{fdrake at acm.org}
 
@@ -73,7 +72,7 @@
 
 \begin{verbatim}
 print db.first()
-for i in xrange(1, len(db)):
+for i in range(1, len(db)):
     print db.next()
 \end{verbatim}
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libdecimal.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdecimal.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdecimal.tex	Wed Jul 11 15:40:56 2007
@@ -425,7 +425,7 @@
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%            
-\subsection{Context objects \label{decimal-decimal}}
+\subsection{Context objects \label{decimal-context}}
 
 Contexts are environments for arithmetic operations.  They govern precision,
 set rules for rounding, determine which signals are treated as exceptions, and
@@ -845,7 +845,7 @@
 The following table summarizes the hierarchy of signals:
 
 \begin{verbatim}    
-    exceptions.ArithmeticError(exceptions.StandardError)
+    exceptions.ArithmeticError(exceptions.Exception)
         DecimalException
             Clamped
             DivisionByZero(DecimalException, exceptions.ZeroDivisionError)

Modified: python/branches/p3yk-noslice/Doc/lib/libdifflib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdifflib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdifflib.tex	Wed Jul 11 15:40:56 2007
@@ -302,7 +302,7 @@
 
 
 \begin{seealso}
-  \seetitle[http://www.ddj.com/documents/s=1103/ddj8807c/]
+  \seetitle[http://www.ddj.com/184407970?pgno=5]
            {Pattern Matching: The Gestalt Approach}{Discussion of a
             similar algorithm by John W. Ratcliff and D. E. Metzener.
             This was published in

Modified: python/branches/p3yk-noslice/Doc/lib/libdis.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdis.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdis.tex	Wed Jul 11 15:40:56 2007
@@ -310,6 +310,10 @@
 instruction).
 \end{opcodedesc}
 
+\begin{opcodedesc}{SET_ADD}{}
+Calls \code{set.add(TOS1, TOS)}.  Used to implement set comprehensions.
+\end{opcodedesc}
+
 \begin{opcodedesc}{LIST_APPEND}{}
 Calls \code{list.append(TOS1, TOS)}.  Used to implement list comprehensions.
 \end{opcodedesc}
@@ -472,10 +476,10 @@
 \end{opcodedesc}
 
 \begin{opcodedesc}{FOR_ITER}{delta}
-\code{TOS} is an iterator.  Call its \method{next()} method.  If this
-yields a new value, push it on the stack (leaving the iterator below
-it).  If the iterator indicates it is exhausted  \code{TOS} is
-popped, and the byte code counter is incremented by \var{delta}.
+  \code{TOS} is an iterator.  Call its \method{__next__()} method.  If this
+  yields a new value, push it on the stack (leaving the iterator below it).  If
+  the iterator indicates it is exhausted \code{TOS} is popped, and the byte code
+  counter is incremented by \var{delta}.
 \end{opcodedesc}
 
 %\begin{opcodedesc}{FOR_LOOP}{delta}
@@ -569,7 +573,7 @@
 \end{opcodedesc}
 
 \begin{opcodedesc}{MAKE_CLOSURE}{argc}
-Creates a new function object, sets its \var{func_closure} slot, and
+Creates a new function object, sets its \var{__closure__} slot, and
 pushes it on the stack.  TOS is the code associated with the function.
 If the code object has N free variables, the next N items on the stack
 are the cells for these variables.  The function also has \var{argc}

Modified: python/branches/p3yk-noslice/Doc/lib/libdl.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdl.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdl.tex	Wed Jul 11 15:40:56 2007
@@ -67,11 +67,11 @@
 Dl objects, as returned by \function{open()} above, have the
 following methods:
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[dl]{close}{}
 Free all resources, except the memory.
 \end{methoddesc}
 
-\begin{methoddesc}{sym}{name}
+\begin{methoddesc}[dl]{sym}{name}
 Return the pointer for the function named \var{name}, as a number, if
 it exists in the referenced shared object, otherwise \code{None}. This
 is useful in code like:
@@ -87,7 +87,7 @@
 \NULL{} pointer)
 \end{methoddesc}
 
-\begin{methoddesc}{call}{name\optional{, arg1\optional{, arg2\ldots}}}
+\begin{methoddesc}[dl]{call}{name\optional{, arg1\optional{, arg2\ldots}}}
 Call the function named \var{name} in the referenced shared object.
 The arguments must be either Python integers, which will be 
 passed as is, Python strings, to which a pointer will be passed, 

Modified: python/branches/p3yk-noslice/Doc/lib/libdoctest.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdoctest.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdoctest.tex	Wed Jul 11 15:40:56 2007
@@ -201,6 +201,19 @@
 \code{sys.argv} is not examined by \function{testmod()} (so passing
 \programopt{-v} or not has no effect).
 
+Since Python 2.6, there is also a command line shortcut for running
+\function{testmod()}.  You can instruct the Python interpreter to run
+the doctest module directly from the standard library and pass the module
+name(s) on the command line:
+
+\begin{verbatim}
+python -m doctest -v example.py
+\end{verbatim}
+
+This will import \file{example.py} as a standalone module and run
+\function{testmod()} on it.  Note that this may not work correctly if the
+file is part of a package and imports other submodules from that package.
+
 For more information on \function{testmod()}, see
 section~\ref{doctest-basic-api}.
 
@@ -267,6 +280,18 @@
 set with the \programopt{-v} command-line switch or with the optional
 keyword argument \var{verbose}.
 
+Since Python 2.6, there is also a command line shortcut for running
+\function{testfile()}.  You can instruct the Python interpreter to run
+the doctest module directly from the standard library and pass the file
+name(s) on the command line:
+
+\begin{verbatim}
+python -m doctest -v example.txt
+\end{verbatim}
+
+Because the file name does not end with \file{.py}, \module{doctest} infers
+that it must be run with \function{testfile()}, not \function{testmod()}.
+
 For more information on \function{testfile()}, see
 section~\ref{doctest-basic-api}.
 
@@ -1716,7 +1741,7 @@
 >>>
 \end{verbatim}
 
-    \versionchanged[The ability to use \code{\refmodule{pdb}.set_trace()}
+    \versionchanged[The ability to use \function{\refmodule{pdb}.set_trace()}
                     usefully inside doctests was added]{2.4}
 \end{itemize}
 
@@ -1800,10 +1825,10 @@
   used.  If \var{pm} has a true value, the script file is run directly, and
   the debugger gets involved only if the script terminates via raising an
   unhandled exception.  If it does, then post-mortem debugging is invoked,
-  via \code{\refmodule{pdb}.post_mortem()}, passing the traceback object
+  via \function{\refmodule{pdb}.post_mortem()}, passing the traceback object
   from the unhandled exception.  If \var{pm} is not specified, or is false,
   the script is run under the debugger from the start, via passing an
-  appropriate \function{execfile()} call to \code{\refmodule{pdb}.run()}.
+  appropriate \function{execfile()} call to \function{\refmodule{pdb}.run()}.
 
   \versionadded{2.3}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libdocxmlrpc.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdocxmlrpc.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdocxmlrpc.tex	Wed Jul 11 15:40:56 2007
@@ -14,8 +14,12 @@
 \class{DocXMLRPCServer}, or embedded in a CGI environment, using
 \class{DocCGIXMLRPCRequestHandler}.
 
-\begin{classdesc}{DocXMLRPCServer}{addr\optional{, 
-                                   requestHandler\optional{, logRequests}}}
+\begin{classdesc}{DocXMLRPCServer}{addr\optional{,
+                                   requestHandler\optional{,
+			                       logRequests\optional{,
+                                   allow_none\optional{, 
+                                   encoding\optional{,
+                                   bind_and_activate}}}}}}
 
 Create a new server instance. All parameters have the same meaning as
 for \class{SimpleXMLRPCServer.SimpleXMLRPCServer};
@@ -47,14 +51,14 @@
 handled by generating pydoc-style HTML documentation. This allows a
 server to provide its own web-based documentation.
 
-\begin{methoddesc}{set_server_title}{server_title}
+\begin{methoddesc}[DocXMLRPCServer]{set_server_title}{server_title}
 
 Set the title used in the generated HTML documentation. This title
 will be used inside the HTML "title" element.
 
 \end{methoddesc}
 
-\begin{methoddesc}{set_server_name}{server_name}
+\begin{methoddesc}[DocXMLRPCServer]{set_server_name}{server_name}
 
 Set the name used in the generated HTML documentation. This name will
 appear at the top of the generated documentation inside a "h1"
@@ -63,7 +67,7 @@
 \end{methoddesc}
 
 
-\begin{methoddesc}{set_server_documentation}{server_documentation}
+\begin{methoddesc}[DocXMLRPCServer]{set_server_documentation}{server_documentation}
 
 Set the description used in the generated HTML documentation. This
 description will appear as a paragraph, below the server name, in the
@@ -80,14 +84,14 @@
 generating pydoc-style HTML documentation. This allows a server to
 provide its own web-based documentation.
 
-\begin{methoddesc}{set_server_title}{server_title}
+\begin{methoddesc}[DocCGIXMLRPCRequestHandler]{set_server_title}{server_title}
 
 Set the title used in the generated HTML documentation. This title
 will be used inside the HTML "title" element.
 
 \end{methoddesc}
 
-\begin{methoddesc}{set_server_name}{server_name}
+\begin{methoddesc}[DocCGIXMLRPCRequestHandler]{set_server_name}{server_name}
 
 Set the name used in the generated HTML documentation. This name will
 appear at the top of the generated documentation inside a "h1"
@@ -96,7 +100,7 @@
 \end{methoddesc}
 
 
-\begin{methoddesc}{set_server_documentation}{server_documentation}
+\begin{methoddesc}[DocCGIXMLRPCRequestHandler]{set_server_documentation}{server_documentation}
 
 Set the description used in the generated HTML documentation. This
 description will appear as a paragraph, below the server name, in the

Modified: python/branches/p3yk-noslice/Doc/lib/libdumbdbm.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdumbdbm.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libdumbdbm.tex	Wed Jul 11 15:40:56 2007
@@ -57,7 +57,7 @@
 In addition to the methods provided by the \class{UserDict.DictMixin} class,
 \class{dumbdbm} objects provide the following methods.
 
-\begin{methoddesc}{sync}{}
+\begin{methoddesc}[dumbdbm]{sync}{}
 Synchronize the on-disk directory and data files.  This method is called by
 the \method{sync} method of \class{Shelve} objects.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libetree.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libetree.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libetree.tex	Wed Jul 11 15:40:56 2007
@@ -38,10 +38,7 @@
 The comment string can be either an 8-bit ASCII string or a Unicode
 string.
 \var{text} is a string containing the comment string.
-
-\begin{datadescni}{Returns:}
-An element instance, representing a comment.
-\end{datadescni}
+Returns an element instance representing a comment.
 \end{funcdesc}
 
 \begin{funcdesc}{dump}{elem}
@@ -65,28 +62,19 @@
 \var{tag} is the element name.
 \var{attrib} is an optional dictionary, containing element attributes.
 \var{extra} contains additional attributes, given as keyword arguments.
-
-\begin{datadescni}{Returns:}
-An element instance.
-\end{datadescni}
+Returns an element instance.
 \end{funcdesc}
 
 \begin{funcdesc}{fromstring}{text}
 Parses an XML section from a string constant.  Same as XML.
 \var{text} is a string containing XML data.
-
-\begin{datadescni}{Returns:}
-An Element instance.
-\end{datadescni}
+Returns an Element instance.
 \end{funcdesc}
 
 \begin{funcdesc}{iselement}{element}
 Checks if an object appears to be a valid element object.
 \var{element} is an element instance.
-
-\begin{datadescni}{Returns:}
-A true value if this is an element object.
-\end{datadescni}
+Returns a true value if this is an element object.
 \end{funcdesc}
 
 \begin{funcdesc}{iterparse}{source\optional{, events}}
@@ -95,10 +83,7 @@
 \var{source} is a filename or file object containing XML data.
 \var{events} is a list of events to report back.  If omitted, only ``end''
 events are reported.
-
-\begin{datadescni}{Returns:}
-A (event, elem) iterator.
-\end{datadescni}
+Returns an iterator providing \code{(\var{event}, \var{elem})} pairs.
 \end{funcdesc}
 
 \begin{funcdesc}{parse}{source\optional{, parser}}
@@ -106,10 +91,7 @@
 \var{source} is a filename or file object containing XML data.
 \var{parser} is an optional parser instance.  If not given, the
 standard XMLTreeBuilder parser is used.
-
-\begin{datadescni}{Returns:}
-An ElementTree instance
-\end{datadescni}
+Returns an ElementTree instance.
 \end{funcdesc}
 
 \begin{funcdesc}{ProcessingInstruction}{target\optional{, text}}
@@ -117,13 +99,11 @@
 that will be serialized as an XML processing instruction.
 \var{target} is a string containing the PI target.
 \var{text} is a string containing the PI contents, if given.
-
-\begin{datadescni}{Returns:}
-An element instance, representing a PI.
-\end{datadescni}
+Returns an element instance, representing a processing instruction.
 \end{funcdesc}
 
-\begin{funcdesc}{SubElement}{parent, tag\optional{, attrib} \optional{, **extra}}
+\begin{funcdesc}{SubElement}{parent, tag\optional{,
+                             attrib\optional{,  **extra}}}
 Subelement factory.  This function creates an element instance, and
 appends it to an existing element.
 
@@ -133,10 +113,7 @@
 \var{tag} is the subelement name.
 \var{attrib} is an optional dictionary, containing element attributes.
 \var{extra} contains additional attributes, given as keyword arguments.
-
-\begin{datadescni}{Returns:}
-An element instance.
-\end{datadescni}
+Returns an element instance.
 \end{funcdesc}
 
 \begin{funcdesc}{tostring}{element\optional{, encoding}}
@@ -144,33 +121,162 @@
 subelements.
 \var{element} is an Element instance.
 \var{encoding} is the output encoding (default is US-ASCII).
-
-\begin{datadescni}{Returns:}
-An encoded string containing the XML data.
-\end{datadescni}
+Returns an encoded string containing the XML data.
 \end{funcdesc}
 
 \begin{funcdesc}{XML}{text}
 Parses an XML section from a string constant.  This function can
 be used to embed ``XML literals'' in Python code.
 \var{text} is a string containing XML data.
-
-\begin{datadescni}{Returns:}
-An Element instance.
-\end{datadescni}
+Returns an Element instance.
 \end{funcdesc}
 
 \begin{funcdesc}{XMLID}{text}
 Parses an XML section from a string constant, and also returns
 a dictionary which maps from element id:s to elements.
 \var{text} is a string containing XML data.
-
-\begin{datadescni}{Returns:}
-A tuple containing an Element instance and a dictionary.
-\end{datadescni}
+Returns a tuple containing an Element instance and a dictionary.
 \end{funcdesc}
 
 
+\subsection{The Element Interface\label{elementtree-element-interface}}
+
+Element objects returned by Element or SubElement have the 
+following methods and attributes.
+
+\begin{memberdesc}[Element]{tag}
+A string identifying what kind of data this element represents
+(the element type, in other words).
+\end{memberdesc}
+
+\begin{memberdesc}[Element]{text}
+The \var{text} attribute can be used to hold additional data
+associated with the element.
+As the name implies this attribute is usually a string but may be any
+application-specific object.
+If the element is created from an XML file the attribute will contain
+any text found between the element tags.
+\end{memberdesc}
+
+\begin{memberdesc}[Element]{tail}
+The \var{tail} attribute can be used to hold additional data
+associated with the element.
+This attribute is usually a string but may be any application-specific object.
+If the element is created from an XML file the attribute will contain
+any text found after the element's end tag and before the next tag.
+\end{memberdesc}
+
+\begin{memberdesc}[Element]{attrib}
+A dictionary containing the element's attributes.
+Note that while the \var{attrib} value is always a real mutable Python
+dictionary, an ElementTree implementation may choose to use another
+internal representation, and create the dictionary only if someone
+asks for it. To take advantage of such implementations, use the
+dictionary methods below whenever possible.
+\end{memberdesc}
+
+The following dictionary-like methods work on the element attributes.
+
+\begin{methoddesc}[Element]{clear}{}
+Resets an element.  This function removes all subelements, clears
+all attributes, and sets the text and tail attributes to None.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{get}{key\optional{, default=None}}
+Gets the element attribute named \var{key}.
+
+Returns the attribute value, or \var{default} if the
+attribute was not found.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{items}{}
+Returns the element attributes as a sequence of (name, value) pairs.
+The attributes are returned in an arbitrary order.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{keys}{}
+Returns the elements attribute names as a list.
+The names are returned in an arbitrary order.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{set}{key, value}
+Set the attribute \var{key} on the element to \var{value}.  
+\end{methoddesc}
+
+The following methods work on the element's children (subelements).
+
+\begin{methoddesc}[Element]{append}{subelement}
+Adds the element \var{subelement} to the end of this elements internal list
+of subelements.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{find}{match}
+Finds the first subelement matching \var{match}. 
+\var{match} may be a tag name or path.
+Returns an element instance or \code{None}.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{findall}{match}
+Finds all subelements matching \var{match}. 
+\var{match} may be a tag name or path.
+Returns an iterable yielding all matching elements in document order.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{findtext}{condition\optional{, default=None}}
+Finds text for the first subelement matching \var{condition}. 
+\var{condition} may be a tag name or path.
+Returns the text content of the first matching element, or
+\var{default} if no element was found.  Note that if the
+matching element has no text content an empty string is returned.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{getchildren}{}
+Returns all subelements.  The elements are returned in document order.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{getiterator}{\optional{tag=None}}
+Creates a tree iterator with the current element as the root.  
+The iterator iterates over this element and all elements below it 
+that match the given tag. If tag
+is \code{None} or \code{'*'} then all elements are iterated over.
+Returns an iterable that provides element objects in document (depth first)
+order.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{insert}{index, element}
+Inserts a subelement at the given position in this element.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{makeelement}{tag, attrib}
+Creates a new element object of the same type as this element.
+Do not call this method, use the SubElement factory function instead.
+\end{methoddesc}
+
+\begin{methoddesc}[Element]{remove}{subelement}
+Removes \var{subelement} from the element.  
+Unlike the findXXX methods this method compares elements based on 
+the instance identity, not on tag value or contents.
+\end{methoddesc}
+
+Element objects also support the following sequence type methods for
+working with subelements: \method{__delitem__()},
+\method{__getitem__()}, \method{__setitem__()}, \method{__len__()}.
+
+Caution: Because Element objects do not define a
+\method{__nonzero__()} method, elements with no subelements will test
+as \code{False}.
+
+\begin{verbatim}
+element = root.find('foo')
+
+if not element: # careful!
+    print "element not found, or element has no subelements"
+
+if element is None:
+    print "element not found"
+\end{verbatim}
+
+
 \subsection{ElementTree Objects\label{elementtree-elementtree-objects}}
 
 \begin{classdesc}{ElementTree}{\optional{element,} \optional{file}}
@@ -193,21 +299,15 @@
 Finds the first toplevel element with given tag.
 Same as getroot().find(path).
 \var{path} is the element to look for.
-
-\begin{datadescni}{Returns:}
-The first matching element, or None if no element was found.
-\end{datadescni}
+Returns the first matching element, or \code{None} if no element was found.
 \end{methoddesc}
 
 \begin{methoddesc}{findall}{path}
 Finds all toplevel elements with the given tag.
 Same as getroot().findall(path).
 \var{path} is the element to look for.
-
-\begin{datadescni}{Returns:}
-A list or iterator containing all matching elements,
-in section order.
-\end{datadescni}
+Returns a list or iterator containing all matching elements,
+in document order.
 \end{methoddesc}
 
 \begin{methoddesc}{findtext}{path\optional{, default}}
@@ -215,31 +315,20 @@
 tag.  Same as getroot().findtext(path).
 \var{path} is the toplevel element to look for.
 \var{default} is the value to return if the element was not found.
-
-\begin{datadescni}{Returns:}
-The text content of the first matching element, or the
+Returns the text content of the first matching element, or the
 default value no element was found.  Note that if the element
 has is found, but has no text content, this method returns an
 empty string.
-\end{datadescni}
 \end{methoddesc}
 
 \begin{methoddesc}{getiterator}{\optional{tag}}
-Creates a tree iterator for the root element.  The iterator loops
+Creates and returns a tree iterator for the root element.  The iterator loops
 over all elements in this tree, in section order.
 \var{tag} is the tag to look for (default is to return all elements)
-
-\begin{datadescni}{Returns:}
-An iterator.
-\end{datadescni}
 \end{methoddesc}
 
 \begin{methoddesc}{getroot}{}
-Gets the root element for this tree.
-
-\begin{datadescni}{Returns:}
-An element instance.
-\end{datadescni}
+Returns the root element for this tree.
 \end{methoddesc}
 
 \begin{methoddesc}{parse}{source\optional{, parser}}
@@ -247,10 +336,7 @@
 \var{source} is a file name or file object.
 \var{parser} is an optional parser instance.  If not given, the
 standard XMLTreeBuilder parser is used.
-
-\begin{datadescni}{Returns:}
-The section root element.
-\end{datadescni}
+Returns the section root element.
 \end{methoddesc}
 
 \begin{methoddesc}{write}{file\optional{, encoding}}
@@ -270,10 +356,7 @@
 the URI part of a QName.
 If \var{tag} is given, the first argument is interpreted as
 an URI, and this argument is interpreted as a local name.
-
-\begin{datadescni}{Returns:}
-An opaque object, representing the QName.
-\end{datadescni}
+\class{QName} instances are opaque.
 \end{classdesc}
 
 
@@ -291,10 +374,7 @@
 \begin{methoddesc}{close}{}
 Flushes the parser buffers, and returns the toplevel documen
 element.
-
-\begin{datadescni}{Returns:}
-An Element instance.
-\end{datadescni}
+Returns an Element instance.
 \end{methoddesc}
 
 \begin{methoddesc}{data}{data}
@@ -306,20 +386,14 @@
 \begin{methoddesc}{end}{tag}
 Closes the current element.
 \var{tag} is the element name.
-
-\begin{datadescni}{Returns:}
-The closed element.
-\end{datadescni}
+Returns the closed element.
 \end{methoddesc}
 
 \begin{methoddesc}{start}{tag, attrs}
 Opens a new element.
 \var{tag} is the element name.
 \var{attrs} is a dictionary containing element attributes.
-
-\begin{datadescni}{Returns:}
-The opened element.
-\end{datadescni}
+Returns the opened element.
 \end{methoddesc}
 
 
@@ -336,10 +410,7 @@
 
 \begin{methoddesc}{close}{}
 Finishes feeding data to the parser.
-
-\begin{datadescni}{Returns:}
-An element structure.
-\end{datadescni}
+Returns an element structure.
 \end{methoddesc}
 
 \begin{methoddesc}{doctype}{name, pubid, system}
@@ -351,6 +422,5 @@
 
 \begin{methoddesc}{feed}{data}
 Feeds data to the parser.
-
 \var{data} is encoded data.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libexcs.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libexcs.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libexcs.tex	Wed Jul 11 15:40:56 2007
@@ -23,14 +23,10 @@
 This may be a string or a tuple containing several items of
 information (e.g., an error code and a string explaining the code).
 The associated value is the second argument to the
-\keyword{raise}\stindex{raise} statement.  For string exceptions, the
-associated value itself will be stored in the variable named as the
-second argument of the \keyword{except} clause (if any).  For class
-exceptions, that variable receives the exception instance.  If the
-exception class is derived from the standard root class
-\exception{BaseException}, the associated value is present as the
-exception instance's \member{args} attribute.  If there is a single argument
-(as is preferred), it is bound to the \member{message} attribute.
+\keyword{raise}\stindex{raise} statement.  If the exception class is
+derived from the standard root class \exception{BaseException}, the
+associated value is present as the exception instance's \member{args}
+attribute.
 
 User code can raise built-in exceptions.  This can be used to test an
 exception handler or to report an error condition ``just like'' the
@@ -56,14 +52,8 @@
 inherited by user-defined classes (for that use \exception{Exception}).  If
 \function{str()} or \function{unicode()} is called on an instance of this
 class, the representation of the argument(s) to the instance are returned or
-the emptry string when there were no arguments.  If only a single argument is
-passed in, it is stored in the \member{message} attribute.  If more than one
-argument is passed in, \member{message} is set to the empty string.  These
-semantics are meant to reflect the fact that \member{message} is to store a
-text message explaining why the exception had been raised.  If more data needs
-to be attached to the exception, attach it through arbitrary attributes on the
-instance.  All arguments are also stored in \member{args} as a tuple, but it will
-eventually be deprecated and thus its use is discouraged.
+the emptry string when there were no arguments.  All arguments are 
+stored in \member{args} as a tuple.
 \versionadded{2.5}
 \end{excdesc}
 
@@ -74,13 +64,6 @@
 \versionchanged[Changed to inherit from \exception{BaseException}]{2.5}
 \end{excdesc}
 
-\begin{excdesc}{StandardError}
-The base class for all built-in exceptions except
-\exception{StopIteration}, \exception{GeneratorExit},
-\exception{KeyboardInterrupt} and \exception{SystemExit}.
-\exception{StandardError} itself is derived from \exception{Exception}.
-\end{excdesc}
-
 \begin{excdesc}{ArithmeticError}
 The base class for those built-in exceptions that are raised for
 various arithmetic errors: \exception{OverflowError},
@@ -153,9 +136,9 @@
 
 \begin{excdesc}{GeneratorExit}
   Raise when a generator's \method{close()} method is called.
-  It directly inherits from \exception{Exception} instead of
-  \exception{StandardError} since it is technically not an error.
   \versionadded{2.5}
+  \versionchanged[Changed to inherit from Exception instead of
+  StandardError]{3.0}
 \end{excdesc}
 
 \begin{excdesc}{IOError}
@@ -265,12 +248,11 @@
 \end{excdesc}
 
 \begin{excdesc}{StopIteration}
-  Raised by an iterator's \method{next()} method to signal that there
-  are no further values.
-  This is derived from \exception{Exception} rather than
-  \exception{StandardError}, since this is not considered an error in
-  its normal application.
+  Raised by builtin \function{next()} and an iterator's \method{__next__()}
+  method to signal that there are no further values.
   \versionadded{2.2}
+  \versionchanged[Changed to inherit from Exception instead of
+  StandardError]{3.0}
 \end{excdesc}
 
 
@@ -314,7 +296,7 @@
   Instances have an attribute \member{code} which is set to the
   proposed exit status or error message (defaulting to \code{None}).
   Also, this exception derives directly from \exception{BaseException} and
-  not \exception{StandardError}, since it is not technically an error.
+  not \exception{Exception}, since it is not technically an error.
 
   A call to \function{sys.exit()} is translated into an exception so that
   clean-up handlers (\keyword{finally} clauses of \keyword{try} statements)
@@ -325,7 +307,7 @@
   \function{fork()}).
 
   The exception inherits from \exception{BaseException} instead of
-  \exception{StandardError} or \exception{Exception} so that it is not
+  \exception{Exception} so that it is not
   accidentally caught by code that catches \exception{Exception}.  This allows
   the exception to properly propagate up and cause the interpreter to exit.
   \versionchanged[Changed to inherit from \exception{BaseException}]{2.5}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libfl.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libfl.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,507 +0,0 @@
-\section{\module{fl} ---
-         FORMS library for graphical user interfaces}
-
-\declaremodule{builtin}{fl}
-  \platform{IRIX}
-\modulesynopsis{FORMS library for applications with graphical user
-                interfaces.}
-
-
-This module provides an interface to the FORMS Library\index{FORMS
-Library} by Mark Overmars\index{Overmars, Mark}.  The source for the
-library can be retrieved by anonymous ftp from host
-\samp{ftp.cs.ruu.nl}, directory \file{SGI/FORMS}.  It was last tested
-with version 2.0b.
-
-Most functions are literal translations of their C equivalents,
-dropping the initial \samp{fl_} from their name.  Constants used by
-the library are defined in module \refmodule[fl-constants]{FL}
-described below.
-
-The creation of objects is a little different in Python than in C:
-instead of the `current form' maintained by the library to which new
-FORMS objects are added, all functions that add a FORMS object to a
-form are methods of the Python object representing the form.
-Consequently, there are no Python equivalents for the C functions
-\cfunction{fl_addto_form()} and \cfunction{fl_end_form()}, and the
-equivalent of \cfunction{fl_bgn_form()} is called
-\function{fl.make_form()}.
-
-Watch out for the somewhat confusing terminology: FORMS uses the word
-\dfn{object} for the buttons, sliders etc. that you can place in a form.
-In Python, `object' means any value.  The Python interface to FORMS
-introduces two new Python object types: form objects (representing an
-entire form) and FORMS objects (representing one button, slider etc.).
-Hopefully this isn't too confusing.
-
-There are no `free objects' in the Python interface to FORMS, nor is
-there an easy way to add object classes written in Python.  The FORMS
-interface to GL event handling is available, though, so you can mix
-FORMS with pure GL windows.
-
-\strong{Please note:} importing \module{fl} implies a call to the GL
-function \cfunction{foreground()} and to the FORMS routine
-\cfunction{fl_init()}.
-
-\subsection{Functions Defined in Module \module{fl}}
-\nodename{FL Functions}
-
-Module \module{fl} defines the following functions.  For more
-information about what they do, see the description of the equivalent
-C function in the FORMS documentation:
-
-\begin{funcdesc}{make_form}{type, width, height}
-Create a form with given type, width and height.  This returns a
-\dfn{form} object, whose methods are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{do_forms}{}
-The standard FORMS main loop.  Returns a Python object representing
-the FORMS object needing interaction, or the special value
-\constant{FL.EVENT}.
-\end{funcdesc}
-
-\begin{funcdesc}{check_forms}{}
-Check for FORMS events.  Returns what \function{do_forms()} above
-returns, or \code{None} if there is no event that immediately needs
-interaction.
-\end{funcdesc}
-
-\begin{funcdesc}{set_event_call_back}{function}
-Set the event callback function.
-\end{funcdesc}
-
-\begin{funcdesc}{set_graphics_mode}{rgbmode, doublebuffering}
-Set the graphics modes.
-\end{funcdesc}
-
-\begin{funcdesc}{get_rgbmode}{}
-Return the current rgb mode.  This is the value of the C global
-variable \cdata{fl_rgbmode}.
-\end{funcdesc}
-
-\begin{funcdesc}{show_message}{str1, str2, str3}
-Show a dialog box with a three-line message and an OK button.
-\end{funcdesc}
-
-\begin{funcdesc}{show_question}{str1, str2, str3}
-Show a dialog box with a three-line message and YES and NO buttons.
-It returns \code{1} if the user pressed YES, \code{0} if NO.
-\end{funcdesc}
-
-\begin{funcdesc}{show_choice}{str1, str2, str3, but1\optional{,
-                              but2\optional{, but3}}}
-Show a dialog box with a three-line message and up to three buttons.
-It returns the number of the button clicked by the user
-(\code{1}, \code{2} or \code{3}).
-\end{funcdesc}
-
-\begin{funcdesc}{show_input}{prompt, default}
-Show a dialog box with a one-line prompt message and text field in
-which the user can enter a string.  The second argument is the default
-input string.  It returns the string value as edited by the user.
-\end{funcdesc}
-
-\begin{funcdesc}{show_file_selector}{message, directory, pattern, default}
-Show a dialog box in which the user can select a file.  It returns
-the absolute filename selected by the user, or \code{None} if the user
-presses Cancel.
-\end{funcdesc}
-
-\begin{funcdesc}{get_directory}{}
-\funcline{get_pattern}{}
-\funcline{get_filename}{}
-These functions return the directory, pattern and filename (the tail
-part only) selected by the user in the last
-\function{show_file_selector()} call.
-\end{funcdesc}
-
-\begin{funcdesc}{qdevice}{dev}
-\funcline{unqdevice}{dev}
-\funcline{isqueued}{dev}
-\funcline{qtest}{}
-\funcline{qread}{}
-%\funcline{blkqread}{?}
-\funcline{qreset}{}
-\funcline{qenter}{dev, val}
-\funcline{get_mouse}{}
-\funcline{tie}{button, valuator1, valuator2}
-These functions are the FORMS interfaces to the corresponding GL
-functions.  Use these if you want to handle some GL events yourself
-when using \function{fl.do_events()}.  When a GL event is detected that
-FORMS cannot handle, \function{fl.do_forms()} returns the special value
-\constant{FL.EVENT} and you should call \function{fl.qread()} to read
-the event from the queue.  Don't use the equivalent GL functions!
-\end{funcdesc}
-
-\begin{funcdesc}{color}{}
-\funcline{mapcolor}{}
-\funcline{getmcolor}{}
-See the description in the FORMS documentation of
-\cfunction{fl_color()}, \cfunction{fl_mapcolor()} and
-\cfunction{fl_getmcolor()}.
-\end{funcdesc}
-
-\subsection{Form Objects}
-\label{form-objects}
-
-Form objects (returned by \function{make_form()} above) have the
-following methods.  Each method corresponds to a C function whose
-name is prefixed with \samp{fl_}; and whose first argument is a form
-pointer; please refer to the official FORMS documentation for
-descriptions.
-
-All the \method{add_*()} methods return a Python object representing
-the FORMS object.  Methods of FORMS objects are described below.  Most
-kinds of FORMS object also have some methods specific to that kind;
-these methods are listed here.
-
-\begin{flushleft}
-
-\begin{methoddesc}[form]{show_form}{placement, bordertype, name}
-  Show the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{hide_form}{}
-  Hide the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{redraw_form}{}
-  Redraw the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{set_form_position}{x, y}
-Set the form's position.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{freeze_form}{}
-Freeze the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{unfreeze_form}{}
-  Unfreeze the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{activate_form}{}
-  Activate the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{deactivate_form}{}
-  Deactivate the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{bgn_group}{}
-  Begin a new group of objects; return a group object.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{end_group}{}
-  End the current group of objects.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{find_first}{}
-  Find the first object in the form.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{find_last}{}
-  Find the last object in the form.
-\end{methoddesc}
-
-%---
-
-\begin{methoddesc}[form]{add_box}{type, x, y, w, h, name}
-Add a box object to the form.
-No extra methods.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_text}{type, x, y, w, h, name}
-Add a text object to the form.
-No extra methods.
-\end{methoddesc}
-
-%\begin{methoddesc}[form]{add_bitmap}{type, x, y, w, h, name}
-%Add a bitmap object to the form.
-%\end{methoddesc}
-
-\begin{methoddesc}[form]{add_clock}{type, x, y, w, h, name}
-Add a clock object to the form. \\
-Method:
-\method{get_clock()}.
-\end{methoddesc}
-
-%---
-
-\begin{methoddesc}[form]{add_button}{type, x, y, w, h,  name}
-Add a button object to the form. \\
-Methods:
-\method{get_button()},
-\method{set_button()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_lightbutton}{type, x, y, w, h, name}
-Add a lightbutton object to the form. \\
-Methods:
-\method{get_button()},
-\method{set_button()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_roundbutton}{type, x, y, w, h, name}
-Add a roundbutton object to the form. \\
-Methods:
-\method{get_button()},
-\method{set_button()}.
-\end{methoddesc}
-
-%---
-
-\begin{methoddesc}[form]{add_slider}{type, x, y, w, h, name}
-Add a slider object to the form. \\
-Methods:
-\method{set_slider_value()},
-\method{get_slider_value()},
-\method{set_slider_bounds()},
-\method{get_slider_bounds()},
-\method{set_slider_return()},
-\method{set_slider_size()},
-\method{set_slider_precision()},
-\method{set_slider_step()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_valslider}{type, x, y, w, h, name}
-Add a valslider object to the form. \\
-Methods:
-\method{set_slider_value()},
-\method{get_slider_value()},
-\method{set_slider_bounds()},
-\method{get_slider_bounds()},
-\method{set_slider_return()},
-\method{set_slider_size()},
-\method{set_slider_precision()},
-\method{set_slider_step()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_dial}{type, x, y, w, h, name}
-Add a dial object to the form. \\
-Methods:
-\method{set_dial_value()},
-\method{get_dial_value()},
-\method{set_dial_bounds()},
-\method{get_dial_bounds()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_positioner}{type, x, y, w, h, name}
-Add a positioner object to the form. \\
-Methods:
-\method{set_positioner_xvalue()},
-\method{set_positioner_yvalue()},
-\method{set_positioner_xbounds()},
-\method{set_positioner_ybounds()},
-\method{get_positioner_xvalue()},
-\method{get_positioner_yvalue()},
-\method{get_positioner_xbounds()},
-\method{get_positioner_ybounds()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_counter}{type, x, y, w, h, name}
-Add a counter object to the form. \\
-Methods:
-\method{set_counter_value()},
-\method{get_counter_value()},
-\method{set_counter_bounds()},
-\method{set_counter_step()},
-\method{set_counter_precision()},
-\method{set_counter_return()}.
-\end{methoddesc}
-
-%---
-
-\begin{methoddesc}[form]{add_input}{type, x, y, w, h, name}
-Add a input object to the form. \\
-Methods:
-\method{set_input()},
-\method{get_input()},
-\method{set_input_color()},
-\method{set_input_return()}.
-\end{methoddesc}
-
-%---
-
-\begin{methoddesc}[form]{add_menu}{type, x, y, w, h, name}
-Add a menu object to the form. \\
-Methods:
-\method{set_menu()},
-\method{get_menu()},
-\method{addto_menu()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_choice}{type, x, y, w, h, name}
-Add a choice object to the form. \\
-Methods:
-\method{set_choice()},
-\method{get_choice()},
-\method{clear_choice()},
-\method{addto_choice()},
-\method{replace_choice()},
-\method{delete_choice()},
-\method{get_choice_text()},
-\method{set_choice_fontsize()},
-\method{set_choice_fontstyle()}.
-\end{methoddesc}
-
-\begin{methoddesc}[form]{add_browser}{type, x, y, w, h, name}
-Add a browser object to the form. \\
-Methods:
-\method{set_browser_topline()},
-\method{clear_browser()},
-\method{add_browser_line()},
-\method{addto_browser()},
-\method{insert_browser_line()},
-\method{delete_browser_line()},
-\method{replace_browser_line()},
-\method{get_browser_line()},
-\method{load_browser()},
-\method{get_browser_maxline()},
-\method{select_browser_line()},
-\method{deselect_browser_line()},
-\method{deselect_browser()},
-\method{isselected_browser_line()},
-\method{get_browser()},
-\method{set_browser_fontsize()},
-\method{set_browser_fontstyle()},
-\method{set_browser_specialkey()}.
-\end{methoddesc}
-
-%---
-
-\begin{methoddesc}[form]{add_timer}{type, x, y, w, h, name}
-Add a timer object to the form. \\
-Methods:
-\method{set_timer()},
-\method{get_timer()}.
-\end{methoddesc}
-\end{flushleft}
-
-Form objects have the following data attributes; see the FORMS
-documentation:
-
-\begin{tableiii}{l|l|l}{member}{Name}{C Type}{Meaning}
-  \lineiii{window}{int (read-only)}{GL window id}
-  \lineiii{w}{float}{form width}
-  \lineiii{h}{float}{form height}
-  \lineiii{x}{float}{form x origin}
-  \lineiii{y}{float}{form y origin}
-  \lineiii{deactivated}{int}{nonzero if form is deactivated}
-  \lineiii{visible}{int}{nonzero if form is visible}
-  \lineiii{frozen}{int}{nonzero if form is frozen}
-  \lineiii{doublebuf}{int}{nonzero if double buffering on}
-\end{tableiii}
-
-\subsection{FORMS Objects}
-\label{forms-objects}
-
-Besides methods specific to particular kinds of FORMS objects, all
-FORMS objects also have the following methods:
-
-\begin{methoddesc}[FORMS object]{set_call_back}{function, argument}
-Set the object's callback function and argument.  When the object
-needs interaction, the callback function will be called with two
-arguments: the object, and the callback argument.  (FORMS objects
-without a callback function are returned by \function{fl.do_forms()}
-or \function{fl.check_forms()} when they need interaction.)  Call this
-method without arguments to remove the callback function.
-\end{methoddesc}
-
-\begin{methoddesc}[FORMS object]{delete_object}{}
-  Delete the object.
-\end{methoddesc}
-
-\begin{methoddesc}[FORMS object]{show_object}{}
-  Show the object.
-\end{methoddesc}
-
-\begin{methoddesc}[FORMS object]{hide_object}{}
-  Hide the object.
-\end{methoddesc}
-
-\begin{methoddesc}[FORMS object]{redraw_object}{}
-  Redraw the object.
-\end{methoddesc}
-
-\begin{methoddesc}[FORMS object]{freeze_object}{}
-  Freeze the object.
-\end{methoddesc}
-
-\begin{methoddesc}[FORMS object]{unfreeze_object}{}
-  Unfreeze the object.
-\end{methoddesc}
-
-%\begin{methoddesc}[FORMS object]{handle_object}{} XXX
-%\end{methoddesc}
-
-%\begin{methoddesc}[FORMS object]{handle_object_direct}{} XXX
-%\end{methoddesc}
-
-FORMS objects have these data attributes; see the FORMS documentation:
-
-\begin{tableiii}{l|l|l}{member}{Name}{C Type}{Meaning}
-  \lineiii{objclass}{int (read-only)}{object class}
-  \lineiii{type}{int (read-only)}{object type}
-  \lineiii{boxtype}{int}{box type}
-  \lineiii{x}{float}{x origin}
-  \lineiii{y}{float}{y origin}
-  \lineiii{w}{float}{width}
-  \lineiii{h}{float}{height}
-  \lineiii{col1}{int}{primary color}
-  \lineiii{col2}{int}{secondary color}
-  \lineiii{align}{int}{alignment}
-  \lineiii{lcol}{int}{label color}
-  \lineiii{lsize}{float}{label font size}
-  \lineiii{label}{string}{label string}
-  \lineiii{lstyle}{int}{label style}
-  \lineiii{pushed}{int (read-only)}{(see FORMS docs)}
-  \lineiii{focus}{int (read-only)}{(see FORMS docs)}
-  \lineiii{belowmouse}{int (read-only)}{(see FORMS docs)}
-  \lineiii{frozen}{int (read-only)}{(see FORMS docs)}
-  \lineiii{active}{int (read-only)}{(see FORMS docs)}
-  \lineiii{input}{int (read-only)}{(see FORMS docs)}
-  \lineiii{visible}{int (read-only)}{(see FORMS docs)}
-  \lineiii{radio}{int (read-only)}{(see FORMS docs)}
-  \lineiii{automatic}{int (read-only)}{(see FORMS docs)}
-\end{tableiii}
-
-
-\section{\module{FL} ---
-         Constants used with the \module{fl} module}
-
-\declaremodule[fl-constants]{standard}{FL}
-  \platform{IRIX}
-\modulesynopsis{Constants used with the \module{fl} module.}
-
-
-This module defines symbolic constants needed to use the built-in
-module \refmodule{fl} (see above); they are equivalent to those defined in
-the C header file \code{<forms.h>} except that the name prefix
-\samp{FL_} is omitted.  Read the module source for a complete list of
-the defined names.  Suggested use:
-
-\begin{verbatim}
-import fl
-from FL import *
-\end{verbatim}
-
-
-\section{\module{flp} ---
-         Functions for loading stored FORMS designs}
-
-\declaremodule{standard}{flp}
-  \platform{IRIX}
-\modulesynopsis{Functions for loading stored FORMS designs.}
-
-
-This module defines functions that can read form definitions created
-by the `form designer' (\program{fdesign}) program that comes with the
-FORMS library (see module \refmodule{fl} above).
-
-For now, see the file \file{flp.doc} in the Python library source
-directory for a description.
-
-XXX A complete description should be inserted here!

Deleted: /python/branches/p3yk-noslice/Doc/lib/libfm.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libfm.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,94 +0,0 @@
-\section{\module{fm} ---
-         \emph{Font Manager} interface}
-
-\declaremodule{builtin}{fm}
-  \platform{IRIX}
-\modulesynopsis{\emph{Font Manager} interface for SGI workstations.}
-
-
-This module provides access to the IRIS \emph{Font Manager} library.
-\index{Font Manager, IRIS}
-\index{IRIS Font Manager}
-It is available only on Silicon Graphics machines.
-See also: \emph{4Sight User's Guide}, section 1, chapter 5: ``Using
-the IRIS Font Manager.''
-
-This is not yet a full interface to the IRIS Font Manager.
-Among the unsupported features are: matrix operations; cache
-operations; character operations (use string operations instead); some
-details of font info; individual glyph metrics; and printer matching.
-
-It supports the following operations:
-
-\begin{funcdesc}{init}{}
-Initialization function.
-Calls \cfunction{fminit()}.
-It is normally not necessary to call this function, since it is called
-automatically the first time the \module{fm} module is imported.
-\end{funcdesc}
-
-\begin{funcdesc}{findfont}{fontname}
-Return a font handle object.
-Calls \code{fmfindfont(\var{fontname})}.
-\end{funcdesc}
-
-\begin{funcdesc}{enumerate}{}
-Returns a list of available font names.
-This is an interface to \cfunction{fmenumerate()}.
-\end{funcdesc}
-
-\begin{funcdesc}{prstr}{string}
-Render a string using the current font (see the \function{setfont()} font
-handle method below).
-Calls \code{fmprstr(\var{string})}.
-\end{funcdesc}
-
-\begin{funcdesc}{setpath}{string}
-Sets the font search path.
-Calls \code{fmsetpath(\var{string})}.
-(XXX Does not work!?!)
-\end{funcdesc}
-
-\begin{funcdesc}{fontpath}{}
-Returns the current font search path.
-\end{funcdesc}
-
-Font handle objects support the following operations:
-
-\setindexsubitem{(font handle method)}
-\begin{funcdesc}{scalefont}{factor}
-Returns a handle for a scaled version of this font.
-Calls \code{fmscalefont(\var{fh}, \var{factor})}.
-\end{funcdesc}
-
-\begin{funcdesc}{setfont}{}
-Makes this font the current font.
-Note: the effect is undone silently when the font handle object is
-deleted.
-Calls \code{fmsetfont(\var{fh})}.
-\end{funcdesc}
-
-\begin{funcdesc}{getfontname}{}
-Returns this font's name.
-Calls \code{fmgetfontname(\var{fh})}.
-\end{funcdesc}
-
-\begin{funcdesc}{getcomment}{}
-Returns the comment string associated with this font.
-Raises an exception if there is none.
-Calls \code{fmgetcomment(\var{fh})}.
-\end{funcdesc}
-
-\begin{funcdesc}{getfontinfo}{}
-Returns a tuple giving some pertinent data about this font.
-This is an interface to \code{fmgetfontinfo()}.
-The returned tuple contains the following numbers:
-\code{(}\var{printermatched}, \var{fixed_width}, \var{xorig},
-\var{yorig}, \var{xsize}, \var{ysize}, \var{height},
-\var{nglyphs}\code{)}.
-\end{funcdesc}
-
-\begin{funcdesc}{getstrwidth}{string}
-Returns the width, in pixels, of \var{string} when drawn in this font.
-Calls \code{fmgetstrwidth(\var{fh}, \var{string})}.
-\end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libfnmatch.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libfnmatch.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libfnmatch.tex	Wed Jul 11 15:40:56 2007
@@ -36,6 +36,19 @@
 require a case-sensitive comparison regardless of whether that's
 standard for your operating system, use \function{fnmatchcase()}
 instead.
+
+This example will print all file names in the current directory with the
+extension \code{.txt}:
+
+\begin{verbatim}
+import fnmatch
+import os
+
+for file in os.listdir('.'):
+    if fnmatch.fnmatch(file, '*.txt'):
+        print file
+\end{verbatim}
+
 \end{funcdesc}
 
 \begin{funcdesc}{fnmatchcase}{filename, pattern}
@@ -50,6 +63,24 @@
 \versionadded{2.2}
 \end{funcdesc}
 
+\begin{funcdesc}{translate}{pattern}
+Return the shell-style \var{pattern} converted to a regular
+expression.
+
+Example:
+
+\begin{verbatim}
+>>> import fnmatch, re
+>>>
+>>> regex = fnmatch.translate('*.txt')
+>>> regex
+'.*\\.txt$'
+>>> reobj = re.compile(regex)
+>>> print reobj.match('foobar.txt')
+<_sre.SRE_Match object at 0x...>
+\end{verbatim}
+\end{funcdesc}
+
 \begin{seealso}
   \seemodule{glob}{\UNIX{} shell-style path expansion.}
 \end{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/libftplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libftplib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libftplib.tex	Wed Jul 11 15:40:56 2007
@@ -37,12 +37,16 @@
 The module defines the following items:
 
 \begin{classdesc}{FTP}{\optional{host\optional{, user\optional{,
-                       passwd\optional{, acct}}}}}
+                       passwd\optional{, acct\optional{, timeout}}}}}}
 Return a new instance of the \class{FTP} class.  When
 \var{host} is given, the method call \code{connect(\var{host})} is
 made.  When \var{user} is given, additionally the method call
 \code{login(\var{user}, \var{passwd}, \var{acct})} is made (where
 \var{passwd} and \var{acct} default to the empty string when not given).
+The optional \var{timeout} parameter specifies a timeout in seconds for the
+connection attempt (if is not specified, or passed as None, the global
+default timeout setting will be used).
+\versionchanged[\var{timeout} was added]{2.6}
 \end{classdesc}
 
 \begin{datadesc}{all_errors}
@@ -92,7 +96,7 @@
 
 \class{FTP} instances have the following methods:
 
-\begin{methoddesc}{set_debuglevel}{level}
+\begin{methoddesc}[FTP]{set_debuglevel}{level}
 Set the instance's debugging level.  This controls the amount of
 debugging output printed.  The default, \code{0}, produces no
 debugging output.  A value of \code{1} produces a moderate amount of
@@ -101,22 +105,30 @@
 logging each line sent and received on the control connection.
 \end{methoddesc}
 
-\begin{methoddesc}{connect}{host\optional{, port}}
+\begin{methoddesc}[FTP]{connect}{host\optional{, port\optional{, timeout}}}
 Connect to the given host and port.  The default port number is \code{21}, as
 specified by the FTP protocol specification.  It is rarely needed to
 specify a different port number.  This function should be called only
 once for each instance; it should not be called at all if a host was
 given when the instance was created.  All other methods can only be
 used after a connection has been made.
+
+The optional \var{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.
+
+\versionchanged[\var{timeout} was added]{2.6}
 \end{methoddesc}
 
-\begin{methoddesc}{getwelcome}{}
+\begin{methoddesc}[FTP]{getwelcome}{}
 Return the welcome message sent by the server in reply to the initial
 connection.  (This message sometimes contains disclaimers or help
 information that may be relevant to the user.)
 \end{methoddesc}
 
-\begin{methoddesc}{login}{\optional{user\optional{, passwd\optional{, acct}}}}
+\begin{methoddesc}[FTP]{login}{\optional{user\optional{, passwd\optional{, acct}}}}
 Log in as the given \var{user}.  The \var{passwd} and \var{acct}
 parameters are optional and default to the empty string.  If no
 \var{user} is specified, it defaults to \code{'anonymous'}.  If
@@ -128,23 +140,23 @@
 client has logged in.
 \end{methoddesc}
 
-\begin{methoddesc}{abort}{}
+\begin{methoddesc}[FTP]{abort}{}
 Abort a file transfer that is in progress.  Using this does not always
 work, but it's worth a try.
 \end{methoddesc}
 
-\begin{methoddesc}{sendcmd}{command}
+\begin{methoddesc}[FTP]{sendcmd}{command}
 Send a simple command string to the server and return the response
 string.
 \end{methoddesc}
 
-\begin{methoddesc}{voidcmd}{command}
+\begin{methoddesc}[FTP]{voidcmd}{command}
 Send a simple command string to the server and handle the response.
 Return nothing if a response code in the range 200--299 is received.
 Raise an exception otherwise.
 \end{methoddesc}
 
-\begin{methoddesc}{retrbinary}{command,
+\begin{methoddesc}[FTP]{retrbinary}{command,
     callback\optional{, maxblocksize\optional{, rest}}}
 Retrieve a file in binary transfer mode.  \var{command} should be an
 appropriate \samp{RETR} command: \code{'RETR \var{filename}'}.
@@ -157,7 +169,7 @@
 same thing as in the \method{transfercmd()} method.
 \end{methoddesc}
 
-\begin{methoddesc}{retrlines}{command\optional{, callback}}
+\begin{methoddesc}[FTP]{retrlines}{command\optional{, callback}}
 Retrieve a file or directory listing in \ASCII{} transfer mode.
 \var{command} should be an appropriate \samp{RETR} command (see
 \method{retrbinary()}) or a \samp{LIST} command (usually just the string
@@ -166,13 +178,13 @@
 the line to \code{sys.stdout}.
 \end{methoddesc}
 
-\begin{methoddesc}{set_pasv}{boolean}
+\begin{methoddesc}[FTP]{set_pasv}{boolean}
 Enable ``passive'' mode if \var{boolean} is true, other disable
 passive mode.  (In Python 2.0 and before, passive mode was off by
 default; in Python 2.1 and later, it is on by default.)
 \end{methoddesc}
 
-\begin{methoddesc}{storbinary}{command, file\optional{, blocksize}}
+\begin{methoddesc}[FTP]{storbinary}{command, file\optional{, blocksize}}
 Store a file in binary transfer mode.  \var{command} should be an
 appropriate \samp{STOR} command: \code{"STOR \var{filename}"}.
 \var{file} is an open file object which is read until \EOF{} using its
@@ -181,14 +193,14 @@
 \versionchanged[default for \var{blocksize} added]{2.1}
 \end{methoddesc}
 
-\begin{methoddesc}{storlines}{command, file}
+\begin{methoddesc}[FTP]{storlines}{command, file}
 Store a file in \ASCII{} transfer mode.  \var{command} should be an
 appropriate \samp{STOR} command (see \method{storbinary()}).  Lines are
 read until \EOF{} from the open file object \var{file} using its
 \method{readline()} method to provide the data to be stored.
 \end{methoddesc}
 
-\begin{methoddesc}{transfercmd}{cmd\optional{, rest}}
+\begin{methoddesc}[FTP]{transfercmd}{cmd\optional{, rest}}
 Initiate a transfer over the data connection.  If the transfer is
 active, send a \samp{EPRT} or  \samp{PORT} command and the transfer command specified
 by \var{cmd}, and accept the connection.  If the server is passive,
@@ -210,7 +222,7 @@
 simply call \method{transfercmd()} without a \var{rest} argument.
 \end{methoddesc}
 
-\begin{methoddesc}{ntransfercmd}{cmd\optional{, rest}}
+\begin{methoddesc}[FTP]{ntransfercmd}{cmd\optional{, rest}}
 Like \method{transfercmd()}, but returns a tuple of the data
 connection and the expected size of the data.  If the expected size
 could not be computed, \code{None} will be returned as the expected
@@ -218,14 +230,14 @@
 \method{transfercmd()}.
 \end{methoddesc}
 
-\begin{methoddesc}{nlst}{argument\optional{, \ldots}}
+\begin{methoddesc}[FTP]{nlst}{argument\optional{, \ldots}}
 Return a list of files as returned by the \samp{NLST} command.  The
 optional \var{argument} is a directory to list (default is the current
 server directory).  Multiple arguments can be used to pass
 non-standard options to the \samp{NLST} command.
 \end{methoddesc}
 
-\begin{methoddesc}{dir}{argument\optional{, \ldots}}
+\begin{methoddesc}[FTP]{dir}{argument\optional{, \ldots}}
 Produce a directory listing as returned by the \samp{LIST} command,
 printing it to standard output.  The optional \var{argument} is a
 directory to list (default is the current server directory).  Multiple
@@ -235,41 +247,41 @@
 prints to \code{sys.stdout}.  This method returns \code{None}.
 \end{methoddesc}
 
-\begin{methoddesc}{rename}{fromname, toname}
+\begin{methoddesc}[FTP]{rename}{fromname, toname}
 Rename file \var{fromname} on the server to \var{toname}.
 \end{methoddesc}
 
-\begin{methoddesc}{delete}{filename}
+\begin{methoddesc}[FTP]{delete}{filename}
 Remove the file named \var{filename} from the server.  If successful,
 returns the text of the response, otherwise raises
 \exception{error_perm} on permission errors or
 \exception{error_reply} on other errors.
 \end{methoddesc}
 
-\begin{methoddesc}{cwd}{pathname}
+\begin{methoddesc}[FTP]{cwd}{pathname}
 Set the current directory on the server.
 \end{methoddesc}
 
-\begin{methoddesc}{mkd}{pathname}
+\begin{methoddesc}[FTP]{mkd}{pathname}
 Create a new directory on the server.
 \end{methoddesc}
 
-\begin{methoddesc}{pwd}{}
+\begin{methoddesc}[FTP]{pwd}{}
 Return the pathname of the current directory on the server.
 \end{methoddesc}
 
-\begin{methoddesc}{rmd}{dirname}
+\begin{methoddesc}[FTP]{rmd}{dirname}
 Remove the directory named \var{dirname} on the server.
 \end{methoddesc}
 
-\begin{methoddesc}{size}{filename}
+\begin{methoddesc}[FTP]{size}{filename}
 Request the size of the file named \var{filename} on the server.  On
 success, the size of the file is returned as an integer, otherwise
 \code{None} is returned.  Note that the \samp{SIZE} command is not 
 standardized, but is supported by many common server implementations.
 \end{methoddesc}
 
-\begin{methoddesc}{quit}{}
+\begin{methoddesc}[FTP]{quit}{}
 Send a \samp{QUIT} command to the server and close the connection.
 This is the ``polite'' way to close a connection, but it may raise an
 exception of the server reponds with an error to the
@@ -278,7 +290,7 @@
 calls (see below).
 \end{methoddesc}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[FTP]{close}{}
 Close the connection unilaterally.  This should not be applied to an
 already closed connection such as after a successful call to
 \method{quit()}.  After this call the \class{FTP} instance should not

Modified: python/branches/p3yk-noslice/Doc/lib/libfuncs.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libfuncs.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libfuncs.tex	Wed Jul 11 15:40:56 2007
@@ -104,6 +104,14 @@
   \versionadded{2.3}
 \end{funcdesc}
 
+\begin{funcdesc}{bin}{x}
+  Convert an integer number to a binary string.
+  The result is a valid Python expression.  If \var{x} is not a Python
+  \class{int} object, it has to define an \method{__index__} method
+  that returns an integer.
+  \versionadded{3.0}
+\end{funcdesc}
+
 \begin{funcdesc}{bool}{\optional{x}}
   Convert a value to a Boolean, using the standard truth testing
   procedure.  If \var{x} is false or omitted, this returns
@@ -118,15 +126,6 @@
                   \constant{False}]{2.3}
 \end{funcdesc}
 
-\begin{funcdesc}{callable}{object}
-  Return true if the \var{object} argument appears callable, false if
-  not.  If this returns true, it is still possible that a call fails,
-  but if it is false, calling \var{object} will never succeed.  Note
-  that classes are callable (calling a class returns a new instance);
-  class instances are callable if they have a \method{__call__()}
-  method.
-\end{funcdesc}
-
 \begin{funcdesc}{chr}{i}
   Return a string of one character whose \ASCII{} code is the integer
   \var{i}.  For example, \code{chr(97)} returns the string \code{'a'}.
@@ -175,15 +174,15 @@
   \code{\var{x} > \var{y}}.
 \end{funcdesc}
 
-\begin{funcdesc}{compile}{string, filename, kind\optional{,
+\begin{funcdesc}{compile}{source, filename, mode\optional{,
                           flags\optional{, dont_inherit}}}
-  Compile the \var{string} into a code object.  Code objects can be
+  Compile the \var{source} into a code object.  Code objects can be
   executed by a call to \function{exec()} or evaluated by a call to
   \function{eval()}.  The \var{filename} argument should
   give the file from which the code was read; pass some recognizable value
   if it wasn't read from a file (\code{'<string>'} is commonly used).
-  The \var{kind} argument specifies what kind of code must be
-  compiled; it can be \code{'exec'} if \var{string} consists of a
+  The \var{mode} argument specifies what kind of code must be
+  compiled; it can be \code{'exec'} if \var{source} consists of a
   sequence of statements, \code{'eval'} if it consists of a single
   expression, or \code{'single'} if it consists of a single
   interactive statement (in the latter case, expression statements
@@ -198,7 +197,7 @@
 
   The optional arguments \var{flags} and \var{dont_inherit}
   (which are new in Python 2.2) control which future statements (see
-  \pep{236}) affect the compilation of \var{string}.  If neither is
+  \pep{236}) affect the compilation of \var{source}.  If neither is
   present (or both are zero) the code is compiled with those future
   statements that are in effect in the code that is calling compile.
   If the \var{flags} argument is given and \var{dont_inherit} is not
@@ -274,21 +273,34 @@
 \end{funcdesc}
 
 \begin{funcdesc}{dir}{\optional{object}}
-  Without arguments, return the list of names in the current local
-  symbol table.  With an argument, attempts to return a list of valid
-  attributes for that object.  This information is gleaned from the
-  object's \member{__dict__} attribute, if defined, and from the class
-  or type object.  The list is not necessarily complete.
-  If the object is a module object, the list contains the names of the
-  module's attributes.
-  If the object is a type or class object,
-  the list contains the names of its attributes,
-  and recursively of the attributes of its bases.
-  Otherwise, the list contains the object's attributes' names,
-  the names of its class's attributes,
-  and recursively of the attributes of its class's base classes.
-  The resulting list is sorted alphabetically.
-  For example:
+  Without arguments, return the list of names in the current local scope.  With
+  an argument, attempt to return a list of valid attributes for that object.
+
+  If the object has a method named \method{__dir__()}, this method will be
+  called and must return the list of attributes. This allows objects that
+  implement a custom \function{__getattr__()} or \function{__getattribute__()}
+  function to customize the way \function{dir()} reports their attributes.
+
+  If the object does not provide \method{__dir__()}, the function tries its best
+  to gather information from the object's \member{__dict__} attribute, if
+  defined, and from its type object.  The resulting list is not necessarily
+  complete, and may be inaccurate when the object has a custom
+  \function{__getattr__()}.
+  
+  The default \function{dir()} mechanism behaves differently with different
+  types of objects, as it attempts to produce the most relevant, rather than
+  complete, information:
+  \begin{itemize}
+  \item If the object is a module object, the list contains the names of the
+    module's attributes.
+  \item If the object is a type or class object, the list contains the names of
+    its attributes, and recursively of the attributes of its bases.
+  \item Otherwise, the list contains the object's attributes' names, the names
+    of its class's attributes, and recursively of the attributes of its class's
+    base classes.
+  \end{itemize}
+  
+  The resulting list is sorted alphabetically.  For example:
 
 \begin{verbatim}
 >>> import struct
@@ -296,13 +308,19 @@
 ['__builtins__', '__doc__', '__name__', 'struct']
 >>> dir(struct)
 ['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack']
+>>> class Foo(object):
+...     def __dir__(self):
+...         return ["kan", "ga", "roo"]
+...
+>>> f = Foo()
+>>> dir(f)
+['ga', 'kan', 'roo']
 \end{verbatim}
 
-  \note{Because \function{dir()} is supplied primarily as a convenience
-  for use at an interactive prompt,
-  it tries to supply an interesting set of names more than it tries to
-  supply a rigorously or consistently defined set of names,
-  and its detailed behavior may change across releases.}
+  \note{Because \function{dir()} is supplied primarily as a convenience for use
+    at an interactive prompt, it tries to supply an interesting set of names
+    more than it tries to supply a rigorously or consistently defined set of
+    names, and its detailed behavior may change across releases.}
 \end{funcdesc}
 
 \begin{funcdesc}{divmod}{a, b}
@@ -323,14 +341,12 @@
 \end{funcdesc}
 
 \begin{funcdesc}{enumerate}{iterable}
-  Return an enumerate object. \var{iterable} must be a sequence, an
-  iterator, or some other object which supports iteration.  The
-  \method{next()} method of the iterator returned by
-  \function{enumerate()} returns a tuple containing a count (from
-  zero) and the corresponding value obtained from iterating over
-  \var{iterable}.  \function{enumerate()} is useful for obtaining an
-  indexed series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2,
-  seq[2])}, \ldots.
+  Return an enumerate object. \var{iterable} must be a sequence, an iterator, or
+  some other object which supports iteration.  The \method{__next__()} method of
+  the iterator returned by \function{enumerate()} returns a tuple containing a
+  count (from zero) and the corresponding value obtained from iterating over
+  \var{iterable}.  \function{enumerate()} is useful for obtaining an indexed
+  series: \code{(0, seq[0])}, \code{(1, seq[1])}, \code{(2, seq[2])}, \ldots.
   \versionadded{2.3}
 \end{funcdesc}
 
@@ -532,8 +548,10 @@
 \end{funcdesc}
 
 \begin{funcdesc}{hex}{x}
-  Convert an integer number (of any size) to a hexadecimal string.
-  The result is a valid Python expression.
+  Convert an integer number to a hexadecimal string.
+  The result is a valid Python expression.  If \var{x} is not a Python
+  \class{int} object, it has to define an \method{__index__} method
+  that returns an integer.
   \versionchanged[Formerly only returned an unsigned literal]{2.4}
 \end{funcdesc}
 
@@ -551,8 +569,7 @@
   representable as a Python integer, possibly embedded in whitespace.
   The \var{radix} parameter gives the base for the
   conversion and may be any integer in the range [2, 36], or zero.  If
-  \var{radix} is zero, the proper radix is guessed based on the
-  contents of string; the interpretation is the same as for integer
+  \var{radix} is zero, the interpretation is the same as for integer
   literals.  If \var{radix} is specified and \var{x} is not a string,
   \exception{TypeError} is raised.
   Otherwise, the argument may be a plain or
@@ -565,8 +582,9 @@
 \begin{funcdesc}{isinstance}{object, classinfo}
   Return true if the \var{object} argument is an instance of the
   \var{classinfo} argument, or of a (direct or indirect) subclass
-  thereof.  Also return true if \var{classinfo} is a type object and
-  \var{object} is an object of that type.  If \var{object} is not a
+  thereof.  Also return true if \var{classinfo} is a type object
+  (new-style class) and \var{object} is an object of that type or of a
+  (direct or indirect) subclass thereof.  If \var{object} is not a
   class instance or an object of the given type, the function always
   returns false.  If \var{classinfo} is neither a class object nor a
   type object, it may be a tuple of class or type objects, or may
@@ -596,7 +614,7 @@
   support either of those protocols, \exception{TypeError} is raised.
   If the second argument, \var{sentinel}, is given, then \var{o} must
   be a callable object.  The iterator created in this case will call
-  \var{o} with no arguments for each call to its \method{next()}
+  \var{o} with no arguments for each call to its \method{__next__()}
   method; if the value returned is equal to \var{sentinel},
   \exception{StopIteration} will be raised, otherwise the value will
   be returned.
@@ -624,6 +642,11 @@
   \warning{The contents of this dictionary should not be modified;
   changes may not affect the values of local variables used by the
   interpreter.}
+
+  Free variables are returned by \var{locals} when it is called in
+  a function block.  Modifications of free variables may not affect
+  the values used by the interpreter.  Free variables are not
+  returned in class blocks.
 \end{funcdesc}
 
 \begin{funcdesc}{long}{\optional{x\optional{, radix}}}
@@ -676,6 +699,12 @@
   \versionchanged[Added support for the optional \var{key} argument]{2.5}
 \end{funcdesc}
 
+\begin{funcdesc}{next}{iterator\optional{, default}}
+  Retrieve the next item from the \var{iterable} by calling its
+  \method{__next__()} method.  If \var{default} is given, it is returned if the
+  iterator is exhausted, otherwise \exception{StopIteration} is raised.
+\end{funcdesc}
+
 \begin{funcdesc}{object}{}
   Return a new featureless object.  \class{object} is a base
   for all new style classes.  It has the methods that are common
@@ -687,8 +716,10 @@
 \end{funcdesc}
 
 \begin{funcdesc}{oct}{x}
-  Convert an integer number (of any size) to an octal string.  The
-  result is a valid Python expression.
+  Convert an integer number to an octal string.  The
+  result is a valid Python expression.  If \var{x} is not a Python
+  \class{int} object, it has to define an \method{__index__} method
+  that returns an integer.
   \versionchanged[Formerly only returned an unsigned literal]{2.4}
 \end{funcdesc}
 
@@ -839,7 +870,7 @@
 \end{funcdesc}
 
 \begin{funcdesc}{range}{\optional{start,} stop\optional{, step}}
-  This is a versatile function to create lists containing arithmetic
+  This is a versatile function to create sequences containing arithmetic
   progressions.  It is most often used in \keyword{for} loops.  The
   arguments must be plain integers.  If the \var{step} argument is
   omitted, it defaults to \code{1}.  If the \var{start} argument is
@@ -853,99 +884,23 @@
   \exception{ValueError} is raised).  Example:
 
 \begin{verbatim}
->>> range(10)
+>>> list(range(10))
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
->>> range(1, 11)
+>>> list(range(1, 11))
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
->>> range(0, 30, 5)
+>>> list(range(0, 30, 5))
 [0, 5, 10, 15, 20, 25]
->>> range(0, 10, 3)
+>>> list(range(0, 10, 3))
 [0, 3, 6, 9]
->>> range(0, -10, -1)
+>>> list(range(0, -10, -1))
 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
->>> range(0)
+>>> list(range(0))
 []
->>> range(1, 0)
+>>> list(range(1, 0))
 []
 \end{verbatim}
 \end{funcdesc}
 
-\begin{funcdesc}{reload}{module}
-  Reload a previously imported \var{module}.  The
-  argument must be a module object, so it must have been successfully
-  imported before.  This is useful if you have edited the module
-  source file using an external editor and want to try out the new
-  version without leaving the Python interpreter.  The return value is
-  the module object (the same as the \var{module} argument).
-
-  When \code{reload(module)} is executed:
-
-\begin{itemize}
-
-    \item Python modules' code is recompiled and the module-level code
-    reexecuted, defining a new set of objects which are bound to names in
-    the module's dictionary.  The \code{init} function of extension
-    modules is not called a second time.
-
-    \item As with all other objects in Python the old objects are only
-    reclaimed after their reference counts drop to zero.
-
-    \item The names in the module namespace are updated to point to
-    any new or changed objects.
-
-    \item Other references to the old objects (such as names external
-    to the module) are not rebound to refer to the new objects and
-    must be updated in each namespace where they occur if that is
-    desired.
-
-\end{itemize}
-
-  There are a number of other caveats:
-
-  If a module is syntactically correct but its initialization fails,
-  the first \keyword{import} statement for it does not bind its name
-  locally, but does store a (partially initialized) module object in
-  \code{sys.modules}.  To reload the module you must first
-  \keyword{import} it again (this will bind the name to the partially
-  initialized module object) before you can \function{reload()} it.
-
-  When a module is reloaded, its dictionary (containing the module's
-  global variables) is retained.  Redefinitions of names will override
-  the old definitions, so this is generally not a problem.  If the new
-  version of a module does not define a name that was defined by the
-  old version, the old definition remains.  This feature can be used
-  to the module's advantage if it maintains a global table or cache of
-  objects --- with a \keyword{try} statement it can test for the
-  table's presence and skip its initialization if desired:
-
-\begin{verbatim}
-try:
-    cache
-except NameError:
-    cache = {}
-\end{verbatim}
-
-
-  It is legal though generally not very useful to reload built-in or
-  dynamically loaded modules, except for \refmodule{sys},
-  \refmodule[main]{__main__} and \refmodule[builtin]{__builtin__}.  In
-  many cases, however, extension modules are not designed to be
-  initialized more than once, and may fail in arbitrary ways when
-  reloaded.
-
-  If a module imports objects from another module using \keyword{from}
-  \ldots{} \keyword{import} \ldots{}, calling \function{reload()} for
-  the other module does not redefine the objects imported from it ---
-  one way around this is to re-execute the \keyword{from} statement,
-  another is to use \keyword{import} and qualified names
-  (\var{module}.\var{name}) instead.
-
-  If a module instantiates instances of a class, reloading the module
-  that defines the class does not affect the method definitions of the
-  instances --- they continue to use the old class definition.  The
-  same is true for derived classes.
-\end{funcdesc}
-
 \begin{funcdesc}{repr}{object}
   Return a string containing a printable representation of an object.
   This is the same value yielded by conversions (reverse quotes).
@@ -957,7 +912,7 @@
 
 \begin{funcdesc}{reversed}{seq}
   Return a reverse iterator.  \var{seq} must be an object which
-  supports the sequence protocol (the __len__() method and the
+  supports the sequence protocol (the \method{__len__()} method and the
   \method{__getitem__()} method with integer arguments starting at
   \code{0}).
   \versionadded{2.4}
@@ -1125,7 +1080,7 @@
   as detailed below.
 \end{funcdesc}
 
-\begin{funcdesc}{type}{name, bases, dict}
+\begin{funcdescni}{type}{name, bases, dict}
   Return a new type object.  This is essentially a dynamic form of the
   \keyword{class} statement. The \var{name} string is the class name
   and becomes the \member{__name__} attribute; the \var{bases} tuple
@@ -1142,7 +1097,7 @@
   >>> X = type('X', (object,), dict(a=1))
 \end{verbatim}
 \versionadded{2.2}          
-\end{funcdesc}
+\end{funcdescni}
 
 \begin{funcdesc}{unichr}{i}
   Return the Unicode string of one character whose Unicode code is the
@@ -1201,24 +1156,6 @@
     other scopes (such as modules) can be.  This may change.}
 \end{funcdesc}
 
-\begin{funcdesc}{xrange}{\optional{start,} stop\optional{, step}}
-  This function is very similar to \function{range()}, but returns an
-  ``xrange object'' instead of a list.  This is an opaque sequence
-  type which yields the same values as the corresponding list, without
-  actually storing them all simultaneously.  The advantage of
-  \function{xrange()} over \function{range()} is minimal (since
-  \function{xrange()} still has to create the values when asked for
-  them) except when a very large range is used on a memory-starved
-  machine or when all of the range's elements are never used (such as
-  when the loop is usually terminated with \keyword{break}).
-
-  \note{\function{xrange()} is intended to be simple and fast.
-        Implementations may impose restrictions to achieve this.
-        The C implementation of Python restricts all arguments to
-        native C longs ("short" Python integers), and also requires
-        that the number of elements fit in a native C long.}
-\end{funcdesc}
-
 \begin{funcdesc}{zip}{\optional{iterable, \moreargs}}
   This function returns a list of tuples, where the \var{i}-th tuple contains
   the \var{i}-th element from each of the argument sequences or iterables.

Modified: python/branches/p3yk-noslice/Doc/lib/libgettext.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libgettext.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libgettext.tex	Wed Jul 11 15:40:56 2007
@@ -102,9 +102,9 @@
 return \var{plural} otherwise.
 
 The Plural formula is taken from the catalog header. It is a C or
-Python expression that has a free variable n; the expression evaluates
+Python expression that has a free variable \var{n}; the expression evaluates
 to the index of the plural in the catalog. See the GNU gettext
-documentation for the precise syntax to be used in .po files, and the
+documentation for the precise syntax to be used in \file{.po} files and the
 formulas for a variety of languages.
 
 \versionadded{2.3}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libgl.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libgl.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,224 +0,0 @@
-\section{\module{gl} ---
-         \emph{Graphics Library} interface}
-
-\declaremodule{builtin}{gl}
-  \platform{IRIX}
-\modulesynopsis{Functions from the Silicon Graphics \emph{Graphics Library}.}
-
-
-This module provides access to the Silicon Graphics
-\emph{Graphics Library}.
-It is available only on Silicon Graphics machines.
-
-\warning{Some illegal calls to the GL library cause the Python
-interpreter to dump core.
-In particular, the use of most GL calls is unsafe before the first
-window is opened.}
-
-The module is too large to document here in its entirety, but the
-following should help you to get started.
-The parameter conventions for the C functions are translated to Python as
-follows:
-
-\begin{itemize}
-\item
-All (short, long, unsigned) int values are represented by Python
-integers.
-\item
-All float and double values are represented by Python floating point
-numbers.
-In most cases, Python integers are also allowed.
-\item
-All arrays are represented by one-dimensional Python lists.
-In most cases, tuples are also allowed.
-\item
-\begin{sloppypar}
-All string and character arguments are represented by Python strings,
-for instance,
-\code{winopen('Hi There!')}
-and
-\code{rotate(900, 'z')}.
-\end{sloppypar}
-\item
-All (short, long, unsigned) integer arguments or return values that are
-only used to specify the length of an array argument are omitted.
-For example, the C call
-
-\begin{verbatim}
-lmdef(deftype, index, np, props)
-\end{verbatim}
-
-is translated to Python as
-
-\begin{verbatim}
-lmdef(deftype, index, props)
-\end{verbatim}
-
-\item
-Output arguments are omitted from the argument list; they are
-transmitted as function return values instead.
-If more than one value must be returned, the return value is a tuple.
-If the C function has both a regular return value (that is not omitted
-because of the previous rule) and an output argument, the return value
-comes first in the tuple.
-Examples: the C call
-
-\begin{verbatim}
-getmcolor(i, &red, &green, &blue)
-\end{verbatim}
-
-is translated to Python as
-
-\begin{verbatim}
-red, green, blue = getmcolor(i)
-\end{verbatim}
-
-\end{itemize}
-
-The following functions are non-standard or have special argument
-conventions:
-
-\begin{funcdesc}{varray}{argument}
-%JHXXX the argument-argument added
-Equivalent to but faster than a number of
-\code{v3d()}
-calls.
-The \var{argument} is a list (or tuple) of points.
-Each point must be a tuple of coordinates
-\code{(\var{x}, \var{y}, \var{z})} or \code{(\var{x}, \var{y})}.
-The points may be 2- or 3-dimensional but must all have the
-same dimension.
-Float and int values may be mixed however.
-The points are always converted to 3D double precision points
-by assuming \code{\var{z} = 0.0} if necessary (as indicated in the man page),
-and for each point
-\code{v3d()}
-is called.
-\end{funcdesc}
-
-\begin{funcdesc}{nvarray}{}
-Equivalent to but faster than a number of
-\code{n3f}
-and
-\code{v3f}
-calls.
-The argument is an array (list or tuple) of pairs of normals and points.
-Each pair is a tuple of a point and a normal for that point.
-Each point or normal must be a tuple of coordinates
-\code{(\var{x}, \var{y}, \var{z})}.
-Three coordinates must be given.
-Float and int values may be mixed.
-For each pair,
-\code{n3f()}
-is called for the normal, and then
-\code{v3f()}
-is called for the point.
-\end{funcdesc}
-
-\begin{funcdesc}{vnarray}{}
-Similar to 
-\code{nvarray()}
-but the pairs have the point first and the normal second.
-\end{funcdesc}
-
-\begin{funcdesc}{nurbssurface}{s_k, t_k, ctl, s_ord, t_ord, type}
-% XXX s_k[], t_k[], ctl[][]
-Defines a nurbs surface.
-The dimensions of
-\code{\var{ctl}[][]}
-are computed as follows:
-\code{[len(\var{s_k}) - \var{s_ord}]},
-\code{[len(\var{t_k}) - \var{t_ord}]}.
-\end{funcdesc}
-
-\begin{funcdesc}{nurbscurve}{knots, ctlpoints, order, type}
-Defines a nurbs curve.
-The length of ctlpoints is
-\code{len(\var{knots}) - \var{order}}.
-\end{funcdesc}
-
-\begin{funcdesc}{pwlcurve}{points, type}
-Defines a piecewise-linear curve.
-\var{points}
-is a list of points.
-\var{type}
-must be
-\code{N_ST}.
-\end{funcdesc}
-
-\begin{funcdesc}{pick}{n}
-\funcline{select}{n}
-The only argument to these functions specifies the desired size of the
-pick or select buffer.
-\end{funcdesc}
-
-\begin{funcdesc}{endpick}{}
-\funcline{endselect}{}
-These functions have no arguments.
-They return a list of integers representing the used part of the
-pick/select buffer.
-No method is provided to detect buffer overrun.
-\end{funcdesc}
-
-Here is a tiny but complete example GL program in Python:
-
-\begin{verbatim}
-import gl, GL, time
-
-def main():
-    gl.foreground()
-    gl.prefposition(500, 900, 500, 900)
-    w = gl.winopen('CrissCross')
-    gl.ortho2(0.0, 400.0, 0.0, 400.0)
-    gl.color(GL.WHITE)
-    gl.clear()
-    gl.color(GL.RED)
-    gl.bgnline()
-    gl.v2f(0.0, 0.0)
-    gl.v2f(400.0, 400.0)
-    gl.endline()
-    gl.bgnline()
-    gl.v2f(400.0, 0.0)
-    gl.v2f(0.0, 400.0)
-    gl.endline()
-    time.sleep(5)
-
-main()
-\end{verbatim}
-
-
-\begin{seealso}
-  \seetitle[http://pyopengl.sourceforge.net/]
-           {PyOpenGL: The Python OpenGL Binding}
-           {An interface to OpenGL\index{OpenGL} is also available;
-            see information about the
-            \strong{PyOpenGL}\index{PyOpenGL} project online at
-            \url{http://pyopengl.sourceforge.net/}.  This may be a
-            better option if support for SGI hardware from before
-            about 1996 is not required.}
-\end{seealso}
-
-
-\section{\module{DEVICE} ---
-         Constants used with the \module{gl} module}
-
-\declaremodule{standard}{DEVICE}
-  \platform{IRIX}
-\modulesynopsis{Constants used with the \module{gl} module.}
-
-This modules defines the constants used by the Silicon Graphics
-\emph{Graphics Library} that C programmers find in the header file
-\code{<gl/device.h>}.
-Read the module source file for details.
-
-
-\section{\module{GL} ---
-         Constants used with the \module{gl} module}
-
-\declaremodule[gl-constants]{standard}{GL}
-  \platform{IRIX}
-\modulesynopsis{Constants used with the \module{gl} module.}
-
-This module contains constants used by the Silicon Graphics
-\emph{Graphics Library} from the C header file \code{<gl/gl.h>}.
-Read the module source file for details.

Deleted: /python/branches/p3yk-noslice/Doc/lib/libgopherlib.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libgopherlib.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,36 +0,0 @@
-\section{\module{gopherlib} ---
-         Gopher protocol client}
-
-\declaremodule{standard}{gopherlib}
-\modulesynopsis{Gopher protocol client (requires sockets).}
-
-\deprecated{2.5}{The \code{gopher} protocol is not in active use
-                 anymore.}
-
-\indexii{Gopher}{protocol}
-
-This module provides a minimal implementation of client side of the
-Gopher protocol.  It is used by the module \refmodule{urllib} to
-handle URLs that use the Gopher protocol.
-
-The module defines the following functions:
-
-\begin{funcdesc}{send_selector}{selector, host\optional{, port}}
-Send a \var{selector} string to the gopher server at \var{host} and
-\var{port} (default \code{70}).  Returns an open file object from
-which the returned document can be read.
-\end{funcdesc}
-
-\begin{funcdesc}{send_query}{selector, query, host\optional{, port}}
-Send a \var{selector} string and a \var{query} string to a gopher
-server at \var{host} and \var{port} (default \code{70}).  Returns an
-open file object from which the returned document can be read.
-\end{funcdesc}
-
-Note that the data returned by the Gopher server can be of any type,
-depending on the first character of the selector string.  If the data
-is text (first character of the selector is \samp{0}), lines are
-terminated by CRLF, and the data is terminated by a line consisting of
-a single \samp{.}, and a leading \samp{.} should be stripped from
-lines that begin with \samp{..}.  Directory listings (first character
-of the selector is \samp{1}) are transferred using the same protocol.

Modified: python/branches/p3yk-noslice/Doc/lib/libhmac.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libhmac.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libhmac.tex	Wed Jul 11 15:40:56 2007
@@ -15,7 +15,7 @@
   Return a new hmac object.  If \var{msg} is present, the method call
   \code{update(\var{msg})} is made. \var{digestmod} is the digest
   constructor or module for the HMAC object to use. It defaults to 
-  the \code{\refmodule{hashlib}.md5} constructor.  \note{The md5 hash
+  the \function{\refmodule{hashlib}.md5} constructor.  \note{The md5 hash
   has known weaknesses but remains the default for backwards compatibility.
   Choose a better one for your application.}
 \end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libhotshot.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libhotshot.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libhotshot.tex	Wed Jul 11 15:40:56 2007
@@ -48,25 +48,25 @@
 
 Profile objects have the following methods:
 
-\begin{methoddesc}{addinfo}{key, value}
+\begin{methoddesc}[Profile]{addinfo}{key, value}
 Add an arbitrary labelled value to the profile output.
 \end{methoddesc}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[Profile]{close}{}
 Close the logfile and terminate the profiler.
 \end{methoddesc}
 
-\begin{methoddesc}{fileno}{}
+\begin{methoddesc}[Profile]{fileno}{}
 Return the file descriptor of the profiler's log file.
 \end{methoddesc}
 
-\begin{methoddesc}{run}{cmd}
+\begin{methoddesc}[Profile]{run}{cmd}
 Profile an \function{exec()}-compatible string in the script environment.
 The globals from the \refmodule[main]{__main__} module are used as
 both the globals and locals for the script.
 \end{methoddesc}
 
-\begin{methoddesc}{runcall}{func, *args, **keywords}
+\begin{methoddesc}[Profile]{runcall}{func, *args, **keywords}
 Profile a single call of a callable.
 Additional positional and keyword arguments may be passed
 along; the result of the call is returned, and exceptions are
@@ -75,16 +75,16 @@
 \end{methoddesc}
 
 
-\begin{methoddesc}{runctx}{cmd, globals, locals}
+\begin{methoddesc}[Profile]{runctx}{cmd, globals, locals}
 Profile an \function{exec()}-compatible string in a specific environment.
 The string is compiled before profiling begins.
 \end{methoddesc}
 
-\begin{methoddesc}{start}{}
+\begin{methoddesc}[Profile]{start}{}
 Start the profiler.
 \end{methoddesc}
 
-\begin{methoddesc}{stop}{}
+\begin{methoddesc}[Profile]{stop}{}
 Stop the profiler.
 \end{methoddesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libhtmllib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libhtmllib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libhtmllib.tex	Wed Jul 11 15:40:56 2007
@@ -96,11 +96,11 @@
 In addition to tag methods, the \class{HTMLParser} class provides some
 additional methods and instance variables for use within tag methods.
 
-\begin{memberdesc}{formatter}
+\begin{memberdesc}[HTMLParser]{formatter}
 This is the formatter instance associated with the parser.
 \end{memberdesc}
 
-\begin{memberdesc}{nofill}
+\begin{memberdesc}[HTMLParser]{nofill}
 Boolean flag which should be true when whitespace should not be
 collapsed, or false when it should be.  In general, this should only
 be true when character data is to be treated as ``preformatted'' text,
@@ -109,7 +109,7 @@
 \end{memberdesc}
 
 
-\begin{methoddesc}{anchor_bgn}{href, name, type}
+\begin{methoddesc}[HTMLParser]{anchor_bgn}{href, name, type}
 This method is called at the start of an anchor region.  The arguments
 correspond to the attributes of the \code{<A>} tag with the same
 names.  The default implementation maintains a list of hyperlinks
@@ -118,27 +118,27 @@
 \member{anchorlist}.
 \end{methoddesc}
 
-\begin{methoddesc}{anchor_end}{}
+\begin{methoddesc}[HTMLParser]{anchor_end}{}
 This method is called at the end of an anchor region.  The default
 implementation adds a textual footnote marker using an index into the
 list of hyperlinks created by \method{anchor_bgn()}.
 \end{methoddesc}
 
-\begin{methoddesc}{handle_image}{source, alt\optional{, ismap\optional{,
+\begin{methoddesc}[HTMLParser]{handle_image}{source, alt\optional{, ismap\optional{,
                                  align\optional{, width\optional{, height}}}}}
 This method is called to handle images.  The default implementation
 simply passes the \var{alt} value to the \method{handle_data()}
 method.
 \end{methoddesc}
 
-\begin{methoddesc}{save_bgn}{}
+\begin{methoddesc}[HTMLParser]{save_bgn}{}
 Begins saving character data in a buffer instead of sending it to the
 formatter object.  Retrieve the stored data via \method{save_end()}.
 Use of the \method{save_bgn()} / \method{save_end()} pair may not be
 nested.
 \end{methoddesc}
 
-\begin{methoddesc}{save_end}{}
+\begin{methoddesc}[HTMLParser]{save_end}{}
 Ends buffering character data and returns all data saved since the
 preceding call to \method{save_bgn()}.  If the \member{nofill} flag is
 false, whitespace is collapsed to single spaces.  A call to this

Modified: python/branches/p3yk-noslice/Doc/lib/libhtmlparser.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libhtmlparser.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libhtmlparser.tex	Wed Jul 11 15:40:56 2007
@@ -75,14 +75,18 @@
 be overridden by a derived class; the base class implementation does
 nothing.  
 
-The \var{tag} argument is the name of the tag converted to
-lower case.  The \var{attrs} argument is a list of \code{(\var{name},
-\var{value})} pairs containing the attributes found inside the tag's
-\code{<>} brackets.  The \var{name} will be translated to lower case
-and double quotes and backslashes in the \var{value} have been
-interpreted.  For instance, for the tag \code{<A
-HREF="http://www.cwi.nl/">}, this method would be called as
+The \var{tag} argument is the name of the tag converted to lower case.
+The \var{attrs} argument is a list of \code{(\var{name}, \var{value})}
+pairs containing the attributes found inside the tag's \code{<>}
+brackets.  The \var{name} will be translated to lower case, and quotes
+in the \var{value} have been removed, and character and entity
+references have been replaced.  For instance, for the tag \code{<A
+  HREF="http://www.cwi.nl/">}, this method would be called as
 \samp{handle_starttag('a', [('href', 'http://www.cwi.nl/')])}.
+
+\versionchanged[All entity references from htmlentitydefs are now
+replaced in the attribute values]{2.6}
+
 \end{methoddesc}
 
 \begin{methoddesc}{handle_startendtag}{tag, attrs}

Modified: python/branches/p3yk-noslice/Doc/lib/libhttplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libhttplib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libhttplib.tex	Wed Jul 11 15:40:56 2007
@@ -26,23 +26,35 @@
 
 The module provides the following classes:
 
-\begin{classdesc}{HTTPConnection}{host\optional{, port}}
+\begin{classdesc}{HTTPConnection}{host\optional{, port\optional{,
+		  strict\optional{, timeout}}}}
 An \class{HTTPConnection} instance represents one transaction with an HTTP
 server.  It should be instantiated passing it a host and optional port number.
 If no port number is passed, the port is extracted from the host string if it
 has the form \code{\var{host}:\var{port}}, else the default HTTP port (80) is
-used.  For example, the following calls all create instances that connect to
+used.  When True, the optional parameter \var{strict}
+causes \code{BadStatusLine} to be raised if the status line can't be parsed
+as a valid HTTP/1.0 or 1.1 status line.  If the optional \var{timeout}
+parameter is given, connection attempts will timeout after that many
+seconds (if it is not given or \code{None}, 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:
 
 \begin{verbatim}
 >>> h1 = httplib.HTTPConnection('www.cwi.nl')
 >>> h2 = httplib.HTTPConnection('www.cwi.nl:80')
 >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80)
+>>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10)
 \end{verbatim}
 \versionadded{2.0}
+\versionchanged[\var{timeout} was added]{2.6}
 \end{classdesc}
 
-\begin{classdesc}{HTTPSConnection}{host\optional{, port, key_file, cert_file}}
+\begin{classdesc}{HTTPSConnection}{host\optional{, port\optional{,
+		  key_file\optional{, cert_file\optional{,
+		  strict\optional{, timeout}}}}}}
 A subclass of \class{HTTPConnection} that uses SSL for communication with
 secure servers.  Default port is \code{443}.
 \var{key_file} is
@@ -52,6 +64,7 @@
 \warning{This does not do any certificate verification!}
 
 \versionadded{2.0}
+\versionchanged[\var{timeout} was added]{2.6}
 \end{classdesc}
 
 \begin{classdesc}{HTTPResponse}{sock\optional{, debuglevel=0}\optional{, strict=0}}
@@ -300,7 +313,7 @@
 
 \class{HTTPConnection} instances have the following methods:
 
-\begin{methoddesc}{request}{method, url\optional{, body\optional{, headers}}}
+\begin{methoddesc}[HTTPConnection]{request}{method, url\optional{, body\optional{, headers}}}
 This will send a request to the server using the HTTP request method
 \var{method} and the selector \var{url}.  If the \var{body} argument is
 present, it should be a string of data to send after the headers are finished.
@@ -314,24 +327,24 @@
 \versionchanged[\var{body} can be a file object]{2.6}
 \end{methoddesc}
 
-\begin{methoddesc}{getresponse}{}
+\begin{methoddesc}[HTTPConnection]{getresponse}{}
 Should be called after a request is sent to get the response from the server.
 Returns an \class{HTTPResponse} instance.
 \note{Note that you must have read the whole response before you can send a new
 request to the server.}
 \end{methoddesc}
 
-\begin{methoddesc}{set_debuglevel}{level}
+\begin{methoddesc}[HTTPConnection]{set_debuglevel}{level}
 Set the debugging level (the amount of debugging output printed).
 The default debug level is \code{0}, meaning no debugging output is
 printed.
 \end{methoddesc}
 
-\begin{methoddesc}{connect}{}
+\begin{methoddesc}[HTTPConnection]{connect}{}
 Connect to the server specified when the object was created.
 \end{methoddesc}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[HTTPConnection]{close}{}
 Close the connection to the server.
 \end{methoddesc}
 
@@ -339,7 +352,7 @@
 you can also send your request step by step, by using the four functions
 below.
 
-\begin{methoddesc}{putrequest}{request, selector\optional{,
+\begin{methoddesc}[HTTPConnection]{putrequest}{request, selector\optional{,
 skip\_host\optional{, skip_accept_encoding}}}
 This should be the first call after the connection to the server has
 been made.  It sends a line to the server consisting of the
@@ -351,18 +364,18 @@
 \versionchanged[\var{skip_accept_encoding} argument added]{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{putheader}{header, argument\optional{, ...}}
+\begin{methoddesc}[HTTPConnection]{putheader}{header, argument\optional{, ...}}
 Send an \rfc{822}-style header to the server.  It sends a line to the
 server consisting of the header, a colon and a space, and the first
 argument.  If more arguments are given, continuation lines are sent,
 each consisting of a tab and an argument.
 \end{methoddesc}
 
-\begin{methoddesc}{endheaders}{}
+\begin{methoddesc}[HTTPConnection]{endheaders}{}
 Send a blank line to the server, signalling the end of the headers.
 \end{methoddesc}
 
-\begin{methoddesc}{send}{data}
+\begin{methoddesc}[HTTPConnection]{send}{data}
 Send data to the server.  This should be used directly only after the
 \method{endheaders()} method has been called and before
 \method{getresponse()} is called.
@@ -372,34 +385,34 @@
 
 \class{HTTPResponse} instances have the following methods and attributes:
 
-\begin{methoddesc}{read}{\optional{amt}}
+\begin{methoddesc}[HTTPResponse]{read}{\optional{amt}}
 Reads and returns the response body, or up to the next \var{amt} bytes.
 \end{methoddesc}
 
-\begin{methoddesc}{getheader}{name\optional{, default}}
+\begin{methoddesc}[HTTPResponse]{getheader}{name\optional{, default}}
 Get the contents of the header \var{name}, or \var{default} if there is no
 matching header.
 \end{methoddesc}
 
-\begin{methoddesc}{getheaders}{}
+\begin{methoddesc}[HTTPResponse]{getheaders}{}
 Return a list of (header, value) tuples. \versionadded{2.4}
 \end{methoddesc}
 
-\begin{datadesc}{msg}
+\begin{memberdesc}[HTTPResponse]{msg}
   A \class{mimetools.Message} instance containing the response headers.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{datadesc}{version}
+\begin{memberdesc}[HTTPResponse]{version}
   HTTP protocol version used by server.  10 for HTTP/1.0, 11 for HTTP/1.1.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{datadesc}{status}
+\begin{memberdesc}[HTTPResponse]{status}
   Status code returned by server.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{datadesc}{reason}
+\begin{memberdesc}[HTTPResponse]{reason}
   Reason phrase returned by server.
-\end{datadesc}
+\end{memberdesc}
 
 
 \subsection{Examples \label{httplib-examples}}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libimageop.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libimageop.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,100 +0,0 @@
-\section{\module{imageop} ---
-         Manipulate raw image data}
-
-\declaremodule{builtin}{imageop}
-\modulesynopsis{Manipulate raw image data.}
-
-
-The \module{imageop} module contains some useful operations on images.
-It operates on images consisting of 8 or 32 bit pixels stored in
-Python strings.  This is the same format as used by
-\function{gl.lrectwrite()} and the \refmodule{imgfile} module.
-
-The module defines the following variables and functions:
-
-\begin{excdesc}{error}
-This exception is raised on all errors, such as unknown number of bits
-per pixel, etc.
-\end{excdesc}
-
-
-\begin{funcdesc}{crop}{image, psize, width, height, x0, y0, x1, y1}
-Return the selected part of \var{image}, which should be
-\var{width} by \var{height} in size and consist of pixels of
-\var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like
-the \function{gl.lrectread()} parameters, i.e.\ the boundary is
-included in the new image.  The new boundaries need not be inside the
-picture.  Pixels that fall outside the old image will have their value
-set to zero.  If \var{x0} is bigger than \var{x1} the new image is
-mirrored.  The same holds for the y coordinates.
-\end{funcdesc}
-
-\begin{funcdesc}{scale}{image, psize, width, height, newwidth, newheight}
-Return \var{image} scaled to size \var{newwidth} by \var{newheight}.
-No interpolation is done, scaling is done by simple-minded pixel
-duplication or removal.  Therefore, computer-generated images or
-dithered images will not look nice after scaling.
-\end{funcdesc}
-
-\begin{funcdesc}{tovideo}{image, psize, width, height}
-Run a vertical low-pass filter over an image.  It does so by computing
-each destination pixel as the average of two vertically-aligned source
-pixels.  The main use of this routine is to forestall excessive
-flicker if the image is displayed on a video device that uses
-interlacing, hence the name.
-\end{funcdesc}
-
-\begin{funcdesc}{grey2mono}{image, width, height, threshold}
-Convert a 8-bit deep greyscale image to a 1-bit deep image by
-thresholding all the pixels.  The resulting image is tightly packed and
-is probably only useful as an argument to \function{mono2grey()}.
-\end{funcdesc}
-
-\begin{funcdesc}{dither2mono}{image, width, height}
-Convert an 8-bit greyscale image to a 1-bit monochrome image using a
-(simple-minded) dithering algorithm.
-\end{funcdesc}
-
-\begin{funcdesc}{mono2grey}{image, width, height, p0, p1}
-Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
-All pixels that are zero-valued on input get value \var{p0} on output
-and all one-value input pixels get value \var{p1} on output.  To
-convert a monochrome black-and-white image to greyscale pass the
-values \code{0} and \code{255} respectively.
-\end{funcdesc}
-
-\begin{funcdesc}{grey2grey4}{image, width, height}
-Convert an 8-bit greyscale image to a 4-bit greyscale image without
-dithering.
-\end{funcdesc}
-
-\begin{funcdesc}{grey2grey2}{image, width, height}
-Convert an 8-bit greyscale image to a 2-bit greyscale image without
-dithering.
-\end{funcdesc}
-
-\begin{funcdesc}{dither2grey2}{image, width, height}
-Convert an 8-bit greyscale image to a 2-bit greyscale image with
-dithering.  As for \function{dither2mono()}, the dithering algorithm
-is currently very simple.
-\end{funcdesc}
-
-\begin{funcdesc}{grey42grey}{image, width, height}
-Convert a 4-bit greyscale image to an 8-bit greyscale image.
-\end{funcdesc}
-
-\begin{funcdesc}{grey22grey}{image, width, height}
-Convert a 2-bit greyscale image to an 8-bit greyscale image.
-\end{funcdesc}
-
-\begin{datadesc}{backward_compatible}
-If set to 0, the functions in this module use a non-backward
-compatible way of representing multi-byte pixels on little-endian
-systems.  The SGI for which this module was originally written is a
-big-endian system, so setting this variable will have no effect.
-However, the code wasn't originally intended to run on anything else,
-so it made assumptions about byte order which are not universal.
-Setting this variable to 0 will cause the byte order to be reversed on
-little-endian systems, so that it then is the same as on big-endian
-systems.
-\end{datadesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libimaplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libimaplib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libimaplib.tex	Wed Jul 11 15:40:56 2007
@@ -153,11 +153,11 @@
 An \class{IMAP4} instance has the following methods:
 
 
-\begin{methoddesc}{append}{mailbox, flags, date_time, message}
+\begin{methoddesc}[IMAP4]{append}{mailbox, flags, date_time, message}
   Append \var{message} to named mailbox. 
 \end{methoddesc}
 
-\begin{methoddesc}{authenticate}{mechanism, authobject}
+\begin{methoddesc}[IMAP4]{authenticate}{mechanism, authobject}
   Authenticate command --- requires response processing.
 
   \var{mechanism} specifies which authentication mechanism is to be
@@ -176,115 +176,115 @@
   be sent instead.
 \end{methoddesc}
 
-\begin{methoddesc}{check}{}
+\begin{methoddesc}[IMAP4]{check}{}
   Checkpoint mailbox on server. 
 \end{methoddesc}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[IMAP4]{close}{}
   Close currently selected mailbox. Deleted messages are removed from
   writable mailbox. This is the recommended command before
   \samp{LOGOUT}.
 \end{methoddesc}
 
-\begin{methoddesc}{copy}{message_set, new_mailbox}
+\begin{methoddesc}[IMAP4]{copy}{message_set, new_mailbox}
   Copy \var{message_set} messages onto end of \var{new_mailbox}. 
 \end{methoddesc}
 
-\begin{methoddesc}{create}{mailbox}
+\begin{methoddesc}[IMAP4]{create}{mailbox}
   Create new mailbox named \var{mailbox}.
 \end{methoddesc}
 
-\begin{methoddesc}{delete}{mailbox}
+\begin{methoddesc}[IMAP4]{delete}{mailbox}
   Delete old mailbox named \var{mailbox}.
 \end{methoddesc}
 
-\begin{methoddesc}{deleteacl}{mailbox, who}
+\begin{methoddesc}[IMAP4]{deleteacl}{mailbox, who}
   Delete the ACLs (remove any rights) set for who on mailbox.
 \versionadded{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{expunge}{}
+\begin{methoddesc}[IMAP4]{expunge}{}
   Permanently remove deleted items from selected mailbox. Generates an
   \samp{EXPUNGE} response for each deleted message. Returned data
   contains a list of \samp{EXPUNGE} message numbers in order
   received.
 \end{methoddesc}
 
-\begin{methoddesc}{fetch}{message_set, message_parts}
+\begin{methoddesc}[IMAP4]{fetch}{message_set, message_parts}
   Fetch (parts of) messages.  \var{message_parts} should be
   a string of message part names enclosed within parentheses,
   eg: \samp{"(UID BODY[TEXT])"}.  Returned data are tuples
   of message part envelope and data.
 \end{methoddesc}
 
-\begin{methoddesc}{getacl}{mailbox}
+\begin{methoddesc}[IMAP4]{getacl}{mailbox}
   Get the \samp{ACL}s for \var{mailbox}.
   The method is non-standard, but is supported by the \samp{Cyrus} server.
 \end{methoddesc}
 
-\begin{methoddesc}{getannotation}{mailbox, entry, attribute}
+\begin{methoddesc}[IMAP4]{getannotation}{mailbox, entry, attribute}
   Retrieve the specified \samp{ANNOTATION}s for \var{mailbox}.
   The method is non-standard, but is supported by the \samp{Cyrus} server.
 \versionadded{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}{getquota}{root}
+\begin{methoddesc}[IMAP4]{getquota}{root}
   Get the \samp{quota} \var{root}'s resource usage and limits.
   This method is part of the IMAP4 QUOTA extension defined in rfc2087.
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{getquotaroot}{mailbox}
+\begin{methoddesc}[IMAP4]{getquotaroot}{mailbox}
   Get the list of \samp{quota} \samp{roots} for the named \var{mailbox}.
   This method is part of the IMAP4 QUOTA extension defined in rfc2087.
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{list}{\optional{directory\optional{, pattern}}}
+\begin{methoddesc}[IMAP4]{list}{\optional{directory\optional{, pattern}}}
   List mailbox names in \var{directory} matching
   \var{pattern}.  \var{directory} defaults to the top-level mail
   folder, and \var{pattern} defaults to match anything.  Returned data
   contains a list of \samp{LIST} responses.
 \end{methoddesc}
 
-\begin{methoddesc}{login}{user, password}
+\begin{methoddesc}[IMAP4]{login}{user, password}
   Identify the client using a plaintext password.
   The \var{password} will be quoted.
 \end{methoddesc}
 
-\begin{methoddesc}{login_cram_md5}{user, password}
+\begin{methoddesc}[IMAP4]{login_cram_md5}{user, password}
   Force use of \samp{CRAM-MD5} authentication when identifying the
   client to protect the password.  Will only work if the server
   \samp{CAPABILITY} response includes the phrase \samp{AUTH=CRAM-MD5}.
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{logout}{}
+\begin{methoddesc}[IMAP4]{logout}{}
   Shutdown connection to server. Returns server \samp{BYE} response.
 \end{methoddesc}
 
-\begin{methoddesc}{lsub}{\optional{directory\optional{, pattern}}}
+\begin{methoddesc}[IMAP4]{lsub}{\optional{directory\optional{, pattern}}}
   List subscribed mailbox names in directory matching pattern.
   \var{directory} defaults to the top level directory and
   \var{pattern} defaults to match any mailbox.
   Returned data are tuples of message part envelope and data.
 \end{methoddesc}
 
-\begin{methoddesc}{myrights}{mailbox}
+\begin{methoddesc}[IMAP4]{myrights}{mailbox}
   Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
 \versionadded{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{namespace}{}
+\begin{methoddesc}[IMAP4]{namespace}{}
   Returns IMAP namespaces as defined in RFC2342.
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{noop}{}
+\begin{methoddesc}[IMAP4]{noop}{}
   Send \samp{NOOP} to server.
 \end{methoddesc}
 
-\begin{methoddesc}{open}{host, port}
+\begin{methoddesc}[IMAP4]{open}{host, port}
   Opens socket to \var{port} at \var{host}.
   The connection objects established by this method
   will be used in the \code{read}, \code{readline}, \code{send}, and
@@ -292,42 +292,42 @@
   You may override this method.
 \end{methoddesc}
 
-\begin{methoddesc}{partial}{message_num, message_part, start, length}
+\begin{methoddesc}[IMAP4]{partial}{message_num, message_part, start, length}
   Fetch truncated part of a message.
   Returned data is a tuple of message part envelope and data.
 \end{methoddesc}
 
-\begin{methoddesc}{proxyauth}{user}
+\begin{methoddesc}[IMAP4]{proxyauth}{user}
   Assume authentication as \var{user}.
   Allows an authorised administrator to proxy into any user's mailbox.
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{read}{size}
+\begin{methoddesc}[IMAP4]{read}{size}
   Reads \var{size} bytes from the remote server.
   You may override this method.
 \end{methoddesc}
 
-\begin{methoddesc}{readline}{}
+\begin{methoddesc}[IMAP4]{readline}{}
   Reads one line from the remote server.
   You may override this method.
 \end{methoddesc}
 
-\begin{methoddesc}{recent}{}
+\begin{methoddesc}[IMAP4]{recent}{}
   Prompt server for an update. Returned data is \code{None} if no new
   messages, else value of \samp{RECENT} response.
 \end{methoddesc}
 
-\begin{methoddesc}{rename}{oldmailbox, newmailbox}
+\begin{methoddesc}[IMAP4]{rename}{oldmailbox, newmailbox}
   Rename mailbox named \var{oldmailbox} to \var{newmailbox}.
 \end{methoddesc}
 
-\begin{methoddesc}{response}{code}
+\begin{methoddesc}[IMAP4]{response}{code}
   Return data for response \var{code} if received, or
   \code{None}. Returns the given code, instead of the usual type.
 \end{methoddesc}
 
-\begin{methoddesc}{search}{charset, criterion\optional{, ...}}
+\begin{methoddesc}[IMAP4]{search}{charset, criterion\optional{, ...}}
   Search mailbox for matching messages.  \var{charset} may be
   \code{None}, in which case no \samp{CHARSET} will be specified in the
   request to the server.  The IMAP protocol requires that at least one
@@ -345,45 +345,45 @@
 \end{verbatim}
 \end{methoddesc}
 
-\begin{methoddesc}{select}{\optional{mailbox\optional{, readonly}}}
+\begin{methoddesc}[IMAP4]{select}{\optional{mailbox\optional{, readonly}}}
   Select a mailbox. Returned data is the count of messages in
   \var{mailbox} (\samp{EXISTS} response).  The default \var{mailbox}
   is \code{'INBOX'}.  If the \var{readonly} flag is set, modifications
   to the mailbox are not allowed.
 \end{methoddesc}
 
-\begin{methoddesc}{send}{data}
+\begin{methoddesc}[IMAP4]{send}{data}
   Sends \code{data} to the remote server.
   You may override this method.
 \end{methoddesc}
 
-\begin{methoddesc}{setacl}{mailbox, who, what}
+\begin{methoddesc}[IMAP4]{setacl}{mailbox, who, what}
   Set an \samp{ACL} for \var{mailbox}.
   The method is non-standard, but is supported by the \samp{Cyrus} server.
 \end{methoddesc}
 
-\begin{methoddesc}{setannotation}{mailbox, entry, attribute\optional{, ...}}
+\begin{methoddesc}[IMAP4]{setannotation}{mailbox, entry, attribute\optional{, ...}}
   Set \samp{ANNOTATION}s for \var{mailbox}.
   The method is non-standard, but is supported by the \samp{Cyrus} server.
 \versionadded{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}{setquota}{root, limits}
+\begin{methoddesc}[IMAP4]{setquota}{root, limits}
   Set the \samp{quota} \var{root}'s resource \var{limits}.
   This method is part of the IMAP4 QUOTA extension defined in rfc2087.
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{shutdown}{}
+\begin{methoddesc}[IMAP4]{shutdown}{}
   Close connection established in \code{open}.
   You may override this method.
 \end{methoddesc}
 
-\begin{methoddesc}{socket}{}
+\begin{methoddesc}[IMAP4]{socket}{}
   Returns socket instance used to connect to server.
 \end{methoddesc}
 
-\begin{methoddesc}{sort}{sort_criteria, charset, search_criterion\optional{, ...}}
+\begin{methoddesc}[IMAP4]{sort}{sort_criteria, charset, search_criterion\optional{, ...}}
   The \code{sort} command is a variant of \code{search} with sorting
   semantics for the results.  Returned data contains a space separated
   list of matching message numbers.
@@ -402,11 +402,11 @@
   This is an \samp{IMAP4rev1} extension command.
 \end{methoddesc}
 
-\begin{methoddesc}{status}{mailbox, names}
+\begin{methoddesc}[IMAP4]{status}{mailbox, names}
   Request named status conditions for \var{mailbox}. 
 \end{methoddesc}
 
-\begin{methoddesc}{store}{message_set, command, flag_list}
+\begin{methoddesc}[IMAP4]{store}{message_set, command, flag_list}
   Alters flag dispositions for messages in mailbox.  \var{command} is
   specified by section 6.4.6 of \rfc{2060} as being one of "FLAGS", "+FLAGS",
   or "-FLAGS", optionally with a suffix of ".SILENT".
@@ -421,11 +421,11 @@
 \end{verbatim}
 \end{methoddesc}
 
-\begin{methoddesc}{subscribe}{mailbox}
+\begin{methoddesc}[IMAP4]{subscribe}{mailbox}
   Subscribe to new mailbox.
 \end{methoddesc}
 
-\begin{methoddesc}{thread}{threading_algorithm, charset,
+\begin{methoddesc}[IMAP4]{thread}{threading_algorithm, charset,
                            search_criterion\optional{, ...}}
   The \code{thread} command is a variant of \code{search} with
   threading semantics for the results.  Returned data contains a space
@@ -448,18 +448,18 @@
   This is an \samp{IMAP4rev1} extension command. \versionadded{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{uid}{command, arg\optional{, ...}}
+\begin{methoddesc}[IMAP4]{uid}{command, arg\optional{, ...}}
   Execute command args with messages identified by UID, rather than
   message number.  Returns response appropriate to command.  At least
   one argument must be supplied; if none are provided, the server will
   return an error and an exception will be raised.
 \end{methoddesc}
 
-\begin{methoddesc}{unsubscribe}{mailbox}
+\begin{methoddesc}[IMAP4]{unsubscribe}{mailbox}
   Unsubscribe from old mailbox.
 \end{methoddesc}
 
-\begin{methoddesc}{xatom}{name\optional{, arg\optional{, ...}}}
+\begin{methoddesc}[IMAP4]{xatom}{name\optional{, arg\optional{, ...}}}
   Allow simple extension commands notified by server in
   \samp{CAPABILITY} response.
 \end{methoddesc}
@@ -467,7 +467,7 @@
 
 Instances of \class{IMAP4_SSL} have just one additional method:
 
-\begin{methoddesc}{ssl}{}
+\begin{methoddesc}[IMAP4_SSL]{ssl}{}
   Returns SSLObject instance used for the secure connection with the server.
 \end{methoddesc}
 
@@ -475,12 +475,12 @@
 The following attributes are defined on instances of \class{IMAP4}:
 
 
-\begin{memberdesc}{PROTOCOL_VERSION}
+\begin{memberdesc}[IMAP4]{PROTOCOL_VERSION}
 The most recent supported protocol in the
 \samp{CAPABILITY} response from the server.
 \end{memberdesc}
 
-\begin{memberdesc}{debug}
+\begin{memberdesc}[IMAP4]{debug}
 Integer value to control debugging output.  The initialize value is
 taken from the module variable \code{Debug}.  Values greater than
 three trace each command.

Deleted: /python/branches/p3yk-noslice/Doc/lib/libimgfile.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libimgfile.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,66 +0,0 @@
-\section{\module{imgfile} ---
-         Support for SGI imglib files}
-
-\declaremodule{builtin}{imgfile}
-  \platform{IRIX}
-\modulesynopsis{Support for SGI imglib files.}
-
-
-The \module{imgfile} module allows Python programs to access SGI imglib image
-files (also known as \file{.rgb} files).  The module is far from
-complete, but is provided anyway since the functionality that there is
-enough in some cases.  Currently, colormap files are not supported.
-
-The module defines the following variables and functions:
-
-\begin{excdesc}{error}
-This exception is raised on all errors, such as unsupported file type, etc.
-\end{excdesc}
-
-\begin{funcdesc}{getsizes}{file}
-This function returns a tuple \code{(\var{x}, \var{y}, \var{z})} where
-\var{x} and \var{y} are the size of the image in pixels and
-\var{z} is the number of
-bytes per pixel. Only 3 byte RGB pixels and 1 byte greyscale pixels
-are currently supported.
-\end{funcdesc}
-
-\begin{funcdesc}{read}{file}
-This function reads and decodes the image on the specified file, and
-returns it as a Python string. The string has either 1 byte greyscale
-pixels or 4 byte RGBA pixels. The bottom left pixel is the first in
-the string. This format is suitable to pass to \function{gl.lrectwrite()},
-for instance.
-\end{funcdesc}
-
-\begin{funcdesc}{readscaled}{file, x, y, filter\optional{, blur}}
-This function is identical to read but it returns an image that is
-scaled to the given \var{x} and \var{y} sizes. If the \var{filter} and
-\var{blur} parameters are omitted scaling is done by
-simply dropping or duplicating pixels, so the result will be less than
-perfect, especially for computer-generated images.
-
-Alternatively, you can specify a filter to use to smooth the image
-after scaling. The filter forms supported are \code{'impulse'},
-\code{'box'}, \code{'triangle'}, \code{'quadratic'} and
-\code{'gaussian'}. If a filter is specified \var{blur} is an optional
-parameter specifying the blurriness of the filter. It defaults to \code{1.0}.
-
-\function{readscaled()} makes no attempt to keep the aspect ratio
-correct, so that is the users' responsibility.
-\end{funcdesc}
-
-\begin{funcdesc}{ttob}{flag}
-This function sets a global flag which defines whether the scan lines
-of the image are read or written from bottom to top (flag is zero,
-compatible with SGI GL) or from top to bottom(flag is one,
-compatible with X).  The default is zero.
-\end{funcdesc}
-
-\begin{funcdesc}{write}{file, data, x, y, z}
-This function writes the RGB or greyscale data in \var{data} to image
-file \var{file}. \var{x} and \var{y} give the size of the image,
-\var{z} is 1 for 1 byte greyscale images or 3 for RGB images (which are
-stored as 4 byte values of which only the lower three bytes are used).
-These are the formats returned by \function{gl.lrectread()}.
-\end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libimp.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libimp.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libimp.tex	Wed Jul 11 15:40:56 2007
@@ -69,8 +69,7 @@
 Load a module that was previously found by \function{find_module()} (or by
 an otherwise conducted search yielding compatible results).  This
 function does more than importing the module: if the module was
-already imported, it is equivalent to a
-\function{reload()}\bifuncindex{reload}!  The \var{name} argument
+already imported, it will reload the module! The \var{name} argument
 indicates the full module name (including the package name, if this is
 a submodule of a package).  The \var{file} argument is an open file,
 and \var{filename} is the corresponding file name; these can be
@@ -286,7 +285,7 @@
 \end{verbatim}
 
 A more complete example that implements hierarchical module names and
-includes a \function{reload()}\bifuncindex{reload} function can be
+includes a \function{reload()} function can be
 found in the module \module{knee}\refmodindex{knee}.  The
 \module{knee} module can be found in \file{Demo/imputil/} in the
 Python source distribution.

Modified: python/branches/p3yk-noslice/Doc/lib/libinspect.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libinspect.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libinspect.tex	Wed Jul 11 15:40:56 2007
@@ -45,11 +45,9 @@
   \hline
   \lineiv{function}{__doc__}{documentation string}{}
   \lineiv{}{__name__}{name with which this function was defined}{}
-  \lineiv{}{func_code}{code object containing compiled function bytecode}{}
-  \lineiv{}{func_defaults}{tuple of any default values for arguments}{}
-  \lineiv{}{func_doc}{(same as __doc__)}{}
-  \lineiv{}{func_globals}{global namespace in which this function was defined}{}
-  \lineiv{}{func_name}{(same as __name__)}{}
+  \lineiv{}{__code__}{code object containing compiled function bytecode}{}
+  \lineiv{}{__defaults__}{tuple of any default values for arguments}{}
+  \lineiv{}{__globals__}{global namespace in which this function was defined}{}
   \hline
   \lineiv{traceback}{tb_frame}{frame object at this level}{}
   \lineiv{}{tb_lasti}{index of last attempted instruction in bytecode}{}

Modified: python/branches/p3yk-noslice/Doc/lib/libitertools.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libitertools.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libitertools.tex	Wed Jul 11 15:40:56 2007
@@ -138,6 +138,13 @@
   identity function and returns  the element unchanged.  Generally, the
   iterable needs to already be sorted on the same key function.
 
+  The operation of \function{groupby()} is similar to the \code{uniq} filter
+  in \UNIX{}.  It generates a break or new group every time the value
+  of the key function changes (which is why it is usually necessary
+  to have sorted the data using the same key function).  That behavior
+  differs from SQL's GROUP BY which aggregates common elements regardless
+  of their input order.
+
   The returned group is itself an iterator that shares the underlying
   iterable with \function{groupby()}.  Because the source is shared, when
   the \function{groupby} object is advanced, the previous group is no
@@ -147,6 +154,7 @@
   \begin{verbatim}
     groups = []
     uniquekeys = []
+    data = sorted(data, key=keyfunc)
     for k, g in groupby(data, keyfunc):
         groups.append(list(g))      # Store group iterator as a list
         uniquekeys.append(k)
@@ -161,19 +169,19 @@
                 key = lambda x: x
             self.keyfunc = key
             self.it = iter(iterable)
-            self.tgtkey = self.currkey = self.currvalue = xrange(0)
+            self.tgtkey = self.currkey = self.currvalue = []
         def __iter__(self):
             return self
-        def next(self):
+        def __next__(self):
             while self.currkey == self.tgtkey:
-                self.currvalue = self.it.next() # Exit on StopIteration
+                self.currvalue = next(self.it) # Exit on StopIteration
                 self.currkey = self.keyfunc(self.currvalue)
             self.tgtkey = self.currkey
             return (self.currkey, self._grouper(self.tgtkey))
         def _grouper(self, tgtkey):
             while self.currkey == tgtkey:
                 yield self.currvalue
-                self.currvalue = self.it.next() # Exit on StopIteration
+                self.currvalue = next(self.it) # Exit on StopIteration
                 self.currkey = self.keyfunc(self.currvalue)
   \end{verbatim}
   \versionadded{2.4}
@@ -227,7 +235,7 @@
      def imap(function, *iterables):
          iterables = map(iter, iterables)
          while True:
-             args = [i.next() for i in iterables]
+             args = [next(i) for i in iterables]
              if function is None:
                  yield tuple(args)
              else:
@@ -252,12 +260,12 @@
   \begin{verbatim}
      def islice(iterable, *args):
          s = slice(*args)
-         it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
-         nexti = it.next()
+         it = iter(range(s.start or 0, s.stop or sys.maxint, s.step or 1))
+         nexti = next(it)
          for i, element in enumerate(iterable):
              if i == nexti:
                  yield element
-                 nexti = it.next()          
+                 nexti = next(it)
   \end{verbatim}
 
   If \var{start} is \code{None}, then iteration starts at zero.
@@ -276,7 +284,7 @@
      def izip(*iterables):
          iterables = map(iter, iterables)
          while iterables:
-             result = [it.next() for it in iterables]
+             result = [next(it) for it in iterables]
              yield tuple(result)
   \end{verbatim}
 
@@ -297,7 +305,7 @@
   from each iterator in-turn, but the process ends when one of the iterators
   terminates.  This leaves the last fetched values in limbo (they cannot be
   returned in a final, incomplete tuple and they are cannot be pushed back
-  into the iterator for retrieval with \code{it.next()}).  In general,
+  into the iterator for retrieval with \code{next(it)}).  In general,
   \function{izip()} should only be used with unequal length inputs when you
   don't care about trailing, unmatched values from the longer iterables.
 \end{funcdesc}
@@ -342,7 +350,7 @@
              while True:
                  yield object
          else:
-             for i in xrange(times):
+             for i in range(times):
                  yield object
   \end{verbatim}
 \end{funcdesc}
@@ -360,7 +368,7 @@
      def starmap(function, iterable):
          iterable = iter(iterable)
          while True:
-             yield function(*iterable.next())
+             yield function(*next(iterable))
   \end{verbatim}
 \end{funcdesc}
 
@@ -393,7 +401,7 @@
                      item = data.pop(i)
                  yield item
          it = iter(iterable)
-         return (gen(it.next), gen(it.next))
+         return (gen(it.__next__), gen(it.__next__))
   \end{verbatim}
 
   Note, once \function{tee()} has made a split, the original \var{iterable}
@@ -425,7 +433,7 @@
 Check 1202 is for $823.14
 
 >>> import operator
->>> for cube in imap(operator.pow, xrange(1,5), repeat(3)):
+>>> for cube in imap(operator.pow, range(1,5), repeat(3)):
 ...    print cube
 ...
 1
@@ -459,7 +467,7 @@
 # is differencing with a range so that consecutive numbers all appear in
 # same group.
 >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
->>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
+>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
 ...     print map(operator.itemgetter(1), g)
 ... 
 [1]
@@ -556,10 +564,7 @@
 def pairwise(iterable):
     "s -> (s0,s1), (s1,s2), (s2, s3), ..."
     a, b = tee(iterable)
-    try:
-        b.next()
-    except StopIteration:
-        pass
+    next(b, None)
     return izip(a, b)
 
 def grouper(n, iterable, padvalue=None):

Deleted: /python/branches/p3yk-noslice/Doc/lib/libjpeg.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libjpeg.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,80 +0,0 @@
-\section{\module{jpeg} ---
-         Read and write JPEG files}
-
-\declaremodule{builtin}{jpeg}
-  \platform{IRIX}
-\modulesynopsis{Read and write image files in compressed JPEG format.}
-
-
-The module \module{jpeg} provides access to the jpeg compressor and
-decompressor written by the Independent JPEG Group
-\index{Independent JPEG Group}(IJG). JPEG is a standard for
-compressing pictures; it is defined in ISO 10918.  For details on JPEG
-or the Independent JPEG Group software refer to the JPEG standard or
-the documentation provided with the software.
-
-A portable interface to JPEG image files is available with the Python
-Imaging Library (PIL) by Fredrik Lundh.  Information on PIL is
-available at \url{http://www.pythonware.com/products/pil/}.
-\index{Python Imaging Library}
-\index{PIL (the Python Imaging Library)}
-\index{Lundh, Fredrik}
-
-The \module{jpeg} module defines an exception and some functions.
-
-\begin{excdesc}{error}
-Exception raised by \function{compress()} and \function{decompress()}
-in case of errors.
-\end{excdesc}
-
-\begin{funcdesc}{compress}{data, w, h, b}
-Treat data as a pixmap of width \var{w} and height \var{h}, with
-\var{b} bytes per pixel.  The data is in SGI GL order, so the first
-pixel is in the lower-left corner. This means that \function{gl.lrectread()}
-return data can immediately be passed to \function{compress()}.
-Currently only 1 byte and 4 byte pixels are allowed, the former being
-treated as greyscale and the latter as RGB color.
-\function{compress()} returns a string that contains the compressed
-picture, in JFIF\index{JFIF} format.
-\end{funcdesc}
-
-\begin{funcdesc}{decompress}{data}
-Data is a string containing a picture in JFIF\index{JFIF} format. It
-returns a tuple \code{(\var{data}, \var{width}, \var{height},
-\var{bytesperpixel})}.  Again, the data is suitable to pass to
-\function{gl.lrectwrite()}.
-\end{funcdesc}
-
-\begin{funcdesc}{setoption}{name, value}
-Set various options.  Subsequent \function{compress()} and
-\function{decompress()} calls will use these options.  The following
-options are available:
-
-\begin{tableii}{l|p{3in}}{code}{Option}{Effect}
-  \lineii{'forcegray'}{%
-    Force output to be grayscale, even if input is RGB.}
-  \lineii{'quality'}{%
-    Set the quality of the compressed image to a value between
-    \code{0} and \code{100} (default is \code{75}).  This only affects
-    compression.}
-  \lineii{'optimize'}{%
-    Perform Huffman table optimization.  Takes longer, but results in
-    smaller compressed image.  This only affects compression.}
-  \lineii{'smooth'}{%
-    Perform inter-block smoothing on uncompressed image.  Only useful
-    for low-quality images.  This only affects decompression.}
-\end{tableii}
-\end{funcdesc}
-
-
-\begin{seealso}
-  \seetitle{JPEG Still Image Data Compression Standard}{The 
-            canonical reference for the JPEG image format, by
-            Pennebaker and Mitchell.}
-
-  \seetitle[http://www.w3.org/Graphics/JPEG/itu-t81.pdf]{Information
-            Technology - Digital Compression and Coding of
-            Continuous-tone Still Images - Requirements and
-            Guidelines}{The ISO standard for JPEG is also published as
-            ITU T.81.  This is available online in PDF form.}
-\end{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/liblogging.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liblogging.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/liblogging.tex	Wed Jul 11 15:40:56 2007
@@ -203,7 +203,7 @@
 \begin{verbatim}
  FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
  logging.basicConfig(format=FORMAT)
- dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
+ d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
  logging.warning("Protocol problem: %s", "connection reset", extra=d)
 \end{verbatim}
 
@@ -364,13 +364,13 @@
 never instantiated directly, but always through the module-level function
 \function{logging.getLogger(name)}.
 
-\begin{datadesc}{propagate}
+\begin{memberdesc}[Logger]{propagate}
 If this evaluates to false, logging messages are not passed by this
 logger or by child loggers to higher level (ancestor) loggers. The
 constructor sets this attribute to 1.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{methoddesc}{setLevel}{lvl}
+\begin{methoddesc}[Logger]{setLevel}{lvl}
 Sets the threshold for this logger to \var{lvl}. Logging messages
 which are less severe than \var{lvl} will be ignored. When a logger is
 created, the level is set to \constant{NOTSET} (which causes all messages
@@ -393,21 +393,21 @@
 as the effective level.
 \end{methoddesc}
 
-\begin{methoddesc}{isEnabledFor}{lvl}
+\begin{methoddesc}[Logger]{isEnabledFor}{lvl}
 Indicates if a message of severity \var{lvl} would be processed by
 this logger.  This method checks first the module-level level set by
 \function{logging.disable(lvl)} and then the logger's effective level as
 determined by \method{getEffectiveLevel()}.
 \end{methoddesc}
 
-\begin{methoddesc}{getEffectiveLevel}{}
+\begin{methoddesc}[Logger]{getEffectiveLevel}{}
 Indicates the effective level for this logger. If a value other than
 \constant{NOTSET} has been set using \method{setLevel()}, it is returned.
 Otherwise, the hierarchy is traversed towards the root until a value
 other than \constant{NOTSET} is found, and that value is returned.
 \end{methoddesc}
 
-\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
+\begin{methoddesc}[Logger]{debug}{msg\optional{, *args\optional{, **kwargs}}}
 Logs a message with level \constant{DEBUG} on this logger.
 The \var{msg} is the message format string, and the \var{args} are the
 arguments which are merged into \var{msg} using the string formatting
@@ -462,67 +462,67 @@
 
 \end{methoddesc}
 
-\begin{methoddesc}{info}{msg\optional{, *args\optional{, **kwargs}}}
+\begin{methoddesc}[Logger]{info}{msg\optional{, *args\optional{, **kwargs}}}
 Logs a message with level \constant{INFO} on this logger.
 The arguments are interpreted as for \method{debug()}.
 \end{methoddesc}
 
-\begin{methoddesc}{warning}{msg\optional{, *args\optional{, **kwargs}}}
+\begin{methoddesc}[Logger]{warning}{msg\optional{, *args\optional{, **kwargs}}}
 Logs a message with level \constant{WARNING} on this logger.
 The arguments are interpreted as for \method{debug()}.
 \end{methoddesc}
 
-\begin{methoddesc}{error}{msg\optional{, *args\optional{, **kwargs}}}
+\begin{methoddesc}[Logger]{error}{msg\optional{, *args\optional{, **kwargs}}}
 Logs a message with level \constant{ERROR} on this logger.
 The arguments are interpreted as for \method{debug()}.
 \end{methoddesc}
 
-\begin{methoddesc}{critical}{msg\optional{, *args\optional{, **kwargs}}}
+\begin{methoddesc}[Logger]{critical}{msg\optional{, *args\optional{, **kwargs}}}
 Logs a message with level \constant{CRITICAL} on this logger.
 The arguments are interpreted as for \method{debug()}.
 \end{methoddesc}
 
-\begin{methoddesc}{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
+\begin{methoddesc}[Logger]{log}{lvl, msg\optional{, *args\optional{, **kwargs}}}
 Logs a message with integer level \var{lvl} on this logger.
 The other arguments are interpreted as for \method{debug()}.
 \end{methoddesc}
 
-\begin{methoddesc}{exception}{msg\optional{, *args}}
+\begin{methoddesc}[Logger]{exception}{msg\optional{, *args}}
 Logs a message with level \constant{ERROR} on this logger.
 The arguments are interpreted as for \method{debug()}. Exception info
 is added to the logging message. This method should only be called
 from an exception handler.
 \end{methoddesc}
 
-\begin{methoddesc}{addFilter}{filt}
+\begin{methoddesc}[Logger]{addFilter}{filt}
 Adds the specified filter \var{filt} to this logger.
 \end{methoddesc}
 
-\begin{methoddesc}{removeFilter}{filt}
+\begin{methoddesc}[Logger]{removeFilter}{filt}
 Removes the specified filter \var{filt} from this logger.
 \end{methoddesc}
 
-\begin{methoddesc}{filter}{record}
+\begin{methoddesc}[Logger]{filter}{record}
 Applies this logger's filters to the record and returns a true value if
 the record is to be processed.
 \end{methoddesc}
 
-\begin{methoddesc}{addHandler}{hdlr}
+\begin{methoddesc}[Logger]{addHandler}{hdlr}
 Adds the specified handler \var{hdlr} to this logger.
 \end{methoddesc}
 
-\begin{methoddesc}{removeHandler}{hdlr}
+\begin{methoddesc}[Logger]{removeHandler}{hdlr}
 Removes the specified handler \var{hdlr} from this logger.
 \end{methoddesc}
 
-\begin{methoddesc}{findCaller}{}
+\begin{methoddesc}[Logger]{findCaller}{}
 Finds the caller's source filename and line number. Returns the filename,
 line number and function name as a 3-element tuple.
 \versionchanged[The function name was added. In earlier versions, the
 filename and line number were returned as a 2-element tuple.]{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}{handle}{record}
+\begin{methoddesc}[Logger]{handle}{record}
 Handles a record by passing it to all handlers associated with this logger
 and its ancestors (until a false value of \var{propagate} is found).
 This method is used for unpickled records received from a socket, as well
@@ -530,8 +530,8 @@
 \method{filter()}.
 \end{methoddesc}
 
-\begin{methoddesc}{makeRecord}{name, lvl, fn, lno, msg, args, exc_info
-                               \optional{, func, extra}}
+\begin{methoddesc}[Logger]{makeRecord}{name, lvl, fn, lno, msg, args, exc_info
+                                       \optional{, func, extra}}
 This is a factory method which can be overridden in subclasses to create
 specialized \class{LogRecord} instances.
 \versionchanged[\var{func} and \var{extra} were added]{2.5}
@@ -875,66 +875,66 @@
 base for more useful subclasses. However, the \method{__init__()}
 method in subclasses needs to call \method{Handler.__init__()}.
 
-\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
+\begin{methoddesc}[Handler]{__init__}{level=\constant{NOTSET}}
 Initializes the \class{Handler} instance by setting its level, setting
 the list of filters to the empty list and creating a lock (using
 \method{createLock()}) for serializing access to an I/O mechanism.
 \end{methoddesc}
 
-\begin{methoddesc}{createLock}{}
+\begin{methoddesc}[Handler]{createLock}{}
 Initializes a thread lock which can be used to serialize access to
 underlying I/O functionality which may not be threadsafe.
 \end{methoddesc}
 
-\begin{methoddesc}{acquire}{}
+\begin{methoddesc}[Handler]{acquire}{}
 Acquires the thread lock created with \method{createLock()}.
 \end{methoddesc}
 
-\begin{methoddesc}{release}{}
+\begin{methoddesc}[Handler]{release}{}
 Releases the thread lock acquired with \method{acquire()}.
 \end{methoddesc}
 
-\begin{methoddesc}{setLevel}{lvl}
+\begin{methoddesc}[Handler]{setLevel}{lvl}
 Sets the threshold for this handler to \var{lvl}. Logging messages which are
 less severe than \var{lvl} will be ignored. When a handler is created, the
 level is set to \constant{NOTSET} (which causes all messages to be processed).
 \end{methoddesc}
 
-\begin{methoddesc}{setFormatter}{form}
+\begin{methoddesc}[Handler]{setFormatter}{form}
 Sets the \class{Formatter} for this handler to \var{form}.
 \end{methoddesc}
 
-\begin{methoddesc}{addFilter}{filt}
+\begin{methoddesc}[Handler]{addFilter}{filt}
 Adds the specified filter \var{filt} to this handler.
 \end{methoddesc}
 
-\begin{methoddesc}{removeFilter}{filt}
+\begin{methoddesc}[Handler]{removeFilter}{filt}
 Removes the specified filter \var{filt} from this handler.
 \end{methoddesc}
 
-\begin{methoddesc}{filter}{record}
+\begin{methoddesc}[Handler]{filter}{record}
 Applies this handler's filters to the record and returns a true value if
 the record is to be processed.
 \end{methoddesc}
 
-\begin{methoddesc}{flush}{}
+\begin{methoddesc}[Handler]{flush}{}
 Ensure all logging output has been flushed. This version does
 nothing and is intended to be implemented by subclasses.
 \end{methoddesc}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[Handler]{close}{}
 Tidy up any resources used by the handler. This version does
 nothing and is intended to be implemented by subclasses.
 \end{methoddesc}
 
-\begin{methoddesc}{handle}{record}
+\begin{methoddesc}[Handler]{handle}{record}
 Conditionally emits the specified logging record, depending on
 filters which may have been added to the handler. Wraps the actual
 emission of the record with acquisition/release of the I/O thread
 lock.
 \end{methoddesc}
 
-\begin{methoddesc}{handleError}{record}
+\begin{methoddesc}[Handler]{handleError}{record}
 This method should be called from handlers when an exception is
 encountered during an \method{emit()} call. By default it does nothing,
 which means that exceptions get silently ignored. This is what is
@@ -945,12 +945,12 @@
 processed when the exception occurred.
 \end{methoddesc}
 
-\begin{methoddesc}{format}{record}
+\begin{methoddesc}[Handler]{format}{record}
 Do formatting for a record - if a formatter is set, use it.
 Otherwise, use the default formatter for the module.
 \end{methoddesc}
 
-\begin{methoddesc}{emit}{record}
+\begin{methoddesc}[Handler]{emit}{record}
 Do whatever it takes to actually log the specified logging record.
 This version is intended to be implemented by subclasses and so
 raises a \exception{NotImplementedError}.
@@ -1138,9 +1138,6 @@
 Closes the socket.
 \end{methoddesc}
 
-\begin{methoddesc}{handleError}{}
-\end{methoddesc}
-
 \begin{methoddesc}{emit}{}
 Pickles the record's attribute dictionary and writes it to the socket in
 binary format. If there is an error with the socket, silently drops the
@@ -1211,8 +1208,11 @@
 communicate with a remote \UNIX{} machine whose address is given by
 \var{address} in the form of a \code{(\var{host}, \var{port})}
 tuple.  If \var{address} is not specified, \code{('localhost', 514)} is
-used.  The address is used to open a UDP socket.  If \var{facility} is
-not specified, \constant{LOG_USER} is used.
+used.  The address is used to open a UDP socket.  An alternative to providing
+a \code{(\var{host}, \var{port})} tuple is providing an address as a string,
+for example "/dev/log". In this case, a Unix domain socket is used to send
+the message to the syslog. If \var{facility} is not specified,
+\constant{LOG_USER} is used.
 \end{classdesc}
 
 \begin{methoddesc}{close}{}
@@ -1299,13 +1299,16 @@
 \module{logging.handlers} module, supports sending logging messages to
 an email address via SMTP.
 
-\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}
+\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject\optional{,
+                               credentials}}
 Returns a new instance of the \class{SMTPHandler} class. The
 instance is initialized with the from and to addresses and subject
 line of the email. The \var{toaddrs} should be a list of strings. To specify a
 non-standard SMTP port, use the (host, port) tuple format for the
 \var{mailhost} argument. If you use a string, the standard SMTP port
-is used.
+is used. If your SMTP server requires authentication, you can specify a
+(username, password) tuple for the \var{credentials} argument.
+\versionchanged[\var{credentials} was added]{2.6}
 \end{classdesc}
 
 \begin{methoddesc}{emit}{record}
@@ -1531,7 +1534,7 @@
 \var{exc_info} is the exception tuple obtained by calling
 \function{sys.exc_info() }(or \constant{None}, if no exception information
 is available). The \var{func} is the name of the function from which the
-logging call was made. If not specified, it defaults to \var{None}.
+logging call was made. If not specified, it defaults to \code{None}.
 \versionchanged[\var{func} was added]{2.5}
 \end{classdesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libmailbox.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmailbox.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmailbox.tex	Wed Jul 11 15:40:56 2007
@@ -1203,7 +1203,6 @@
 \end{tableii}
 
 \subsection{Exceptions}
-\label{mailbox-deprecated}
 
 The following exception classes are defined in the \module{mailbox} module:
 
@@ -1247,7 +1246,7 @@
 Older mailbox objects support only iteration and provide a single public
 method:
 
-\begin{methoddesc}{next}{}
+\begin{methoddesc}[oldmailbox]{next}{}
 Return the next message in the mailbox, created with the optional \var{factory}
 argument passed into the mailbox object's constructor. By default this is an
 \class{rfc822.Message} object (see the \refmodule{rfc822} module).  Depending
@@ -1286,13 +1285,13 @@
 separated by any line that begins exactly with the string \code{'From
 '} (note the trailing space) if preceded by exactly two newlines.
 Because of the wide-range of variations in practice, nothing else on
-the From_ line should be considered.  However, the current
+the \samp{From_} line should be considered.  However, the current
 implementation doesn't check for the leading two newlines.  This is
 usually fine for most applications.
 
 The \class{UnixMailbox} class implements a more strict version of
-From_ line checking, using a regular expression that usually correctly
-matched From_ delimiters.  It considers delimiter line to be separated
+\samp{From_} line checking, using a regular expression that usually correctly
+matched \samp{From_} delimiters.  It considers delimiter line to be separated
 by \samp{From \var{name} \var{time}} lines.  For maximum portability,
 use the \class{PortableUnixMailbox} class instead.  This class is
 identical to \class{UnixMailbox} except that individual messages are

Deleted: /python/branches/p3yk-noslice/Doc/lib/libmd5.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libmd5.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,92 +0,0 @@
-\section{\module{md5} ---
-         MD5 message digest algorithm}
-
-\declaremodule{builtin}{md5}
-\modulesynopsis{RSA's MD5 message digest algorithm.}
-
-\deprecated{2.5}{Use the \refmodule{hashlib} module instead.}
-
-This module implements the interface to RSA's MD5 message digest
-\index{message digest, MD5}
-algorithm (see also Internet \rfc{1321}).  Its use is quite
-straightforward:\ use \function{new()} to create an md5 object.
-You can now feed this object with arbitrary strings using the
-\method{update()} method, and at any point you can ask it for the
-\dfn{digest} (a strong kind of 128-bit checksum,
-a.k.a. ``fingerprint'') of the concatenation of the strings fed to it
-so far using the \method{digest()} method.
-\index{checksum!MD5}
-
-For example, to obtain the digest of the string \code{'Nobody inspects
-the spammish repetition'}:
-
-\begin{verbatim}
->>> import md5
->>> m = md5.new()
->>> m.update("Nobody inspects")
->>> m.update(" the spammish repetition")
->>> m.digest()
-'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
-\end{verbatim}
-
-More condensed:
-
-\begin{verbatim}
->>> md5.new("Nobody inspects the spammish repetition").digest()
-'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
-\end{verbatim}
-
-The following values are provided as constants in the module and as
-attributes of the md5 objects returned by \function{new()}:
-
-\begin{datadesc}{digest_size}
-  The size of the resulting digest in bytes.  This is always
-  \code{16}.
-\end{datadesc}
-
-The md5 module provides the following functions:
-
-\begin{funcdesc}{new}{\optional{arg}}
-Return a new md5 object.  If \var{arg} is present, the method call
-\code{update(\var{arg})} is made.
-\end{funcdesc}
-
-\begin{funcdesc}{md5}{\optional{arg}}
-For backward compatibility reasons, this is an alternative name for the
-\function{new()} function.
-\end{funcdesc}
-
-An md5 object has the following methods:
-
-\begin{methoddesc}[md5]{update}{arg}
-Update the md5 object with the string \var{arg}.  Repeated calls are
-equivalent to a single call with the concatenation of all the
-arguments: \code{m.update(a); m.update(b)} is equivalent to
-\code{m.update(a+b)}.
-\end{methoddesc}
-
-\begin{methoddesc}[md5]{digest}{}
-Return the digest of the strings passed to the \method{update()}
-method so far.  This is a 16-byte string which may contain
-non-\ASCII{} characters, including null bytes.
-\end{methoddesc}
-
-\begin{methoddesc}[md5]{hexdigest}{}
-Like \method{digest()} except the digest is returned as a string of
-length 32, containing only hexadecimal digits.  This may 
-be used to exchange the value safely in email or other non-binary
-environments.
-\end{methoddesc}
-
-\begin{methoddesc}[md5]{copy}{}
-Return a copy (``clone'') of the md5 object.  This can be used to
-efficiently compute the digests of strings that share a common initial
-substring.
-\end{methoddesc}
-
-
-\begin{seealso}
-  \seemodule{sha}{Similar module implementing the Secure Hash
-                  Algorithm (SHA).  The SHA algorithm is considered a
-                  more secure hash.}
-\end{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/libmimetools.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmimetools.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmimetools.tex	Wed Jul 11 15:40:56 2007
@@ -76,7 +76,7 @@
 The \class{Message} class defines the following methods in
 addition to the \class{rfc822.Message} methods:
 
-\begin{methoddesc}{getplist}{}
+\begin{methoddesc}[Message]{getplist}{}
 Return the parameter list of the \mailheader{Content-Type} header.
 This is a list of strings.  For parameters of the form
 \samp{\var{key}=\var{value}}, \var{key} is converted to lower case but
@@ -86,34 +86,34 @@
 'spam=2', 'Spam']}.
 \end{methoddesc}
 
-\begin{methoddesc}{getparam}{name}
+\begin{methoddesc}[Message]{getparam}{name}
 Return the \var{value} of the first parameter (as returned by
 \method{getplist()}) of the form \samp{\var{name}=\var{value}} for the
 given \var{name}.  If \var{value} is surrounded by quotes of the form
 `\code{<}...\code{>}' or `\code{"}...\code{"}', these are removed.
 \end{methoddesc}
 
-\begin{methoddesc}{getencoding}{}
+\begin{methoddesc}[Message]{getencoding}{}
 Return the encoding specified in the
 \mailheader{Content-Transfer-Encoding} message header.  If no such
 header exists, return \code{'7bit'}.  The encoding is converted to
 lower case.
 \end{methoddesc}
 
-\begin{methoddesc}{gettype}{}
+\begin{methoddesc}[Message]{gettype}{}
 Return the message type (of the form \samp{\var{type}/\var{subtype}})
 as specified in the \mailheader{Content-Type} header.  If no such
 header exists, return \code{'text/plain'}.  The type is converted to
 lower case.
 \end{methoddesc}
 
-\begin{methoddesc}{getmaintype}{}
+\begin{methoddesc}[Message]{getmaintype}{}
 Return the main type as specified in the \mailheader{Content-Type}
 header.  If no such header exists, return \code{'text'}.  The main
 type is converted to lower case.
 \end{methoddesc}
 
-\begin{methoddesc}{getsubtype}{}
+\begin{methoddesc}[Message]{getsubtype}{}
 Return the subtype as specified in the \mailheader{Content-Type}
 header.  If no such header exists, return \code{'plain'}.  The subtype
 is converted to lower case.

Modified: python/branches/p3yk-noslice/Doc/lib/libmimetypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmimetypes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmimetypes.tex	Wed Jul 11 15:40:56 2007
@@ -178,49 +178,49 @@
 \class{MimeTypes} instances provide an interface which is very like
 that of the \refmodule{mimetypes} module.
 
-\begin{datadesc}{suffix_map}
+\begin{memberdesc}[MimeTypes]{suffix_map}
   Dictionary mapping suffixes to suffixes.  This is used to allow
   recognition of encoded files for which the encoding and the type are
   indicated by the same extension.  For example, the \file{.tgz}
   extension is mapped to \file{.tar.gz} to allow the encoding and type
   to be recognized separately.  This is initially a copy of the global
   \code{suffix_map} defined in the module.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{datadesc}{encodings_map}
+\begin{memberdesc}[MimeTypes]{encodings_map}
   Dictionary mapping filename extensions to encoding types.  This is
   initially a copy of the global \code{encodings_map} defined in the
   module.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{datadesc}{types_map}
+\begin{memberdesc}[MimeTypes]{types_map}
   Dictionary mapping filename extensions to MIME types.  This is
   initially a copy of the global \code{types_map} defined in the
   module.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{datadesc}{common_types}
+\begin{memberdesc}[MimeTypes]{common_types}
   Dictionary mapping filename extensions to non-standard, but commonly
   found MIME types.  This is initially a copy of the global
   \code{common_types} defined in the module.
-\end{datadesc}
+\end{memberdesc}
 
-\begin{methoddesc}{guess_extension}{type\optional{, strict}}
+\begin{methoddesc}[MimeTypes]{guess_extension}{type\optional{, strict}}
   Similar to the \function{guess_extension()} function, using the
   tables stored as part of the object.
 \end{methoddesc}
 
-\begin{methoddesc}{guess_type}{url\optional{, strict}}
+\begin{methoddesc}[MimeTypes]{guess_type}{url\optional{, strict}}
   Similar to the \function{guess_type()} function, using the tables
   stored as part of the object.
 \end{methoddesc}
 
-\begin{methoddesc}{read}{path}
+\begin{methoddesc}[MimeTypes]{read}{path}
   Load MIME information from a file named \var{path}.  This uses
   \method{readfp()} to parse the file.
 \end{methoddesc}
 
-\begin{methoddesc}{readfp}{file}
+\begin{methoddesc}[MimeTypes]{readfp}{file}
   Load MIME type information from an open file.  The file must have
   the format of the standard \file{mime.types} files.
 \end{methoddesc}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libmimewriter.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libmimewriter.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,80 +0,0 @@
-\section{\module{MimeWriter} ---
-         Generic MIME file writer}
-
-\declaremodule{standard}{MimeWriter}
-
-\modulesynopsis{Generic MIME file writer.}
-\sectionauthor{Christopher G. Petrilli}{petrilli at amber.org}
-
-\deprecated{2.3}{The \refmodule{email} package should be used in
-                 preference to the \module{MimeWriter} module.  This
-                 module is present only to maintain backward
-                 compatibility.}
-
-This module defines the class \class{MimeWriter}.  The
-\class{MimeWriter} class implements a basic formatter for creating
-MIME multi-part files.  It doesn't seek around the output file nor
-does it use large amounts of buffer space. You must write the parts
-out in the order that they should occur in the final
-file. \class{MimeWriter} does buffer the headers you add, allowing you 
-to rearrange their order.
-
-\begin{classdesc}{MimeWriter}{fp}
-Return a new instance of the \class{MimeWriter} class.  The only
-argument passed, \var{fp}, is a file object to be used for
-writing. Note that a \class{StringIO} object could also be used.
-\end{classdesc}
-
-
-\subsection{MimeWriter Objects \label{MimeWriter-objects}}
-
-
-\class{MimeWriter} instances have the following methods:
-
-\begin{methoddesc}{addheader}{key, value\optional{, prefix}}
-Add a header line to the MIME message. The \var{key} is the name of
-the header, where the \var{value} obviously provides the value of the
-header. The optional argument \var{prefix} determines where the header 
-is inserted; \samp{0} means append at the end, \samp{1} is insert at
-the start. The default is to append.
-\end{methoddesc}
-
-\begin{methoddesc}{flushheaders}{}
-Causes all headers accumulated so far to be written out (and
-forgotten). This is useful if you don't need a body part at all,
-e.g.\ for a subpart of type \mimetype{message/rfc822} that's (mis)used
-to store some header-like information.
-\end{methoddesc}
-
-\begin{methoddesc}{startbody}{ctype\optional{, plist\optional{, prefix}}}
-Returns a file-like object which can be used to write to the
-body of the message.  The content-type is set to the provided
-\var{ctype}, and the optional parameter \var{plist} provides
-additional parameters for the content-type declaration. \var{prefix}
-functions as in \method{addheader()} except that the default is to
-insert at the start.
-\end{methoddesc}
-
-\begin{methoddesc}{startmultipartbody}{subtype\optional{,
-                   boundary\optional{, plist\optional{, prefix}}}}
-Returns a file-like object which can be used to write to the
-body of the message.  Additionally, this method initializes the
-multi-part code, where \var{subtype} provides the multipart subtype,
-\var{boundary} may provide a user-defined boundary specification, and
-\var{plist} provides optional parameters for the subtype.
-\var{prefix} functions as in \method{startbody()}.  Subparts should be
-created using \method{nextpart()}.
-\end{methoddesc}
-
-\begin{methoddesc}{nextpart}{}
-Returns a new instance of \class{MimeWriter} which represents an
-individual part in a multipart message.  This may be used to write the 
-part as well as used for creating recursively complex multipart
-messages. The message must first be initialized with
-\method{startmultipartbody()} before using \method{nextpart()}.
-\end{methoddesc}
-
-\begin{methoddesc}{lastpart}{}
-This is used to designate the last part of a multipart message, and
-should \emph{always} be used when writing multipart messages.
-\end{methoddesc}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libmimify.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libmimify.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,94 +0,0 @@
-\section{\module{mimify} ---
-         MIME processing of mail messages}
-
-\declaremodule{standard}{mimify}
-\modulesynopsis{Mimification and unmimification of mail messages.}
-
-\deprecated{2.3}{The \refmodule{email} package should be used in
-                 preference to the \module{mimify} module.  This
-                 module is present only to maintain backward
-                 compatibility.}
-
-The \module{mimify} module defines two functions to convert mail messages to
-and from MIME format.  The mail message can be either a simple message
-or a so-called multipart message.  Each part is treated separately.
-Mimifying (a part of) a message entails encoding the message as
-quoted-printable if it contains any characters that cannot be
-represented using 7-bit \ASCII.  Unmimifying (a part of) a message
-entails undoing the quoted-printable encoding.  Mimify and unmimify
-are especially useful when a message has to be edited before being
-sent.  Typical use would be:
-
-\begin{verbatim}
-unmimify message
-edit message
-mimify message
-send message
-\end{verbatim}
-
-The modules defines the following user-callable functions and
-user-settable variables:
-
-\begin{funcdesc}{mimify}{infile, outfile}
-Copy the message in \var{infile} to \var{outfile}, converting parts to
-quoted-printable and adding MIME mail headers when necessary.
-\var{infile} and \var{outfile} can be file objects (actually, any
-object that has a \method{readline()} method (for \var{infile}) or a
-\method{write()} method (for \var{outfile})) or strings naming the files.
-If \var{infile} and \var{outfile} are both strings, they may have the
-same value.
-\end{funcdesc}
-
-\begin{funcdesc}{unmimify}{infile, outfile\optional{, decode_base64}}
-Copy the message in \var{infile} to \var{outfile}, decoding all
-quoted-printable parts.  \var{infile} and \var{outfile} can be file
-objects (actually, any object that has a \method{readline()} method (for
-\var{infile}) or a \method{write()} method (for \var{outfile})) or strings
-naming the files.  If \var{infile} and \var{outfile} are both strings,
-they may have the same value.
-If the \var{decode_base64} argument is provided and tests true, any
-parts that are coded in the base64 encoding are decoded as well.
-\end{funcdesc}
-
-\begin{funcdesc}{mime_decode_header}{line}
-Return a decoded version of the encoded header line in \var{line}.
-This only supports the ISO 8859-1 charset (Latin-1).
-\end{funcdesc}
-
-\begin{funcdesc}{mime_encode_header}{line}
-Return a MIME-encoded version of the header line in \var{line}.
-\end{funcdesc}
-
-\begin{datadesc}{MAXLEN}
-By default, a part will be encoded as quoted-printable when it
-contains any non-\ASCII{} characters (characters with the 8th bit
-set), or if there are any lines longer than \constant{MAXLEN} characters
-(default value 200).  
-\end{datadesc}
-
-\begin{datadesc}{CHARSET}
-When not specified in the mail headers, a character set must be filled
-in.  The string used is stored in \constant{CHARSET}, and the default
-value is ISO-8859-1 (also known as Latin1 (latin-one)).
-\end{datadesc}
-
-This module can also be used from the command line.  Usage is as
-follows:
-\begin{verbatim}
-mimify.py -e [-l length] [infile [outfile]]
-mimify.py -d [-b] [infile [outfile]]
-\end{verbatim}
-to encode (mimify) and decode (unmimify) respectively.  \var{infile}
-defaults to standard input, \var{outfile} defaults to standard output.
-The same file can be specified for input and output.
-
-If the \strong{-l} option is given when encoding, if there are any lines
-longer than the specified \var{length}, the containing part will be
-encoded.
-
-If the \strong{-b} option is given when decoding, any base64 parts will
-be decoded as well.
-
-\begin{seealso}
-  \seemodule{quopri}{Encode and decode MIME quoted-printable files.}
-\end{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/libmmap.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmmap.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmmap.tex	Wed Jul 11 15:40:56 2007
@@ -89,18 +89,18 @@
 Memory-mapped file objects support the following methods:
 
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[mmap]{close}{}
   Close the file.  Subsequent calls to other methods of the object
   will result in an exception being raised.
 \end{methoddesc}
 
-\begin{methoddesc}{find}{string\optional{, start}}
+\begin{methoddesc}[mmap]{find}{string\optional{, start}}
   Returns the lowest index in the object where the substring
   \var{string} is found.  Returns \code{-1} on failure.  \var{start}
   is the index at which the search begins, and defaults to zero.
 \end{methoddesc}
 
-\begin{methoddesc}{flush}{\optional{offset, size}}
+\begin{methoddesc}[mmap]{flush}{\optional{offset, size}}
   Flushes changes made to the in-memory copy of a file back to disk.
   Without use of this call there is no guarantee that changes are
   written back before the object is destroyed.  If \var{offset} and
@@ -109,36 +109,36 @@
   is flushed.
 \end{methoddesc}
 
-\begin{methoddesc}{move}{\var{dest}, \var{src}, \var{count}}
+\begin{methoddesc}[mmap]{move}{\var{dest}, \var{src}, \var{count}}
   Copy the \var{count} bytes starting at offset \var{src} to the
   destination index \var{dest}.  If the mmap was created with
   \constant{ACCESS_READ}, then calls to move will throw a
   \exception{TypeError} exception.
 \end{methoddesc}
 
-\begin{methoddesc}{read}{\var{num}}
+\begin{methoddesc}[mmap]{read}{\var{num}}
   Return a string containing up to \var{num} bytes starting from the
   current file position; the file position is updated to point after the
   bytes that were returned.
 \end{methoddesc}
 
-\begin{methoddesc}{read_byte}{}
+\begin{methoddesc}[mmap]{read_byte}{}
   Returns a string of length 1 containing the character at the current
   file position, and advances the file position by 1.
 \end{methoddesc}
 
-\begin{methoddesc}{readline}{}
+\begin{methoddesc}[mmap]{readline}{}
   Returns a single line, starting at the current file position and up to
   the next newline.
 \end{methoddesc}
 
-\begin{methoddesc}{resize}{\var{newsize}}
+\begin{methoddesc}[mmap]{resize}{\var{newsize}}
   Resizes the map and the underlying file, if any.
   If the mmap was created with \constant{ACCESS_READ} or
   \constant{ACCESS_COPY}, resizing the map will throw a \exception{TypeError} exception.
 \end{methoddesc}
 
-\begin{methoddesc}{seek}{pos\optional{, whence}}
+\begin{methoddesc}[mmap]{seek}{pos\optional{, whence}}
   Set the file's current position.  \var{whence} argument is optional
   and defaults to \code{os.SEEK_SET} or \code{0} (absolute file
   positioning); other values are \code{os.SEEK_CUR} or \code{1} (seek
@@ -146,16 +146,16 @@
   (seek relative to the file's end).
 \end{methoddesc}
 
-\begin{methoddesc}{size}{}
+\begin{methoddesc}[mmap]{size}{}
   Return the length of the file, which can be larger than the size of
   the memory-mapped area.
 \end{methoddesc}
 
-\begin{methoddesc}{tell}{}
+\begin{methoddesc}[mmap]{tell}{}
   Returns the current position of the file pointer.
 \end{methoddesc}
 
-\begin{methoddesc}{write}{\var{string}}
+\begin{methoddesc}[mmap]{write}{\var{string}}
   Write the bytes in \var{string} into memory at the current position
   of the file pointer; the file position is updated to point after the
   bytes that were written. If the mmap was created with
@@ -163,7 +163,7 @@
   \exception{TypeError} exception.
 \end{methoddesc}
 
-\begin{methoddesc}{write_byte}{\var{byte}}
+\begin{methoddesc}[mmap]{write_byte}{\var{byte}}
   Write the single-character string \var{byte} into memory at the
   current position of the file pointer; the file position is advanced
   by \code{1}. If the mmap was created with \constant{ACCESS_READ},

Modified: python/branches/p3yk-noslice/Doc/lib/libmsilib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmsilib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmsilib.tex	Wed Jul 11 15:40:56 2007
@@ -121,17 +121,17 @@
 
 \subsection{Database Objects\label{database-objects}}
 
-\begin{methoddesc}{OpenView}{sql}
+\begin{methoddesc}[Database]{OpenView}{sql}
   Return a view object, by calling \cfunction{MSIDatabaseOpenView}.
   \var{sql} is the SQL statement to execute.
 \end{methoddesc}
 
-\begin{methoddesc}{Commit}{}
+\begin{methoddesc}[Database]{Commit}{}
   Commit the changes pending in the current transaction,
   by calling \cfunction{MSIDatabaseCommit}.
 \end{methoddesc}
 
-\begin{methoddesc}{GetSummaryInformation}{count}
+\begin{methoddesc}[Database]{GetSummaryInformation}{count}
   Return a new summary information object, by calling
   \cfunction{MsiGetSummaryInformation}.  \var{count} is the maximum number of
   updated values.
@@ -145,24 +145,24 @@
 
 \subsection{View Objects\label{view-objects}}
 
-\begin{methoddesc}{Execute}{\optional{params=None}}
+\begin{methoddesc}[View]{Execute}{\optional{params=None}}
   Execute the SQL query of the view, through \cfunction{MSIViewExecute}.
   \var{params} is an optional record describing actual values
   of the parameter tokens in the query.
 \end{methoddesc}
 
-\begin{methoddesc}{GetColumnInfo}{kind}
+\begin{methoddesc}[View]{GetColumnInfo}{kind}
   Return a record describing the columns of the view, through
   calling \cfunction{MsiViewGetColumnInfo}. \var{kind} can be either
   \code{MSICOLINFO_NAMES} or \code{MSICOLINFO_TYPES}.
 \end{methoddesc}
 
-\begin{methoddesc}{Fetch}{}
+\begin{methoddesc}[View]{Fetch}{}
   Return a result record of the query, through calling
   \cfunction{MsiViewFetch}.
 \end{methoddesc}
 
-\begin{methoddesc}{Modify}{kind, data}
+\begin{methoddesc}[View]{Modify}{kind, data}
   Modify the view, by calling \cfunction{MsiViewModify}. \var{kind}
   can be one of  \code{MSIMODIFY_SEEK}, \code{MSIMODIFY_REFRESH},
   \code{MSIMODIFY_INSERT}, \code{MSIMODIFY_UPDATE}, \code{MSIMODIFY_ASSIGN},
@@ -174,7 +174,7 @@
   \var{data} must be a record describing the new data.
 \end{methoddesc}
 
-\begin{methoddesc}{Close}{}
+\begin{methoddesc}[View]{Close}{}
   Close the view, through \cfunction{MsiViewClose}.
 \end{methoddesc}
 
@@ -188,7 +188,7 @@
 
 \subsection{Summary Information Objects\label{summary-objects}}
 
-\begin{methoddesc}{GetProperty}{field}
+\begin{methoddesc}[SummaryInformation]{GetProperty}{field}
   Return a property of the summary, through \cfunction{MsiSummaryInfoGetProperty}.
   \var{field} is the name of the property, and can be one of the
   constants
@@ -200,19 +200,19 @@
   \code{PID_APPNAME}, or \code{PID_SECURITY}.
 \end{methoddesc}
 
-\begin{methoddesc}{GetPropertyCount}{}
+\begin{methoddesc}[SummaryInformation]{GetPropertyCount}{}
   Return the number of summary properties, through
   \cfunction{MsiSummaryInfoGetPropertyCount}.
 \end{methoddesc}
 
-\begin{methoddesc}{SetProperty}{field, value}
+\begin{methoddesc}[SummaryInformation]{SetProperty}{field, value}
   Set a property through \cfunction{MsiSummaryInfoSetProperty}. \var{field}
   can have the same values as in \method{GetProperty}, \var{value}
   is the new value of the property. Possible value types are integer
   and string.
 \end{methoddesc}
 
-\begin{methoddesc}{Persist}{}
+\begin{methoddesc}[SummaryInformation]{Persist}{}
   Write the modified properties to the summary information stream,
   using \cfunction{MsiSummaryInfoPersist}.
 \end{methoddesc}
@@ -226,27 +226,27 @@
 
 \subsection{Record Objects\label{record-objects}}
 
-\begin{methoddesc}{GetFieldCount}{}
+\begin{methoddesc}[Record]{GetFieldCount}{}
   Return the number of fields of the record, through \cfunction{MsiRecordGetFieldCount}.
 \end{methoddesc}
 
-\begin{methoddesc}{SetString}{field, value}
+\begin{methoddesc}[Record]{SetString}{field, value}
   Set \var{field} to \var{value} through \cfunction{MsiRecordSetString}.
   \var{field} must be an integer; \var{value} a string.
 \end{methoddesc}
 
-\begin{methoddesc}{SetStream}{field, value}
+\begin{methoddesc}[Record]{SetStream}{field, value}
   Set \var{field} to the contents of the file named \var{value},
   through \cfunction{MsiRecordSetStream}.
   \var{field} must be an integer; \var{value} a string.
 \end{methoddesc}
 
-\begin{methoddesc}{SetInteger}{field, value}
+\begin{methoddesc}[Record]{SetInteger}{field, value}
   Set \var{field} to \var{value} through \cfunction{MsiRecordSetInteger}.
   Both \var{field} and \var{value} must be an integer.
 \end{methoddesc}
 
-\begin{methoddesc}{ClearData}{}
+\begin{methoddesc}[Record]{ClearData}{}
   Set all fields of the record to 0, through \cfunction{MsiRecordClearData}.
 \end{methoddesc}
 
@@ -274,7 +274,7 @@
   \var{name} is the name of the CAB file in the MSI file.
 \end{classdesc}
 
-\begin{methoddesc}[CAB]{append}{full, logical}
+\begin{methoddesc}[CAB]{append}{full, file, logical}
   Add the file with the pathname \var{full} to the CAB file,
   under the name \var{logical}. If there is already a file
   named \var{logical}, a new file name is created.
@@ -283,7 +283,7 @@
   new name of the file inside the CAB file.
 \end{methoddesc}
 
-\begin{methoddesc}[CAB]{append}{database}
+\begin{methoddesc}[CAB]{commit}{database}
   Generate a CAB file, add it as a stream to the MSI file,
   put it into the \code{Media} table, and remove the generated
   file from the disk.

Modified: python/branches/p3yk-noslice/Doc/lib/libmultifile.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmultifile.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmultifile.tex	Wed Jul 11 15:40:56 2007
@@ -48,7 +48,7 @@
 
 A \class{MultiFile} instance has the following methods:
 
-\begin{methoddesc}{readline}{str}
+\begin{methoddesc}[MultiFile]{readline}{str}
 Read a line.  If the line is data (not a section-divider or end-marker
 or real EOF) return it.  If the line matches the most-recently-stacked
 boundary, return \code{''} and set \code{self.last} to 1 or 0 according as
@@ -58,33 +58,33 @@
 all boundaries have been popped.
 \end{methoddesc}
 
-\begin{methoddesc}{readlines}{str}
+\begin{methoddesc}[MultiFile]{readlines}{str}
 Return all lines remaining in this part as a list of strings.
 \end{methoddesc}
 
-\begin{methoddesc}{read}{}
+\begin{methoddesc}[MultiFile]{read}{}
 Read all lines, up to the next section.  Return them as a single
 (multiline) string.  Note that this doesn't take a size argument!
 \end{methoddesc}
 
-\begin{methoddesc}{seek}{pos\optional{, whence}}
+\begin{methoddesc}[MultiFile]{seek}{pos\optional{, whence}}
 Seek.  Seek indices are relative to the start of the current section.
 The \var{pos} and \var{whence} arguments are interpreted as for a file
 seek.
 \end{methoddesc}
 
-\begin{methoddesc}{tell}{}
+\begin{methoddesc}[MultiFile]{tell}{}
 Return the file position relative to the start of the current section.
 \end{methoddesc}
 
-\begin{methoddesc}{next}{}
+\begin{methoddesc}[MultiFile]{next}{}
 Skip lines to the next section (that is, read lines until a
 section-divider or end-marker has been consumed).  Return true if
 there is such a section, false if an end-marker is seen.  Re-enable
 the most-recently-pushed boundary.
 \end{methoddesc}
 
-\begin{methoddesc}{is_data}{str}
+\begin{methoddesc}[MultiFile]{is_data}{str}
 Return true if \var{str} is data and false if it might be a section
 boundary.  As written, it tests for a prefix other than \code{'-}\code{-'} at
 start of line (which all MIME boundaries have) but it is declared so
@@ -95,7 +95,7 @@
 processing, not cause it to fail.
 \end{methoddesc}
 
-\begin{methoddesc}{push}{str}
+\begin{methoddesc}[MultiFile]{push}{str}
 Push a boundary string.  When a decorated version of this boundary 
 is found as an input line, it will be interpreted as a section-divider 
 or end-marker (depending on the decoration, see \rfc{2045}).  All subsequent
@@ -108,12 +108,12 @@
 boundary will raise an error.
 \end{methoddesc}
 
-\begin{methoddesc}{pop}{}
+\begin{methoddesc}[MultiFile]{pop}{}
 Pop a section boundary.  This boundary will no longer be interpreted
 as EOF.
 \end{methoddesc}
 
-\begin{methoddesc}{section_divider}{str}
+\begin{methoddesc}[MultiFile]{section_divider}{str}
 Turn a boundary into a section-divider line.  By default, this
 method prepends \code{'-}\code{-'} (which MIME section boundaries have) but
 it is declared so it can be overridden in derived classes.  This
@@ -121,7 +121,7 @@
 ignores trailing whitespace. 
 \end{methoddesc}
 
-\begin{methoddesc}{end_marker}{str}
+\begin{methoddesc}[MultiFile]{end_marker}{str}
 Turn a boundary string into an end-marker line.  By default, this
 method prepends \code{'-}\code{-'} and appends \code{'-}\code{-'} (like a
 MIME-multipart end-of-message marker) but it is declared so it can be
@@ -131,11 +131,11 @@
 
 Finally, \class{MultiFile} instances have two public instance variables:
 
-\begin{memberdesc}{level}
+\begin{memberdesc}[MultiFile]{level}
 Nesting depth of the current part.
 \end{memberdesc}
 
-\begin{memberdesc}{last}
+\begin{memberdesc}[MultiFile]{last}
 True if the last end-of-file was for an end-of-message marker. 
 \end{memberdesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libmutex.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmutex.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libmutex.tex	Wed Jul 11 15:40:56 2007
@@ -35,23 +35,23 @@
 
 \class{mutex} objects have following methods:
 
-\begin{methoddesc}{test}{}
+\begin{methoddesc}[mutex]{test}{}
 Check whether the mutex is locked.
 \end{methoddesc}
 
-\begin{methoddesc}{testandset}{}
+\begin{methoddesc}[mutex]{testandset}{}
 ``Atomic'' test-and-set, grab the lock if it is not set,
 and return \code{True}, otherwise, return \code{False}.
 \end{methoddesc}
 
-\begin{methoddesc}{lock}{function, argument}
+\begin{methoddesc}[mutex]{lock}{function, argument}
 Execute \code{\var{function}(\var{argument})}, unless the mutex is locked.
 In the case it is locked, place the function and argument on the queue.
 See \method{unlock} for explanation of when
 \code{\var{function}(\var{argument})} is executed in that case.
 \end{methoddesc}
 
-\begin{methoddesc}{unlock}{}
+\begin{methoddesc}[mutex]{unlock}{}
 Unlock the mutex if queue is empty, otherwise execute the first element
 in the queue.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libnetrc.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libnetrc.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libnetrc.tex	Wed Jul 11 15:40:56 2007
@@ -35,7 +35,7 @@
 
 A \class{netrc} instance has the following methods:
 
-\begin{methoddesc}{authenticators}{host}
+\begin{methoddesc}[netrc]{authenticators}{host}
 Return a 3-tuple \code{(\var{login}, \var{account}, \var{password})}
 of authenticators for \var{host}.  If the netrc file did not
 contain an entry for the given host, return the tuple associated with
@@ -43,20 +43,20 @@
 available, return \code{None}.
 \end{methoddesc}
 
-\begin{methoddesc}{__repr__}{}
+\begin{methoddesc}[netrc]{__repr__}{}
 Dump the class data as a string in the format of a netrc file.
 (This discards comments and may reorder the entries.)
 \end{methoddesc}
 
 Instances of \class{netrc} have public instance variables:
 
-\begin{memberdesc}{hosts}
+\begin{memberdesc}[netrc]{hosts}
 Dictionary mapping host names to \code{(\var{login}, \var{account},
 \var{password})} tuples.  The `default' entry, if any, is represented
 as a pseudo-host by that name.
 \end{memberdesc}
 
-\begin{memberdesc}{macros}
+\begin{memberdesc}[netrc]{macros}
 Dictionary mapping macro names to string lists.
 \end{memberdesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libnntplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libnntplib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libnntplib.tex	Wed Jul 11 15:40:56 2007
@@ -121,13 +121,13 @@
 the above exceptions.
 
 
-\begin{methoddesc}{getwelcome}{}
+\begin{methoddesc}[NNTP]{getwelcome}{}
 Return the welcome message sent by the server in reply to the initial
 connection.  (This message sometimes contains disclaimers or help
 information that may be relevant to the user.)
 \end{methoddesc}
 
-\begin{methoddesc}{set_debuglevel}{level}
+\begin{methoddesc}[NNTP]{set_debuglevel}{level}
 Set the instance's debugging level.  This controls the amount of
 debugging output printed.  The default, \code{0}, produces no debugging
 output.  A value of \code{1} produces a moderate amount of debugging
@@ -137,7 +137,7 @@
 message text).
 \end{methoddesc}
 
-\begin{methoddesc}{newgroups}{date, time, \optional{file}}
+\begin{methoddesc}[NNTP]{newgroups}{date, time, \optional{file}}
 Send a \samp{NEWGROUPS} command.  The \var{date} argument should be a
 string of the form \code{'\var{yy}\var{mm}\var{dd}'} indicating the
 date, and \var{time} should be a string of the form
@@ -152,7 +152,7 @@
 If \var{file} is supplied, then the returned \var{list} is an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{newnews}{group, date, time, \optional{file}}
+\begin{methoddesc}[NNTP]{newnews}{group, date, time, \optional{file}}
 Send a \samp{NEWNEWS} command.  Here, \var{group} is a group name or
 \code{'*'}, and \var{date} and \var{time} have the same meaning as for
 \method{newgroups()}.  Return a pair \code{(\var{response},
@@ -165,7 +165,7 @@
 If \var{file} is supplied, then the returned \var{list} is an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{list}{\optional{file}}
+\begin{methoddesc}[NNTP]{list}{\optional{file}}
 Send a \samp{LIST} command.  Return a pair \code{(\var{response},
 \var{list})} where \var{list} is a list of tuples.  Each tuple has the
 form \code{(\var{group}, \var{last}, \var{first}, \var{flag})}, where
@@ -182,7 +182,7 @@
 If \var{file} is supplied, then the returned \var{list} is an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{descriptions}{grouppattern}
+\begin{methoddesc}[NNTP]{descriptions}{grouppattern}
 Send a \samp{LIST NEWSGROUPS} command, where \var{grouppattern} is a wildmat
 string as specified in RFC2980 (it's essentially the same as DOS or UNIX
 shell wildcard strings).  Return a pair \code{(\var{response},
@@ -192,7 +192,7 @@
 \versionadded{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{description}{group}
+\begin{methoddesc}[NNTP]{description}{group}
 Get a description for a single group \var{group}.  If more than one group
 matches (if 'group' is a real wildmat string), return the first match.  
 If no group matches, return an empty string.
@@ -203,7 +203,7 @@
 \versionadded{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}{group}{name}
+\begin{methoddesc}[NNTP]{group}{name}
 Send a \samp{GROUP} command, where \var{name} is the group name.
 Return a tuple \code{(\var{response}, \var{count}, \var{first},
 \var{last}, \var{name})} where \var{count} is the (estimated) number
@@ -212,7 +212,7 @@
 \var{name} is the group name.  The numbers are returned as strings.
 \end{methoddesc}
 
-\begin{methoddesc}{help}{\optional{file}}
+\begin{methoddesc}[NNTP]{help}{\optional{file}}
 Send a \samp{HELP} command.  Return a pair \code{(\var{response},
 \var{list})} where \var{list} is a list of help strings.
 If the \var{file} parameter is supplied, then the output of the 
@@ -223,7 +223,7 @@
 If \var{file} is supplied, then the returned \var{list} is an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{stat}{id}
+\begin{methoddesc}[NNTP]{stat}{id}
 Send a \samp{STAT} command, where \var{id} is the message id (enclosed
 in \character{<} and \character{>}) or an article number (as a string).
 Return a triple \code{(\var{response}, \var{number}, \var{id})} where
@@ -231,15 +231,15 @@
 message id  (enclosed in \character{<} and \character{>}).
 \end{methoddesc}
 
-\begin{methoddesc}{next}{}
+\begin{methoddesc}[NNTP]{next}{}
 Send a \samp{NEXT} command.  Return as for \method{stat()}.
 \end{methoddesc}
 
-\begin{methoddesc}{last}{}
+\begin{methoddesc}[NNTP]{last}{}
 Send a \samp{LAST} command.  Return as for \method{stat()}.
 \end{methoddesc}
 
-\begin{methoddesc}{head}{id}
+\begin{methoddesc}[NNTP]{head}{id}
 Send a \samp{HEAD} command, where \var{id} has the same meaning as for
 \method{stat()}.  Return a tuple
 \code{(\var{response}, \var{number}, \var{id}, \var{list})}
@@ -248,7 +248,7 @@
 list of lines, without trailing newlines).
 \end{methoddesc}
 
-\begin{methoddesc}{body}{id,\optional{file}}
+\begin{methoddesc}[NNTP]{body}{id,\optional{file}}
 Send a \samp{BODY} command, where \var{id} has the same meaning as for
 \method{stat()}.  If the \var{file} parameter is supplied, then
 the body is stored in a file.  If \var{file} is a string, then
@@ -259,16 +259,16 @@
 the returned \var{list} is an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{article}{id}
+\begin{methoddesc}[NNTP]{article}{id}
 Send an \samp{ARTICLE} command, where \var{id} has the same meaning as
 for \method{stat()}.  Return as for \method{head()}.
 \end{methoddesc}
 
-\begin{methoddesc}{slave}{}
+\begin{methoddesc}[NNTP]{slave}{}
 Send a \samp{SLAVE} command.  Return the server's \var{response}.
 \end{methoddesc}
 
-\begin{methoddesc}{xhdr}{header, string, \optional{file}}
+\begin{methoddesc}[NNTP]{xhdr}{header, string, \optional{file}}
 Send an \samp{XHDR} command.  This command is not defined in the RFC
 but is a common extension.  The \var{header} argument is a header
 keyword, e.g. \code{'subject'}.  The \var{string} argument should have
@@ -286,7 +286,7 @@
 If \var{file} is supplied, then the returned \var{list} is an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}{post}{file}
+\begin{methoddesc}[NNTP]{post}{file}
 Post an article using the \samp{POST} command.  The \var{file}
 argument is an open file object which is read until EOF using its
 \method{readline()} method.  It should be a well-formed news article,
@@ -294,14 +294,14 @@
 automatically escapes lines beginning with \samp{.}.
 \end{methoddesc}
 
-\begin{methoddesc}{ihave}{id, file}
+\begin{methoddesc}[NNTP]{ihave}{id, file}
 Send an \samp{IHAVE} command. \var{id} is a message id (enclosed in 
 \character{<} and \character{>}).
 If the response is not an error, treat
 \var{file} exactly as for the \method{post()} method.
 \end{methoddesc}
 
-\begin{methoddesc}{date}{}
+\begin{methoddesc}[NNTP]{date}{}
 Return a triple \code{(\var{response}, \var{date}, \var{time})},
 containing the current date and time in a form suitable for the
 \method{newnews()} and \method{newgroups()} methods.
@@ -309,7 +309,7 @@
 servers.
 \end{methoddesc}
 
-\begin{methoddesc}{xgtitle}{name, \optional{file}}
+\begin{methoddesc}[NNTP]{xgtitle}{name, \optional{file}}
 Process an \samp{XGTITLE} command, returning a pair \code{(\var{response},
 \var{list})}, where \var{list} is a list of tuples containing
 \code{(\var{name}, \var{title})}.
@@ -327,7 +327,7 @@
 \method{descriptions()} or \method{description()} instead.
 \end{methoddesc}
 
-\begin{methoddesc}{xover}{start, end, \optional{file}}
+\begin{methoddesc}[NNTP]{xover}{start, end, \optional{file}}
 Return a pair \code{(\var{resp}, \var{list})}.  \var{list} is a list
 of tuples, one for each article in the range delimited by the \var{start}
 and \var{end} article numbers.  Each tuple is of the form
@@ -343,13 +343,13 @@
 servers.
 \end{methoddesc}
 
-\begin{methoddesc}{xpath}{id}
+\begin{methoddesc}[NNTP]{xpath}{id}
 Return a pair \code{(\var{resp}, \var{path})}, where \var{path} is the
 directory path to the article with message ID \var{id}.  This is an
 optional NNTP extension, and may not be supported by all servers.
 \end{methoddesc}
 
-\begin{methoddesc}{quit}{}
+\begin{methoddesc}[NNTP]{quit}{}
 Send a \samp{QUIT} command and close the connection.  Once this method
 has been called, no other methods of the NNTP object should be called.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/liboptparse.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liboptparse.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/liboptparse.tex	Wed Jul 11 15:40:56 2007
@@ -518,7 +518,7 @@
 is then printed before the detailed option help.
 
 If you don't supply a usage string, \module{optparse} uses a bland but sensible
-default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script
+default: \code{"usage: {\%}prog {[}options]"}, which is fine if your script
 doesn't take any positional arguments.
 
 \item {} 
@@ -1191,14 +1191,14 @@
 The whole point of creating and populating an OptionParser is to call
 its \method{parse{\_}args()} method:
 \begin{verbatim}
-(options, args) = parser.parse_args(args=None, options=None)
+(options, args) = parser.parse_args(args=None, values=None)
 \end{verbatim}
 
 where the input parameters are
 \begin{description}
 \item[\code{args}]
 the list of arguments to process (default: \code{sys.argv{[}1:]})
-\item[\code{options}]
+\item[\code{values}]
 object to store option arguments in (default: a new instance of
 optparse.Values)
 \end{description}

Modified: python/branches/p3yk-noslice/Doc/lib/libos.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libos.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libos.tex	Wed Jul 11 15:40:56 2007
@@ -361,9 +361,8 @@
 errors), \code{None} is returned.
 Availability: Macintosh, \UNIX, Windows.
 
-The \module{subprocess} module provides more powerful facilities for
-spawning new processes and retrieving their results; using that module
-is preferable to using this function.
+\deprecated{2.6}{This function is obsolete.  Use the
+                 \module{subprocess} module.}
 
 \versionchanged[This function worked unreliably under Windows in
   earlier versions of Python.  This was due to the use of the
@@ -379,64 +378,6 @@
 Availability: Macintosh, \UNIX, Windows.
 \end{funcdesc}
 
-There are a number of different \function{popen*()} functions that
-provide slightly different ways to create subprocesses.  Note that the
-\module{subprocess} module is easier to use and more powerful;
-consider using that module before writing code using the
-lower-level \function{popen*()} functions.
-
-For each of the \function{popen*()} variants, if \var{bufsize} is
-specified, it specifies the buffer size for the I/O pipes.
-\var{mode}, if provided, should be the string \code{'b'} or
-\code{'t'}; on Windows this is needed to determine whether the file
-objects should be opened in binary or text mode.  The default value
-for \var{mode} is \code{'t'}.
-
-Also, for each of these variants, on \UNIX, \var{cmd} may be a sequence, in
-which case arguments will be passed directly to the program without shell
-intervention (as with \function{os.spawnv()}). If \var{cmd} is a string it will
-be passed to the shell (as with \function{os.system()}).
-
-These methods do not make it possible to retrieve the exit status from
-the child processes.  The only way to control the input and output
-streams and also retrieve the return codes is to use the
-\class{Popen3} and \class{Popen4} classes from the \refmodule{popen2}
-module; these are only available on \UNIX.
-
-For a discussion of possible deadlock conditions related to the use
-of these functions, see ``\ulink{Flow Control
-Issues}{popen2-flow-control.html}''
-(section~\ref{popen2-flow-control}).
-
-\begin{funcdesc}{popen2}{cmd\optional{, mode\optional{, bufsize}}}
-Executes \var{cmd} as a sub-process.  Returns the file objects
-\code{(\var{child_stdin}, \var{child_stdout})}.
-Availability: Macintosh, \UNIX, Windows.
-\versionadded{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{popen3}{cmd\optional{, mode\optional{, bufsize}}}
-Executes \var{cmd} as a sub-process.  Returns the file objects
-\code{(\var{child_stdin}, \var{child_stdout}, \var{child_stderr})}.
-Availability: Macintosh, \UNIX, Windows.
-\versionadded{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{popen4}{cmd\optional{, mode\optional{, bufsize}}}
-Executes \var{cmd} as a sub-process.  Returns the file objects
-\code{(\var{child_stdin}, \var{child_stdout_and_stderr})}.
-Availability: Macintosh, \UNIX, Windows.
-\versionadded{2.0}
-\end{funcdesc}
-
-(Note that \code{\var{child_stdin}, \var{child_stdout}, and
-\var{child_stderr}} are named from the point of view of the child
-process, so \var{child_stdin} is the child's standard input.)
-
-This functionality is also available in the \refmodule{popen2} module
-using functions of the same names, but the return values of those
-functions have a different order.
-
 
 \subsection{File Descriptor Operations \label{os-fd-ops}}
 
@@ -1233,7 +1174,8 @@
 \end{funcdesc}
 
 \begin{funcdesc}{walk}{top\optional{, topdown\code{=True}
-                       \optional{, onerror\code{=None}}}}
+                       \optional{, onerror\code{=None}\optional{,
+		       followlinks\code{=False}}}}}
 \index{directory!walking}
 \index{directory!traversal}
 \function{walk()} generates the file names in a directory tree, by
@@ -1273,6 +1215,18 @@
 to abort the walk.  Note that the filename is available as the
 \code{filename} attribute of the exception object.
 
+By default, \function{walk()} will not walk down into symbolic links that
+resolve to directories. Set \var{followlinks} to True to visit directories
+pointed to by symlinks, on systems that support them.
+
+\versionadded[The \var{followlinks} parameter]{2.6}
+
+\begin{notice}
+Be aware that setting \var{followlinks} to true can lead to infinite recursion
+if a link points to a parent directory of itself. \function{walk()} does not
+keep track of the directories it visited already.
+\end{notice}
+
 \begin{notice}
 If you pass a relative pathname, don't change the current working
 directory between resumptions of \function{walk()}.  \function{walk()}
@@ -1280,15 +1234,6 @@
 doesn't either.
 \end{notice}
 
-\begin{notice}
-On systems that support symbolic links, links to subdirectories appear
-in \var{dirnames} lists, but \function{walk()} will not visit them
-(infinite loops are hard to avoid when following symbolic links).
-To visit linked directories, you can identify them with
-\code{os.path.islink(\var{path})}, and invoke \code{walk(\var{path})}
-on each directly.
-\end{notice}
-
 This example displays the number of bytes taken by non-directory files
 in each directory under the starting directory, except that it doesn't
 look under any CVS subdirectory:
@@ -1568,9 +1513,6 @@
 \end{funcdesc}
 
 \begin{funcdescni}{popen}{\unspecified}
-\funclineni{popen2}{\unspecified}
-\funclineni{popen3}{\unspecified}
-\funclineni{popen4}{\unspecified}
 Run child processes, returning opened pipes for communications.  These
 functions are described in section \ref{os-newstreams}.
 \end{funcdescni}
@@ -2002,9 +1944,12 @@
 
 \begin{datadesc}{linesep}
 The string used to separate (or, rather, terminate) lines on the
-current platform.  This may be a single character, such as \code{'\e
-n'} for \POSIX{} or \code{'\e r'} for Mac OS, or multiple characters,
-for example, \code{'\e r\e n'} for Windows.
+current platform.  This may be a single character, such as 
+\code{'\e n'} for \POSIX{} or \code{'\e r'} for Mac OS, or multiple 
+characters, for example, \code{'\e r\e n'} for Windows.
+Do not use \var{os.linesep} as a line terminator when writing files 
+opened in text mode (the default); use a single \code{'\e n'} instead, 
+on all platforms. 
 \end{datadesc}
 
 \begin{datadesc}{devnull}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libpanel.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libpanel.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,74 +0,0 @@
-\section{\module{panel} ---
-         None}
-\declaremodule{standard}{panel}
-
-\modulesynopsis{None}
-
-
-\strong{Please note:} The FORMS library, to which the
-\code{fl}\refbimodindex{fl} module described above interfaces, is a
-simpler and more accessible user interface library for use with GL
-than the \code{panel} module (besides also being by a Dutch author).
-
-This module should be used instead of the built-in module
-\code{pnl}\refbimodindex{pnl}
-to interface with the
-\emph{Panel Library}.
-
-The module is too large to document here in its entirety.
-One interesting function:
-
-\begin{funcdesc}{defpanellist}{filename}
-Parses a panel description file containing S-expressions written by the
-\emph{Panel Editor}
-that accompanies the Panel Library and creates the described panels.
-It returns a list of panel objects.
-\end{funcdesc}
-
-\warning{The Python interpreter will dump core if you don't create a
-GL window before calling
-\code{panel.mkpanel()}
-or
-\code{panel.defpanellist()}.}
-
-\section{\module{panelparser} ---
-         None}
-\declaremodule{standard}{panelparser}
-
-\modulesynopsis{None}
-
-
-This module defines a self-contained parser for S-expressions as output
-by the Panel Editor (which is written in Scheme so it can't help writing
-S-expressions).
-The relevant function is
-\code{panelparser.parse_file(\var{file})}
-which has a file object (not a filename!) as argument and returns a list
-of parsed S-expressions.
-Each S-expression is converted into a Python list, with atoms converted
-to Python strings and sub-expressions (recursively) to Python lists.
-For more details, read the module file.
-% XXXXJH should be funcdesc, I think
-
-\section{\module{pnl} ---
-         None}
-\declaremodule{builtin}{pnl}
-
-\modulesynopsis{None}
-
-
-This module provides access to the
-\emph{Panel Library}
-built by NASA Ames\index{NASA} (to get it, send email to
-\code{panel-request at nas.nasa.gov}).
-All access to it should be done through the standard module
-\code{panel}\refstmodindex{panel},
-which transparently exports most functions from
-\code{pnl}
-but redefines
-\code{pnl.dopanel()}.
-
-\warning{The Python interpreter will dump core if you don't create a
-GL window before calling \code{pnl.mkpanel()}.}
-
-The module is too large to document here in its entirety.

Modified: python/branches/p3yk-noslice/Doc/lib/libpdb.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libpdb.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libpdb.tex	Wed Jul 11 15:40:56 2007
@@ -378,6 +378,14 @@
 (Pdb)
 \end{verbatim}
 
+\item[run \optional{\var{args} ...}]
+Restart the debugged python program. If an argument is supplied, it is
+splitted with "shlex" and the result is used as the new sys.argv.
+History, breakpoints, actions and debugger options are preserved.
+"restart" is an alias for "run".
+
+\versionadded{2.6}
+
 \item[q(uit)]
 
 Quit from the debugger.

Modified: python/branches/p3yk-noslice/Doc/lib/libpickle.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libpickle.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libpickle.tex	Wed Jul 11 15:40:56 2007
@@ -799,7 +799,7 @@
         del odict['fh']              # remove filehandle entry
         return odict
 
-    def __setstate__(self,dict):
+    def __setstate__(self, dict):
         fh = open(dict['file'])      # reopen file
         count = dict['lineno']       # read from file...
         while count:                 # until line count is restored
@@ -820,7 +820,7 @@
 ... obj.readline()
 '7: class TextReader:'
 >>> import pickle
->>> pickle.dump(obj,open('save.p','w'))
+>>> pickle.dump(obj,open('save.p', 'wb'))
 \end{verbatim}
 
 If you want to see that \refmodule{pickle} works across Python
@@ -829,7 +829,7 @@
 
 \begin{verbatim}
 >>> import pickle
->>> reader = pickle.load(open('save.p'))
+>>> reader = pickle.load(open('save.p', 'rb'))
 >>> reader.readline()
 '8:     "Print and number lines in a text file."'
 \end{verbatim}

Modified: python/branches/p3yk-noslice/Doc/lib/libpipes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libpipes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libpipes.tex	Wed Jul 11 15:40:56 2007
@@ -39,21 +39,21 @@
 
 Template objects following methods:
 
-\begin{methoddesc}{reset}{}
+\begin{methoddesc}[Template]{reset}{}
 Restore a pipeline template to its initial state.
 \end{methoddesc}
 
-\begin{methoddesc}{clone}{}
+\begin{methoddesc}[Template]{clone}{}
 Return a new, equivalent, pipeline template.
 \end{methoddesc}
 
-\begin{methoddesc}{debug}{flag}
+\begin{methoddesc}[Template]{debug}{flag}
 If \var{flag} is true, turn debugging on. Otherwise, turn debugging
 off. When debugging is on, commands to be executed are printed, and
 the shell is given \code{set -x} command to be more verbose.
 \end{methoddesc}
 
-\begin{methoddesc}{append}{cmd, kind}
+\begin{methoddesc}[Template]{append}{cmd, kind}
 Append a new action at the end. The \var{cmd} variable must be a valid
 bourne shell command. The \var{kind} variable consists of two letters.
 
@@ -68,17 +68,17 @@
 the command does not write anything, and hence must be last.)
 \end{methoddesc}
 
-\begin{methoddesc}{prepend}{cmd, kind}
+\begin{methoddesc}[Template]{prepend}{cmd, kind}
 Add a new action at the beginning. See \method{append()} for explanations
 of the arguments.
 \end{methoddesc}
 
-\begin{methoddesc}{open}{file, mode}
+\begin{methoddesc}[Template]{open}{file, mode}
 Return a file-like object, open to \var{file}, but read from or
 written to by the pipeline.  Note that only one of \code{'r'},
 \code{'w'} may be given.
 \end{methoddesc}
 
-\begin{methoddesc}{copy}{infile, outfile}
+\begin{methoddesc}[Template]{copy}{infile, outfile}
 Copy \var{infile} to \var{outfile} through the pipe.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libplatform.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libplatform.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libplatform.tex	Wed Jul 11 15:40:56 2007
@@ -80,6 +80,22 @@
   Returns a string identifying the compiler used for compiling Python.
 \end{funcdesc}
 
+\begin{funcdesc}{python_branch}{}
+  Returns a string identifying the Python implementation SCM branch.
+  \versionadded{2.6}
+\end{funcdesc}
+
+\begin{funcdesc}{python_implementation}{}
+  Returns a string identifying the Python implementation.
+  Possible return values are: 'CPython', 'IronPython', 'Jython'
+  \versionadded{2.6}
+\end{funcdesc}
+
+\begin{funcdesc}{python_revision}{}
+  Returns a string identifying the Python implementation SCM revision.
+  \versionadded{2.6}
+\end{funcdesc}
+
 \begin{funcdesc}{python_version}{}
   Returns the Python version as string \code{'major.minor.patchlevel'}
 
@@ -205,6 +221,7 @@
   which defaults to the args given as parameters.
 \end{funcdesc}
 
+% Document linux_distribution()?
 
 \begin{funcdesc}{libc_ver}{executable=sys.executable, lib='',
                            version='', chunksize=2048}

Deleted: /python/branches/p3yk-noslice/Doc/lib/libpopen2.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libpopen2.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,190 +0,0 @@
-\section{\module{popen2} ---
-         Subprocesses with accessible I/O streams}
-
-\declaremodule{standard}{popen2}
-  \platform{Unix, Windows}
-\modulesynopsis{Subprocesses with accessible standard I/O streams.}
-\sectionauthor{Drew Csillag}{drew_csillag at geocities.com}
-
-
-This module allows you to spawn processes and connect to their
-input/output/error pipes and obtain their return codes under
-\UNIX{} and Windows.
-
-The \module{subprocess} module provides more powerful facilities for
-spawning new processes and retrieving their results.  Using the
-\module{subprocess} module is preferable to using the \module{popen2}
-module.
-
-The primary interface offered by this module is a trio of factory
-functions.  For each of these, if \var{bufsize} is specified, 
-it specifies the buffer size for the I/O pipes.  \var{mode}, if
-provided, should be the string \code{'b'} or \code{'t'}; on Windows
-this is needed to determine whether the file objects should be opened
-in binary or text mode.  The default value for \var{mode} is
-\code{'t'}.
-
-On \UNIX, \var{cmd} may be a sequence, in which case arguments will be passed
-directly to the program without shell intervention (as with
-\function{os.spawnv()}). If \var{cmd} is a string it will be passed to the
-shell (as with \function{os.system()}).
-
-The only way to retrieve the return codes for the child processes is
-by using the \method{poll()} or \method{wait()} methods on the
-\class{Popen3} and \class{Popen4} classes; these are only available on
-\UNIX.  This information is not available when using the
-\function{popen2()}, \function{popen3()}, and \function{popen4()}
-functions, or the equivalent functions in the \refmodule{os} module.
-(Note that the tuples returned by the \refmodule{os} module's functions
-are in a different order from the ones returned by the \module{popen2}
-module.)
-
-\begin{funcdesc}{popen2}{cmd\optional{, bufsize\optional{, mode}}}
-Executes \var{cmd} as a sub-process.  Returns the file objects
-\code{(\var{child_stdout}, \var{child_stdin})}.
-\end{funcdesc}
-
-\begin{funcdesc}{popen3}{cmd\optional{, bufsize\optional{, mode}}}
-Executes \var{cmd} as a sub-process.  Returns the file objects
-\code{(\var{child_stdout}, \var{child_stdin}, \var{child_stderr})}.
-\end{funcdesc}
-
-\begin{funcdesc}{popen4}{cmd\optional{, bufsize\optional{, mode}}}
-Executes \var{cmd} as a sub-process.  Returns the file objects
-\code{(\var{child_stdout_and_stderr}, \var{child_stdin})}.
-\versionadded{2.0}
-\end{funcdesc}
-
-
-On \UNIX, a class defining the objects returned by the factory
-functions is also available.  These are not used for the Windows
-implementation, and are not available on that platform.
-
-\begin{classdesc}{Popen3}{cmd\optional{, capturestderr\optional{, bufsize}}}
-This class represents a child process.  Normally, \class{Popen3}
-instances are created using the \function{popen2()} and
-\function{popen3()} factory functions described above.
-
-If not using one of the helper functions to create \class{Popen3}
-objects, the parameter \var{cmd} is the shell command to execute in a
-sub-process.  The \var{capturestderr} flag, if true, specifies that
-the object should capture standard error output of the child process.
-The default is false.  If the \var{bufsize} parameter is specified, it
-specifies the size of the I/O buffers to/from the child process.
-\end{classdesc}
-
-\begin{classdesc}{Popen4}{cmd\optional{, bufsize}}
-Similar to \class{Popen3}, but always captures standard error into the
-same file object as standard output.  These are typically created
-using \function{popen4()}.
-\versionadded{2.0}
-\end{classdesc}
-
-\subsection{Popen3 and Popen4 Objects \label{popen3-objects}}
-
-Instances of the \class{Popen3} and \class{Popen4} classes have the
-following methods:
-
-\begin{methoddesc}{poll}{}
-Returns \code{-1} if child process hasn't completed yet, or its return 
-code otherwise.
-\end{methoddesc}
-
-\begin{methoddesc}{wait}{}
-Waits for and returns the status code of the child process.  The
-status code encodes both the return code of the process and
-information about whether it exited using the \cfunction{exit()}
-system call or died due to a signal.  Functions to help interpret the
-status code are defined in the \refmodule{os} module; see section
-\ref{os-process} for the \function{W\var{*}()} family of functions.
-\end{methoddesc}
-
-
-The following attributes are also available: 
-
-\begin{memberdesc}{fromchild}
-A file object that provides output from the child process.  For
-\class{Popen4} instances, this will provide both the standard output
-and standard error streams.
-\end{memberdesc}
-
-\begin{memberdesc}{tochild}
-A file object that provides input to the child process.
-\end{memberdesc}
-
-\begin{memberdesc}{childerr}
-A file object that provides error output from the child process, if
-\var{capturestderr} was true for the constructor, otherwise
-\code{None}.  This will always be \code{None} for \class{Popen4}
-instances.
-\end{memberdesc}
-
-\begin{memberdesc}{pid}
-The process ID of the child process.
-\end{memberdesc}
-
-
-\subsection{Flow Control Issues \label{popen2-flow-control}}
-
-Any time you are working with any form of inter-process communication,
-control flow needs to be carefully thought out.  This remains the case
-with the file objects provided by this module (or the \refmodule{os}
-module equivalents).
-
-% Example explanation and suggested work-arounds substantially stolen
-% from Martin von Löwis:
-% http://mail.python.org/pipermail/python-dev/2000-September/009460.html
-
-When reading output from a child process that writes a lot of data to
-standard error while the parent is reading from the child's standard
-output, a deadlock can occur.  A similar situation can occur with other
-combinations of reads and writes.  The essential factors are that more
-than \constant{_PC_PIPE_BUF} bytes are being written by one process in
-a blocking fashion, while the other process is reading from the other
-process, also in a blocking fashion.
-
-There are several ways to deal with this situation.
-
-The simplest application change, in many cases, will be to follow this
-model in the parent process:
-
-\begin{verbatim}
-import popen2
-
-r, w, e = popen2.popen3('python slave.py')
-e.readlines()
-r.readlines()
-r.close()
-e.close()
-w.close()
-\end{verbatim}
-
-with code like this in the child:
-
-\begin{verbatim}
-import os
-import sys
-
-# note that each of these print statements
-# writes a single long string
-
-print >>sys.stderr, 400 * 'this is a test\n'
-os.close(sys.stderr.fileno())
-print >>sys.stdout, 400 * 'this is another test\n'
-\end{verbatim}
-
-In particular, note that \code{sys.stderr} must be closed after
-writing all data, or \method{readlines()} won't return.  Also note
-that \function{os.close()} must be used, as \code{sys.stderr.close()}
-won't close \code{stderr} (otherwise assigning to \code{sys.stderr}
-will silently close it, so no further errors can be printed).
-
-Applications which need to support a more general approach should
-integrate I/O over pipes with their \function{select()} loops, or use
-separate threads to read each of the individual files provided by
-whichever \function{popen*()} function or \class{Popen*} class was
-used.
-
-\begin{seealso}
-  \seemodule{subprocess}{Module for spawning and managing subprocesses.}
-\end{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/libpoplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libpoplib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libpoplib.tex	Wed Jul 11 15:40:56 2007
@@ -23,15 +23,20 @@
 Note that POP3, though widely supported, is obsolescent.  The
 implementation quality of POP3 servers varies widely, and too many are
 quite poor. If your mailserver supports IMAP, you would be better off
-using the \code{\refmodule{imaplib}.\class{IMAP4}} class, as IMAP
+using the \class{\refmodule{imaplib}.IMAP4} class, as IMAP
 servers tend to be better implemented.
 
 A single class is provided by the \module{poplib} module:
 
-\begin{classdesc}{POP3}{host\optional{, port}}
+\begin{classdesc}{POP3}{host\optional{, port\optional{, timeout}}}
 This class implements the actual POP3 protocol.  The connection is
 created when the instance is initialized.
 If \var{port} is omitted, the standard POP3 port (110) is used.
+The optional \var{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).
+
+\versionchanged[\var{timeout} was added]{2.6}
 \end{classdesc}
 
 \begin{classdesc}{POP3_SSL}{host\optional{, port\optional{, keyfile\optional{, certfile}}}}
@@ -47,8 +52,9 @@
 One exception is defined as an attribute of the \module{poplib} module:
 
 \begin{excdesc}{error_proto}
-Exception raised on any errors.  The reason for the exception is
-passed to the constructor as a string.
+Exception raised on any errors from this module (errors from
+\module{socket} module are not caught). The reason for the exception
+is passed to the constructor as a string.
 \end{excdesc}
 
 \begin{seealso}
@@ -70,7 +76,7 @@
 An \class{POP3} instance has the following methods:
 
 
-\begin{methoddesc}{set_debuglevel}{level}
+\begin{methoddesc}[POP3]{set_debuglevel}{level}
 Set the instance's debugging level.  This controls the amount of
 debugging output printed.  The default, \code{0}, produces no
 debugging output.  A value of \code{1} produces a moderate amount of
@@ -79,64 +85,64 @@
 logging each line sent and received on the control connection.
 \end{methoddesc}
 
-\begin{methoddesc}{getwelcome}{}
+\begin{methoddesc}[POP3]{getwelcome}{}
 Returns the greeting string sent by the POP3 server.
 \end{methoddesc}
 
-\begin{methoddesc}{user}{username}
+\begin{methoddesc}[POP3]{user}{username}
 Send user command, response should indicate that a password is required.
 \end{methoddesc}
 
-\begin{methoddesc}{pass_}{password}
+\begin{methoddesc}[POP3]{pass_}{password}
 Send password, response includes message count and mailbox size.
 Note: the mailbox on the server is locked until \method{quit()} is
 called.
 \end{methoddesc}
 
-\begin{methoddesc}{apop}{user, secret}
+\begin{methoddesc}[POP3]{apop}{user, secret}
 Use the more secure APOP authentication to log into the POP3 server.
 \end{methoddesc}
 
-\begin{methoddesc}{rpop}{user}
+\begin{methoddesc}[POP3]{rpop}{user}
 Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server.
 \end{methoddesc}
 
-\begin{methoddesc}{stat}{}
+\begin{methoddesc}[POP3]{stat}{}
 Get mailbox status.  The result is a tuple of 2 integers:
 \code{(\var{message count}, \var{mailbox size})}.
 \end{methoddesc}
 
-\begin{methoddesc}{list}{\optional{which}}
+\begin{methoddesc}[POP3]{list}{\optional{which}}
 Request message list, result is in the form
 \code{(\var{response}, ['mesg_num octets', ...], \var{octets})}.
 If \var{which} is set, it is the message to list.
 \end{methoddesc}
 
-\begin{methoddesc}{retr}{which}
+\begin{methoddesc}[POP3]{retr}{which}
 Retrieve whole message number \var{which}, and set its seen flag.
 Result is in form  \code{(\var{response}, ['line', ...], \var{octets})}.
 \end{methoddesc}
 
-\begin{methoddesc}{dele}{which}
+\begin{methoddesc}[POP3]{dele}{which}
 Flag message number \var{which} for deletion.  On most servers
 deletions are not actually performed until QUIT (the major exception is
 Eudora QPOP, which deliberately violates the RFCs by doing pending
 deletes on any disconnect).
 \end{methoddesc}
 
-\begin{methoddesc}{rset}{}
+\begin{methoddesc}[POP3]{rset}{}
 Remove any deletion marks for the mailbox.
 \end{methoddesc}
 
-\begin{methoddesc}{noop}{}
+\begin{methoddesc}[POP3]{noop}{}
 Do nothing.  Might be used as a keep-alive.
 \end{methoddesc}
 
-\begin{methoddesc}{quit}{}
+\begin{methoddesc}[POP3]{quit}{}
 Signoff:  commit changes, unlock mailbox, drop connection.
 \end{methoddesc}
 
-\begin{methoddesc}{top}{which, howmuch}
+\begin{methoddesc}[POP3]{top}{which, howmuch}
 Retrieves the message header plus \var{howmuch} lines of the message
 after the header of message number \var{which}. Result is in form
 \code{(\var{response}, ['line', ...], \var{octets})}.
@@ -148,7 +154,7 @@
 trusting it.
 \end{methoddesc}
 
-\begin{methoddesc}{uidl}{\optional{which}}
+\begin{methoddesc}[POP3]{uidl}{\optional{which}}
 Return message digest (unique id) list.
 If \var{which} is specified, result contains the unique id for that
 message in the form \code{'\var{response}\ \var{mesgnum}\ \var{uid}},

Deleted: /python/branches/p3yk-noslice/Doc/lib/libposixfile.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libposixfile.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,175 +0,0 @@
-% Manual text and implementation by Jaap Vermeulen
-\section{\module{posixfile} ---
-         File-like objects with locking support}
-
-\declaremodule{builtin}{posixfile}
-  \platform{Unix}
-\modulesynopsis{A file-like object with support for locking.}
-\moduleauthor{Jaap Vermeulen}{}
-\sectionauthor{Jaap Vermeulen}{}
-
-
-\indexii{\POSIX}{file object}
-
-\deprecated{1.5}{The locking operation that this module provides is
-done better and more portably by the
-\function{\refmodule{fcntl}.lockf()} call.
-\withsubitem{(in module fcntl)}{\ttindex{lockf()}}}
-
-This module implements some additional functionality over the built-in
-file objects.  In particular, it implements file locking, control over
-the file flags, and an easy interface to duplicate the file object.
-The module defines a new file object, the posixfile object.  It
-has all the standard file object methods and adds the methods
-described below.  This module only works for certain flavors of
-\UNIX, since it uses \function{fcntl.fcntl()} for file locking.%
-\withsubitem{(in module fcntl)}{\ttindex{fcntl()}}
-
-To instantiate a posixfile object, use the \function{open()} function
-in the \module{posixfile} module.  The resulting object looks and
-feels roughly the same as a standard file object.
-
-The \module{posixfile} module defines the following constants:
-
-
-\begin{datadesc}{SEEK_SET}
-Offset is calculated from the start of the file.
-\end{datadesc}
-
-\begin{datadesc}{SEEK_CUR}
-Offset is calculated from the current position in the file.
-\end{datadesc}
-
-\begin{datadesc}{SEEK_END}
-Offset is calculated from the end of the file.
-\end{datadesc}
-
-The \module{posixfile} module defines the following functions:
-
-
-\begin{funcdesc}{open}{filename\optional{, mode\optional{, bufsize}}}
- Create a new posixfile object with the given filename and mode.  The
- \var{filename}, \var{mode} and \var{bufsize} arguments are
- interpreted the same way as by the built-in \function{open()}
- function.
-\end{funcdesc}
-
-\begin{funcdesc}{fileopen}{fileobject}
- Create a new posixfile object with the given standard file object.
- The resulting object has the same filename and mode as the original
- file object.
-\end{funcdesc}
-
-The posixfile object defines the following additional methods:
-
-\setindexsubitem{(posixfile method)}
-\begin{funcdesc}{lock}{fmt, \optional{len\optional{, start\optional{, whence}}}}
- Lock the specified section of the file that the file object is
- referring to.  The format is explained
- below in a table.  The \var{len} argument specifies the length of the
- section that should be locked. The default is \code{0}. \var{start}
- specifies the starting offset of the section, where the default is
- \code{0}.  The \var{whence} argument specifies where the offset is
- relative to. It accepts one of the constants \constant{SEEK_SET},
- \constant{SEEK_CUR} or \constant{SEEK_END}.  The default is
- \constant{SEEK_SET}.  For more information about the arguments refer
- to the \manpage{fcntl}{2} manual page on your system.
-\end{funcdesc}
-
-\begin{funcdesc}{flags}{\optional{flags}}
- Set the specified flags for the file that the file object is referring
- to.  The new flags are ORed with the old flags, unless specified
- otherwise.  The format is explained below in a table.  Without
- the \var{flags} argument
- a string indicating the current flags is returned (this is
- the same as the \samp{?} modifier).  For more information about the
- flags refer to the \manpage{fcntl}{2} manual page on your system.
-\end{funcdesc}
-
-\begin{funcdesc}{dup}{}
- Duplicate the file object and the underlying file pointer and file
- descriptor.  The resulting object behaves as if it were newly
- opened.
-\end{funcdesc}
-
-\begin{funcdesc}{dup2}{fd}
- Duplicate the file object and the underlying file pointer and file
- descriptor.  The new object will have the given file descriptor.
- Otherwise the resulting object behaves as if it were newly opened.
-\end{funcdesc}
-
-\begin{funcdesc}{file}{}
- Return the standard file object that the posixfile object is based
- on.  This is sometimes necessary for functions that insist on a
- standard file object.
-\end{funcdesc}
-
-All methods raise \exception{IOError} when the request fails.
-
-Format characters for the \method{lock()} method have the following
-meaning:
-
-\begin{tableii}{c|l}{samp}{Format}{Meaning}
-  \lineii{u}{unlock the specified region}
-  \lineii{r}{request a read lock for the specified section}
-  \lineii{w}{request a write lock for the specified section}
-\end{tableii}
-
-In addition the following modifiers can be added to the format:
-
-\begin{tableiii}{c|l|c}{samp}{Modifier}{Meaning}{Notes}
-  \lineiii{|}{wait until the lock has been granted}{}
-  \lineiii{?}{return the first lock conflicting with the requested lock, or
-              \code{None} if there is no conflict.}{(1)} 
-\end{tableiii}
-
-\noindent
-Note:
-
-\begin{description}
-\item[(1)] The lock returned is in the format \code{(\var{mode}, \var{len},
-\var{start}, \var{whence}, \var{pid})} where \var{mode} is a character
-representing the type of lock ('r' or 'w').  This modifier prevents a
-request from being granted; it is for query purposes only.
-\end{description}
-
-Format characters for the \method{flags()} method have the following
-meanings:
-
-\begin{tableii}{c|l}{samp}{Format}{Meaning}
-  \lineii{a}{append only flag}
-  \lineii{c}{close on exec flag}
-  \lineii{n}{no delay flag (also called non-blocking flag)}
-  \lineii{s}{synchronization flag}
-\end{tableii}
-
-In addition the following modifiers can be added to the format:
-
-\begin{tableiii}{c|l|c}{samp}{Modifier}{Meaning}{Notes}
-  \lineiii{!}{turn the specified flags 'off', instead of the default 'on'}{(1)}
-  \lineiii{=}{replace the flags, instead of the default 'OR' operation}{(1)}
-  \lineiii{?}{return a string in which the characters represent the flags that
-  are set.}{(2)}
-\end{tableiii}
-
-\noindent
-Notes:
-
-\begin{description}
-\item[(1)] The \samp{!} and \samp{=} modifiers are mutually exclusive.
-
-\item[(2)] This string represents the flags after they may have been altered
-by the same call.
-\end{description}
-
-Examples:
-
-\begin{verbatim}
-import posixfile
-
-file = posixfile.open('/tmp/test', 'w')
-file.lock('w|')
-...
-file.lock('u')
-file.close()
-\end{verbatim}

Modified: python/branches/p3yk-noslice/Doc/lib/libposixpath.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libposixpath.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libposixpath.tex	Wed Jul 11 15:40:56 2007
@@ -58,18 +58,20 @@
 \end{funcdesc}
 
 \begin{funcdesc}{expanduser}{path}
-On \UNIX, return the argument with an initial component of \samp{\~} or
-\samp{\~\var{user}} replaced by that \var{user}'s home directory.
-An initial \samp{\~} is replaced by the environment variable
+On \UNIX{} and Windows, return the argument with an initial component of
+\samp{\~} or \samp{\~\var{user}} replaced by that \var{user}'s home directory.
+
+On \UNIX, an initial \samp{\~} is replaced by the environment variable
 \envvar{HOME} if it is set; otherwise the current user's home directory
 is looked up in the password directory through the built-in module
 \refmodule{pwd}\refbimodindex{pwd}.
 An initial \samp{\~\var{user}} is looked up directly in the
 password directory.
 
-On Windows, only \samp{\~} is supported; it is replaced by the
-environment variable \envvar{HOME} or by a combination of
-\envvar{HOMEDRIVE} and \envvar{HOMEPATH}.
+On Windows, \envvar{HOME} and \envvar{USERPROFILE} will be used if set,
+otherwise a combination of \envvar{HOMEPATH} and \envvar{HOMEDRIVE} will be
+used.  An initial \samp{\~\var{user}} is handled by stripping the last
+directory component from the created user path derived above.
 
 If the expansion fails or if the
 path does not begin with a tilde, the path is returned unchanged.
@@ -81,6 +83,9 @@
 replaced by the value of environment variable \var{name}.  Malformed
 variable names and references to non-existing variables are left
 unchanged.
+
+On Windows, \samp{\%\var{name}\%} expansions are supported in addition to
+\samp{\$\var{name}} and \samp{\$\{\var{name}\}}.
 \end{funcdesc}
 
 \begin{funcdesc}{getatime}{path}
@@ -184,6 +189,15 @@
 \versionadded{2.2}
 \end{funcdesc}
 
+\begin{funcdesc}{relpath}{path\optional{, start}}
+Return a relative filepath to \var{path} either from the current
+directory or from an optional \var{start} point.
+
+\var{start} defaults to \member{os.curdir}.
+Availability:  Windows, \UNIX.
+\versionadded{2.6}
+\end{funcdesc}
+
 \begin{funcdesc}{samefile}{path1, path2}
 Return \code{True} if both pathname arguments refer to the same file or
 directory (as indicated by device number and i-node number).
@@ -234,7 +248,12 @@
 Split the pathname \var{path} into a pair \code{(\var{root}, \var{ext})} 
 such that \code{\var{root} + \var{ext} == \var{path}},
 and \var{ext} is empty or begins with a period and contains
-at most one period.
+at most one period. Leading periods on the basename are 
+ignored; \code{\var{splitext}.('.cshrc')} returns 
+\code{('.cshrc', '')}.
+
+\versionchanged[Earlier versions could produce an empty root when
+the only period was the first character]{2.6}
 \end{funcdesc}
 
 \begin{funcdesc}{splitunc}{path}

Modified: python/branches/p3yk-noslice/Doc/lib/libpprint.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libpprint.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libpprint.tex	Wed Jul 11 15:40:56 2007
@@ -118,7 +118,7 @@
 \begin{funcdesc}{isreadable}{object}
 Determine if the formatted representation of \var{object} is
 ``readable,'' or can be used to reconstruct the value using
-\function{eval()}\bifuncindex{eval}.  This always returns false for
+\function{eval()}\bifuncindex{eval}.  This always returns \code{False} for
 recursive objects.
 
 \begin{verbatim}
@@ -158,12 +158,12 @@
 \class{PrettyPrinter} instances have the following methods:
 
 
-\begin{methoddesc}{pformat}{object}
+\begin{methoddesc}[PrettyPrinter]{pformat}{object}
 Return the formatted representation of \var{object}.  This takes into
 account the options passed to the \class{PrettyPrinter} constructor.
 \end{methoddesc}
 
-\begin{methoddesc}{pprint}{object}
+\begin{methoddesc}[PrettyPrinter]{pprint}{object}
 Print the formatted representation of \var{object} on the configured
 stream, followed by a newline.
 \end{methoddesc}
@@ -173,16 +173,16 @@
 instance is slightly more efficient since new \class{PrettyPrinter}
 objects don't need to be created.
 
-\begin{methoddesc}{isreadable}{object}
+\begin{methoddesc}[PrettyPrinter]{isreadable}{object}
 Determine if the formatted representation of the object is
 ``readable,'' or can be used to reconstruct the value using
-\function{eval()}\bifuncindex{eval}.  Note that this returns false for
+\function{eval()}\bifuncindex{eval}.  Note that this returns \code{False} for
 recursive objects.  If the \var{depth} parameter of the
 \class{PrettyPrinter} is set and the object is deeper than allowed,
-this returns false.
+this returns \code{False}.
 \end{methoddesc}
 
-\begin{methoddesc}{isrecursive}{object}
+\begin{methoddesc}[PrettyPrinter]{isrecursive}{object}
 Determine if the object requires a recursive representation.
 \end{methoddesc}
 
@@ -190,7 +190,7 @@
 way objects are converted to strings.  The default implementation uses
 the internals of the \function{saferepr()} implementation.
 
-\begin{methoddesc}{format}{object, context, maxlevels, level}
+\begin{methoddesc}[PrettyPrinter]{format}{object, context, maxlevels, level}
 Returns three values: the formatted version of \var{object} as a
 string, a flag indicating whether the result is readable, and a flag
 indicating whether recursion was detected.  The first argument is the
@@ -199,7 +199,7 @@
 context (direct and indirect containers for \var{object} that are
 affecting the presentation) as the keys; if an object needs to be
 presented which is already represented in \var{context}, the third
-return value should be true.  Recursive calls to the \method{format()}
+return value should be \code{True}.  Recursive calls to the \method{format()}
 method should add additional entries for containers to this
 dictionary.  The third argument, \var{maxlevels}, gives the requested
 limit to recursion; this will be \code{0} if there is no requested

Modified: python/branches/p3yk-noslice/Doc/lib/libqueue.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libqueue.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libqueue.tex	Wed Jul 11 15:40:56 2007
@@ -45,22 +45,22 @@
 is not described here.  See the source code for details.  The public
 methods are:
 
-\begin{methoddesc}{qsize}{}
+\begin{methoddesc}[Queue]{qsize}{}
 Return the approximate size of the queue.  Because of multithreading
 semantics, this number is not reliable.
 \end{methoddesc}
 
-\begin{methoddesc}{empty}{}
+\begin{methoddesc}[Queue]{empty}{}
 Return \code{True} if the queue is empty, \code{False} otherwise.
 Because of multithreading semantics, this is not reliable.
 \end{methoddesc}
 
-\begin{methoddesc}{full}{}
+\begin{methoddesc}[Queue]{full}{}
 Return \code{True} if the queue is full, \code{False} otherwise.
 Because of multithreading semantics, this is not reliable.
 \end{methoddesc}
 
-\begin{methoddesc}{put}{item\optional{, block\optional{, timeout}}}
+\begin{methoddesc}[Queue]{put}{item\optional{, block\optional{, timeout}}}
 Put \var{item} into the queue. If optional args \var{block} is true
 and \var{timeout} is None (the default), block if necessary until a
 free slot is available. If \var{timeout} is a positive number, it
@@ -74,11 +74,11 @@
 
 \end{methoddesc}
 
-\begin{methoddesc}{put_nowait}{item}
+\begin{methoddesc}[Queue]{put_nowait}{item}
 Equivalent to \code{put(\var{item}, False)}.
 \end{methoddesc}
 
-\begin{methoddesc}{get}{\optional{block\optional{, timeout}}}
+\begin{methoddesc}[Queue]{get}{\optional{block\optional{, timeout}}}
 Remove and return an item from the queue. If optional args
 \var{block} is true and \var{timeout} is None (the default),
 block if necessary until an item is available. If \var{timeout} is
@@ -92,14 +92,14 @@
 
 \end{methoddesc}
 
-\begin{methoddesc}{get_nowait}{}
+\begin{methoddesc}[Queue]{get_nowait}{}
 Equivalent to \code{get(False)}.
 \end{methoddesc}
 
 Two methods are offered to support tracking whether enqueued tasks have
 been fully processed by daemon consumer threads.
 
-\begin{methoddesc}{task_done}{}
+\begin{methoddesc}[Queue]{task_done}{}
 Indicate that a formerly enqueued task is complete.  Used by queue consumer
 threads.  For each \method{get()} used to fetch a task, a subsequent call to
 \method{task_done()} tells the queue that the processing on the task is complete.
@@ -113,7 +113,7 @@
 \versionadded{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}{join}{}
+\begin{methoddesc}[Queue]{join}{}
 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

Modified: python/branches/p3yk-noslice/Doc/lib/librandom.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/librandom.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/librandom.tex	Wed Jul 11 15:40:56 2007
@@ -163,9 +163,9 @@
   population contains repeats, then each occurrence is a possible
   selection in the sample.
 
-  To choose a sample from a range of integers, use an \function{xrange()}
+  To choose a sample from a range of integers, use an \function{range()}
   object as an argument.  This is especially fast and space efficient for
-  sampling from a large population:  \code{sample(xrange(10000000), 60)}.
+  sampling from a large population:  \code{sample(range(10000000), 60)}.
 \end{funcdesc}
 
 

Modified: python/branches/p3yk-noslice/Doc/lib/libre.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libre.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libre.tex	Wed Jul 11 15:40:56 2007
@@ -812,7 +812,7 @@
 \end{methoddesc}
 
 \begin{methoddesc}[MatchObject]{start}{\optional{group}}
-\methodline{end}{\optional{group}}
+\methodline[MatchObject]{end}{\optional{group}}
 Return the indices of the start and end of the substring
 matched by \var{group}; \var{group} defaults to zero (meaning the whole
 matched substring).

Modified: python/branches/p3yk-noslice/Doc/lib/librepr.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/librepr.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/librepr.tex	Wed Jul 11 15:40:56 2007
@@ -44,18 +44,18 @@
 and methods which format specific object types.
 
 
-\begin{memberdesc}{maxlevel}
+\begin{memberdesc}[Repr]{maxlevel}
   Depth limit on the creation of recursive representations.  The
   default is \code{6}.
 \end{memberdesc}
 
-\begin{memberdesc}{maxdict}
-\memberline{maxlist}
-\memberline{maxtuple}
-\memberline{maxset}
-\memberline{maxfrozenset}
-\memberline{maxdeque}
-\memberline{maxarray}
+\begin{memberdesc}[Repr]{maxdict}
+\memberline[Repr]{maxlist}
+\memberline[Repr]{maxtuple}
+\memberline[Repr]{maxset}
+\memberline[Repr]{maxfrozenset}
+\memberline[Repr]{maxdeque}
+\memberline[Repr]{maxarray}
   Limits on the number of entries represented for the named object
   type.  The default is \code{4} for \member{maxdict}, \code{5} for
   \member{maxarray}, and  \code{6} for the others.
@@ -63,13 +63,13 @@
   and \member{set}]{2.4}.
 \end{memberdesc}
 
-\begin{memberdesc}{maxlong}
+\begin{memberdesc}[Repr]{maxlong}
   Maximum number of characters in the representation for a long
   integer.  Digits are dropped from the middle.  The default is
   \code{40}.
 \end{memberdesc}
 
-\begin{memberdesc}{maxstring}
+\begin{memberdesc}[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
@@ -77,19 +77,19 @@
   shortened.  The default is \code{30}.
 \end{memberdesc}
 
-\begin{memberdesc}{maxother}
+\begin{memberdesc}[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 \member{maxstring}.  The
   default is \code{20}.
 \end{memberdesc}
 
-\begin{methoddesc}{repr}{obj}
+\begin{methoddesc}[Repr]{repr}{obj}
   The equivalent to the built-in \function{repr()} that uses the
   formatting imposed by the instance.
 \end{methoddesc}
 
-\begin{methoddesc}{repr1}{obj, level}
+\begin{methoddesc}[Repr]{repr1}{obj, level}
   Recursive implementation used by \method{repr()}.  This uses the
   type of \var{obj} to determine which formatting method to call,
   passing it \var{obj} and \var{level}.  The type-specific methods
@@ -98,7 +98,7 @@
   call.
 \end{methoddesc}
 
-\begin{methoddescni}{repr_\var{type}}{obj, level}
+\begin{methoddescni}[Repr]{repr_\var{type}}{obj, level}
   Formatting methods for specific types are implemented as methods
   with a name based on the type name.  In the method name, \var{type}
   is replaced by

Deleted: /python/branches/p3yk-noslice/Doc/lib/librestricted.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/librestricted.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,66 +0,0 @@
-\chapter{Restricted Execution \label{restricted}}
-
-\begin{notice}[warning]
-   In Python 2.3 these modules have been disabled due to various known
-   and not readily fixable security holes.  The modules are still
-   documented here to help in reading old code that uses the
-   \module{rexec} and \module{Bastion} modules.
-\end{notice}
-
-\emph{Restricted execution} is the basic framework in Python that allows
-for the segregation of trusted and untrusted code.  The framework is based on the
-notion that trusted Python code (a \emph{supervisor}) can create a
-``padded cell' (or environment) with limited permissions, and run the
-untrusted code within this cell.  The untrusted code cannot break out
-of its cell, and can only interact with sensitive system resources
-through interfaces defined and managed by the trusted code.  The term
-``restricted execution'' is favored over ``safe-Python''
-since true safety is hard to define, and is determined by the way the
-restricted environment is created.  Note that the restricted
-environments can be nested, with inner cells creating subcells of
-lesser, but never greater, privilege.
-
-An interesting aspect of Python's restricted execution model is that
-the interfaces presented to untrusted code usually have the same names
-as those presented to trusted code.  Therefore no special interfaces
-need to be learned to write code designed to run in a restricted
-environment.  And because the exact nature of the padded cell is
-determined by the supervisor, different restrictions can be imposed,
-depending on the application.  For example, it might be deemed
-``safe'' for untrusted code to read any file within a specified
-directory, but never to write a file.  In this case, the supervisor
-may redefine the built-in \function{open()} function so that it raises
-an exception whenever the \var{mode} parameter is \code{'w'}.  It
-might also perform a \cfunction{chroot()}-like operation on the
-\var{filename} parameter, such that root is always relative to some
-safe ``sandbox'' area of the filesystem.  In this case, the untrusted
-code would still see an built-in \function{open()} function in its
-environment, with the same calling interface.  The semantics would be
-identical too, with \exception{IOError}s being raised when the
-supervisor determined that an unallowable parameter is being used.
-
-The Python run-time determines whether a particular code block is
-executing in restricted execution mode based on the identity of the
-\code{__builtins__} object in its global variables: if this is (the
-dictionary of) the standard \refmodule[builtin]{__builtin__} module,
-the code is deemed to be unrestricted, else it is deemed to be
-restricted.
-
-Python code executing in restricted mode faces a number of limitations
-that are designed to prevent it from escaping from the padded cell.
-For instance, the function object attribute \member{func_globals} and
-the class and instance object attribute \member{__dict__} are
-unavailable.
-
-Two modules provide the framework for setting up restricted execution
-environments:
-
-\localmoduletable
-
-\begin{seealso}
-  \seetitle[http://grail.sourceforge.net/]{Grail Home Page}
-           {Grail, an Internet browser written in Python, uses these
-            modules to support Python applets.  More
-            information on the use of Python's restricted execution
-            mode in Grail is available on the Web site.}
-\end{seealso}

Deleted: /python/branches/p3yk-noslice/Doc/lib/librexec.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/librexec.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,275 +0,0 @@
-\section{\module{rexec} ---
-         Restricted execution framework}
-
-\declaremodule{standard}{rexec}
-\modulesynopsis{Basic restricted execution framework.}
-\versionchanged[Disabled module]{2.3}
-
-\begin{notice}[warning]
-  The documentation has been left in place to help in reading old code
-  that uses the module.
-\end{notice}
-
-This module contains the \class{RExec} class, which supports
-\method{r_exec()}, \method{r_eval()}, \method{r_execfile()}, and
-\method{r_import()} methods, which are restricted versions of the standard
-Python functions \method{exec()}, \method{eval()}, \method{execfile()} and
-the \keyword{import} statement.
-Code executed in this restricted environment will
-only have access to modules and functions that are deemed safe; you
-can subclass \class{RExec} to add or remove capabilities as desired.
-
-\begin{notice}[warning]
-  While the \module{rexec} module is designed to perform as described
-  below, it does have a few known vulnerabilities which could be
-  exploited by carefully written code.  Thus it should not be relied
-  upon in situations requiring ``production ready'' security.  In such
-  situations, execution via sub-processes or very careful
-  ``cleansing'' of both code and data to be processed may be
-  necessary.  Alternatively, help in patching known \module{rexec}
-  vulnerabilities would be welcomed.
-\end{notice}
-
-\begin{notice}
-  The \class{RExec} class can prevent code from performing unsafe
-  operations like reading or writing disk files, or using TCP/IP
-  sockets.  However, it does not protect against code using extremely
-  large amounts of memory or processor time.
-\end{notice}
-
-\begin{classdesc}{RExec}{\optional{hooks\optional{, verbose}}}
-Returns an instance of the \class{RExec} class.  
-
-\var{hooks} is an instance of the \class{RHooks} class or a subclass of it.
-If it is omitted or \code{None}, the default \class{RHooks} class is
-instantiated.
-Whenever the \module{rexec} module searches for a module (even a
-built-in one) or reads a module's code, it doesn't actually go out to
-the file system itself.  Rather, it calls methods of an \class{RHooks}
-instance that was passed to or created by its constructor.  (Actually,
-the \class{RExec} object doesn't make these calls --- they are made by
-a module loader object that's part of the \class{RExec} object.  This
-allows another level of flexibility, which can be useful when changing
-the mechanics of \keyword{import} within the restricted environment.)
-
-By providing an alternate \class{RHooks} object, we can control the
-file system accesses made to import a module, without changing the
-actual algorithm that controls the order in which those accesses are
-made.  For instance, we could substitute an \class{RHooks} object that
-passes all filesystem requests to a file server elsewhere, via some
-RPC mechanism such as ILU.  Grail's applet loader uses this to support
-importing applets from a URL for a directory.
-
-If \var{verbose} is true, additional debugging output may be sent to
-standard output.
-\end{classdesc}
-
-It is important to be aware that code running in a restricted
-environment can still call the \function{sys.exit()} function.  To
-disallow restricted code from exiting the interpreter, always protect
-calls that cause restricted code to run with a
-\keyword{try}/\keyword{except} statement that catches the
-\exception{SystemExit} exception.  Removing the \function{sys.exit()}
-function from the restricted environment is not sufficient --- the
-restricted code could still use \code{raise SystemExit}.  Removing
-\exception{SystemExit} is not a reasonable option; some library code
-makes use of this and would break were it not available.
-
-
-\begin{seealso}
-  \seetitle[http://grail.sourceforge.net/]{Grail Home Page}{Grail is a
-            Web browser written entirely in Python.  It uses the
-            \module{rexec} module as a foundation for supporting
-            Python applets, and can be used as an example usage of
-            this module.}
-\end{seealso}
-
-
-\subsection{RExec Objects \label{rexec-objects}}
-
-\class{RExec} instances support the following methods:
-
-\begin{methoddesc}{r_eval}{code}
-\var{code} must either be a string containing a Python expression, or
-a compiled code object, which will be evaluated in the restricted
-environment's \module{__main__} module.  The value of the expression or
-code object will be returned.
-\end{methoddesc}
-
-\begin{methoddesc}{r_exec}{code}
-\var{code} must either be a string containing one or more lines of
-Python code, or a compiled code object, which will be executed in the
-restricted environment's \module{__main__} module.
-\end{methoddesc}
-
-\begin{methoddesc}{r_execfile}{filename}
-Execute the Python code contained in the file \var{filename} in the
-restricted environment's \module{__main__} module.
-\end{methoddesc}
-
-Methods whose names begin with \samp{s_} are similar to the functions
-beginning with \samp{r_}, but the code will be granted access to
-restricted versions of the standard I/O streams \code{sys.stdin},
-\code{sys.stderr}, and \code{sys.stdout}.
-
-\begin{methoddesc}{s_eval}{code}
-\var{code} must be a string containing a Python expression, which will
-be evaluated in the restricted environment.  
-\end{methoddesc}
-
-\begin{methoddesc}{s_exec}{code}
-\var{code} must be a string containing one or more lines of Python code,
-which will be executed in the restricted environment.  
-\end{methoddesc}
-
-\begin{methoddesc}{s_execfile}{code}
-Execute the Python code contained in the file \var{filename} in the
-restricted environment.
-\end{methoddesc}
-
-\class{RExec} objects must also support various methods which will be
-implicitly called by code executing in the restricted environment.
-Overriding these methods in a subclass is used to change the policies
-enforced by a restricted environment.
-
-\begin{methoddesc}{r_import}{modulename\optional{, globals\optional{,
-                             locals\optional{, fromlist}}}}
-Import the module \var{modulename}, raising an \exception{ImportError}
-exception if the module is considered unsafe.
-\end{methoddesc}
-
-\begin{methoddesc}{r_open}{filename\optional{, mode\optional{, bufsize}}}
-Method called when \function{open()} is called in the restricted
-environment.  The arguments are identical to those of \function{open()},
-and a file object (or a class instance compatible with file objects)
-should be returned.  \class{RExec}'s default behaviour is allow opening
-any file for reading, but forbidding any attempt to write a file.  See
-the example below for an implementation of a less restrictive
-\method{r_open()}.
-\end{methoddesc}
-
-\begin{methoddesc}{r_reload}{module}
-Reload the module object \var{module}, re-parsing and re-initializing it.  
-\end{methoddesc}
-
-\begin{methoddesc}{r_unload}{module}
-Unload the module object \var{module} (remove it from the
-restricted environment's \code{sys.modules} dictionary).
-\end{methoddesc}
-
-And their equivalents with access to restricted standard I/O streams:
-
-\begin{methoddesc}{s_import}{modulename\optional{, globals\optional{,
-                             locals\optional{, fromlist}}}}
-Import the module \var{modulename}, raising an \exception{ImportError}
-exception if the module is considered unsafe.
-\end{methoddesc}
-
-\begin{methoddesc}{s_reload}{module}
-Reload the module object \var{module}, re-parsing and re-initializing it.  
-\end{methoddesc}
-
-\begin{methoddesc}{s_unload}{module}
-Unload the module object \var{module}.   
-% XXX what are the semantics of this?  
-\end{methoddesc}
-
-
-\subsection{Defining restricted environments \label{rexec-extension}}
-
-The \class{RExec} class has the following class attributes, which are
-used by the \method{__init__()} method.  Changing them on an existing
-instance won't have any effect; instead, create a subclass of
-\class{RExec} and assign them new values in the class definition.
-Instances of the new class will then use those new values.  All these
-attributes are tuples of strings.
-
-\begin{memberdesc}{nok_builtin_names}
-Contains the names of built-in functions which will \emph{not} be
-available to programs running in the restricted environment.  The
-value for \class{RExec} is \code{('open', 'reload', '__import__')}.
-(This gives the exceptions, because by far the majority of built-in
-functions are harmless.  A subclass that wants to override this
-variable should probably start with the value from the base class and
-concatenate additional forbidden functions --- when new dangerous
-built-in functions are added to Python, they will also be added to
-this module.)
-\end{memberdesc}
-
-\begin{memberdesc}{ok_builtin_modules}
-Contains the names of built-in modules which can be safely imported.
-The value for \class{RExec} is \code{('audioop', 'array', 'binascii',
-'cmath', 'errno', 'imageop', 'marshal', 'math', 'md5', 'operator',
-'parser', 'regex', 'select', 'sha', '_sre', 'strop',
-'struct', 'time')}.  A similar remark about overriding this variable
-applies --- use the value from the base class as a starting point.
-\end{memberdesc}
-
-\begin{memberdesc}{ok_path}
-Contains the directories which will be searched when an \keyword{import}
-is performed in the restricted environment.  
-The value for \class{RExec} is the same as \code{sys.path} (at the time
-the module is loaded) for unrestricted code.
-\end{memberdesc}
-
-\begin{memberdesc}{ok_posix_names}
-% Should this be called ok_os_names?
-Contains the names of the functions in the \refmodule{os} module which will be
-available to programs running in the restricted environment.  The
-value for \class{RExec} is \code{('error', 'fstat', 'listdir',
-'lstat', 'readlink', 'stat', 'times', 'uname', 'getpid', 'getppid',
-'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')}.
-\end{memberdesc}
-
-\begin{memberdesc}{ok_sys_names}
-Contains the names of the functions and variables in the \refmodule{sys}
-module which will be available to programs running in the restricted
-environment.  The value for \class{RExec} is \code{('ps1', 'ps2',
-'copyright', 'version', 'platform', 'exit', 'maxint')}.
-\end{memberdesc}
-
-\begin{memberdesc}{ok_file_types}
-Contains the file types from which modules are allowed to be loaded.
-Each file type is an integer constant defined in the \refmodule{imp} module.
-The meaningful values are \constant{PY_SOURCE}, \constant{PY_COMPILED}, and
-\constant{C_EXTENSION}.  The value for \class{RExec} is \code{(C_EXTENSION,
-PY_SOURCE)}.  Adding \constant{PY_COMPILED} in subclasses is not recommended;
-an attacker could exit the restricted execution mode by putting a forged
-byte-compiled file (\file{.pyc}) anywhere in your file system, for example
-by writing it to \file{/tmp} or uploading it to the \file{/incoming}
-directory of your public FTP server.
-\end{memberdesc}
-
-
-\subsection{An example}
-
-Let us say that we want a slightly more relaxed policy than the
-standard \class{RExec} class.  For example, if we're willing to allow
-files in \file{/tmp} to be written, we can subclass the \class{RExec}
-class:
-
-\begin{verbatim}
-class TmpWriterRExec(rexec.RExec):
-    def r_open(self, file, mode='r', buf=-1):
-        if mode in ('r', 'rb'):
-            pass
-        elif mode in ('w', 'wb', 'a', 'ab'):
-            # check filename : must begin with /tmp/
-            if file[:5]!='/tmp/': 
-                raise IOError, "can't write outside /tmp"
-            elif (string.find(file, '/../') >= 0 or
-                 file[:3] == '../' or file[-3:] == '/..'):
-                raise IOError, "'..' in filename forbidden"
-        else: raise IOError, "Illegal open() mode"
-        return open(file, mode, buf)
-\end{verbatim}
-%
-Notice that the above code will occasionally forbid a perfectly valid
-filename; for example, code in the restricted environment won't be
-able to open a file called \file{/tmp/foo/../bar}.  To fix this, the
-\method{r_open()} method would have to simplify the filename to
-\file{/tmp/bar}, which would require splitting apart the filename and
-performing various operations on it.  In cases where security is at
-stake, it may be preferable to write simple code which is sometimes
-overly restrictive, instead of more general code that is also more
-complex and may harbor a subtle security hole.

Modified: python/branches/p3yk-noslice/Doc/lib/librfc822.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/librfc822.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/librfc822.tex	Wed Jul 11 15:40:56 2007
@@ -100,7 +100,7 @@
 \code{'Mon, 20 Nov 1995 19:12:08 -0500'}.  If it succeeds in parsing
 the date, \function{parsedate()} returns a 9-tuple that can be passed
 directly to \function{time.mktime()}; otherwise \code{None} will be
-returned.  Note that fields 6, 7, and 8 of the result tuple are not
+returned.  Note that indexes 6, 7, and 8 of the result tuple are not
 usable.
 \end{funcdesc}
 
@@ -114,7 +114,7 @@
 variable for the same timezone; the latter variable follows the
 \POSIX{} standard while this module follows \rfc{2822}.)  If the input
 string has no timezone, the last element of the tuple returned is
-\code{None}.  Note that fields 6, 7, and 8 of the result tuple are not
+\code{None}.  Note that indexes 6, 7, and 8 of the result tuple are not
 usable.
 \end{funcdesc}
 
@@ -142,12 +142,12 @@
 
 A \class{Message} instance has the following methods:
 
-\begin{methoddesc}{rewindbody}{}
+\begin{methoddesc}[Message]{rewindbody}{}
 Seek to the start of the message body.  This only works if the file
 object is seekable.
 \end{methoddesc}
 
-\begin{methoddesc}{isheader}{line}
+\begin{methoddesc}[Message]{isheader}{line}
 Returns a line's canonicalized fieldname (the dictionary key that will
 be used to index it) if the line is a legal \rfc{2822} header; otherwise
 returns \code{None} (implying that parsing should stop here and the
@@ -155,33 +155,33 @@
 override this method in a subclass.
 \end{methoddesc}
 
-\begin{methoddesc}{islast}{line}
+\begin{methoddesc}[Message]{islast}{line}
 Return true if the given line is a delimiter on which Message should
 stop.  The delimiter line is consumed, and the file object's read
 location positioned immediately after it.  By default this method just
 checks that the line is blank, but you can override it in a subclass.
 \end{methoddesc}
 
-\begin{methoddesc}{iscomment}{line}
+\begin{methoddesc}[Message]{iscomment}{line}
 Return \code{True} if the given line should be ignored entirely, just skipped.
 By default this is a stub that always returns \code{False}, but you can
 override it in a subclass.
 \end{methoddesc}
 
-\begin{methoddesc}{getallmatchingheaders}{name}
+\begin{methoddesc}[Message]{getallmatchingheaders}{name}
 Return a list of lines consisting of all headers matching
 \var{name}, if any.  Each physical line, whether it is a continuation
 line or not, is a separate list item.  Return the empty list if no
 header matches \var{name}.
 \end{methoddesc}
 
-\begin{methoddesc}{getfirstmatchingheader}{name}
+\begin{methoddesc}[Message]{getfirstmatchingheader}{name}
 Return a list of lines comprising the first header matching
 \var{name}, and its continuation line(s), if any.  Return
 \code{None} if there is no header matching \var{name}.
 \end{methoddesc}
 
-\begin{methoddesc}{getrawheader}{name}
+\begin{methoddesc}[Message]{getrawheader}{name}
 Return a single string consisting of the text after the colon in the
 first header matching \var{name}.  This includes leading whitespace,
 the trailing linefeed, and internal linefeeds and whitespace if there
@@ -189,19 +189,19 @@
 no header matching \var{name}.
 \end{methoddesc}
 
-\begin{methoddesc}{getheader}{name\optional{, default}}
+\begin{methoddesc}[Message]{getheader}{name\optional{, default}}
 Like \code{getrawheader(\var{name})}, but strip leading and trailing
 whitespace.  Internal whitespace is not stripped.  The optional
 \var{default} argument can be used to specify a different default to
 be returned when there is no header matching \var{name}.
 \end{methoddesc}
 
-\begin{methoddesc}{get}{name\optional{, default}}
+\begin{methoddesc}[Message]{get}{name\optional{, default}}
 An alias for \method{getheader()}, to make the interface more compatible 
 with regular dictionaries.
 \end{methoddesc}
 
-\begin{methoddesc}{getaddr}{name}
+\begin{methoddesc}[Message]{getaddr}{name}
 Return a pair \code{(\var{full name}, \var{email address})} parsed
 from the string returned by \code{getheader(\var{name})}.  If no
 header matching \var{name} exists, return \code{(None, None)};
@@ -217,7 +217,7 @@
 exact same result.
 \end{methoddesc}
 
-\begin{methoddesc}{getaddrlist}{name}
+\begin{methoddesc}[Message]{getaddrlist}{name}
 This is similar to \code{getaddr(\var{list})}, but parses a header
 containing a list of email addresses (e.g.\ a \mailheader{To} header) and
 returns a list of \code{(\var{full name}, \var{email address})} pairs
@@ -229,7 +229,7 @@
 Any continuation lines the named headers contain are also parsed.
 \end{methoddesc}
 
-\begin{methoddesc}{getdate}{name}
+\begin{methoddesc}[Message]{getdate}{name}
 Retrieve a header using \method{getheader()} and parse it into a 9-tuple
 compatible with \function{time.mktime()}; note that fields 6, 7, and 8 
 are not usable.  If there is no header matching
@@ -241,7 +241,7 @@
 function may occasionally yield an incorrect result.
 \end{methoddesc}
 
-\begin{methoddesc}{getdate_tz}{name}
+\begin{methoddesc}[Message]{getdate_tz}{name}
 Retrieve a header using \method{getheader()} and parse it into a
 10-tuple; the first 9 elements will make a tuple compatible with
 \function{time.mktime()}, and the 10th is a number giving the offset
@@ -270,19 +270,19 @@
 
 Finally, \class{Message} instances have some public instance variables:
 
-\begin{memberdesc}{headers}
+\begin{memberdesc}[Message]{headers}
 A list containing the entire set of header lines, in the order in
 which they were read (except that setitem calls may disturb this
 order). Each line contains a trailing newline.  The
 blank line terminating the headers is not contained in the list.
 \end{memberdesc}
 
-\begin{memberdesc}{fp}
+\begin{memberdesc}[Message]{fp}
 The file or file-like object passed at instantiation time.  This can
 be used to read the message content.
 \end{memberdesc}
 
-\begin{memberdesc}{unixfrom}
+\begin{memberdesc}[Message]{unixfrom}
 The \UNIX{} \samp{From~} line, if the message had one, or an empty
 string.  This is needed to regenerate the message in some contexts,
 such as an \code{mbox}-style mailbox file.
@@ -293,34 +293,34 @@
 
 An \class{AddressList} instance has the following methods:
 
-\begin{methoddesc}{__len__}{}
+\begin{methoddesc}[AddressList]{__len__}{}
 Return the number of addresses in the address list.
 \end{methoddesc}
 
-\begin{methoddesc}{__str__}{}
+\begin{methoddesc}[AddressList]{__str__}{}
 Return a canonicalized string representation of the address list.
 Addresses are rendered in "name" <host at domain> form, comma-separated.
 \end{methoddesc}
 
-\begin{methoddesc}{__add__}{alist}
+\begin{methoddesc}[AddressList]{__add__}{alist}
 Return a new \class{AddressList} instance that contains all addresses
 in both \class{AddressList} operands, with duplicates removed (set
 union).
 \end{methoddesc}
 
-\begin{methoddesc}{__iadd__}{alist}
+\begin{methoddesc}[AddressList]{__iadd__}{alist}
 In-place version of \method{__add__()}; turns this \class{AddressList}
 instance into the union of itself and the right-hand instance,
 \var{alist}.
 \end{methoddesc}
 
-\begin{methoddesc}{__sub__}{alist}
+\begin{methoddesc}[AddressList]{__sub__}{alist}
 Return a new \class{AddressList} instance that contains every address
 in the left-hand \class{AddressList} operand that is not present in
 the right-hand address operand (set difference).
 \end{methoddesc}
 
-\begin{methoddesc}{__isub__}{alist}
+\begin{methoddesc}[AddressList]{__isub__}{alist}
 In-place version of \method{__sub__()}, removing addresses in this
 list which are also in \var{alist}.
 \end{methoddesc}
@@ -328,7 +328,7 @@
 
 Finally, \class{AddressList} instances have one public instance variable:
 
-\begin{memberdesc}{addresslist}
+\begin{memberdesc}[AddressList]{addresslist}
 A list of tuple string pairs, one per address.  In each member, the
 first is the canonicalized name part, the second is the
 actual route-address (\character{@}-separated username-host.domain

Deleted: /python/branches/p3yk-noslice/Doc/lib/librgbimg.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/librgbimg.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,54 +0,0 @@
-\section{\module{rgbimg} ---
-         Read and write ``SGI RGB'' files}
-
-\declaremodule{builtin}{rgbimg}
-\modulesynopsis{Read and write image files in ``SGI RGB'' format (the module
-                is \emph{not} SGI specific though!).}
-
-\deprecated{2.5}{This module is not maintained anymore and seems to be
-                 unused.}
-
-The \module{rgbimg} module allows Python programs to access SGI imglib image
-files (also known as \file{.rgb} files).  The module is far from
-complete, but is provided anyway since the functionality that there is
-enough in some cases.  Currently, colormap files are not supported.
-
-\note{This module is only built by default for 32-bit platforms; it is
-not expected to work properly on other systems.}
-
-The module defines the following variables and functions:
-
-\begin{excdesc}{error}
-This exception is raised on all errors, such as unsupported file type, etc.
-\end{excdesc}
-
-\begin{funcdesc}{sizeofimage}{file}
-This function returns a tuple \code{(\var{x}, \var{y})} where
-\var{x} and \var{y} are the size of the image in pixels.
-Only 4 byte RGBA pixels, 3 byte RGB pixels, and 1 byte greyscale pixels
-are currently supported.
-\end{funcdesc}
-
-\begin{funcdesc}{longimagedata}{file}
-This function reads and decodes the image on the specified file, and
-returns it as a Python string. The string has 4 byte RGBA pixels.
-The bottom left pixel is the first in
-the string. This format is suitable to pass to \function{gl.lrectwrite()},
-for instance.
-\end{funcdesc}
-
-\begin{funcdesc}{longstoimage}{data, x, y, z, file}
-This function writes the RGBA data in \var{data} to image
-file \var{file}. \var{x} and \var{y} give the size of the image.
-\var{z} is 1 if the saved image should be 1 byte greyscale, 3 if the
-saved image should be 3 byte RGB data, or 4 if the saved images should
-be 4 byte RGBA data.  The input data always contains 4 bytes per pixel.
-These are the formats returned by \function{gl.lrectread()}.
-\end{funcdesc}
-
-\begin{funcdesc}{ttob}{flag}
-This function sets a global flag which defines whether the scan lines
-of the image are read or written from bottom to top (flag is zero,
-compatible with SGI GL) or from top to bottom (flag is one,
-compatible with X).  The default is zero.
-\end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libsched.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsched.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsched.tex	Wed Jul 11 15:40:56 2007
@@ -48,7 +48,7 @@
 
 \class{scheduler} instances have the following methods:
 
-\begin{methoddesc}{enterabs}{time, priority, action, argument}
+\begin{methoddesc}[scheduler]{enterabs}{time, priority, action, argument}
 Schedule a new event. The \var{time} argument should be a numeric type
 compatible with the return value of the \var{timefunc} function passed 
 to the constructor. Events scheduled for
@@ -63,23 +63,23 @@
 the event (see \method{cancel()}).
 \end{methoddesc}
 
-\begin{methoddesc}{enter}{delay, priority, action, argument}
+\begin{methoddesc}[scheduler]{enter}{delay, priority, action, argument}
 Schedule an event for \var{delay} more time units. Other then the
 relative time, the other arguments, the effect and the return value
 are the same as those for \method{enterabs()}.
 \end{methoddesc}
 
-\begin{methoddesc}{cancel}{event}
+\begin{methoddesc}[scheduler]{cancel}{event}
 Remove the event from the queue. If \var{event} is not an event
 currently in the queue, this method will raise a
 \exception{RuntimeError}.
 \end{methoddesc}
 
-\begin{methoddesc}{empty}{}
+\begin{methoddesc}[scheduler]{empty}{}
 Return true if the event queue is empty.
 \end{methoddesc}
 
-\begin{methoddesc}{run}{}
+\begin{methoddesc}[scheduler]{run}{}
 Run all scheduled events. This function will wait 
 (using the \function{delayfunc} function passed to the constructor)
 for the next event, then execute it and so on until there are no more

Modified: python/branches/p3yk-noslice/Doc/lib/libselect.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libselect.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libselect.tex	Wed Jul 11 15:40:56 2007
@@ -77,7 +77,7 @@
 \cfunction{select()} is O(highest file descriptor), while
 \cfunction{poll()} is O(number of file descriptors).
 
-\begin{methoddesc}{register}{fd\optional{, eventmask}}
+\begin{methoddesc}[poll]{register}{fd\optional{, eventmask}}
 Register a file descriptor with the polling object.  Future calls to
 the \method{poll()} method will then check whether the file descriptor
 has any pending I/O events.  \var{fd} can be either an integer, or an
@@ -105,7 +105,7 @@
 once.
 \end{methoddesc}
 
-\begin{methoddesc}{unregister}{fd}
+\begin{methoddesc}[poll]{unregister}{fd}
 Remove a file descriptor being tracked by a polling object.  Just like
 the \method{register()} method, \var{fd} can be an integer or an
 object with a \method{fileno()} method that returns an integer.
@@ -114,7 +114,7 @@
 causes a \exception{KeyError} exception to be raised.
 \end{methoddesc}
 
-\begin{methoddesc}{poll}{\optional{timeout}}
+\begin{methoddesc}[poll]{poll}{\optional{timeout}}
 Polls the set of registered file descriptors, and returns a
 possibly-empty list containing \code{(\var{fd}, \var{event})} 2-tuples
 for the descriptors that have events or errors to report.

Deleted: /python/branches/p3yk-noslice/Doc/lib/libsets.tex
==============================================================================

Deleted: /python/branches/p3yk-noslice/Doc/lib/libsgi.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libsgi.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,7 +0,0 @@
-\chapter{SGI IRIX Specific Services}
-\label{sgi}
-
-The modules described in this chapter provide interfaces to features
-that are unique to SGI's IRIX operating system (versions 4 and 5).
-
-\localmoduletable

Deleted: /python/branches/p3yk-noslice/Doc/lib/libsha.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libsha.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,83 +0,0 @@
-\section{\module{sha} ---
-         SHA-1 message digest algorithm}
-
-\declaremodule{builtin}{sha}
-\modulesynopsis{NIST's secure hash algorithm, SHA.}
-\sectionauthor{Fred L. Drake, Jr.}{fdrake at acm.org}
-
-\deprecated{2.5}{Use the \refmodule{hashlib} module instead.}
-
-
-This module implements the interface to NIST's\index{NIST} secure hash 
-algorithm,\index{Secure Hash Algorithm} known as SHA-1.  SHA-1 is an
-improved version of the original SHA hash algorithm.  It is used in
-the same way as the \refmodule{md5} module:\ use \function{new()}
-to create an sha object, then feed this object with arbitrary strings
-using the \method{update()} method, and at any point you can ask it
-for the \dfn{digest} of the concatenation of the strings fed to it
-so far.\index{checksum!SHA}  SHA-1 digests are 160 bits instead of
-MD5's 128 bits.
-
-
-\begin{funcdesc}{new}{\optional{string}}
-  Return a new sha object.  If \var{string} is present, the method
-  call \code{update(\var{string})} is made.
-\end{funcdesc}
-
-
-The following values are provided as constants in the module and as
-attributes of the sha objects returned by \function{new()}:
-
-\begin{datadesc}{blocksize}
-  Size of the blocks fed into the hash function; this is always
-  \code{1}.  This size is used to allow an arbitrary string to be
-  hashed.
-\end{datadesc}
-
-\begin{datadesc}{digest_size}
-  The size of the resulting digest in bytes.  This is always
-  \code{20}.
-\end{datadesc}
-
-
-An sha object has the same methods as md5 objects:
-
-\begin{methoddesc}[sha]{update}{arg}
-Update the sha object with the string \var{arg}.  Repeated calls are
-equivalent to a single call with the concatenation of all the
-arguments: \code{m.update(a); m.update(b)} is equivalent to
-\code{m.update(a+b)}.
-\end{methoddesc}
-
-\begin{methoddesc}[sha]{digest}{}
-Return the digest of the strings passed to the \method{update()}
-method so far.  This is a 20-byte string which may contain
-non-\ASCII{} characters, including null bytes.
-\end{methoddesc}
-
-\begin{methoddesc}[sha]{hexdigest}{}
-Like \method{digest()} except the digest is returned as a string of
-length 40, containing only hexadecimal digits.  This may 
-be used to exchange the value safely in email or other non-binary
-environments.
-\end{methoddesc}
-
-\begin{methoddesc}[sha]{copy}{}
-Return a copy (``clone'') of the sha object.  This can be used to
-efficiently compute the digests of strings that share a common initial
-substring.
-\end{methoddesc}
-
-\begin{seealso}
-  \seetitle[http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf]
-    {Secure Hash Standard}
-    {The Secure Hash Algorithm is defined by NIST document FIPS
-     PUB 180-2:
-     \citetitle[http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf]
-        {Secure Hash Standard}, published in August 2002.}
-
-  \seetitle[http://csrc.nist.gov/encryption/tkhash.html]
-           {Cryptographic Toolkit (Secure Hashing)}
-           {Links from NIST to various information on secure hashing.}
-\end{seealso}
-

Modified: python/branches/p3yk-noslice/Doc/lib/libshlex.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libshlex.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libshlex.tex	Wed Jul 11 15:40:56 2007
@@ -19,13 +19,18 @@
 
 The \module{shlex} module defines the following functions:
 
-\begin{funcdesc}{split}{s\optional{, comments}}
+\begin{funcdesc}{split}{s\optional{, comments\optional{, posix}}}
 Split the string \var{s} using shell-like syntax. If \var{comments} is
 \constant{False} (the default), the parsing of comments in the given
 string will be disabled (setting the \member{commenters} member of the
 \class{shlex} instance to the empty string).  This function operates
-in \POSIX{} mode.
+in \POSIX{} mode by default, but uses non-\POSIX{} mode if the
+\var{posix} argument is false.
 \versionadded{2.3}
+\versionchanged[Added the \var{posix} parameter]{2.6}
+\note{Since the \function{split()} function instantiates a \class{shlex}
+      instance, passing \code{None} for \var{s} will read the string
+      to split from standard input.}
 \end{funcdesc}
 
 The \module{shlex} module defines the following class:
@@ -58,7 +63,7 @@
 
 A \class{shlex} instance has the following methods:
 
-\begin{methoddesc}{get_token}{}
+\begin{methoddesc}[shlex]{get_token}{}
 Return a token.  If tokens have been stacked using
 \method{push_token()}, pop a token off the stack.  Otherwise, read one
 from the input stream.  If reading encounters an immediate
@@ -66,17 +71,17 @@
 in non-\POSIX{} mode, and \code{None} in \POSIX{} mode).
 \end{methoddesc}
 
-\begin{methoddesc}{push_token}{str}
+\begin{methoddesc}[shlex]{push_token}{str}
 Push the argument onto the token stack.
 \end{methoddesc}
 
-\begin{methoddesc}{read_token}{}
+\begin{methoddesc}[shlex]{read_token}{}
 Read a raw token.  Ignore the pushback stack, and do not interpret source
 requests.  (This is not ordinarily a useful entry point, and is
 documented here only for the sake of completeness.)
 \end{methoddesc}
 
-\begin{methoddesc}{sourcehook}{filename}
+\begin{methoddesc}[shlex]{sourcehook}{filename}
 When \class{shlex} detects a source request (see
 \member{source} below) this method is given the following token as
 argument, and expected to return a tuple consisting of a filename and
@@ -106,7 +111,7 @@
 \method{push_source()} and \method{pop_source()} methods. 
 \end{methoddesc}
 
-\begin{methoddesc}{push_source}{stream\optional{, filename}}
+\begin{methoddesc}[shlex]{push_source}{stream\optional{, filename}}
 Push an input source stream onto the input stack.  If the filename
 argument is specified it will later be available for use in error
 messages.  This is the same method used internally by the
@@ -114,14 +119,14 @@
 \versionadded{2.1}
 \end{methoddesc}
 
-\begin{methoddesc}{pop_source}{}
+\begin{methoddesc}[shlex]{pop_source}{}
 Pop the last-pushed input source from the input stack.
 This is the same method used internally when the lexer reaches
 \EOF{} on a stacked input stream.
 \versionadded{2.1}
 \end{methoddesc}
 
-\begin{methoddesc}{error_leader}{\optional{file\optional{, line}}}
+\begin{methoddesc}[shlex]{error_leader}{\optional{file\optional{, line}}}
 This method generates an error message leader in the format of a
 \UNIX{} C compiler error label; the format is \code{'"\%s", line \%d: '},
 where the \samp{\%s} is replaced with the name of the current source
@@ -137,63 +142,63 @@
 variables which either control lexical analysis or can be used for
 debugging:
 
-\begin{memberdesc}{commenters}
+\begin{memberdesc}[shlex]{commenters}
 The string of characters that are recognized as comment beginners.
 All characters from the comment beginner to end of line are ignored.
 Includes just \character{\#} by default.   
 \end{memberdesc}
 
-\begin{memberdesc}{wordchars}
+\begin{memberdesc}[shlex]{wordchars}
 The string of characters that will accumulate into multi-character
 tokens.  By default, includes all \ASCII{} alphanumerics and
 underscore.
 \end{memberdesc}
 
-\begin{memberdesc}{whitespace}
+\begin{memberdesc}[shlex]{whitespace}
 Characters that will be considered whitespace and skipped.  Whitespace
 bounds tokens.  By default, includes space, tab, linefeed and
 carriage-return.
 \end{memberdesc}
 
-\begin{memberdesc}{escape}
+\begin{memberdesc}[shlex]{escape}
 Characters that will be considered as escape. This will be only used
 in \POSIX{} mode, and includes just \character{\textbackslash} by default.
 \versionadded{2.3}
 \end{memberdesc}
 
-\begin{memberdesc}{quotes}
+\begin{memberdesc}[shlex]{quotes}
 Characters that will be considered string quotes.  The token
 accumulates until the same quote is encountered again (thus, different
 quote types protect each other as in the shell.)  By default, includes
 \ASCII{} single and double quotes.
 \end{memberdesc}
 
-\begin{memberdesc}{escapedquotes}
+\begin{memberdesc}[shlex]{escapedquotes}
 Characters in \member{quotes} that will interpret escape characters
 defined in \member{escape}.  This is only used in \POSIX{} mode, and
 includes just \character{"} by default.
 \versionadded{2.3}
 \end{memberdesc}
 
-\begin{memberdesc}{whitespace_split}
+\begin{memberdesc}[shlex]{whitespace_split}
 If \code{True}, tokens will only be split in whitespaces. This is useful, for
 example, for parsing command lines with \class{shlex}, getting tokens
 in a similar way to shell arguments.
 \versionadded{2.3}
 \end{memberdesc}
 
-\begin{memberdesc}{infile}
+\begin{memberdesc}[shlex]{infile}
 The name of the current input file, as initially set at class
 instantiation time or stacked by later source requests.  It may
 be useful to examine this when constructing error messages.
 \end{memberdesc}
 
-\begin{memberdesc}{instream}
+\begin{memberdesc}[shlex]{instream}
 The input stream from which this \class{shlex} instance is reading
 characters.
 \end{memberdesc}
 
-\begin{memberdesc}{source}
+\begin{memberdesc}[shlex]{source}
 This member is \code{None} by default.  If you assign a string to it,
 that string will be recognized as a lexical-level inclusion request
 similar to the \samp{source} keyword in various shells.  That is, the
@@ -204,23 +209,23 @@
 number of levels deep.
 \end{memberdesc}
 
-\begin{memberdesc}{debug}
+\begin{memberdesc}[shlex]{debug}
 If this member is numeric and \code{1} or more, a \class{shlex}
 instance will print verbose progress output on its behavior.  If you
 need to use this, you can read the module source code to learn the
 details.
 \end{memberdesc}
 
-\begin{memberdesc}{lineno}
+\begin{memberdesc}[shlex]{lineno}
 Source line number (count of newlines seen so far plus one).
 \end{memberdesc}
 
-\begin{memberdesc}{token}
+\begin{memberdesc}[shlex]{token}
 The token buffer.  It may be useful to examine this when catching
 exceptions.
 \end{memberdesc}
 
-\begin{memberdesc}{eof}
+\begin{memberdesc}[shlex]{eof}
 Token used to determine end of file. This will be set to the empty
 string (\code{''}), in non-\POSIX{} mode, and to \code{None} in
 \POSIX{} mode.

Modified: python/branches/p3yk-noslice/Doc/lib/libshutil.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libshutil.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libshutil.tex	Wed Jul 11 15:40:56 2007
@@ -34,7 +34,9 @@
   is the buffer size. In particular, a negative \var{length} value
   means to copy the data without looping over the source data in
   chunks; by default the data is read in chunks to avoid uncontrolled
-  memory consumption.
+  memory consumption. Note that if the current file position of the
+  \var{fsrc} object is not 0, only the contents from the current file
+  position to the end of the file will be copied.
 \end{funcdesc}
 
 \begin{funcdesc}{copymode}{src, dst}
@@ -89,11 +91,12 @@
 \end{funcdesc}
 
 \begin{funcdesc}{rmtree}{path\optional{, ignore_errors\optional{, onerror}}}
-  Delete an entire directory tree.\index{directory!deleting}
-  If \var{ignore_errors} is true,
-  errors resulting from failed removals will be ignored; if false or
-  omitted, such errors are handled by calling a handler specified by
-  \var{onerror} or, if that is omitted, they raise an exception.
+  \index{directory!deleting}
+  Delete an entire directory tree (\var{path} must point to a directory).
+  If \var{ignore_errors} is true, errors resulting from failed removals
+  will be ignored; if false or omitted, such errors are handled by
+  calling a handler specified by \var{onerror} or, if that is omitted,
+  they raise an exception.
 
   If \var{onerror} is provided, it must be a callable that accepts
   three parameters: \var{function}, \var{path}, and \var{excinfo}.

Modified: python/branches/p3yk-noslice/Doc/lib/libsignal.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsignal.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsignal.tex	Wed Jul 11 15:40:56 2007
@@ -101,8 +101,7 @@
   be scheduled at any time).  The returned value is then the number of
   seconds before any previously set alarm was to have been delivered.
   If \var{time} is zero, no alarm is scheduled, and any scheduled
-  alarm is canceled.  The return value is the number of seconds
-  remaining before a previously scheduled alarm.  If the return value
+  alarm is canceled.  If the return value
   is zero, no alarm is currently scheduled.  (See the \UNIX{} man page
   \manpage{alarm}{2}.)
   Availability: \UNIX.

Modified: python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsimplexmlrpc.tex	Wed Jul 11 15:40:56 2007
@@ -15,7 +15,9 @@
 
 \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{,
                                       requestHandler\optional{,
-					logRequests\optional{, allow_none\optional{, encoding}}}}}
+					                  logRequests\optional{,
+                                      allow_none\optional{,
+                                      encoding}}}}}
 
   Create a new server instance.  This class
   provides methods for registration of functions that can be called by
@@ -28,8 +30,13 @@
   setting this parameter to false will turn off logging.  
   The \var{allow_none} and \var{encoding} parameters are passed on to 
   \module{xmlrpclib} and control the XML-RPC responses that will be returned 
-  from the server.
+  from the server. The \var{bind_and_activate} parameter controls whether
+  \method{server_bind()} and \method{server_activate()} are called immediately
+  by the constructor; it defaults to true. Setting it to false allows code to
+  manipulate the \var{allow_reuse_address} class variable before the address
+  is bound.
   \versionchanged[The \var{allow_none} and \var{encoding} parameters were added]{2.5}
+  \versionchanged[The \var{bind_and_activate} parameter was added]{2.6}
 \end{classdesc}
 
 \begin{classdesc}{CGIXMLRPCRequestHandler}{\optional{allow_none\optional{, encoding}}}
@@ -101,13 +108,13 @@
 
 \end{methoddesc}
 
-\begin{methoddesc}{register_introspection_functions}{}
+\begin{methoddesc}[SimpleXMLRPCServer]{register_introspection_functions}{}
   Registers the XML-RPC introspection functions \code{system.listMethods},
   \code{system.methodHelp} and \code{system.methodSignature}. 
   \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{register_multicall_functions}{}
+\begin{methoddesc}[SimpleXMLRPCServer]{register_multicall_functions}{}
   Registers the XML-RPC multicall function system.multicall.
 \end{methoddesc}
 
@@ -171,7 +178,7 @@
 The \class{CGIXMLRPCRequestHandler} class can be used to 
 handle XML-RPC requests sent to Python CGI scripts.
 
-\begin{methoddesc}{register_function}{function\optional{, name}}
+\begin{methoddesc}[CGIXMLRPCRequestHandler]{register_function}{function\optional{, name}}
 Register a function that can respond to XML-RPC requests. If 
 \var{name} is given, it will be the method name associated with 
 function, otherwise \var{function.__name__} will be used. \var{name}
@@ -180,7 +187,7 @@
 character. 
 \end{methoddesc}
 
-\begin{methoddesc}{register_instance}{instance}
+\begin{methoddesc}[CGIXMLRPCRequestHandler]{register_instance}{instance}
 Register an object which is used to expose method names 
 which have not been registered using \method{register_function()}. If 
 instance contains a \method{_dispatch()} method, it is called with the 
@@ -196,17 +203,17 @@
 back to the client. 
 \end{methoddesc}
 
-\begin{methoddesc}{register_introspection_functions}{}
+\begin{methoddesc}[CGIXMLRPCRequestHandler]{register_introspection_functions}{}
 Register the XML-RPC introspection functions 
 \code{system.listMethods}, \code{system.methodHelp} and 
 \code{system.methodSignature}.
 \end{methoddesc}
 
-\begin{methoddesc}{register_multicall_functions}{}
+\begin{methoddesc}[CGIXMLRPCRequestHandler]{register_multicall_functions}{}
 Register the XML-RPC multicall function \code{system.multicall}.
 \end{methoddesc}
 
-\begin{methoddesc}{handle_request}{\optional{request_text = None}}
+\begin{methoddesc}[CGIXMLRPCRequestHandler]{handle_request}{\optional{request_text = None}}
 Handle a XML-RPC request. If \var{request_text} is given, it 
 should be the POST data provided by the HTTP server, 
 otherwise the contents of stdin will be used.

Modified: python/branches/p3yk-noslice/Doc/lib/libsite.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsite.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsite.tex	Wed Jul 11 15:40:56 2007
@@ -28,12 +28,17 @@
 
 A path configuration file is a file whose name has the form
 \file{\var{package}.pth} and exists in one of the four directories
-mentioned above; its contents are additional items (one
-per line) to be added to \code{sys.path}.  Non-existing items are
-never added to \code{sys.path}, but no check is made that the item
-refers to a directory (rather than a file).  No item is added to
-\code{sys.path} more than once.  Blank lines and lines beginning with
-\code{\#} are skipped.  Lines starting with \code{import} are executed.
+mentioned above; its contents are additional items (one per line) to
+be added to \code{sys.path}.  Non-existing items are never added to
+\code{sys.path}, but no check is made that the item refers to a
+directory (rather than a file).  No item is added to \code{sys.path}
+more than once.  Blank lines and lines beginning with \code{\#} are
+skipped.  Lines starting with \code{import} (followed by space or tab)
+are executed.
+
+\versionchanged[A space or tab is now required after the import
+keyword]{2.6}
+
 \index{package}
 \indexiii{path}{configuration}{file}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex	Wed Jul 11 15:40:56 2007
@@ -15,23 +15,28 @@
 (\citetitle{SMTP Service Extensions}).
 
 \begin{classdesc}{SMTP}{\optional{host\optional{, port\optional{,
-                        local_hostname}}}}
+                        local_hostname\optional{, timeout}}}}}
 A \class{SMTP} instance encapsulates an SMTP connection.  It has
 methods that support a full repertoire of SMTP and ESMTP
 operations. If the optional host and port parameters are given, the
 SMTP \method{connect()} method is called with those parameters during
 initialization.  An \exception{SMTPConnectError} is raised if the
 specified host doesn't respond correctly.
+The optional \var{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).
 
 For normal use, you should only require the initialization/connect,
 \method{sendmail()}, and \method{quit()} methods.  An example is
 included below.
+
+\versionchanged[\var{timeout} was added]{2.6}
 \end{classdesc}
 
 \begin{classdesc}{SMTP_SSL}{\optional{host\optional{, port\optional{,
                         local_hostname\optional{,
                         keyfile\optional{,
-                        certfile}}}}}}
+                        certfile\optional{, timeout}}}}}}}
 A \class{SMTP_SSL} instance behaves exactly the same as instances of \class{SMTP}.
 \class{SMTP_SSL} should be used for situations where SSL is required from 
 the beginning of the connection and using \method{starttls()} is not appropriate.
@@ -39,6 +44,28 @@
 omitted, the standard SMTP-over-SSL port (465) is used. \var{keyfile} and \var{certfile}
 are also optional, and can contain a PEM formatted private key and
 certificate chain file for the SSL connection.
+The optional \var{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).
+
+\versionchanged[\var{timeout} was added]{2.6}
+\end{classdesc}
+
+\begin{classdesc}{LMTP}{\optional{host\optional{, port\optional{,
+                        local_hostname}}}}
+
+The LMTP protocol, which is very similar to ESMTP, is heavily based
+on the standard SMTP client. It's common to use Unix sockets for LMTP,
+so our connect() method must support that as well as a regular
+host:port server. To specify a Unix socket, you must use an absolute
+path for \var{host}, starting with a '/'.
+
+Authentication is supported, using the regular SMTP mechanism. When
+using a Unix socket, LMTP generally don't support or require any
+authentication, but your mileage might vary.
+
+\versionadded{2.6}
+
 \end{classdesc}
 
 A nice selection of exceptions is defined as well:
@@ -86,6 +113,10 @@
   The server refused our \samp{HELO} message.
 \end{excdesc}
 
+\begin{excdesc}{SMTPAuthenticationError}
+  SMTP authentication went wrong.  Most probably the server didn't accept
+  the username/password combination provided.
+\end{excdesc}
 
 \begin{seealso}
   \seerfc{821}{Simple Mail Transfer Protocol}{Protocol definition for
@@ -103,13 +134,13 @@
 
 An \class{SMTP} instance has the following methods:
 
-\begin{methoddesc}{set_debuglevel}{level}
+\begin{methoddesc}[SMTP]{set_debuglevel}{level}
 Set the debug output level.  A true value for \var{level} results in
 debug messages for connection and for all messages sent to and
 received from the server.
 \end{methoddesc}
 
-\begin{methoddesc}{connect}{\optional{host\optional{, port}}}
+\begin{methoddesc}[SMTP]{connect}{\optional{host\optional{, port}}}
 Connect to a host on a given port.  The defaults are to connect to the
 local host at the standard SMTP port (25).
 If the hostname ends with a colon (\character{:}) followed by a
@@ -119,7 +150,7 @@
 host is specified during instantiation.
 \end{methoddesc}
 
-\begin{methoddesc}{docmd}{cmd, \optional{, argstring}}
+\begin{methoddesc}[SMTP]{docmd}{cmd, \optional{, argstring}}
 Send a command \var{cmd} to the server.  The optional argument
 \var{argstring} is simply concatenated to the command, separated by a
 space.
@@ -136,7 +167,7 @@
 \exception{SMTPServerDisconnected} will be raised.
 \end{methoddesc}
 
-\begin{methoddesc}{helo}{\optional{hostname}}
+\begin{methoddesc}[SMTP]{helo}{\optional{hostname}}
 Identify yourself to the SMTP server using \samp{HELO}.  The hostname
 argument defaults to the fully qualified domain name of the local
 host.
@@ -146,7 +177,7 @@
 when necessary.
 \end{methoddesc}
 
-\begin{methoddesc}{ehlo}{\optional{hostname}}
+\begin{methoddesc}[SMTP]{ehlo}{\optional{hostname}}
 Identify yourself to an ESMTP server using \samp{EHLO}.  The hostname
 argument defaults to the fully qualified domain name of the local
 host.  Examine the response for ESMTP option and store them for use by
@@ -157,13 +188,13 @@
 will be implicitly called by \method{sendmail()} when necessary.
 \end{methoddesc}
 
-\begin{methoddesc}{has_extn}{name}
+\begin{methoddesc}[SMTP]{has_extn}{name}
 Return \constant{True} if \var{name} is in the set of SMTP service
 extensions returned by the server, \constant{False} otherwise.
 Case is ignored.
 \end{methoddesc}
 
-\begin{methoddesc}{verify}{address}
+\begin{methoddesc}[SMTP]{verify}{address}
 Check the validity of an address on this server using SMTP \samp{VRFY}.
 Returns a tuple consisting of code 250 and a full \rfc{822} address
 (including human name) if the user address is valid. Otherwise returns
@@ -172,7 +203,7 @@
 \note{Many sites disable SMTP \samp{VRFY} in order to foil spammers.}
 \end{methoddesc}
 
-\begin{methoddesc}{login}{user, password}
+\begin{methoddesc}[SMTP]{login}{user, password}
 Log in on an SMTP server that requires authentication.
 The arguments are the username and the password to authenticate with.
 If there has been no previous \samp{EHLO} or \samp{HELO} command this
@@ -190,7 +221,7 @@
 \end{description}
 \end{methoddesc}
 
-\begin{methoddesc}{starttls}{\optional{keyfile\optional{, certfile}}}
+\begin{methoddesc}[SMTP]{starttls}{\optional{keyfile\optional{, certfile}}}
 Put the SMTP connection in TLS (Transport Layer Security) mode.  All
 SMTP commands that follow will be encrypted.  You should then call
 \method{ehlo()} again.
@@ -199,8 +230,8 @@
 the \refmodule{socket} module's \function{ssl()} function.
 \end{methoddesc}
 
-\begin{methoddesc}{sendmail}{from_addr, to_addrs, msg\optional{,
-                             mail_options, rcpt_options}}
+\begin{methoddesc}[SMTP]{sendmail}{from_addr, to_addrs, msg\optional{,
+                                   mail_options, rcpt_options}}
 Send mail.  The required arguments are an \rfc{822} from-address
 string, a list of \rfc{822} to-address strings (a bare string will be
 treated as a list with 1 address), and a message string.  The caller
@@ -256,7 +287,7 @@
 
 \end{methoddesc}
 
-\begin{methoddesc}{quit}{}
+\begin{methoddesc}[SMTP]{quit}{}
 Terminate the SMTP session and close the connection.
 \end{methoddesc}
 

Modified: python/branches/p3yk-noslice/Doc/lib/libsocket.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsocket.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsocket.tex	Wed Jul 11 15:40:56 2007
@@ -14,7 +14,7 @@
 papers: \citetitle{An Introductory 4.3BSD Interprocess Communication
 Tutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSD
 Interprocess Communication Tutorial}, by Samuel J.  Leffler et al,
-both in the \citetitle{\UNIX{} Programmer's Manual, Supplementary Documents 1}
+both in the \citetitle{UNIX Programmer's Manual, Supplementary Documents 1}
 (sections PS1:7 and PS1:8).  The platform-specific reference material
 for the various socket-related system calls are also a valuable source
 of information on the details of socket semantics.  For \UNIX, refer
@@ -170,6 +170,16 @@
 \versionadded{2.3}
 \end{datadesc}
 
+\begin{funcdesc}{create_connection}{address\optional{, timeout}}
+Connects to the \var{address} received (as usual, a \code{(host, port)}
+pair), with an optional timeout for the connection.  Specially useful for
+higher-level protocols, it is not normally used directly from
+application-level code.  Passing the optional \var{timeout} parameter
+will set the timeout on the socket instance (if it is not given or
+\code{None}, the global default timeout setting is used).
+\versionadded{2.6}
+\end{funcdesc}
+
 \begin{funcdesc}{getaddrinfo}{host, port\optional{, family\optional{,
                               socktype\optional{, proto\optional{,
                               flags}}}}}
@@ -548,7 +558,7 @@
 The file object references a \cfunction{dup()}ped version of the
 socket file descriptor, so the file object and socket object may be
 closed or garbage-collected independently.
-The socket must be in blocking mode.
+The socket must be in blocking mode (it can not have a timeout).
 \index{I/O control!buffering}The optional \var{mode}
 and \var{bufsize} arguments are interpreted the same way as by the
 built-in \function{file()} function; see ``Built-in Functions''
@@ -584,6 +594,7 @@
 \manpage{recv}{2} for the meaning of the optional argument
 \var{flags}; it defaults to zero.  (The format of \var{address}
 depends on the address family --- see above.)
+\versionadded{2.5}
 \end{methoddesc}
 
 \begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}}
@@ -593,6 +604,7 @@
 receive up to the size available in the given buffer.
 See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the
 optional argument \var{flags}; it defaults to zero.
+\versionadded{2.5}
 \end{methoddesc}
 
 \begin{methoddesc}[socket]{send}{string\optional{, flags}}
@@ -722,23 +734,23 @@
 
 SSL objects have the following methods.
 
-\begin{methoddesc}{write}{s}
+\begin{methoddesc}[SSL]{write}{s}
 Writes the string \var{s} to the on the object's SSL connection.
 The return value is the number of bytes written.
 \end{methoddesc}
 
-\begin{methoddesc}{read}{\optional{n}}
+\begin{methoddesc}[SSL]{read}{\optional{n}}
 If \var{n} is provided, read \var{n} bytes from the SSL connection, otherwise
 read until EOF. The return value is a string of the bytes read.
 \end{methoddesc}
 
-\begin{methoddesc}{server}{}
+\begin{methoddesc}[SSL]{server}{}
 Returns a string describing the server's certificate.
 Useful for debugging purposes; do not parse the content of this string
 because its format can't be parsed unambiguously.
 \end{methoddesc}
 
-\begin{methoddesc}{issuer}{}
+\begin{methoddesc}[SSL]{issuer}{}
 Returns a string describing the issuer of the server's certificate.
 Useful for debugging purposes; do not parse the content of this string
 because its format can't be parsed unambiguously.

Modified: python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsqlite3.tex	Wed Jul 11 15:40:56 2007
@@ -42,6 +42,12 @@
 # Insert a row of data
 c.execute("""insert into stocks
           values ('2006-01-05','BUY','RHAT',100,35.14)""")
+
+# Save (commit) the changes
+conn.commit()
+
+# We can also close the cursor if we are done with it
+c.close()
 \end{verbatim}    
 
 Usually your SQL operations will need to use values from Python
@@ -210,37 +216,37 @@
 A \class{Connection} instance has the following attributes and methods:
 
 \label{sqlite3-Connection-IsolationLevel}
-\begin{memberdesc}{isolation_level}
+\begin{memberdesc}[Connection]{isolation_level}
   Get or set the current isolation level. None for autocommit mode or one of
   "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See ``Controlling Transactions'', 
   section~\ref{sqlite3-Controlling-Transactions}, for a more detailed explanation.
 \end{memberdesc}
 
-\begin{methoddesc}{cursor}{\optional{cursorClass}}
+\begin{methoddesc}[Connection]{cursor}{\optional{cursorClass}}
   The cursor method accepts a single optional parameter \var{cursorClass}.
   If supplied, this must be a custom cursor class that extends 
   \class{sqlite3.Cursor}.
 \end{methoddesc}
 
-\begin{methoddesc}{execute}{sql, \optional{parameters}}
+\begin{methoddesc}[Connection]{execute}{sql, \optional{parameters}}
 This is a nonstandard shortcut that creates an intermediate cursor object by
 calling the cursor method, then calls the cursor's \method{execute} method with the
 parameters given.
 \end{methoddesc}
 
-\begin{methoddesc}{executemany}{sql, \optional{parameters}}
+\begin{methoddesc}[Connection]{executemany}{sql, \optional{parameters}}
 This is a nonstandard shortcut that creates an intermediate cursor object by
 calling the cursor method, then calls the cursor's \method{executemany} method with the
 parameters given.
 \end{methoddesc}
 
-\begin{methoddesc}{executescript}{sql_script}
+\begin{methoddesc}[Connection]{executescript}{sql_script}
 This is a nonstandard shortcut that creates an intermediate cursor object by
 calling the cursor method, then calls the cursor's \method{executescript} method with the
 parameters given.
 \end{methoddesc}
 
-\begin{methoddesc}{create_function}{name, num_params, func}
+\begin{methoddesc}[Connection]{create_function}{name, num_params, func}
 
 Creates a user-defined function that you can later use from within SQL
 statements under the function name \var{name}. \var{num_params} is the number
@@ -255,7 +261,7 @@
   \verbatiminput{sqlite3/md5func.py}
 \end{methoddesc}
 
-\begin{methoddesc}{create_aggregate}{name, num_params, aggregate_class}
+\begin{methoddesc}[Connection]{create_aggregate}{name, num_params, aggregate_class}
 
 Creates a user-defined aggregate function.
 
@@ -271,7 +277,7 @@
   \verbatiminput{sqlite3/mysumaggr.py}
 \end{methoddesc}
 
-\begin{methoddesc}{create_collation}{name, callable}
+\begin{methoddesc}[Connection]{create_collation}{name, callable}
 
 Creates a collation with the specified \var{name} and \var{callable}. The
 callable will be passed two string arguments. It should return -1 if the first
@@ -293,14 +299,14 @@
 \end{verbatim}
 \end{methoddesc}
 
-\begin{methoddesc}{interrupt}{}
+\begin{methoddesc}[Connection]{interrupt}{}
 
 You can call this method from a different thread to abort any queries that
 might be executing on the connection. The query will then abort and the caller
 will get an exception.
 \end{methoddesc}
 
-\begin{methoddesc}{set_authorizer}{authorizer_callback}
+\begin{methoddesc}[Connection]{set_authorizer}{authorizer_callback}
 
 This routine registers a callback. The callback is invoked for each attempt to
 access a column of a table in the database. The callback should return
@@ -322,7 +328,7 @@
 module.
 \end{methoddesc}
 
-\begin{memberdesc}{row_factory}
+\begin{memberdesc}[Connection]{row_factory}
   You can change this attribute to a callable that accepts the cursor and
   the original row as a tuple and will return the real result row.  This
   way, you can implement more advanced ways of returning results, such 
@@ -341,7 +347,7 @@
   % XXX what's a db_row-based solution?
 \end{memberdesc}
 
-\begin{memberdesc}{text_factory}
+\begin{memberdesc}[Connection]{text_factory}
   Using this attribute you can control what objects are returned for the
   TEXT data type. By default, this attribute is set to \class{unicode} and
   the \module{sqlite3} module will return Unicode objects for TEXT. If you want to return
@@ -359,7 +365,7 @@
   \verbatiminput{sqlite3/text_factory.py}
 \end{memberdesc}
 
-\begin{memberdesc}{total_changes}
+\begin{memberdesc}[Connection]{total_changes}
   Returns the total number of database rows that have been modified, inserted,
   or deleted since the database connection was opened.
 \end{memberdesc}
@@ -372,7 +378,7 @@
 
 A \class{Cursor} instance has the following attributes and methods:
 
-\begin{methoddesc}{execute}{sql, \optional{parameters}}
+\begin{methoddesc}[Cursor]{execute}{sql, \optional{parameters}}
 
 Executes a SQL statement. The SQL statement may be parametrized (i. e.
 placeholders instead of SQL literals). The \module{sqlite3} module supports two kinds of
@@ -394,7 +400,7 @@
 \end{methoddesc}
 
 
-\begin{methoddesc}{executemany}{sql, seq_of_parameters}
+\begin{methoddesc}[Cursor]{executemany}{sql, seq_of_parameters}
 Executes a SQL command against all parameter sequences or mappings found in the
 sequence \var{sql}. The \module{sqlite3} module also allows
 using an iterator yielding parameters instead of a sequence.
@@ -406,7 +412,7 @@
 \verbatiminput{sqlite3/executemany_2.py}
 \end{methoddesc}
 
-\begin{methoddesc}{executescript}{sql_script}
+\begin{methoddesc}[Cursor]{executescript}{sql_script}
 
 This is a nonstandard convenience method for executing multiple SQL statements
 at once. It issues a COMMIT statement first, then executes the SQL script it
@@ -419,7 +425,7 @@
 \verbatiminput{sqlite3/executescript.py}
 \end{methoddesc}
 
-\begin{memberdesc}{rowcount}
+\begin{memberdesc}[Cursor]{rowcount}
   Although the \class{Cursor} class of the \module{sqlite3} module implements this
   attribute, the database engine's own support for the determination of "rows
   affected"/"rows selected" is quirky.

Modified: python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex	Wed Jul 11 15:40:56 2007
@@ -388,27 +388,26 @@
 specialized forms.  The specific types are not important beyond their
 implementation of the iterator protocol.
 
-The intention of the protocol is that once an iterator's
-\method{next()} method raises \exception{StopIteration}, it will
-continue to do so on subsequent calls.  Implementations that
-do not obey this property are deemed broken.  (This constraint
-was added in Python 2.3; in Python 2.2, various iterators are
-broken according to this rule.)
-
-Python's generators provide a convenient way to implement the
-iterator protocol.  If a container object's \method{__iter__()}
-method is implemented as a generator, it will automatically
-return an iterator object (technically, a generator object)
-supplying the \method{__iter__()} and \method{next()} methods.
+The intention of the protocol is that once an iterator's \method{__next__()}
+method raises \exception{StopIteration}, it will continue to do so on subsequent
+calls.  Implementations that do not obey this property are deemed broken.  (This
+constraint was added in Python 2.3; in Python 2.2, various iterators are broken
+according to this rule.)
+
+Python's generators provide a convenient way to implement the iterator protocol.
+If a container object's \method{__iter__()} method is implemented as a
+generator, it will automatically return an iterator object (technically, a
+generator object) supplying the \method{__iter__()} and \method{__next__()}
+methods.
 
 
 \section{Sequence Types ---
 	    \class{str}, \class{unicode}, \class{list},
-	    \class{tuple}, \class{buffer}, \class{xrange}
+	    \class{tuple}, \class{buffer}, \class{range}
 	    \label{typesseq}}
 
 There are six sequence types: strings, Unicode strings, lists,
-tuples, buffers, and xrange objects.
+tuples, buffers, and range objects.
 
 String literals are written in single or double quotes:
 \code{'xyzzy'}, \code{"frobozz"}.  See chapter 2 of the
@@ -434,11 +433,11 @@
 \obindex{buffer}
 
 Xrange objects are similar to buffers in that there is no specific
-syntax to create them, but they are created using the \function{xrange()}
-function.\bifuncindex{xrange}  They don't support slicing,
+syntax to create them, but they are created using the \function{range()}
+function.\bifuncindex{range}  They don't support slicing,
 concatenation or repetition, and using \code{in}, \code{not in},
 \function{min()} or \function{max()} on them is inefficient.
-\obindex{xrange}
+\obindex{range}
 
 Most sequence types support the following operations.  The \samp{in} and
 \samp{not in} operations have the same priorities as the comparison
@@ -560,25 +559,25 @@
 These are the string methods which both 8-bit strings and Unicode
 objects support:
 
-\begin{methoddesc}[string]{capitalize}{}
+\begin{methoddesc}[str]{capitalize}{}
 Return a copy of the string with only its first character capitalized.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{center}{width\optional{, fillchar}}
+\begin{methoddesc}[str]{center}{width\optional{, fillchar}}
 Return centered in a string of length \var{width}. Padding is done
 using the specified \var{fillchar} (default is a space).
 \versionchanged[Support for the \var{fillchar} argument]{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{count}{sub\optional{, start\optional{, end}}}
+\begin{methoddesc}[str]{count}{sub\optional{, start\optional{, end}}}
 Return the number of occurrences of substring \var{sub} in string
 S\code{[\var{start}:\var{end}]}.  Optional arguments \var{start} and
 \var{end} are interpreted as in slice notation.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{decode}{\optional{encoding\optional{, errors}}}
+\begin{methoddesc}[str]{decode}{\optional{encoding\optional{, errors}}}
 Decodes the string using the codec registered for \var{encoding}.
 \var{encoding} defaults to the default string encoding.  \var{errors}
 may be given to set a different error handling scheme.  The default is
@@ -590,7 +589,7 @@
 \versionchanged[Support for other error handling schemes added]{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{encode}{\optional{encoding\optional{,errors}}}
+\begin{methoddesc}[str]{encode}{\optional{encoding\optional{,errors}}}
 Return an encoded version of the string.  Default encoding is the current
 default string encoding.  \var{errors} may be given to set a different
 error handling scheme.  The default for \var{errors} is
@@ -605,7 +604,7 @@
 \code{'backslashreplace'} and other error handling schemes added]{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{endswith}{suffix\optional{, start\optional{, end}}}
+\begin{methoddesc}[str]{endswith}{suffix\optional{, start\optional{, end}}}
 Return \code{True} if the string ends with the specified \var{suffix},
 otherwise return \code{False}.  \var{suffix} can also be a tuple of
 suffixes to look for.  With optional \var{start}, test beginning at
@@ -614,13 +613,13 @@
 \versionchanged[Accept tuples as \var{suffix}]{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{expandtabs}{\optional{tabsize}}
+\begin{methoddesc}[str]{expandtabs}{\optional{tabsize}}
 Return a copy of the string where all tab characters are expanded
 using spaces.  If \var{tabsize} is not given, a tab size of \code{8}
 characters is assumed.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{find}{sub\optional{, start\optional{, end}}}
+\begin{methoddesc}[str]{find}{sub\optional{, start\optional{, end}}}
 Return the lowest index in the string where substring \var{sub} is
 found, such that \var{sub} is contained in the range [\var{start},
 \var{end}].  Optional arguments \var{start} and \var{end} are
@@ -628,47 +627,47 @@
 not found.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{index}{sub\optional{, start\optional{, end}}}
+\begin{methoddesc}[str]{index}{sub\optional{, start\optional{, end}}}
 Like \method{find()}, but raise \exception{ValueError} when the
 substring is not found.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{isalnum}{}
+\begin{methoddesc}[str]{isalnum}{}
 Return true if all characters in the string are alphanumeric and there
 is at least one character, false otherwise.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{isalpha}{}
+\begin{methoddesc}[str]{isalpha}{}
 Return true if all characters in the string are alphabetic and there
 is at least one character, false otherwise.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{isdigit}{}
+\begin{methoddesc}[str]{isdigit}{}
 Return true if all characters in the string are digits and there
 is at least one character, false otherwise.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{islower}{}
+\begin{methoddesc}[str]{islower}{}
 Return true if all cased characters in the string are lowercase and
 there is at least one cased character, false otherwise.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{isspace}{}
+\begin{methoddesc}[str]{isspace}{}
 Return true if there are only whitespace characters in the string and
 there is at least one character, false otherwise.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{istitle}{}
+\begin{methoddesc}[str]{istitle}{}
 Return true if the string is a titlecased string and there is at least one
 character, for example uppercase characters may only follow uncased
 characters and lowercase characters only cased ones.  Return false
@@ -677,20 +676,20 @@
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{isupper}{}
+\begin{methoddesc}[str]{isupper}{}
 Return true if all cased characters in the string are uppercase and
 there is at least one cased character, false otherwise.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{join}{seq}
+\begin{methoddesc}[str]{join}{seq}
 Return a string which is the concatenation of the strings in the
 sequence \var{seq}.  The separator between elements is the string
 providing this method.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{ljust}{width\optional{, fillchar}}
+\begin{methoddesc}[str]{ljust}{width\optional{, fillchar}}
 Return the string left justified in a string of length \var{width}.
 Padding is done using the specified \var{fillchar} (default is a
 space).  The original string is returned if
@@ -698,13 +697,13 @@
 \versionchanged[Support for the \var{fillchar} argument]{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{lower}{}
+\begin{methoddesc}[str]{lower}{}
 Return a copy of the string converted to lowercase.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{lstrip}{\optional{chars}}
+\begin{methoddesc}[str]{lstrip}{\optional{chars}}
 Return a copy of the string with leading characters removed.  The
 \var{chars} argument is a string specifying the set of characters
 to be removed.  If omitted or \code{None}, the \var{chars} argument
@@ -719,7 +718,7 @@
 \versionchanged[Support for the \var{chars} argument]{2.2.2}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{partition}{sep}
+\begin{methoddesc}[str]{partition}{sep}
 Split the string at the first occurrence of \var{sep}, and return
 a 3-tuple containing the part before the separator, the separator
 itself, and the part after the separator.  If the separator is not
@@ -728,26 +727,26 @@
 \versionadded{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{replace}{old, new\optional{, count}}
+\begin{methoddesc}[str]{replace}{old, new\optional{, count}}
 Return a copy of the string with all occurrences of substring
 \var{old} replaced by \var{new}.  If the optional argument
 \var{count} is given, only the first \var{count} occurrences are
 replaced.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{rfind}{sub \optional{,start \optional{,end}}}
+\begin{methoddesc}[str]{rfind}{sub \optional{,start \optional{,end}}}
 Return the highest index in the string where substring \var{sub} is
 found, such that \var{sub} is contained within s[start,end].  Optional
 arguments \var{start} and \var{end} are interpreted as in slice
 notation.  Return \code{-1} on failure.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{rindex}{sub\optional{, start\optional{, end}}}
+\begin{methoddesc}[str]{rindex}{sub\optional{, start\optional{, end}}}
 Like \method{rfind()} but raises \exception{ValueError} when the
 substring \var{sub} is not found.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{rjust}{width\optional{, fillchar}}
+\begin{methoddesc}[str]{rjust}{width\optional{, fillchar}}
 Return the string right justified in a string of length \var{width}.
 Padding is done using the specified \var{fillchar} (default is a space).
 The original string is returned if
@@ -755,7 +754,7 @@
 \versionchanged[Support for the \var{fillchar} argument]{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{rpartition}{sep}
+\begin{methoddesc}[str]{rpartition}{sep}
 Split the string at the last occurrence of \var{sep}, and return
 a 3-tuple containing the part before the separator, the separator
 itself, and the part after the separator.  If the separator is not
@@ -764,7 +763,7 @@
 \versionadded{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{rsplit}{\optional{sep \optional{,maxsplit}}}
+\begin{methoddesc}[str]{rsplit}{\optional{sep \optional{,maxsplit}}}
 Return a list of the words in the string, using \var{sep} as the
 delimiter string.  If \var{maxsplit} is given, at most \var{maxsplit}
 splits are done, the \emph{rightmost} ones.  If \var{sep} is not specified
@@ -774,7 +773,7 @@
 \versionadded{2.4}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{rstrip}{\optional{chars}}
+\begin{methoddesc}[str]{rstrip}{\optional{chars}}
 Return a copy of the string with trailing characters removed.  The
 \var{chars} argument is a string specifying the set of characters
 to be removed.  If omitted or \code{None}, the \var{chars} argument
@@ -789,7 +788,7 @@
 \versionchanged[Support for the \var{chars} argument]{2.2.2}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{split}{\optional{sep \optional{,maxsplit}}}
+\begin{methoddesc}[str]{split}{\optional{sep \optional{,maxsplit}}}
 Return a list of the words in the string, using \var{sep} as the
 delimiter string.  If \var{maxsplit} is given, at most \var{maxsplit}
 splits are done. (thus, the list will have at most \code{\var{maxsplit}+1}
@@ -812,13 +811,13 @@
 returns an empty list.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{splitlines}{\optional{keepends}}
+\begin{methoddesc}[str]{splitlines}{\optional{keepends}}
 Return a list of the lines in the string, breaking at line
 boundaries.  Line breaks are not included in the resulting list unless
 \var{keepends} is given and true.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{startswith}{prefix\optional{,
+\begin{methoddesc}[str]{startswith}{prefix\optional{,
                                        start\optional{, end}}}
 Return \code{True} if string starts with the \var{prefix}, otherwise
 return \code{False}.  \var{prefix} can also be a tuple of
@@ -829,7 +828,7 @@
 \versionchanged[Accept tuples as \var{prefix}]{2.5}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{strip}{\optional{chars}}
+\begin{methoddesc}[str]{strip}{\optional{chars}}
 Return a copy of the string with the leading and trailing characters
 removed.  The \var{chars} argument is a string specifying the set of
 characters to be removed.  If omitted or \code{None}, the \var{chars}
@@ -844,21 +843,21 @@
 \versionchanged[Support for the \var{chars} argument]{2.2.2}
 \end{methoddesc}
 
-\begin{methoddesc}[string]{swapcase}{}
+\begin{methoddesc}[str]{swapcase}{}
 Return a copy of the string with uppercase characters converted to
 lowercase and vice versa.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{title}{}
+\begin{methoddesc}[str]{title}{}
 Return a titlecased version of the string: words start with uppercase
 characters, all remaining cased characters are lowercase.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{translate}{table\optional{, deletechars}}
+\begin{methoddesc}[str]{translate}{table\optional{, deletechars}}
 Return a copy of the string where all characters occurring in the
 optional argument \var{deletechars} are removed, and the remaining
 characters have been mapped through the given translation table, which
@@ -866,6 +865,13 @@
 
 You can use the \function{maketrans()} helper function in the
 \refmodule{string} module to create a translation table.
+For string objects, set the \var{table} argument to \code{None}
+for translations that only delete characters:
+\begin{verbatim}
+    >>> 'read this short text'.translate(None, 'aeiou')
+    'rd ths shrt txt'
+\end{verbatim}
+\versionadded[Support for a \code{None} \var{table} argument]{2.6}
 
 For Unicode objects, the \method{translate()} method does not
 accept the optional \var{deletechars} argument.  Instead, it
@@ -878,13 +884,13 @@
 \module{encodings.cp1251} for an example).      
 \end{methoddesc}
 
-\begin{methoddesc}[string]{upper}{}
+\begin{methoddesc}[str]{upper}{}
 Return a copy of the string converted to uppercase.
 
 For 8-bit strings, this method is locale-dependent.
 \end{methoddesc}
 
-\begin{methoddesc}[string]{zfill}{width}
+\begin{methoddesc}[str]{zfill}{width}
 Return the numeric string left filled with zeros in a string
 of length \var{width}. The original string is returned if
 \var{width} is less than \code{len(\var{s})}.
@@ -1063,11 +1069,11 @@
 \refmodule{re}.\refstmodindex{re}
 
 
-\subsection{XRange Type \label{typesseq-xrange}}
+\subsection{XRange Type \label{typesseq-range}}
 
-The \class{xrange}\obindex{xrange} type is an immutable sequence which
-is commonly used for looping.  The advantage of the \class{xrange}
-type is that an \class{xrange} object will always take the same amount
+The \class{range}\obindex{range} type is an immutable sequence which
+is commonly used for looping.  The advantage of the \class{range}
+type is that an \class{range} object will always take the same amount
 of memory, no matter the size of the range it represents.  There are
 no consistent performance advantages.
 
@@ -1467,7 +1473,7 @@
 
 \item[(5)] \function{setdefault()} is like \function{get()}, except
 that if \var{k} is missing, \var{x} is both returned and inserted into
-the dictionary as the value of \var{k}. \var{x} defaults to \var{None}.
+the dictionary as the value of \var{k}. \var{x} defaults to \code{None}.
 
 \item[(6)] \function{popitem()} is useful to destructively iterate
 over a dictionary, as often used in set algorithms.  If the dictionary
@@ -1587,20 +1593,21 @@
   with a real file, this method should \emph{not} be implemented.}
 \end{methoddesc}
 
-\begin{methoddesc}[file]{next}{}
+\begin{methoddesc}[file]{__next__}{}
 A file object is its own iterator, for example \code{iter(\var{f})} returns
 \var{f} (unless \var{f} is closed).  When a file is used as an
 iterator, typically in a \keyword{for} loop (for example,
-\code{for line in f: print line}), the \method{next()} method is
+\code{for line in f: print line}), the \method{__next__()} method is
 called repeatedly.  This method returns the next input line, or raises
-\exception{StopIteration} when \EOF{} is hit.  In order to make a
-\keyword{for} loop the most efficient way of looping over the lines of
-a file (a very common operation), the \method{next()} method uses a
-hidden read-ahead buffer.  As a consequence of using a read-ahead
-buffer, combining \method{next()} with other file methods (like
-\method{readline()}) does not work right.  However, using
-\method{seek()} to reposition the file to an absolute position will
-flush the read-ahead buffer.
+\exception{StopIteration} when \EOF{} is hit when the file is open for
+reading (behavior is undefined when the file is open for writing).  In
+order to make a \keyword{for} loop the most efficient way of looping
+over the lines of a file (a very common operation), the
+\method{__next__()} method uses a hidden read-ahead buffer.  As a
+consequence of using a read-ahead buffer, combining \method{__next__()}
+with other file methods (like \method{readline()}) does not work
+right.  However, using \method{seek()} to reposition the file to an
+absolute position will flush the read-ahead buffer.
 \versionadded{2.3}
 \end{methoddesc}
 
@@ -1819,7 +1826,7 @@
   expection that occurred should be suppressed. If an exception
   occurred while executing the body of the \keyword{with} statement, the
   arguments contain the exception type, value and traceback information.
-  Otherwise, all three arguments are \var{None}.
+  Otherwise, all three arguments are \code{None}.
 
   Returning a true value from this method will cause the \keyword{with}
   statement to suppress the exception and continue execution with the
@@ -1964,10 +1971,10 @@
 They differ from function objects because they don't contain a
 reference to their global execution environment.  Code objects are
 returned by the built-in \function{compile()} function and can be
-extracted from function objects through their \member{func_code}
+extracted from function objects through their \member{__code__}
 attribute.
 \bifuncindex{compile}
-\withsubitem{(function object attribute)}{\ttindex{func_code}}
+\withsubitem{(function object attribute)}{\ttindex{__code__}}
 
 A code object can be executed or evaluated by passing it (instead of a
 source string) to the \function{exec()} or \function{eval()} 

Deleted: /python/branches/p3yk-noslice/Doc/lib/libstdwin.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libstdwin.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,832 +0,0 @@
-\chapter{Standard Windowing Interface}
-
-The modules in this chapter are available only on those systems where
-the STDWIN library is available.  STDWIN runs on \UNIX{} under X11 and
-on the Macintosh.  See CWI report CS-R8817.
-
-\warning{Using STDWIN is not recommended for new
-applications.  It has never been ported to Microsoft Windows or
-Windows NT, and for X11 or the Macintosh it lacks important
-functionality --- in particular, it has no tools for the construction
-of dialogs.  For most platforms, alternative, native solutions exist
-(though none are currently documented in this manual): Tkinter for
-\UNIX{} under X11, native Xt with Motif or Athena widgets for \UNIX{}
-under X11, Win32 for Windows and Windows NT, and a collection of
-native toolkit interfaces for the Macintosh.}
-
-
-\section{\module{stdwin} ---
-         Platform-independent Graphical User Interface System}
-
-\declaremodule{builtin}{stdwin}
-\modulesynopsis{Older graphical user interface system for X11 and Macintosh.}
-
-
-This module defines several new object types and functions that
-provide access to the functionality of STDWIN.
-
-On \UNIX{} running X11, it can only be used if the \envvar{DISPLAY}
-environment variable is set or an explicit
-\programopt{-display} \var{displayname} argument is passed to the
-Python interpreter.
-
-Functions have names that usually resemble their C STDWIN counterparts
-with the initial `w' dropped.  Points are represented by pairs of
-integers; rectangles by pairs of points.  For a complete description
-of STDWIN please refer to the documentation of STDWIN for C
-programmers (aforementioned CWI report).
-
-\subsection{Functions Defined in Module \module{stdwin}}
-\nodename{STDWIN Functions}
-
-The following functions are defined in the \module{stdwin} module:
-
-\begin{funcdesc}{open}{title}
-Open a new window whose initial title is given by the string argument.
-Return a window object; window object methods are described
-below.\footnote{
-	The Python version of STDWIN does not support draw procedures;
-	all drawing requests are reported as draw events.}
-\end{funcdesc}
-
-\begin{funcdesc}{getevent}{}
-Wait for and return the next event.
-An event is returned as a triple: the first element is the event
-type, a small integer; the second element is the window object to which
-the event applies, or
-\code{None}
-if it applies to no window in particular;
-the third element is type-dependent.
-Names for event types and command codes are defined in the standard
-module \refmodule{stdwinevents}.
-\end{funcdesc}
-
-\begin{funcdesc}{pollevent}{}
-Return the next event, if one is immediately available.
-If no event is available, return \code{()}.
-\end{funcdesc}
-
-\begin{funcdesc}{getactive}{}
-Return the window that is currently active, or \code{None} if no
-window is currently active.  (This can be emulated by monitoring
-WE_ACTIVATE and WE_DEACTIVATE events.)
-\end{funcdesc}
-
-\begin{funcdesc}{listfontnames}{pattern}
-Return the list of font names in the system that match the pattern (a
-string).  The pattern should normally be \code{'*'}; returns all
-available fonts.  If the underlying window system is X11, other
-patterns follow the standard X11 font selection syntax (as used e.g.
-in resource definitions), i.e. the wildcard character \code{'*'}
-matches any sequence of characters (including none) and \code{'?'}
-matches any single character.
-On the Macintosh this function currently returns an empty list.
-\end{funcdesc}
-
-\begin{funcdesc}{setdefscrollbars}{hflag, vflag}
-Set the flags controlling whether subsequently opened windows will
-have horizontal and/or vertical scroll bars.
-\end{funcdesc}
-
-\begin{funcdesc}{setdefwinpos}{h, v}
-Set the default window position for windows opened subsequently.
-\end{funcdesc}
-
-\begin{funcdesc}{setdefwinsize}{width, height}
-Set the default window size for windows opened subsequently.
-\end{funcdesc}
-
-\begin{funcdesc}{getdefscrollbars}{}
-Return the flags controlling whether subsequently opened windows will
-have horizontal and/or vertical scroll bars.
-\end{funcdesc}
-
-\begin{funcdesc}{getdefwinpos}{}
-Return the default window position for windows opened subsequently.
-\end{funcdesc}
-
-\begin{funcdesc}{getdefwinsize}{}
-Return the default window size for windows opened subsequently.
-\end{funcdesc}
-
-\begin{funcdesc}{getscrsize}{}
-Return the screen size in pixels.
-\end{funcdesc}
-
-\begin{funcdesc}{getscrmm}{}
-Return the screen size in millimetres.
-\end{funcdesc}
-
-\begin{funcdesc}{fetchcolor}{colorname}
-Return the pixel value corresponding to the given color name.
-Return the default foreground color for unknown color names.
-Hint: the following code tests whether you are on a machine that
-supports more than two colors:
-\begin{verbatim}
-if stdwin.fetchcolor('black') != \
-          stdwin.fetchcolor('red') != \
-          stdwin.fetchcolor('white'):
-    print 'color machine'
-else:
-    print 'monochrome machine'
-\end{verbatim}
-\end{funcdesc}
-
-\begin{funcdesc}{setfgcolor}{pixel}
-Set the default foreground color.
-This will become the default foreground color of windows opened
-subsequently, including dialogs.
-\end{funcdesc}
-
-\begin{funcdesc}{setbgcolor}{pixel}
-Set the default background color.
-This will become the default background color of windows opened
-subsequently, including dialogs.
-\end{funcdesc}
-
-\begin{funcdesc}{getfgcolor}{}
-Return the pixel value of the current default foreground color.
-\end{funcdesc}
-
-\begin{funcdesc}{getbgcolor}{}
-Return the pixel value of the current default background color.
-\end{funcdesc}
-
-\begin{funcdesc}{setfont}{fontname}
-Set the current default font.
-This will become the default font for windows opened subsequently,
-and is also used by the text measuring functions \function{textwidth()},
-\function{textbreak()}, \function{lineheight()} and
-\function{baseline()} below.  This accepts two more optional
-parameters, size and style:  Size is the font size (in `points').
-Style is a single character specifying the style, as follows:
-\code{'b'} = bold,
-\code{'i'} = italic,
-\code{'o'} = bold + italic,
-\code{'u'} = underline;
-default style is roman.
-Size and style are ignored under X11 but used on the Macintosh.
-(Sorry for all this complexity --- a more uniform interface is being designed.)
-\end{funcdesc}
-
-\begin{funcdesc}{menucreate}{title}
-Create a menu object referring to a global menu (a menu that appears in
-all windows).
-Methods of menu objects are described below.
-Note: normally, menus are created locally; see the window method
-\method{menucreate()} below.
-\warning{The menu only appears in a window as long as the object
-returned by this call exists.}
-\end{funcdesc}
-
-\begin{funcdesc}{newbitmap}{width, height}
-Create a new bitmap object of the given dimensions.
-Methods of bitmap objects are described below.
-Not available on the Macintosh.
-\end{funcdesc}
-
-\begin{funcdesc}{fleep}{}
-Cause a beep or bell (or perhaps a `visual bell' or flash, hence the
-name).
-\end{funcdesc}
-
-\begin{funcdesc}{message}{string}
-Display a dialog box containing the string.
-The user must click OK before the function returns.
-\end{funcdesc}
-
-\begin{funcdesc}{askync}{prompt, default}
-Display a dialog that prompts the user to answer a question with yes or
-no.  Return 0 for no, 1 for yes.  If the user hits the Return key, the
-default (which must be 0 or 1) is returned.  If the user cancels the
-dialog, \exception{KeyboardInterrupt} is raised.
-\end{funcdesc}
-
-\begin{funcdesc}{askstr}{prompt, default}
-Display a dialog that prompts the user for a string.
-If the user hits the Return key, the default string is returned.
-If the user cancels the dialog, \exception{KeyboardInterrupt} is
-raised.
-\end{funcdesc}
-
-\begin{funcdesc}{askfile}{prompt, default, new}
-Ask the user to specify a filename.  If \var{new} is zero it must be
-an existing file; otherwise, it must be a new file.  If the user
-cancels the dialog, \exception{KeyboardInterrupt} is raised.
-\end{funcdesc}
-
-\begin{funcdesc}{setcutbuffer}{i, string}
-Store the string in the system's cut buffer number \var{i}, where it
-can be found (for pasting) by other applications.  On X11, there are 8
-cut buffers (numbered 0..7).  Cut buffer number 0 is the `clipboard'
-on the Macintosh.
-\end{funcdesc}
-
-\begin{funcdesc}{getcutbuffer}{i}
-Return the contents of the system's cut buffer number \var{i}.
-\end{funcdesc}
-
-\begin{funcdesc}{rotatecutbuffers}{n}
-On X11, rotate the 8 cut buffers by \var{n}.  Ignored on the
-Macintosh.
-\end{funcdesc}
-
-\begin{funcdesc}{getselection}{i}
-Return X11 selection number \var{i.}  Selections are not cut buffers.
-Selection numbers are defined in module \refmodule{stdwinevents}.
-Selection \constant{WS_PRIMARY} is the \dfn{primary} selection (used
-by \program{xterm}, for instance); selection \constant{WS_SECONDARY}
-is the \dfn{secondary} selection; selection \constant{WS_CLIPBOARD} is
-the \dfn{clipboard} selection (used by \program{xclipboard}).  On the
-Macintosh, this always returns an empty string.
-\end{funcdesc}
-
-\begin{funcdesc}{resetselection}{i}
-Reset selection number \var{i}, if this process owns it.  (See window
-method \method{setselection()}).
-\end{funcdesc}
-
-\begin{funcdesc}{baseline}{}
-Return the baseline of the current font (defined by STDWIN as the
-vertical distance between the baseline and the top of the
-characters).
-\end{funcdesc}
-
-\begin{funcdesc}{lineheight}{}
-Return the total line height of the current font.
-\end{funcdesc}
-
-\begin{funcdesc}{textbreak}{str, width}
-Return the number of characters of the string that fit into a space of
-\var{width}
-bits wide when drawn in the current font.
-\end{funcdesc}
-
-\begin{funcdesc}{textwidth}{str}
-Return the width in bits of the string when drawn in the current font.
-\end{funcdesc}
-
-\begin{funcdesc}{connectionnumber}{}
-\funcline{fileno}{}
-(X11 under \UNIX{} only) Return the ``connection number'' used by the
-underlying X11 implementation.  (This is normally the file number of
-the socket.)  Both functions return the same value;
-\method{connectionnumber()} is named after the corresponding function in
-X11 and STDWIN, while \method{fileno()} makes it possible to use the
-\module{stdwin} module as a ``file'' object parameter to
-\function{select.select()}.  Note that if \constant{select()} implies that
-input is possible on \module{stdwin}, this does not guarantee that an
-event is ready --- it may be some internal communication going on
-between the X server and the client library.  Thus, you should call
-\function{stdwin.pollevent()} until it returns \code{None} to check for
-events if you don't want your program to block.  Because of internal
-buffering in X11, it is also possible that \function{stdwin.pollevent()}
-returns an event while \function{select()} does not find \module{stdwin} to
-be ready, so you should read any pending events with
-\function{stdwin.pollevent()} until it returns \code{None} before entering
-a blocking \function{select()} call.
-\withsubitem{(in module select)}{\ttindex{select()}}
-\end{funcdesc}
-
-\subsection{Window Objects}
-\nodename{STDWIN Window Objects}
-
-Window objects are created by \function{stdwin.open()}.  They are closed
-by their \method{close()} method or when they are garbage-collected.
-Window objects have the following methods:
-
-\begin{methoddesc}[window]{begindrawing}{}
-Return a drawing object, whose methods (described below) allow drawing
-in the window.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{change}{rect}
-Invalidate the given rectangle; this may cause a draw event.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{gettitle}{}
-Returns the window's title string.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{getdocsize}{}
-\begin{sloppypar}
-Return a pair of integers giving the size of the document as set by
-\method{setdocsize()}.
-\end{sloppypar}
-\end{methoddesc}
-
-\begin{methoddesc}[window]{getorigin}{}
-Return a pair of integers giving the origin of the window with respect
-to the document.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{gettitle}{}
-Return the window's title string.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{getwinsize}{}
-Return a pair of integers giving the size of the window.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{getwinpos}{}
-Return a pair of integers giving the position of the window's upper
-left corner (relative to the upper left corner of the screen).
-\end{methoddesc}
-
-\begin{methoddesc}[window]{menucreate}{title}
-Create a menu object referring to a local menu (a menu that appears
-only in this window).
-Methods of menu objects are described below.
-\warning{The menu only appears as long as the object
-returned by this call exists.}
-\end{methoddesc}
-
-\begin{methoddesc}[window]{scroll}{rect, point}
-Scroll the given rectangle by the vector given by the point.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setdocsize}{point}
-Set the size of the drawing document.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setorigin}{point}
-Move the origin of the window (its upper left corner)
-to the given point in the document.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setselection}{i, str}
-Attempt to set X11 selection number \var{i} to the string \var{str}.
-(See \module{stdwin} function \function{getselection()} for the
-meaning of \var{i}.)  Return true if it succeeds.
-If  succeeds, the window ``owns'' the selection until
-(a) another application takes ownership of the selection; or
-(b) the window is deleted; or
-(c) the application clears ownership by calling
-\function{stdwin.resetselection(\var{i})}.  When another application
-takes ownership of the selection, a \constant{WE_LOST_SEL} event is
-received for no particular window and with the selection number as
-detail.  Ignored on the Macintosh.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{settimer}{dsecs}
-Schedule a timer event for the window in \code{\var{dsecs}/10}
-seconds.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{settitle}{title}
-Set the window's title string.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setwincursor}{name}
-\begin{sloppypar}
-Set the window cursor to a cursor of the given name.  It raises
-\exception{RuntimeError} if no cursor of the given name exists.
-Suitable names include
-\code{'ibeam'},
-\code{'arrow'},
-\code{'cross'},
-\code{'watch'}
-and
-\code{'plus'}.
-On X11, there are many more (see \code{<X11/cursorfont.h>}).
-\end{sloppypar}
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setwinpos}{h, v}
-Set the position of the window's upper left corner (relative to
-the upper left corner of the screen).
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setwinsize}{width, height}
-Set the window's size.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{show}{rect}
-Try to ensure that the given rectangle of the document is visible in
-the window.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{textcreate}{rect}
-Create a text-edit object in the document at the given rectangle.
-Methods of text-edit objects are described below.
-\end{methoddesc}
-
-\begin{methoddesc}[window]{setactive}{}
-Attempt to make this window the active window.  If successful, this
-will generate a WE_ACTIVATE event (and a WE_DEACTIVATE event in case
-another window in this application became inactive).
-\end{methoddesc}
-
-\begin{methoddesc}[window]{close}{}
-Discard the window object.  It should not be used again.
-\end{methoddesc}
-
-\subsection{Drawing Objects}
-
-Drawing objects are created exclusively by the window method
-\method{begindrawing()}.  Only one drawing object can exist at any
-given time; the drawing object must be deleted to finish drawing.  No
-drawing object may exist when \function{stdwin.getevent()} is called.
-Drawing objects have the following methods:
-
-\begin{methoddesc}[drawing]{box}{rect}
-Draw a box just inside a rectangle.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{circle}{center, radius}
-Draw a circle with given center point and radius.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{elarc}{center, (rh, rv), (a1, a2)}
-Draw an elliptical arc with given center point.
-\code{(\var{rh}, \var{rv})}
-gives the half sizes of the horizontal and vertical radii.
-\code{(\var{a1}, \var{a2})}
-gives the angles (in degrees) of the begin and end points.
-0 degrees is at 3 o'clock, 90 degrees is at 12 o'clock.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{erase}{rect}
-Erase a rectangle.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{fillcircle}{center, radius}
-Draw a filled circle with given center point and radius.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{fillelarc}{center, (rh, rv), (a1, a2)}
-Draw a filled elliptical arc; arguments as for \method{elarc()}.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{fillpoly}{points}
-Draw a filled polygon given by a list (or tuple) of points.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{invert}{rect}
-Invert a rectangle.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{line}{p1, p2}
-Draw a line from point
-\var{p1}
-to
-\var{p2}.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{paint}{rect}
-Fill a rectangle.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{poly}{points}
-Draw the lines connecting the given list (or tuple) of points.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{shade}{rect, percent}
-Fill a rectangle with a shading pattern that is about
-\var{percent}
-percent filled.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{text}{p, str}
-Draw a string starting at point p (the point specifies the
-top left coordinate of the string).
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{xorcircle}{center, radius}
-\funcline{xorelarc}{center, (rh, rv), (a1, a2)}
-\funcline{xorline}{p1, p2}
-\funcline{xorpoly}{points}
-Draw a circle, an elliptical arc, a line or a polygon, respectively,
-in XOR mode.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{setfgcolor}{}
-\funcline{setbgcolor}{}
-\funcline{getfgcolor}{}
-\funcline{getbgcolor}{}
-These functions are similar to the corresponding functions described
-above for the \module{stdwin}
-module, but affect or return the colors currently used for drawing
-instead of the global default colors.
-When a drawing object is created, its colors are set to the window's
-default colors, which are in turn initialized from the global default
-colors when the window is created.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{setfont}{}
-\funcline{baseline}{}
-\funcline{lineheight}{}
-\funcline{textbreak}{}
-\funcline{textwidth}{}
-These functions are similar to the corresponding functions described
-above for the \module{stdwin}
-module, but affect or use the current drawing font instead of
-the global default font.
-When a drawing object is created, its font is set to the window's
-default font, which is in turn initialized from the global default
-font when the window is created.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{bitmap}{point, bitmap, mask}
-Draw the \var{bitmap} with its top left corner at \var{point}.
-If the optional \var{mask} argument is present, it should be either
-the same object as \var{bitmap}, to draw only those bits that are set
-in the bitmap, in the foreground color, or \code{None}, to draw all
-bits (ones are drawn in the foreground color, zeros in the background
-color).
-Not available on the Macintosh.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{cliprect}{rect}
-Set the ``clipping region'' to a rectangle.
-The clipping region limits the effect of all drawing operations, until
-it is changed again or until the drawing object is closed.  When a
-drawing object is created the clipping region is set to the entire
-window.  When an object to be drawn falls partly outside the clipping
-region, the set of pixels drawn is the intersection of the clipping
-region and the set of pixels that would be drawn by the same operation
-in the absence of a clipping region.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{noclip}{}
-Reset the clipping region to the entire window.
-\end{methoddesc}
-
-\begin{methoddesc}[drawing]{close}{}
-\funcline{enddrawing}{}
-Discard the drawing object.  It should not be used again.
-\end{methoddesc}
-
-\subsection{Menu Objects}
-
-A menu object represents a menu.
-The menu is destroyed when the menu object is deleted.
-The following methods are defined:
-
-
-\begin{methoddesc}[menu]{additem}{text, shortcut}
-Add a menu item with given text.
-The shortcut must be a string of length 1, or omitted (to specify no
-shortcut).
-\end{methoddesc}
-
-\begin{methoddesc}[menu]{setitem}{i, text}
-Set the text of item number \var{i}.
-\end{methoddesc}
-
-\begin{methoddesc}[menu]{enable}{i, flag}
-Enable or disables item \var{i}.
-\end{methoddesc}
-
-\begin{methoddesc}[menu]{check}{i, flag}
-Set or clear the \dfn{check mark} for item \var{i}.
-\end{methoddesc}
-
-\begin{methoddesc}[menu]{close}{}
-Discard the menu object.  It should not be used again.
-\end{methoddesc}
-
-\subsection{Bitmap Objects}
-
-A bitmap represents a rectangular array of bits.
-The top left bit has coordinate (0, 0).
-A bitmap can be drawn with the \method{bitmap()} method of a drawing object.
-Bitmaps are currently not available on the Macintosh.
-
-The following methods are defined:
-
-
-\begin{methoddesc}[bitmap]{getsize}{}
-Return a tuple representing the width and height of the bitmap.
-(This returns the values that have been passed to the
-\function{newbitmap()} function.)
-\end{methoddesc}
-
-\begin{methoddesc}[bitmap]{setbit}{point, bit}
-Set the value of the bit indicated by \var{point} to \var{bit}.
-\end{methoddesc}
-
-\begin{methoddesc}[bitmap]{getbit}{point}
-Return the value of the bit indicated by \var{point}.
-\end{methoddesc}
-
-\begin{methoddesc}[bitmap]{close}{}
-Discard the bitmap object.  It should not be used again.
-\end{methoddesc}
-
-\subsection{Text-edit Objects}
-
-A text-edit object represents a text-edit block.
-For semantics, see the STDWIN documentation for \C{} programmers.
-The following methods exist:
-
-
-\begin{methoddesc}[text-edit]{arrow}{code}
-Pass an arrow event to the text-edit block.
-The \var{code} must be one of \constant{WC_LEFT}, \constant{WC_RIGHT}, 
-\constant{WC_UP} or \constant{WC_DOWN} (see module
-\refmodule{stdwinevents}).
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{draw}{rect}
-Pass a draw event to the text-edit block.
-The rectangle specifies the redraw area.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{event}{type, window, detail}
-Pass an event gotten from
-\function{stdwin.getevent()}
-to the text-edit block.
-Return true if the event was handled.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{getfocus}{}
-Return 2 integers representing the start and end positions of the
-focus, usable as slice indices on the string returned by
-\method{gettext()}.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{getfocustext}{}
-Return the text in the focus.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{getrect}{}
-Return a rectangle giving the actual position of the text-edit block.
-(The bottom coordinate may differ from the initial position because
-the block automatically shrinks or grows to fit.)
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{gettext}{}
-Return the entire text buffer.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{move}{rect}
-Specify a new position for the text-edit block in the document.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{replace}{str}
-Replace the text in the focus by the given string.
-The new focus is an insert point at the end of the string.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{setfocus}{i, j}
-Specify the new focus.
-Out-of-bounds values are silently clipped.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{settext}{str}
-Replace the entire text buffer by the given string and set the focus
-to \code{(0, 0)}.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{setview}{rect}
-Set the view rectangle to \var{rect}.  If \var{rect} is \code{None},
-viewing mode is reset.  In viewing mode, all output from the text-edit
-object is clipped to the viewing rectangle.  This may be useful to
-implement your own scrolling text subwindow.
-\end{methoddesc}
-
-\begin{methoddesc}[text-edit]{close}{}
-Discard the text-edit object.  It should not be used again.
-\end{methoddesc}
-
-\subsection{Example}
-\nodename{STDWIN Example}
-
-Here is a minimal example of using STDWIN in Python.
-It creates a window and draws the string ``Hello world'' in the top
-left corner of the window.
-The window will be correctly redrawn when covered and re-exposed.
-The program quits when the close icon or menu item is requested.
-
-\begin{verbatim}
-import stdwin
-from stdwinevents import *
-
-def main():
-    mywin = stdwin.open('Hello')
-    #
-    while 1:
-        (type, win, detail) = stdwin.getevent()
-        if type == WE_DRAW:
-            draw = win.begindrawing()
-            draw.text((0, 0), 'Hello, world')
-            del draw
-        elif type == WE_CLOSE:
-            break
-
-main()
-\end{verbatim}
-
-
-\section{\module{stdwinevents} ---
-         Constants for use with \module{stdwin}}
-
-\declaremodule{standard}{stdwinevents}
-\modulesynopsis{Constant definitions for use with \module{stdwin}}
-
-
-This module defines constants used by STDWIN for event types
-(\constant{WE_ACTIVATE} etc.), command codes (\constant{WC_LEFT} etc.)
-and selection types (\constant{WS_PRIMARY} etc.).
-Read the file for details.
-Suggested usage is
-
-\begin{verbatim}
->>> from stdwinevents import *
->>> 
-\end{verbatim}
-
-
-\section{\module{rect} ---
-         Functions for use with \module{stdwin}}
-
-\declaremodule{standard}{rect}
-\modulesynopsis{Geometry-related utility function for use with
-                \module{stdwin}.}
-
-
-This module contains useful operations on rectangles.
-A rectangle is defined as in module \refmodule{stdwin}:
-a pair of points, where a point is a pair of integers.
-For example, the rectangle
-
-\begin{verbatim}
-(10, 20), (90, 80)
-\end{verbatim}
-
-is a rectangle whose left, top, right and bottom edges are 10, 20, 90
-and 80, respectively.  Note that the positive vertical axis points
-down (as in \refmodule{stdwin}).
-
-The module defines the following objects:
-
-\begin{excdesc}{error}
-The exception raised by functions in this module when they detect an
-error.  The exception argument is a string describing the problem in
-more detail.
-\end{excdesc}
-
-\begin{datadesc}{empty}
-The rectangle returned when some operations return an empty result.
-This makes it possible to quickly check whether a result is empty:
-
-\begin{verbatim}
->>> import rect
->>> r1 = (10, 20), (90, 80)
->>> r2 = (0, 0), (10, 20)
->>> r3 = rect.intersect([r1, r2])
->>> if r3 is rect.empty: print 'Empty intersection'
-Empty intersection
->>> 
-\end{verbatim}
-\end{datadesc}
-
-\begin{funcdesc}{is_empty}{r}
-Returns true if the given rectangle is empty.
-A rectangle
-\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}
-is empty if
-\begin{math}\var{left} \geq \var{right}\end{math} or
-\begin{math}\var{top} \geq \var{bottom}\end{math}.
-\end{funcdesc}
-
-\begin{funcdesc}{intersect}{list}
-Returns the intersection of all rectangles in the list argument.
-It may also be called with a tuple argument.  Raises
-\exception{rect.error} if the list is empty.  Returns
-\constant{rect.empty} if the intersection of the rectangles is empty.
-\end{funcdesc}
-
-\begin{funcdesc}{union}{list}
-Returns the smallest rectangle that contains all non-empty rectangles in
-the list argument.  It may also be called with a tuple argument or
-with two or more rectangles as arguments.  Returns
-\constant{rect.empty} if the list is empty or all its rectangles are
-empty.
-\end{funcdesc}
-
-\begin{funcdesc}{pointinrect}{point, rect}
-Returns true if the point is inside the rectangle.  By definition, a
-point \code{(\var{h}, \var{v})} is inside a rectangle
-\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})} if
-\begin{math}\var{left} \leq \var{h} < \var{right}\end{math} and
-\begin{math}\var{top} \leq \var{v} < \var{bottom}\end{math}.
-\end{funcdesc}
-
-\begin{funcdesc}{inset}{rect, (dh, dv)}
-Returns a rectangle that lies inside the \var{rect} argument by
-\var{dh} pixels horizontally and \var{dv} pixels vertically.  If
-\var{dh} or \var{dv} is negative, the result lies outside \var{rect}.
-\end{funcdesc}
-
-\begin{funcdesc}{rect2geom}{rect}
-Converts a rectangle to geometry representation:
-\code{(\var{left}, \var{top}), (\var{width}, \var{height})}.
-\end{funcdesc}
-
-\begin{funcdesc}{geom2rect}{geom}
-Converts a rectangle given in geometry representation back to the
-standard rectangle representation
-\code{(\var{left}, \var{top}), (\var{right}, \var{bottom})}.
-\end{funcdesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libstring.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libstring.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libstring.tex	Wed Jul 11 15:40:56 2007
@@ -419,7 +419,8 @@
   Delete all characters from \var{s} that are in \var{deletechars} (if 
   present), and then translate the characters using \var{table}, which 
   must be a 256-character string giving the translation for each
-  character value, indexed by its ordinal.
+  character value, indexed by its ordinal.  If \var{table} is \code{None},
+  then only the character deletion step is performed.
 \end{funcdesc}
 
 \begin{funcdesc}{upper}{s}

Modified: python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsubprocess.tex	Wed Jul 11 15:40:56 2007
@@ -15,8 +15,6 @@
 \begin{verbatim}
 os.system
 os.spawn*
-os.popen*
-popen2.*
 commands.*
 \end{verbatim}
 
@@ -89,7 +87,10 @@
 
 If \var{close_fds} is true, all file descriptors except \constant{0},
 \constant{1} and \constant{2} will be closed before the child process is
-executed. (\UNIX{} only)
+executed. (\UNIX{} only).  Or, on Windows, if \var{close_fds} is true
+then no handles will be inherited by the child process.  Note that on
+Windows, you cannot set \var{close_fds} to true and also redirect the
+standard handles by setting \var{stdin}, \var{stdout} or \var{stderr}.
 
 If \var{shell} is \constant{True}, the specified command will be
 executed through the shell.
@@ -176,16 +177,16 @@
 
 Instances of the \class{Popen} class have the following methods:
 
-\begin{methoddesc}{poll}{}
+\begin{methoddesc}[Popen]{poll}{}
 Check if child process has terminated.  Returns returncode
 attribute.
 \end{methoddesc}
 
-\begin{methoddesc}{wait}{}
+\begin{methoddesc}[Popen]{wait}{}
 Wait for child process to terminate.  Returns returncode attribute.
 \end{methoddesc}
 
-\begin{methoddesc}{communicate}{input=None}
+\begin{methoddesc}[Popen]{communicate}{input=None}
 Interact with process: Send data to stdin.  Read data from stdout and
 stderr, until end-of-file is reached.  Wait for process to terminate.
 The optional \var{input} argument should be a string to be sent to the
@@ -199,29 +200,29 @@
 
 The following attributes are also available:
 
-\begin{memberdesc}{stdin}
+\begin{memberdesc}[Popen]{stdin}
 If the \var{stdin} argument is \code{PIPE}, this attribute is a file
 object that provides input to the child process.  Otherwise, it is
 \code{None}.
 \end{memberdesc}
 
-\begin{memberdesc}{stdout}
+\begin{memberdesc}[Popen]{stdout}
 If the \var{stdout} argument is \code{PIPE}, this attribute is a file
 object that provides output from the child process.  Otherwise, it is
 \code{None}.
 \end{memberdesc}
 
-\begin{memberdesc}{stderr}
+\begin{memberdesc}[Popen]{stderr}
 If the \var{stderr} argument is \code{PIPE}, this attribute is file
 object that provides error output from the child process.  Otherwise,
 it is \code{None}.
 \end{memberdesc}
 
-\begin{memberdesc}{pid}
+\begin{memberdesc}[Popen]{pid}
 The process ID of the child process.
 \end{memberdesc}
 
-\begin{memberdesc}{returncode}
+\begin{memberdesc}[Popen]{returncode}
 The child return code.  A \code{None} value indicates that the process
 hasn't terminated yet.  A negative value -N indicates that the child
 was terminated by signal N (\UNIX{} only).
@@ -335,68 +336,3 @@
 ==>
 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
 \end{verbatim}
-
-\begin{verbatim}
-(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
-==>
-p = Popen(cmd, shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdin, child_stdout) = (p.stdin, p.stdout)
-\end{verbatim}
-
-\begin{verbatim}
-(child_stdin,
- child_stdout,
- child_stderr) = os.popen3(cmd, mode, bufsize)
-==>
-p = Popen(cmd, shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
-(child_stdin,
- child_stdout,
- child_stderr) = (p.stdin, p.stdout, p.stderr)
-\end{verbatim}
-
-\begin{verbatim}
-(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
-==>
-p = Popen(cmd, shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
-(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
-\end{verbatim}
-
-\subsubsection{Replacing popen2.*}
-
-\note{If the cmd argument to popen2 functions is a string, the command
-is executed through /bin/sh.  If it is a list, the command is directly
-executed.}
-
-\begin{verbatim}
-(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
-==>
-p = Popen(["somestring"], shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdout, child_stdin) = (p.stdout, p.stdin)
-\end{verbatim}
-
-\begin{verbatim}
-(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
-==>
-p = Popen(["mycmd", "myarg"], bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdout, child_stdin) = (p.stdout, p.stdin)
-\end{verbatim}
-
-The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
-except that:
-
-\begin{itemize}
-\item subprocess.Popen raises an exception if the execution fails
-
-\item the \var{capturestderr} argument is replaced with the \var{stderr}
-      argument.
-
-\item stdin=PIPE and stdout=PIPE must be specified.
-
-\item popen2 closes all file descriptors by default, but you have to
-      specify close_fds=True with subprocess.Popen.
-\end{itemize}

Modified: python/branches/p3yk-noslice/Doc/lib/libsun.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsun.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsun.tex	Wed Jul 11 15:40:56 2007
@@ -3,3 +3,5 @@
 
 The modules described in this chapter provide interfaces to features
 that are unique to SunOS 5 (also known as Solaris version 2).
+
+\localmoduletable

Modified: python/branches/p3yk-noslice/Doc/lib/libsys.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsys.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libsys.tex	Wed Jul 11 15:40:56 2007
@@ -15,8 +15,8 @@
   whether this is a full pathname or not).  If the command was
   executed using the \programopt{-c} command line option to the
   interpreter, \code{argv[0]} is set to the string \code{'-c'}.  If no
-  script name was passed to the Python interpreter, \code{argv} has
-  zero length.
+  script name was passed to the Python interpreter, \code{argv[0]} is
+  the empty string.
 \end{datadesc}
 
 \begin{datadesc}{byteorder}
@@ -132,11 +132,6 @@
   encapsulates the call stack at the point where the exception
   originally occurred.  \obindex{traceback}
 
-  If \function{exc_clear()} is called, this function will return three
-  \code{None} values until either another exception is raised in the
-  current thread or the execution stack returns to a frame where
-  another exception is being handled.
-
   \warning{Assigning the \var{traceback} return value to a
   local variable in a function that is handling an exception will
   cause a circular reference.  This will prevent anything referenced
@@ -153,32 +148,6 @@
   efficient to avoid creating cycles.}
 \end{funcdesc}
 
-\begin{funcdesc}{exc_clear}{}
-  This function clears all information relating to the current or last
-  exception that occurred in the current thread.  After calling this
-  function, \function{exc_info()} will return three \code{None} values until
-  another exception is raised in the current thread or the execution stack
-  returns to a frame where another exception is being handled.
-
-  This function is only needed in only a few obscure situations.  These
-  include logging and error handling systems that report information on the
-  last or current exception.  This function can also be used to try to free
-  resources and trigger object finalization, though no guarantee is made as
-  to what objects will be freed, if any.
-\versionadded{2.3}
-\end{funcdesc}
-
-\begin{datadesc}{exc_type}
-\dataline{exc_value}
-\dataline{exc_traceback}
-\deprecated {1.5}
-            {Use \function{exc_info()} instead.}
-  Since they are global variables, they are not specific to the
-  current thread, so their use is not safe in a multi-threaded
-  program.  When no exception is being handled, \code{exc_type} is set
-  to \code{None} and the other two are undefined.
-\end{datadesc}
-
 \begin{datadesc}{exec_prefix}
   A string giving the site-specific directory prefix where the
   platform-dependent Python files are installed; by default, this is
@@ -218,19 +187,6 @@
   program when an error occurs.
 \end{funcdesc}
 
-\begin{datadesc}{exitfunc}
-  This value is not actually defined by the module, but can be set by
-  the user (or by a program) to specify a clean-up action at program
-  exit.  When set, it should be a parameterless function.  This
-  function will be called when the interpreter exits.  Only one
-  function may be installed in this way; to allow multiple functions
-  which will be called at termination, use the \refmodule{atexit}
-  module.  \note{The exit function is not called when the program is
-  killed by a signal, when a Python fatal internal error is detected,
-  or when \code{os._exit()} is called.}
-  \deprecated{2.4}{Use \refmodule{atexit} instead.}
-\end{datadesc}
-
 \begin{funcdesc}{getcheckinterval}{}
   Return the interpreter's ``check interval'';
   see \function{setcheckinterval()}.
@@ -390,10 +346,7 @@
 \begin{datadesc}{modules}
   This is a dictionary that maps module names to modules which have
   already been loaded.  This can be manipulated to force reloading of
-  modules and other tricks.  Note that removing a module from this
-  dictionary is \emph{not} the same as calling
-  \function{reload()}\bifuncindex{reload} on the corresponding module
-  object.
+  modules and other tricks.
 \end{datadesc}
 
 \begin{datadesc}{path}

Modified: python/branches/p3yk-noslice/Doc/lib/libtarfile.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtarfile.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtarfile.tex	Wed Jul 11 15:40:56 2007
@@ -12,21 +12,24 @@
 
 \begin{itemize}
 \item reads and writes \module{gzip} and \module{bzip2} compressed archives.
-\item creates \POSIX{} 1003.1-1990 compliant or GNU tar compatible archives.
-\item reads GNU tar extensions \emph{longname}, \emph{longlink} and
-      \emph{sparse}.
-\item stores pathnames of unlimited length using GNU tar extensions.
+\item read/write support for the \POSIX{}.1-1988 (ustar) format.
+\item read/write support for the GNU tar format including \emph{longname} and
+      \emph{longlink} extensions, read-only support for the \emph{sparse}
+      extension.
+\item read/write support for the \POSIX{}.1-2001 (pax) format.
+      \versionadded{2.6}
 \item handles directories, regular files, hardlinks, symbolic links, fifos,
       character devices and block devices and is able to acquire and
       restore file information like timestamp, access permissions and owner.
 \item can handle tape devices.
 \end{itemize}
 
-\begin{funcdesc}{open}{\optional{name\optional{, mode
-                       \optional{, fileobj\optional{, bufsize}}}}}
+\begin{funcdesc}{open}{name\optional{, mode\optional{,
+        fileobj\optional{, bufsize}}}, **kwargs}
     Return a \class{TarFile} object for the pathname \var{name}.
-    For detailed information on \class{TarFile} objects,
-    see \citetitle{TarFile Objects} (section \ref{tarfile-objects}).
+    For detailed information on \class{TarFile} objects and the keyword
+    arguments that are allowed, see \citetitle{TarFile Objects}
+    (section \ref{tarfile-objects}).
 
     \var{mode} has to be a string of the form \code{'filemode[:compression]'},
     it defaults to \code{'r'}. Here is a full list of mode combinations:
@@ -130,6 +133,27 @@
     \versionadded{2.6}
 \end{excdesc}
 
+Each of the following constants defines a tar archive format that the
+\module{tarfile} module is able to create. See section \ref{tar-formats} for
+details.
+
+\begin{datadesc}{USTAR_FORMAT}
+    \POSIX{}.1-1988 (ustar) format.
+\end{datadesc}
+
+\begin{datadesc}{GNU_FORMAT}
+    GNU tar format.
+\end{datadesc}
+
+\begin{datadesc}{PAX_FORMAT}
+    \POSIX{}.1-2001 (pax) format.
+\end{datadesc}
+
+\begin{datadesc}{DEFAULT_FORMAT}
+    The default format for creating archives. This is currently
+    \constant{GNU_FORMAT}.
+\end{datadesc}
+
 \begin{seealso}
     \seemodule{zipfile}{Documentation of the \refmodule{zipfile}
     standard module.}
@@ -147,17 +171,26 @@
 
 The \class{TarFile} object provides an interface to a tar archive. A tar
 archive is a sequence of blocks. An archive member (a stored file) is made up
-of a header block followed by data blocks. It is possible, to store a file in a
+of a header block followed by data blocks. It is possible to store a file in a
 tar archive several times. Each archive member is represented by a
 \class{TarInfo} object, see \citetitle{TarInfo Objects} (section
 \ref{tarinfo-objects}) for details.
 
-\begin{classdesc}{TarFile}{\optional{name
-                           \optional{, mode\optional{, fileobj}}}}
-    Open an \emph{(uncompressed)} tar archive \var{name}.
+\begin{classdesc}{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}
+
+    All following arguments are optional and can be accessed as instance
+    attributes as well.
+
+    \var{name} is the pathname of the archive. It can be omitted if
+    \var{fileobj} is given. In this case, the file object's \member{name}
+    attribute is used if it exists.
+
     \var{mode} is either \code{'r'} to read from an existing archive,
     \code{'a'} to append data to an existing file or \code{'w'} to create a new
-    file overwriting an existing one. \var{mode} defaults to \code{'r'}.
+    file overwriting an existing one.
 
     If \var{fileobj} is given, it is used for reading or writing data.
     If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode.
@@ -165,6 +198,44 @@
     \begin{notice}
         \var{fileobj} is not closed, when \class{TarFile} is closed.
     \end{notice}
+
+    \var{format} controls the archive format. It must be one of the constants
+    \constant{USTAR_FORMAT}, \constant{GNU_FORMAT} or \constant{PAX_FORMAT}
+    that are defined at module level.
+    \versionadded{2.6}
+
+    The \var{tarinfo} argument can be used to replace the default
+    \class{TarInfo} class with a different one.
+    \versionadded{2.6}
+
+    If \var{dereference} is \code{False}, add symbolic and hard links to the
+    archive. If it is \code{True}, add the content of the target files to the
+    archive. This has no effect on systems that do not support symbolic links.
+
+    If \var{ignore_zeros} is \code{False}, treat an empty block as the end of
+    the archive. If it is \var{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.
+
+    \var{debug} can be set from \code{0} (no debug messages) up to \code{3}
+    (all debug messages). The messages are written to \code{sys.stderr}.
+
+    If \var{errorlevel} is \code{0}, all errors are ignored when using
+    \method{extract()}.  Nevertheless, they appear as error messages in the
+    debug output, when debugging is enabled.  If \code{1}, all \emph{fatal}
+    errors are raised as \exception{OSError} or \exception{IOError} exceptions.
+    If \code{2}, all \emph{non-fatal} errors are raised as \exception{TarError}
+    exceptions as well.
+
+    The \var{encoding} and \var{errors} arguments control the way strings are
+    converted to unicode objects and vice versa. The default settings will work
+    for most users. See section \ref{tar-unicode} for in-depth information.
+    \versionadded{2.6}
+
+    The \var{pax_headers} argument is an optional dictionary of unicode strings
+    which will be added as a pax global header if \var{format} is
+    \constant{PAX_FORMAT}.
+    \versionadded{2.6}
 \end{classdesc}
 
 \begin{methoddesc}{open}{...}
@@ -208,7 +279,7 @@
     Extract all members from the archive to the current working directory
     or directory \var{path}. If optional \var{members} is given, it must be
     a subset of the list returned by \method{getmembers()}.
-    Directory informations like owner, modification time and permissions are
+    Directory information like owner, modification time and permissions are
     set after all members have been extracted. This is done to work around two
     problems: A directory's modification time is reset each time a file is
     created in it. And, if a directory's permissions do not allow writing,
@@ -243,13 +314,17 @@
     \end{notice}
 \end{methoddesc}
 
-\begin{methoddesc}{add}{name\optional{, arcname\optional{, recursive}}}
+\begin{methoddesc}{add}{name\optional{, arcname\optional{, recursive\optional{, exclude}}}}
     Add the file \var{name} to the archive. \var{name} may be any type
     of file (directory, fifo, symbolic link, etc.).
     If given, \var{arcname} specifies an alternative name for the file in the
     archive. Directories are added recursively by default.
-    This can be avoided by setting \var{recursive} to \constant{False};
-    the default is \constant{True}.
+    This can be avoided by setting \var{recursive} to \constant{False}.
+    If \var{exclude} is given it must be a function that takes one filename
+    argument and returns a boolean value. Depending on this value the
+    respective file is either excluded (\constant{True}) or added
+    (\constant{False}).
+    \versionchanged[Added the \var{exclude} parameter]{2.6}
 \end{methoddesc}
 
 \begin{methoddesc}{addfile}{tarinfo\optional{, fileobj}}
@@ -279,43 +354,16 @@
 \end{methoddesc}
 
 \begin{memberdesc}{posix}
-    If true, create a \POSIX{} 1003.1-1990 compliant archive. GNU
-    extensions are not used, because they are not part of the \POSIX{}
-    standard.  This limits the length of filenames to at most 256,
-    link names to 100 characters and the maximum file size to 8
-    gigabytes. A \exception{ValueError} is raised if a file exceeds
-    this limit.  If false, create a GNU tar compatible archive.  It
-    will not be \POSIX{} compliant, but can store files without any
-    of the above restrictions. 
+    Setting this to \constant{True} is equivalent to setting the
+    \member{format} attribute to \constant{USTAR_FORMAT},
+    \constant{False} is equivalent to \constant{GNU_FORMAT}.
     \versionchanged[\var{posix} defaults to \constant{False}]{2.4}
+    \deprecated{2.6}{Use the \member{format} attribute instead.}
 \end{memberdesc}
 
-\begin{memberdesc}{dereference}
-    If false, add symbolic and hard links to archive. If true, add the
-    content of the target files to the archive.  This has no effect on
-    systems that do not support symbolic links.
-\end{memberdesc}
-
-\begin{memberdesc}{ignore_zeros}
-    If false, treat an empty block as the end of the archive. If true,
-    skip empty (and invalid) blocks and try to get as many members as
-    possible. This is only useful for concatenated or damaged
-    archives.
-\end{memberdesc}
-
-\begin{memberdesc}{debug=0}
-    To be set from \code{0} (no debug messages; the default) up to
-    \code{3} (all debug messages). The messages are written to
-    \code{sys.stderr}.
-\end{memberdesc}
-
-\begin{memberdesc}{errorlevel}
-    If \code{0} (the default), all errors are ignored when using
-    \method{extract()}.  Nevertheless, they appear as error messages
-    in the debug output, when debugging is enabled.  If \code{1}, all
-    \emph{fatal} errors are raised as \exception{OSError} or
-    \exception{IOError} exceptions.  If \code{2}, all \emph{non-fatal}
-    errors are raised as \exception{TarError} exceptions as well.
+\begin{memberdesc}{pax_headers}
+    A dictionary containing key-value pairs of pax global headers.
+    \versionadded{2.6}
 \end{memberdesc}
 
 %-----------------
@@ -337,18 +385,23 @@
     Create a \class{TarInfo} object.
 \end{classdesc}
 
-\begin{methoddesc}{frombuf}{}
-    Create and return a \class{TarInfo} object from a string buffer.
+\begin{methoddesc}{frombuf}{buf}
+    Create and return a \class{TarInfo} object from string buffer \var{buf}.
     \versionadded[Raises \exception{HeaderError} if the buffer is
     invalid.]{2.6}
 \end{methoddesc}
 
-\begin{methoddesc}{tobuf}{posix}
-    Create a string buffer from a \class{TarInfo} object.
-    See \class{TarFile}'s \member{posix} attribute for information
-    on the \var{posix} argument. It defaults to \constant{False}.
+\begin{methoddesc}{fromtarfile}{tarfile}
+    Read the next member from the \class{TarFile} object \var{tarfile} and
+    return it as a \class{TarInfo} object.
+    \versionadded{2.6}
+\end{methoddesc}
 
-    \versionadded[The \var{posix} parameter]{2.5}
+\begin{methoddesc}{tobuf}{\optional{format\optional{, encoding
+        \optional{, errors}}}}
+    Create a string buffer from a \class{TarInfo} object. For information
+    on the arguments see the constructor of the \class{TarFile} class.
+    \versionchanged[The arguments were added]{2.6}
 \end{methoddesc}
 
 A \code{TarInfo} object has the following public data attributes:
@@ -401,6 +454,12 @@
     Group name.
 \end{memberdesc}
 
+\begin{memberdesc}{pax_headers}
+    A dictionary containing key-value pairs of an associated pax
+    extended header.
+    \versionadded{2.6}
+\end{memberdesc}
+
 A \class{TarInfo} object also provides some convenient query methods:
 
 \begin{methoddesc}{isfile}{}
@@ -503,3 +562,103 @@
     tar.extract(tarinfo)
 tar.close()
 \end{verbatim}
+
+%------------
+% Tar format
+%------------
+
+\subsection{Supported tar formats \label{tar-formats}}
+
+There are three tar formats that can be created with the \module{tarfile}
+module:
+
+\begin{itemize}
+
+\item
+The \POSIX{}.1-1988 ustar format (\constant{USTAR_FORMAT}). It supports
+filenames up to a length of at best 256 characters and linknames up to 100
+characters. The maximum file size is 8 gigabytes. This is an old and limited
+but widely supported format.
+
+\item
+The GNU tar format (\constant{GNU_FORMAT}). It supports long filenames and
+linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
+standard on GNU/Linux systems. \module{tarfile} fully supports the GNU tar
+extensions for long names, sparse file support is read-only.
+
+\item
+The \POSIX{}.1-2001 pax format (\constant{PAX_FORMAT}). It is the most
+flexible format with virtually no limits. It supports long filenames and
+linknames, large files and stores pathnames in a portable way. However, not
+all tar implementations today are able to handle pax archives properly.
+
+The \emph{pax} format is an extension to the existing \emph{ustar} format. It
+uses extra headers for information that cannot be stored otherwise. There are
+two flavours of pax headers: Extended headers only affect the subsequent file
+header, global headers are valid for the complete archive and affect all
+following files. All the data in a pax header is encoded in \emph{UTF-8} for
+portability reasons.
+
+\end{itemize}
+
+There are some more variants of the tar format which can be read, but not
+created:
+
+\begin{itemize}
+
+\item
+The ancient V7 format. This is the first tar format from \UNIX{} Seventh
+Edition, storing only regular files and directories. Names must not be longer
+than 100 characters, there is no user/group name information. Some archives
+have miscalculated header checksums in case of fields with non-\ASCII{}
+characters.
+
+\item
+The SunOS tar extended format. This format is a variant of the \POSIX{}.1-2001
+pax format, but is not compatible.
+
+\end{itemize}
+
+%----------------
+% Unicode issues
+%----------------
+
+\subsection{Unicode issues \label{tar-unicode}}
+
+The tar format was originally conceived to make backups on tape drives with the
+main focus on preserving file system information. Nowadays tar archives are
+commonly used for file distribution and exchanging archives over networks. One
+problem of the original format (that all other formats are merely variants of)
+is that there is no concept of supporting different character encodings.
+For example, an ordinary tar archive created on a \emph{UTF-8} system cannot be
+read correctly on a \emph{Latin-1} system if it contains non-\ASCII{}
+characters. Names (i.e. filenames, linknames, user/group names) containing
+these characters will appear damaged.  Unfortunately, there is no way to
+autodetect the encoding of an archive.
+
+The pax format was designed to solve this problem. It stores non-\ASCII{} names
+using the universal character encoding \emph{UTF-8}. When a pax archive is
+read, these \emph{UTF-8} names are converted to the encoding of the local
+file system.
+
+The details of unicode conversion are controlled by the \var{encoding} and
+\var{errors} keyword arguments of the \class{TarFile} class.
+
+The default value for \var{encoding} is the local character encoding. It is
+deduced from \function{sys.getfilesystemencoding()} and
+\function{sys.getdefaultencoding()}. In read mode, \var{encoding} is used
+exclusively to convert unicode names from a pax archive to strings in the local
+character encoding. In write mode, the use of \var{encoding} depends on the
+chosen archive format. In case of \constant{PAX_FORMAT}, input names that
+contain non-\ASCII{} characters need to be decoded before being stored as
+\emph{UTF-8} strings. The other formats do not make use of \var{encoding}
+unless unicode objects are used as input names. These are converted to
+8-bit character strings before they are added to the archive.
+
+The \var{errors} argument defines how characters are treated that cannot be
+converted to or from \var{encoding}. Possible values are listed in section
+\ref{codec-base-classes}. In read mode, there is an additional scheme
+\code{'utf-8'} which means that bad characters are replaced by their
+\emph{UTF-8} representation. This is the default scheme. In write mode the
+default value for \var{errors} is \code{'strict'} to ensure that name
+information is not altered unnoticed.

Modified: python/branches/p3yk-noslice/Doc/lib/libtelnetlib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtelnetlib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtelnetlib.tex	Wed Jul 11 15:40:56 2007
@@ -23,13 +23,16 @@
 SB (Subnegotiation Begin).
 
 
-\begin{classdesc}{Telnet}{\optional{host\optional{, port}}}
+\begin{classdesc}{Telnet}{\optional{host\optional{, port\optional{, timeout}}}}
 \class{Telnet} represents a connection to a Telnet server. The
 instance is initially not connected by default; the \method{open()}
 method must be used to establish a connection.  Alternatively, the
 host name and optional port 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 \var{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).
 
 Do not reopen an already connected instance.
 
@@ -37,6 +40,7 @@
 raise \exception{EOFError} when the end of the connection is read,
 because they can return an empty string for other reasons.  See the
 individual descriptions below.
+\versionchanged[\var{timeout} was added]{2.6}
 \end{classdesc}
 
 
@@ -52,7 +56,7 @@
 \class{Telnet} instances have the following methods:
 
 
-\begin{methoddesc}{read_until}{expected\optional{, timeout}}
+\begin{methoddesc}[Telnet]{read_until}{expected\optional{, timeout}}
 Read until a given string, \var{expected}, is encountered or until
 \var{timeout} seconds have passed.
 
@@ -61,17 +65,17 @@
 is closed and no cooked data is available.
 \end{methoddesc}
 
-\begin{methoddesc}{read_all}{}
+\begin{methoddesc}[Telnet]{read_all}{}
 Read all data until \EOF; block until connection closed.
 \end{methoddesc}
 
-\begin{methoddesc}{read_some}{}
+\begin{methoddesc}[Telnet]{read_some}{}
 Read at least one byte of cooked data unless \EOF{} is hit.
 Return \code{''} if \EOF{} is hit.  Block if no data is immediately
 available.
 \end{methoddesc}
 
-\begin{methoddesc}{read_very_eager}{}
+\begin{methoddesc}[Telnet]{read_very_eager}{}
 Read everything that can be without blocking in I/O (eager).
 
 Raise \exception{EOFError} if connection closed and no cooked data
@@ -79,7 +83,7 @@
 Do not block unless in the midst of an IAC sequence.
 \end{methoddesc}
 
-\begin{methoddesc}{read_eager}{}
+\begin{methoddesc}[Telnet]{read_eager}{}
 Read readily available data.
 
 Raise \exception{EOFError} if connection closed and no cooked data
@@ -87,7 +91,7 @@
 Do not block unless in the midst of an IAC sequence.
 \end{methoddesc}
 
-\begin{methoddesc}{read_lazy}{}
+\begin{methoddesc}[Telnet]{read_lazy}{}
 Process and return data already in the queues (lazy).
 
 Raise \exception{EOFError} if connection closed and no data available.
@@ -95,7 +99,7 @@
 unless in the midst of an IAC sequence.
 \end{methoddesc}
 
-\begin{methoddesc}{read_very_lazy}{}
+\begin{methoddesc}[Telnet]{read_very_lazy}{}
 Return any data available in the cooked queue (very lazy).
 
 Raise \exception{EOFError} if connection closed and no data available.
@@ -103,7 +107,7 @@
 never blocks.
 \end{methoddesc}
 
-\begin{methoddesc}{read_sb_data}{}
+\begin{methoddesc}[Telnet]{read_sb_data}{}
 Return the data collected between a SB/SE pair (suboption begin/end).
 The callback should access these data when it was invoked with a
 \code{SE} command. This method never blocks.
@@ -111,52 +115,56 @@
 \versionadded{2.3}
 \end{methoddesc}
 
-\begin{methoddesc}{open}{host\optional{, port}}
+\begin{methoddesc}[Telnet]{open}{host\optional{, port\optional{, timeout}}}
 Connect to a host.
 The optional second argument is the port number, which
 defaults to the standard Telnet port (23).
+The optional \var{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).
 
 Do not try to reopen an already connected instance.
+\versionchanged[\var{timeout} was added]{2.6}
 \end{methoddesc}
 
-\begin{methoddesc}{msg}{msg\optional{, *args}}
+\begin{methoddesc}[Telnet]{msg}{msg\optional{, *args}}
 Print a debug message when the debug level is \code{>} 0.
 If extra arguments are present, they are substituted in the
 message using the standard string formatting operator.
 \end{methoddesc}
 
-\begin{methoddesc}{set_debuglevel}{debuglevel}
+\begin{methoddesc}[Telnet]{set_debuglevel}{debuglevel}
 Set the debug level.  The higher the value of \var{debuglevel}, the
 more debug output you get (on \code{sys.stdout}).
 \end{methoddesc}
 
-\begin{methoddesc}{close}{}
+\begin{methoddesc}[Telnet]{close}{}
 Close the connection.
 \end{methoddesc}
 
-\begin{methoddesc}{get_socket}{}
+\begin{methoddesc}[Telnet]{get_socket}{}
 Return the socket object used internally.
 \end{methoddesc}
 
-\begin{methoddesc}{fileno}{}
+\begin{methoddesc}[Telnet]{fileno}{}
 Return the file descriptor of the socket object used internally.
 \end{methoddesc}
 
-\begin{methoddesc}{write}{buffer}
+\begin{methoddesc}[Telnet]{write}{buffer}
 Write a string to the socket, doubling any IAC characters.
 This can block if the connection is blocked.  May raise
 \exception{socket.error} if the connection is closed.
 \end{methoddesc}
 
-\begin{methoddesc}{interact}{}
+\begin{methoddesc}[Telnet]{interact}{}
 Interaction function, emulates a very dumb Telnet client.
 \end{methoddesc}
 
-\begin{methoddesc}{mt_interact}{}
+\begin{methoddesc}[Telnet]{mt_interact}{}
 Multithreaded version of \method{interact()}.
 \end{methoddesc}
 
-\begin{methoddesc}{expect}{list\optional{, timeout}}
+\begin{methoddesc}[Telnet]{expect}{list\optional{, timeout}}
 Read until one from a list of a regular expressions matches.
 
 The first argument is a list of regular expressions, either
@@ -178,7 +186,7 @@
 results are indeterministic, and may depend on the I/O timing.
 \end{methoddesc}
 
-\begin{methoddesc}{set_option_negotiation_callback}{callback}
+\begin{methoddesc}[Telnet]{set_option_negotiation_callback}{callback}
 Each time a telnet option is read on the input flow, this
 \var{callback} (if set) is called with the following parameters :
 callback(telnet socket, command (DO/DONT/WILL/WONT), option).  No other

Modified: python/branches/p3yk-noslice/Doc/lib/libtempfile.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtempfile.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtempfile.tex	Wed Jul 11 15:40:56 2007
@@ -53,7 +53,7 @@
 \begin{funcdesc}{NamedTemporaryFile}{\optional{mode=\code{'w+b'}\optional{,
                                      bufsize=\code{-1}\optional{,
                                      suffix\optional{, prefix\optional{,
-                                     dir}}}}}}
+                                     dir\optional{, delete}}}}}}}
 This function operates exactly as \function{TemporaryFile()} does,
 except that the file is guaranteed to have a visible name in the file
 system (on \UNIX, the directory entry is not unlinked).  That name can
@@ -61,7 +61,27 @@
 the name can be used to open the file a second time, while the
 named temporary file is still open, varies across platforms (it can
 be so used on \UNIX; it cannot on Windows NT or later).
+If \var{delete} is true (the default), the file is deleted as soon as
+it is closed.
 \versionadded{2.3}
+\versionadded[The \var{delete} parameter]{2.6}
+\end{funcdesc}
+
+\begin{funcdesc}{SpooledTemporaryFile}{\optional{max\_size=\code{0},
+                                \optional{mode=\code{'w+b'}\optional{,
+                                bufsize=\code{-1}\optional{,
+                                suffix\optional{, prefix\optional{,
+                                dir}}}}}}}
+This function operates exactly as \function{TemporaryFile()} does,
+except that data is spooled in memory until the file size exceeds
+\var{max_size}, or until the file's \function{fileno()} method is
+called, at which point the contents are written to disk and operation
+proceeds as with \function{TemporaryFile()}.
+
+The resulting file has one additional method, \function{rollover()},
+which causes the file to roll over to an on-disk file regardless of
+its size.
+\versionadded{2.6}
 \end{funcdesc}
 
 \begin{funcdesc}{mkstemp}{\optional{suffix\optional{,

Modified: python/branches/p3yk-noslice/Doc/lib/libtest.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtest.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtest.tex	Wed Jul 11 15:40:56 2007
@@ -14,11 +14,11 @@
 
 Each module in the \module{test} package whose name starts with
 \samp{test_} is a testing suite for a specific module or feature.
-All new tests should be written using the \refmodule{unittest} module;
-using \refmodule{unittest} is not required but makes the tests more
-flexible and maintenance of the tests easier.  Some older tests are
-written to use \refmodule{doctest} and a ``traditional'' testing
-style; these styles of tests will not be covered.
+All new tests should be written using the \refmodule{unittest} or
+\refmodule{doctest} module.  Some older tests are
+written using a ``traditional'' testing style that compares output
+printed to \code{sys.stdout}; this style of test is considered
+deprecated.
 
 \begin{seealso}
 \seemodule{unittest}{Writing PyUnit regression tests.}
@@ -29,8 +29,8 @@
 \subsection{Writing Unit Tests for the \module{test} package%
             \label{writing-tests}}
 
-It is preferred that tests for the \module{test} package use the
-\refmodule{unittest} module and follow a few guidelines.
+It is preferred that tests that use the \refmodule{unittest} module
+follow a few guidelines.
 One is to name the test module by starting it with \samp{test_} and end it with
 the name of the module being tested.
 The test methods in the test module should start with \samp{test_} and end with
@@ -196,7 +196,9 @@
 This module defines the following exceptions:
 
 \begin{excdesc}{TestFailed}
-Exception to be raised when a test fails.
+Exception to be raised when a test fails. This is deprecated in favor
+of \module{unittest}-based tests and \class{unittest.TestCase}'s
+assertion methods.
 \end{excdesc}
 
 \begin{excdesc}{TestSkipped}
@@ -273,18 +275,30 @@
 Execute \class{unittest.TestCase} subclasses passed to the function.
 The function scans the classes for methods starting with the prefix
 \samp{test_} and executes the tests individually.
-This is the preferred way to execute tests.
-\end{funcdesc}
 
-\begin{funcdesc}{run_suite}{suite\optional{, testclass}}
-Execute the \class{unittest.TestSuite} instance \var{suite}.
-The optional argument \var{testclass} accepts one of the test classes in the
-suite so as to print out more detailed information on where the testing suite
-originated from.
+It is also legal to pass strings as parameters; these should be keys in
+\code{sys.modules}. Each associated module will be scanned by
+\code{unittest.TestLoader.loadTestsFromModule()}. This is usually seen in
+the following \function{test_main()} function:
+
+\begin{verbatim}
+def test_main():
+    test_support.run_unittest(__name__)
+\end{verbatim}
+
+This will run all tests defined in the named module.
 \end{funcdesc}
 
 The \module{test.test_support} module defines the following classes:
 
+\begin{classdesc}{TransientResource}{exc\optional{, **kwargs}}
+Create a context manager that raises \class{ResourceDenied} if the specified
+exception type is raised.  Any keyword arguments are treated as name/value
+pairs to be compared against any exception raised with the \code{with}
+statement.  Only if all pairs match is \class{ResourceDenied} raised.
+\versionadded{2.6}
+\end{classdesc}
+
 \begin{classdesc}{EnvironmentVarGuard}{}
 Class used to temporarily set or unset environment variables.  Instances can be
 used as a context manager.

Modified: python/branches/p3yk-noslice/Doc/lib/libtextwrap.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtextwrap.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtextwrap.tex	Wed Jul 11 15:40:56 2007
@@ -54,7 +54,7 @@
 in indented form.
 
 Note that tabs and spaces are both treated as whitespace, but they are
-not equal: the lines \code{" {} hello"} and \code{"\textbackslash{}thello"}
+not equal: the lines \code{" {} hello"} and \code{"\e thello"}
 are considered to have no common leading whitespace.  (This behaviour is
 new in Python 2.5; older versions of this module incorrectly expanded
 tabs before searching for common leading whitespace.)
@@ -115,6 +115,13 @@
 expansion.}
 \end{memberdesc}
 
+\begin{memberdesc}{drop_whitespace}
+(default: \code{True}) If true, whitespace that, after wrapping, happens
+to end up at the beginning or end of a line is dropped (leading whitespace
+in the first line is always preserved, though).
+\versionadded[Whitespace was always dropped in earlier versions]{2.6}
+\end{memberdesc}
+
 \begin{memberdesc}{initial_indent}
 (default: \code{''}) String that will be prepended to the first line
 of wrapped output.  Counts towards the length of the first line.

Modified: python/branches/p3yk-noslice/Doc/lib/libthreading.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libthreading.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libthreading.tex	Wed Jul 11 15:40:56 2007
@@ -15,17 +15,16 @@
 This module defines the following functions and objects:
 
 \begin{funcdesc}{activeCount}{}
-Return the number of currently active \class{Thread} objects.
-The returned count is equal to the length of the list returned by
+Return the number of \class{Thread} objects currently alive.  The
+returned count is equal to the length of the list returned by
 \function{enumerate()}.
-A function that returns the number of currently active threads.
 \end{funcdesc}
 
-\begin{funcdesc}{Condition}{}
+\begin{funcdescni}{Condition}{}
 A factory function that returns a new condition variable object.
 A condition variable allows one or more threads to wait until they
 are notified by another thread.
-\end{funcdesc}
+\end{funcdescni}
 
 \begin{funcdesc}{currentThread}{}
 Return the current \class{Thread} object, corresponding to the
@@ -36,18 +35,18 @@
 \end{funcdesc}
 
 \begin{funcdesc}{enumerate}{}
-Return a list of all currently active \class{Thread} objects.
-The list includes daemonic threads, dummy thread objects created
-by \function{currentThread()}, and the main thread.  It excludes terminated
-threads and threads that have not yet been started.
+Return a list of all \class{Thread} objects currently alive.  The list
+includes daemonic threads, dummy thread objects created by
+\function{currentThread()}, and the main thread.  It excludes
+terminated threads and threads that have not yet been started.
 \end{funcdesc}
 
-\begin{funcdesc}{Event}{}
+\begin{funcdescni}{Event}{}
 A factory function that returns a new event object.  An event manages
 a flag that can be set to true with the \method{set()} method and
 reset to false with the \method{clear()} method.  The \method{wait()}
 method blocks until the flag is true.
-\end{funcdesc}
+\end{funcdescni}
 
 \begin{classdesc*}{local}{}
 A class that represents thread-local data.  Thread-local data are data
@@ -82,14 +81,14 @@
 for each time it has acquired it.
 \end{funcdesc}
 
-\begin{funcdesc}{Semaphore}{\optional{value}}
+\begin{funcdescni}{Semaphore}{\optional{value}}
 A factory function that returns a new semaphore object.  A
 semaphore manages a counter representing the number of \method{release()}
 calls minus the number of \method{acquire()} calls, plus an initial value.
 The \method{acquire()} method blocks if necessary until it can return
 without making the counter negative.  If not given, \var{value} defaults to
 1. 
-\end{funcdesc}
+\end{funcdescni}
 
 \begin{funcdesc}{BoundedSemaphore}{\optional{value}}
 A factory function that returns a new bounded semaphore object.  A bounded
@@ -100,12 +99,12 @@
 \var{value} defaults to 1. 
 \end{funcdesc}
 
-\begin{classdesc*}{Thread}{}
+\begin{classdesc*}{Thread}
 A class that represents a thread of control.  This class can be safely
 subclassed in a limited fashion.
 \end{classdesc*}
 
-\begin{classdesc*}{Timer}{}
+\begin{classdesc*}{Timer}
 A thread that executes a function after a specified interval has passed.
 \end{classdesc*}
 
@@ -175,15 +174,18 @@
 unlocked, then the \method{acquire()} call resets it to locked and
 returns.  The \method{release()} method should only be called in the
 locked state; it changes the state to unlocked and returns
-immediately.  When more than one thread is blocked in
-\method{acquire()} waiting for the state to turn to unlocked, only one
-thread proceeds when a \method{release()} call resets the state to
-unlocked; which one of the waiting threads proceeds is not defined,
-and may vary across implementations.
+immediately. If an attempt is made to release an unlocked lock, a
+\exception{RuntimeError} will be raised.
+
+When more than one thread is blocked in \method{acquire()} waiting for
+the state to turn to unlocked, only one thread proceeds when a
+\method{release()} call resets the state to unlocked; which one of the
+waiting threads proceeds is not defined, and may vary across
+implementations.
 
 All methods are executed atomically.
 
-\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
+\begin{methoddesc}[Lock]{acquire}{\optional{blocking\code{ = 1}}}
 Acquire a lock, blocking or non-blocking.
 
 When invoked without arguments, block until the lock is
@@ -198,7 +200,7 @@
 without arguments, and return true.
 \end{methoddesc}
 
-\begin{methoddesc}{release}{}
+\begin{methoddesc}[Lock]{release}{}
 Release a lock.
 
 When the lock is locked, reset it to unlocked, and return.  If
@@ -228,7 +230,7 @@
 pair) resets the lock to unlocked and allows another thread blocked in
 \method{acquire()} to proceed.
 
-\begin{methoddesc}{acquire}{\optional{blocking\code{ = 1}}}
+\begin{methoddesc}[RLock]{acquire}{\optional{blocking\code{ = 1}}}
 Acquire a lock, blocking or non-blocking.
 
 When invoked without arguments: if this thread already owns
@@ -250,7 +252,7 @@
 without arguments, and return true.
 \end{methoddesc}
 
-\begin{methoddesc}{release}{}
+\begin{methoddesc}[RLock]{release}{}
 Release a lock, decrementing the recursion level.  If after the
 decrement it is zero, reset the lock to unlocked (not owned by any
 thread), and if any other threads are blocked waiting for the lock to
@@ -258,8 +260,9 @@
 decrement the recursion level is still nonzero, the lock remains
 locked and owned by the calling thread.
 
-Only call this method when the calling thread owns the lock.
-Do not call this method when the lock is unlocked.
+Only call this method when the calling thread owns the lock. A
+\exception{RuntimeError} is raised if this method is called when the
+lock is unlocked.
 
 There is no return value.
 \end{methoddesc}
@@ -276,7 +279,8 @@
 methods that call the corresponding methods of the associated lock.
 It also has a \method{wait()} method, and \method{notify()} and
 \method{notifyAll()} methods.  These three must only be called when
-the calling thread has acquired the lock.
+the calling thread has acquired the lock, otherwise a
+\exception{RuntimeError} is raised.
 
 The \method{wait()} method releases the lock, and then blocks until it
 is awakened by a \method{notify()} or \method{notifyAll()} call for
@@ -344,9 +348,9 @@
 \end{methoddesc}
 
 \begin{methoddesc}{wait}{\optional{timeout}}
-Wait until notified or until a timeout occurs.
-This must only be called when the calling thread has acquired the
-lock.
+Wait until notified or until a timeout occurs. If the calling thread
+has not acquired the lock when this method is called, a
+\exception{RuntimeError} is raised.
 
 This method releases the underlying lock, and then blocks until it is
 awakened by a \method{notify()} or \method{notifyAll()} call for the
@@ -368,9 +372,10 @@
 \end{methoddesc}
 
 \begin{methoddesc}{notify}{}
-Wake up a thread waiting on this condition, if any.
-This must only be called when the calling thread has acquired the
-lock.
+Wake up a thread waiting on this condition, if any. Wait until
+notified or until a timeout occurs. If the calling thread has not
+acquired the lock when this method is called, a
+\exception{RuntimeError} is raised.
 
 This method wakes up one of the threads waiting for the condition
 variable, if any are waiting; it is a no-op if no threads are waiting.
@@ -387,7 +392,9 @@
 
 \begin{methoddesc}{notifyAll}{}
 Wake up all threads waiting on this condition.  This method acts like
-\method{notify()}, but wakes up all waiting threads instead of one.
+\method{notify()}, but wakes up all waiting threads instead of one. If
+the calling thread has not acquired the lock when this method is
+called, a \exception{RuntimeError} is raised.
 \end{methoddesc}
 
 
@@ -405,8 +412,9 @@
 calls \method{release()}.
 
 \begin{classdesc}{Semaphore}{\optional{value}}
-The optional argument gives the initial value for the internal
-counter; it defaults to \code{1}.
+The optional argument gives the initial \var{value} for the internal
+counter; it defaults to \code{1}. If the \var{value} given is less
+than 0, \exception{ValueError} is raised.
 \end{classdesc}
 
 \begin{methoddesc}{acquire}{\optional{blocking}}
@@ -526,12 +534,9 @@
 \method{run()} method in a separate thread of control.
 
 Once the thread's activity is started, the thread is considered
-'alive' and 'active' (these concepts are almost, but not quite
-exactly, the same; their definition is intentionally somewhat
-vague).  It stops being alive and active when its \method{run()}
-method terminates -- either normally, or by raising an unhandled
-exception.  The \method{isAlive()} method tests whether the thread is
-alive.
+'alive'. It stops being alive when its \method{run()} method terminates
+-- either normally, or by raising an unhandled exception.  The
+\method{isAlive()} method tests whether the thread is alive.
 
 Other threads can call a thread's \method{join()} method.  This blocks
 the calling thread until the thread whose \method{join()} method is
@@ -551,14 +556,13 @@
 initial thread of control in the Python program.  It is not a
 daemon thread.
 
-There is the possibility that ``dummy thread objects'' are
-created.  These are thread objects corresponding to ``alien
-threads''.  These are threads of control started outside the
-threading module, such as directly from C code.  Dummy thread objects
-have limited functionality; they are always considered alive,
-active, and daemonic, and cannot be \method{join()}ed.  They are never 
-deleted, since it is impossible to detect the termination of alien
-threads.
+There is the possibility that ``dummy thread objects'' are created.
+These are thread objects corresponding to ``alien threads'', which
+are threads of control started outside the threading module, such as
+directly from C code.  Dummy thread objects have limited
+functionality; they are always considered alive and daemonic, and
+cannot be \method{join()}ed.  They are never deleted, since it is
+impossible to detect the termination of alien threads.
 
 
 \begin{classdesc}{Thread}{group=None, target=None, name=None,
@@ -591,9 +595,12 @@
 \begin{methoddesc}{start}{}
 Start the thread's activity.
 
-This must be called at most once per thread object.  It
-arranges for the object's \method{run()} method to be invoked in a
-separate thread of control.
+It must be called at most once per thread object.  It arranges for the
+object's \method{run()} method to be invoked in a separate thread of
+control.
+
+This method will raise a \exception{RuntimeException} if called more
+than once on the same thread object.
 \end{methoddesc}
 
 \begin{methoddesc}{run}{}
@@ -623,11 +630,10 @@
 
 A thread can be \method{join()}ed many times.
 
-A thread cannot join itself because this would cause a
-deadlock.
-
-It is an error to attempt to \method{join()} a thread before it has
-been started.
+\method{join()} may throw a \exception{RuntimeError}, if an attempt is
+made to join the current thread as that would cause a deadlock. It is
+also an error to \method{join()} a thread before it has been started
+and attempts to do so raises same exception.
 \end{methoddesc}
 
 \begin{methoddesc}{getName}{}
@@ -646,7 +652,8 @@
 Return whether the thread is alive.
 
 Roughly, a thread is alive from the moment the \method{start()} method
-returns until its \method{run()} method terminates.
+returns until its \method{run()} method terminates. The module
+function \function{enumerate()} returns a list of all alive threads.
 \end{methoddesc}
 
 \begin{methoddesc}{isDaemon}{}
@@ -655,12 +662,13 @@
 
 \begin{methoddesc}{setDaemon}{daemonic}
 Set the thread's daemon flag to the Boolean value \var{daemonic}.
-This must be called before \method{start()} is called.
+This must be called before \method{start()} is called, otherwise
+\exception{RuntimeError} is raised.
 
 The initial value is inherited from the creating thread.
 
-The entire Python program exits when no active non-daemon
-threads are left.
+The entire Python program exits when no alive non-daemon threads are
+left.
 \end{methoddesc}
 
 

Modified: python/branches/p3yk-noslice/Doc/lib/libtimeit.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtimeit.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtimeit.tex	Wed Jul 11 15:40:56 2007
@@ -31,6 +31,13 @@
 \method{timeit()} method.  The \method{repeat()} method is a
 convenience to call \method{timeit()} multiple times and return a list
 of results.
+
+\versionchanged[The \var{stmt} and \var{setup} parameters can now also
+                take objects that are callable without arguments. This
+		will embed calls to them in a timer function that will
+		then be executed by \method{timeit()}.  Note that the timing
+		overhead is a little larger in this case because of the
+		extra function calls]{2.6}
 \end{classdesc}
 
 \begin{methoddesc}{print_exc}{\optional{file=\constant{None}}}
@@ -91,18 +98,36 @@
 measured.  If so, GC can be re-enabled as the first statement in the
 \var{setup} string.  For example:
 \begin{verbatim}
-    timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()
+    timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()
 \end{verbatim}
 \end{notice}
 \end{methoddesc}
 
 
+Starting with version 2.6, the module also defines two convenience functions:
+
+\begin{funcdesc}{repeat}{stmt\optional{, setup\optional{, timer\optional{,
+                         repeat\code{=3} \optional{, number\code{=1000000}}}}}}
+Create a \class{Timer} instance with the given statement, setup code and timer
+function and run its \method{repeat} method with the given repeat count and
+\var{number} executions.
+\versionadded{2.6}
+\end{funcdesc}
+
+\begin{funcdesc}{timeit}{stmt\optional{, setup\optional{, timer\optional{,
+                         number\code{=1000000}}}}}
+Create a \class{Timer} instance with the given statement, setup code and timer
+function and run its \method{timeit} method with \var{number} executions.
+\versionadded{2.6}
+\end{funcdesc}
+
+
 \subsection{Command Line Interface}
 
 When called as a program from the command line, the following form is used:
 
 \begin{verbatim}
-python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
+python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
 \end{verbatim}
 
 where the following options are understood:

Modified: python/branches/p3yk-noslice/Doc/lib/libturtle.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libturtle.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libturtle.tex	Wed Jul 11 15:40:56 2007
@@ -261,7 +261,7 @@
 \function{degrees()}, which takes an optional argument letting 
 you specify the number of units corresponding to a full circle:
 
-\begin{methoddesc}{degrees}{\optional{fullcircle}}
+\begin{methoddesc}[Turtle]{degrees}{\optional{fullcircle}}
 \var{fullcircle} is by default 360. This can cause the pen to have any
 angular units whatever: give \var{fullcircle} 2*$\pi$ for radians, or
 400 for gradians.

Modified: python/branches/p3yk-noslice/Doc/lib/libtypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtypes.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libtypes.tex	Wed Jul 11 15:40:56 2007
@@ -147,9 +147,9 @@
 The type of open file objects such as \code{sys.stdout}.
 \end{datadesc}
 
-\begin{datadesc}{XRangeType}
+\begin{datadesc}{RangeType}
 The type of range objects returned by
-\function{xrange()}\bifuncindex{xrange}.
+\function{range()}\bifuncindex{range}.
 \end{datadesc}
 
 \begin{datadesc}{SliceType}
@@ -163,7 +163,7 @@
 
 \begin{datadesc}{TracebackType}
 The type of traceback objects such as found in
-\code{sys.exc_traceback}.
+\code{sys.exc_info()[2]}.
 \end{datadesc}
 
 \begin{datadesc}{FrameType}

Modified: python/branches/p3yk-noslice/Doc/lib/libundoc.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libundoc.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libundoc.tex	Wed Jul 11 15:40:56 2007
@@ -46,11 +46,6 @@
 
 \item[\module{posixpath}]
 --- Implementation of \module{os.path} on \POSIX.
-
-\item[\module{bsddb185}]
---- Backwards compatibility module for systems which still use the Berkeley
-    DB 1.85 module.  It is normally only available on certain BSD \UNIX-based
-    systems.  It should never be used directly.
 \end{description}
 
 
@@ -93,21 +88,6 @@
 % XXX need Windows instructions!
 
 \begin{description}
-\item[\module{timing}]
---- Measure time intervals to high resolution (use \function{time.clock()}
-    instead).
-\end{description}
-
-\section{SGI-specific Extension modules}
-
-The following are SGI specific, and may be out of touch with the
-current version of reality.
-
-\begin{description}
-\item[\module{cl}]
---- Interface to the SGI compression library.
-
-\item[\module{sv}]
---- Interface to the ``simple video'' board on SGI Indigo
-    (obsolete hardware).
+\item
+--- This section should be empty for Python 3.0.
 \end{description}

Modified: python/branches/p3yk-noslice/Doc/lib/libunittest.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libunittest.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libunittest.tex	Wed Jul 11 15:40:56 2007
@@ -91,7 +91,7 @@
 \end{seealso}
 
 
-\subsection{Basic example \label{minimal-example}}
+\subsection{Basic example \label{unittest-minimal-example}}
 
 The \module{unittest} module provides a rich set of tools for
 constructing and running tests.  This section demonstrates that a
@@ -290,6 +290,7 @@
 we would end up subclassing \class{SimpleWidgetTestCase} into many
 small one-method classes such as
 \class{DefaultWidgetSizeTestCase}.  This is time-consuming and
+
 discouraging, so in the same vein as JUnit, \module{unittest} provides
 a simpler mechanism:
 
@@ -540,7 +541,7 @@
 
 \begin{funcdesc}{main}{\optional{module\optional{,
                  defaultTest\optional{, argv\optional{,
-                 testRunner\optional{, testRunner}}}}}}
+                 testRunner\optional{, testLoader}}}}}}
   A command-line program that runs a set of tests; this is primarily
   for making test modules conveniently executable.  The simplest use
   for this function is to include the following line at the end of a
@@ -550,6 +551,9 @@
 if __name__ == '__main__':
     unittest.main()
 \end{verbatim}
+
+  The \var{testRunner} argument can either be a test runner class or
+  an already created instance of it.
 \end{funcdesc}
 
 In some cases, the existing tests may have been written using the
@@ -615,14 +619,14 @@
 report failures.
 
 \begin{methoddesc}[TestCase]{assert_}{expr\optional{, msg}}
-\methodline{failUnless}{expr\optional{, msg}}
+\methodline[TestCase]{failUnless}{expr\optional{, msg}}
   Signal a test failure if \var{expr} is false; the explanation for
   the error will be \var{msg} if given, otherwise it will be
   \constant{None}.
 \end{methoddesc}
 
 \begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}}
-\methodline{failUnlessEqual}{first, second\optional{, msg}}
+\methodline[TestCase]{failUnlessEqual}{first, second\optional{, msg}}
   Test that \var{first} and \var{second} are equal.  If the values do
   not compare equal, the test will fail with the explanation given by
   \var{msg}, or \constant{None}.  Note that using \method{failUnlessEqual()}
@@ -633,7 +637,7 @@
 \end{methoddesc}
 
 \begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}}
-\methodline{failIfEqual}{first, second\optional{, msg}}
+\methodline[TestCase]{failIfEqual}{first, second\optional{, msg}}
   Test that \var{first} and \var{second} are not equal.  If the values
   do compare equal, the test will fail with the explanation given by
   \var{msg}, or \constant{None}.  Note that using \method{failIfEqual()}
@@ -645,7 +649,7 @@
 
 \begin{methoddesc}[TestCase]{assertAlmostEqual}{first, second\optional{,
 						places\optional{, msg}}}
-\methodline{failUnlessAlmostEqual}{first, second\optional{,
+\methodline[TestCase]{failUnlessAlmostEqual}{first, second\optional{,
 						places\optional{, msg}}}
   Test that \var{first} and \var{second} are approximately equal
   by computing the difference, rounding to the given number of \var{places},
@@ -657,7 +661,7 @@
 
 \begin{methoddesc}[TestCase]{assertNotAlmostEqual}{first, second\optional{,
 						places\optional{, msg}}}
-\methodline{failIfAlmostEqual}{first, second\optional{,
+\methodline[TestCase]{failIfAlmostEqual}{first, second\optional{,
 						places\optional{, msg}}}
   Test that \var{first} and \var{second} are not approximately equal
   by computing the difference, rounding to the given number of \var{places},
@@ -668,7 +672,7 @@
 \end{methoddesc}
 
 \begin{methoddesc}[TestCase]{assertRaises}{exception, callable, \moreargs}
-\methodline{failUnlessRaises}{exception, callable, \moreargs}
+\methodline[TestCase]{failUnlessRaises}{exception, callable, \moreargs}
   Test that an exception is raised when \var{callable} is called with
   any positional or keyword arguments that are also passed to
   \method{assertRaises()}.  The test passes if \var{exception} is

Modified: python/branches/p3yk-noslice/Doc/lib/liburllib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liburllib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/liburllib.tex	Wed Jul 11 15:40:56 2007
@@ -70,8 +70,8 @@
 
 The \function{urlopen()} function works transparently with proxies
 which do not require authentication.  In a \UNIX{} or Windows
-environment, set the \envvar{http_proxy}, \envvar{ftp_proxy} or
-\envvar{gopher_proxy} environment variables to a URL that identifies
+environment, set the \envvar{http_proxy}, or \envvar{ftp_proxy}
+environment variables to a URL that identifies
 the proxy server before starting the Python interpreter.  For example
 (the \character{\%} is the command prompt):
 
@@ -253,7 +253,7 @@
 \begin{classdesc}{URLopener}{\optional{proxies\optional{, **x509}}}
 Base class for opening and reading URLs.  Unless you need to support
 opening objects using schemes other than \file{http:}, \file{ftp:},
-\file{gopher:} or \file{file:}, you probably want to use
+or \file{file:}, you probably want to use
 \class{FancyURLopener}.
 
 By default, the \class{URLopener} class sends a
@@ -324,9 +324,8 @@
 
 \item
 Currently, only the following protocols are supported: HTTP, (versions
-0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.
+0.9 and 1.0),  FTP, and local files.
 \indexii{HTTP}{protocol}
-\indexii{Gopher}{protocol}
 \indexii{FTP}{protocol}
 
 \item
@@ -355,9 +354,7 @@
 (such as an image), plain text or (for example) HTML\index{HTML}.  The
 HTTP\indexii{HTTP}{protocol} protocol provides type information in the
 reply header, which can be inspected by looking at the
-\mailheader{Content-Type} header.  For the
-Gopher\indexii{Gopher}{protocol} protocol, type information is encoded
-in the URL; there is currently no easy way to extract it.  If the
+\mailheader{Content-Type} header.  If the
 returned data is HTML, you can use the module
 \refmodule{htmllib}\refstmodindex{htmllib} to parse it.
 

Modified: python/branches/p3yk-noslice/Doc/lib/liburllib2.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liburllib2.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/liburllib2.tex	Wed Jul 11 15:40:56 2007
@@ -14,7 +14,7 @@
 
 The \module{urllib2} module defines the following functions:
 
-\begin{funcdesc}{urlopen}{url\optional{, data}}
+\begin{funcdesc}{urlopen}{url\optional{, data}\optional{, timeout}}
 Open the URL \var{url}, which can be either a string or a \class{Request}
 object.
 
@@ -27,6 +27,11 @@
 \function{urllib.urlencode()} function takes a mapping or sequence of
 2-tuples and returns a string in this format.
 
+The optional \var{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). This actually only work for HTTP, HTTPS, FTP
+and FTPS connections.
+
 This function returns a file-like object with two additional methods:
 
 \begin{itemize}
@@ -40,6 +45,8 @@
 Note that \code{None} may be returned if no handler handles the
 request (though the default installed global \class{OpenerDirector}
 uses \class{UnknownHandler} to ensure this never happens).
+
+\versionchanged[\var{timeout} was added]{2.6}
 \end{funcdesc}
 
 \begin{funcdesc}{install_opener}{opener}
@@ -86,11 +93,6 @@
 HTTP errors, such as requests for authentication.
 \end{excdesc}
 
-\begin{excdesc}{GopherError}
-A subclass of \exception{URLError}, this is the error raised by the
-Gopher handler.
-\end{excdesc}
-
 
 The following classes are provided:
 
@@ -241,10 +243,6 @@
 delays.
 \end{classdesc}
 
-\begin{classdesc}{GopherHandler}{}
-Open gopher URLs.
-\end{classdesc}
-
 \begin{classdesc}{UnknownHandler}{}
 A catch-all class to handle unknown URLs.
 \end{classdesc}
@@ -360,12 +358,18 @@
 \end{itemize}
 \end{methoddesc}
 
-\begin{methoddesc}[OpenerDirector]{open}{url\optional{, data}}
+\begin{methoddesc}[OpenerDirector]{open}{url\optional{, data}{\optional{, timeout}}}
 Open the given \var{url} (which can be a request object or a string),
 optionally passing the given \var{data}.
 Arguments, return values and exceptions raised are the same as those
 of \function{urlopen()} (which simply calls the \method{open()} method
-on the currently installed global \class{OpenerDirector}).
+on the currently installed global \class{OpenerDirector}).  The optional
+\var{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; this actually only work for HTTP, HTTPS, FTP
+and FTPS connections).
+
+\versionchanged[\var{timeout} was added]{2.6}
 \end{methoddesc}
 
 \begin{methoddesc}[OpenerDirector]{error}{proto\optional{,
@@ -588,7 +592,7 @@
 
 \class{HTTPCookieProcessor} instances have one attribute:
 
-\begin{memberdesc}{cookiejar}
+\begin{memberdesc}[HTTPCookieProcessor]{cookiejar}
 The \class{cookielib.CookieJar} in which cookies are stored.
 \end{memberdesc}
 
@@ -744,13 +748,6 @@
 \end{methoddesc}
 
 
-\subsection{GopherHandler Objects \label{gopher-handler}}
-
-\begin{methoddesc}[GopherHandler]{gopher_open}{req}
-Open the gopher resource indicated by \var{req}.
-\end{methoddesc}
-
-
 \subsection{UnknownHandler Objects \label{unknown-handler-objects}}
 
 \begin{methoddesc}[UnknownHandler]{unknown_open}{}
@@ -817,7 +814,10 @@
 import urllib2
 # Create an OpenerDirector with support for Basic HTTP Authentication...
 auth_handler = urllib2.HTTPBasicAuthHandler()
-auth_handler.add_password('realm', 'host', 'username', 'password')
+auth_handler.add_password(realm='PDQ Application',
+                          uri='https://mahler:8092/site-updates.py',
+                          user='klem',
+                          passwd='kadidd!ehopper')
 opener = urllib2.build_opener(auth_handler)
 # ...and install it globally so it can be used with urlopen.
 urllib2.install_opener(opener)

Modified: python/branches/p3yk-noslice/Doc/lib/liburlparse.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liburlparse.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/liburlparse.tex	Wed Jul 11 15:40:56 2007
@@ -157,7 +157,7 @@
 for \function{urlparse()}.
 
 \note{If \var{url} is an absolute URL (that is, starting with \code{//}
-      or \code{scheme://}, the \var{url}'s host name and/or scheme
+      or \code{scheme://}), the \var{url}'s host name and/or scheme
       will be present in the result.  For example:}
 
 \begin{verbatim}
@@ -168,7 +168,7 @@
       
 If you do not want that behavior, preprocess
 the \var{url} with \function{urlsplit()} and \function{urlunsplit()},
-removing possible \em{scheme} and \em{netloc} parts.
+removing possible \emph{scheme} and \emph{netloc} parts.
 \end{funcdesc}
 
 \begin{funcdesc}{urldefrag}{url}

Modified: python/branches/p3yk-noslice/Doc/lib/libwebbrowser.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libwebbrowser.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libwebbrowser.tex	Wed Jul 11 15:40:56 2007
@@ -154,20 +154,20 @@
 Browser controllers provide two methods which parallel two of the
 module-level convenience functions:
 
-\begin{funcdesc}{open}{url\optional{, new\optional{, autoraise=1}}}
+\begin{methoddesc}[controller]{open}{url\optional{, new\optional{, autoraise=1}}}
   Display \var{url} using the browser handled by this controller.
   If \var{new} is 1, a new browser window is opened if possible.
   If \var{new} is 2, a new browser page ("tab") is opened if possible.
-\end{funcdesc}
+\end{methoddesc}
 
-\begin{funcdesc}{open_new}{url}
+\begin{methoddesc}[controller]{open_new}{url}
   Open \var{url} in a new window of the browser handled by this
   controller, if possible, otherwise, open \var{url} in the only
   browser window.  Alias \function{open_new}.
-\end{funcdesc}
+\end{methoddesc}
 
-\begin{funcdesc}{open_new_tab}{url}
+\begin{methoddesc}[controller]{open_new_tab}{url}
   Open \var{url} in a new page ("tab") of the browser handled by this
   controller, if possible, otherwise equivalent to \function{open_new}.
 \versionadded{2.5}
-\end{funcdesc}
+\end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libwinreg.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libwinreg.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libwinreg.tex	Wed Jul 11 15:40:56 2007
@@ -151,7 +151,7 @@
  An application should only call \function{FlushKey()} if it requires absolute 
  certainty that registry changes are on disk.
  
- \emph{If you don't know whether a \function{FlushKey()} call is required, it 
+ \note{If you don't know whether a \function{FlushKey()} call is required, it 
  probably isn't.}
  
 \end{funcdesc}
@@ -321,7 +321,7 @@
  \var{key} is an already open key, or one of the predefined 
  \constant{HKEY_*} constants.
 
- \var{sub_key} is a string that names the subkey with which the 
+ \var{value_name} is a string that names the subkey with which the 
  value is associated.
 
  \var{type} is an integer that specifies the type of the data.  
@@ -393,14 +393,14 @@
  \method{Detach()} method to return the integer handle, and
  also disconnect the Windows handle from the handle object.
 
-\begin{methoddesc}{Close}{}
+\begin{methoddesc}[PyHKEY]{Close}{}
   Closes the underlying Windows handle.
 
   If the handle is already closed, no error is raised.
 \end{methoddesc}
 
 
-\begin{methoddesc}{Detach}{}
+\begin{methoddesc}[PyHKEY]{Detach}{}
   Detaches the Windows handle from the handle object.
 
  The result is an integer (or long on 64 bit Windows) that holds

Deleted: /python/branches/p3yk-noslice/Doc/lib/libxmllib.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/lib/libxmllib.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,287 +0,0 @@
-\section{\module{xmllib} ---
-         A parser for XML documents}
-
-\declaremodule{standard}{xmllib}
-\modulesynopsis{A parser for XML documents.}
-\moduleauthor{Sjoerd Mullender}{Sjoerd.Mullender at cwi.nl}
-\sectionauthor{Sjoerd Mullender}{Sjoerd.Mullender at cwi.nl}
-
-
-\index{XML}
-\index{Extensible Markup Language}
-
-\deprecated{2.0}{Use \refmodule{xml.sax} instead.  The newer XML
-                 package includes full support for XML 1.0.}
-
-\versionchanged[Added namespace support]{1.5.2}
-
-This module defines a class \class{XMLParser} which serves as the basis 
-for parsing text files formatted in XML (Extensible Markup Language).
-
-\begin{classdesc}{XMLParser}{}
-The \class{XMLParser} class must be instantiated without
-arguments.\footnote{Actually, a number of keyword arguments are
-recognized which influence the parser to accept certain non-standard
-constructs.  The following keyword arguments are currently
-recognized.  The defaults for all of these is \code{0} (false) except
-for the last one for which the default is \code{1} (true).
-\var{accept_unquoted_attributes} (accept certain attribute values
-without requiring quotes), \var{accept_missing_endtag_name} (accept
-end tags that look like \code{</>}), \var{map_case} (map upper case to
-lower case in tags and attributes), \var{accept_utf8} (allow UTF-8
-characters in input; this is required according to the XML standard,
-but Python does not as yet deal properly with these characters, so
-this is not the default), \var{translate_attribute_references} (don't
-attempt to translate character and entity references in attribute values).}
-\end{classdesc}
-
-This class provides the following interface methods and instance variables:
-
-\begin{memberdesc}{attributes}
-A mapping of element names to mappings.  The latter mapping maps
-attribute names that are valid for the element to the default value of 
-the attribute, or if there is no default to \code{None}.  The default
-value is the empty dictionary.  This variable is meant to be
-overridden, not extended since the default is shared by all instances
-of \class{XMLParser}.
-\end{memberdesc}
-
-\begin{memberdesc}{elements} 
-A mapping of element names to tuples.  The tuples contain a function
-for handling the start and end tag respectively of the element, or
-\code{None} if the method \method{unknown_starttag()} or
-\method{unknown_endtag()} is to be called.  The default value is the
-empty dictionary.  This variable is meant to be overridden, not
-extended since the default is shared by all instances of
-\class{XMLParser}.
-\end{memberdesc}
-
-\begin{memberdesc}{entitydefs}
-A mapping of entitynames to their values.  The default value contains
-definitions for \code{'lt'}, \code{'gt'}, \code{'amp'}, \code{'quot'}, 
-and \code{'apos'}.
-\end{memberdesc}
-
-\begin{methoddesc}{reset}{}
-Reset the instance.  Loses all unprocessed data.  This is called
-implicitly at the instantiation time.
-\end{methoddesc}
-
-\begin{methoddesc}{setnomoretags}{}
-Stop processing tags.  Treat all following input as literal input
-(CDATA).
-\end{methoddesc}
-
-\begin{methoddesc}{setliteral}{}
-Enter literal mode (CDATA mode).  This mode is automatically exited
-when the close tag matching the last unclosed open tag is encountered.
-\end{methoddesc}
-
-\begin{methoddesc}{feed}{data}
-Feed some text to the parser.  It is processed insofar as it consists
-of complete tags; incomplete data is buffered until more data is
-fed or \method{close()} is called.
-\end{methoddesc}
-
-\begin{methoddesc}{close}{}
-Force processing of all buffered data as if it were followed by an
-end-of-file mark.  This method may be redefined by a derived class to
-define additional processing at the end of the input, but the
-redefined version should always call \method{close()}.
-\end{methoddesc}
-
-\begin{methoddesc}{translate_references}{data}
-Translate all entity and character references in \var{data} and
-return the translated string.
-\end{methoddesc}
-
-\begin{methoddesc}{getnamespace}{}
-Return a mapping of namespace abbreviations to namespace URIs that are
-currently in effect.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_xml}{encoding, standalone}
-This method is called when the \samp{<?xml ...?>} tag is processed.
-The arguments are the values of the encoding and standalone attributes 
-in the tag.  Both encoding and standalone are optional.  The values
-passed to \method{handle_xml()} default to \code{None} and the string
-\code{'no'} respectively.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_doctype}{tag, pubid, syslit, data}
-This\index{DOCTYPE declaration} method is called when the
-\samp{<!DOCTYPE...>} declaration is processed.  The arguments are the
-tag name of the root element, the Formal Public\index{Formal Public
-Identifier} Identifier (or \code{None} if not specified), the system
-identifier, and the uninterpreted contents of the internal DTD subset
-as a string (or \code{None} if not present).
-\end{methoddesc}
-
-\begin{methoddesc}{handle_starttag}{tag, method, attributes}
-This method is called to handle start tags for which a start tag
-handler is defined in the instance variable \member{elements}.  The
-\var{tag} argument is the name of the tag, and the
-\var{method} argument is the function (method) which should be used to
-support semantic interpretation of the start tag.  The
-\var{attributes} argument is a dictionary of attributes, the key being
-the \var{name} and the value being the \var{value} of the attribute
-found inside the tag's \code{<>} brackets.  Character and entity
-references in the \var{value} have been interpreted.  For instance,
-for the start tag \code{<A HREF="http://www.cwi.nl/">}, this method
-would be called as \code{handle_starttag('A', self.elements['A'][0],
-\{'HREF': 'http://www.cwi.nl/'\})}.  The base implementation simply
-calls \var{method} with \var{attributes} as the only argument.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_endtag}{tag, method}
-This method is called to handle endtags for which an end tag handler
-is defined in the instance variable \member{elements}.  The \var{tag}
-argument is the name of the tag, and the \var{method} argument is the
-function (method) which should be used to support semantic
-interpretation of the end tag.  For instance, for the endtag
-\code{</A>}, this method would be called as \code{handle_endtag('A',
-self.elements['A'][1])}.  The base implementation simply calls
-\var{method}.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_data}{data}
-This method is called to process arbitrary data.  It is intended to be
-overridden by a derived class; the base class implementation does
-nothing.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_charref}{ref}
-This method is called to process a character reference of the form
-\samp{\&\#\var{ref};}.  \var{ref} can either be a decimal number,
-or a hexadecimal number when preceded by an \character{x}.
-In the base implementation, \var{ref} must be a number in the
-range 0-255.  It translates the character to \ASCII{} and calls the
-method \method{handle_data()} with the character as argument.  If
-\var{ref} is invalid or out of range, the method
-\code{unknown_charref(\var{ref})} is called to handle the error.  A
-subclass must override this method to provide support for character
-references outside of the \ASCII{} range.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_comment}{comment}
-This method is called when a comment is encountered.  The
-\var{comment} argument is a string containing the text between the
-\samp{<!--} and \samp{-->} delimiters, but not the delimiters
-themselves.  For example, the comment \samp{<!--text-->} will
-cause this method to be called with the argument \code{'text'}.  The
-default method does nothing.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_cdata}{data}
-This method is called when a CDATA element is encountered.  The
-\var{data} argument is a string containing the text between the
-\samp{<![CDATA[} and \samp{]]>} delimiters, but not the delimiters
-themselves.  For example, the entity \samp{<![CDATA[text]]>} will
-cause this method to be called with the argument \code{'text'}.  The
-default method does nothing, and is intended to be overridden.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_proc}{name, data}
-This method is called when a processing instruction (PI) is
-encountered.  The \var{name} is the PI target, and the \var{data}
-argument is a string containing the text between the PI target and the
-closing delimiter, but not the delimiter itself.  For example, the
-instruction \samp{<?XML text?>} will cause this method to be called
-with the arguments \code{'XML'} and \code{'text'}.  The default method
-does nothing.  Note that if a document starts with \samp{<?xml
-..?>}, \method{handle_xml()} is called to handle it.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_special}{data}
-This method is called when a declaration is encountered.  The
-\var{data} argument is a string containing the text between the
-\samp{<!} and \samp{>} delimiters, but not the delimiters
-themselves.  For example, the \index{ENTITY declaration}entity
-declaration \samp{<!ENTITY text>} will cause this method to be called
-with the argument \code{'ENTITY text'}.  The default method does
-nothing.  Note that \samp{<!DOCTYPE ...>} is handled separately if it
-is located at the start of the document.
-\end{methoddesc}
-
-\begin{methoddesc}{syntax_error}{message}
-This method is called when a syntax error is encountered.  The
-\var{message} is a description of what was wrong.  The default method 
-raises a \exception{RuntimeError} exception.  If this method is
-overridden, it is permissible for it to return.  This method is only
-called when the error can be recovered from.  Unrecoverable errors
-raise a \exception{RuntimeError} without first calling
-\method{syntax_error()}.
-\end{methoddesc}
-
-\begin{methoddesc}{unknown_starttag}{tag, attributes}
-This method is called to process an unknown start tag.  It is intended
-to be overridden by a derived class; the base class implementation
-does nothing.
-\end{methoddesc}
-
-\begin{methoddesc}{unknown_endtag}{tag}
-This method is called to process an unknown end tag.  It is intended
-to be overridden by a derived class; the base class implementation
-does nothing.
-\end{methoddesc}
-
-\begin{methoddesc}{unknown_charref}{ref}
-This method is called to process unresolvable numeric character
-references.  It is intended to be overridden by a derived class; the
-base class implementation does nothing.
-\end{methoddesc}
-
-\begin{methoddesc}{unknown_entityref}{ref}
-This method is called to process an unknown entity reference.  It is
-intended to be overridden by a derived class; the base class
-implementation calls \method{syntax_error()} to signal an error.
-\end{methoddesc}
-
-
-\begin{seealso}
-  \seetitle[http://www.w3.org/TR/REC-xml]{Extensible Markup Language
-            (XML) 1.0}{The XML specification, published by the World
-            Wide Web Consortium (W3C), defines the syntax and
-            processor requirements for XML.  References to additional
-            material on XML, including translations of the
-            specification, are available at
-            \url{http://www.w3.org/XML/}.}
-
-  \seetitle[http://www.python.org/topics/xml/]{Python and XML
-            Processing}{The Python XML Topic Guide provides a great
-            deal of information on using XML from Python and links to
-            other sources of information on XML.}
-
-  \seetitle[http://www.python.org/sigs/xml-sig/]{SIG for XML
-            Processing in Python}{The Python XML Special Interest
-            Group is developing substantial support for processing XML
-            from Python.}
-\end{seealso}
-
-
-\subsection{XML Namespaces \label{xml-namespace}}
-
-This module has support for XML namespaces as defined in the XML
-Namespaces proposed recommendation.
-\indexii{XML}{namespaces}
-
-Tag and attribute names that are defined in an XML namespace are
-handled as if the name of the tag or element consisted of the
-namespace (the URL that defines the namespace) followed by a
-space and the name of the tag or attribute.  For instance, the tag
-\code{<html xmlns='http://www.w3.org/TR/REC-html40'>} is treated as if 
-the tag name was \code{'http://www.w3.org/TR/REC-html40 html'}, and
-the tag \code{<html:a href='http://frob.com'>} inside the above
-mentioned element is treated as if the tag name were
-\code{'http://www.w3.org/TR/REC-html40 a'} and the attribute name as
-if it were \code{'http://www.w3.org/TR/REC-html40 href'}.
-
-An older draft of the XML Namespaces proposal is also recognized, but
-triggers a warning.
-
-\begin{seealso}
-  \seetitle[http://www.w3.org/TR/REC-xml-names/]{Namespaces in XML}{
-           This World Wide Web Consortium recommendation describes the
-           proper syntax and processing requirements for namespaces in
-           XML.}
-\end{seealso}

Modified: python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libxmlrpclib.tex	Wed Jul 11 15:40:56 2007
@@ -134,12 +134,12 @@
 Servers that support the XML introspection API support some common
 methods grouped under the reserved \member{system} member:
 
-\begin{methoddesc}{system.listMethods}{}
+\begin{methoddesc}[ServerProxy]{system.listMethods}{}
 This method returns a list of strings, one for each (non-system)
 method supported by the XML-RPC server.
 \end{methoddesc}
 
-\begin{methoddesc}{system.methodSignature}{name}
+\begin{methoddesc}[ServerProxy]{system.methodSignature}{name}
 This method takes one parameter, the name of a method implemented by
 the XML-RPC server.It returns an array of possible signatures for this
 method. A signature is an array of types. The first of these types is
@@ -159,7 +159,7 @@
 value will be something other that list.
 \end{methoddesc}
 
-\begin{methoddesc}{system.methodHelp}{name}
+\begin{methoddesc}[ServerProxy]{system.methodHelp}{name}
 This method takes one parameter, the name of a method implemented by
 the XML-RPC server.  It returns a documentation string describing the
 use of that method. If no such string is available, an empty string is
@@ -184,7 +184,7 @@
 It also has the following method, supported mainly for internal use by
 the unmarshalling code:
 
-\begin{methoddesc}{encode}{out}
+\begin{methoddesc}[Boolean]{encode}{out}
 Write the XML-RPC encoding of this Boolean item to the out stream object.
 \end{methoddesc}
 
@@ -197,11 +197,11 @@
 instance.  It has the following methods, supported mainly for internal use
 by the marshalling/unmarshalling code:
 
-\begin{methoddesc}{decode}{string}
+\begin{methoddesc}[DateTime]{decode}{string}
 Accept a string as the instance's new time value.
 \end{methoddesc}
 
-\begin{methoddesc}{encode}{out}
+\begin{methoddesc}[DateTime]{encode}{out}
 Write the XML-RPC encoding of this \class{DateTime} item to the
 \var{out} stream object.
 \end{methoddesc}
@@ -242,11 +242,11 @@
 A \class{Fault} object encapsulates the content of an XML-RPC fault tag.
 Fault objects have the following members:
 
-\begin{memberdesc}{faultCode}
+\begin{memberdesc}[Fault]{faultCode}
 A string indicating the fault type.
 \end{memberdesc}
 
-\begin{memberdesc}{faultString}
+\begin{memberdesc}[Fault]{faultString}
 A string containing a diagnostic message associated with the fault.
 \end{memberdesc}
 
@@ -258,19 +258,19 @@
 server named by the URI does not exist).  It has the following
 members:
 
-\begin{memberdesc}{url}
+\begin{memberdesc}[ProtocolError]{url}
 The URI or URL that triggered the error.
 \end{memberdesc}
 
-\begin{memberdesc}{errcode}
+\begin{memberdesc}[ProtocolError]{errcode}
 The error code.
 \end{memberdesc}
 
-\begin{memberdesc}{errmsg}
+\begin{memberdesc}[ProtocolError]{errmsg}
 The error message or diagnostic string.
 \end{memberdesc}
 
-\begin{memberdesc}{headers}
+\begin{memberdesc}[ProtocolError]{headers}
 A string containing the headers of the HTTP/HTTPS request that
 triggered the error.
 \end{memberdesc}
@@ -287,7 +287,7 @@
 
 Create an object used to boxcar method calls. \var{server} is the
 eventual target of the call. Calls can be made to the result object,
-but they will immediately return \var{None}, and only store the
+but they will immediately return \code{None}, and only store the
 call name and parameters in the \class{MultiCall} object. Calling
 the object itself causes all stored calls to be transmitted as
 a single \code{system.multicall} request. The result of this call

Modified: python/branches/p3yk-noslice/Doc/lib/libzipfile.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libzipfile.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libzipfile.tex	Wed Jul 11 15:40:56 2007
@@ -141,6 +141,34 @@
   Return a list of archive members by name.
 \end{methoddesc}
 
+\begin{methoddesc}{open}{name\optional{, mode\optional{, pwd}}}
+    Extract a member from the archive as a file-like object (ZipExtFile).
+    \var{name} is the name of the file in the archive. The \var{mode}
+    parameter, if included, must be one of the following: \code{'r'} (the 
+    default), \code{'U'}, or \code{'rU'}. Choosing \code{'U'} or 
+    \code{'rU'} will enable universal newline support in the read-only
+    object. \var{pwd} is the password used for encrypted files.
+    \begin{notice}
+        The file-like object is read-only and provides the following methods:
+        \method{read()}, \method{readline()}, \method{readlines()},
+        \method{__iter__()}, \method{next()}. 
+    \end{notice}
+    \begin{notice}
+        If the ZipFile was created by passing in a file-like object as the 
+        first argument to the constructor, then the object returned by
+        \method{open()} shares the ZipFile's file pointer.  Under these 
+        circumstances, the object returned by \method{open()} should not 
+        be used after any additional operations are performed on the 
+        ZipFile object.  If the ZipFile was created by passing in a string
+        (the filename) as the first argument to the constructor, then 
+        \method{open()} will create a new file object that will be held
+        by the ZipExtFile, allowing it to operate independently of the 
+        ZipFile.
+    \end{notice}
+
+    \versionadded{2.6}
+\end{methoddesc}
+
 \begin{methoddesc}{printdir}{}
   Print a table of contents for the archive to \code{sys.stdout}.
 \end{methoddesc}

Modified: python/branches/p3yk-noslice/Doc/lib/libzipimport.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libzipimport.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libzipimport.tex	Wed Jul 11 15:40:56 2007
@@ -29,11 +29,6 @@
 if a ZIP archive doesn't contain \file{.pyc} files, importing may be rather
 slow.
 
-Using the built-in \function{reload()} function will
-fail if called on a module loaded from a ZIP archive; it is unlikely that
-\function{reload()} would be needed, since this would imply that the ZIP
-has been altered during runtime.
-
 The available attributes of this module are:
 
 \begin{excdesc}{ZipImportError}

Modified: python/branches/p3yk-noslice/Doc/lib/libzlib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libzlib.tex	(original)
+++ python/branches/p3yk-noslice/Doc/lib/libzlib.tex	Wed Jul 11 15:40:56 2007
@@ -131,7 +131,7 @@
 
 Decompression objects support the following methods, and two attributes:
 
-\begin{memberdesc}{unused_data}
+\begin{memberdesc}[Decompress]{unused_data}
 A string which contains any bytes past the end of the compressed data.
 That is, this remains \code{""} until the last byte that contains
 compression data is available.  If the whole string turned out to
@@ -145,7 +145,7 @@
 \member{unused_data} attribute is no longer the empty string.
 \end{memberdesc}
 
-\begin{memberdesc}{unconsumed_tail}
+\begin{memberdesc}[Decompress]{unconsumed_tail}
 A string that contains any data that was not consumed by the last
 \method{decompress} call because it exceeded the limit for the
 uncompressed data buffer.  This data has not yet been seen by the zlib

Modified: python/branches/p3yk-noslice/Doc/lib/sqlite3/executemany_1.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/sqlite3/executemany_1.py	(original)
+++ python/branches/p3yk-noslice/Doc/lib/sqlite3/executemany_1.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         if self.count > ord('z'):
             raise StopIteration
         self.count += 1

Modified: python/branches/p3yk-noslice/Doc/mac/libframework.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/mac/libframework.tex	(original)
+++ python/branches/p3yk-noslice/Doc/mac/libframework.tex	Wed Jul 11 15:40:56 2007
@@ -189,8 +189,6 @@
 
 Window objects have the following methods, among others:
 
-\setindexsubitem{(Window method)}
-
 \begin{methoddesc}[Window]{open}{}
 Override this method to open a window. Store the MacOS window-id in
 \member{self.wid} and call the \method{do_postopen()} method to
@@ -218,7 +216,7 @@
 An update event for the window was received. Redraw the window.
 \end{methoddesc}
 
-\begin{methoddesc}{do_activate}{activate, event}
+\begin{methoddesc}[Window]{do_activate}{activate, event}
 The window was activated (\code{\var{activate} == 1}) or deactivated
 (\code{\var{activate} == 0}). Handle things like focus highlighting,
 etc.

Deleted: /python/branches/p3yk-noslice/Doc/mac/libmacfs.tex
==============================================================================
--- /python/branches/p3yk-noslice/Doc/mac/libmacfs.tex	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,241 +0,0 @@
-\section{\module{macfs} ---
-         Various file system services}
-
-\declaremodule{standard}{macfs}
-  \platform{Mac}
-\modulesynopsis{Support for FSSpec, the Alias Manager,
-                \program{finder} aliases, and the Standard File package.}
-
-\deprecated{2.3}{The macfs module should be considered obsolete. For
-\class{FSSpec}, \class{FSRef} and \class{Alias} handling use the
-\module{Carbon.File} or \refmodule{Carbon.Folder} module. For file
-dialogs use the \refmodule{EasyDialogs} module.  Also, this module is
-known to not work correctly with UFS partitions.}
-
-This module provides access to Macintosh \class{FSSpec} handling, the
-Alias Manager, \program{finder} aliases and the Standard File package.
-\index{Macintosh Alias Manager}
-\index{Alias Manager, Macintosh}
-\index{Standard File}
-
-Whenever a function or method expects a \var{file} argument, this
-argument can be one of three things:\ (1) a full or partial Macintosh
-pathname, (2) an \class{FSSpec} object or (3) a 3-tuple
-\code{(\var{wdRefNum}, \var{parID}, \var{name})} as described in
-\citetitle{Inside Macintosh:\ Files}.  An \class{FSSpec} can point to
-a non-existing file, as long as the folder containing the file exists.
-Under MacPython the same is true for a pathname, but not under \UNIX-Python
-because of the way pathnames and FSRefs works.  See Apple's documentation
-for details.
-
-A description of aliases and the
-Standard File package can also be found there.
-
-\begin{funcdesc}{FSSpec}{file}
-Create an \class{FSSpec} object for the specified file.
-\end{funcdesc}
-
-\begin{funcdesc}{RawFSSpec}{data}
-Create an \class{FSSpec} object given the raw data for the \C{}
-structure for the \class{FSSpec} as a string.  This is mainly useful
-if you have obtained an \class{FSSpec} structure over a network.
-\end{funcdesc}
-
-\begin{funcdesc}{RawAlias}{data}
-Create an \class{Alias} object given the raw data for the \C{}
-structure for the alias as a string.  This is mainly useful if you
-have obtained an \class{FSSpec} structure over a network.
-\end{funcdesc}
-
-\begin{funcdesc}{FInfo}{}
-Create a zero-filled \class{FInfo} object.
-\end{funcdesc}
-
-\begin{funcdesc}{ResolveAliasFile}{file}
-Resolve an alias file. Returns a 3-tuple \code{(\var{fsspec},
-\var{isfolder}, \var{aliased})} where \var{fsspec} is the resulting
-\class{FSSpec} object, \var{isfolder} is true if \var{fsspec} points
-to a folder and \var{aliased} is true if the file was an alias in the
-first place (otherwise the \class{FSSpec} object for the file itself
-is returned).
-\end{funcdesc}
-
-\begin{funcdesc}{StandardGetFile}{\optional{type, \moreargs}}
-Present the user with a standard ``open input file''
-dialog. Optionally, you can pass up to four 4-character file types to limit
-the files the user can choose from. The function returns an \class{FSSpec}
-object and a flag indicating that the user completed the dialog
-without cancelling.
-\end{funcdesc}
-
-\begin{funcdesc}{PromptGetFile}{prompt\optional{, type, \moreargs}}
-Similar to \function{StandardGetFile()} but allows you to specify a
-prompt which will be displayed at the top of the dialog.
-\end{funcdesc}
-
-\begin{funcdesc}{StandardPutFile}{prompt\optional{, default}}
-Present the user with a standard ``open output file''
-dialog. \var{prompt} is the prompt string, and the optional
-\var{default} argument initializes the output file name. The function
-returns an \class{FSSpec} object and a flag indicating that the user
-completed the dialog without cancelling.
-\end{funcdesc}
-
-\begin{funcdesc}{GetDirectory}{\optional{prompt}}
-Present the user with a non-standard ``select a directory'' dialog.  You
-have to first open the directory before clicking on the ``select current
-directory'' button. \var{prompt} is the prompt string which will be
-displayed at the top of the dialog. Return an \class{FSSpec} object and
-a success-indicator.
-\end{funcdesc}
-
-\begin{funcdesc}{SetFolder}{\optional{fsspec}}
-Set the folder that is initially presented to the user when one of
-the file selection dialogs is presented. \var{fsspec} should point to
-a file in the folder, not the folder itself (the file need not exist,
-though). If no argument is passed the folder will be set to the
-current directory, i.e. what \function{os.getcwd()} returns.
-
-Note that starting with System 7.5 the user can change Standard File
-behaviour with the ``general controls'' control panel, thereby making
-this call inoperative.
-\end{funcdesc}
-
-\begin{funcdesc}{FindFolder}{where, which, create}
-Locates one of the ``special'' folders that Mac OS knows about, such as
-the trash or the Preferences folder. \var{where} is the disk to
-search, \var{which} is the 4-character string specifying which folder to
-locate. Setting \var{create} causes the folder to be created if it
-does not exist. Returns a \code{(\var{vrefnum}, \var{dirid})} tuple.
-
-The constants for \var{where} and \var{which} can be obtained from the
-standard module \var{Carbon.Folders}.
-\end{funcdesc}
-
-\begin{funcdesc}{NewAliasMinimalFromFullPath}{pathname}
-Return a minimal \class{alias} object that points to the given file, which
-must be specified as a full pathname. This is the only way to create an
-\class{Alias} pointing to a non-existing file.
-
-\end{funcdesc}
-
-\begin{funcdesc}{FindApplication}{creator}
-Locate the application with 4-character creator code \var{creator}. The
-function returns an \class{FSSpec} object pointing to the application.
-\end{funcdesc}
-
-
-\subsection{FSSpec Objects \label{fsspec-objects}}
-
-\begin{memberdesc}[FSSpec]{data}
-The raw data from the FSSpec object, suitable for passing
-to other applications, for instance.
-\end{memberdesc}
-
-\begin{methoddesc}[FSSpec]{as_pathname}{}
-Return the full pathname of the file described by the \class{FSSpec}
-object.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{as_tuple}{}
-Return the \code{(\var{wdRefNum}, \var{parID}, \var{name})} tuple of
-the file described by the \class{FSSpec} object.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{NewAlias}{\optional{file}}
-Create an Alias object pointing to the file described by this
-FSSpec. If the optional \var{file} parameter is present the alias
-will be relative to that file, otherwise it will be absolute.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{NewAliasMinimal}{}
-Create a minimal alias pointing to this file.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{GetCreatorType}{}
-Return the 4-character creator and type of the file.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{SetCreatorType}{creator, type}
-Set the 4-character creator and type of the file.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{GetFInfo}{}
-Return a \class{FInfo} object describing the finder info for the file.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{SetFInfo}{finfo}
-Set the finder info for the file to the values given as \var{finfo}
-(an \class{FInfo} object).
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{GetDates}{}
-Return a tuple with three floating point values representing the
-creation date, modification date and backup date of the file.
-\end{methoddesc}
-
-\begin{methoddesc}[FSSpec]{SetDates}{crdate, moddate, backupdate}
-Set the creation, modification and backup date of the file. The values
-are in the standard floating point format used for times throughout
-Python.
-\end{methoddesc}
-
-
-\subsection{Alias Objects \label{alias-objects}}
-
-\begin{memberdesc}[Alias]{data}
-The raw data for the Alias record, suitable for storing in a resource
-or transmitting to other programs.
-\end{memberdesc}
-
-\begin{methoddesc}[Alias]{Resolve}{\optional{file}}
-Resolve the alias. If the alias was created as a relative alias you
-should pass the file relative to which it is. Return the FSSpec for
-the file pointed to and a flag indicating whether the \class{Alias} object
-itself was modified during the search process. If the file does
-not exist but the path leading up to it does exist a valid fsspec
-is returned.
-\end{methoddesc}
-
-\begin{methoddesc}[Alias]{GetInfo}{num}
-An interface to the \C{} routine \cfunction{GetAliasInfo()}.
-\end{methoddesc}
-
-\begin{methoddesc}[Alias]{Update}{file\optional{, file2}}
-Update the alias to point to the \var{file} given. If \var{file2} is
-present a relative alias will be created.
-\end{methoddesc}
-
-Note that it is currently not possible to directly manipulate a
-resource as an \class{Alias} object. Hence, after calling
-\method{Update()} or after \method{Resolve()} indicates that the alias
-has changed the Python program is responsible for getting the
-\member{data} value from the \class{Alias} object and modifying the
-resource.
-
-
-\subsection{FInfo Objects \label{finfo-objects}}
-
-See \citetitle{Inside Macintosh: Files} for a complete description of what
-the various fields mean.
-
-\begin{memberdesc}[FInfo]{Creator}
-The 4-character creator code of the file.
-\end{memberdesc}
-
-\begin{memberdesc}[FInfo]{Type}
-The 4-character type code of the file.
-\end{memberdesc}
-
-\begin{memberdesc}[FInfo]{Flags}
-The finder flags for the file as 16-bit integer. The bit values in
-\var{Flags} are defined in standard module \module{MACFS}.
-\end{memberdesc}
-
-\begin{memberdesc}[FInfo]{Location}
-A Point giving the position of the file's icon in its folder.
-\end{memberdesc}
-
-\begin{memberdesc}[FInfo]{Fldr}
-The folder the file is in (as an integer).
-\end{memberdesc}

Modified: python/branches/p3yk-noslice/Doc/mac/libmacic.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/mac/libmacic.tex	(original)
+++ python/branches/p3yk-noslice/Doc/mac/libmacic.tex	Wed Jul 11 15:40:56 2007
@@ -68,14 +68,14 @@
 following methods:
 
 
-\begin{methoddesc}{launchurl}{url\optional{, hint}}
+\begin{methoddesc}[IC]{launchurl}{url\optional{, hint}}
 Parse the given URL, launch the correct application and pass it the
 URL. The optional \var{hint} can be a scheme name such as
 \code{'mailto:'}, in which case incomplete URLs are completed with this
 scheme.  If \var{hint} is not provided, incomplete URLs are invalid.
 \end{methoddesc}
 
-\begin{methoddesc}{parseurl}{data\optional{, start\optional{, end\optional{, hint}}}}
+\begin{methoddesc}[IC]{parseurl}{data\optional{, start\optional{, end\optional{, hint}}}}
 Find an URL somewhere in \var{data} and return start position, end
 position and the URL. The optional \var{start} and \var{end} can be
 used to limit the search, so for instance if a user clicks in a long
@@ -85,7 +85,7 @@
 complete incomplete URLs.
 \end{methoddesc}
 
-\begin{methoddesc}{mapfile}{file}
+\begin{methoddesc}[IC]{mapfile}{file}
 Return the mapping entry for the given \var{file}, which can be passed
 as either a filename or an \function{FSSpec()} result, and which
 need not exist.
@@ -106,7 +106,7 @@
 file and \var{entryname} is the name of this entry.
 \end{methoddesc}
 
-\begin{methoddesc}{maptypecreator}{type, creator\optional{, filename}}
+\begin{methoddesc}[IC]{maptypecreator}{type, creator\optional{, filename}}
 Return the mapping entry for files with given 4-character \var{type} and
 \var{creator} codes. The optional \var{filename} may be specified to
 further help finding the correct entry (if the creator code is
@@ -115,7 +115,7 @@
 The mapping entry is returned in the same format as for \var{mapfile}.
 \end{methoddesc}
 
-\begin{methoddesc}{settypecreator}{file}
+\begin{methoddesc}[IC]{settypecreator}{file}
 Given an existing \var{file}, specified either as a filename or as an
 \function{FSSpec()} result, set its creator and type correctly based
 on its extension.  The finder is told about the change, so the finder

Modified: python/branches/p3yk-noslice/Doc/mac/libmacostools.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/mac/libmacostools.tex	(original)
+++ python/branches/p3yk-noslice/Doc/mac/libmacostools.tex	Wed Jul 11 15:40:56 2007
@@ -39,6 +39,7 @@
 or type for file \var{dst} has changed. The file can be specified by
 pathname or fsspec. This call should tell the finder to redraw the
 files icon.
+\deprecated{2.6}{The function is a no-op on OS X.}
 \end{funcdesc}
 
 \begin{datadesc}{BUFSIZ}

Modified: python/branches/p3yk-noslice/Doc/mac/mac.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/mac/mac.tex	(original)
+++ python/branches/p3yk-noslice/Doc/mac/mac.tex	Wed Jul 11 15:40:56 2007
@@ -51,7 +51,6 @@
 \localmoduletable
 
 \input{libmac}
-\input{libmacfs}
 \input{libmacic}
 \input{libmacos}
 \input{libmacostools}

Modified: python/branches/p3yk-noslice/Doc/mac/undoc.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/mac/undoc.tex	(original)
+++ python/branches/p3yk-noslice/Doc/mac/undoc.tex	Wed Jul 11 15:40:56 2007
@@ -21,19 +21,7 @@
 \modulesynopsis{Helper module for BuildApplet, BuildApplication and
                 macfreeze.}
 
-\deprecated{2.4}
-
-\section{\module{cfmfile} --- Code Fragment Resource module}
-\declaremodule{standard}{cfmfile}
-  \platform{Mac}
-\modulesynopsis{Code Fragment Resource module.}
-
-\module{cfmfile} is a module that understands Code Fragments and the
-accompanying ``cfrg'' resources. It can parse them and merge them, and is
-used by BuildApplication to combine all plugin modules to a single
-executable.
-
-\deprecated{2.4}
+\deprecated{2.4}{}
 
 \section{\module{icopen} --- Internet Config replacement for \method{open()}}
 \declaremodule{standard}{icopen}

Modified: python/branches/p3yk-noslice/Doc/mac/using.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/mac/using.tex	(original)
+++ python/branches/p3yk-noslice/Doc/mac/using.tex	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 \sectionauthor{Bob Savage}{bobsavage at mac.com}
 
 Python on a Macintosh running Mac OS X is in principle very similar to
-Python on any other \UNIX platform, but there are a number of additional
+Python on any other \UNIX{} platform, but there are a number of additional
 features such as the IDE and the Package Manager that are worth pointing out.
 
 Python on Mac OS 9 or earlier can be quite different from Python on
@@ -13,206 +13,166 @@
 
 \section{Getting and Installing MacPython \label{getting-OSX}}
 
-Mac OS X 10.3 comes with Python 2.3 pre-installed by Apple.
-This installation does not come with the IDE and other additions, however,
-so to get these you need to install the \program{MacPython for Panther additions}
-from the MacPython website, \url{http://www.cwi.nl/\textasciitilde jack/macpython}.
-
-For MacPython 2.4, or for any MacPython on earlier releases of Mac OS X,
-you need to install a full distribution from the same website.
+Mac OS X 10.4 comes with Python 2.3 pre-installed by Apple. However, you are
+encouraged to install the most recent version of Python from the Python website
+(\url{http://www.python.org}). A ``universal binary'' build of Python 2.5, which
+runs natively on the Mac's new Intel and legacy PPC CPU's, is available there.
 
 What you get after installing is a number of things:
 
 \begin{itemize}
-    \item A \file{MacPython-2.3} folder in your \file{Applications}
-    folder. In here you find the PythonIDE Integrated Development Environment;
-    PythonLauncher, which handles double-clicking Python scripts from
-    the Finder; and the Package Manager.
-    
-    \item A fairly standard \UNIX{} commandline Python interpreter in
-    \file{/usr/local/bin/python}, but without the usual
-    \file{/usr/local/lib/python}.
-    
-    \item A framework \file{/Library/Frameworks/Python.framework}, where
-    all the action really is, but which you usually do not have to be aware of.
+\item A \file{MacPython 2.5} folder in your \file{Applications} folder. In here
+  you find IDLE, the development environment that is a standard part of official
+  Python distributions; PythonLauncher, which handles double-clicking Python
+  scripts from the Finder; and the ``Build Applet'' tool, which allows you to
+  package Python scripts as standalone applications on your system.
+
+\item A framework \file{/Library/Frameworks/Python.framework}, which includes
+  the Python executable and libraries. The installer adds this location to your
+  shell path. To uninstall MacPython, you can simply remove these three
+  things. A symlink to the Python executable is placed in /usr/local/bin/.
 \end{itemize}
 
-To uninstall MacPython you can simply remove these three things.
+The Apple-provided build of Python is installed in
+\file{/System/Library/Frameworks/Python.framework} and \file{/usr/bin/python},
+respectively. You should never modify or delete these, as they are
+Apple-controlled and are used by Apple- or third-party software.
+
+IDLE includes a help menu that allows you to access Python documentation. If you
+are completely new to Python you should start reading the tutorial introduction
+in that document.
 
-If you use the ``additions'' installer to install on top of an existing
-Apple-Python you will not get the framework and the commandline interpreter,
-as they have been installed by Apple already, in
-\file{/System/Library/Frameworks/Python.framework} and
-\file{/usr/bin/python}, respectively. You should in principle never modify
-or delete these, as they are Apple-controlled and may be used by Apple- or
-third-party software.
-
-PythonIDE contains an Apple Help Viewer book called "MacPython Help"
-which you can access through its help menu. If you are completely new to
-Python you should start reading the IDE introduction in that document.
+If you are familiar with Python on other \UNIX{} platforms you should read the
+section on running Python scripts from the \UNIX{} shell.
 
-If you are familiar with Python on other \UNIX{} platforms you should
-read the section on running Python scripts from the \UNIX{} shell.
 
 \subsection{How to run a Python script}
 
-Your best way to get started with Python on Mac OS X is through the PythonIDE
-integrated development environment, see section \ref{IDE} and use the Help
-menu when the IDE is running.
-
-If you want to run Python scripts from the Terminal window command line
-or from the Finder you first need an editor to create your script.
-Mac OS X comes with a number of standard \UNIX{} command line editors,
-\program{vim} and \program{emacs} among them. If you want a more Mac-like
-editor \program{BBEdit} or \program{TextWrangler} from Bare Bones Software
-(see \url{http://www.barebones.com/products/bbedit/index.shtml}) are
-good choices.  \program{AppleWorks} or any other
-word processor that can save files in ASCII is also a possibility, including
-\program{TextEdit} which is included with OS X.
+Your best way to get started with Python on Mac OS X is through the IDLE
+integrated development environment, see section \ref{IDE} and use the Help menu
+when the IDE is running.
+
+If you want to run Python scripts from the Terminal window command line or from
+the Finder you first need an editor to create your script. Mac OS X comes with a
+number of standard \UNIX{} command line editors, \program{vim} and
+\program{emacs} among them. If you want a more Mac-like editor, \program{BBEdit}
+or \program{TextWrangler} from Bare Bones Software (see
+\url{http://www.barebones.com/products/bbedit/index.shtml}) are good choices, as
+is \program{TextMate} (see \url{http://macromates.com/}). Other editors include
+\program{Gvim} (\url{http://macvim.org}) and \program{Aquamacs}
+(\url{http://aquamacs.org}).
 
 To run your script from the Terminal window you must make sure that
-\file{/usr/local/bin} is in your shell search path. 
+\file{/usr/local/bin} is in your shell search path.
 
 To run your script from the Finder you have two options:
+
 \begin{itemize}
-    \item Drag it to \program{PythonLauncher}
-    \item Select \program{PythonLauncher} as the default application
-    to open your script (or any .py script) through the finder Info window
-    and double-click it.
+\item Drag it to \program{PythonLauncher}
+\item Select \program{PythonLauncher} as the default application to open your
+  script (or any .py script) through the finder Info window and double-click it.
+  \program{PythonLauncher} has various preferences to control how your script is
+  launched. Option-dragging allows you to change these for one invocation, or
+  use its Preferences menu to change things globally.
 \end{itemize}
 
-PythonLauncher has various preferences to control how your script is launched.
-Option-dragging allows you to change these for one invocation, or use its
-Preferences menu to change things globally.
 
 \subsection{Running scripts with a GUI \label{osx-gui-scripts}}
 
-There is one Mac OS X quirk that you need to be aware of: programs
-that talk to the Aqua window manager (in other words, anything that has a GUI)
-need to be run in a special way. Use \program{pythonw} instead of \program{python}
-to start such scripts.
-
-\subsection{configuration}
-
-MacPython honours all standard \UNIX{} environment variables such as
-\envvar{PYTHONPATH}, but setting these variables for programs started
-from the Finder is non-standard
-as the Finder does not read your \file{.profile} or \file{.cshrc} at startup.
-You need to create a file \file{\textasciitilde /.MacOSX/environment.plist}.
-See Apple's Technical Document QA1067 for details.
+With older versions of Python, there is one Mac OS X quirk that you need to be
+aware of: programs that talk to the Aqua window manager (in other words,
+anything that has a GUI) need to be run in a special way. Use \program{pythonw}
+instead of \program{python} to start such scripts.
+
+With Python 2.5, you can use either \program{python} or \program{pythonw}.
+
+\subsection{Configuration}
+
+Python on OS X honors all standard \UNIX{} environment variables such as
+\envvar{PYTHONPATH}, but setting these variables for programs started from the
+Finder is non-standard as the Finder does not read your \file{.profile} or
+\file{.cshrc} at startup. You need to create a file \file{\textasciitilde
+  /.MacOSX/environment.plist}. See Apple's Technical Document QA1067 for
+details.
 
-Installing additional Python packages is most easily done through the
-Package Manager, see the MacPython Help Book for details.
+For more information on installation Python packages in MacPython, see section
+\ref{mac-package-manager}, ``Installing Additional Python Packages.''
 
 
 \section{The IDE\label{IDE}}
 
-The \program{Python IDE} (Integrated Development Environment) is a
-separate application that acts as a text editor for your Python code,
-a class browser, a graphical debugger, and more.
-
-The online Python Help contains a quick walkthrough of the IDE that
-shows the major features and how to use them.
-
-\subsection{Using the ``Python Interactive'' window}
-
-Use this window like you would use a normal \UNIX{} command line
-interpreter.
-
-\subsection{Writing a Python Script \label{IDEwrite}}
-
-In addition to using the \program{Python IDE} interactively, you can
-also type out a complete Python program, saving it incrementally, and
-execute it or smaller selections of it.
-
-You can create a new script, open a previously saved script, and save
-your currently open script by selecting the appropriate item in the
-``File'' menu. Dropping a Python script onto the
-\program{Python IDE} will open it for editing.
-
-When the \program{Python IDE} saves a script, it uses the creator code
-settings which are available by clicking on the small black triangle
-on the top right of the document window, and selecting ``save
-options''. The default is to save the file with the \program{Python
-IDE} as the creator, this means that you can open the file for editing
-by simply double-clicking on its icon. You might want to change this
-behaviour so that it will be opened by the
-\program{PythonLauncher}, and run. To do this simply choose
-``PythonLauncher'' from the ``save options''. Note that these
-options are associated with the \emph{file} not the application.
-
-
-\subsection{Executing a script from within the IDE
-            \label{IDEexecution}}
-
-You can run the script in the frontmost window of the \program{Python
-IDE} by hitting the run all button.  You should be aware, however that
-if you use the Python convention \samp{if __name__ == "__main__":} the
-script will \emph{not} be ``__main__'' by default. To get that
-behaviour you must select the ``Run as __main__'' option from the
-small black triangle on the top right of the document window.  Note
-that this option is associated with the \emph{file} not the
-application. It \emph{will} stay active after a save, however; to shut
-this feature off simply select it again.
- 
-
-\subsection{``Save as'' versus ``Save as Applet''
-            \label{IDEapplet}}
-
-When you are done writing your Python script you have the option of
-saving it as an ``applet'' (by selecting ``Save as applet'' from the
-``File'' menu). This has a significant advantage in that you can drop
-files or folders onto it, to pass them to the applet the way
-command-line users would type them onto the command-line to pass them
-as arguments to the script. However, you should make sure to save the
-applet as a separate file, do not overwrite the script you are
-writing, because you will not be able to edit it again.
-
-Accessing the items passed to the applet via ``drag-and-drop'' is done
-using the standard \member{sys.argv} mechanism. See the general
-documentation for more
-% need to link to the appropriate place in non-Mac docs
-
-Note that saving a script as an applet will not make it runnable on a
-system without a Python installation.
-
-%\subsection{Debugger}
-% **NEED INFO HERE**
- 
-%\subsection{Module Browser}
-% **NEED INFO HERE**
- 
-%\subsection{Profiler}
-% **NEED INFO HERE**
-% end IDE
-
-%\subsection{The ``Scripts'' menu}
-% **NEED INFO HERE**
-
-\section{The Package Manager}
-
-Historically MacPython came with a number of useful extension packages
-included, because most Macintosh users do not have access to a development
-environment and C compiler. For Mac OS X that bundling is no longer done,
-but a new mechanism has been made available to allow easy access to
-extension packages.
-
-The Python Package Manager helps you installing additional packages
-that enhance Python. It determines the exact MacOS version  and Python
-version you have and uses that information to download  a database that
-has packages that are tested and tried on that combination. In other
-words: if something is in your Package Manager  window but does not work
-you are free to blame the database maintainer.
-
-PackageManager then checks which of the packages you have installed  and
-which ones are not. This should also work when you have installed packages 
-outside of PackageManager.  You can select packages and install them,
-and PackageManager will work out the requirements and install these too.
-
-Often PackageManager will list a package in two flavors: binary  and
-source. Binary should always work, source will only work if  you have
-installed the Apple Developer Tools. PackageManager will warn  you about
-this, and also about other external dependencies.
+MacPython ships with the standard IDLE development environment. A good
+introduction to using IDLE can be found at
+\url{http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html}.
+
+
+\section{Installing Additional Python Packages \label{mac-package-manager}}
+
+There are several methods to install additional Python packages:
+
+\begin{itemize}
+\item \url{http://pythonmac.org/packages/} contains selected compiled packages
+  for Python 2.5, 2.4, and 2.3.
+\item Packages can be installed via the standard Python distutils mode
+  (\samp{python setup.py install}).
+\item Many packages can also be installed via the \program{setuptools}
+  extension.
+\end{itemize}
+
+
+\section{GUI Programming on the Mac}
+
+There are several options for building GUI applications on the Mac with Python.
+
+\emph{PyObjC} is a Python binding to Apple's Objective-C/Cocoa framework, which
+is the foundation of most modern Mac development. Information on PyObjC is
+available from \url{http://pybojc.sourceforge.net}.
+
+The standard Python GUI toolkit is \module{Tkinter}, based on the cross-platform
+Tk toolkit (\url{http://www.tcl.tk}). An Aqua-native version of Tk is bundled
+with OS X by Apple, and the latest version can be downloaded and installed from
+\url{http://www.activestate.com}; it can also be built from source.
+
+\emph{wxPython} is another popular cross-platform GUI toolkit that runs natively
+on Mac OS X. Packages and documentation are available from
+\url{http://www.wxpython.org}.
+
+\emph{PyQt} is another popular cross-platform GUI toolkit that runs natively on
+Mac OS X. More information can be found at
+\url{http://www.riverbankcomputing.co.uk/pyqt/}.
+
+
+\section{Distributing Python Applications on the Mac}
+
+The ``Build Applet'' tool that is placed in the MacPython 2.5 folder is fine for
+packaging small Python scripts on your own machine to run as a standard Mac
+application. This tool, however, is not robust enough to distribute Python
+applications to other users.
+
+The standard tool for deploying standalone Python applications on the Mac is
+\program{py2app}. More information on installing and using py2app can be found
+at \url{http://undefined.org/python/\#py2app}.
+
+\section{Application Scripting}
+
+Python can also be used to script other Mac applications via Apple's Open
+Scripting Architecture (OSA); see
+\url{http://appscript.sourceforge.net}. Appscript is a high-level, user-friendly
+Apple event bridge that allows you to control scriptable Mac OS X applications
+using ordinary Python scripts. Appscript makes Python a serious alternative to
+Apple's own \emph{AppleScript} language for automating your Mac. A related
+package, \emph{PyOSA}, is an OSA language component for the Python scripting
+language, allowing Python code to be executed by any OSA-enabled application
+(Script Editor, Mail, iTunes, etc.). PyOSA makes Python a full peer to
+AppleScript.
+
+\section{Other Resources}
+
+The MacPython mailing list is an excellent support resource for Python users and
+developers on the Mac:
+
+\url{http://www.python.org/community/sigs/current/pythonmac-sig/}
+
+Another useful resource is the MacPython wiki:
 
-PackageManager is available as a separate application and also  as a
-function of the IDE, through the File->Package Manager menu  entry.
+\url{http://wiki.python.org/moin/MacPython}

Modified: python/branches/p3yk-noslice/Doc/ref/ref1.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref1.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ref/ref1.tex	Wed Jul 11 15:40:56 2007
@@ -93,7 +93,7 @@
 \index{syntax}
 \index{notation}
 
-\begin{productionlist}
+\begin{productionlist}[*]
   \production{name}{\token{lc_letter} (\token{lc_letter} | "_")*}
   \production{lc_letter}{"a"..."z"}
 \end{productionlist}

Modified: python/branches/p3yk-noslice/Doc/ref/ref2.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref2.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ref/ref2.tex	Wed Jul 11 15:40:56 2007
@@ -565,6 +565,7 @@
 \index{floating point literal}
 \index{hexadecimal literal}
 \index{octal literal}
+\index{binary literal}
 \index{decimal literal}
 \index{imaginary literal}
 \index{complex!literal}
@@ -574,35 +575,32 @@
 `\code{-}' and the literal \code{1}.
 
 
-\subsection{Integer and long integer literals\label{integers}}
+\subsection{Integer literals\label{integers}}
 
-Integer and long integer literals are described by the following
+Integer literals are described by the following
 lexical definitions:
 
 \begin{productionlist}
-  \production{longinteger}
-             {\token{integer} ("l" | "L")}
   \production{integer}
              {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
   \production{decimalinteger}
-             {\token{nonzerodigit} \token{digit}* | "0"}
+             {\token{nonzerodigit} \token{digit}* | "0"+}
   \production{octinteger}
-             {"0" \token{octdigit}+}
+             {"0" ("o" | "O") \token{octdigit}+}
   \production{hexinteger}
              {"0" ("x" | "X") \token{hexdigit}+}
+  \production{bininteger}
+             {"0" ("b" | "B") \token{bindigit}+}
   \production{nonzerodigit}
              {"1"..."9"}
   \production{octdigit}
              {"0"..."7"}
   \production{hexdigit}
              {\token{digit} | "a"..."f" | "A"..."F"}
+  \production{bindigit}
+             {"0"..."1"}
 \end{productionlist}
 
-Although both lower case \character{l} and upper case \character{L} are
-allowed as suffix for long integers, it is strongly recommended to always
-use \character{L}, since the letter \character{l} looks too much like the
-digit \character{1}.
-
 Plain integer literals that are above the largest representable plain
 integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted
 as if they were long integers instead.\footnote{In versions of Python
@@ -613,13 +611,16 @@
 from their unsigned value.}  There is no limit for long integer
 literals apart from what can be stored in available memory.
 
-Some examples of plain integer literals (first row) and long integer
-literals (second and third rows):
+Note that leading zeros in a non-zero decimal number are not allowed.
+This is for disambiguation with C-style octal literals, which Python
+used before version 3.0.
+
+Some examples of integer literals:
 
 \begin{verbatim}
-7     2147483647                        0177
-3L    79228162514264337593543950336L    0377L   0x100000000L
-      79228162514264337593543950336             0xdeadbeef						    
+7     2147483647                        0o177    0b100110111
+3     79228162514264337593543950336     0o377    0x100000000
+      79228162514264337593543950336              0xdeadbeef						    
 \end{verbatim}
 
 
@@ -644,12 +645,10 @@
              {("e" | "E") ["+" | "-"] \token{digit}+}
 \end{productionlist}
 
-Note that the integer and exponent parts of floating point numbers
-can look like octal integers, but are interpreted using radix 10.  For
-example, \samp{077e010} is legal, and denotes the same number
-as \samp{77e10}.
-The allowed range of floating point literals is
-implementation-dependent.
+Note that the integer and exponent parts are always interpreted using
+radix 10.  For example, \samp{077e010} is legal, and denotes the same
+number as \samp{77e10}.
+The allowed range of floating point literals is implementation-dependent.
 Some examples of floating point literals:
 
 \begin{verbatim}

Modified: python/branches/p3yk-noslice/Doc/ref/ref3.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref3.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ref/ref3.tex	Wed Jul 11 15:40:56 2007
@@ -218,7 +218,7 @@
 \indexii{integer}{representation}
 
 \item[Floating point numbers]
-These represent machine-level double precision floating point numbers.  
+These represent machine-level double precision floating point numbers.
 You are at the mercy of the underlying machine architecture (and
 C or Java implementation) for the accepted range and handling of overflow.
 Python does not support single-precision floating point numbers; the
@@ -470,45 +470,46 @@
 \obindex{function}
 \obindex{user-defined function}
 
-Special attributes: 
+Special attributes:
 
 \begin{tableiii}{lll}{member}{Attribute}{Meaning}{}
-  \lineiii{func_doc}{The function's documentation string, or
+  \lineiii{__doc__}{The function's documentation string, or
     \code{None} if unavailable}{Writable}
 
-  \lineiii{__doc__}{Another way of spelling
-    \member{func_doc}}{Writable}
-
-  \lineiii{func_name}{The function's name}{Writable}
-
-  \lineiii{__name__}{Another way of spelling
-    \member{func_name}}{Writable}
+  \lineiii{__name__}{The function's name}{Writable}
 
   \lineiii{__module__}{The name of the module the function was defined
     in, or \code{None} if unavailable.}{Writable}
 
-  \lineiii{func_defaults}{A tuple containing default argument values
+  \lineiii{__defaults__}{A tuple containing default argument values
     for those arguments that have defaults, or \code{None} if no
     arguments have a default value}{Writable}
 
-  \lineiii{func_code}{The code object representing the compiled
+  \lineiii{__code__}{The code object representing the compiled
     function body.}{Writable}
 
-  \lineiii{func_globals}{A reference to the dictionary that holds the
+  \lineiii{__globals__}{A reference to the dictionary that holds the
     function's global variables --- the global namespace of the module
     in which the function was defined.}{Read-only}
 
-  \lineiii{func_dict}{The namespace supporting arbitrary function
+  \lineiii{__dict__}{The namespace supporting arbitrary function
     attributes.}{Writable}
 
-  \lineiii{func_closure}{\code{None} or a tuple of cells that contain
+  \lineiii{__closure__}{\code{None} or a tuple of cells that contain
     bindings for the function's free variables.}{Read-only}
+
+  \lineiii{__annotations__}{A dict containing annotations of parameters. 
+    The keys of the dict are the parameter names, or \code{'return'}
+    for the return annotation, if provided.}{Writable}
+
+  \lineiii{__kwdefaults__}{A dict containing defaults for keyword-only
+    parameters.}{Writable}
 \end{tableiii}
 
 Most of the attributes labelled ``Writable'' check the type of the
 assigned value.
 
-\versionchanged[\code{func_name} is now writable]{2.4}
+\versionchanged[\code{__name__} is now writable]{2.4}
 
 Function objects also support getting and setting arbitrary
 attributes, which can be used, for example, to attach metadata to
@@ -521,16 +522,16 @@
 from its code object; see the description of internal types below.
 
 \withsubitem{(function attribute)}{
-  \ttindex{func_doc}
   \ttindex{__doc__}
   \ttindex{__name__}
   \ttindex{__module__}
   \ttindex{__dict__}
-  \ttindex{func_defaults}
-  \ttindex{func_closure}
-  \ttindex{func_code}
-  \ttindex{func_globals}
-  \ttindex{func_dict}}
+  \ttindex{__defaults__}
+  \ttindex{__closure__}
+  \ttindex{__code__}
+  \ttindex{__globals__}
+  \ttindex{__annotations__}
+  \ttindex{__kwdefaults__}}
 \indexii{global}{namespace}
 
 \item[User-defined methods]
@@ -633,7 +634,7 @@
 section~\ref{yield}, ``The \keyword{yield} statement'') is called a
 \dfn{generator function}.  Such a function, when called, always
 returns an iterator object which can be used to execute the body of
-the function:  calling the iterator's \method{next()} method will
+the function:  calling the iterator's \method{__next__()} method will
 cause the function to execute until it provides a value using the
 \keyword{yield} statement.  When the function executes a
 \keyword{return} statement or falls off the end, a
@@ -700,7 +701,7 @@
 section~\ref{import}, ``The \keyword{import} statement'').%
 \stindex{import}\obindex{module}
 A module object has a namespace implemented by a dictionary object
-(this is the dictionary referenced by the func_globals attribute of
+(this is the dictionary referenced by the __globals__ attribute of
 functions defined in the module).  Attribute references are translated
 to lookups in this dictionary, e.g., \code{m.x} is equivalent to
 \code{m.__dict__["x"]}.
@@ -860,12 +861,12 @@
 \begin{description}
 
 \item[Code objects]
-Code objects represent \emph{byte-compiled} executable Python code, or 
+Code objects represent \emph{byte-compiled} executable Python code, or
 \emph{bytecode}.
 The difference between a code
 object and a function object is that the function object contains an
 explicit reference to the function's globals (the module in which it
-was defined), while a code object contains no context; 
+was defined), while a code object contains no context;
 also the default argument values are stored in the function object,
 not in the code object (because they represent values calculated at
 run-time).  Unlike function objects, code objects are immutable and
@@ -941,18 +942,15 @@
 frame; \member{f_locals} is the dictionary used to look up local
 variables; \member{f_globals} is used for global variables;
 \member{f_builtins} is used for built-in (intrinsic) names;
-\member{f_restricted} is a flag indicating whether the function is
-executing in restricted execution mode; \member{f_lasti} gives the
-precise instruction (this is an index into the bytecode string of
-the code object).
+ \member{f_lasti} gives the precise instruction (this is an index into
+ the bytecode string of the code object).
 \withsubitem{(frame attribute)}{
   \ttindex{f_back}
   \ttindex{f_code}
   \ttindex{f_globals}
   \ttindex{f_locals}
   \ttindex{f_lasti}
-  \ttindex{f_builtins}
-  \ttindex{f_restricted}}
+  \ttindex{f_builtins}}
 
 Special writable attributes: \member{f_trace}, if not \code{None}, is
 a function called at the start of each source code line (this is used
@@ -979,10 +977,8 @@
 traceback.  When an exception handler is entered, the stack trace is
 made available to the program.
 (See section~\ref{try}, ``The \code{try} statement.'')
-It is accessible as \code{sys.exc_traceback}, and also as the third
-item of the tuple returned by \code{sys.exc_info()}.  The latter is
-the preferred interface, since it works correctly when the program is
-using multiple threads.
+It is accessible as the third
+item of the tuple returned by \code{sys.exc_info()}.
 When the program contains no suitable handler, the stack trace is written
 (nicely formatted) to the standard error stream; if the interpreter is
 interactive, it is also made available to the user as
@@ -996,7 +992,6 @@
   \ttindex{exc_traceback}
   \ttindex{last_traceback}}
 \ttindex{sys.exc_info}
-\ttindex{sys.exc_traceback}
 \ttindex{sys.last_traceback}
 
 Special read-only attributes: \member{tb_next} is the next level in the
@@ -1069,7 +1064,7 @@
 %=========================================================================
 \section{New-style and classic classes}
 
-Classes and instances come in two flavors: old-style or classic, and new-style.  
+Classes and instances come in two flavors: old-style or classic, and new-style.
 
 Up to Python 2.1, old-style classes were the only flavour available to the
 user.  The concept of (old-style) class is unrelated to the concept of type: if
@@ -1200,13 +1195,13 @@
 references between objects (e.g., a doubly-linked list or a tree data
 structure with parent and child pointers); a reference to the object
 on the stack frame of a function that caught an exception (the
-traceback stored in \code{sys.exc_traceback} keeps the stack frame
+traceback stored in \code{sys.exc_info()[2]} keeps the stack frame
 alive); or a reference to the object on the stack frame that raised an
 unhandled exception in interactive mode (the traceback stored in
 \code{sys.last_traceback} keeps the stack frame alive).  The first
 situation can only be remedied by explicitly breaking the cycles; the
 latter two situations can be resolved by storing \code{None} in
-\code{sys.exc_traceback} or \code{sys.last_traceback}.  Circular
+\code{sys.last_traceback}.  Circular
 references which are garbage are detected when the option cycle
 detector is enabled (it's on by default), but can only be cleaned up
 if there are no Python-level \method{__del__()} methods involved.
@@ -1244,7 +1239,7 @@
 string object.
 If a class defines \method{__repr__()} but not \method{__str__()},
 then \method{__repr__()} is also used when an ``informal'' string
-representation of instances of that class is required.		     
+representation of instances of that class is required.
 
 This is typically used for debugging, so it is important that the
 representation is information-rich and unambiguous.
@@ -1280,10 +1275,14 @@
 \code{\var{x}!=\var{y}} calls \code{\var{x}.__ne__(\var{y})},
 \code{\var{x}>\var{y}} calls \code{\var{x}.__gt__(\var{y})}, and
 \code{\var{x}>=\var{y}} calls \code{\var{x}.__ge__(\var{y})}.
-These methods can return any value, but if the comparison operator is
-used in a Boolean context, the return value should be interpretable as
-a Boolean value, else a \exception{TypeError} will be raised.
-By convention, \code{False} is used for false and \code{True} for true.
+
+A rich comparison method may return the singleton \code{NotImplemented} if it
+does not implement the operation for a given pair of arguments.
+By convention, \code{False} and \code{True} are returned for a successful
+comparison. However, these methods can return any value, so if the
+comparison operator is used in a Boolean context (e.g., in the condition
+of an \code{if} statement), Python will call \function{bool()} on the
+value to determine if the result is true or false.
 
 There are no implied relationships among the comparison operators.
 The truth of \code{\var{x}==\var{y}} does not imply that \code{\var{x}!=\var{y}}
@@ -1297,9 +1296,7 @@
 \method{__ge__()} are each other's reflection, and \method{__eq__()}
 and \method{__ne__()} are their own reflection.
 
-Arguments to rich comparison methods are never coerced.  A rich
-comparison method may return \code{NotImplemented} if it does not
-implement the operation for a given pair of arguments.
+Arguments to rich comparison methods are never coerced.
 \end{methoddesc}
 
 \begin{methoddesc}[object]{__cmp__}{self, other}
@@ -1399,7 +1396,7 @@
 dictionary).  \var{name} is the attribute name, \var{value} is the
 value to be assigned to it.
 
-If \method{__setattr__()} wants to assign to an instance attribute, it 
+If \method{__setattr__()} wants to assign to an instance attribute, it
 should not simply execute \samp{self.\var{name} = value} --- this
 would cause a recursive call to itself.  Instead, it should insert the
 value in the dictionary of instance attributes, e.g.,
@@ -1422,8 +1419,8 @@
 
 \begin{methoddesc}[object]{__getattribute__}{self, name}
 Called unconditionally to implement attribute accesses for instances
-of the class. If the class also defines \method{__getattr__()}, the latter 
-will not be called unless \method{__getattribute__()} either calls it 
+of the class. If the class also defines \method{__getattr__()}, the latter
+will not be called unless \method{__getattribute__()} either calls it
 explicitly or raises an \exception{AttributeError}.
 This method should return the (computed) attribute
 value or raise an \exception{AttributeError} exception.
@@ -1475,7 +1472,7 @@
 The default behavior for attribute access is to get, set, or delete the
 attribute from an object's dictionary. For instance, \code{a.x} has a
 lookup chain starting with \code{a.__dict__['x']}, then
-\code{type(a).__dict__['x']}, and continuing 
+\code{type(a).__dict__['x']}, and continuing
 through the base classes of \code{type(a)} excluding metaclasses.
 
 However, if the looked-up value is an object defining one of the descriptor
@@ -1489,14 +1486,14 @@
 How the arguments are assembled depends on \code{a}:
 
 \begin{itemize}
-                      
+
   \item[Direct Call] The simplest and least common call is when user code
     directly invokes a descriptor method:    \code{x.__get__(a)}.
 
   \item[Instance Binding]  If binding to a new-style object instance,
     \code{a.x} is transformed into the call:
     \code{type(a).__dict__['x'].__get__(a, type(a))}.
-                     
+
   \item[Class Binding]  If binding to a new-style class, \code{A.x}
     is transformed into the call: \code{A.__dict__['x'].__get__(None, A)}.
 
@@ -1505,7 +1502,7 @@
     \code{obj.__class__.__mro__} for the base class \code{A} immediately
     preceding \code{B} and then invokes the descriptor with the call:
     \code{A.__dict__['m'].__get__(obj, A)}.
-                     
+
 \end{itemize}
 
 For instance bindings, the precedence of descriptor invocation depends
@@ -1518,7 +1515,7 @@
 Python methods (including \function{staticmethod()} and \function{classmethod()})
 are implemented as non-data descriptors.  Accordingly, instances can
 redefine and override methods.  This allows individual instances to acquire
-behaviors that differ from other instances of the same class.                     
+behaviors that differ from other instances of the same class.
 
 The \function{property()} function is implemented as a data descriptor.
 Accordingly, instances cannot override the behavior of a property.
@@ -1536,14 +1533,14 @@
 variables and reserves just enough space in each instance to hold a value
 for each variable.  Space is saved because \var{__dict__} is not created for
 each instance.
-    
+
 \begin{datadesc}{__slots__}
 This class variable can be assigned a string, iterable, or sequence of strings
 with variable names used by instances.  If defined in a new-style class,
 \var{__slots__} reserves space for the declared variables
 and prevents the automatic creation of \var{__dict__} and \var{__weakref__}
 for each instance.
-\versionadded{2.2}                     
+\versionadded{2.2}
 \end{datadesc}
 
 \noindent
@@ -1555,23 +1552,23 @@
 variables not listed in the \var{__slots__} definition.  Attempts to assign
 to an unlisted variable name raises \exception{AttributeError}. If dynamic
 assignment of new variables is desired, then add \code{'__dict__'} to the
-sequence of strings in the \var{__slots__} declaration.                                     
+sequence of strings in the \var{__slots__} declaration.
 \versionchanged[Previously, adding \code{'__dict__'} to the \var{__slots__}
 declaration would not enable the assignment of new attributes not
-specifically listed in the sequence of instance variable names]{2.3}                     
+specifically listed in the sequence of instance variable names]{2.3}
 
 \item Without a \var{__weakref__} variable for each instance, classes
 defining \var{__slots__} do not support weak references to its instances.
 If weak reference support is needed, then add \code{'__weakref__'} to the
-sequence of strings in the \var{__slots__} declaration.                    
+sequence of strings in the \var{__slots__} declaration.
 \versionchanged[Previously, adding \code{'__weakref__'} to the \var{__slots__}
-declaration would not enable support for weak references]{2.3}                                            
+declaration would not enable support for weak references]{2.3}
 
 \item \var{__slots__} are implemented at the class level by creating
 descriptors (\ref{descriptors}) for each variable name.  As a result,
 class attributes cannot be used to set default values for instance
 variables defined by \var{__slots__}; otherwise, the class attribute would
-overwrite the descriptor assignment. 
+overwrite the descriptor assignment.
 
 \item If a class defines a slot also defined in a base class, the instance
 variable defined by the base class slot is inaccessible (except by retrieving
@@ -1580,14 +1577,19 @@
 
 \item The action of a \var{__slots__} declaration is limited to the class
 where it is defined.  As a result, subclasses will have a \var{__dict__}
-unless they also define  \var{__slots__}.                     
+unless they also define  \var{__slots__}.
 
 \item \var{__slots__} do not work for classes derived from ``variable-length''
-built-in types such as \class{long}, \class{str} and \class{tuple}. 
+built-in types such as \class{long}, \class{str} and \class{tuple}.
 
 \item Any non-string iterable may be assigned to \var{__slots__}.
 Mappings may also be used; however, in the future, special meaning may
-be assigned to the values corresponding to each key.                      
+be assigned to the values corresponding to each key.
+
+\item \var{__class__} assignment works only if both classes have the
+same \var{__slots__}.
+\versionchanged[Previously, \var{__class__} assignment raised an error
+if either new or old class had \var{__slots__}]{2.6}
 
 \end{itemize}
 
@@ -1613,7 +1615,7 @@
 This variable can be any callable accepting arguments for \code{name},
 \code{bases}, and \code{dict}.  Upon class creation, the callable is
 used instead of the built-in \function{type()}.
-\versionadded{2.2}                     
+\versionadded{2.2}
 \end{datadesc}
 
 The appropriate metaclass is determined by the following precedence rules:
@@ -1630,7 +1632,7 @@
 
 \item Otherwise, the old-style, classic metaclass (types.ClassType) is used.
 
-\end{itemize}      
+\end{itemize}
 
 The potential uses for metaclasses are boundless. Some ideas that have
 been explored including logging, interface checking, automatic delegation,
@@ -1663,15 +1665,15 @@
 that mappings provide the methods \method{keys()}, \method{values()},
 \method{items()}, \method{has_key()}, \method{get()}, \method{clear()},
 \method{setdefault()}, \method{iterkeys()}, \method{itervalues()},
-\method{iteritems()}, \method{pop()}, \method{popitem()},		     
+\method{iteritems()}, \method{pop()}, \method{popitem()},
 \method{copy()}, and \method{update()} behaving similar to those for
 Python's standard dictionary objects.  The \module{UserDict} module
 provides a \class{DictMixin} class to help create those methods
 from a base set of \method{__getitem__()}, \method{__setitem__()},
-\method{__delitem__()}, and \method{keys()}.		     
+\method{__delitem__()}, and \method{keys()}.
 Mutable sequences should provide
 methods \method{append()}, \method{count()}, \method{index()},
-\method{extend()},		     
+\method{extend()},
 \method{insert()}, \method{pop()}, \method{remove()}, \method{reverse()}
 and \method{sort()}, like Python standard list objects.  Finally,
 sequence types should implement addition (meaning concatenation) and
@@ -1694,12 +1696,12 @@
   \ttindex{items()}
   \ttindex{iterkeys()}
   \ttindex{itervalues()}
-  \ttindex{iteritems()}    
+  \ttindex{iteritems()}
   \ttindex{has_key()}
   \ttindex{get()}
   \ttindex{setdefault()}
-  \ttindex{pop()}      
-  \ttindex{popitem()}    
+  \ttindex{pop()}
+  \ttindex{popitem()}
   \ttindex{clear()}
   \ttindex{copy()}
   \ttindex{update()}
@@ -1707,7 +1709,7 @@
 \withsubitem{(sequence object method)}{
   \ttindex{append()}
   \ttindex{count()}
-  \ttindex{extend()}    
+  \ttindex{extend()}
   \ttindex{index()}
   \ttindex{insert()}
   \ttindex{pop()}
@@ -1721,7 +1723,7 @@
   \ttindex{__rmul__()}
   \ttindex{__imul__()}
   \ttindex{__contains__()}
-  \ttindex{__iter__()}}		     
+  \ttindex{__iter__()}}
 \withsubitem{(numeric object method)}
 
 \begin{methoddesc}[container object]{__len__}{self}
@@ -1744,7 +1746,7 @@
 (after any special interpretation of negative values),
 \exception{IndexError} should be raised.
 For mapping types, if \var{key} is missing (not in the container),
-\exception{KeyError} should be raised.                     
+\exception{KeyError} should be raised.
 \note{\keyword{for} loops expect that an
 \exception{IndexError} will be raised for illegal indexes to allow
 proper detection of the end of the sequence.}
@@ -1943,7 +1945,7 @@
 \methodline[numeric object]{__rmul__}{self, other}
 \methodline[numeric object]{__rdiv__}{self, other}
 \methodline[numeric object]{__rtruediv__}{self, other}
-\methodline[numeric object]{__rfloordiv__}{self, other}	     
+\methodline[numeric object]{__rfloordiv__}{self, other}
 \methodline[numeric object]{__rmod__}{self, other}
 \methodline[numeric object]{__rdivmod__}{self, other}
 \methodline[numeric object]{__rpow__}{self, other}
@@ -1964,7 +1966,7 @@
     For operands of the same type, it is assumed that if the
     non-reflected method (such as \method{__add__()}) fails the
     operation is not supported, which is why the reflected method
-    is not called.} 
+    is not called.}
 For instance, to evaluate the expression \var{x}\code{-}\var{y},
 where \var{y} is an instance of a class that has an
 \method{__rsub__()} method, \code{\var{y}.__rsub__(\var{x})}
@@ -1989,7 +1991,7 @@
 \methodline[numeric object]{__idiv__}{self, other}
 \methodline[numeric object]{__itruediv__}{self, other}
 \methodline[numeric object]{__ifloordiv__}{self, other}
-\methodline[numeric object]{__imod__}{self, other}		     
+\methodline[numeric object]{__imod__}{self, other}
 \methodline[numeric object]{__ipow__}{self, other\optional{, modulo}}
 \methodline[numeric object]{__ilshift__}{self, other}
 \methodline[numeric object]{__irshift__}{self, other}
@@ -2031,17 +2033,11 @@
 the appropriate type.
 \end{methoddesc}
 
-\begin{methoddesc}[numeric object]{__oct__}{self}
-\methodline[numeric object]{__hex__}{self}
-Called to implement the built-in functions
-\function{oct()}\bifuncindex{oct} and
-\function{hex()}\bifuncindex{hex}.  Should return a string value.
-\end{methoddesc}
-
 \begin{methoddesc}[numeric object]{__index__}{self}
 Called to implement \function{operator.index()}.  Also called whenever
-Python needs an integer object (such as in slicing).  Must return an
-integer (int or long).
+Python needs an integer object (such as in slicing, or in the built-in
+\function{bin()}, \function{hex()} and \function{oct()} functions).
+Must return an integer (int or long).
 \versionadded{2.5}
 \end{methoddesc}
 

Modified: python/branches/p3yk-noslice/Doc/ref/ref5.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref5.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ref/ref5.tex	Wed Jul 11 15:40:56 2007
@@ -56,7 +56,7 @@
   \production{enclosure}
              {\token{parenth_form} | \token{list_display}}
   \productioncont{| \token{generator_expression} | \token{dict_display}}
-  \productioncont{| \token{string_conversion}}
+  \productioncont{| \token{string_conversion} | \token{yield_atom}}
 \end{productionlist}
 
 
@@ -65,6 +65,7 @@
 \index{identifier}
 
 An identifier occurring as an atom is a name.  See
+section \ref{identifiers} for lexical definition and
 section~\ref{naming} for documentation of naming and binding.
 
 When the name is bound to an object, evaluation of the atom yields
@@ -154,22 +155,20 @@
 square brackets:
 
 \begin{productionlist}
-  \production{test}
-             {\token{or_test} | \token{lambda_form}}
-  \production{testlist}
-             {\token{test} ( "," \token{test} )* [ "," ]}
   \production{list_display}
-             {"[" [\token{listmaker}] "]"}
-  \production{listmaker}
-             {\token{expression} ( \token{list_for}
-              | ( "," \token{expression} )* [","] )}
-  \production{list_iter}
-             {\token{list_for} | \token{list_if}}
+             {"[" [\token{expression_list} | \token{list_comprehension}] "]"}
+  \production{list_comprehension}
+             {\token{expression} \token{list_for}}
   \production{list_for}
-             {"for" \token{expression_list} "in" \token{testlist}
+             {"for" \token{target_list} "in" \token{old_expression_list}
               [\token{list_iter}]}
+  \production{old_expression_list}
+             {\token{old_expression}
+              [("," \token{old_expression})+ [","]]}
+  \production{list_iter}
+             {\token{list_for} | \token{list_if}}
   \production{list_if}
-             {"if" \token{test} [\token{list_iter}]}
+             {"if" \token{old_expression} [\token{list_iter}]}
 \end{productionlist}
 
 A list display yields a new list object.  Its contents are specified
@@ -200,19 +199,18 @@
 
 \begin{productionlist}
   \production{generator_expression}
-             {"(" \token{test} \token{genexpr_for} ")"}
+             {"(" \token{expression} \token{genexpr_for} ")"}
   \production{genexpr_for}
-             {"for" \token{expression_list} "in" \token{test}
+             {"for" \token{target_list} "in" \token{or_test}
               [\token{genexpr_iter}]}
   \production{genexpr_iter}
              {\token{genexpr_for} | \token{genexpr_if}}
   \production{genexpr_if}
-             {"if" \token{test} [\token{genexpr_iter}]}
+             {"if" \token{old_expression} [\token{genexpr_iter}]}
 \end{productionlist}
 
 A generator expression yields a new generator object.
 \obindex{generator}
-\obindex{generator expression}
 It consists of a single expression followed by at least one
 \keyword{for} clause and zero or more \keyword{for} or \keyword{if}
 clauses.  The iterating values of the new generator are those that
@@ -222,7 +220,7 @@
 innermost block for each iteration.
 
 Variables used in the generator expression are evaluated lazily
-when the \method{next()} method is called for generator object
+when the \method{__next__()} method is called for generator object
 (in the same fashion as normal generators). However, the leftmost
 \keyword{for} clause is immediately evaluated so that error produced
 by it can be seen before any other possible error in the code that
@@ -268,6 +266,142 @@
 \indexii{immutable}{object}
 
 
+\subsection{Yield expressions\label{yieldexpr}}
+\kwindex{yield}
+\indexii{yield}{expression}
+\indexii{generator}{function}
+
+\begin{productionlist}
+  \production{yield_atom}
+             {"(" \token{yield_expression} ")"}
+  \production{yield_expression}
+             {"yield" [\token{expression_list}]}
+\end{productionlist}
+
+\versionadded{2.5}
+
+The \keyword{yield} expression is only used when defining a generator
+function, and can only be used in the body of a function definition.
+Using a \keyword{yield} expression in a function definition is
+sufficient to cause that definition to create a generator function
+instead of a normal function.
+
+When a generator function is called, it returns an iterator known as a
+generator.  That generator then controls the execution of a generator
+function.  The execution starts when one of the generator's methods is
+called.  At that time, the execution proceeds to the first
+\keyword{yield} expression, where it is suspended again, returning the
+value of \grammartoken{expression_list} to generator's caller.  By
+suspended we mean that all local state is retained, including the
+current bindings of local variables, the instruction pointer, and the
+internal evaluation stack.  When the execution is resumed by calling
+one of the generator's methods, the function can proceed exactly as
+if the \keyword{yield} expression was just another external call.
+The value of the \keyword{yield} expression after resuming depends on
+the method which resumed the execution.
+
+\index{coroutine}
+
+All of this makes generator functions quite similar to coroutines; they
+yield multiple times, they have more than one entry point and their
+execution can be suspended.  The only difference is that a generator
+function cannot control where should the execution continue after it
+yields; the control is always transfered to the generator's caller.
+
+\obindex{generator}
+
+The following generator's methods can be used to control the execution
+of a generator function:
+
+\exindex{StopIteration}
+
+\begin{methoddesc}[generator]{next}{}
+  Starts the execution of a generator function or resumes it at the
+  last executed \keyword{yield} expression.  When a generator function
+  is resumed with a \method{next()} method, the current \keyword{yield}
+  expression always evaluates to \constant{None}.  The execution then
+  continues to the next \keyword{yield} expression, where the generator
+  is suspended again, and the value of the
+  \grammartoken{expression_list} is returned to \method{next()}'s
+  caller. If the generator exits without yielding another value, a
+  \exception{StopIteration} exception is raised.
+\end{methoddesc}
+
+\begin{methoddesc}[generator]{send}{value}
+  Resumes the execution and ``sends'' a value into the generator
+  function.  The \code{value} argument becomes the result of the
+  current \keyword{yield} expression.  The \method{send()} method
+  returns the next value yielded by the generator, or raises
+  \exception{StopIteration} if the generator exits without yielding
+  another value.
+  When \method{send()} is called to start the generator, it must be
+  called with \constant{None} as the argument, because there is no
+  \keyword{yield} expression that could receieve the value.
+\end{methoddesc}
+
+\begin{methoddesc}[generator]{throw}
+                  {type\optional{, value\optional{, traceback}}}
+  Raises an exception of type \code{type} at the point where generator
+  was paused, and returns the next value yielded by the generator
+  function.  If the generator exits without yielding another value, a
+  \exception{StopIteration} exception is raised.  If the generator
+  function does not catch the passed-in exception, or raises a
+  different exception, then that exception propagates to the caller.
+\end{methoddesc}
+
+\exindex{GeneratorExit}
+
+\begin{methoddesc}[generator]{close}{}
+  Raises a \exception{GeneratorExit} at the point where the generator
+  function was paused.  If the generator function then raises
+  \exception{StopIteration} (by exiting normally, or due to already
+  being closed) or \exception{GeneratorExit} (by not catching the
+  exception), close returns to its caller.  If the generator yields a
+  value, a \exception{RuntimeError} is raised.  If the generator raises
+  any other exception, it is propagated to the caller.  \method{close}
+  does nothing if the generator has already exited due to an exception
+  or normal exit.
+\end{methoddesc}
+
+Here is a simple example that demonstrates the behavior of generators
+and generator functions:
+
+\begin{verbatim}
+>>> def echo(value=None):
+...     print "Execution starts when 'next()' is called for the first time."
+...     try:
+...         while True:
+...             try:
+...                 value = (yield value)
+...             except GeneratorExit:
+...                 # never catch GeneratorExit
+...                 raise
+...             except Exception, e:
+...                 value = e
+...     finally:
+...         print "Don't forget to clean up when 'close()' is called."
+...
+>>> generator = echo(1)
+>>> print generator.next()
+Execution starts when 'next()' is called for the first time.
+1
+>>> print generator.next()
+None
+>>> print generator.send(2)
+2
+>>> generator.throw(TypeError, "spam")
+TypeError('spam',)
+>>> generator.close()
+Don't forget to clean up when 'close()' is called.
+\end{verbatim}
+
+\begin{seealso}
+  \seepep{0342}{Coroutines via Enhanced Generators}
+         {The proposal to enhance the API and syntax of generators,
+          making them usable as simple coroutines.}
+\end{seealso}
+
+
 \section{Primaries\label{primaries}}
 \index{primary}
 
@@ -430,9 +564,8 @@
 
 \begin{productionlist}
   \production{call}
-             {\token{primary} "(" [\token{argument_list} [","]] ")"}
-             {\token{primary} "(" [\token{argument_list} [","] |
-	      \token{test} \token{genexpr_for} ] ")"}                                                   
+             {\token{primary} "(" [\token{argument_list} [","]}
+  \productioncont{            | \token{expression} \token{genexpr_for}] ")"}
   \production{argument_list}
              {\token{positional_arguments} ["," \token{keyword_arguments}]}
   \productioncont{                     ["," "*" \token{expression}]}
@@ -527,7 +660,7 @@
 this confusion does not arise.
 
 If the syntax \samp{**expression} appears in the function call,
-\samp{expression} must evaluate to a (subclass of) dictionary, the
+\samp{expression} must evaluate to a mapping, the
 contents of which are treated as additional keyword arguments.  In the
 case of a keyword appearing in both \samp{expression} and as an
 explicit keyword argument, a \exception{TypeError} exception is
@@ -535,11 +668,7 @@
 
 Formal parameters using the syntax \samp{*identifier} or
 \samp{**identifier} cannot be used as positional argument slots or
-as keyword argument names.  Formal parameters using the syntax
-\samp{(sublist)} cannot be used as keyword argument names; the
-outermost sublist corresponds to a single unnamed argument slot, and
-the argument value is assigned to the sublist using the usual tuple
-assignment rules after all other parameter processing is done.
+as keyword argument names.
 
 A call always returns some value, possibly \code{None}, unless it
 raises an exception.  How this value is computed depends on the type
@@ -765,10 +894,9 @@
 operations:
 
 \begin{productionlist}
-  % The empty groups below prevent conversion to guillemets.
   \production{shift_expr}
              {\token{a_expr}
-              | \token{shift_expr} ( "<{}<" | ">{}>" ) \token{a_expr}}
+              | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
 \end{productionlist}
 
 These operators accept plain or long integers as arguments.  The
@@ -966,14 +1094,18 @@
 
 
 \section{Boolean operations\label{Booleans}}
+\indexii{Conditional}{expression}
 \indexii{Boolean}{operation}
 
 Boolean operations have the lowest priority of all Python operations:
 
 \begin{productionlist}
   \production{expression}
-             {\token{or_test} [\token{if} \token{or_test} \token{else}
-              \token{test}] | \token{lambda_form}}
+             {\token{conditional_expression} | \token{lambda_form}}
+  \production{old_expression}
+             {\token{or_test} | \token{old_lambda_form}}
+  \production{conditional_expression}
+             {\token{or_test} ["if" \token{or_test} "else" \token{expression}]}
   \production{or_test}
              {\token{and_test} | \token{or_test} "or" \token{and_test}}
   \production{and_test}
@@ -1025,6 +1157,8 @@
 \begin{productionlist}
   \production{lambda_form}
              {"lambda" [\token{parameter_list}]: \token{expression}}
+  \production{old_lambda_form}
+             {"lambda" [\token{parameter_list}]: \token{old_expression}}
 \end{productionlist}
 
 Lambda forms (lambda expressions) have the same syntactic position as
@@ -1039,7 +1173,8 @@
 \end{verbatim}
 
 See section \ref{function} for the syntax of parameter lists.  Note
-that functions created with lambda forms cannot contain statements.
+that functions created with lambda forms cannot contain statements
+or annotations.
 \label{lambda}
 
 \section{Expression lists\label{exprlists}}

Modified: python/branches/p3yk-noslice/Doc/ref/ref6.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref6.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ref/ref6.tex	Wed Jul 11 15:40:56 2007
@@ -106,7 +106,8 @@
 
 \begin{productionlist}
   \production{assignment_stmt}
-             {(\token{target_list} "=")+ \token{expression_list}}
+             {(\token{target_list} "=")+
+              (\token{expression_list} | \token{yield_expression})}
   \production{target_list}
              {\token{target} ("," \token{target})* [","]}
   \production{target}
@@ -271,11 +272,11 @@
 
 \begin{productionlist}
   \production{augmented_assignment_stmt}
-             {\token{target} \token{augop} \token{expression_list}}
+             {\token{target} \token{augop}
+              (\token{expression_list} | \token{yield_expression})}
   \production{augop}
              {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}
-  % The empty groups below prevent conversion to guillemets.
-  \productioncont{| ">{}>=" | "<{}<=" | "\&=" | "\textasciicircum=" | "|="}
+  \productioncont{| ">>=" | "<<=" | "\&=" | "\textasciicircum=" | "|="}
 \end{productionlist}
 
 (See section~\ref{primaries} for the syntax definitions for the last
@@ -404,7 +405,7 @@
 
 \begin{productionlist}
   \production{yield_stmt}
-             {"yield" \token{expression_list}}
+             {\token{yield_expression}}
 \end{productionlist}
 
 \index{generator!function}
@@ -418,19 +419,18 @@
 sufficient to cause that definition to create a generator function
 instead of a normal function.
 
-When a generator function is called, it returns an iterator known as a
-generator iterator, or more commonly, a generator.  The body of the
-generator function is executed by calling the generator's
-\method{next()} method repeatedly until it raises an exception.
-
-When a \keyword{yield} statement is executed, the state of the
-generator is frozen and the value of \grammartoken{expression_list} is
-returned to \method{next()}'s caller.  By ``frozen'' we mean that all
-local state is retained, including the current bindings of local
-variables, the instruction pointer, and the internal evaluation stack:
-enough information is saved so that the next time \method{next()} is
-invoked, the function can proceed exactly as if the \keyword{yield}
-statement were just another external call.
+When a generator function is called, it returns an iterator known as a generator
+iterator, or more commonly, a generator.  The body of the generator function is
+executed by calling the generator's \method{__next__()} method repeatedly until
+it raises an exception.
+
+When a \keyword{yield} statement is executed, the state of the generator is
+frozen and the value of \grammartoken{expression_list} is returned to
+\method{__next__()}'s caller.  By ``frozen'' we mean that all local state is
+retained, including the current bindings of local variables, the instruction
+pointer, and the internal evaluation stack: enough information is saved so that
+the next time \method{__next__()} is invoked, the function can proceed exactly
+as if the \keyword{yield} statement were just another external call.
 
 As of Python version 2.5, the \keyword{yield} statement is now
 allowed in the \keyword{try} clause of a \keyword{try} ...\ 
@@ -574,15 +574,19 @@
   \production{import_stmt}
              {"import" \token{module} ["as" \token{name}]
                 ( "," \token{module} ["as" \token{name}] )*}
-  \productioncont{| "from" \token{module} "import" \token{identifier}
+  \productioncont{| "from" \token{relative_module} "import" \token{identifier}
                     ["as" \token{name}]}
   \productioncont{  ( "," \token{identifier} ["as" \token{name}] )*}
-  \productioncont{| "from" \token{module} "import" "(" \token{identifier}
-                    ["as" \token{name}]}
+  \productioncont{| "from" \token{relative_module} "import" "("
+                    \token{identifier} ["as" \token{name}]}
   \productioncont{  ( "," \token{identifier} ["as" \token{name}] )* [","] ")"}
   \productioncont{| "from" \token{module} "import" "*"}
   \production{module}
              {(\token{identifier} ".")* \token{identifier}}
+  \production{relative_module}
+             {"."* \token{module} | "."+}
+  \production{name}
+             {\token{identifier}}
 \end{productionlist}
 
 Import statements are executed in two steps: (1) find a module, and
@@ -701,8 +705,10 @@
 
 \begin{productionlist}[*]
   \production{future_statement}
-             {"from" "__future__" "import" feature ["as" name] ("," feature ["as" name])*}
-  \productioncont{| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])* [","] ")"}
+             {"from" "__future__" "import" feature ["as" name]}
+  \productioncont{  ("," feature ["as" name])*}
+  \productioncont{| "from" "__future__" "import" "(" feature ["as" name]}
+  \productioncont{  ("," feature ["as" name])* [","] ")"}
   \production{feature}{identifier}
   \production{name}{identifier}
 \end{productionlist}
@@ -719,9 +725,10 @@
 
 \end{itemize}
 
-The features recognized by Python 2.3 are \samp{generators},
-\samp{division} and \samp{nested_scopes}.  \samp{generators} and
-\samp{nested_scopes} are redundant in 2.3 because they are always
+The features recognized by Python 2.5 are \samp{absolute_import},
+\samp{division}, \samp{generators}, \samp{nested_scopes} and
+\samp{with_statement}.  \samp{generators} and \samp{nested_scopes} 
+are redundant in Python version 2.3 and above because they are always
 enabled. 
 
 A future statement is recognized and treated specially at compile

Modified: python/branches/p3yk-noslice/Doc/ref/ref7.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref7.tex	(original)
+++ python/branches/p3yk-noslice/Doc/ref/ref7.tex	Wed Jul 11 15:40:56 2007
@@ -313,7 +313,7 @@
 
 \begin{productionlist}
   \production{with_stmt}
-  {"with" \token{expression} ["as" target] ":" \token{suite}}
+  {"with" \token{expression} ["as" \token{target}] ":" \token{suite}}
 \end{productionlist}
 
 The execution of the \keyword{with} statement proceeds as follows:
@@ -381,6 +381,7 @@
 \begin{productionlist}
   \production{funcdef}
              {[\token{decorators}] "def" \token{funcname} "(" [\token{parameter_list}] ")"
+              ["->" \token{expression}]?
               ":" \token{suite}}
   \production{decorators}
              {\token{decorator}+}
@@ -390,15 +391,14 @@
              {\token{identifier} ("." \token{identifier})*}
   \production{parameter_list}
                  {(\token{defparameter} ",")*}
-  \productioncont{(~~"*" \token{identifier} [, "**" \token{identifier}]}
-  \productioncont{ | "**" \token{identifier}}
+  \productioncont{(~~"*" [\token{parameter}] ("," \token{defparameter})*}
+  \productioncont{   [, "**" \token{parameter}]}
+  \productioncont{ | "**" \token{parameter}}
   \productioncont{ | \token{defparameter} [","] )}
+  \production{parameter}
+             {\token{identifier} [":" \token{expression}]}
   \production{defparameter}
              {\token{parameter} ["=" \token{expression}]}
-  \production{sublist}
-             {\token{parameter} ("," \token{parameter})* [","]}
-  \production{parameter}
-             {\token{identifier} | "(" \token{sublist} ")"}
   \production{funcname}
              {\token{identifier}}
 \end{productionlist}
@@ -435,14 +435,14 @@
 func = f1(arg)(f2(func))
 \end{verbatim}
 
-When one or more top-level parameters have the form \var{parameter}
+When one or more parameters have the form \var{parameter}
 \code{=} \var{expression}, the function is said to have ``default
 parameter values.''  For a parameter with a
 default value, the corresponding argument may be omitted from a call,
 in which case the parameter's default value is substituted.  If a
-parameter has a default value, all following parameters must also have
-a default value --- this is a syntactic restriction that is not
-expressed by the grammar.
+parameter has a default value, all following parameters up until the 
+``\code{*}'' must also have a default value --- this is a syntactic 
+restriction that is not expressed by the grammar.
 \indexiii{default}{parameter}{value}
 
 \strong{Default parameter values are evaluated when the function
@@ -473,7 +473,21 @@
 positional parameters, defaulting to the empty tuple.  If the form
 ``\code{**identifier}'' is present, it is initialized to a new
 dictionary receiving any excess keyword arguments, defaulting to a
-new empty dictionary.
+new empty dictionary. Parameters after ``\code{*}'' or ``\code{*identifier}''
+are keyword-only parameters and may only be passed used keyword arguments.
+
+Parameters may have annotations of the form ``\code{: expression}''
+following the parameter name. Any parameter may have an annotation even
+those of the form \code{*identifier} or \code{**identifier}.
+Functions may have ``return'' annotation of the form ``\code{-> expression}''
+after the parameter list. These annotations can be any valid Python
+expression and are evaluated when the function definition is executed.
+Annotations may be evaluated in a different order than they appear in the
+source code. The presence of annotations does not change the semantics of a
+function. The annotation values are available as values of a dictionary 
+keyed by the parameters' names in the \member{__annotations__}
+attribute of the function object.
+\indexii{function}{annotations}
 
 It is also possible to create anonymous functions (functions not bound
 to a name), for immediate use in expressions.  This uses lambda forms,
@@ -482,7 +496,7 @@
 defined in a ``\keyword{def}'' statement can be passed around or
 assigned to another name just like a function defined by a lambda
 form.  The ``\keyword{def}'' form is actually more powerful since it
-allows the execution of multiple statements.
+allows the execution of multiple statements and annotations.
 \indexii{lambda}{form}
 
 \strong{Programmer's note:} Functions are first-class objects.  A

Modified: python/branches/p3yk-noslice/Doc/texinputs/python.sty
==============================================================================
--- python/branches/p3yk-noslice/Doc/texinputs/python.sty	(original)
+++ python/branches/p3yk-noslice/Doc/texinputs/python.sty	Wed Jul 11 15:40:56 2007
@@ -612,7 +612,7 @@
 \newenvironment{cfuncdesc}[4][\py at badkey]{
   \begin{fulllineitems}
     \cfuncline{#2}{#3}{#4}
-    \ifx#1\@undefined\else%
+    \ifx\@undefined#1\relax\else%
       \emph{Return value: \textbf{#1}.}\\
     \fi
 }{\end{fulllineitems}}
@@ -629,7 +629,7 @@
 \newenvironment{ctypedesc}[2][\py at badkey]{
   \begin{fulllineitems}
     \item[\bfcode{#2}%
-    \ifx#1\@undefined%
+    \ifx\@undefined#1\relax%
       \index{#2@{\py at idxcode{#2}} (C type)}
     \else%
       \index{#2@{\py at idxcode{#1}} (C type)}
@@ -712,7 +712,7 @@
 % \begin{methoddesc}[classname]{methodname}{args}
 \newcommand{\methodline}[3][\@undefined]{
   \methodlineni{#2}{#3}
-  \ifx#1\@undefined
+  \ifx\@undefined#1\relax
     \index{#2@{\py at idxcode{#2()}} (\py at thisclass\ method)}
   \else
     \index{#2@{\py at idxcode{#2()}} (#1 method)}
@@ -720,7 +720,7 @@
 }
 \newenvironment{methoddesc}[3][\@undefined]{
   \begin{fulllineitems}
-    \ifx#1\@undefined
+    \ifx\@undefined#1\relax
       \methodline{#2}{#3}
     \else
       \def\py at thisclass{#1}
@@ -740,7 +740,7 @@
 % object data attribute --------------------------------------------------
 % \begin{memberdesc}[classname]{membername}
 \newcommand{\memberline}[2][\py at classbadkey]{%
-  \ifx#1\@undefined
+  \ifx\@undefined#1\relax
     \memberlineni{#2}
     \index{#2@{\py at idxcode{#2}} (\py at thisclass\ attribute)}
   \else
@@ -750,7 +750,7 @@
 }
 \newenvironment{memberdesc}[2][\py at classbadkey]{
   \begin{fulllineitems}
-    \ifx#1\@undefined
+    \ifx\@undefined#1\relax
       \memberline{#2}
     \else
       \def\py at thisclass{#1}
@@ -1046,14 +1046,14 @@
 %  \versionchanged[short explanation]{2.0}
 %
 \newcommand{\versionadded}[2][\py at badkey]{%
-  \ifx#1\@undefined%
+  \ifx\@undefined#1\relax%
     {  New in version #2.  }%
   \else%
     {  New in version #2:\ #1.  }%
   \fi%
 }
 \newcommand{\versionchanged}[2][\py at badkey]{%
-  \ifx#1\@undefined%
+  \ifx\@undefined#1\relax%
     {  Changed in version #2.  }%
   \else%
     {  Changed in version #2:\ #1.  }%

Modified: python/branches/p3yk-noslice/Doc/tools/buildindex.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/buildindex.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/buildindex.py	Wed Jul 11 15:40:56 2007
@@ -38,6 +38,15 @@
         self.text = split_entry_text(str)
         self.key = split_entry_key(str)
 
+    def __eq__(self, other):
+        return cmp(self, other) == 0
+
+    def __lt__(self, other):
+        return cmp(self, other) == -1
+
+    def __gt__(self, other):
+        return cmp(self, other) == 1
+
     def __cmp__(self, other):
         """Comparison operator includes sequence number, for use with
         list.sort()."""
@@ -380,8 +389,8 @@
         sys.stderr.write("\n%s: %d index nodes" % (program, num_nodes))
     else:
         open(ofn, "w").write(html)
-        print
-        print "%s: %d index nodes" % (program, num_nodes)
+        print()
+        print("%s: %d index nodes" % (program, num_nodes))
 
 
 if __name__ == "__main__":

Modified: python/branches/p3yk-noslice/Doc/tools/custlib.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/custlib.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/custlib.py	Wed Jul 11 15:40:56 2007
@@ -31,7 +31,7 @@
         modules[base.lower()] = base
 
 # Minor oddity: the types module is documented in libtypes2.tex
-if modules.has_key('types'):
+if 'types' in modules:
     del modules['types']
     modules['types2'] = None
 
@@ -44,8 +44,8 @@
     modname = file[3:-4]
     docs[modname] = modname
 
-mlist = modules.keys()
-mlist = filter(lambda x, docs=docs: docs.has_key(x), mlist)
+mlist = list(modules.keys())
+mlist = filter(lambda x, docs=docs: x in docs, mlist)
 mlist.sort()
 mlist = map(lambda x, docs=docs: docs[x], mlist)
 
@@ -55,7 +55,7 @@
 
 # Write the boilerplate
 # XXX should be fancied up.
-print """\documentstyle[twoside,11pt,myformat]{report}
+print("""\documentstyle[twoside,11pt,myformat]{report}
 \\title{Python Library Reference}
 \\input{boilerplate}
 \\makeindex                     % tell \\index to actually write the .idx file
@@ -68,11 +68,11 @@
 \\end{abstract}
 \\pagebreak
 {\\parskip = 0mm \\tableofcontents}
-\\pagebreak\\pagenumbering{arabic}"""
+\\pagebreak\\pagenumbering{arabic}""")
 
 for modname in mlist:
-    print "\\input{lib%s}" % (modname,)
+    print("\\input{lib%s}" % (modname,))
 
 # Write the end
-print """\\input{custlib.ind}                   % Index
-\\end{document}"""
+print("""\\input{custlib.ind}                   % Index
+\\end{document}""")

Modified: python/branches/p3yk-noslice/Doc/tools/getversioninfo
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/getversioninfo	(original)
+++ python/branches/p3yk-noslice/Doc/tools/getversioninfo	Wed Jul 11 15:40:56 2007
@@ -68,4 +68,4 @@
            "\\setshortversion{%s}\n"
            % (release, releaseinfo, shortversion))
 
-print release + releaseinfo
+print(release + releaseinfo)

Modified: python/branches/p3yk-noslice/Doc/tools/keywords.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/keywords.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/keywords.py	Wed Jul 11 15:40:56 2007
@@ -21,5 +21,5 @@
 nrows = (len(l)+ncols-1)/ncols
 for i in range(nrows):
     for j in range(i, len(l), nrows):
-        print l[j].ljust(10),
-    print
+        print(l[j].ljust(10), end=' ')
+    print()

Modified: python/branches/p3yk-noslice/Doc/tools/listmodules
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/listmodules	(original)
+++ python/branches/p3yk-noslice/Doc/tools/listmodules	Wed Jul 11 15:40:56 2007
@@ -34,12 +34,11 @@
 import glob
 import os
 import re
-import string
 import sys
 
 
-REMOVE_DIRS = ["dos-8x3", "encodings", "distutils",
-               "lib-old", "lib-stdwin", "test"]
+REMOVE_DIRS = ["encodings", "distutils",
+               "lib-old", ""test"]
 
 
 def main():
@@ -156,17 +155,17 @@
     else:
         modules = modules_by_name.keys()
         modules.sort()
-        print string.join(modules, "\n")
+        print "\n".join(modules)
 
 
 def ignore_from_modulelist(data, ignore_dict):
-    for name in string.split(data):
+    for name in data.split():
         ignore_dict[name] = name
 
 def ignore_from_idx(data, ignore_dict):
-    data = string.replace(data, r"\hackscore  {}", "_")
+    data = data.replace(r"\hackscore  {}", "_")
     rx = re.compile(r"\\indexentry\s*{([^@]*)@")
-    for line in string.split(data, "\n"):
+    for line in data.split("\n"):
         m = rx.match(line)
         if m:
             name = m.group(1)

Modified: python/branches/p3yk-noslice/Doc/tools/listmodules.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/listmodules.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/listmodules.py	Wed Jul 11 15:40:56 2007
@@ -40,8 +40,7 @@
     for p in path:
         modules.update(getmodules(p))
 
-    keys = modules.keys()
-    keys.sort()
+    keys = sorted(modules.keys())
 
     # filter out known test packages
     def cb(m):
@@ -79,7 +78,7 @@
 
     if out is not sys.stdout:
         out.close()
-        print out.name, "ok (%d modules)" % len(modules)
+        print(out.name, "ok (%d modules)" % len(modules))
 
 def getmodules(p):
     # get modules in a given directory

Modified: python/branches/p3yk-noslice/Doc/tools/mkackshtml
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/mkackshtml	(original)
+++ python/branches/p3yk-noslice/Doc/tools/mkackshtml	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,6 @@
 #! /usr/bin/env python
 #  -*- Python -*-
 
-import string
 import support
 import sys
 
@@ -12,7 +11,7 @@
         line = fp.readline()
         if not line:
             break
-        line = string.strip(line)
+        line = line.strip()
         if line:
             names.append(line)
         else:
@@ -26,13 +25,13 @@
     options.variables["title"] = "Acknowledgements"
     options.parse(sys.argv[1:])
     names = collect(sys.stdin)
-    percol = (len(names) + options.columns - 1) / options.columns
+    percol = (len(names) + options.columns - 1) // options.columns
     colnums = []
     for i in range(options.columns):
         colnums.append(percol*i)
     options.aesop_type = "information"
     fp = options.get_output_file()
-    fp.write(string.rstrip(options.get_header()) + "\n")
+    fp.write(options.get_header().rstrip() + "\n")
     fp.write(THANKS + "\n")
     fp.write('<table width="100%" align="center">\n')
     for i in range(percol):
@@ -44,7 +43,7 @@
                 pass
         fp.write("  </tr>\n")
     fp.write("</table>\n")
-    fp.write(string.rstrip(options.get_footer()) + "\n")
+    fp.write(options.get_footer().rstrip() + "\n")
     fp.close()
 
 THANKS = '''\

Modified: python/branches/p3yk-noslice/Doc/tools/mkhowto
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/mkhowto	(original)
+++ python/branches/p3yk-noslice/Doc/tools/mkhowto	Wed Jul 11 15:40:56 2007
@@ -65,11 +65,11 @@
 
 
 def usage(options, file):
-    print >>file, __doc__ % options
+    print(__doc__ % options, file=file)
 
 def error(options, message, err=2):
-    print >>sys.stderr, message
-    print >>sys.stderr
+    print(message, file=sys.stderr)
+    print(file=sys.stderr)
     usage(options, sys.stderr)
     sys.exit(2)
 
@@ -132,7 +132,7 @@
         try:
             return getattr(self, key)
         except AttributeError:
-            raise KeyError, key
+            raise KeyError(key)
 
     def parse(self, args):
         opts, args = getopt.getopt(args, "Hi:a:s:lDkqr:",
@@ -289,7 +289,7 @@
                 if not imgs:
                     self.warning(
                         "Could not locate support images of type %s."
-                        % `self.options.image_type`)
+                        % repr(self.options.image_type))
                 for fn in imgs:
                     new_fn = os.path.join(self.builddir, os.path.basename(fn))
                     shutil.copyfile(fn, new_fn)
@@ -534,7 +534,7 @@
     def message(self, msg):
         msg = "+++ " + msg
         if not self.options.quiet:
-            print msg
+            print(msg)
         self.log(msg + "\n")
 
     def warning(self, msg):

Modified: python/branches/p3yk-noslice/Doc/tools/mkmodindex
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/mkmodindex	(original)
+++ python/branches/p3yk-noslice/Doc/tools/mkmodindex	Wed Jul 11 15:40:56 2007
@@ -49,7 +49,7 @@
 
     def usage(self):
         program = os.path.basename(sys.argv[0])
-        print __doc__ % {"program": program}
+        print(__doc__ % {"program": program})
 
     links = [
         ('author', 'acks.html',  'Acknowledgements'),
@@ -143,8 +143,8 @@
     if options.outputfile == "-":
         sys.stderr.write("%s: %d index nodes\n" % (program, num_nodes))
     else:
-        print
-        print "%s: %d index nodes" % (program, num_nodes)
+        print()
+        print("%s: %d index nodes" % (program, num_nodes))
 
 
 PLAT_DISCUSS = """

Modified: python/branches/p3yk-noslice/Doc/tools/prechm.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/prechm.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/prechm.py	Wed Jul 11 15:40:56 2007
@@ -413,7 +413,7 @@
 def do_index(library, output):
     output.write('<UL>\n')
     for book in library:
-        print '\t', book.title, '-', book.indexpage
+        print('\t', book.title, '-', book.indexpage)
         if book.indexpage:
             index(book.directory, book.indexpage, output)
     output.write('</UL>\n')
@@ -421,7 +421,7 @@
 def do_content(library, version, output):
     output.write(contents_header)
     for book in library:
-        print '\t', book.title, '-', book.firstpage
+        print('\t', book.title, '-', book.firstpage)
         path = book.directory + "/" + book.firstpage
         output.write('<LI>')
         output.write(object_sitemap % (book.title, path))
@@ -449,12 +449,12 @@
     try:
         p = open(file, "w")
     except IOError as msg:
-        print file, ":", msg
+        print(file, ":", msg)
         sys.exit(1)
     return p
 
 def usage():
-    print usage_mode
+    print(usage_mode)
     sys.exit(0)
 
 def do_it(args = None):
@@ -467,7 +467,7 @@
     try:
         optlist, args = getopt.getopt(args, 'ckpv:')
     except getopt.error as msg:
-        print msg
+        print(msg)
         usage()
 
     if not args or len(args) > 1:
@@ -487,15 +487,15 @@
     if not (('-p','') in optlist):
         fname = arch + '.stp'
         f = openfile(fname)
-        print "Building stoplist", fname, "..."
+        print("Building stoplist", fname, "...")
         words = stop_list.split()
         words.sort()
         for word in words:
-            print >> f, word
+            print(word, file=f)
         f.close()
 
         f = openfile(arch + '.hhp')
-        print "Building Project..."
+        print("Building Project...")
         do_project(library, f, arch, version)
         if version == '2.0.0':
             for image in os.listdir('icons'):
@@ -505,13 +505,13 @@
 
     if not (('-c','') in optlist):
         f = openfile(arch + '.hhc')
-        print "Building Table of Content..."
+        print("Building Table of Content...")
         do_content(library, version, f)
         f.close()
 
     if not (('-k','') in optlist):
         f = openfile(arch + '.hhk')
-        print "Building Index..."
+        print("Building Index...")
         do_index(library, f)
         f.close()
 

Modified: python/branches/p3yk-noslice/Doc/tools/refcounts.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/refcounts.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/refcounts.py	Wed Jul 11 15:40:56 2007
@@ -69,24 +69,23 @@
 def dump(d):
     """Dump the data in the 'canonical' format, with functions in
     sorted order."""
-    items = d.items()
-    items.sort()
+    items = sorted(d.items())
     first = 1
     for k, entry in items:
         if first:
             first = 0
         else:
-            print
+            print()
         s = entry.name + ":%s:%s:%s:"
         if entry.result_refs is None:
             r = ""
         else:
             r = entry.result_refs
-        print s % (entry.result_type, "", r)
+        print(s % (entry.result_type, "", r))
         for t, n, r in entry.args:
             if r is None:
                 r = ""
-            print s % (t, n, r)
+            print(s % (t, n, r))
 
 
 def main():

Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/docfixer.py	Wed Jul 11 15:40:56 2007
@@ -210,8 +210,7 @@
     # 2a.
     if descriptor.hasAttribute("var"):
         if descname != "opcodedesc":
-            raise RuntimeError, \
-                  "got 'var' attribute on descriptor other than opcodedesc"
+            raise RuntimeError("got 'var' attribute on descriptor other than opcodedesc")
         variable = descriptor.getAttribute("var")
         if variable:
             args = doc.createElement("args")
@@ -241,7 +240,7 @@
             try:
                 sig = methodline_to_signature(doc, children[pos])
             except KeyError:
-                print oldchild.toxml()
+                print(oldchild.toxml())
                 raise
             newchildren.append(sig)
         else:
@@ -347,7 +346,7 @@
     while queue:
         node = queue[0]
         del queue[0]
-        if wsmap.has_key(node.nodeName):
+        if node.nodeName in wsmap:
             fixups.append(node)
         for child in node.childNodes:
             if child.nodeType == ELEMENT:
@@ -962,8 +961,7 @@
             gi = node.tagName
             if knownempty(gi):
                 if node.hasChildNodes():
-                    raise ValueError, \
-                          "declared-empty node <%s> has children" % gi
+                    raise ValueError("declared-empty node <%s> has children" % gi)
                 ofp.write("e\n")
             for k, value in node.attributes.items():
                 if _token_rx.match(value):
@@ -979,7 +977,7 @@
         elif nodeType == ENTITY_REFERENCE:
             ofp.write("&%s\n" % node.nodeName)
         else:
-            raise RuntimeError, "unsupported node type: %s" % nodeType
+            raise RuntimeError("unsupported node type: %s" % nodeType)
 
 
 def convert(ifp, ofp):
@@ -1033,7 +1031,7 @@
     for gi in events.parser.get_empties():
         d[gi] = gi
     for key in ("author", "pep", "rfc"):
-        if d.has_key(key):
+        if key in d:
             del d[key]
     knownempty = d.has_key
     #

Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/esis2sgml.py	Wed Jul 11 15:40:56 2007
@@ -44,8 +44,7 @@
 
 
 def format_attrs(attrs, xml=0):
-    attrs = attrs.items()
-    attrs.sort()
+    attrs = sorted(attrs.items())
     parts = []
     append = parts.append
     for name, value in attrs:
@@ -149,7 +148,7 @@
             ofp.write("&%s;" % data)
             knownempty = 0
         else:
-            raise RuntimeError, "unrecognized ESIS event type: '%s'" % type
+            raise RuntimeError("unrecognized ESIS event type: '%s'" % type)
 
     if LIST_EMPTIES:
         dump_empty_element_names(knownempties)
@@ -170,8 +169,7 @@
             if gi:
                 d[gi] = gi
     fp = open(EMPTIES_FILENAME, "w")
-    gilist = d.keys()
-    gilist.sort()
+    gilist = sorted(d.keys())
     fp.write("\n".join(gilist))
     fp.write("\n")
     fp.close()

Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/esistools.py	Wed Jul 11 15:40:56 2007
@@ -29,7 +29,7 @@
             n, s = s.split(";", 1)
             r = r + unichr(int(n))
         else:
-            raise ValueError, "can't handle %r" % s
+            raise ValueError("can't handle %r" % s)
     return r
 
 
@@ -80,7 +80,7 @@
             self.setErrorHandler(errorHandler)
 
     def get_empties(self):
-        return self._empties.keys()
+        return list(self._empties.keys())
 
     #
     #  XMLReader interface
@@ -270,7 +270,7 @@
         return self._attrs[name][0]
 
     def get(self, name, default=None):
-        if self._attrs.has_key(name):
+        if name in self._attrs:
             return self._attrs[name][0]
         return default
 
@@ -282,7 +282,7 @@
 
     def values(self):
         L = []
-        for value, type in self._attrs.values():
+        for value, type in list(self._attrs.values()):
             L.append(value)
         return L
 

Modified: python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/sgmlconv/latex2esis.py	Wed Jul 11 15:40:56 2007
@@ -472,7 +472,7 @@
         name = attrs["name"]
         self.__current = TableEntry(name, environment=1)
         self.__current.verbatim = attrs.get("verbatim") == "yes"
-        if attrs.has_key("outputname"):
+        if "outputname" in attrs:
             self.__current.outputname = attrs.get("outputname")
         self.__current.endcloses = attrs.get("endcloses", "").split()
     def end_environment(self):
@@ -482,11 +482,11 @@
         name = attrs["name"]
         self.__current = TableEntry(name)
         self.__current.closes = attrs.get("closes", "").split()
-        if attrs.has_key("outputname"):
+        if "outputname" in attrs:
             self.__current.outputname = attrs.get("outputname")
     def end_macro(self):
         name = self.__current.name
-        if self.__table.has_key(name):
+        if name in self.__table:
             raise ValueError("name %r already in use" % (name,))
         self.__table[name] = self.__current
         self.__current = None

Modified: python/branches/p3yk-noslice/Doc/tools/undoc_symbols.py
==============================================================================
--- python/branches/p3yk-noslice/Doc/tools/undoc_symbols.py	(original)
+++ python/branches/p3yk-noslice/Doc/tools/undoc_symbols.py	Wed Jul 11 15:40:56 2007
@@ -80,11 +80,10 @@
     fp = os.popen("ctags -IPyAPI_FUNC -IPy_GCC_ATTRIBUTE --c-types=%s -f - %s"
                   % (TAG_KINDS, incfiles))
     dict = findnames(fp, prefix)
-    names = dict.keys()
-    names.sort()
+    names = sorted(dict.keys())
     for name in names:
         if not re.search("%s\\W" % name, docs):
-            print dict[name], name
+            print(dict[name], name)
 
 if __name__ == '__main__':
     srcdir = os.path.dirname(sys.argv[0])

Modified: python/branches/p3yk-noslice/Doc/tut/glossary.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/tut/glossary.tex	(original)
+++ python/branches/p3yk-noslice/Doc/tut/glossary.tex	Wed Jul 11 15:40:56 2007
@@ -117,7 +117,7 @@
 \keyword{yield} elements back to the caller.  The function execution is
 stopped at the {}\keyword{yield} keyword (returning the result) and is
 resumed there when the next element is requested by calling the
-\method{next()} method of the returned iterator.
+\method{__next__()} method of the returned iterator.
 
 \index{generator expression}
 \item[generator expression]
@@ -207,10 +207,10 @@
 \index{iterator}
 \item[iterator]
 An object representing a stream of data.  Repeated calls to the
-iterator's \method{next()} method return successive items in the
+iterator's \method{__next__()} method return successive items in the
 stream.  When no more data is available a \exception{StopIteration}
 exception is raised instead.  At this point, the iterator object is
-exhausted and any further calls to its \method{next()} method just
+exhausted and any further calls to its \method{__next__()} method just
 raise \exception{StopIteration} again.  Iterators are required to have
 an \method{__iter__()} method that returns the iterator object
 itself so every iterator is also iterable and may be used in most

Modified: python/branches/p3yk-noslice/Doc/tut/tut.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/tut/tut.tex	(original)
+++ python/branches/p3yk-noslice/Doc/tut/tut.tex	Wed Jul 11 15:40:56 2007
@@ -184,12 +184,12 @@
 \file{/usr/local/python} is a popular alternative location.)
 
 On Windows machines, the Python installation is usually placed in
-\file{C:\e Python24}, though you can change this when you're running
+\file{C:\e Python30}, though you can change this when you're running
 the installer.  To add this directory to your path, 
 you can type the following command into the command prompt in a DOS box:
 
 \begin{verbatim}
-set path=%path%;C:\python24
+set path=%path%;C:\python30
 \end{verbatim}
 
 
@@ -813,7 +813,7 @@
 IndexError: string index out of range
 \end{verbatim}
 
-The best way to remember how slices work is to think of the indices as
+One way to remember how slices work is to think of the indices as
 pointing \emph{between} characters, with the left edge of the first
 character numbered 0.  Then the right edge of the last character of a
 string of \var{n} characters has index \var{n}, for example:
@@ -2260,7 +2260,7 @@
 function.
 
 \begin{verbatim}
->>> for i in reversed(xrange(1,10,2)):
+>>> for i in reversed(range(1,10,2)):
 ...     print i
 ...
 9
@@ -2605,8 +2605,8 @@
 efficiency or to provide access to operating system primitives such as
 system calls.  The set of such modules is a configuration option which
 also depends on the underlying platform  For example,
-the \module{amoeba} module is only provided on systems that somehow
-support Amoeba primitives.  One particular module deserves some
+the \module{winreg} module is only provided on Windows systems.
+One particular module deserves some
 attention: \ulink{\module{sys}}{../lib/module-sys.html}%
 \refstmodindex{sys}, which is built into every 
 Python interpreter.  The variables \code{sys.ps1} and
@@ -2653,7 +2653,7 @@
 ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
  '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 
  'builtin_module_names', 'byteorder', 'callstats', 'copyright',
- 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
+ 'displayhook', 'exc_info', 'excepthook',
  'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
  'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
  'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
@@ -2689,23 +2689,23 @@
  'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
  'NotImplementedError', 'OSError', 'OverflowError', 
  'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
- 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
+ 'RuntimeWarning', 'StopIteration', 'SyntaxError',
  'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
  'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
  'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
  'UserWarning', 'ValueError', 'Warning', 'WindowsError',
  'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
  '__name__', 'abs', 'basestring', 'bool', 'buffer',
- 'callable', 'chr', 'classmethod', 'cmp', 'compile',
+ 'chr', 'classmethod', 'cmp', 'compile',
  'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
- 'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float',
+ 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
  'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
- 'id', 'int', 'isinstance', 'issubclass', 'iter',
+ 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
  'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
  'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
- 'reload', 'repr', 'reversed', 'round', 'set',
+ 'repr', 'reversed', 'round', 'set',
  'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
- 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
+ 'tuple', 'type', 'unichr', 'unicode', 'vars', 'zip']
 \end{verbatim}
 
 
@@ -2734,9 +2734,9 @@
 hierarchical filesystem):
 
 \begin{verbatim}
-Sound/                          Top-level package
+sound/                          Top-level package
       __init__.py               Initialize the sound package
-      Formats/                  Subpackage for file format conversions
+      formats/                  Subpackage for file format conversions
               __init__.py
               wavread.py
               wavwrite.py
@@ -2745,13 +2745,13 @@
               auread.py
               auwrite.py
               ...
-      Effects/                  Subpackage for sound effects
+      effects/                  Subpackage for sound effects
               __init__.py
               echo.py
               surround.py
               reverse.py
               ...
-      Filters/                  Subpackage for filters
+      filters/                  Subpackage for filters
               __init__.py
               equalizer.py
               vocoder.py
@@ -2774,20 +2774,20 @@
 package, for example:
 
 \begin{verbatim}
-import Sound.Effects.echo
+import sound.effects.echo
 \end{verbatim}
 
-This loads the submodule \module{Sound.Effects.echo}.  It must be referenced
+This loads the submodule \module{sound.effects.echo}.  It must be referenced
 with its full name.
 
 \begin{verbatim}
-Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
+sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
 \end{verbatim}
 
 An alternative way of importing the submodule is:
 
 \begin{verbatim}
-from Sound.Effects import echo
+from sound.effects import echo
 \end{verbatim}
 
 This also loads the submodule \module{echo}, and makes it available without
@@ -2800,7 +2800,7 @@
 Yet another variation is to import the desired function or variable directly:
 
 \begin{verbatim}
-from Sound.Effects.echo import echofilter
+from sound.effects.echo import echofilter
 \end{verbatim}
 
 Again, this loads the submodule \module{echo}, but this makes its function
@@ -2827,7 +2827,7 @@
 %The \code{__all__} Attribute
 
 \ttindex{__all__}
-Now what happens when the user writes \code{from Sound.Effects import
+Now what happens when the user writes \code{from sound.effects import
 *}?  Ideally, one would hope that this somehow goes out to the
 filesystem, finds which submodules are present in the package, and
 imports them all.  Unfortunately, this operation does not work very
@@ -2849,19 +2849,19 @@
 up-to-date when a new version of the package is released.  Package
 authors may also decide not to support it, if they don't see a use for
 importing * from their package.  For example, the file
-\file{Sounds/Effects/__init__.py} could contain the following code:
+\file{sounds/effects/__init__.py} could contain the following code:
 
 \begin{verbatim}
 __all__ = ["echo", "surround", "reverse"]
 \end{verbatim}
 
-This would mean that \code{from Sound.Effects import *} would
-import the three named submodules of the \module{Sound} package.
+This would mean that \code{from sound.effects import *} would
+import the three named submodules of the \module{sound} package.
 
-If \code{__all__} is not defined, the statement \code{from Sound.Effects
+If \code{__all__} is not defined, the statement \code{from sound.effects
 import *} does \emph{not} import all submodules from the package
-\module{Sound.Effects} into the current namespace; it only ensures that the
-package \module{Sound.Effects} has been imported (possibly running any
+\module{sound.effects} into the current namespace; it only ensures that the
+package \module{sound.effects} has been imported (possibly running any
 initialization code in \file{__init__.py}) and then imports whatever names are
 defined in the package.  This includes any names defined (and
 submodules explicitly loaded) by \file{__init__.py}.  It also includes any
@@ -2869,14 +2869,14 @@
 import statements.  Consider this code:
 
 \begin{verbatim}
-import Sound.Effects.echo
-import Sound.Effects.surround
-from Sound.Effects import *
+import sound.effects.echo
+import sound.effects.surround
+from sound.effects import *
 \end{verbatim}
 
 In this example, the echo and surround modules are imported in the
 current namespace because they are defined in the
-\module{Sound.Effects} package when the \code{from...import} statement
+\module{sound.effects} package when the \code{from...import} statement
 is executed.  (This also works when \code{__all__} is defined.)
 
 Note that in general the practice of importing \code{*} from a module or
@@ -2904,12 +2904,12 @@
 statement looks for a top-level module with the given name.
 
 When packages are structured into subpackages (as with the
-\module{Sound} package in the example), there's no shortcut to refer
+\module{sound} package in the example), there's no shortcut to refer
 to submodules of sibling packages - the full name of the subpackage
 must be used.  For example, if the module
-\module{Sound.Filters.vocoder} needs to use the \module{echo} module
-in the \module{Sound.Effects} package, it can use \code{from
-Sound.Effects import echo}.
+\module{sound.filters.vocoder} needs to use the \module{echo} module
+in the \module{sound.effects} package, it can use \code{from
+sound.effects import echo}.
 
 Starting with Python 2.5, in addition to the implicit relative imports
 described above, you can write explicit relative imports with the
@@ -2920,8 +2920,8 @@
 
 \begin{verbatim}
 from . import echo
-from .. import Formats
-from ..Filters import equalizer
+from .. import formats
+from ..filters import equalizer
 \end{verbatim}
 
 Note that both explicit and implicit relative imports are based on the
@@ -3539,7 +3539,7 @@
 ...    print 'x =', x
 ...    print 'y =', y
 ...
-<type 'instance'>
+<type 'Exception'>
 ('spam', 'eggs')
 ('spam', 'eggs')
 x = spam
@@ -4312,8 +4312,7 @@
     <statement-N>
 \end{verbatim}
 
-The only rule necessary to explain the semantics is the resolution
-rule used for class attribute references.  This is depth-first,
+For old-style classes, the only rule is depth-first,
 left-to-right.  Thus, if an attribute is not found in
 \class{DerivedClassName}, it is searched in \class{Base1}, then
 (recursively) in the base classes of \class{Base1}, and only if it is
@@ -4328,16 +4327,26 @@
 rule makes no differences between direct and inherited attributes of
 \class{Base1}.)
 
-It is clear that indiscriminate use of multiple inheritance is a
-maintenance nightmare, given the reliance in Python on conventions to
-avoid accidental name conflicts.  A well-known problem with multiple
-inheritance is a class derived from two classes that happen to have a
-common base class.  While it is easy enough to figure out what happens
-in this case (the instance will have a single copy of ``instance
-variables'' or data attributes used by the common base class), it is
-not clear that these semantics are in any way useful.
+For new-style classes, the method resolution order changes dynamically
+to support cooperative calls to \function{super()}.  This approach
+is known in some other multiple-inheritance languages as call-next-method
+and is more powerful than the super call found in single-inheritance languages.
+
+With new-style classes, dynamic ordering is necessary because all 
+cases of multiple inheritance exhibit one or more diamond relationships
+(where one at least one of the parent classes can be accessed through
+multiple paths from the bottommost class).  For example, all new-style
+classes inherit from \class{object}, so any case of multiple inheritance
+provides more than one path to reach \class{object}.  To keep the
+base classes from being accessed more than once, the dynamic algorithm
+linearizes the search order in a way that preserves the left-to-right
+ordering specified in each class, that calls each parent only once, and
+that is monotonic (meaning that a class can be subclassed without affecting
+the precedence order of its parents).  Taken together, these properties
+make it possible to design reliable and extensible classes with
+multiple inheritance.  For more detail, see 
+\url{http://www.python.org/download/releases/2.3/mro/}.
 
-%% XXX Add rules for new-style MRO?
 
 \section{Private Variables \label{private}}
 
@@ -4488,34 +4497,35 @@
 pervades and unifies Python.  Behind the scenes, the \keyword{for}
 statement calls \function{iter()} on the container object.  The
 function returns an iterator object that defines the method
-\method{next()} which accesses elements in the container one at a
-time.  When there are no more elements, \method{next()} raises a
+\method{__next__()} which accesses elements in the container one at a
+time.  When there are no more elements, \method{__next__()} raises a
 \exception{StopIteration} exception which tells the \keyword{for} loop
-to terminate.  This example shows how it all works:
+to terminate.  You can call the \method{__next__()} method using the
+\function{next()} builtin; this example shows how it all works:
 
 \begin{verbatim}
 >>> s = 'abc'
 >>> it = iter(s)
 >>> it
 <iterator object at 0x00A1DB50>
->>> it.next()
+>>> next(it)
 'a'
->>> it.next()
+>>> next(it)
 'b'
->>> it.next()
+>>> next(it)
 'c'
->>> it.next()
+>>> next(it)
 
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
-    it.next()
+    next(it)
 StopIteration
 \end{verbatim}
 
 Having seen the mechanics behind the iterator protocol, it is easy to add
 iterator behavior to your classes.  Define a \method{__iter__()} method
-which returns an object with a \method{next()} method.  If the class defines
-\method{next()}, then \method{__iter__()} can just return \code{self}:
+which returns an object with a \method{__next__()} method.  If the class defines
+\method{__next__()}, then \method{__iter__()} can just return \code{self}:
 
 \begin{verbatim}
 class Reverse:
@@ -4525,7 +4535,7 @@
         self.index = len(data)
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.index == 0:
             raise StopIteration
         self.index = self.index - 1
@@ -4545,7 +4555,7 @@
 
 Generators are a simple and powerful tool for creating iterators.  They are
 written like regular functions but use the \keyword{yield} statement whenever
-they want to return data.  Each time \method{next()} is called, the
+they want to return data.  Each time \function{next()} is called on it, the
 generator resumes where it left-off (it remembers all the data values and
 which statement was last executed).  An example shows that generators can
 be trivially easy to create:
@@ -4566,7 +4576,7 @@
 
 Anything that can be done with generators can also be done with class based
 iterators as described in the previous section.  What makes generators so
-compact is that the \method{__iter__()} and \method{next()} methods are
+compact is that the \method{__iter__()} and \method{__next__()} methods are
 created automatically.
 
 Another key feature is that the local variables and execution state
@@ -4628,7 +4638,7 @@
 >>> os.system('time 0:02')
 0
 >>> os.getcwd()      # Return the current working directory
-'C:\\Python24'
+'C:\\Python30'
 >>> os.chdir('/server/accesslogs')
 \end{verbatim}
 
@@ -4752,7 +4762,7 @@
 >>> import random
 >>> random.choice(['apple', 'pear', 'banana'])
 'apple'
->>> random.sample(xrange(100), 10)   # sampling without replacement
+>>> random.sample(range(100), 10)   # sampling without replacement
 [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
 >>> random.random()    # random float
 0.17970987693706186
@@ -5233,7 +5243,7 @@
     Traceback (most recent call last):
       File "<pyshell#108>", line 1, in -toplevel-
         d['primary']                # entry was automatically removed
-      File "C:/PY24/lib/weakref.py", line 46, in __getitem__
+      File "C:/python30/lib/weakref.py", line 46, in __getitem__
         o = self.data[key]()
     KeyError: 'primary'
 \end{verbatim}

Deleted: /python/branches/p3yk-noslice/Doc/whatsnew/Makefile
==============================================================================
--- /python/branches/p3yk-noslice/Doc/whatsnew/Makefile	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,3 +0,0 @@
-
-check:
-	../../python.exe ../../Tools/scripts/texcheck.py whatsnew25.tex

Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew23.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew23.tex	(original)
+++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew23.tex	Wed Jul 11 15:40:56 2007
@@ -896,7 +896,7 @@
 \end{seealso}
 
 %======================================================================
-\section{PEP 307: Pickle Enhancements \label{section-pep305}}
+\section{PEP 307: Pickle Enhancements \label{section-pep307}}
 
 The \module{pickle} and \module{cPickle} modules received some
 attention during the 2.3 development cycle.  In 2.2, new-style classes

Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew24.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew24.tex	(original)
+++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew24.tex	Wed Jul 11 15:40:56 2007
@@ -1291,7 +1291,7 @@
 [1, 2, 3]
 >>> list(i2)               # Run the second iterator to exhaustion
 [1, 2, 3]
->\end{verbatim}
+\end{verbatim}
 
 Note that \function{tee()} has to keep copies of the values returned 
 by the iterator; in the worst case, it may need to keep all of them.  

Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex	(original)
+++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew25.tex	Wed Jul 11 15:40:56 2007
@@ -1294,6 +1294,17 @@
 (Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.)
 % Patch 1442927
 
+\item It's now illegal to mix iterating over a file 
+with \code{for line in \var{file}} and calling 
+the file object's \method{read()}/\method{readline()}/\method{readlines()}
+methods.  Iteration uses an internal buffer and the 
+\method{read*()} methods don't use that buffer.  
+Instead they would return the data following the buffer, causing the
+data to appear out of order.  Mixing iteration and these methods will
+now trigger a \exception{ValueError} from the \method{read*()} method.
+(Implemented by Thomas Wouters.)
+% Patch 1397960
+
 \item The \module{struct} module now compiles structure format 
 strings into an internal representation and caches this
 representation, yielding a 20\% speedup.  (Contributed by Bob Ippolito
@@ -1704,8 +1715,8 @@
 In Python code, netlink addresses are represented as a tuple of 2 integers, 
 \code{(\var{pid}, \var{group_mask})}.
 
-Two new methods on socket objects, \method{recv_buf(\var{buffer})} and
-\method{recvfrom_buf(\var{buffer})}, store the received data in an object 
+Two new methods on socket objects, \method{recv_into(\var{buffer})} and
+\method{recvfrom_into(\var{buffer})}, store the received data in an object 
 that supports the buffer protocol instead of returning the data as a
 string.  This means you can put the data directly into an array or a
 memory-mapped file.

Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex	(original)
+++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex	Wed Jul 11 15:40:56 2007
@@ -2,6 +2,46 @@
 \usepackage{distutils}
 % $Id$
 
+% 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 as a comment:
+%
+%       % Patch 12345
+%       XXX Describe the transmogrify() function added to the socket
+%       module.
+%       (Contributed by P.Y. Developer.)
+%
+%    This saves the maintainer the effort of going through the SVN log
+%    when researching a change.
 
 \title{What's New in Python 2.6}
 \release{0.0}
@@ -13,7 +53,7 @@
 \tableofcontents
 
 This article explains the new features in Python 2.6.  No release date
-for Python 2.6 has been set; it will probably be released in late 2007.
+for Python 2.6 has been set; it will probably be released in mid 2008.
 
 % Compare with previous release in 2 - 3 sentences here.
 
@@ -29,6 +69,9 @@
 
 % Large, PEP-level features and changes should be described here.
 
+% Should there be a new section here for 3k migration?
+% Or perhaps a more general section describing module changes/deprecation?
+% sets module deprecated
 
 %======================================================================
 \section{Other Language Changes}
@@ -37,7 +80,13 @@
 language.
 
 \begin{itemize}
-\item TBD
+
+% Bug 1569356
+\item An obscure change: when you use the the \function{locals()}
+function inside a \keyword{class} statement, the resulting dictionary
+no longer returns free variables.  (Free variables, in this case, are
+variables referred to in the \keyword{class} statement 
+that aren't attributes of the class.)
 
 \end{itemize}
 
@@ -47,7 +96,10 @@
 
 \begin{itemize}
 
-\item Optimizations should be described here.
+% Patch 1624059
+\item Internally, a bit is now set in type objects to indicate some of
+the standard built-in types.  This speeds up checking if an object is
+a subclass of one of these types.  (Contributed by Neal Norwitz.)
 
 \end{itemize}
 
@@ -67,6 +119,79 @@
 
 \begin{itemize}
 
+\item New data type in the \module{collections} module:
+\class{NamedTuple(\var{typename}, \var{fieldnames})} is a factory function that
+creates subclasses of the standard tuple whose fields are accessible
+by name as well as index.  For example:
+
+\begin{verbatim}
+var_type = collections.NamedTuple('variable', 
+             'id name type size')
+var = var_type(1, 'frequency', 'int', 4)
+
+print var[0], var.id		# Equivalent
+print var[2], var.type          # Equivalent
+\end{verbatim}
+
+(Contributed by Raymond Hettinger.)
+
+\item New method in the \module{curses} module:
+for a window, \method{chgat()} changes the display characters for a 
+certain number of characters on a single line.
+
+\begin{verbatim}
+# Boldface text starting at y=0,x=21 
+# and affecting the rest of the line.
+stdscr.chgat(0,21, curses.A_BOLD)  
+\end{verbatim}
+
+(Contributed by Fabian Kreutz.)
+
+\item The \module{gopherlib} module has been removed.
+
+\item New function in the \module{heapq} module:
+\function{merge(iter1, iter2, ...)} 
+takes any number of iterables that return data 
+\emph{in sorted order}, 
+and 
+returns a new iterator that returns the contents of
+all the iterators, also in sorted order.  For example:
+
+\begin{verbatim}
+heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
+  [1, 2, 3, 5, 8, 9, 16]
+\end{verbatim}
+
+(Contributed by Raymond Hettinger.)
+
+\item New function in the \module{itertools} module:
+\function{izip_longest(iter1, iter2, ...\optional{, fillvalue})}
+makes tuples from each of the elements; if some of the iterables
+are shorter than others, the missing values 
+are set to \var{fillvalue}.  For example:
+
+\begin{verbatim}
+itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
+  [(1, 1), (2, 2), (3, 3), (None, 4), (None, 5)]
+\end{verbatim}
+
+(Contributed by Raymond Hettinger.)
+
+\item The \module{macfs} module has been removed.  This in turn
+required the \function{macostools.touched()} function to be removed
+because it depended on the \module{macfs} module.
+
+% Patch #1490190
+\item New functions in the \module{posix} module: \function{chflags()}
+and \function{lchflags()} are wrappers for the corresponding system
+calls (where they're available).  Constants for the flag values are
+defined in the \module{stat} module; some possible values include
+\constant{UF_IMMUTABLE} to signal the file may not be changed and
+\constant{UF_APPEND} to indicate that data can only be appended to the
+file.  (Contributed by M. Levinson.)
+
+\item The \module{rgbimg} module has been removed.
+
 \item The \module{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} 

Modified: python/branches/p3yk-noslice/Grammar/Grammar
==============================================================================
--- python/branches/p3yk-noslice/Grammar/Grammar	(original)
+++ python/branches/p3yk-noslice/Grammar/Grammar	Wed Jul 11 15:40:56 2007
@@ -21,25 +21,22 @@
 
 decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
 decorators: decorator+
-funcdef: [decorators] 'def' NAME parameters ['->' test] ':' suite
+decorated: decorators (classdef | funcdef)
+funcdef: 'def' NAME parameters ['->' test] ':' suite
 parameters: '(' [typedargslist] ')'
 typedargslist: ((tfpdef ['=' test] ',')*
-                ('*' [tname] (',' tname ['=' test])* [',' '**' tname] | '**' tname)
+                ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
                 | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
-tname: NAME [':' test]
-tfpdef: tname | '(' tfplist ')'
-tfplist: tfpdef (',' tfpdef)* [',']
+tfpdef: NAME [':' test]
 varargslist: ((vfpdef ['=' test] ',')*
-              ('*' [vname] (',' vname ['=' test])*  [',' '**' vname] | '**' vname)
+              ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] | '**' vfpdef)
               | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
-vname: NAME
-vfpdef: vname | '(' vfplist ')'
-vfplist: vfpdef (',' vfpdef)* [',']
+vfpdef: NAME
 
 stmt: simple_stmt | compound_stmt
 simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
 small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
-             import_stmt | global_stmt | assert_stmt)
+             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
 expr_stmt: testlist (augassign (yield_expr|testlist) |
                      ('=' (yield_expr|testlist))*)
 augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
@@ -55,7 +52,8 @@
 raise_stmt: 'raise' [test [',' test [',' test]]]
 import_stmt: import_name | import_from
 import_name: 'import' dotted_as_names
-import_from: ('from' ('.'* dotted_name | '.'+)
+# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
+import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)
               'import' ('*' | '(' import_as_names ')' | import_as_names))
 import_as_name: NAME ['as' NAME]
 dotted_as_name: dotted_name ['as' NAME]
@@ -63,9 +61,10 @@
 dotted_as_names: dotted_as_name (',' dotted_as_name)*
 dotted_name: NAME ('.' NAME)*
 global_stmt: 'global' NAME (',' NAME)*
+nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
 assert_stmt: 'assert' test [',' test]
 
-compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef
+compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
 if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
 while_stmt: 'while' test ':' suite ['else' ':' suite]
 for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
@@ -80,21 +79,16 @@
 except_clause: 'except' [test ['as' NAME]]
 suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
 
-# Backward compatibility cruft to support:
-# [ x for x in lambda: True, lambda: False if x() ]
-# even while also allowing:
-# lambda x: 5 if x else 2
-# (But not a mix of the two)
-testlist_safe: old_test [(',' old_test)+ [',']]
-old_test: or_test | old_lambdef
-old_lambdef: 'lambda' [varargslist] ':' old_test
-
 test: or_test ['if' or_test 'else' test] | lambdef
+test_nocond: or_test | lambdef_nocond
+lambdef: 'lambda' [varargslist] ':' test
+lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
 or_test: and_test ('or' and_test)*
 and_test: not_test ('and' not_test)*
 not_test: 'not' not_test | comparison
-comparison: expr (comp_op expr)*
+comparison: star_expr (comp_op star_expr)*
 comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
+star_expr: ['*'] expr
 expr: xor_expr ('|' xor_expr)*
 xor_expr: and_expr ('^' and_expr)*
 and_expr: shift_expr ('&' shift_expr)*
@@ -103,33 +97,28 @@
 term: factor (('*'|'/'|'%'|'//') factor)*
 factor: ('+'|'-'|'~') factor | power
 power: atom trailer* ['**' factor]
-atom: ('(' [yield_expr|testlist_gexp] ')' |
-       '[' [listmaker] ']' |
-       '{' [dictsetmaker] '}' |
-       NAME | NUMBER | STRING+ | '.' '.' '.')
-listmaker: test ( list_for | (',' test)* [','] )
-testlist_gexp: test ( gen_for | (',' test)* [','] )
-lambdef: 'lambda' [varargslist] ':' test
+atom: ('(' [yield_expr|testlist_comp] ')' |
+       '[' [testlist_comp] ']' |
+       '{' [dictorsetmaker] '}' |
+       NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
+testlist_comp: test ( comp_for | (',' test)* [','] )
 trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
 subscriptlist: subscript (',' subscript)* [',']
 subscript: test | [test] ':' [test] [sliceop]
 sliceop: ':' [test]
-exprlist: expr (',' expr)* [',']
+exprlist: star_expr (',' star_expr)* [',']
 testlist: test (',' test)* [',']
-dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
+dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
+                  (test (comp_for | (',' test)* [','])) )
 
-classdef: 'class' NAME ['(' [testlist] ')'] ':' suite
+classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
 
 arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
-argument: test [gen_for] | test '=' test  # Really [keyword '='] test
+argument: test [comp_for] | test '=' test  # Really [keyword '='] test
 
-list_iter: list_for | list_if
-list_for: 'for' exprlist 'in' testlist_safe [list_iter]
-list_if: 'if' old_test [list_iter]
-
-gen_iter: gen_for | gen_if
-gen_for: 'for' exprlist 'in' or_test [gen_iter]
-gen_if: 'if' old_test [gen_iter]
+comp_iter: comp_for | comp_if
+comp_for: 'for' exprlist 'in' or_test [comp_iter]
+comp_if: 'if' test_nocond [comp_iter]
 
 testlist1: test (',' test)*
 

Modified: python/branches/p3yk-noslice/Include/Python-ast.h
==============================================================================
--- python/branches/p3yk-noslice/Include/Python-ast.h	(original)
+++ python/branches/p3yk-noslice/Include/Python-ast.h	Wed Jul 11 15:40:56 2007
@@ -66,7 +66,8 @@
                   While_kind=8, If_kind=9, With_kind=10, Raise_kind=11,
                   TryExcept_kind=12, TryFinally_kind=13, Assert_kind=14,
                   Import_kind=15, ImportFrom_kind=16, Global_kind=17,
-                  Expr_kind=18, Pass_kind=19, Break_kind=20, Continue_kind=21};
+                  Nonlocal_kind=18, Expr_kind=19, Pass_kind=20, Break_kind=21,
+                  Continue_kind=22};
 struct _stmt {
         enum _stmt_kind kind;
         union {
@@ -74,14 +75,18 @@
                         identifier name;
                         arguments_ty args;
                         asdl_seq *body;
-                        asdl_seq *decorators;
+                        asdl_seq *decorator_list;
                         expr_ty returns;
                 } FunctionDef;
                 
                 struct {
                         identifier name;
                         asdl_seq *bases;
+                        asdl_seq *keywords;
+                        expr_ty starargs;
+                        expr_ty kwargs;
                         asdl_seq *body;
+                        asdl_seq *decorator_list;
                 } ClassDef;
                 
                 struct {
@@ -165,6 +170,10 @@
                 } Global;
                 
                 struct {
+                        asdl_seq *names;
+                } Nonlocal;
+                
+                struct {
                         expr_ty value;
                 } Expr;
                 
@@ -175,10 +184,11 @@
 
 enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4,
                   IfExp_kind=5, Dict_kind=6, Set_kind=7, ListComp_kind=8,
-                  GeneratorExp_kind=9, Yield_kind=10, Compare_kind=11,
-                  Call_kind=12, Num_kind=13, Str_kind=14, Ellipsis_kind=15,
-                  Attribute_kind=16, Subscript_kind=17, Name_kind=18,
-                  List_kind=19, Tuple_kind=20};
+                  SetComp_kind=9, GeneratorExp_kind=10, Yield_kind=11,
+                  Compare_kind=12, Call_kind=13, Num_kind=14, Str_kind=15,
+                  Bytes_kind=16, Ellipsis_kind=17, Attribute_kind=18,
+                  Subscript_kind=19, Starred_kind=20, Name_kind=21,
+                  List_kind=22, Tuple_kind=23};
 struct _expr {
         enum _expr_kind kind;
         union {
@@ -226,6 +236,11 @@
                 struct {
                         expr_ty elt;
                         asdl_seq *generators;
+                } SetComp;
+                
+                struct {
+                        expr_ty elt;
+                        asdl_seq *generators;
                 } GeneratorExp;
                 
                 struct {
@@ -255,6 +270,10 @@
                 } Str;
                 
                 struct {
+                        string s;
+                } Bytes;
+                
+                struct {
                         expr_ty value;
                         identifier attr;
                         expr_context_ty ctx;
@@ -267,6 +286,11 @@
                 } Subscript;
                 
                 struct {
+                        expr_ty value;
+                        expr_context_ty ctx;
+                } Starred;
+                
+                struct {
                         identifier id;
                         expr_context_ty ctx;
                 } Name;
@@ -332,20 +356,9 @@
         asdl_seq *kw_defaults;
 };
 
-enum _arg_kind {SimpleArg_kind=1, NestedArgs_kind=2};
 struct _arg {
-        enum _arg_kind kind;
-        union {
-                struct {
-                        identifier arg;
-                        expr_ty annotation;
-                } SimpleArg;
-                
-                struct {
-                        asdl_seq *args;
-                } NestedArgs;
-                
-        } v;
+        identifier arg;
+        expr_ty annotation;
 };
 
 struct _keyword {
@@ -369,11 +382,13 @@
 mod_ty _Py_Suite(asdl_seq * body, PyArena *arena);
 #define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7)
 stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body,
-                        asdl_seq * decorators, expr_ty returns, int lineno, int
-                        col_offset, PyArena *arena);
-#define ClassDef(a0, a1, a2, a3, a4, a5) _Py_ClassDef(a0, a1, a2, a3, a4, a5)
-stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int
-                     lineno, int col_offset, PyArena *arena);
+                        asdl_seq * decorator_list, expr_ty returns, int lineno,
+                        int col_offset, PyArena *arena);
+#define ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) _Py_ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)
+stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords,
+                     expr_ty starargs, expr_ty kwargs, asdl_seq * body,
+                     asdl_seq * decorator_list, int lineno, int col_offset,
+                     PyArena *arena);
 #define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3)
 stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena);
 #define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3)
@@ -418,6 +433,9 @@
 #define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3)
 stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena
                    *arena);
+#define Nonlocal(a0, a1, a2, a3) _Py_Nonlocal(a0, a1, a2, a3)
+stmt_ty _Py_Nonlocal(asdl_seq * names, int lineno, int col_offset, PyArena
+                     *arena);
 #define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3)
 stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena);
 #define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2)
@@ -449,6 +467,9 @@
 #define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4)
 expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int
                      col_offset, PyArena *arena);
+#define SetComp(a0, a1, a2, a3, a4) _Py_SetComp(a0, a1, a2, a3, a4)
+expr_ty _Py_SetComp(expr_ty elt, asdl_seq * generators, int lineno, int
+                    col_offset, PyArena *arena);
 #define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4)
 expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int
                          col_offset, PyArena *arena);
@@ -465,6 +486,8 @@
 expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena);
 #define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3)
 expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena);
+#define Bytes(a0, a1, a2, a3) _Py_Bytes(a0, a1, a2, a3)
+expr_ty _Py_Bytes(string s, int lineno, int col_offset, PyArena *arena);
 #define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2)
 expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena);
 #define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5)
@@ -473,6 +496,9 @@
 #define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5)
 expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int
                       lineno, int col_offset, PyArena *arena);
+#define Starred(a0, a1, a2, a3, a4) _Py_Starred(a0, a1, a2, a3, a4)
+expr_ty _Py_Starred(expr_ty value, expr_context_ty ctx, int lineno, int
+                    col_offset, PyArena *arena);
 #define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4)
 expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int
                  col_offset, PyArena *arena);
@@ -500,10 +526,8 @@
                            varargannotation, asdl_seq * kwonlyargs, identifier
                            kwarg, expr_ty kwargannotation, asdl_seq * defaults,
                            asdl_seq * kw_defaults, PyArena *arena);
-#define SimpleArg(a0, a1, a2) _Py_SimpleArg(a0, a1, a2)
-arg_ty _Py_SimpleArg(identifier arg, expr_ty annotation, PyArena *arena);
-#define NestedArgs(a0, a1) _Py_NestedArgs(a0, a1)
-arg_ty _Py_NestedArgs(asdl_seq * args, PyArena *arena);
+#define arg(a0, a1, a2) _Py_arg(a0, a1, a2)
+arg_ty _Py_arg(identifier arg, expr_ty annotation, PyArena *arena);
 #define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2)
 keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena);
 #define alias(a0, a1, a2) _Py_alias(a0, a1, a2)

Modified: python/branches/p3yk-noslice/Include/abstract.h
==============================================================================
--- python/branches/p3yk-noslice/Include/abstract.h	(original)
+++ python/branches/p3yk-noslice/Include/abstract.h	Wed Jul 11 15:40:56 2007
@@ -851,6 +851,14 @@
 	 expression: o1 |= o2.
        */
 
+     PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base);
+
+       /*
+	 Returns the integer n converted to a string with a base, with a base
+	 marker of 0b, 0o or 0x prefixed if applicable.
+	 If n is not an int object, it is converted with PyNumber_Index first.
+       */
+
 
 /*  Sequence protocol:*/
 

Modified: python/branches/p3yk-noslice/Include/asdl.h
==============================================================================
--- python/branches/p3yk-noslice/Include/asdl.h	(original)
+++ python/branches/p3yk-noslice/Include/asdl.h	Wed Jul 11 15:40:56 2007
@@ -5,10 +5,6 @@
 typedef PyObject * string;
 typedef PyObject * object;
 
-#ifndef __cplusplus
-typedef enum {false, true} bool;
-#endif
-
 /* It would be nice if the code generated by asdl_c.py was completely
    independent of Python, but it is a goal the requires too much work
    at this stage.  So, for example, I'll represent identifiers as

Modified: python/branches/p3yk-noslice/Include/bytesobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/bytesobject.h	(original)
+++ python/branches/p3yk-noslice/Include/bytesobject.h	Wed Jul 11 15:40:56 2007
@@ -34,6 +34,7 @@
 
 /* Direct API functions */
 PyAPI_FUNC(PyObject *) PyBytes_FromObject(PyObject *);
+PyAPI_FUNC(PyObject *) PyBytes_Concat(PyObject *, PyObject *);
 PyAPI_FUNC(PyObject *) PyBytes_FromStringAndSize(const char *, Py_ssize_t);
 PyAPI_FUNC(Py_ssize_t) PyBytes_Size(PyObject *);
 PyAPI_FUNC(char *) PyBytes_AsString(PyObject *);

Modified: python/branches/p3yk-noslice/Include/ceval.h
==============================================================================
--- python/branches/p3yk-noslice/Include/ceval.h	(original)
+++ python/branches/p3yk-noslice/Include/ceval.h	Wed Jul 11 15:40:56 2007
@@ -33,7 +33,6 @@
 PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void);
 PyAPI_FUNC(PyObject *) PyEval_GetLocals(void);
 PyAPI_FUNC(struct _frame *) PyEval_GetFrame(void);
-PyAPI_FUNC(int) PyEval_GetRestricted(void);
 
 /* Look at the current frame's (if any) code's co_flags, and turn on
    the corresponding compiler flags in cf->cf_flags.  Return 1 if any

Modified: python/branches/p3yk-noslice/Include/dictobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/dictobject.h	(original)
+++ python/branches/p3yk-noslice/Include/dictobject.h	Wed Jul 11 15:40:56 2007
@@ -90,7 +90,8 @@
 
 PyAPI_DATA(PyTypeObject) PyDict_Type;
 
-#define PyDict_Check(op) PyObject_TypeCheck(op, &PyDict_Type)
+#define PyDict_Check(op) \
+                 PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_DICT_SUBCLASS)
 #define PyDict_CheckExact(op) ((op)->ob_type == &PyDict_Type)
 
 PyAPI_FUNC(PyObject *) PyDict_New(void);

Modified: python/branches/p3yk-noslice/Include/fileobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/fileobject.h	(original)
+++ python/branches/p3yk-noslice/Include/fileobject.h	Wed Jul 11 15:40:56 2007
@@ -55,6 +55,11 @@
 char *Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
 size_t Py_UniversalNewlineFread(char *, size_t, FILE *, PyObject *);
 
+/* A routine to do sanity checking on the file mode string.  returns
+   non-zero on if an exception occurred
+*/
+int _PyFile_SanitizeMode(char *mode);
+
 #ifdef __cplusplus
 }
 #endif

Modified: python/branches/p3yk-noslice/Include/floatobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/floatobject.h	(original)
+++ python/branches/p3yk-noslice/Include/floatobject.h	Wed Jul 11 15:40:56 2007
@@ -21,10 +21,8 @@
 #define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type)
 #define PyFloat_CheckExact(op) ((op)->ob_type == &PyFloat_Type)
 
-/* Return Python float from string PyObject.  Second argument ignored on
-   input, and, if non-NULL, NULL is stored into *junk (this tried to serve a
-   purpose once but can't be made to work as intended). */
-PyAPI_FUNC(PyObject *) PyFloat_FromString(PyObject*, char** junk);
+/* Return Python float from string PyObject. */
+PyAPI_FUNC(PyObject *) PyFloat_FromString(PyObject*);
 
 /* Return Python float from C double. */
 PyAPI_FUNC(PyObject *) PyFloat_FromDouble(double);

Modified: python/branches/p3yk-noslice/Include/frameobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/frameobject.h	(original)
+++ python/branches/p3yk-noslice/Include/frameobject.h	Wed Jul 11 15:40:56 2007
@@ -52,8 +52,6 @@
 PyAPI_DATA(PyTypeObject) PyFrame_Type;
 
 #define PyFrame_Check(op) ((op)->ob_type == &PyFrame_Type)
-#define PyFrame_IsRestricted(f) \
-	((f)->f_builtins != (f)->f_tstate->interp->builtins)
 
 PyAPI_FUNC(PyFrameObject *) PyFrame_New(PyThreadState *, PyCodeObject *,
                                        PyObject *, PyObject *);

Modified: python/branches/p3yk-noslice/Include/graminit.h
==============================================================================
--- python/branches/p3yk-noslice/Include/graminit.h	(original)
+++ python/branches/p3yk-noslice/Include/graminit.h	Wed Jul 11 15:40:56 2007
@@ -3,85 +3,79 @@
 #define eval_input 258
 #define decorator 259
 #define decorators 260
-#define funcdef 261
-#define parameters 262
-#define typedargslist 263
-#define tname 264
+#define decorated 261
+#define funcdef 262
+#define parameters 263
+#define typedargslist 264
 #define tfpdef 265
-#define tfplist 266
-#define varargslist 267
-#define vname 268
-#define vfpdef 269
-#define vfplist 270
-#define stmt 271
-#define simple_stmt 272
-#define small_stmt 273
-#define expr_stmt 274
-#define augassign 275
-#define del_stmt 276
-#define pass_stmt 277
-#define flow_stmt 278
-#define break_stmt 279
-#define continue_stmt 280
-#define return_stmt 281
-#define yield_stmt 282
-#define raise_stmt 283
-#define import_stmt 284
-#define import_name 285
-#define import_from 286
-#define import_as_name 287
-#define dotted_as_name 288
-#define import_as_names 289
-#define dotted_as_names 290
-#define dotted_name 291
-#define global_stmt 292
-#define assert_stmt 293
-#define compound_stmt 294
-#define if_stmt 295
-#define while_stmt 296
-#define for_stmt 297
-#define try_stmt 298
-#define with_stmt 299
-#define with_var 300
-#define except_clause 301
-#define suite 302
-#define testlist_safe 303
-#define old_test 304
-#define old_lambdef 305
-#define test 306
-#define or_test 307
-#define and_test 308
-#define not_test 309
-#define comparison 310
-#define comp_op 311
-#define expr 312
-#define xor_expr 313
-#define and_expr 314
-#define shift_expr 315
-#define arith_expr 316
-#define term 317
-#define factor 318
-#define power 319
-#define atom 320
-#define listmaker 321
-#define testlist_gexp 322
-#define lambdef 323
-#define trailer 324
-#define subscriptlist 325
-#define subscript 326
-#define sliceop 327
-#define exprlist 328
-#define testlist 329
-#define dictsetmaker 330
-#define classdef 331
-#define arglist 332
-#define argument 333
-#define list_iter 334
-#define list_for 335
-#define list_if 336
-#define gen_iter 337
-#define gen_for 338
-#define gen_if 339
-#define testlist1 340
-#define encoding_decl 341
-#define yield_expr 342
+#define varargslist 266
+#define vfpdef 267
+#define stmt 268
+#define simple_stmt 269
+#define small_stmt 270
+#define expr_stmt 271
+#define augassign 272
+#define del_stmt 273
+#define pass_stmt 274
+#define flow_stmt 275
+#define break_stmt 276
+#define continue_stmt 277
+#define return_stmt 278
+#define yield_stmt 279
+#define raise_stmt 280
+#define import_stmt 281
+#define import_name 282
+#define import_from 283
+#define import_as_name 284
+#define dotted_as_name 285
+#define import_as_names 286
+#define dotted_as_names 287
+#define dotted_name 288
+#define global_stmt 289
+#define nonlocal_stmt 290
+#define assert_stmt 291
+#define compound_stmt 292
+#define if_stmt 293
+#define while_stmt 294
+#define for_stmt 295
+#define try_stmt 296
+#define with_stmt 297
+#define with_var 298
+#define except_clause 299
+#define suite 300
+#define test 301
+#define test_nocond 302
+#define lambdef 303
+#define lambdef_nocond 304
+#define or_test 305
+#define and_test 306
+#define not_test 307
+#define comparison 308
+#define comp_op 309
+#define star_expr 310
+#define expr 311
+#define xor_expr 312
+#define and_expr 313
+#define shift_expr 314
+#define arith_expr 315
+#define term 316
+#define factor 317
+#define power 318
+#define atom 319
+#define testlist_comp 320
+#define trailer 321
+#define subscriptlist 322
+#define subscript 323
+#define sliceop 324
+#define exprlist 325
+#define testlist 326
+#define dictorsetmaker 327
+#define classdef 328
+#define arglist 329
+#define argument 330
+#define comp_iter 331
+#define comp_for 332
+#define comp_if 333
+#define testlist1 334
+#define encoding_decl 335
+#define yield_expr 336

Modified: python/branches/p3yk-noslice/Include/intobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/intobject.h	(original)
+++ python/branches/p3yk-noslice/Include/intobject.h	Wed Jul 11 15:40:56 2007
@@ -47,10 +47,7 @@
 #define PyInt_AS_LONG(op) PyLong_AsLong(op)
 
 /* These aren't really part of the Int object, but they're handy; the protos
- * are necessary for systems that need the magic of PyAPI_FUNC and that want
- * to have stropmodule as a dynamically loaded module instead of building it
- * into the main Python shared library/DLL.  Guido thinks I'm weird for
- * building it this way.  :-)  [cjh]
+ * are necessary for systems that need the magic of PyAPI_FUNC.
  */
 PyAPI_FUNC(unsigned long) PyOS_strtoul(char *, char **, int);
 PyAPI_FUNC(long) PyOS_strtol(char *, char **, int);

Modified: python/branches/p3yk-noslice/Include/listobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/listobject.h	(original)
+++ python/branches/p3yk-noslice/Include/listobject.h	Wed Jul 11 15:40:56 2007
@@ -40,7 +40,8 @@
 
 PyAPI_DATA(PyTypeObject) PyList_Type;
 
-#define PyList_Check(op) PyObject_TypeCheck(op, &PyList_Type)
+#define PyList_Check(op) \
+		PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LIST_SUBCLASS)
 #define PyList_CheckExact(op) ((op)->ob_type == &PyList_Type)
 
 PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size);

Modified: python/branches/p3yk-noslice/Include/longobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/longobject.h	(original)
+++ python/branches/p3yk-noslice/Include/longobject.h	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,8 @@
 
 PyAPI_DATA(PyTypeObject) PyLong_Type;
 
-#define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type)
+#define PyLong_Check(op) \
+		PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_LONG_SUBCLASS)
 #define PyLong_CheckExact(op) ((op)->ob_type == &PyLong_Type)
 
 PyAPI_FUNC(PyObject *) PyLong_FromLong(long);
@@ -20,7 +21,7 @@
 PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t);
 PyAPI_FUNC(PyObject *) PyLong_FromDouble(double);
 PyAPI_FUNC(long) PyLong_AsLong(PyObject *);
-PyAPI_FUNC(ssize_t) PyLong_AsSsize_t(PyObject *);
+PyAPI_FUNC(Py_ssize_t) PyLong_AsSsize_t(PyObject *);
 PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *);
 PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *);
 PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *);
@@ -110,6 +111,11 @@
 	unsigned char* bytes, size_t n,
 	int little_endian, int is_signed);
 
+
+/* _PyLong_Format: Convert the long to a string object with given base,
+   appending a base prefix of 0[box] if base is 2, 8 or 16. */
+PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *aa, int base);
+
 #ifdef __cplusplus
 }
 #endif

Modified: python/branches/p3yk-noslice/Include/object.h
==============================================================================
--- python/branches/p3yk-noslice/Include/object.h	(original)
+++ python/branches/p3yk-noslice/Include/object.h	Wed Jul 11 15:40:56 2007
@@ -171,6 +171,7 @@
 	unaryfunc nb_int;
 	unaryfunc nb_long;
 	unaryfunc nb_float;
+	/* NB: nb_oct and nb_hex are not used anymore. */
 	unaryfunc nb_oct;
 	unaryfunc nb_hex;
 
@@ -357,7 +358,8 @@
 PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
 PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
 
-#define PyType_Check(op) PyObject_TypeCheck(op, &PyType_Type)
+#define PyType_Check(op) \
+	PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TYPE_SUBCLASS)
 #define PyType_CheckExact(op) ((op)->ob_type == &PyType_Type)
 
 PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
@@ -469,11 +471,23 @@
 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
 #endif
 
+/* These flags are used to determine if a type is a subclass. */
+#define Py_TPFLAGS_INT_SUBCLASS		(1L<<23)
+#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_UNICODE_SUBCLASS	(1L<<28)
+#define Py_TPFLAGS_DICT_SUBCLASS	(1L<<29)
+#define Py_TPFLAGS_BASE_EXC_SUBCLASS	(1L<<30)
+#define Py_TPFLAGS_TYPE_SUBCLASS	(1L<<31)
+
 #define Py_TPFLAGS_DEFAULT  ( \
                              Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
                             0)
 
 #define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)
+#define PyType_FastSubclass(t,f)  PyType_HasFeature(t,f)
 
 
 /*

Modified: python/branches/p3yk-noslice/Include/opcode.h
==============================================================================
--- python/branches/p3yk-noslice/Include/opcode.h	(original)
+++ python/branches/p3yk-noslice/Include/opcode.h	Wed Jul 11 15:40:56 2007
@@ -21,6 +21,7 @@
 
 #define UNARY_INVERT	15
 
+#define SET_ADD	17
 #define LIST_APPEND	18
 #define BINARY_POWER	19
 
@@ -50,8 +51,9 @@
 #define BINARY_OR	66
 #define INPLACE_POWER	67
 #define GET_ITER	68
-
+#define STORE_LOCALS	69
 #define PRINT_EXPR	70
+#define LOAD_BUILD_CLASS 71
 
 #define INPLACE_LSHIFT	75
 #define INPLACE_RSHIFT	76
@@ -60,14 +62,13 @@
 #define INPLACE_OR	79
 #define BREAK_LOOP	80
 #define WITH_CLEANUP    81
-#define LOAD_LOCALS	82
+
 #define RETURN_VALUE	83
 #define IMPORT_STAR	84
-
+#define MAKE_BYTES	85
 #define YIELD_VALUE	86
 #define POP_BLOCK	87
 #define END_FINALLY	88
-#define BUILD_CLASS	89
 
 #define HAVE_ARGUMENT	90	/* Opcodes from here have an argument: */
 
@@ -75,6 +76,8 @@
 #define DELETE_NAME	91	/* "" */
 #define UNPACK_SEQUENCE	92	/* Number of sequence items */
 #define FOR_ITER	93
+#define UNPACK_EX       94      /* Num items before variable part +
+                                   (Num items after variable part << 8) */
 
 #define STORE_ATTR	95	/* Index in name list */
 #define DELETE_ATTR	96	/* "" */
@@ -111,10 +114,10 @@
 #define RAISE_VARARGS	130	/* Number of raise arguments (1, 2 or 3) */
 /* CALL_FUNCTION_XXX opcodes defined below depend on this definition */
 #define CALL_FUNCTION	131	/* #args + (#kwargs<<8) */
-#define MAKE_FUNCTION	132	/* #defaults */
+#define MAKE_FUNCTION	132	/* #defaults + #kwdefaults<<8 + #annotations<<16 */
 #define BUILD_SLICE 	133	/* Number of items */
 
-#define MAKE_CLOSURE    134     /* #free vars */
+#define MAKE_CLOSURE    134     /* same as MAKE_FUNCTION */
 #define LOAD_CLOSURE    135     /* Load free variable from closure */
 #define LOAD_DEREF      136     /* Load and dereference from closure cell */ 
 #define STORE_DEREF     137     /* Store into cell */ 

Modified: python/branches/p3yk-noslice/Include/pydebug.h
==============================================================================
--- python/branches/p3yk-noslice/Include/pydebug.h	(original)
+++ python/branches/p3yk-noslice/Include/pydebug.h	Wed Jul 11 15:40:56 2007
@@ -8,6 +8,7 @@
 PyAPI_DATA(int) Py_DebugFlag;
 PyAPI_DATA(int) Py_VerboseFlag;
 PyAPI_DATA(int) Py_InteractiveFlag;
+PyAPI_DATA(int) Py_InspectFlag;
 PyAPI_DATA(int) Py_OptimizeFlag;
 PyAPI_DATA(int) Py_NoSiteFlag;
 PyAPI_DATA(int) Py_UseClassExceptionsFlag;

Modified: python/branches/p3yk-noslice/Include/pyerrors.h
==============================================================================
--- python/branches/p3yk-noslice/Include/pyerrors.h	(original)
+++ python/branches/p3yk-noslice/Include/pyerrors.h	Wed Jul 11 15:40:56 2007
@@ -10,14 +10,12 @@
     PyObject_HEAD
     PyObject *dict;
     PyObject *args;
-    PyObject *message;
 } PyBaseExceptionObject;
 
 typedef struct {
     PyObject_HEAD
     PyObject *dict;
     PyObject *args;
-    PyObject *message;
     PyObject *msg;
     PyObject *filename;
     PyObject *lineno;
@@ -31,11 +29,10 @@
     PyObject_HEAD
     PyObject *dict;
     PyObject *args;
-    PyObject *message;
     PyObject *encoding;
     PyObject *object;
-    PyObject *start;
-    PyObject *end;
+    Py_ssize_t start;
+    Py_ssize_t end;
     PyObject *reason;
 } PyUnicodeErrorObject;
 #endif
@@ -44,7 +41,6 @@
     PyObject_HEAD
     PyObject *dict;
     PyObject *args;
-    PyObject *message;
     PyObject *code;
 } PySystemExitObject;
 
@@ -52,7 +48,6 @@
     PyObject_HEAD
     PyObject *dict;
     PyObject *args;
-    PyObject *message;
     PyObject *myerrno;
     PyObject *strerror;
     PyObject *filename;
@@ -63,7 +58,6 @@
     PyObject_HEAD
     PyObject *dict;
     PyObject *args;
-    PyObject *message;
     PyObject *myerrno;
     PyObject *strerror;
     PyObject *filename;
@@ -94,13 +88,12 @@
 
 /* */
 
-#define PyExceptionClass_Check(x) \
-	    (PyType_Check((x)) && PyType_IsSubtype(			\
-		     (PyTypeObject*)(x), (PyTypeObject*)PyExc_BaseException))
+#define PyExceptionClass_Check(x)					\
+	(PyType_Check((x)) &&						\
+	 PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
 
-
-#define PyExceptionInstance_Check(x) \
-	 (PyType_IsSubtype((x)->ob_type, (PyTypeObject*)PyExc_BaseException))
+#define PyExceptionInstance_Check(x)			\
+	PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS)
 
 #define PyExceptionClass_Name(x) \
 	 ((char *)(((PyTypeObject*)(x))->tp_name))
@@ -114,7 +107,6 @@
 PyAPI_DATA(PyObject *) PyExc_Exception;
 PyAPI_DATA(PyObject *) PyExc_StopIteration;
 PyAPI_DATA(PyObject *) PyExc_GeneratorExit;
-PyAPI_DATA(PyObject *) PyExc_StandardError;
 PyAPI_DATA(PyObject *) PyExc_ArithmeticError;
 PyAPI_DATA(PyObject *) PyExc_LookupError;
 

Modified: python/branches/p3yk-noslice/Include/pymem.h
==============================================================================
--- python/branches/p3yk-noslice/Include/pymem.h	(original)
+++ python/branches/p3yk-noslice/Include/pymem.h	Wed Jul 11 15:40:56 2007
@@ -30,6 +30,8 @@
    debugging info to dynamic memory blocks.  The system routines have no idea
    what to do with that stuff, and the Python wrappers have no idea what to do
    with raw blocks obtained directly by the system routines then.
+
+   The GIL must be held when using these APIs.
 */
 
 /*

Modified: python/branches/p3yk-noslice/Include/pyport.h
==============================================================================
--- python/branches/p3yk-noslice/Include/pyport.h	(original)
+++ python/branches/p3yk-noslice/Include/pyport.h	Wed Jul 11 15:40:56 2007
@@ -50,6 +50,22 @@
 #ifdef HAVE_LONG_LONG
 #ifndef PY_LONG_LONG
 #define PY_LONG_LONG long long
+#if defined(LLONG_MAX)
+/* If LLONG_MAX is defined in limits.h, use that. */
+#define PY_LLONG_MIN LLONG_MIN
+#define PY_LLONG_MAX LLONG_MAX
+#define PY_ULLONG_MAX ULLONG_MAX
+#elif defined(__LONG_LONG_MAX__)
+/* Otherwise, if GCC has a builtin define, use that. */
+#define PY_LLONG_MAX __LONG_LONG_MAX__
+#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
+#define PY_ULLONG_MAX (__LONG_LONG_MAX__*2ULL + 1ULL)
+#else
+/* Otherwise, rely on two's complement. */
+#define PY_ULLONG_MAX (~0ULL)
+#define PY_LLONG_MAX  ((long long)(PY_ULLONG_MAX>>1))
+#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
+#endif /* LLONG_MAX */
 #endif
 #endif /* HAVE_LONG_LONG */
 

Modified: python/branches/p3yk-noslice/Include/pystate.h
==============================================================================
--- python/branches/p3yk-noslice/Include/pystate.h	(original)
+++ python/branches/p3yk-noslice/Include/pystate.h	Wed Jul 11 15:40:56 2007
@@ -21,6 +21,7 @@
     PyObject *modules;
     PyObject *sysdict;
     PyObject *builtins;
+    PyObject *modules_reloading;
 
     PyObject *codec_search_path;
     PyObject *codec_search_cache;

Modified: python/branches/p3yk-noslice/Include/pythonrun.h
==============================================================================
--- python/branches/p3yk-noslice/Include/pythonrun.h	(original)
+++ python/branches/p3yk-noslice/Include/pythonrun.h	Wed Jul 11 15:40:56 2007
@@ -69,6 +69,10 @@
 PyAPI_FUNC(void) PyErr_PrintEx(int);
 PyAPI_FUNC(void) PyErr_Display(PyObject *, PyObject *, PyObject *);
 
+/* Py_PyAtExit is for the atexit module, Py_AtExit is for low-level
+ * exit functions.
+ */
+PyAPI_FUNC(void) _Py_PyAtExit(void (*func)(void));
 PyAPI_FUNC(int) Py_AtExit(void (*func)(void));
 
 PyAPI_FUNC(void) Py_Exit(int);
@@ -122,6 +126,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);
 
 /* Various internal finalizers */
 PyAPI_FUNC(void) _PyExc_Fini(void);
@@ -133,6 +138,7 @@
 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);

Modified: python/branches/p3yk-noslice/Include/setobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/setobject.h	(original)
+++ python/branches/p3yk-noslice/Include/setobject.h	Wed Jul 11 15:40:56 2007
@@ -82,7 +82,8 @@
 PyAPI_FUNC(int) PySet_Contains(PyObject *anyset, PyObject *key);
 PyAPI_FUNC(int) PySet_Discard(PyObject *set, PyObject *key);
 PyAPI_FUNC(int) PySet_Add(PyObject *set, PyObject *key);
-PyAPI_FUNC(int) _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **entry);
+PyAPI_FUNC(int) _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key);
+PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash);
 PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set);
 PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable);
 

Modified: python/branches/p3yk-noslice/Include/stringobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/stringobject.h	(original)
+++ python/branches/p3yk-noslice/Include/stringobject.h	Wed Jul 11 15:40:56 2007
@@ -55,7 +55,8 @@
 PyAPI_DATA(PyTypeObject) PyBaseString_Type;
 PyAPI_DATA(PyTypeObject) PyString_Type;
 
-#define PyString_Check(op) PyObject_TypeCheck(op, &PyString_Type)
+#define PyString_Check(op) \
+                 PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_STRING_SUBCLASS)
 #define PyString_CheckExact(op) ((op)->ob_type == &PyString_Type)
 
 PyAPI_FUNC(PyObject *) PyString_FromStringAndSize(const char *, Py_ssize_t);

Modified: python/branches/p3yk-noslice/Include/structmember.h
==============================================================================
--- python/branches/p3yk-noslice/Include/structmember.h	(original)
+++ python/branches/p3yk-noslice/Include/structmember.h	Wed Jul 11 15:40:56 2007
@@ -68,9 +68,10 @@
 #ifdef HAVE_LONG_LONG
 #define T_LONGLONG      17  
 #define T_ULONGLONG     18
+#define T_PYSSIZET       19 /* Py_ssize_t */
 #endif /* HAVE_LONG_LONG */
 
-#define T_NONE          19      /* Value is always None */
+#define T_NONE          20      /* Value is always None */
 
 /* Flags */
 #define READONLY	1

Modified: python/branches/p3yk-noslice/Include/symtable.h
==============================================================================
--- python/branches/p3yk-noslice/Include/symtable.h	(original)
+++ python/branches/p3yk-noslice/Include/symtable.h	Wed Jul 11 15:40:56 2007
@@ -5,31 +5,35 @@
 extern "C" {
 #endif
 
+/* XXX(ncoghlan): This is a weird mix of public names and interpreter internal
+ *                names.
+ */
+
 typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock }
     _Py_block_ty;
 
 struct _symtable_entry;
 
 struct symtable {
-	const char *st_filename; /* name of file being compiled */
+	const char *st_filename;        /* name of file being compiled */
 	struct _symtable_entry *st_cur; /* current symbol table entry */
-	struct _symtable_entry *st_top; /* module entry */
-	PyObject *st_symbols;    /* dictionary of symbol table entries */
-        PyObject *st_stack;      /* stack of namespace info */
-	PyObject *st_global;     /* borrowed ref to MODULE in st_symbols */
-	int st_nblocks;          /* number of blocks */
-	PyObject *st_private;        /* name of current class or NULL */
-        int st_tmpname;          /* temporary name counter */
-	PyFutureFeatures *st_future; /* module's future features */
+	struct _symtable_entry *st_top; /* symbol table entry for module */
+	PyObject *st_blocks;            /* dict: map AST node addresses
+	                                 *       to symbol table entries */
+	PyObject *st_stack;             /* list: stack of namespace info */
+	PyObject *st_global;            /* borrowed ref to st_top->st_symbols */
+	int st_nblocks;                 /* number of blocks used */
+	PyObject *st_private;           /* name of current class or NULL */
+	PyFutureFeatures *st_future;    /* module's future features */
 };
 
 typedef struct _symtable_entry {
 	PyObject_HEAD
-	PyObject *ste_id;        /* int: key in st_symbols */
-	PyObject *ste_symbols;   /* dict: name to flags */
-	PyObject *ste_name;      /* string: name of block */
+	PyObject *ste_id;        /* int: key in ste_table->st_blocks */
+	PyObject *ste_symbols;   /* dict: variable names to flags */
+	PyObject *ste_name;      /* string: name of current block */
 	PyObject *ste_varnames;  /* list of variable names */
-	PyObject *ste_children;  /* list of child ids */
+	PyObject *ste_children;  /* list of child blocks */
 	_Py_block_ty ste_type;   /* module, class, or function */
 	int ste_unoptimized;     /* false if namespace is optimized */
 	unsigned ste_nested : 1;      /* true if block is nested */
@@ -64,23 +68,24 @@
 #define DEF_GLOBAL 1           /* global stmt */
 #define DEF_LOCAL 2            /* assignment in code block */
 #define DEF_PARAM 2<<1         /* formal parameter */
-#define USE 2<<2               /* name is used */
-#define DEF_STAR 2<<3          /* parameter is star arg */
-#define DEF_DOUBLESTAR 2<<4    /* parameter is star-star arg */
-#define DEF_INTUPLE 2<<5       /* name defined in tuple in parameters */
-#define DEF_FREE 2<<6          /* name used but not defined in nested block */
-#define DEF_FREE_GLOBAL 2<<7   /* free variable is actually implicit global */
-#define DEF_FREE_CLASS 2<<8    /* free variable from class's method */
-#define DEF_IMPORT 2<<9        /* assignment occurred via import */
+#define DEF_NONLOCAL 2<<2      /* nonlocal stmt */
+#define USE 2<<3               /* name is used */
+#define DEF_STAR 2<<4          /* parameter is star arg */
+#define DEF_DOUBLESTAR 2<<5    /* parameter is star-star arg */
+#define DEF_INTUPLE 2<<6       /* name defined in tuple in parameters */
+#define DEF_FREE 2<<7          /* name used but not defined in nested block */
+#define DEF_FREE_GLOBAL 2<<8   /* free variable is actually implicit global */
+#define DEF_FREE_CLASS 2<<9    /* free variable from class's method */
+#define DEF_IMPORT 2<<10        /* assignment occurred via import */
 
 #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
 
 /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol
    table.  GLOBAL is returned from PyST_GetScope() for either of them. 
-   It is stored in ste_symbols at bits 12-14.
+   It is stored in ste_symbols at bits 12-15.
 */
-#define SCOPE_OFF 11
-#define SCOPE_MASK 7
+#define SCOPE_OFFSET 11
+#define SCOPE_MASK (DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL)
 
 #define LOCAL 1
 #define GLOBAL_EXPLICIT 2

Modified: python/branches/p3yk-noslice/Include/token.h
==============================================================================
--- python/branches/p3yk-noslice/Include/token.h	(original)
+++ python/branches/p3yk-noslice/Include/token.h	Wed Jul 11 15:40:56 2007
@@ -59,10 +59,11 @@
 #define DOUBLESLASHEQUAL 49
 #define AT              50	
 #define RARROW          51
+#define ELLIPSIS        52
 /* Don't forget to update the table _PyParser_TokenNames in tokenizer.c! */
-#define OP		52
-#define ERRORTOKEN	53
-#define N_TOKENS	54
+#define OP		53
+#define ERRORTOKEN	54
+#define N_TOKENS	55
 
 /* Special definitions for cooperation with parser */
 

Modified: python/branches/p3yk-noslice/Include/tupleobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/tupleobject.h	(original)
+++ python/branches/p3yk-noslice/Include/tupleobject.h	Wed Jul 11 15:40:56 2007
@@ -33,7 +33,8 @@
 
 PyAPI_DATA(PyTypeObject) PyTuple_Type;
 
-#define PyTuple_Check(op) PyObject_TypeCheck(op, &PyTuple_Type)
+#define PyTuple_Check(op) \
+                 PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_TUPLE_SUBCLASS)
 #define PyTuple_CheckExact(op) ((op)->ob_type == &PyTuple_Type)
 
 PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size);

Modified: python/branches/p3yk-noslice/Include/unicodeobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/unicodeobject.h	(original)
+++ python/branches/p3yk-noslice/Include/unicodeobject.h	Wed Jul 11 15:40:56 2007
@@ -392,7 +392,8 @@
 
 PyAPI_DATA(PyTypeObject) PyUnicode_Type;
 
-#define PyUnicode_Check(op) PyObject_TypeCheck(op, &PyUnicode_Type)
+#define PyUnicode_Check(op) \
+                 PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_UNICODE_SUBCLASS)
 #define PyUnicode_CheckExact(op) ((op)->ob_type == &PyUnicode_Type)
 
 /* Fast access macros */

Modified: python/branches/p3yk-noslice/LICENSE
==============================================================================
--- python/branches/p3yk-noslice/LICENSE	(original)
+++ python/branches/p3yk-noslice/LICENSE	Wed Jul 11 15:40:56 2007
@@ -52,7 +52,9 @@
     2.4.1           2.4         2005        PSF         yes
     2.4.2           2.4.1       2005        PSF         yes
     2.4.3           2.4.2       2006        PSF         yes
+    2.4.4           2.4.3       2006        PSF         yes
     2.5             2.4         2006        PSF         yes
+    2.5.1           2.5         2007        PSF         yes
 
 Footnotes:
 

Deleted: /python/branches/p3yk-noslice/Lib/Bastion.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/Bastion.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,177 +0,0 @@
-"""Bastionification utility.
-
-A bastion (for another object -- the 'original') is an object that has
-the same methods as the original but does not give access to its
-instance variables.  Bastions have a number of uses, but the most
-obvious one is to provide code executing in restricted mode with a
-safe interface to an object implemented in unrestricted mode.
-
-The bastionification routine has an optional second argument which is
-a filter function.  Only those methods for which the filter method
-(called with the method name as argument) returns true are accessible.
-The default filter method returns true unless the method name begins
-with an underscore.
-
-There are a number of possible implementations of bastions.  We use a
-'lazy' approach where the bastion's __getattr__() discipline does all
-the work for a particular method the first time it is used.  This is
-usually fastest, especially if the user doesn't call all available
-methods.  The retrieved methods are stored as instance variables of
-the bastion, so the overhead is only occurred on the first use of each
-method.
-
-Detail: the bastion class has a __repr__() discipline which includes
-the repr() of the original object.  This is precomputed when the
-bastion is created.
-
-"""
-
-__all__ = ["BastionClass", "Bastion"]
-
-from types import MethodType
-
-
-class BastionClass:
-
-    """Helper class used by the Bastion() function.
-
-    You could subclass this and pass the subclass as the bastionclass
-    argument to the Bastion() function, as long as the constructor has
-    the same signature (a get() function and a name for the object).
-
-    """
-
-    def __init__(self, get, name):
-        """Constructor.
-
-        Arguments:
-
-        get - a function that gets the attribute value (by name)
-        name - a human-readable name for the original object
-               (suggestion: use repr(object))
-
-        """
-        self._get_ = get
-        self._name_ = name
-
-    def __repr__(self):
-        """Return a representation string.
-
-        This includes the name passed in to the constructor, so that
-        if you print the bastion during debugging, at least you have
-        some idea of what it is.
-
-        """
-        return "<Bastion for %s>" % self._name_
-
-    def __getattr__(self, name):
-        """Get an as-yet undefined attribute value.
-
-        This calls the get() function that was passed to the
-        constructor.  The result is stored as an instance variable so
-        that the next time the same attribute is requested,
-        __getattr__() won't be invoked.
-
-        If the get() function raises an exception, this is simply
-        passed on -- exceptions are not cached.
-
-        """
-        attribute = self._get_(name)
-        self.__dict__[name] = attribute
-        return attribute
-
-
-def Bastion(object, filter = lambda name: name[:1] != '_',
-            name=None, bastionclass=BastionClass):
-    """Create a bastion for an object, using an optional filter.
-
-    See the Bastion module's documentation for background.
-
-    Arguments:
-
-    object - the original object
-    filter - a predicate that decides whether a function name is OK;
-             by default all names are OK that don't start with '_'
-    name - the name of the object; default repr(object)
-    bastionclass - class used to create the bastion; default BastionClass
-
-    """
-
-    raise RuntimeError, "This code is not secure in Python 2.2 and 2.3"
-
-    # Note: we define *two* ad-hoc functions here, get1 and get2.
-    # Both are intended to be called in the same way: get(name).
-    # It is clear that the real work (getting the attribute
-    # from the object and calling the filter) is done in get1.
-    # Why can't we pass get1 to the bastion?  Because the user
-    # would be able to override the filter argument!  With get2,
-    # overriding the default argument is no security loophole:
-    # all it does is call it.
-    # Also notice that we can't place the object and filter as
-    # instance variables on the bastion object itself, since
-    # the user has full access to all instance variables!
-
-    def get1(name, object=object, filter=filter):
-        """Internal function for Bastion().  See source comments."""
-        if filter(name):
-            attribute = getattr(object, name)
-            if type(attribute) == MethodType:
-                return attribute
-        raise AttributeError, name
-
-    def get2(name, get1=get1):
-        """Internal function for Bastion().  See source comments."""
-        return get1(name)
-
-    if name is None:
-        name = repr(object)
-    return bastionclass(get2, name)
-
-
-def _test():
-    """Test the Bastion() function."""
-    class Original:
-        def __init__(self):
-            self.sum = 0
-        def add(self, n):
-            self._add(n)
-        def _add(self, n):
-            self.sum = self.sum + n
-        def total(self):
-            return self.sum
-    o = Original()
-    b = Bastion(o)
-    testcode = """if 1:
-    b.add(81)
-    b.add(18)
-    print "b.total() =", b.total()
-    try:
-        print "b.sum =", b.sum,
-    except:
-        print "inaccessible"
-    else:
-        print "accessible"
-    try:
-        print "b._add =", b._add,
-    except:
-        print "inaccessible"
-    else:
-        print "accessible"
-    try:
-        print "b._get_.func_defaults =", map(type, b._get_.func_defaults),
-    except:
-        print "inaccessible"
-    else:
-        print "accessible"
-    \n"""
-    exec(testcode)
-    print('='*20, "Using rexec:", '='*20)
-    import rexec
-    r = rexec.RExec()
-    m = r.add_module('__main__')
-    m.b = b
-    r.r_exec(testcode)
-
-
-if __name__ == '__main__':
-    _test()

Modified: python/branches/p3yk-noslice/Lib/CGIHTTPServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/CGIHTTPServer.py	(original)
+++ python/branches/p3yk-noslice/Lib/CGIHTTPServer.py	Wed Jul 11 15:40:56 2007
@@ -197,6 +197,9 @@
         length = self.headers.getheader('content-length')
         if length:
             env['CONTENT_LENGTH'] = length
+        referer = self.headers.getheader('referer')
+        if referer:
+            env['HTTP_REFERER'] = referer
         accept = []
         for line in self.headers.getallmatchingheaders('accept'):
             if line[:1] in "\t\n\r ":
@@ -214,7 +217,7 @@
         # Since we're setting the env in the parent, provide empty
         # values to override previously set values
         for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
-                  'HTTP_USER_AGENT', 'HTTP_COOKIE'):
+                  'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
             env.setdefault(k, "")
         os.environ.update(env)
 
@@ -350,7 +353,7 @@
         st = os.stat(path)
     except os.error:
         return False
-    return st.st_mode & 0111 != 0
+    return st.st_mode & 0o111 != 0
 
 
 def test(HandlerClass = CGIHTTPRequestHandler,

Modified: python/branches/p3yk-noslice/Lib/ConfigParser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ConfigParser.py	(original)
+++ python/branches/p3yk-noslice/Lib/ConfigParser.py	Wed Jul 11 15:40:56 2007
@@ -106,6 +106,21 @@
 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)
@@ -569,7 +584,7 @@
                     value = value % vars
                 except KeyError as e:
                     raise InterpolationMissingOptionError(
-                        option, section, rawval, e[0])
+                        option, section, rawval, e.args[0])
             else:
                 break
         if "%(" in value:
@@ -594,7 +609,8 @@
         self._interpolate_some(option, L, rawval, section, vars, 1)
         return ''.join(L)
 
-    _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
+    _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:
@@ -613,7 +629,7 @@
                 accum.append("%")
                 rest = rest[2:]
             elif c == "(":
-                m = self._interpvar_match(rest)
+                m = self._interpvar_re.match(rest)
                 if m is None:
                     raise InterpolationSyntaxError(option, section,
                         "bad interpolation variable reference %r" % rest)
@@ -638,4 +654,12 @@
         """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/p3yk-noslice/Lib/Cookie.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/Cookie.py	(original)
+++ python/branches/p3yk-noslice/Lib/Cookie.py	Wed Jul 11 15:40:56 2007
@@ -305,17 +305,16 @@
     '\375' : '\\375',  '\376' : '\\376',  '\377' : '\\377'
     }
 
-_idmap = ''.join(chr(x) for x in xrange(256))
+_idmap = ''.join(chr(x) for x in range(256))
 
-def _quote(str, LegalChars=_LegalChars,
-           idmap=_idmap, translate=string.translate):
+def _quote(str, LegalChars=_LegalChars, idmap=_idmap):
     #
     # If the string does not need to be double-quoted,
     # then just return the string.  Otherwise, surround
     # the string in doublequotes and precede quote (with a \)
     # special characters.
     #
-    if "" == translate(str, idmap, LegalChars):
+    if "" == str.translate(idmap, LegalChars):
         return str
     else:
         return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
@@ -440,14 +439,12 @@
         return K.lower() in self._reserved
     # end isReservedKey
 
-    def set(self, key, val, coded_val,
-            LegalChars=_LegalChars,
-            idmap=_idmap, translate=string.translate):
+    def set(self, key, val, coded_val, LegalChars=_LegalChars, idmap=_idmap):
         # First we verify that the key isn't a reserved word
         # Second we make sure it only contains legal characters
         if key.lower() in self._reserved:
             raise CookieError("Attempt to set a reserved key: %s" % key)
-        if "" != translate(key, idmap, LegalChars):
+        if "" != key.translate(idmap, LegalChars):
             raise CookieError("Illegal key value: %s" % key)
 
         # It's a good key, so save it.

Modified: python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py	(original)
+++ python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py	Wed Jul 11 15:40:56 2007
@@ -252,8 +252,10 @@
     """
 
     def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
-                 logRequests=1):
-        SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
+                 logRequests=1, allow_none=False, encoding=None,
+                 bind_and_activate=True):
+        SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
+                                    allow_none, encoding, bind_and_activate)
         XMLRPCDocGenerator.__init__(self)
 
 class DocCGIXMLRPCRequestHandler(   CGIXMLRPCRequestHandler,

Modified: python/branches/p3yk-noslice/Lib/HTMLParser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/HTMLParser.py	(original)
+++ python/branches/p3yk-noslice/Lib/HTMLParser.py	Wed Jul 11 15:40:56 2007
@@ -358,12 +358,30 @@
         self.error("unknown declaration: %r" % (data,))
 
     # Internal -- helper to remove special character quoting
+    entitydefs = None
     def unescape(self, s):
         if '&' not in s:
             return s
-        s = s.replace("&lt;", "<")
-        s = s.replace("&gt;", ">")
-        s = s.replace("&apos;", "'")
-        s = s.replace("&quot;", '"')
-        s = s.replace("&amp;", "&") # Must be last
-        return s
+        def replaceEntities(s):
+            s = s.groups()[0]
+            if s[0] == "#":
+                s = s[1:]
+                if s[0] in ['x','X']:
+                    c = int(s[1:], 16)
+                else:
+                    c = int(s)
+                return unichr(c)
+            else:
+                # Cannot use name2codepoint directly, because HTMLParser supports apos,
+                # which is not part of HTML 4
+                import htmlentitydefs
+                if HTMLParser.entitydefs is None:
+                    entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
+                    for k, v in htmlentitydefs.name2codepoint.items():
+                        entitydefs[k] = unichr(v)
+                try:
+                    return self.entitydefs[s]
+                except KeyError:
+                    return '&'+s+';'
+
+        return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)

Deleted: /python/branches/p3yk-noslice/Lib/MimeWriter.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/MimeWriter.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,181 +0,0 @@
-"""Generic MIME writer.
-
-This module defines the class MimeWriter.  The MimeWriter class implements
-a basic formatter for creating MIME multi-part files.  It doesn't seek around
-the output file nor does it use large amounts of buffer space. You must write
-the parts out in the order that they should occur in the final file.
-MimeWriter does buffer the headers you add, allowing you to rearrange their
-order.
-
-"""
-
-
-import mimetools
-
-__all__ = ["MimeWriter"]
-
-class MimeWriter:
-
-    """Generic MIME writer.
-
-    Methods:
-
-    __init__()
-    addheader()
-    flushheaders()
-    startbody()
-    startmultipartbody()
-    nextpart()
-    lastpart()
-
-    A MIME writer is much more primitive than a MIME parser.  It
-    doesn't seek around on the output file, and it doesn't use large
-    amounts of buffer space, so you have to write the parts in the
-    order they should occur on the output file.  It does buffer the
-    headers you add, allowing you to rearrange their order.
-
-    General usage is:
-
-    f = <open the output file>
-    w = MimeWriter(f)
-    ...call w.addheader(key, value) 0 or more times...
-
-    followed by either:
-
-    f = w.startbody(content_type)
-    ...call f.write(data) for body data...
-
-    or:
-
-    w.startmultipartbody(subtype)
-    for each part:
-        subwriter = w.nextpart()
-        ...use the subwriter's methods to create the subpart...
-    w.lastpart()
-
-    The subwriter is another MimeWriter instance, and should be
-    treated in the same way as the toplevel MimeWriter.  This way,
-    writing recursive body parts is easy.
-
-    Warning: don't forget to call lastpart()!
-
-    XXX There should be more state so calls made in the wrong order
-    are detected.
-
-    Some special cases:
-
-    - startbody() just returns the file passed to the constructor;
-      but don't use this knowledge, as it may be changed.
-
-    - startmultipartbody() actually returns a file as well;
-      this can be used to write the initial 'if you can read this your
-      mailer is not MIME-aware' message.
-
-    - If you call flushheaders(), the headers accumulated so far are
-      written out (and forgotten); this is useful if you don't need a
-      body part at all, e.g. for a subpart of type message/rfc822
-      that's (mis)used to store some header-like information.
-
-    - Passing a keyword argument 'prefix=<flag>' to addheader(),
-      start*body() affects where the header is inserted; 0 means
-      append at the end, 1 means insert at the start; default is
-      append for addheader(), but insert for start*body(), which use
-      it to determine where the Content-Type header goes.
-
-    """
-
-    def __init__(self, fp):
-        self._fp = fp
-        self._headers = []
-
-    def addheader(self, key, value, prefix=0):
-        """Add a header line to the MIME message.
-
-        The key is the name of the header, where the value obviously provides
-        the value of the header. The optional argument prefix determines
-        where the header is inserted; 0 means append at the end, 1 means
-        insert at the start. The default is to append.
-
-        """
-        lines = value.split("\n")
-        while lines and not lines[-1]: del lines[-1]
-        while lines and not lines[0]: del lines[0]
-        for i in range(1, len(lines)):
-            lines[i] = "    " + lines[i].strip()
-        value = "\n".join(lines) + "\n"
-        line = key + ": " + value
-        if prefix:
-            self._headers.insert(0, line)
-        else:
-            self._headers.append(line)
-
-    def flushheaders(self):
-        """Writes out and forgets all headers accumulated so far.
-
-        This is useful if you don't need a body part at all; for example,
-        for a subpart of type message/rfc822 that's (mis)used to store some
-        header-like information.
-
-        """
-        self._fp.writelines(self._headers)
-        self._headers = []
-
-    def startbody(self, ctype, plist=[], prefix=1):
-        """Returns a file-like object for writing the body of the message.
-
-        The content-type is set to the provided ctype, and the optional
-        parameter, plist, provides additional parameters for the
-        content-type declaration.  The optional argument prefix determines
-        where the header is inserted; 0 means append at the end, 1 means
-        insert at the start. The default is to insert at the start.
-
-        """
-        for name, value in plist:
-            ctype = ctype + ';\n %s=\"%s\"' % (name, value)
-        self.addheader("Content-Type", ctype, prefix=prefix)
-        self.flushheaders()
-        self._fp.write("\n")
-        return self._fp
-
-    def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
-        """Returns a file-like object for writing the body of the message.
-
-        Additionally, this method initializes the multi-part code, where the
-        subtype parameter provides the multipart subtype, the boundary
-        parameter may provide a user-defined boundary specification, and the
-        plist parameter provides optional parameters for the subtype.  The
-        optional argument, prefix, determines where the header is inserted;
-        0 means append at the end, 1 means insert at the start. The default
-        is to insert at the start.  Subparts should be created using the
-        nextpart() method.
-
-        """
-        self._boundary = boundary or mimetools.choose_boundary()
-        return self.startbody("multipart/" + subtype,
-                              [("boundary", self._boundary)] + plist,
-                              prefix=prefix)
-
-    def nextpart(self):
-        """Returns a new instance of MimeWriter which represents an
-        individual part in a multipart message.
-
-        This may be used to write the part as well as used for creating
-        recursively complex multipart messages. The message must first be
-        initialized with the startmultipartbody() method before using the
-        nextpart() method.
-
-        """
-        self._fp.write("\n--" + self._boundary + "\n")
-        return self.__class__(self._fp)
-
-    def lastpart(self):
-        """This is used to designate the last part of a multipart message.
-
-        It should always be used when writing multipart messages.
-
-        """
-        self._fp.write("\n--" + self._boundary + "--\n")
-
-
-if __name__ == '__main__':
-    import test.test_MimeWriter

Modified: python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py	(original)
+++ python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py	Wed Jul 11 15:40:56 2007
@@ -21,15 +21,14 @@
 
 class MyFuncs:
     def __init__(self):
-        # make all of the string functions available through
-        # string.func_name
-        import string
-        self.string = string
+        # make all of the sys functions available through sys.func_name
+        import sys
+        self.sys = sys
     def _listMethods(self):
         # implement this method so that system.listMethods
-        # knows to advertise the strings methods
+        # knows to advertise the sys methods
         return list_public_methods(self) + \
-                ['string.' + method for method in list_public_methods(self.string)]
+                ['sys.' + method for method in list_public_methods(self.sys)]
     def pow(self, x, y): return pow(x, y)
     def add(self, x, y) : return x + y
 
@@ -140,7 +139,7 @@
 
     return [member for member in dir(obj)
                 if not member.startswith('_') and
-                    callable(getattr(obj, member))]
+                    hasattr(getattr(obj, member), '__call__')]
 
 def remove_duplicates(lst):
     """remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
@@ -518,11 +517,11 @@
     allow_reuse_address = True
 
     def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
-                 logRequests=True, allow_none=False, encoding=None):
+                 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
         self.logRequests = logRequests
 
         SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
-        SocketServer.TCPServer.__init__(self, addr, requestHandler)
+        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/p3yk-noslice/Lib/SocketServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/SocketServer.py	(original)
+++ python/branches/p3yk-noslice/Lib/SocketServer.py	Wed Jul 11 15:40:56 2007
@@ -279,7 +279,7 @@
 
     Methods for the caller:
 
-    - __init__(server_address, RequestHandlerClass)
+    - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
     - serve_forever()
     - handle_request()  # if you don't use serve_forever()
     - fileno() -> int   # for select()
@@ -322,13 +322,14 @@
 
     allow_reuse_address = False
 
-    def __init__(self, server_address, RequestHandlerClass):
+    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)
-        self.server_bind()
-        self.server_activate()
+        if bind_and_activate:
+            self.server_bind()
+            self.server_activate()
 
     def server_bind(self):
         """Called by constructor to bind the socket.
@@ -339,6 +340,7 @@
         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.
@@ -516,12 +518,9 @@
         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
+        self.setup()
+        self.handle()
+        self.finish()
 
     def setup(self):
         pass

Modified: python/branches/p3yk-noslice/Lib/StringIO.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/StringIO.py	(original)
+++ python/branches/p3yk-noslice/Lib/StringIO.py	Wed Jul 11 15:40:56 2007
@@ -64,10 +64,10 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         """A file object is its own iterator, for example iter(f) returns f
         (unless f is closed). When a file is used as an iterator, typically
-        in a for loop (for example, for line in f: print line), the next()
+        in a for loop (for example, for line in f: print line), the __next__()
         method is called repeatedly. This method returns the next input line,
         or raises StopIteration when EOF is hit.
         """

Modified: python/branches/p3yk-noslice/Lib/UserDict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/UserDict.py	(original)
+++ python/branches/p3yk-noslice/Lib/UserDict.py	Wed Jul 11 15:40:56 2007
@@ -139,7 +139,7 @@
         return value
     def popitem(self):
         try:
-            k, v = self.iteritems().next()
+            k, v = next(self.iteritems())
         except StopIteration:
             raise KeyError, 'container is empty'
         del self[k]

Modified: python/branches/p3yk-noslice/Lib/_strptime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/_strptime.py	(original)
+++ python/branches/p3yk-noslice/Lib/_strptime.py	Wed Jul 11 15:40:56 2007
@@ -107,7 +107,7 @@
         # magical; just happened to have used it everywhere else where a
         # static date was needed.
         am_pm = []
-        for hour in (01,22):
+        for hour in (1, 22):
             time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
             am_pm.append(time.strftime("%p", time_tuple).lower())
         self.am_pm = am_pm
@@ -186,7 +186,7 @@
             self.locale_time = locale_time
         else:
             self.locale_time = LocaleTime()
-        base = super(TimeRE, self)
+        base = super()
         base.__init__({
             # The " \d" part of the regex is to make %c from ANSI C work
             'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
@@ -250,7 +250,7 @@
         regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
         format = regex_chars.sub(r"\\\1", format)
         whitespace_replacement = re_compile('\s+')
-        format = whitespace_replacement.sub('\s*', format)
+        format = whitespace_replacement.sub('\s+', format)
         while '%' in format:
             directive_index = format.index('%')+1
             processed_format = "%s%s%s" % (processed_format,
@@ -295,17 +295,16 @@
     """Return a time struct based on the input string and the format string."""
     global _TimeRE_cache, _regex_cache
     with _cache_lock:
-        time_re = _TimeRE_cache
-        locale_time = time_re.locale_time
-        if _getlang() != locale_time.lang:
+        if _getlang() != _TimeRE_cache.locale_time.lang:
             _TimeRE_cache = TimeRE()
-            _regex_cache = {}
+            _regex_cache.clear()
         if len(_regex_cache) > _CACHE_MAX_SIZE:
             _regex_cache.clear()
+        locale_time = _TimeRE_cache.locale_time
         format_regex = _regex_cache.get(format)
         if not format_regex:
             try:
-                format_regex = time_re.compile(format)
+                format_regex = _TimeRE_cache.compile(format)
             # KeyError raised when a bad format is found; can be specified as
             # \\, in which case it was a stray % but with a space after it
             except KeyError as err:

Modified: python/branches/p3yk-noslice/Lib/aifc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/aifc.py	(original)
+++ python/branches/p3yk-noslice/Lib/aifc.py	Wed Jul 11 15:40:56 2007
@@ -665,7 +665,8 @@
 ##          raise Error, 'cannot change parameters after starting to write'
 ##      self._version = version
 
-    def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
+    def setparams(self, params):
+        nchannels, sampwidth, framerate, nframes, comptype, compname = params
         if self._nframeswritten:
             raise Error, 'cannot change parameters after starting to write'
         if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'):

Modified: python/branches/p3yk-noslice/Lib/anydbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/anydbm.py	(original)
+++ python/branches/p3yk-noslice/Lib/anydbm.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,7 @@
 Instead of
 
         import dbm
-        d = dbm.open(file, 'w', 0666)
+        d = dbm.open(file, 'w', 0o666)
 
 use
 
@@ -63,7 +63,7 @@
 
 error = tuple(_errors)
 
-def open(file, flag = 'r', mode = 0666):
+def open(file, flag = 'r', mode = 0o666):
     # guess the type of an existing database
     from whichdb import whichdb
     result=whichdb(file)

Deleted: /python/branches/p3yk-noslice/Lib/atexit.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/atexit.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,65 +0,0 @@
-"""
-atexit.py - allow programmer to define multiple exit functions to be executed
-upon normal program termination.
-
-One public function, register, is defined.
-"""
-
-__all__ = ["register"]
-
-import sys
-
-_exithandlers = []
-def _run_exitfuncs():
-    """run any registered exit functions
-
-    _exithandlers is traversed in reverse order so functions are executed
-    last in, first out.
-    """
-
-    exc_info = None
-    while _exithandlers:
-        func, targs, kargs = _exithandlers.pop()
-        try:
-            func(*targs, **kargs)
-        except SystemExit:
-            exc_info = sys.exc_info()
-        except:
-            import traceback
-            print("Error in atexit._run_exitfuncs:", file=sys.stderr)
-            traceback.print_exc()
-            exc_info = sys.exc_info()
-
-    if exc_info is not None:
-        raise exc_info[0], exc_info[1], exc_info[2]
-
-
-def register(func, *targs, **kargs):
-    """register a function to be executed upon normal program termination
-
-    func - function to be called at exit
-    targs - optional arguments to pass to func
-    kargs - optional keyword arguments to pass to func
-
-    func is returned to facilitate usage as a decorator.
-    """
-    _exithandlers.append((func, targs, kargs))
-    return func
-
-if hasattr(sys, "exitfunc"):
-    # Assume it's another registered exit function - append it to our list
-    register(sys.exitfunc)
-sys.exitfunc = _run_exitfuncs
-
-if __name__ == "__main__":
-    def x1():
-        print("running x1")
-    def x2(n):
-        print("running x2(%r)" % (n,))
-    def x3(n, kwd=None):
-        print("running x3(%r, kwd=%r)" % (n, kwd))
-
-    register(x1)
-    register(x2, 12)
-    register(x3, 5, "bar")
-    register(x3, "no kwd args")

Modified: python/branches/p3yk-noslice/Lib/bdb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bdb.py	(original)
+++ python/branches/p3yk-noslice/Lib/bdb.py	Wed Jul 11 15:40:56 2007
@@ -151,7 +151,7 @@
         """This method is called when a return trap is set here."""
         pass
 
-    def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
+    def user_exception(self, frame, exc_info):
         """This method is called if an exception occurs,
         but only if we are to stop at or just below this level."""
         pass

Modified: python/branches/p3yk-noslice/Lib/binhex.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/binhex.py	(original)
+++ python/branches/p3yk-noslice/Lib/binhex.py	Wed Jul 11 15:40:56 2007
@@ -170,7 +170,8 @@
         del self.ofp
 
 class BinHex:
-    def __init__(self, (name, finfo, dlen, rlen), ofp):
+    def __init__(self, name_finfo_dlen_rlen, ofp):
+        name, finfo, dlen, rlen = name_finfo_dlen_rlen
         if type(ofp) == type(''):
             ofname = ofp
             ofp = open(ofname, 'w')
@@ -510,14 +511,7 @@
     ifp.close()
 
 def _test():
-    if os.name == 'mac':
-        import macfs
-        fss, ok = macfs.PromptGetFile('File to convert:')
-        if not ok:
-            sys.exit(0)
-        fname = fss.as_pathname()
-    else:
-        fname = sys.argv[1]
+    fname = sys.argv[1]
     binhex(fname, fname+'.hqx')
     hexbin(fname+'.hqx', fname+'.viahqx')
     #hexbin(fname, fname+'.unpacked')

Modified: python/branches/p3yk-noslice/Lib/bisect.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bisect.py	(original)
+++ python/branches/p3yk-noslice/Lib/bisect.py	Wed Jul 11 15:40:56 2007
@@ -23,8 +23,8 @@
     """Return the index where to insert item x in list a, assuming a is sorted.
 
     The return value i is such that all e in a[:i] have e <= x, and all e in
-    a[i:] have e > x.  So if x already appears in the list, i points just
-    beyond the rightmost x already there.
+    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
+    insert just after the rightmost x already there.
 
     Optional args lo (default 0) and hi (default len(a)) bound the
     slice of a to be searched.
@@ -62,8 +62,8 @@
     """Return the index where to insert item x in list a, assuming a is sorted.
 
     The return value i is such that all e in a[:i] have e < x, and all e in
-    a[i:] have e >= x.  So if x already appears in the list, i points just
-    before the leftmost x already there.
+    a[i:] have e >= x.  So if x already appears in the list, a.insert(x) will
+    insert just before the leftmost x already there.
 
     Optional args lo (default 0) and hi (default len(a)) bound the
     slice of a to be searched.

Modified: python/branches/p3yk-noslice/Lib/bsddb/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/__init__.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/__init__.py	Wed Jul 11 15:40:56 2007
@@ -294,7 +294,7 @@
 #----------------------------------------------------------------------
 # Compatibility object factory functions
 
-def hashopen(file, flag='c', mode=0666, pgsize=None, ffactor=None, nelem=None,
+def hashopen(file, flag='c', mode=0o666, pgsize=None, ffactor=None, nelem=None,
             cachesize=None, lorder=None, hflags=0):
 
     flags = _checkflag(flag, file)
@@ -310,7 +310,7 @@
 
 #----------------------------------------------------------------------
 
-def btopen(file, flag='c', mode=0666,
+def btopen(file, flag='c', mode=0o666,
             btflags=0, cachesize=None, maxkeypage=None, minkeypage=None,
             pgsize=None, lorder=None):
 
@@ -328,7 +328,7 @@
 #----------------------------------------------------------------------
 
 
-def rnopen(file, flag='c', mode=0666,
+def rnopen(file, flag='c', mode=0o666,
             rnflags=0, cachesize=None, pgsize=None, lorder=None,
             rlen=None, delim=None, source=None, pad=None):
 

Modified: python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py	Wed Jul 11 15:40:56 2007
@@ -29,7 +29,6 @@
 """
 
 import errno
-import string
 
 class DBRecIO:
     def __init__(self, db, key, txn=None):
@@ -83,9 +82,9 @@
         if self.closed:
             raise ValueError, "I/O operation on closed file"
         if self.buflist:
-            self.buf = self.buf + string.joinfields(self.buflist, '')
+            self.buf = self.buf + ''.join(self.buflist)
             self.buflist = []
-        i = string.find(self.buf, '\n', self.pos)
+        i = self.buf.find('\n', self.pos)
         if i < 0:
             newpos = self.len
         else:
@@ -134,7 +133,7 @@
         self.pos = newpos
 
     def writelines(self, list):
-        self.write(string.joinfields(list, ''))
+        self.write(''.join(list))
 
     def flush(self):
         if self.closed:

Modified: python/branches/p3yk-noslice/Lib/bsddb/dbshelve.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/dbshelve.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/dbshelve.py	Wed Jul 11 15:40:56 2007
@@ -40,7 +40,7 @@
 #------------------------------------------------------------------------
 
 
-def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH,
+def open(filename, flags=db.DB_CREATE, mode=0o660, filetype=db.DB_HASH,
          dbenv=None, dbname=None):
     """
     A simple factory function for compatibility with the standard

Modified: python/branches/p3yk-noslice/Lib/bsddb/dbtables.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/dbtables.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/dbtables.py	Wed Jul 11 15:40:56 2007
@@ -22,7 +22,6 @@
 import copy
 import xdrlib
 import random
-from types import ListType, StringType
 import cPickle as pickle
 
 try:
@@ -39,7 +38,7 @@
     class DBIncompleteError(Exception):
         pass
 
-class TableDBError(StandardError):
+class TableDBError(Exception):
     pass
 class TableAlreadyExists(TableDBError):
     pass
@@ -135,9 +134,9 @@
 
 
 class bsdTableDB :
-    def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600,
+    def __init__(self, filename, dbhome, create=0, truncate=0, mode=0o600,
                  recover=0, dbflags=0):
-        """bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0600)
+        """bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0o600)
 
         Open database name in the dbhome BerkeleyDB directory.
         Use keyword arguments when calling this constructor.
@@ -229,7 +228,7 @@
 
         raises TableDBError if it already exists or for other DB errors.
         """
-        assert isinstance(columns, ListType)
+        assert isinstance(columns, list)
         txn = None
         try:
             # checking sanity of the table and column names here on
@@ -263,14 +262,14 @@
         except DBError as dberror:
             if txn:
                 txn.abort()
-            raise TableDBError, dberror[1]
+            raise TableDBError, dberror.args[1]
 
 
     def ListTableColumns(self, table):
         """Return a list of columns in the given table.
         [] if the table doesn't exist.
         """
-        assert isinstance(table, StringType)
+        assert isinstance(table, str)
         if contains_metastrings(table):
             raise ValueError, "bad table name: contains reserved metastrings"
 
@@ -300,7 +299,7 @@
         additional columns present in the given list as well as
         all of its current columns.
         """
-        assert isinstance(columns, ListType)
+        assert isinstance(columns, list)
         try:
             self.CreateTable(table, columns)
         except TableAlreadyExists:
@@ -341,7 +340,7 @@
             except DBError as dberror:
                 if txn:
                     txn.abort()
-                raise TableDBError, dberror[1]
+                raise TableDBError, dberror.args[1]
 
 
     def __load_column_info(self, table) :
@@ -416,7 +415,7 @@
             if txn:
                 txn.abort()
                 self.db.delete(_rowid_key(table, rowid))
-            raise TableDBError, dberror[1], info[2]
+            raise TableDBError, dberror.args[1], info[2]
 
 
     def Modify(self, table, conditions={}, mappings={}):
@@ -467,7 +466,7 @@
                     raise
 
         except DBError as dberror:
-            raise TableDBError, dberror[1]
+            raise TableDBError, dberror.args[1]
 
     def Delete(self, table, conditions={}):
         """Delete(table, conditions) - Delete items matching the given
@@ -507,7 +506,7 @@
                         txn.abort()
                     raise
         except DBError as dberror:
-            raise TableDBError, dberror[1]
+            raise TableDBError, dberror.args[1]
 
 
     def Select(self, table, columns, conditions={}):
@@ -527,7 +526,7 @@
                 columns = self.__tablecolumns[table]
             matching_rowids = self.__Select(table, columns, conditions)
         except DBError as dberror:
-            raise TableDBError, dberror[1]
+            raise TableDBError, dberror.args[1]
         # return the matches as a list of dictionaries
         return matching_rowids.values()
 
@@ -617,7 +616,7 @@
                     key, data = cur.next()
 
             except DBError as dberror:
-                if dberror[0] != DB_NOTFOUND:
+                if dberror.args[0] != DB_NOTFOUND:
                     raise
                 continue
 
@@ -637,7 +636,7 @@
                         rowdata[column] = self.db.get(
                             _data_key(table, column, rowid))
                     except DBError as dberror:
-                        if dberror[0] != DB_NOTFOUND:
+                        if dberror.args[0] != DB_NOTFOUND:
                             raise
                         rowdata[column] = None
 
@@ -703,4 +702,4 @@
         except DBError as dberror:
             if txn:
                 txn.abort()
-            raise TableDBError, dberror[1]
+            raise TableDBError, dberror.args[1]

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_1413192.py	Wed Jul 11 15:40:56 2007
@@ -18,4 +18,4 @@
 the_txn = env.txn_begin()
 
 map = db.DB(env)
-map.open('xxx.db', "p", db.DB_HASH, db.DB_CREATE, 0666, txn=the_txn)
+map.open('xxx.db', "p", db.DB_HASH, db.DB_CREATE, 0o666, txn=the_txn)

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 TestCases for DB.associate.
 """
 
-import sys, os, string
+import sys, os
 import tempfile
 import time
 from pprint import pprint
@@ -177,7 +177,7 @@
         for key, value in musicdata.items():
             if type(self.keytype) == type(''):
                 key = "%02d" % key
-            d.put(key, string.join(value, '|'), txn=txn)
+            d.put(key, '|'.join(value), txn=txn)
 
     def createDB(self, txn=None):
         self.cur = None
@@ -263,7 +263,7 @@
         rec = self.cur.first()
         while rec is not None:
             if type(self.keytype) == type(''):
-                assert string.atoi(rec[0])  # for primary db, key is a number
+                assert int(rec[0])  # for primary db, key is a number
             else:
                 assert rec[0] and type(rec[0]) == type(0)
             count = count + 1
@@ -305,7 +305,7 @@
         assert type(priData) == type("")
         if verbose:
             print('getGenre key: %r data: %r' % (priKey, priData))
-        genre = string.split(priData, '|')[2]
+        genre = priData.split('|')[2]
         if genre == 'Blues':
             return db.DB_DONOTINDEX
         else:
@@ -427,13 +427,13 @@
         for key, value in musicdata.items():
             if type(self.keytype) == type(''):
                 key = "%02d" % key
-            d.put(key, string.join(value, '|'))
+            d.put(key, '|'.join(value))
 
     def writer2(self, d):
         for x in range(100, 600):
             key = 'z%2d' % x
             value = [key] * 4
-            d.put(key, string.join(value, '|'))
+            d.put(key, '|'.join(value))
 
 
 class ThreadedAssociateHashTestCase(ShelveAssociateTestCase):

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py	Wed Jul 11 15:40:56 2007
@@ -44,7 +44,7 @@
     dbtype       = db.DB_UNKNOWN  # must be set in derived class
     dbopenflags  = 0
     dbsetflags   = 0
-    dbmode       = 0660
+    dbmode       = 0o660
     dbname       = None
     useEnv       = 0
     envflags     = 0
@@ -163,7 +163,7 @@
         try:
             d.delete('abcd')
         except db.DBNotFoundError as val:
-            assert val[0] == db.DB_NOTFOUND
+            assert val.args[0] == db.DB_NOTFOUND
             if verbose: print(val)
         else:
             self.fail("expected exception")
@@ -182,7 +182,7 @@
         try:
             d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE)
         except db.DBKeyExistError as val:
-            assert val[0] == db.DB_KEYEXIST
+            assert val.args[0] == db.DB_KEYEXIST
             if verbose: print(val)
         else:
             self.fail("expected exception")
@@ -315,7 +315,7 @@
                 rec = c.next()
             except db.DBNotFoundError as val:
                 if get_raises_error:
-                    assert val[0] == db.DB_NOTFOUND
+                    assert val.args[0] == db.DB_NOTFOUND
                     if verbose: print(val)
                     rec = None
                 else:
@@ -335,7 +335,7 @@
                 rec = c.prev()
             except db.DBNotFoundError as val:
                 if get_raises_error:
-                    assert val[0] == db.DB_NOTFOUND
+                    assert val.args[0] == db.DB_NOTFOUND
                     if verbose: print(val)
                     rec = None
                 else:
@@ -358,7 +358,7 @@
         try:
             n = c.set('bad key')
         except db.DBNotFoundError as val:
-            assert val[0] == db.DB_NOTFOUND
+            assert val.args[0] == db.DB_NOTFOUND
             if verbose: print(val)
         else:
             if set_raises_error:
@@ -372,7 +372,7 @@
         try:
             n = c.get_both('0404', 'bad data')
         except db.DBNotFoundError as val:
-            assert val[0] == db.DB_NOTFOUND
+            assert val.args[0] == db.DB_NOTFOUND
             if verbose: print(val)
         else:
             if get_raises_error:
@@ -401,7 +401,7 @@
             rec = c.current()
         except db.DBKeyEmptyError as val:
             if get_raises_error:
-                assert val[0] == db.DB_KEYEMPTY
+                assert val.args[0] == db.DB_KEYEMPTY
                 if verbose: print(val)
             else:
                 self.fail("unexpected DBKeyEmptyError")
@@ -446,7 +446,7 @@
                 # a bug may cause a NULL pointer dereference...
                 getattr(c, method)(*args)
             except db.DBError as val:
-                assert val[0] == 0
+                assert val.args[0] == 0
                 if verbose: print(val)
             else:
                 self.fail("no exception raised when using a buggy cursor's"

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,7 @@
 regression test suite.
 """
 
-import sys, os, string
+import sys, os
 import unittest
 import tempfile
 
@@ -35,7 +35,7 @@
         self.do_bthash_test(hashopen, 'hashopen')
 
     def test03_rnopen(self):
-        data = string.split("The quick brown fox jumped over the lazy dog.")
+        data = "The quick brown fox jumped over the lazy dog.".split()
         if verbose:
             print("\nTesting: rnopen")
 

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_dbobj.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 
-import sys, os, string
+import sys, os
 import unittest
 import glob
 import tempfile
@@ -38,7 +38,7 @@
         class TestDBEnv(dbobj.DBEnv): pass
         class TestDB(dbobj.DB):
             def put(self, key, *args, **kwargs):
-                key = string.upper(key)
+                key = key.upper()
                 # call our parent classes put method with an upper case key
                 return dbobj.DB.put(self, key, *args, **kwargs)
         self.env = TestDBEnv()

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_env_close.py	Wed Jul 11 15:40:56 2007
@@ -50,10 +50,10 @@
         dbenv = db.DBEnv()
         dbenv.open(self.homeDir,
                    db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL,
-                   0666)
+                   0o666)
 
         d = db.DB(dbenv)
-        d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0666)
+        d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0o666)
 
         try:
             dbenv.close()
@@ -75,10 +75,10 @@
         dbenv = db.DBEnv()
         dbenv.open(self.homeDir,
                    db.DB_INIT_CDB| db.DB_CREATE |db.DB_THREAD|db.DB_INIT_MPOOL,
-                   0666)
+                   0o666)
 
         d = db.DB(dbenv)
-        d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0666)
+        d.open(self.filename, db.DB_BTREE, db.DB_CREATE | db.DB_THREAD, 0o666)
 
         try:
             dbenv.close()

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,7 @@
 """TestCases for using the DB.join and DBCursor.join_item methods.
 """
 
-import sys, os, string
+import sys, os
 import tempfile
 import time
 from pprint import pprint
@@ -72,13 +72,13 @@
         # create and populate primary index
         priDB = db.DB(self.env)
         priDB.open(self.filename, "primary", db.DB_BTREE, db.DB_CREATE)
-        map(lambda t, priDB=priDB: priDB.put(*t), ProductIndex)
+        [priDB.put(*t) for t in ProductIndex]
 
         # create and populate secondary index
         secDB = db.DB(self.env)
         secDB.set_flags(db.DB_DUP | db.DB_DUPSORT)
         secDB.open(self.filename, "secondary", db.DB_BTREE, db.DB_CREATE)
-        map(lambda t, secDB=secDB: secDB.put(*t), ColorIndex)
+        [secDB.put(*t) for t in ColorIndex]
 
         sCursor = None
         jCursor = None

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 TestCases for testing the locking sub-system.
 """
 
-import sys, os, string
+import sys, os
 import tempfile
 import time
 from pprint import pprint

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_pickle.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 
-import sys, os, string
+import sys, os
 import pickle
 try:
     import cPickle

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py	Wed Jul 11 15:40:56 2007
@@ -64,7 +64,7 @@
         try:
             data = d[0]  # This should raise a KeyError!?!?!
         except db.DBInvalidArgError as val:
-            assert val[0] == db.EINVAL
+            assert val.args[0] == db.EINVAL
             if verbose: print(val)
         else:
             self.fail("expected exception")
@@ -118,7 +118,7 @@
         assert not d.has_key(13)
 
         data = d.get_both(26, "z" * 60)
-        assert data == "z" * 60
+        assert data == "z" * 60, 'was %r' % data
         if verbose:
             print(data)
 
@@ -181,7 +181,7 @@
             if get_returns_none:
                 self.fail("unexpected DBKeyEmptyError exception")
             else:
-                assert val[0] == db.DB_KEYEMPTY
+                assert val.args[0] == db.DB_KEYEMPTY
                 if verbose: print(val)
         else:
             if not get_returns_none:
@@ -268,7 +268,7 @@
         try:                    # this one will fail
             d.append('bad' * 20)
         except db.DBInvalidArgError as val:
-            assert val[0] == db.EINVAL
+            assert val.args[0] == db.EINVAL
             if verbose: print(val)
         else:
             self.fail("expected exception")

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_sequence.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_sequence.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_sequence.py	Wed Jul 11 15:40:56 2007
@@ -26,9 +26,9 @@
         tempfile.tempdir = None
 
         self.dbenv = db.DBEnv()
-        self.dbenv.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL, 0666)
+        self.dbenv.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL, 0o666)
         self.d = db.DB(self.dbenv)
-        self.d.open(self.filename, db.DB_BTREE, db.DB_CREATE, 0666)
+        self.d.open(self.filename, db.DB_BTREE, db.DB_CREATE, 0o666)
 
     def tearDown(self):
         if hasattr(self, 'seq'):

Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py	(original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py	Wed Jul 11 15:40:56 2007
@@ -10,12 +10,6 @@
 from pprint import pprint
 from random import random
 
-try:
-    True, False
-except NameError:
-    True = 1
-    False = 0
-
 DASH = '-'
 
 try:
@@ -229,7 +223,7 @@
             print("%s: creating records %d - %d" % (name, start, stop))
 
         # create a bunch of records
-        for x in xrange(start, stop):
+        for x in range(start, stop):
             key = '%04d' % x
             dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                  max_retries=12)
@@ -239,7 +233,7 @@
 
             # do a bit or reading too
             if random() <= 0.05:
-                for y in xrange(start, x):
+                for y in range(start, x):
                     key = '%04d' % x
                     data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
                     self.assertEqual(data, self.makeData(key))
@@ -252,7 +246,7 @@
                 print("could not complete sync()...")
 
         # read them back, deleting a few
-        for x in xrange(start, stop):
+        for x in range(start, stop):
             key = '%04d' % x
             data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
             if verbose and x % 100 == 0:

Modified: python/branches/p3yk-noslice/Lib/calendar.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/calendar.py	(original)
+++ python/branches/p3yk-noslice/Lib/calendar.py	Wed Jul 11 15:40:56 2007
@@ -45,7 +45,7 @@
 
 class _localized_month:
 
-    _months = [datetime.date(2001, i+1, 1).strftime for i in xrange(12)]
+    _months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
     _months.insert(0, lambda x: "")
 
     def __init__(self, format):
@@ -65,7 +65,7 @@
 class _localized_day:
 
     # January 1, 2001, was a Monday.
-    _days = [datetime.date(2001, 1, i+1).strftime for i in xrange(7)]
+    _days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
 
     def __init__(self, format):
         self.format = format
@@ -144,7 +144,7 @@
         Return a iterator for one week of weekday numbers starting with the
         configured first one.
         """
-        for i in xrange(self.firstweekday, self.firstweekday + 7):
+        for i in range(self.firstweekday, self.firstweekday + 7):
             yield i%7
 
     def itermonthdates(self, year, month):
@@ -192,7 +192,7 @@
         Each row represents a week; week entries are datetime.date values.
         """
         dates = list(self.itermonthdates(year, month))
-        return [ dates[i:i+7] for i in xrange(0, len(dates), 7) ]
+        return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
 
     def monthdays2calendar(self, year, month):
         """
@@ -202,7 +202,7 @@
         are zero.
         """
         days = list(self.itermonthdays2(year, month))
-        return [ days[i:i+7] for i in xrange(0, len(days), 7) ]
+        return [ days[i:i+7] for i in range(0, len(days), 7) ]
 
     def monthdayscalendar(self, year, month):
         """
@@ -210,7 +210,7 @@
         Each row represents a week; days outside this month are zero.
         """
         days = list(self.itermonthdays(year, month))
-        return [ days[i:i+7] for i in xrange(0, len(days), 7) ]
+        return [ days[i:i+7] for i in range(0, len(days), 7) ]
 
     def yeardatescalendar(self, year, width=3):
         """
@@ -221,9 +221,9 @@
         """
         months = [
             self.monthdatescalendar(year, i)
-            for i in xrange(January, January+12)
+            for i in range(January, January+12)
         ]
-        return [months[i:i+width] for i in xrange(0, len(months), width) ]
+        return [months[i:i+width] for i in range(0, len(months), width) ]
 
     def yeardays2calendar(self, year, width=3):
         """
@@ -234,9 +234,9 @@
         """
         months = [
             self.monthdays2calendar(year, i)
-            for i in xrange(January, January+12)
+            for i in range(January, January+12)
         ]
-        return [months[i:i+width] for i in xrange(0, len(months), width) ]
+        return [months[i:i+width] for i in range(0, len(months), width) ]
 
     def yeardayscalendar(self, year, width=3):
         """
@@ -246,9 +246,9 @@
         """
         months = [
             self.monthdayscalendar(year, i)
-            for i in xrange(January, January+12)
+            for i in range(January, January+12)
         ]
-        return [months[i:i+width] for i in xrange(0, len(months), width) ]
+        return [months[i:i+width] for i in range(0, len(months), width) ]
 
 
 class TextCalendar(Calendar):
@@ -341,7 +341,7 @@
         header = self.formatweekheader(w)
         for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
             # months in this row
-            months = xrange(m*i+1, min(m*(i+1)+1, 13))
+            months = range(m*i+1, min(m*(i+1)+1, 13))
             a('\n'*l)
             names = (self.formatmonthname(theyear, k, colwidth, False)
                      for k in months)
@@ -352,7 +352,7 @@
             a('\n'*l)
             # max number of weeks for this row
             height = max(len(cal) for cal in row)
-            for j in xrange(height):
+            for j in range(height):
                 weeks = []
                 for cal in row:
                     if j >= len(cal):
@@ -444,9 +444,9 @@
         a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
         a('\n')
         a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
-        for i in xrange(January, January+12, width):
+        for i in range(January, January+12, width):
             # months in this row
-            months = xrange(i, min(i+width, 13))
+            months = range(i, min(i+width, 13))
             a('<tr>')
             for m in months:
                 a('<td>')

Modified: python/branches/p3yk-noslice/Lib/cgi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/cgi.py	(original)
+++ python/branches/p3yk-noslice/Lib/cgi.py	Wed Jul 11 15:40:56 2007
@@ -575,7 +575,7 @@
         if key in self:
             value = self[key]
             if type(value) is type([]):
-                return map(attrgetter('value'), value)
+                return [x.value for x in value]
             else:
                 return value.value
         else:
@@ -597,7 +597,7 @@
         if key in self:
             value = self[key]
             if type(value) is type([]):
-                return map(attrgetter('value'), value)
+                return [x.value for x in value]
             else:
                 return [value.value]
         else:

Modified: python/branches/p3yk-noslice/Lib/cgitb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/cgitb.py	(original)
+++ python/branches/p3yk-noslice/Lib/cgitb.py	Wed Jul 11 15:40:56 2007
@@ -94,11 +94,12 @@
         lasttoken = token
     return vars
 
-def html((etype, evalue, etb), context=5):
+def html(einfo, context=5):
     """Return a nice HTML document describing a given traceback."""
-    import os, types, time, traceback, linecache, inspect, pydoc
+    import os, time, traceback, linecache, inspect, pydoc
 
-    if type(etype) is types.ClassType:
+    etype, evalue, etb = einfo
+    if isinstance(etype, type):
         etype = etype.__name__
     pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
     date = time.ctime(time.time())
@@ -167,11 +168,10 @@
 
     exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
                                 pydoc.html.escape(str(evalue)))]
-    if type(evalue) is types.InstanceType:
-        for name in dir(evalue):
-            if name[:1] == '_': continue
-            value = pydoc.html.repr(getattr(evalue, name))
-            exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
+    for name in dir(evalue):
+        if name[:1] == '_': continue
+        value = pydoc.html.repr(getattr(evalue, name))
+        exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))
 
     import traceback
     return head + ''.join(frames) + ''.join(exception) + '''
@@ -183,13 +183,15 @@
 
 %s
 -->
-''' % ''.join(traceback.format_exception(etype, evalue, etb))
+''' % pydoc.html.escape(
+          ''.join(traceback.format_exception(etype, evalue, etb)))
 
-def text((etype, evalue, etb), context=5):
+def text(einfo, context=5):
     """Return a plain text document describing a given traceback."""
-    import os, types, time, traceback, linecache, inspect, pydoc
+    import os, time, traceback, linecache, inspect, pydoc
 
-    if type(etype) is types.ClassType:
+    etype, evalue, etb = einfo
+    if isinstance(etype, type):
         etype = etype.__name__
     pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
     date = time.ctime(time.time())
@@ -239,10 +241,9 @@
         frames.append('\n%s\n' % '\n'.join(rows))
 
     exception = ['%s: %s' % (str(etype), str(evalue))]
-    if type(evalue) is types.InstanceType:
-        for name in dir(evalue):
-            value = pydoc.text.repr(getattr(evalue, name))
-            exception.append('\n%s%s = %s' % (" "*4, name, value))
+    for name in dir(evalue):
+        value = pydoc.text.repr(getattr(evalue, name))
+        exception.append('\n%s%s = %s' % (" "*4, name, value))
 
     import traceback
     return head + ''.join(frames) + ''.join(exception) + '''

Modified: python/branches/p3yk-noslice/Lib/chunk.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/chunk.py	(original)
+++ python/branches/p3yk-noslice/Lib/chunk.py	Wed Jul 11 15:40:56 2007
@@ -62,7 +62,7 @@
         if len(self.chunkname) < 4:
             raise EOFError
         try:
-            self.chunksize = struct.unpack(strflag+'L', file.read(4))[0]
+            self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0]
         except struct.error:
             raise EOFError
         if inclheader:

Modified: python/branches/p3yk-noslice/Lib/cmd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/cmd.py	(original)
+++ python/branches/p3yk-noslice/Lib/cmd.py	Wed Jul 11 15:40:56 2007
@@ -49,11 +49,6 @@
 PROMPT = '(Cmd) '
 IDENTCHARS = string.ascii_letters + string.digits + '_'
 
-def raw_input(prompt):
-    sys.stdout.write(prompt)
-    sys.stdout.flush()
-    return sys.stdin.readline()
-
 class Cmd:
     """A simple framework for writing line-oriented command interpreters.
 
@@ -129,7 +124,7 @@
                 else:
                     if self.use_rawinput:
                         try:
-                            line = raw_input(self.prompt)
+                            line = input(self.prompt)
                         except EOFError:
                             line = 'EOF'
                     else:

Modified: python/branches/p3yk-noslice/Lib/codecs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/codecs.py	(original)
+++ python/branches/p3yk-noslice/Lib/codecs.py	Wed Jul 11 15:40:56 2007
@@ -87,7 +87,9 @@
         return self
 
     def __repr__(self):
-        return "<%s.%s object for encoding %s at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
+        return "<%s.%s object for encoding %s at 0x%x>" % \
+                (self.__class__.__module__, self.__class__.__name__,
+                 self.name, id(self))
 
 class Codec:
 
@@ -155,9 +157,9 @@
 
 class IncrementalEncoder(object):
     """
-    An IncrementalEncoder encodes an input in multiple steps. The input can be
-    passed piece by piece to the encode() method. The IncrementalEncoder remembers
-    the state of the Encoding process between calls to encode().
+    An IncrementalEncoder encodes an input in multiple steps. The input can
+    be passed piece by piece to the encode() method. The IncrementalEncoder
+    remembers the state of the encoding process between calls to encode().
     """
     def __init__(self, errors='strict'):
         """
@@ -181,6 +183,18 @@
         Resets the encoder to the initial state.
         """
 
+    def getstate(self):
+        """
+        Return the current state of the encoder.
+        """
+        return 0
+
+    def setstate(self, state):
+        """
+        Set the current state of the encoder. state must have been
+        returned by getstate().
+        """
+
 class BufferedIncrementalEncoder(IncrementalEncoder):
     """
     This subclass of IncrementalEncoder can be used as the baseclass for an
@@ -189,7 +203,8 @@
     """
     def __init__(self, errors='strict'):
         IncrementalEncoder.__init__(self, errors)
-        self.buffer = "" # unencoded input that is kept between calls to encode()
+        # unencoded input that is kept between calls to encode()
+        self.buffer = ""
 
     def _buffer_encode(self, input, errors, final):
         # Overwrite this method in subclasses: It must encode input
@@ -208,10 +223,16 @@
         IncrementalEncoder.reset(self)
         self.buffer = ""
 
+    def getstate(self):
+        return self.buffer or 0
+
+    def setstate(self, state):
+        self.buffer = state or ""
+
 class IncrementalDecoder(object):
     """
-    An IncrementalDecoder decodes an input in multiple steps. The input can be
-    passed piece by piece to the decode() method. The IncrementalDecoder
+    An IncrementalDecoder decodes an input in multiple steps. The input can
+    be passed piece by piece to the decode() method. The IncrementalDecoder
     remembers the state of the decoding process between calls to decode().
     """
     def __init__(self, errors='strict'):
@@ -235,15 +256,29 @@
         Resets the decoder to the initial state.
         """
 
+    def getstate(self):
+        """
+        Return the current state of the decoder. This must be a
+        (buffered_input, additional_state_info) tuple.
+        """
+        return ("", 0)
+
+    def setstate(self, state):
+        """
+        Set the current state of the decoder. state must have been
+        returned by getstate().
+        """
+
 class BufferedIncrementalDecoder(IncrementalDecoder):
     """
     This subclass of IncrementalDecoder can be used as the baseclass for an
-    incremental decoder if the decoder must be able to handle incomplete byte
-    sequences.
+    incremental decoder if the decoder must be able to handle incomplete
+    byte sequences.
     """
     def __init__(self, errors='strict'):
         IncrementalDecoder.__init__(self, errors)
-        self.buffer = "" # undecoded input that is kept between calls to decode()
+        # undecoded input that is kept between calls to decode()
+        self.buffer = ""
 
     def _buffer_decode(self, input, errors, final):
         # Overwrite this method in subclasses: It must decode input
@@ -262,6 +297,14 @@
         IncrementalDecoder.reset(self)
         self.buffer = ""
 
+    def getstate(self):
+        # additional state info is always 0
+        return (self.buffer, 0)
+
+    def setstate(self, state):
+        # ignore additional state info
+        self.buffer = state[0]
+
 #
 # The StreamWriter and StreamReader class provide generic working
 # interfaces which can be used to implement new encoding submodules
@@ -424,7 +467,8 @@
                 newchars, decodedbytes = self.decode(data, self.errors)
             except UnicodeDecodeError as exc:
                 if firstline:
-                    newchars, decodedbytes = self.decode(data[:exc.start], self.errors)
+                    newchars, decodedbytes = \
+                        self.decode(data[:exc.start], self.errors)
                     lines = newchars.splitlines(True)
                     if len(lines)<=1:
                         raise
@@ -556,7 +600,7 @@
         self.reset()
         self.stream.seek(offset, whence)
 
-    def next(self):
+    def __next__(self):
 
         """ Return the next decoded line from the input stream."""
         line = self.readline()
@@ -625,10 +669,10 @@
 
         return self.reader.readlines(sizehint)
 
-    def next(self):
+    def __next__(self):
 
         """ Return the next decoded line from the input stream."""
-        return self.reader.next()
+        return next(self.reader)
 
     def __iter__(self):
         return self
@@ -738,10 +782,10 @@
         data, bytesencoded = self.encode(data, self.errors)
         return data.splitlines(1)
 
-    def next(self):
+    def __next__(self):
 
         """ Return the next decoded line from the input stream."""
-        data = self.reader.next()
+        data = next(self.reader)
         data, bytesencoded = self.encode(data, self.errors)
         return data
 

Modified: python/branches/p3yk-noslice/Lib/commands.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/commands.py	(original)
+++ python/branches/p3yk-noslice/Lib/commands.py	Wed Jul 11 15:40:56 2007
@@ -19,7 +19,7 @@
  [Note:  it would be nice to add functions to interpret the exit status.]
 """
 
-__all__ = ["getstatusoutput","getoutput","getstatus"]
+__all__ = ["getstatusoutput", "getoutput"]
 
 # Module 'commands'
 #
@@ -28,13 +28,6 @@
 # NB This only works (and is only relevant) for UNIX.
 
 
-# Get 'ls -l' status for an object into a string
-#
-def getstatus(file):
-    """Return output of "ls -ld <file>" in a string."""
-    return getoutput('ls -ld' + mkarg(file))
-
-
 # Get the output from a shell command into a string.
 # The exit status is ignored; a trailing newline is stripped.
 # Assume the command will work with '{ ... ; } 2>&1' around it..

Modified: python/branches/p3yk-noslice/Lib/contextlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/contextlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/contextlib.py	Wed Jul 11 15:40:56 2007
@@ -12,14 +12,14 @@
 
     def __enter__(self):
         try:
-            return self.gen.next()
+            return next(self.gen)
         except StopIteration:
             raise RuntimeError("generator didn't yield")
 
     def __exit__(self, type, value, traceback):
         if type is None:
             try:
-                self.gen.next()
+                next(self.gen)
             except StopIteration:
                 return
             else:

Modified: python/branches/p3yk-noslice/Lib/copy.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/copy.py	(original)
+++ python/branches/p3yk-noslice/Lib/copy.py	Wed Jul 11 15:40:56 2007
@@ -99,13 +99,16 @@
 
 def _copy_immutable(x):
     return x
-for t in (type(None), int, int, float, bool, str, tuple,
-          frozenset, type, xrange, types.ClassType,
+for t in (type(None), int, float, bool, str, tuple,
+          frozenset, type, range,
           types.BuiltinFunctionType,
           types.FunctionType):
     d[t] = _copy_immutable
-for name in ("ComplexType", "UnicodeType", "CodeType"):
-    t = getattr(types, name, None)
+t = getattr(types, "CodeType", None)
+if t is not None:
+    d[t] = _copy_immutable
+for name in ("complex", "unicode"):
+    t = globals()['__builtins__'].get(name)
     if t is not None:
         d[t] = _copy_immutable
 
@@ -178,7 +181,6 @@
     return x
 d[type(None)] = _deepcopy_atomic
 d[int] = _deepcopy_atomic
-d[int] = _deepcopy_atomic
 d[float] = _deepcopy_atomic
 d[bool] = _deepcopy_atomic
 try:
@@ -195,8 +197,7 @@
 except AttributeError:
     pass
 d[type] = _deepcopy_atomic
-d[xrange] = _deepcopy_atomic
-d[types.ClassType] = _deepcopy_atomic
+d[range] = _deepcopy_atomic
 d[types.BuiltinFunctionType] = _deepcopy_atomic
 d[types.FunctionType] = _deepcopy_atomic
 

Modified: python/branches/p3yk-noslice/Lib/copy_reg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/copy_reg.py	(original)
+++ python/branches/p3yk-noslice/Lib/copy_reg.py	Wed Jul 11 15:40:56 2007
@@ -10,7 +10,7 @@
 dispatch_table = {}
 
 def pickle(ob_type, pickle_function, constructor_ob=None):
-    if not callable(pickle_function):
+    if not hasattr(pickle_function, '__call__'):
         raise TypeError("reduction functions must be callable")
     dispatch_table[ob_type] = pickle_function
 
@@ -20,7 +20,7 @@
         constructor(constructor_ob)
 
 def constructor(object):
-    if not callable(object):
+    if not hasattr(object, '__call__'):
         raise TypeError("constructors must be callable")
 
 # Example: provide pickling support for complex numbers.
@@ -43,7 +43,8 @@
         obj = object.__new__(cls)
     else:
         obj = base.__new__(cls, state)
-        base.__init__(obj, state)
+        if base.__init__ != object.__init__:
+            base.__init__(obj, state)
     return obj
 
 _HEAPTYPE = 1<<9

Modified: python/branches/p3yk-noslice/Lib/csv.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/csv.py	(original)
+++ python/branches/p3yk-noslice/Lib/csv.py	Wed Jul 11 15:40:56 2007
@@ -79,17 +79,17 @@
     def __iter__(self):
         return self
 
-    def next(self):
-        row = self.reader.next()
+    def __next__(self):
+        row = next(self.reader)
         if self.fieldnames is None:
             self.fieldnames = row
-            row = self.reader.next()
+            row = next(self.reader)
 
         # unlike the basic reader, we prefer not to return blanks,
         # because we will typically wind up with a dict full of None
         # values
         while row == []:
-            row = self.reader.next()
+            row = next(self.reader)
         d = dict(zip(self.fieldnames, row))
         lf = len(self.fieldnames)
         lr = len(row)
@@ -115,9 +115,10 @@
 
     def _dict_to_list(self, rowdict):
         if self.extrasaction == "raise":
-            for k in rowdict.keys():
-                if k not in self.fieldnames:
-                    raise ValueError, "dict contains fields not in fieldnames"
+            wrong_fields = [k for k in rowdict if k not in self.fieldnames]
+            if wrong_fields:
+                raise ValueError("dict contains fields not in fieldnames: " +
+                                 ", ".join(wrong_fields))
         return [rowdict.get(key, self.restval) for key in self.fieldnames]
 
     def writerow(self, rowdict):
@@ -255,7 +256,7 @@
         additional chunks as necessary.
         """
 
-        data = filter(None, data.split('\n'))
+        data = list(filter(None, data.split('\n')))
 
         ascii = [chr(c) for c in range(127)] # 7-bit ASCII
 
@@ -351,7 +352,7 @@
 
         rdr = reader(StringIO(sample), self.sniff(sample))
 
-        header = rdr.next() # assume first row is header
+        header = next(rdr) # assume first row is header
 
         columns = len(header)
         columnTypes = {}

Modified: python/branches/p3yk-noslice/Lib/ctypes/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/__init__.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/__init__.py	Wed Jul 11 15:40:56 2007
@@ -149,7 +149,7 @@
     _type_ = "O"
     def __repr__(self):
         try:
-            return super(py_object, self).__repr__()
+            return super().__repr__()
         except ValueError:
             return "%s(<NULL>)" % type(self).__name__
 _check_size(py_object, "P")
@@ -233,6 +233,9 @@
 c_voidp = c_void_p # backwards compatibility (to a bug)
 _check_size(c_void_p)
 
+class c_bool(_SimpleCData):
+    _type_ = "t"
+
 # This cache maps types to pointers to them.
 _pointer_type_cache = {}
 
@@ -480,7 +483,7 @@
     return _cast(obj, obj, typ)
 
 _string_at = CFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
-def string_at(ptr, size=0):
+def string_at(ptr, size=-1):
     """string_at(addr[, size]) -> string
 
     Return the string at addr."""
@@ -492,7 +495,7 @@
     pass
 else:
     _wstring_at = CFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr)
-    def wstring_at(ptr, size=0):
+    def wstring_at(ptr, size=-1):
         """wstring_at(addr[, size]) -> string
 
         Return the string at addr."""

Modified: python/branches/p3yk-noslice/Lib/ctypes/_endian.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/_endian.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/_endian.py	Wed Jul 11 15:40:56 2007
@@ -29,7 +29,7 @@
                 rest = desc[2:]
                 fields.append((name, _other_endian(typ)) + rest)
             value = fields
-        super(_swapped_meta, self).__setattr__(attrname, value)
+        super().__setattr__(attrname, value)
 
 ################################################################
 
@@ -42,18 +42,16 @@
 
     LittleEndianStructure = Structure
 
-    class BigEndianStructure(Structure):
+    class BigEndianStructure(Structure, metaclass=_swapped_meta):
         """Structure with big endian byte order"""
-        __metaclass__ = _swapped_meta
         _swappedbytes_ = None
 
 elif sys.byteorder == "big":
     _OTHER_ENDIAN = "__ctype_le__"
 
     BigEndianStructure = Structure
-    class LittleEndianStructure(Structure):
+    class LittleEndianStructure(Structure, metaclass=_swapped_meta):
         """Structure with little endian byte order"""
-        __metaclass__ = _swapped_meta
         _swappedbytes_ = None
 
 else:

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_arrays.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_arrays.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_arrays.py	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,7 @@
         # create classes holding simple numeric types, and check
         # various properties.
 
-        init = range(15, 25)
+        init = list(range(15, 25))
 
         for fmt in formats:
             alen = len(init)
@@ -27,7 +27,7 @@
 
             # change the items
             from operator import setitem
-            new_values = range(42, 42+alen)
+            new_values = list(range(42, 42+alen))
             [setitem(ia, n, new_values[n]) for n in range(alen)]
             values = [ia[i] for i in range(len(init))]
             self.failUnlessEqual(values, new_values)

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_checkretval.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_checkretval.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_checkretval.py	Wed Jul 11 15:40:56 2007
@@ -34,7 +34,7 @@
         def test_oledll(self):
             self.failUnlessRaises(WindowsError,
                                   oledll.oleaut32.CreateTypeLib2,
-                                  0, 0, 0)
+                                  0, None, None)
 
 if __name__ == "__main__":
     unittest.main()

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py	Wed Jul 11 15:40:56 2007
@@ -21,7 +21,9 @@
 
 class POINT(Structure):
     _fields_ = [("x", c_int), ("y", c_int)]
-
+class RECT(Structure):
+    _fields_ = [("left", c_int), ("top", c_int),
+                ("right", c_int), ("bottom", c_int)]
 class FunctionTestCase(unittest.TestCase):
 
     def test_mro(self):
@@ -379,5 +381,15 @@
             self.failUnlessEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h),
                                  (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
 
+    def test_sf1651235(self):
+        # see http://www.python.org/sf/1651235
+
+        proto = CFUNCTYPE(c_int, RECT, POINT)
+        def callback(*args):
+            return 0
+
+        callback = proto(callback)
+        self.failUnlessRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT()))
+
 if __name__ == '__main__':
     unittest.main()

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_init.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_init.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_init.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
     new_was_called = False
 
     def __new__(cls):
-        result = super(X, cls).__new__(cls)
+        result = super().__new__(cls)
         result.new_was_called = True
         return result
 

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py	Wed Jul 11 15:40:56 2007
@@ -73,5 +73,33 @@
 
             self.failUnlessRaises(AttributeError, dll.__getitem__, 1234)
 
+    if os.name == "nt":
+        def test_1703286_A(self):
+            from _ctypes import LoadLibrary, FreeLibrary
+            # On winXP 64-bit, advapi32 loads at an address that does
+            # NOT fit into a 32-bit integer.  FreeLibrary must be able
+            # to accept this address.
+
+            # These are tests for http://www.python.org/sf/1703286
+            handle = LoadLibrary("advapi32")
+            FreeLibrary(handle)
+
+        def test_1703286_B(self):
+            # Since on winXP 64-bit advapi32 loads like described
+            # above, the (arbitrarily selected) CloseEventLog function
+            # also has a high address.  'call_function' should accept
+            # addresses so large.
+            from _ctypes import call_function
+            advapi32 = windll.advapi32
+            # Calling CloseEventLog with a NULL argument should fail,
+            # but the call should not segfault or so.
+            self.failUnlessEqual(0, advapi32.CloseEventLog(None))
+            windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
+            windll.kernel32.GetProcAddress.restype = c_void_p
+            proc = windll.kernel32.GetProcAddress(advapi32._handle, "CloseEventLog")
+            self.failUnless(proc)
+            # This is the real test: call the function via 'call_function'
+            self.failUnlessEqual(0, call_function(proc, (None,)))
+
 if __name__ == "__main__":
     unittest.main()

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_memfunctions.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_memfunctions.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_memfunctions.py	Wed Jul 11 15:40:56 2007
@@ -14,6 +14,7 @@
         self.failUnlessEqual(string_at(result), "Hello, World")
         self.failUnlessEqual(string_at(result, 5), "Hello")
         self.failUnlessEqual(string_at(result, 16), "Hello, World\0\0\0\0")
+        self.failUnlessEqual(string_at(result, 0), "")
 
     def test_memset(self):
         a = create_string_buffer(1000000)
@@ -54,6 +55,7 @@
             self.failUnlessEqual(wstring_at(a), "Hello, World")
             self.failUnlessEqual(wstring_at(a, 5), "Hello")
             self.failUnlessEqual(wstring_at(a, 16), "Hello, World\0\0\0\0")
+            self.failUnlessEqual(wstring_at(a, 0), "")
 
 if __name__ == "__main__":
     unittest.main()

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py	Wed Jul 11 15:40:56 2007
@@ -24,6 +24,8 @@
 unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong]
 signed_types = [c_byte, c_short, c_int, c_long, c_longlong]
 
+bool_types = []
+
 float_types = [c_double, c_float]
 
 try:
@@ -35,8 +37,16 @@
     unsigned_types.append(c_ulonglong)
     signed_types.append(c_longlong)
 
+try:
+    c_bool
+except NameError:
+    pass
+else:
+    bool_types.append(c_bool)
+
 unsigned_ranges = valid_ranges(*unsigned_types)
 signed_ranges = valid_ranges(*signed_types)
+bool_values = [True, False, 0, 1, -1, 5000, 'test', [], [1]]
 
 ################################################################
 
@@ -60,6 +70,11 @@
             self.failUnlessEqual(t(l).value, l)
             self.failUnlessEqual(t(h).value, h)
 
+    def test_bool_values(self):
+        from operator import truth
+        for t, v in zip(bool_types, bool_values):
+            self.failUnlessEqual(t(v).value, truth(v))
+
     def test_typeerror(self):
         # Only numbers are allowed in the contructor,
         # otherwise TypeError is raised
@@ -82,7 +97,7 @@
 
     def test_byref(self):
         # calling byref returns also a PyCArgObject instance
-        for t in signed_types + unsigned_types + float_types:
+        for t in signed_types + unsigned_types + float_types + bool_types:
             parm = byref(t())
             self.failUnlessEqual(ArgType, type(parm))
 
@@ -101,8 +116,11 @@
             self.assertRaises(TypeError, t, 3.14)
 
     def test_sizes(self):
-        for t in signed_types + unsigned_types + float_types:
-            size = struct.calcsize(t._type_)
+        for t in signed_types + unsigned_types + float_types + bool_types:
+            try:
+                size = struct.calcsize(t._type_)
+            except struct.error:
+                continue
             # sizeof of the type...
             self.failUnlessEqual(sizeof(t), size)
             # and sizeof of an instance
@@ -164,6 +182,18 @@
         a[0] = '?'
         self.failUnlessEqual(v.value, a[0])
 
+    # array does not support c_bool / 't'
+    # def test_bool_from_address(self):
+    #     from ctypes import c_bool
+    #     from array import array
+    #     a = array(c_bool._type_, [True])
+    #     v = t.from_address(a.buffer_info()[0])
+    #     self.failUnlessEqual(v.value, a[0])
+    #     self.failUnlessEqual(type(v) is t)
+    #     a[0] = False
+    #     self.failUnlessEqual(v.value, a[0])
+    #     self.failUnlessEqual(type(v) is t)
+
     def test_init(self):
         # c_int() can be initialized from Python's int, and c_int.
         # Not from c_long or so, which seems strange, abd should

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_python_api.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_python_api.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_python_api.py	Wed Jul 11 15:40:56 2007
@@ -10,7 +10,10 @@
 ################################################################
 
 from sys import getrefcount as grc
-
+if sys.version_info > (2, 4):
+    c_py_ssize_t = c_size_t
+else:
+    c_py_ssize_t = c_int
 
 class PythonAPITestCase(unittest.TestCase):
 
@@ -18,7 +21,7 @@
         PyString_FromStringAndSize = pythonapi.PyString_FromStringAndSize
 
         PyString_FromStringAndSize.restype = py_object
-        PyString_FromStringAndSize.argtypes = c_char_p, c_int
+        PyString_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t
 
         self.failUnlessEqual(PyString_FromStringAndSize("abcdefghi", 3), "abc")
 
@@ -66,7 +69,7 @@
 
     def test_PyOS_snprintf(self):
         PyOS_snprintf = pythonapi.PyOS_snprintf
-        PyOS_snprintf.argtypes = POINTER(c_char), c_int, c_char_p
+        PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
 
         buf = c_buffer(256)
         PyOS_snprintf(buf, sizeof(buf), "Hello from %s", "ctypes")

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_random_things.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_random_things.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_random_things.py	Wed Jul 11 15:40:56 2007
@@ -13,6 +13,10 @@
 
         def test(self):
             from _ctypes import call_function
+            windll.kernel32.LoadLibraryA.restype = c_void_p
+            windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
+            windll.kernel32.GetProcAddress.restype = c_void_p
+
             hdll = windll.kernel32.LoadLibraryA("kernel32")
             funcaddr = windll.kernel32.GetProcAddress(hdll, "GetModuleHandleA")
 

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_repr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_repr.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_repr.py	Wed Jul 11 15:40:56 2007
@@ -4,7 +4,7 @@
 subclasses = []
 for base in [c_byte, c_short, c_int, c_long, c_longlong,
         c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong,
-        c_float, c_double]:
+        c_float, c_double, c_bool]:
     class X(base):
         pass
     subclasses.append(X)

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_slicing.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_slicing.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_slicing.py	Wed Jul 11 15:40:56 2007
@@ -5,8 +5,8 @@
 
 class SlicesTestCase(unittest.TestCase):
     def test_getslice_cint(self):
-        a = (c_int * 100)(*xrange(1100, 1200))
-        b = range(1100, 1200)
+        a = (c_int * 100)(*range(1100, 1200))
+        b = list(range(1100, 1200))
         self.failUnlessEqual(a[0:2], b[0:2])
         self.failUnlessEqual(len(a), len(b))
         self.failUnlessEqual(a[5:7], b[5:7])
@@ -14,14 +14,14 @@
         self.failUnlessEqual(a[:], b[:])
 
         a[0:5] = range(5, 10)
-        self.failUnlessEqual(a[0:5], range(5, 10))
+        self.failUnlessEqual(a[0:5], list(range(5, 10)))
 
     def test_setslice_cint(self):
-        a = (c_int * 100)(*xrange(1100, 1200))
-        b = range(1100, 1200)
+        a = (c_int * 100)(*range(1100, 1200))
+        b = list(range(1100, 1200))
 
-        a[32:47] = range(32, 47)
-        self.failUnlessEqual(a[32:47], range(32, 47))
+        a[32:47] = list(range(32, 47))
+        self.failUnlessEqual(a[32:47], list(range(32, 47)))
 
         from operator import setslice
 
@@ -50,7 +50,7 @@
 
         dll.my_strdup.restype = POINTER(c_byte)
         res = dll.my_strdup(s)
-        self.failUnlessEqual(res[:len(s)], range(ord("a"), ord("z")+1))
+        self.failUnlessEqual(res[:len(s)], list(range(ord("a"), ord("z")+1)))
         dll.my_free(res)
 
     def test_char_ptr_with_free(self):
@@ -111,7 +111,8 @@
             else:
                 return
             res = dll.my_wcsdup(s)
-            self.failUnlessEqual(res[:len(s)-1], range(ord("a"), ord("z")+1))
+            self.failUnlessEqual(res[:len(s)-1],
+                                 list(range(ord("a"), ord("z")+1)))
             dll.my_free(res)
 
 ################################################################

Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_structures.py	Wed Jul 11 15:40:56 2007
@@ -294,20 +294,20 @@
         # In Python 2.5, Exception is a new-style class, and the repr changed
         if issubclass(Exception, object):
             self.failUnlessEqual(msg,
-                                 "(Phone) <type 'exceptions.TypeError'>: "
+                                 "(Phone) <type 'TypeError'>: "
                                  "expected string or Unicode object, int found")
         else:
             self.failUnlessEqual(msg,
-                                 "(Phone) exceptions.TypeError: "
+                                 "(Phone) TypeError: "
                                  "expected string or Unicode object, int found")
 
         cls, msg = self.get_except(Person, "Someone", ("a", "b", "c"))
         self.failUnlessEqual(cls, RuntimeError)
         if issubclass(Exception, object):
             self.failUnlessEqual(msg,
-                                 "(Phone) <type 'exceptions.ValueError'>: too many initializers")
+                                 "(Phone) <type 'ValueError'>: too many initializers")
         else:
-            self.failUnlessEqual(msg, "(Phone) exceptions.ValueError: too many initializers")
+            self.failUnlessEqual(msg, "(Phone) ValueError: too many initializers")
 
 
     def get_except(self, func, *args):

Modified: python/branches/p3yk-noslice/Lib/ctypes/wintypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/wintypes.py	(original)
+++ python/branches/p3yk-noslice/Lib/ctypes/wintypes.py	Wed Jul 11 15:40:56 2007
@@ -147,7 +147,7 @@
                 ("dwReserved0", DWORD),
                 ("dwReserved1", DWORD),
                 ("cFileName", c_char * MAX_PATH),
-                ("cAlternameFileName", c_char * 14)]
+                ("cAlternateFileName", c_char * 14)]
 
 class WIN32_FIND_DATAW(Structure):
     _fields_ = [("dwFileAttributes", DWORD),
@@ -159,7 +159,7 @@
                 ("dwReserved0", DWORD),
                 ("dwReserved1", DWORD),
                 ("cFileName", c_wchar * MAX_PATH),
-                ("cAlternameFileName", c_wchar * 14)]
+                ("cAlternateFileName", c_wchar * 14)]
 
 __all__ = ['ATOM', 'BOOL', 'BOOLEAN', 'BYTE', 'COLORREF', 'DOUBLE',
            'DWORD', 'FILETIME', 'HACCEL', 'HANDLE', 'HBITMAP', 'HBRUSH',

Modified: python/branches/p3yk-noslice/Lib/dbhash.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dbhash.py	(original)
+++ python/branches/p3yk-noslice/Lib/dbhash.py	Wed Jul 11 15:40:56 2007
@@ -12,5 +12,5 @@
 
 error = bsddb.error                     # Exported for anydbm
 
-def open(file, flag = 'r', mode=0666):
+def open(file, flag = 'r', mode=0o666):
     return bsddb.hashopen(file, flag, mode)

Modified: python/branches/p3yk-noslice/Lib/decimal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/decimal.py	(original)
+++ python/branches/p3yk-noslice/Lib/decimal.py	Wed Jul 11 15:40:56 2007
@@ -29,8 +29,8 @@
 
 Decimal floating point has finite precision with arbitrarily large bounds.
 
-The purpose of the module is to support arithmetic using familiar
-"schoolhouse" rules and to avoid the some of tricky representation
+The purpose of this module is to support arithmetic using familiar
+"schoolhouse" rules and to avoid some of the tricky representation
 issues associated with binary floating point.  The package is especially
 useful for financial applications or for contexts where users have
 expectations that are at odds with binary floating point (for instance,
@@ -136,7 +136,7 @@
 
 import copy as _copy
 
-#Rounding
+# Rounding
 ROUND_DOWN = 'ROUND_DOWN'
 ROUND_HALF_UP = 'ROUND_HALF_UP'
 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
@@ -145,11 +145,11 @@
 ROUND_UP = 'ROUND_UP'
 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
 
-#Rounding decision (not part of the public API)
+# Rounding decision (not part of the public API)
 NEVER_ROUND = 'NEVER_ROUND'    # Round in division (non-divmod), sqrt ONLY
 ALWAYS_ROUND = 'ALWAYS_ROUND'  # Every operation rounds at end.
 
-#Errors
+# Errors
 
 class DecimalException(ArithmeticError):
     """Base exception class.
@@ -179,9 +179,9 @@
 
     This occurs and signals clamped if the exponent of a result has been
     altered in order to fit the constraints of a specific concrete
-    representation. This may occur when the exponent of a zero result would
-    be outside the bounds of a representation, or  when a large normal
-    number would have an encoded exponent that cannot be represented. In
+    representation.  This may occur when the exponent of a zero result would
+    be outside the bounds of a representation, or when a large normal
+    number would have an encoded exponent that cannot be represented.  In
     this latter case, the exponent is reduced to fit and the corresponding
     number of zero digits are appended to the coefficient ("fold-down").
     """
@@ -194,8 +194,8 @@
 
     Something creates a signaling NaN
     -INF + INF
-     0 * (+-)INF
-     (+-)INF / (+-)INF
+    0 * (+-)INF
+    (+-)INF / (+-)INF
     x % 0
     (+-)INF % x
     x._rescale( non-integer )
@@ -207,7 +207,7 @@
     """
     def handle(self, context, *args):
         if args:
-            if args[0] == 1: #sNaN, must drop 's' but keep diagnostics
+            if args[0] == 1:  # sNaN, must drop 's' but keep diagnostics
                 return Decimal( (args[1]._sign, args[1]._int, 'n') )
         return NaN
 
@@ -216,11 +216,11 @@
 
     This occurs and signals invalid-operation if an string is being
     converted to a number and it does not conform to the numeric string
-    syntax. The result is [0,qNaN].
+    syntax.  The result is [0,qNaN].
     """
 
     def handle(self, context, *args):
-        return (0, (0,), 'n') #Passed to something which uses a tuple.
+        return (0, (0,), 'n')  # Passed to something which uses a tuple.
 
 class DivisionByZero(DecimalException, ZeroDivisionError):
     """Division by 0.
@@ -245,7 +245,7 @@
 
     This occurs and signals invalid-operation if the integer result of a
     divide-integer or remainder operation had too many digits (would be
-    longer than precision). The result is [0,qNaN].
+    longer than precision).  The result is [0,qNaN].
     """
 
     def handle(self, context, *args):
@@ -256,12 +256,12 @@
 
     This occurs and signals invalid-operation if division by zero was
     attempted (during a divide-integer, divide, or remainder operation), and
-    the dividend is also zero. The result is [0,qNaN].
+    the dividend is also zero.  The result is [0,qNaN].
     """
 
     def handle(self, context, tup=None, *args):
         if tup is not None:
-            return (NaN, NaN) #for 0 %0, 0 // 0
+            return (NaN, NaN)  # for 0 %0, 0 // 0
         return NaN
 
 class Inexact(DecimalException):
@@ -269,7 +269,7 @@
 
     This occurs and signals inexact whenever the result of an operation is
     not exact (that is, it needed to be rounded and any discarded digits
-    were non-zero), or if an overflow or underflow condition occurs. The
+    were non-zero), or if an overflow or underflow condition occurs.  The
     result in all cases is unchanged.
 
     The inexact signal may be tested (or trapped) to determine if a given
@@ -281,11 +281,11 @@
     """Invalid context.  Unknown rounding, for example.
 
     This occurs and signals invalid-operation if an invalid context was
-    detected during an operation. This can occur if contexts are not checked
+    detected during an operation.  This can occur if contexts are not checked
     on creation and either the precision exceeds the capability of the
     underlying concrete representation or an unknown or unsupported rounding
-    was specified. These aspects of the context need only be checked when
-    the values are required to be used. The result is [0,qNaN].
+    was specified.  These aspects of the context need only be checked when
+    the values are required to be used.  The result is [0,qNaN].
     """
 
     def handle(self, context, *args):
@@ -296,7 +296,7 @@
 
     This occurs and signals rounded whenever the result of an operation is
     rounded (that is, some zero or non-zero digits were discarded from the
-    coefficient), or if an overflow or underflow condition occurs. The
+    coefficient), or if an overflow or underflow condition occurs.  The
     result in all cases is unchanged.
 
     The rounded signal may be tested (or trapped) to determine if a given
@@ -309,7 +309,7 @@
 
     This occurs and signals subnormal whenever the result of a conversion or
     operation is subnormal (that is, its adjusted exponent is less than
-    Emin, before any rounding). The result in all cases is unchanged.
+    Emin, before any rounding).  The result in all cases is unchanged.
 
     The subnormal signal may be tested (or trapped) to determine if a given
     or operation (or sequence of operations) yielded a subnormal result.
@@ -328,13 +328,13 @@
 
     For round-half-up and round-half-even (and for round-half-down and
     round-up, if implemented), the result of the operation is [sign,inf],
-    where sign is the sign of the intermediate result. For round-down, the
+    where sign is the sign of the intermediate result.  For round-down, the
     result is the largest finite number that can be represented in the
-    current precision, with the sign of the intermediate result. For
+    current precision, with the sign of the intermediate result.  For
     round-ceiling, the result is the same as for round-down if the sign of
-    the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
+    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
     the result is the same as for round-down if the sign of the intermediate
-    result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
+    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
     will also be raised.
    """
 
@@ -360,10 +360,10 @@
     This occurs and signals underflow if a result is inexact and the
     adjusted exponent of the result would be smaller (more negative) than
     the smallest value that can be handled by the implementation (the value
-    Emin). That is, the result is both inexact and subnormal.
+    Emin).  That is, the result is both inexact and subnormal.
 
     The result after an underflow will be a subnormal number rounded, if
-    necessary, so that its exponent is not less than Etiny. This may result
+    necessary, so that its exponent is not less than Etiny.  This may result
     in 0 with the sign of the intermediate result and an exponent of Etiny.
 
     In all cases, Inexact, Rounded, and Subnormal will also be raised.
@@ -379,7 +379,7 @@
                   DivisionUndefined:InvalidOperation,
                   InvalidContext:InvalidOperation}
 
-##### Context Functions #######################################
+##### Context Functions ##################################################
 
 # The getcontext() and setcontext() function manage access to a thread-local
 # current context.  Py2.4 offers direct support for thread locals.  If that
@@ -392,7 +392,7 @@
 except ImportError:
     # Python was compiled without threads; create a mock object instead
     import sys
-    class MockThreading:
+    class MockThreading(object):
         def local(self, sys=sys):
             return sys.modules[__name__]
     threading = MockThreading()
@@ -403,8 +403,8 @@
 
 except AttributeError:
 
-    #To fix reloading, force it to create a new context
-    #Old contexts have different exceptions in their dicts, making problems.
+    # To fix reloading, force it to create a new context
+    # Old contexts have different exceptions in their dicts, making problems.
     if hasattr(threading.currentThread(), '__decimal_context__'):
         del threading.currentThread().__decimal_context__
 
@@ -469,14 +469,14 @@
                  ctx.prec += 2
                  # Rest of sin calculation algorithm
                  # uses a precision 2 greater than normal
-             return +s # Convert result to normal precision
+             return +s  # Convert result to normal precision
 
          def sin(x):
              with localcontext(ExtendedContext):
                  # Rest of sin calculation algorithm
                  # uses the Extended Context from the
                  # General Decimal Arithmetic Specification
-             return +s # Convert result to normal context
+             return +s  # Convert result to normal context
 
     """
     # The string below can't be included in the docstring until Python 2.6
@@ -489,11 +489,11 @@
     ...     ctx = getcontext()
     ...     ctx.prec += 2
     ...     print(ctx.prec)
-    ... 
+    ...
     30
     >>> with localcontext(ExtendedContext):
     ...     print(getcontext().prec)
-    ... 
+    ...
     9
     >>> print(getcontext().prec)
     28
@@ -502,7 +502,7 @@
     return _ContextManager(ctx)
 
 
-##### Decimal class ###########################################
+##### Decimal class #######################################################
 
 class Decimal(object):
     """Floating point class for decimal arithmetic."""
@@ -518,7 +518,7 @@
 
         >>> Decimal('3.14')              # string input
         Decimal("3.14")
-        >>> Decimal((0, (3, 1, 4), -2))  # tuple input (sign, digit_tuple, exponent)
+        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
         Decimal("3.14")
         >>> Decimal(314)                 # int or long
         Decimal("314")
@@ -557,13 +557,13 @@
         # tuple/list conversion (possibly from as_tuple())
         if isinstance(value, (list,tuple)):
             if len(value) != 3:
-                raise ValueError, 'Invalid arguments'
+                raise ValueError('Invalid arguments')
             if value[0] not in (0,1):
-                raise ValueError, 'Invalid sign'
+                raise ValueError('Invalid sign')
             for digit in value[1]:
                 if not isinstance(digit, (int,int)) or digit < 0:
-                    raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
-
+                    raise ValueError("The second value in the tuple must be"
+                                "composed of non negative integer elements.")
             self._sign = value[0]
             self._int  = tuple(value[1])
             if value[2] in ('F','n','N'):
@@ -596,22 +596,23 @@
             if _isnan(value):
                 sig, sign, diag = _isnan(value)
                 self._is_special = True
-                if len(diag) > context.prec: #Diagnostic info too long
+                if len(diag) > context.prec:  # Diagnostic info too long
                     self._sign, self._int, self._exp = \
                                 context._raise_error(ConversionSyntax)
                     return self
                 if sig == 1:
-                    self._exp = 'n' #qNaN
-                else: #sig == 2
-                    self._exp = 'N' #sNaN
+                    self._exp = 'n'  # qNaN
+                else:  # sig == 2
+                    self._exp = 'N'  # sNaN
                 self._sign = sign
-                self._int = tuple(map(int, diag)) #Diagnostic info
+                self._int = tuple(map(int, diag))  # Diagnostic info
                 return self
             try:
                 self._sign, self._int, self._exp = _string2exact(value)
             except ValueError:
                 self._is_special = True
-                self._sign, self._int, self._exp = context._raise_error(ConversionSyntax)
+                self._sign, self._int, self._exp = \
+                                        context._raise_error(ConversionSyntax)
             return self
 
         raise TypeError("Cannot convert %r to Decimal" % value)
@@ -694,15 +695,15 @@
         if self._is_special or other._is_special:
             ans = self._check_nans(other, context)
             if ans:
-                return 1 # Comparison involving NaN's always reports self > other
+                return 1  # Comparison involving NaN's always reports self > other
 
             # INF = INF
             return cmp(self._isinfinity(), other._isinfinity())
 
         if not self and not other:
-            return 0 #If both 0, sign comparison isn't certain.
+            return 0  # If both 0, sign comparison isn't certain.
 
-        #If different signs, neg one is less
+        # If different signs, neg one is less
         if other._sign < self._sign:
             return -1
         if self._sign < other._sign:
@@ -713,7 +714,7 @@
         if self_adjusted == other_adjusted and \
            self._int + (0,)*(self._exp - other._exp) == \
            other._int + (0,)*(other._exp - self._exp):
-            return 0 #equal, except in precision. ([0]*(-x) = [])
+            return 0  # equal, except in precision. ([0]*(-x) = [])
         elif self_adjusted > other_adjusted and self._int[0] != 0:
             return (-1)**self._sign
         elif self_adjusted < other_adjusted and other._int[0] != 0:
@@ -724,7 +725,7 @@
             context = getcontext()
 
         context = context._shallow_copy()
-        rounding = context._set_rounding(ROUND_UP) #round away from 0
+        rounding = context._set_rounding(ROUND_UP)  # round away from 0
 
         flags = context._ignore_all_flags()
         res = self.__sub__(other, context=context)
@@ -782,7 +783,7 @@
         if other is NotImplemented:
             return other
 
-        #compare(NaN, NaN) = NaN
+        # Compare(NaN, NaN) = NaN
         if (self._is_special or other and other._is_special):
             ans = self._check_nans(other, context)
             if ans:
@@ -840,14 +841,14 @@
         if context is None:
             context = getcontext()
 
-        tmp = map(str, self._int)
+        tmp = list(map(str, self._int))
         numdigits = len(self._int)
         leftdigits = self._exp + numdigits
-        if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
-            if self._exp < 0 and self._exp >= -6: #short, no need for e/E
+        if eng and not self:  # self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
+            if self._exp < 0 and self._exp >= -6:  # short, no need for e/E
                 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
                 return s
-            #exp is closest mult. of 3 >= self._exp
+            # exp is closest mult. of 3 >= self._exp
             exp = ((self._exp - 1)// 3 + 1) * 3
             if exp != self._exp:
                 s = '0.'+'0'*(exp - self._exp)
@@ -859,7 +860,7 @@
                 else:
                     s += 'e'
                 if exp > 0:
-                    s += '+' #0.0e+3, not 0.0e3
+                    s += '+'  # 0.0e+3, not 0.0e3
                 s += str(exp)
             s = '-'*self._sign + s
             return s
@@ -999,19 +1000,19 @@
                 return ans
 
             if self._isinfinity():
-                #If both INF, same sign => same as both, opposite => error.
+                # If both INF, same sign => same as both, opposite => error.
                 if self._sign != other._sign and other._isinfinity():
                     return context._raise_error(InvalidOperation, '-INF + INF')
                 return Decimal(self)
             if other._isinfinity():
-                return Decimal(other)  #Can't both be infinity here
+                return Decimal(other)  # Can't both be infinity here
 
         shouldround = context._rounding_decision == ALWAYS_ROUND
 
         exp = min(self._exp, other._exp)
         negativezero = 0
         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
-            #If the answer is 0, the sign should be negative, in this case.
+            # If the answer is 0, the sign should be negative, in this case.
             negativezero = 1
 
         if not self and not other:
@@ -1046,19 +1047,19 @@
                 return Decimal((negativezero, (0,), exp))
             if op1.int < op2.int:
                 op1, op2 = op2, op1
-                #OK, now abs(op1) > abs(op2)
+                # OK, now abs(op1) > abs(op2)
             if op1.sign == 1:
                 result.sign = 1
                 op1.sign, op2.sign = op2.sign, op1.sign
             else:
                 result.sign = 0
-                #So we know the sign, and op1 > 0.
+                # So we know the sign, and op1 > 0.
         elif op1.sign == 1:
             result.sign = 1
             op1.sign, op2.sign = (0, 0)
         else:
             result.sign = 0
-        #Now, op1 > abs(op2) > 0
+        # Now, op1 > abs(op2) > 0
 
         if op2.sign == 0:
             result.int = op1.int + op2.int
@@ -1116,7 +1117,8 @@
             if ans:
                 return ans
 
-            return Decimal(self) # Must be infinite, and incrementing makes no difference
+            # Must be infinite, and incrementing makes no difference
+            return Decimal(self)
 
         L = list(self._int)
         L[-1] += 1
@@ -1172,7 +1174,7 @@
         if not self or not other:
             ans = Decimal((resultsign, (0,), resultexp))
             if shouldround:
-                #Fixing in case the exponent is out of bounds
+                # Fixing in case the exponent is out of bounds
                 ans = ans._fix(context)
             return ans
 
@@ -1191,7 +1193,9 @@
         op1 = _WorkRep(self)
         op2 = _WorkRep(other)
 
-        ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
+        ans = Decimal((resultsign,
+                       tuple(map(int, str(op1.int * op2.int))),
+                       resultexp))
         if shouldround:
             ans = ans._fix(context)
 
@@ -1283,12 +1287,11 @@
                                            sign, 1)
             return context._raise_error(DivisionByZero, 'x / 0', sign)
 
-        #OK, so neither = 0, INF or NaN
-
+        # OK, so neither = 0, INF or NaN
         shouldround = context._rounding_decision == ALWAYS_ROUND
 
-        #If we're dividing into ints, and self < other, stop.
-        #self.__abs__(0) does not round.
+        # If we're dividing into ints, and self < other, stop.
+        # self.__abs__(0) does not round.
         if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
 
             if divmod == 1 or divmod == 3:
@@ -1300,7 +1303,7 @@
                         ans2)
 
             elif divmod == 2:
-                #Don't round the mod part, if we don't need it.
+                # Don't round the mod part, if we don't need it.
                 return (Decimal( (sign, (0,), 0) ), Decimal(self))
 
         op1 = _WorkRep(self)
@@ -1349,7 +1352,7 @@
             op1.exp -= 1
 
             if res.exp == 0 and divmod and op2.int > op1.int:
-                #Solves an error in precision.  Same as a previous block.
+                # Solves an error in precision.  Same as a previous block.
 
                 if res.int >= prec_limit and shouldround:
                     return context._raise_error(DivisionImpossible)
@@ -1434,7 +1437,7 @@
         # ignored in the calling function.
         context = context._shallow_copy()
         flags = context._ignore_flags(Rounded, Inexact)
-        #keep DivisionImpossible flags
+        # Keep DivisionImpossible flags
         (side, r) = self.__divmod__(other, context=context)
 
         if r._isnan():
@@ -1457,7 +1460,7 @@
 
         if r < comparison:
             r._sign, comparison._sign = s1, s2
-            #Get flags now
+            # Get flags now
             self.__divmod__(other, context=context)
             return r._fix(context)
         r._sign, comparison._sign = s1, s2
@@ -1479,7 +1482,8 @@
         if r > comparison or decrease and r == comparison:
             r._sign, comparison._sign = s1, s2
             context.prec += 1
-            if len(side.__add__(Decimal(1), context=context)._int) >= context.prec:
+            numbsquant = len(side.__add__(Decimal(1), context=context)._int)
+            if numbsquant >= context.prec:
                 context.prec -= 1
                 return context._raise_error(DivisionImpossible)[1]
             context.prec -= 1
@@ -1514,7 +1518,7 @@
                 context = getcontext()
                 return context._raise_error(InvalidContext)
             elif self._isinfinity():
-                raise OverflowError, "Cannot convert infinity to long"
+                raise OverflowError("Cannot convert infinity to long")
         if self._exp >= 0:
             s = ''.join(map(str, self._int)) + '0'*self._exp
         else:
@@ -1568,13 +1572,13 @@
                     context._raise_error(Clamped)
                     return ans
                 ans = ans._rescale(Etiny, context=context)
-                #It isn't zero, and exp < Emin => subnormal
+                # It isn't zero, and exp < Emin => subnormal
                 context._raise_error(Subnormal)
                 if context.flags[Inexact]:
                     context._raise_error(Underflow)
             else:
                 if ans:
-                    #Only raise subnormal if non-zero.
+                    # Only raise subnormal if non-zero.
                     context._raise_error(Subnormal)
         else:
             Etop = context.Etop()
@@ -1591,7 +1595,8 @@
                         return ans
                     context._raise_error(Inexact)
                     context._raise_error(Rounded)
-                    return context._raise_error(Overflow, 'above Emax', ans._sign)
+                    c = context._raise_error(Overflow, 'above Emax', ans._sign)
+                    return c
         return ans
 
     def _round(self, prec=None, rounding=None, context=None):
@@ -1651,18 +1656,18 @@
             ans =  Decimal( (temp._sign, tmp, temp._exp - expdiff))
             return ans
 
-        #OK, but maybe all the lost digits are 0.
+        # OK, but maybe all the lost digits are 0.
         lostdigits = self._int[expdiff:]
         if lostdigits == (0,) * len(lostdigits):
             ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
-            #Rounded, but not Inexact
+            # Rounded, but not Inexact
             context._raise_error(Rounded)
             return ans
 
         # Okay, let's round and lose data
 
         this_function = getattr(temp, self._pick_rounding_function[rounding])
-        #Now we've got the rounding function
+        # Now we've got the rounding function
 
         if prec != context.prec:
             context = context._shallow_copy()
@@ -1758,7 +1763,7 @@
             context = getcontext()
 
         if self._is_special or n._is_special or n.adjusted() > 8:
-            #Because the spot << doesn't work with really big exponents
+            # Because the spot << doesn't work with really big exponents
             if n._isinfinity() or n.adjusted() > 8:
                 return context._raise_error(InvalidOperation, 'x ** INF')
 
@@ -1788,9 +1793,10 @@
                 return Infsign[sign]
             return Decimal( (sign, (0,), 0) )
 
-        #with ludicrously large exponent, just raise an overflow and return inf.
-        if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \
-           and self:
+        # With ludicrously large exponent, just raise an overflow
+        # and return inf.
+        if not modulo and n > 0 and \
+           (self._exp + len(self._int) - 1) * n > context.Emax and self:
 
             tmp = Decimal('inf')
             tmp._sign = sign
@@ -1810,7 +1816,7 @@
         context = context._shallow_copy()
         context.prec = firstprec + elength + 1
         if n < 0:
-            #n is a long now, not Decimal instance
+            # n is a long now, not Decimal instance
             n = -n
             mul = Decimal(1).__truediv__(mul, context=context)
 
@@ -1819,7 +1825,7 @@
             spot <<= 1
 
         spot >>= 1
-        #Spot is the highest power of 2 less than n
+        # spot is the highest power of 2 less than n
         while spot:
             val = val.__mul__(val, context=context)
             if val._isinfinity():
@@ -1877,7 +1883,7 @@
 
             if exp._isinfinity() or self._isinfinity():
                 if exp._isinfinity() and self._isinfinity():
-                    return self  #if both are inf, it is OK
+                    return self  # if both are inf, it is OK
                 if context is None:
                     context = getcontext()
                 return context._raise_error(InvalidOperation,
@@ -1982,13 +1988,13 @@
                 return Decimal(self)
 
         if not self:
-            #exponent = self._exp / 2, using round_down.
-            #if self._exp < 0:
+            # exponent = self._exp / 2, using round_down.
+            # if self._exp < 0:
             #    exp = (self._exp+1) // 2
-            #else:
+            # else:
             exp = (self._exp) // 2
             if self._sign == 1:
-                #sqrt(-0) = -0
+                # sqrt(-0) = -0
                 return Decimal( (1, (0,), exp))
             else:
                 return Decimal( (0, (0,), exp))
@@ -2023,8 +2029,7 @@
                                           context=context), context=context)
             ans._exp -= 1 + tmp.adjusted()  // 2
 
-        #ans is now a linear approximation.
-
+        # ans is now a linear approximation.
         Emax, Emin = context.Emax, context.Emin
         context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
 
@@ -2039,12 +2044,12 @@
             if context.prec == maxp:
                 break
 
-        #round to the answer's precision-- the only error can be 1 ulp.
+        # Round to the answer's precision-- the only error can be 1 ulp.
         context.prec = firstprec
         prevexp = ans.adjusted()
         ans = ans._round(context=context)
 
-        #Now, check if the other last digits are better.
+        # Now, check if the other last digits are better.
         context.prec = firstprec + 1
         # In case we rounded up another digit and we should actually go lower.
         if prevexp != ans.adjusted():
@@ -2076,10 +2081,10 @@
             context._raise_error(Rounded)
             context._raise_error(Inexact)
         else:
-            #Exact answer, so let's set the exponent right.
-            #if self._exp < 0:
+            # Exact answer, so let's set the exponent right.
+            # if self._exp < 0:
             #    exp = (self._exp +1)// 2
-            #else:
+            # else:
             exp = self._exp // 2
             context.prec += ans._exp - exp
             ans = ans._rescale(exp, context=context)
@@ -2100,7 +2105,7 @@
             return other
 
         if self._is_special or other._is_special:
-            # if one operand is a quiet NaN and the other is number, then the
+            # If one operand is a quiet NaN and the other is number, then the
             # number is always returned
             sn = self._isnan()
             on = other._isnan()
@@ -2114,13 +2119,13 @@
         ans = self
         c = self.__cmp__(other)
         if c == 0:
-            # if both operands are finite and equal in numerical value
+            # If both operands are finite and equal in numerical value
             # then an ordering is applied:
             #
-            # if the signs differ then max returns the operand with the
+            # If the signs differ then max returns the operand with the
             # positive sign and min returns the operand with the negative sign
             #
-            # if the signs are the same then the exponent is used to select
+            # If the signs are the same then the exponent is used to select
             # the result.
             if self._sign != other._sign:
                 if self._sign:
@@ -2141,7 +2146,7 @@
     def min(self, other, context=None):
         """Returns the smaller value.
 
-        like min(self, other) except if one is not a number, returns
+        Like min(self, other) except if one is not a number, returns
         NaN (and signals if one is sNaN).  Also rounds.
         """
         other = _convert_other(other)
@@ -2149,7 +2154,7 @@
             return other
 
         if self._is_special or other._is_special:
-            # if one operand is a quiet NaN and the other is number, then the
+            # If one operand is a quiet NaN and the other is number, then the
             # number is always returned
             sn = self._isnan()
             on = other._isnan()
@@ -2163,13 +2168,13 @@
         ans = self
         c = self.__cmp__(other)
         if c == 0:
-            # if both operands are finite and equal in numerical value
+            # If both operands are finite and equal in numerical value
             # then an ordering is applied:
             #
-            # if the signs differ then max returns the operand with the
+            # If the signs differ then max returns the operand with the
             # positive sign and min returns the operand with the negative sign
             #
-            # if the signs are the same then the exponent is used to select
+            # If the signs are the same then the exponent is used to select
             # the result.
             if self._sign != other._sign:
                 if other._sign:
@@ -2204,11 +2209,11 @@
         """Return the adjusted exponent of self"""
         try:
             return self._exp + len(self._int) - 1
-        #If NaN or Infinity, self._exp is string
+        # If NaN or Infinity, self._exp is string
         except TypeError:
             return 0
 
-    # support for pickling, copy, and deepcopy
+    # Support for pickling, copy, and deepcopy
     def __reduce__(self):
         return (self.__class__, (str(self),))
 
@@ -2222,13 +2227,14 @@
             return self     # My components are also immutable
         return self.__class__(str(self))
 
-##### Context class ###########################################
+##### Context class #######################################################
 
 
 # get rounding method function:
-rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')]
+rounding_functions = [name for name in Decimal.__dict__.keys()
+                                    if name.startswith('_round_')]
 for name in rounding_functions:
-    #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
+    # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
     globalname = name[1:].upper()
     val = globals()[globalname]
     Decimal._pick_rounding_function[val] = name
@@ -2255,7 +2261,7 @@
 
     Contains:
     prec - precision (for use in rounding, division, square roots..)
-    rounding - rounding type. (how you round)
+    rounding - rounding type (how you round)
     _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
     traps - If traps[exception] = 1, then the exception is
                     raised when it is caused.  Otherwise, a value is
@@ -2282,10 +2288,8 @@
             _ignored_flags = []
         if not isinstance(flags, dict):
             flags = dict([(s,s in flags) for s in _signals])
-            del s
         if traps is not None and not isinstance(traps, dict):
             traps = dict([(s,s in traps) for s in _signals])
-            del s
         for name, val in locals().items():
             if val is None:
                 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
@@ -2296,9 +2300,13 @@
     def __repr__(self):
         """Show the current context."""
         s = []
-        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
-        s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']')
-        s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
+        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
+                 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
+                 % vars(self))
+        names = [f.__name__ for f, v in self.flags.items() if v]
+        s.append('flags=[' + ', '.join(names) + ']')
+        names = [t.__name__ for t, v in self.traps.items() if v]
+        s.append('traps=[' + ', '.join(names) + ']')
         return ', '.join(s) + ')'
 
     def clear_flags(self):
@@ -2315,9 +2323,9 @@
 
     def copy(self):
         """Returns a deep copy from self."""
-        nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(),
-                         self._rounding_decision, self.Emin, self.Emax,
-                         self.capitals, self._clamp, self._ignored_flags)
+        nc = Context(self.prec, self.rounding, self.traps.copy(),
+                self.flags.copy(), self._rounding_decision, self.Emin,
+                self.Emax, self.capitals, self._clamp, self._ignored_flags)
         return nc
     __copy__ = copy
 
@@ -2331,16 +2339,16 @@
         """
         error = _condition_map.get(condition, condition)
         if error in self._ignored_flags:
-            #Don't touch the flag
+            # Don't touch the flag
             return error().handle(self, *args)
 
         self.flags[error] += 1
         if not self.traps[error]:
-            #The errors define how to handle themselves.
+            # The errors define how to handle themselves.
             return condition().handle(self, *args)
 
         # Errors should only be risked on copies of the context
-        #self._ignored_flags = []
+        # self._ignored_flags = []
         raise error, explanation
 
     def _ignore_all_flags(self):
@@ -2364,7 +2372,7 @@
     def __hash__(self):
         """A Context cannot be hashed."""
         # We inherit object.__hash__, so we must deny this explicitly
-        raise TypeError, "Cannot hash a Context."
+        raise TypeError("Cannot hash a Context.")
 
     def Etiny(self):
         """Returns Etiny (= Emin - prec + 1)"""
@@ -2419,12 +2427,12 @@
         d = Decimal(num, context=self)
         return d._fix(self)
 
-    #Methods
+    # Methods
     def abs(self, a):
         """Returns the absolute value of the operand.
 
         If the operand is negative, the result is the same as using the minus
-        operation on the operand. Otherwise, the result is the same as using
+        operation on the operand.  Otherwise, the result is the same as using
         the plus operation on the operand.
 
         >>> ExtendedContext.abs(Decimal('2.1'))
@@ -2526,8 +2534,8 @@
 
         If either operand is a NaN then the general rules apply.
         Otherwise, the operands are compared as as though by the compare
-        operation. If they are numerically equal then the left-hand operand
-        is chosen as the result. Otherwise the maximum (closer to positive
+        operation.  If they are numerically equal then the left-hand operand
+        is chosen as the result.  Otherwise the maximum (closer to positive
         infinity) of the two operands is chosen as the result.
 
         >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
@@ -2546,8 +2554,8 @@
 
         If either operand is a NaN then the general rules apply.
         Otherwise, the operands are compared as as though by the compare
-        operation. If they are numerically equal then the left-hand operand
-        is chosen as the result. Otherwise the minimum (closer to negative
+        operation.  If they are numerically equal then the left-hand operand
+        is chosen as the result.  Otherwise the minimum (closer to negative
         infinity) of the two operands is chosen as the result.
 
         >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
@@ -2636,14 +2644,14 @@
 
         The right-hand operand must be a whole number whose integer part (after
         any exponent has been applied) has no more than 9 digits and whose
-        fractional part (if any) is all zeros before any rounding. The operand
+        fractional part (if any) is all zeros before any rounding.  The operand
         may be positive, negative, or zero; if negative, the absolute value of
         the power is used, and the left-hand operand is inverted (divided into
         1) before use.
 
         If the increased precision needed for the intermediate calculations
-        exceeds the capabilities of the implementation then an Invalid operation
-        condition is raised.
+        exceeds the capabilities of the implementation then an Invalid
+        operation condition is raised.
 
         If, when raising to a negative power, an underflow occurs during the
         division into 1, the operation is not halted at that point but
@@ -2681,18 +2689,18 @@
         return a.__pow__(b, modulo, context=self)
 
     def quantize(self, a, b):
-        """Returns a value equal to 'a' (rounded) and having the exponent of 'b'.
+        """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
 
         The coefficient of the result is derived from that of the left-hand
-        operand. It may be rounded using the current rounding setting (if the
+        operand.  It may be rounded using the current rounding setting (if the
         exponent is being increased), multiplied by a positive power of ten (if
         the exponent is being decreased), or is unchanged (if the exponent is
         already equal to that of the right-hand operand).
 
         Unlike other operations, if the length of the coefficient after the
         quantize operation would be greater than precision then an Invalid
-        operation condition is raised. This guarantees that, unless there is an
-        error condition, the exponent of the result of a quantize is always
+        operation condition is raised.  This guarantees that, unless there is
+        an error condition, the exponent of the result of a quantize is always
         equal to that of the right-hand operand.
 
         Also unlike other operations, quantize will never raise Underflow, even
@@ -2735,9 +2743,9 @@
         """Returns the remainder from integer division.
 
         The result is the residue of the dividend after the operation of
-        calculating integer division as described for divide-integer, rounded to
-        precision digits if necessary. The sign of the result, if non-zero, is
-        the same as that of the original dividend.
+        calculating integer division as described for divide-integer, rounded
+        to precision digits if necessary.  The sign of the result, if
+        non-zero, is the same as that of the original dividend.
 
         This operation will fail under the same conditions as integer division
         (that is, if integer division on the same two operands would fail, the
@@ -2761,7 +2769,7 @@
     def remainder_near(self, a, b):
         """Returns to be "a - b * n", where n is the integer nearest the exact
         value of "x / b" (if two integers are equally near then the even one
-        is chosen). If the result is equal to 0 then its sign will be the
+        is chosen).  If the result is equal to 0 then its sign will be the
         sign of a.
 
         This operation will fail under the same conditions as integer division
@@ -2803,7 +2811,7 @@
         return a.same_quantum(b)
 
     def sqrt(self, a):
-        """Returns the square root of a non-negative number to context precision.
+        """Square root of a non-negative number to context precision.
 
         If the result must be inexact, it is rounded using the round-half-even
         algorithm.
@@ -2864,7 +2872,7 @@
         as using the quantize() operation using the given operand as the
         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
         of the operand as the precision setting, except that no flags will
-        be set. The rounding mode is taken from the context.
+        be set.  The rounding mode is taken from the context.
 
         >>> ExtendedContext.to_integral(Decimal('2.1'))
         Decimal("2")
@@ -2939,8 +2947,9 @@
         other_len = len(str(other.int))
         if numdigits > (other_len + prec + 1 - tmp_len):
             # If the difference in adjusted exps is > prec+1, we know
-            # other is insignificant, so might as well put a 1 after the precision.
-            # (since this is only for addition.)  Also stops use of massive longs.
+            # other is insignificant, so might as well put a 1 after the
+            # precision (since this is only for addition).  Also stops
+            # use of massive longs.
 
             extend = prec + 2 - tmp_len
             if extend <= 0:
@@ -2963,13 +2972,13 @@
     Used on _WorkRep instances during division.
     """
     adjust = 0
-    #If op1 is smaller, make it larger
+    # If op1 is smaller, make it larger
     while op2.int > op1.int:
         op1.int *= 10
         op1.exp -= 1
         adjust += 1
 
-    #If op2 is too small, make it larger
+    # If op2 is too small, make it larger
     while op1.int >= (10 * op2.int):
         op2.int *= 10
         op2.exp -= 1
@@ -2977,7 +2986,7 @@
 
     return op1, op2, adjust
 
-##### Helper Functions ########################################
+##### Helper Functions ####################################################
 
 def _convert_other(other):
     """Convert other to Decimal.
@@ -3018,16 +3027,16 @@
     if not num:
         return 0
 
-    #get the sign, get rid of trailing [+-]
+    # Get the sign, get rid of trailing [+-]
     sign = 0
     if num[0] == '+':
         num = num[1:]
-    elif num[0] == '-':  #elif avoids '+-nan'
+    elif num[0] == '-':  # elif avoids '+-nan'
         num = num[1:]
         sign = 1
 
     if num.startswith('nan'):
-        if len(num) > 3 and not num[3:].isdigit(): #diagnostic info
+        if len(num) > 3 and not num[3:].isdigit():  # diagnostic info
             return 0
         return (1, sign, num[3:].lstrip('0'))
     if num.startswith('snan'):
@@ -3037,7 +3046,7 @@
     return 0
 
 
-##### Setup Specific Contexts ################################
+##### Setup Specific Contexts ############################################
 
 # The default context prototype used by Context()
 # Is mutable, so that new contexts can have different default values
@@ -3070,19 +3079,19 @@
 )
 
 
-##### Useful Constants (internal use only) ####################
+##### Useful Constants (internal use only) ################################
 
-#Reusable defaults
+# Reusable defaults
 Inf = Decimal('Inf')
 negInf = Decimal('-Inf')
 
-#Infsign[sign] is infinity w/ that sign
+# Infsign[sign] is infinity w/ that sign
 Infsign = (Inf, negInf)
 
 NaN = Decimal('NaN')
 
 
-##### crud for parsing strings #################################
+##### crud for parsing strings #############################################
 import re
 
 # There's an optional sign at the start, and an optional exponent
@@ -3102,13 +3111,15 @@
     ([eE](?P<exp>[-+]? \d+))?
 #    \s*
     $
-""", re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces.
+""", re.VERBOSE).match  # Uncomment the \s* to allow leading or trailing spaces.
 
 del re
 
-# return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly
-
 def _string2exact(s):
+    """Return sign, n, p s.t.
+
+    Float string value == -1**sign * n * 10**p exactly
+    """
     m = _parser(s)
     if m is None:
         raise ValueError("invalid literal for Decimal: %r" % s)
@@ -3136,7 +3147,7 @@
     exp -= len(fracpart)
 
     mantissa = intpart + fracpart
-    tmp = map(int, mantissa)
+    tmp = list(map(int, mantissa))
     backup = tmp
     while tmp and tmp[0] == 0:
         del tmp[0]

Modified: python/branches/p3yk-noslice/Lib/difflib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/difflib.py	(original)
+++ python/branches/p3yk-noslice/Lib/difflib.py	Wed Jul 11 15:40:56 2007
@@ -407,7 +407,7 @@
         # junk-free match ending with a[i-1] and b[j]
         j2len = {}
         nothing = []
-        for i in xrange(alo, ahi):
+        for i in range(alo, ahi):
             # look at all instances of a[i] in b; note that because
             # b2j has no junk keys, the loop is skipped if a[i] is junk
             j2lenget = j2len.get
@@ -587,7 +587,7 @@
         Each group is in the same format as returned by get_opcodes().
 
         >>> from pprint import pprint
-        >>> a = map(str, range(1,40))
+        >>> a = list(map(str, range(1,40)))
         >>> b = a[:]
         >>> b[8:8] = ['i']     # Make an insertion
         >>> b[20] += 'x'       # Make a replacement
@@ -719,7 +719,7 @@
     >>> import keyword as _keyword
     >>> get_close_matches("wheel", _keyword.kwlist)
     ['while']
-    >>> get_close_matches("apple", _keyword.kwlist)
+    >>> get_close_matches("Apple", _keyword.kwlist)
     []
     >>> get_close_matches("accept", _keyword.kwlist)
     ['except']
@@ -921,7 +921,7 @@
 
     def _dump(self, tag, x, lo, hi):
         """Generate comparison results for a same-tagged range."""
-        for i in xrange(lo, hi):
+        for i in range(lo, hi):
             yield '%s %s' % (tag, x[i])
 
     def _plain_replace(self, a, alo, ahi, b, blo, bhi):
@@ -967,10 +967,10 @@
         # search for the pair that matches best without being identical
         # (identical lines must be junk lines, & we don't want to synch up
         # on junk -- unless we have to)
-        for j in xrange(blo, bhi):
+        for j in range(blo, bhi):
             bj = b[j]
             cruncher.set_seq2(bj)
-            for i in xrange(alo, ahi):
+            for i in range(alo, ahi):
                 ai = a[i]
                 if ai == bj:
                     if eqi is None:
@@ -1430,7 +1430,7 @@
             # so we can do some very readable comparisons.
             while len(lines) < 4:
                 try:
-                    lines.append(diff_lines_iterator.next())
+                    lines.append(next(diff_lines_iterator))
                 except StopIteration:
                     lines.append('X')
             s = ''.join([line[0] for line in lines])
@@ -1517,7 +1517,7 @@
         while True:
             # Collecting lines of text until we have a from/to pair
             while (len(fromlines)==0 or len(tolines)==0):
-                from_line, to_line, found_diff =line_iterator.next()
+                from_line, to_line, found_diff = next(line_iterator)
                 if from_line is not None:
                     fromlines.append((from_line,found_diff))
                 if to_line is not None:
@@ -1532,7 +1532,7 @@
     line_pair_iterator = _line_pair_iterator()
     if context is None:
         while True:
-            yield line_pair_iterator.next()
+            yield next(line_pair_iterator)
     # Handle case where user wants context differencing.  We must do some
     # storage of lines until we know for sure that they are to be yielded.
     else:
@@ -1545,7 +1545,7 @@
             index, contextLines = 0, [None]*(context)
             found_diff = False
             while(found_diff is False):
-                from_line, to_line, found_diff = line_pair_iterator.next()
+                from_line, to_line, found_diff = next(line_pair_iterator)
                 i = index % context
                 contextLines[i] = (from_line, to_line, found_diff)
                 index += 1
@@ -1565,7 +1565,7 @@
             # Now yield the context lines after the change
             lines_to_write = context-1
             while(lines_to_write):
-                from_line, to_line, found_diff = line_pair_iterator.next()
+                from_line, to_line, found_diff = next(line_pair_iterator)
                 # If another change within the context, extend the context
                 if found_diff:
                     lines_to_write = context-1
@@ -1946,8 +1946,7 @@
         fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
             fromlist,tolist,flaglist,context,numlines)
 
-        import cStringIO
-        s = cStringIO.StringIO()
+        s = []
         fmt = '            <tr><td class="diff_next"%s>%s</td>%s' + \
               '<td class="diff_next">%s</td>%s</tr>\n'
         for i in range(len(flaglist)):
@@ -1955,9 +1954,9 @@
                 # mdiff yields None on separator lines skip the bogus ones
                 # generated for the first line
                 if i > 0:
-                    s.write('        </tbody>        \n        <tbody>\n')
+                    s.append('        </tbody>        \n        <tbody>\n')
             else:
-                s.write( fmt % (next_id[i],next_href[i],fromlist[i],
+                s.append( fmt % (next_id[i],next_href[i],fromlist[i],
                                            next_href[i],tolist[i]))
         if fromdesc or todesc:
             header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
@@ -1969,7 +1968,7 @@
             header_row = ''
 
         table = self._table_template % dict(
-            data_rows=s.getvalue(),
+            data_rows=''.join(s),
             header_row=header_row,
             prefix=self._prefix[1])
 

Modified: python/branches/p3yk-noslice/Lib/dis.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dis.py	(original)
+++ python/branches/p3yk-noslice/Lib/dis.py	Wed Jul 11 15:40:56 2007
@@ -20,16 +20,13 @@
         return
     if hasattr(x, 'im_func'):
         x = x.im_func
-    if hasattr(x, 'func_code'):
-        x = x.func_code
+    if hasattr(x, '__code__'):
+        x = x.__code__
     if hasattr(x, '__dict__'):
-        items = x.__dict__.items()
-        items.sort()
+        items = sorted(x.__dict__.items())
         for name, x1 in items:
-            if type(x1) in (types.MethodType,
-                            types.FunctionType,
-                            types.CodeType,
-                            types.ClassType):
+            if isinstance(x1, (types.MethodType, types.FunctionType,
+                               types.CodeType, type)):
                 print("Disassembly of %s:" % name)
                 try:
                     dis(x1)
@@ -41,9 +38,8 @@
     elif isinstance(x, str):
         disassemble_string(x)
     else:
-        raise TypeError, \
-              "don't know how to disassemble %s objects" % \
-              type(x).__name__
+        raise TypeError("don't know how to disassemble %s objects" %
+                        type(x).__name__)
 
 def distb(tb=None):
     """Disassemble a traceback (default: last traceback)."""
@@ -55,6 +51,62 @@
         while tb.tb_next: tb = tb.tb_next
     disassemble(tb.tb_frame.f_code, tb.tb_lasti)
 
+# XXX This duplicates information from code.h, also duplicated in inspect.py.
+# XXX Maybe this ought to be put in a central location, like opcode.py?
+flag2name = {
+     1: "OPTIMIZED",
+     2: "NEWLOCALS",
+     4: "VARARGS",
+     8: "VARKEYWORDS",
+    16: "NESTED",
+    32: "GENERATOR",
+    64: "NOFREE",
+}
+
+def pretty_flags(flags):
+    """Return pretty representation of code flags."""
+    names = []
+    for i in range(32):
+        flag = 1<<i
+        if flags & flag:
+            names.append(flag2name.get(flag, hex(flag)))
+            flags ^= flag
+            if not flags:
+                break
+    else:
+        names.append(hex(flags))
+    return ", ".join(names)
+
+def show_code(co):
+    """Show details about a code object."""
+    print("Name:             ", co.co_name)
+    print("Filename:         ", co.co_filename)
+    print("Argument count:   ", co.co_argcount)
+    print("Kw-only arguments:", co.co_kwonlyargcount)
+    print("Number of locals: ", co.co_nlocals)
+    print("Stack size:       ", co.co_stacksize)
+    print("Flags:            ", pretty_flags(co.co_flags))
+    if co.co_consts:
+        print("Constants:")
+        for i_c in enumerate(co.co_consts):
+            print("%4d: %r" % i_c)
+    if co.co_names:
+        print("Names:")
+        for i_n in enumerate(co.co_names):
+            print("%4d: %s" % i_n)
+    if co.co_varnames:
+        print("Variable names:")
+        for i_n in enumerate(co.co_varnames):
+            print("%4d: %s" % i_n)
+    if co.co_freevars:
+        print("Free variables:")
+        for i_n in enumerate(co.co_freevars):
+            print("%4d: %s" % i_n)
+    if co.co_cellvars:
+        print("Cell variables:")
+        for i_n in enumerate(co.co_cellvars):
+            print("%4d: %s" % i_n)
+
 def disassemble(co, lasti=-1):
     """Disassemble a code object."""
     code = co.co_code

Modified: python/branches/p3yk-noslice/Lib/distutils/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/__init__.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/__init__.py	Wed Jul 11 15:40:56 2007
@@ -20,4 +20,4 @@
 # In general, major and minor version should loosely follow the Python
 # version number the distutils code was shipped with.
 #
-__version__ = "2.5.0"
+__version__ = "2.5.1"

Modified: python/branches/p3yk-noslice/Lib/distutils/ccompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/ccompiler.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/ccompiler.py	Wed Jul 11 15:40:56 2007
@@ -1040,7 +1040,7 @@
     def move_file (self, src, dst):
         return move_file (src, dst, dry_run=self.dry_run)
 
-    def mkpath (self, name, mode=0777):
+    def mkpath (self, name, mode=0o777):
         mkpath (name, mode, self.dry_run)
 
 

Modified: python/branches/p3yk-noslice/Lib/distutils/cmd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/cmd.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/cmd.py	Wed Jul 11 15:40:56 2007
@@ -8,8 +8,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string, re
-from types import *
+import sys, os, re
 from distutils.errors import *
 from distutils import util, dir_util, file_util, archive_util, dep_util
 from distutils import log
@@ -166,7 +165,7 @@
         print(indent + header)
         indent = indent + "  "
         for (option, _, _) in self.user_options:
-            option = string.translate(option, longopt_xlate)
+            option = option.translate(longopt_xlate)
             if option[-1] == "=":
                 option = option[:-1]
             value = getattr(self, option)
@@ -222,7 +221,7 @@
         if val is None:
             setattr(self, option, default)
             return default
-        elif type(val) is not StringType:
+        elif not isinstance(val, str):
             raise DistutilsOptionError, \
                   "'%s' must be a %s (got `%s`)" % (option, what, val)
         return val
@@ -242,12 +241,12 @@
         val = getattr(self, option)
         if val is None:
             return
-        elif type(val) is StringType:
+        elif isinstance(val, str):
             setattr(self, option, re.split(r',\s*|\s+', val))
         else:
-            if type(val) is ListType:
+            if isinstance(val, list):
                 types = map(type, val)
-                ok = (types == [StringType] * len(val))
+                ok = (types == [str] * len(val))
             else:
                 ok = 0
 
@@ -358,7 +357,7 @@
         util.execute(func, args, msg, dry_run=self.dry_run)
 
 
-    def mkpath (self, name, mode=0777):
+    def mkpath (self, name, mode=0o777):
         dir_util.mkpath(name, mode, dry_run=self.dry_run)
 
 
@@ -415,15 +414,15 @@
         """
         if exec_msg is None:
             exec_msg = "generating %s from %s" % \
-                       (outfile, string.join(infiles, ', '))
+                       (outfile, ', '.join(infiles))
         if skip_msg is None:
             skip_msg = "skipping %s (inputs unchanged)" % outfile
 
 
         # Allow 'infiles' to be a single string
-        if type(infiles) is StringType:
+        if isinstance(infiles, str):
             infiles = (infiles,)
-        elif type(infiles) not in (ListType, TupleType):
+        elif not isinstance(infiles, (list, tuple)):
             raise TypeError, \
                   "'infiles' must be a string, or a list or tuple of strings"
 

Modified: python/branches/p3yk-noslice/Lib/distutils/command/bdist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/bdist.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/bdist.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 
 __revision__ = "$Id$"
 
-import os, string
+import os
 from types import *
 from distutils.core import Command
 from distutils.errors import *

Modified: python/branches/p3yk-noslice/Lib/distutils/command/bdist_msi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/bdist_msi.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/bdist_msi.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 Implements the bdist_msi command.
 """
 
-import sys, os, string
+import sys, os
 from distutils.core import Command
 from distutils.util import get_platform
 from distutils.dir_util import remove_tree

Modified: python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 import glob
 from types import *
 from distutils.core import Command
@@ -354,7 +354,7 @@
             line = out.readline()
             if not line:
                 break
-            l = string.split(string.strip(line))
+            l = line.strip().split()
             assert(len(l) == 2)
             binary_rpms.append(l[1])
             # The source rpm is named after the first entry in the spec file
@@ -437,9 +437,9 @@
                       'Conflicts',
                       'Obsoletes',
                       ):
-            val = getattr(self, string.lower(field))
+            val = getattr(self, field.lower())
             if type(val) is ListType:
-                spec_file.append('%s: %s' % (field, string.join(val)))
+                spec_file.append('%s: %s' % (field, ' '.join(val)))
             elif val is not None:
                 spec_file.append('%s: %s' % (field, val))
 
@@ -452,7 +452,7 @@
 
         if self.build_requires:
             spec_file.append('BuildRequires: ' +
-                             string.join(self.build_requires))
+                             ' '.join(self.build_requires))
 
         if self.icon:
             spec_file.append('Icon: ' + os.path.basename(self.icon))
@@ -513,7 +513,7 @@
                     '',
                     '%' + rpm_opt,])
                 if val:
-                    spec_file.extend(string.split(open(val, 'r').read(), '\n'))
+                    spec_file.extend(open(val, 'r').read().split('\n'))
                 else:
                     spec_file.append(default)
 
@@ -526,7 +526,7 @@
             ])
 
         if self.doc_files:
-            spec_file.append('%doc ' + string.join(self.doc_files))
+            spec_file.append('%doc ' + ' '.join(self.doc_files))
 
         if self.changelog:
             spec_file.extend([
@@ -544,8 +544,8 @@
         if not changelog:
             return changelog
         new_changelog = []
-        for line in string.split(string.strip(changelog), '\n'):
-            line = string.strip(line)
+        for line in changelog.strip().split('\n'):
+            line = line.strip()
             if line[0] == '*':
                 new_changelog.extend(['', line])
             elif line[0] == '-':

Modified: python/branches/p3yk-noslice/Lib/distutils/command/bdist_wininst.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/bdist_wininst.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/bdist_wininst.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from distutils.core import Command
 from distutils.util import get_platform
 from distutils.dir_util import create_tree, remove_tree
@@ -135,7 +135,7 @@
         # Use a custom scheme for the zip-file, because we have to decide
         # at installation time which scheme to use.
         for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
-            value = string.upper(key)
+            value = key.upper()
             if key == 'headers':
                 value = value + '/Include/$dist_name'
             setattr(install,
@@ -192,14 +192,14 @@
 
         # Escape newline characters
         def escape(s):
-            return string.replace(s, "\n", "\\n")
+            return s.replace("\n", "\\n")
 
         for name in ["author", "author_email", "description", "maintainer",
                      "maintainer_email", "name", "url", "version"]:
             data = getattr(metadata, name, "")
             if data:
                 info = info + ("\n    %s: %s" % \
-                               (string.capitalize(name), escape(data)))
+                               (name.capitalize(), escape(data)))
                 lines.append("%s=%s" % (name, escape(data)))
 
         # The [setup] section contains entries controlling
@@ -220,7 +220,7 @@
         build_info = "Built %s with distutils-%s" % \
                      (time.ctime(time.time()), distutils.__version__)
         lines.append("build_info=%s" % build_info)
-        return string.join(lines, "\n")
+        return "\n".join(lines)
 
     # get_inidata()
 

Modified: python/branches/p3yk-noslice/Lib/distutils/command/build_clib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/build_clib.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/build_clib.py	Wed Jul 11 15:40:56 2007
@@ -18,7 +18,7 @@
 # two modules, mainly because a number of subtle details changed in the
 # cut 'n paste.  Sigh.
 
-import os, string
+import os
 from types import *
 from distutils.core import Command
 from distutils.errors import *
@@ -93,8 +93,7 @@
         if self.include_dirs is None:
             self.include_dirs = self.distribution.include_dirs or []
         if type(self.include_dirs) is StringType:
-            self.include_dirs = string.split(self.include_dirs,
-                                             os.pathsep)
+            self.include_dirs = self.include_dirs.split(os.pathsep)
 
         # XXX same as for build_ext -- what about 'self.define' and
         # 'self.undef' ?

Modified: python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string, re
+import sys, os, re
 from types import *
 from distutils.core import Command
 from distutils.errors import *
@@ -138,7 +138,7 @@
         if self.include_dirs is None:
             self.include_dirs = self.distribution.include_dirs or []
         if type(self.include_dirs) is StringType:
-            self.include_dirs = string.split(self.include_dirs, os.pathsep)
+            self.include_dirs = self.include_dirs.split(os.pathsep)
 
         # Put the Python "system" include dir at the end, so that
         # any local include dirs take precedence.
@@ -156,12 +156,12 @@
         if self.library_dirs is None:
             self.library_dirs = []
         elif type(self.library_dirs) is StringType:
-            self.library_dirs = string.split(self.library_dirs, os.pathsep)
+            self.library_dirs = self.library_dirs.split(os.pathsep)
 
         if self.rpath is None:
             self.rpath = []
         elif type(self.rpath) is StringType:
-            self.rpath = string.split(self.rpath, os.pathsep)
+            self.rpath = self.rpath.split(os.pathsep)
 
         # for extensions under windows use different directories
         # for Release and Debug builds.
@@ -186,7 +186,7 @@
         # for extensions under Cygwin and AtheOS Python's library directory must be
         # appended to library_dirs
         if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
-            if string.find(sys.executable, sys.exec_prefix) != -1:
+            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
                 # building third party extensions
                 self.library_dirs.append(os.path.join(sys.prefix, "lib",
                                                       "python" + get_python_version(),
@@ -199,7 +199,7 @@
         # Python's library directory must be appended to library_dirs
         if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \
                 and sysconfig.get_config_var('Py_ENABLE_SHARED'):
-            if string.find(sys.executable, sys.exec_prefix) != -1:
+            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
                 # building third party extensions
                 self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
             else:
@@ -212,14 +212,14 @@
         # symbols can be separated with commas.
 
         if self.define:
-            defines = string.split(self.define, ',')
+            defines = self.define.split(',')
             self.define = map(lambda symbol: (symbol, '1'), defines)
 
         # The option for macros to undefine is also a string from the
         # option parsing, but has to be a list.  Multiple symbols can also
         # be separated with commas here.
         if self.undef:
-            self.undef = string.split(self.undef, ',')
+            self.undef = self.undef.split(',')
 
         if self.swig_opts is None:
             self.swig_opts = []
@@ -429,8 +429,8 @@
             # ignore build-lib -- put the compiled extension into
             # the source tree along with pure Python modules
 
-            modpath = string.split(fullname, '.')
-            package = string.join(modpath[0:-1], '.')
+            modpath = fullname.split('.')
+            package = '.'.join(modpath[0:-1])
             base = modpath[-1]
 
             build_py = self.get_finalized_command('build_py')
@@ -533,7 +533,8 @@
         if self.swig_cpp:
             log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
 
-        if self.swig_cpp or ('-c++' in self.swig_opts):
+        if self.swig_cpp or ('-c++' in self.swig_opts) or \
+           ('-c++' in extension.swig_opts):
             target_ext = '.cpp'
         else:
             target_ext = '.c'
@@ -617,7 +618,7 @@
         """
 
         from distutils.sysconfig import get_config_var
-        ext_path = string.split(ext_name, '.')
+        ext_path = ext_name.split('.')
         # OS/2 has an 8 character module (extension) limit :-(
         if os.name == "os2":
             ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
@@ -634,7 +635,7 @@
         the .pyd file (DLL) must export the module "init" function.
         """
 
-        initfunc_name = "init" + string.split(ext.name,'.')[-1]
+        initfunc_name = "init" + ext.name.split('.')[-1]
         if initfunc_name not in ext.export_symbols:
             ext.export_symbols.append(initfunc_name)
         return ext.export_symbols

Modified: python/branches/p3yk-noslice/Lib/distutils/command/build_py.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/build_py.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/build_py.py	Wed Jul 11 15:40:56 2007
@@ -6,7 +6,7 @@
 
 __revision__ = "$Id$"
 
-import sys, string, os
+import sys, os
 from types import *
 from glob import glob
 
@@ -114,7 +114,9 @@
             build_dir = os.path.join(*([self.build_lib] + package.split('.')))
 
             # Length of path to strip from found files
-            plen = len(src_dir)+1
+            plen = 0
+            if src_dir:
+                plen = len(src_dir)+1
 
             # Strip directory from globbed filenames
             filenames = [
@@ -150,7 +152,7 @@
            distribution, where package 'package' should be found
            (at least according to the 'package_dir' option, if any)."""
 
-        path = string.split(package, '.')
+        path = package.split('.')
 
         if not self.package_dir:
             if path:
@@ -161,7 +163,7 @@
             tail = []
             while path:
                 try:
-                    pdir = self.package_dir[string.join(path, '.')]
+                    pdir = self.package_dir['.'.join(path)]
                 except KeyError:
                     tail.insert(0, path[-1])
                     del path[-1]
@@ -272,8 +274,8 @@
         #   - don't check for __init__.py in directory for empty package
 
         for module in self.py_modules:
-            path = string.split(module, '.')
-            package = string.join(path[0:-1], '.')
+            path = module.split('.')
+            package = '.'.join(path[0:-1])
             module_base = path[-1]
 
             try:
@@ -342,7 +344,7 @@
         modules = self.find_all_modules()
         outputs = []
         for (package, module, module_file) in modules:
-            package = string.split(package, '.')
+            package = package.split('.')
             filename = self.get_module_outfile(self.build_lib, package, module)
             outputs.append(filename)
             if include_bytecode:
@@ -362,7 +364,7 @@
 
     def build_module (self, module, module_file, package):
         if type(package) is StringType:
-            package = string.split(package, '.')
+            package = package.split('.')
         elif type(package) not in (ListType, TupleType):
             raise TypeError, \
                   "'package' must be a string (dot-separated), list, or tuple"

Modified: python/branches/p3yk-noslice/Lib/distutils/command/build_scripts.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/build_scripts.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/build_scripts.py	Wed Jul 11 15:40:56 2007
@@ -119,8 +119,8 @@
                 if self.dry_run:
                     log.info("changing mode of %s", file)
                 else:
-                    oldmode = os.stat(file)[ST_MODE] & 07777
-                    newmode = (oldmode | 0555) & 07777
+                    oldmode = os.stat(file)[ST_MODE] & 0o7777
+                    newmode = (oldmode | 0o555) & 0o7777
                     if newmode != oldmode:
                         log.info("changing mode of %s from %o to %o",
                                  file, oldmode, newmode)

Modified: python/branches/p3yk-noslice/Lib/distutils/command/config.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/config.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/config.py	Wed Jul 11 15:40:56 2007
@@ -13,7 +13,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string, re
+import sys, os, re
 from types import *
 from distutils.core import Command
 from distutils.errors import DistutilsExecError
@@ -74,7 +74,7 @@
         if self.include_dirs is None:
             self.include_dirs = self.distribution.include_dirs or []
         elif type(self.include_dirs) is StringType:
-            self.include_dirs = string.split(self.include_dirs, os.pathsep)
+            self.include_dirs = self.include_dirs.split(os.pathsep)
 
         if self.libraries is None:
             self.libraries = []
@@ -84,7 +84,7 @@
         if self.library_dirs is None:
             self.library_dirs = []
         elif type(self.library_dirs) is StringType:
-            self.library_dirs = string.split(self.library_dirs, os.pathsep)
+            self.library_dirs = self.library_dirs.split(os.pathsep)
 
 
     def run (self):
@@ -163,7 +163,7 @@
         if not filenames:
             filenames = self.temp_files
             self.temp_files = []
-        log.info("removing: %s", string.join(filenames))
+        log.info("removing: %s", ' '.join(filenames))
         for filename in filenames:
             try:
                 os.remove(filename)
@@ -322,7 +322,7 @@
         else:
             body.append("  %s;" % func)
         body.append("}")
-        body = string.join(body, "\n") + "\n"
+        body = "\n".join(body) + "\n"
 
         return self.try_link(body, headers, include_dirs,
                              libraries, library_dirs)

Modified: python/branches/p3yk-noslice/Lib/distutils/command/install.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/install.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/install.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from types import *
 from distutils.core import Command
 from distutils.debug import DEBUG
@@ -269,7 +269,7 @@
         # $platbase in the other installation directories and not worry
         # about needing recursive variable expansion (shudder).
 
-        py_version = (string.split(sys.version))[0]
+        py_version = sys.version.split()[0]
         (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
         self.config_vars = {'dist_name': self.distribution.get_name(),
                             'dist_version': self.distribution.get_version(),
@@ -353,11 +353,11 @@
                 if opt_name[-1] == "=":
                     opt_name = opt_name[0:-1]
                 if self.negative_opt.has_key(opt_name):
-                    opt_name = string.translate(self.negative_opt[opt_name],
-                                                longopt_xlate)
+                    opt_name = self.negative_opt[opt_name].translate(
+                                                               longopt_xlate)
                     val = not getattr(self, opt_name)
                 else:
-                    opt_name = string.translate(opt_name, longopt_xlate)
+                    opt_name = opt_name.translate(longopt_xlate)
                     val = getattr(self, opt_name)
                 print("  %s: %s" % (opt_name, val))
 
@@ -464,7 +464,7 @@
 
         if self.extra_path is not None:
             if type(self.extra_path) is StringType:
-                self.extra_path = string.split(self.extra_path, ',')
+                self.extra_path = self.extra_path.split(',')
 
             if len(self.extra_path) == 1:
                 path_file = extra_dirs = self.extra_path[0]
@@ -517,7 +517,7 @@
             outputs = self.get_outputs()
             if self.root:               # strip any package prefix
                 root_len = len(self.root)
-                for counter in xrange(len(outputs)):
+                for counter in range(len(outputs)):
                     outputs[counter] = outputs[counter][root_len:]
             self.execute(write_file,
                          (self.record, outputs),

Modified: python/branches/p3yk-noslice/Lib/distutils/command/install_lib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/install_lib.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/install_lib.py	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from types import IntType
 from distutils.core import Command
 from distutils.errors import DistutilsOptionError

Modified: python/branches/p3yk-noslice/Lib/distutils/command/install_scripts.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/install_scripts.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/install_scripts.py	Wed Jul 11 15:40:56 2007
@@ -53,7 +53,7 @@
                 if self.dry_run:
                     log.info("changing mode of %s", file)
                 else:
-                    mode = ((os.stat(file)[ST_MODE]) | 0555) & 07777
+                    mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777
                     log.info("changing mode of %s to %o", file, mode)
                     os.chmod(file, mode)
 

Modified: python/branches/p3yk-noslice/Lib/distutils/command/register.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/register.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/register.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string, urllib2, getpass, urlparse
+import sys, os, urllib2, getpass, urlparse
 import StringIO, ConfigParser
 
 from distutils.core import Command
@@ -67,7 +67,7 @@
 
         if missing:
             self.warn("missing required meta-data: " +
-                      string.join(missing, ", "))
+                      ", ".join(missing))
 
         if metadata.author:
             if not metadata.author_email:
@@ -183,7 +183,7 @@
                         username, password))
                     f.close()
                     try:
-                        os.chmod(rc, 0600)
+                        os.chmod(rc, 0o600)
                     except:
                         pass
         elif choice == '2':

Modified: python/branches/p3yk-noslice/Lib/distutils/command/sdist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/sdist.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/sdist.py	Wed Jul 11 15:40:56 2007
@@ -6,7 +6,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from types import *
 from glob import glob
 from distutils.core import Command
@@ -166,7 +166,7 @@
 
         if missing:
             self.warn("missing required meta-data: " +
-                      string.join(missing, ", "))
+                      ", ".join(missing))
 
         if metadata.author:
             if not metadata.author_email:
@@ -279,7 +279,7 @@
 
                 if not got_it:
                     self.warn("standard file not found: should have one of " +
-                              string.join(alts, ', '))
+                              ', '.join(alts))
             else:
                 if os.path.exists(fn):
                     self.filelist.append(fn)

Modified: python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/cygwinccompiler.py	Wed Jul 11 15:40:56 2007
@@ -365,10 +365,9 @@
     # "pyconfig.h" check -- should probably be renamed...
 
     from distutils import sysconfig
-    import string
     # if sys.version contains GCC then python was compiled with
     # GCC, and the pyconfig.h file should be OK
-    if string.find(sys.version,"GCC") >= 0:
+    if sys.version.find("GCC") >= 0:
         return (CONFIG_H_OK, "sys.version mentions 'GCC'")
 
     fn = sysconfig.get_config_h_filename()
@@ -387,7 +386,7 @@
 
     else:
         # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar
-        if string.find(s,"__GNUC__") >= 0:
+        if s.find("__GNUC__") >= 0:
             return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn)
         else:
             return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn)

Modified: python/branches/p3yk-noslice/Lib/distutils/dir_util.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/dir_util.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/dir_util.py	Wed Jul 11 15:40:56 2007
@@ -18,7 +18,7 @@
 # I don't use os.makedirs because a) it's new to Python 1.5.2, and
 # b) it blows up if the directory already exists (I want to silently
 # succeed in that case).
-def mkpath (name, mode=0777, verbose=0, dry_run=0):
+def mkpath (name, mode=0o777, verbose=0, dry_run=0):
     """Create a directory and any missing ancestor directories.  If the
        directory already exists (or if 'name' is the empty string, which
        means the current directory, which of course exists), then do
@@ -85,7 +85,7 @@
 # mkpath ()
 
 
-def create_tree (base_dir, files, mode=0777, verbose=0, dry_run=0):
+def create_tree (base_dir, files, mode=0o777, verbose=0, dry_run=0):
 
     """Create all the empty directories under 'base_dir' needed to
        put 'files' there.  'base_dir' is just the a name of a directory
@@ -96,14 +96,12 @@
        for 'mkpath()'."""
 
     # First get the list of directories to create
-    need_dir = {}
+    need_dir = set()
     for file in files:
-        need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1
-    need_dirs = need_dir.keys()
-    need_dirs.sort()
+        need_dir.add(os.path.join(base_dir, os.path.dirname(file)))
 
     # Now create them
-    for dir in need_dirs:
+    for dir in sorted(need_dir):
         mkpath(dir, mode, dry_run=dry_run)
 
 # create_tree ()

Modified: python/branches/p3yk-noslice/Lib/distutils/dist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/dist.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/dist.py	Wed Jul 11 15:40:56 2007
@@ -8,8 +8,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string, re
-from types import *
+import sys, os, re
 from copy import copy
 
 try:
@@ -113,8 +112,7 @@
         ('obsoletes', None,
          "print the list of packages/modules made obsolete")
         ]
-    display_option_names = map(lambda x: translate_longopt(x[0]),
-                               display_options)
+    display_option_names = [translate_longopt(x[0]) for x in display_options]
 
     # negative options are options that exclude other options
     negative_opt = {'quiet': 'verbose'}
@@ -304,7 +302,7 @@
             else:
                 print(indent + "option dict for '%s' command:" % cmd_name)
                 out = pformat(opt_dict)
-                for line in string.split(out, "\n"):
+                for line in out.split("\n"):
                     print(indent + "  " + line)
 
     # dump_option_dicts ()
@@ -378,7 +376,7 @@
                 for opt in options:
                     if opt != '__name__':
                         val = parser.get(section,opt)
-                        opt = string.replace(opt, '-', '_')
+                        opt = opt.replace('-', '_')
                         opt_dict[opt] = (filename, val)
 
             # Make the ConfigParser forget everything (so we retain
@@ -527,7 +525,7 @@
         # Also make sure that the command object provides a list of its
         # known options.
         if not (hasattr(cmd_class, 'user_options') and
-                type(cmd_class.user_options) is ListType):
+                isinstance(cmd_class.user_options, list)):
             raise DistutilsClassError, \
                   ("command class %s must provide " +
                    "'user_options' attribute (a list of tuples)") % \
@@ -543,7 +541,7 @@
         # Check for help_options in command class.  They have a different
         # format (tuple of four) so we need to preprocess them here.
         if (hasattr(cmd_class, 'help_options') and
-            type(cmd_class.help_options) is ListType):
+            isinstance(cmd_class.help_options, list)):
             help_options = fix_help_options(cmd_class.help_options)
         else:
             help_options = []
@@ -561,7 +559,7 @@
             return
 
         if (hasattr(cmd_class, 'help_options') and
-            type(cmd_class.help_options) is ListType):
+            isinstance(cmd_class.help_options, list)):
             help_option_found=0
             for (help_option, short, desc, func) in cmd_class.help_options:
                 if hasattr(opts, parser.get_attr_name(help_option)):
@@ -569,7 +567,7 @@
                     #print "showing help for option %s of command %s" % \
                     #      (help_option[0],cmd_class)
 
-                    if callable(func):
+                    if hasattr(func, '__call__'):
                         func()
                     else:
                         raise DistutilsClassError(
@@ -598,15 +596,15 @@
 
         keywords = self.metadata.keywords
         if keywords is not None:
-            if type(keywords) is StringType:
-                keywordlist = string.split(keywords, ',')
-                self.metadata.keywords = map(string.strip, keywordlist)
+            if isinstance(keywords, str):
+                keywordlist = keywords.split(',')
+                self.metadata.keywords = [x.strip() for x in keywordlist]
 
         platforms = self.metadata.platforms
         if platforms is not None:
-            if type(platforms) is StringType:
-                platformlist = string.split(platforms, ',')
-                self.metadata.platforms = map(string.strip, platformlist)
+            if isinstance(platforms, str):
+                platformlist = platforms.split(',')
+                self.metadata.platforms = [x.strip() for x in platformlist]
 
     def _show_help (self,
                     parser,
@@ -646,12 +644,12 @@
             print()
 
         for command in self.commands:
-            if type(command) is ClassType and issubclass(command, Command):
+            if isinstance(command, type) and issubclass(command, Command):
                 klass = command
             else:
                 klass = self.get_command_class(command)
             if (hasattr(klass, 'help_options') and
-                type(klass.help_options) is ListType):
+                isinstance(klass.help_options, list)):
                 parser.set_option_table(klass.user_options +
                                         fix_help_options(klass.help_options))
             else:
@@ -695,10 +693,10 @@
                 opt = translate_longopt(opt)
                 value = getattr(self.metadata, "get_"+opt)()
                 if opt in ['keywords', 'platforms']:
-                    print(string.join(value, ','))
+                    print(','.join(value))
                 elif opt in ('classifiers', 'provides', 'requires',
                              'obsoletes'):
-                    print(string.join(value, '\n'))
+                    print('\n'.join(value))
                 else:
                     print(value)
                 any_display_options = 1
@@ -803,10 +801,10 @@
         """Return a list of packages from which commands are loaded."""
         pkgs = self.command_packages
         if not isinstance(pkgs, type([])):
-            pkgs = string.split(pkgs or "", ",")
+            pkgs = (pkgs or "").split(",")
             for i in range(len(pkgs)):
-                pkgs[i] = string.strip(pkgs[i])
-            pkgs = filter(None, pkgs)
+                pkgs[i] = pkgs[i].strip()
+            pkgs = [p for p in pkgs if p]
             if "distutils.command" not in pkgs:
                 pkgs.insert(0, "distutils.command")
             self.command_packages = pkgs
@@ -906,7 +904,7 @@
                 neg_opt = {}
 
             try:
-                is_string = type(value) is StringType
+                is_string = isinstance(value, str)
                 if option in neg_opt and is_string:
                     setattr(command_obj, neg_opt[option], not strtobool(value))
                 elif option in bool_opts and is_string:
@@ -1100,7 +1098,7 @@
         long_desc = rfc822_escape( self.get_long_description() )
         file.write('Description: %s\n' % long_desc)
 
-        keywords = string.join( self.get_keywords(), ',')
+        keywords = ','.join(self.get_keywords())
         if keywords:
             file.write('Keywords: %s\n' % keywords )
 

Modified: python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/emxccompiler.py	Wed Jul 11 15:40:56 2007
@@ -261,10 +261,9 @@
     # "pyconfig.h" check -- should probably be renamed...
 
     from distutils import sysconfig
-    import string
     # if sys.version contains GCC then python was compiled with
     # GCC, and the pyconfig.h file should be OK
-    if string.find(sys.version,"GCC") >= 0:
+    if sys.version.find("GCC") >= 0:
         return (CONFIG_H_OK, "sys.version mentions 'GCC'")
 
     fn = sysconfig.get_config_h_filename()
@@ -283,7 +282,7 @@
 
     else:
         # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar
-        if string.find(s,"__GNUC__") >= 0:
+        if s.find("__GNUC__") >= 0:
             return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn)
         else:
             return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn)

Modified: python/branches/p3yk-noslice/Lib/distutils/extension.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/extension.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/extension.py	Wed Jul 11 15:40:56 2007
@@ -5,8 +5,7 @@
 
 __revision__ = "$Id$"
 
-import os, string, sys
-from types import *
+import os, sys
 
 try:
     import warnings
@@ -103,9 +102,9 @@
                   language=None,
                   **kw                      # To catch unknown keywords
                  ):
-        assert type(name) is StringType, "'name' must be a string"
-        assert (type(sources) is ListType and
-                map(type, sources) == [StringType]*len(sources)), \
+        assert isinstance(name, str), "'name' must be a string"
+        assert (isinstance(sources, list) and
+                all(isinstance(s, str) for s in sources)), \
                 "'sources' must be a list of strings"
 
         self.name = name
@@ -128,7 +127,7 @@
         if len(kw):
             L = kw.keys() ; L.sort()
             L = map(repr, L)
-            msg = "Unknown Extension options: " + string.join(L, ', ')
+            msg = "Unknown Extension options: " + ', '.join(L)
             if warnings is not None:
                 warnings.warn(msg)
             else:
@@ -195,7 +194,7 @@
             elif switch == "-I":
                 ext.include_dirs.append(value)
             elif switch == "-D":
-                equals = string.find(value, "=")
+                equals = value.find("=")
                 if equals == -1:        # bare "-DFOO" -- no value
                     ext.define_macros.append((value, None))
                 else:                   # "-DFOO=blah"

Modified: python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py	Wed Jul 11 15:40:56 2007
@@ -115,7 +115,7 @@
         """Translate long option name 'long_option' to the form it
         has as an attribute of some object: ie., translate hyphens
         to underscores."""
-        return string.translate(long_option, longopt_xlate)
+        return long_option.translate(longopt_xlate)
 
 
     def _check_alias_dict (self, aliases, what):
@@ -253,7 +253,7 @@
 
         self._grok_option_table()
 
-        short_opts = string.join(self.short_opts)
+        short_opts = ' '.join(self.short_opts)
         try:
             opts, args = getopt.getopt(args, short_opts, self.long_opts)
         except getopt.error as msg:
@@ -420,8 +420,8 @@
     if len(text) <= width:
         return [text]
 
-    text = string.expandtabs(text)
-    text = string.translate(text, WS_TRANS)
+    text = text.expandtabs()
+    text = text.translate(WS_TRANS)
     chunks = re.split(r'( +|-+)', text)
     chunks = filter(None, chunks)      # ' - ' results in empty strings
     lines = []
@@ -460,7 +460,7 @@
 
         # and store this line in the list-of-all-lines -- as a single
         # string, of course!
-        lines.append(string.join(cur_line, ''))
+        lines.append(''.join(cur_line))
 
     # while chunks
 
@@ -473,7 +473,7 @@
     """Convert a long option name to a valid Python identifier by
     changing "-" to "_".
     """
-    return string.translate(opt, longopt_xlate)
+    return opt.translate(longopt_xlate)
 
 
 class OptionDummy:
@@ -498,5 +498,5 @@
 
     for w in (10, 20, 30, 40):
         print("width: %d" % w)
-        print(string.join(wrap_text(text, w), "\n"))
+        print("\n".join(wrap_text(text, w)))
         print()

Modified: python/branches/p3yk-noslice/Lib/distutils/filelist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/filelist.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/filelist.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
 __revision__ = "$Id$"
 
-import os, string, re
+import os, re
 import fnmatch
 from types import *
 from glob import glob
@@ -84,7 +84,7 @@
     # -- "File template" methods ---------------------------------------
 
     def _parse_template_line (self, line):
-        words = string.split(line)
+        words = line.split()
         action = words[0]
 
         patterns = dir = dir_pattern = None
@@ -133,28 +133,28 @@
         # right number of words on the line for that action -- so we
         # can proceed with minimal error-checking.
         if action == 'include':
-            self.debug_print("include " + string.join(patterns))
+            self.debug_print("include " + ' '.join(patterns))
             for pattern in patterns:
                 if not self.include_pattern(pattern, anchor=1):
                     log.warn("warning: no files found matching '%s'",
                              pattern)
 
         elif action == 'exclude':
-            self.debug_print("exclude " + string.join(patterns))
+            self.debug_print("exclude " + ' '.join(patterns))
             for pattern in patterns:
                 if not self.exclude_pattern(pattern, anchor=1):
                     log.warn(("warning: no previously-included files "
                               "found matching '%s'"), pattern)
 
         elif action == 'global-include':
-            self.debug_print("global-include " + string.join(patterns))
+            self.debug_print("global-include " + ' '.join(patterns))
             for pattern in patterns:
                 if not self.include_pattern(pattern, anchor=0):
                     log.warn(("warning: no files found matching '%s' " +
                               "anywhere in distribution"), pattern)
 
         elif action == 'global-exclude':
-            self.debug_print("global-exclude " + string.join(patterns))
+            self.debug_print("global-exclude " + ' '.join(patterns))
             for pattern in patterns:
                 if not self.exclude_pattern(pattern, anchor=0):
                     log.warn(("warning: no previously-included files matching "
@@ -163,7 +163,7 @@
 
         elif action == 'recursive-include':
             self.debug_print("recursive-include %s %s" %
-                             (dir, string.join(patterns)))
+                             (dir, ' '.join(patterns)))
             for pattern in patterns:
                 if not self.include_pattern(pattern, prefix=dir):
                     log.warn(("warning: no files found matching '%s' " +
@@ -172,7 +172,7 @@
 
         elif action == 'recursive-exclude':
             self.debug_print("recursive-exclude %s %s" %
-                             (dir, string.join(patterns)))
+                             (dir, ' '.join(patterns)))
             for pattern in patterns:
                 if not self.exclude_pattern(pattern, prefix=dir):
                     log.warn(("warning: no previously-included files matching "

Modified: python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/msvccompiler.py	Wed Jul 11 15:40:56 2007
@@ -12,7 +12,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from distutils.errors import \
      DistutilsExecError, DistutilsPlatformError, \
      CompileError, LibError, LinkError
@@ -148,7 +148,7 @@
 
     def sub(self, s):
         for k, v in self.macros.items():
-            s = string.replace(s, k, v)
+            s = s.replace(k, v)
         return s
 
 def get_build_version():
@@ -159,7 +159,7 @@
     """
 
     prefix = "MSC v."
-    i = string.find(sys.version, prefix)
+    i = sys.version.find(prefix)
     if i == -1:
         return 6
     i = i + len(prefix)
@@ -181,12 +181,25 @@
     """
 
     prefix = " bit ("
-    i = string.find(sys.version, prefix)
+    i = sys.version.find(prefix)
     if i == -1:
         return "Intel"
-    j = string.find(sys.version, ")", i)
+    j = sys.version.find(")", i)
     return sys.version[i+len(prefix):j]
 
+def normalize_and_reduce_paths(paths):
+    """Return a list of normalized paths with duplicates removed.
+
+    The current order of paths is maintained.
+    """
+    # Paths are normalized so things like:  /a and /a/ aren't both preserved.
+    reduced_paths = []
+    for p in paths:
+        np = os.path.normpath(p)
+        # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
+        if np not in reduced_paths:
+            reduced_paths.append(np)
+    return reduced_paths
 
 
 class MSVCCompiler (CCompiler) :
@@ -266,11 +279,12 @@
 
         # extend the MSVC path with the current path
         try:
-            for p in string.split(os.environ['path'], ';'):
+            for p in os.environ['path'].split(';'):
                 self.__paths.append(p)
         except KeyError:
             pass
-        os.environ['path'] = string.join(self.__paths, ';')
+        self.__paths = normalize_and_reduce_paths(self.__paths)
+        os.environ['path'] = ";".join(self.__paths)
 
         self.preprocess_options = None
         if self.__arch == "Intel":
@@ -579,7 +593,7 @@
                 return fn
 
         # didn't find it; try existing path
-        for p in string.split(os.environ['Path'],';'):
+        for p in os.environ['Path'].split(';'):
             fn = os.path.join(os.path.abspath(p),exe)
             if os.path.isfile(fn):
                 return fn
@@ -608,9 +622,9 @@
             d = read_values(base, key)
             if d:
                 if self.__version >= 7:
-                    return string.split(self.__macros.sub(d[path]), ";")
+                    return self.__macros.sub(d[path]).split(";")
                 else:
-                    return string.split(d[path], ";")
+                    return d[path].split(";")
         # MSVC 6 seems to create the registry entries we need only when
         # the GUI is run.
         if self.__version == 6:
@@ -635,4 +649,4 @@
         else:
             p = self.get_msvc_paths(name)
         if p:
-            os.environ[name] = string.join(p, ';')
+            os.environ[name] = ';'.join(p)

Modified: python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from types import *
 from distutils.errors import \
      DistutilsExecError, DistutilsPlatformError, \
@@ -18,7 +18,6 @@
 import distutils.util
 import distutils.dir_util
 from distutils import log
-import mkcwproject
 
 class MWerksCompiler (CCompiler) :
     """Concrete class that implements an interface to MetroWerks CodeWarrior,
@@ -188,6 +187,7 @@
         # doesn't have a clue about our working directory.
         xmlfilename = os.path.join(os.getcwd(), os.path.join(build_temp, xmlname))
         log.debug("\tCreate XML file %s", xmlfilename)
+        import mkcwproject
         xmlbuilder = mkcwproject.cwxmlgen.ProjectBuilder(settings)
         xmlbuilder.generate()
         xmldata = settings['tmp_projectxmldata']
@@ -213,11 +213,11 @@
             curdir = os.getcwd()
             filename = os.path.join(curdir, filename)
         # Finally remove .. components
-        components = string.split(filename, ':')
+        components = filename.split(':')
         for i in range(1, len(components)):
             if components[i] == '..':
                 components[i] = ''
-        return string.join(components, ':')
+        return ':'.join(components)
 
     def library_dir_option (self, dir):
         """Return the compiler option to add 'dir' to the list of

Modified: python/branches/p3yk-noslice/Lib/distutils/spawn.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/spawn.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/spawn.py	Wed Jul 11 15:40:56 2007
@@ -10,7 +10,7 @@
 
 __revision__ = "$Id$"
 
-import sys, os, string
+import sys, os
 from distutils.errors import *
 from distutils import log
 
@@ -59,7 +59,7 @@
     # quoting?)
 
     for i in range(len(args)):
-        if string.find(args[i], ' ') != -1:
+        if args[i].find(' ') != -1:
             args[i] = '"%s"' % args[i]
     return args
 
@@ -73,7 +73,7 @@
     if search_path:
         # either we find one or it stays the same
         executable = find_executable(executable) or executable
-    log.info(string.join([executable] + cmd[1:], ' '))
+    log.info(' '.join([executable] + cmd[1:]))
     if not dry_run:
         # spawn for NT requires a full path to the .exe
         try:
@@ -98,7 +98,7 @@
     if search_path:
         # either we find one or it stays the same
         executable = find_executable(executable) or executable
-    log.info(string.join([executable] + cmd[1:], ' '))
+    log.info(' '.join([executable] + cmd[1:]))
     if not dry_run:
         # spawnv for OS/2 EMX requires a full path to the .exe
         try:
@@ -119,7 +119,7 @@
                   verbose=0,
                   dry_run=0):
 
-    log.info(string.join(cmd, ' '))
+    log.info(' '.join(cmd))
     if dry_run:
         return
     exec_fn = search_path and os.execvp or os.execv
@@ -184,7 +184,7 @@
     """
     if path is None:
         path = os.environ['PATH']
-    paths = string.split(path, os.pathsep)
+    paths = path.split(os.pathsep)
     (base, ext) = os.path.splitext(executable)
     if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
         executable = executable + '.exe'

Modified: python/branches/p3yk-noslice/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/sysconfig.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/sysconfig.py	Wed Jul 11 15:40:56 2007
@@ -13,7 +13,6 @@
 
 import os
 import re
-import string
 import sys
 
 from .errors import DistutilsPlatformError
@@ -261,7 +260,7 @@
         m = _variable_rx.match(line)
         if m:
             n, v = m.group(1, 2)
-            v = string.strip(v)
+            v = v.strip()
             if "$" in v:
                 notdone[n] = v
             else:
@@ -295,7 +294,7 @@
                     else:
                         try: value = int(value)
                         except ValueError:
-                            done[name] = string.strip(value)
+                            done[name] = value.strip()
                         else:
                             done[name] = value
                         del notdone[name]
@@ -372,7 +371,7 @@
         if cur_target == '':
             cur_target = cfg_target
             os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
-        elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
+        elif [int(x) for x in cfg_target.split('.')] > [int(x) for x in cur_target.split('.')]:
             my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
                 % (cur_target, cfg_target))
             raise DistutilsPlatformError(my_msg)
@@ -399,7 +398,7 @@
             # relative to the srcdir, which after installation no longer makes
             # sense.
             python_lib = get_python_lib(standard_lib=1)
-            linkerscript_path = string.split(g['LDSHARED'])[0]
+            linkerscript_path = g['LDSHARED'].split()[0]
             linkerscript_name = os.path.basename(linkerscript_path)
             linkerscript = os.path.join(python_lib, 'config',
                                         linkerscript_name)

Modified: python/branches/p3yk-noslice/Lib/distutils/tests/support.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/tests/support.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/tests/support.py	Wed Jul 11 15:40:56 2007
@@ -9,12 +9,12 @@
 class LoggingSilencer(object):
 
     def setUp(self):
-        super(LoggingSilencer, self).setUp()
+        super().setUp()
         self.threshold = log.set_threshold(log.FATAL)
 
     def tearDown(self):
         log.set_threshold(self.threshold)
-        super(LoggingSilencer, self).tearDown()
+        super().tearDown()
 
 
 class TempdirManager(object):
@@ -24,11 +24,11 @@
     """
 
     def setUp(self):
-        super(TempdirManager, self).setUp()
+        super().setUp()
         self.tempdirs = []
 
     def tearDown(self):
-        super(TempdirManager, self).tearDown()
+        super().tearDown()
         while self.tempdirs:
             d = self.tempdirs.pop()
             shutil.rmtree(d)

Modified: python/branches/p3yk-noslice/Lib/distutils/tests/test_build_py.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/tests/test_build_py.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/tests/test_build_py.py	Wed Jul 11 15:40:56 2007
@@ -1,10 +1,13 @@
 """Tests for distutils.command.build_py."""
 
 import os
+import sys
+import StringIO
 import unittest
 
 from distutils.command.build_py import build_py
 from distutils.core import Distribution
+from distutils.errors import DistutilsFileError
 
 from distutils.tests import support
 
@@ -53,6 +56,38 @@
         self.assert_("__init__.pyc" in files)
         self.assert_("README.txt" in files)
 
+    def test_empty_package_dir (self):
+        # See SF 1668596/1720897.
+        cwd = os.getcwd()
+
+        # create the distribution files.
+        sources = self.mkdtemp()
+        open(os.path.join(sources, "__init__.py"), "w").close()
+
+        testdir = os.path.join(sources, "doc")
+        os.mkdir(testdir)
+        open(os.path.join(testdir, "testfile"), "w").close()
+
+        os.chdir(sources)
+        sys.stdout = StringIO.StringIO()
+
+        try:
+            dist = Distribution({"packages": ["pkg"],
+                                 "package_dir": {"pkg": ""},
+                                 "package_data": {"pkg": ["doc/*"]}})
+            # script_name need not exist, it just need to be initialized
+            dist.script_name = os.path.join(sources, "setup.py")
+            dist.script_args = ["build"]
+            dist.parse_command_line()
+
+            try:
+                dist.run_commands()
+            except DistutilsFileError:
+                self.fail("failed package_data test when package_dir is ''")
+        finally:
+            # Restore state.
+            os.chdir(cwd)
+            sys.stdout = sys.__stdout__
 
 def test_suite():
     return unittest.makeSuite(BuildPyTestCase)

Modified: python/branches/p3yk-noslice/Lib/distutils/text_file.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/text_file.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/text_file.py	Wed Jul 11 15:40:56 2007
@@ -6,8 +6,7 @@
 
 __revision__ = "$Id$"
 
-from types import *
-import sys, os, string
+import sys, os
 
 
 class TextFile:
@@ -137,12 +136,12 @@
         if line is None:
             line = self.current_line
         outmsg.append(self.filename + ", ")
-        if type (line) in (ListType, TupleType):
+        if isinstance (line, (list, tuple)):
             outmsg.append("lines %d-%d: " % tuple (line))
         else:
             outmsg.append("line %d: " % line)
         outmsg.append(str(msg))
-        return string.join(outmsg, "")
+        return "".join(outmsg)
 
 
     def error (self, msg, line=None):
@@ -196,7 +195,7 @@
                 # unescape it (and any other escaped "#"'s that might be
                 # lurking in there) and otherwise leave the line alone.
 
-                pos = string.find (line, "#")
+                pos = line.find ("#")
                 if pos == -1:           # no "#" -- no comments
                     pass
 
@@ -219,11 +218,11 @@
                     #   # comment that should be ignored
                     #   there
                     # result in "hello there".
-                    if string.strip(line) == "":
+                    if line.strip () == "":
                         continue
 
                 else:                   # it's an escaped "#"
-                    line = string.replace (line, "\\#", "#")
+                    line = line.replace("\\#", "#")
 
 
             # did previous line end with a backslash? then accumulate
@@ -235,11 +234,11 @@
                     return buildup_line
 
                 if self.collapse_join:
-                    line = string.lstrip (line)
+                    line = line.lstrip ()
                 line = buildup_line + line
 
                 # careful: pay attention to line number when incrementing it
-                if type (self.current_line) is ListType:
+                if isinstance (self.current_line, list):
                     self.current_line[1] = self.current_line[1] + 1
                 else:
                     self.current_line = [self.current_line,
@@ -250,7 +249,7 @@
                     return None
 
                 # still have to be careful about incrementing the line number!
-                if type (self.current_line) is ListType:
+                if isinstance (self.current_line, list):
                     self.current_line = self.current_line[1] + 1
                 else:
                     self.current_line = self.current_line + 1
@@ -259,11 +258,11 @@
             # strip whitespace however the client wants (leading and
             # trailing, or one or the other, or neither)
             if self.lstrip_ws and self.rstrip_ws:
-                line = string.strip (line)
+                line = line.strip ()
             elif self.lstrip_ws:
-                line = string.lstrip (line)
+                line = line.lstrip ()
             elif self.rstrip_ws:
-                line = string.rstrip (line)
+                line = line.rstrip ()
 
             # blank line (whether we rstrip'ed or not)? skip to next line
             # if appropriate
@@ -313,7 +312,7 @@
   continues on next line
 """
     # result 1: no fancy options
-    result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
+    result1 = map (lambda x: x + "\n", test_data.split ("\n")[0:-1])
 
     # result 2: just strip comments
     result2 = ["\n",
@@ -340,7 +339,7 @@
 
     def test_input (count, description, file, expected_result):
         result = file.readlines ()
-        # result = string.join (result, '')
+        # result = ''.join (result)
         if result == expected_result:
             print("ok %d (%s)" % (count, description))
         else:

Modified: python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/unixccompiler.py	Wed Jul 11 15:40:56 2007
@@ -16,7 +16,6 @@
 __revision__ = "$Id$"
 
 import os, sys
-from types import StringType, NoneType
 from copy import copy
 
 from distutils import sysconfig
@@ -212,7 +211,7 @@
 
         lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
                                    libraries)
-        if type(output_dir) not in (StringType, NoneType):
+        if not isinstance(output_dir, (str, type(None))):
             raise TypeError, "'output_dir' must be a string or None"
         if output_dir is not None:
             output_filename = os.path.join(output_dir, output_filename)

Modified: python/branches/p3yk-noslice/Lib/distutils/util.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/util.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/util.py	Wed Jul 11 15:40:56 2007
@@ -42,10 +42,9 @@
 
     # Convert the OS name to lowercase, remove '/' characters
     # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
-    osname = string.lower(osname)
-    osname = string.replace(osname, '/', '')
-    machine = string.replace(machine, ' ', '_')
-    machine = string.replace(machine, '/', '-')
+    osname = osname.lower().replace('/', '')
+    machine = machine.replace(' ', '_')
+    machine = machine.replace('/', '-')
 
     if osname[:5] == "linux":
         # At least on Linux/Intel, 'machine' is the processor --
@@ -139,7 +138,7 @@
     if pathname[-1] == '/':
         raise ValueError, "path '%s' cannot end with '/'" % pathname
 
-    paths = string.split(pathname, '/')
+    paths = pathname.split('/')
     while '.' in paths:
         paths.remove('.')
     if not paths:
@@ -178,7 +177,7 @@
             return os.path.join(new_root, pathname)
         else:
             # Chop off volume name from start of path
-            elements = string.split(pathname, ":", 1)
+            elements = pathname.split(":", 1)
             pathname = ":" + elements[1]
             return os.path.join(new_root, pathname)
 
@@ -281,7 +280,7 @@
     # bit of a brain-bender to get it working right, though...
     if _wordchars_re is None: _init_regex()
 
-    s = string.strip(s)
+    s = s.strip()
     words = []
     pos = 0
 
@@ -294,7 +293,7 @@
 
         if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
             words.append(s[:end])       # we definitely have a word delimiter
-            s = string.lstrip(s[end:])
+            s = s[end:].lstrip()
             pos = 0
 
         elif s[end] == '\\':            # preserve whatever is being escaped;
@@ -354,7 +353,7 @@
     are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
     'val' is anything else.
     """
-    val = string.lower(val)
+    val = val.lower()
     if val in ('y', 'yes', 't', 'true', 'on', '1'):
         return 1
     elif val in ('n', 'no', 'f', 'false', 'off', '0'):
@@ -445,7 +444,7 @@
             #if prefix:
             #    prefix = os.path.abspath(prefix)
 
-            script.write(string.join(map(repr, py_files), ",\n") + "]\n")
+            script.write(",\n".join(map(repr, py_files)) + "]\n")
             script.write("""
 byte_compile(files, optimize=%r, force=%r,
              prefix=%r, base_dir=%r,
@@ -507,7 +506,6 @@
     """Return a version of the string escaped for inclusion in an
     RFC-822 header, by ensuring there are 8 spaces space after each newline.
     """
-    lines = string.split(header, '\n')
-    lines = map(string.strip, lines)
-    header = string.join(lines, '\n' + 8*' ')
-    return header
+    lines = [x.strip() for x in header.split('\n')]
+    sep = '\n' + 8*' '
+    return sep.join(lines)

Modified: python/branches/p3yk-noslice/Lib/distutils/version.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/version.py	(original)
+++ python/branches/p3yk-noslice/Lib/distutils/version.py	Wed Jul 11 15:40:56 2007
@@ -26,8 +26,7 @@
     of the same class, thus must follow the same rules)
 """
 
-import string, re
-from types import StringType
+import re
 
 class Version:
     """Abstract base class for version numbering classes.  Just provides
@@ -147,12 +146,12 @@
             match.group(1, 2, 4, 5, 6)
 
         if patch:
-            self.version = tuple(map(string.atoi, [major, minor, patch]))
+            self.version = tuple(map(int, [major, minor, patch]))
         else:
-            self.version = tuple(map(string.atoi, [major, minor]) + [0])
+            self.version = tuple(map(int, [major, minor])) + (0,)
 
         if prerelease:
-            self.prerelease = (prerelease[0], string.atoi(prerelease_num))
+            self.prerelease = (prerelease[0], int(prerelease_num))
         else:
             self.prerelease = None
 
@@ -160,9 +159,9 @@
     def __str__ (self):
 
         if self.version[2] == 0:
-            vstring = string.join(map(str, self.version[0:2]), '.')
+            vstring = '.'.join(map(str, self.version[0:2]))
         else:
-            vstring = string.join(map(str, self.version), '.')
+            vstring = '.'.join(map(str, self.version))
 
         if self.prerelease:
             vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
@@ -171,7 +170,7 @@
 
 
     def __cmp__ (self, other):
-        if isinstance(other, StringType):
+        if isinstance(other, str):
             other = StrictVersion(other)
 
         compare = cmp(self.version, other.version)
@@ -327,7 +326,7 @@
 
 
     def __cmp__ (self, other):
-        if isinstance(other, StringType):
+        if isinstance(other, str):
             other = LooseVersion(other)
 
         return cmp(self.version, other.version)

Modified: python/branches/p3yk-noslice/Lib/doctest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/doctest.py	(original)
+++ python/branches/p3yk-noslice/Lib/doctest.py	Wed Jul 11 15:40:56 2007
@@ -831,7 +831,7 @@
         if module is None:
             return True
         elif inspect.isfunction(object):
-            return module.__dict__ is object.func_globals
+            return module.__dict__ is object.__globals__
         elif inspect.isclass(object):
             return module.__name__ == object.__module__
         elif inspect.getmodule(object) is not None:
@@ -969,7 +969,7 @@
 
         # Find the line number for functions & methods.
         if inspect.ismethod(obj): obj = obj.im_func
-        if inspect.isfunction(obj): obj = obj.func_code
+        if inspect.isfunction(obj): obj = obj.__code__
         if inspect.istraceback(obj): obj = obj.tb_frame
         if inspect.isframe(obj): obj = obj.f_code
         if inspect.iscode(obj):
@@ -2610,14 +2610,14 @@
             "ellipsis": r"""
                 If the ellipsis flag is used, then '...' can be used to
                 elide substrings in the desired output:
-                    >>> print(range(1000)) #doctest: +ELLIPSIS
+                    >>> print(list(range(1000))) #doctest: +ELLIPSIS
                     [0, 1, 2, ..., 999]
             """,
 
             "whitespace normalization": r"""
                 If the whitespace normalization flag is used, then
                 differences in whitespace are ignored.
-                    >>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE
+                    >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE
                     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                      15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
                      27, 28, 29]
@@ -2625,8 +2625,23 @@
            }
 
 def _test():
-    r = unittest.TextTestRunner()
-    r.run(DocTestSuite())
+    testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
+    if testfiles:
+        for filename in testfiles:
+            if filename.endswith(".py"):
+                # It is a module -- insert its dir into sys.path and try to
+                # import it. If it is part of a package, that possibly won't work
+                # because of package imports.
+                dirname, filename = os.path.split(filename)
+                sys.path.insert(0, dirname)
+                m = __import__(filename[:-3])
+                del sys.path[0]
+                testmod(m)
+            else:
+                testfile(filename, module_relative=False)
+    else:
+        r = unittest.TextTestRunner()
+        r.run(DocTestSuite())
 
 if __name__ == "__main__":
     _test()

Modified: python/branches/p3yk-noslice/Lib/dumbdbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dumbdbm.py	(original)
+++ python/branches/p3yk-noslice/Lib/dumbdbm.py	Wed Jul 11 15:40:56 2007
@@ -219,7 +219,7 @@
             self._os.chmod(file, self._mode)
 
 
-def open(file, flag=None, mode=0666):
+def open(file, flag=None, mode=0o666):
     """Open the database file, filename, and return corresponding object.
 
     The flag argument, used to control how the database is opened in the
@@ -228,7 +228,7 @@
     not exist.
 
     The optional mode argument is the UNIX mode of the file, used only when
-    the database has to be created.  It defaults to octal code 0666 (and
+    the database has to be created.  It defaults to octal code 0o666 (and
     will be modified by the prevailing umask).
 
     """

Modified: python/branches/p3yk-noslice/Lib/email/_parseaddr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/_parseaddr.py	(original)
+++ python/branches/p3yk-noslice/Lib/email/_parseaddr.py	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2006 Python Software Foundation
+# Copyright (C) 2002-2007 Python Software Foundation
 # Contact: email-sig at python.org
 
 """Email address parsing code.
@@ -172,6 +172,7 @@
         self.pos = 0
         self.LWS = ' \t'
         self.CR = '\r\n'
+        self.FWS = self.LWS + self.CR
         self.atomends = self.specials + self.LWS + self.CR
         # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it
         # is obsolete syntax.  RFC 2822 requires that we recognize obsolete
@@ -418,7 +419,7 @@
         plist = []
 
         while self.pos < len(self.field):
-            if self.field[self.pos] in self.LWS:
+            if self.field[self.pos] in self.FWS:
                 self.pos += 1
             elif self.field[self.pos] == '"':
                 plist.append(self.getquote())

Modified: python/branches/p3yk-noslice/Lib/email/feedparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/feedparser.py	(original)
+++ python/branches/p3yk-noslice/Lib/email/feedparser.py	Wed Jul 11 15:40:56 2007
@@ -122,7 +122,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         line = self.readline()
         if line == '':
             raise StopIteration
@@ -138,7 +138,7 @@
         self._factory = _factory
         self._input = BufferedSubFile()
         self._msgstack = []
-        self._parse = self._parsegen().next
+        self._parse = self._parsegen().__next__
         self._cur = None
         self._last = None
         self._headersonly = False

Modified: python/branches/p3yk-noslice/Lib/email/header.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/header.py	(original)
+++ python/branches/p3yk-noslice/Lib/email/header.py	Wed Jul 11 15:40:56 2007
@@ -39,7 +39,8 @@
   \?                    # literal ?
   (?P<encoded>.*?)      # non-greedy up to the next ?= is the encoded string
   \?=                   # literal ?=
-  ''', re.VERBOSE | re.IGNORECASE)
+  (?=[ \t]|$)           # whitespace or the end of the string
+  ''', re.VERBOSE | re.IGNORECASE | re.MULTILINE)
 
 # Field name regexp, including trailing colon, but not separating whitespace,
 # according to RFC 2822.  Character range is from tilde to exclamation mark.

Modified: python/branches/p3yk-noslice/Lib/email/message.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/message.py	(original)
+++ python/branches/p3yk-noslice/Lib/email/message.py	Wed Jul 11 15:40:56 2007
@@ -238,7 +238,7 @@
             self.del_param('charset')
             self._charset = None
             return
-        if isinstance(charset, str):
+        if isinstance(charset, basestring):
             charset = email.charset.Charset(charset)
         if not isinstance(charset, email.charset.Charset):
             raise TypeError(charset)
@@ -756,7 +756,9 @@
                 charset = charset[2]
         # charset character must be in us-ascii range
         try:
-            charset = unicode(charset, 'us-ascii').encode('us-ascii')
+            if isinstance(charset, str):
+                charset = unicode(charset, 'us-ascii')
+            charset = charset.encode('us-ascii')
         except UnicodeError:
             return failobj
         # RFC 2046, $4.1.2 says charsets are not case sensitive

Modified: python/branches/p3yk-noslice/Lib/email/test/test_email.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/test/test_email.py	(original)
+++ python/branches/p3yk-noslice/Lib/email/test/test_email.py	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
-# Copyright (C) 2001-2006 Python Software Foundation
+# Copyright (C) 2001-2007 Python Software Foundation
 # Contact: email-sig at python.org
 # email package unit tests
 
@@ -501,6 +501,13 @@
         msg.set_payload(x)
         self.assertEqual(msg.get_payload(decode=True), x)
 
+    def test_get_content_charset(self):
+        msg = Message()
+        msg.set_charset('us-ascii')
+        self.assertEqual('us-ascii', msg.get_content_charset())
+        msg.set_charset(u'us-ascii')
+        self.assertEqual('us-ascii', msg.get_content_charset())
+
 
 
 # Test the email.Encoders module
@@ -1519,6 +1526,18 @@
         hu = make_header(dh).__unicode__()
         eq(hu, u'The quick brown fox jumped over the lazy dog')
 
+    def test_rfc2047_without_whitespace(self):
+        s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord'
+        dh = decode_header(s)
+        self.assertEqual(dh, [(s, None)])
+
+    def test_rfc2047_with_whitespace(self):
+        s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord'
+        dh = decode_header(s)
+        self.assertEqual(dh, [('Sm', None), ('\xf6', 'iso-8859-1'),
+                              ('rg', None), ('\xe5', 'iso-8859-1'),
+                              ('sbord', None)])
+
 
 
 # Test the MIMEMessage class
@@ -2164,6 +2183,12 @@
         # formataddr() quotes the name if there's a dot in it
         self.assertEqual(Utils.formataddr((a, b)), y)
 
+    def test_multiline_from_comment(self):
+        x = """\
+Foo
+\tBar <foo at example.com>"""
+        self.assertEqual(Utils.parseaddr(x), ('Foo Bar', 'foo at example.com'))
+
     def test_quote_dump(self):
         self.assertEqual(
             Utils.formataddr(('A Silly; Person', 'person at dom.ain')),

Modified: python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py	(original)
+++ python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
-# Copyright (C) 2001-2006 Python Software Foundation
+# Copyright (C) 2001-2007 Python Software Foundation
 # Contact: email-sig at python.org
 # email package unit tests
 
@@ -1524,6 +1524,18 @@
         hu = make_header(dh).__unicode__()
         eq(hu, u'The quick brown fox jumped over the lazy dog')
 
+    def test_rfc2047_missing_whitespace(self):
+        s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord'
+        dh = decode_header(s)
+        self.assertEqual(dh, [(s, None)])
+
+    def test_rfc2047_with_whitespace(self):
+        s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord'
+        dh = decode_header(s)
+        self.assertEqual(dh, [('Sm', None), ('\xf6', 'iso-8859-1'),
+                              ('rg', None), ('\xe5', 'iso-8859-1'),
+                              ('sbord', None)])
+
 
 
 # Test the MIMEMessage class
@@ -2170,6 +2182,12 @@
         # formataddr() quotes the name if there's a dot in it
         self.assertEqual(utils.formataddr((a, b)), y)
 
+    def test_multiline_from_comment(self):
+        x = """\
+Foo
+\tBar <foo at example.com>"""
+        self.assertEqual(utils.parseaddr(x), ('Foo Bar', 'foo at example.com'))
+
     def test_quote_dump(self):
         self.assertEqual(
             utils.formataddr(('A Silly; Person', 'person at dom.ain')),

Modified: python/branches/p3yk-noslice/Lib/encodings/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/__init__.py	(original)
+++ python/branches/p3yk-noslice/Lib/encodings/__init__.py	Wed Jul 11 15:40:56 2007
@@ -122,12 +122,12 @@
             raise CodecRegistryError,\
                  'module "%s" (%s) failed to register' % \
                   (mod.__name__, mod.__file__)
-        if not callable(entry[0]) or \
-           not callable(entry[1]) or \
-           (entry[2] is not None and not callable(entry[2])) or \
-           (entry[3] is not None and not callable(entry[3])) or \
-           (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \
-           (len(entry) > 5 and entry[5] is not None and not callable(entry[5])):
+        if not hasattr(entry[0], '__call__') or \
+           not hasattr(entry[1], '__call__') or \
+           (entry[2] is not None and not hasattr(entry[2], '__call__')) or \
+           (entry[3] is not None and not hasattr(entry[3], '__call__')) or \
+           (len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \
+           (len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')):
             raise CodecRegistryError,\
                 'incompatible codecs in module "%s" (%s)' % \
                 (mod.__name__, mod.__file__)

Modified: python/branches/p3yk-noslice/Lib/encodings/idna.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/idna.py	(original)
+++ python/branches/p3yk-noslice/Lib/encodings/idna.py	Wed Jul 11 15:40:56 2007
@@ -38,7 +38,7 @@
             raise UnicodeError("Invalid character %r" % c)
 
     # Check bidi
-    RandAL = map(stringprep.in_table_d1, label)
+    RandAL = [stringprep.in_table_d1(x) for x in label]
     for c in RandAL:
         if c:
             # There is a RandAL char in the string. Must perform further
@@ -47,7 +47,7 @@
             # This is table C.8, which was already checked
             # 2) If a string contains any RandALCat character, the string
             # MUST NOT contain any LCat character.
-            if filter(stringprep.in_table_d2, label):
+            if any(stringprep.in_table_d2(x) for x in label):
                 raise UnicodeError("Violation of BIDI requirement 2")
 
             # 3) If a string contains any RandALCat character, a

Modified: python/branches/p3yk-noslice/Lib/encodings/utf_16.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/utf_16.py	(original)
+++ python/branches/p3yk-noslice/Lib/encodings/utf_16.py	Wed Jul 11 15:40:56 2007
@@ -34,6 +34,22 @@
         codecs.IncrementalEncoder.reset(self)
         self.encoder = None
 
+    def getstate(self):
+        # state info we return to the caller:
+        # 0: stream is in natural order for this platform
+        # 2: endianness hasn't been determined yet
+        # (we're never writing in unnatural order)
+        return (2 if self.encoder is None else 0)
+
+    def setstate(self, state):
+        if state:
+            self.encoder = None
+        else:
+            if sys.byteorder == 'little':
+                self.encoder = codecs.utf_16_le_encode
+            else:
+                self.encoder = codecs.utf_16_be_encode
+
 class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
     def __init__(self, errors='strict'):
         codecs.BufferedIncrementalDecoder.__init__(self, errors)
@@ -56,6 +72,35 @@
         codecs.BufferedIncrementalDecoder.reset(self)
         self.decoder = None
 
+    def getstate(self):
+        # additonal state info from the base class must be None here,
+        # as it isn't passed along to the caller
+        state = codecs.BufferedIncrementalDecoder.getstate(self)[0]
+        # additional state info we pass to the caller:
+        # 0: stream is in natural order for this platform
+        # 1: stream is in unnatural order
+        # 2: endianness hasn't been determined yet
+        if self.decoder is None:
+            return (state, 2)
+        addstate = int((sys.byteorder == "big") !=
+                       (self.decoder is codecs.utf_16_be_decode))
+        return (state, addstate)
+
+    def setstate(self, state):
+        # state[1] will be ignored by BufferedIncrementalDecoder.setstate()
+        codecs.BufferedIncrementalDecoder.setstate(self, state)
+        state = state[1]
+        if state == 0:
+            self.decoder = (codecs.utf_16_be_decode
+                            if sys.byteorder == "big"
+                            else codecs.utf_16_le_decode)
+        elif state == 1:
+            self.decoder = (codecs.utf_16_le_decode
+                            if sys.byteorder == "big"
+                            else codecs.utf_16_be_decode)
+        else:
+            self.decoder = None
+
 class StreamWriter(codecs.StreamWriter):
     def __init__(self, stream, errors='strict'):
         self.bom_written = False

Modified: python/branches/p3yk-noslice/Lib/encodings/utf_8_sig.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/utf_8_sig.py	(original)
+++ python/branches/p3yk-noslice/Lib/encodings/utf_8_sig.py	Wed Jul 11 15:40:56 2007
@@ -12,7 +12,8 @@
 ### Codec APIs
 
 def encode(input, errors='strict'):
-    return (codecs.BOM_UTF8 + codecs.utf_8_encode(input, errors)[0], len(input))
+    return (codecs.BOM_UTF8 + codecs.utf_8_encode(input, errors)[0],
+            len(input))
 
 def decode(input, errors='strict'):
     prefix = 0
@@ -25,38 +26,61 @@
 class IncrementalEncoder(codecs.IncrementalEncoder):
     def __init__(self, errors='strict'):
         codecs.IncrementalEncoder.__init__(self, errors)
-        self.first = True
+        self.first = 1
 
     def encode(self, input, final=False):
         if self.first:
-            self.first = False
-            return codecs.BOM_UTF8 + codecs.utf_8_encode(input, self.errors)[0]
+            self.first = 0
+            return codecs.BOM_UTF8 + \
+                   codecs.utf_8_encode(input, self.errors)[0]
         else:
             return codecs.utf_8_encode(input, self.errors)[0]
 
     def reset(self):
         codecs.IncrementalEncoder.reset(self)
-        self.first = True
+        self.first = 1
+
+    def getstate(self):
+        return self.first
+
+    def setstate(self, state):
+        self.first = state
 
 class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
     def __init__(self, errors='strict'):
         codecs.BufferedIncrementalDecoder.__init__(self, errors)
-        self.first = True
+        self.first = 1
 
     def _buffer_decode(self, input, errors, final):
-        if self.first and codecs.BOM_UTF8.startswith(input): # might be a BOM
+        if self.first:
             if len(input) < 3:
-                # not enough data to decide if this really is a BOM
-                # => try again on the next call
-                return (u"", 0)
-            (output, consumed) = codecs.utf_8_decode(input[3:], errors, final)
-            self.first = False
-            return (output, consumed+3)
+                if codecs.BOM_UTF8.startswith(input):
+                    # not enough data to decide if this really is a BOM
+                    # => try again on the next call
+                    return (u"", 0)
+                else:
+                    self.first = 0
+            else:
+                self.first = 0
+                if input[:3] == codecs.BOM_UTF8:
+                    (output, consumed) = \
+                       codecs.utf_8_decode(input[3:], errors, final)
+                    return (output, consumed+3)
         return codecs.utf_8_decode(input, errors, final)
 
     def reset(self):
         codecs.BufferedIncrementalDecoder.reset(self)
-        self.first = True
+        self.first = 1
+
+    def getstate(self):
+        state = codecs.BufferedIncrementalDecoder.getstate(self)
+        # state[1] must be 0 here, as it isn't passed along to the caller
+        return (state[0], self.first)
+
+    def setstate(self, state):
+        # state[1] will be ignored by BufferedIncrementalDecoder.setstate()
+        codecs.BufferedIncrementalDecoder.setstate(self, state)
+        self.first = state[1]
 
 class StreamWriter(codecs.StreamWriter):
     def reset(self):

Modified: python/branches/p3yk-noslice/Lib/encodings/uu_codec.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/uu_codec.py	(original)
+++ python/branches/p3yk-noslice/Lib/encodings/uu_codec.py	Wed Jul 11 15:40:56 2007
@@ -12,7 +12,7 @@
 
 ### Codec APIs
 
-def uu_encode(input,errors='strict',filename='<data>',mode=0666):
+def uu_encode(input,errors='strict',filename='<data>',mode=0o666):
 
     """ Encodes the object input and returns a tuple (output
         object, length consumed).
@@ -31,7 +31,7 @@
     write = outfile.write
 
     # Encode
-    write('begin %o %s\n' % (mode & 0777, filename))
+    write('begin %o %s\n' % (mode & 0o777, filename))
     chunk = read(45)
     while chunk:
         write(b2a_uu(chunk))

Modified: python/branches/p3yk-noslice/Lib/filecmp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/filecmp.py	(original)
+++ python/branches/p3yk-noslice/Lib/filecmp.py	Wed Jul 11 15:40:56 2007
@@ -132,9 +132,9 @@
     def phase1(self): # Compute common names
         a = dict(izip(imap(os.path.normcase, self.left_list), self.left_list))
         b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list))
-        self.common = map(a.__getitem__, ifilter(b.__contains__, a))
-        self.left_only = map(a.__getitem__, ifilterfalse(b.__contains__, a))
-        self.right_only = map(b.__getitem__, ifilterfalse(a.__contains__, b))
+        self.common = list(map(a.__getitem__, ifilter(b.__contains__, a)))
+        self.left_only = list(map(a.__getitem__, ifilterfalse(b.__contains__, a)))
+        self.right_only = list(map(b.__getitem__, ifilterfalse(a.__contains__, b)))
 
     def phase2(self): # Distinguish files, directories, funnies
         self.common_dirs = []

Modified: python/branches/p3yk-noslice/Lib/fileinput.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/fileinput.py	(original)
+++ python/branches/p3yk-noslice/Lib/fileinput.py	Wed Jul 11 15:40:56 2007
@@ -226,7 +226,7 @@
         self._mode = mode
         if inplace and openhook:
             raise ValueError("FileInput cannot use an opening hook in inplace mode")
-        elif openhook and not callable(openhook):
+        elif openhook and not hasattr(openhook, '__call__'):
             raise ValueError("FileInput openhook must be callable")
         self._openhook = openhook
 
@@ -240,7 +240,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         try:
             line = self._buffer[self._bufindex]
         except IndexError:
@@ -259,7 +259,7 @@
         if i != self._lineno:
             raise RuntimeError, "accessing lines out of order"
         try:
-            return self.next()
+            return self.__next__()
         except StopIteration:
             raise IndexError, "end of input reached"
 

Modified: python/branches/p3yk-noslice/Lib/formatter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/formatter.py	(original)
+++ python/branches/p3yk-noslice/Lib/formatter.py	Wed Jul 11 15:40:56 2007
@@ -228,7 +228,8 @@
             self.align = None
             self.writer.new_alignment(None)
 
-    def push_font(self, (size, i, b, tt)):
+    def push_font(self, font):
+        size, i, b, tt = font
         if self.softspace:
             self.hard_break = self.para_end = self.softspace = 0
             self.nospace = 1

Modified: python/branches/p3yk-noslice/Lib/ftplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ftplib.py	(original)
+++ python/branches/p3yk-noslice/Lib/ftplib.py	Wed Jul 11 15:40:56 2007
@@ -76,9 +76,15 @@
 
     '''An FTP client class.
 
-    To create a connection, call the class using these argument:
-            host, user, passwd, acct
-    These are all strings, and have default value ''.
+    To create a connection, call the class using these arguments:
+            host, user, passwd, acct, timeout
+
+    The first four arguments are all strings, and have default value ''.
+    timeout must be numeric and defaults to None if not passed,
+    meaning that no timeout will be set on any ftp socket(s)
+    If a timeout is passed, then this is now the default timeout for all ftp
+    socket operations for this instance.
+
     Then use self.connect() with optional host and port argument.
 
     To download a file, use ftp.retrlines('RETR ' + filename),
@@ -102,33 +108,26 @@
     # 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=''):
+    def __init__(self, host='', user='', passwd='', acct='', timeout=None):
+        self.timeout = timeout
         if host:
             self.connect(host)
-            if user: self.login(user, passwd, acct)
+            if user:
+                self.login(user, passwd, acct)
 
-    def connect(self, host = '', port = 0):
+    def connect(self, host='', port=0, timeout=None):
         '''Connect to host.  Arguments are:
-        - host: hostname to connect to (string, default previous host)
-        - port: port to connect to (integer, default previous port)'''
-        if host: self.host = host
-        if port: self.port = port
-        msg = "getaddrinfo returns an empty list"
-        for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
-            af, socktype, proto, canonname, sa = res
-            try:
-                self.sock = socket.socket(af, socktype, proto)
-                self.sock.connect(sa)
-            except socket.error as err:
-                msg = err
-                if self.sock:
-                    self.sock.close()
-                self.sock = None
-                continue
-            break
-        if not self.sock:
-            raise socket.error, msg
-        self.af = af
+         - host: hostname to connect to (string, default previous host)
+         - port: port to connect to (integer, default previous port)
+        '''
+        if host != '':
+            self.host = host
+        if port > 0:
+            self.port = port
+        if timeout is not None:
+            self.timeout = timeout
+        self.sock = socket.create_connection((self.host, self.port), self.timeout)
+        self.af = self.sock.family
         self.file = self.sock.makefile('rb')
         self.welcome = self.getresp()
         return self.welcome
@@ -320,9 +319,7 @@
         size = None
         if self.passiveserver:
             host, port = self.makepasv()
-            af, socktype, proto, canon, sa = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
-            conn = socket.socket(af, socktype, proto)
-            conn.connect(sa)
+            conn = socket.create_connection((host, port), self.timeout)
             if rest is not None:
                 self.sendcmd("REST %s" % rest)
             resp = self.sendcmd(cmd)

Modified: python/branches/p3yk-noslice/Lib/genericpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/genericpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/genericpath.py	Wed Jul 11 15:40:56 2007
@@ -70,8 +70,36 @@
     if not m: return ''
     s1 = min(m)
     s2 = max(m)
-    n = min(len(s1), len(s2))
-    for i in xrange(n):
-        if s1[i] != s2[i]:
+    for i, c in enumerate(s1):
+        if c != s2[i]:
             return s1[:i]
-    return s1[:n]
+    return s1
+
+# Split a path in root and extension.
+# The extension is everything starting at the last dot in the last
+# pathname component; the root is everything before that.
+# It is always true that root + ext == p.
+
+# Generic implementation of splitext, to be parametrized with
+# the separators
+def _splitext(p, sep, altsep, extsep):
+    """Split the extension from a pathname.
+
+    Extension is everything from the last dot to the end, ignoring
+    leading dots.  Returns "(root, ext)"; ext may be empty."""
+
+    sepIndex = p.rfind(sep)
+    if altsep:
+        altsepIndex = p.rfind(altsep)
+        sepIndex = max(sepIndex, altsepIndex)
+
+    dotIndex = p.rfind(extsep)
+    if dotIndex > sepIndex:
+        # skip all leading dots
+        filenameIndex = sepIndex + 1
+        while filenameIndex < dotIndex:
+            if p[filenameIndex] != extsep:
+                return p[:dotIndex], p[dotIndex:]
+            filenameIndex += 1
+
+    return p, ''

Modified: python/branches/p3yk-noslice/Lib/gettext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/gettext.py	(original)
+++ python/branches/p3yk-noslice/Lib/gettext.py	Wed Jul 11 15:40:56 2007
@@ -281,7 +281,7 @@
             raise IOError(0, 'Bad magic number', filename)
         # Now put all messages from the .mo file buffer into the catalog
         # dictionary.
-        for i in xrange(0, msgcount):
+        for i in range(0, msgcount):
             mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
             mend = moff + mlen
             tlen, toff = unpack(ii, buf[transidx:transidx+8])

Modified: python/branches/p3yk-noslice/Lib/glob.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/glob.py	(original)
+++ python/branches/p3yk-noslice/Lib/glob.py	Wed Jul 11 15:40:56 2007
@@ -1,8 +1,9 @@
 """Filename globbing utility."""
 
+import sys
 import os
-import fnmatch
 import re
+import fnmatch
 
 __all__ = ["glob", "iglob"]
 
@@ -48,13 +49,16 @@
 def glob1(dirname, pattern):
     if not dirname:
         dirname = os.curdir
+    if isinstance(pattern, unicode) and not isinstance(dirname, unicode):
+        dirname = unicode(dirname, sys.getfilesystemencoding() or
+                                   sys.getdefaultencoding())
     try:
         names = os.listdir(dirname)
     except os.error:
         return []
-    if pattern[0]!='.':
-        names=filter(lambda x: x[0]!='.',names)
-    return fnmatch.filter(names,pattern)
+    if pattern[0] != '.':
+        names = filter(lambda x: x[0] != '.', names)
+    return fnmatch.filter(names, pattern)
 
 def glob0(dirname, basename):
     if basename == '':

Deleted: /python/branches/p3yk-noslice/Lib/gopherlib.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/gopherlib.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,209 +0,0 @@
-"""Gopher protocol client interface."""
-
-__all__ = ["send_selector","send_query"]
-
-import warnings
-warnings.warn("the gopherlib module is deprecated", DeprecationWarning,
-              stacklevel=2)
-
-# Default selector, host and port
-DEF_SELECTOR = '1/'
-DEF_HOST     = 'gopher.micro.umn.edu'
-DEF_PORT     = 70
-
-# Recognized file types
-A_TEXT       = '0'
-A_MENU       = '1'
-A_CSO        = '2'
-A_ERROR      = '3'
-A_MACBINHEX  = '4'
-A_PCBINHEX   = '5'
-A_UUENCODED  = '6'
-A_INDEX      = '7'
-A_TELNET     = '8'
-A_BINARY     = '9'
-A_DUPLICATE  = '+'
-A_SOUND      = 's'
-A_EVENT      = 'e'
-A_CALENDAR   = 'c'
-A_HTML       = 'h'
-A_TN3270     = 'T'
-A_MIME       = 'M'
-A_IMAGE      = 'I'
-A_WHOIS      = 'w'
-A_QUERY      = 'q'
-A_GIF        = 'g'
-A_HTML       = 'h'          # HTML file
-A_WWW        = 'w'          # WWW address
-A_PLUS_IMAGE = ':'
-A_PLUS_MOVIE = ';'
-A_PLUS_SOUND = '<'
-
-
-_names = dir()
-_type_to_name_map = {}
-def type_to_name(gtype):
-    """Map all file types to strings; unknown types become TYPE='x'."""
-    global _type_to_name_map
-    if _type_to_name_map=={}:
-        for name in _names:
-            if name[:2] == 'A_':
-                _type_to_name_map[eval(name)] = name[2:]
-    if gtype in _type_to_name_map:
-        return _type_to_name_map[gtype]
-    return 'TYPE=%r' % (gtype,)
-
-# Names for characters and strings
-CRLF = '\r\n'
-TAB = '\t'
-
-def send_selector(selector, host, port = 0):
-    """Send a selector to a given host and port, return a file with the reply."""
-    import socket
-    if not port:
-        i = host.find(':')
-        if i >= 0:
-            host, port = host[:i], int(host[i+1:])
-    if not port:
-        port = DEF_PORT
-    elif type(port) == type(''):
-        port = int(port)
-    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    s.connect((host, port))
-    s.sendall(selector + CRLF)
-    s.shutdown(1)
-    return s.makefile('rb')
-
-def send_query(selector, query, host, port = 0):
-    """Send a selector and a query string."""
-    return send_selector(selector + '\t' + query, host, port)
-
-def path_to_selector(path):
-    """Takes a path as returned by urlparse and returns the appropriate selector."""
-    if path=="/":
-        return "/"
-    else:
-        return path[2:] # Cuts initial slash and data type identifier
-
-def path_to_datatype_name(path):
-    """Takes a path as returned by urlparse and maps it to a string.
-    See section 3.4 of RFC 1738 for details."""
-    if path=="/":
-        # No way to tell, although "INDEX" is likely
-        return "TYPE='unknown'"
-    else:
-        return type_to_name(path[1])
-
-# The following functions interpret the data returned by the gopher
-# server according to the expected type, e.g. textfile or directory
-
-def get_directory(f):
-    """Get a directory in the form of a list of entries."""
-    entries = []
-    while 1:
-        line = f.readline()
-        if not line:
-            print('(Unexpected EOF from server)')
-            break
-        if line[-2:] == CRLF:
-            line = line[:-2]
-        elif line[-1:] in CRLF:
-            line = line[:-1]
-        if line == '.':
-            break
-        if not line:
-            print('(Empty line from server)')
-            continue
-        gtype = line[0]
-        parts = line[1:].split(TAB)
-        if len(parts) < 4:
-            print('(Bad line from server: %r)' % (line,))
-            continue
-        if len(parts) > 4:
-            if parts[4:] != ['+']:
-                print('(Extra info from server:', end=' ')
-                print(parts[4:], ')')
-        else:
-            parts.append('')
-        parts.insert(0, gtype)
-        entries.append(parts)
-    return entries
-
-def get_textfile(f):
-    """Get a text file as a list of lines, with trailing CRLF stripped."""
-    lines = []
-    get_alt_textfile(f, lines.append)
-    return lines
-
-def get_alt_textfile(f, func):
-    """Get a text file and pass each line to a function, with trailing CRLF stripped."""
-    while 1:
-        line = f.readline()
-        if not line:
-            print('(Unexpected EOF from server)')
-            break
-        if line[-2:] == CRLF:
-            line = line[:-2]
-        elif line[-1:] in CRLF:
-            line = line[:-1]
-        if line == '.':
-            break
-        if line[:2] == '..':
-            line = line[1:]
-        func(line)
-
-def get_binary(f):
-    """Get a binary file as one solid data block."""
-    data = f.read()
-    return data
-
-def get_alt_binary(f, func, blocksize):
-    """Get a binary file and pass each block to a function."""
-    while 1:
-        data = f.read(blocksize)
-        if not data:
-            break
-        func(data)
-
-def test():
-    """Trivial test program."""
-    import sys
-    import getopt
-    opts, args = getopt.getopt(sys.argv[1:], '')
-    selector = DEF_SELECTOR
-    type = selector[0]
-    host = DEF_HOST
-    if args:
-        host = args[0]
-        args = args[1:]
-    if args:
-        type = args[0]
-        args = args[1:]
-        if len(type) > 1:
-            type, selector = type[0], type
-        else:
-            selector = ''
-            if args:
-                selector = args[0]
-                args = args[1:]
-        query = ''
-        if args:
-            query = args[0]
-            args = args[1:]
-    if type == A_INDEX:
-        f = send_query(selector, query, host)
-    else:
-        f = send_selector(selector, host)
-    if type == A_TEXT:
-        lines = get_textfile(f)
-        for item in lines: print(item)
-    elif type in (A_MENU, A_INDEX):
-        entries = get_directory(f)
-        for item in entries: print(item)
-    else:
-        data = get_binary(f)
-        print('binary data:', len(data), 'bytes:', repr(data[:100])[:40])
-
-# Run the test when run as script
-if __name__ == '__main__':
-    test()

Modified: python/branches/p3yk-noslice/Lib/gzip.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/gzip.py	(original)
+++ python/branches/p3yk-noslice/Lib/gzip.py	Wed Jul 11 15:40:56 2007
@@ -453,7 +453,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         line = self.readline()
         if line:
             return line

Modified: python/branches/p3yk-noslice/Lib/heapq.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/heapq.py	(original)
+++ python/branches/p3yk-noslice/Lib/heapq.py	Wed Jul 11 15:40:56 2007
@@ -129,7 +129,7 @@
 __all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
            'nlargest', 'nsmallest']
 
-from itertools import islice, repeat, count, imap, izip, tee
+from itertools import islice, repeat, count, izip, tee
 from operator import itemgetter, neg
 import bisect
 
@@ -173,7 +173,7 @@
     # or i < (n-1)/2.  If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
     # j-1 is the largest, which is n//2 - 1.  If n is odd = 2*j+1, this is
     # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
-    for i in reversed(xrange(n//2)):
+    for i in reversed(range(n//2)):
         _siftup(x, i)
 
 def nlargest(n, iterable):
@@ -225,7 +225,7 @@
     #    O(m) + O(n log m) comparisons.
     h = list(iterable)
     heapify(h)
-    return map(heappop, repeat(h, min(n, len(h))))
+    return list(map(heappop, repeat(h, min(n, len(h)))))
 
 # 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
 # is the index of a leaf with a possibly out-of-order value.  Restore the
@@ -311,7 +311,7 @@
 def merge(*iterables):
     '''Merge multiple sorted inputs into a single sorted output.
 
-    Similar to sorted(itertools.chain(*iterables)) but returns an iterable,
+    Similar to sorted(itertools.chain(*iterables)) but returns a generator,
     does not pull the data into memory all at once, and assumes that each of
     the input streams is already sorted (smallest to largest).
 
@@ -325,7 +325,7 @@
     h_append = h.append
     for itnum, it in enumerate(map(iter, iterables)):
         try:
-            next = it.next
+            next = it.__next__
             h_append([next(), itnum, next])
         except _StopIteration:
             pass
@@ -351,9 +351,9 @@
     Equivalent to:  sorted(iterable, key=key)[:n]
     """
     in1, in2 = tee(iterable)
-    it = izip(imap(key, in1), count(), in2)                 # decorate
+    it = izip(map(key, in1), count(), in2)                  # decorate
     result = _nsmallest(n, it)
-    return map(itemgetter(2), result)                       # undecorate
+    return list(map(itemgetter(2), result))                 # undecorate
 
 _nlargest = nlargest
 def nlargest(n, iterable, key=None):
@@ -362,9 +362,9 @@
     Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
     """
     in1, in2 = tee(iterable)
-    it = izip(imap(key, in1), imap(neg, count()), in2)      # decorate
+    it = izip(map(key, in1), map(neg, count()), in2)        # decorate
     result = _nlargest(n, it)
-    return map(itemgetter(2), result)                       # undecorate
+    return list(map(itemgetter(2), result))                 # undecorate
 
 if __name__ == "__main__":
     # Simple sanity test

Modified: python/branches/p3yk-noslice/Lib/hmac.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/hmac.py	(original)
+++ python/branches/p3yk-noslice/Lib/hmac.py	Wed Jul 11 15:40:56 2007
@@ -3,8 +3,8 @@
 Implements the HMAC algorithm as described by RFC 2104.
 """
 
-trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
-trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])
+trans_5C = "".join ([chr (x ^ 0x5C) for x in range(256)])
+trans_36 = "".join ([chr (x ^ 0x36) for x in range(256)])
 
 # The size of the digests returned by HMAC depends on the underlying
 # hashing module used.  Use digest_size from the instance of HMAC instead.
@@ -39,7 +39,7 @@
             import hashlib
             digestmod = hashlib.md5
 
-        if callable(digestmod):
+        if hasattr(digestmod, '__call__'):
             self.digest_cons = digestmod
         else:
             self.digest_cons = lambda d='': digestmod.new(d)

Modified: python/branches/p3yk-noslice/Lib/hotshot/log.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/hotshot/log.py	(original)
+++ python/branches/p3yk-noslice/Lib/hotshot/log.py	Wed Jul 11 15:40:56 2007
@@ -29,7 +29,7 @@
         self._funcmap = {}
 
         self._reader = _hotshot.logreader(logfn)
-        self._nextitem = self._reader.next
+        self._nextitem = self._reader.__next__
         self._info = self._reader.info
         if 'current-directory' in self._info:
             self.cwd = self._info['current-directory']
@@ -93,7 +93,7 @@
     # same bound method can be used as the __getitem__() method -- this
     # avoids using an additional method call which kills the performance.
 
-    def next(self, index=0):
+    def __next__(self, index=0):
         while 1:
             # This call may raise StopIteration:
             what, tdelta, fileno, lineno = self._nextitem()

Modified: python/branches/p3yk-noslice/Lib/httplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/httplib.py	(original)
+++ python/branches/p3yk-noslice/Lib/httplib.py	Wed Jul 11 15:40:56 2007
@@ -625,7 +625,8 @@
     debuglevel = 0
     strict = 0
 
-    def __init__(self, host, port=None, strict=None):
+    def __init__(self, host, port=None, strict=None, timeout=None):
+        self.timeout = timeout
         self.sock = None
         self._buffer = []
         self.__response = None
@@ -658,25 +659,8 @@
 
     def connect(self):
         """Connect to the host and port specified in __init__."""
-        msg = "getaddrinfo returns an empty list"
-        for res in socket.getaddrinfo(self.host, self.port, 0,
-                                      socket.SOCK_STREAM):
-            af, socktype, proto, canonname, sa = res
-            try:
-                self.sock = socket.socket(af, socktype, proto)
-                if self.debuglevel > 0:
-                    print("connect: (%s, %s)" % (self.host, self.port))
-                self.sock.connect(sa)
-            except socket.error as msg:
-                if self.debuglevel > 0:
-                    print('connect fail:', (self.host, self.port))
-                if self.sock:
-                    self.sock.close()
-                self.sock = None
-                continue
-            break
-        if not self.sock:
-            raise socket.error, msg
+        self.sock = socket.create_connection((self.host,self.port),
+                                             self.timeout)
 
     def close(self):
         """Close the connection to the HTTP server."""
@@ -714,7 +698,7 @@
             else:
                 self.sock.sendall(str)
         except socket.error as v:
-            if v[0] == 32:      # Broken pipe
+            if v.args[0] == 32:      # Broken pipe
                 self.close()
             raise
 
@@ -870,7 +854,7 @@
             self._send_request(method, url, body, headers)
         except socket.error as v:
             # trap 'Broken pipe' if we're allowed to automatically reconnect
-            if v[0] != 32 or not self.auto_open:
+            if v.args[0] != 32 or not self.auto_open:
                 raise
             # try one more time
             self._send_request(method, url, body, headers)
@@ -948,8 +932,8 @@
         self.__state = _CS_IDLE
 
         if response.will_close:
-            # Pass the socket to the response
-            self.sock = None
+            # this effectively passes the connection to the response
+            self.close()
         else:
             # remember this, so we can tell when it is complete
             self.__response = response
@@ -1020,17 +1004,19 @@
             try:
                 buf = self._ssl.read(self._bufsize)
             except socket.sslerror as err:
-                if (err[0] == socket.SSL_ERROR_WANT_READ
-                    or err[0] == socket.SSL_ERROR_WANT_WRITE):
+                err_type = err.args[0]
+                if (err_type == socket.SSL_ERROR_WANT_READ
+                    or err_type == socket.SSL_ERROR_WANT_WRITE):
                     continue
-                if (err[0] == socket.SSL_ERROR_ZERO_RETURN
-                    or err[0] == socket.SSL_ERROR_EOF):
+                if (err_type == socket.SSL_ERROR_ZERO_RETURN
+                    or err_type == socket.SSL_ERROR_EOF):
                     break
                 raise
             except socket.error as err:
-                if err[0] == errno.EINTR:
+                err_type = err.args[0]
+                if err_type == errno.EINTR:
                     continue
-                if err[0] == errno.EBADF:
+                if err_type == errno.EBADF:
                     # XXX socket was closed?
                     break
                 raise
@@ -1096,7 +1082,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         line = self.readline()
         if not line:
             raise StopIteration
@@ -1140,16 +1126,15 @@
     default_port = HTTPS_PORT
 
     def __init__(self, host, port=None, key_file=None, cert_file=None,
-                 strict=None):
-        HTTPConnection.__init__(self, host, port, strict)
+                 strict=None, timeout=None):
+        HTTPConnection.__init__(self, host, port, strict, timeout)
         self.key_file = key_file
         self.cert_file = cert_file
 
     def connect(self):
         "Connect to a host on a given (SSL) port."
 
-        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        sock.connect((self.host, self.port))
+        sock = socket.create_connection((self.host, self.port), self.timeout)
         ssl = socket.ssl(sock, self.key_file, self.cert_file)
         self.sock = FakeSocket(sock, ssl)
 

Modified: python/branches/p3yk-noslice/Lib/idlelib/CallTips.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/CallTips.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/CallTips.py	Wed Jul 11 15:40:56 2007
@@ -131,14 +131,14 @@
     arg_text = ""
     if ob is not None:
         arg_offset = 0
-        if type(ob) in (types.ClassType, types.TypeType):
+        if isinstance(ob, type):
             # Look for the highest __init__ in the class chain.
             fob = _find_constructor(ob)
             if fob is None:
                 fob = lambda: None
             else:
                 arg_offset = 1
-        elif type(ob)==types.MethodType:
+        elif isinstace(ob, types.MethodType):
             # bit of a hack for methods - turn it into a function
             # but we drop the "self" param.
             fob = ob.im_func
@@ -146,16 +146,16 @@
         else:
             fob = ob
         # Try to build one for Python defined functions
-        if type(fob) in [types.FunctionType, types.LambdaType]:
-            argcount = fob.func_code.co_argcount
-            real_args = fob.func_code.co_varnames[arg_offset:argcount]
-            defaults = fob.func_defaults or []
+        if isinstance(fob, (types.FunctionType, types.LambdaType)):
+            argcount = fob.__code__.co_argcount
+            real_args = fob.__code__.co_varnames[arg_offset:argcount]
+            defaults = fob.__defaults__ or []
             defaults = list(map(lambda name: "=%s" % repr(name), defaults))
             defaults = [""] * (len(real_args) - len(defaults)) + defaults
             items = map(lambda arg, dflt: arg + dflt, real_args, defaults)
-            if fob.func_code.co_flags & 0x4:
+            if fob.__code__.co_flags & 0x4:
                 items.append("...")
-            if fob.func_code.co_flags & 0x8:
+            if fob.__code__.co_flags & 0x8:
                 items.append("***")
             arg_text = ", ".join(items)
             arg_text = "(%s)" % re.sub("\.\d+", "<tuple>", arg_text)
@@ -183,7 +183,6 @@
     def t4(*args): "(...)"
     def t5(a, *args): "(a, ...)"
     def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
-    def t7((a, b), c, (d, e)): "(<tuple>, c, <tuple>)"
 
     class TC(object):
         "(ai=None, ...)"
@@ -194,7 +193,6 @@
         def t4(self, *args): "(...)"
         def t5(self, ai, *args): "(ai, ...)"
         def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)"
-        def t7(self, (ai, b), c, (d, e)): "(<tuple>, c, <tuple>)"
 
     def test(tests):
         ct = CallTips()
@@ -215,7 +213,7 @@
         print("%d of %d tests failed" % (len(failed), len(tests)))
 
     tc = TC()
-    tests = (t1, t2, t3, t4, t5, t6, t7,
-             TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7)
+    tests = (t1, t2, t3, t4, t5, t6,
+             TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6)
 
     test(tests)

Modified: python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py	Wed Jul 11 15:40:56 2007
@@ -117,7 +117,7 @@
         lastindent = INFINITY
         # For a line to be interesting, it must begin with a block opening
         # keyword, and have less indentation than lastindent.
-        for linenum in xrange(new_topvisible, stopline-1, -1):
+        for linenum in range(new_topvisible, stopline-1, -1):
             indent, text, opener = self.get_line_info(linenum)
             if indent < lastindent:
                 lastindent = indent

Modified: python/branches/p3yk-noslice/Lib/idlelib/Debugger.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/Debugger.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/Debugger.py	Wed Jul 11 15:40:56 2007
@@ -253,7 +253,8 @@
         if self.vsource.get():
             self.sync_source_line()
 
-    def show_frame(self, (frame, lineno)):
+    def show_frame(self, stackitem):
+        frame, lineno = stackitem
         self.frame = frame
         self.show_variables()
 
@@ -348,8 +349,7 @@
             funcname = code.co_name
             import linecache
             sourceline = linecache.getline(filename, lineno)
-            import string
-            sourceline = string.strip(sourceline)
+            sourceline = sourceline.strip()
             if funcname in ("?", "", None):
                 item = "%s, line %d: %s" % (modname, lineno, sourceline)
             else:

Modified: python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py	Wed Jul 11 15:40:56 2007
@@ -31,7 +31,6 @@
 
 import sys
 import os
-import string
 import re
 import Tkinter
 
@@ -244,7 +243,7 @@
     """
     if not sequence or sequence[0] != '<' or sequence[-1] != '>':
         return None
-    words = string.split(sequence[1:-1], '-')
+    words = '-'.split(sequence[1:-1])
 
     modifiers = 0
     while words and words[0] in _modifier_names:
@@ -351,6 +350,8 @@
                     triplets.append(triplet)
 
         def event_delete(self, virtual, *sequences):
+            if virtual not in self.__eventinfo:
+                return
             func, triplets = self.__eventinfo[virtual]
             for seq in sequences:
                 triplet = _parse_sequence(seq)

Modified: python/branches/p3yk-noslice/Lib/idlelib/ObjectBrowser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/ObjectBrowser.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/ObjectBrowser.py	Wed Jul 11 15:40:56 2007
@@ -57,15 +57,6 @@
             sublist.append(item)
         return sublist
 
-class InstanceTreeItem(ObjectTreeItem):
-    def IsExpandable(self):
-        return True
-    def GetSubList(self):
-        sublist = ObjectTreeItem.GetSubList(self)
-        sublist.insert(0,
-            make_objecttreeitem("__class__ =", self.object.__class__))
-        return sublist
-
 class ClassTreeItem(ObjectTreeItem):
     def IsExpandable(self):
         return True
@@ -110,18 +101,14 @@
             pass
         return keys
 
-from types import *
-
 dispatch = {
-    IntType: AtomicObjectTreeItem,
-    LongType: AtomicObjectTreeItem,
-    FloatType: AtomicObjectTreeItem,
-    StringType: AtomicObjectTreeItem,
-    TupleType: SequenceTreeItem,
-    ListType: SequenceTreeItem,
-    DictType: DictTreeItem,
-    InstanceType: InstanceTreeItem,
-    ClassType: ClassTreeItem,
+    int: AtomicObjectTreeItem,
+    float: AtomicObjectTreeItem,
+    str: AtomicObjectTreeItem,
+    tuple: SequenceTreeItem,
+    list: SequenceTreeItem,
+    dict: DictTreeItem,
+    type: ClassTreeItem,
 }
 
 def make_objecttreeitem(labeltext, object, setfunction=None):

Modified: python/branches/p3yk-noslice/Lib/idlelib/PyShell.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/PyShell.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/PyShell.py	Wed Jul 11 15:40:56 2007
@@ -722,6 +722,7 @@
                     master=self.tkconsole.text):
                     raise
                 else:
+                    self.showtraceback()
             else:
                 raise
         except:

Modified: python/branches/p3yk-noslice/Lib/idlelib/StackViewer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/StackViewer.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/StackViewer.py	Wed Jul 11 15:40:56 2007
@@ -120,18 +120,3 @@
             item = make_objecttreeitem(key + " =", value, setfunction)
             sublist.append(item)
         return sublist
-
-
-def _test():
-    try:
-        import testcode
-        reload(testcode)
-    except:
-        sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info()
-    from Tkinter import Tk
-    root = Tk()
-    StackBrowser(None, top=root)
-    root.mainloop()
-
-if __name__ == "__main__":
-    _test()

Modified: python/branches/p3yk-noslice/Lib/idlelib/aboutDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/aboutDialog.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/aboutDialog.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,7 @@
 """
 
 from Tkinter import *
-import string, os
+import os
 import textView
 import idlever
 
@@ -70,7 +70,7 @@
         tkVer[len(tkVer)-1] = str('%.3g' % (float('.'+tkVer[len(tkVer)-1])))[2:]
         if tkVer[len(tkVer)-1] == '':
             tkVer[len(tkVer)-1] = '0'
-        tkVer = string.join(tkVer,'.')
+        tkVer = '.'.join(tkVer)
         labelTkVer = Label(frameBg, text='Tk version:  '+
                            tkVer, fg=self.fg, bg=self.bg)
         labelTkVer.grid(row=9, column=1, sticky=W, padx=2, pady=0)

Modified: python/branches/p3yk-noslice/Lib/idlelib/configDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/configDialog.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/configDialog.py	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,7 @@
 """
 from Tkinter import *
 import tkMessageBox, tkColorChooser, tkFont
-import string, copy
+import copy
 
 from configHandler import idleConf
 from dynOptionMenuWidget import DynOptionMenu
@@ -650,7 +650,7 @@
         newKeys={}
         for event in prevKeys.keys(): #add key set to changed items
             eventName=event[2:-2] #trim off the angle brackets
-            binding=string.join(prevKeys[event])
+            binding=' '.join(prevKeys[event])
             newKeys[eventName]=binding
         #handle any unsaved changes to prev key set
         if prevKeySetName in self.changedItems['keys'].keys():
@@ -677,7 +677,7 @@
         bindNames.sort()
         self.listBindings.delete(0,END)
         for bindName in bindNames:
-            key=string.join(keySet[bindName]) #make key(s) into a string
+            key=' '.join(keySet[bindName]) #make key(s) into a string
             bindName=bindName[2:-2] #trim off the angle brackets
             if keySetName in self.changedItems['keys'].keys():
                 #handle any unsaved changes to this key set
@@ -914,7 +914,7 @@
         self.changedItems['main']['HelpFiles'] = {}
         for num in range(1,len(self.userHelpList)+1):
             self.AddChangedItem('main','HelpFiles',str(num),
-                    string.join(self.userHelpList[num-1][:2],';'))
+                    ';'.join(self.userHelpList[num-1][:2]))
 
     def LoadFontCfg(self):
         ##base editor font selection list

Modified: python/branches/p3yk-noslice/Lib/idlelib/configHandler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/configHandler.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/configHandler.py	Wed Jul 11 15:40:56 2007
@@ -19,7 +19,6 @@
 """
 import os
 import sys
-import string
 import macosxSupport
 from ConfigParser import ConfigParser, NoOptionError, NoSectionError
 
@@ -632,7 +631,7 @@
                 menuItem='' #make these empty
                 helpPath='' #so value won't be added to list
             else: #config entry contains ';' as expected
-                value=string.split(value,';')
+                value=value.split(';')
                 menuItem=value[0].strip()
                 helpPath=value[1].strip()
             if menuItem and helpPath: #neither are empty strings

Modified: python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py	Wed Jul 11 15:40:56 2007
@@ -163,7 +163,7 @@
         if finalKey:
             finalKey = self.TranslateKey(finalKey, modifiers)
             keyList.append(finalKey)
-        self.keyString.set('<' + string.join(keyList,'-') + '>')
+        self.keyString.set('<' + '-'.join(keyList) + '>')
 
     def GetModifiers(self):
         modList = [variable.get() for variable in self.modifier_vars]

Modified: python/branches/p3yk-noslice/Lib/idlelib/rpc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/rpc.py	(original)
+++ python/branches/p3yk-noslice/Lib/idlelib/rpc.py	Wed Jul 11 15:40:56 2007
@@ -287,7 +287,7 @@
     def _proxify(self, obj):
         if isinstance(obj, RemoteProxy):
             return RPCProxy(self, obj.oid)
-        if isinstance(obj, types.ListType):
+        if isinstance(obj, list):
             return map(self._proxify, obj)
         # XXX Check for other types -- not currently needed
         return obj
@@ -572,18 +572,16 @@
     # Adds names to dictionary argument 'methods'
     for name in dir(obj):
         attr = getattr(obj, name)
-        if callable(attr):
+        if hasattr(attr, '__call__'):
             methods[name] = 1
-    if type(obj) == types.InstanceType:
-        _getmethods(obj.__class__, methods)
-    if type(obj) == types.ClassType:
+    if isinstance(obj, type):
         for super in obj.__bases__:
             _getmethods(super, methods)
 
 def _getattributes(obj, attributes):
     for name in dir(obj):
         attr = getattr(obj, name)
-        if not callable(attr):
+        if not hasattr(attr, '__call__'):
             attributes[name] = 1
 
 class MethodProxy(object):

Modified: python/branches/p3yk-noslice/Lib/ihooks.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ihooks.py	(original)
+++ python/branches/p3yk-noslice/Lib/ihooks.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 the built-in function __import__ in order to change the semantics of
 the import statement, until now it has been difficult to combine the
 effect of different __import__ hacks, like loading modules from URLs
-by rimport.py, or restricted execution by rexec.py.
+by rimport.py.
 
 This module defines three new concepts:
 
@@ -45,9 +45,7 @@
 If a module importer class supports dotted names, its import_module()
 must return a different value depending on whether it is called on
 behalf of a "from ... import ..." statement or not.  (This is caused
-by the way the __import__ hook is used by the Python interpreter.)  It
-would also do wise to install a different version of reload().
-
+by the way the __import__ hook is used by the Python interpreter.)
 """
 
 
@@ -379,17 +377,14 @@
 
     def install(self):
         self.save_import_module = __builtin__.__import__
-        self.save_reload = __builtin__.reload
         if not hasattr(__builtin__, 'unload'):
             __builtin__.unload = None
         self.save_unload = __builtin__.unload
         __builtin__.__import__ = self.import_module
-        __builtin__.reload = self.reload
         __builtin__.unload = self.unload
 
     def uninstall(self):
         __builtin__.__import__ = self.save_import_module
-        __builtin__.reload = self.save_reload
         __builtin__.unload = self.save_unload
         if not __builtin__.unload:
             del __builtin__.unload

Modified: python/branches/p3yk-noslice/Lib/imaplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/imaplib.py	(original)
+++ python/branches/p3yk-noslice/Lib/imaplib.py	Wed Jul 11 15:40:56 2007
@@ -746,8 +746,10 @@
         if not command in Commands:
             raise self.error("Unknown IMAP4 UID command: %s" % command)
         if self.state not in Commands[command]:
-            raise self.error('command %s illegal in state %s'
-                                    % (command, self.state))
+            raise self.error("command %s illegal in state %s, "
+                             "only allowed in states %s" %
+                             (command, self.state,
+                              ', '.join(Commands[command])))
         name = 'UID'
         typ, dat = self._simple_command(name, command, *args)
         if command in ('SEARCH', 'SORT'):
@@ -811,8 +813,10 @@
 
         if self.state not in Commands[name]:
             self.literal = None
-            raise self.error(
-            'command %s illegal in state %s' % (name, self.state))
+            raise self.error("command %s illegal in state %s, "
+                             "only allowed in states %s" %
+                             (name, self.state,
+                              ', '.join(Commands[name])))
 
         for typ in ('OK', 'NO', 'BAD'):
             if typ in self.untagged_responses:

Modified: python/branches/p3yk-noslice/Lib/imputil.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/imputil.py	(original)
+++ python/branches/p3yk-noslice/Lib/imputil.py	Wed Jul 11 15:40:56 2007
@@ -40,15 +40,12 @@
         self.namespace = namespace
         namespace['__import__'] = self._import_hook
 
-        ### fix this
-        #namespace['reload'] = self._reload_hook
-
     def uninstall(self):
         "Restore the previous import mechanism."
         self.namespace['__import__'] = self.previous_importer
 
     def add_suffix(self, suffix, importFunc):
-        assert callable(importFunc)
+        assert hasattr(importFunc, '__call__')
         self.fs_imp.add_suffix(suffix, importFunc)
 
     ######################################################################
@@ -194,22 +191,6 @@
                 return module
         return None
 
-    def _reload_hook(self, module):
-        "Python calls this hook to reload a module."
-
-        # reloading of a module may or may not be possible (depending on the
-        # importer), but at least we can validate that it's ours to reload
-        importer = module.__dict__.get('__importer__')
-        if not importer:
-            ### oops. now what...
-            pass
-
-        # okay. it is using the imputil system, and we must delegate it, but
-        # we don't know what to do (yet)
-        ### we should blast the module dict and do another get_code(). need to
-        ### flesh this out and add proper docco...
-        raise SystemError, "reload not yet implemented"
-
 
 class Importer:
     "Base class for replacing standard import functions."
@@ -278,7 +259,10 @@
             setattr(parent, modname, module)
         return module
 
-    def _process_result(self, (ispkg, code, values), fqname):
+    def _process_result(self, result, fqname):
+        # unpack result
+        ispkg, code, values = result
+
         # did get_code() return an actual module? (rather than a code object)
         is_module = isinstance(code, _ModuleType)
 
@@ -492,7 +476,7 @@
         s = _os_stat(pathname)
     except OSError:
         return None
-    return (s.st_mode & 0170000) == 0040000
+    return (s.st_mode & 0o170000) == 0o040000
 
 def _timestamp(pathname):
     "Return the file modification time as a Long."
@@ -536,7 +520,7 @@
         self.suffixes = [ ]
 
     def add_suffix(self, suffix, importFunc):
-        assert callable(importFunc)
+        assert hasattr(importFunc, '__call__')
         self.suffixes.append((suffix, importFunc))
 
     def import_from_dir(self, dir, fqname):
@@ -674,13 +658,11 @@
 #   push MAL's mapper into sys.path[0] as a cache (hard-coded for apps)
 #
 # from Guido:
-#   need to change sys.* references for rexec environs
 #   need hook for MAL's walk-me-up import strategy, or Tim's absolute strategy
 #   watch out for sys.modules[...] is None
 #   flag to force absolute imports? (speeds _determine_import_context and
 #       checking for a relative module)
 #   insert names of archives into sys.path  (see quote below)
-#   note: reload does NOT blast module dict
 #   shift import mechanisms and policies around; provide for hooks, overrides
 #       (see quote below)
 #   add get_source stuff
@@ -714,7 +696,7 @@
 # > However, we still have a tension occurring here:
 # >
 # > 1) implementing policy in ImportManager assists in single-point policy
-# >    changes for app/rexec situations
+# >    changes for app situations
 # > 2) implementing policy in Importer assists in package-private policy
 # >    changes for normal, operating conditions
 # >

Modified: python/branches/p3yk-noslice/Lib/inspect.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/inspect.py	(original)
+++ python/branches/p3yk-noslice/Lib/inspect.py	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 """Get useful information from live Python objects.
 
 This module encapsulates the interface provided by the internal special
-attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
+attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
 It also provides some help for examining source code and class layout.
 
 Here are some of the useful functions provided by this module:
@@ -17,6 +17,7 @@
     getclasstree() - arrange classes so as to represent their hierarchy
 
     getargspec(), getargvalues() - get info about function arguments
+    getfullargspec() - same, with support for Python-3000 features
     formatargspec(), formatargvalues() - format an argument spec
     getouterframes(), getinnerframes() - get info about frames
     currentframe() - get the current stack frame
@@ -28,7 +29,7 @@
 __author__ = 'Ka-Ping Yee <ping at lfw.org>'
 __date__ = '1 Jan 2001'
 
-import sys, os, types, string, re, dis, imp, tokenize, linecache
+import sys, os, types, re, dis, imp, tokenize, linecache
 from operator import attrgetter
 
 # ----------------------------------------------------------- type-checking
@@ -46,7 +47,7 @@
     Class objects provide these attributes:
         __doc__         documentation string
         __module__      name of module in which this class was defined"""
-    return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
+    return isinstance(object, type) or hasattr(object, '__bases__')
 
 def ismethod(object):
     """Return true if the object is an instance method.
@@ -129,11 +130,11 @@
     Function objects provide these attributes:
         __doc__         documentation string
         __name__        name with which this function was defined
-        func_code       code object containing compiled function bytecode
-        func_defaults   tuple of any default values for arguments
-        func_doc        (same as __doc__)
-        func_globals    global namespace in which this function was defined
-        func_name       (same as __name__)"""
+        __code__        code object containing compiled function bytecode
+        __defaults__    tuple of any default values for arguments
+        __globals__     global namespace in which this function was defined
+        __annotations__ dict of parameter annotations
+        __kwdefaults__  dict of keyword only parameters with defaults"""
     return isinstance(object, types.FunctionType)
 
 def istraceback(object):
@@ -160,7 +161,6 @@
         f_lasti         index of last attempted instruction in bytecode
         f_lineno        current line number in Python source code
         f_locals        local namespace seen by this frame
-        f_restricted    0 or 1 if frame is in restricted execution mode
         f_trace         tracing function for this frame, or None"""
     return isinstance(object, types.FrameType)
 
@@ -300,8 +300,8 @@
 # -------------------------------------------------- source code extraction
 def indentsize(line):
     """Return the indent size, in spaces, at the start of a line of text."""
-    expline = string.expandtabs(line)
-    return len(expline) - len(string.lstrip(expline))
+    expline = line.expandtabs()
+    return len(expline) - len(expline.lstrip())
 
 def getdoc(object):
     """Get the documentation string for an object.
@@ -313,17 +313,17 @@
         doc = object.__doc__
     except AttributeError:
         return None
-    if not isinstance(doc, types.StringTypes):
+    if not isinstance(doc, basestring):
         return None
     try:
-        lines = string.split(string.expandtabs(doc), '\n')
+        lines = doc.expandtabs().split('\n')
     except UnicodeError:
         return None
     else:
         # Find minimum indentation of any non-blank lines after first line.
         margin = sys.maxint
         for line in lines[1:]:
-            content = len(string.lstrip(line))
+            content = len(line.lstrip())
             if content:
                 indent = len(line) - content
                 margin = min(margin, indent)
@@ -337,7 +337,7 @@
             lines.pop()
         while lines and not lines[0]:
             lines.pop(0)
-        return string.join(lines, '\n')
+        return '\n'.join(lines)
 
 def getfile(object):
     """Work out which source or compiled file an object was defined in."""
@@ -353,7 +353,7 @@
     if ismethod(object):
         object = object.im_func
     if isfunction(object):
-        object = object.func_code
+        object = object.__code__
     if istraceback(object):
         object = object.tb_frame
     if isframe(object):
@@ -366,8 +366,8 @@
 def getmoduleinfo(path):
     """Get the module name, suffix, mode, and module type for a given file."""
     filename = os.path.basename(path)
-    suffixes = map(lambda (suffix, mode, mtype):
-                   (-len(suffix), suffix, mode, mtype), imp.get_suffixes())
+    suffixes = [(-len(suffix), suffix, mode, mtype)
+                    for suffix, mode, mtype in imp.get_suffixes()]
     suffixes.sort() # try longest suffixes first, in case they overlap
     for neglen, suffix, mode, mtype in suffixes:
         if filename[neglen:] == suffix:
@@ -381,10 +381,10 @@
 def getsourcefile(object):
     """Return the Python source file an object was defined in, if it exists."""
     filename = getfile(object)
-    if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
+    if filename[-4:].lower() in ('.pyc', '.pyo'):
         filename = filename[:-4] + '.py'
     for suffix, mode, kind in imp.get_suffixes():
-        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
+        if 'b' in mode and filename[-len(suffix):].lower() == suffix:
             # Looks like a binary file.  We want to only return a text file.
             return None
     if os.path.exists(filename):
@@ -496,7 +496,7 @@
     if ismethod(object):
         object = object.im_func
     if isfunction(object):
-        object = object.func_code
+        object = object.__code__
     if istraceback(object):
         object = object.tb_frame
     if isframe(object):
@@ -526,36 +526,36 @@
         # Look for a comment block at the top of the file.
         start = 0
         if lines and lines[0][:2] == '#!': start = 1
-        while start < len(lines) and string.strip(lines[start]) in ('', '#'):
+        while start < len(lines) and lines[start].strip() in ('', '#'):
             start = start + 1
         if start < len(lines) and lines[start][:1] == '#':
             comments = []
             end = start
             while end < len(lines) and lines[end][:1] == '#':
-                comments.append(string.expandtabs(lines[end]))
+                comments.append(lines[end].expandtabs())
                 end = end + 1
-            return string.join(comments, '')
+            return ''.join(comments)
 
     # Look for a preceding block of comments at the same indentation.
     elif lnum > 0:
         indent = indentsize(lines[lnum])
         end = lnum - 1
-        if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
+        if end >= 0 and lines[end].lstrip()[:1] == '#' and \
             indentsize(lines[end]) == indent:
-            comments = [string.lstrip(string.expandtabs(lines[end]))]
+            comments = [lines[end].expandtabs().lstrip()]
             if end > 0:
                 end = end - 1
-                comment = string.lstrip(string.expandtabs(lines[end]))
+                comment = lines[end].expandtabs().lstrip()
                 while comment[:1] == '#' and indentsize(lines[end]) == indent:
                     comments[:0] = [comment]
                     end = end - 1
                     if end < 0: break
-                    comment = string.lstrip(string.expandtabs(lines[end]))
-            while comments and string.strip(comments[0]) == '#':
+                    comment = lines[end].expandtabs().lstrip()
+            while comments and comments[0].strip() == '#':
                 comments[:1] = []
-            while comments and string.strip(comments[-1]) == '#':
+            while comments and comments[-1].strip() == '#':
                 comments[-1:] = []
-            return string.join(comments, '')
+            return ''.join(comments)
 
 class EndOfBlock(Exception): pass
 
@@ -568,7 +568,7 @@
         self.passline = False
         self.last = 1
 
-    def tokeneater(self, type, token, (srow, scol), (erow, ecol), line):
+    def tokeneater(self, type, token, srowcol, erowcol, line):
         if not self.started:
             # look for the first "def", "class" or "lambda"
             if token in ("def", "class", "lambda"):
@@ -578,7 +578,7 @@
             self.passline = True    # skip to the end of the line
         elif type == tokenize.NEWLINE:
             self.passline = False   # stop skipping when a NEWLINE is seen
-            self.last = srow
+            self.last = srowcol[0]
             if self.islambda:       # lambdas always end at the first NEWLINE
                 raise EndOfBlock
         elif self.passline:
@@ -602,7 +602,7 @@
     """Extract the block of code at the top of the given list of lines."""
     blockfinder = BlockFinder()
     try:
-        tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
+        tokenize.tokenize(iter(lines).__next__, blockfinder.tokeneater)
     except (EndOfBlock, IndentationError):
         pass
     return lines[:blockfinder.last]
@@ -627,7 +627,7 @@
     or code object.  The source code is returned as a single string.  An
     IOError is raised if the source code cannot be retrieved."""
     lines, lnum = getsourcelines(object)
-    return string.join(lines, '')
+    return ''.join(lines)
 
 # --------------------------------------------------- class tree extraction
 def walktree(classes, children, parent):
@@ -672,9 +672,20 @@
 def getargs(co):
     """Get information about the arguments accepted by a code object.
 
-    Three things are returned: (args, varargs, varkw), where 'args' is
-    a list of argument names (possibly containing nested lists), and
-    'varargs' and 'varkw' are the names of the * and ** arguments or None."""
+    Three things are returned: (args, varargs, varkw), where
+    'args' is the list of argument names, possibly containing nested
+    lists. Keyword-only arguments are appended. 'varargs' and 'varkw'
+    are the names of the * and ** arguments or None."""
+    args, varargs, kwonlyargs, varkw = _getfullargs(co)
+    return args + kwonlyargs, varargs, varkw
+
+def _getfullargs(co):
+    """Get information about the arguments accepted by a code object.
+
+    Four things are returned: (args, varargs, kwonlyargs, varkw), where
+    'args' and 'kwonlyargs' are lists of argument names (with 'args'
+    possibly containing nested lists), and 'varargs' and 'varkw' are the
+    names of the * and ** arguments or None."""
 
     if not iscode(co):
         raise TypeError('arg is not a code object')
@@ -682,43 +693,12 @@
     code = co.co_code
     nargs = co.co_argcount
     names = co.co_varnames
+    nkwargs = co.co_kwonlyargcount
     args = list(names[:nargs])
+    kwonlyargs = list(names[nargs:nargs+nkwargs])
     step = 0
 
-    # The following acrobatics are for anonymous (tuple) arguments.
-    for i in range(nargs):
-        if args[i][:1] in ('', '.'):
-            stack, remain, count = [], [], []
-            while step < len(code):
-                op = ord(code[step])
-                step = step + 1
-                if op >= dis.HAVE_ARGUMENT:
-                    opname = dis.opname[op]
-                    value = ord(code[step]) + ord(code[step+1])*256
-                    step = step + 2
-                    if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
-                        remain.append(value)
-                        count.append(value)
-                    elif opname == 'STORE_FAST':
-                        stack.append(names[value])
-
-                        # Special case for sublists of length 1: def foo((bar))
-                        # doesn't generate the UNPACK_TUPLE bytecode, so if
-                        # `remain` is empty here, we have such a sublist.
-                        if not remain:
-                            stack[0] = [stack[0]]
-                            break
-                        else:
-                            remain[-1] = remain[-1] - 1
-                            while remain[-1] == 0:
-                                remain.pop()
-                                size = count.pop()
-                                stack[-size:] = [stack[-size:]]
-                                if not remain: break
-                                remain[-1] = remain[-1] - 1
-                            if not remain: break
-            args[i] = stack[0]
-
+    nargs += nkwargs
     varargs = None
     if co.co_flags & CO_VARARGS:
         varargs = co.co_varnames[nargs]
@@ -726,23 +706,51 @@
     varkw = None
     if co.co_flags & CO_VARKEYWORDS:
         varkw = co.co_varnames[nargs]
-    return args, varargs, varkw
+    return args, varargs, kwonlyargs, varkw
 
 def getargspec(func):
     """Get the names and default values of a function's arguments.
 
     A tuple of four things is returned: (args, varargs, varkw, defaults).
     'args' is a list of the argument names (it may contain nested lists).
+    'args' will include keyword-only argument names.
     'varargs' and 'varkw' are the names of the * and ** arguments or None.
     'defaults' is an n-tuple of the default values of the last n arguments.
+
+    Use the getfullargspec() API for Python-3000 code, as annotations
+    and keyword arguments are supported. getargspec() will raise ValueError
+    if the func has either annotations or keyword arguments.
+    """
+
+    args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
+        getfullargspec(func)
+    if kwonlyargs or ann:
+        raise ValueError, ("Function has keyword-only arguments or annotations"
+                           ", use getfullargspec() API which can support them")
+    return (args, varargs, varkw, defaults)
+
+def getfullargspec(func):
+    """Get the names and default values of a function's arguments.
+
+    A tuple of seven things is returned: (args, varargs, kwonlyargs,
+    kwonlydefaults, varkw, defaults, annotations).
+    'args' is a list of the argument names (it may contain nested lists).
+    'varargs' and 'varkw' are the names of the * and ** arguments or None.
+    'defaults' is an n-tuple of the default values of the last n arguments.
+    'kwonlyargs' is a list of keyword-only argument names.
+    'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
+    'annotations' is a dictionary mapping argument names to annotations.
+
+    The first four items in the tuple correspond to getargspec().
     """
 
     if ismethod(func):
         func = func.im_func
     if not isfunction(func):
         raise TypeError('arg is not a Python function')
-    args, varargs, varkw = getargs(func.func_code)
-    return args, varargs, varkw, func.func_defaults
+    args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__)
+    return (args, varargs, varkw, func.__defaults__,
+            kwonlyargs, func.__kwdefaults__, func.__annotations__)
 
 def getargvalues(frame):
     """Get information about arguments passed into a particular frame.
@@ -758,7 +766,7 @@
     if len(seq) == 1:
         return '(' + seq[0] + ',)'
     else:
-        return '(' + string.join(seq, ', ') + ')'
+        return '(' + ', '.join(seq) + ')'
 
 def strseq(object, convert, join=joinseq):
     """Recursively walk a sequence, stringifying each element."""
@@ -767,31 +775,66 @@
     else:
         return convert(object)
 
+def formatannotation(annotation, base_module=None):
+    if isinstance(annotation, type):
+        if annotation.__module__ in ('__builtin__', base_module):
+            return annotation.__name__
+        return annotation.__module__+'.'+annotation.__name__
+    return repr(annotation)
+
+def formatannotationrelativeto(object):
+    module = getattr(object, '__module__', None)
+    def _formatannotation(annotation):
+        return formatannotation(annotation, module)
+    return _formatannotation
+
 def formatargspec(args, varargs=None, varkw=None, defaults=None,
+                  kwonlyargs=(), kwonlydefaults={}, annotations={},
                   formatarg=str,
                   formatvarargs=lambda name: '*' + name,
                   formatvarkw=lambda name: '**' + name,
                   formatvalue=lambda value: '=' + repr(value),
+                  formatreturns=lambda text: ' -> ' + text,
+                  formatannotation=formatannotation,
                   join=joinseq):
-    """Format an argument spec from the 4 values returned by getargspec.
+    """Format an argument spec from the values returned by getargspec
+    or getfullargspec.
 
-    The first four arguments are (args, varargs, varkw, defaults).  The
-    other four arguments are the corresponding optional formatting functions
-    that are called to turn names and values into strings.  The ninth
-    argument is an optional function to format the sequence of arguments."""
+    The first seven arguments are (args, varargs, varkw, defaults,
+    kwonlyargs, kwonlydefaults, annotations).  The other five arguments
+    are the corresponding optional formatting functions that are called to
+    turn names and values into strings.  The last argument is an optional
+    function to format the sequence of arguments."""
+    def formatargandannotation(arg):
+        result = formatarg(arg)
+        if arg in annotations:
+            result += ': ' + formatannotation(annotations[arg])
+        return result
     specs = []
     if defaults:
         firstdefault = len(args) - len(defaults)
     for i in range(len(args)):
-        spec = strseq(args[i], formatarg, join)
+        spec = strseq(args[i], formatargandannotation, join)
         if defaults and i >= firstdefault:
             spec = spec + formatvalue(defaults[i - firstdefault])
         specs.append(spec)
     if varargs is not None:
-        specs.append(formatvarargs(varargs))
+        specs.append(formatvarargs(formatargandannotation(varargs)))
+    else:
+        if kwonlyargs:
+            specs.append('*')
+    if kwonlyargs:
+        for kwonlyarg in kwonlyargs:
+            spec = formatargandannotation(kwonlyarg)
+            if kwonlyarg in kwonlydefaults:
+                spec += formatvalue(kwonlydefaults[kwonlyarg])
+            specs.append(spec)
     if varkw is not None:
-        specs.append(formatvarkw(varkw))
-    return '(' + string.join(specs, ', ') + ')'
+        specs.append(formatvarkw(formatargandannotation(varkw)))
+    result = '(' + ', '.join(specs) + ')'
+    if 'return' in annotations:
+        result += formatreturns(formatannotation(annotations['return']))
+    return result
 
 def formatargvalues(args, varargs, varkw, locals,
                     formatarg=str,
@@ -815,7 +858,7 @@
         specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
     if varkw:
         specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
-    return '(' + string.join(specs, ', ') + ')'
+    return '(' + ', '.join(specs) + ')'
 
 # -------------------------------------------------- stack frame extraction
 def getframeinfo(frame, context=1):

Modified: python/branches/p3yk-noslice/Lib/keyword.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/keyword.py	(original)
+++ python/branches/p3yk-noslice/Lib/keyword.py	Wed Jul 11 15:40:56 2007
@@ -14,6 +14,9 @@
 
 kwlist = [
 #--start keywords--
+        'False',
+        'None',
+        'True',
         'and',
         'as',
         'assert',
@@ -34,10 +37,10 @@
         'in',
         'is',
         'lambda',
+        'nonlocal',
         'not',
         'or',
         'pass',
-        'print',
         'raise',
         'return',
         'try',

Modified: python/branches/p3yk-noslice/Lib/lib-tk/ScrolledText.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/ScrolledText.py	(original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/ScrolledText.py	Wed Jul 11 15:40:56 2007
@@ -21,7 +21,7 @@
             cnf = _cnfmerge((cnf, kw))
         fcnf = {}
         for k in cnf.keys():
-            if type(k) == ClassType or k == 'name':
+            if isinstace(k, type) or k == 'name':
                 fcnf[k] = cnf[k]
                 del cnf[k]
         self.frame = Frame(master, **fcnf)

Modified: python/branches/p3yk-noslice/Lib/lib-tk/Tix.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/Tix.py	(original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/Tix.py	Wed Jul 11 15:40:56 2007
@@ -390,7 +390,7 @@
         elif kw: cnf = kw
         options = ()
         for k, v in cnf.items():
-            if callable(v):
+            if hasattr(v, '__call__'):
                 v = self._register(v)
             options = options + ('-'+k, v)
         return master.tk.call(('image', 'create', imgtype,) + options)

Modified: python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py	(original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py	Wed Jul 11 15:40:56 2007
@@ -38,7 +38,6 @@
 import _tkinter # If this fails your Python may not be configured for Tk
 tkinter = _tkinter # b/w compat for export
 TclError = _tkinter.TclError
-from types import *
 from Tkconstants import *
 try:
     import MacOS; _MacOS = MacOS; del MacOS
@@ -61,11 +60,11 @@
 except AttributeError: _tkinter.deletefilehandler = None
 
 
-def _flatten(tuple):
+def _flatten(seq):
     """Internal function."""
     res = ()
-    for item in tuple:
-        if type(item) in (TupleType, ListType):
+    for item in seq:
+        if isinstance(item, (tuple, list)):
             res = res + _flatten(item)
         elif item is not None:
             res = res + (item,)
@@ -76,9 +75,9 @@
 
 def _cnfmerge(cnfs):
     """Internal function."""
-    if type(cnfs) is DictionaryType:
+    if isinstance(cnfs, dict):
         return cnfs
-    elif type(cnfs) in (NoneType, StringType):
+    elif isinstance(cnfs, (type(None), str)):
         return cnfs
     else:
         cnf = {}
@@ -867,7 +866,7 @@
         data = self.tk.split(
             self.tk.call('winfo', 'visualsavailable', self._w,
                      includeids and 'includeids' or None))
-        if type(data) is StringType:
+        if isinstance(data, str):
             data = [self.tk.split(data)]
         return map(self.__winfo_parseitem, data)
     def __winfo_parseitem(self, t):
@@ -934,7 +933,7 @@
             self.tk.call('bindtags', self._w, tagList)
     def _bind(self, what, sequence, func, add, needcleanup=1):
         """Internal function."""
-        if type(func) is StringType:
+        if isinstance(func, str):
             self.tk.call(what + (sequence, func))
         elif func:
             funcid = self._register(func, self._substitute,
@@ -1053,7 +1052,7 @@
         for k, v in cnf.items():
             if v is not None:
                 if k[-1] == '_': k = k[:-1]
-                if callable(v):
+                if hasattr(v, '__call__'):
                     v = self._register(v)
                 res = res + ('-'+k, v)
         return res
@@ -1181,7 +1180,7 @@
                     self.tk.call(_flatten((self._w, cmd)))):
                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
             return cnf
-        if type(cnf) is StringType:
+        if isinstance(cnf, str):
             x = self.tk.split(
                     self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
             return (x[0][1:],) + x[1:]
@@ -1262,7 +1261,7 @@
     bbox = grid_bbox
     def _grid_configure(self, command, index, cnf, kw):
         """Internal function."""
-        if type(cnf) is StringType and not kw:
+        if isinstance(cnf, str) and not kw:
             if cnf[-1:] == '_':
                 cnf = cnf[:-1]
             if cnf[:1] != '-':
@@ -1570,7 +1569,7 @@
         """Bind function FUNC to command NAME for this widget.
         Return the function bound to NAME if None is given. NAME could be
         e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
-        if callable(func):
+        if hasattr(func, '__call__'):
             command = self._register(func)
         else:
             command = func
@@ -1923,7 +1922,7 @@
         BaseWidget._setup(self, master, cnf)
         classes = []
         for k in cnf.keys():
-            if type(k) is ClassType:
+            if isinstance(k, type):
                 classes.append((k, cnf[k]))
                 del cnf[k]
         self.tk.call(
@@ -2136,7 +2135,7 @@
         """Internal function."""
         args = _flatten(args)
         cnf = args[-1]
-        if type(cnf) in (DictionaryType, TupleType):
+        if isinstance(cnf, (dict, tuple)):
             args = args[:-1]
         else:
             cnf = {}
@@ -3221,7 +3220,7 @@
         elif kw: cnf = kw
         options = ()
         for k, v in cnf.items():
-            if callable(v):
+            if hasattr(v, '__call__'):
                 v = self._register(v)
             options = options + ('-'+k, v)
         self.tk.call(('image', 'create', imgtype, name,) + options)
@@ -3244,7 +3243,7 @@
         for k, v in _cnfmerge(kw).items():
             if v is not None:
                 if k[-1] == '_': k = k[:-1]
-                if callable(v):
+                if hasattr(v, '__call__'):
                     v = self._register(v)
                 res = res + ('-'+k, v)
         self.tk.call((self.name, 'config') + res)
@@ -3695,7 +3694,7 @@
                          'paneconfigure', tagOrId)):
                 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
             return cnf
-        if type(cnf) == StringType and not kw:
+        if isinstance(cnf, str) and not kw:
             x = self.tk.split(self.tk.call(
                 self._w, 'paneconfigure', tagOrId, '-'+cnf))
             return (x[0][1:],) + x[1:]

Modified: python/branches/p3yk-noslice/Lib/linecache.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/linecache.py	(original)
+++ python/branches/p3yk-noslice/Lib/linecache.py	Wed Jul 11 15:40:56 2007
@@ -45,7 +45,7 @@
     (This is not checked upon each call!)"""
 
     if filename is None:
-        filenames = cache.keys()
+        filenames = list(cache.keys())
     else:
         if filename in cache:
             filenames = [filename]

Modified: python/branches/p3yk-noslice/Lib/locale.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/locale.py	(original)
+++ python/branches/p3yk-noslice/Lib/locale.py	Wed Jul 11 15:40:56 2007
@@ -19,9 +19,11 @@
 
 # Yuck:  LC_MESSAGES is non-standard:  can't tell whether it exists before
 # trying the import.  So __all__ is also fiddled at the end of the file.
-__all__ = ["setlocale","Error","localeconv","strcoll","strxfrm",
-           "format","str","atof","atoi","LC_CTYPE","LC_COLLATE",
-           "LC_TIME","LC_MONETARY","LC_NUMERIC", "LC_ALL","CHAR_MAX"]
+__all__ = ["getlocale", "getdefaultlocale", "getpreferredencoding", "Error",
+           "setlocale", "resetlocale", "localeconv", "strcoll", "strxfrm",
+           "str", "atof", "atoi", "format", "format_string", "currency",
+           "normalize", "LC_CTYPE", "LC_COLLATE", "LC_TIME", "LC_MONETARY",
+           "LC_NUMERIC", "LC_ALL", "CHAR_MAX"]
 
 try:
 

Modified: python/branches/p3yk-noslice/Lib/logging/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/logging/__init__.py	(original)
+++ python/branches/p3yk-noslice/Lib/logging/__init__.py	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
 To use, simply 'import logging' and log away!
 """
 
-import sys, os, types, time, string, cStringIO, traceback
+import sys, os, time, cStringIO, traceback
 
 try:
     import codecs
@@ -48,13 +48,15 @@
 #   Miscellaneous module data
 #---------------------------------------------------------------------------
 
+_unicode = 'unicode' in dir(__builtins__)
+
 #
 # _srcfile is used when walking the stack to check when we've got the first
 # caller stack frame.
 #
 if hasattr(sys, 'frozen'): #support for py2exe
     _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:])
-elif string.lower(__file__[-4:]) in ['.pyc', '.pyo']:
+elif __file__[-4:].lower() in ['.pyc', '.pyo']:
     _srcfile = __file__[:-4] + '.py'
 else:
     _srcfile = __file__
@@ -66,7 +68,7 @@
     try:
         raise Exception
     except:
-        return sys.exc_traceback.tb_frame.f_back
+        return sys.exc_info()[2].tb_frame.f_back
 
 if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3)
 # done filching
@@ -234,7 +236,7 @@
         # 'Value is %d' instead of 'Value is 0'.
         # For the use case of passing a dictionary, this should not be a
         # problem.
-        if args and (len(args) == 1) and args[0] and (type(args[0]) == types.DictType):
+        if args and (len(args) == 1) and args[0] and isinstance(args[0], dict):
             args = args[0]
         self.args = args
         self.levelname = getLevelName(level)
@@ -275,11 +277,11 @@
         Return the message for this LogRecord after merging any user-supplied
         arguments with the message.
         """
-        if not hasattr(types, "UnicodeType"): #if no unicode support...
+        if not _unicode: #if no unicode support...
             msg = str(self.msg)
         else:
             msg = self.msg
-            if type(msg) not in (types.UnicodeType, types.StringType):
+            if not isinstance(msg, basestring):
                 try:
                     msg = str(self.msg)
                 except UnicodeError:
@@ -398,7 +400,7 @@
         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
         s = sio.getvalue()
         sio.close()
-        if s[-1] == "\n":
+        if s[-1:] == "\n":
             s = s[:-1]
         return s
 
@@ -416,7 +418,7 @@
         formatException() and appended to the message.
         """
         record.message = record.getMessage()
-        if string.find(self._fmt,"%(asctime)") >= 0:
+        if self._fmt.find("%(asctime)") >= 0:
             record.asctime = self.formatTime(record, self.datefmt)
         s = self._fmt % record.__dict__
         if record.exc_info:
@@ -425,7 +427,7 @@
             if not record.exc_text:
                 record.exc_text = self.formatException(record.exc_info)
         if record.exc_text:
-            if s[-1] != "\n":
+            if s[-1:] != "\n":
                 s = s + "\n"
             s = s + record.exc_text
         return s
@@ -510,7 +512,7 @@
             return 1
         elif self.name == record.name:
             return 1
-        elif string.find(record.name, self.name, 0, self.nlen) != 0:
+        elif record.name.find(self.name, 0, self.nlen) != 0:
             return 0
         return (record.name[self.nlen] == ".")
 
@@ -743,7 +745,7 @@
         try:
             msg = self.format(record)
             fs = "%s\n"
-            if not hasattr(types, "UnicodeType"): #if no unicode support...
+            if not _unicode: #if no unicode support...
                 self.stream.write(fs % msg)
             else:
                 try:
@@ -896,7 +898,7 @@
         from the specified logger to the root of the logger hierarchy.
         """
         name = alogger.name
-        i = string.rfind(name, ".")
+        i = name.rfind(".")
         rv = None
         while (i > 0) and not rv:
             substr = name[:i]
@@ -909,7 +911,7 @@
                 else:
                     assert isinstance(obj, PlaceHolder)
                     obj.append(alogger)
-            i = string.rfind(name, ".", 0, i - 1)
+            i = name.rfind(".", 0, i - 1)
         if not rv:
             rv = self.root
         alogger.parent = rv
@@ -1053,7 +1055,7 @@
 
         logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
         """
-        if type(level) != types.IntType:
+        if not isinstance(level, int):
             if raiseExceptions:
                 raise TypeError, "level must be an integer"
             else:
@@ -1103,7 +1105,7 @@
         else:
             fn, lno, func = "(unknown file)", 0, "(unknown function)"
         if exc_info:
-            if type(exc_info) != types.TupleType:
+            if not isinstance(exc_info, tuple):
                 exc_info = sys.exc_info()
         record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
         self.handle(record)

Modified: python/branches/p3yk-noslice/Lib/logging/config.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/logging/config.py	(original)
+++ python/branches/p3yk-noslice/Lib/logging/config.py	Wed Jul 11 15:40:56 2007
@@ -27,7 +27,7 @@
 To use, simply 'import logging' and log away!
 """
 
-import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
+import sys, logging, logging.handlers, socket, struct, os, traceback
 
 try:
     import thread
@@ -89,7 +89,7 @@
 
 def _resolve(name):
     """Resolve a dotted name to a global object."""
-    name = string.split(name, '.')
+    name = name.split('.')
     used = name.pop(0)
     found = __import__(used)
     for n in name:
@@ -107,10 +107,10 @@
     flist = cp.get("formatters", "keys")
     if not len(flist):
         return {}
-    flist = string.split(flist, ",")
+    flist = flist.split(",")
     formatters = {}
     for form in flist:
-        sectname = "formatter_%s" % string.strip(form)
+        sectname = "formatter_%s" % form.strip()
         opts = cp.options(sectname)
         if "format" in opts:
             fs = cp.get(sectname, "format", 1)
@@ -135,11 +135,11 @@
     hlist = cp.get("handlers", "keys")
     if not len(hlist):
         return {}
-    hlist = string.split(hlist, ",")
+    hlist = hlist.split(",")
     handlers = {}
     fixups = [] #for inter-handler references
     for hand in hlist:
-        sectname = "handler_%s" % string.strip(hand)
+        sectname = "handler_%s" % hand.strip()
         klass = cp.get(sectname, "class")
         opts = cp.options(sectname)
         if "formatter" in opts:
@@ -175,8 +175,8 @@
 
     # configure the root first
     llist = cp.get("loggers", "keys")
-    llist = string.split(llist, ",")
-    llist = map(lambda x: string.strip(x), llist)
+    llist = llist.split(",")
+    llist = list(map(lambda x: x.strip(), llist))
     llist.remove("root")
     sectname = "logger_root"
     root = logging.root
@@ -189,9 +189,9 @@
         root.removeHandler(h)
     hlist = cp.get(sectname, "handlers")
     if len(hlist):
-        hlist = string.split(hlist, ",")
+        hlist = hlist.split(",")
         for hand in hlist:
-            log.addHandler(handlers[string.strip(hand)])
+            log.addHandler(handlers[hand.strip()])
 
     #and now the others...
     #we don't want to lose the existing loggers,
@@ -224,9 +224,9 @@
         logger.disabled = 0
         hlist = cp.get(sectname, "handlers")
         if len(hlist):
-            hlist = string.split(hlist, ",")
+            hlist = hlist.split(",")
             for hand in hlist:
-                logger.addHandler(handlers[string.strip(hand)])
+                logger.addHandler(handlers[hand.strip()])
 
     #Disable any old loggers. There's no point deleting
     #them as other threads may continue to hold references
@@ -289,7 +289,7 @@
                         traceback.print_exc()
                     os.remove(file)
             except socket.error as e:
-                if type(e.args) != types.TupleType:
+                if not isinstancetype(e.args, tuple):
                     raise
                 else:
                     errcode = e.args[0]

Modified: python/branches/p3yk-noslice/Lib/logging/handlers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/logging/handlers.py	(original)
+++ python/branches/p3yk-noslice/Lib/logging/handlers.py	Wed Jul 11 15:40:56 2007
@@ -27,7 +27,7 @@
 To use, simply 'import logging' and log away!
 """
 
-import sys, logging, socket, types, os, string, struct, time, glob
+import sys, logging, socket, os, struct, time, glob
 try:
     import cPickle as pickle
 except ImportError:
@@ -162,7 +162,7 @@
     """
     def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None):
         BaseRotatingHandler.__init__(self, filename, 'a', encoding)
-        self.when = string.upper(when)
+        self.when = when.upper()
         self.backupCount = backupCount
         # Calculate the real rollover interval, which is just the number of
         # seconds between rollovers.  Also set the filename suffix used when
@@ -365,12 +365,14 @@
         self.retryMax = 30.0
         self.retryFactor = 2.0
 
-    def makeSocket(self):
+    def makeSocket(self, timeout=1):
         """
         A factory method which allows subclasses to define the precise
         type of socket they want.
         """
         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        if hasattr(s, 'settimeout'):
+            s.settimeout(timeout)
         s.connect((self.host, self.port))
         return s
 
@@ -627,14 +629,15 @@
         """
         Initialize a handler.
 
-        If address is specified as a string, UNIX socket is used.
+        If address is specified as a string, a UNIX socket is used. To log to a
+        local syslogd, "SysLogHandler(address="/dev/log")" can be used.
         If facility is not specified, LOG_USER is used.
         """
         logging.Handler.__init__(self)
 
         self.address = address
         self.facility = facility
-        if type(address) == types.StringType:
+        if isinstance(address, str):
             self.unixsocket = 1
             self._connect_unixsocket(address)
         else:
@@ -666,9 +669,9 @@
         priority_names mapping dictionaries are used to convert them to
         integers.
         """
-        if type(facility) == types.StringType:
+        if isinstance(facility, str):
             facility = self.facility_names[facility]
-        if type(priority) == types.StringType:
+        if isinstance(priority, str):
             priority = self.priority_names[priority]
         return (facility << 3) | priority
 
@@ -724,24 +727,27 @@
     """
     A handler class which sends an SMTP email for each logging event.
     """
-    def __init__(self, mailhost, fromaddr, toaddrs, subject):
+    def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None):
         """
         Initialize the handler.
 
         Initialize the instance with the from and to addresses and subject
         line of the email. To specify a non-standard SMTP port, use the
-        (host, port) tuple format for the mailhost argument.
+        (host, port) tuple format for the mailhost argument. To specify
+        authentication credentials, supply a (username, password) tuple
+        for the credentials argument.
         """
         logging.Handler.__init__(self)
-        if type(mailhost) == types.TupleType:
-            host, port = mailhost
-            self.mailhost = host
-            self.mailport = port
+        if isinstance(mailhost, tuple):
+            self.mailhost, self.mailport = mailhost
+        else:
+            self.mailhost, self.mailport = mailhost, None
+        if isinstance(credentials, tuple):
+            self.username, self.password = credentials
         else:
-            self.mailhost = mailhost
-            self.mailport = None
+            self.username = None
         self.fromaddr = fromaddr
-        if type(toaddrs) == types.StringType:
+        if isinstance(toaddrs, str):
             toaddrs = [toaddrs]
         self.toaddrs = toaddrs
         self.subject = subject
@@ -792,9 +798,11 @@
             msg = self.format(record)
             msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                             self.fromaddr,
-                            string.join(self.toaddrs, ","),
+                            ",".join(self.toaddrs),
                             self.getSubject(record),
                             formatdate(), msg)
+            if self.username:
+                smtp.login(self.username, self.password)
             smtp.sendmail(self.fromaddr, self.toaddrs, msg)
             smtp.quit()
         except (KeyboardInterrupt, SystemExit):
@@ -913,7 +921,7 @@
         ("GET" or "POST")
         """
         logging.Handler.__init__(self)
-        method = string.upper(method)
+        method = method.upper()
         if method not in ["GET", "POST"]:
             raise ValueError, "method must be GET or POST"
         self.host = host
@@ -941,7 +949,7 @@
             url = self.url
             data = urllib.urlencode(self.mapLogRecord(record))
             if self.method == "GET":
-                if (string.find(url, '?') >= 0):
+                if (url.find('?') >= 0):
                     sep = '&'
                 else:
                     sep = '?'
@@ -949,7 +957,7 @@
             h.putrequest(self.method, url)
             # support multiple hosts on one IP address...
             # need to strip optional :port from host, if present
-            i = string.find(host, ":")
+            i = host.find(":")
             if i >= 0:
                 host = host[:i]
             h.putheader("Host", host)

Modified: python/branches/p3yk-noslice/Lib/macpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/macpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/macpath.py	Wed Jul 11 15:40:56 2007
@@ -2,6 +2,7 @@
 
 import os
 from stat import *
+import genericpath
 from genericpath import *
 
 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
@@ -69,17 +70,8 @@
 
 
 def splitext(p):
-    """Split a path into root and extension.
-    The extension is everything starting at the last dot in the last
-    pathname component; the root is everything before that.
-    It is always true that root + ext == p."""
-
-    i = p.rfind('.')
-    if i<=p.rfind(':'):
-        return p, ''
-    else:
-        return p[:i], p[i:]
-
+    return genericpath._splitext(p, sep, altsep, extsep)
+splitext.__doc__ = genericpath._splitext.__doc__
 
 def splitdrive(p):
     """Split a pathname into a drive specification and the rest of the

Modified: python/branches/p3yk-noslice/Lib/mailbox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mailbox.py	(original)
+++ python/branches/p3yk-noslice/Lib/mailbox.py	Wed Jul 11 15:40:56 2007
@@ -227,10 +227,10 @@
         Mailbox.__init__(self, dirname, factory, create)
         if not os.path.exists(self._path):
             if create:
-                os.mkdir(self._path, 0700)
-                os.mkdir(os.path.join(self._path, 'tmp'), 0700)
-                os.mkdir(os.path.join(self._path, 'new'), 0700)
-                os.mkdir(os.path.join(self._path, 'cur'), 0700)
+                os.mkdir(self._path, 0o700)
+                os.mkdir(os.path.join(self._path, 'tmp'), 0o700)
+                os.mkdir(os.path.join(self._path, 'new'), 0o700)
+                os.mkdir(os.path.join(self._path, 'cur'), 0o700)
             else:
                 raise NoSuchMailboxError(self._path)
         self._toc = {}
@@ -480,7 +480,7 @@
             self._onetime_keys = iter(self.keys())
         while True:
             try:
-                return self[self._onetime_keys.next()]
+                return self[next(self._onetime_keys)]
             except StopIteration:
                 return None
             except KeyError:
@@ -802,9 +802,9 @@
         Mailbox.__init__(self, path, factory, create)
         if not os.path.exists(self._path):
             if create:
-                os.mkdir(self._path, 0700)
+                os.mkdir(self._path, 0o700)
                 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
-                                 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
+                                 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
             else:
                 raise NoSuchMailboxError(self._path)
         self._locked = False

Deleted: /python/branches/p3yk-noslice/Lib/md5.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/md5.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,10 +0,0 @@
-# $Id$
-#
-#  Copyright (C) 2005   Gregory P. Smith (greg at electricrain.com)
-#  Licensed to PSF under a Contributor Agreement.
-
-from hashlib import md5
-new = md5
-
-blocksize = 1        # legacy value (wrong in any useful sense)
-digest_size = 16

Modified: python/branches/p3yk-noslice/Lib/mhlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mhlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/mhlib.py	Wed Jul 11 15:40:56 2007
@@ -67,7 +67,7 @@
 MH_PROFILE = '~/.mh_profile'
 PATH = '~/Mail'
 MH_SEQUENCES = '.mh_sequences'
-FOLDER_PROTECT = 0700
+FOLDER_PROTECT = 0o700
 
 
 # Imported modules
@@ -282,8 +282,7 @@
         for name in os.listdir(self.getfullname()):
             if match(name):
                 append(name)
-        messages = map(int, messages)
-        messages.sort()
+        messages = sorted(map(int, messages))
         if messages:
             self.last = messages[-1]
         else:
@@ -828,7 +827,7 @@
     def tolist(self):
         l = []
         for lo, hi in self.pairs:
-            m = range(lo, hi+1)
+            m = list(range(lo, hi+1))
             l = l + m
         return l
 

Modified: python/branches/p3yk-noslice/Lib/mimetypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mimetypes.py	(original)
+++ python/branches/p3yk-noslice/Lib/mimetypes.py	Wed Jul 11 15:40:56 2007
@@ -329,11 +329,13 @@
         '.tgz': '.tar.gz',
         '.taz': '.tar.gz',
         '.tz': '.tar.gz',
+        '.tbz2': '.tar.bz2',
         }
 
     encodings_map = {
         '.gz': 'gzip',
         '.Z': 'compress',
+        '.bz2': 'bzip2',
         }
 
     # Before adding new types, make sure they are either registered with IANA,

Deleted: /python/branches/p3yk-noslice/Lib/mimify.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/mimify.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,464 +0,0 @@
-#! /usr/bin/env python
-
-"""Mimification and unmimification of mail messages.
-
-Decode quoted-printable parts of a mail message or encode using
-quoted-printable.
-
-Usage:
-        mimify(input, output)
-        unmimify(input, output, decode_base64 = 0)
-to encode and decode respectively.  Input and output may be the name
-of a file or an open file object.  Only a readline() method is used
-on the input file, only a write() method is used on the output file.
-When using file names, the input and output file names may be the
-same.
-
-Interactive usage:
-        mimify.py -e [infile [outfile]]
-        mimify.py -d [infile [outfile]]
-to encode and decode respectively.  Infile defaults to standard
-input and outfile to standard output.
-"""
-
-# Configure
-MAXLEN = 200    # if lines longer than this, encode as quoted-printable
-CHARSET = 'ISO-8859-1'  # default charset for non-US-ASCII mail
-QUOTE = '> '            # string replies are quoted with
-# End configure
-
-import re
-
-__all__ = ["mimify","unmimify","mime_encode_header","mime_decode_header"]
-
-qp = re.compile('^content-transfer-encoding:\\s*quoted-printable', re.I)
-base64_re = re.compile('^content-transfer-encoding:\\s*base64', re.I)
-mp = re.compile('^content-type:.*multipart/.*boundary="?([^;"\n]*)', re.I|re.S)
-chrset = re.compile('^(content-type:.*charset=")(us-ascii|iso-8859-[0-9]+)(".*)', re.I|re.S)
-he = re.compile('^-*\n')
-mime_code = re.compile('=([0-9a-f][0-9a-f])', re.I)
-mime_head = re.compile('=\\?iso-8859-1\\?q\\?([^? \t\n]+)\\?=', re.I)
-repl = re.compile('^subject:\\s+re: ', re.I)
-
-class File:
-    """A simple fake file object that knows about limited read-ahead and
-    boundaries.  The only supported method is readline()."""
-
-    def __init__(self, file, boundary):
-        self.file = file
-        self.boundary = boundary
-        self.peek = None
-
-    def readline(self):
-        if self.peek is not None:
-            return ''
-        line = self.file.readline()
-        if not line:
-            return line
-        if self.boundary:
-            if line == self.boundary + '\n':
-                self.peek = line
-                return ''
-            if line == self.boundary + '--\n':
-                self.peek = line
-                return ''
-        return line
-
-class HeaderFile:
-    def __init__(self, file):
-        self.file = file
-        self.peek = None
-
-    def readline(self):
-        if self.peek is not None:
-            line = self.peek
-            self.peek = None
-        else:
-            line = self.file.readline()
-        if not line:
-            return line
-        if he.match(line):
-            return line
-        while 1:
-            self.peek = self.file.readline()
-            if len(self.peek) == 0 or \
-               (self.peek[0] != ' ' and self.peek[0] != '\t'):
-                return line
-            line = line + self.peek
-            self.peek = None
-
-def mime_decode(line):
-    """Decode a single line of quoted-printable text to 8bit."""
-    newline = ''
-    pos = 0
-    while 1:
-        res = mime_code.search(line, pos)
-        if res is None:
-            break
-        newline = newline + line[pos:res.start(0)] + \
-                  chr(int(res.group(1), 16))
-        pos = res.end(0)
-    return newline + line[pos:]
-
-def mime_decode_header(line):
-    """Decode a header line to 8bit."""
-    newline = ''
-    pos = 0
-    while 1:
-        res = mime_head.search(line, pos)
-        if res is None:
-            break
-        match = res.group(1)
-        # convert underscores to spaces (before =XX conversion!)
-        match = ' '.join(match.split('_'))
-        newline = newline + line[pos:res.start(0)] + mime_decode(match)
-        pos = res.end(0)
-    return newline + line[pos:]
-
-def unmimify_part(ifile, ofile, decode_base64 = 0):
-    """Convert a quoted-printable part of a MIME mail message to 8bit."""
-    multipart = None
-    quoted_printable = 0
-    is_base64 = 0
-    is_repl = 0
-    if ifile.boundary and ifile.boundary[:2] == QUOTE:
-        prefix = QUOTE
-    else:
-        prefix = ''
-
-    # read header
-    hfile = HeaderFile(ifile)
-    while 1:
-        line = hfile.readline()
-        if not line:
-            return
-        if prefix and line[:len(prefix)] == prefix:
-            line = line[len(prefix):]
-            pref = prefix
-        else:
-            pref = ''
-        line = mime_decode_header(line)
-        if qp.match(line):
-            quoted_printable = 1
-            continue        # skip this header
-        if decode_base64 and base64_re.match(line):
-            is_base64 = 1
-            continue
-        ofile.write(pref + line)
-        if not prefix and repl.match(line):
-            # we're dealing with a reply message
-            is_repl = 1
-        mp_res = mp.match(line)
-        if mp_res:
-            multipart = '--' + mp_res.group(1)
-        if he.match(line):
-            break
-    if is_repl and (quoted_printable or multipart):
-        is_repl = 0
-
-    # read body
-    while 1:
-        line = ifile.readline()
-        if not line:
-            return
-        line = re.sub(mime_head, '\\1', line)
-        if prefix and line[:len(prefix)] == prefix:
-            line = line[len(prefix):]
-            pref = prefix
-        else:
-            pref = ''
-##              if is_repl and len(line) >= 4 and line[:4] == QUOTE+'--' and line[-3:] != '--\n':
-##                      multipart = line[:-1]
-        while multipart:
-            if line == multipart + '--\n':
-                ofile.write(pref + line)
-                multipart = None
-                line = None
-                break
-            if line == multipart + '\n':
-                ofile.write(pref + line)
-                nifile = File(ifile, multipart)
-                unmimify_part(nifile, ofile, decode_base64)
-                line = nifile.peek
-                if not line:
-                    # premature end of file
-                    break
-                continue
-            # not a boundary between parts
-            break
-        if line and quoted_printable:
-            while line[-2:] == '=\n':
-                line = line[:-2]
-                newline = ifile.readline()
-                if newline[:len(QUOTE)] == QUOTE:
-                    newline = newline[len(QUOTE):]
-                line = line + newline
-            line = mime_decode(line)
-        if line and is_base64 and not pref:
-            import base64
-            line = base64.decodestring(line)
-        if line:
-            ofile.write(pref + line)
-
-def unmimify(infile, outfile, decode_base64 = 0):
-    """Convert quoted-printable parts of a MIME mail message to 8bit."""
-    if type(infile) == type(''):
-        ifile = open(infile)
-        if type(outfile) == type('') and infile == outfile:
-            import os
-            d, f = os.path.split(infile)
-            os.rename(infile, os.path.join(d, ',' + f))
-    else:
-        ifile = infile
-    if type(outfile) == type(''):
-        ofile = open(outfile, 'w')
-    else:
-        ofile = outfile
-    nifile = File(ifile, None)
-    unmimify_part(nifile, ofile, decode_base64)
-    ofile.flush()
-
-mime_char = re.compile('[=\177-\377]') # quote these chars in body
-mime_header_char = re.compile('[=?\177-\377]') # quote these in header
-
-def mime_encode(line, header):
-    """Code a single line as quoted-printable.
-    If header is set, quote some extra characters."""
-    if header:
-        reg = mime_header_char
-    else:
-        reg = mime_char
-    newline = ''
-    pos = 0
-    if len(line) >= 5 and line[:5] == 'From ':
-        # quote 'From ' at the start of a line for stupid mailers
-        newline = ('=%02x' % ord('F')).upper()
-        pos = 1
-    while 1:
-        res = reg.search(line, pos)
-        if res is None:
-            break
-        newline = newline + line[pos:res.start(0)] + \
-                  ('=%02x' % ord(res.group(0))).upper()
-        pos = res.end(0)
-    line = newline + line[pos:]
-
-    newline = ''
-    while len(line) >= 75:
-        i = 73
-        while line[i] == '=' or line[i-1] == '=':
-            i = i - 1
-        i = i + 1
-        newline = newline + line[:i] + '=\n'
-        line = line[i:]
-    return newline + line
-
-mime_header = re.compile('([ \t(]|^)([-a-zA-Z0-9_+]*[\177-\377][-a-zA-Z0-9_+\177-\377]*)(?=[ \t)]|\n)')
-
-def mime_encode_header(line):
-    """Code a single header line as quoted-printable."""
-    newline = ''
-    pos = 0
-    while 1:
-        res = mime_header.search(line, pos)
-        if res is None:
-            break
-        newline = '%s%s%s=?%s?Q?%s?=' % \
-                  (newline, line[pos:res.start(0)], res.group(1),
-                   CHARSET, mime_encode(res.group(2), 1))
-        pos = res.end(0)
-    return newline + line[pos:]
-
-mv = re.compile('^mime-version:', re.I)
-cte = re.compile('^content-transfer-encoding:', re.I)
-iso_char = re.compile('[\177-\377]')
-
-def mimify_part(ifile, ofile, is_mime):
-    """Convert an 8bit part of a MIME mail message to quoted-printable."""
-    has_cte = is_qp = is_base64 = 0
-    multipart = None
-    must_quote_body = must_quote_header = has_iso_chars = 0
-
-    header = []
-    header_end = ''
-    message = []
-    message_end = ''
-    # read header
-    hfile = HeaderFile(ifile)
-    while 1:
-        line = hfile.readline()
-        if not line:
-            break
-        if not must_quote_header and iso_char.search(line):
-            must_quote_header = 1
-        if mv.match(line):
-            is_mime = 1
-        if cte.match(line):
-            has_cte = 1
-            if qp.match(line):
-                is_qp = 1
-            elif base64_re.match(line):
-                is_base64 = 1
-        mp_res = mp.match(line)
-        if mp_res:
-            multipart = '--' + mp_res.group(1)
-        if he.match(line):
-            header_end = line
-            break
-        header.append(line)
-
-    # read body
-    while 1:
-        line = ifile.readline()
-        if not line:
-            break
-        if multipart:
-            if line == multipart + '--\n':
-                message_end = line
-                break
-            if line == multipart + '\n':
-                message_end = line
-                break
-        if is_base64:
-            message.append(line)
-            continue
-        if is_qp:
-            while line[-2:] == '=\n':
-                line = line[:-2]
-                newline = ifile.readline()
-                if newline[:len(QUOTE)] == QUOTE:
-                    newline = newline[len(QUOTE):]
-                line = line + newline
-            line = mime_decode(line)
-        message.append(line)
-        if not has_iso_chars:
-            if iso_char.search(line):
-                has_iso_chars = must_quote_body = 1
-        if not must_quote_body:
-            if len(line) > MAXLEN:
-                must_quote_body = 1
-
-    # convert and output header and body
-    for line in header:
-        if must_quote_header:
-            line = mime_encode_header(line)
-        chrset_res = chrset.match(line)
-        if chrset_res:
-            if has_iso_chars:
-                # change us-ascii into iso-8859-1
-                if chrset_res.group(2).lower() == 'us-ascii':
-                    line = '%s%s%s' % (chrset_res.group(1),
-                                       CHARSET,
-                                       chrset_res.group(3))
-            else:
-                # change iso-8859-* into us-ascii
-                line = '%sus-ascii%s' % chrset_res.group(1, 3)
-        if has_cte and cte.match(line):
-            line = 'Content-Transfer-Encoding: '
-            if is_base64:
-                line = line + 'base64\n'
-            elif must_quote_body:
-                line = line + 'quoted-printable\n'
-            else:
-                line = line + '7bit\n'
-        ofile.write(line)
-    if (must_quote_header or must_quote_body) and not is_mime:
-        ofile.write('Mime-Version: 1.0\n')
-        ofile.write('Content-Type: text/plain; ')
-        if has_iso_chars:
-            ofile.write('charset="%s"\n' % CHARSET)
-        else:
-            ofile.write('charset="us-ascii"\n')
-    if must_quote_body and not has_cte:
-        ofile.write('Content-Transfer-Encoding: quoted-printable\n')
-    ofile.write(header_end)
-
-    for line in message:
-        if must_quote_body:
-            line = mime_encode(line, 0)
-        ofile.write(line)
-    ofile.write(message_end)
-
-    line = message_end
-    while multipart:
-        if line == multipart + '--\n':
-            # read bit after the end of the last part
-            while 1:
-                line = ifile.readline()
-                if not line:
-                    return
-                if must_quote_body:
-                    line = mime_encode(line, 0)
-                ofile.write(line)
-        if line == multipart + '\n':
-            nifile = File(ifile, multipart)
-            mimify_part(nifile, ofile, 1)
-            line = nifile.peek
-            if not line:
-                # premature end of file
-                break
-            ofile.write(line)
-            continue
-        # unexpectedly no multipart separator--copy rest of file
-        while 1:
-            line = ifile.readline()
-            if not line:
-                return
-            if must_quote_body:
-                line = mime_encode(line, 0)
-            ofile.write(line)
-
-def mimify(infile, outfile):
-    """Convert 8bit parts of a MIME mail message to quoted-printable."""
-    if type(infile) == type(''):
-        ifile = open(infile)
-        if type(outfile) == type('') and infile == outfile:
-            import os
-            d, f = os.path.split(infile)
-            os.rename(infile, os.path.join(d, ',' + f))
-    else:
-        ifile = infile
-    if type(outfile) == type(''):
-        ofile = open(outfile, 'w')
-    else:
-        ofile = outfile
-    nifile = File(ifile, None)
-    mimify_part(nifile, ofile, 0)
-    ofile.flush()
-
-import sys
-if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'):
-    import getopt
-    usage = 'Usage: mimify [-l len] -[ed] [infile [outfile]]'
-
-    decode_base64 = 0
-    opts, args = getopt.getopt(sys.argv[1:], 'l:edb')
-    if len(args) not in (0, 1, 2):
-        print(usage)
-        sys.exit(1)
-    if (('-e', '') in opts) == (('-d', '') in opts) or \
-       ((('-b', '') in opts) and (('-d', '') not in opts)):
-        print(usage)
-        sys.exit(1)
-    for o, a in opts:
-        if o == '-e':
-            encode = mimify
-        elif o == '-d':
-            encode = unmimify
-        elif o == '-l':
-            try:
-                MAXLEN = int(a)
-            except (ValueError, OverflowError):
-                print(usage)
-                sys.exit(1)
-        elif o == '-b':
-            decode_base64 = 1
-    if len(args) == 0:
-        encode_args = (sys.stdin, sys.stdout)
-    elif len(args) == 1:
-        encode_args = (args[0], sys.stdout)
-    else:
-        encode_args = (args[0], args[1])
-    if decode_base64:
-        encode_args = encode_args + (decode_base64,)
-    encode(*encode_args)

Modified: python/branches/p3yk-noslice/Lib/modulefinder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/modulefinder.py	(original)
+++ python/branches/p3yk-noslice/Lib/modulefinder.py	Wed Jul 11 15:40:56 2007
@@ -279,7 +279,8 @@
         self.msgout(3, "import_module ->", m)
         return m
 
-    def load_module(self, fqname, fp, pathname, (suffix, mode, type)):
+    def load_module(self, fqname, fp, pathname, file_info):
+        suffix, mode, type = file_info
         self.msgin(2, "load_module", fqname, fp and "fp", pathname)
         if type == imp.PKG_DIRECTORY:
             m = self.load_package(fqname, pathname)

Modified: python/branches/p3yk-noslice/Lib/new.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/new.py	(original)
+++ python/branches/p3yk-noslice/Lib/new.py	Wed Jul 11 15:40:56 2007
@@ -4,13 +4,8 @@
 Objects of most types can now be created by calling the type object.
 """
 
-from types import ClassType as classobj
+classobj = type
 from types import FunctionType as function
 from types import MethodType as instancemethod
 from types import ModuleType as module
-
-# CodeType is not accessible in restricted execution mode
-try:
-    from types import CodeType as code
-except ImportError:
-    pass
+from types import CodeType as code

Modified: python/branches/p3yk-noslice/Lib/ntpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ntpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/ntpath.py	Wed Jul 11 15:40:56 2007
@@ -8,6 +8,7 @@
 import os
 import stat
 import sys
+import genericpath
 from genericpath import *
 
 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
@@ -15,7 +16,7 @@
            "getatime","getctime", "islink","exists","lexists","isdir","isfile",
            "ismount","walk","expanduser","expandvars","normpath","abspath",
            "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
-           "extsep","devnull","realpath","supports_unicode_filenames"]
+           "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
 
 # strings representing various path-related bits and pieces
 curdir = '.'
@@ -182,16 +183,8 @@
 # It is always true that root + ext == p.
 
 def splitext(p):
-    """Split the extension from a pathname.
-
-    Extension is everything from the last dot to the end.
-    Return (root, ext), either part may be empty."""
-
-    i = p.rfind('.')
-    if i<=max(p.rfind('/'), p.rfind('\\')):
-        return p, ''
-    else:
-        return p[:i], p[i:]
+    return genericpath._splitext(p, sep, altsep, extsep)
+splitext.__doc__ = genericpath._splitext.__doc__
 
 
 # Return the tail (basename) part of a path.
@@ -285,36 +278,44 @@
     i, n = 1, len(path)
     while i < n and path[i] not in '/\\':
         i = i + 1
-    if i == 1:
-        if 'HOME' in os.environ:
-            userhome = os.environ['HOME']
-        elif not 'HOMEPATH' in os.environ:
-            return path
-        else:
-            try:
-                drive = os.environ['HOMEDRIVE']
-            except KeyError:
-                drive = ''
-            userhome = join(drive, os.environ['HOMEPATH'])
-    else:
+
+    if 'HOME' in os.environ:
+        userhome = os.environ['HOME']
+    elif 'USERPROFILE' in os.environ:
+        userhome = os.environ['USERPROFILE']
+    elif not 'HOMEPATH' in os.environ:
         return path
+    else:
+        try:
+            drive = os.environ['HOMEDRIVE']
+        except KeyError:
+            drive = ''
+        userhome = join(drive, os.environ['HOMEPATH'])
+
+    if i != 1: #~user
+        userhome = join(dirname(userhome), path[1:i])
+
     return userhome + path[i:]
 
 
 # Expand paths containing shell variable substitutions.
 # The following rules apply:
 #       - no expansion within single quotes
-#       - no escape character, except for '$$' which is translated into '$'
+#       - '$$' is translated into '$'
+#       - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
 #       - ${varname} is accepted.
-#       - varnames can be made out of letters, digits and the character '_'
+#       - $varname is accepted.
+#       - %varname% is accepted.
+#       - varnames can be made out of letters, digits and the characters '_-'
+#         (though is not verifed in the ${varname} and %varname% cases)
 # XXX With COMMAND.COM you can use any characters in a variable name,
 # XXX except '^|<>='.
 
 def expandvars(path):
-    """Expand shell variables of form $var and ${var}.
+    """Expand shell variables of the forms $var, ${var} and %var%.
 
     Unknown variables are left unchanged."""
-    if '$' not in path:
+    if '$' not in path and '%' not in path:
         return path
     import string
     varchars = string.ascii_letters + string.digits + '_-'
@@ -332,6 +333,24 @@
             except ValueError:
                 res = res + path
                 index = pathlen - 1
+        elif c == '%':  # variable or '%'
+            if path[index + 1:index + 2] == '%':
+                res = res + c
+                index = index + 1
+            else:
+                path = path[index+1:]
+                pathlen = len(path)
+                try:
+                    index = path.index('%')
+                except ValueError:
+                    res = res + '%' + path
+                    index = pathlen - 1
+                else:
+                    var = path[:index]
+                    if var in os.environ:
+                        res = res + os.environ[var]
+                    else:
+                        res = res + '%' + var + '%'
         elif c == '$':  # variable or '$$'
             if path[index + 1:index + 2] == '$':
                 res = res + c
@@ -446,3 +465,29 @@
 # Win9x family and earlier have no Unicode filename support.
 supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
                               sys.getwindowsversion()[3] >= 2)
+
+def relpath(path, start=curdir):
+    """Return a relative version of a path"""
+
+    if not path:
+        raise ValueError("no path specified")
+    start_list = abspath(start).split(sep)
+    path_list = abspath(path).split(sep)
+    if start_list[0].lower() != path_list[0].lower():
+        unc_path, rest = splitunc(path)
+        unc_start, rest = splitunc(start)
+        if bool(unc_path) ^ bool(unc_start):
+            raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
+                                                                % (path, start))
+        else:
+            raise ValueError("path is on drive %s, start on drive %s"
+                                                % (path_list[0], start_list[0]))
+    # Work out how much of the filepath is shared by start and path.
+    for i in range(min(len(start_list), len(path_list))):
+        if start_list[i].lower() != path_list[i].lower():
+            break
+    else:
+        i += 1
+
+    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
+    return join(*rel_list)

Modified: python/branches/p3yk-noslice/Lib/opcode.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/opcode.py	(original)
+++ python/branches/p3yk-noslice/Lib/opcode.py	Wed Jul 11 15:40:56 2007
@@ -57,6 +57,7 @@
 
 def_op('UNARY_INVERT', 15)
 
+def_op('SET_ADD', 17)
 def_op('LIST_APPEND', 18)
 def_op('BINARY_POWER', 19)
 def_op('BINARY_MULTIPLY', 20)
@@ -84,8 +85,10 @@
 def_op('BINARY_OR', 66)
 def_op('INPLACE_POWER', 67)
 def_op('GET_ITER', 68)
+def_op('STORE_LOCALS', 69)
 
 def_op('PRINT_EXPR', 70)
+def_op('LOAD_BUILD_CLASS', 71)
 
 def_op('INPLACE_LSHIFT', 75)
 def_op('INPLACE_RSHIFT', 76)
@@ -94,13 +97,13 @@
 def_op('INPLACE_OR', 79)
 def_op('BREAK_LOOP', 80)
 def_op('WITH_CLEANUP', 81)
-def_op('LOAD_LOCALS', 82)
+
 def_op('RETURN_VALUE', 83)
 def_op('IMPORT_STAR', 84)
+def_op('MAKE_BYTES', 85)
 def_op('YIELD_VALUE', 86)
 def_op('POP_BLOCK', 87)
 def_op('END_FINALLY', 88)
-def_op('BUILD_CLASS', 89)
 
 HAVE_ARGUMENT = 90              # Opcodes from here have an argument:
 

Modified: python/branches/p3yk-noslice/Lib/optparse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/optparse.py	(original)
+++ python/branches/p3yk-noslice/Lib/optparse.py	Wed Jul 11 15:40:56 2007
@@ -67,7 +67,6 @@
 """
 
 import sys, os
-import types
 import textwrap
 
 def _repr(self):
@@ -574,7 +573,7 @@
         # Filter out None because early versions of Optik had exactly
         # one short option and one long option, either of which
         # could be None.
-        opts = filter(None, opts)
+        opts = [opt for opt in opts if opt]
         if not opts:
             raise TypeError("at least one option string must be supplied")
         return opts
@@ -641,7 +640,7 @@
             # Python 2.1 and earlier, and is short-circuited by the
             # first check on modern Pythons.)
             import __builtin__
-            if ( type(self.type) is types.TypeType or
+            if ( isinstance(self.type, type) or
                  (hasattr(self.type, "__name__") and
                   getattr(__builtin__, self.type.__name__, None) is self.type) ):
                 self.type = self.type.__name__
@@ -660,7 +659,7 @@
             if self.choices is None:
                 raise OptionError(
                     "must supply a list of choices for type 'choice'", self)
-            elif type(self.choices) not in (types.TupleType, types.ListType):
+            elif not isinstance(self.choices, (tuple, list)):
                 raise OptionError(
                     "choices must be a list of strings ('%s' supplied)"
                     % str(type(self.choices)).split("'")[1], self)
@@ -700,16 +699,16 @@
 
     def _check_callback(self):
         if self.action == "callback":
-            if not callable(self.callback):
+            if not hasattr(self.callback, '__call__'):
                 raise OptionError(
                     "callback not callable: %r" % self.callback, self)
             if (self.callback_args is not None and
-                type(self.callback_args) is not types.TupleType):
+                not isinstance(self.callback_args, tuple)):
                 raise OptionError(
                     "callback_args, if supplied, must be a tuple: not %r"
                     % self.callback_args, self)
             if (self.callback_kwargs is not None and
-                type(self.callback_kwargs) is not types.DictType):
+                not isinstance(self.callback_kwargs, dict)):
                 raise OptionError(
                     "callback_kwargs, if supplied, must be a dict: not %r"
                     % self.callback_kwargs, self)
@@ -816,14 +815,8 @@
 SUPPRESS_HELP = "SUPPRESS"+"HELP"
 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
 
-# For compatibility with Python 2.2
-try:
-    True, False
-except NameError:
-    (True, False) = (1, 0)
-
 def isbasestring(x):
-    return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
+    return isinstance(x, basestring)
 
 class Values:
 
@@ -840,7 +833,7 @@
     def __eq__(self, other):
         if isinstance(other, Values):
             return self.__dict__ == other.__dict__
-        elif isinstance(other, types.DictType):
+        elif isinstance(other, dict):
             return self.__dict__ == other
         else:
             return NotImplemented
@@ -1001,7 +994,7 @@
         """add_option(Option)
            add_option(opt_str, ..., kwarg=val, ...)
         """
-        if type(args[0]) is types.StringType:
+        if isinstance(args[0], str):
             option = self.option_class(*args, **kwargs)
         elif len(args) == 1 and not kwargs:
             option = args[0]
@@ -1312,7 +1305,7 @@
 
     def add_option_group(self, *args, **kwargs):
         # XXX lots of overlap with OptionContainer.add_option()
-        if type(args[0]) is types.StringType:
+        if isinstance(args[0], str):
             group = OptionGroup(self, *args, **kwargs)
         elif len(args) == 1 and not kwargs:
             group = args[0]

Modified: python/branches/p3yk-noslice/Lib/os.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/os.py	(original)
+++ python/branches/p3yk-noslice/Lib/os.py	Wed Jul 11 15:40:56 2007
@@ -147,8 +147,8 @@
 # Super directory utilities.
 # (Inspired by Eric Raymond; the doc strings are mostly his)
 
-def makedirs(name, mode=0777):
-    """makedirs(path [, mode=0777])
+def makedirs(name, mode=0o777):
+    """makedirs(path [, mode=0o777])
 
     Super-mkdir; create a leaf directory and all intermediate ones.
     Works like mkdir, except that any intermediate path segment (not
@@ -221,7 +221,7 @@
 
 __all__.extend(["makedirs", "removedirs", "renames"])
 
-def walk(top, topdown=True, onerror=None):
+def walk(top, topdown=True, onerror=None, followlinks=False):
     """Directory tree generator.
 
     For each directory in the directory tree rooted at top (including top
@@ -257,6 +257,10 @@
     to abort the walk.  Note that the filename is available as the
     filename attribute of the exception object.
 
+    By default, os.walk does not follow symbolic links to subdirectories on
+    systems that support them.  In order to get this functionality, set the
+    optional argument 'followlinks' to true.
+
     Caution:  if you pass a relative pathname for top, don't change the
     current working directory between resumptions of walk.  walk never
     changes the current directory, and assumes that the client doesn't
@@ -300,8 +304,8 @@
         yield top, dirs, nondirs
     for name in dirs:
         path = join(top, name)
-        if not islink(path):
-            for x in walk(path, topdown, onerror):
+        if followlinks or not islink(path):
+            for x in walk(path, topdown, onerror, followlinks):
                 yield x
     if not topdown:
         yield top, dirs, nondirs
@@ -384,13 +388,14 @@
     else:
         envpath = defpath
     PATH = envpath.split(pathsep)
-    saved_exc = None
+    last_exc = saved_exc = None
     saved_tb = None
     for dir in PATH:
         fullname = path.join(dir, file)
         try:
             func(fullname, *argrest)
         except error as e:
+            last_exc = e
             tb = sys.exc_info()[2]
             if (e.errno != ENOENT and e.errno != ENOTDIR
                 and saved_exc is None):
@@ -398,110 +403,65 @@
                 saved_tb = tb
     if saved_exc:
         raise error, saved_exc, saved_tb
-    raise error, e, tb
+    raise error, last_exc, tb
 
-# Change environ to automatically call putenv() if it exists
-try:
-    # This will fail if there's no putenv
-    putenv
-except NameError:
-    pass
+
+if name == "riscos":
+    # On RISC OS, all env access goes through getenv and putenv
+    from riscosenviron import _Environ
 else:
-    import UserDict
+    # Change environ to automatically call putenv(), unsetenv if they exist.
+    from _abcoll import MutableMapping  # Can't use collections (bootstrap)
 
-    # Fake unsetenv() for Windows
-    # not sure about os2 here but
-    # I'm guessing they are the same.
-
-    if name in ('os2', 'nt'):
-        def unsetenv(key):
-            putenv(key, "")
-
-    if name == "riscos":
-        # On RISC OS, all env access goes through getenv and putenv
-        from riscosenviron import _Environ
-    elif name in ('os2', 'nt'):  # Where Env Var Names Must Be UPPERCASE
-        # But we store them as upper case
-        class _Environ(UserDict.IterableUserDict):
-            def __init__(self, environ):
-                UserDict.UserDict.__init__(self)
-                data = self.data
-                for k, v in environ.items():
-                    data[k.upper()] = v
-            def __setitem__(self, key, item):
-                putenv(key, item)
-                self.data[key.upper()] = item
-            def __getitem__(self, key):
-                return self.data[key.upper()]
-            try:
-                unsetenv
-            except NameError:
-                def __delitem__(self, key):
-                    del self.data[key.upper()]
-            else:
-                def __delitem__(self, key):
-                    unsetenv(key)
-                    del self.data[key.upper()]
-            def __contains__(self, key):
-                return key.upper() in self.data
-            def get(self, key, failobj=None):
-                return self.data.get(key.upper(), failobj)
-            def update(self, dict=None, **kwargs):
-                if dict:
-                    try:
-                        keys = dict.keys()
-                    except AttributeError:
-                        # List of (key, value)
-                        for k, v in dict:
-                            self[k] = v
-                    else:
-                        # got keys
-                        # cannot use items(), since mappings
-                        # may not have them.
-                        for k in keys:
-                            self[k] = dict[k]
-                if kwargs:
-                    self.update(kwargs)
-            def copy(self):
-                return dict(self)
+    class _Environ(MutableMapping):
+        def __init__(self, environ, keymap, putenv, unsetenv):
+            self.keymap = keymap
+            self.putenv = putenv
+            self.unsetenv = unsetenv
+            self.data = data = {}
+            for key, value in environ.items():
+                data[keymap(key)] = value
+        def __getitem__(self, key):
+            return self.data[self.keymap(key)]
+        def __setitem__(self, key, item):
+            self.putenv(key, item)
+            self.data[self.keymap(key)] = item
+        def __delitem__(self, key):
+            self.unsetenv(key)
+            del self.data[self.keymap(key)]
+        def __iter__(self):
+            for key in self.data:
+                yield key
+        def __len__(self):
+            return len(self.data)
+        def copy(self):
+            return dict(self)
+        def setdefault(self, key, value):
+            if key not in self:
+                self[key] = value
+            return self[key]
 
+    try:
+        _putenv = putenv
+    except NameError:
+        _putenv = lambda key, value: None
+    else:
+        __all__.append("putenv")
+
+    try:
+        _unsetenv = unsetenv
+    except NameError:
+        _unsetenv = lambda key: _putenv(key, "")
+    else:
+        __all__.append("unsetenv")
+
+    if name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
+        _keymap = lambda key: key.upper()
     else:  # Where Env Var Names Can Be Mixed Case
-        class _Environ(UserDict.IterableUserDict):
-            def __init__(self, environ):
-                UserDict.UserDict.__init__(self)
-                self.data = environ
-            def __setitem__(self, key, item):
-                putenv(key, item)
-                self.data[key] = item
-            def update(self,  dict=None, **kwargs):
-                if dict:
-                    try:
-                        keys = dict.keys()
-                    except AttributeError:
-                        # List of (key, value)
-                        for k, v in dict:
-                            self[k] = v
-                    else:
-                        # got keys
-                        # cannot use items(), since mappings
-                        # may not have them.
-                        for k in keys:
-                            self[k] = dict[k]
-                if kwargs:
-                    self.update(kwargs)
-            try:
-                unsetenv
-            except NameError:
-                pass
-            else:
-                def __delitem__(self, key):
-                    unsetenv(key)
-                    del self.data[key]
-            def copy(self):
-                return dict(self)
+        _keymap = lambda key: key
 
+    environ = _Environ(environ, _keymap, _putenv, _unsetenv)
 
-    environ = _Environ(environ)
 
 def getenv(key, default=None):
     """Get an environment variable, return None if it doesn't exist.
@@ -649,48 +609,6 @@
 
     __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
 
-
-# Supply popen2 etc. (for Unix)
-if _exists("fork"):
-    if not _exists("popen2"):
-        def popen2(cmd, mode="t", bufsize=-1):
-            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
-            may be a sequence, in which case arguments will be passed directly to
-            the program without shell intervention (as with os.spawnv()).  If 'cmd'
-            is a string it will be passed to the shell (as with os.system()). If
-            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
-            file objects (child_stdin, child_stdout) are returned."""
-            import popen2
-            stdout, stdin = popen2.popen2(cmd, bufsize)
-            return stdin, stdout
-        __all__.append("popen2")
-
-    if not _exists("popen3"):
-        def popen3(cmd, mode="t", bufsize=-1):
-            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
-            may be a sequence, in which case arguments will be passed directly to
-            the program without shell intervention (as with os.spawnv()).  If 'cmd'
-            is a string it will be passed to the shell (as with os.system()). If
-            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
-            file objects (child_stdin, child_stdout, child_stderr) are returned."""
-            import popen2
-            stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
-            return stdin, stdout, stderr
-        __all__.append("popen3")
-
-    if not _exists("popen4"):
-        def popen4(cmd, mode="t", bufsize=-1):
-            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
-            may be a sequence, in which case arguments will be passed directly to
-            the program without shell intervention (as with os.spawnv()).  If 'cmd'
-            is a string it will be passed to the shell (as with os.system()). If
-            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
-            file objects (child_stdin, child_stdout_stderr) are returned."""
-            import popen2
-            stdout, stdin = popen2.popen4(cmd, bufsize)
-            return stdin, stdout
-        __all__.append("popen4")
-
 import copy_reg as _copy_reg
 
 def _make_stat_result(tup, dict):

Modified: python/branches/p3yk-noslice/Lib/pdb.doc
==============================================================================
--- python/branches/p3yk-noslice/Lib/pdb.doc	(original)
+++ python/branches/p3yk-noslice/Lib/pdb.doc	Wed Jul 11 15:40:56 2007
@@ -131,6 +131,12 @@
 r(eturn)
         Continue execution until the current function returns.
 
+run [args...]
+        Restart the debugged python program. If a string is supplied it is
+        splitted with "shlex", and the result is used as the new sys.argv.
+	History, breakpoints, actions and debugger options are preserved.
+	"restart" is an alias for "run".
+
 c(ont(inue))
         Continue execution, only stop when a breakpoint is encountered.
 

Modified: python/branches/p3yk-noslice/Lib/pdb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pdb.py	(original)
+++ python/branches/p3yk-noslice/Lib/pdb.py	Wed Jul 11 15:40:56 2007
@@ -13,6 +13,12 @@
 import re
 import pprint
 import traceback
+
+
+class Restart(Exception):
+    """Causes a debugger to be restarted for the debugged python program."""
+    pass
+
 # Create a custom safe Repr instance and increase its maxstring.
 # The default of 30 truncates error messages too easily.
 _repr = Repr()
@@ -174,13 +180,12 @@
         print('--Return--', file=self.stdout)
         self.interaction(frame, None)
 
-    def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
+    def user_exception(self, frame, exc_info):
         """This function is called if an exception occurs,
         but only if we are to stop at or just below this level."""
+        exc_type, exc_value, exc_traceback = exc_info
         frame.f_locals['__exception__'] = exc_type, exc_value
-        if type(exc_type) == type(''):
-            exc_type_name = exc_type
-        else: exc_type_name = exc_type.__name__
+        exc_type_name = exc_type.__name__
         print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
         self.interaction(frame, exc_traceback)
 
@@ -262,7 +267,7 @@
             func = getattr(self, 'do_' + cmd)
         except AttributeError:
             func = self.default
-        if func.func_name in self.commands_resuming : # one of the resuming commands.
+        if func.__name__ in self.commands_resuming : # one of the resuming commands.
             self.commands_doprompt[self.commands_bnum] = False
             self.cmdqueue = []
             return 1
@@ -347,7 +352,7 @@
                 try:
                     if hasattr(func, 'im_func'):
                         func = func.im_func
-                    code = func.func_code
+                    code = func.__code__
                     #use co_name to identify the bkpt (function names
                     #could be aliased, but co_name is invariant)
                     funcname = code.co_name
@@ -484,11 +489,16 @@
         except ValueError:
             # something went wrong
             print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
+            return
         try:
             cond = args[1]
         except:
             cond = None
-        bp = bdb.Breakpoint.bpbynumber[bpnum]
+        try:
+            bp = bdb.Breakpoint.bpbynumber[bpnum]
+        except IndexError:
+            print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
+            return
         if bp:
             bp.cond = cond
             if not cond:
@@ -503,11 +513,16 @@
         except ValueError:
             # something went wrong
             print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
+            return
         try:
             count = int(args[1].strip())
         except:
             count = 0
-        bp = bdb.Breakpoint.bpbynumber[bpnum]
+        try:
+            bp = bdb.Breakpoint.bpbynumber[bpnum]
+        except IndexError:
+            print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
+            return
         if bp:
             bp.ignore = count
             if count > 0:
@@ -601,6 +616,18 @@
         return 1
     do_n = do_next
 
+    def do_run(self, arg):
+        """Restart program by raising an exception to be caught in the main debugger
+        loop. If arguments were given, set them in sys.argv."""
+        if arg:
+            import shlex
+            argv0 = sys.argv[0:1]
+            sys.argv = shlex.split(arg)
+            sys.argv[:0] = argv0
+        raise Restart
+
+    do_restart = do_run
+
     def do_return(self, arg):
         self.set_return(self.curframe)
         return 1
@@ -759,13 +786,13 @@
             return
         code = None
         # Is it a function?
-        try: code = value.func_code
+        try: code = value.__code__
         except: pass
         if code:
             print('Function', code.co_name, file=self.stdout)
             return
         # Is it an instance method?
-        try: code = value.im_func.func_code
+        try: code = value.im_func.__code__
         except: pass
         if code:
             print('Method', code.co_name, file=self.stdout)
@@ -1005,6 +1032,15 @@
 (Pdb) global list_options; list_options = ['-l']
 (Pdb)""", file=self.stdout)
 
+    def help_run(self):
+        print("""run [args...]
+Restart the debugged python program. If a string is supplied, it is
+splitted with "shlex" and the result is used as the new sys.argv.
+History, breakpoints, actions and debugger options are preserved.
+"restart" is an alias for "run".""")
+
+    help_restart = help_run
+
     def help_quit(self):
         self.help_q()
 
@@ -1113,11 +1149,17 @@
         return None
 
     def _runscript(self, filename):
-        # Start with fresh empty copy of globals and locals and tell the script
-        # that it's being run as __main__ to avoid scripts being able to access
-        # the pdb.py namespace.
-        globals_ = {"__name__" : "__main__"}
-        locals_ = globals_
+        # The script has to run in __main__ namespace (or imports from
+        # __main__ will break).
+        #
+        # So we clear up the __main__ and set several special variables
+        # (this gets rid of pdb's globals and cleans old variables on restarts).
+        import __main__
+        __main__.__dict__.clear()
+        __main__.__dict__.update({"__name__"    : "__main__",
+                                  "__file__"    : filename,
+                                  "__builtins__": __builtins__,
+                                 })
 
         # When bdb sets tracing, a number of call and line events happens
         # BEFORE debugger even reaches user's code (and the exact sequence of
@@ -1128,7 +1170,7 @@
         self.mainpyfile = self.canonic(filename)
         self._user_requested_quit = 0
         statement = 'execfile( "%s")' % filename
-        self.run(statement, globals=globals_, locals=locals_)
+        self.run(statement)
 
 # Simplified interface
 
@@ -1197,9 +1239,8 @@
 
     # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
     # modified by the script being debugged. It's a bad idea when it was
-    # changed by the user from the command line. The best approach would be to
-    # have a "restart" command which would allow explicit specification of
-    # command line arguments.
+    # changed by the user from the command line. There is a "restart" command which
+    # allows explicit specification of command line arguments.
     pdb = Pdb()
     while 1:
         try:
@@ -1207,6 +1248,9 @@
             if pdb._user_requested_quit:
                 break
             print("The program finished and will be restarted")
+        except Restart:
+            print("Restarting", mainpyfile, "with arguments:")
+            print("\t" + " ".join(sys.argv[1:]))
         except SystemExit:
             # In most cases SystemExit does not warrant a post-mortem session.
             print("The program exited via sys.exit(). Exit status: ", end=' ')
@@ -1223,5 +1267,6 @@
 
 
 # When invoked as main program, invoke the debugger on a script
-if __name__=='__main__':
-    main()
+if __name__ == '__main__':
+    import pdb
+    pdb.main()

Modified: python/branches/p3yk-noslice/Lib/pickle.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pickle.py	(original)
+++ python/branches/p3yk-noslice/Lib/pickle.py	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
 
 __version__ = "$Revision$"       # Code version
 
-from types import *
+from types import FunctionType, BuiltinFunctionType
 from copy_reg import dispatch_table
 from copy_reg import _extension_registry, _inverted_registry, _extension_cache
 import marshal
@@ -89,11 +89,11 @@
 except ImportError:
     PyStringMap = None
 
-# UnicodeType may or may not be exported (normally imported from types)
+# unicode may or may not be exported (normally imported from types)
 try:
-    UnicodeType
+    unicode
 except NameError:
-    UnicodeType = None
+    unicode = None
 
 # Pickle opcodes.  See pickletools.py for extensive docs.  The listing
 # here is in kind-of alphabetical order of 1-character pickle code.
@@ -163,7 +163,6 @@
 
 
 __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
-del x
 
 
 # Pickling machinery
@@ -288,7 +287,7 @@
 
         # Check for a class with a custom metaclass; treat as regular class
         try:
-            issc = issubclass(t, TypeType)
+            issc = issubclass(t, type)
         except TypeError: # t is not a class (old Boost; see SF #502085)
             issc = 0
         if issc:
@@ -313,12 +312,12 @@
                                         (t.__name__, obj))
 
         # Check for string returned by reduce(), meaning "save as global"
-        if type(rv) is StringType:
+        if isinstance(rv, str):
             self.save_global(obj, rv)
             return
 
         # Assert that reduce() returned a tuple
-        if type(rv) is not TupleType:
+        if not isinstance(rv, tuple):
             raise PicklingError("%s must return string or tuple" % reduce)
 
         # Assert that it returned an appropriately sized tuple
@@ -347,11 +346,11 @@
         # This API is called by some subclasses
 
         # Assert that args is a tuple or None
-        if not isinstance(args, TupleType):
+        if not isinstance(args, tuple):
             raise PicklingError("args from reduce() should be a tuple")
 
         # Assert that func is callable
-        if not callable(func):
+        if not hasattr(func, '__call__'):
             raise PicklingError("func from reduce should be callable")
 
         save = self.save
@@ -425,7 +424,7 @@
 
     def save_none(self, obj):
         self.write(NONE)
-    dispatch[NoneType] = save_none
+    dispatch[type(None)] = save_none
 
     def save_bool(self, obj):
         if self.proto >= 2:
@@ -457,7 +456,7 @@
         # Text pickle, or int too big to fit in signed 4-byte format.
         self.write(INT + repr(obj) + '\n')
     # XXX save_int is merged into save_long
-    # dispatch[IntType] = save_int
+    # dispatch[int] = save_int
 
     def save_long(self, obj, pack=struct.pack):
         if self.bin:
@@ -488,14 +487,14 @@
                 self.write(LONG4 + pack("<i", n) + bytes)
             return
         self.write(LONG + repr(obj) + '\n')
-    dispatch[LongType] = save_long
+    dispatch[int] = save_long
 
     def save_float(self, obj, pack=struct.pack):
         if self.bin:
             self.write(BINFLOAT + pack('>d', obj))
         else:
             self.write(FLOAT + repr(obj) + '\n')
-    dispatch[FloatType] = save_float
+    dispatch[float] = save_float
 
     def save_string(self, obj, pack=struct.pack):
         if self.bin:
@@ -507,7 +506,7 @@
         else:
             self.write(STRING + repr(obj) + '\n')
         self.memoize(obj)
-    dispatch[StringType] = save_string
+    dispatch[str] = save_string
 
     def save_unicode(self, obj, pack=struct.pack):
         if self.bin:
@@ -519,9 +518,9 @@
             obj = obj.replace("\n", "\\u000a")
             self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
         self.memoize(obj)
-    dispatch[UnicodeType] = save_unicode
+    dispatch[unicode] = save_unicode
 
-    if StringType == UnicodeType:
+    if str == unicode:
         # This is true for Jython
         def save_string(self, obj, pack=struct.pack):
             unicode = obj.isunicode()
@@ -547,7 +546,7 @@
                 else:
                     self.write(STRING + repr(obj) + '\n')
             self.memoize(obj)
-        dispatch[StringType] = save_string
+        dispatch[str] = save_string
 
     def save_tuple(self, obj):
         write = self.write
@@ -600,7 +599,7 @@
         self.write(TUPLE)
         self.memoize(obj)
 
-    dispatch[TupleType] = save_tuple
+    dispatch[tuple] = save_tuple
 
     # save_empty_tuple() isn't used by anything in Python 2.3.  However, I
     # found a Pickler subclass in Zope3 that calls it, so it's not harmless
@@ -619,7 +618,7 @@
         self.memoize(obj)
         self._batch_appends(iter(obj))
 
-    dispatch[ListType] = save_list
+    dispatch[list] = save_list
 
     # Keep in synch with cPickle's BATCHSIZE.  Nothing will break if it gets
     # out of synch, though.
@@ -636,12 +635,12 @@
                 write(APPEND)
             return
 
-        r = xrange(self._BATCHSIZE)
+        r = range(self._BATCHSIZE)
         while items is not None:
             tmp = []
             for i in r:
                 try:
-                    x = items.next()
+                    x = next(items)
                     tmp.append(x)
                 except StopIteration:
                     items = None
@@ -668,8 +667,8 @@
         self.memoize(obj)
         self._batch_setitems(iter(obj.items()))
 
-    dispatch[DictionaryType] = save_dict
-    if not PyStringMap is None:
+    dispatch[dict] = save_dict
+    if PyStringMap is not None:
         dispatch[PyStringMap] = save_dict
 
     def _batch_setitems(self, items):
@@ -684,12 +683,12 @@
                 write(SETITEM)
             return
 
-        r = xrange(self._BATCHSIZE)
+        r = range(self._BATCHSIZE)
         while items is not None:
             tmp = []
             for i in r:
                 try:
-                    tmp.append(items.next())
+                    tmp.append(next(items))
                 except StopIteration:
                     items = None
                     break
@@ -747,10 +746,9 @@
         write(GLOBAL + module + '\n' + name + '\n')
         self.memoize(obj)
 
-    dispatch[ClassType] = save_global
     dispatch[FunctionType] = save_global
     dispatch[BuiltinFunctionType] = save_global
-    dispatch[TypeType] = save_global
+    dispatch[type] = save_global
 
 # Pickling helpers
 
@@ -791,7 +789,7 @@
     if func in classmap:
         return classmap[func]
 
-    for name, module in sys.modules.items():
+    for name, module in list(sys.modules.items()):
         if module is None:
             continue # skip dummy package entries
         if name != '__main__' and getattr(module, funcname, None) is func:
@@ -1025,16 +1023,11 @@
         del self.stack[k:]
         instantiated = 0
         if (not args and
-                type(klass) is ClassType and
+                isinstance(klass, type) and
                 not hasattr(klass, "__getinitargs__")):
-            try:
-                value = _EmptyClass()
-                value.__class__ = klass
-                instantiated = 1
-            except RuntimeError:
-                # In restricted execution, assignment to inst.__class__ is
-                # prohibited
-                pass
+            value = _EmptyClass()
+            value.__class__ = klass
+            instantiated = 1
         if not instantiated:
             try:
                 value = klass(*args)
@@ -1200,20 +1193,7 @@
         if isinstance(state, tuple) and len(state) == 2:
             state, slotstate = state
         if state:
-            try:
-                inst.__dict__.update(state)
-            except RuntimeError:
-                # XXX In restricted execution, the instance's __dict__
-                # is not accessible.  Use the old way of unpickling
-                # the instance variables.  This is a semantic
-                # difference when unpickling in restricted
-                # vs. unrestricted modes.
-                # Note, however, that cPickle has never tried to do the
-                # .update() business, and always uses
-                #     PyObject_SetItem(inst.__dict__, key, value) in a
-                # loop over state.items().
-                for k, v in state.items():
-                    setattr(inst, k, v)
+            inst.__dict__.update(state)
         if slotstate:
             for k, v in slotstate.items():
                 setattr(inst, k, v)

Modified: python/branches/p3yk-noslice/Lib/pickletools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pickletools.py	(original)
+++ python/branches/p3yk-noslice/Lib/pickletools.py	Wed Jul 11 15:40:56 2007
@@ -1517,7 +1517,7 @@
       opcode is followed by code to create setstate's argument, and then a
       BUILD opcode to apply  __setstate__ to that argument.
 
-      If type(callable) is not ClassType, REDUCE complains unless the
+      If not isinstance(callable, type), REDUCE complains unless the
       callable has been registered with the copy_reg module's
       safe_constructors dict, or the callable has a magic
       '__safe_for_unpickling__' attribute with a true value.  I'm not sure
@@ -1548,13 +1548,6 @@
       the object is updated via
 
           anyobject.__dict__.update(argument)
-
-      This may raise RuntimeError in restricted execution mode (which
-      disallows access to __dict__ directly); in that case, the object
-      is updated instead via
-
-          for k, v in argument.items():
-              anyobject[k] = v
       """),
 
     I(name='INST',
@@ -1580,9 +1573,6 @@
         + The argtuple is empty (markobject was at the top of the stack
           at the start).
 
-        + It's an old-style class object (the type of the class object is
-          ClassType).
-
         + The class object does not have a __getinitargs__ attribute.
 
       then we want to create an old-style class instance without invoking
@@ -1590,11 +1580,7 @@
       calling __init__() is current wisdom).  In this case, an instance of
       an old-style dummy class is created, and then we try to rebind its
       __class__ attribute to the desired class object.  If this succeeds,
-      the new instance object is pushed on the stack, and we're done.  In
-      restricted execution mode it can fail (assignment to __class__ is
-      disallowed), and I'm not really sure what happens then -- it looks
-      like the code ends up calling the class object's __init__ anyway,
-      via falling into the next case.
+      the new instance object is pushed on the stack, and we're done.
 
       Else (the argtuple is not empty, it's not an old-style class object,
       or the class object does have a __getinitargs__ attribute), the code
@@ -2050,10 +2036,10 @@
 Exercise the INST/OBJ/BUILD family.
 
 >>> import random
->>> dis(pickle.dumps(random.random, 0))
-    0: c    GLOBAL     'random random'
-   15: p    PUT        0
-   18: .    STOP
+>>> dis(pickle.dumps(random.getrandbits, 0))
+    0: c    GLOBAL     'random getrandbits'
+   20: p    PUT        0
+   23: .    STOP
 highest protocol among opcodes = 0
 
 >>> from pickletools import _Example

Modified: python/branches/p3yk-noslice/Lib/plat-atheos/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-atheos/IN.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-atheos/IN.py	Wed Jul 11 15:40:56 2007
@@ -557,7 +557,7 @@
 # Included from bits/dirent.h
 def _D_ALLOC_NAMLEN(d): return (_D_EXACT_NAMLEN (d) + 1)
 
-def IFTODT(mode): return (((mode) & 0170000) >> 12)
+def IFTODT(mode): return (((mode) & 0o170000) >> 12)
 
 def DTTOIF(dirtype): return ((dirtype) << 12)
 
@@ -567,17 +567,17 @@
 MAXNAMLEN = 255
 
 # Included from posix/stat.h
-S_IFMT = 00170000
-S_IFSOCK = 0140000
-S_IFLNK = 0120000
-S_IFREG = 0100000
-S_IFBLK = 0060000
-S_IFDIR = 0040000
-S_IFCHR = 0020000
-S_IFIFO = 0010000
-S_ISUID = 0004000
-S_ISGID = 0002000
-S_ISVTX = 0001000
+S_IFMT = 0o0170000
+S_IFSOCK = 0o140000
+S_IFLNK = 0o120000
+S_IFREG = 0o100000
+S_IFBLK = 0o060000
+S_IFDIR = 0o040000
+S_IFCHR = 0o020000
+S_IFIFO = 0o010000
+S_ISUID = 0o004000
+S_ISGID = 0o002000
+S_ISVTX = 0o001000
 def S_ISLNK(m): return (((m) & S_IFMT) == S_IFLNK)
 
 def S_ISREG(m): return (((m) & S_IFMT) == S_IFREG)
@@ -592,18 +592,18 @@
 
 def S_ISSOCK(m): return (((m) & S_IFMT) == S_IFSOCK)
 
-S_IRWXU = 00700
-S_IRUSR = 00400
-S_IWUSR = 00200
-S_IXUSR = 00100
-S_IRWXG = 00070
-S_IRGRP = 00040
-S_IWGRP = 00020
-S_IXGRP = 00010
-S_IRWXO = 00007
-S_IROTH = 00004
-S_IWOTH = 00002
-S_IXOTH = 00001
+S_IRWXU = 0o0700
+S_IRUSR = 0o0400
+S_IWUSR = 0o0200
+S_IXUSR = 0o0100
+S_IRWXG = 0o0070
+S_IRGRP = 0o0040
+S_IWGRP = 0o0020
+S_IXGRP = 0o0010
+S_IRWXO = 0o0007
+S_IROTH = 0o0004
+S_IWOTH = 0o0002
+S_IXOTH = 0o0001
 S_IRWXUGO = (S_IRWXU|S_IRWXG|S_IRWXO)
 S_IALLUGO = (S_ISUID|S_ISGID|S_ISVTX|S_IRWXUGO)
 S_IRUGO = (S_IRUSR|S_IRGRP|S_IROTH)
@@ -612,24 +612,24 @@
 _STAT_VER_KERNEL = 0
 
 # Included from posix/fcntl.h
-O_ACCMODE = 0003
+O_ACCMODE = 0o003
 O_RWMASK = O_ACCMODE
 O_RDONLY = 00
-O_WRONLY = 01
-O_RDWR = 02
-O_CREAT = 0100
-O_EXCL = 0200
-O_NOCTTY = 0400
-O_TRUNC = 01000
-O_APPEND = 02000
-O_NONBLOCK = 04000
+O_WRONLY = 0o1
+O_RDWR = 0o2
+O_CREAT = 0o100
+O_EXCL = 0o200
+O_NOCTTY = 0o400
+O_TRUNC = 0o1000
+O_APPEND = 0o2000
+O_NONBLOCK = 0o4000
 O_NDELAY = O_NONBLOCK
-O_SYNC = 010000
+O_SYNC = 0o10000
 O_FSYNC = O_SYNC
-O_ASYNC = 020000
+O_ASYNC = 0o20000
 FASYNC = O_ASYNC
-O_DIRECTORY = 040000
-O_NOTRAVERSE = 0100000
+O_DIRECTORY = 0o40000
+O_NOTRAVERSE = 0o100000
 O_NOFOLLOW = O_NOTRAVERSE
 F_DUPFD = 0
 F_GETFD = 1

Modified: python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py	Wed Jul 11 15:40:56 2007
@@ -30,7 +30,6 @@
 from Carbon import AE
 import Nav
 import MacOS
-import string
 from Carbon.ControlAccessor import *    # Also import Controls constants
 import Carbon.File
 import macresource
@@ -54,12 +53,12 @@
 
 def cr2lf(text):
     if '\r' in text:
-        text = string.join(string.split(text, '\r'), '\n')
+        text = '\n'.join(text.split('\r'))
     return text
 
 def lf2cr(text):
     if '\n' in text:
-        text = string.join(string.split(text, '\n'), '\r')
+        text = '\r'.join(text.split('\n'))
     if len(text) > 253:
         text = text[:253] + '\311'
     return text
@@ -543,7 +542,7 @@
                 d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff)
         h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
         oldstr = GetDialogItemText(h)
-        tmplist = string.split(oldstr)
+        tmplist = oldstr.split()
         newlist = []
         while tmplist:
             item = tmplist[0]
@@ -815,11 +814,11 @@
     try:
         if hasattr(MacOS, 'SchedParams'):
             appsw = MacOS.SchedParams(1, 0)
-        for i in xrange(20):
+        for i in range(20):
             bar.inc()
             time.sleep(0.05)
         bar.set(0,100)
-        for i in xrange(100):
+        for i in range(100):
             bar.set(i)
             time.sleep(0.05)
             if i % 10 == 0:

Modified: python/branches/p3yk-noslice/Lib/plat-mac/aepack.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/aepack.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/aepack.py	Wed Jul 11 15:40:56 2007
@@ -13,10 +13,6 @@
 #
 
 import struct
-import string
-import types
-from string import strip
-from types import *
 from Carbon import AE
 from Carbon.AppleEvents import *
 import MacOS
@@ -76,7 +72,7 @@
     """Pack a python object into an AE descriptor"""
 
     if forcetype:
-        if type(x) is StringType:
+        if isinstance(x, str):
             return AE.AECreateDesc(forcetype, x)
         else:
             return pack(x).AECoerceDesc(forcetype)
@@ -92,29 +88,29 @@
         return AE.AECreateDesc('fsrf', x.data)
     if isinstance(x, AliasType):
         return AE.AECreateDesc('alis', x.data)
-    if isinstance(x, IntType):
+    if isinstance(x, int):
         return AE.AECreateDesc('long', struct.pack('l', x))
-    if isinstance(x, FloatType):
+    if isinstance(x, float):
         return AE.AECreateDesc('doub', struct.pack('d', x))
-    if isinstance(x, StringType):
+    if isinstance(x, str):
         return AE.AECreateDesc('TEXT', x)
-    if isinstance(x, UnicodeType):
+    if isinstance(x, unicode):
         data = x.encode('utf16')
         if data[:2] == '\xfe\xff':
             data = data[2:]
         return AE.AECreateDesc('utxt', data)
-    if isinstance(x, ListType):
-        list = AE.AECreateList('', 0)
+    if isinstance(x, list):
+        lst = AE.AECreateList('', 0)
         for item in x:
-            list.AEPutDesc(0, pack(item))
-        return list
-    if isinstance(x, DictionaryType):
+            lst.AEPutDesc(0, pack(item))
+        return lst
+    if isinstance(x, dict):
         record = AE.AECreateList('', 1)
         for key, value in x.items():
             packkey(record, key, value)
             #record.AEPutParamDesc(key, pack(value))
         return record
-    if type(x) == types.ClassType and issubclass(x, ObjectSpecifier):
+    if isinstance(x, type) and issubclass(x, ObjectSpecifier):
         # Note: we are getting a class object here, not an instance
         return AE.AECreateDesc('type', x.want)
     if hasattr(x, '__aepack__'):
@@ -342,7 +338,7 @@
 # to __class__ is safe. Moreover, shouldn't there be a better
 # initializer for the classes in the suites?
 def mkobjectfrommodule(dict, modulename):
-    if type(dict['want']) == types.ClassType and issubclass(dict['want'], ObjectSpecifier):
+    if isinstance(dict['want'], type) and issubclass(dict['want'], ObjectSpecifier):
         # The type has already been converted to Python. Convert back:-(
         classtype = dict['want']
         dict['want'] = aetypes.mktype(classtype.want)

Modified: python/branches/p3yk-noslice/Lib/plat-mac/aetypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/aetypes.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/aetypes.py	Wed Jul 11 15:40:56 2007
@@ -2,8 +2,6 @@
 
 from Carbon.AppleEvents import *
 import struct
-from types import *
-import string
 
 #
 # convoluted, since there are cyclic dependencies between this file and
@@ -15,7 +13,7 @@
 
 def nice(s):
     """'nice' representation of an object"""
-    if type(s) is StringType: return repr(s)
+    if isinstance(s, str): return repr(s)
     else: return str(s)
 
 class Unknown:
@@ -41,7 +39,7 @@
         return "Enum(%r)" % (self.enum,)
 
     def __str__(self):
-        return string.strip(self.enum)
+        return self.enum.strip()
 
     def __aepack__(self):
         return pack(self.enum, typeEnumeration)
@@ -108,7 +106,7 @@
         return "Type(%r)" % (self.type,)
 
     def __str__(self):
-        return string.strip(self.type)
+        return self.type.strip()
 
     def __aepack__(self):
         return pack(self.type, typeType)
@@ -131,7 +129,7 @@
         return "Keyword(%r)" % self.keyword
 
     def __str__(self):
-        return string.strip(self.keyword)
+        return self.keyword.strip()
 
     def __aepack__(self):
         return pack(self.keyword, typeKeyword)
@@ -170,7 +168,7 @@
         return "Comparison(%r, %r, %r)" % (self.obj1, self.relo, self.obj2)
 
     def __str__(self):
-        return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2))
+        return "%s %s %s" % (nice(self.obj1), self.relo.strip(), nice(self.obj2))
 
     def __aepack__(self):
         return pack({'obj1': self.obj1,
@@ -198,7 +196,7 @@
         return "Ordinal(%r)" % (self.abso,)
 
     def __str__(self):
-        return "%s" % (string.strip(self.abso))
+        return "%s" % (self.abso.strip())
 
     def __aepack__(self):
         return pack(self.abso, 'abso')
@@ -223,12 +221,12 @@
         return "Logical(%r, %r)" % (self.logc, self.term)
 
     def __str__(self):
-        if type(self.term) == ListType and len(self.term) == 2:
+        if isinstance(self.term, list) and len(self.term) == 2:
             return "%s %s %s" % (nice(self.term[0]),
-                                 string.strip(self.logc),
+                                 self.logc.strip(),
                                  nice(self.term[1]))
         else:
-            return "%s(%s)" % (string.strip(self.logc), nice(self.term))
+            return "%s(%s)" % (self.logc.strip(), nice(self.term))
 
     def __aepack__(self):
         return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi')
@@ -482,13 +480,13 @@
 
     def __init__(self, want, seld, fr = None):
         t = type(seld)
-        if t == StringType:
+        if isinstance(t, str):
             form = 'name'
         elif IsRange(seld):
             form = 'rang'
         elif IsComparison(seld) or IsLogical(seld):
             form = 'test'
-        elif t == TupleType:
+        elif isinstance(t, tuple):
             # Breakout: specify both form and seld in a tuple
             # (if you want ID or rele or somesuch)
             form, seld = seld
@@ -514,12 +512,11 @@
 
     def __str__(self):
         seld = self.seld
-        if type(seld) == StringType:
+        if isinstance(seld, str):
             ss = repr(seld)
         elif IsRange(seld):
             start, stop = seld.start, seld.stop
-            if type(start) == InstanceType == type(stop) and \
-               start.__class__ == self.__class__ == stop.__class__:
+            if type(start) == type(stop) == type(self):
                 ss = str(start.seld) + " thru " + str(stop.seld)
             else:
                 ss = str(seld)

Modified: python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py	Wed Jul 11 15:40:56 2007
@@ -60,7 +60,7 @@
             raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,)
         if nentry <= 0:
             raise Error, "AppleSingle file contains no forks"
-        headers = [fileobj.read(AS_ENTRY_LENGTH) for i in xrange(nentry)]
+        headers = [fileobj.read(AS_ENTRY_LENGTH) for i in range(nentry)]
         self.forks = []
         for hdr in headers:
             try:

Modified: python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/buildtools.py	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,6 @@
 
 import sys
 import os
-import string
 import imp
 import marshal
 from Carbon import Res
@@ -14,6 +13,9 @@
 import EasyDialogs
 import shutil
 
+import warnings
+warnings.warn("the buildtools module is deprecated", DeprecationWarning, 2)
+
 
 BuildError = "BuildError"
 
@@ -86,7 +88,7 @@
     # Set the destination file name. Note that basename
     # does contain the whole filepath, only a .py is stripped.
 
-    if string.lower(filename[-3:]) == ".py":
+    if filename[-3:].lower() == ".py":
         basename = filename[:-3]
         if MacOS.runtimemodel != 'macho' and not destname:
             destname = basename
@@ -347,7 +349,7 @@
         for ires in range(1, 1+nresources):
             res = Res.Get1IndResource(type, ires)
             id, type, name = res.GetResInfo()
-            lcname = string.lower(name)
+            lcname = name.lower()
 
             if lcname == OWNERNAME and id == 0:
                 if skipowner:

Modified: python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py	Wed Jul 11 15:40:56 2007
@@ -504,7 +504,7 @@
             standalone = self.standalone
             semi_standalone = self.semi_standalone
             open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
-            os.chmod(bootstrappath, 0775)
+            os.chmod(bootstrappath, 0o775)
 
         if self.iconfile is not None:
             iconbase = os.path.basename(self.iconfile)
@@ -603,7 +603,7 @@
                         walk(path)
                     else:
                         mod = os.stat(path)[stat.ST_MODE]
-                        if not (mod & 0100):
+                        if not (mod & 0o100):
                             continue
                         relpath = path[len(self.bundlepath):]
                         self.message("Stripping %s" % relpath, 2)

Deleted: /python/branches/p3yk-noslice/Lib/plat-mac/cfmfile.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/plat-mac/cfmfile.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,183 +0,0 @@
-"""codefragments.py -- wrapper to modify code fragments."""
-
-# (c) 1998, Just van Rossum, Letterror
-
-__version__ = "0.8b3"
-__author__ = "jvr"
-
-import Carbon.File
-import struct
-from Carbon import Res
-import os
-import sys
-
-DEBUG = 0
-
-error = "cfm.error"
-
-BUFSIZE = 0x80000
-
-def mergecfmfiles(srclist, dst, architecture = 'fat'):
-    """Merge all files in srclist into a new file dst.
-
-    If architecture is given, only code fragments of that type will be used:
-    "pwpc" for PPC, "m68k" for cfm68k. This does not work for "classic"
-    68k code, since it does not use code fragments to begin with.
-    If architecture is None, all fragments will be used, enabling FAT binaries.
-    """
-
-    srclist = list(srclist)
-    for i in range(len(srclist)):
-        srclist[i] = Carbon.File.pathname(srclist[i])
-    dst = Carbon.File.pathname(dst)
-
-    dstfile = open(dst, "wb")
-    rf = Res.FSpOpenResFile(dst, 3)
-    try:
-        dstcfrg = CfrgResource()
-        for src in srclist:
-            srccfrg = CfrgResource(src)
-            for frag in srccfrg.fragments:
-                if frag.architecture == 'pwpc' and architecture == 'm68k':
-                    continue
-                if frag.architecture == 'm68k' and architecture == 'pwpc':
-                    continue
-                dstcfrg.append(frag)
-
-                frag.copydata(dstfile)
-
-        cfrgres = Res.Resource(dstcfrg.build())
-        Res.UseResFile(rf)
-        cfrgres.AddResource('cfrg', 0, "")
-    finally:
-        dstfile.close()
-        rf = Res.CloseResFile(rf)
-
-
-class CfrgResource:
-
-    def __init__(self, path = None):
-        self.version = 1
-        self.fragments = []
-        self.path = path
-        if path is not None and os.path.exists(path):
-            currentresref = Res.CurResFile()
-            resref = Res.FSpOpenResFile(path, 1)
-            Res.UseResFile(resref)
-            try:
-                try:
-                    data = Res.Get1Resource('cfrg', 0).data
-                except Res.Error:
-                    raise Res.Error, "no 'cfrg' resource found", sys.exc_traceback
-            finally:
-                Res.CloseResFile(resref)
-                Res.UseResFile(currentresref)
-            self.parse(data)
-            if self.version != 1:
-                raise error, "unknown 'cfrg' resource format"
-
-    def parse(self, data):
-        (res1, res2, self.version,
-            res3, res4, res5, res6,
-            self.memberCount) = struct.unpack("8l", data[:32])
-        data = data[32:]
-        while data:
-            frag = FragmentDescriptor(self.path, data)
-            data = data[frag.memberSize:]
-            self.fragments.append(frag)
-
-    def build(self):
-        self.memberCount = len(self.fragments)
-        data = struct.pack("8l", 0, 0, self.version, 0, 0, 0, 0, self.memberCount)
-        for frag in self.fragments:
-            data = data + frag.build()
-        return data
-
-    def append(self, frag):
-        self.fragments.append(frag)
-
-
-class FragmentDescriptor:
-
-    def __init__(self, path, data = None):
-        self.path = path
-        if data is not None:
-            self.parse(data)
-
-    def parse(self, data):
-        self.architecture = data[:4]
-        (   self.updatelevel,
-            self.currentVersion,
-            self.oldDefVersion,
-            self.stacksize,
-            self.applibdir,
-            self.fragtype,
-            self.where,
-            self.offset,
-            self.length,
-            self.res1, self.res2,
-            self.memberSize,) = struct.unpack("4lhBB4lh", data[4:42])
-        pname = data[42:self.memberSize]
-        self.name = pname[1:1+ord(pname[0])]
-
-    def build(self):
-        data = self.architecture
-        data = data + struct.pack("4lhBB4l",
-                self.updatelevel,
-                self.currentVersion,
-                self.oldDefVersion,
-                self.stacksize,
-                self.applibdir,
-                self.fragtype,
-                self.where,
-                self.offset,
-                self.length,
-                self.res1, self.res2)
-        self.memberSize = len(data) + 2 + 1 + len(self.name)
-        # pad to 4 byte boundaries
-        if self.memberSize % 4:
-            self.memberSize = self.memberSize + 4 - (self.memberSize % 4)
-        data = data + struct.pack("hb", self.memberSize, len(self.name))
-        data = data + self.name
-        data = data + '\000' * (self.memberSize - len(data))
-        return data
-
-    def getfragment(self):
-        if self.where != 1:
-            raise error, "can't read fragment, unsupported location"
-        f = open(self.path, "rb")
-        f.seek(self.offset)
-        if self.length:
-            frag = f.read(self.length)
-        else:
-            frag = f.read()
-        f.close()
-        return frag
-
-    def copydata(self, outfile):
-        if self.where != 1:
-            raise error, "can't read fragment, unsupported location"
-        infile = open(self.path, "rb")
-        if self.length == 0:
-            infile.seek(0, 2)
-            self.length = infile.tell()
-
-        # Position input file and record new offset from output file
-        infile.seek(self.offset)
-
-        # pad to 16 byte boundaries
-        offset = outfile.tell()
-        if offset % 16:
-            offset = offset + 16 - (offset % 16)
-        outfile.seek(offset)
-        self.offset = offset
-
-        l = self.length
-        while l:
-            if l > BUFSIZE:
-                outfile.write(infile.read(BUFSIZE))
-                l = l - BUFSIZE
-            else:
-                outfile.write(infile.read(l))
-                l = 0
-        infile.close()

Modified: python/branches/p3yk-noslice/Lib/plat-mac/findertools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/findertools.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/findertools.py	Wed Jul 11 15:40:56 2007
@@ -296,8 +296,9 @@
         return _getlocation(object_alias)
     return _setlocation(object_alias, pos)
 
-def _setlocation(object_alias, (x, y)):
+def _setlocation(object_alias, location):
     """_setlocation: Set the location of the icon for the object."""
+    x, y = location
     finder = _getfinder()
     args = {}
     attrs = {}
@@ -438,8 +439,9 @@
         return _getwindowsize(folder_alias)
     return _setwindowsize(folder_alias, size)
 
-def _setwindowsize(folder_alias, (w, h)):
+def _setwindowsize(folder_alias, size):
     """Set the size of a Finder window for folder to (w, h)"""
+    w, h = size
     finder = _getfinder()
     args = {}
     attrs = {}
@@ -484,13 +486,14 @@
     openwindow(fsr)
     if not pos:
         return _getwindowposition(folder_alias)
-    if type(pos) == InstanceType:
-        # pos might be a QDPoint object as returned by _getwindowposition
+    if aetypes.IsQDPoint(pos):
+        # QDPoint object as returned by _getwindowposition
         pos = (pos.h, pos.v)
     return _setwindowposition(folder_alias, pos)
 
-def _setwindowposition(folder_alias, (x, y)):
+def _setwindowposition(folder_alias, position):
     """Set the size of a Finder window for folder to (w, h)."""
+    x, y = position
     finder = _getfinder()
     args = {}
     attrs = {}

Modified: python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py	Wed Jul 11 15:40:56 2007
@@ -279,9 +279,9 @@
 
 def simplify(item):
     """Recursively replace singleton tuples by their constituent item"""
-    if type(item) is types.ListType:
+    if isinstance(item, list):
         return map(simplify, item)
-    elif type(item) == types.TupleType and len(item) == 2:
+    elif isinstance(item, tuple) and len(item) == 2:
         return simplify(item[1])
     else:
         return item
@@ -352,7 +352,7 @@
 def generic(what, f, *args):
     if type(what) == types.FunctionType:
         return what(f, *args)
-    if type(what) == types.ListType:
+    if isinstance(what, list):
         record = []
         for thing in what:
             item = generic(thing[:1], f, *thing[1:])
@@ -698,7 +698,7 @@
         """Generate class boilerplate"""
         classname = '%s_Events'%self.modname
         if self.basemodule:
-            modshortname = string.split(self.basemodule.__name__, '.')[-1]
+            modshortname = self.basemodule.__name__.split('.')[-1]
             baseclassname = '%s_Events'%modshortname
             self.fp.write("class %s(%s):\n\n"%(classname, baseclassname))
         else:
@@ -1169,7 +1169,7 @@
                 bits.append(dataflagdict[i])
             else:
                 bits.append(repr(i))
-    return '[%s]' % string.join(bits)
+    return '[%s]' % ' '.join(bits)
 
 def ascii(str):
     """Return a string with all non-ascii characters hex-encoded"""

Modified: python/branches/p3yk-noslice/Lib/plat-mac/ic.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/ic.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/ic.py	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,6 @@
 """IC wrapper module, based on Internet Config 1.3"""
 
 import icglue
-import string
 import sys
 import os
 from Carbon import Res
@@ -135,7 +134,7 @@
 
 def _decode(data, key):
     if '\245' in key:
-        key2 = key[:string.index(key, '\245')+1]
+        key2 = key[:key.index('\245')+1]
     else:
         key2 = key
     if key2 in _decoder_table:
@@ -148,7 +147,7 @@
     if type(data) == _ICOpaqueDataType:
         return data.data
     if '\245' in key:
-        key2 = key[:string.index(key, '\245')+1]
+        key2 = key[:key.index('\245')+1]
     else:
         key2 = key
     if key2 in _decoder_table:

Deleted: /python/branches/p3yk-noslice/Lib/plat-mac/macfs.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/plat-mac/macfs.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,198 +0,0 @@
-"""macfs - Pure Python module designed to be backward compatible with
-macfs and MACFS.
-"""
-import sys
-import struct
-import Carbon.Res
-import Carbon.File
-import warnings
-
-warnings.warn("macfs is deprecated, use Carbon.File, Carbon.Folder or EasyDialogs",
-              DeprecationWarning, stacklevel=2)
-
-# First step: ensure we also emulate the MACFS module, which contained
-# all the constants
-
-sys.modules['MACFS'] = sys.modules[__name__]
-
-# Import all those constants
-from Carbon.Files import *
-from Carbon.Folders import *
-
-# For some obscure historical reason these are here too:
-READ = 1
-WRITE = 2
-smAllScripts = -3
-
-#
-# Find the epoch conversion for file dates in a way that works on OS9 and OSX
-import time
-if time.gmtime(0)[0] == 1970:
-    _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000
-    def _utc2time(utc):
-        t = utc[1] + _EPOCHCONVERT
-        return int(t)
-    def _time2utc(t):
-        t = int(t) - _EPOCHCONVERT
-        if t < -0x7fffffff:
-            t = t + 0x10000000
-        return (0, int(t), 0)
-else:
-    def _utc2time(utc):
-        t = utc[1]
-        if t < 0:
-            t = t + 0x100000000
-        return t
-    def _time2utc(t):
-        if t > 0x7fffffff:
-            t = t - 0x100000000
-        return (0, int(t), 0)
-
-# The old name of the error object:
-error = Carbon.File.Error
-
-#
-# The various objects macfs used to export. We override them here, because some
-# of the method names are subtly different.
-#
-class FSSpec(Carbon.File.FSSpec):
-    def as_fsref(self):
-        return FSRef(self)
-
-    def NewAlias(self, src=None):
-        return Alias(Carbon.File.NewAlias(src, self))
-
-    def GetCreatorType(self):
-        finfo = self.FSpGetFInfo()
-        return finfo.Creator, finfo.Type
-
-    def SetCreatorType(self, ctor, tp):
-        finfo = self.FSpGetFInfo()
-        finfo.Creator = ctor
-        finfo.Type = tp
-        self.FSpSetFInfo(finfo)
-
-    def GetFInfo(self):
-        return self.FSpGetFInfo()
-
-    def SetFInfo(self, info):
-        return self.FSpSetFInfo(info)
-
-    def GetDates(self):
-        catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
-        catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags)
-        cdate = catinfo.createDate
-        mdate = catinfo.contentModDate
-        bdate = catinfo.backupDate
-        return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate)
-
-    def SetDates(self, cdate, mdate, bdate):
-        catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
-        catinfo = Carbon.File.FSCatalogInfo(
-            createDate = _time2utc(cdate),
-            contentModDate = _time2utc(mdate),
-            backupDate = _time2utc(bdate))
-        FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo)
-
-class FSRef(Carbon.File.FSRef):
-    def as_fsspec(self):
-        return FSSpec(self)
-
-class Alias(Carbon.File.Alias):
-
-    def GetInfo(self, index):
-        return self.GetAliasInfo(index)
-
-    def Update(self, *args):
-        pass # print "Alias.Update not yet implemented"
-
-    def Resolve(self, src=None):
-        fss, changed = self.ResolveAlias(src)
-        return FSSpec(fss), changed
-
-from Carbon.File import FInfo
-
-# Backward-compatible type names:
-FSSpecType = FSSpec
-FSRefType = FSRef
-AliasType = Alias
-FInfoType = FInfo
-
-# Global functions:
-def ResolveAliasFile(fss, chain=1):
-    fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain)
-    return FSSpec(fss), isdir, isalias
-
-def RawFSSpec(data):
-    return FSSpec(rawdata=data)
-
-def RawAlias(data):
-    return Alias(rawdata=data)
-
-def FindApplication(*args):
-    raise NotImplementedError, "FindApplication no longer implemented"
-
-def NewAliasMinimalFromFullPath(path):
-    return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', ''))
-
-# Another global function:
-from Carbon.Folder import FindFolder
-
-#
-# Finally the old Standard File routine emulators.
-#
-
-_curfolder = None
-
-def StandardGetFile(*typelist):
-    """Ask for an input file, optionally specifying 4-char file types that are
-    allowable"""
-    return PromptGetFile('', *typelist)
-
-def PromptGetFile(prompt, *typelist):
-    """Ask for an input file giving the user a prompt message. Optionally you can
-    specifying 4-char file types that are allowable"""
-    import EasyDialogs
-    warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
-              DeprecationWarning, stacklevel=2)
-    if not typelist:
-        typelist = None
-    fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
-        typeList=typelist, defaultLocation=_handleSetFolder())
-    return fss, not fss is None
-
-def StandardPutFile(prompt, default=None):
-    """Ask the user for an output file, with a prompt. Optionally you cn supply a
-    default output filename"""
-    import EasyDialogs
-    warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
-              DeprecationWarning, stacklevel=2)
-    fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
-    savedFileName=default, defaultLocation=_handleSetFolder())
-    return fss, not fss is None
-
-def SetFolder(folder):
-    global _curfolder
-    warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
-              DeprecationWarning, stacklevel=2)
-    if _curfolder:
-        rv = FSSpec(_curfolder)
-    else:
-        rv = None
-    _curfolder = folder
-    return rv
-
-def _handleSetFolder():
-    global _curfolder
-    rv = _curfolder
-    _curfolder = None
-    return rv
-
-def GetDirectory(prompt=None):
-    """Ask the user to select a folder. Optionally you can give a prompt."""
-    import EasyDialogs
-    warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
-              DeprecationWarning, stacklevel=2)
-    fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
-        defaultLocation=_handleSetFolder())
-    return fss, not fss is None

Modified: python/branches/p3yk-noslice/Lib/plat-mac/macostools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/macostools.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/macostools.py	Wed Jul 11 15:40:56 2007
@@ -61,25 +61,13 @@
     if os.sep == ':' and not ':' in head:
         head = head + ':'
     mkdirs(head)
-    os.mkdir(dst, 0777)
+    os.mkdir(dst, 0o777)
 
 def touched(dst):
     """Tell the finder a file has changed. No-op on MacOSX."""
-    if sys.platform != 'mac': return
     import warnings
-    warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
-    import macfs
-    file_fss = macfs.FSSpec(dst)
-    vRefNum, dirID, name = file_fss.as_tuple()
-    dir_fss = macfs.FSSpec((vRefNum, dirID, ''))
-    crdate, moddate, bkdate = dir_fss.GetDates()
-    now = time.time()
-    if now == moddate:
-        now = now + 1
-    try:
-        dir_fss.SetDates(crdate, now, bkdate)
-    except macfs.error:
-        pass
+    warnings.warn("macostools.touched() has been deprecated",
+                    DeprecationWarning, 2)
 
 def touched_ae(dst):
     """Tell the finder a file has changed"""
@@ -129,7 +117,6 @@
         dstfsr = File.FSRef(dst)
         catinfo, _, _, _ = srcfsr.FSGetCatalogInfo(Files.kFSCatInfoAllDates)
         dstfsr.FSSetCatalogInfo(Files.kFSCatInfoAllDates, catinfo)
-    touched(dstfss)
 
 def copytree(src, dst, copydates=1):
     """Copy a complete file tree to a new destination"""

Modified: python/branches/p3yk-noslice/Lib/plat-mac/pimp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/pimp.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/pimp.py	Wed Jul 11 15:40:56 2007
@@ -14,7 +14,7 @@
 """
 import sys
 import os
-import popen2
+import subprocess
 import urllib
 import urllib2
 import urlparse
@@ -101,10 +101,11 @@
         output.write("+ %s\n" % cmd)
     if NO_EXECUTE:
         return 0
-    child = popen2.Popen4(cmd)
-    child.tochild.close()
+    child = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+    child.stdin.close()
     while 1:
-        line = child.fromchild.readline()
+        line = child.stdout.readline()
         if not line:
             break
         if output:

Modified: python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py	Wed Jul 11 15:40:56 2007
@@ -320,7 +320,7 @@
         from warnings import warn
         warn("The plistlib.Dict class is deprecated, use builtin dict instead",
              PendingDeprecationWarning)
-        super(Dict, self).__init__(**kwargs)
+        super().__init__(**kwargs)
 
 
 class Plist(_InternalDict):
@@ -333,7 +333,7 @@
         from warnings import warn
         warn("The Plist class is deprecated, use the readPlist() and "
              "writePlist() functions instead", PendingDeprecationWarning)
-        super(Plist, self).__init__(**kwargs)
+        super().__init__(**kwargs)
 
     def fromFile(cls, pathOrFile):
         """Deprecated. Use the readPlist() function instead."""

Modified: python/branches/p3yk-noslice/Lib/plat-riscos/riscospath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-riscos/riscospath.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-riscos/riscospath.py	Wed Jul 11 15:40:56 2007
@@ -59,13 +59,13 @@
   """
     dash= _allowMOSFSNames and p[:1]=='-'
     if dash:
-        q= string.find(p, '-', 1)+1
+        q= p.find('-', 1)+1
     else:
         if p[:1]==':':
             q= 0
         else:
-            q= string.find(p, ':')+1 # q= index of start of non-FS portion of path
-    s= string.find(p, '#')
+            q= p.find(':')+1 # q= index of start of non-FS portion of path
+    s= p.find('#')
     if s==-1 or s>q:
         s= q # find end of main FS name, not including special field
     else:
@@ -75,7 +75,7 @@
                 break # disallow invalid non-special-field characters in FS name
     r= q
     if p[q:q+1]==':':
-        r= string.find(p, '.', q+1)+1
+        r= p.find('.', q+1)+1
         if r==0:
             r= len(p) # find end of drive name (if any) following FS name (if any)
     return (p[:q], p[q:r], p[r:])
@@ -87,7 +87,7 @@
   OS filesystems are case-insensitive. However, not all filesystems have to be,
   and there's no simple way to find out what type an FS is argh.
   """
-    return string.lower(p)
+    return p.lower()
 
 
 def isabs(p):
@@ -126,7 +126,7 @@
   name must still be dealt with separately since special field may contain '.'.
   """
     (fs, drive, path)= _split(p)
-    q= string.rfind(path, '.')
+    q= path.rfind('.')
     if q!=-1:
         return (fs+drive+path[:q], path[q+1:])
     return ('', p)
@@ -139,7 +139,7 @@
   """
     (tail, head)= split(p)
     if '/' in head:
-        q= len(head)-string.rfind(head, '/')
+        q= len(head)-head.rfind('/')
         return (p[:-q], p[-q:])
     return (p, '')
 
@@ -174,7 +174,7 @@
     s1 = min(m)
     s2 = max(m)
     n = min(len(s1), len(s2))
-    for i in xrange(n):
+    for i in range(n):
         if s1[i] != s2[i]:
             return s1[:i]
     return s1[:n]
@@ -291,7 +291,7 @@
             fsname= fs[1:-1]
         else:
             fsname= fs[:-1]
-        fsname= string.split(fsname, '#', 1)[0] # remove special field from fs
+        fsname= fsname.split('#', 1)[0] # remove special field from fs
     x= swi.swi('OS_FSControl', 'ib2s.i;.....i', 54, b, fsname, l)
     if x<l:
         urd= b.tostring(0, l-x-1)

Modified: python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py	Wed Jul 11 15:40:56 2007
@@ -21,7 +21,7 @@
         url = url[2:]
     elif url[:2] == '//':
         raise RuntimeError, 'Cannot convert non-local URL to pathname'
-    components = string.split(url, '/')
+    components = url.split('/')
     if not components[0]:
         if '$' in components:
             del components[0]

Modified: python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py	Wed Jul 11 15:40:56 2007
@@ -97,7 +97,7 @@
 NZERO = 20
 NULL = 0
 NULL = 0
-CMASK = 022
+CMASK = 0o22
 CDLIMIT = (1<<11)
 NBPS = 0x20000
 NBPSCTR = 512
@@ -733,13 +733,13 @@
 _XRS_ID = 0x78727300
 GETCONTEXT = 0
 SETCONTEXT = 1
-UC_SIGMASK = 001
-UC_STACK = 002
-UC_CPU = 004
-UC_MAU = 010
+UC_SIGMASK = 0o01
+UC_STACK = 0o02
+UC_CPU = 0o04
+UC_MAU = 0o10
 UC_FPU = UC_MAU
-UC_INTR = 020
-UC_ASR = 040
+UC_INTR = 0o20
+UC_ASR = 0o40
 UC_MCONTEXT = (UC_CPU|UC_FPU|UC_ASR)
 UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT)
 _SIGQUEUE_MAX = 32
@@ -1021,14 +1021,14 @@
 AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME)
 AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\
                         AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
-VSUID = 04000
-VSGID = 02000
-VSVTX = 01000
-VREAD = 00400
-VWRITE = 00200
-VEXEC = 00100
-MODEMASK = 07777
-PERMMASK = 00777
+VSUID = 0o4000
+VSGID = 0o2000
+VSVTX = 0o1000
+VREAD = 0o0400
+VWRITE = 0o0200
+VEXEC = 0o0100
+MODEMASK = 0o7777
+PERMMASK = 0o0777
 def MANDMODE(mode): return (((mode) & (VSGID|(VEXEC>>3))) == VSGID)
 
 VSA_ACL = 0x0001

Modified: python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py	Wed Jul 11 15:40:56 2007
@@ -94,7 +94,7 @@
 NZERO = 20
 NULL = 0
 NULL = 0
-CMASK = 022
+CMASK = 0o22
 CDLIMIT = (1<<11)
 NBPS = 0x20000
 NBPSCTR = 512
@@ -730,13 +730,13 @@
 _XRS_ID = 0x78727300
 GETCONTEXT = 0
 SETCONTEXT = 1
-UC_SIGMASK = 001
-UC_STACK = 002
-UC_CPU = 004
-UC_MAU = 010
+UC_SIGMASK = 0o01
+UC_STACK = 0o02
+UC_CPU = 0o04
+UC_MAU = 0o10
 UC_FPU = UC_MAU
-UC_INTR = 020
-UC_ASR = 040
+UC_INTR = 0o20
+UC_ASR = 0o40
 UC_MCONTEXT = (UC_CPU|UC_FPU|UC_ASR)
 UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT)
 _SIGQUEUE_MAX = 32
@@ -1400,14 +1400,14 @@
 AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME)
 AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\
                         AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
-VSUID = 04000
-VSGID = 02000
-VSVTX = 01000
-VREAD = 00400
-VWRITE = 00200
-VEXEC = 00100
-MODEMASK = 07777
-PERMMASK = 00777
+VSUID = 0o4000
+VSGID = 0o2000
+VSVTX = 0o1000
+VREAD = 0o0400
+VWRITE = 0o0200
+VEXEC = 0o0100
+MODEMASK = 0o7777
+PERMMASK = 0o0777
 def MANDMODE(mode): return (((mode) & (VSGID|(VEXEC>>3))) == VSGID)
 
 VSA_ACL = 0x0001

Modified: python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py	Wed Jul 11 15:40:56 2007
@@ -187,8 +187,8 @@
 NC_TPI_COTS_ORD = 3
 NC_TPI_RAW = 4
 NC_NOFLAG = 00
-NC_VISIBLE = 01
-NC_BROADCAST = 02
+NC_VISIBLE = 0o1
+NC_BROADCAST = 0o2
 NC_NOPROTOFMLY = "-"
 NC_LOOPBACK = "loopback"
 NC_INET = "inet"

Modified: python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py	(original)
+++ python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py	Wed Jul 11 15:40:56 2007
@@ -65,41 +65,41 @@
 ES_MACADTLID = 7
 ES_PRVID = 8
 ES_TPGETMAJOR = 9
-SA_EXEC = 001
-SA_WRITE = 002
-SA_READ = 004
-SA_SUBSIZE = 010
+SA_EXEC = 0o01
+SA_WRITE = 0o02
+SA_READ = 0o04
+SA_SUBSIZE = 0o10
 
 # Included from sys/stropts_f.h
 X_STR = (ord('S')<<8)
-X_I_BASE = (X_STR|0200)
-X_I_NREAD = (X_STR|0201)
-X_I_PUSH = (X_STR|0202)
-X_I_POP = (X_STR|0203)
-X_I_LOOK = (X_STR|0204)
-X_I_FLUSH = (X_STR|0205)
-X_I_SRDOPT = (X_STR|0206)
-X_I_GRDOPT = (X_STR|0207)
-X_I_STR = (X_STR|0210)
-X_I_SETSIG = (X_STR|0211)
-X_I_GETSIG = (X_STR|0212)
-X_I_FIND = (X_STR|0213)
-X_I_LINK = (X_STR|0214)
-X_I_UNLINK = (X_STR|0215)
-X_I_PEEK = (X_STR|0217)
-X_I_FDINSERT = (X_STR|0220)
-X_I_SENDFD = (X_STR|0221)
-X_I_RECVFD = (X_STR|0222)
+X_I_BASE = (X_STR|0o200)
+X_I_NREAD = (X_STR|0o201)
+X_I_PUSH = (X_STR|0o202)
+X_I_POP = (X_STR|0o203)
+X_I_LOOK = (X_STR|0o204)
+X_I_FLUSH = (X_STR|0o205)
+X_I_SRDOPT = (X_STR|0o206)
+X_I_GRDOPT = (X_STR|0o207)
+X_I_STR = (X_STR|0o210)
+X_I_SETSIG = (X_STR|0o211)
+X_I_GETSIG = (X_STR|0o212)
+X_I_FIND = (X_STR|0o213)
+X_I_LINK = (X_STR|0o214)
+X_I_UNLINK = (X_STR|0o215)
+X_I_PEEK = (X_STR|0o217)
+X_I_FDINSERT = (X_STR|0o220)
+X_I_SENDFD = (X_STR|0o221)
+X_I_RECVFD = (X_STR|0o222)
 
 # Included from unistd.h
 
 # Included from sys/unistd.h
-R_OK = 004
-W_OK = 002
-X_OK = 001
+R_OK = 0o04
+W_OK = 0o02
+X_OK = 0o01
 F_OK = 000
-EFF_ONLY_OK = 010
-EX_OK = 020
+EFF_ONLY_OK = 0o10
+EX_OK = 0o20
 SEEK_SET = 0
 SEEK_CUR = 1
 SEEK_END = 2
@@ -289,40 +289,40 @@
 ANYMARK = 0x01
 LASTMARK = 0x02
 STR = (ord('S')<<8)
-I_NREAD = (STR|01)
-I_PUSH = (STR|02)
-I_POP = (STR|03)
-I_LOOK = (STR|04)
-I_FLUSH = (STR|05)
-I_SRDOPT = (STR|06)
-I_GRDOPT = (STR|07)
-I_STR = (STR|010)
-I_SETSIG = (STR|011)
-I_GETSIG = (STR|012)
-I_FIND = (STR|013)
-I_LINK = (STR|014)
-I_UNLINK = (STR|015)
-I_PEEK = (STR|017)
-I_FDINSERT = (STR|020)
-I_SENDFD = (STR|021)
-I_RECVFD = (STR|022)
-I_E_RECVFD = (STR|016)
-I_RECVFD = (STR|016)
-I_RECVFD = (STR|022)
-I_SWROPT = (STR|023)
-I_GWROPT = (STR|024)
-I_LIST = (STR|025)
-I_PLINK = (STR|026)
-I_PUNLINK = (STR|027)
-I_FLUSHBAND = (STR|034)
-I_CKBAND = (STR|035)
-I_GETBAND = (STR|036)
-I_ATMARK = (STR|037)
-I_SETCLTIME = (STR|040)
-I_GETCLTIME = (STR|041)
-I_CANPUT = (STR|042)
-I_S_RECVFD = (STR|043)
-I_STATS = (STR|044)
-I_BIGPIPE = (STR|045)
-I_GETTP = (STR|046)
+I_NREAD = (STR|0o1)
+I_PUSH = (STR|0o2)
+I_POP = (STR|0o3)
+I_LOOK = (STR|0o4)
+I_FLUSH = (STR|0o5)
+I_SRDOPT = (STR|0o6)
+I_GRDOPT = (STR|0o7)
+I_STR = (STR|0o10)
+I_SETSIG = (STR|0o11)
+I_GETSIG = (STR|0o12)
+I_FIND = (STR|0o13)
+I_LINK = (STR|0o14)
+I_UNLINK = (STR|0o15)
+I_PEEK = (STR|0o17)
+I_FDINSERT = (STR|0o20)
+I_SENDFD = (STR|0o21)
+I_RECVFD = (STR|0o22)
+I_E_RECVFD = (STR|0o16)
+I_RECVFD = (STR|0o16)
+I_RECVFD = (STR|0o22)
+I_SWROPT = (STR|0o23)
+I_GWROPT = (STR|0o24)
+I_LIST = (STR|0o25)
+I_PLINK = (STR|0o26)
+I_PUNLINK = (STR|0o27)
+I_FLUSHBAND = (STR|0o34)
+I_CKBAND = (STR|0o35)
+I_GETBAND = (STR|0o36)
+I_ATMARK = (STR|0o37)
+I_SETCLTIME = (STR|0o40)
+I_GETCLTIME = (STR|0o41)
+I_CANPUT = (STR|0o42)
+I_S_RECVFD = (STR|0o43)
+I_STATS = (STR|0o44)
+I_BIGPIPE = (STR|0o45)
+I_GETTP = (STR|0o46)
 INFTIM = -1

Modified: python/branches/p3yk-noslice/Lib/platform.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/platform.py	(original)
+++ python/branches/p3yk-noslice/Lib/platform.py	Wed Jul 11 15:40:56 2007
@@ -112,7 +112,7 @@
 
 __version__ = '1.0.6'
 
-import sys,string,os,re
+import sys, os, re
 
 ### Platform specific APIs
 
@@ -189,15 +189,15 @@
         info = open('/var/adm/inst-log/info').readlines()
         distname = 'SuSE'
         for line in info:
-            tv = string.split(line)
+            tv = line.split()
             if len(tv) == 2:
                 tag,value = tv
             else:
                 continue
             if tag == 'MIN_DIST_VERSION':
-                version = string.strip(value)
+                version = value.strip()
             elif tag == 'DIST_IDENT':
-                values = string.split(value,'-')
+                values = value.split('-')
                 id = values[2]
         return distname,version,id
 
@@ -205,7 +205,7 @@
         # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
         info = open('/etc/.installed').readlines()
         for line in info:
-            pkg = string.split(line,'-')
+            pkg = line.split('-')
             if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
                 # XXX does Caldera support non Intel platforms ? If yes,
                 #     where can we find the needed id ?
@@ -242,7 +242,7 @@
 
 _supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos',
                     'mandrake', 'rocks', 'slackware', 'yellowdog',
-                    'gentoo', 'UnitedLinux')
+                    'gentoo', 'UnitedLinux', 'turbolinux')
 
 def _parse_release_file(firstline):
 
@@ -258,7 +258,7 @@
         return tuple(m.groups())
 
     # Unkown format... take the first two words
-    l = string.split(string.strip(firstline))
+    l = firstline.strip().split()
     if l:
         version = l[0]
         if len(l) > 1:
@@ -451,7 +451,7 @@
     """ Normalize the version and build strings and return a single
         version string using the format major.minor.build (or patchlevel).
     """
-    l = string.split(version,'.')
+    l = version.split('.')
     if build:
         l.append(build)
     try:
@@ -460,7 +460,7 @@
         strings = l
     else:
         strings = map(str,ints)
-    version = string.join(strings[:3],'.')
+    version = '.'.join(strings[:3])
     return version
 
 _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
@@ -505,7 +505,7 @@
         return system,release,version
 
     # Parse the output
-    info = string.strip(info)
+    info = info.strip()
     m = _ver_output.match(info)
     if m is not None:
         system,release,version = m.groups()
@@ -600,6 +600,16 @@
                 release = '2003Server'
             else:
                 release = 'post2003'
+        elif maj == 6:
+            if min == 0:
+                # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx
+                productType = GetVersionEx(1)[8]
+                if productType == 1: # VER_NT_WORKSTATION
+                    release = 'Vista'
+                else:
+                    release = '2008Server'
+            else:
+                release = 'post2008Server'
     else:
         if not release:
             # E.g. Win3.1 with win32s
@@ -766,7 +776,7 @@
             # These releases use the old name SunOS
             return system,release,version
         # Modify release (marketing release = SunOS release - 3)
-        l = string.split(release,'.')
+        l = release.split('.')
         if l:
             try:
                 major = int(l[0])
@@ -775,7 +785,7 @@
             else:
                 major = major - 3
                 l[0] = str(major)
-                release = string.join(l,'.')
+                release = '.'.join(l)
         if release < '6':
             system = 'Solaris'
         else:
@@ -806,28 +816,24 @@
         compatible format e.g. "system-version-machine".
     """
     # Format the platform string
-    platform = string.join(
-        map(string.strip,
-            filter(len, args)),
-        '-')
+    platform = '-'.join(x.strip() for x in filter(len, args))
 
     # Cleanup some possible filename obstacles...
-    replace = string.replace
-    platform = replace(platform,' ','_')
-    platform = replace(platform,'/','-')
-    platform = replace(platform,'\\','-')
-    platform = replace(platform,':','-')
-    platform = replace(platform,';','-')
-    platform = replace(platform,'"','-')
-    platform = replace(platform,'(','-')
-    platform = replace(platform,')','-')
+    platform = platform.replace(' ','_')
+    platform = platform.replace('/','-')
+    platform = platform.replace('\\','-')
+    platform = platform.replace(':','-')
+    platform = platform.replace(';','-')
+    platform = platform.replace('"','-')
+    platform = platform.replace('(','-')
+    platform = platform.replace(')','-')
 
     # No need to report 'unknown' information...
-    platform = replace(platform,'unknown','')
+    platform = platform.replace('unknown','')
 
     # Fold '--'s and remove trailing '-'
     while 1:
-        cleaned = replace(platform,'--','-')
+        cleaned = platform.replace('--','-')
         if cleaned == platform:
             break
         platform = cleaned
@@ -889,7 +895,7 @@
         f = os.popen('uname %s 2> /dev/null' % option)
     except (AttributeError,os.error):
         return default
-    output = string.strip(f.read())
+    output = f.read().strip()
     rc = f.close()
     if not output or rc:
         return default
@@ -911,7 +917,7 @@
         f = os.popen('file %s 2> /dev/null' % target)
     except (AttributeError,os.error):
         return default
-    output = string.strip(f.read())
+    output = f.read().strip()
     rc = f.close()
     if not output or rc:
         return default
@@ -1068,6 +1074,16 @@
             # (_syscmd_ver() tends to return the vendor name as well)
             if system == 'Microsoft Windows':
                 system = 'Windows'
+            elif system == 'Microsoft' and release == 'Windows':
+                # Under Windows Vista and Windows Server 2008,
+                # Microsoft changed the output of the ver command. The
+                # release is no longer printed.  This causes the
+                # system and release to be misidentified.
+                system = 'Windows'
+                if '6.0' == version[:3]:
+                    release = 'Vista'
+                else:
+                    release = ''
 
         # In case we still don't know anything useful, we'll try to
         # help ourselves
@@ -1082,7 +1098,7 @@
         elif system[:4] == 'java':
             release,vendor,vminfo,osinfo = java_ver()
             system = 'Java'
-            version = string.join(vminfo,', ')
+            version = ', '.join(vminfo)
             if not version:
                 version = vendor
 
@@ -1285,10 +1301,10 @@
         builddate = builddate + ' ' + buildtime
 
     # Add the patchlevel version if missing
-    l = string.split(version, '.')
+    l = version.split('.')
     if len(l) == 2:
         l.append('0')
-        version = string.join(l, '.')
+        version = '.'.join(l)
 
     # Build and cache the result
     result = (name, version, branch, revision, buildno, builddate, compiler)
@@ -1345,7 +1361,7 @@
     """
     if hasattr(sys, 'version_info'):
         return sys.version_info[:3]
-    return tuple(string.split(_sys_version()[1], '.'))
+    return tuple(_sys_version()[1].split('.'))
 
 def python_branch():
 

Deleted: /python/branches/p3yk-noslice/Lib/popen2.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/popen2.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,244 +0,0 @@
-"""Spawn a command with pipes to its stdin, stdout, and optionally stderr.
-
-The normal os.popen(cmd, mode) call spawns a shell command and provides a
-file interface to just the input or output of the process depending on
-whether mode is 'r' or 'w'.  This module provides the functions popen2(cmd)
-and popen3(cmd) which return two or three pipes to the spawned command.
-"""
-
-import os
-import sys
-
-__all__ = ["popen2", "popen3", "popen4"]
-
-try:
-    MAXFD = os.sysconf('SC_OPEN_MAX')
-except (AttributeError, ValueError):
-    MAXFD = 256
-
-_active = []
-
-def _cleanup():
-    for inst in _active[:]:
-        if inst.poll(_deadstate=sys.maxint) >= 0:
-            try:
-                _active.remove(inst)
-            except ValueError:
-                # This can happen if two threads create a new Popen instance.
-                # It's harmless that it was already removed, so ignore.
-                pass
-
-class Popen3:
-    """Class representing a child process.  Normally instances are created
-    by the factory functions popen2() and popen3()."""
-
-    sts = -1                    # Child not completed yet
-
-    def __init__(self, cmd, capturestderr=False, bufsize=-1):
-        """The parameter 'cmd' is the shell command to execute in a
-        sub-process.  On UNIX, 'cmd' may be a sequence, in which case arguments
-        will be passed directly to the program without shell intervention (as
-        with os.spawnv()).  If 'cmd' is a string it will be passed to the shell
-        (as with os.system()).   The 'capturestderr' flag, if true, specifies
-        that the object should capture standard error output of the child
-        process.  The default is false.  If the 'bufsize' parameter is
-        specified, it specifies the size of the I/O buffers to/from the child
-        process."""
-        _cleanup()
-        self.cmd = cmd
-        p2cread, p2cwrite = os.pipe()
-        c2pread, c2pwrite = os.pipe()
-        if capturestderr:
-            errout, errin = os.pipe()
-        self.pid = os.fork()
-        if self.pid == 0:
-            # Child
-            os.dup2(p2cread, 0)
-            os.dup2(c2pwrite, 1)
-            if capturestderr:
-                os.dup2(errin, 2)
-            self._run_child(cmd)
-        os.close(p2cread)
-        self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
-        os.close(c2pwrite)
-        self.fromchild = os.fdopen(c2pread, 'r', bufsize)
-        if capturestderr:
-            os.close(errin)
-            self.childerr = os.fdopen(errout, 'r', bufsize)
-        else:
-            self.childerr = None
-
-    def __del__(self):
-        # In case the child hasn't been waited on, check if it's done.
-        self.poll(_deadstate=sys.maxint)
-        if self.sts < 0:
-            if _active is not None:
-                # Child is still running, keep us alive until we can wait on it.
-                _active.append(self)
-
-    def _run_child(self, cmd):
-        if isinstance(cmd, basestring):
-            cmd = ['/bin/sh', '-c', cmd]
-        for i in xrange(3, MAXFD):
-            try:
-                os.close(i)
-            except OSError:
-                pass
-        try:
-            os.execvp(cmd[0], cmd)
-        finally:
-            os._exit(1)
-
-    def poll(self, _deadstate=None):
-        """Return the exit status of the child process if it has finished,
-        or -1 if it hasn't finished yet."""
-        if self.sts < 0:
-            try:
-                pid, sts = os.waitpid(self.pid, os.WNOHANG)
-                # pid will be 0 if self.pid hasn't terminated
-                if pid == self.pid:
-                    self.sts = sts
-            except os.error:
-                if _deadstate is not None:
-                    self.sts = _deadstate
-        return self.sts
-
-    def wait(self):
-        """Wait for and return the exit status of the child process."""
-        if self.sts < 0:
-            pid, sts = os.waitpid(self.pid, 0)
-            # This used to be a test, but it is believed to be
-            # always true, so I changed it to an assertion - mvl
-            assert pid == self.pid
-            self.sts = sts
-        return self.sts
-
-
-class Popen4(Popen3):
-    childerr = None
-
-    def __init__(self, cmd, bufsize=-1):
-        _cleanup()
-        self.cmd = cmd
-        p2cread, p2cwrite = os.pipe()
-        c2pread, c2pwrite = os.pipe()
-        self.pid = os.fork()
-        if self.pid == 0:
-            # Child
-            os.dup2(p2cread, 0)
-            os.dup2(c2pwrite, 1)
-            os.dup2(c2pwrite, 2)
-            self._run_child(cmd)
-        os.close(p2cread)
-        self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
-        os.close(c2pwrite)
-        self.fromchild = os.fdopen(c2pread, 'r', bufsize)
-
-
-if sys.platform[:3] == "win" or sys.platform == "os2emx":
-    # Some things don't make sense on non-Unix platforms.
-    del Popen3, Popen4
-
-    def popen2(cmd, bufsize=-1, mode='t'):
-        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
-        be a sequence, in which case arguments will be passed directly to the
-        program without shell intervention (as with os.spawnv()). If 'cmd' is a
-        string it will be passed to the shell (as with os.system()). If
-        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
-        file objects (child_stdout, child_stdin) are returned."""
-        w, r = os.popen2(cmd, mode, bufsize)
-        return r, w
-
-    def popen3(cmd, bufsize=-1, mode='t'):
-        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
-        be a sequence, in which case arguments will be passed directly to the
-        program without shell intervention (as with os.spawnv()). If 'cmd' is a
-        string it will be passed to the shell (as with os.system()). If
-        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
-        file objects (child_stdout, child_stdin, child_stderr) are returned."""
-        w, r, e = os.popen3(cmd, mode, bufsize)
-        return r, w, e
-
-    def popen4(cmd, bufsize=-1, mode='t'):
-        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
-        be a sequence, in which case arguments will be passed directly to the
-        program without shell intervention (as with os.spawnv()). If 'cmd' is a
-        string it will be passed to the shell (as with os.system()). If
-        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
-        file objects (child_stdout_stderr, child_stdin) are returned."""
-        w, r = os.popen4(cmd, mode, bufsize)
-        return r, w
-else:
-    def popen2(cmd, bufsize=-1, mode='t'):
-        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
-        be a sequence, in which case arguments will be passed directly to the
-        program without shell intervention (as with os.spawnv()). If 'cmd' is a
-        string it will be passed to the shell (as with os.system()). If
-        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
-        file objects (child_stdout, child_stdin) are returned."""
-        inst = Popen3(cmd, False, bufsize)
-        return inst.fromchild, inst.tochild
-
-    def popen3(cmd, bufsize=-1, mode='t'):
-        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
-        be a sequence, in which case arguments will be passed directly to the
-        program without shell intervention (as with os.spawnv()). If 'cmd' is a
-        string it will be passed to the shell (as with os.system()). If
-        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
-        file objects (child_stdout, child_stdin, child_stderr) are returned."""
-        inst = Popen3(cmd, True, bufsize)
-        return inst.fromchild, inst.tochild, inst.childerr
-
-    def popen4(cmd, bufsize=-1, mode='t'):
-        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
-        be a sequence, in which case arguments will be passed directly to the
-        program without shell intervention (as with os.spawnv()). If 'cmd' is a
-        string it will be passed to the shell (as with os.system()). If
-        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
-        file objects (child_stdout_stderr, child_stdin) are returned."""
-        inst = Popen4(cmd, bufsize)
-        return inst.fromchild, inst.tochild
-
-    __all__.extend(["Popen3", "Popen4"])
-
-def _test():
-    # When the test runs, there shouldn't be any open pipes
-    _cleanup()
-    assert not _active, "Active pipes when test starts " + repr([c.cmd for c in _active])
-    cmd  = "cat"
-    teststr = "ab cd\n"
-    if os.name == "nt":
-        cmd = "more"
-    # "more" doesn't act the same way across Windows flavors,
-    # sometimes adding an extra newline at the start or the
-    # end.  So we strip whitespace off both ends for comparison.
-    expected = teststr.strip()
-    print("testing popen2...")
-    r, w = popen2(cmd)
-    w.write(teststr)
-    w.close()
-    got = r.read()
-    if got.strip() != expected:
-        raise ValueError("wrote %r read %r" % (teststr, got))
-    print("testing popen3...")
-    try:
-        r, w, e = popen3([cmd])
-    except:
-        r, w, e = popen3(cmd)
-    w.write(teststr)
-    w.close()
-    got = r.read()
-    if got.strip() != expected:
-        raise ValueError("wrote %r read %r" % (teststr, got))
-    got = e.read()
-    if got:
-        raise ValueError("unexpected %r on stderr" % (got,))
-    for inst in _active[:]:
-        inst.wait()
-    _cleanup()
-    if _active:
-        raise ValueError("_active not empty")
-    print("All OK")
-
-if __name__ == '__main__':
-    _test()

Modified: python/branches/p3yk-noslice/Lib/poplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/poplib.py	(original)
+++ python/branches/p3yk-noslice/Lib/poplib.py	Wed Jul 11 15:40:56 2007
@@ -76,24 +76,10 @@
     """
 
 
-    def __init__(self, host, port = POP3_PORT):
+    def __init__(self, host, port=POP3_PORT, timeout=None):
         self.host = host
         self.port = port
-        msg = "getaddrinfo returns an empty list"
-        self.sock = None
-        for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
-            af, socktype, proto, canonname, sa = res
-            try:
-                self.sock = socket.socket(af, socktype, proto)
-                self.sock.connect(sa)
-            except socket.error as msg:
-                if self.sock:
-                    self.sock.close()
-                self.sock = None
-                continue
-            break
-        if not self.sock:
-            raise socket.error, msg
+        self.sock = socket.create_connection((host, port), timeout)
         self.file = self.sock.makefile('rb')
         self._debugging = 0
         self.welcome = self._getresp()

Deleted: /python/branches/p3yk-noslice/Lib/posixfile.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/posixfile.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,235 +0,0 @@
-"""Extended file operations available in POSIX.
-
-f = posixfile.open(filename, [mode, [bufsize]])
-      will create a new posixfile object
-
-f = posixfile.fileopen(fileobject)
-      will create a posixfile object from a builtin file object
-
-f.file()
-      will return the original builtin file object
-
-f.dup()
-      will return a new file object based on a new filedescriptor
-
-f.dup2(fd)
-      will return a new file object based on the given filedescriptor
-
-f.flags(mode)
-      will turn on the associated flag (merge)
-      mode can contain the following characters:
-
-  (character representing a flag)
-      a       append only flag
-      c       close on exec flag
-      n       no delay flag
-      s       synchronization flag
-  (modifiers)
-      !       turn flags 'off' instead of default 'on'
-      =       copy flags 'as is' instead of default 'merge'
-      ?       return a string in which the characters represent the flags
-              that are set
-
-      note: - the '!' and '=' modifiers are mutually exclusive.
-            - the '?' modifier will return the status of the flags after they
-              have been changed by other characters in the mode string
-
-f.lock(mode [, len [, start [, whence]]])
-      will (un)lock a region
-      mode can contain the following characters:
-
-  (character representing type of lock)
-      u       unlock
-      r       read lock
-      w       write lock
-  (modifiers)
-      |       wait until the lock can be granted
-      ?       return the first lock conflicting with the requested lock
-              or 'None' if there is no conflict. The lock returned is in the
-              format (mode, len, start, whence, pid) where mode is a
-              character representing the type of lock ('r' or 'w')
-
-      note: - the '?' modifier prevents a region from being locked; it is
-              query only
-"""
-
-
-class _posixfile_:
-    """File wrapper class that provides extra POSIX file routines."""
-
-    states = ['open', 'closed']
-
-    #
-    # Internal routines
-    #
-    def __repr__(self):
-        file = self._file_
-        return "<%s posixfile '%s', mode '%s' at %s>" % \
-                (self.states[file.closed], file.name, file.mode, \
-                 hex(id(self))[2:])
-
-    #
-    # Initialization routines
-    #
-    def open(self, name, mode='r', bufsize=-1):
-        import __builtin__
-        return self.fileopen(__builtin__.open(name, mode, bufsize))
-
-    def fileopen(self, file):
-        import types
-        if repr(type(file)) != "<type 'file'>":
-            raise TypeError, 'posixfile.fileopen() arg must be file object'
-        self._file_  = file
-        # Copy basic file methods
-        for maybemethod in dir(file):
-            if not maybemethod.startswith('_'):
-                attr = getattr(file, maybemethod)
-                if isinstance(attr, types.BuiltinMethodType):
-                    setattr(self, maybemethod, attr)
-        return self
-
-    #
-    # New methods
-    #
-    def file(self):
-        return self._file_
-
-    def dup(self):
-        import posix
-
-        if not hasattr(posix, 'fdopen'):
-            raise AttributeError, 'dup() method unavailable'
-
-        return posix.fdopen(posix.dup(self._file_.fileno()), self._file_.mode)
-
-    def dup2(self, fd):
-        import posix
-
-        if not hasattr(posix, 'fdopen'):
-            raise AttributeError, 'dup() method unavailable'
-
-        posix.dup2(self._file_.fileno(), fd)
-        return posix.fdopen(fd, self._file_.mode)
-
-    def flags(self, *which):
-        import fcntl, os
-
-        if which:
-            if len(which) > 1:
-                raise TypeError, 'Too many arguments'
-            which = which[0]
-        else: which = '?'
-
-        l_flags = 0
-        if 'n' in which: l_flags = l_flags | os.O_NDELAY
-        if 'a' in which: l_flags = l_flags | os.O_APPEND
-        if 's' in which: l_flags = l_flags | os.O_SYNC
-
-        file = self._file_
-
-        if '=' not in which:
-            cur_fl = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
-            if '!' in which: l_flags = cur_fl & ~ l_flags
-            else: l_flags = cur_fl | l_flags
-
-        l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFL, l_flags)
-
-        if 'c' in which:
-            arg = ('!' not in which)    # 0 is don't, 1 is do close on exec
-            l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFD, arg)
-
-        if '?' in which:
-            which = ''                  # Return current flags
-            l_flags = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
-            if os.O_APPEND & l_flags: which = which + 'a'
-            if fcntl.fcntl(file.fileno(), fcntl.F_GETFD, 0) & 1:
-                which = which + 'c'
-            if os.O_NDELAY & l_flags: which = which + 'n'
-            if os.O_SYNC & l_flags: which = which + 's'
-            return which
-
-    def lock(self, how, *args):
-        import struct, fcntl
-
-        if 'w' in how: l_type = fcntl.F_WRLCK
-        elif 'r' in how: l_type = fcntl.F_RDLCK
-        elif 'u' in how: l_type = fcntl.F_UNLCK
-        else: raise TypeError, 'no type of lock specified'
-
-        if '|' in how: cmd = fcntl.F_SETLKW
-        elif '?' in how: cmd = fcntl.F_GETLK
-        else: cmd = fcntl.F_SETLK
-
-        l_whence = 0
-        l_start = 0
-        l_len = 0
-
-        if len(args) == 1:
-            l_len = args[0]
-        elif len(args) == 2:
-            l_len, l_start = args
-        elif len(args) == 3:
-            l_len, l_start, l_whence = args
-        elif len(args) > 3:
-            raise TypeError, 'too many arguments'
-
-        # Hack by davem at magnet.com to get locking to go on freebsd;
-        # additions for AIX by Vladimir.Marangozov at imag.fr
-        import sys, os
-        if sys.platform in ('netbsd1',
-                            'openbsd2',
-                            'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
-                            'freebsd6', 'freebsd7',
-                            'bsdos2', 'bsdos3', 'bsdos4'):
-            flock = struct.pack('lxxxxlxxxxlhh', \
-                  l_start, l_len, os.getpid(), l_type, l_whence)
-        elif sys.platform in ('aix3', 'aix4'):
-            flock = struct.pack('hhlllii', \
-                  l_type, l_whence, l_start, l_len, 0, 0, 0)
-        else:
-            flock = struct.pack('hhllhh', \
-                  l_type, l_whence, l_start, l_len, 0, 0)
-
-        flock = fcntl.fcntl(self._file_.fileno(), cmd, flock)
-
-        if '?' in how:
-            if sys.platform in ('netbsd1',
-                                'openbsd2',
-                                'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
-                                'bsdos2', 'bsdos3', 'bsdos4'):
-                l_start, l_len, l_pid, l_type, l_whence = \
-                    struct.unpack('lxxxxlxxxxlhh', flock)
-            elif sys.platform in ('aix3', 'aix4'):
-                l_type, l_whence, l_start, l_len, l_sysid, l_pid, l_vfs = \
-                    struct.unpack('hhlllii', flock)
-            elif sys.platform == "linux2":
-                l_type, l_whence, l_start, l_len, l_pid, l_sysid = \
-                    struct.unpack('hhllhh', flock)
-            else:
-                l_type, l_whence, l_start, l_len, l_sysid, l_pid = \
-                    struct.unpack('hhllhh', flock)
-
-            if l_type != fcntl.F_UNLCK:
-                if l_type == fcntl.F_RDLCK:
-                    return 'r', l_len, l_start, l_whence, l_pid
-                else:
-                    return 'w', l_len, l_start, l_whence, l_pid
-
-def open(name, mode='r', bufsize=-1):
-    """Public routine to open a file as a posixfile object."""
-    return _posixfile_().open(name, mode, bufsize)
-
-def fileopen(file):
-    """Public routine to get a posixfile object from a Python file object."""
-    return _posixfile_().fileopen(file)
-
-#
-# Constants
-#
-SEEK_SET = 0
-SEEK_CUR = 1
-SEEK_END = 2
-
-#
-# End of posixfile.py
-#

Modified: python/branches/p3yk-noslice/Lib/posixpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/posixpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/posixpath.py	Wed Jul 11 15:40:56 2007
@@ -12,6 +12,7 @@
 
 import os
 import stat
+import genericpath
 from genericpath import *
 
 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
@@ -20,7 +21,7 @@
            "ismount","walk","expanduser","expandvars","normpath","abspath",
            "samefile","sameopenfile","samestat",
            "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
-           "devnull","realpath","supports_unicode_filenames"]
+           "devnull","realpath","supports_unicode_filenames","relpath"]
 
 # strings representing various path-related bits and pieces
 curdir = '.'
@@ -88,14 +89,8 @@
 # It is always true that root + ext == p.
 
 def splitext(p):
-    """Split the extension from a pathname.  Extension is everything from the
-    last dot to the end.  Returns "(root, ext)", either part may be empty."""
-    i = p.rfind('.')
-    if i<=p.rfind('/'):
-        return p, ''
-    else:
-        return p[:i], p[i:]
-
+    return genericpath._splitext(p, sep, altsep, extsep)
+splitext.__doc__ = genericpath._splitext.__doc__
 
 # Split a pathname into a drive specification and the rest of the
 # path.  Useful on DOS/Windows/NT; on Unix, the drive is always empty.
@@ -387,3 +382,18 @@
     return path
 
 supports_unicode_filenames = False
+
+def relpath(path, start=curdir):
+    """Return a relative version of a path"""
+
+    if not path:
+        raise ValueError("no path specified")
+
+    start_list = abspath(start).split(sep)
+    path_list = abspath(path).split(sep)
+
+    # Work out how much of the filepath is shared by start and path.
+    i = len(commonprefix([start_list, path_list]))
+
+    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
+    return join(*rel_list)

Modified: python/branches/p3yk-noslice/Lib/pprint.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pprint.py	(original)
+++ python/branches/p3yk-noslice/Lib/pprint.py	Wed Jul 11 15:40:56 2007
@@ -249,7 +249,10 @@
         try:
             items = sorted(items)
         except TypeError:
-            items = sorted(items, key=lambda (k, v): (str(type(k)), k, v))
+            def sortkey(item):
+                key, value = item
+                return str(type(key)), key, value
+            items = sorted(items, key=sortkey)
         for k, v in items:
             krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
             vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)

Modified: python/branches/p3yk-noslice/Lib/pstats.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pstats.py	(original)
+++ python/branches/p3yk-noslice/Lib/pstats.py	Wed Jul 11 15:40:56 2007
@@ -396,7 +396,7 @@
         subheader = False
         for cc, nc, tt, ct, callers in self.stats.values():
             if callers:
-                value = iter(callers.values()).next()
+                value = next(iter(callers.values()))
                 subheader = isinstance(value, tuple)
                 break
         if subheader:

Modified: python/branches/p3yk-noslice/Lib/pty.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pty.py	(original)
+++ python/branches/p3yk-noslice/Lib/pty.py	Wed Jul 11 15:40:56 2007
@@ -55,7 +55,7 @@
         pass
     else:
         try:
-            tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0)
+            tty_name, master_fd = sgi._getpty(os.O_RDWR, 0o666, 0)
         except IOError as msg:
             raise os.error, msg
         return master_fd, tty_name

Modified: python/branches/p3yk-noslice/Lib/pyclbr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pyclbr.py	(original)
+++ python/branches/p3yk-noslice/Lib/pyclbr.py	Wed Jul 11 15:40:56 2007
@@ -161,7 +161,7 @@
                 # close previous nested classes and defs
                 while stack and stack[-1][1] >= thisindent:
                     del stack[-1]
-                tokentype, meth_name, start, end, line = g.next()
+                tokentype, meth_name, start, end, line = next(g)
                 if tokentype != NAME:
                     continue # Syntax error
                 if stack:
@@ -179,11 +179,11 @@
                 # close previous nested classes and defs
                 while stack and stack[-1][1] >= thisindent:
                     del stack[-1]
-                tokentype, class_name, start, end, line = g.next()
+                tokentype, class_name, start, end, line = next(g)
                 if tokentype != NAME:
                     continue # Syntax error
                 # parse what follows the class name
-                tokentype, token, start, end, line = g.next()
+                tokentype, token, start, end, line = next(g)
                 inherit = None
                 if token == '(':
                     names = [] # List of superclasses
@@ -191,7 +191,7 @@
                     level = 1
                     super = [] # Tokens making up current superclass
                     while True:
-                        tokentype, token, start, end, line = g.next()
+                        tokentype, token, start, end, line = next(g)
                         if token in (')', ',') and level == 1:
                             n = "".join(super)
                             if n in dict:
@@ -287,7 +287,7 @@
             name2 = None
         names.append((name, name2))
         while token != "," and "\n" not in token:
-            tokentype, token, start, end, line = g.next()
+            tokentype, token, start, end, line = next(g)
         if token != ",":
             break
     return names
@@ -297,15 +297,15 @@
     # name is the dotted name, or None if there was no dotted name,
     # and token is the next input token.
     parts = []
-    tokentype, token, start, end, line = g.next()
+    tokentype, token, start, end, line = next(g)
     if tokentype != NAME and token != '*':
         return (None, token)
     parts.append(token)
     while True:
-        tokentype, token, start, end, line = g.next()
+        tokentype, token, start, end, line = next(g)
         if token != '.':
             break
-        tokentype, token, start, end, line = g.next()
+        tokentype, token, start, end, line = next(g)
         if tokentype != NAME:
             break
         parts.append(token)

Modified: python/branches/p3yk-noslice/Lib/pydoc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pydoc.py	(original)
+++ python/branches/p3yk-noslice/Lib/pydoc.py	Wed Jul 11 15:40:56 2007
@@ -54,7 +54,6 @@
 
 import sys, imp, os, re, types, inspect, __builtin__, pkgutil
 from repr import Repr
-from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
 try:
     from collections import deque
 except ImportError:
@@ -80,16 +79,16 @@
 def getdoc(object):
     """Get the doc string or comments for an object."""
     result = inspect.getdoc(object) or inspect.getcomments(object)
-    return result and re.sub('^ *\n', '', rstrip(result)) or ''
+    return result and re.sub('^ *\n', '', result.rstrip()) or ''
 
 def splitdoc(doc):
     """Split a doc string into a synopsis line (if any) and the rest."""
-    lines = split(strip(doc), '\n')
+    lines = doc.strip().split('\n')
     if len(lines) == 1:
         return lines[0], ''
-    elif len(lines) >= 2 and not rstrip(lines[1]):
-        return lines[0], join(lines[2:], '\n')
-    return '', join(lines, '\n')
+    elif len(lines) >= 2 and not lines[1].rstrip():
+        return lines[0], '\n'.join(lines[2:])
+    return '', '\n'.join(lines)
 
 def classname(object, modname):
     """Get a class name and qualify it with a module name if necessary."""
@@ -107,7 +106,7 @@
 def replace(text, *pairs):
     """Do a series of global replacements on a string."""
     while pairs:
-        text = join(split(text, pairs[0]), pairs[1])
+        text = pairs[1].join(text.split(pairs[0]))
         pairs = pairs[2:]
     return text
 
@@ -172,11 +171,12 @@
 
 def classify_class_attrs(object):
     """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
-    def fixup((name, kind, cls, value)):
+    results = []
+    for (name, kind, cls, value) in inspect.classify_class_attrs(object):
         if inspect.isdatadescriptor(value):
             kind = 'data descriptor'
-        return name, kind, cls, value
-    return map(fixup, inspect.classify_class_attrs(object))
+        results.append((name, kind, cls, value))
+    return results
 
 # ----------------------------------------------------- module manipulation
 
@@ -190,18 +190,18 @@
 
 def source_synopsis(file):
     line = file.readline()
-    while line[:1] == '#' or not strip(line):
+    while line[:1] == '#' or not line.strip():
         line = file.readline()
         if not line: break
-    line = strip(line)
+    line = line.strip()
     if line[:4] == 'r"""': line = line[1:]
     if line[:3] == '"""':
         line = line[3:]
         if line[-1:] == '\\': line = line[:-1]
-        while not strip(line):
+        while not line.strip():
             line = file.readline()
             if not line: break
-        result = strip(split(line, '"""')[0])
+        result = line.split('"""')[0].strip()
     else: result = None
     return result
 
@@ -229,15 +229,13 @@
 
 class ErrorDuringImport(Exception):
     """Errors that occurred while trying to import something to document it."""
-    def __init__(self, filename, (exc, value, tb)):
+    def __init__(self, filename, exc_info):
         self.filename = filename
-        self.exc = exc
-        self.value = value
-        self.tb = tb
+        self.exc, self.value, self.tb = exc_info
 
     def __str__(self):
         exc = self.exc
-        if type(exc) is types.ClassType:
+        if isinstance(exc, type):
             exc = exc.__name__
         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
 
@@ -275,12 +273,11 @@
         # that inherits from another module that has changed).
         if forceload and path in sys.modules:
             if path not in sys.builtin_module_names:
-                # Avoid simply calling reload() because it leaves names in
-                # the currently loaded module lying around if they're not
-                # defined in the new source file.  Instead, remove the
-                # module from sys.modules and re-import.  Also remove any
-                # submodules because they won't appear in the newly loaded
-                # module's namespace if they're already in sys.modules.
+                # Remove the module from sys.modules and re-import to try
+                # and avoid problems with partially loaded modules.
+                # Also remove any submodules because they won't appear
+                # in the newly loaded module's namespace if they're already
+                # in sys.modules.
                 subs = [m for m in sys.modules if m.startswith(path + '.')]
                 for key in [path] + subs:
                     # Prevent garbage collection.
@@ -297,13 +294,13 @@
             # A SyntaxError occurred before we could execute the module.
             raise ErrorDuringImport(value.filename, info)
         elif exc is ImportError and \
-             split(lower(str(value)))[:2] == ['no', 'module']:
+             str(value).lower().split()[:2] == ['no', 'module']:
             # The module was not found.
             return None
         else:
             # Some other error occurred during the importing process.
             raise ErrorDuringImport(path, sys.exc_info())
-    for part in split(path, '.')[1:]:
+    for part in path.split('.')[1:]:
         try: module = getattr(module, part)
         except AttributeError: return None
     return module
@@ -382,7 +379,7 @@
 
     def repr1(self, x, level):
         if hasattr(type(x), '__name__'):
-            methodname = 'repr_' + join(split(type(x).__name__), '_')
+            methodname = 'repr_' + '_'.join(type(x).__name__.split())
             if hasattr(self, methodname):
                 return getattr(self, methodname)(x, level)
         return self.escape(cram(stripid(repr(x)), self.maxother))
@@ -466,16 +463,16 @@
 
     def preformat(self, text):
         """Format literal preformatted text."""
-        text = self.escape(expandtabs(text))
+        text = self.escape(text.expandtabs())
         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
                              ' ', '&nbsp;', '\n', '<br>\n')
 
     def multicolumn(self, list, format, cols=4):
         """Format a list of items into a multi-column list."""
         result = ''
-        rows = (len(list)+cols-1)/cols
+        rows = (len(list)+cols-1)//cols
         for col in range(cols):
-            result = result + '<td width="%d%%" valign=top>' % (100/cols)
+            result = result + '<td width="%d%%" valign=top>' % (100//cols)
             for i in range(rows*col, rows*col+rows):
                 if i < len(list):
                     result = result + format(list[i]) + '<br>\n'
@@ -503,8 +500,9 @@
         """Make a link for a module."""
         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
 
-    def modpkglink(self, (name, path, ispackage, shadowed)):
+    def modpkglink(self, modpkginfo):
         """Make a link for a module or package to display in an index."""
+        name, path, ispackage, shadowed = modpkginfo
         if shadowed:
             return self.grey(name)
         if path:
@@ -551,7 +549,7 @@
                 results.append(self.namelink(name, classes))
             here = end
         results.append(escape(text[here:]))
-        return join(results, '')
+        return ''.join(results)
 
     # ---------------------------------------------- type-specific routines
 
@@ -567,7 +565,7 @@
                     parents = []
                     for base in bases:
                         parents.append(self.classlink(base, modname))
-                    result = result + '(' + join(parents, ', ') + ')'
+                    result = result + '(' + ', '.join(parents) + ')'
                 result = result + '\n</font></dt>'
             elif type(entry) is type([]):
                 result = result + '<dd>\n%s</dd>\n' % self.formattree(
@@ -581,13 +579,13 @@
             all = object.__all__
         except AttributeError:
             all = None
-        parts = split(name, '.')
+        parts = name.split('.')
         links = []
         for i in range(len(parts)-1):
             links.append(
                 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
-                (join(parts[:i+1], '.'), parts[i]))
-        linkedname = join(links + parts[-1:], '.')
+                ('.'.join(parts[:i+1]), parts[i]))
+        linkedname = '.'.join(links + parts[-1:])
         head = '<big><big><strong>%s</strong></big></big>' % linkedname
         try:
             path = inspect.getabsfile(object)
@@ -602,12 +600,12 @@
         if hasattr(object, '__version__'):
             version = str(object.__version__)
             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
-                version = strip(version[11:-1])
+                version = version[11:-1].strip()
             info.append('version %s' % self.escape(version))
         if hasattr(object, '__date__'):
             info.append(self.escape(str(object.__date__)))
         if info:
-            head = head + ' (%s)' % join(info, ', ')
+            head = head + ' (%s)' % ', '.join(info)
         docloc = self.getdocloc(object)
         if docloc is not None:
             docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
@@ -663,30 +661,30 @@
                 'Package Contents', '#ffffff', '#aa55cc', contents)
         elif modules:
             contents = self.multicolumn(
-                modules, lambda (key, value), s=self: s.modulelink(value))
+                modules, lambda t: self.modulelink(t[1]))
             result = result + self.bigsection(
                 'Modules', '#fffff', '#aa55cc', contents)
 
         if classes:
-            classlist = map(lambda (key, value): value, classes)
+            classlist = [value for (key, value) in classes]
             contents = [
                 self.formattree(inspect.getclasstree(classlist, 1), name)]
             for key, value in classes:
                 contents.append(self.document(value, key, name, fdict, cdict))
             result = result + self.bigsection(
-                'Classes', '#ffffff', '#ee77aa', join(contents))
+                'Classes', '#ffffff', '#ee77aa', ' '.join(contents))
         if funcs:
             contents = []
             for key, value in funcs:
                 contents.append(self.document(value, key, name, fdict, cdict))
             result = result + self.bigsection(
-                'Functions', '#ffffff', '#eeaa77', join(contents))
+                'Functions', '#ffffff', '#eeaa77', ' '.join(contents))
         if data:
             contents = []
             for key, value in data:
                 contents.append(self.document(value, key))
             result = result + self.bigsection(
-                'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
+                'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents))
         if hasattr(object, '__author__'):
             contents = self.markup(str(object.__author__), self.preformat)
             result = result + self.bigsection(
@@ -755,7 +753,7 @@
                 push(msg)
                 for name, kind, homecls, value in ok:
                     base = self.docother(getattr(object, name), name, mod)
-                    if callable(value) or inspect.isdatadescriptor(value):
+                    if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
                         doc = getattr(value, "__doc__", None)
                     else:
                         doc = None
@@ -769,8 +767,10 @@
                     push('\n')
             return attrs
 
-        attrs = filter(lambda (name, kind, cls, value): visiblename(name),
-                       classify_class_attrs(object))
+        attrs = [(name, kind, cls, value)
+                 for name, kind, cls, value in classify_class_attrs(object)
+                 if visiblename(name)]
+
         mdict = {}
         for key, kind, homecls, value in attrs:
             mdict[key] = anchor = '#' + name + '-' + key
@@ -831,7 +831,7 @@
             parents = []
             for base in bases:
                 parents.append(self.classlink(base, object.__module__))
-            title = title + '(%s)' % join(parents, ', ')
+            title = title + '(%s)' % ', '.join(parents)
         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
         doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
 
@@ -855,7 +855,7 @@
                 if imclass is not cl:
                     note = ' from ' + self.classlink(imclass, mod)
             else:
-                if object.im_self:
+                if object.im_self is not None:
                     note = ' method of %s instance' % self.classlink(
                         object.im_self.__class__, mod)
                 else:
@@ -875,11 +875,17 @@
             title = '<a name="%s"><strong>%s</strong></a> = %s' % (
                 anchor, name, reallink)
         if inspect.isfunction(object):
-            args, varargs, varkw, defaults = inspect.getargspec(object)
+            args, varargs, kwonlyargs, kwdefaults, varkw, defaults, ann = \
+                inspect.getfullargspec(object)
             argspec = inspect.formatargspec(
-                args, varargs, varkw, defaults, formatvalue=self.formatvalue)
+                args, varargs, kwonlyargs, kwdefaults, varkw, defaults, ann,
+                formatvalue=self.formatvalue,
+                formatannotation=inspect.formatannotationrelativeto(object))
             if realname == '<lambda>':
                 title = '<strong>%s</strong> <em>lambda</em> ' % name
+                # XXX lambda's won't usually have func_annotations['return']
+                # since the syntax doesn't support but it is possible.
+                # So removing parentheses isn't truly safe.
                 argspec = argspec[1:-1] # remove parentheses
         else:
             argspec = '(...)'
@@ -945,7 +951,7 @@
 
     def repr1(self, x, level):
         if hasattr(type(x), '__name__'):
-            methodname = 'repr_' + join(split(type(x).__name__), '_')
+            methodname = 'repr_' + '_'.join(type(x).__name__.split())
             if hasattr(self, methodname):
                 return getattr(self, methodname)(x, level)
         return cram(stripid(repr(x)), self.maxother)
@@ -977,19 +983,20 @@
 
     def bold(self, text):
         """Format a string in bold by overstriking."""
-        return join(map(lambda ch: ch + '\b' + ch, text), '')
+        return ''.join(map(lambda ch: ch + '\b' + ch, text))
 
     def indent(self, text, prefix='    '):
         """Indent text by prepending a given prefix to each line."""
         if not text: return ''
-        lines = split(text, '\n')
+        lines = text.split('\n')
         lines = map(lambda line, prefix=prefix: prefix + line, lines)
-        if lines: lines[-1] = rstrip(lines[-1])
-        return join(lines, '\n')
+        if lines: lines[-1] = lines[-1].rstrip()
+        return '\n'.join(lines)
 
     def section(self, title, contents):
         """Format a section with a given heading."""
-        return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
+        clean_contents = self.indent(contents).rstrip()
+        return self.bold(title) + '\n' + clean_contents + '\n\n'
 
     # ---------------------------------------------- type-specific routines
 
@@ -1002,7 +1009,7 @@
                 result = result + prefix + classname(c, modname)
                 if bases and bases != (parent,):
                     parents = map(lambda c, m=modname: classname(c, m), bases)
-                    result = result + '(%s)' % join(parents, ', ')
+                    result = result + '(%s)' % ', '.join(parents)
                 result = result + '\n'
             elif type(entry) is type([]):
                 result = result + self.formattree(
@@ -1062,32 +1069,32 @@
 
             modpkgs.sort()
             result = result + self.section(
-                'PACKAGE CONTENTS', join(modpkgs, '\n'))
+                'PACKAGE CONTENTS', '\n'.join(modpkgs))
 
         if classes:
-            classlist = map(lambda (key, value): value, classes)
+            classlist = [value for key, value in classes]
             contents = [self.formattree(
                 inspect.getclasstree(classlist, 1), name)]
             for key, value in classes:
                 contents.append(self.document(value, key, name))
-            result = result + self.section('CLASSES', join(contents, '\n'))
+            result = result + self.section('CLASSES', '\n'.join(contents))
 
         if funcs:
             contents = []
             for key, value in funcs:
                 contents.append(self.document(value, key, name))
-            result = result + self.section('FUNCTIONS', join(contents, '\n'))
+            result = result + self.section('FUNCTIONS', '\n'.join(contents))
 
         if data:
             contents = []
             for key, value in data:
                 contents.append(self.docother(value, key, name, maxlen=70))
-            result = result + self.section('DATA', join(contents, '\n'))
+            result = result + self.section('DATA', '\n'.join(contents))
 
         if hasattr(object, '__version__'):
             version = str(object.__version__)
             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
-                version = strip(version[11:-1])
+                version = version[11:-1].strip()
             result = result + self.section('VERSION', version)
         if hasattr(object, '__date__'):
             result = result + self.section('DATE', str(object.__date__))
@@ -1112,7 +1119,7 @@
             title = self.bold(name) + ' = class ' + realname
         if bases:
             parents = map(makename, bases)
-            title = title + '(%s)' % join(parents, ', ')
+            title = title + '(%s)' % ', '.join(parents)
 
         doc = getdoc(object)
         contents = doc and [doc + '\n'] or []
@@ -1161,7 +1168,7 @@
                 hr.maybe()
                 push(msg)
                 for name, kind, homecls, value in ok:
-                    if callable(value) or inspect.isdatadescriptor(value):
+                    if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
                         doc = getdoc(value)
                     else:
                         doc = None
@@ -1169,8 +1176,10 @@
                                        name, mod, maxlen=70, doc=doc) + '\n')
             return attrs
 
-        attrs = filter(lambda (name, kind, cls, value): visiblename(name),
-                       classify_class_attrs(object))
+        attrs = [(name, kind, cls, value)
+                 for name, kind, cls, value in classify_class_attrs(object)
+                 if visiblename(name)]
+
         while attrs:
             if mro:
                 thisclass = mro.popleft()
@@ -1208,7 +1217,7 @@
         contents = '\n'.join(contents)
         if not contents:
             return title + '\n'
-        return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
+        return title + '\n' + self.indent(contents.rstrip(), ' |  ') + '\n'
 
     def formatvalue(self, object):
         """Format an argument default value as text."""
@@ -1226,7 +1235,7 @@
                 if imclass is not cl:
                     note = ' from ' + classname(imclass, mod)
             else:
-                if object.im_self:
+                if object.im_self is not None:
                     note = ' method of %s instance' % classname(
                         object.im_self.__class__, mod)
                 else:
@@ -1241,11 +1250,17 @@
                 skipdocs = 1
             title = self.bold(name) + ' = ' + realname
         if inspect.isfunction(object):
-            args, varargs, varkw, defaults = inspect.getargspec(object)
+            args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = \
+              inspect.getfullargspec(object)
             argspec = inspect.formatargspec(
-                args, varargs, varkw, defaults, formatvalue=self.formatvalue)
+                args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann,
+                formatvalue=self.formatvalue,
+                formatannotation=inspect.formatannotationrelativeto(object))
             if realname == '<lambda>':
                 title = self.bold(name) + ' lambda '
+                # XXX lambda's won't usually have func_annotations['return']
+                # since the syntax doesn't support but it is possible.
+                # So removing parentheses isn't truly safe.
                 argspec = argspec[1:-1] # remove parentheses
         else:
             argspec = '(...)'
@@ -1255,7 +1270,7 @@
             return decl + '\n'
         else:
             doc = getdoc(object) or ''
-            return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
+            return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
 
     def _docdescriptor(self, name, value, mod):
         results = []
@@ -1356,7 +1371,7 @@
 
 def ttypager(text):
     """Page through text on a text terminal."""
-    lines = split(plain(text), '\n')
+    lines = plain(text).split('\n')
     try:
         import tty
         fd = sys.stdin.fileno()
@@ -1369,7 +1384,7 @@
 
     try:
         r = inc = os.environ.get('LINES', 25) - 1
-        sys.stdout.write(join(lines[:inc], '\n') + '\n')
+        sys.stdout.write('\n'.join(lines[:inc]) + '\n')
         while lines[r:]:
             sys.stdout.write('-- more --')
             sys.stdout.flush()
@@ -1385,7 +1400,7 @@
             if c in ('b', 'B', '\x1b'):
                 r = r - inc - inc
                 if r < 0: r = 0
-            sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
+            sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
             r = r + inc
 
     finally:
@@ -1421,16 +1436,14 @@
         return 'function ' + thing.__name__
     if inspect.ismethod(thing):
         return 'method ' + thing.__name__
-    if type(thing) is types.InstanceType:
-        return 'instance of ' + thing.__class__.__name__
     return type(thing).__name__
 
 def locate(path, forceload=0):
     """Locate an object by name or dotted path, importing as necessary."""
-    parts = [part for part in split(path, '.') if part]
+    parts = [part for part in path.split('.') if part]
     module, n = None, 0
     while n < len(parts):
-        nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
+        nextmodule = safeimport('.'.join(parts[:n+1]), forceload)
         if nextmodule: module, n = nextmodule, n + 1
         else: break
     if module:
@@ -1458,6 +1471,27 @@
     else:
         return thing, getattr(thing, '__name__', None)
 
+def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
+    """Render text documentation, given an object or a path to an object."""
+    object, name = resolve(thing, forceload)
+    desc = describe(object)
+    module = inspect.getmodule(object)
+    if name and '.' in name:
+        desc += ' in ' + name[:name.rfind('.')]
+    elif module and module is not object:
+        desc += ' in module ' + module.__name__
+    elif not (inspect.ismodule(object) or
+              inspect.isclass(object) or
+              inspect.isroutine(object) or
+              inspect.isgetsetdescriptor(object) or
+              inspect.ismemberdescriptor(object) or
+              isinstance(object, property)):
+        # If the passed object is a piece of data or an instance,
+        # document its available methods instead of its value.
+        object = type(object)
+        desc += ' object'
+    return title % desc + '\n\n' + text.document(object, name)
+
 def doc(thing, title='Python Library Documentation: %s', forceload=0):
     """Display text documentation, given an object or a path to an object."""
     try:
@@ -1478,7 +1512,7 @@
             # document its available methods instead of its value.
             object = type(object)
             desc += ' object'
-        pager(title % desc + '\n\n' + text.document(object, name))
+        pager(render_doc(thing, title, forceload))
     except (ImportError, ErrorDuringImport) as value:
         print(value)
 
@@ -1509,6 +1543,7 @@
 class Helper:
     keywords = {
         'and': 'BOOLEAN',
+        'as': 'with',
         'assert': ('ref/assert', ''),
         'break': ('ref/break', 'while for'),
         'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
@@ -1536,6 +1571,7 @@
         'return': ('ref/return', 'FUNCTIONS'),
         'try': ('ref/try', 'EXCEPTIONS'),
         'while': ('ref/while', 'break continue if TRUTHVALUE'),
+        'with': ('ref/with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
         'yield': ('ref/yield', ''),
     }
 
@@ -1549,7 +1585,7 @@
         'INTEGER': ('ref/integers', 'int range'),
         'FLOAT': ('ref/floating', 'float math'),
         'COMPLEX': ('ref/imaginary', 'complex cmath'),
-        'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
+        'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING range LISTS'),
         'MAPPINGS': 'DICTIONARIES',
         'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
         'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
@@ -1616,6 +1652,7 @@
         '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'),
     }
 
     def __init__(self, input, output):
@@ -1624,16 +1661,21 @@
         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'),
-                    os.path.join(execdir, 'doc'),
-                    '/usr/doc/python-docs-' + split(sys.version)[0],
-                    '/usr/doc/python-' + split(sys.version)[0],
-                    '/usr/doc/python-docs-' + sys.version[:3],
-                    '/usr/doc/python-' + sys.version[:3],
-                    os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]:
-            if dir and os.path.isdir(os.path.join(dir, 'lib')):
+                    join(execdir, 'doc'), # for Windows
+                    join(sys.prefix, 'doc/python-docs-' + sys.version.split()[0]),
+                    join(sys.prefix, 'doc/python-' + sys.version.split()[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] == '?':
@@ -1662,8 +1704,8 @@
                 if not request: break
             except (KeyboardInterrupt, EOFError):
                 break
-            request = strip(replace(request, '"', '', "'", ''))
-            if lower(request) in ('q', 'quit'): break
+            request = replace(request, '"', '', "'", '').strip()
+            if request.lower() in ('q', 'quit'): break
             self.help(request)
 
     def getline(self, prompt):
@@ -1682,7 +1724,7 @@
             elif request == 'topics': self.listtopics()
             elif request == 'modules': self.listmodules()
             elif request[:8] == 'modules ':
-                self.listmodules(split(request)[1])
+                self.listmodules(request.split()[1])
             elif request in self.keywords: self.showtopic(request)
             elif request in self.topics: self.showtopic(request)
             elif request: doc(request, 'Help on %s:')
@@ -1708,17 +1750,16 @@
 ''' % sys.version[:3])
 
     def list(self, items, columns=4, width=80):
-        items = items[:]
-        items.sort()
-        colw = width / columns
-        rows = (len(items) + columns - 1) / columns
+        items = list(sorted(items))
+        colw = width // columns
+        rows = (len(items) + columns - 1) // columns
         for row in range(rows):
             for col in range(columns):
                 i = col * rows + row
                 if i < len(items):
                     self.output.write(items[i])
                     if col < columns - 1:
-                        self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
+                        self.output.write(' ' + ' ' * (colw - 1 - len(items[i])))
             self.output.write('\n')
 
     def listkeywords(self):
@@ -1776,11 +1817,11 @@
         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('  ' + buffer.strip() + '\n')
         if xrefs:
             buffer = StringIO.StringIO()
             formatter.DumbWriter(buffer).send_flowing_data(
-                'Related help topics: ' + join(split(xrefs), ', ') + '\n')
+                'Related help topics: ' + ', '.join(xrefs.split()) + '\n')
             self.output.write('\n%s\n' % buffer.getvalue())
 
     def listmodules(self, key=''):
@@ -1799,7 +1840,7 @@
             def callback(path, modname, desc, modules=modules):
                 if modname and modname[-9:] == '.__init__':
                     modname = modname[:-9] + ' (package)'
-                if find(modname, '.') < 0:
+                if modname.find('.') < 0:
                     modules[modname] = 1
             ModuleScanner().run(callback)
             self.list(modules.keys())
@@ -1838,7 +1879,7 @@
     """An interruptible scanner that searches module synopses."""
 
     def run(self, callback, key=None, completer=None):
-        if key: key = lower(key)
+        if key: key = key.lower()
         self.quit = False
         seen = {}
 
@@ -1848,8 +1889,10 @@
                 if key is None:
                     callback(None, modname, '')
                 else:
-                    desc = split(__import__(modname).__doc__ or '', '\n')[0]
-                    if find(lower(modname + ' - ' + desc), key) >= 0:
+                    name = __import__(modname).__doc__ or ''
+                    desc = name.split('\n')[0]
+                    name = modname + ' - ' + desc
+                    if name.lower().find(key) >= 0:
                         callback(None, modname, desc)
 
         for importer, modname, ispkg in pkgutil.walk_packages():
@@ -1872,7 +1915,8 @@
                     module = loader.load_module(modname)
                     desc = (module.__doc__ or '').splitlines()[0]
                     path = getattr(module,'__file__',None)
-                if find(lower(modname + ' - ' + desc), key) >= 0:
+                name = modname + ' - ' + desc
+                if name.lower().find(key) >= 0:
                     callback(path, modname, desc)
 
         if completer:
@@ -1943,7 +1987,7 @@
                 seen = {}
                 for dir in sys.path:
                     indices.append(html.index(dir, seen))
-                contents = heading + join(indices) + '''<p align=right>
+                contents = heading + ' '.join(indices) + '''<p align=right>
 <font color="#909090" face="helvetica, arial"><strong>
 pydoc</strong> by Ka-Ping Yee &lt;ping at lfw.org&gt;</font>'''
                 self.send_document('Index of Modules', contents)
@@ -2125,7 +2169,7 @@
         def goto(self, event=None):
             selection = self.result_lst.curselection()
             if selection:
-                modname = split(self.result_lst.get(selection[0]))[0]
+                modname = self.result_lst.get(selection[0]).split()[0]
                 self.open(url=self.server.url + modname + '.html')
 
         def collapse(self):
@@ -2170,12 +2214,12 @@
 # -------------------------------------------------- command-line interface
 
 def ispath(x):
-    return isinstance(x, str) and find(x, os.sep) >= 0
+    return isinstance(x, str) and x.find(os.sep) >= 0
 
 def cli():
     """Command-line interface (looks at sys.argv to decide what to do)."""
     import getopt
-    class BadUsage: pass
+    class BadUsage(Exception): pass
 
     # Scripts don't get the current directory in their path by default.
     scriptdir = os.path.dirname(sys.argv[0])

Modified: python/branches/p3yk-noslice/Lib/random.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/random.py	(original)
+++ python/branches/p3yk-noslice/Lib/random.py	Wed Jul 11 15:40:56 2007
@@ -110,19 +110,19 @@
                 import time
                 a = int(time.time() * 256) # use fractional seconds
 
-        super(Random, self).seed(a)
+        super().seed(a)
         self.gauss_next = None
 
     def getstate(self):
         """Return internal state; can be passed to setstate() later."""
-        return self.VERSION, super(Random, self).getstate(), self.gauss_next
+        return self.VERSION, super().getstate(), self.gauss_next
 
     def setstate(self, state):
         """Restore internal state from object returned by getstate()."""
         version = state[0]
         if version == 2:
             version, internalstate, self.gauss_next = state
-            super(Random, self).setstate(internalstate)
+            super().setstate(internalstate)
         else:
             raise ValueError("state with version %s passed to "
                              "Random.setstate() of version %s" %
@@ -256,7 +256,7 @@
 
         if random is None:
             random = self.random
-        for i in reversed(xrange(1, len(x))):
+        for i in reversed(range(1, len(x))):
             # pick an element in x[:i+1] with which to exchange x[i]
             j = int(random() * (i+1))
             x[i], x[j] = x[j], x[i]
@@ -274,9 +274,9 @@
         population contains repeats, then each occurrence is a possible
         selection in the sample.
 
-        To choose a sample in a range of integers, use xrange as an argument.
+        To choose a sample in a range of integers, use range as an argument.
         This is especially fast and space efficient for sampling from a
-        large population:   sample(xrange(10000000), 60)
+        large population:   sample(range(10000000), 60)
         """
 
         # XXX Although the documentation says `population` is "a sequence",
@@ -311,7 +311,7 @@
             # An n-length list is smaller than a k-length set, or this is a
             # mapping type so the other algorithm wouldn't work.
             pool = list(population)
-            for i in xrange(k):         # invariant:  non-selected at [0,n-i)
+            for i in range(k):         # invariant:  non-selected at [0,n-i)
                 j = _int(random() * (n-i))
                 result[i] = pool[j]
                 pool[j] = pool[n-i-1]   # move non-selected item into vacancy
@@ -319,7 +319,7 @@
             try:
                 selected = set()
                 selected_add = selected.add
-                for i in xrange(k):
+                for i in range(k):
                     j = _int(random() * n)
                     while j in selected:
                         j = _int(random() * n)

Modified: python/branches/p3yk-noslice/Lib/re.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/re.py	(original)
+++ python/branches/p3yk-noslice/Lib/re.py	Wed Jul 11 15:40:56 2007
@@ -306,7 +306,7 @@
             if i == j:
                 break
             action = self.lexicon[m.lastindex-1][1]
-            if callable(action):
+            if hasattr(action, '__call__'):
                 self.match = m
                 action = action(self, m.group())
             if action is not None:

Modified: python/branches/p3yk-noslice/Lib/repr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/repr.py	(original)
+++ python/branches/p3yk-noslice/Lib/repr.py	Wed Jul 11 15:40:56 2007
@@ -47,7 +47,7 @@
         return '%s%s%s' % (left, s, right)
 
     def repr_tuple(self, x, level):
-        return self._repr_iterable(x, level, '(', ')', self.maxlist, ',')
+        return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',')
 
     def repr_list(self, x, level):
         return self._repr_iterable(x, level, '[', ']', self.maxlist)

Deleted: /python/branches/p3yk-noslice/Lib/rexec.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/rexec.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,585 +0,0 @@
-"""Restricted execution facilities.
-
-The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
-r_import(), which correspond roughly to the built-in operations
-exec, eval(), execfile() and import, but executing the code in an
-environment that only exposes those built-in operations that are
-deemed safe.  To this end, a modest collection of 'fake' modules is
-created which mimics the standard modules by the same names.  It is a
-policy decision which built-in modules and operations are made
-available; this module provides a reasonable default, but derived
-classes can change the policies e.g. by overriding or extending class
-variables like ok_builtin_modules or methods like make_sys().
-
-XXX To do:
-- r_open should allow writing tmp dir
-- r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)
-
-"""
-
-
-import sys
-import __builtin__
-import os
-import ihooks
-import imp
-
-__all__ = ["RExec"]
-
-class FileBase:
-
-    ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
-            'readlines', 'seek', 'tell', 'write', 'writelines', 
-            '__iter__')
-
-
-class FileWrapper(FileBase):
-
-    # XXX This is just like a Bastion -- should use that!
-
-    def __init__(self, f):
-        for m in self.ok_file_methods:
-            if not hasattr(self, m) and hasattr(f, m):
-                setattr(self, m, getattr(f, m))
-
-    def close(self):
-        self.flush()
-
-
-TEMPLATE = """
-def %s(self, *args):
-        return getattr(self.mod, self.name).%s(*args)
-"""
-
-class FileDelegate(FileBase):
-
-    def __init__(self, mod, name):
-        self.mod = mod
-        self.name = name
-
-    for m in FileBase.ok_file_methods + ('close',):
-        exec(TEMPLATE % (m, m))
-
-
-class RHooks(ihooks.Hooks):
-
-    def __init__(self, *args):
-        # Hacks to support both old and new interfaces:
-        # old interface was RHooks(rexec[, verbose])
-        # new interface is RHooks([verbose])
-        verbose = 0
-        rexec = None
-        if args and type(args[-1]) == type(0):
-            verbose = args[-1]
-            args = args[:-1]
-        if args and hasattr(args[0], '__class__'):
-            rexec = args[0]
-            args = args[1:]
-        if args:
-            raise TypeError, "too many arguments"
-        ihooks.Hooks.__init__(self, verbose)
-        self.rexec = rexec
-
-    def set_rexec(self, rexec):
-        # Called by RExec instance to complete initialization
-        self.rexec = rexec
-
-    def get_suffixes(self):
-        return self.rexec.get_suffixes()
-
-    def is_builtin(self, name):
-        return self.rexec.is_builtin(name)
-
-    def init_builtin(self, name):
-        m = __import__(name)
-        return self.rexec.copy_except(m, ())
-
-    def init_frozen(self, name): raise SystemError, "don't use this"
-    def load_source(self, *args): raise SystemError, "don't use this"
-    def load_compiled(self, *args): raise SystemError, "don't use this"
-    def load_package(self, *args): raise SystemError, "don't use this"
-
-    def load_dynamic(self, name, filename, file):
-        return self.rexec.load_dynamic(name, filename, file)
-
-    def add_module(self, name):
-        return self.rexec.add_module(name)
-
-    def modules_dict(self):
-        return self.rexec.modules
-
-    def default_path(self):
-        return self.rexec.modules['sys'].path
-
-
-# XXX Backwards compatibility
-RModuleLoader = ihooks.FancyModuleLoader
-RModuleImporter = ihooks.ModuleImporter
-
-
-class RExec(ihooks._Verbose):
-    """Basic restricted execution framework.
-
-    Code executed in this restricted environment will only have access to
-    modules and functions that are deemed safe; you can subclass RExec to
-    add or remove capabilities as desired.
-
-    The RExec class can prevent code from performing unsafe operations like
-    reading or writing disk files, or using TCP/IP sockets.  However, it does
-    not protect against code using extremely large amounts of memory or
-    processor time.
-
-    """
-
-    ok_path = tuple(sys.path)           # That's a policy decision
-
-    ok_builtin_modules = ('audioop', 'array', 'binascii',
-                          'cmath', 'errno', 'imageop',
-                          'marshal', 'math', 'md5', 'operator',
-                          'parser', 'select',
-                          'sha', '_sre', 'strop', 'struct', 'time',
-                          '_weakref')
-
-    ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
-                      'stat', 'times', 'uname', 'getpid', 'getppid',
-                      'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
-
-    ok_sys_names = ('byteorder', 'copyright', 'exit', 'getdefaultencoding',
-                    'getrefcount', 'hexversion', 'maxint', 'maxunicode',
-                    'platform', 'ps1', 'ps2', 'version', 'version_info')
-
-    nok_builtin_names = ('open', 'file', 'reload', '__import__')
-
-    ok_file_types = (imp.C_EXTENSION, imp.PY_SOURCE)
-
-    def __init__(self, hooks = None, verbose = 0):
-        """Returns an instance of the RExec class.
-
-        The hooks parameter is an instance of the RHooks class or a subclass
-        of it.  If it is omitted or None, the default RHooks class is
-        instantiated.
-
-        Whenever the RExec module searches for a module (even a built-in one)
-        or reads a module's code, it doesn't actually go out to the file
-        system itself.  Rather, it calls methods of an RHooks instance that
-        was passed to or created by its constructor.  (Actually, the RExec
-        object doesn't make these calls --- they are made by a module loader
-        object that's part of the RExec object.  This allows another level of
-        flexibility, which can be useful when changing the mechanics of
-        import within the restricted environment.)
-
-        By providing an alternate RHooks object, we can control the file
-        system accesses made to import a module, without changing the
-        actual algorithm that controls the order in which those accesses are
-        made.  For instance, we could substitute an RHooks object that
-        passes all filesystem requests to a file server elsewhere, via some
-        RPC mechanism such as ILU.  Grail's applet loader uses this to support
-        importing applets from a URL for a directory.
-
-        If the verbose parameter is true, additional debugging output may be
-        sent to standard output.
-
-        """
-
-        raise RuntimeError, "This code is not secure in Python 2.2 and 2.3"
-
-        ihooks._Verbose.__init__(self, verbose)
-        # XXX There's a circular reference here:
-        self.hooks = hooks or RHooks(verbose)
-        self.hooks.set_rexec(self)
-        self.modules = {}
-        self.ok_dynamic_modules = self.ok_builtin_modules
-        list = []
-        for mname in self.ok_builtin_modules:
-            if mname in sys.builtin_module_names:
-                list.append(mname)
-        self.ok_builtin_modules = tuple(list)
-        self.set_trusted_path()
-        self.make_builtin()
-        self.make_initial_modules()
-        # make_sys must be last because it adds the already created
-        # modules to its builtin_module_names
-        self.make_sys()
-        self.loader = RModuleLoader(self.hooks, verbose)
-        self.importer = RModuleImporter(self.loader, verbose)
-
-    def set_trusted_path(self):
-        # Set the path from which dynamic modules may be loaded.
-        # Those dynamic modules must also occur in ok_builtin_modules
-        self.trusted_path = filter(os.path.isabs, sys.path)
-
-    def load_dynamic(self, name, filename, file):
-        if name not in self.ok_dynamic_modules:
-            raise ImportError, "untrusted dynamic module: %s" % name
-        if name in sys.modules:
-            src = sys.modules[name]
-        else:
-            src = imp.load_dynamic(name, filename, file)
-        dst = self.copy_except(src, [])
-        return dst
-
-    def make_initial_modules(self):
-        self.make_main()
-        self.make_osname()
-
-    # Helpers for RHooks
-
-    def get_suffixes(self):
-        return [item   # (suff, mode, type)
-                for item in imp.get_suffixes()
-                if item[2] in self.ok_file_types]
-
-    def is_builtin(self, mname):
-        return mname in self.ok_builtin_modules
-
-    # The make_* methods create specific built-in modules
-
-    def make_builtin(self):
-        m = self.copy_except(__builtin__, self.nok_builtin_names)
-        m.__import__ = self.r_import
-        m.reload = self.r_reload
-        m.open = m.file = self.r_open
-
-    def make_main(self):
-        m = self.add_module('__main__')
-
-    def make_osname(self):
-        osname = os.name
-        src = __import__(osname)
-        dst = self.copy_only(src, self.ok_posix_names)
-        dst.environ = e = {}
-        for key, value in os.environ.items():
-            e[key] = value
-
-    def make_sys(self):
-        m = self.copy_only(sys, self.ok_sys_names)
-        m.modules = self.modules
-        m.argv = ['RESTRICTED']
-        m.path = map(None, self.ok_path)
-        m.exc_info = self.r_exc_info
-        m = self.modules['sys']
-        l = self.modules.keys() + list(self.ok_builtin_modules)
-        l.sort()
-        m.builtin_module_names = tuple(l)
-
-    # The copy_* methods copy existing modules with some changes
-
-    def copy_except(self, src, exceptions):
-        dst = self.copy_none(src)
-        for name in dir(src):
-            setattr(dst, name, getattr(src, name))
-        for name in exceptions:
-            try:
-                delattr(dst, name)
-            except AttributeError:
-                pass
-        return dst
-
-    def copy_only(self, src, names):
-        dst = self.copy_none(src)
-        for name in names:
-            try:
-                value = getattr(src, name)
-            except AttributeError:
-                continue
-            setattr(dst, name, value)
-        return dst
-
-    def copy_none(self, src):
-        m = self.add_module(src.__name__)
-        m.__doc__ = src.__doc__
-        return m
-
-    # Add a module -- return an existing module or create one
-
-    def add_module(self, mname):
-        m = self.modules.get(mname)
-        if m is None:
-            self.modules[mname] = m = self.hooks.new_module(mname)
-        m.__builtins__ = self.modules['__builtin__']
-        return m
-
-    # The r* methods are public interfaces
-
-    def r_exec(self, code):
-        """Execute code within a restricted environment.
-
-        The code parameter must either be a string containing one or more
-        lines of Python code, or a compiled code object, which will be
-        executed in the restricted environment's __main__ module.
-
-        """
-        m = self.add_module('__main__')
-        exec(code, m.__dict__)
-
-    def r_eval(self, code):
-        """Evaluate code within a restricted environment.
-
-        The code parameter must either be a string containing a Python
-        expression, or a compiled code object, which will be evaluated in
-        the restricted environment's __main__ module.  The value of the
-        expression or code object will be returned.
-
-        """
-        m = self.add_module('__main__')
-        return eval(code, m.__dict__)
-
-    def r_execfile(self, file):
-        """Execute the Python code in the file in the restricted
-        environment's __main__ module.
-
-        """
-        m = self.add_module('__main__')
-        execfile(file, m.__dict__)
-
-    def r_import(self, mname, globals={}, locals={}, fromlist=[]):
-        """Import a module, raising an ImportError exception if the module
-        is considered unsafe.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        """
-        return self.importer.import_module(mname, globals, locals, fromlist)
-
-    def r_reload(self, m):
-        """Reload the module object, re-parsing and re-initializing it.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        """
-        return self.importer.reload(m)
-
-    def r_unload(self, m):
-        """Unload the module.
-
-        Removes it from the restricted environment's sys.modules dictionary.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        """
-        return self.importer.unload(m)
-
-    # The s_* methods are similar but also swap std{in,out,err}
-
-    def make_delegate_files(self):
-        s = self.modules['sys']
-        self.delegate_stdin = FileDelegate(s, 'stdin')
-        self.delegate_stdout = FileDelegate(s, 'stdout')
-        self.delegate_stderr = FileDelegate(s, 'stderr')
-        self.restricted_stdin = FileWrapper(sys.stdin)
-        self.restricted_stdout = FileWrapper(sys.stdout)
-        self.restricted_stderr = FileWrapper(sys.stderr)
-
-    def set_files(self):
-        if not hasattr(self, 'save_stdin'):
-            self.save_files()
-        if not hasattr(self, 'delegate_stdin'):
-            self.make_delegate_files()
-        s = self.modules['sys']
-        s.stdin = self.restricted_stdin
-        s.stdout = self.restricted_stdout
-        s.stderr = self.restricted_stderr
-        sys.stdin = self.delegate_stdin
-        sys.stdout = self.delegate_stdout
-        sys.stderr = self.delegate_stderr
-
-    def reset_files(self):
-        self.restore_files()
-        s = self.modules['sys']
-        self.restricted_stdin = s.stdin
-        self.restricted_stdout = s.stdout
-        self.restricted_stderr = s.stderr
-
-
-    def save_files(self):
-        self.save_stdin = sys.stdin
-        self.save_stdout = sys.stdout
-        self.save_stderr = sys.stderr
-
-    def restore_files(self):
-        sys.stdin = self.save_stdin
-        sys.stdout = self.save_stdout
-        sys.stderr = self.save_stderr
-
-    def s_apply(self, func, args=(), kw={}):
-        self.save_files()
-        try:
-            self.set_files()
-            r = func(*args, **kw)
-        finally:
-            self.restore_files()
-        return r
-
-    def s_exec(self, *args):
-        """Execute code within a restricted environment.
-
-        Similar to the r_exec() method, but the code will be granted access
-        to restricted versions of the standard I/O streams sys.stdin,
-        sys.stderr, and sys.stdout.
-
-        The code parameter must either be a string containing one or more
-        lines of Python code, or a compiled code object, which will be
-        executed in the restricted environment's __main__ module.
-
-        """
-        return self.s_apply(self.r_exec, args)
-
-    def s_eval(self, *args):
-        """Evaluate code within a restricted environment.
-
-        Similar to the r_eval() method, but the code will be granted access
-        to restricted versions of the standard I/O streams sys.stdin,
-        sys.stderr, and sys.stdout.
-
-        The code parameter must either be a string containing a Python
-        expression, or a compiled code object, which will be evaluated in
-        the restricted environment's __main__ module.  The value of the
-        expression or code object will be returned.
-
-        """
-        return self.s_apply(self.r_eval, args)
-
-    def s_execfile(self, *args):
-        """Execute the Python code in the file in the restricted
-        environment's __main__ module.
-
-        Similar to the r_execfile() method, but the code will be granted
-        access to restricted versions of the standard I/O streams sys.stdin,
-        sys.stderr, and sys.stdout.
-
-        """
-        return self.s_apply(self.r_execfile, args)
-
-    def s_import(self, *args):
-        """Import a module, raising an ImportError exception if the module
-        is considered unsafe.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        Similar to the r_import() method, but has access to restricted
-        versions of the standard I/O streams sys.stdin, sys.stderr, and
-        sys.stdout.
-
-        """
-        return self.s_apply(self.r_import, args)
-
-    def s_reload(self, *args):
-        """Reload the module object, re-parsing and re-initializing it.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        Similar to the r_reload() method, but has access to restricted
-        versions of the standard I/O streams sys.stdin, sys.stderr, and
-        sys.stdout.
-
-        """
-        return self.s_apply(self.r_reload, args)
-
-    def s_unload(self, *args):
-        """Unload the module.
-
-        Removes it from the restricted environment's sys.modules dictionary.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        Similar to the r_unload() method, but has access to restricted
-        versions of the standard I/O streams sys.stdin, sys.stderr, and
-        sys.stdout.
-
-        """
-        return self.s_apply(self.r_unload, args)
-
-    # Restricted open(...)
-
-    def r_open(self, file, mode='r', buf=-1):
-        """Method called when open() is called in the restricted environment.
-
-        The arguments are identical to those of the open() function, and a
-        file object (or a class instance compatible with file objects)
-        should be returned.  RExec's default behaviour is allow opening
-        any file for reading, but forbidding any attempt to write a file.
-
-        This method is implicitly called by code executing in the
-        restricted environment.  Overriding this method in a subclass is
-        used to change the policies enforced by a restricted environment.
-
-        """
-        mode = str(mode)
-        if mode not in ('r', 'rb'):
-            raise IOError, "can't open files for writing in restricted mode"
-        return open(file, mode, buf)
-
-    # Restricted version of sys.exc_info()
-
-    def r_exc_info(self):
-        ty, va, tr = sys.exc_info()
-        tr = None
-        return ty, va, tr
-
-
-def test():
-    import getopt, traceback
-    opts, args = getopt.getopt(sys.argv[1:], 'vt:')
-    verbose = 0
-    trusted = []
-    for o, a in opts:
-        if o == '-v':
-            verbose = verbose+1
-        if o == '-t':
-            trusted.append(a)
-    r = RExec(verbose=verbose)
-    if trusted:
-        r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
-    if args:
-        r.modules['sys'].argv = args
-        r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
-    else:
-        r.modules['sys'].path.insert(0, "")
-    fp = sys.stdin
-    if args and args[0] != '-':
-        try:
-            fp = open(args[0])
-        except IOError as msg:
-            print("%s: can't open file %r" % (sys.argv[0], args[0]))
-            return 1
-    if fp.isatty():
-        try:
-            import readline
-        except ImportError:
-            pass
-        import code
-        class RestrictedConsole(code.InteractiveConsole):
-            def runcode(self, co):
-                self.locals['__builtins__'] = r.modules['__builtin__']
-                r.s_apply(code.InteractiveConsole.runcode, (self, co))
-        try:
-            RestrictedConsole(r.modules['__main__'].__dict__).interact()
-        except SystemExit as n:
-            return n
-    else:
-        text = fp.read()
-        fp.close()
-        c = compile(text, fp.name, 'exec')
-        try:
-            r.s_exec(c)
-        except SystemExit as n:
-            return n
-        except:
-            traceback.print_exc()
-            return 1
-
-
-if __name__ == '__main__':
-    sys.exit(test())

Modified: python/branches/p3yk-noslice/Lib/robotparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/robotparser.py	(original)
+++ python/branches/p3yk-noslice/Lib/robotparser.py	Wed Jul 11 15:40:56 2007
@@ -65,7 +65,7 @@
             lines.append(line.strip())
             line = f.readline()
         self.errcode = opener.errcode
-        if self.errcode == 401 or self.errcode == 403:
+        if self.errcode in (401, 403):
             self.disallow_all = True
             _debug("disallow all")
         elif self.errcode >= 400:
@@ -168,10 +168,7 @@
 
 
     def __str__(self):
-        ret = ""
-        for entry in self.entries:
-            ret = ret + str(entry) + "\n"
-        return ret
+        return ''.join([str(entry) + "\n" for entry in self.entries])
 
 
 class RuleLine:
@@ -198,12 +195,12 @@
         self.rulelines = []
 
     def __str__(self):
-        ret = ""
+        ret = []
         for agent in self.useragents:
-            ret = ret + "User-agent: "+agent+"\n"
+            ret.extend(["User-agent: ", agent, "\n"])
         for line in self.rulelines:
-            ret = ret + str(line) + "\n"
-        return ret
+            ret.extend([str(line), "\n"])
+        return ''.join(ret)
 
     def applies_to(self, useragent):
         """check if this entry applies to the specified agent"""

Modified: python/branches/p3yk-noslice/Lib/sched.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sched.py	(original)
+++ python/branches/p3yk-noslice/Lib/sched.py	Wed Jul 11 15:40:56 2007
@@ -72,7 +72,7 @@
 
     def empty(self):
         """Check whether the queue is empty."""
-        return not not self.queue
+        return not self.queue
 
     def run(self):
         """Execute events until the queue is empty.

Deleted: /python/branches/p3yk-noslice/Lib/sha.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/sha.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,11 +0,0 @@
-# $Id$
-#
-#  Copyright (C) 2005   Gregory P. Smith (greg at electricrain.com)
-#  Licensed to PSF under a Contributor Agreement.
-
-from hashlib import sha1 as sha
-new = sha
-
-blocksize = 1        # legacy value (wrong in any useful sense)
-digest_size = 20
-digestsize = 20

Modified: python/branches/p3yk-noslice/Lib/shelve.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/shelve.py	(original)
+++ python/branches/p3yk-noslice/Lib/shelve.py	Wed Jul 11 15:40:56 2007
@@ -174,7 +174,7 @@
         return (key, Unpickler(f).load())
 
     def next(self):
-        (key, value) = self.dict.next()
+        (key, value) = next(self.dict)
         f = StringIO(value)
         return (key, Unpickler(f).load())
 

Modified: python/branches/p3yk-noslice/Lib/shlex.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/shlex.py	(original)
+++ python/branches/p3yk-noslice/Lib/shlex.py	Wed Jul 11 15:40:56 2007
@@ -265,14 +265,14 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         token = self.get_token()
         if token == self.eof:
             raise StopIteration
         return token
 
-def split(s, comments=False):
-    lex = shlex(s, posix=True)
+def split(s, comments=False, posix=True):
+    lex = shlex(s, posix=posix)
     lex.whitespace_split = True
     if not comments:
         lex.commenters = ''

Modified: python/branches/p3yk-noslice/Lib/site.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/site.py	(original)
+++ python/branches/p3yk-noslice/Lib/site.py	Wed Jul 11 15:40:56 2007
@@ -118,8 +118,10 @@
     return d
 
 def addpackage(sitedir, name, known_paths):
-    """Add a new path to known_paths by combining sitedir and 'name' or execute
-    sitedir if it starts with 'import'"""
+    """Process a .pth file within the site-packages directory:
+       For each line in the file, either combine it with sitedir to a path
+       and add that to known_paths, or execute it if it starts with 'import '.
+    """
     if known_paths is None:
         _init_pathinfo()
         reset = 1
@@ -134,7 +136,7 @@
         for line in f:
             if line.startswith("#"):
                 continue
-            if line.startswith("import"):
+            if line.startswith("import ") or line.startswith("import\t"):
                 exec(line)
                 continue
             line = line.rstrip()
@@ -400,6 +402,28 @@
             (err.__class__.__name__, err))
 
 
+def installnewio():
+    """Install new I/O library as default.
+
+    This is only done if $PYTHONNEWIO is set and non-empty.
+    """
+    if not os.getenv("PYTHONNEWIO"):
+        return
+    import io
+    # Trick so that open won't become a bound method when stored
+    # as a class variable (as dumbdbm does)
+    class open:
+        def __new__(cls, *args, **kwds):
+            return io.open(*args, **kwds)
+    __builtin__.classic_open = __builtin__.open
+    __builtin__.classic_file = __builtin__.file
+    __builtin__.open = open
+    __builtin__.file = open
+    sys.stdin = io.open(0, "r")
+    sys.stdout = io.open(1, "w")
+    sys.stderr = io.open(2, "w")
+
+
 def main():
     abs__file__()
     paths_in_sys = removeduppaths()
@@ -414,6 +438,7 @@
     sethelper()
     aliasmbcs()
     setencoding()
+    installnewio()
     execsitecustomize()
     # Remove sys.setdefaultencoding() so that users cannot change the
     # encoding after initialization.  The test for presence is needed when

Modified: python/branches/p3yk-noslice/Lib/smtplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/smtplib.py	(original)
+++ python/branches/p3yk-noslice/Lib/smtplib.py	Wed Jul 11 15:40:56 2007
@@ -226,10 +226,11 @@
     debuglevel = 0
     file = None
     helo_resp = None
+    ehlo_msg = "ehlo"
     ehlo_resp = None
     does_esmtp = 0
 
-    def __init__(self, host = '', port = 0, local_hostname = None):
+    def __init__(self, host='', port=0, local_hostname=None, timeout=None):
         """Initialize a new instance.
 
         If specified, `host' is the name of the remote host to which to
@@ -240,6 +241,7 @@
         the local hostname is found using socket.getfqdn().
 
         """
+        self.timeout = timeout
         self.esmtp_features = {}
         self.default_port = SMTP_PORT
         if host:
@@ -273,12 +275,11 @@
         """
         self.debuglevel = debuglevel
 
-    def _get_socket(self,af, socktype, proto,sa):
+    def _get_socket(self, port, host, timeout):
         # This makes it simpler for SMTP_SSL to use the SMTP connect code
         # and just alter the socket connection bit.
-        self.sock = socket.socket(af, socktype, proto)
         if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
-        self.sock.connect(sa)
+        return socket.create_connection((port, host), timeout)
 
     def connect(self, host='localhost', port = 0):
         """Connect to a host on a given port.
@@ -297,24 +298,10 @@
                 host, port = host[:i], host[i+1:]
                 try: port = int(port)
                 except ValueError:
-                    raise socket.error, "nonnumeric port"
+                    raise socket.error("nonnumeric port")
         if not port: port = self.default_port
         if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
-        msg = "getaddrinfo returns an empty list"
-        self.sock = None
-        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
-            af, socktype, proto, canonname, sa = res
-            try:
-                self._get_socket(af,socktype,proto,sa)
-            except socket.error as msg:
-                if self.debuglevel > 0: print('connect fail:', msg, file=stderr)
-                if self.sock:
-                    self.sock.close()
-                self.sock = None
-                continue
-            break
-        if not self.sock:
-            raise socket.error, msg
+        self.sock = self._get_socket(host, port, self.timeout)
         (code, msg) = self.getreply()
         if self.debuglevel > 0: print("connect:", msg, file=stderr)
         return (code, msg)
@@ -401,7 +388,7 @@
         host.
         """
         self.esmtp_features = {}
-        self.putcmd("ehlo", name or self.local_hostname)
+        self.putcmd(self.ehlo_msg, name or self.local_hostname)
         (code,msg)=self.getreply()
         # According to RFC1869 some (badly written)
         # MTA's will disconnect on an ehlo. Toss an exception if
@@ -731,21 +718,64 @@
     are also optional - they can contain a PEM formatted private key and
     certificate chain file for the SSL connection.
     """
-    def __init__(self, host = '', port = 0, local_hostname = None,
-                 keyfile = None, certfile = None):
+    def __init__(self, host='', port=0, local_hostname=None,
+                 keyfile=None, certfile=None, timeout=None):
         self.keyfile = keyfile
         self.certfile = certfile
-        SMTP.__init__(self,host,port,local_hostname)
+        SMTP.__init__(self, host, port, local_hostname, timeout)
         self.default_port = SMTP_SSL_PORT
 
-    def _get_socket(self,af, socktype, proto,sa):
-        self.sock = socket.socket(af, socktype, proto)
+    def _get_socket(self, host, port, timeout):
         if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
-        self.sock.connect(sa)
+        self.sock = socket.create_connection((host, port), timeout)
         sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
         self.sock = SSLFakeSocket(self.sock, sslobj)
         self.file = SSLFakeFile(sslobj)
 
+#
+# LMTP extension
+#
+LMTP_PORT = 2003
+
+class LMTP(SMTP):
+    """LMTP - Local Mail Transfer Protocol
+
+    The LMTP protocol, which is very similar to ESMTP, is heavily based
+    on the standard SMTP client. It's common to use Unix sockets for LMTP,
+    so our connect() method must support that as well as a regular
+    host:port server. To specify a Unix socket, you must use an absolute
+    path as the host, starting with a '/'.
+
+    Authentication is supported, using the regular SMTP mechanism. When
+    using a Unix socket, LMTP generally don't support or require any
+    authentication, but your mileage might vary."""
+
+    ehlo_msg = "lhlo"
+
+    def __init__(self, host = '', port = LMTP_PORT, local_hostname = None):
+        """Initialize a new instance."""
+        SMTP.__init__(self, host, port, local_hostname)
+
+    def connect(self, host = 'localhost', port = 0):
+        """Connect to the LMTP daemon, on either a Unix or a TCP socket."""
+        if host[0] != '/':
+            return SMTP.connect(self, host, port)
+
+        # Handle Unix-domain sockets.
+        try:
+            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+            self.sock.connect(host)
+        except socket.error as msg:
+            if self.debuglevel > 0: print>>stderr, 'connect fail:', host
+            if self.sock:
+                self.sock.close()
+            self.sock = None
+            raise socket.error(msg)
+        (code, msg) = self.getreply()
+        if self.debuglevel > 0: print>>stderr, "connect:", msg
+        return (code, msg)
+
+
 # Test the sendmail method, which tests most of the others.
 # Note: This always sends to localhost.
 if __name__ == '__main__':

Modified: python/branches/p3yk-noslice/Lib/socket.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/socket.py	(original)
+++ python/branches/p3yk-noslice/Lib/socket.py	Wed Jul 11 15:40:56 2007
@@ -24,6 +24,7 @@
 ssl() -- secure socket layer support (only available if configured)
 socket.getdefaulttimeout() -- get the default timeout value
 socket.setdefaulttimeout() -- set the default timeout value
+create_connection() -- connects to an address, with an optional timeout
 
  [*] not available on all platforms!
 
@@ -139,8 +140,6 @@
     __slots__ = []
     def _dummy(*args):
         raise error(EBADF, 'Bad file descriptor')
-    def close(self):
-        pass
     # All _delegate_methods must also be initialized here.
     send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
     __getattr__ = _dummy
@@ -159,7 +158,6 @@
             setattr(self, method, getattr(_sock, method))
 
     def close(self):
-        self._sock.close()
         self._sock = _closedsocket()
         dummy = self._sock._dummy
         for method in _delegate_methods:
@@ -409,8 +407,37 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         line = self.readline()
         if not line:
             raise StopIteration
         return line
+
+
+def create_connection(address, timeout=None):
+    """Connect to address (host, port) with an optional timeout.
+
+    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).
+    """
+
+    msg = "getaddrinfo returns an empty list"
+    host, port = address
+    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
+        af, socktype, proto, canonname, sa = res
+        sock = None
+        try:
+            sock = socket(af, socktype, proto)
+            if timeout is not None:
+                sock.settimeout(timeout)
+            sock.connect(sa)
+            return sock
+
+        except error as err:
+            msg = err
+            if sock is not None:
+                sock.close()
+
+    raise error(msg)

Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py	(original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py	Wed Jul 11 15:40:56 2007
@@ -40,12 +40,12 @@
                          sqlite.paramstyle)
 
     def CheckWarning(self):
-        self.assert_(issubclass(sqlite.Warning, StandardError),
-                     "Warning is not a subclass of StandardError")
+        self.assert_(issubclass(sqlite.Warning, Exception),
+                     "Warning is not a subclass of Exception")
 
     def CheckError(self):
-        self.failUnless(issubclass(sqlite.Error, StandardError),
-                        "Error is not a subclass of StandardError")
+        self.failUnless(issubclass(sqlite.Error, Exception),
+                        "Error is not a subclass of Exception")
 
     def CheckInterfaceError(self):
         self.failUnless(issubclass(sqlite.InterfaceError, sqlite.Error),
@@ -286,7 +286,7 @@
             def __init__(self):
                 self.value = 5
 
-            def next(self):
+            def __next__(self):
                 if self.value == 10:
                     raise StopIteration
                 else:

Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py	(original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py	Wed Jul 11 15:40:56 2007
@@ -51,10 +51,10 @@
         # reset before a rollback, but only those that are still in the
         # statement cache. The others are not accessible from the connection object.
         con = sqlite.connect(":memory:", cached_statements=5)
-        cursors = [con.cursor() for x in xrange(5)]
+        cursors = [con.cursor() for x in range(5)]
         cursors[0].execute("create table test(x)")
         for i in range(10):
-            cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in xrange(10)])
+            cursors[0].executemany("insert into test(x) values (?)", [(x,) for x in range(10)])
 
         for i in range(5):
             cursors[i].execute(" " * i + "select x from test")

Modified: python/branches/p3yk-noslice/Lib/sre.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sre.py	(original)
+++ python/branches/p3yk-noslice/Lib/sre.py	Wed Jul 11 15:40:56 2007
@@ -8,3 +8,6 @@
 
 from re import *
 from re import __all__
+
+# old pickles expect the _compile() reconstructor in this module
+from re import _compile

Modified: python/branches/p3yk-noslice/Lib/sre_compile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sre_compile.py	(original)
+++ python/branches/p3yk-noslice/Lib/sre_compile.py	Wed Jul 11 15:40:56 2007
@@ -280,7 +280,7 @@
 
 # To represent a big charset, first a bitmap of all characters in the
 # set is constructed. Then, this bitmap is sliced into chunks of 256
-# characters, duplicate chunks are eliminitated, and each chunk is
+# characters, duplicate chunks are eliminated, and each chunk is
 # given a number. In the compiled expression, the charset is
 # represented by a 16-bit word sequence, consisting of one word for
 # the number of different chunks, a sequence of 256 bytes (128 words)
@@ -318,7 +318,7 @@
             elif op is LITERAL:
                 charmap[fixup(av)] = 1
             elif op is RANGE:
-                for i in xrange(fixup(av[0]), fixup(av[1])+1):
+                for i in range(fixup(av[0]), fixup(av[1])+1):
                     charmap[i] = 1
             elif op is CATEGORY:
                 # XXX: could expand category
@@ -330,13 +330,13 @@
         if sys.maxunicode != 65535:
             # XXX: negation does not work with big charsets
             return charset
-        for i in xrange(65536):
+        for i in range(65536):
             charmap[i] = not charmap[i]
     comps = {}
     mapping = [0]*256
     block = 0
     data = []
-    for i in xrange(256):
+    for i in range(256):
         chunk = tuple(charmap[i*256:(i+1)*256])
         new = comps.setdefault(chunk, block)
         mapping[i] = new
@@ -461,7 +461,7 @@
         code.extend(prefix)
         # generate overlap table
         table = [-1] + ([0]*len(prefix))
-        for i in xrange(len(prefix)):
+        for i in range(len(prefix)):
             table[i+1] = table[i]+1
             while table[i+1] > 0 and prefix[i] != prefix[table[i+1]-1]:
                 table[i+1] = table[table[i+1]-1]+1

Modified: python/branches/p3yk-noslice/Lib/sre_parse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sre_parse.py	(original)
+++ python/branches/p3yk-noslice/Lib/sre_parse.py	Wed Jul 11 15:40:56 2007
@@ -101,7 +101,7 @@
         self.width = None
     def dump(self, level=0):
         nl = 1
-        seqtypes = type(()), type([])
+        seqtypes = (tuple, list)
         for op, av in self.data:
             print(level*"  " + op, end=' '); nl = 0
             if op == "in":
@@ -117,7 +117,7 @@
                         print(level*"  " + "or")
                     a.dump(level+1); nl = 1
                     i = i + 1
-            elif type(av) in seqtypes:
+            elif isinstance(av, seqtypes):
                 for a in av:
                     if isinstance(a, SubPattern):
                         if not nl: print()
@@ -707,7 +707,7 @@
         else:
             pappend((LITERAL, literal))
     sep = source[:0]
-    if type(sep) is type(""):
+    if isinstance(sep, str):
         makechar = chr
     else:
         makechar = unichr

Modified: python/branches/p3yk-noslice/Lib/stat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/stat.py	(original)
+++ python/branches/p3yk-noslice/Lib/stat.py	Wed Jul 11 15:40:56 2007
@@ -24,21 +24,21 @@
 # Extract bits from the mode
 
 def S_IMODE(mode):
-    return mode & 07777
+    return mode & 0o7777
 
 def S_IFMT(mode):
-    return mode & 0170000
+    return mode & 0o170000
 
 # Constants used as S_IFMT() for various file types
 # (not all are implemented on all systems)
 
-S_IFDIR  = 0040000
-S_IFCHR  = 0020000
-S_IFBLK  = 0060000
-S_IFREG  = 0100000
-S_IFIFO  = 0010000
-S_IFLNK  = 0120000
-S_IFSOCK = 0140000
+S_IFDIR  = 0o040000
+S_IFCHR  = 0o020000
+S_IFBLK  = 0o060000
+S_IFREG  = 0o100000
+S_IFIFO  = 0o010000
+S_IFLNK  = 0o120000
+S_IFSOCK = 0o140000
 
 # Functions to test for each file type
 
@@ -65,25 +65,25 @@
 
 # Names for permission bits
 
-S_ISUID = 04000
-S_ISGID = 02000
+S_ISUID = 0o4000
+S_ISGID = 0o2000
 S_ENFMT = S_ISGID
-S_ISVTX = 01000
-S_IREAD = 00400
-S_IWRITE = 00200
-S_IEXEC = 00100
-S_IRWXU = 00700
-S_IRUSR = 00400
-S_IWUSR = 00200
-S_IXUSR = 00100
-S_IRWXG = 00070
-S_IRGRP = 00040
-S_IWGRP = 00020
-S_IXGRP = 00010
-S_IRWXO = 00007
-S_IROTH = 00004
-S_IWOTH = 00002
-S_IXOTH = 00001
+S_ISVTX = 0o1000
+S_IREAD = 0o0400
+S_IWRITE = 0o0200
+S_IEXEC = 0o0100
+S_IRWXU = 0o0700
+S_IRUSR = 0o0400
+S_IWUSR = 0o0200
+S_IXUSR = 0o0100
+S_IRWXG = 0o0070
+S_IRGRP = 0o0040
+S_IWGRP = 0o0020
+S_IXGRP = 0o0010
+S_IRWXO = 0o0007
+S_IROTH = 0o0004
+S_IWOTH = 0o0002
+S_IXOTH = 0o0001
 
 # Names for file flags
 

Modified: python/branches/p3yk-noslice/Lib/string.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/string.py	(original)
+++ python/branches/p3yk-noslice/Lib/string.py	Wed Jul 11 15:40:56 2007
@@ -1,9 +1,4 @@
-"""A collection of string operations (most are no longer used).
-
-Warning: most of the code you see here isn't normally used nowadays.
-Beginning with Python 1.6, many of these functions are implemented as
-methods on the standard string object. They used to be implemented by
-a built-in module called strop, but strop is now obsolete itself.
+"""A collection of string constants.
 
 Public module variables:
 
@@ -35,9 +30,7 @@
 
 # Case conversion helpers
 # Use str to convert Unicode literal in case of -U
-l = map(chr, xrange(256))
-_idmap = str('').join(l)
-del l
+_idmap = str('').join(chr(c) for c in range(256))
 
 # Functions which aren't available as string methods.
 
@@ -68,11 +61,10 @@
         raise ValueError, "maketrans arguments must have same length"
     global _idmapL
     if not _idmapL:
-        _idmapL = map(None, _idmap)
+        _idmapL = list(_idmap)
     L = _idmapL[:]
-    fromstr = map(ord, fromstr)
-    for i in range(len(fromstr)):
-        L[fromstr[i]] = tostr[i]
+    for i, c in enumerate(fromstr):
+        L[ord(c)] = tostr[i]
     return ''.join(L)
 
 
@@ -108,7 +100,7 @@
     """
 
     def __init__(cls, name, bases, dct):
-        super(_TemplateMetaclass, cls).__init__(name, bases, dct)
+        super().__init__(name, bases, dct)
         if 'pattern' in dct:
             pattern = cls.pattern
         else:
@@ -119,9 +111,8 @@
         cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
 
 
-class Template:
+class Template(metaclass=_TemplateMetaclass):
     """A string class for supporting $-substitutions."""
-    __metaclass__ = _TemplateMetaclass
 
     delimiter = '$'
     idpattern = r'[_a-z][_a-z0-9]*'
@@ -201,329 +192,3 @@
             raise ValueError('Unrecognized named group in pattern',
                              self.pattern)
         return self.pattern.sub(convert, self.template)
-
-
-
-####################################################################
-# NOTE: Everything below here is deprecated.  Use string methods instead.
-# This stuff will go away in Python 3.0.
-
-# Backward compatible names for exceptions
-index_error = ValueError
-atoi_error = ValueError
-atof_error = ValueError
-atol_error = ValueError
-
-# convert UPPER CASE letters to lower case
-def lower(s):
-    """lower(s) -> string
-
-    Return a copy of the string s converted to lowercase.
-
-    """
-    return s.lower()
-
-# Convert lower case letters to UPPER CASE
-def upper(s):
-    """upper(s) -> string
-
-    Return a copy of the string s converted to uppercase.
-
-    """
-    return s.upper()
-
-# Swap lower case letters and UPPER CASE
-def swapcase(s):
-    """swapcase(s) -> string
-
-    Return a copy of the string s with upper case characters
-    converted to lowercase and vice versa.
-
-    """
-    return s.swapcase()
-
-# Strip leading and trailing tabs and spaces
-def strip(s, chars=None):
-    """strip(s [,chars]) -> string
-
-    Return a copy of the string s with leading and trailing
-    whitespace removed.
-    If chars is given and not None, remove characters in chars instead.
-    If chars is unicode, S will be converted to unicode before stripping.
-
-    """
-    return s.strip(chars)
-
-# Strip leading tabs and spaces
-def lstrip(s, chars=None):
-    """lstrip(s [,chars]) -> string
-
-    Return a copy of the string s with leading whitespace removed.
-    If chars is given and not None, remove characters in chars instead.
-
-    """
-    return s.lstrip(chars)
-
-# Strip trailing tabs and spaces
-def rstrip(s, chars=None):
-    """rstrip(s [,chars]) -> string
-
-    Return a copy of the string s with trailing whitespace removed.
-    If chars is given and not None, remove characters in chars instead.
-
-    """
-    return s.rstrip(chars)
-
-
-# Split a string into a list of space/tab-separated words
-def split(s, sep=None, maxsplit=-1):
-    """split(s [,sep [,maxsplit]]) -> list of strings
-
-    Return a list of the words in the string s, using sep as the
-    delimiter string.  If maxsplit is given, splits at no more than
-    maxsplit places (resulting in at most maxsplit+1 words).  If sep
-    is not specified or is None, any whitespace string is a separator.
-
-    (split and splitfields are synonymous)
-
-    """
-    return s.split(sep, maxsplit)
-splitfields = split
-
-# Split a string into a list of space/tab-separated words
-def rsplit(s, sep=None, maxsplit=-1):
-    """rsplit(s [,sep [,maxsplit]]) -> list of strings
-
-    Return a list of the words in the string s, using sep as the
-    delimiter string, starting at the end of the string and working
-    to the front.  If maxsplit is given, at most maxsplit splits are
-    done. If sep is not specified or is None, any whitespace string
-    is a separator.
-    """
-    return s.rsplit(sep, maxsplit)
-
-# Join fields with optional separator
-def join(words, sep = ' '):
-    """join(list [,sep]) -> string
-
-    Return a string composed of the words in list, with
-    intervening occurrences of sep.  The default separator is a
-    single space.
-
-    (joinfields and join are synonymous)
-
-    """
-    return sep.join(words)
-joinfields = join
-
-# Find substring, raise exception if not found
-def index(s, *args):
-    """index(s, sub [,start [,end]]) -> int
-
-    Like find but raises ValueError when the substring is not found.
-
-    """
-    return s.index(*args)
-
-# Find last substring, raise exception if not found
-def rindex(s, *args):
-    """rindex(s, sub [,start [,end]]) -> int
-
-    Like rfind but raises ValueError when the substring is not found.
-
-    """
-    return s.rindex(*args)
-
-# Count non-overlapping occurrences of substring
-def count(s, *args):
-    """count(s, sub[, start[,end]]) -> int
-
-    Return the number of occurrences of substring sub in string
-    s[start:end].  Optional arguments start and end are
-    interpreted as in slice notation.
-
-    """
-    return s.count(*args)
-
-# Find substring, return -1 if not found
-def find(s, *args):
-    """find(s, sub [,start [,end]]) -> in
-
-    Return the lowest index in s where substring sub is found,
-    such that sub is contained within s[start,end].  Optional
-    arguments start and end are interpreted as in slice notation.
-
-    Return -1 on failure.
-
-    """
-    return s.find(*args)
-
-# Find last substring, return -1 if not found
-def rfind(s, *args):
-    """rfind(s, sub [,start [,end]]) -> int
-
-    Return the highest index in s where substring sub is found,
-    such that sub is contained within s[start,end].  Optional
-    arguments start and end are interpreted as in slice notation.
-
-    Return -1 on failure.
-
-    """
-    return s.rfind(*args)
-
-# for a bit of speed
-_float = float
-_int = int
-_long = int
-
-# Convert string to float
-def atof(s):
-    """atof(s) -> float
-
-    Return the floating point number represented by the string s.
-
-    """
-    return _float(s)
-
-
-# Convert string to integer
-def atoi(s , base=10):
-    """atoi(s [,base]) -> int
-
-    Return the integer represented by the string s in the given
-    base, which defaults to 10.  The string s must consist of one
-    or more digits, possibly preceded by a sign.  If base is 0, it
-    is chosen from the leading characters of s, 0 for octal, 0x or
-    0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
-    accepted.
-
-    """
-    return _int(s, base)
-
-
-# Convert string to long integer
-def atol(s, base=10):
-    """atol(s [,base]) -> long
-
-    Return the long integer represented by the string s in the
-    given base, which defaults to 10.  The string s must consist
-    of one or more digits, possibly preceded by a sign.  If base
-    is 0, it is chosen from the leading characters of s, 0 for
-    octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
-    0x or 0X is accepted.  A trailing L or l is not accepted,
-    unless base is 0.
-
-    """
-    return _long(s, base)
-
-
-# Left-justify a string
-def ljust(s, width, *args):
-    """ljust(s, width[, fillchar]) -> string
-
-    Return a left-justified version of s, in a field of the
-    specified width, padded with spaces as needed.  The string is
-    never truncated.  If specified the fillchar is used instead of spaces.
-
-    """
-    return s.ljust(width, *args)
-
-# Right-justify a string
-def rjust(s, width, *args):
-    """rjust(s, width[, fillchar]) -> string
-
-    Return a right-justified version of s, in a field of the
-    specified width, padded with spaces as needed.  The string is
-    never truncated.  If specified the fillchar is used instead of spaces.
-
-    """
-    return s.rjust(width, *args)
-
-# Center a string
-def center(s, width, *args):
-    """center(s, width[, fillchar]) -> string
-
-    Return a center version of s, in a field of the specified
-    width. padded with spaces as needed.  The string is never
-    truncated.  If specified the fillchar is used instead of spaces.
-
-    """
-    return s.center(width, *args)
-
-# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
-# Decadent feature: the argument may be a string or a number
-# (Use of this is deprecated; it should be a string as with ljust c.s.)
-def zfill(x, width):
-    """zfill(x, width) -> string
-
-    Pad a numeric string x with zeros on the left, to fill a field
-    of the specified width.  The string x is never truncated.
-
-    """
-    if not isinstance(x, basestring):
-        x = repr(x)
-    return x.zfill(width)
-
-# Expand tabs in a string.
-# Doesn't take non-printing chars into account, but does understand \n.
-def expandtabs(s, tabsize=8):
-    """expandtabs(s [,tabsize]) -> string
-
-    Return a copy of the string s with all tab characters replaced
-    by the appropriate number of spaces, depending on the current
-    column, and the tabsize (default 8).
-
-    """
-    return s.expandtabs(tabsize)
-
-# Character translation through look-up table.
-def translate(s, table, deletions=""):
-    """translate(s,table [,deletions]) -> string
-
-    Return a copy of the string s, where all characters occurring
-    in the optional argument deletions are removed, and the
-    remaining characters have been mapped through the given
-    translation table, which must be a string of length 256.  The
-    deletions argument is not allowed for Unicode strings.
-
-    """
-    if deletions:
-        return s.translate(table, deletions)
-    else:
-        # Add s[:0] so that if s is Unicode and table is an 8-bit string,
-        # table is converted to Unicode.  This means that table *cannot*
-        # be a dictionary -- for that feature, use u.translate() directly.
-        return s.translate(table + s[:0])
-
-# Capitalize a string, e.g. "aBc  dEf" -> "Abc  def".
-def capitalize(s):
-    """capitalize(s) -> string
-
-    Return a copy of the string s with only its first character
-    capitalized.
-
-    """
-    return s.capitalize()
-
-# Substring replacement (global)
-def replace(s, old, new, maxsplit=-1):
-    """replace (str, old, new[, maxsplit]) -> string
-
-    Return a copy of string str with all occurrences of substring
-    old replaced by new. If the optional argument maxsplit is
-    given, only the first maxsplit occurrences are replaced.
-
-    """
-    return s.replace(old, new, maxsplit)
-
-
-# Try importing optional built-in module "strop" -- if it exists,
-# it redefines some string operations that are 100-1000 times faster.
-# It also defines values for whitespace, lowercase and uppercase
-# that match <ctype.h>'s definitions.
-
-try:
-    from strop import maketrans, lowercase, uppercase, whitespace
-    letters = lowercase + uppercase
-except ImportError:
-    pass                                          # Use the original versions

Deleted: /python/branches/p3yk-noslice/Lib/stringold.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/stringold.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,426 +0,0 @@
-# module 'string' -- A collection of string operations
-
-# Warning: most of the code you see here isn't normally used nowadays.  With
-# Python 1.6, many of these functions are implemented as methods on the
-# standard string object. They used to be implemented by a built-in module
-# called strop, but strop is now obsolete itself.
-
-"""Common string manipulations.
-
-Public module variables:
-
-whitespace -- a string containing all characters considered whitespace
-lowercase -- a string containing all characters considered lowercase letters
-uppercase -- a string containing all characters considered uppercase letters
-letters -- a string containing all characters considered letters
-digits -- a string containing all characters considered decimal digits
-hexdigits -- a string containing all characters considered hexadecimal digits
-octdigits -- a string containing all characters considered octal digits
-
-"""
-
-# Some strings for ctype-style character classification
-whitespace = ' \t\n\r\v\f'
-lowercase = 'abcdefghijklmnopqrstuvwxyz'
-uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-letters = lowercase + uppercase
-digits = '0123456789'
-hexdigits = digits + 'abcdef' + 'ABCDEF'
-octdigits = '01234567'
-
-# Case conversion helpers
-_idmap = ''
-for i in range(256): _idmap = _idmap + chr(i)
-del i
-
-# Backward compatible names for exceptions
-index_error = ValueError
-atoi_error = ValueError
-atof_error = ValueError
-atol_error = ValueError
-
-# convert UPPER CASE letters to lower case
-def lower(s):
-    """lower(s) -> string
-
-    Return a copy of the string s converted to lowercase.
-
-    """
-    return s.lower()
-
-# Convert lower case letters to UPPER CASE
-def upper(s):
-    """upper(s) -> string
-
-    Return a copy of the string s converted to uppercase.
-
-    """
-    return s.upper()
-
-# Swap lower case letters and UPPER CASE
-def swapcase(s):
-    """swapcase(s) -> string
-
-    Return a copy of the string s with upper case characters
-    converted to lowercase and vice versa.
-
-    """
-    return s.swapcase()
-
-# Strip leading and trailing tabs and spaces
-def strip(s):
-    """strip(s) -> string
-
-    Return a copy of the string s with leading and trailing
-    whitespace removed.
-
-    """
-    return s.strip()
-
-# Strip leading tabs and spaces
-def lstrip(s):
-    """lstrip(s) -> string
-
-    Return a copy of the string s with leading whitespace removed.
-
-    """
-    return s.lstrip()
-
-# Strip trailing tabs and spaces
-def rstrip(s):
-    """rstrip(s) -> string
-
-    Return a copy of the string s with trailing whitespace
-    removed.
-
-    """
-    return s.rstrip()
-
-
-# Split a string into a list of space/tab-separated words
-def split(s, sep=None, maxsplit=0):
-    """split(str [,sep [,maxsplit]]) -> list of strings
-
-    Return a list of the words in the string s, using sep as the
-    delimiter string.  If maxsplit is nonzero, splits into at most
-    maxsplit words If sep is not specified, any whitespace string
-    is a separator.  Maxsplit defaults to 0.
-
-    (split and splitfields are synonymous)
-
-    """
-    return s.split(sep, maxsplit)
-splitfields = split
-
-# Join fields with optional separator
-def join(words, sep = ' '):
-    """join(list [,sep]) -> string
-
-    Return a string composed of the words in list, with
-    intervening occurrences of sep.  The default separator is a
-    single space.
-
-    (joinfields and join are synonymous)
-
-    """
-    return sep.join(words)
-joinfields = join
-
-# Find substring, raise exception if not found
-def index(s, *args):
-    """index(s, sub [,start [,end]]) -> int
-
-    Like find but raises ValueError when the substring is not found.
-
-    """
-    return s.index(*args)
-
-# Find last substring, raise exception if not found
-def rindex(s, *args):
-    """rindex(s, sub [,start [,end]]) -> int
-
-    Like rfind but raises ValueError when the substring is not found.
-
-    """
-    return s.rindex(*args)
-
-# Count non-overlapping occurrences of substring
-def count(s, *args):
-    """count(s, sub[, start[,end]]) -> int
-
-    Return the number of occurrences of substring sub in string
-    s[start:end].  Optional arguments start and end are
-    interpreted as in slice notation.
-
-    """
-    return s.count(*args)
-
-# Find substring, return -1 if not found
-def find(s, *args):
-    """find(s, sub [,start [,end]]) -> in
-
-    Return the lowest index in s where substring sub is found,
-    such that sub is contained within s[start,end].  Optional
-    arguments start and end are interpreted as in slice notation.
-
-    Return -1 on failure.
-
-    """
-    return s.find(*args)
-
-# Find last substring, return -1 if not found
-def rfind(s, *args):
-    """rfind(s, sub [,start [,end]]) -> int
-
-    Return the highest index in s where substring sub is found,
-    such that sub is contained within s[start,end].  Optional
-    arguments start and end are interpreted as in slice notation.
-
-    Return -1 on failure.
-
-    """
-    return s.rfind(*args)
-
-# for a bit of speed
-_float = float
-_int = int
-_long = int
-_StringType = type('')
-
-# Convert string to float
-def atof(s):
-    """atof(s) -> float
-
-    Return the floating point number represented by the string s.
-
-    """
-    if type(s) == _StringType:
-        return _float(s)
-    else:
-        raise TypeError('argument 1: expected string, %s found' %
-                        type(s).__name__)
-
-# Convert string to integer
-def atoi(*args):
-    """atoi(s [,base]) -> int
-
-    Return the integer represented by the string s in the given
-    base, which defaults to 10.  The string s must consist of one
-    or more digits, possibly preceded by a sign.  If base is 0, it
-    is chosen from the leading characters of s, 0 for octal, 0x or
-    0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
-    accepted.
-
-    """
-    try:
-        s = args[0]
-    except IndexError:
-        raise TypeError('function requires at least 1 argument: %d given' %
-                        len(args))
-    # Don't catch type error resulting from too many arguments to int().  The
-    # error message isn't compatible but the error type is, and this function
-    # is complicated enough already.
-    if type(s) == _StringType:
-        return _int(*args)
-    else:
-        raise TypeError('argument 1: expected string, %s found' %
-                        type(s).__name__)
-
-
-# Convert string to long integer
-def atol(*args):
-    """atol(s [,base]) -> long
-
-    Return the long integer represented by the string s in the
-    given base, which defaults to 10.  The string s must consist
-    of one or more digits, possibly preceded by a sign.  If base
-    is 0, it is chosen from the leading characters of s, 0 for
-    octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
-    0x or 0X is accepted.  A trailing L or l is not accepted,
-    unless base is 0.
-
-    """
-    try:
-        s = args[0]
-    except IndexError:
-        raise TypeError('function requires at least 1 argument: %d given' %
-                        len(args))
-    # Don't catch type error resulting from too many arguments to long().  The
-    # error message isn't compatible but the error type is, and this function
-    # is complicated enough already.
-    if type(s) == _StringType:
-        return _long(*args)
-    else:
-        raise TypeError('argument 1: expected string, %s found' %
-                        type(s).__name__)
-
-
-# Left-justify a string
-def ljust(s, width):
-    """ljust(s, width) -> string
-
-    Return a left-justified version of s, in a field of the
-    specified width, padded with spaces as needed.  The string is
-    never truncated.
-
-    """
-    n = width - len(s)
-    if n <= 0: return s
-    return s + ' '*n
-
-# Right-justify a string
-def rjust(s, width):
-    """rjust(s, width) -> string
-
-    Return a right-justified version of s, in a field of the
-    specified width, padded with spaces as needed.  The string is
-    never truncated.
-
-    """
-    n = width - len(s)
-    if n <= 0: return s
-    return ' '*n + s
-
-# Center a string
-def center(s, width):
-    """center(s, width) -> string
-
-    Return a center version of s, in a field of the specified
-    width. padded with spaces as needed.  The string is never
-    truncated.
-
-    """
-    n = width - len(s)
-    if n <= 0: return s
-    half = n/2
-    if n%2 and width%2:
-        # This ensures that center(center(s, i), j) = center(s, j)
-        half = half+1
-    return ' '*half +  s + ' '*(n-half)
-
-# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
-# Decadent feature: the argument may be a string or a number
-# (Use of this is deprecated; it should be a string as with ljust c.s.)
-def zfill(x, width):
-    """zfill(x, width) -> string
-
-    Pad a numeric string x with zeros on the left, to fill a field
-    of the specified width.  The string x is never truncated.
-
-    """
-    if type(x) == type(''): s = x
-    else: s = repr(x)
-    n = len(s)
-    if n >= width: return s
-    sign = ''
-    if s[0] in ('-', '+'):
-        sign, s = s[0], s[1:]
-    return sign + '0'*(width-n) + s
-
-# Expand tabs in a string.
-# Doesn't take non-printing chars into account, but does understand \n.
-def expandtabs(s, tabsize=8):
-    """expandtabs(s [,tabsize]) -> string
-
-    Return a copy of the string s with all tab characters replaced
-    by the appropriate number of spaces, depending on the current
-    column, and the tabsize (default 8).
-
-    """
-    res = line = ''
-    for c in s:
-        if c == '\t':
-            c = ' '*(tabsize - len(line) % tabsize)
-        line = line + c
-        if c == '\n':
-            res = res + line
-            line = ''
-    return res + line
-
-# Character translation through look-up table.
-def translate(s, table, deletions=""):
-    """translate(s,table [,deletechars]) -> string
-
-    Return a copy of the string s, where all characters occurring
-    in the optional argument deletechars are removed, and the
-    remaining characters have been mapped through the given
-    translation table, which must be a string of length 256.
-
-    """
-    return s.translate(table, deletions)
-
-# Capitalize a string, e.g. "aBc  dEf" -> "Abc  def".
-def capitalize(s):
-    """capitalize(s) -> string
-
-    Return a copy of the string s with only its first character
-    capitalized.
-
-    """
-    return s.capitalize()
-
-# Capitalize the words in a string, e.g. " aBc  dEf " -> "Abc Def".
-def capwords(s, sep=None):
-    """capwords(s, [sep]) -> string
-
-    Split the argument into words using split, capitalize each
-    word using capitalize, and join the capitalized words using
-    join. Note that this replaces runs of whitespace characters by
-    a single space.
-
-    """
-    return join(map(capitalize, s.split(sep)), sep or ' ')
-
-# Construct a translation string
-_idmapL = None
-def maketrans(fromstr, tostr):
-    """maketrans(frm, to) -> string
-
-    Return a translation table (a string of 256 bytes long)
-    suitable for use in string.translate.  The strings frm and to
-    must be of the same length.
-
-    """
-    if len(fromstr) != len(tostr):
-        raise ValueError, "maketrans arguments must have same length"
-    global _idmapL
-    if not _idmapL:
-        _idmapL = map(None, _idmap)
-    L = _idmapL[:]
-    fromstr = map(ord, fromstr)
-    for i in range(len(fromstr)):
-        L[fromstr[i]] = tostr[i]
-    return join(L, "")
-
-# Substring replacement (global)
-def replace(s, old, new, maxsplit=0):
-    """replace (str, old, new[, maxsplit]) -> string
-
-    Return a copy of string str with all occurrences of substring
-    old replaced by new. If the optional argument maxsplit is
-    given, only the first maxsplit occurrences are replaced.
-
-    """
-    return s.replace(old, new, maxsplit)
-
-
-# XXX: transitional
-#
-# If string objects do not have methods, then we need to use the old string.py
-# library, which uses strop for many more things than just the few outlined
-# below.
-try:
-    ''.upper
-except AttributeError:
-    from stringold import *
-
-# Try importing optional built-in module "strop" -- if it exists,
-# it redefines some string operations that are 100-1000 times faster.
-# It also defines values for whitespace, lowercase and uppercase
-# that match <ctype.h>'s definitions.
-
-try:
-    from strop import maketrans, lowercase, uppercase, whitespace
-    letters = lowercase + uppercase
-except ImportError:
-    pass                                          # Use the original versions

Modified: python/branches/p3yk-noslice/Lib/stringprep.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/stringprep.py	(original)
+++ python/branches/p3yk-noslice/Lib/stringprep.py	Wed Jul 11 15:40:56 2007
@@ -16,7 +16,7 @@
     return (c & 0xFFFF) not in (0xFFFE, 0xFFFF)
 
 
-b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + range(65024,65040))
+b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + list(range(65024,65040)))
 def in_table_b1(code):
     return ord(code) in b1_set
 
@@ -217,7 +217,7 @@
 def in_table_c21(code):
     return ord(code) < 128 and unicodedata.category(code) == "Cc"
 
-c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + range(8288,8292) + range(8298,8304) + range(65529,65533) + range(119155,119163))
+c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + list(range(8288,8292)) + list(range(8298,8304)) + list(range(65529,65533)) + list(range(119155,119163)))
 def in_table_c22(code):
     c = ord(code)
     if c < 128: return False
@@ -254,12 +254,12 @@
     return ord(code) in c7_set
 
 
-c8_set = set([832, 833, 8206, 8207] + range(8234,8239) + range(8298,8304))
+c8_set = set([832, 833, 8206, 8207] + list(range(8234,8239)) + list(range(8298,8304)))
 def in_table_c8(code):
     return ord(code) in c8_set
 
 
-c9_set = set([917505] + range(917536,917632))
+c9_set = set([917505] + list(range(917536,917632)))
 def in_table_c9(code):
     return ord(code) in c9_set
 

Modified: python/branches/p3yk-noslice/Lib/subprocess.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/subprocess.py	(original)
+++ python/branches/p3yk-noslice/Lib/subprocess.py	Wed Jul 11 15:40:56 2007
@@ -17,8 +17,6 @@
 
 os.system
 os.spawn*
-os.popen*
-popen2.*
 commands.*
 
 Information about how the subprocess module can be used to replace these
@@ -283,80 +281,12 @@
 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
 ==>
 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
-
-
-Replacing os.popen*
--------------------
-pipe = os.popen(cmd, mode='r', bufsize)
-==>
-pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
-
-pipe = os.popen(cmd, mode='w', bufsize)
-==>
-pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
-
-
-(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
-==>
-p = Popen(cmd, shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdin, child_stdout) = (p.stdin, p.stdout)
-
-
-(child_stdin,
- child_stdout,
- child_stderr) = os.popen3(cmd, mode, bufsize)
-==>
-p = Popen(cmd, shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
-(child_stdin,
- child_stdout,
- child_stderr) = (p.stdin, p.stdout, p.stderr)
-
-
-(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
-==>
-p = Popen(cmd, shell=True, bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
-(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
-
-
-Replacing popen2.*
-------------------
-Note: If the cmd argument to popen2 functions is a string, the command
-is executed through /bin/sh.  If it is a list, the command is directly
-executed.
-
-(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
-==>
-p = Popen(["somestring"], shell=True, bufsize=bufsize
-          stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdout, child_stdin) = (p.stdout, p.stdin)
-
-
-(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
-==>
-p = Popen(["mycmd", "myarg"], bufsize=bufsize,
-          stdin=PIPE, stdout=PIPE, close_fds=True)
-(child_stdout, child_stdin) = (p.stdout, p.stdin)
-
-The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
-except that:
-
-* subprocess.Popen raises an exception if the execution fails
-* the capturestderr argument is replaced with the stderr argument.
-* stdin=PIPE and stdout=PIPE must be specified.
-* popen2 closes all filedescriptors by default, but you have to specify
-  close_fds=True with subprocess.Popen.
-
-
 """
 
 import sys
 mswindows = (sys.platform == "win32")
 
 import os
-import types
 import traceback
 
 # Exception classes used by this module.
@@ -409,13 +339,6 @@
 except:
     MAXFD = 256
 
-# True/False does not exist on 2.2.0
-try:
-    False
-except NameError:
-    False = 0
-    True = 1
-
 _active = []
 
 def _cleanup():
@@ -548,9 +471,10 @@
             if preexec_fn is not None:
                 raise ValueError("preexec_fn is not supported on Windows "
                                  "platforms")
-            if close_fds:
+            if close_fds and (stdin is not None or stdout is not None or
+                              stderr is not None):
                 raise ValueError("close_fds is not supported on Windows "
-                                 "platforms")
+                                 "platforms if you redirect stdin/stdout/stderr")
         else:
             # POSIX
             if startupinfo is not None:
@@ -597,7 +521,7 @@
         # either have to redirect all three or none. If the subprocess
         # user has only redirected one or two handles, we are
         # automatically creating PIPEs for the rest. We should close
-        # these after the process is started. See bug #1124861. 
+        # these after the process is started. See bug #1124861.
         if mswindows:
             if stdin is None and p2cwrite is not None:
                 os.close(p2cwrite)
@@ -629,7 +553,7 @@
         return data
 
 
-    def __del__(self):
+    def __del__(self, sys=sys):
         if not self._child_created:
             # We didn't get to successfully create a child process.
             return
@@ -769,7 +693,7 @@
                            errread, errwrite):
             """Execute program (MS Windows version)"""
 
-            if not isinstance(args, types.StringTypes):
+            if not isinstance(args, basestring):
                 args = list2cmdline(args)
 
             # Process startup details
@@ -807,9 +731,7 @@
                 hp, ht, pid, tid = CreateProcess(executable, args,
                                          # no special security
                                          None, None,
-                                         # must inherit handles to pass std
-                                         # handles
-                                         1,
+                                         int(not close_fds),
                                          creationflags,
                                          env,
                                          cwd,
@@ -969,7 +891,7 @@
 
 
         def _close_fds(self, but):
-            for i in xrange(3, MAXFD):
+            for i in range(3, MAXFD):
                 if i == but:
                     continue
                 try:
@@ -986,7 +908,7 @@
                            errread, errwrite):
             """Execute program (POSIX version)"""
 
-            if isinstance(args, types.StringTypes):
+            if isinstance(args, basestring):
                 args = [args]
             else:
                 args = list(args)

Modified: python/branches/p3yk-noslice/Lib/sunau.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sunau.py	(original)
+++ python/branches/p3yk-noslice/Lib/sunau.py	Wed Jul 11 15:40:56 2007
@@ -364,7 +364,8 @@
         else:
             return 'not compressed'
 
-    def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
+    def setparams(self, params):
+        nchannels, sampwidth, framerate, nframes, comptype, compname = params
         self.setnchannels(nchannels)
         self.setsampwidth(sampwidth)
         self.setframerate(framerate)

Modified: python/branches/p3yk-noslice/Lib/symbol.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/symbol.py	(original)
+++ python/branches/p3yk-noslice/Lib/symbol.py	Wed Jul 11 15:40:56 2007
@@ -15,88 +15,90 @@
 eval_input = 258
 decorator = 259
 decorators = 260
-funcdef = 261
-parameters = 262
-typedargslist = 263
-tname = 264
-tfpdef = 265
-tfplist = 266
-varargslist = 267
-vname = 268
-vfpdef = 269
-vfplist = 270
-stmt = 271
-simple_stmt = 272
-small_stmt = 273
-expr_stmt = 274
-augassign = 275
-del_stmt = 276
-pass_stmt = 277
-flow_stmt = 278
-break_stmt = 279
-continue_stmt = 280
-return_stmt = 281
-yield_stmt = 282
-raise_stmt = 283
-import_stmt = 284
-import_name = 285
-import_from = 286
-import_as_name = 287
-dotted_as_name = 288
-import_as_names = 289
-dotted_as_names = 290
-dotted_name = 291
-global_stmt = 292
-assert_stmt = 293
-compound_stmt = 294
-if_stmt = 295
-while_stmt = 296
-for_stmt = 297
-try_stmt = 298
-with_stmt = 299
-with_var = 300
-except_clause = 301
-suite = 302
-testlist_safe = 303
-old_test = 304
-old_lambdef = 305
-test = 306
-or_test = 307
-and_test = 308
-not_test = 309
-comparison = 310
-comp_op = 311
-expr = 312
-xor_expr = 313
-and_expr = 314
-shift_expr = 315
-arith_expr = 316
-term = 317
-factor = 318
-power = 319
-atom = 320
-listmaker = 321
-testlist_gexp = 322
-lambdef = 323
-trailer = 324
-subscriptlist = 325
-subscript = 326
-sliceop = 327
-exprlist = 328
-testlist = 329
-dictsetmaker = 330
-classdef = 331
-arglist = 332
-argument = 333
-list_iter = 334
-list_for = 335
-list_if = 336
-gen_iter = 337
-gen_for = 338
-gen_if = 339
-testlist1 = 340
-encoding_decl = 341
-yield_expr = 342
+decorated_thing = 261
+funcdef = 262
+parameters = 263
+typedargslist = 264
+tname = 265
+tfpdef = 266
+tfplist = 267
+varargslist = 268
+vname = 269
+vfpdef = 270
+vfplist = 271
+stmt = 272
+simple_stmt = 273
+small_stmt = 274
+expr_stmt = 275
+augassign = 276
+del_stmt = 277
+pass_stmt = 278
+flow_stmt = 279
+break_stmt = 280
+continue_stmt = 281
+return_stmt = 282
+yield_stmt = 283
+raise_stmt = 284
+import_stmt = 285
+import_name = 286
+import_from = 287
+import_as_name = 288
+dotted_as_name = 289
+import_as_names = 290
+dotted_as_names = 291
+dotted_name = 292
+global_stmt = 293
+nonlocal_stmt = 294
+assert_stmt = 295
+compound_stmt = 296
+if_stmt = 297
+while_stmt = 298
+for_stmt = 299
+try_stmt = 300
+with_stmt = 301
+with_var = 302
+except_clause = 303
+suite = 304
+testlist_safe = 305
+old_test = 306
+old_lambdef = 307
+test = 308
+or_test = 309
+and_test = 310
+not_test = 311
+comparison = 312
+comp_op = 313
+expr = 314
+xor_expr = 315
+and_expr = 316
+shift_expr = 317
+arith_expr = 318
+term = 319
+factor = 320
+power = 321
+atom = 322
+listmaker = 323
+testlist_gexp = 324
+lambdef = 325
+trailer = 326
+subscriptlist = 327
+subscript = 328
+sliceop = 329
+exprlist = 330
+testlist = 331
+dictsetmaker = 332
+classdef = 333
+arglist = 334
+argument = 335
+list_iter = 336
+list_for = 337
+list_if = 338
+gen_iter = 339
+gen_for = 340
+gen_if = 341
+testlist1 = 342
+encoding_decl = 343
+yield_expr = 344
 #--end constants--
 
 sym_name = {}

Modified: python/branches/p3yk-noslice/Lib/tarfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/tarfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/tarfile.py	Wed Jul 11 15:40:56 2007
@@ -33,7 +33,7 @@
 __version__ = "$Revision$"
 # $Source$
 
-version     = "0.8.0"
+version     = "0.9.0"
 __author__  = "Lars Gustäbel (lars at gustaebel.de)"
 __date__    = "$Date$"
 __cvsid__   = "$Id$"
@@ -50,6 +50,7 @@
 import time
 import struct
 import copy
+import re
 
 if sys.platform == 'mac':
     # This module needs work for MacOS9, especially in the area of pathname
@@ -71,66 +72,102 @@
 #---------------------------------------------------------
 # tar constants
 #---------------------------------------------------------
-NUL        = "\0"               # the null character
-BLOCKSIZE  = 512                # length of processing blocks
+NUL = "\0"                      # the null character
+BLOCKSIZE = 512                 # length of processing blocks
 RECORDSIZE = BLOCKSIZE * 20     # length of records
-MAGIC      = "ustar"            # magic tar string
-VERSION    = "00"               # version number
+GNU_MAGIC = "ustar  \0"         # magic gnu tar string
+POSIX_MAGIC = "ustar\x0000"     # magic posix tar string
 
-LENGTH_NAME    = 100            # maximum length of a filename
-LENGTH_LINK    = 100            # maximum length of a linkname
-LENGTH_PREFIX  = 155            # maximum length of the prefix field
-MAXSIZE_MEMBER = 077777777777  # maximum size of a file (11 octal digits)
+LENGTH_NAME = 100               # maximum length of a filename
+LENGTH_LINK = 100               # maximum length of a linkname
+LENGTH_PREFIX = 155             # maximum length of the prefix field
 
-REGTYPE  = "0"                  # regular file
+REGTYPE = "0"                   # regular file
 AREGTYPE = "\0"                 # regular file
-LNKTYPE  = "1"                  # link (inside tarfile)
-SYMTYPE  = "2"                  # symbolic link
-CHRTYPE  = "3"                  # character special device
-BLKTYPE  = "4"                  # block special device
-DIRTYPE  = "5"                  # directory
+LNKTYPE = "1"                   # link (inside tarfile)
+SYMTYPE = "2"                   # symbolic link
+CHRTYPE = "3"                   # character special device
+BLKTYPE = "4"                   # block special device
+DIRTYPE = "5"                   # directory
 FIFOTYPE = "6"                  # fifo special device
 CONTTYPE = "7"                  # contiguous file
 
-GNUTYPE_LONGNAME = "L"          # GNU tar extension for longnames
-GNUTYPE_LONGLINK = "K"          # GNU tar extension for longlink
-GNUTYPE_SPARSE   = "S"          # GNU tar extension for sparse file
+GNUTYPE_LONGNAME = "L"          # GNU tar longname
+GNUTYPE_LONGLINK = "K"          # GNU tar longlink
+GNUTYPE_SPARSE = "S"            # GNU tar sparse file
+
+XHDTYPE = "x"                   # POSIX.1-2001 extended header
+XGLTYPE = "g"                   # POSIX.1-2001 global header
+SOLARIS_XHDTYPE = "X"           # Solaris extended header
+
+USTAR_FORMAT = 0                # POSIX.1-1988 (ustar) format
+GNU_FORMAT = 1                  # GNU tar format
+PAX_FORMAT = 2                  # POSIX.1-2001 (pax) format
+DEFAULT_FORMAT = GNU_FORMAT
 
 #---------------------------------------------------------
 # tarfile constants
 #---------------------------------------------------------
-SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,  # file types that tarfile
-                   SYMTYPE, DIRTYPE, FIFOTYPE,  # can cope with.
+# File types that tarfile supports:
+SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
+                   SYMTYPE, DIRTYPE, FIFOTYPE,
                    CONTTYPE, CHRTYPE, BLKTYPE,
                    GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
                    GNUTYPE_SPARSE)
 
-REGULAR_TYPES = (REGTYPE, AREGTYPE,             # file types that somehow
-                 CONTTYPE, GNUTYPE_SPARSE)      # represent regular files
+# File types that will be treated as a regular file.
+REGULAR_TYPES = (REGTYPE, AREGTYPE,
+                 CONTTYPE, GNUTYPE_SPARSE)
+
+# File types that are part of the GNU tar format.
+GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
+             GNUTYPE_SPARSE)
+
+# Fields from a pax header that override a TarInfo attribute.
+PAX_FIELDS = ("path", "linkpath", "size", "mtime",
+              "uid", "gid", "uname", "gname")
+
+# Fields in a pax header that are numbers, all other fields
+# are treated as strings.
+PAX_NUMBER_FIELDS = {
+    "atime": float,
+    "ctime": float,
+    "mtime": float,
+    "uid": int,
+    "gid": int,
+    "size": int
+}
 
 #---------------------------------------------------------
 # Bits used in the mode field, values in octal.
 #---------------------------------------------------------
-S_IFLNK = 0120000        # symbolic link
-S_IFREG = 0100000        # regular file
-S_IFBLK = 0060000        # block device
-S_IFDIR = 0040000        # directory
-S_IFCHR = 0020000        # character device
-S_IFIFO = 0010000        # fifo
-
-TSUID   = 04000          # set UID on execution
-TSGID   = 02000          # set GID on execution
-TSVTX   = 01000          # reserved
-
-TUREAD  = 0400           # read by owner
-TUWRITE = 0200           # write by owner
-TUEXEC  = 0100           # execute/search by owner
-TGREAD  = 0040           # read by group
-TGWRITE = 0020           # write by group
-TGEXEC  = 0010           # execute/search by group
-TOREAD  = 0004           # read by other
-TOWRITE = 0002           # write by other
-TOEXEC  = 0001           # execute/search by other
+S_IFLNK = 0o120000        # symbolic link
+S_IFREG = 0o100000        # regular file
+S_IFBLK = 0o060000        # block device
+S_IFDIR = 0o040000        # directory
+S_IFCHR = 0o020000        # character device
+S_IFIFO = 0o010000        # fifo
+
+TSUID   = 0o4000          # set UID on execution
+TSGID   = 0o2000          # set GID on execution
+TSVTX   = 0o1000          # reserved
+
+TUREAD  = 0o400           # read by owner
+TUWRITE = 0o200           # write by owner
+TUEXEC  = 0o100           # execute/search by owner
+TGREAD  = 0o040           # read by group
+TGWRITE = 0o020           # write by group
+TGEXEC  = 0o010           # execute/search by group
+TOREAD  = 0o004           # read by other
+TOWRITE = 0o002           # write by other
+TOEXEC  = 0o001           # execute/search by other
+
+#---------------------------------------------------------
+# initialization
+#---------------------------------------------------------
+ENCODING = sys.getfilesystemencoding()
+if ENCODING is None:
+    ENCODING = sys.getdefaultencoding()
 
 #---------------------------------------------------------
 # Some useful functions
@@ -141,36 +178,45 @@
     """
     return s[:length] + (length - len(s)) * NUL
 
+def nts(s):
+    """Convert a null-terminated string field to a python string.
+    """
+    # Use the string up to the first null char.
+    p = s.find("\0")
+    if p == -1:
+        return s
+    return s[:p]
+
 def nti(s):
     """Convert a number field to a python number.
     """
     # There are two possible encodings for a number field, see
     # itn() below.
-    if s[0] != chr(0200):
+    if s[0] != chr(0o200):
         try:
-            n = int(s.rstrip(NUL + " ") or "0", 8)
+            n = int(nts(s) or "0", 8)
         except ValueError:
             raise HeaderError("invalid header")
     else:
         n = 0
-        for i in xrange(len(s) - 1):
+        for i in range(len(s) - 1):
             n <<= 8
             n += ord(s[i + 1])
     return n
 
-def itn(n, digits=8, posix=False):
+def itn(n, digits=8, format=DEFAULT_FORMAT):
     """Convert a python number to a number field.
     """
     # POSIX 1003.1-1988 requires numbers to be encoded as a string of
     # octal digits followed by a null-byte, this allows values up to
     # (8**(digits-1))-1. GNU tar allows storing numbers greater than
-    # that if necessary. A leading 0200 byte indicates this particular
+    # that if necessary. A leading 0o200 byte indicates this particular
     # encoding, the following digits-1 bytes are a big-endian
     # representation. This allows values up to (256**(digits-1))-1.
     if 0 <= n < 8 ** (digits - 1):
         s = "%0*o" % (digits - 1, n) + NUL
     else:
-        if posix:
+        if format != GNU_FORMAT or n >= 256 ** (digits - 1):
             raise ValueError("overflow in number field")
 
         if n < 0:
@@ -179,12 +225,32 @@
             n = struct.unpack("L", struct.pack("l", n))[0]
 
         s = ""
-        for i in xrange(digits - 1):
-            s = chr(n & 0377) + s
+        for i in range(digits - 1):
+            s = chr(n & 0o377) + s
             n >>= 8
-        s = chr(0200) + s
+        s = chr(0o200) + s
     return s
 
+def uts(s, encoding, errors):
+    """Convert a unicode object to a string.
+    """
+    if errors == "utf-8":
+        # An extra error handler similar to the -o invalid=UTF-8 option
+        # in POSIX.1-2001. Replace untranslatable characters with their
+        # UTF-8 representation.
+        try:
+            return s.encode(encoding, "strict")
+        except UnicodeEncodeError:
+            x = []
+            for c in s:
+                try:
+                    x.append(c.encode(encoding, "strict"))
+                except UnicodeEncodeError:
+                    x.append(c.encode("utf8"))
+            return "".join(x)
+    else:
+        return s.encode(encoding, errors)
+
 def calc_chksums(buf):
     """Calculate the checksum for a member's header by summing up all
        characters except for the chksum field which is treated as if
@@ -210,7 +276,7 @@
 
     BUFSIZE = 16 * 1024
     blocks, remainder = divmod(length, BUFSIZE)
-    for b in xrange(blocks):
+    for b in range(blocks):
         buf = src.read(BUFSIZE)
         if len(buf) < BUFSIZE:
             raise IOError("end of file reached")
@@ -479,7 +545,7 @@
         """
         if pos - self.pos >= 0:
             blocks, remainder = divmod(pos - self.pos, self.bufsize)
-            for i in xrange(blocks):
+            for i in range(blocks):
                 self.read(self.bufsize)
             self.read(remainder)
         else:
@@ -516,7 +582,10 @@
             buf = self.__read(self.bufsize)
             if not buf:
                 break
-            buf = self.cmp.decompress(buf)
+            try:
+                buf = self.cmp.decompress(buf)
+            except IOError:
+                raise ReadError("invalid compressed data")
             t.append(buf)
             c += len(buf)
         t = "".join(t)
@@ -577,6 +646,7 @@
     def __init__(self, fileobj, mode):
         self.fileobj = fileobj
         self.mode = mode
+        self.name = getattr(self.fileobj, "name", None)
         self.init()
 
     def init(self):
@@ -849,8 +919,8 @@
         """Construct a TarInfo object. name is the optional name
            of the member.
         """
-        self.name = name        # member name (dirnames must end with '/')
-        self.mode = 0666        # file permissions
+        self.name = name        # member name
+        self.mode = 0o644       # file permissions
         self.uid = 0            # user id
         self.gid = 0            # group id
         self.size = 0           # file size
@@ -858,17 +928,261 @@
         self.chksum = 0         # header checksum
         self.type = REGTYPE     # member type
         self.linkname = ""      # link name
-        self.uname = "user"     # user name
-        self.gname = "group"    # group name
+        self.uname = "root"     # user name
+        self.gname = "root"     # group name
         self.devmajor = 0       # device major number
         self.devminor = 0       # device minor number
 
         self.offset = 0         # the tar header starts here
         self.offset_data = 0    # the file's data starts here
 
+        self.pax_headers = {}   # pax header information
+
+    # In pax headers the "name" and "linkname" field are called
+    # "path" and "linkpath".
+    def _getpath(self):
+        return self.name
+    def _setpath(self, name):
+        self.name = name
+    path = property(_getpath, _setpath)
+
+    def _getlinkpath(self):
+        return self.linkname
+    def _setlinkpath(self, linkname):
+        self.linkname = linkname
+    linkpath = property(_getlinkpath, _setlinkpath)
+
     def __repr__(self):
         return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
 
+    def get_info(self, encoding, errors):
+        """Return the TarInfo's attributes as a dictionary.
+        """
+        info = {
+            "name":     normpath(self.name),
+            "mode":     self.mode & 0o7777,
+            "uid":      self.uid,
+            "gid":      self.gid,
+            "size":     self.size,
+            "mtime":    self.mtime,
+            "chksum":   self.chksum,
+            "type":     self.type,
+            "linkname": normpath(self.linkname) if self.linkname else "",
+            "uname":    self.uname,
+            "gname":    self.gname,
+            "devmajor": self.devmajor,
+            "devminor": self.devminor
+        }
+
+        if info["type"] == DIRTYPE and not info["name"].endswith("/"):
+            info["name"] += "/"
+
+        for key in ("name", "linkname", "uname", "gname"):
+            if type(info[key]) is unicode:
+                info[key] = info[key].encode(encoding, errors)
+
+        return info
+
+    def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="strict"):
+        """Return a tar header as a string of 512 byte blocks.
+        """
+        info = self.get_info(encoding, errors)
+
+        if format == USTAR_FORMAT:
+            return self.create_ustar_header(info)
+        elif format == GNU_FORMAT:
+            return self.create_gnu_header(info)
+        elif format == PAX_FORMAT:
+            return self.create_pax_header(info, encoding, errors)
+        else:
+            raise ValueError("invalid format")
+
+    def create_ustar_header(self, info):
+        """Return the object as a ustar header block.
+        """
+        info["magic"] = POSIX_MAGIC
+
+        if len(info["linkname"]) > LENGTH_LINK:
+            raise ValueError("linkname is too long")
+
+        if len(info["name"]) > LENGTH_NAME:
+            info["prefix"], info["name"] = self._posix_split_name(info["name"])
+
+        return self._create_header(info, USTAR_FORMAT)
+
+    def create_gnu_header(self, info):
+        """Return the object as a GNU header block sequence.
+        """
+        info["magic"] = GNU_MAGIC
+
+        buf = ""
+        if len(info["linkname"]) > LENGTH_LINK:
+            buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK)
+
+        if len(info["name"]) > LENGTH_NAME:
+            buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME)
+
+        return buf + self._create_header(info, GNU_FORMAT)
+
+    def create_pax_header(self, info, encoding, errors):
+        """Return the object as a ustar header block. If it cannot be
+           represented this way, prepend a pax extended header sequence
+           with supplement information.
+        """
+        info["magic"] = POSIX_MAGIC
+        pax_headers = self.pax_headers.copy()
+
+        # Test string fields for values that exceed the field length or cannot
+        # be represented in ASCII encoding.
+        for name, hname, length in (
+                ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
+                ("uname", "uname", 32), ("gname", "gname", 32)):
+
+            if hname in pax_headers:
+                # The pax header has priority.
+                continue
+
+            val = info[name].decode(encoding, errors)
+
+            # Try to encode the string as ASCII.
+            try:
+                val.encode("ascii")
+            except UnicodeEncodeError:
+                pax_headers[hname] = val
+                continue
+
+            if len(info[name]) > length:
+                pax_headers[hname] = val
+
+        # Test number fields for values that exceed the field limit or values
+        # that like to be stored as float.
+        for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
+            if name in pax_headers:
+                # The pax header has priority. Avoid overflow.
+                info[name] = 0
+                continue
+
+            val = info[name]
+            if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float):
+                pax_headers[name] = unicode(val)
+                info[name] = 0
+
+        # Create a pax extended header if necessary.
+        if pax_headers:
+            buf = self._create_pax_generic_header(pax_headers)
+        else:
+            buf = ""
+
+        return buf + self._create_header(info, USTAR_FORMAT)
+
+    @classmethod
+    def create_pax_global_header(cls, pax_headers):
+        """Return the object as a pax global header block sequence.
+        """
+        return cls._create_pax_generic_header(pax_headers, type=XGLTYPE)
+
+    def _posix_split_name(self, name):
+        """Split a name longer than 100 chars into a prefix
+           and a name part.
+        """
+        prefix = name[:LENGTH_PREFIX + 1]
+        while prefix and prefix[-1] != "/":
+            prefix = prefix[:-1]
+
+        name = name[len(prefix):]
+        prefix = prefix[:-1]
+
+        if not prefix or len(name) > LENGTH_NAME:
+            raise ValueError("name is too long")
+        return prefix, name
+
+    @staticmethod
+    def _create_header(info, format):
+        """Return a header block. info is a dictionary with file
+           information, format must be one of the *_FORMAT constants.
+        """
+        parts = [
+            stn(info.get("name", ""), 100),
+            itn(info.get("mode", 0) & 0o7777, 8, format),
+            itn(info.get("uid", 0), 8, format),
+            itn(info.get("gid", 0), 8, format),
+            itn(info.get("size", 0), 12, format),
+            itn(info.get("mtime", 0), 12, format),
+            "        ", # checksum field
+            info.get("type", REGTYPE),
+            stn(info.get("linkname", ""), 100),
+            stn(info.get("magic", POSIX_MAGIC), 8),
+            stn(info.get("uname", "root"), 32),
+            stn(info.get("gname", "root"), 32),
+            itn(info.get("devmajor", 0), 8, format),
+            itn(info.get("devminor", 0), 8, format),
+            stn(info.get("prefix", ""), 155)
+        ]
+
+        buf = struct.pack("%ds" % BLOCKSIZE, "".join(parts))
+        chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
+        buf = buf[:-364] + "%06o\0" % chksum + buf[-357:]
+        return buf
+
+    @staticmethod
+    def _create_payload(payload):
+        """Return the string payload filled with zero bytes
+           up to the next 512 byte border.
+        """
+        blocks, remainder = divmod(len(payload), BLOCKSIZE)
+        if remainder > 0:
+            payload += (BLOCKSIZE - remainder) * NUL
+        return payload
+
+    @classmethod
+    def _create_gnu_long_header(cls, name, type):
+        """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
+           for name.
+        """
+        name += NUL
+
+        info = {}
+        info["name"] = "././@LongLink"
+        info["type"] = type
+        info["size"] = len(name)
+        info["magic"] = GNU_MAGIC
+
+        # create extended header + name blocks.
+        return cls._create_header(info, USTAR_FORMAT) + \
+                cls._create_payload(name)
+
+    @classmethod
+    def _create_pax_generic_header(cls, pax_headers, type=XHDTYPE):
+        """Return a POSIX.1-2001 extended or global header sequence
+           that contains a list of keyword, value pairs. The values
+           must be unicode objects.
+        """
+        records = []
+        for keyword, value in pax_headers.items():
+            keyword = keyword.encode("utf8")
+            value = value.encode("utf8")
+            l = len(keyword) + len(value) + 3   # ' ' + '=' + '\n'
+            n = p = 0
+            while True:
+                n = l + len(str(p))
+                if n == p:
+                    break
+                p = n
+            records.append("%d %s=%s\n" % (p, keyword, value))
+        records = "".join(records)
+
+        # We use a hardcoded "././@PaxHeader" name like star does
+        # instead of the one that POSIX recommends.
+        info = {}
+        info["name"] = "././@PaxHeader"
+        info["type"] = type
+        info["size"] = len(records)
+        info["magic"] = POSIX_MAGIC
+
+        # Create pax header + record blocks.
+        return cls._create_header(info, USTAR_FORMAT) + \
+                cls._create_payload(records)
+
     @classmethod
     def frombuf(cls, buf):
         """Construct a TarInfo object from a 512 byte string buffer.
@@ -882,125 +1196,256 @@
         if chksum not in calc_chksums(buf):
             raise HeaderError("bad checksum")
 
-        tarinfo = cls()
-        tarinfo.buf = buf
-        tarinfo.name = buf[0:100].rstrip(NUL)
-        tarinfo.mode = nti(buf[100:108])
-        tarinfo.uid = nti(buf[108:116])
-        tarinfo.gid = nti(buf[116:124])
-        tarinfo.size = nti(buf[124:136])
-        tarinfo.mtime = nti(buf[136:148])
-        tarinfo.chksum = chksum
-        tarinfo.type = buf[156:157]
-        tarinfo.linkname = buf[157:257].rstrip(NUL)
-        tarinfo.uname = buf[265:297].rstrip(NUL)
-        tarinfo.gname = buf[297:329].rstrip(NUL)
-        tarinfo.devmajor = nti(buf[329:337])
-        tarinfo.devminor = nti(buf[337:345])
-        prefix = buf[345:500].rstrip(NUL)
+        obj = cls()
+        obj.buf = buf
+        obj.name = nts(buf[0:100])
+        obj.mode = nti(buf[100:108])
+        obj.uid = nti(buf[108:116])
+        obj.gid = nti(buf[116:124])
+        obj.size = nti(buf[124:136])
+        obj.mtime = nti(buf[136:148])
+        obj.chksum = chksum
+        obj.type = buf[156:157]
+        obj.linkname = nts(buf[157:257])
+        obj.uname = nts(buf[265:297])
+        obj.gname = nts(buf[297:329])
+        obj.devmajor = nti(buf[329:337])
+        obj.devminor = nti(buf[337:345])
+        prefix = nts(buf[345:500])
 
-        if prefix and not tarinfo.issparse():
-            tarinfo.name = prefix + "/" + tarinfo.name
+        # Old V7 tar format represents a directory as a regular
+        # file with a trailing slash.
+        if obj.type == AREGTYPE and obj.name.endswith("/"):
+            obj.type = DIRTYPE
 
-        return tarinfo
+        # Remove redundant slashes from directories.
+        if obj.isdir():
+            obj.name = obj.name.rstrip("/")
+
+        # Reconstruct a ustar longname.
+        if prefix and obj.type not in GNU_TYPES:
+            obj.name = prefix + "/" + obj.name
+        return obj
 
-    def tobuf(self, posix=False):
-        """Return a tar header as a string of 512 byte blocks.
+    @classmethod
+    def fromtarfile(cls, tarfile):
+        """Return the next TarInfo object from TarFile object
+           tarfile.
         """
-        buf = ""
-        type = self.type
-        prefix = ""
+        buf = tarfile.fileobj.read(BLOCKSIZE)
+        if not buf:
+            return
+        obj = cls.frombuf(buf)
+        obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
+        return obj._proc_member(tarfile)
 
-        if self.name.endswith("/"):
-            type = DIRTYPE
+    #--------------------------------------------------------------------------
+    # The following are methods that are called depending on the type of a
+    # member. The entry point is _proc_member() which can be overridden in a
+    # subclass to add custom _proc_*() methods. A _proc_*() method MUST
+    # implement the following
+    # operations:
+    # 1. Set self.offset_data to the position where the data blocks begin,
+    #    if there is data that follows.
+    # 2. Set tarfile.offset to the position where the next member's header will
+    #    begin.
+    # 3. Return self or another valid TarInfo object.
+    def _proc_member(self, tarfile):
+        """Choose the right processing method depending on
+           the type and call it.
+        """
+        if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
+            return self._proc_gnulong(tarfile)
+        elif self.type == GNUTYPE_SPARSE:
+            return self._proc_sparse(tarfile)
+        elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
+            return self._proc_pax(tarfile)
+        else:
+            return self._proc_builtin(tarfile)
+
+    def _proc_builtin(self, tarfile):
+        """Process a builtin type or an unknown type which
+           will be treated as a regular file.
+        """
+        self.offset_data = tarfile.fileobj.tell()
+        offset = self.offset_data
+        if self.isreg() or self.type not in SUPPORTED_TYPES:
+            # Skip the following data blocks.
+            offset += self._block(self.size)
+        tarfile.offset = offset
 
-        if type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
-            # Prevent "././@LongLink" from being normalized.
-            name = self.name
-        else:
-            name = normpath(self.name)
+        # Patch the TarInfo object with saved global
+        # header information.
+        self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
 
-        if type == DIRTYPE:
-            # directories should end with '/'
-            name += "/"
+        return self
 
-        linkname = self.linkname
-        if linkname:
-            # if linkname is empty we end up with a '.'
-            linkname = normpath(linkname)
+    def _proc_gnulong(self, tarfile):
+        """Process the blocks that hold a GNU longname
+           or longlink member.
+        """
+        buf = tarfile.fileobj.read(self._block(self.size))
 
-        if posix:
-            if self.size > MAXSIZE_MEMBER:
-                raise ValueError("file is too large (>= 8 GB)")
+        # Fetch the next header and process it.
+        next = self.fromtarfile(tarfile)
+        if next is None:
+            raise HeaderError("missing subsequent header")
 
-            if len(self.linkname) > LENGTH_LINK:
-                raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK))
+        # Patch the TarInfo object from the next header with
+        # the longname information.
+        next.offset = self.offset
+        if self.type == GNUTYPE_LONGNAME:
+            next.name = nts(buf)
+        elif self.type == GNUTYPE_LONGLINK:
+            next.linkname = nts(buf)
 
-            if len(name) > LENGTH_NAME:
-                prefix = name[:LENGTH_PREFIX + 1]
-                while prefix and prefix[-1] != "/":
-                    prefix = prefix[:-1]
+        return next
 
-                name = name[len(prefix):]
-                prefix = prefix[:-1]
+    def _proc_sparse(self, tarfile):
+        """Process a GNU sparse header plus extra headers.
+        """
+        buf = self.buf
+        sp = _ringbuffer()
+        pos = 386
+        lastpos = 0
+        realpos = 0
+        # There are 4 possible sparse structs in the
+        # first header.
+        for i in range(4):
+            try:
+                offset = nti(buf[pos:pos + 12])
+                numbytes = nti(buf[pos + 12:pos + 24])
+            except ValueError:
+                break
+            if offset > lastpos:
+                sp.append(_hole(lastpos, offset - lastpos))
+            sp.append(_data(offset, numbytes, realpos))
+            realpos += numbytes
+            lastpos = offset + numbytes
+            pos += 24
 
-                if not prefix or len(name) > LENGTH_NAME:
-                    raise ValueError("name is too long")
+        isextended = ord(buf[482])
+        origsize = nti(buf[483:495])
 
-        else:
-            if len(self.linkname) > LENGTH_LINK:
-                buf += self._create_gnulong(self.linkname, GNUTYPE_LONGLINK)
+        # If the isextended flag is given,
+        # there are extra headers to process.
+        while isextended == 1:
+            buf = tarfile.fileobj.read(BLOCKSIZE)
+            pos = 0
+            for i in range(21):
+                try:
+                    offset = nti(buf[pos:pos + 12])
+                    numbytes = nti(buf[pos + 12:pos + 24])
+                except ValueError:
+                    break
+                if offset > lastpos:
+                    sp.append(_hole(lastpos, offset - lastpos))
+                sp.append(_data(offset, numbytes, realpos))
+                realpos += numbytes
+                lastpos = offset + numbytes
+                pos += 24
+            isextended = ord(buf[504])
 
-            if len(name) > LENGTH_NAME:
-                buf += self._create_gnulong(name, GNUTYPE_LONGNAME)
+        if lastpos < origsize:
+            sp.append(_hole(lastpos, origsize - lastpos))
 
-        parts = [
-            stn(name, 100),
-            itn(self.mode & 07777, 8, posix),
-            itn(self.uid, 8, posix),
-            itn(self.gid, 8, posix),
-            itn(self.size, 12, posix),
-            itn(self.mtime, 12, posix),
-            "        ", # checksum field
-            type,
-            stn(self.linkname, 100),
-            stn(MAGIC, 6),
-            stn(VERSION, 2),
-            stn(self.uname, 32),
-            stn(self.gname, 32),
-            itn(self.devmajor, 8, posix),
-            itn(self.devminor, 8, posix),
-            stn(prefix, 155)
-        ]
+        self.sparse = sp
 
-        buf += struct.pack("%ds" % BLOCKSIZE, "".join(parts))
-        chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
-        buf = buf[:-364] + "%06o\0" % chksum + buf[-357:]
-        self.buf = buf
-        return buf
+        self.offset_data = tarfile.fileobj.tell()
+        tarfile.offset = self.offset_data + self._block(self.size)
+        self.size = origsize
 
-    def _create_gnulong(self, name, type):
-        """Create a GNU longname/longlink header from name.
-           It consists of an extended tar header, with the length
-           of the longname as size, followed by data blocks,
-           which contain the longname as a null terminated string.
-        """
-        name += NUL
+        return self
 
-        tarinfo = self.__class__()
-        tarinfo.name = "././@LongLink"
-        tarinfo.type = type
-        tarinfo.mode = 0
-        tarinfo.size = len(name)
+    def _proc_pax(self, tarfile):
+        """Process an extended or global header as described in
+           POSIX.1-2001.
+        """
+        # Read the header information.
+        buf = tarfile.fileobj.read(self._block(self.size))
+
+        # A pax header stores supplemental information for either
+        # the following file (extended) or all following files
+        # (global).
+        if self.type == XGLTYPE:
+            pax_headers = tarfile.pax_headers
+        else:
+            pax_headers = tarfile.pax_headers.copy()
+
+        # Parse pax header information. A record looks like that:
+        # "%d %s=%s\n" % (length, keyword, value). length is the size
+        # of the complete record including the length field itself and
+        # the newline. keyword and value are both UTF-8 encoded strings.
+        regex = re.compile(r"(\d+) ([^=]+)=", re.U)
+        pos = 0
+        while True:
+            match = regex.match(buf, pos)
+            if not match:
+                break
 
-        # create extended header
-        buf = tarinfo.tobuf()
-        # create name blocks
-        buf += name
-        blocks, remainder = divmod(len(name), BLOCKSIZE)
-        if remainder > 0:
-            buf += (BLOCKSIZE - remainder) * NUL
-        return buf
+            length, keyword = match.groups()
+            length = int(length)
+            value = buf[match.end(2) + 1:match.start(1) + length - 1]
+
+            keyword = keyword.decode("utf8")
+            value = value.decode("utf8")
+
+            pax_headers[keyword] = value
+            pos += length
+
+        # Fetch the next header.
+        next = self.fromtarfile(tarfile)
+
+        if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
+            if next is None:
+                raise HeaderError("missing subsequent header")
+
+            # Patch the TarInfo object with the extended header info.
+            next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
+            next.offset = self.offset
+
+            if "size" in pax_headers:
+                # If the extended header replaces the size field,
+                # we need to recalculate the offset where the next
+                # header starts.
+                offset = next.offset_data
+                if next.isreg() or next.type not in SUPPORTED_TYPES:
+                    offset += next._block(next.size)
+                tarfile.offset = offset
+
+        return next
+
+    def _apply_pax_info(self, pax_headers, encoding, errors):
+        """Replace fields with supplemental information from a previous
+           pax extended or global header.
+        """
+        for keyword, value in pax_headers.items():
+            if keyword not in PAX_FIELDS:
+                continue
+
+            if keyword == "path":
+                value = value.rstrip("/")
+
+            if keyword in PAX_NUMBER_FIELDS:
+                try:
+                    value = PAX_NUMBER_FIELDS[keyword](value)
+                except ValueError:
+                    value = 0
+            else:
+                value = uts(value, encoding, errors)
+
+            setattr(self, keyword, value)
+
+        self.pax_headers = pax_headers.copy()
+
+    def _block(self, count):
+        """Round up a byte count by BLOCKSIZE and return it,
+           e.g. _block(834) => 1024.
+        """
+        blocks, remainder = divmod(count, BLOCKSIZE)
+        if remainder:
+            blocks += 1
+        return blocks * BLOCKSIZE
 
     def isreg(self):
         return self.type in REGULAR_TYPES
@@ -1040,12 +1485,19 @@
                                 # messages (if debug >= 0). If > 0, errors
                                 # are passed to the caller as exceptions.
 
-    posix = False               # If True, generates POSIX.1-1990-compliant
-                                # archives (no GNU extensions!)
+    format = DEFAULT_FORMAT     # The format to use when creating an archive.
+
+    encoding = ENCODING         # Encoding for 8-bit character strings.
+
+    errors = None               # Error handler for unicode conversion.
+
+    tarinfo = TarInfo           # The default TarInfo class to use.
 
-    fileobject = ExFileObject
+    fileobject = ExFileObject   # The default ExFileObject class to use.
 
-    def __init__(self, name=None, mode="r", fileobj=None):
+    def __init__(self, name=None, mode="r", fileobj=None, format=None,
+            tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
+            errors=None, pax_headers=None, debug=None, errorlevel=None):
         """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
            read from an existing archive, 'a' to append data to an existing
            file or 'w' to create a new file overwriting an existing one. `mode'
@@ -1054,29 +1506,57 @@
            can be determined, `mode' is overridden by `fileobj's mode.
            `fileobj' is not closed, when TarFile is closed.
         """
-        self.name = os.path.abspath(name)
-
         if len(mode) > 1 or mode not in "raw":
             raise ValueError("mode must be 'r', 'a' or 'w'")
-        self._mode = mode
-        self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
+        self.mode = mode
+        self._mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
 
         if not fileobj:
-            if self._mode == "a" and not os.path.exists(self.name):
+            if self.mode == "a" and not os.path.exists(name):
                 # Create nonexistent files in append mode.
-                self._mode = "w"
-                self.mode = "wb"
-            fileobj = _open(self.name, self.mode)
+                self.mode = "w"
+                self._mode = "wb"
+            fileobj = bltn_open(name, self._mode)
             self._extfileobj = False
         else:
-            if self.name is None and hasattr(fileobj, "name"):
-                self.name = os.path.abspath(fileobj.name)
+            if name is None and hasattr(fileobj, "name"):
+                name = fileobj.name
             if hasattr(fileobj, "mode"):
-                self.mode = fileobj.mode
+                self._mode = fileobj.mode
             self._extfileobj = True
+        self.name = os.path.abspath(name)
         self.fileobj = fileobj
 
-        # Init datastructures
+        # Init attributes.
+        if format is not None:
+            self.format = format
+        if tarinfo is not None:
+            self.tarinfo = tarinfo
+        if dereference is not None:
+            self.dereference = dereference
+        if ignore_zeros is not None:
+            self.ignore_zeros = ignore_zeros
+        if encoding is not None:
+            self.encoding = encoding
+
+        if errors is not None:
+            self.errors = errors
+        elif mode == "r":
+            self.errors = "utf-8"
+        else:
+            self.errors = "strict"
+
+        if pax_headers is not None and self.format == PAX_FORMAT:
+            self.pax_headers = pax_headers
+        else:
+            self.pax_headers = {}
+
+        if debug is not None:
+            self.debug = debug
+        if errorlevel is not None:
+            self.errorlevel = errorlevel
+
+        # Init datastructures.
         self.closed = False
         self.members = []       # list of members as TarInfo objects
         self._loaded = False    # flag if all members have been read
@@ -1084,28 +1564,39 @@
         self.inodes = {}        # dictionary caching the inodes of
                                 # archive members already added
 
-        if self._mode == "r":
+        if self.mode == "r":
             self.firstmember = None
             self.firstmember = self.next()
 
-        if self._mode == "a":
+        if self.mode == "a":
             # Move to the end of the archive,
             # before the first empty block.
             self.firstmember = None
             while True:
-                try:
-                    tarinfo = self.next()
-                except ReadError:
-                    self.fileobj.seek(0)
-                    break
-                if tarinfo is None:
+                if self.next() is None:
                     if self.offset > 0:
                         self.fileobj.seek(- BLOCKSIZE, 1)
                     break
 
-        if self._mode in "aw":
+        if self.mode in "aw":
             self._loaded = True
 
+            if self.pax_headers:
+                buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
+                self.fileobj.write(buf)
+                self.offset += len(buf)
+
+    def _getposix(self):
+        return self.format == USTAR_FORMAT
+    def _setposix(self, value):
+        import warnings
+        warnings.warn("use the format attribute instead", DeprecationWarning)
+        if value:
+            self.format = USTAR_FORMAT
+        else:
+            self.format = GNU_FORMAT
+    posix = property(_getposix, _setposix)
+
     #--------------------------------------------------------------------------
     # Below are the classmethods which act as alternate constructors to the
     # TarFile class. The open() method is the only one that is needed for
@@ -1118,7 +1609,7 @@
     # by adding it to the mapping in OPEN_METH.
 
     @classmethod
-    def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512):
+    def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
         """Open a tar archive for reading, writing or appending. Return
            an appropriate TarFile class.
 
@@ -1151,8 +1642,8 @@
                 if fileobj is not None:
                     saved_pos = fileobj.tell()
                 try:
-                    return func(name, "r", fileobj)
-                except (ReadError, CompressionError):
+                    return func(name, "r", fileobj, **kwargs)
+                except (ReadError, CompressionError) as e:
                     if fileobj is not None:
                         fileobj.seek(saved_pos)
                     continue
@@ -1169,7 +1660,7 @@
                 func = getattr(cls, cls.OPEN_METH[comptype])
             else:
                 raise CompressionError("unknown compression type %r" % comptype)
-            return func(name, filemode, fileobj)
+            return func(name, filemode, fileobj, **kwargs)
 
         elif "|" in mode:
             filemode, comptype = mode.split("|", 1)
@@ -1180,25 +1671,26 @@
                 raise ValueError("mode must be 'r' or 'w'")
 
             t = cls(name, filemode,
-                    _Stream(name, filemode, comptype, fileobj, bufsize))
+                    _Stream(name, filemode, comptype, fileobj, bufsize),
+                    **kwargs)
             t._extfileobj = False
             return t
 
         elif mode in "aw":
-            return cls.taropen(name, mode, fileobj)
+            return cls.taropen(name, mode, fileobj, **kwargs)
 
         raise ValueError("undiscernible mode")
 
     @classmethod
-    def taropen(cls, name, mode="r", fileobj=None):
+    def taropen(cls, name, mode="r", fileobj=None, **kwargs):
         """Open uncompressed tar archive name for reading or writing.
         """
         if len(mode) > 1 or mode not in "raw":
             raise ValueError("mode must be 'r', 'a' or 'w'")
-        return cls(name, mode, fileobj)
+        return cls(name, mode, fileobj, **kwargs)
 
     @classmethod
-    def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9):
+    def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
         """Open gzip compressed tar archive name for reading or writing.
            Appending is not allowed.
         """
@@ -1212,18 +1704,19 @@
             raise CompressionError("gzip module is not available")
 
         if fileobj is None:
-            fileobj = _open(name, mode + "b")
+            fileobj = bltn_open(name, mode + "b")
 
         try:
             t = cls.taropen(name, mode,
-                gzip.GzipFile(name, mode, compresslevel, fileobj))
+                gzip.GzipFile(name, mode, compresslevel, fileobj),
+                **kwargs)
         except IOError:
             raise ReadError("not a gzip file")
         t._extfileobj = False
         return t
 
     @classmethod
-    def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9):
+    def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
         """Open bzip2 compressed tar archive name for reading or writing.
            Appending is not allowed.
         """
@@ -1241,7 +1734,7 @@
             fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
 
         try:
-            t = cls.taropen(name, mode, fileobj)
+            t = cls.taropen(name, mode, fileobj, **kwargs)
         except IOError:
             raise ReadError("not a bzip2 file")
         t._extfileobj = False
@@ -1264,7 +1757,7 @@
         if self.closed:
             return
 
-        if self._mode in "aw":
+        if self.mode in "aw":
             self.fileobj.write(NUL * (BLOCKSIZE * 2))
             self.offset += (BLOCKSIZE * 2)
             # fill up the end with zero-blocks
@@ -1330,7 +1823,8 @@
 
         # Now, fill the TarInfo object with
         # information specific for the file.
-        tarinfo = TarInfo()
+        tarinfo = self.tarinfo()
+        tarinfo.tarfile = self
 
         # Use os.stat or os.lstat, depending on platform
         # and if symlinks shall be resolved.
@@ -1346,8 +1840,8 @@
         stmd = statres.st_mode
         if stat.S_ISREG(stmd):
             inode = (statres.st_ino, statres.st_dev)
-            if not self.dereference and \
-                    statres.st_nlink > 1 and inode in self.inodes:
+            if not self.dereference and statres.st_nlink > 1 and \
+                    inode in self.inodes and arcname != self.inodes[inode]:
                 # Is it a hardlink to an already
                 # archived file?
                 type = LNKTYPE
@@ -1360,8 +1854,6 @@
                     self.inodes[inode] = arcname
         elif stat.S_ISDIR(stmd):
             type = DIRTYPE
-            if arcname[-1:] != "/":
-                arcname += "/"
         elif stat.S_ISFIFO(stmd):
             type = FIFOTYPE
         elif stat.S_ISLNK(stmd):
@@ -1424,7 +1916,7 @@
                 print("%d-%02d-%02d %02d:%02d:%02d" \
                       % time.localtime(tarinfo.mtime)[:6], end=' ')
 
-            print(tarinfo.name, end=' ')
+            print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')
 
             if verbose:
                 if tarinfo.issym():
@@ -1433,18 +1925,24 @@
                     print("link to", tarinfo.linkname, end=' ')
             print()
 
-    def add(self, name, arcname=None, recursive=True):
+    def add(self, 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 for the file in the archive.
            Directories are added recursively by default. This can be avoided by
-           setting `recursive' to False.
+           setting `recursive' to False. `exclude' is a function that should
+           return True for each filename to be excluded.
         """
         self._check("aw")
 
         if arcname is None:
             arcname = name
 
+        # Exclude pathnames.
+        if exclude is not None and exclude(name):
+            self._dbg(2, "tarfile: Excluded %r" % name)
+            return
+
         # Skip if somebody tries to archive the archive...
         if self.name is not None and os.path.abspath(name) == self.name:
             self._dbg(2, "tarfile: Skipped %r" % name)
@@ -1456,8 +1954,8 @@
             if recursive:
                 if arcname == ".":
                     arcname = ""
-                for f in os.listdir("."):
-                    self.add(f, os.path.join(arcname, f))
+                for f in os.listdir(name):
+                    self.add(f, os.path.join(arcname, f), recursive, exclude)
             return
 
         self._dbg(1, name)
@@ -1471,7 +1969,7 @@
 
         # Append the tar header and data to the archive.
         if tarinfo.isreg():
-            f = _open(name, "rb")
+            f = bltn_open(name, "rb")
             self.addfile(tarinfo, f)
             f.close()
 
@@ -1479,7 +1977,7 @@
             self.addfile(tarinfo)
             if recursive:
                 for f in os.listdir(name):
-                    self.add(os.path.join(name, f), os.path.join(arcname, f))
+                    self.add(os.path.join(name, f), os.path.join(arcname, f), recursive, exclude)
 
         else:
             self.addfile(tarinfo)
@@ -1495,7 +1993,7 @@
 
         tarinfo = copy.copy(tarinfo)
 
-        buf = tarinfo.tobuf(self.posix)
+        buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
         self.fileobj.write(buf)
         self.offset += len(buf)
 
@@ -1527,7 +2025,7 @@
                 # Extract directory with a safe mode, so that
                 # all files below can be extracted as well.
                 try:
-                    os.makedirs(os.path.join(path, tarinfo.name), 0777)
+                    os.makedirs(os.path.join(path, tarinfo.name), 0o700)
                 except EnvironmentError:
                     pass
                 directories.append(tarinfo)
@@ -1559,10 +2057,10 @@
         """
         self._check("r")
 
-        if isinstance(member, TarInfo):
-            tarinfo = member
-        else:
+        if isinstance(member, basestring):
             tarinfo = self.getmember(member)
+        else:
+            tarinfo = member
 
         # Prepare the link target for makelink().
         if tarinfo.islnk():
@@ -1595,10 +2093,10 @@
         """
         self._check("r")
 
-        if isinstance(member, TarInfo):
-            tarinfo = member
-        else:
+        if isinstance(member, basestring):
             tarinfo = self.getmember(member)
+        else:
+            tarinfo = member
 
         if tarinfo.isreg():
             return self.fileobject(self, tarinfo)
@@ -1682,7 +2180,7 @@
         """Make a file called targetpath.
         """
         source = self.extractfile(tarinfo)
-        target = _open(targetpath, "wb")
+        target = bltn_open(targetpath, "wb")
         copyfileobj(source, target)
         source.close()
         target.close()
@@ -1811,20 +2309,11 @@
         # Read the next block.
         self.fileobj.seek(self.offset)
         while True:
-            buf = self.fileobj.read(BLOCKSIZE)
-            if not buf:
-                return None
-
             try:
-                tarinfo = TarInfo.frombuf(buf)
-
-                # Set the TarInfo object's offset to the current position of the
-                # TarFile and set self.offset to the position where the data blocks
-                # should begin.
-                tarinfo.offset = self.offset
-                self.offset += BLOCKSIZE
-
-                tarinfo = self.proc_member(tarinfo)
+                tarinfo = self.tarinfo.fromtarfile(self)
+                if tarinfo is None:
+                    return
+                self.members.append(tarinfo)
 
             except HeaderError as e:
                 if self.ignore_zeros:
@@ -1837,149 +2326,11 @@
                     return None
             break
 
-        # Some old tar programs represent a directory as a regular
-        # file with a trailing slash.
-        if tarinfo.isreg() and tarinfo.name.endswith("/"):
-            tarinfo.type = DIRTYPE
-
-        # Directory names should have a '/' at the end.
-        if tarinfo.isdir():
-            tarinfo.name += "/"
-
-        self.members.append(tarinfo)
-        return tarinfo
-
-    #--------------------------------------------------------------------------
-    # The following are methods that are called depending on the type of a
-    # member. The entry point is proc_member() which is called with a TarInfo
-    # object created from the header block from the current offset. The
-    # proc_member() method can be overridden in a subclass to add custom
-    # proc_*() methods. A proc_*() method MUST implement the following
-    # operations:
-    # 1. Set tarinfo.offset_data to the position where the data blocks begin,
-    #    if there is data that follows.
-    # 2. Set self.offset to the position where the next member's header will
-    #    begin.
-    # 3. Return tarinfo or another valid TarInfo object.
-    def proc_member(self, tarinfo):
-        """Choose the right processing method for tarinfo depending
-           on its type and call it.
-        """
-        if tarinfo.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
-            return self.proc_gnulong(tarinfo)
-        elif tarinfo.type == GNUTYPE_SPARSE:
-            return self.proc_sparse(tarinfo)
-        else:
-            return self.proc_builtin(tarinfo)
-
-    def proc_builtin(self, tarinfo):
-        """Process a builtin type member or an unknown member
-           which will be treated as a regular file.
-        """
-        tarinfo.offset_data = self.offset
-        if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
-            # Skip the following data blocks.
-            self.offset += self._block(tarinfo.size)
-        return tarinfo
-
-    def proc_gnulong(self, tarinfo):
-        """Process the blocks that hold a GNU longname
-           or longlink member.
-        """
-        buf = ""
-        count = tarinfo.size
-        while count > 0:
-            block = self.fileobj.read(BLOCKSIZE)
-            buf += block
-            self.offset += BLOCKSIZE
-            count -= BLOCKSIZE
-
-        # Fetch the next header and process it.
-        b = self.fileobj.read(BLOCKSIZE)
-        t = TarInfo.frombuf(b)
-        t.offset = self.offset
-        self.offset += BLOCKSIZE
-        next = self.proc_member(t)
-
-        # Patch the TarInfo object from the next header with
-        # the longname information.
-        next.offset = tarinfo.offset
-        if tarinfo.type == GNUTYPE_LONGNAME:
-            next.name = buf.rstrip(NUL)
-        elif tarinfo.type == GNUTYPE_LONGLINK:
-            next.linkname = buf.rstrip(NUL)
-
-        return next
-
-    def proc_sparse(self, tarinfo):
-        """Process a GNU sparse header plus extra headers.
-        """
-        buf = tarinfo.buf
-        sp = _ringbuffer()
-        pos = 386
-        lastpos = 0
-        realpos = 0
-        # There are 4 possible sparse structs in the
-        # first header.
-        for i in xrange(4):
-            try:
-                offset = nti(buf[pos:pos + 12])
-                numbytes = nti(buf[pos + 12:pos + 24])
-            except ValueError:
-                break
-            if offset > lastpos:
-                sp.append(_hole(lastpos, offset - lastpos))
-            sp.append(_data(offset, numbytes, realpos))
-            realpos += numbytes
-            lastpos = offset + numbytes
-            pos += 24
-
-        isextended = ord(buf[482])
-        origsize = nti(buf[483:495])
-
-        # If the isextended flag is given,
-        # there are extra headers to process.
-        while isextended == 1:
-            buf = self.fileobj.read(BLOCKSIZE)
-            self.offset += BLOCKSIZE
-            pos = 0
-            for i in xrange(21):
-                try:
-                    offset = nti(buf[pos:pos + 12])
-                    numbytes = nti(buf[pos + 12:pos + 24])
-                except ValueError:
-                    break
-                if offset > lastpos:
-                    sp.append(_hole(lastpos, offset - lastpos))
-                sp.append(_data(offset, numbytes, realpos))
-                realpos += numbytes
-                lastpos = offset + numbytes
-                pos += 24
-            isextended = ord(buf[504])
-
-        if lastpos < origsize:
-            sp.append(_hole(lastpos, origsize - lastpos))
-
-        tarinfo.sparse = sp
-
-        tarinfo.offset_data = self.offset
-        self.offset += self._block(tarinfo.size)
-        tarinfo.size = origsize
-
         return tarinfo
 
     #--------------------------------------------------------------------------
     # Little helper methods:
 
-    def _block(self, count):
-        """Round up a byte count by BLOCKSIZE and return it,
-           e.g. _block(834) => 1024.
-        """
-        blocks, remainder = divmod(count, BLOCKSIZE)
-        if remainder:
-            blocks += 1
-        return blocks * BLOCKSIZE
-
     def _getmember(self, name, tarinfo=None):
         """Find an archive member by name from bottom to top.
            If tarinfo is given, it is used as the starting point.
@@ -1992,7 +2343,7 @@
         else:
             end = members.index(tarinfo)
 
-        for i in xrange(end - 1, -1, -1):
+        for i in range(end - 1, -1, -1):
             if name == members[i].name:
                 return members[i]
 
@@ -2012,8 +2363,8 @@
         """
         if self.closed:
             raise IOError("%s is closed" % self.__class__.__name__)
-        if mode is not None and self._mode not in mode:
-            raise IOError("bad operation for mode %r" % self._mode)
+        if mode is not None and self.mode not in mode:
+            raise IOError("bad operation for mode %r" % self.mode)
 
     def __iter__(self):
         """Provide an iterator object.
@@ -2046,7 +2397,7 @@
         """Return iterator object.
         """
         return self
-    def next(self):
+    def __next__(self):
         """Return the next item using TarFile's next() method.
            When all members have been read, set TarFile as _loaded.
         """
@@ -2174,4 +2525,5 @@
     except TarError:
         return False
 
+bltn_open = open
 open = TarFile.open

Modified: python/branches/p3yk-noslice/Lib/telnetlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/telnetlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/telnetlib.py	Wed Jul 11 15:40:56 2007
@@ -184,7 +184,7 @@
 
     """
 
-    def __init__(self, host=None, port=0):
+    def __init__(self, host=None, port=0, timeout=None):
         """Constructor.
 
         When called without arguments, create an unconnected instance.
@@ -195,6 +195,7 @@
         self.debuglevel = DEBUGLEVEL
         self.host = host
         self.port = port
+        self.timeout = timeout
         self.sock = None
         self.rawq = ''
         self.irawq = 0
@@ -205,9 +206,9 @@
         self.sbdataq = ''
         self.option_callback = None
         if host is not None:
-            self.open(host, port)
+            self.open(host, port, timeout)
 
-    def open(self, host, port=0):
+    def open(self, host, port=0, timeout=None):
         """Connect to a host.
 
         The optional second argument is the port number, which
@@ -221,20 +222,9 @@
             port = TELNET_PORT
         self.host = host
         self.port = port
-        msg = "getaddrinfo returns an empty list"
-        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
-            af, socktype, proto, canonname, sa = res
-            try:
-                self.sock = socket.socket(af, socktype, proto)
-                self.sock.connect(sa)
-            except socket.error as msg:
-                if self.sock:
-                    self.sock.close()
-                self.sock = None
-                continue
-            break
-        if not self.sock:
-            raise socket.error, msg
+        if timeout is not None:
+            self.timeout = timeout
+        self.sock = socket.create_connection((host, port), self.timeout)
 
     def __del__(self):
         """Destructor -- close the connection."""
@@ -661,7 +651,7 @@
             port = socket.getservbyname(portstr, 'tcp')
     tn = Telnet()
     tn.set_debuglevel(debuglevel)
-    tn.open(host, port)
+    tn.open(host, port, timeout=0.5)
     tn.interact()
     tn.close()
 

Modified: python/branches/p3yk-noslice/Lib/tempfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/tempfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/tempfile.py	Wed Jul 11 15:40:56 2007
@@ -19,6 +19,7 @@
 
 __all__ = [
     "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
+    "SpooledTemporaryFile",
     "mkstemp", "mkdtemp",                  # low level safe interfaces
     "mktemp",                              # deprecated unsafe interface
     "TMP_MAX", "gettempprefix",            # constants
@@ -37,6 +38,11 @@
     import Carbon.Folders as _Folders
 
 try:
+    from cStringIO import StringIO as _StringIO
+except:
+    from StringIO import StringIO as _StringIO
+
+try:
     import fcntl as _fcntl
 except ImportError:
     def _set_cloexec(fd):
@@ -114,7 +120,7 @@
 
     characters = ("abcdefghijklmnopqrstuvwxyz" +
                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
-                  "0123456789-_")
+                  "0123456789_")
 
     def __init__(self):
         self.mutex = _allocate_lock()
@@ -124,7 +130,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         m = self.mutex
         c = self.characters
         choose = self.rng.choice
@@ -190,11 +196,11 @@
         if dir != _os.curdir:
             dir = _os.path.normcase(_os.path.abspath(dir))
         # Try only a few names per directory.
-        for seq in xrange(100):
-            name = namer.next()
+        for seq in range(100):
+            name = next(namer)
             filename = _os.path.join(dir, name)
             try:
-                fd = _os.open(filename, flags, 0600)
+                fd = _os.open(filename, flags, 0o600)
                 fp = _os.fdopen(fd, 'w')
                 fp.write('blat')
                 fp.close()
@@ -229,11 +235,11 @@
 
     names = _get_candidate_names()
 
-    for seq in xrange(TMP_MAX):
-        name = names.next()
+    for seq in range(TMP_MAX):
+        name = next(names)
         file = _os.path.join(dir, pre + name + suf)
         try:
-            fd = _os.open(file, flags, 0600)
+            fd = _os.open(file, flags, 0o600)
             _set_cloexec(fd)
             return (fd, _os.path.abspath(file))
         except OSError as e:
@@ -321,11 +327,11 @@
 
     names = _get_candidate_names()
 
-    for seq in xrange(TMP_MAX):
-        name = names.next()
+    for seq in range(TMP_MAX):
+        name = next(names)
         file = _os.path.join(dir, prefix + name + suffix)
         try:
-            _os.mkdir(file, 0700)
+            _os.mkdir(file, 0o700)
             return file
         except OSError as e:
             if e.errno == _errno.EEXIST:
@@ -356,8 +362,8 @@
         dir = gettempdir()
 
     names = _get_candidate_names()
-    for seq in xrange(TMP_MAX):
-        name = names.next()
+    for seq in range(TMP_MAX):
+        name = next(names)
         file = _os.path.join(dir, prefix + name + suffix)
         if not _exists(file):
             return file
@@ -372,10 +378,11 @@
     remove the file when it is no longer needed.
     """
 
-    def __init__(self, file, name):
+    def __init__(self, file, name, delete=True):
         self.file = file
         self.name = name
         self.close_called = False
+        self.delete = delete
 
     def __getattr__(self, name):
         file = self.__dict__['file']
@@ -400,23 +407,25 @@
             if not self.close_called:
                 self.close_called = True
                 self.file.close()
-                self.unlink(self.name)
+                if self.delete:
+                    self.unlink(self.name)
 
         def __del__(self):
             self.close()
 
 def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
-                       prefix=template, dir=None):
+                       prefix=template, dir=None, delete=True):
     """Create and return a temporary file.
     Arguments:
     'prefix', 'suffix', 'dir' -- as for mkstemp.
     'mode' -- the mode argument to os.fdopen (default "w+b").
     'bufsize' -- the buffer size argument to os.fdopen (default -1).
+    'delete' -- whether the file is deleted on close (default True).
     The file is created as mkstemp() would do it.
 
     Returns an object with a file-like interface; the name of the file
     is accessible as file.name.  The file will be automatically deleted
-    when it is closed.
+    when it is closed unless the 'delete' argument is set to False.
     """
 
     if dir is None:
@@ -429,12 +438,12 @@
 
     # Setting O_TEMPORARY in the flags causes the OS to delete
     # the file when it is closed.  This is only supported by Windows.
-    if _os.name == 'nt':
+    if _os.name == 'nt' and delete:
         flags |= _os.O_TEMPORARY
 
     (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
     file = _os.fdopen(fd, mode, bufsize)
-    return _TemporaryFileWrapper(file, name)
+    return _TemporaryFileWrapper(file, name, delete)
 
 if _os.name != 'posix' or _os.sys.platform == 'cygwin':
     # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
@@ -470,3 +479,111 @@
         except:
             _os.close(fd)
             raise
+
+class SpooledTemporaryFile:
+    """Temporary file wrapper, specialized to switch from
+    StringIO to a real file when it exceeds a certain size or
+    when a fileno is needed.
+    """
+    _rolled = False
+
+    def __init__(self, max_size=0, mode='w+b', bufsize=-1,
+                 suffix="", prefix=template, dir=None):
+        self._file = _StringIO()
+        self._max_size = max_size
+        self._rolled = False
+        self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir)
+
+    def _check(self, file):
+        if self._rolled: return
+        max_size = self._max_size
+        if max_size and file.tell() > max_size:
+            self.rollover()
+
+    def rollover(self):
+        if self._rolled: return
+        file = self._file
+        newfile = self._file = TemporaryFile(*self._TemporaryFileArgs)
+        del self._TemporaryFileArgs
+
+        newfile.write(file.getvalue())
+        newfile.seek(file.tell(), 0)
+
+        self._rolled = True
+
+    # file protocol
+    def __iter__(self):
+        return self._file.__iter__()
+
+    def close(self):
+        self._file.close()
+
+    @property
+    def closed(self):
+        return self._file.closed
+
+    @property
+    def encoding(self):
+        return self._file.encoding
+
+    def fileno(self):
+        self.rollover()
+        return self._file.fileno()
+
+    def flush(self):
+        self._file.flush()
+
+    def isatty(self):
+        return self._file.isatty()
+
+    @property
+    def mode(self):
+        return self._file.mode
+
+    @property
+    def name(self):
+        return self._file.name
+
+    @property
+    def newlines(self):
+        return self._file.newlines
+
+    def next(self):
+        return self._file.next
+
+    def read(self, *args):
+        return self._file.read(*args)
+
+    def readline(self, *args):
+        return self._file.readline(*args)
+
+    def readlines(self, *args):
+        return self._file.readlines(*args)
+
+    def seek(self, *args):
+        self._file.seek(*args)
+
+    @property
+    def softspace(self):
+        return self._file.softspace
+
+    def tell(self):
+        return self._file.tell()
+
+    def truncate(self):
+        self._file.truncate()
+
+    def write(self, s):
+        file = self._file
+        rv = file.write(s)
+        self._check(file)
+        return rv
+
+    def writelines(self, iterable):
+        file = self._file
+        rv = file.writelines(iterable)
+        self._check(file)
+        return rv
+
+    def xreadlines(self, *args):
+        return self._file.xreadlines(*args)

Modified: python/branches/p3yk-noslice/Lib/test/README
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/README	(original)
+++ python/branches/p3yk-noslice/Lib/test/README	Wed Jul 11 15:40:56 2007
@@ -15,7 +15,7 @@
 one of these options.  Each option requires writing a test module using the
 conventions of the selected option:
 
-    - PyUnit_ based tests
+    - unittest_ based tests
     - doctest_ based tests
     - "traditional" Python test modules
 
@@ -28,31 +28,34 @@
 able to refer to the C and Python code in the CVS repository when writing
 your regression test cases.
 
-.. _PyUnit:
 .. _unittest: http://www.python.org/doc/current/lib/module-unittest.html
 .. _doctest: http://www.python.org/doc/current/lib/module-doctest.html
 
-PyUnit based tests
+unittest-based tests
 ------------------
-The PyUnit_ framework is based on the ideas of unit testing as espoused
+The unittest_ framework is based on the ideas of unit testing as espoused
 by Kent Beck and the `Extreme Programming`_ (XP) movement.  The specific
 interface provided by the framework is tightly based on the JUnit_
 Java implementation of Beck's original SmallTalk test framework.  Please
 see the documentation of the unittest_ module for detailed information on
-the interface and general guidelines on writing PyUnit based tests.
+the interface and general guidelines on writing unittest-based tests.
 
-The test_support helper module provides two functions for use by
-PyUnit based tests in the Python regression testing framework:
-
-- ``run_unittest()`` takes a ``unittest.TestCase`` derived class as a
-  parameter and runs the tests defined in that class
-   
-- ``run_suite()`` takes a populated ``TestSuite`` instance and runs the
-  tests
+The test_support helper module provides a function for use by
+unittest-based tests in the Python regression testing framework,
+``run_unittest()``. This is the primary way of running tests in the
+standard library. You can pass it any number of the following:
+
+- classes derived from or instances of ``unittest.TestCase`` or
+  ``unittest.TestSuite``. These will be handed off to unittest for
+  converting into a proper TestSuite instance.
+
+- a string; this must be a key in sys.modules. The module associated with
+  that string will be scanned by ``unittest.TestLoader.loadTestsFromModule``.
+  This is usually seen as ``test_support.run_unittest(__name__)`` in a test
+  module's ``test_main()`` function. This has the advantage of picking up
+  new tests automatically, without you having to add each new test case
+  manually.
    
-``run_suite()`` is preferred because unittest files typically grow multiple
-test classes, and you might as well be prepared.
-
 All test methods in the Python regression framework have names that
 start with "``test_``" and use lower-case names with words separated with
 underscores.
@@ -63,7 +66,7 @@
 latter information makes it easier to find the source for the test
 than the docstring.
 
-All PyUnit-based tests in the Python test suite use boilerplate that
+All unittest-based tests in the Python test suite use boilerplate that
 looks like this (with minor variations)::
 
     import unittest
@@ -97,11 +100,7 @@
     ...etc...
 
     def test_main():
-        suite = unittest.TestSuite()
-        suite.addTest(unittest.makeSuite(MyTestCase1))
-        suite.addTest(unittest.makeSuite(MyTestCase2))
-        ...add more suites...
-        test_support.run_suite(suite)
+        test_support.run_unittest(__name__)
 
     if __name__ == "__main__":
         test_main()
@@ -415,7 +414,7 @@
       This is rarely required with the "traditional" Python tests, and
       you shouldn't create a module global with name test_main unless
       you're specifically exploiting this gimmick.  This usage does
-      prove useful with PyUnit-based tests as well, however; defining
+      prove useful with unittest-based tests as well, however; defining
       a ``test_main()`` which is run by regrtest and a script-stub in the
       test module ("``if __name__ == '__main__': test_main()``") allows
       the test to be used like any other Python test and also work

Modified: python/branches/p3yk-noslice/Lib/test/bad_coding2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/bad_coding2.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/bad_coding2.py	Wed Jul 11 15:40:56 2007
@@ -1,2 +1,2 @@
 #coding: utf8
-print '我'
+print('我')

Deleted: /python/branches/p3yk-noslice/Lib/test/crashers/dangerous_subclassing.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/crashers/dangerous_subclassing.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,12 +0,0 @@
-
-# http://python.org/sf/1174712
-
-import types
-
-class X(types.ModuleType, str):
-    """Such a subclassing is incorrectly allowed --
-    see the SF bug report for explanations"""
-
-if __name__ == '__main__':
-    X('name')    # segfault: ModuleType.__init__() reads
-                 # the dict at the wrong offset

Deleted: /python/branches/p3yk-noslice/Lib/test/crashers/infinite_rec_5.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/crashers/infinite_rec_5.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,10 +0,0 @@
-
-# http://python.org/sf/1267884
-
-import types
-
-class C:
-    __str__ = types.InstanceType.__str__
-
-if __name__ == '__main__':
-    str(C())   # segfault: infinite recursion in C

Deleted: /python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,19 +0,0 @@
-
-# http://python.org/sf/1303614
-
-class Y(object):
-    pass
-
-class type_with_modifiable_dict(Y, type):
-    pass
-
-class MyClass(object):
-    """This class has its __dict__ attribute completely exposed:
-    user code can read, reassign and even delete it.
-    """
-    __metaclass__ = type_with_modifiable_dict
-
-
-if __name__ == '__main__':
-    del MyClass.__dict__  # if we set tp_dict to NULL,
-    print(MyClass)         # doing anything with MyClass segfaults

Modified: python/branches/p3yk-noslice/Lib/test/exception_hierarchy.txt
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/exception_hierarchy.txt	(original)
+++ python/branches/p3yk-noslice/Lib/test/exception_hierarchy.txt	Wed Jul 11 15:40:56 2007
@@ -4,39 +4,38 @@
  +-- Exception
       +-- GeneratorExit
       +-- StopIteration
-      +-- StandardError
-      |    +-- ArithmeticError
-      |    |    +-- FloatingPointError
-      |    |    +-- OverflowError
-      |    |    +-- ZeroDivisionError
-      |    +-- AssertionError
-      |    +-- AttributeError
-      |    +-- EnvironmentError
-      |    |    +-- IOError
-      |    |    +-- OSError
-      |    |         +-- WindowsError (Windows)
-      |    |         +-- VMSError (VMS)
-      |    +-- EOFError
-      |    +-- ImportError
-      |    +-- LookupError
-      |    |    +-- IndexError
-      |    |    +-- KeyError
-      |    +-- MemoryError
-      |    +-- NameError
-      |    |    +-- UnboundLocalError
-      |    +-- ReferenceError
-      |    +-- RuntimeError
-      |    |    +-- NotImplementedError
-      |    +-- SyntaxError
-      |    |    +-- IndentationError
-      |    |         +-- TabError
-      |    +-- SystemError
-      |    +-- TypeError
-      |    +-- ValueError
-      |    |    +-- UnicodeError
-      |    |         +-- UnicodeDecodeError
-      |    |         +-- UnicodeEncodeError
-      |    |         +-- UnicodeTranslateError
+      +-- ArithmeticError
+      |    +-- FloatingPointError
+      |    +-- OverflowError
+      |    +-- ZeroDivisionError
+      +-- AssertionError
+      +-- AttributeError
+      +-- EnvironmentError
+      |    +-- IOError
+      |    +-- OSError
+      |         +-- WindowsError (Windows)
+      |         +-- VMSError (VMS)
+      +-- EOFError
+      +-- ImportError
+      +-- LookupError
+      |    +-- IndexError
+      |    +-- KeyError
+      +-- MemoryError
+      +-- NameError
+      |    +-- UnboundLocalError
+      +-- ReferenceError
+      +-- RuntimeError
+      |    +-- NotImplementedError
+      +-- SyntaxError
+      |    +-- IndentationError
+      |         +-- TabError
+      +-- SystemError
+      +-- TypeError
+      +-- ValueError
+      |    +-- UnicodeError
+      |         +-- UnicodeDecodeError
+      |         +-- UnicodeEncodeError
+      |         +-- UnicodeTranslateError
       +-- Warning
            +-- DeprecationWarning
            +-- PendingDeprecationWarning

Modified: python/branches/p3yk-noslice/Lib/test/fork_wait.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/fork_wait.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/fork_wait.py	Wed Jul 11 15:40:56 2007
@@ -52,7 +52,7 @@
         time.sleep(LONGSLEEP)
 
         a = sorted(self.alive.keys())
-        self.assertEquals(a, range(NUM_THREADS))
+        self.assertEquals(a, list(range(NUM_THREADS)))
 
         prefork_lives = self.alive.copy()
 

Modified: python/branches/p3yk-noslice/Lib/test/inspect_fodder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/inspect_fodder.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/inspect_fodder.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,7 @@
 # line 5
 
 # line 7
-def spam(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h):
+def spam(a, b, c, d=3, e=4, f=5, *g, **h):
     eggs(b + d, c + f)
 
 # line 11

Modified: python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py	Wed Jul 11 15:40:56 2007
@@ -60,8 +60,8 @@
 
 # line 61
 multiline_sig = [
-    lambda (x,
-            y): x+y,
+    lambda x, \
+            y: x+y,
     None,
     ]
 

Modified: python/branches/p3yk-noslice/Lib/test/leakers/test_selftype.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/leakers/test_selftype.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/leakers/test_selftype.py	Wed Jul 11 15:40:56 2007
@@ -6,8 +6,8 @@
 def leak():
     class T(type):
         pass
-    class U(type):
-        __metaclass__ = T
+    class U(type, metaclass=T):
+        pass
     U.__class__ = U
     del U
     gc.collect(); gc.collect(); gc.collect()

Modified: python/branches/p3yk-noslice/Lib/test/list_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/list_tests.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/list_tests.py	Wed Jul 11 15:40:56 2007
@@ -47,9 +47,9 @@
         self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
 
     def test_print(self):
-        d = self.type2test(xrange(200))
+        d = self.type2test(range(200))
         d.append(d)
-        d.extend(xrange(200,400))
+        d.extend(range(200,400))
         d.append(d)
         d.append(400)
         try:
@@ -77,7 +77,7 @@
         a = self.type2test(range(20))
         r = reversed(a)
         self.assertEqual(list(r), self.type2test(range(19, -1, -1)))
-        self.assertRaises(StopIteration, r.next)
+        self.assertRaises(StopIteration, next, r)
         self.assertEqual(list(reversed(self.type2test())),
                          self.type2test())
 
@@ -398,7 +398,7 @@
                 del self.victim[:]
                 return False
         a = self.type2test()
-        a[:] = [EvilCmp(a) for _ in xrange(100)]
+        a[:] = [EvilCmp(a) for _ in range(100)]
         # This used to seg fault before patch #1005778
         self.assertRaises(ValueError, a.index, None)
 
@@ -451,7 +451,7 @@
         self.assertEqual(u, list("ham"))
 
     def test_iadd(self):
-        super(CommonTest, self).test_iadd()
+        super().test_iadd()
         u = self.type2test([0, 1])
         u2 = u
         u += [2, 3]

Modified: python/branches/p3yk-noslice/Lib/test/mapping_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/mapping_tests.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/mapping_tests.py	Wed Jul 11 15:40:56 2007
@@ -69,7 +69,7 @@
         if not d: self.fail("Full mapping must compare to True")
         # keys(), items(), iterkeys() ...
         def check_iterandlist(iter, lst, ref):
-            self.assert_(hasattr(iter, 'next'))
+            self.assert_(hasattr(iter, '__next__'))
             self.assert_(hasattr(iter, '__iter__'))
             x = list(iter)
             self.assert_(set(x)==set(lst)==set(ref))
@@ -81,8 +81,8 @@
         check_iterandlist(iter(d.items()), list(d.items()),
                           self.reference.items())
         #get
-        key, value = iter(d.items()).next()
-        knownkey, knownvalue = iter(self.other.items()).next()
+        key, value = next(iter(d.items()))
+        knownkey, knownvalue = next(iter(self.other.items()))
         self.assertEqual(d.get(key, knownvalue), value)
         self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
         self.failIf(knownkey in d)
@@ -107,8 +107,8 @@
         self.assertEqual(dict(p), self.reference)
         d = self._full_mapping(self.reference)
         #setdefault
-        key, value = iter(d.items()).next()
-        knownkey, knownvalue = iter(self.other.items()).next()
+        key, value = next(iter(d.items()))
+        knownkey, knownvalue = next(iter(self.other.items()))
         self.assertEqual(d.setdefault(key, knownvalue), value)
         self.assertEqual(d[key], value)
         self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
@@ -225,7 +225,7 @@
                         self.i = 1
                     def __iter__(self):
                         return self
-                    def next(self):
+                    def __next__(self):
                         if self.i:
                             self.i = 0
                             return 'a'
@@ -242,7 +242,7 @@
                         self.i = ord('a')
                     def __iter__(self):
                         return self
-                    def next(self):
+                    def __next__(self):
                         if self.i <= ord('z'):
                             rtn = chr(self.i)
                             self.i += 1
@@ -257,7 +257,7 @@
         class badseq(object):
             def __iter__(self):
                 return self
-            def next(self):
+            def __next__(self):
                 raise Exc()
 
         self.assertRaises(Exc, d.update, badseq())
@@ -456,7 +456,7 @@
         class BadSeq(object):
             def __iter__(self):
                 return self
-            def next(self):
+            def __next__(self):
                 raise Exc()
 
         self.assertRaises(Exc, self.type2test.fromkeys, BadSeq())

Modified: python/branches/p3yk-noslice/Lib/test/output/test_cProfile
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_cProfile	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_cProfile	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 test_cProfile
-         127 function calls (107 primitive calls) in 1.000 CPU seconds
+         119 function calls (99 primitive calls) in 1.000 CPU seconds
 
    Ordered by: standard name
 
@@ -18,7 +18,6 @@
        12    0.000    0.000    0.012    0.001 {hasattr}
         4    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
-        8    0.000    0.000    0.000    0.000 {range}
         4    0.000    0.000    0.000    0.000 {sys.exc_info}
 
 
@@ -28,7 +27,6 @@
                                                       ncalls  tottime  cumtime
 <string>:1(<module>)                              ->       1    0.270    1.000  test_cProfile.py:30(testfunc)
 test_cProfile.py:103(subhelper)                   ->      16    0.016    0.016  test_cProfile.py:115(__getattr__)
-                                                           8    0.000    0.000  {range}
 test_cProfile.py:115(__getattr__)                 -> 
 test_cProfile.py:30(testfunc)                     ->       1    0.014    0.130  test_cProfile.py:40(factorial)
                                                            2    0.040    0.600  test_cProfile.py:60(helper)
@@ -49,7 +47,6 @@
 {hasattr}                                         ->      12    0.012    0.012  test_cProfile.py:115(__getattr__)
 {method 'append' of 'list' objects}               -> 
 {method 'disable' of '_lsprof.Profiler' objects}  -> 
-{range}                                           -> 
 {sys.exc_info}                                    -> 
 
 
@@ -76,7 +73,6 @@
                                                            8    0.000    0.008  test_cProfile.py:93(helper2)
 {method 'append' of 'list' objects}               <-       4    0.000    0.000  test_cProfile.py:78(helper1)
 {method 'disable' of '_lsprof.Profiler' objects}  <- 
-{range}                                           <-       8    0.000    0.000  test_cProfile.py:103(subhelper)
 {sys.exc_info}                                    <-       4    0.000    0.000  test_cProfile.py:78(helper1)
 
 

Modified: python/branches/p3yk-noslice/Lib/test/output/test_class
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_class	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_class	Wed Jul 11 15:40:56 2007
@@ -46,8 +46,7 @@
 __int__: ()
 __int__: ()
 __float__: ()
-__oct__: ()
-__hex__: ()
+__index__: ()
 __hash__: ()
 __repr__: ()
 __str__: ()

Modified: python/branches/p3yk-noslice/Lib/test/output/test_extcall
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_extcall	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_extcall	Wed Jul 11 15:40:56 2007
@@ -9,6 +9,9 @@
 (1, 2, 3) {'a': 4, 'b': 5}
 (1, 2, 3, 4, 5) {'a': 6, 'b': 7}
 (1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
+(1, 2, 3) {'a': 4, 'b': 5}
+(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
+(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
 TypeError: g() takes at least 1 positional argument (0 given)
 TypeError: g() takes at least 1 positional argument (0 given)
 TypeError: g() takes at least 1 positional argument (0 given)
@@ -25,12 +28,12 @@
 g() got multiple values for keyword argument 'b'
 f() keywords must be strings
 h() got an unexpected keyword argument 'e'
-h() argument after * must be a sequence
-dir() argument after * must be a sequence
-NoneType object argument after * must be a sequence
-h() argument after ** must be a dictionary
-dir() argument after ** must be a dictionary
-NoneType object argument after ** must be a dictionary
+h() argument after * must be a sequence, not function
+dir() argument after * must be a sequence, not function
+NoneType object argument after * must be a sequence, not function
+h() argument after ** must be a mapping, not function
+dir() argument after ** must be a mapping, not function
+NoneType object argument after ** must be a mapping, not function
 dir() got multiple values for keyword argument 'b'
 3 512 True
 3

Modified: python/branches/p3yk-noslice/Lib/test/output/test_logging
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_logging	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_logging	Wed Jul 11 15:40:56 2007
@@ -488,12 +488,12 @@
 -- log_test4  begin  ---------------------------------------------------
 config0: ok.
 config1: ok.
-config2: <type 'exceptions.AttributeError'>
-config3: <type 'exceptions.KeyError'>
+config2: <type 'AttributeError'>
+config3: <type 'KeyError'>
 -- log_test4  end    ---------------------------------------------------
 -- log_test5  begin  ---------------------------------------------------
 ERROR:root:just testing
-<type 'exceptions.KeyError'>... Don't panic!
+<type 'KeyError'>... Don't panic!
 -- log_test5  end    ---------------------------------------------------
 -- logrecv output begin  ---------------------------------------------------
 ERR -> CRITICAL: Message 0 (via logrecv.tcp.ERR)

Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_operations
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_operations	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,19 +0,0 @@
-test_operations
-3. Operations
-XXX Mostly not yet implemented
-3.1 Dictionary lookups fail if __cmp__() raises an exception
-raising error
-d[x2] = 2: caught the RuntimeError outside
-raising error
-z = d[x2]: caught the RuntimeError outside
-raising error
-x2 in d: caught the RuntimeError outside
-raising error
-d.get(x2): caught the RuntimeError outside
-raising error
-d.setdefault(x2, 42): caught the RuntimeError outside
-raising error
-d.pop(x2): caught the RuntimeError outside
-raising error
-d.update({x2: 2}): caught the RuntimeError outside
-resize bugs not triggered.

Modified: python/branches/p3yk-noslice/Lib/test/output/test_pkg
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_pkg	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_pkg	Wed Jul 11 15:40:56 2007
@@ -15,8 +15,6 @@
 t3 loading
 t3.sub.subsub loading
 t3 t3.sub t3.sub.subsub
-t3 loading
-t3.sub.subsub loading
 running test t4
 t4 loading
 t4.sub.subsub loading

Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_popen2
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_popen2	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,9 +0,0 @@
-test_popen2
-Test popen2 module:
-testing popen2...
-testing popen3...
-All OK
-Testing os module:
-testing popen2...
-testing popen3...
-All OK

Modified: python/branches/p3yk-noslice/Lib/test/output/test_profile
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_profile	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_profile	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 test_profile
-         128 function calls (108 primitive calls) in 1.000 CPU seconds
+         120 function calls (100 primitive calls) in 1.000 CPU seconds
 
    Ordered by: standard name
 
@@ -8,7 +8,6 @@
         4    0.000    0.000    0.000    0.000 :0(exc_info)
         1    0.000    0.000    1.000    1.000 :0(exec)
        12    0.000    0.000    0.012    0.001 :0(hasattr)
-        8    0.000    0.000    0.000    0.000 :0(range)
         1    0.000    0.000    0.000    0.000 :0(setprofile)
         1    0.000    0.000    1.000    1.000 <string>:1(<module>)
         0    0.000             0.000          profile:0(profiler)
@@ -31,14 +30,12 @@
 :0(exc_info)                          -> 
 :0(exec)                              -> <string>:1(<module>)(1)    1.000
 :0(hasattr)                           -> test_profile.py:115(__getattr__)(12)    0.028
-:0(range)                             -> 
 :0(setprofile)                        -> 
 <string>:1(<module>)                  -> test_profile.py:30(testfunc)(1)    1.000
 profile:0(profiler)                   -> profile:0(testfunc())(1)    1.000
 profile:0(testfunc())                 -> :0(exec)(1)    1.000
                                          :0(setprofile)(1)    0.000
-test_profile.py:103(subhelper)        -> :0(range)(8)    0.000
-                                         test_profile.py:115(__getattr__)(16)    0.028
+test_profile.py:103(subhelper)        -> test_profile.py:115(__getattr__)(16)    0.028
 test_profile.py:115(__getattr__)      -> 
 test_profile.py:30(testfunc)          -> test_profile.py:40(factorial)(1)    0.170
                                          test_profile.py:60(helper)(2)    0.600
@@ -65,7 +62,6 @@
 :0(exec)                              <- profile:0(testfunc())(1)    1.000
 :0(hasattr)                           <- test_profile.py:78(helper1)(4)    0.120
                                          test_profile.py:93(helper2)(8)    0.400
-:0(range)                             <- test_profile.py:103(subhelper)(8)    0.080
 :0(setprofile)                        <- profile:0(testfunc())(1)    1.000
 <string>:1(<module>)                  <- :0(exec)(1)    1.000
 profile:0(profiler)                   <- 

Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_pty
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_pty	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,3 +0,0 @@
-test_pty
-I wish to buy a fish license.
-For my pet fish, Eric.

Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_pyexpat
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_pyexpat	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,110 +0,0 @@
-test_pyexpat
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-PI:
-	'xml-stylesheet' 'href="stylesheet.css"'
-Comment:
-	' comment data '
-Notation declared: ('notation', None, 'notation.jpeg', None)
-Unparsed entity decl:
-	('unparsed_entity', None, 'entity.file', None, 'notation')
-Start element:
-	'root' {'attr1': 'value1', 'attr2': 'value2\xe1\xbd\x80'}
-NS decl:
-	'myns' 'http://www.python.org/namespace'
-Start element:
-	'http://www.python.org/namespace!subelement' {}
-Character data:
-	'Contents of subelements'
-End element:
-	'http://www.python.org/namespace!subelement'
-End of NS decl:
-	'myns'
-Start element:
-	'sub2' {}
-Start of CDATA section
-Character data:
-	'contents of CDATA section'
-End of CDATA section
-End element:
-	'sub2'
-External entity ref: (None, 'entity.file', None)
-End element:
-	'root'
-PI:
-	u'xml-stylesheet' u'href="stylesheet.css"'
-Comment:
-	u' comment data '
-Notation declared: (u'notation', None, u'notation.jpeg', None)
-Unparsed entity decl:
-	(u'unparsed_entity', None, u'entity.file', None, u'notation')
-Start element:
-	u'root' {u'attr1': u'value1', u'attr2': u'value2\u1f40'}
-NS decl:
-	u'myns' u'http://www.python.org/namespace'
-Start element:
-	u'http://www.python.org/namespace!subelement' {}
-Character data:
-	u'Contents of subelements'
-End element:
-	u'http://www.python.org/namespace!subelement'
-End of NS decl:
-	u'myns'
-Start element:
-	u'sub2' {}
-Start of CDATA section
-Character data:
-	u'contents of CDATA section'
-End of CDATA section
-End element:
-	u'sub2'
-External entity ref: (None, u'entity.file', None)
-End element:
-	u'root'
-PI:
-	u'xml-stylesheet' u'href="stylesheet.css"'
-Comment:
-	u' comment data '
-Notation declared: (u'notation', None, u'notation.jpeg', None)
-Unparsed entity decl:
-	(u'unparsed_entity', None, u'entity.file', None, u'notation')
-Start element:
-	u'root' {u'attr1': u'value1', u'attr2': u'value2\u1f40'}
-NS decl:
-	u'myns' u'http://www.python.org/namespace'
-Start element:
-	u'http://www.python.org/namespace!subelement' {}
-Character data:
-	u'Contents of subelements'
-End element:
-	u'http://www.python.org/namespace!subelement'
-End of NS decl:
-	u'myns'
-Start element:
-	u'sub2' {}
-Start of CDATA section
-Character data:
-	u'contents of CDATA section'
-End of CDATA section
-End element:
-	u'sub2'
-External entity ref: (None, u'entity.file', None)
-End element:
-	u'root'
-
-Testing constructor for proper handling of namespace_separator values:
-Legal values tested o.k.
-Caught expected TypeError:
-ParserCreate() argument 2 must be string or None, not int
-Caught expected ValueError:
-namespace_separator must be at most one character, omitted, or None

Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_threadedtempfile
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_threadedtempfile	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,5 +0,0 @@
-test_threadedtempfile
-Creating
-Starting
-Reaping
-Done: errors 0 ok 1000

Modified: python/branches/p3yk-noslice/Lib/test/output/test_tokenize
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_tokenize	(original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_tokenize	Wed Jul 11 15:40:56 2007
@@ -124,66 +124,80 @@
 39,5-39,7:	OP	'!='
 39,8-39,11:	NUMBER	'255'
 39,11-39,12:	NEWLINE	'\n'
-40,0-40,4:	NUMBER	'0377'
-40,5-40,7:	OP	'!='
-40,8-40,11:	NUMBER	'255'
-40,11-40,12:	NEWLINE	'\n'
+40,0-40,5:	NUMBER	'0o377'
+40,6-40,8:	OP	'!='
+40,9-40,12:	NUMBER	'255'
+40,12-40,13:	NEWLINE	'\n'
 41,0-41,10:	NUMBER	'2147483647'
 41,13-41,15:	OP	'!='
-41,16-41,28:	NUMBER	'017777777777'
-41,28-41,29:	NEWLINE	'\n'
+41,16-41,29:	NUMBER	'0o17777777777'
+41,29-41,30:	NEWLINE	'\n'
 42,0-42,1:	OP	'-'
 42,1-42,11:	NUMBER	'2147483647'
 42,11-42,12:	OP	'-'
 42,12-42,13:	NUMBER	'1'
 42,14-42,16:	OP	'!='
-42,17-42,29:	NUMBER	'020000000000'
-42,29-42,30:	NEWLINE	'\n'
-43,0-43,12:	NUMBER	'037777777777'
-43,13-43,15:	OP	'!='
-43,16-43,17:	OP	'-'
-43,17-43,18:	NUMBER	'1'
-43,18-43,19:	NEWLINE	'\n'
+42,17-42,30:	NUMBER	'0o20000000000'
+42,30-42,31:	NEWLINE	'\n'
+43,0-43,13:	NUMBER	'0o37777777777'
+43,14-43,16:	OP	'!='
+43,17-43,18:	OP	'-'
+43,18-43,19:	NUMBER	'1'
+43,19-43,20:	NEWLINE	'\n'
 44,0-44,10:	NUMBER	'0xffffffff'
 44,11-44,13:	OP	'!='
 44,14-44,15:	OP	'-'
 44,15-44,16:	NUMBER	'1'
-44,16-44,17:	NEWLINE	'\n'
+44,16-44,17:	OP	';'
+44,18-44,31:	NUMBER	'0o37777777777'
+44,32-44,34:	OP	'!='
+44,35-44,36:	OP	'-'
+44,36-44,37:	NUMBER	'1'
+44,37-44,38:	OP	';'
+44,39-44,40:	OP	'-'
+44,40-44,49:	NUMBER	'0o1234567'
+44,50-44,52:	OP	'=='
+44,53-44,64:	NUMBER	'0O001234567'
+44,64-44,65:	OP	';'
+44,66-44,73:	NUMBER	'0b10101'
+44,74-44,76:	OP	'=='
+44,77-44,87:	NUMBER	'0B00010101'
+44,87-44,88:	NEWLINE	'\n'
 45,0-45,1:	NL	'\n'
 46,0-46,15:	COMMENT	'# Long integers'
 46,15-46,16:	NL	'\n'
 47,0-47,1:	NAME	'x'
 47,2-47,3:	OP	'='
-47,4-47,6:	NUMBER	'0L'
-47,6-47,7:	NEWLINE	'\n'
+47,4-47,5:	NUMBER	'0'
+47,5-47,6:	NEWLINE	'\n'
 48,0-48,1:	NAME	'x'
 48,2-48,3:	OP	'='
-48,4-48,6:	NUMBER	'0l'
-48,6-48,7:	NEWLINE	'\n'
+48,4-48,5:	NUMBER	'0'
+48,5-48,6:	NEWLINE	'\n'
 49,0-49,1:	NAME	'x'
 49,2-49,3:	OP	'='
-49,4-49,23:	NUMBER	'0xffffffffffffffffL'
-49,23-49,24:	NEWLINE	'\n'
+49,4-49,22:	NUMBER	'0xffffffffffffffff'
+49,22-49,23:	NEWLINE	'\n'
 50,0-50,1:	NAME	'x'
 50,2-50,3:	OP	'='
-50,4-50,23:	NUMBER	'0xffffffffffffffffl'
-50,23-50,24:	NEWLINE	'\n'
+50,4-50,22:	NUMBER	'0xffffffffffffffff'
+50,22-50,23:	NEWLINE	'\n'
 51,0-51,1:	NAME	'x'
 51,2-51,3:	OP	'='
-51,4-51,23:	NUMBER	'077777777777777777L'
+51,4-51,23:	NUMBER	'0o77777777777777777'
 51,23-51,24:	NEWLINE	'\n'
 52,0-52,1:	NAME	'x'
 52,2-52,3:	OP	'='
-52,4-52,23:	NUMBER	'077777777777777777l'
+52,4-52,23:	NUMBER	'0B11101010111111111'
 52,23-52,24:	NEWLINE	'\n'
 53,0-53,1:	NAME	'x'
 53,2-53,3:	OP	'='
-53,4-53,35:	NUMBER	'123456789012345678901234567890L'
-53,35-53,36:	NEWLINE	'\n'
+53,4-53,34:	NUMBER	'123456789012345678901234567890'
+53,34-53,35:	NEWLINE	'\n'
 54,0-54,1:	NAME	'x'
 54,2-54,3:	OP	'='
-54,4-54,35:	NUMBER	'123456789012345678901234567890l'
-54,35-54,36:	NEWLINE	'\n'
+54,4-54,34:	NUMBER	'123456789012345678901234567890'
+54,34-54,35:	NEWLINE	'\n'
 55,0-55,1:	NL	'\n'
 56,0-56,24:	COMMENT	'# Floating-point numbers'
 56,24-56,25:	NL	'\n'

Deleted: /python/branches/p3yk-noslice/Lib/test/output/xmltests
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/xmltests	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,364 +0,0 @@
-xmltests
-Passed testAAA
-Passed setAttribute() sets ownerDocument
-Passed setAttribute() sets ownerElement
-Test Succeeded testAAA
-Passed assertion: len(Node.allnodes) == 0
-Passed testAAB
-Test Succeeded testAAB
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Test Succeeded testAddAttr
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testAppendChild
-Passed assertion: len(Node.allnodes) == 0
-Passed appendChild(<fragment>)
-Test Succeeded testAppendChildFragment
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListItem
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListItemNS
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListItems
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListKeys
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListKeysNS
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListLength
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrListValues
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrList__getitem__
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testAttrList__setitem__
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testAttributeRepr
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Passed Test
-Test Succeeded testChangeAttr
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testChildNodes
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testCloneAttributeDeep
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testCloneAttributeShallow
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testCloneDocumentDeep
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testCloneDocumentShallow
-Passed assertion: len(Node.allnodes) == 0
-Passed clone of element has same attribute keys
-Passed clone of attribute node has proper attribute values
-Passed clone of attribute node correctly owned
-Passed testCloneElementDeep
-Test Succeeded testCloneElementDeep
-Passed assertion: len(Node.allnodes) == 0
-Passed clone of element has same attribute keys
-Passed clone of attribute node has proper attribute values
-Passed clone of attribute node correctly owned
-Passed testCloneElementShallow
-Test Succeeded testCloneElementShallow
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testClonePIDeep
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testClonePIShallow
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testComment
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testCreateAttributeNS
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testCreateElementNS
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Passed Test
-Test Succeeded testDeleteAttr
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testDocumentElement
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Test Succeeded testElement
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Test Succeeded testElementReprAndStr
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testFirstChild
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetAttrLength
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetAttrList
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetAttrValues
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetAttribute
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetAttributeNS
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetAttributeNode
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Test Succeeded testGetElementsByTagName
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Test Succeeded testGetElementsByTagNameNS
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testGetEmptyNodeListFromElementsByTagNameNS
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testHasChildNodes
-Passed assertion: len(Node.allnodes) == 0
-Passed testInsertBefore -- node properly placed in tree
-Passed testInsertBefore -- node properly placed in tree
-Passed testInsertBefore -- node properly placed in tree
-Test Succeeded testInsertBefore
-Passed assertion: len(Node.allnodes) == 0
-Passed insertBefore(<fragment>, None)
-Passed insertBefore(<fragment>, orig)
-Test Succeeded testInsertBeforeFragment
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testLegalChildren
-Passed assertion: len(Node.allnodes) == 0
-Passed NamedNodeMap.__setitem__() sets ownerDocument
-Passed NamedNodeMap.__setitem__() sets ownerElement
-Passed NamedNodeMap.__setitem__() sets value
-Passed NamedNodeMap.__setitem__() sets nodeValue
-Test Succeeded testNamedNodeMapSetItem
-Passed assertion: len(Node.allnodes) == 0
-Passed test NodeList.item()
-Test Succeeded testNodeListItem
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testNonZero
-Passed assertion: len(Node.allnodes) == 0
-Passed testNormalize -- preparation
-Passed testNormalize -- result
-Passed testNormalize -- single empty node removed
-Test Succeeded testNormalize
-Passed assertion: len(Node.allnodes) == 0
-Passed testParents
-Test Succeeded testParents
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParse
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParseAttributeNamespaces
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParseAttributes
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParseElement
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParseElementNamespaces
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Test Succeeded testParseFromFile
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParseProcessingInstructions
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testParseString
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testProcessingInstruction
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testProcessingInstructionRepr
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testRemoveAttr
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testRemoveAttrNS
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testRemoveAttributeNode
-Passed assertion: len(Node.allnodes) == 0
-Passed replaceChild(<fragment>)
-Test Succeeded testReplaceChildFragment
-Passed assertion: len(Node.allnodes) == 0
-Passed testSAX2DOM - siblings
-Passed testSAX2DOM - parents
-Test Succeeded testSAX2DOM
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testSetAttrValueandNodeValue
-Passed assertion: len(Node.allnodes) == 0
-Passed testSiblings
-Test Succeeded testSiblings
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testTextNodeRepr
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testTextRepr
-Passed assertion: len(Node.allnodes) == 0
-Caught expected exception when adding extra document element.
-Test Succeeded testTooManyDocumentElements
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testUnlink
-Passed assertion: len(Node.allnodes) == 0
-Test Succeeded testWriteText
-Passed assertion: len(Node.allnodes) == 0
-Passed Test
-Passed Test
-Test Succeeded testWriteXML
-Passed assertion: len(Node.allnodes) == 0
-All tests succeeded
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-OK.
-PI:
-	'xml-stylesheet' 'href="stylesheet.css"'
-Comment:
-	' comment data '
-Notation declared: ('notation', None, 'notation.jpeg', None)
-Unparsed entity decl:
-	('unparsed_entity', None, 'entity.file', None, 'notation')
-Start element:
-	'root' {'attr1': 'value1', 'attr2': 'value2\xe1\xbd\x80'}
-NS decl:
-	'myns' 'http://www.python.org/namespace'
-Start element:
-	'http://www.python.org/namespace!subelement' {}
-Character data:
-	'Contents of subelements'
-End element:
-	'http://www.python.org/namespace!subelement'
-End of NS decl:
-	'myns'
-Start element:
-	'sub2' {}
-Start of CDATA section
-Character data:
-	'contents of CDATA section'
-End of CDATA section
-End element:
-	'sub2'
-External entity ref: (None, 'entity.file', None)
-End element:
-	'root'
-PI:
-	u'xml-stylesheet' u'href="stylesheet.css"'
-Comment:
-	u' comment data '
-Notation declared: (u'notation', None, u'notation.jpeg', None)
-Unparsed entity decl:
-	(u'unparsed_entity', None, u'entity.file', None, u'notation')
-Start element:
-	u'root' {u'attr1': u'value1', u'attr2': u'value2\u1f40'}
-NS decl:
-	u'myns' u'http://www.python.org/namespace'
-Start element:
-	u'http://www.python.org/namespace!subelement' {}
-Character data:
-	u'Contents of subelements'
-End element:
-	u'http://www.python.org/namespace!subelement'
-End of NS decl:
-	u'myns'
-Start element:
-	u'sub2' {}
-Start of CDATA section
-Character data:
-	u'contents of CDATA section'
-End of CDATA section
-End element:
-	u'sub2'
-External entity ref: (None, u'entity.file', None)
-End element:
-	u'root'
-PI:
-	u'xml-stylesheet' u'href="stylesheet.css"'
-Comment:
-	u' comment data '
-Notation declared: (u'notation', None, u'notation.jpeg', None)
-Unparsed entity decl:
-	(u'unparsed_entity', None, u'entity.file', None, u'notation')
-Start element:
-	u'root' {u'attr1': u'value1', u'attr2': u'value2\u1f40'}
-NS decl:
-	u'myns' u'http://www.python.org/namespace'
-Start element:
-	u'http://www.python.org/namespace!subelement' {}
-Character data:
-	u'Contents of subelements'
-End element:
-	u'http://www.python.org/namespace!subelement'
-End of NS decl:
-	u'myns'
-Start element:
-	u'sub2' {}
-Start of CDATA section
-Character data:
-	u'contents of CDATA section'
-End of CDATA section
-End element:
-	u'sub2'
-External entity ref: (None, u'entity.file', None)
-End element:
-	u'root'
-
-Testing constructor for proper handling of namespace_separator values:
-Legal values tested o.k.
-Caught expected TypeError:
-ParserCreate() argument 2 must be string or None, not int
-Caught expected ValueError:
-namespace_separator must be at most one character, omitted, or None
-Passed test_attrs_empty
-Passed test_attrs_wattr
-Passed test_double_quoteattr
-Passed test_escape_all
-Passed test_escape_basic
-Passed test_escape_extra
-Passed test_expat_attrs_empty
-Passed test_expat_attrs_wattr
-Passed test_expat_dtdhandler
-Passed test_expat_entityresolver
-Passed test_expat_file
-Passed test_expat_incomplete
-Passed test_expat_incremental
-Passed test_expat_incremental_reset
-Passed test_expat_inpsource_filename
-Passed test_expat_inpsource_location
-Passed test_expat_inpsource_stream
-Passed test_expat_inpsource_sysid
-Passed test_expat_locator_noinfo
-Passed test_expat_locator_withinfo
-Passed test_expat_nsattrs_empty
-Passed test_expat_nsattrs_wattr
-Passed test_filter_basic
-Passed test_make_parser
-Passed test_make_parser2
-Passed test_nsattrs_empty
-Passed test_nsattrs_wattr
-Passed test_quoteattr_basic
-Passed test_single_double_quoteattr
-Passed test_single_quoteattr
-Passed test_xmlgen_attr_escape
-Passed test_xmlgen_basic
-Passed test_xmlgen_content
-Passed test_xmlgen_content_escape
-Passed test_xmlgen_ignorable
-Passed test_xmlgen_ns
-Passed test_xmlgen_pi
-37 tests, 0 failures

Modified: python/branches/p3yk-noslice/Lib/test/outstanding_bugs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/outstanding_bugs.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/outstanding_bugs.py	Wed Jul 11 15:40:56 2007
@@ -10,13 +10,44 @@
 from test import test_support
 
 #
-# No test cases for outstanding bugs at the moment.
+# One test case for outstanding bugs at the moment:
 #
 
+class TestDifflibLongestMatch(unittest.TestCase):
+    # From Patch #1678339:
+    # The find_longest_match method in the difflib's SequenceMatcher has a bug.
+
+    # The bug is in turn caused by a problem with creating a b2j mapping which
+    # should contain a list of indices for each of the list elements in b.
+    # However, when the b2j mapping is being created (this is being done in
+    # __chain_b method in the SequenceMatcher) the mapping becomes broken. The
+    # cause of this is that for the frequently used elements the list of indices
+    # is removed and the element is being enlisted in the populardict mapping.
+
+    # The test case tries to match two strings like:
+    # abbbbbb.... and ...bbbbbbc
+
+    # The number of b is equal and the find_longest_match should have returned
+    # the proper amount. However, in case the number of "b"s is large enough, the
+    # method reports that the length of the longest common substring is 0. It
+    # simply can't find it.
+
+    # A bug was raised some time ago on this matter. It's ID is 1528074.
+
+    def test_find_longest_match(self):
+        import difflib
+        for i in (190, 200, 210):
+            text1 = "a" + "b"*i
+            text2 = "b"*i + "c"
+            m = difflib.SequenceMatcher(None, text1, text2)
+            (aptr, bptr, l) = m.find_longest_match(0, len(text1), 0, len(text2))
+            self.assertEquals(i, l)
+            self.assertEquals(aptr, 1)
+            self.assertEquals(bptr, 0)
+
 
 def test_main():
-    #test_support.run_unittest()
-    pass
+    test_support.run_unittest(TestDifflibLongestMatch)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/pickletester.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/pickletester.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/pickletester.py	Wed Jul 11 15:40:56 2007
@@ -88,8 +88,8 @@
 class metaclass(type):
     pass
 
-class use_metaclass(object):
-    __metaclass__ = metaclass
+class use_metaclass(object, metaclass=metaclass):
+    pass
 
 # DATA0 .. DATA2 are the pickles we expect under the various protocols, for
 # the object returned by create_data().
@@ -745,7 +745,7 @@
 
     def test_list_chunking(self):
         n = 10  # too small to chunk
-        x = range(n)
+        x = list(range(n))
         for proto in protocols:
             s = self.dumps(x, proto)
             y = self.loads(s)
@@ -754,7 +754,7 @@
             self.assertEqual(num_appends, proto > 0)
 
         n = 2500  # expect at least two chunks when proto > 0
-        x = range(n)
+        x = list(range(n))
         for proto in protocols:
             s = self.dumps(x, proto)
             y = self.loads(s)
@@ -835,6 +835,24 @@
             y = self.loads(s)
             self.assertEqual(y._proto, None)
 
+    def test_reduce_ex_calls_base(self):
+        for proto in 0, 1, 2:
+            x = REX_four()
+            self.assertEqual(x._proto, None)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._proto, proto)
+            y = self.loads(s)
+            self.assertEqual(y._proto, proto)
+
+    def test_reduce_calls_base(self):
+        for proto in 0, 1, 2:
+            x = REX_five()
+            self.assertEqual(x._reduce_called, 0)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._reduce_called, 1)
+            y = self.loads(s)
+            self.assertEqual(y._reduce_called, 1)
+
 # Test classes for reduce_ex
 
 class REX_one(object):
@@ -859,6 +877,20 @@
     def __reduce__(self):
         raise TestFailed, "This __reduce__ shouldn't be called"
 
+class REX_four(object):
+    _proto = None
+    def __reduce_ex__(self, proto):
+        self._proto = proto
+        return object.__reduce_ex__(self, proto)
+    # Calling base class method should succeed
+
+class REX_five(object):
+    _reduce_called = 0
+    def __reduce__(self):
+        self._reduce_called = 1
+        return object.__reduce__(self)
+    # This one used to fail with infinite recursion
+
 # Test classes for newobj
 
 class MyInt(int):
@@ -959,7 +991,7 @@
     def test_persistence(self):
         self.id_count = 0
         self.load_count = 0
-        L = range(10)
+        L = list(range(10))
         self.assertEqual(self.loads(self.dumps(L)), L)
         self.assertEqual(self.id_count, 5)
         self.assertEqual(self.load_count, 5)
@@ -967,7 +999,7 @@
     def test_bin_persistence(self):
         self.id_count = 0
         self.load_count = 0
-        L = range(10)
+        L = list(range(10))
         self.assertEqual(self.loads(self.dumps(L, 1)), L)
         self.assertEqual(self.id_count, 5)
         self.assertEqual(self.load_count, 5)

Modified: python/branches/p3yk-noslice/Lib/test/regrtest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/regrtest.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/regrtest.py	Wed Jul 11 15:40:56 2007
@@ -10,6 +10,7 @@
 
 -v: verbose    -- run tests in verbose mode with output to stdout
 -w: verbose2   -- re-run failed tests in verbose mode
+-d: debug      -- print traceback for failed tests
 -q: quiet      -- don't print anything except if a test fails
 -g: generate   -- write the output file for a test instead of comparing it
 -x: exclude    -- arguments are tests to *exclude*
@@ -106,11 +107,8 @@
     decimal -   Test the decimal module against a large suite that
                 verifies compliance with standards.
 
-    compiler -  Test the compiler package by compiling all the source
-                in the standard library and test suite.  This takes
-                a long time.  Enabling this resource also allows
-                test_tokenize to verify round-trip lexing on every
-                file in the test library.
+    compiler -  Allow test_tokenize to verify round-trip lexing on
+                every file in the test library.
 
     subprocess  Run all tests for the subprocess module.
 
@@ -179,7 +177,7 @@
 def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
          exclude=False, single=False, randomize=False, fromfile=None,
          findleaks=False, use_resources=None, trace=False, coverdir='coverage',
-         runleaks=False, huntrleaks=False, verbose2=False):
+         runleaks=False, huntrleaks=False, verbose2=False, debug=False):
     """Execute a test suite.
 
     This also parses command-line options and modifies its behavior
@@ -204,12 +202,13 @@
 
     test_support.record_original_stdout(sys.stdout)
     try:
-        opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:wM:',
+        opts, args = getopt.getopt(sys.argv[1:], 'dhvgqxsrf:lu:t:TD:NLR:wM:',
                                    ['help', 'verbose', 'quiet', 'generate',
                                     'exclude', 'single', 'random', 'fromfile',
                                     'findleaks', 'use=', 'threshold=', 'trace',
                                     'coverdir=', 'nocoverdir', 'runleaks',
                                     'huntrleaks=', 'verbose2', 'memlimit=',
+                                    'debug',
                                     ])
     except getopt.error as msg:
         usage(2, msg)
@@ -224,6 +223,8 @@
             verbose += 1
         elif o in ('-w', '--verbose2'):
             verbose2 = True
+        elif o in ('-d', '--debug'):
+            debug = True
         elif o in ('-q', '--quiet'):
             quiet = True;
             verbose = 0
@@ -435,7 +436,7 @@
             try:
                 test_support.verbose = 1
                 ok = runtest(test, generate, 1, quiet, testdir,
-                             huntrleaks)
+                             huntrleaks, debug)
             except KeyboardInterrupt:
                 # print a newline separate from the ^C
                 print()
@@ -470,10 +471,13 @@
 STDTESTS = [
     'test_grammar',
     'test_opcodes',
-    'test_operations',
+    'test_dict',
     'test_builtin',
     'test_exceptions',
     'test_types',
+    'test_unittest',
+    'test_doctest',
+    'test_doctest2',
    ]
 
 NOTTESTS = [
@@ -496,7 +500,8 @@
     tests.sort()
     return stdtests + tests
 
-def runtest(test, generate, verbose, quiet, testdir=None, huntrleaks=False):
+def runtest(test, generate, verbose, quiet, testdir=None,
+            huntrleaks=False, debug=False):
     """Run a single test.
 
     test -- the name of the test
@@ -507,6 +512,8 @@
     testdir -- test directory
     huntrleaks -- run multiple times to test for leaks; requires a debug
                   build; a triple corresponding to -R's three arguments
+    debug -- if true, print tracebacks for failed tests regardless of
+             verbose setting
     Return:
         -2  test skipped because resource denied
         -1  test skipped for some other reason
@@ -516,12 +523,12 @@
 
     try:
         return runtest_inner(test, generate, verbose, quiet, testdir,
-                             huntrleaks)
+                             huntrleaks, debug)
     finally:
         cleanup_test_droppings(test, verbose)
 
 def runtest_inner(test, generate, verbose, quiet,
-                     testdir=None, huntrleaks=False):
+                     testdir=None, huntrleaks=False, debug=False):
     test_support.unload(test)
     if not testdir:
         testdir = findtestdir()
@@ -576,7 +583,7 @@
         type, value = sys.exc_info()[:2]
         print("test", test, "crashed --", str(type) + ":", value)
         sys.stdout.flush()
-        if verbose:
+        if verbose or debug:
             traceback.print_exc(file=sys.stdout)
             sys.stdout.flush()
         return 0
@@ -662,7 +669,8 @@
             indirect_test()
     else:
         def run_the_test():
-            reload(the_module)
+            del sys.modules[the_module.__name__]
+            exec('import ' + the_module.__name__)
 
     deltas = []
     nwarmup, ntracked, fname = huntrleaks
@@ -679,16 +687,17 @@
             deltas.append(sys.gettotalrefcount() - rc - 2)
     print(file=sys.stderr)
     if any(deltas):
-        print(test, 'leaked', deltas, 'references', file=sys.stderr)
+        msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas))
+        print(msg, file=sys.stderr)
         refrep = open(fname, "a")
-        print(test, 'leaked', deltas, 'references', file=refrep)
+        print(msg, file=refrep)
         refrep.close()
 
 def dash_R_cleanup(fs, ps, pic):
     import gc, copy_reg
     import _strptime, linecache, dircache
     import urlparse, urllib, urllib2, mimetypes, doctest
-    import struct, filecmp
+    import struct, filecmp, _abcoll
     from distutils.dir_util import _path_created
 
     # Restore some original values.
@@ -698,6 +707,13 @@
     sys.path_importer_cache.clear()
     sys.path_importer_cache.update(pic)
 
+    # Clear ABC registries.
+    for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]:
+        for obj in abc.__subclasses__() + [abc]:
+            obj._ABCMeta__registry.clear()
+            obj._ABCMeta__cache.clear()
+            obj._ABCMeta__negative_cache.clear()
+
     # Clear assorted module caches.
     _path_created.clear()
     re.purge()
@@ -808,11 +824,7 @@
         """
         test__locale
         test_applesingle
-        test_al
-        test_bsddb185
         test_bsddb3
-        test_cd
-        test_cl
         test_commands
         test_crypt
         test_curses
@@ -821,9 +833,7 @@
         test_fcntl
         test_fork1
         test_gdbm
-        test_gl
         test_grp
-        test_imgfile
         test_ioctl
         test_largefile
         test_linuxaudiodev
@@ -839,21 +849,14 @@
         test_signal
         test_sunaudiodev
         test_threadsignals
-        test_timing
         test_wait3
         test_wait4
         """,
     'linux2':
         """
-        test_al
         test_applesingle
-        test_bsddb185
-        test_cd
-        test_cl
         test_curses
         test_dl
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_nis
@@ -865,14 +868,10 @@
         """,
    'mac':
         """
-        test_al
         test_atexit
         test_bsddb
-        test_bsddb185
         test_bsddb3
         test_bz2
-        test_cd
-        test_cl
         test_commands
         test_crypt
         test_curses
@@ -880,10 +879,8 @@
         test_dl
         test_fcntl
         test_fork1
-        test_gl
         test_grp
         test_ioctl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_locale
@@ -894,7 +891,6 @@
         test_ossaudiodev
         test_poll
         test_popen
-        test_popen2
         test_posix
         test_pty
         test_pwd
@@ -905,19 +901,12 @@
         test_sunaudiodev
         test_sundry
         test_tarfile
-        test_timing
         """,
     'unixware7':
         """
-        test_al
         test_applesingle
         test_bsddb
-        test_bsddb185
-        test_cd
-        test_cl
         test_dl
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_minidom
@@ -933,15 +922,9 @@
         """,
     'openunix8':
         """
-        test_al
         test_applesingle
         test_bsddb
-        test_bsddb185
-        test_cd
-        test_cl
         test_dl
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_minidom
@@ -957,18 +940,12 @@
         """,
     'sco_sv3':
         """
-        test_al
         test_applesingle
         test_asynchat
         test_bsddb
-        test_bsddb185
-        test_cd
-        test_cl
         test_dl
         test_fork1
         test_gettext
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_locale
@@ -990,15 +967,11 @@
         """,
     'riscos':
         """
-        test_al
         test_applesingle
         test_asynchat
         test_atexit
         test_bsddb
-        test_bsddb185
         test_bsddb3
-        test_cd
-        test_cl
         test_commands
         test_crypt
         test_dbm
@@ -1006,9 +979,7 @@
         test_fcntl
         test_fork1
         test_gdbm
-        test_gl
         test_grp
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_locale
@@ -1017,10 +988,8 @@
         test_ntpath
         test_openpty
         test_poll
-        test_popen2
         test_pty
         test_pwd
-        test_strop
         test_sqlite
         test_startfile
         test_sunaudiodev
@@ -1029,16 +998,10 @@
         test_threaded_import
         test_threadedtempfile
         test_threading
-        test_timing
         """,
     'darwin':
         """
-        test_al
-        test_cd
-        test_cl
         test_gdbm
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_locale
@@ -1049,18 +1012,12 @@
         """,
     'sunos5':
         """
-        test_al
         test_applesingle
         test_bsddb
-        test_bsddb185
-        test_cd
-        test_cl
         test_curses
         test_dbm
         test_gdbm
-        test_gl
         test_gzip
-        test_imgfile
         test_linuxaudiodev
         test_openpty
         test_sqlite
@@ -1070,18 +1027,12 @@
         """,
     'hp-ux11':
         """
-        test_al
         test_applesingle
         test_bsddb
-        test_bsddb185
-        test_cd
-        test_cl
         test_curses
         test_dl
         test_gdbm
-        test_gl
         test_gzip
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_locale
@@ -1099,16 +1050,10 @@
         """,
     'atheos':
         """
-        test_al
         test_applesingle
-        test_bsddb185
-        test_cd
-        test_cl
         test_curses
         test_dl
         test_gdbm
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_locale
@@ -1116,7 +1061,6 @@
         test_mmap
         test_nis
         test_poll
-        test_popen2
         test_resource
         test_sqlite
         test_startfile
@@ -1124,16 +1068,10 @@
         """,
     'cygwin':
         """
-        test_al
         test_applesingle
-        test_bsddb185
         test_bsddb3
-        test_cd
-        test_cl
         test_curses
         test_dbm
-        test_gl
-        test_imgfile
         test_ioctl
         test_largefile
         test_linuxaudiodev
@@ -1146,18 +1084,12 @@
         """,
     'os2emx':
         """
-        test_al
         test_applesingle
         test_audioop
-        test_bsddb185
         test_bsddb3
-        test_cd
-        test_cl
         test_commands
         test_curses
         test_dl
-        test_gl
-        test_imgfile
         test_largefile
         test_linuxaudiodev
         test_mhlib
@@ -1175,18 +1107,12 @@
     'freebsd4':
         """
         test_aepack
-        test_al
         test_applesingle
         test_bsddb
         test_bsddb3
-        test_cd
-        test_cl
         test_gdbm
-        test_gl
-        test_imgfile
         test_linuxaudiodev
         test_locale
-        test_macfs
         test_macostools
         test_nis
         test_ossaudiodev
@@ -1209,21 +1135,14 @@
     'aix5':
         """
         test_aepack
-        test_al
         test_applesingle
         test_bsddb
-        test_bsddb185
         test_bsddb3
         test_bz2
-        test_cd
-        test_cl
         test_dl
         test_gdbm
-        test_gl
         test_gzip
-        test_imgfile
         test_linuxaudiodev
-        test_macfs
         test_macostools
         test_nis
         test_ossaudiodev
@@ -1239,20 +1158,14 @@
     'openbsd3':
         """
         test_aepack
-        test_al
         test_applesingle
         test_bsddb
         test_bsddb3
-        test_cd
-        test_cl
         test_ctypes
         test_dl
         test_gdbm
-        test_gl
-        test_imgfile
         test_linuxaudiodev
         test_locale
-        test_macfs
         test_macostools
         test_nis
         test_normalization
@@ -1271,22 +1184,15 @@
     'netbsd3':
         """
         test_aepack
-        test_al
         test_applesingle
         test_bsddb
-        test_bsddb185
         test_bsddb3
-        test_cd
-        test_cl
         test_ctypes
         test_curses
         test_dl
         test_gdbm
-        test_gl
-        test_imgfile
         test_linuxaudiodev
         test_locale
-        test_macfs
         test_macostools
         test_nis
         test_ossaudiodev
@@ -1324,12 +1230,8 @@
             if test_timeout.skip_expected:
                 self.expected.add('test_timeout')
 
-            if sys.maxint == 9223372036854775807:
-                self.expected.add('test_rgbimg')
-                self.expected.add('test_imageop')
-
             if not sys.platform in ("mac", "darwin"):
-                MAC_ONLY = ["test_macostools", "test_macfs", "test_aepack",
+                MAC_ONLY = ["test_macostools", "test_aepack",
                             "test_plistlib", "test_scriptpackages"]
                 for skip in MAC_ONLY:
                     self.expected.add(skip)
@@ -1340,6 +1242,11 @@
                 for skip in WIN_ONLY:
                     self.expected.add(skip)
 
+            if sys.platform != 'irix':
+                IRIX_ONLY =["test_imageop"]
+                for skip in IRIX_ONLY:
+                    self.expected.add(skip)
+
             self.valid = True
 
     def isvalid(self):

Modified: python/branches/p3yk-noslice/Lib/test/seq_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/seq_tests.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/seq_tests.py	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
@@ -46,14 +46,14 @@
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
         return v
 
 class IterNoNext:
-    'Iterator missing next()'
+    'Iterator missing __next__()'
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
@@ -67,7 +67,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         3 // 0
 
 class IterFuncStop:
@@ -76,7 +76,7 @@
         pass
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         raise StopIteration
 
 from itertools import chain, imap
@@ -120,7 +120,7 @@
         self.assertEqual(len(vv), len(s))
 
         # Create from various iteratables
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (Sequence, IterFunc, IterGen,
                       itermulti, iterfunc):
                 self.assertEqual(self.type2test(g(s)), self.type2test(s))
@@ -136,10 +136,10 @@
 
     def test_getitem(self):
         u = self.type2test([0, 1, 2, 3, 4])
-        for i in xrange(len(u)):
+        for i in range(len(u)):
             self.assertEqual(u[i], i)
             self.assertEqual(u[int(i)], i)
-        for i in xrange(-len(u), -1):
+        for i in range(-len(u), -1):
             self.assertEqual(u[i], len(u)+i)
             self.assertEqual(u[int(i)], len(u)+i)
         self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
@@ -294,12 +294,12 @@
         class T(self.type2test):
             def __getitem__(self, key):
                 return str(key) + '!!!'
-        self.assertEqual(iter(T((1,2))).next(), 1)
+        self.assertEqual(next(iter(T((1,2)))), 1)
 
     def test_repeat(self):
-        for m in xrange(4):
+        for m in range(4):
             s = tuple(range(m))
-            for n in xrange(-3, 5):
+            for n in range(-3, 5):
                 self.assertEqual(self.type2test(s*n), self.type2test(s)*n)
             self.assertEqual(self.type2test(s)*(-4), self.type2test([]))
             self.assertEqual(id(s), id(s*1))

Modified: python/branches/p3yk-noslice/Lib/test/sortperf.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/sortperf.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/sortperf.py	Wed Jul 11 15:40:56 2007
@@ -24,7 +24,7 @@
         fp = open(fn, "rb")
     except IOError:
         r = random.random
-        result = [r() for i in xrange(n)]
+        result = [r() for i in range(n)]
         try:
             try:
                 fp = open(fn, "wb")
@@ -108,7 +108,7 @@
         doit(L) # +sort
 
         # Replace 1% of the elements at random.
-        for dummy in xrange(n // 100):
+        for dummy in range(n // 100):
             L[random.randrange(n)] = random.random()
         doit(L) # %sort
 

Modified: python/branches/p3yk-noslice/Lib/test/string_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/string_tests.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/string_tests.py	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 Common tests shared by test_str, test_unicode, test_userstring and test_string.
 """
 
-import unittest, string, sys
+import unittest, string, sys, struct
 from test import test_support
 from UserList import UserList
 
@@ -18,10 +18,10 @@
     def __init__(self): self.seq = ['a', 'b', 'c']
     def __len__(self): return 8
 
-class CommonTest(unittest.TestCase):
-    # This testcase contains test that can be used in all
-    # stringlike classes. Currently this is str, unicode
-    # UserString and the string module.
+class BaseTest(unittest.TestCase):
+    # These tests are for buffers of values (bytes) and not
+    # specific to character interpretation, used for bytes objects
+    # and various string implementations
 
     # The type to be tested
     # Change in subclasses to change the behaviour of fixtesttype()
@@ -80,24 +80,6 @@
         args = self.fixtype(args)
         getattr(object, methodname)(*args)
 
-    def test_hash(self):
-        # SF bug 1054139:  += optimization was not invalidating cached hash value
-        a = self.type2test('DNSSEC')
-        b = self.type2test('')
-        for c in a:
-            b += c
-            hash(b)
-        self.assertEqual(hash(a), hash(b))
-
-    def test_capitalize(self):
-        self.checkequal(' hello ', ' hello ', 'capitalize')
-        self.checkequal('Hello ', 'Hello ','capitalize')
-        self.checkequal('Hello ', 'hello ','capitalize')
-        self.checkequal('Aaaa', 'aaaa', 'capitalize')
-        self.checkequal('Aaaa', 'AaAa', 'capitalize')
-
-        self.checkraises(TypeError, 'hello', 'capitalize', 42)
-
     def test_count(self):
         self.checkequal(3, 'aaa', 'count', 'a')
         self.checkequal(0, 'aaa', 'count', 'b')
@@ -130,9 +112,9 @@
         digits = 7
         base = len(charset)
         teststrings = set()
-        for i in xrange(base ** digits):
+        for i in range(base ** digits):
             entry = []
-            for j in xrange(digits):
+            for j in range(digits):
                 i, m = divmod(i, base)
                 entry.append(charset[m])
             teststrings.add(''.join(entry))
@@ -169,9 +151,9 @@
         digits = 5
         base = len(charset)
         teststrings = set()
-        for i in xrange(base ** digits):
+        for i in range(base ** digits):
             entry = []
-            for j in xrange(digits):
+            for j in range(digits):
                 i, m = divmod(i, base)
                 entry.append(charset[m])
             teststrings.add(''.join(entry))
@@ -247,37 +229,15 @@
         self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
         self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
         self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
+        self.checkequal('  a\n b', ' \ta\n\tb', 'expandtabs', 1)
 
         self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
+        # This test is only valid when sizeof(int) == sizeof(void*) == 4.
+        if sys.maxint < (1 << 32) and struct.calcsize('P') == 4:
+            self.checkraises(OverflowError,
+                             '\ta\n\tb', 'expandtabs', sys.maxint)
 
     def test_split(self):
-        self.checkequal(['this', 'is', 'the', 'split', 'function'],
-            'this is the split function', 'split')
-
-        # by whitespace
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
-        self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
-        self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
-                        sys.maxint-1)
-        self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
-        self.checkequal(['a b c d'], '  a b c d', 'split', None, 0)
-        self.checkequal(['a', 'b', 'c  d'], 'a  b  c  d', 'split', None, 2)
-
-        self.checkequal([], '         ', 'split')
-        self.checkequal(['a'], '  a    ', 'split')
-        self.checkequal(['a', 'b'], '  a    b   ', 'split')
-        self.checkequal(['a', 'b   '], '  a    b   ', 'split', None, 1)
-        self.checkequal(['a', 'b   c   '], '  a    b   c   ', 'split', None, 1)
-        self.checkequal(['a', 'b', 'c   '], '  a    b   c   ', 'split', None, 2)
-        self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
-        aaa = ' a '*20
-        self.checkequal(['a']*20, aaa, 'split')
-        self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
-        self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
-
         # by a char
         self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
         self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
@@ -327,9 +287,6 @@
         self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
                         'split', 'BLAH', 18)
 
-        # mixed use of str and unicode
-        self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
-
         # argument type
         self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
 
@@ -338,36 +295,6 @@
         self.checkraises(ValueError, 'hello', 'split', '', 0)
 
     def test_rsplit(self):
-        self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
-                         'this is the rsplit function', 'rsplit')
-
-        # by whitespace
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
-        self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
-        self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
-        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
-                        sys.maxint-20)
-        self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
-        self.checkequal(['a b c d'], 'a b c d  ', 'rsplit', None, 0)
-        self.checkequal(['a  b', 'c', 'd'], 'a  b  c  d', 'rsplit', None, 2)
-
-        self.checkequal([], '         ', 'rsplit')
-        self.checkequal(['a'], '  a    ', 'rsplit')
-        self.checkequal(['a', 'b'], '  a    b   ', 'rsplit')
-        self.checkequal(['  a', 'b'], '  a    b   ', 'rsplit', None, 1)
-        self.checkequal(['  a    b','c'], '  a    b   c   ', 'rsplit',
-                        None, 1)
-        self.checkequal(['  a', 'b', 'c'], '  a    b   c   ', 'rsplit',
-                        None, 2)
-        self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
-        aaa = ' a '*20
-        self.checkequal(['a']*20, aaa, 'rsplit')
-        self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
-        self.checkequal([' a  a'] + ['a']*18, aaa, 'rsplit', None, 18)
-
-
         # by a char
         self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
         self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
@@ -417,9 +344,6 @@
         self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
                         'rsplit', 'BLAH', 18)
 
-        # mixed use of str and unicode
-        self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
-
         # argument type
         self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
 
@@ -427,68 +351,6 @@
         self.checkraises(ValueError, 'hello', 'rsplit', '')
         self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
 
-    def test_strip(self):
-        self.checkequal('hello', '   hello   ', 'strip')
-        self.checkequal('hello   ', '   hello   ', 'lstrip')
-        self.checkequal('   hello', '   hello   ', 'rstrip')
-        self.checkequal('hello', 'hello', 'strip')
-
-        # strip/lstrip/rstrip with None arg
-        self.checkequal('hello', '   hello   ', 'strip', None)
-        self.checkequal('hello   ', '   hello   ', 'lstrip', None)
-        self.checkequal('   hello', '   hello   ', 'rstrip', None)
-        self.checkequal('hello', 'hello', 'strip', None)
-
-        # strip/lstrip/rstrip with str arg
-        self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
-        self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
-        self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
-        self.checkequal('hello', 'hello', 'strip', 'xyz')
-
-        # strip/lstrip/rstrip with unicode arg
-        if test_support.have_unicode:
-            self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
-                 'strip', unicode('xyz', 'ascii'))
-            self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
-                 'lstrip', unicode('xyz', 'ascii'))
-            self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
-                 'rstrip', unicode('xyz', 'ascii'))
-            self.checkequal(unicode('hello', 'ascii'), 'hello',
-                 'strip', unicode('xyz', 'ascii'))
-
-        self.checkraises(TypeError, 'hello', 'strip', 42, 42)
-        self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
-        self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
-
-    def test_ljust(self):
-        self.checkequal('abc       ', 'abc', 'ljust', 10)
-        self.checkequal('abc   ', 'abc', 'ljust', 6)
-        self.checkequal('abc', 'abc', 'ljust', 3)
-        self.checkequal('abc', 'abc', 'ljust', 2)
-        self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
-        self.checkraises(TypeError, 'abc', 'ljust')
-
-    def test_rjust(self):
-        self.checkequal('       abc', 'abc', 'rjust', 10)
-        self.checkequal('   abc', 'abc', 'rjust', 6)
-        self.checkequal('abc', 'abc', 'rjust', 3)
-        self.checkequal('abc', 'abc', 'rjust', 2)
-        self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
-        self.checkraises(TypeError, 'abc', 'rjust')
-
-    def test_center(self):
-        self.checkequal('   abc    ', 'abc', 'center', 10)
-        self.checkequal(' abc  ', 'abc', 'center', 6)
-        self.checkequal('abc', 'abc', 'center', 3)
-        self.checkequal('abc', 'abc', 'center', 2)
-        self.checkequal('***abc****', 'abc', 'center', 10, '*')
-        self.checkraises(TypeError, 'abc', 'center')
-
-    def test_swapcase(self):
-        self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
-
-        self.checkraises(TypeError, 'hello', 'swapcase', 42)
-
     def test_replace(self):
         EQ = self.checkequal
 
@@ -671,13 +533,185 @@
 
     def test_replace_overflow(self):
         # Check for overflow checking on 32 bit machines
-        if sys.maxint != 2147483647:
+        if sys.maxint != 2147483647 or struct.calcsize("P") > 4:
             return
         A2_16 = "A" * (2**16)
         self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
         self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
         self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
 
+
+
+class CommonTest(BaseTest):
+    # This testcase contains test that can be used in all
+    # stringlike classes. Currently this is str, unicode
+    # UserString and the string module.
+
+    def test_hash(self):
+        # SF bug 1054139:  += optimization was not invalidating cached hash value
+        a = self.type2test('DNSSEC')
+        b = self.type2test('')
+        for c in a:
+            b += c
+            hash(b)
+        self.assertEqual(hash(a), hash(b))
+
+    def test_capitalize(self):
+        self.checkequal(' hello ', ' hello ', 'capitalize')
+        self.checkequal('Hello ', 'Hello ','capitalize')
+        self.checkequal('Hello ', 'hello ','capitalize')
+        self.checkequal('Aaaa', 'aaaa', 'capitalize')
+        self.checkequal('Aaaa', 'AaAa', 'capitalize')
+
+        self.checkraises(TypeError, 'hello', 'capitalize', 42)
+
+    def test_lower(self):
+        self.checkequal('hello', 'HeLLo', 'lower')
+        self.checkequal('hello', 'hello', 'lower')
+        self.checkraises(TypeError, 'hello', 'lower', 42)
+
+    def test_upper(self):
+        self.checkequal('HELLO', 'HeLLo', 'upper')
+        self.checkequal('HELLO', 'HELLO', 'upper')
+        self.checkraises(TypeError, 'hello', 'upper', 42)
+
+    def test_expandtabs(self):
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
+        self.checkequal('abc\rab  def\ng   hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
+        self.checkequal('abc\r\nab  def\ng   hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
+        self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
+
+        self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
+
+    def test_additional_split(self):
+        self.checkequal(['this', 'is', 'the', 'split', 'function'],
+            'this is the split function', 'split')
+
+        # by whitespace
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
+        self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
+        self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
+                        sys.maxint-1)
+        self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
+        self.checkequal(['a b c d'], '  a b c d', 'split', None, 0)
+        self.checkequal(['a', 'b', 'c  d'], 'a  b  c  d', 'split', None, 2)
+
+        self.checkequal([], '         ', 'split')
+        self.checkequal(['a'], '  a    ', 'split')
+        self.checkequal(['a', 'b'], '  a    b   ', 'split')
+        self.checkequal(['a', 'b   '], '  a    b   ', 'split', None, 1)
+        self.checkequal(['a', 'b   c   '], '  a    b   c   ', 'split', None, 1)
+        self.checkequal(['a', 'b', 'c   '], '  a    b   c   ', 'split', None, 2)
+        self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
+        aaa = ' a '*20
+        self.checkequal(['a']*20, aaa, 'split')
+        self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
+        self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
+
+        # mixed use of str and unicode
+        self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
+
+    def test_additional_rsplit(self):
+        self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
+                         'this is the rsplit function', 'rsplit')
+
+        # by whitespace
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
+        self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
+        self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
+                        sys.maxint-20)
+        self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
+        self.checkequal(['a b c d'], 'a b c d  ', 'rsplit', None, 0)
+        self.checkequal(['a  b', 'c', 'd'], 'a  b  c  d', 'rsplit', None, 2)
+
+        self.checkequal([], '         ', 'rsplit')
+        self.checkequal(['a'], '  a    ', 'rsplit')
+        self.checkequal(['a', 'b'], '  a    b   ', 'rsplit')
+        self.checkequal(['  a', 'b'], '  a    b   ', 'rsplit', None, 1)
+        self.checkequal(['  a    b','c'], '  a    b   c   ', 'rsplit',
+                        None, 1)
+        self.checkequal(['  a', 'b', 'c'], '  a    b   c   ', 'rsplit',
+                        None, 2)
+        self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
+        aaa = ' a '*20
+        self.checkequal(['a']*20, aaa, 'rsplit')
+        self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
+        self.checkequal([' a  a'] + ['a']*18, aaa, 'rsplit', None, 18)
+
+        # mixed use of str and unicode
+        self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
+
+    def test_strip(self):
+        self.checkequal('hello', '   hello   ', 'strip')
+        self.checkequal('hello   ', '   hello   ', 'lstrip')
+        self.checkequal('   hello', '   hello   ', 'rstrip')
+        self.checkequal('hello', 'hello', 'strip')
+
+        # strip/lstrip/rstrip with None arg
+        self.checkequal('hello', '   hello   ', 'strip', None)
+        self.checkequal('hello   ', '   hello   ', 'lstrip', None)
+        self.checkequal('   hello', '   hello   ', 'rstrip', None)
+        self.checkequal('hello', 'hello', 'strip', None)
+
+        # strip/lstrip/rstrip with str arg
+        self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
+        self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
+        self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
+        self.checkequal('hello', 'hello', 'strip', 'xyz')
+
+        # strip/lstrip/rstrip with unicode arg
+        if test_support.have_unicode:
+            self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
+                 'strip', unicode('xyz', 'ascii'))
+            self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
+                 'lstrip', unicode('xyz', 'ascii'))
+            self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
+                 'rstrip', unicode('xyz', 'ascii'))
+            self.checkequal(unicode('hello', 'ascii'), 'hello',
+                 'strip', unicode('xyz', 'ascii'))
+
+        self.checkraises(TypeError, 'hello', 'strip', 42, 42)
+        self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
+        self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
+
+    def test_ljust(self):
+        self.checkequal('abc       ', 'abc', 'ljust', 10)
+        self.checkequal('abc   ', 'abc', 'ljust', 6)
+        self.checkequal('abc', 'abc', 'ljust', 3)
+        self.checkequal('abc', 'abc', 'ljust', 2)
+        self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
+        self.checkraises(TypeError, 'abc', 'ljust')
+
+    def test_rjust(self):
+        self.checkequal('       abc', 'abc', 'rjust', 10)
+        self.checkequal('   abc', 'abc', 'rjust', 6)
+        self.checkequal('abc', 'abc', 'rjust', 3)
+        self.checkequal('abc', 'abc', 'rjust', 2)
+        self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
+        self.checkraises(TypeError, 'abc', 'rjust')
+
+    def test_center(self):
+        self.checkequal('   abc    ', 'abc', 'center', 10)
+        self.checkequal(' abc  ', 'abc', 'center', 6)
+        self.checkequal('abc', 'abc', 'center', 3)
+        self.checkequal('abc', 'abc', 'center', 2)
+        self.checkequal('***abc****', 'abc', 'center', 10, '*')
+        self.checkraises(TypeError, 'abc', 'center')
+
+    def test_swapcase(self):
+        self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
+
+        self.checkraises(TypeError, 'hello', 'swapcase', 42)
+
     def test_zfill(self):
         self.checkequal('123', '123', 'zfill', 2)
         self.checkequal('123', '123', 'zfill', 3)
@@ -921,7 +955,7 @@
                     L = list(s)[start:stop:step]
                     self.checkequal(u"".join(L), s, '__getitem__',
                                     slice(start, stop, step))
-        
+
     def test_mul(self):
         self.checkequal('', 'abc', '__mul__', -1)
         self.checkequal('', 'abc', '__mul__', 0)
@@ -1010,10 +1044,10 @@
 
     def test_floatformatting(self):
         # float formatting
-        for prec in xrange(100):
+        for prec in range(100):
             format = '%%.%if' % prec
             value = 0.01
-            for x in xrange(60):
+            for x in range(60):
                 value = value * 3.141592655 / 3.0 * 10.0
                 # The formatfloat() code in stringobject.c and
                 # unicodeobject.c uses a 120 byte buffer and switches from
@@ -1080,7 +1114,7 @@
 
     def test_maketrans(self):
         self.assertEqual(
-           ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
+           ''.join(map(chr, range(256))).replace('abc', 'xyz'),
            string.maketrans('abc', 'xyz')
         )
         self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
@@ -1093,6 +1127,9 @@
         self.checkequal('Abc', 'abc', 'translate', table)
         self.checkequal('xyz', 'xyz', 'translate', table)
         self.checkequal('yz', 'xyz', 'translate', table, 'x')
+        self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
+        self.checkequal('zyzzx', 'zyzzx', 'translate', None, '')
+        self.checkequal('zyzzx', 'zyzzx', 'translate', None)
         self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
         self.checkraises(ValueError, 'xyz', 'translate', 'too short')
 

Deleted: /python/branches/p3yk-noslice/Lib/test/test_MimeWriter.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_MimeWriter.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,291 +0,0 @@
-"""Test program for MimeWriter module.
-
-The test program was too big to comfortably fit in the MimeWriter
-class, so it's here in its own file.
-
-This should generate Barry's example, modulo some quotes and newlines.
-
-"""
-
-import unittest, sys, StringIO
-from test.test_support import run_unittest
-
-from MimeWriter import MimeWriter
-
-SELLER = '''\
-INTERFACE Seller-1;
-
-TYPE Seller = OBJECT
-    DOCUMENTATION "A simple Seller interface to test ILU"
-    METHODS
-            price():INTEGER,
-    END;
-'''
-
-BUYER = '''\
-class Buyer:
-    def __setup__(self, maxprice):
-        self._maxprice = maxprice
-
-    def __main__(self, kos):
-        """Entry point upon arrival at a new KOS."""
-        broker = kos.broker()
-        # B4 == Barry's Big Bass Business :-)
-        seller = broker.lookup('Seller_1.Seller', 'B4')
-        if seller:
-            price = seller.price()
-            print 'Seller wants $', price, '... '
-            if price > self._maxprice:
-                print 'too much!'
-            else:
-                print "I'll take it!"
-        else:
-            print 'no seller found here'
-'''                                     # Don't ask why this comment is here
-
-STATE = '''\
-# instantiate a buyer instance and put it in a magic place for the KOS
-# to find.
-__kp__ = Buyer()
-__kp__.__setup__(500)
-'''
-
-SIMPLE_METADATA = [
-        ("Interpreter", "python"),
-        ("Interpreter-Version", "1.3"),
-        ("Owner-Name", "Barry Warsaw"),
-        ("Owner-Rendezvous", "bwarsaw at cnri.reston.va.us"),
-        ("Home-KSS", "kss.cnri.reston.va.us"),
-        ("Identifier", "hdl://cnri.kss/my_first_knowbot"),
-        ("Launch-Date", "Mon Feb 12 16:39:03 EST 1996"),
-        ]
-
-COMPLEX_METADATA = [
-        ("Metadata-Type", "complex"),
-        ("Metadata-Key", "connection"),
-        ("Access", "read-only"),
-        ("Connection-Description", "Barry's Big Bass Business"),
-        ("Connection-Id", "B4"),
-        ("Connection-Direction", "client"),
-        ]
-
-EXTERNAL_METADATA = [
-        ("Metadata-Type", "complex"),
-        ("Metadata-Key", "generic-interface"),
-        ("Access", "read-only"),
-        ("Connection-Description", "Generic Interface for All Knowbots"),
-        ("Connection-Id", "generic-kp"),
-        ("Connection-Direction", "client"),
-        ]
-
-
-OUTPUT = '''\
-From: bwarsaw at cnri.reston.va.us
-Date: Mon Feb 12 17:21:48 EST 1996
-To: kss-submit at cnri.reston.va.us
-MIME-Version: 1.0
-Content-Type: multipart/knowbot;
-    boundary="801spam999";
-    version="0.1"
-
-This is a multi-part message in MIME format.
-
---801spam999
-Content-Type: multipart/knowbot-metadata;
-    boundary="802spam999"
-
-
---802spam999
-Content-Type: message/rfc822
-KP-Metadata-Type: simple
-KP-Access: read-only
-
-KPMD-Interpreter: python
-KPMD-Interpreter-Version: 1.3
-KPMD-Owner-Name: Barry Warsaw
-KPMD-Owner-Rendezvous: bwarsaw at cnri.reston.va.us
-KPMD-Home-KSS: kss.cnri.reston.va.us
-KPMD-Identifier: hdl://cnri.kss/my_first_knowbot
-KPMD-Launch-Date: Mon Feb 12 16:39:03 EST 1996
-
---802spam999
-Content-Type: text/isl
-KP-Metadata-Type: complex
-KP-Metadata-Key: connection
-KP-Access: read-only
-KP-Connection-Description: Barry's Big Bass Business
-KP-Connection-Id: B4
-KP-Connection-Direction: client
-
-INTERFACE Seller-1;
-
-TYPE Seller = OBJECT
-    DOCUMENTATION "A simple Seller interface to test ILU"
-    METHODS
-            price():INTEGER,
-    END;
-
---802spam999
-Content-Type: message/external-body;
-    access-type="URL";
-    URL="hdl://cnri.kss/generic-knowbot"
-
-Content-Type: text/isl
-KP-Metadata-Type: complex
-KP-Metadata-Key: generic-interface
-KP-Access: read-only
-KP-Connection-Description: Generic Interface for All Knowbots
-KP-Connection-Id: generic-kp
-KP-Connection-Direction: client
-
-
---802spam999--
-
---801spam999
-Content-Type: multipart/knowbot-code;
-    boundary="803spam999"
-
-
---803spam999
-Content-Type: text/plain
-KP-Module-Name: BuyerKP
-
-class Buyer:
-    def __setup__(self, maxprice):
-        self._maxprice = maxprice
-
-    def __main__(self, kos):
-        """Entry point upon arrival at a new KOS."""
-        broker = kos.broker()
-        # B4 == Barry's Big Bass Business :-)
-        seller = broker.lookup('Seller_1.Seller', 'B4')
-        if seller:
-            price = seller.price()
-            print 'Seller wants $', price, '... '
-            if price > self._maxprice:
-                print 'too much!'
-            else:
-                print "I'll take it!"
-        else:
-            print 'no seller found here'
-
---803spam999--
-
---801spam999
-Content-Type: multipart/knowbot-state;
-    boundary="804spam999"
-KP-Main-Module: main
-
-
---804spam999
-Content-Type: text/plain
-KP-Module-Name: main
-
-# instantiate a buyer instance and put it in a magic place for the KOS
-# to find.
-__kp__ = Buyer()
-__kp__.__setup__(500)
-
---804spam999--
-
---801spam999--
-'''
-
-class MimewriterTest(unittest.TestCase):
-
-    def test(self):
-        buf = StringIO.StringIO()
-
-        # Toplevel headers
-
-        toplevel = MimeWriter(buf)
-        toplevel.addheader("From", "bwarsaw at cnri.reston.va.us")
-        toplevel.addheader("Date", "Mon Feb 12 17:21:48 EST 1996")
-        toplevel.addheader("To", "kss-submit at cnri.reston.va.us")
-        toplevel.addheader("MIME-Version", "1.0")
-
-        # Toplevel body parts
-
-        f = toplevel.startmultipartbody("knowbot", "801spam999",
-                                        [("version", "0.1")], prefix=0)
-        f.write("This is a multi-part message in MIME format.\n")
-
-        # First toplevel body part: metadata
-
-        md = toplevel.nextpart()
-        md.startmultipartbody("knowbot-metadata", "802spam999")
-
-        # Metadata part 1
-
-        md1 = md.nextpart()
-        md1.addheader("KP-Metadata-Type", "simple")
-        md1.addheader("KP-Access", "read-only")
-        m = MimeWriter(md1.startbody("message/rfc822"))
-        for key, value in SIMPLE_METADATA:
-            m.addheader("KPMD-" + key, value)
-        m.flushheaders()
-        del md1
-
-        # Metadata part 2
-
-        md2 = md.nextpart()
-        for key, value in COMPLEX_METADATA:
-            md2.addheader("KP-" + key, value)
-        f = md2.startbody("text/isl")
-        f.write(SELLER)
-        del md2
-
-        # Metadata part 3
-
-        md3 = md.nextpart()
-        f = md3.startbody("message/external-body",
-                          [("access-type", "URL"),
-                           ("URL", "hdl://cnri.kss/generic-knowbot")])
-        m = MimeWriter(f)
-        for key, value in EXTERNAL_METADATA:
-            md3.addheader("KP-" + key, value)
-        md3.startbody("text/isl")
-        # Phantom body doesn't need to be written
-
-        md.lastpart()
-
-        # Second toplevel body part: code
-
-        code = toplevel.nextpart()
-        code.startmultipartbody("knowbot-code", "803spam999")
-
-        # Code: buyer program source
-
-        buyer = code.nextpart()
-        buyer.addheader("KP-Module-Name", "BuyerKP")
-        f = buyer.startbody("text/plain")
-        f.write(BUYER)
-
-        code.lastpart()
-
-        # Third toplevel body part: state
-
-        state = toplevel.nextpart()
-        state.addheader("KP-Main-Module", "main")
-        state.startmultipartbody("knowbot-state", "804spam999")
-
-        # State: a bunch of assignments
-
-        st = state.nextpart()
-        st.addheader("KP-Module-Name", "main")
-        f = st.startbody("text/plain")
-        f.write(STATE)
-
-        state.lastpart()
-
-        # End toplevel body parts
-
-        toplevel.lastpart()
-
-        self.assertEqual(buf.getvalue(), OUTPUT)
-
-def test_main():
-    run_unittest(MimewriterTest)
-
-if __name__ == '__main__':
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_StringIO.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_StringIO.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_StringIO.py	Wed Jul 11 15:40:56 2007
@@ -89,14 +89,14 @@
         eq(iter(self._fp), self._fp)
         # Does this object support the iteration protocol?
         unless(hasattr(self._fp, '__iter__'))
-        unless(hasattr(self._fp, 'next'))
+        unless(hasattr(self._fp, '__next__'))
         i = 0
         for line in self._fp:
             eq(line, self._line + '\n')
             i += 1
         eq(i, 5)
         self._fp.close()
-        self.assertRaises(ValueError, self._fp.next)
+        self.assertRaises(ValueError, next, self._fp)
 
 class TestStringIO(TestGenericStringIO):
     MODULE = StringIO

Modified: python/branches/p3yk-noslice/Lib/test/test___all__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test___all__.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test___all__.py	Wed Jul 11 15:40:56 2007
@@ -1,14 +1,7 @@
 import unittest
-from test import test_support
-
-from test.test_support import verify, verbose
+from test.test_support import verbose, run_unittest
 import sys
-import warnings
 
-warnings.filterwarnings("ignore",
-                        "the gopherlib module is deprecated",
-                        DeprecationWarning,
-                        "<string>")
 
 class AllTest(unittest.TestCase):
 
@@ -20,15 +13,15 @@
             # Silent fail here seems the best route since some modules
             # may not be available in all environments.
             return
-        verify(hasattr(sys.modules[modname], "__all__"),
-               "%s has no __all__ attribute" % modname)
+        self.failUnless(hasattr(sys.modules[modname], "__all__"),
+                        "%s has no __all__ attribute" % modname)
         names = {}
         exec("from %s import *" % modname, names)
         if "__builtins__" in names:
             del names["__builtins__"]
         keys = set(names)
         all = set(sys.modules[modname].__all__)
-        verify(keys==all, "%s != %s" % (keys, all))
+        self.assertEqual(keys, all)
 
     def test_all(self):
         if not sys.platform.startswith('java'):
@@ -37,18 +30,15 @@
             import _socket
 
         self.check_all("BaseHTTPServer")
-        self.check_all("Bastion")
         self.check_all("CGIHTTPServer")
         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("StringIO")
         self.check_all("UserString")
         self.check_all("aifc")
-        self.check_all("atexit")
         self.check_all("audiodev")
         self.check_all("base64")
         self.check_all("bdb")
@@ -82,7 +72,6 @@
         self.check_all("getpass")
         self.check_all("gettext")
         self.check_all("glob")
-        self.check_all("gopherlib")
         self.check_all("gzip")
         self.check_all("heapq")
         self.check_all("htmllib")
@@ -101,7 +90,6 @@
         self.check_all("mhlib")
         self.check_all("mimetools")
         self.check_all("mimetypes")
-        self.check_all("mimify")
         self.check_all("multifile")
         self.check_all("netrc")
         self.check_all("nntplib")
@@ -114,7 +102,6 @@
         self.check_all("pickle")
         self.check_all("pickletools")
         self.check_all("pipes")
-        self.check_all("popen2")
         self.check_all("poplib")
         self.check_all("posixpath")
         self.check_all("pprint")
@@ -127,7 +114,6 @@
         self.check_all("random")
         self.check_all("re")
         self.check_all("repr")
-        self.check_all("rexec")
         self.check_all("rfc822")
         self.check_all("rlcompleter")
         self.check_all("robotparser")
@@ -178,7 +164,7 @@
 
 
 def test_main():
-    test_support.run_unittest(AllTest)
+    run_unittest(AllTest)
 
 if __name__ == "__main__":
     test_main()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_al.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_al.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,23 +0,0 @@
-#! /usr/bin/env python
-"""Whimpy test script for the al module
-   Roger E. Masse
-"""
-import al
-from test.test_support import verbose
-
-alattrs = ['__doc__', '__name__', 'getdefault', 'getminmax', 'getname', 'getparams',
-           'newconfig', 'openport', 'queryparams', 'setparams']
-
-# This is a very unobtrusive test for the existence of the al module and all its
-# attributes.  More comprehensive examples can be found in Demo/al
-
-def main():
-    # touch all the attributes of al without doing anything
-    if verbose:
-        print('Touching al module attributes...')
-    for attr in alattrs:
-        if verbose:
-            print('touching: ', attr)
-        getattr(al, attr)
-
-main()

Modified: python/branches/p3yk-noslice/Lib/test/test_anydbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_anydbm.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_anydbm.py	Wed Jul 11 15:40:56 2007
@@ -35,7 +35,7 @@
 
     def test_anydbm_creation(self):
         f = anydbm.open(_fname, 'c')
-        self.assertEqual(f.keys(), [])
+        self.assertEqual(list(f.keys()), [])
         for key in self._dict:
             f[key] = self._dict[key]
         self.read_helper(f)

Modified: python/branches/p3yk-noslice/Lib/test/test_array.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_array.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_array.py	Wed Jul 11 15:40:56 2007
@@ -111,6 +111,21 @@
             self.assertEqual(a.x, b.x)
             self.assertEqual(type(a), type(b))
 
+    def test_pickle_for_empty_array(self):
+        for protocol in (0, 1, 2):
+            a = array.array(self.typecode)
+            b = loads(dumps(a, protocol))
+            self.assertNotEqual(id(a), id(b))
+            self.assertEqual(a, b)
+
+            a = ArraySubclass(self.typecode)
+            a.x = 10
+            b = loads(dumps(a, protocol))
+            self.assertNotEqual(id(a), id(b))
+            self.assertEqual(a, b)
+            self.assertEqual(a.x, b.x)
+            self.assertEqual(type(a), type(b))
+
     def test_insert(self):
         a = array.array(self.typecode, self.example)
         a.insert(0, self.example[0])
@@ -147,7 +162,7 @@
     def test_tofromfile(self):
         a = array.array(self.typecode, 2*self.example)
         self.assertRaises(TypeError, a.tofile)
-        self.assertRaises(TypeError, a.tofile, cStringIO.StringIO())
+        ##self.assertRaises(TypeError, a.tofile, cStringIO.StringIO())
         f = open(test_support.TESTFN, 'wb')
         try:
             a.tofile(f)
@@ -470,7 +485,7 @@
                 for step in indices[1:]:
                     self.assertEqual(list(a[start:stop:step]),
                                      list(a)[start:stop:step])
-        
+
     def test_setslice(self):
         a = array.array(self.typecode, self.example)
         a[:1] = a
@@ -575,7 +590,7 @@
                     L[start:stop:step] = data
                     a[start:stop:step] = array.array(self.typecode, data)
                     self.assertEquals(a, array.array(self.typecode, L))
-                    
+
                     del L[start:stop:step]
                     del a[start:stop:step]
                     self.assertEquals(a, array.array(self.typecode, L))
@@ -727,7 +742,7 @@
 class StringTest(BaseTest):
 
     def test_setitem(self):
-        super(StringTest, self).test_setitem()
+        super().test_setitem()
         a = array.array(self.typecode, self.example)
         self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2])
 
@@ -745,7 +760,6 @@
                 return array.array.__new__(cls, 'c', s)
 
             def __init__(self, s, color='blue'):
-                array.array.__init__(self, 'c', s)
                 self.color = color
 
             def strip(self):
@@ -854,7 +868,7 @@
 
     def test_iterationcontains(self):
         a = array.array(self.typecode, range(10))
-        self.assertEqual(list(a), range(10))
+        self.assertEqual(list(a), list(range(10)))
         b = array.array(self.typecode, [20])
         self.assertEqual(a[-1] in a, True)
         self.assertEqual(b[0] not in a, True)
@@ -1003,7 +1017,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*tests)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_ast.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ast.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_ast.py	Wed Jul 11 15:40:56 2007
@@ -144,13 +144,15 @@
                                 (eval_tests, eval_results, "eval")):
         for i, o in itertools.izip(input, output):
             ast_tree = compile(i, "?", kind, 0x400)
-            assert to_tuple(ast_tree) == o
+            tup = to_tuple(ast_tree)
+            assert tup == o, ("kind=%r\ninput=%r\nexpected=%r\ngot=%r" %
+                              (kind, i, o, tup))
             test_order(ast_tree, (0, 0))
 
 #### EVERYTHING BELOW IS GENERATED #####
 exec_results = [
 ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
-('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))])]),
+('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [], )]),
 ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]),
 ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
 ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),

Modified: python/branches/p3yk-noslice/Lib/test/test_atexit.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_atexit.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_atexit.py	Wed Jul 11 15:40:56 2007
@@ -4,97 +4,112 @@
 import atexit
 from test import test_support
 
+### helpers
+def h1():
+    print("h1")
+
+def h2():
+    print("h2")
+
+def h3():
+    print("h3")
+
+def h4(*args, **kwargs):
+    print("h4", args, kwargs)
+
+def raise1():
+    raise TypeError
+
+def raise2():
+    raise SystemError
+
 class TestCase(unittest.TestCase):
+    def setUp(self):
+        self.stream = StringIO.StringIO()
+        sys.stdout = sys.stderr = self.stream
+        atexit._clear()
+
+    def tearDown(self):
+        sys.stdout = sys.__stdout__
+        sys.stderr = sys.__stderr__
+        atexit._clear()
+
     def test_args(self):
         # be sure args are handled properly
-        s = StringIO.StringIO()
-        sys.stdout = sys.stderr = s
-        save_handlers = atexit._exithandlers
-        atexit._exithandlers = []
-        try:
-            atexit.register(self.h1)
-            atexit.register(self.h4)
-            atexit.register(self.h4, 4, kw="abc")
-            atexit._run_exitfuncs()
-        finally:
-            sys.stdout = sys.__stdout__
-            sys.stderr = sys.__stderr__
-            atexit._exithandlers = save_handlers
-        self.assertEqual(s.getvalue(), "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
+        atexit.register(h1)
+        atexit.register(h4)
+        atexit.register(h4, 4, kw="abc")
+        atexit._run_exitfuncs()
+
+        self.assertEqual(self.stream.getvalue(),
+                            "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
 
     def test_order(self):
         # be sure handlers are executed in reverse order
-        s = StringIO.StringIO()
-        sys.stdout = sys.stderr = s
-        save_handlers = atexit._exithandlers
-        atexit._exithandlers = []
-        try:
-            atexit.register(self.h1)
-            atexit.register(self.h2)
-            atexit.register(self.h3)
-            atexit._run_exitfuncs()
-        finally:
-            sys.stdout = sys.__stdout__
-            sys.stderr = sys.__stderr__
-            atexit._exithandlers = save_handlers
-        self.assertEqual(s.getvalue(), "h3\nh2\nh1\n")
-
-    def test_sys_override(self):
-        # be sure a preset sys.exitfunc is handled properly
-        s = StringIO.StringIO()
-        sys.stdout = sys.stderr = s
-        save_handlers = atexit._exithandlers
-        atexit._exithandlers = []
-        exfunc = sys.exitfunc
-        sys.exitfunc = self.h1
-        reload(atexit)
-        try:
-            atexit.register(self.h2)
-            atexit._run_exitfuncs()
-        finally:
-            sys.stdout = sys.__stdout__
-            sys.stderr = sys.__stderr__
-            atexit._exithandlers = save_handlers
-            sys.exitfunc = exfunc
-        self.assertEqual(s.getvalue(), "h2\nh1\n")
+        atexit.register(h1)
+        atexit.register(h2)
+        atexit.register(h3)
+        atexit._run_exitfuncs()
+
+        self.assertEqual(self.stream.getvalue(), "h3\nh2\nh1\n")
 
     def test_raise(self):
         # be sure raises are handled properly
-        s = StringIO.StringIO()
-        sys.stdout = sys.stderr = s
-        save_handlers = atexit._exithandlers
-        atexit._exithandlers = []
-        try:
-            atexit.register(self.raise1)
-            atexit.register(self.raise2)
-            self.assertRaises(TypeError, atexit._run_exitfuncs)
-        finally:
-            sys.stdout = sys.__stdout__
-            sys.stderr = sys.__stderr__
-            atexit._exithandlers = save_handlers
-
-    ### helpers
-    def h1(self):
-        print("h1")
-
-    def h2(self):
-        print("h2")
-
-    def h3(self):
-        print("h3")
+        atexit.register(raise1)
+        atexit.register(raise2)
 
-    def h4(self, *args, **kwargs):
-        print("h4", args, kwargs)
+        self.assertRaises(TypeError, atexit._run_exitfuncs)
 
-    def raise1(self):
-        raise TypeError
+    def test_stress(self):
+        a = [0]
+        def inc():
+            a[0] += 1
+
+        for i in range(128):
+            atexit.register(inc)
+        atexit._run_exitfuncs()
+
+        self.assertEqual(a[0], 128)
+
+    def test_clear(self):
+        a = [0]
+        def inc():
+            a[0] += 1
+
+        atexit.register(inc)
+        atexit._clear()
+        atexit._run_exitfuncs()
+
+        self.assertEqual(a[0], 0)
+
+    def test_unregister(self):
+        a = [0]
+        def inc():
+            a[0] += 1
+        def dec():
+            a[0] -= 1
+
+        for i in range(4):
+            atexit.register(inc)
+        atexit.register(dec)
+        atexit.unregister(inc)
+        atexit._run_exitfuncs()
+
+        self.assertEqual(a[0], -1)
+
+    def test_bound_methods(self):
+        l = []
+        atexit.register(l.append, 5)
+        atexit._run_exitfuncs()
+        self.assertEqual(l, [5])
+
+        atexit.unregister(l.append)
+        atexit._run_exitfuncs()
+        self.assertEqual(l, [5])
 
-    def raise2(self):
-        raise SystemError
 
 def test_main():
     test_support.run_unittest(TestCase)
 
-
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_base64.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_base64.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_base64.py	Wed Jul 11 15:40:56 2007
@@ -183,16 +183,8 @@
 
 
 
-def suite():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(LegacyBase64TestCase))
-    suite.addTest(unittest.makeSuite(BaseXYTestCase))
-    return suite
-
-
 def test_main():
-    test_support.run_suite(suite())
-
+    test_support.run_unittest(__name__)
 
 if __name__ == '__main__':
-    unittest.main(defaultTest='suite')
+    test_main()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_bastion.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_bastion.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,3 +0,0 @@
-##import Bastion
-##
-##Bastion._test()

Modified: python/branches/p3yk-noslice/Lib/test/test_binascii.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_binascii.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_binascii.py	Wed Jul 11 15:40:56 2007
@@ -9,7 +9,7 @@
     # Create binary test data
     data = "The quick brown fox jumps over the lazy dog.\r\n"
     # Be slow so we don't depend on other modules
-    data += "".join(map(chr, xrange(256)))
+    data += "".join(map(chr, range(256)))
     data += "\r\nHello world.\n"
 
     def test_exceptions(self):
@@ -26,10 +26,10 @@
                 prefixes.extend(["crc_", "rlecode_", "rledecode_"])
             for prefix in prefixes:
                 name = prefix + suffix
-                self.assert_(callable(getattr(binascii, name)))
+                self.assert_(hasattr(getattr(binascii, name), '__call__'))
                 self.assertRaises(TypeError, getattr(binascii, name))
         for name in ("hexlify", "unhexlify"):
-            self.assert_(callable(getattr(binascii, name)))
+            self.assert_(hasattr(getattr(binascii, name), '__call__'))
             self.assertRaises(TypeError, getattr(binascii, name))
 
     def test_base64valid(self):
@@ -58,7 +58,7 @@
 
         fillers = ""
         valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
-        for i in xrange(256):
+        for i in range(256):
             c = chr(i)
             if c not in valid:
                 fillers += c
@@ -148,6 +148,15 @@
             "0"*75+"=\r\n=FF\r\n=FF\r\n=FF"
         )
 
+        self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n')
+        self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n')
+        self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n')
+        self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n')
+
+        self.assertEqual(binascii.b2a_qp('.'), '=2E')
+        self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n')
+        self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
+
     def test_empty_string(self):
         # A test for SF bug #1022953.  Make sure SystemError is not raised.
         for n in ['b2a_qp', 'a2b_hex', 'b2a_base64', 'a2b_uu', 'a2b_qp',

Modified: python/branches/p3yk-noslice/Lib/test/test_bisect.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bisect.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bisect.py	Wed Jul 11 15:40:56 2007
@@ -94,8 +94,8 @@
 
     def test_random(self, n=25):
         from random import randrange
-        for i in xrange(n):
-            data = [randrange(0, n, 2) for j in xrange(i)]
+        for i in range(n):
+            data = [randrange(0, n, 2) for j in range(i)]
             data.sort()
             elem = randrange(-1, n+1)
             ip = bisect_left(data, elem)
@@ -111,9 +111,9 @@
 
     def test_optionalSlicing(self):
         for func, data, elem, expected in self.precomputedCases:
-            for lo in xrange(4):
+            for lo in range(4):
                 lo = min(len(data), lo)
-                for hi in xrange(3,8):
+                for hi in range(3,8):
                     hi = min(len(data), hi)
                     ip = func(data, elem, lo, hi)
                     self.failUnless(lo <= ip <= hi)
@@ -147,7 +147,7 @@
     def test_vsBuiltinSort(self, n=500):
         from random import choice
         for insorted in (list(), UserList()):
-            for i in xrange(n):
+            for i in range(n):
                 digit = choice("0123456789")
                 if digit in "02468":
                     f = insort_left
@@ -223,7 +223,7 @@
     ...
     >>> grade(66)
     'C'
-    >>> map(grade, [33, 99, 77, 44, 12, 88])
+    >>> list(map(grade, [33, 99, 77, 44, 12, 88]))
     ['E', 'A', 'B', 'D', 'F', 'A']
 
 """
@@ -248,7 +248,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_bool.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bool.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bool.py	Wed Jul 11 15:40:56 2007
@@ -168,8 +168,8 @@
         self.assertIs(hasattr([], "wobble"), False)
 
     def test_callable(self):
-        self.assertIs(callable(len), True)
-        self.assertIs(callable(1), False)
+        self.assertIs(hasattr(len, '__call__'), True)
+        self.assertIs(hasattr(1, '__call__'), False)
 
     def test_isinstance(self):
         self.assertIs(isinstance(True, bool), True)
@@ -257,8 +257,6 @@
         import operator
         self.assertIs(operator.truth(0), False)
         self.assertIs(operator.truth(1), True)
-        self.assertIs(operator.isCallable(0), False)
-        self.assertIs(operator.isCallable(len), True)
         self.assertIs(operator.isNumberType(None), False)
         self.assertIs(operator.isNumberType(0), True)
         self.assertIs(operator.not_(1), False)
@@ -323,7 +321,7 @@
         self.assertEqual(pickle.dumps(False), "I00\n.")
         self.assertEqual(pickle.dumps(True, True), "I01\n.")
         self.assertEqual(pickle.dumps(False, True), "I00\n.")
- 
+
         try:
             import cPickle
         except ImportError:

Modified: python/branches/p3yk-noslice/Lib/test/test_bsddb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bsddb.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bsddb.py	Wed Jul 11 15:40:56 2007
@@ -72,7 +72,7 @@
         di = iter(self.d)
         while 1:
             try:
-                key = di.next()
+                key = next(di)
                 self.d[key] = 'modified '+key
             except StopIteration:
                 break
@@ -83,7 +83,7 @@
         fi = iter(self.f)
         while 1:
             try:
-                key = fi.next()
+                key = next(fi)
                 self.f[key] = 'modified '+key
             except StopIteration:
                 break
@@ -97,7 +97,7 @@
         di = iter(self.d.items())
         while 1:
             try:
-                k, v = di.next()
+                k, v = next(di)
                 self.d[k] = 'modified '+v
             except StopIteration:
                 break
@@ -108,7 +108,7 @@
         fi = iter(self.f.items())
         while 1:
             try:
-                k, v = fi.next()
+                k, v = next(fi)
                 self.f[k] = 'modified '+v
             except StopIteration:
                 break
@@ -117,13 +117,13 @@
 
     def test_first_next_looping(self):
         items = [self.f.first()]
-        for i in xrange(1, len(self.f)):
+        for i in range(1, len(self.f)):
             items.append(self.f.next())
         self.assertSetEquals(items, self.d.items())
 
     def test_previous_last_looping(self):
         items = [self.f.last()]
-        for i in xrange(1, len(self.f)):
+        for i in range(1, len(self.f)):
             items.append(self.f.previous())
         self.assertSetEquals(items, self.d.items())
 
@@ -160,13 +160,13 @@
         if hasattr(self.f, 'iteritems'):
             if debug: print("D")
             i = iter(self.f.items())
-            k,v = i.next()
+            k,v = next(i)
             if debug: print("E")
             self.f[k] = "please don't deadlock"
             if debug: print("F")
             while 1:
                 try:
-                    k,v = i.next()
+                    k,v = next(i)
                 except StopIteration:
                     break
             if debug: print("F2")
@@ -176,7 +176,7 @@
             while i:
                 try:
                     if debug: print("H")
-                    k = i.next()
+                    k = next(i)
                     if debug: print("I")
                     self.f[k] = "deadlocks-r-us"
                     if debug: print("J")
@@ -201,7 +201,7 @@
         i = iter(self.f.iteritems())
         nc2 = len(self.f._cursor_refs)
         # use the iterator (should run to the first yield, creating the cursor)
-        k, v = i.next()
+        k, v = next(i)
         nc3 = len(self.f._cursor_refs)
         # destroy the iterator; this should cause the weakref callback
         # to remove the cursor object from self.f._cursor_refs

Deleted: /python/branches/p3yk-noslice/Lib/test/test_bsddb185.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_bsddb185.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,43 +0,0 @@
-"""Tests for the bsddb185 module.
-
-The file 185test.db found in Lib/test/ is for testing purposes with this
-testing suite.
-
-"""
-from test.test_support import verbose, run_unittest, findfile
-import unittest
-import bsddb185
-import anydbm
-import whichdb
-import os
-import tempfile
-import shutil
-
-class Bsddb185Tests(unittest.TestCase):
-
-    def test_open_existing_hash(self):
-        # Verify we can open a file known to be a hash v2 file
-        db = bsddb185.hashopen(findfile("185test.db"))
-        self.assertEqual(db["1"], "1")
-        db.close()
-
-    def test_whichdb(self):
-        # Verify that whichdb correctly sniffs the known hash v2 file
-        self.assertEqual(whichdb.whichdb(findfile("185test.db")), "bsddb185")
-
-    def test_anydbm_create(self):
-        # Verify that anydbm.open does *not* create a bsddb185 file
-        tmpdir = tempfile.mkdtemp()
-        try:
-            dbfile = os.path.join(tmpdir, "foo.db")
-            anydbm.open(dbfile, "c").close()
-            ftype = whichdb.whichdb(dbfile)
-            self.assertNotEqual(ftype, "bsddb185")
-        finally:
-            shutil.rmtree(tmpdir)
-
-def test_main():
-    run_unittest(Bsddb185Tests)
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_bsddb3.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bsddb3.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bsddb3.py	Wed Jul 11 15:40:56 2007
@@ -4,7 +4,7 @@
 """
 import sys
 import unittest
-from test.test_support import requires, verbose, run_suite, unlink
+from test.test_support import requires, verbose, run_unittest, unlink
 
 # When running as a script instead of within the regrtest framework, skip the
 # requires test, since it's obvious we want to run them.
@@ -58,9 +58,7 @@
 
 # For invocation through regrtest
 def test_main():
-    tests = suite()
-    run_suite(tests)
-
+    run_unittest(suite())
 
 # For invocation as a script
 if __name__ == '__main__':
@@ -73,4 +71,4 @@
     print('python version:        %s' % sys.version)
     print('-=' * 38)
 
-    unittest.main(defaultTest='suite')
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_bufio.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bufio.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bufio.py	Wed Jul 11 15:40:56 2007
@@ -5,8 +5,8 @@
 # the expected results.  For best testing, run this under a debug-build
 # Python too (to exercise asserts in the C code).
 
-lengths = range(1, 257) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
-                           16384, 32768, 65536, 1000000]
+lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
+                                 16384, 32768, 65536, 1000000]
 
 class BufferSizeTest(unittest.TestCase):
     def try_one(self, s):

Modified: python/branches/p3yk-noslice/Lib/test/test_builtin.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_builtin.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_builtin.py	Wed Jul 11 15:40:56 2007
@@ -107,9 +107,12 @@
         __import__('sys')
         __import__('time')
         __import__('string')
+        __import__(name='sys')
+        __import__(name='time', level=0)
         self.assertRaises(ImportError, __import__, 'spamspam')
         self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
         self.assertRaises(ValueError, __import__, '')
+        self.assertRaises(TypeError, __import__, 'sys', name='sys')
 
     def test_abs(self):
         # int
@@ -161,20 +164,21 @@
         self.assert_(isinstance(x, int))
         self.assertEqual(-x, sys.maxint+1)
 
+    # XXX(nnorwitz): This test case for callable should probably be removed.
     def test_callable(self):
-        self.assert_(callable(len))
+        self.assert_(hasattr(len, '__call__'))
         def f(): pass
-        self.assert_(callable(f))
+        self.assert_(hasattr(f, '__call__'))
         class C:
             def meth(self): pass
-        self.assert_(callable(C))
+        self.assert_(hasattr(C, '__call__'))
         x = C()
-        self.assert_(callable(x.meth))
-        self.assert_(not callable(x))
+        self.assert_(hasattr(x.meth, '__call__'))
+        self.assert_(not hasattr(x, '__call__'))
         class D(C):
             def __call__(self): pass
         y = D()
-        self.assert_(callable(y))
+        self.assert_(hasattr(y, '__call__'))
         y()
 
     def test_chr(self):
@@ -207,15 +211,21 @@
         compile('print(1)\n', '', 'exec')
         bom = '\xef\xbb\xbf'
         compile(bom + 'print(1)\n', '', 'exec')
+        compile(source='pass', filename='?', mode='exec')
+        compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
+        compile('pass', '?', dont_inherit=1, mode='exec')
         self.assertRaises(TypeError, compile)
         self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
         self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
         self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
+        self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
+                          mode='eval', source='0', filename='tmp')
         if have_unicode:
             compile(unicode('print(u"\xc3\xa5")\n', 'utf8'), '', 'exec')
             self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
             self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
 
+
     def test_delattr(self):
         import sys
         sys.spam = 1
@@ -223,12 +233,67 @@
         self.assertRaises(TypeError, delattr)
 
     def test_dir(self):
-        x = 1
-        self.assert_('x' in dir())
-        import sys
-        self.assert_('modules' in dir(sys))
+        # dir(wrong number of arguments)
         self.assertRaises(TypeError, dir, 42, 42)
 
+        # dir() - local scope
+        local_var = 1
+        self.assert_('local_var' in dir())
+
+        # dir(module)
+        import sys
+        self.assert_('exit' in dir(sys))
+
+        # dir(module_with_invalid__dict__)
+        import types
+        class Foo(types.ModuleType):
+            __dict__ = 8
+        f = Foo("foo")
+        self.assertRaises(TypeError, dir, f)
+
+        # dir(type)
+        self.assert_("strip" in dir(str))
+        self.assert_("__mro__" not in dir(str))
+
+        # dir(obj)
+        class Foo(object):
+            def __init__(self):
+                self.x = 7
+                self.y = 8
+                self.z = 9
+        f = Foo()
+        self.assert_("y" in dir(f))
+
+        # dir(obj_no__dict__)
+        class Foo(object):
+            __slots__ = []
+        f = Foo()
+        self.assert_("__repr__" in dir(f))
+
+        # dir(obj_no__class__with__dict__)
+        # (an ugly trick to cause getattr(f, "__class__") to fail)
+        class Foo(object):
+            __slots__ = ["__class__", "__dict__"]
+            def __init__(self):
+                self.bar = "wow"
+        f = Foo()
+        self.assert_("__repr__" not in dir(f))
+        self.assert_("bar" in dir(f))
+
+        # dir(obj_using __dir__)
+        class Foo(object):
+            def __dir__(self):
+                return ["kan", "ga", "roo"]
+        f = Foo()
+        self.assert_(dir(f) == ["ga", "kan", "roo"])
+
+        # dir(obj__dir__not_list)
+        class Foo(object):
+            def __dir__(self):
+                return 7
+        f = Foo()
+        self.assertRaises(TypeError, dir, f)
+
     def test_divmod(self):
         self.assertEqual(divmod(12, 7), (1, 5))
         self.assertEqual(divmod(-12, 7), (-2, 2))
@@ -428,11 +493,11 @@
         self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
 
     def test_filter(self):
-        self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
-        self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
-        self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
-        self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
-        self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
+        self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
+        self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
+        self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
+        self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
+        self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
         def identity(item):
             return 1
         filter(identity, Squares(5))
@@ -442,101 +507,15 @@
                 if index<4:
                     return 42
                 raise ValueError
-        self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
+        self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
         def badfunc():
             pass
-        self.assertRaises(TypeError, filter, badfunc, range(5))
+        self.assertRaises(TypeError, list, filter(badfunc, range(5)))
 
         # test bltinmodule.c::filtertuple()
-        self.assertEqual(filter(None, (1, 2)), (1, 2))
-        self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
-        self.assertRaises(TypeError, filter, 42, (1, 2))
-
-        # test bltinmodule.c::filterstring()
-        self.assertEqual(filter(None, "12"), "12")
-        self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
-        self.assertRaises(TypeError, filter, 42, "12")
-        class badstr(str):
-            def __getitem__(self, index):
-                raise ValueError
-        self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
-
-        class badstr2(str):
-            def __getitem__(self, index):
-                return 42
-        self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
-
-        class weirdstr(str):
-            def __getitem__(self, index):
-                return weirdstr(2*str.__getitem__(self, index))
-        self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
-
-        class shiftstr(str):
-            def __getitem__(self, index):
-                return chr(ord(str.__getitem__(self, index))+1)
-        self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
-
-        if have_unicode:
-            # test bltinmodule.c::filterunicode()
-            self.assertEqual(filter(None, unicode("12")), unicode("12"))
-            self.assertEqual(filter(lambda x: x>="3", unicode("1234")), unicode("34"))
-            self.assertRaises(TypeError, filter, 42, unicode("12"))
-            self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234")))
-
-            class badunicode(unicode):
-                def __getitem__(self, index):
-                    return 42
-            self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234"))
-
-            class weirdunicode(unicode):
-                def __getitem__(self, index):
-                    return weirdunicode(2*unicode.__getitem__(self, index))
-            self.assertEqual(
-                filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344"))
-
-            class shiftunicode(unicode):
-                def __getitem__(self, index):
-                    return unichr(ord(unicode.__getitem__(self, index))+1)
-            self.assertEqual(
-                filter(lambda x: x>=unicode("3"), shiftunicode("1234")),
-                unicode("345")
-            )
-
-    def test_filter_subclasses(self):
-        # test that filter() never returns tuple, str or unicode subclasses
-        # and that the result always goes through __getitem__
-        funcs = (None, bool, lambda x: True)
-        class tuple2(tuple):
-            def __getitem__(self, index):
-                return 2*tuple.__getitem__(self, index)
-        class str2(str):
-            def __getitem__(self, index):
-                return 2*str.__getitem__(self, index)
-        inputs = {
-            tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
-            str2:   {"": "", "123": "112233"}
-        }
-        if have_unicode:
-            class unicode2(unicode):
-                def __getitem__(self, index):
-                    return 2*unicode.__getitem__(self, index)
-            inputs[unicode2] = {
-                unicode(): unicode(),
-                unicode("123"): unicode("112233")
-            }
-
-        for (cls, inps) in inputs.items():
-            for (inp, exp) in inps.items():
-                # make sure the output goes through __getitem__
-                # even if func is None
-                self.assertEqual(
-                    filter(funcs[0], cls(inp)),
-                    filter(funcs[1], cls(inp))
-                )
-                for func in funcs:
-                    outp = filter(func, cls(inp))
-                    self.assertEqual(outp, exp)
-                    self.assert_(not isinstance(outp, cls))
+        self.assertEqual(list(filter(None, (1, 2))), [1, 2])
+        self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
+        self.assertRaises(TypeError, list, filter(42, (1, 2)))
 
     def test_float(self):
         self.assertEqual(float(3.14), 3.14)
@@ -667,6 +646,8 @@
         id([0,1,2,3])
         id({'spam': 1, 'eggs': 2, 'ham': 3})
 
+    # Test input() later, alphabetized as if it were raw_input
+
     def test_int(self):
         self.assertEqual(int(314), 314)
         self.assertEqual(int(3.14), 3)
@@ -731,8 +712,27 @@
 
         self.assertRaises(TypeError, int, 1, 12)
 
-        self.assertEqual(int('0123', 0), 83)
+        # tests with base 0
+        self.assertRaises(ValueError, int, ' 0123  ', 0) # old octal syntax
+        self.assertEqual(int('000', 0), 0)
+        self.assertEqual(int('0o123', 0), 83)
+        self.assertEqual(int('0x123', 0), 291)
+        self.assertEqual(int('0b100', 0), 4)
+        self.assertEqual(int(' 0O123   ', 0), 83)
+        self.assertEqual(int(' 0X123  ', 0), 291)
+        self.assertEqual(int(' 0B100 ', 0), 4)
+
+        # without base still base 10
+        self.assertEqual(int('0123'), 123)
+        self.assertEqual(int('0123', 10), 123)
+
+        # tests with prefix and base != 0
         self.assertEqual(int('0x123', 16), 291)
+        self.assertEqual(int('0o123', 8), 83)
+        self.assertEqual(int('0b100', 2), 4)
+        self.assertEqual(int('0X123', 16), 291)
+        self.assertEqual(int('0O123', 8), 83)
+        self.assertEqual(int('0B100', 2), 4)
 
         # SF bug 1334662: int(string, base) wrong answers
         # Various representations of 2**32 evaluated to 0
@@ -853,9 +853,9 @@
             lists.append(unicode("12"))
         for l in lists:
             i = iter(l)
-            self.assertEqual(i.next(), '1')
-            self.assertEqual(i.next(), '2')
-            self.assertRaises(StopIteration, i.next)
+            self.assertEqual(next(i), '1')
+            self.assertEqual(next(i), '2')
+            self.assertRaises(StopIteration, next, i)
 
     def test_isinstance(self):
         class C:
@@ -930,7 +930,7 @@
             # thread for the details:
 
             #     http://sources.redhat.com/ml/newlib/2002/msg00369.html
-            self.assertRaises(MemoryError, list, xrange(sys.maxint // 2))
+            self.assertRaises(MemoryError, list, range(sys.maxint // 2))
 
         # This code used to segfault in Py2.4a3
         x = []
@@ -981,6 +981,11 @@
         self.assertRaises(ValueError, int, '53', 40)
         self.assertRaises(TypeError, int, 1, 12)
 
+        # SF patch #1638879: embedded NULs were not detected with
+        # explicit base
+        self.assertRaises(ValueError, int, '123\0', 10)
+        self.assertRaises(ValueError, int, '123\x00 245', 20)
+
         self.assertEqual(int('100000000000000000000000000000000', 2),
                          4294967296)
         self.assertEqual(int('102002022201221111211', 3), 4294967296)
@@ -1084,28 +1089,28 @@
 
         self.assertEqual(int(Foo0()), 42)
         self.assertEqual(int(Foo1()), 42)
-	# XXX invokes __int__ now
+        # XXX invokes __int__ now
         # self.assertEqual(long(Foo2()), 42L)
         self.assertEqual(int(Foo3()), 0)
-	# XXX likewise
+        # XXX likewise
         # self.assertEqual(long(Foo4()), 42)
         # self.assertRaises(TypeError, long, Foo5())
 
     def test_map(self):
         self.assertEqual(
-            map(None, 'hello world'),
-            ['h','e','l','l','o',' ','w','o','r','l','d']
+            list(map(None, 'hello')),
+            [('h',), ('e',), ('l',), ('l',), ('o',)]
         )
         self.assertEqual(
-            map(None, 'abcd', 'efg'),
-            [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
+            list(map(None, 'abcd', 'efg')),
+            [('a', 'e'), ('b', 'f'), ('c', 'g')]
         )
         self.assertEqual(
-            map(None, range(10)),
-            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+            list(map(None, range(3))),
+            [(0,), (1,), (2,)]
         )
         self.assertEqual(
-            map(lambda x: x*x, range(1,4)),
+            list(map(lambda x: x*x, range(1,4))),
             [1, 4, 9]
         )
         try:
@@ -1114,11 +1119,11 @@
             def sqrt(x):
                 return pow(x, 0.5)
         self.assertEqual(
-            map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
+            list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
             [[4.0, 2.0], [9.0, 3.0]]
         )
         self.assertEqual(
-            map(lambda x, y: x+y, [1,3,2], [9,1,4]),
+            list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
             [10, 4, 6]
         )
 
@@ -1127,28 +1132,28 @@
             for i in v: accu = accu + i
             return accu
         self.assertEqual(
-            map(plus, [1, 3, 7]),
+            list(map(plus, [1, 3, 7])),
             [1, 3, 7]
         )
         self.assertEqual(
-            map(plus, [1, 3, 7], [4, 9, 2]),
+            list(map(plus, [1, 3, 7], [4, 9, 2])),
             [1+4, 3+9, 7+2]
         )
         self.assertEqual(
-            map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
+            list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
             [1+4+1, 3+9+1, 7+2+0]
         )
         self.assertEqual(
-            map(None, Squares(10)),
-            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
+            list(map(None, Squares(10))),
+            [(0,), (1,), (4,), (9,), (16,), (25,), (36,), (49,), (64,), (81,)]
         )
         self.assertEqual(
-            map(int, Squares(10)),
+            list(map(int, Squares(10))),
             [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
         )
         self.assertEqual(
-            map(None, Squares(3), Squares(2)),
-            [(0,0), (1,1), (4,None)]
+            list(map(None, Squares(3), Squares(2))),
+            [(0,0), (1,1)]
         )
         def Max(a, b):
             if a is None:
@@ -1157,19 +1162,20 @@
                 return a
             return max(a, b)
         self.assertEqual(
-            map(Max, Squares(3), Squares(2)),
-            [0, 1, 4]
+            list(map(Max, Squares(3), Squares(2))),
+            [0, 1]
         )
         self.assertRaises(TypeError, map)
         self.assertRaises(TypeError, map, lambda x: x, 42)
-        self.assertEqual(map(None, [42]), [42])
+        self.assertEqual(list(map(None, [42])), [(42,)])
         class BadSeq:
-            def __getitem__(self, index):
+            def __iter__(self):
                 raise ValueError
-        self.assertRaises(ValueError, map, lambda x: x, BadSeq())
+                yield None
+        self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
         def badfunc(x):
             raise RuntimeError
-        self.assertRaises(RuntimeError, map, badfunc, range(5))
+        self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
 
     def test_max(self):
         self.assertEqual(max('123123'), '3')
@@ -1251,14 +1257,42 @@
         self.assertEqual(min(data, key=f),
                          sorted(data, key=f)[0])
 
+    def test_next(self):
+        it = iter(range(2))
+        self.assertEqual(next(it), 0)
+        self.assertEqual(next(it), 1)
+        self.assertRaises(StopIteration, next, it)
+        self.assertRaises(StopIteration, next, it)
+        self.assertEquals(next(it, 42), 42)
+
+        class Iter(object):
+            def __iter__(self):
+                return self
+            def __next__(self):
+                raise StopIteration
+
+        it = iter(Iter())
+        self.assertEquals(next(it, 42), 42)
+        self.assertRaises(StopIteration, next, it)
+
+        def gen():
+            yield 1
+            return
+
+        it = gen()
+        self.assertEquals(next(it), 1)
+        self.assertRaises(StopIteration, next, it)
+        self.assertEquals(next(it, 42), 42)
+
     def test_oct(self):
-        self.assertEqual(oct(100), '0144')
-        self.assertEqual(oct(100), '0144')
-        self.assertEqual(oct(-100), '-0144')
-        self.assertEqual(oct(-100), '-0144')
+        self.assertEqual(oct(100), '0o144')
+        self.assertEqual(oct(100), '0o144')
+        self.assertEqual(oct(-100), '-0o144')
+        self.assertEqual(oct(-100), '-0o144')
         self.assertRaises(TypeError, oct, ())
 
     def write_testfile(self):
+        # NB the first 4 lines are also used to test input, below
         fp = open(TESTFN, 'w')
         try:
             fp.write('1+1\n')
@@ -1361,38 +1395,39 @@
         self.assertRaises(TypeError, pow)
 
     def test_range(self):
-        self.assertEqual(range(3), [0, 1, 2])
-        self.assertEqual(range(1, 5), [1, 2, 3, 4])
-        self.assertEqual(range(0), [])
-        self.assertEqual(range(-3), [])
-        self.assertEqual(range(1, 10, 3), [1, 4, 7])
-        self.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
+        self.assertEqual(list(range(3)), [0, 1, 2])
+        self.assertEqual(list(range(1, 5)), [1, 2, 3, 4])
+        self.assertEqual(list(range(0)), [])
+        self.assertEqual(list(range(-3)), [])
+        self.assertEqual(list(range(1, 10, 3)), [1, 4, 7])
+        #self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4])
 
+        """ XXX(nnorwitz):
         # Now test range() with longs
-        self.assertEqual(range(-2**100), [])
-        self.assertEqual(range(0, -2**100), [])
-        self.assertEqual(range(0, 2**100, -1), [])
-        self.assertEqual(range(0, 2**100, -1), [])
+        self.assertEqual(list(range(-2**100)), [])
+        self.assertEqual(list(range(0, -2**100)), [])
+        self.assertEqual(list(range(0, 2**100, -1)), [])
+        self.assertEqual(list(range(0, 2**100, -1)), [])
 
         a = int(10 * sys.maxint)
         b = int(100 * sys.maxint)
         c = int(50 * sys.maxint)
 
-        self.assertEqual(range(a, a+2), [a, a+1])
-        self.assertEqual(range(a+2, a, -1), [a+2, a+1])
-        self.assertEqual(range(a+4, a, -2), [a+4, a+2])
+        self.assertEqual(list(range(a, a+2)), [a, a+1])
+        self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1])
+        self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2])
 
-        seq = range(a, b, c)
+        seq = list(range(a, b, c))
         self.assert_(a in seq)
         self.assert_(b not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = range(b, a, -c)
+        seq = list(range(b, a, -c))
         self.assert_(b in seq)
         self.assert_(a not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = range(-a, -b, -c)
+        seq = list(range(-a, -b, -c))
         self.assert_(-a in seq)
         self.assert_(-b not in seq)
         self.assertEqual(len(seq), 2)
@@ -1409,6 +1444,7 @@
 
         # XXX This won't (but should!) raise RuntimeError if a is an int...
         self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
+        """
 
         # Reject floats when it would require PyLongs to represent.
         # (smaller floats still accepted, but deprecated)
@@ -1417,16 +1453,47 @@
         self.assertRaises(TypeError, range, 0, "spam")
         self.assertRaises(TypeError, range, 0, 42, "spam")
 
-        self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
-        self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
+        #NEAL self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
+        #NEAL self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
 
-    def test_reload(self):
-        import marshal
-        reload(marshal)
-        import string
-        reload(string)
-        ## import sys
-        ## self.assertRaises(ImportError, reload, sys)
+        self.assertRaises(OverflowError, len, range(0, sys.maxint**10))
+
+    def test_input(self):
+        self.write_testfile()
+        fp = open(TESTFN, 'r')
+        savestdin = sys.stdin
+        savestdout = sys.stdout # Eats the echo
+        try:
+            sys.stdin = fp
+            sys.stdout = BitBucket()
+            self.assertEqual(input(), "1+1")
+            self.assertEqual(input('testing\n'), "1+1")
+            self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
+            self.assertEqual(input('testing\n'), 'Dear John')
+
+            # SF 1535165: don't segfault on closed stdin
+            # sys.stdout must be a regular file for triggering
+            sys.stdout = savestdout
+            sys.stdin.close()
+            self.assertRaises(ValueError, input)
+
+            sys.stdout = BitBucket()
+            sys.stdin = cStringIO.StringIO("NULL\0")
+            self.assertRaises(TypeError, input, 42, 42)
+            sys.stdin = cStringIO.StringIO("    'whitespace'")
+            self.assertEqual(input(), "    'whitespace'")
+            sys.stdin = cStringIO.StringIO()
+            self.assertRaises(EOFError, input)
+
+            del sys.stdout
+            self.assertRaises(RuntimeError, input, 'prompt')
+            del sys.stdin
+            self.assertRaises(RuntimeError, input, 'prompt')
+        finally:
+            sys.stdin = savestdin
+            sys.stdout = savestdout
+            fp.close()
+            unlink(TESTFN)
 
     def test_repr(self):
         self.assertEqual(repr(''), '\'\'')
@@ -1500,8 +1567,8 @@
 
     def test_sum(self):
         self.assertEqual(sum([]), 0)
-        self.assertEqual(sum(range(2,8)), 27)
-        self.assertEqual(sum(iter(range(2,8))), 27)
+        self.assertEqual(sum(list(range(2,8))), 27)
+        self.assertEqual(sum(iter(list(range(2,8)))), 27)
         self.assertEqual(sum(Squares(10)), 285)
         self.assertEqual(sum(iter(Squares(10))), 285)
         self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
@@ -1598,7 +1665,7 @@
                 else:
                     return i
         self.assertEqual(
-            list(zip(SequenceWithoutALength(), xrange(2**30))),
+            list(zip(SequenceWithoutALength(), range(2**30))),
             list(enumerate(range(5)))
         )
 
@@ -1613,7 +1680,7 @@
 class TestSorted(unittest.TestCase):
 
     def test_basic(self):
-        data = range(100)
+        data = list(range(100))
         copy = data[:]
         random.shuffle(copy)
         self.assertEqual(data, sorted(copy))
@@ -1658,7 +1725,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_bytes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bytes.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bytes.py	Wed Jul 11 15:40:56 2007
@@ -3,9 +3,12 @@
 import os
 import re
 import sys
+import pickle
+import cPickle
 import tempfile
 import unittest
 import test.test_support
+import test.string_tests
 
 
 class BytesTest(unittest.TestCase):
@@ -69,9 +72,11 @@
         self.assertRaises(ValueError, bytes, [10**100])
 
     def test_repr(self):
-        self.assertEqual(repr(bytes()), "bytes()")
-        self.assertEqual(repr(bytes([0])), "bytes([0x00])")
-        self.assertEqual(repr(bytes([0, 1, 254, 255])), "bytes([0x00, 0x01, 0xfe, 0xff])")
+        self.assertEqual(repr(bytes()), "b''")
+        self.assertEqual(repr(bytes([0])), "b'\\0'")
+        self.assertEqual(repr(bytes([0, 1, 254, 255])), "b'\\0\\x01\\xfe\\xff'")
+        self.assertEqual(repr(bytes('abc')), "b'abc'")
+        self.assertEqual(repr(bytes("'")), "b'\\''")
 
     def test_compare(self):
         b1 = bytes([1, 2, 3])
@@ -96,6 +101,42 @@
         self.failIf(b3 <  b2)
         self.failIf(b3 <= b2)
 
+    def test_compare_to_str(self):
+        self.assertEqual(b"abc" == "abc", True)
+        self.assertEqual(b"ab" != "abc", True)
+        self.assertEqual(b"ab" <= "abc", True)
+        self.assertEqual(b"ab" < "abc", True)
+        self.assertEqual(b"abc" >= "ab", True)
+        self.assertEqual(b"abc" > "ab", True)
+
+        self.assertEqual(b"abc" != "abc", False)
+        self.assertEqual(b"ab" == "abc", False)
+        self.assertEqual(b"ab" > "abc", False)
+        self.assertEqual(b"ab" >= "abc", False)
+        self.assertEqual(b"abc" < "ab", False)
+        self.assertEqual(b"abc" <= "ab", False)
+
+        self.assertEqual("abc" == b"abc", True)
+        self.assertEqual("ab" != b"abc", True)
+        self.assertEqual("ab" <= b"abc", True)
+        self.assertEqual("ab" < b"abc", True)
+        self.assertEqual("abc" >= b"ab", True)
+        self.assertEqual("abc" > b"ab", True)
+
+        self.assertEqual("abc" != b"abc", False)
+        self.assertEqual("ab" == b"abc", False)
+        self.assertEqual("ab" > b"abc", False)
+        self.assertEqual("ab" >= b"abc", False)
+        self.assertEqual("abc" < b"ab", False)
+        self.assertEqual("abc" <= b"ab", False)
+
+        # But they should never compare equal to Unicode!
+        # Test this for all expected byte orders and Unicode character sizes
+        self.assertEqual(b"\0a\0b\0c" == u"abc", False)
+        self.assertEqual(b"\0\0\0a\0\0\0b\0\0\0c" == u"abc", False)
+        self.assertEqual(b"a\0b\0c\0" == u"abc", False)
+        self.assertEqual(b"a\0\0\0b\0\0\0c\0\0\0" == u"abc", False)
+
     def test_nohash(self):
         self.assertRaises(TypeError, hash, bytes())
 
@@ -116,20 +157,13 @@
                 b = bytes([ord('x')]*20)
                 n = f.readinto(b)
             self.assertEqual(n, len(short_sample))
-            self.assertEqual(list(b), map(ord, sample))
+            self.assertEqual(list(b), list(map(ord, sample)))
             # Test writing in binary mode
             with open(tfn, "wb") as f:
                 f.write(b)
             with open(tfn, "rb") as f:
                 self.assertEqual(f.read(), sample)
-            # Test writing in text mode
-            with open(tfn, "w") as f:
-                f.write(b)
-            with open(tfn, "r") as f:
-                self.assertEqual(f.read(), sample)
-            # Can't use readinto in text mode
-            with open(tfn, "r") as f:
-                self.assertRaises(TypeError, f.readinto, b)
+            # Text mode is ambiguous; don't test
         finally:
             try:
                 os.remove(tfn)
@@ -137,12 +171,23 @@
                 pass
 
     def test_reversed(self):
-        input = map(ord, "Hello")
+        input = list(map(ord, "Hello"))
         b = bytes(input)
         output = list(reversed(b))
         input.reverse()
         self.assertEqual(output, input)
 
+    def test_reverse(self):
+        b = b'hello'
+        self.assertEqual(b.reverse(), None)
+        self.assertEqual(b, b'olleh')
+        b = b'hello1' # test even number of items
+        b.reverse()
+        self.assertEqual(b, b'1olleh')
+        b = bytes()
+        b.reverse()
+        self.assertFalse(b)
+
     def test_getslice(self):
         def by(s):
             return bytes(map(ord, s))
@@ -173,7 +218,7 @@
                 # Skip step 0 (invalid)
                 for step in indices[1:]:
                     self.assertEqual(b[start:stop:step], bytes(L[start:stop:step]))
-        
+
     def test_regexps(self):
         def by(s):
             return bytes(map(ord, s))
@@ -246,7 +291,7 @@
 
         b[3:5] = [3, 4, 5, 6]
         self.assertEqual(b, bytes(range(10)))
-        
+
         b[3:0] = [42, 42, 42]
         self.assertEqual(b, bytes([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
 
@@ -265,7 +310,7 @@
                     L[start:stop:step] = data
                     b[start:stop:step] = data
                     self.assertEquals(b, bytes(L))
-                    
+
                     del L[start:stop:step]
                     del b[start:stop:step]
                     self.assertEquals(b, bytes(L))
@@ -319,8 +364,10 @@
         b1 = bytes("abc")
         b2 = bytes("def")
         self.assertEqual(b1 + b2, bytes("abcdef"))
-        self.assertRaises(TypeError, lambda: b1 + "def")
-        self.assertRaises(TypeError, lambda: "abc" + b2)
+        self.assertEqual(b1 + "def", bytes("abcdef"))
+        self.assertEqual("def" + b1, bytes("defabc"))
+        self.assertRaises(TypeError, lambda: b1 + u"def")
+        self.assertRaises(TypeError, lambda: u"abc" + b2)
 
     def test_repeat(self):
         b = bytes("abc")
@@ -341,6 +388,14 @@
         self.assertEqual(b, bytes("abcdef"))
         self.assertEqual(b, b1)
         self.failUnless(b is b1)
+        b += "xyz"
+        self.assertEqual(b, b"abcdefxyz")
+        try:
+            b += u""
+        except TypeError:
+            pass
+        else:
+            self.fail("bytes += unicode didn't raise TypeError")
 
     def test_irepeat(self):
         b = bytes("abc")
@@ -394,51 +449,277 @@
                 seq.append(alloc)
         #print seq
 
+    def test_fromhex(self):
+        self.assertRaises(TypeError, bytes.fromhex)
+        self.assertRaises(TypeError, bytes.fromhex, 1)
+        self.assertEquals(bytes.fromhex(''), bytes())
+        b = bytes([0x1a, 0x2b, 0x30])
+        self.assertEquals(bytes.fromhex('1a2B30'), b)
+        self.assertEquals(bytes.fromhex('  1A 2B  30   '), b)
+        self.assertEquals(bytes.fromhex(buffer('')), bytes())
+        self.assertEquals(bytes.fromhex(buffer('0000')), bytes([0, 0]))
+        self.assertRaises(ValueError, bytes.fromhex, 'a')
+        self.assertRaises(ValueError, bytes.fromhex, 'rt')
+        self.assertRaises(ValueError, bytes.fromhex, '1a b cd')
+        self.assertRaises(ValueError, bytes.fromhex, '\x00')
+        self.assertRaises(ValueError, bytes.fromhex, '12   \x00   34')
+
     def test_join(self):
         self.assertEqual(bytes.join([]), bytes())
         self.assertEqual(bytes.join([bytes()]), bytes())
         for part in [("abc",), ("a", "bc"), ("ab", "c"), ("a", "b", "c")]:
-            lst = map(bytes, part)
+            lst = list(map(bytes, part))
             self.assertEqual(bytes.join(lst), bytes("abc"))
             self.assertEqual(bytes.join(tuple(lst)), bytes("abc"))
             self.assertEqual(bytes.join(iter(lst)), bytes("abc"))
         # XXX more...
-            
+
+    def test_literal(self):
+        tests =  [
+            (b"Wonderful spam", u"Wonderful spam"),
+            (br"Wonderful spam too", u"Wonderful spam too"),
+            (b"\xaa\x00\000\200", u"\xaa\x00\000\200"),
+            (br"\xaa\x00\000\200", ur"\xaa\x00\000\200"),
+        ]
+        for b, s in tests:
+            self.assertEqual(b, bytes(s, 'latin-1'))
+        for c in range(128, 256):
+            self.assertRaises(SyntaxError, eval,
+                              'b"%s"' % chr(c))
+
+    def test_extend(self):
+        orig = b'hello'
+        a = bytes(orig)
+        a.extend(a)
+        self.assertEqual(a, orig + orig)
+        self.assertEqual(a[5:], orig)
+
+    def test_remove(self):
+        b = b'hello'
+        b.remove(ord('l'))
+        self.assertEqual(b, b'helo')
+        b.remove(ord('l'))
+        self.assertEqual(b, b'heo')
+        self.assertRaises(ValueError, lambda: b.remove(ord('l')))
+        self.assertRaises(ValueError, lambda: b.remove(400))
+        self.assertRaises(ValueError, lambda: b.remove('e'))
+        # remove first and last
+        b.remove(ord('o'))
+        b.remove(ord('h'))
+        self.assertEqual(b, b'e')
+
+    def test_pop(self):
+        b = b'world'
+        self.assertEqual(b.pop(), ord('d'))
+        self.assertEqual(b.pop(0), ord('w'))
+        self.assertEqual(b.pop(-2), ord('r'))
+        self.assertRaises(IndexError, lambda: b.pop(10))
+        self.assertRaises(OverflowError, lambda: bytes().pop())
+
+    def test_nosort(self):
+        self.assertRaises(AttributeError, lambda: bytes().sort())
+
+    def test_index(self):
+        b = b'parrot'
+        self.assertEqual(b.index('p'), 0)
+        self.assertEqual(b.index('rr'), 2)
+        self.assertEqual(b.index('t'), 5)
+        self.assertRaises(ValueError, lambda: b.index('w'))
+
+    def test_count(self):
+        b = b'mississippi'
+        self.assertEqual(b.count('i'), 4)
+        self.assertEqual(b.count('ss'), 2)
+        self.assertEqual(b.count('w'), 0)
+
+    def test_append(self):
+        b = b'hell'
+        b.append(ord('o'))
+        self.assertEqual(b, b'hello')
+        self.assertEqual(b.append(100), None)
+        b = bytes()
+        b.append(ord('A'))
+        self.assertEqual(len(b), 1)
+
+    def test_insert(self):
+        b = b'msssspp'
+        b.insert(1, ord('i'))
+        b.insert(4, ord('i'))
+        b.insert(-2, ord('i'))
+        b.insert(1000, ord('i'))
+        self.assertEqual(b, b'mississippi')
+
+    def test_startswith(self):
+        b = b'hello'
+        self.assertFalse(bytes().startswith("anything"))
+        self.assertTrue(b.startswith("hello"))
+        self.assertTrue(b.startswith("hel"))
+        self.assertTrue(b.startswith("h"))
+        self.assertFalse(b.startswith("hellow"))
+        self.assertFalse(b.startswith("ha"))
+
+    def test_endswith(self):
+        b = b'hello'
+        self.assertFalse(bytes().endswith("anything"))
+        self.assertTrue(b.endswith("hello"))
+        self.assertTrue(b.endswith("llo"))
+        self.assertTrue(b.endswith("o"))
+        self.assertFalse(b.endswith("whello"))
+        self.assertFalse(b.endswith("no"))
+
+    def test_find(self):
+        b = b'mississippi'
+        self.assertEqual(b.find('ss'), 2)
+        self.assertEqual(b.find('ss', 3), 5)
+        self.assertEqual(b.find('ss', 1, 7), 2)
+        self.assertEqual(b.find('ss', 1, 3), -1)
+        self.assertEqual(b.find('w'), -1)
+        self.assertEqual(b.find('mississippian'), -1)
+
+    def test_rfind(self):
+        b = b'mississippi'
+        self.assertEqual(b.rfind('ss'), 5)
+        self.assertEqual(b.rfind('ss', 3), 5)
+        self.assertEqual(b.rfind('ss', 0, 6), 2)
+        self.assertEqual(b.rfind('w'), -1)
+        self.assertEqual(b.rfind('mississippian'), -1)
+
+    def test_index(self):
+        b = b'world'
+        self.assertEqual(b.index('w'), 0)
+        self.assertEqual(b.index('orl'), 1)
+        self.assertRaises(ValueError, lambda: b.index('worm'))
+        self.assertRaises(ValueError, lambda: b.index('ldo'))
+
+    def test_rindex(self):
+        # XXX could be more rigorous
+        b = b'world'
+        self.assertEqual(b.rindex('w'), 0)
+        self.assertEqual(b.rindex('orl'), 1)
+        self.assertRaises(ValueError, lambda: b.rindex('worm'))
+        self.assertRaises(ValueError, lambda: b.rindex('ldo'))
+
+    def test_replace(self):
+        b = b'mississippi'
+        self.assertEqual(b.replace('i', 'a'), b'massassappa')
+        self.assertEqual(b.replace('ss', 'x'), b'mixixippi')
+
+    def test_translate(self):
+        b = b'hello'
+        rosetta = bytes(range(0, 256))
+        rosetta[ord('o')] = ord('e')
+        c = b.translate(rosetta, b'l')
+        self.assertEqual(b, b'hello')
+        self.assertEqual(c, b'hee')
+
+    def test_split(self):
+        b = b'mississippi'
+        self.assertEqual(b.split('i'), [b'm', b'ss', b'ss', b'pp', b''])
+        self.assertEqual(b.split('ss'), [b'mi', b'i', b'ippi'])
+        self.assertEqual(b.split('w'), [b])
+        # require an arg (no magic whitespace split)
+        self.assertRaises(TypeError, lambda: b.split())
+
+    def test_rsplit(self):
+        b = b'mississippi'
+        self.assertEqual(b.rsplit('i'), [b'm', b'ss', b'ss', b'pp', b''])
+        self.assertEqual(b.rsplit('ss'), [b'mi', b'i', b'ippi'])
+        self.assertEqual(b.rsplit('w'), [b])
+        # require an arg (no magic whitespace split)
+        self.assertRaises(TypeError, lambda: b.rsplit())
+
+    def test_partition(self):
+        b = b'mississippi'
+        self.assertEqual(b.partition(b'ss'), (b'mi', b'ss', b'issippi'))
+        self.assertEqual(b.rpartition(b'w'), (b'', b'', b'mississippi'))
+
+    def test_rpartition(self):
+        b = b'mississippi'
+        self.assertEqual(b.rpartition(b'ss'), (b'missi', b'ss', b'ippi'))
+        self.assertEqual(b.rpartition(b'i'), (b'mississipp', b'i', b''))
+
+    def test_pickling(self):
+        for pm in pickle, cPickle:
+            for proto in range(pm.HIGHEST_PROTOCOL):
+                for b in b"", b"a", b"abc", b"\xffab\x80", b"\0\0\377\0\0":
+                    ps = pm.dumps(b, proto)
+                    q = pm.loads(ps)
+                    self.assertEqual(b, q)
+
+    def test_strip(self):
+        b = b'mississippi'
+        self.assertEqual(b.strip(b'i'), b'mississipp')
+        self.assertEqual(b.strip(b'm'), b'ississippi')
+        self.assertEqual(b.strip(b'pi'), b'mississ')
+        self.assertEqual(b.strip(b'im'), b'ssissipp')
+        self.assertEqual(b.strip(b'pim'), b'ssiss')
+
+    def test_lstrip(self):
+        b = b'mississippi'
+        self.assertEqual(b.lstrip(b'i'), b'mississippi')
+        self.assertEqual(b.lstrip(b'm'), b'ississippi')
+        self.assertEqual(b.lstrip(b'pi'), b'mississippi')
+        self.assertEqual(b.lstrip(b'im'), b'ssissippi')
+        self.assertEqual(b.lstrip(b'pim'), b'ssissippi')
+
+    def test_rstrip(self):
+        b = b'mississippi'
+        self.assertEqual(b.rstrip(b'i'), b'mississipp')
+        self.assertEqual(b.rstrip(b'm'), b'mississippi')
+        self.assertEqual(b.rstrip(b'pi'), b'mississ')
+        self.assertEqual(b.rstrip(b'im'), b'mississipp')
+        self.assertEqual(b.rstrip(b'pim'), b'mississ')
 
     # Optimizations:
     # __iter__? (optimization)
     # __reversed__? (optimization)
 
-    # XXX Some list methods?
-    # extended slicing
-    # extended slice assignment
-    # extend (same as b[len(b):] = src)
-    # reverse (in-place)
-    # remove
-    # pop
-    # NOT sort!
-    # With int arg:
-    # index
-    # count
-    # append
-    # insert
-
-    # XXX Some string methods?  (Those that don't use character properties)
-    # startswith
-    # endswidth
-    # find, rfind
-    # index, rindex (bytes arg)
-    # join
-    # replace
-    # translate
-    # split, rsplit
-    # lstrip, rstrip, strip??
+    # XXX More string methods?  (Those that don't use character properties)
 
-    # XXX pickle and marshal support?
+    # There are tests in string_tests.py that are more
+    # comprehensive for things like split, partition, etc.
+    # Unfortunately they are all bundled with tests that
+    # are not appropriate for bytes
+
+
+class BytesAsStringTest(test.string_tests.BaseTest):
+    type2test = bytes
+
+    def checkequal(self, result, object, methodname, *args):
+        object = bytes(object)
+        realresult = getattr(bytes, methodname)(object, *args)
+        self.assertEqual(
+            self.fixtype(result),
+            realresult
+        )
+
+    def checkraises(self, exc, object, methodname, *args):
+        object = bytes(object)
+        self.assertRaises(
+            exc,
+            getattr(bytes, methodname),
+            object,
+            *args
+        )
+
+    # Currently the bytes containment testing uses a single integer
+    # value. This may not be the final design, but until then the
+    # bytes section with in a bytes containment not valid
+    def test_contains(self):
+        pass
+    def test_find(self):
+        pass
+    def test_expandtabs(self):
+        pass
+    def test_upper(self):
+        pass
+    def test_lower(self):
+        pass
 
 
 def test_main():
     test.test_support.run_unittest(BytesTest)
+    test.test_support.run_unittest(BytesAsStringTest)
 
 
 if __name__ == "__main__":

Modified: python/branches/p3yk-noslice/Lib/test/test_bz2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bz2.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_bz2.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,7 @@
 import unittest
 from cStringIO import StringIO
 import os
-import popen2
+import subprocess
 import sys
 
 import bz2
@@ -21,18 +21,20 @@
 
     if has_cmdline_bunzip2:
         def decompress(self, data):
-            pop = popen2.Popen3("bunzip2", capturestderr=1)
-            pop.tochild.write(data)
-            pop.tochild.close()
-            ret = pop.fromchild.read()
-            pop.fromchild.close()
+            pop = subprocess.Popen("bunzip2", shell=True,
+                                   stdin=subprocess.PIPE,
+                                   stdout=subprocess.PIPE,
+                                   stderr=subprocess.STDOUT)
+            pop.stdin.write(data)
+            pop.stdin.close()
+            ret = pop.stdout.read()
+            pop.stdout.close()
             if pop.wait() != 0:
                 ret = bz2.decompress(data)
             return ret
 
     else:
-        # popen2.Popen3 doesn't exist on Windows, and even if it did, bunzip2
-        # isn't available to run.
+        # bunzip2 isn't available to run on Windows.
         def decompress(self, data):
             return bz2.decompress(data)
 
@@ -230,7 +232,7 @@
     def testOpenDel(self):
         # "Test opening and deleting a file many times"
         self.createTempFile()
-        for i in xrange(10000):
+        for i in range(10000):
             o = BZ2File(self.filename)
             del o
 
@@ -243,7 +245,7 @@
         self.createTempFile()
         bz2f = BZ2File(self.filename, "U")
         bz2f.close()
-        f = open(self.filename)
+        f = open(self.filename, "rb")
         f.seek(0, 2)
         self.assertEqual(f.tell(), len(self.DATA))
         f.close()

Modified: python/branches/p3yk-noslice/Lib/test/test_calendar.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_calendar.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_calendar.py	Wed Jul 11 15:40:56 2007
@@ -260,7 +260,7 @@
     def check_weeks(self, year, month, weeks):
         cal = calendar.monthcalendar(year, month)
         self.assertEqual(len(cal), len(weeks))
-        for i in xrange(len(weeks)):
+        for i in range(len(weeks)):
             self.assertEqual(weeks[i], sum(day != 0 for day in cal[i]))
 
 

Deleted: /python/branches/p3yk-noslice/Lib/test/test_cd.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_cd.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,26 +0,0 @@
-#! /usr/bin/env python
-"""Whimpy test script for the cd module
-   Roger E. Masse
-"""
-import cd
-from test.test_support import verbose
-
-cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYING', 'READY',
-           'STILL', '__doc__', '__name__', 'atime', 'audio', 'catalog', 'control', 'createparser', 'error',
-           'ident', 'index', 'msftoframe', 'open', 'pnum', 'ptime']
-
-
-# This is a very inobtrusive test for the existence of the cd module and all its
-# attributes.  More comprehensive examples can be found in Demo/cd and
-# require that you have a CD and a CD ROM drive
-
-def main():
-    # touch all the attributes of cd without doing anything
-    if verbose:
-        print('Touching cd module attributes...')
-    for attr in cdattrs:
-        if verbose:
-            print('touching: ', attr)
-        getattr(cd, attr)
-
-main()

Modified: python/branches/p3yk-noslice/Lib/test/test_cfgparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cfgparser.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_cfgparser.py	Wed Jul 11 15:40:56 2007
@@ -417,6 +417,18 @@
         self.assertEqual(cf.get("section", "ok"), "xxx/%s")
         self.assertEqual(cf.get("section", "not_ok"), "xxx/xxx/%s")
 
+    def test_set_malformatted_interpolation(self):
+        cf = self.fromstring("[sect]\n"
+                             "option1=foo\n")
+
+        self.assertEqual(cf.get('sect', "option1"), "foo")
+
+        self.assertRaises(ValueError, cf.set, "sect", "option1", "%foo")
+        self.assertRaises(ValueError, cf.set, "sect", "option1", "foo%")
+        self.assertRaises(ValueError, cf.set, "sect", "option1", "f%oo")
+
+        self.assertEqual(cf.get('sect', "option1"), "foo")
+
     def test_set_nonstring_types(self):
         cf = self.fromstring("[sect]\n"
                              "option1=foo\n")

Modified: python/branches/p3yk-noslice/Lib/test/test_cgi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cgi.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_cgi.py	Wed Jul 11 15:40:56 2007
@@ -50,7 +50,7 @@
         raise ValueError, "unknown method: %s" % method
     try:
         return cgi.parse(fp, env, strict_parsing=1)
-    except StandardError as err:
+    except Exception as err:
         return ComparableException(err)
 
 # A list of test cases.  Each test case is a a two-tuple that contains
@@ -121,10 +121,11 @@
     return sorted(seq, key=repr)
 
 def first_elts(list):
-    return map(lambda x:x[0], list)
+    return [p[0] for p in list]
 
 def first_second_elts(list):
-    return map(lambda p:(p[0], p[1][0]), list)
+    return [(p[0], p[1][0]) for p in list]
+
 
 class CgiTests(unittest.TestCase):
 

Deleted: /python/branches/p3yk-noslice/Lib/test/test_cl.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_cl.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,78 +0,0 @@
-#! /usr/bin/env python
-"""Whimpy test script for the cl module
-   Roger E. Masse
-"""
-import cl
-from test.test_support import verbose
-
-clattrs = ['ADDED_ALGORITHM_ERROR', 'ALAW', 'ALGORITHM_ID',
-'ALGORITHM_VERSION', 'AUDIO', 'AWARE_ERROR', 'AWARE_MPEG_AUDIO',
-'AWARE_MULTIRATE', 'AWCMP_CONST_QUAL', 'AWCMP_FIXED_RATE',
-'AWCMP_INDEPENDENT', 'AWCMP_JOINT_STEREO', 'AWCMP_LOSSLESS',
-'AWCMP_MPEG_LAYER_I', 'AWCMP_MPEG_LAYER_II', 'AWCMP_STEREO',
-'Algorithm', 'AlgorithmNumber', 'AlgorithmType', 'AudioFormatName',
-'BAD_ALGORITHM_NAME', 'BAD_ALGORITHM_TYPE', 'BAD_BLOCK_SIZE',
-'BAD_BOARD', 'BAD_BUFFERING', 'BAD_BUFFERLENGTH_NEG',
-'BAD_BUFFERLENGTH_ODD', 'BAD_BUFFER_EXISTS', 'BAD_BUFFER_HANDLE',
-'BAD_BUFFER_POINTER', 'BAD_BUFFER_QUERY_SIZE', 'BAD_BUFFER_SIZE',
-'BAD_BUFFER_SIZE_POINTER', 'BAD_BUFFER_TYPE',
-'BAD_COMPRESSION_SCHEME', 'BAD_COMPRESSOR_HANDLE',
-'BAD_COMPRESSOR_HANDLE_POINTER', 'BAD_FRAME_SIZE',
-'BAD_FUNCTIONALITY', 'BAD_FUNCTION_POINTER', 'BAD_HEADER_SIZE',
-'BAD_INITIAL_VALUE', 'BAD_INTERNAL_FORMAT', 'BAD_LICENSE',
-'BAD_MIN_GT_MAX', 'BAD_NO_BUFFERSPACE', 'BAD_NUMBER_OF_BLOCKS',
-'BAD_PARAM', 'BAD_PARAM_ID_POINTER', 'BAD_PARAM_TYPE', 'BAD_POINTER',
-'BAD_PVBUFFER', 'BAD_SCHEME_POINTER', 'BAD_STREAM_HEADER',
-'BAD_STRING_POINTER', 'BAD_TEXT_STRING_PTR', 'BEST_FIT',
-'BIDIRECTIONAL', 'BITRATE_POLICY', 'BITRATE_TARGET',
-'BITS_PER_COMPONENT', 'BLENDING', 'BLOCK_SIZE', 'BOTTOM_UP',
-'BUFFER_NOT_CREATED', 'BUF_DATA', 'BUF_FRAME', 'BytesPerPixel',
-'BytesPerSample', 'CHANNEL_POLICY', 'CHROMA_THRESHOLD', 'CODEC',
-'COMPONENTS', 'COMPRESSED_BUFFER_SIZE', 'COMPRESSION_RATIO',
-'COMPRESSOR', 'CONTINUOUS_BLOCK', 'CONTINUOUS_NONBLOCK',
-'CompressImage', 'DATA', 'DECOMPRESSOR', 'DecompressImage',
-'EDGE_THRESHOLD', 'ENABLE_IMAGEINFO', 'END_OF_SEQUENCE', 'ENUM_VALUE',
-'EXACT_COMPRESSION_RATIO', 'EXTERNAL_DEVICE', 'FLOATING_ENUM_VALUE',
-'FLOATING_RANGE_VALUE', 'FRAME', 'FRAME_BUFFER_SIZE',
-'FRAME_BUFFER_SIZE_ZERO', 'FRAME_RATE', 'FRAME_TYPE', 'G711_ALAW',
-'G711_ULAW', 'GRAYSCALE', 'GetAlgorithmName', 'HDCC',
-'HDCC_SAMPLES_PER_TILE', 'HDCC_TILE_THRESHOLD', 'HEADER_START_CODE',
-'IMAGE_HEIGHT', 'IMAGE_WIDTH', 'INTERNAL_FORMAT',
-'INTERNAL_IMAGE_HEIGHT', 'INTERNAL_IMAGE_WIDTH', 'INTRA', 'JPEG',
-'JPEG_ERROR', 'JPEG_NUM_PARAMS', 'JPEG_QUALITY_FACTOR',
-'JPEG_QUANTIZATION_TABLES', 'JPEG_SOFTWARE', 'JPEG_STREAM_HEADERS',
-'KEYFRAME', 'LAST_FRAME_INDEX', 'LAYER', 'LUMA_THRESHOLD',
-'MAX_NUMBER_OF_AUDIO_ALGORITHMS', 'MAX_NUMBER_OF_ORIGINAL_FORMATS',
-'MAX_NUMBER_OF_PARAMS', 'MAX_NUMBER_OF_VIDEO_ALGORITHMS', 'MONO',
-'MPEG_VIDEO', 'MVC1', 'MVC2', 'MVC2_BLENDING', 'MVC2_BLENDING_OFF',
-'MVC2_BLENDING_ON', 'MVC2_CHROMA_THRESHOLD', 'MVC2_EDGE_THRESHOLD',
-'MVC2_ERROR', 'MVC2_LUMA_THRESHOLD', 'NEXT_NOT_AVAILABLE',
-'NOISE_MARGIN', 'NONE', 'NUMBER_OF_FRAMES', 'NUMBER_OF_PARAMS',
-'ORIENTATION', 'ORIGINAL_FORMAT', 'OpenCompressor',
-'OpenDecompressor', 'PARAM_OUT_OF_RANGE', 'PREDICTED', 'PREROLL',
-'ParamID', 'ParamNumber', 'ParamType', 'QUALITY_FACTOR',
-'QUALITY_LEVEL', 'QueryAlgorithms', 'QueryMaxHeaderSize',
-'QueryScheme', 'QuerySchemeFromName', 'RANGE_VALUE', 'RGB', 'RGB332',
-'RGB8', 'RGBA', 'RGBX', 'RLE', 'RLE24', 'RTR', 'RTR1',
-'RTR_QUALITY_LEVEL', 'SAMPLES_PER_TILE', 'SCHEME_BUSY',
-'SCHEME_NOT_AVAILABLE', 'SPEED', 'STEREO_INTERLEAVED',
-'STREAM_HEADERS', 'SetDefault', 'SetMax', 'SetMin', 'TILE_THRESHOLD',
-'TOP_DOWN', 'ULAW', 'UNCOMPRESSED', 'UNCOMPRESSED_AUDIO',
-'UNCOMPRESSED_VIDEO', 'UNKNOWN_SCHEME', 'VIDEO', 'VideoFormatName',
-'Y', 'YCbCr', 'YCbCr422', 'YCbCr422DC', 'YCbCr422HC', 'YUV', 'YUV422',
-'YUV422DC', 'YUV422HC', '__doc__', '__name__', 'cvt_type', 'error']
-
-
-# This is a very inobtrusive test for the existence of the cl
-# module and all its attributes.
-
-def main():
-    # touch all the attributes of al without doing anything
-    if verbose:
-        print('Touching cl module attributes...')
-    for attr in clattrs:
-        if verbose:
-            print('touching: ', attr)
-        getattr(cl, attr)
-
-main()

Modified: python/branches/p3yk-noslice/Lib/test/test_class.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_class.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_class.py	Wed Jul 11 15:40:56 2007
@@ -80,18 +80,14 @@
         print("__int__:", args)
         return 1
 
+    def __index__(self, *args):
+        print("__index__:", args)
+        return 1
+
     def __float__(self, *args):
         print("__float__:", args)
         return 1.0
 
-    def __oct__(self, *args):
-        print("__oct__:", args)
-        return '01'
-
-    def __hex__(self, *args):
-        print("__hex__:", args)
-        return '0x1'
-
     def __cmp__(self, *args):
         print("__cmp__:", args)
         return 0
@@ -237,7 +233,6 @@
 int(testme)
 float(testme)
 oct(testme)
-hex(testme)
 
 # And the rest...
 
@@ -287,8 +282,6 @@
     __float__ = __int__
     __str__ = __int__
     __repr__ = __int__
-    __oct__ = __int__
-    __hex__ = __int__
 
 def check_exc(stmt, exception):
     """Raise TestFailed if executing 'stmt' does not raise 'exception'

Modified: python/branches/p3yk-noslice/Lib/test/test_cmath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cmath.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_cmath.py	Wed Jul 11 15:40:56 2007
@@ -1,52 +1,196 @@
-#! /usr/bin/env python
-""" Simple test script for cmathmodule.c
-    Roger E. Masse
-"""
+from test.test_support import run_unittest
+import unittest
 import cmath, math
-from test.test_support import verbose, verify, TestFailed
 
-verify(abs(cmath.log(10) - math.log(10)) < 1e-9)
-verify(abs(cmath.log(10,2) - math.log(10,2)) < 1e-9)
-try:
-    cmath.log('a')
-except TypeError:
-    pass
-else:
-    raise TestFailed
-
-try:
-    cmath.log(10, 'a')
-except TypeError:
-    pass
-else:
-    raise TestFailed
-
-
-testdict = {'acos' : 1.0,
-            'acosh' : 1.0,
-            'asin' : 1.0,
-            'asinh' : 1.0,
-            'atan' : 0.2,
-            'atanh' : 0.2,
-            'cos' : 1.0,
-            'cosh' : 1.0,
-            'exp' : 1.0,
-            'log' : 1.0,
-            'log10' : 1.0,
-            'sin' : 1.0,
-            'sinh' : 1.0,
-            'sqrt' : 1.0,
-            'tan' : 1.0,
-            'tanh' : 1.0}
-
-for func in testdict.keys():
-    f = getattr(cmath, func)
-    r = f(testdict[func])
-    if verbose:
-        print('Calling %s(%f) = %f' % (func, testdict[func], abs(r)))
-
-p = cmath.pi
-e = cmath.e
-if verbose:
-    print('PI = ', abs(p))
-    print('E = ', abs(e))
+class CMathTests(unittest.TestCase):
+    # list of all functions in cmath
+    test_functions = [getattr(cmath, fname) for fname in [
+            'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh',
+            'cos', 'cosh', 'exp', 'log', 'log10', 'sin', 'sinh',
+            'sqrt', 'tan', 'tanh']]
+    # test first and second arguments independently for 2-argument log
+    test_functions.append(lambda x : cmath.log(x, 1729. + 0j))
+    test_functions.append(lambda x : cmath.log(14.-27j, x))
+
+    def cAssertAlmostEqual(self, a, b, rel_eps = 1e-10, abs_eps = 1e-100):
+        """Check that two complex numbers are almost equal."""
+        # the two complex numbers are considered almost equal if
+        # either the relative error is <= rel_eps or the absolute error
+        # is tiny, <= abs_eps.
+        if a == b == 0:
+            return
+        absolute_error = abs(a-b)
+        relative_error = absolute_error/max(abs(a), abs(b))
+        if relative_error > rel_eps and absolute_error > abs_eps:
+            self.fail("%s and %s are not almost equal" % (a, b))
+
+    def test_constants(self):
+        e_expected = 2.71828182845904523536
+        pi_expected = 3.14159265358979323846
+        self.assertAlmostEqual(cmath.pi, pi_expected, 9,
+            "cmath.pi is %s; should be %s" % (cmath.pi, pi_expected))
+        self.assertAlmostEqual(cmath.e,  e_expected, 9,
+            "cmath.e is %s; should be %s" % (cmath.e, e_expected))
+
+    def test_user_object(self):
+        # Test automatic calling of __complex__ and __float__ by cmath
+        # functions
+
+        # some random values to use as test values; we avoid values
+        # for which any of the functions in cmath is undefined
+        # (i.e. 0., 1., -1., 1j, -1j) or would cause overflow
+        cx_arg = 4.419414439 + 1.497100113j
+        flt_arg = -6.131677725
+
+        # a variety of non-complex numbers, used to check that
+        # non-complex return values from __complex__ give an error
+        non_complexes = ["not complex", 1, 5, 2., None,
+                         object(), NotImplemented]
+
+        # Now we introduce a variety of classes whose instances might
+        # end up being passed to the cmath functions
+
+        # usual case: new-style class implementing __complex__
+        class MyComplex(object):
+            def __init__(self, value):
+                self.value = value
+            def __complex__(self):
+                return self.value
+
+        # old-style class implementing __complex__
+        class MyComplexOS:
+            def __init__(self, value):
+                self.value = value
+            def __complex__(self):
+                return self.value
+
+        # classes for which __complex__ raises an exception
+        class SomeException(Exception):
+            pass
+        class MyComplexException(object):
+            def __complex__(self):
+                raise SomeException
+        class MyComplexExceptionOS:
+            def __complex__(self):
+                raise SomeException
+
+        # some classes not providing __float__ or __complex__
+        class NeitherComplexNorFloat(object):
+            pass
+        class NeitherComplexNorFloatOS:
+            pass
+        class MyInt(object):
+            def __int__(self): return 2
+            def __long__(self): return 2
+            def __index__(self): return 2
+        class MyIntOS:
+            def __int__(self): return 2
+            def __long__(self): return 2
+            def __index__(self): return 2
+
+        # other possible combinations of __float__ and __complex__
+        # that should work
+        class FloatAndComplex(object):
+            def __float__(self):
+                return flt_arg
+            def __complex__(self):
+                return cx_arg
+        class FloatAndComplexOS:
+            def __float__(self):
+                return flt_arg
+            def __complex__(self):
+                return cx_arg
+        class JustFloat(object):
+            def __float__(self):
+                return flt_arg
+        class JustFloatOS:
+            def __float__(self):
+                return flt_arg
+
+        for f in self.test_functions:
+            # usual usage
+            self.cAssertAlmostEqual(f(MyComplex(cx_arg)), f(cx_arg))
+            self.cAssertAlmostEqual(f(MyComplexOS(cx_arg)), f(cx_arg))
+            # other combinations of __float__ and __complex__
+            self.cAssertAlmostEqual(f(FloatAndComplex()), f(cx_arg))
+            self.cAssertAlmostEqual(f(FloatAndComplexOS()), f(cx_arg))
+            self.cAssertAlmostEqual(f(JustFloat()), f(flt_arg))
+            self.cAssertAlmostEqual(f(JustFloatOS()), f(flt_arg))
+            # TypeError should be raised for classes not providing
+            # either __complex__ or __float__, even if they provide
+            # __int__, __long__ or __index__.  An old-style class
+            # currently raises AttributeError instead of a TypeError;
+            # this could be considered a bug.
+            self.assertRaises(TypeError, f, NeitherComplexNorFloat())
+            self.assertRaises(TypeError, f, MyInt())
+            self.assertRaises(Exception, f, NeitherComplexNorFloatOS())
+            self.assertRaises(Exception, f, MyIntOS())
+            # non-complex return value from __complex__ -> TypeError
+            for bad_complex in non_complexes:
+                self.assertRaises(TypeError, f, MyComplex(bad_complex))
+                self.assertRaises(TypeError, f, MyComplexOS(bad_complex))
+            # exceptions in __complex__ should be propagated correctly
+            self.assertRaises(SomeException, f, MyComplexException())
+            self.assertRaises(SomeException, f, MyComplexExceptionOS())
+
+    def test_input_type(self):
+        # ints and longs should be acceptable inputs to all cmath
+        # functions, by virtue of providing a __float__ method
+        for f in self.test_functions:
+            for arg in [2, 2.]:
+                self.cAssertAlmostEqual(f(arg), f(arg.__float__()))
+
+        # but strings should give a TypeError
+        for f in self.test_functions:
+            for arg in ["a", "long_string", "0", "1j", ""]:
+                self.assertRaises(TypeError, f, arg)
+
+    def test_cmath_matches_math(self):
+        # check that corresponding cmath and math functions are equal
+        # for floats in the appropriate range
+
+        # test_values in (0, 1)
+        test_values = [0.01, 0.1, 0.2, 0.5, 0.9, 0.99]
+
+        # test_values for functions defined on [-1., 1.]
+        unit_interval = test_values + [-x for x in test_values] + \
+            [0., 1., -1.]
+
+        # test_values for log, log10, sqrt
+        positive = test_values + [1.] + [1./x for x in test_values]
+        nonnegative = [0.] + positive
+
+        # test_values for functions defined on the whole real line
+        real_line = [0.] + positive + [-x for x in positive]
+
+        test_functions = {
+            'acos' : unit_interval,
+            'asin' : unit_interval,
+            'atan' : real_line,
+            'cos' : real_line,
+            'cosh' : real_line,
+            'exp' : real_line,
+            'log' : positive,
+            'log10' : positive,
+            'sin' : real_line,
+            'sinh' : real_line,
+            'sqrt' : nonnegative,
+            'tan' : real_line,
+            'tanh' : real_line}
+
+        for fn, values in test_functions.items():
+            float_fn = getattr(math, fn)
+            complex_fn = getattr(cmath, fn)
+            for v in values:
+                self.cAssertAlmostEqual(float_fn(v), complex_fn(v))
+
+        # test two-argument version of log with various bases
+        for base in [0.5, 2., 10.]:
+            for v in positive:
+                self.cAssertAlmostEqual(cmath.log(v, base), math.log(v, base))
+
+def test_main():
+    run_unittest(CMathTests)
+
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_cmd_line.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cmd_line.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_cmd_line.py	Wed Jul 11 15:40:56 2007
@@ -1,18 +1,19 @@
 
 import test.test_support, unittest
 import sys
-import popen2
 import subprocess
 
 class CmdLineTest(unittest.TestCase):
     def start_python(self, cmd_line):
-        outfp, infp = popen2.popen4('%s %s' % (sys.executable, cmd_line))
-        infp.close()
-        data = outfp.read()
-        outfp.close()
+        cmd = '"%s" %s' % (sys.executable, cmd_line)
+        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+        p.stdin.close()
+        data = p.stdout.read()
+        p.stdout.close()
         # try to cleanup the child so we don't appear to leak when running
         # with regrtest -R.  This should be a no-op on Windows.
-        popen2._cleanup()
+        subprocess._cleanup()
         return data
 
     def exit_code(self, *args):

Modified: python/branches/p3yk-noslice/Lib/test/test_code.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_code.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_code.py	Wed Jul 11 15:40:56 2007
@@ -6,7 +6,7 @@
 ...     return g
 ...
 
->>> dump(f.func_code)
+>>> dump(f.__code__)
 name: f
 argcount: 1
 kwonlyargcount: 0
@@ -18,7 +18,7 @@
 flags: 3
 consts: ('None', '<code object g>')
 
->>> dump(f(4).func_code)
+>>> dump(f(4).__code__)
 name: g
 argcount: 1
 kwonlyargcount: 0
@@ -37,7 +37,7 @@
 ...     return c
 ...
 
->>> dump(h.func_code)
+>>> dump(h.__code__)
 name: h
 argcount: 2
 kwonlyargcount: 0
@@ -54,7 +54,7 @@
 ...     print(obj.attr2)
 ...     print(obj.attr3)
 
->>> dump(attrs.func_code)
+>>> dump(attrs.__code__)
 name: attrs
 argcount: 1
 kwonlyargcount: 0
@@ -72,7 +72,7 @@
 ...     53
 ...     0x53
 
->>> dump(optimize_away.func_code)
+>>> dump(optimize_away.__code__)
 name: optimize_away
 argcount: 0
 kwonlyargcount: 0
@@ -88,7 +88,7 @@
 ...     return a,b,k1
 ...
 
->>> dump(keywordonly_args.func_code)
+>>> dump(keywordonly_args.__code__)
 name: keywordonly_args
 argcount: 2
 kwonlyargcount: 1

Modified: python/branches/p3yk-noslice/Lib/test/test_codeccallbacks.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codeccallbacks.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codeccallbacks.py	Wed Jul 11 15:40:56 2007
@@ -234,7 +234,7 @@
             if not isinstance(exc, UnicodeEncodeError) \
                and not isinstance(exc, UnicodeDecodeError):
                 raise TypeError("don't know how to handle %r" % exc)
-            l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
+            l = [u"<%d>" % ord(exc.object[pos]) for pos in range(exc.start, exc.end)]
             return (u"[%s]" % u"".join(l), exc.end)
 
         codecs.register_error("test.handler1", handler1)
@@ -242,7 +242,7 @@
         def handler2(exc):
             if not isinstance(exc, UnicodeDecodeError):
                 raise TypeError("don't know how to handle %r" % exc)
-            l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
+            l = [u"<%d>" % ord(exc.object[pos]) for pos in range(exc.start, exc.end)]
             return (u"[%s]" % u"".join(l), exc.end+1) # skip one character
 
         codecs.register_error("test.handler2", handler2)
@@ -308,13 +308,13 @@
         self.assertRaises(TypeError, exctype, *(args + ["too much"]))
         # check with one argument of the wrong type
         wrongargs = [ "spam", u"eggs", 42, 1.0, None ]
-        for i in xrange(len(args)):
+        for i in range(len(args)):
             for wrongarg in wrongargs:
                 if type(wrongarg) is type(args[i]):
                     continue
                 # build argument array
                 callargs = []
-                for j in xrange(len(args)):
+                for j in range(len(args)):
                     if i==j:
                         callargs.append(wrongarg)
                     else:

Modified: python/branches/p3yk-noslice/Lib/test/test_codecencodings_cn.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecencodings_cn.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecencodings_cn.py	Wed Jul 11 15:40:56 2007
@@ -51,11 +51,7 @@
     has_iso10646 = True
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(Test_GB2312))
-    suite.addTest(unittest.makeSuite(Test_GBK))
-    suite.addTest(unittest.makeSuite(Test_GB18030))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecencodings_hk.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecencodings_hk.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecencodings_hk.py	Wed Jul 11 15:40:56 2007
@@ -21,9 +21,7 @@
     )
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(Test_Big5HKSCS))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecencodings_jp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecencodings_jp.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecencodings_jp.py	Wed Jul 11 15:40:56 2007
@@ -99,13 +99,7 @@
     )
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(Test_CP932))
-    suite.addTest(unittest.makeSuite(Test_EUC_JISX0213))
-    suite.addTest(unittest.makeSuite(Test_EUC_JP_COMPAT))
-    suite.addTest(unittest.makeSuite(Test_SJIS_COMPAT))
-    suite.addTest(unittest.makeSuite(Test_SJISX0213))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecencodings_kr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecencodings_kr.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecencodings_kr.py	Wed Jul 11 15:40:56 2007
@@ -45,11 +45,7 @@
     )
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(Test_CP949))
-    suite.addTest(unittest.makeSuite(Test_EUCKR))
-    suite.addTest(unittest.makeSuite(Test_JOHAB))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecencodings_tw.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecencodings_tw.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecencodings_tw.py	Wed Jul 11 15:40:56 2007
@@ -21,9 +21,7 @@
     )
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(Test_Big5))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecmaps_cn.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecmaps_cn.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecmaps_cn.py	Wed Jul 11 15:40:56 2007
@@ -20,10 +20,7 @@
                  'MICSFT/WINDOWS/CP936.TXT'
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(TestGB2312Map))
-    suite.addTest(unittest.makeSuite(TestGBKMap))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecmaps_hk.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecmaps_hk.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecmaps_hk.py	Wed Jul 11 15:40:56 2007
@@ -14,9 +14,7 @@
     mapfileurl = 'http://people.freebsd.org/~perky/i18n/BIG5HKSCS.TXT'
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(TestBig5HKSCSMap))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecmaps_jp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecmaps_jp.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecmaps_jp.py	Wed Jul 11 15:40:56 2007
@@ -61,13 +61,7 @@
 
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(TestCP932Map))
-    suite.addTest(unittest.makeSuite(TestEUCJPCOMPATMap))
-    suite.addTest(unittest.makeSuite(TestSJISCOMPATMap))
-    suite.addTest(unittest.makeSuite(TestEUCJISX0213Map))
-    suite.addTest(unittest.makeSuite(TestSJISX0213Map))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecmaps_kr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecmaps_kr.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecmaps_kr.py	Wed Jul 11 15:40:56 2007
@@ -34,11 +34,7 @@
     pass_dectest = [('\\', u'\u20a9')]
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(TestCP949Map))
-    suite.addTest(unittest.makeSuite(TestEUCKRMap))
-    suite.addTest(unittest.makeSuite(TestJOHABMap))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecmaps_tw.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecmaps_tw.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecmaps_tw.py	Wed Jul 11 15:40:56 2007
@@ -25,10 +25,7 @@
     ]
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(TestBIG5Map))
-    suite.addTest(unittest.makeSuite(TestCP950Map))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_codecs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecs.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecs.py	Wed Jul 11 15:40:56 2007
@@ -23,7 +23,40 @@
             self._buffer = self._buffer[size:]
             return s
 
-class ReadTest(unittest.TestCase):
+class MixInCheckStateHandling:
+    def check_state_handling_decode(self, encoding, u, s):
+        for i in range(len(s)+1):
+            d = codecs.getincrementaldecoder(encoding)()
+            part1 = d.decode(s[:i])
+            state = d.getstate()
+            self.assert_(isinstance(state[1], int))
+            # Check that the condition stated in the documentation for
+            # IncrementalDecoder.getstate() holds
+            if not state[1]:
+                # reset decoder to the default state without anything buffered
+                d.setstate((state[0][:0], 0))
+                # Feeding the previous input may not produce any output
+                self.assert_(not d.decode(state[0]))
+                # The decoder must return to the same state
+                self.assertEqual(state, d.getstate())
+            # Create a new decoder and set it to the state
+            # we extracted from the old one
+            d = codecs.getincrementaldecoder(encoding)()
+            d.setstate(state)
+            part2 = d.decode(s[i:], True)
+            self.assertEqual(u, part1+part2)
+
+    def check_state_handling_encode(self, encoding, u, s):
+        for i in range(len(u)+1):
+            d = codecs.getincrementalencoder(encoding)()
+            part1 = d.encode(u[:i])
+            state = d.getstate()
+            d = codecs.getincrementalencoder(encoding)()
+            d.setstate(state)
+            part2 = d.encode(u[i:], True)
+            self.assertEqual(s, part1+part2)
+
+class ReadTest(unittest.TestCase, MixInCheckStateHandling):
     def check_partial(self, input, partialresults):
         # get a StreamReader for the encoding and feed the bytestring version
         # of input to the reader byte by byte. Read every available from
@@ -102,17 +135,17 @@
 
         # Test lines where the first read might end with \r, so the
         # reader has to look ahead whether this is a lone \r or a \r\n
-        for size in xrange(80):
+        for size in range(80):
             for lineend in u"\n \r\n \r \u2028".split():
                 s = 10*(size*u"a" + lineend + u"xxx\n")
                 reader = getreader(s)
-                for i in xrange(10):
+                for i in range(10):
                     self.assertEqual(
                         reader.readline(keepends=True),
                         size*u"a" + lineend,
                     )
                 reader = getreader(s)
-                for i in xrange(10):
+                for i in range(10):
                     self.assertEqual(
                         reader.readline(keepends=False),
                         size*u"a",
@@ -292,7 +325,14 @@
         )
 
     def test_errors(self):
-        self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode, "\xff", "strict", True)
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode,
+                          "\xff", "strict", True)
+
+    def test_decoder_state(self):
+        self.check_state_handling_decode(self.encoding,
+                                         u"spamspam", self.spamle)
+        self.check_state_handling_decode(self.encoding,
+                                         u"spamspam", self.spambe)
 
 class UTF16LETest(ReadTest):
     encoding = "utf-16-le"
@@ -313,7 +353,8 @@
         )
 
     def test_errors(self):
-        self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode, "\xff", "strict", True)
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode,
+                          "\xff", "strict", True)
 
 class UTF16BETest(ReadTest):
     encoding = "utf-16-be"
@@ -334,7 +375,8 @@
         )
 
     def test_errors(self):
-        self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode, "\xff", "strict", True)
+        self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode,
+                          "\xff", "strict", True)
 
 class UTF8Test(ReadTest):
     encoding = "utf-8"
@@ -357,6 +399,11 @@
             ]
         )
 
+    def test_decoder_state(self):
+        u = u"\x00\x7f\x80\xff\u0100\u07ff\u0800\uffff\U0010ffff"
+        self.check_state_handling_decode(self.encoding,
+                                         u, u.encode(self.encoding))
+
 class UTF7Test(ReadTest):
     encoding = "utf-7"
 
@@ -429,6 +476,16 @@
         # SF bug #1601501: check that the codec works with a buffer
         unicode("\xef\xbb\xbf", "utf-8-sig")
 
+    def test_bom(self):
+        d = codecs.getincrementaldecoder("utf-8-sig")()
+        s = u"spam"
+        self.assertEqual(d.decode(s.encode("utf-8-sig")), s)
+
+    def test_decoder_state(self):
+        u = u"\x00\x7f\x80\xff\u0100\u07ff\u0800\uffff\U0010ffff"
+        self.check_state_handling_decode(self.encoding,
+                                         u, u.encode(self.encoding))
+
 class EscapeDecodeTest(unittest.TestCase):
     def test_empty(self):
         self.assertEquals(codecs.escape_decode(""), ("", 0))
@@ -1066,7 +1123,11 @@
     "punycode",
     "unicode_internal"
 ]
-broken_incremental_coders = broken_unicode_with_streams[:]
+broken_incremental_coders = broken_unicode_with_streams + [
+    "idna",
+    "zlib_codec",
+    "bz2_codec",
+]
 
 # The following encodings only support "strict" mode
 only_strict_mode = [
@@ -1091,7 +1152,7 @@
     all_unicode_encodings.append("zlib_codec")
     broken_unicode_with_streams.append("zlib_codec")
 
-class BasicUnicodeTest(unittest.TestCase):
+class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
     def test_basics(self):
         s = u"abc123" # all codecs should be able to encode these
         for encoding in all_unicode_encodings:
@@ -1191,7 +1252,7 @@
             if encoding in broken_unicode_with_streams:
                 continue
             reader = codecs.getreader(encoding)(StringIO.StringIO(s.encode(encoding)))
-            for t in xrange(5):
+            for t in range(5):
                 # Test that calling seek resets the internal codec state and buffers
                 reader.seek(0, 0)
                 line = reader.readline()
@@ -1215,6 +1276,14 @@
         table_type = type(cp1140.encoding_table)
         self.assertEqual(table_type, table_type)
 
+    def test_decoder_state(self):
+        # Check that getstate() and setstate() handle the state properly
+        u = u"abc123"
+        for encoding in all_unicode_encodings:
+            if encoding not in broken_incremental_coders:
+                self.check_state_handling_decode(encoding, u, u.encode(encoding))
+                self.check_state_handling_encode(encoding, u, u.encode(encoding))
+
 class BasicStrTest(unittest.TestCase):
     def test_basics(self):
         s = "abc123"
@@ -1251,7 +1320,7 @@
             (u"ab", 3)
         )
 
-        allbytes = "".join(chr(i) for i in xrange(256))
+        allbytes = "".join(chr(i) for i in range(256))
         self.assertEquals(
             codecs.charmap_decode(allbytes, "ignore", u""),
             (u"", len(allbytes))

Modified: python/branches/p3yk-noslice/Lib/test/test_codeop.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codeop.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_codeop.py	Wed Jul 11 15:40:56 2007
@@ -13,8 +13,8 @@
 
     def unify_callables(d):
         for n,v in d.items():
-            if callable(v):
-                d[n] = callable
+            if hasattr(v, '__call__'):
+                d[n] = True
         return d
 
 class CodeopTests(unittest.TestCase):

Modified: python/branches/p3yk-noslice/Lib/test/test_commands.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_commands.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_commands.py	Wed Jul 11 15:40:56 2007
@@ -38,28 +38,10 @@
             if dir is not None:
                 os.rmdir(dir)
 
-    def test_getstatus(self):
-        # This pattern should match 'ls -ld /.' on any posix
-        # system, however perversely configured.  Even on systems
-        # (e.g., Cygwin) where user and group names can have spaces:
-        #     drwxr-xr-x   15 Administ Domain U     4096 Aug 12 12:50 /
-        #     drwxr-xr-x   15 Joe User My Group     4096 Aug 12 12:50 /
-        # Note that the first case above has a space in the group name
-        # while the second one has a space in both names.
-        pat = r'''d.........   # It is a directory.
-                  \+?          # It may have ACLs.
-                  \s+\d+       # It has some number of links.
-                  [^/]*        # Skip user, group, size, and date.
-                  /\.          # and end with the name of the file.
-               '''
-
-        self.assert_(re.match(pat, getstatus("/."), re.VERBOSE))
-
 
 def test_main():
     run_unittest(CommandTests)
     reap_children()
 
-
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_compare.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_compare.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_compare.py	Wed Jul 11 15:40:56 2007
@@ -39,6 +39,12 @@
                 self.assertEqual(a == b, id(a) == id(b),
                                  'a=%r, b=%r' % (a, b))
 
+    def test_ne_defaults_to_not_eq(self):
+        a = Cmp(1)
+        b = Cmp(1)
+        self.assertTrue(a == b)
+        self.assertFalse(a != b)
+
 def test_main():
     test_support.run_unittest(ComparisonTest)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_compile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_compile.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_compile.py	Wed Jul 11 15:40:56 2007
@@ -36,6 +36,9 @@
     def test_syntax_error(self):
         self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
 
+    def test_none_keyword_arg(self):
+        self.assertRaises(SyntaxError, compile, "f(None=1)", "<string>", "exec")
+
     def test_duplicate_global_local(self):
         try:
             exec('def f(a): global a; a = 1')
@@ -124,29 +127,9 @@
         exec(code, g)
         self.assertEqual(g['f'](5), 0)
 
-    def test_complex_args(self):
-
-        def comp_args((a, b)):
-            return a,b
-        self.assertEqual(comp_args((1, 2)), (1, 2))
-
-        def comp_args((a, b)=(3, 4)):
-            return a, b
-        self.assertEqual(comp_args((1, 2)), (1, 2))
-        self.assertEqual(comp_args(), (3, 4))
-
-        def comp_args(a, (b, c)):
-            return a, b, c
-        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
-
-        def comp_args(a=2, (b, c)=(3, 4)):
-            return a, b, c
-        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
-        self.assertEqual(comp_args(), (2, 3, 4))
-
     def test_argument_order(self):
         try:
-            exec('def f(a=1, (b, c)): pass')
+            exec('def f(a=1, b): pass')
             self.fail("non-default args after default")
         except SyntaxError:
             pass
@@ -178,21 +161,22 @@
 
     def test_literals_with_leading_zeroes(self):
         for arg in ["077787", "0xj", "0x.", "0e",  "090000000000000",
-                    "080000000000000", "000000000000009", "000000000000008"]:
+                    "080000000000000", "000000000000009", "000000000000008",
+                    "0b42", "0BADCAFE", "0o123456789", "0b1.1", "0o4.2",
+                    "0b101j2", "0o153j2", "0b100e1", "0o777e1", "0777",
+                    "000777", "000000000000007"]:
             self.assertRaises(SyntaxError, eval, arg)
 
-        self.assertEqual(eval("0777"), 511)
-        self.assertEqual(eval("000777"), 511)
         self.assertEqual(eval("0xff"), 255)
-        self.assertEqual(eval("0XfF"), 255)
         self.assertEqual(eval("0777."), 777)
         self.assertEqual(eval("0777.0"), 777)
         self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
         self.assertEqual(eval("0777e1"), 7770)
         self.assertEqual(eval("0e0"), 0)
-        self.assertEqual(eval("0000E-012"), 0)
+        self.assertEqual(eval("0000e-012"), 0)
         self.assertEqual(eval("09.5"), 9.5)
         self.assertEqual(eval("0777j"), 777j)
+        self.assertEqual(eval("000"), 0)
         self.assertEqual(eval("00j"), 0j)
         self.assertEqual(eval("00.0"), 0)
         self.assertEqual(eval("0e3"), 0)
@@ -201,9 +185,12 @@
         self.assertEqual(eval("090000000000000e0"), 90000000000000.)
         self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
         self.assertEqual(eval("090000000000000j"), 90000000000000j)
-        self.assertEqual(eval("000000000000007"), 7)
         self.assertEqual(eval("000000000000008."), 8.)
         self.assertEqual(eval("000000000000009."), 9.)
+        self.assertEqual(eval("0b101010"), 42)
+        self.assertEqual(eval("-0b000000000010"), -2)
+        self.assertEqual(eval("0o777"), 511)
+        self.assertEqual(eval("-0o0000010"), -8)
 
     def test_unary_minus(self):
         # Verify treatment of unary minus on negative numbers SF bug #660455
@@ -235,7 +222,7 @@
             g = +9223372036854775807  # 1 << 63 - 1
             h = -9223372036854775807  # 1 << 63 - 1
 
-            for variable in self.test_32_63_bit_values.func_code.co_consts:
+            for variable in self.test_32_63_bit_values.__code__.co_consts:
                 if variable is not None:
                     self.assertTrue(isinstance(variable, int))
 
@@ -315,7 +302,7 @@
             f2 = lambda x=2: x
             return f1, f2
         f1, f2 = f()
-        self.assertNotEqual(id(f1.func_code), id(f2.func_code))
+        self.assertNotEqual(id(f1.__code__), id(f2.__code__))
 
     def test_unicode_encoding(self):
         code = u"# -*- coding: utf-8 -*-\npass\n"
@@ -393,6 +380,32 @@
         del d[..., ...]
         self.assertEqual((Ellipsis, Ellipsis) in d, False)
 
+    def test_annotation_limit(self):
+        # 16 bits are available for # of annotations, but only 8 bits are
+        # available for the parameter count, hence 255
+        # is the max. Ensure the result of too many annotations is a
+        # SyntaxError.
+        s = "def f(%s): pass"
+        s %= ', '.join('a%d:%d' % (i,i) for i in range(256))
+        self.assertRaises(SyntaxError, compile, s, '?', 'exec')
+        # Test that the max # of annotations compiles.
+        s = "def f(%s): pass"
+        s %= ', '.join('a%d:%d' % (i,i) for i in range(255))
+        compile(s, '?', 'exec')
+
+    def test_mangling(self):
+        class A:
+            def f():
+                __mangled = 1
+                __not_mangled__ = 2
+                import __mangled_mod
+                import __package__.module
+
+        self.assert_("_A__mangled" in A.f.__code__.co_varnames)
+        self.assert_("__not_mangled__" in A.f.__code__.co_varnames)
+        self.assert_("_A__mangled_mod" in A.f.__code__.co_varnames)
+        self.assert_("__package__" in A.f.__code__.co_varnames)
+
 def test_main():
     test_support.run_unittest(TestSpecifics)
 

Deleted: /python/branches/p3yk-noslice/Lib/test/test_compiler.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_compiler.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,242 +0,0 @@
-import compiler
-from compiler.ast import flatten
-import os, sys, time, unittest
-import test.test_support
-from random import random
-
-# How much time in seconds can pass before we print a 'Still working' message.
-_PRINT_WORKING_MSG_INTERVAL = 5 * 60
-
-class TrivialContext(object):
-    def __enter__(self):
-        return self
-    def __exit__(self, *exc_info):
-        pass
-
-class CompilerTest(unittest.TestCase):
-
-    def testCompileLibrary(self):
-        # A simple but large test.  Compile all the code in the
-        # standard library and its test suite.  This doesn't verify
-        # that any of the code is correct, merely the compiler is able
-        # to generate some kind of code for it.
-
-        next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
-        libdir = os.path.dirname(unittest.__file__)
-        testdir = os.path.dirname(test.test_support.__file__)
-
-        for dir in [libdir, testdir]:
-            for basename in os.listdir(dir):
-                # Print still working message since this test can be really slow
-                if next_time <= time.time():
-                    next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
-                    print('  testCompileLibrary still working, be patient...', file=sys.__stdout__)
-                    sys.__stdout__.flush()
-
-                if not basename.endswith(".py"):
-                    continue
-                if not TEST_ALL and random() < 0.98:
-                    continue
-                path = os.path.join(dir, basename)
-                if test.test_support.verbose:
-                    print("compiling", path)
-                f = open(path, "U")
-                buf = f.read()
-                f.close()
-                if "badsyntax" in basename or "bad_coding" in basename:
-                    self.assertRaises(SyntaxError, compiler.compile,
-                                      buf, basename, "exec")
-                else:
-                    try:
-                        compiler.compile(buf, basename, "exec")
-                    except Exception as e:
-                        args = list(e.args)
-                        args[0] += "[in file %s]" % basename
-                        e.args = tuple(args)
-                        raise
-
-    def testNewClassSyntax(self):
-        compiler.compile("class foo():pass\n\n","<string>","exec")
-
-    def testYieldExpr(self):
-        compiler.compile("def g(): yield\n\n", "<string>", "exec")
-
-    def testTryExceptFinally(self):
-        # Test that except and finally clauses in one try stmt are recognized
-        c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
-                             "<string>", "exec")
-        dct = {}
-        exec(c, dct)
-        self.assertEquals(dct.get('e'), 1)
-        self.assertEquals(dct.get('f'), 1)
-
-    def testDefaultArgs(self):
-        self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")
-
-    def testDocstrings(self):
-        c = compiler.compile('"doc"', '<string>', 'exec')
-        self.assert_('__doc__' in c.co_names)
-        c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
-        g = {}
-        exec(c, g)
-        self.assertEquals(g['f'].__doc__, "doc")
-
-    def testLineNo(self):
-        # Test that all nodes except Module have a correct lineno attribute.
-        filename = __file__
-        if filename.endswith((".pyc", ".pyo")):
-            filename = filename[:-1]
-        tree = compiler.parseFile(filename)
-        self.check_lineno(tree)
-
-    def check_lineno(self, node):
-        try:
-            self._check_lineno(node)
-        except AssertionError:
-            print(node.__class__, node.lineno)
-            raise
-
-    def _check_lineno(self, node):
-        if not node.__class__ in NOLINENO:
-            self.assert_(isinstance(node.lineno, int),
-                "lineno=%s on %s" % (node.lineno, node.__class__))
-            self.assert_(node.lineno > 0,
-                "lineno=%s on %s" % (node.lineno, node.__class__))
-        for child in node.getChildNodes():
-            self.check_lineno(child)
-
-    def testFlatten(self):
-        self.assertEquals(flatten([1, [2]]), [1, 2])
-        self.assertEquals(flatten((1, (2,))), [1, 2])
-
-    def testNestedScope(self):
-        c = compiler.compile('def g():\n'
-                             '    a = 1\n'
-                             '    def f(): return a + 2\n'
-                             '    return f()\n'
-                             'result = g()',
-                             '<string>',
-                             'exec')
-        dct = {}
-        exec(c, dct)
-        self.assertEquals(dct.get('result'), 3)
-        c = compiler.compile('def g(a):\n'
-                             '    def f(): return a + 2\n'
-                             '    return f()\n'
-                             'result = g(1)',
-                             '<string>',
-                             'exec')
-        dct = {}
-        exec(c, dct)
-        self.assertEquals(dct.get('result'), 3)
-        c = compiler.compile('def g((a, b)):\n'
-                             '    def f(): return a + b\n'
-                             '    return f()\n'
-                             'result = g((1, 2))',
-                             '<string>',
-                             'exec')
-        dct = {}
-        exec(c, dct)
-        self.assertEquals(dct.get('result'), 3)
-
-    def testGenExp(self):
-        c = compiler.compile('list((i,j) for i in range(3) if i < 3'
-                             '           for j in range(4) if j > 2)',
-                             '<string>',
-                             'eval')
-        self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)])
-
-    def testFuncAnnotations(self):
-        testdata = [
-            ('def f(a: 1): pass', {'a': 1}),
-            ('''def f(a, (b:1, c:2, d), e:3=4, f=5,
-                    *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass
-             ''', {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
-                   'k': 11, 'return': 12}),
-        ]
-        for sourcecode, expected in testdata:
-            # avoid IndentationError: unexpected indent from trailing lines
-            sourcecode = sourcecode.rstrip()+'\n'
-            c = compiler.compile(sourcecode, '<string>', 'exec')
-            dct = {}
-            exec(c, dct)
-            self.assertEquals(dct['f'].func_annotations, expected)
-
-    def testWith(self):
-        # SF bug 1638243
-        c = compiler.compile('from __future__ import with_statement\n'
-                             'def f():\n'
-                             '    with TrivialContext():\n'
-                             '        return 1\n'
-                             'result = f()',
-                             '<string>',
-                             'exec' )
-        dct = {'TrivialContext': TrivialContext}
-        exec(c, dct)
-        self.assertEquals(dct.get('result'), 1)
-
-    def testWithAss(self):
-        c = compiler.compile('from __future__ import with_statement\n'
-                             'def f():\n'
-                             '    with TrivialContext() as tc:\n'
-                             '        return 1\n'
-                             'result = f()',
-                             '<string>',
-                             'exec' )
-        dct = {'TrivialContext': TrivialContext}
-        exec(c, dct)
-        self.assertEquals(dct.get('result'), 1)
-
-
-NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard,
-            compiler.ast.Const)
-
-###############################################################################
-# code below is just used to trigger some possible errors, for the benefit of
-# testLineNo
-###############################################################################
-
-class Toto:
-    """docstring"""
-    pass
-
-a, b = 2, 3
-[c, d] = 5, 6
-l = [(x, y) for x, y in zip(range(5), range(5,10))]
-l[0]
-l[3:4]
-d = {'a': 2}
-d = {}
-t = ()
-t = (1, 2)
-l = []
-l = [1, 2]
-if l:
-    pass
-else:
-    a, b = b, a
-
-try:
-    print(yo)
-except:
-    yo = 3
-else:
-    yo += 3
-
-try:
-    a += b
-finally:
-    b = 0
-
-from math import *
-
-###############################################################################
-
-def test_main(all=False):
-    global TEST_ALL
-    TEST_ALL = all or test.test_support.is_resource_enabled("compiler")
-    test.test_support.run_unittest(CompilerTest)
-
-if __name__ == "__main__":
-    import sys
-    test_main('all' in sys.argv)

Modified: python/branches/p3yk-noslice/Lib/test/test_complex.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_complex.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_complex.py	Wed Jul 11 15:40:56 2007
@@ -64,7 +64,7 @@
             self.assertClose(q, x)
 
     def test_truediv(self):
-        simple_real = [float(i) for i in xrange(-5, 6)]
+        simple_real = [float(i) for i in range(-5, 6)]
         simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
         for x in simple_complex:
             for y in simple_complex:
@@ -76,7 +76,7 @@
         self.check_div(complex(1e-200, 1e-200), 1+0j)
 
         # Just for fun.
-        for i in xrange(100):
+        for i in range(100):
             self.check_div(complex(random(), random()),
                            complex(random(), random()))
 
@@ -158,7 +158,7 @@
         self.assertRaises(ValueError, pow, a, b, 0)
 
     def test_boolcontext(self):
-        for i in xrange(100):
+        for i in range(100):
             self.assert_(complex(random() + 1e-6, random() + 1e-6))
         self.assert_(not complex(0.0, 0.0))
 
@@ -208,6 +208,8 @@
         self.assertAlmostEqual(complex(),  0)
         self.assertAlmostEqual(complex("-1"), -1)
         self.assertAlmostEqual(complex("+1"), +1)
+        self.assertAlmostEqual(complex("(1+2j)"), 1+2j)
+        self.assertAlmostEqual(complex("(1.3+2.2j)"), 1.3+2.2j)
 
         class complex2(complex): pass
         self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j)
@@ -237,12 +239,17 @@
         self.assertRaises(ValueError, complex, "")
         self.assertRaises(TypeError, complex, None)
         self.assertRaises(ValueError, complex, "\0")
+        self.assertRaises(ValueError, complex, "3\09")
         self.assertRaises(TypeError, complex, "1", "2")
         self.assertRaises(TypeError, complex, "1", 42)
         self.assertRaises(TypeError, complex, 1, "2")
         self.assertRaises(ValueError, complex, "1+")
         self.assertRaises(ValueError, complex, "1+1j+1j")
         self.assertRaises(ValueError, complex, "--")
+        self.assertRaises(ValueError, complex, "(1+2j")
+        self.assertRaises(ValueError, complex, "1+2j)")
+        self.assertRaises(ValueError, complex, "1+(2j)")
+        self.assertRaises(ValueError, complex, "(1+2j)123")
         if test_support.have_unicode:
             self.assertRaises(ValueError, complex, unicode("1"*500))
             self.assertRaises(ValueError, complex, unicode("x"))
@@ -289,13 +296,13 @@
         self.assertRaises(TypeError, complex, complex2(1j))
 
     def test_hash(self):
-        for x in xrange(-30, 30):
+        for x in range(-30, 30):
             self.assertEqual(hash(x), hash(complex(x, 0)))
             x /= 3.0    # now check against floating point
             self.assertEqual(hash(x), hash(complex(x, 0.)))
 
     def test_abs(self):
-        nums = [complex(x/3., y/7.) for x in xrange(-9,9) for y in xrange(-9,9)]
+        nums = [complex(x/3., y/7.) for x in range(-9,9) for y in range(-9,9)]
         for num in nums:
             self.assertAlmostEqual((num.real**2 + num.imag**2)  ** 0.5, abs(num))
 
@@ -305,6 +312,11 @@
 
         self.assertNotEqual(repr(-(1+0j)), '(-1+-0j)')
 
+        self.assertEqual(1-6j,complex(repr(1-6j)))
+        self.assertEqual(1+6j,complex(repr(1+6j)))
+        self.assertEqual(-6j,complex(repr(-6j)))
+        self.assertEqual(6j,complex(repr(6j)))
+
     def test_neg(self):
         self.assertEqual(-(1+6j), -1-6j)
 

Deleted: /python/branches/p3yk-noslice/Lib/test/test_complex_args.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_complex_args.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,91 +0,0 @@
-
-import unittest
-from test import test_support
-
-class ComplexArgsTestCase(unittest.TestCase):
-
-    def check(self, func, expected, *args):
-        self.assertEqual(func(*args), expected)
-
-    # These functions are tested below as lambdas too.  If you add a function test,
-    # also add a similar lambda test.
-
-    def test_func_parens_no_unpacking(self):
-        def f(((((x))))): return x
-        self.check(f, 1, 1)
-        # Inner parens are elided, same as: f(x,)
-        def f(((x)),): return x
-        self.check(f, 2, 2)
-
-    def test_func_1(self):
-        def f(((((x),)))): return x
-        self.check(f, 3, (3,))
-        def f(((((x)),))): return x
-        self.check(f, 4, (4,))
-        def f(((((x))),)): return x
-        self.check(f, 5, (5,))
-        def f(((x),)): return x
-        self.check(f, 6, (6,))
-
-    def test_func_2(self):
-        def f(((((x)),),)): return x
-        self.check(f, 2, ((2,),))
-
-    def test_func_3(self):
-        def f((((((x)),),),)): return x
-        self.check(f, 3, (((3,),),))
-
-    def test_func_complex(self):
-        def f((((((x)),),),), a, b, c): return x, a, b, c
-        self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
-
-        def f(((((((x)),)),),), a, b, c): return x, a, b, c
-        self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
-
-        def f(a, b, c, ((((((x)),)),),)): return a, b, c, x
-        self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),))
-
-    # Duplicate the tests above, but for lambda.  If you add a lambda test,
-    # also add a similar function test above.
-
-    def test_lambda_parens_no_unpacking(self):
-        f = lambda (((((x))))): x
-        self.check(f, 1, 1)
-        # Inner parens are elided, same as: f(x,)
-        f = lambda ((x)),: x
-        self.check(f, 2, 2)
-
-    def test_lambda_1(self):
-        f = lambda (((((x),)))): x
-        self.check(f, 3, (3,))
-        f = lambda (((((x)),))): x
-        self.check(f, 4, (4,))
-        f = lambda (((((x))),)): x
-        self.check(f, 5, (5,))
-        f = lambda (((x),)): x
-        self.check(f, 6, (6,))
-
-    def test_lambda_2(self):
-        f = lambda (((((x)),),)): x
-        self.check(f, 2, ((2,),))
-
-    def test_lambda_3(self):
-        f = lambda ((((((x)),),),)): x
-        self.check(f, 3, (((3,),),))
-
-    def test_lambda_complex(self):
-        f = lambda (((((x)),),),), a, b, c: (x, a, b, c)
-        self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
-
-        f = lambda ((((((x)),)),),), a, b, c: (x, a, b, c)
-        self.check(f, (3, 9, 8, 7), (((3,),),), 9, 8, 7)
-
-        f = lambda a, b, c, ((((((x)),)),),): (a, b, c, x)
-        self.check(f, (9, 8, 7, 3), 9, 8, 7, (((3,),),))
-
-
-def test_main():
-    test_support.run_unittest(ComplexArgsTestCase)
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_contains.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_contains.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_contains.py	Wed Jul 11 15:40:56 2007
@@ -86,7 +86,7 @@
     check(unicode('d') not in 'abc', "u'd' in 'abc'")
 
 # A collection of tests on builtin sequence types
-a = range(10)
+a = list(range(10))
 for i in a:
     check(i in a, "%r not in %r" % (i, a))
 check(16 not in a, "16 not in %r" % (a,))
@@ -105,7 +105,7 @@
     works when the list is modified during the check.
     """
 
-    aList = range(15)
+    aList = list(range(15))
 
     def __cmp__(self, other):
         if other == 12:

Modified: python/branches/p3yk-noslice/Lib/test/test_contextlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_contextlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_contextlib.py	Wed Jul 11 15:40:56 2007
@@ -9,7 +9,7 @@
 import unittest
 import threading
 from contextlib import *  # Tests __all__
-from test.test_support import run_suite
+from test import test_support
 
 class ContextManagerTestCase(unittest.TestCase):
 
@@ -332,9 +332,7 @@
 
 # This is needed to make the test actually run under regrtest.py!
 def test_main():
-    run_suite(
-        unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])
-    )
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_copy.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_copy.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_copy.py	Wed Jul 11 15:40:56 2007
@@ -83,8 +83,8 @@
         def f():
             pass
         tests = [None, 42, 2**100, 3.14, True, False, 1j,
-                 "hello", u"hello\u1234", f.func_code,
-                 NewStyle, xrange(10), Classic, max]
+                 "hello", u"hello\u1234", f.__code__,
+                 NewStyle, range(10), Classic, max]
         for x in tests:
             self.assert_(copy.copy(x) is x, repr(x))
 
@@ -191,8 +191,8 @@
         # type.
         class Meta(type):
             pass
-        class C:
-            __metaclass__ = Meta
+        class C(metaclass=Meta):
+            pass
         self.assertEqual(copy.deepcopy(C), C)
 
     def test_deepcopy_deepcopy(self):
@@ -256,8 +256,8 @@
         def f():
             pass
         tests = [None, 42, 2**100, 3.14, True, False, 1j,
-                 "hello", u"hello\u1234", f.func_code,
-                 NewStyle, xrange(10), Classic, max]
+                 "hello", u"hello\u1234", f.__code__,
+                 NewStyle, range(10), Classic, max]
         for x in tests:
             self.assert_(copy.deepcopy(x) is x, repr(x))
 

Modified: python/branches/p3yk-noslice/Lib/test/test_crypt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_crypt.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_crypt.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,7 @@
    Roger E. Masse
 """
 
-from test.test_support import verify, verbose
+from test.test_support import verbose
 import crypt
 
 c = crypt.crypt('mypassword', 'ab')

Modified: python/branches/p3yk-noslice/Lib/test/test_csv.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_csv.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_csv.py	Wed Jul 11 15:40:56 2007
@@ -53,8 +53,8 @@
         self.assertEqual(obj.dialect.skipinitialspace, False)
         self.assertEqual(obj.dialect.strict, False)
         # Try deleting or changing attributes (they are read-only)
-        self.assertRaises(TypeError, delattr, obj.dialect, 'delimiter')
-        self.assertRaises(TypeError, setattr, obj.dialect, 'delimiter', ':')
+        self.assertRaises(AttributeError, delattr, obj.dialect, 'delimiter')
+        self.assertRaises(AttributeError, setattr, obj.dialect, 'delimiter', ':')
         self.assertRaises(AttributeError, delattr, obj.dialect, 'quoting')
         self.assertRaises(AttributeError, setattr, obj.dialect,
                           'quoting', None)
@@ -271,13 +271,13 @@
     def test_read_linenum(self):
         r = csv.reader(['line,1', 'line,2', 'line,3'])
         self.assertEqual(r.line_num, 0)
-        r.next()
+        next(r)
         self.assertEqual(r.line_num, 1)
-        r.next()
+        next(r)
         self.assertEqual(r.line_num, 2)
-        r.next()
+        next(r)
         self.assertEqual(r.line_num, 3)
-        self.assertRaises(StopIteration, r.next)
+        self.assertRaises(StopIteration, next, r)
         self.assertEqual(r.line_num, 3)
 
 class TestDialectRegistry(unittest.TestCase):
@@ -338,9 +338,9 @@
         try:
             fileobj.write("abc def\nc1ccccc1 benzene\n")
             fileobj.seek(0)
-            rdr = csv.reader(fileobj, dialect=space())
-            self.assertEqual(rdr.next(), ["abc", "def"])
-            self.assertEqual(rdr.next(), ["c1ccccc1", "benzene"])
+            reader = csv.reader(fileobj, dialect=space())
+            self.assertEqual(next(reader), ["abc", "def"])
+            self.assertEqual(next(reader), ["c1ccccc1", "benzene"])
         finally:
             fileobj.close()
             os.unlink(name)
@@ -484,12 +484,16 @@
         self.readerAssertEqual('a"b"c', [['a"b"c']])
 
     def test_quotes_and_more(self):
+        # Excel would never write a field containing '"a"b', but when
+        # reading one, it will return 'ab'.
         self.readerAssertEqual('"a"b', [['ab']])
 
     def test_lone_quote(self):
         self.readerAssertEqual('a"b', [['a"b']])
 
     def test_quote_and_quote(self):
+        # Excel would never write a field containing '"a" "b"', but when
+        # reading one, it will return 'a "b"'.
         self.readerAssertEqual('"a" "b"', [['a "b"']])
 
     def test_space_and_quote(self):
@@ -593,7 +597,7 @@
             fileobj.seek(0)
             reader = csv.DictReader(fileobj,
                                     fieldnames=["f1", "f2", "f3"])
-            self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'})
+            self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
         finally:
             fileobj.close()
             os.unlink(name)
@@ -605,7 +609,7 @@
             fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
             fileobj.seek(0)
             reader = csv.DictReader(fileobj)
-            self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'})
+            self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
         finally:
             fileobj.close()
             os.unlink(name)
@@ -618,7 +622,7 @@
             fileobj.seek(0)
             reader = csv.DictReader(fileobj,
                                     fieldnames=["f1", "f2"])
-            self.assertEqual(reader.next(), {"f1": '1', "f2": '2',
+            self.assertEqual(next(reader), {"f1": '1', "f2": '2',
                                              None: ["abc", "4", "5", "6"]})
         finally:
             fileobj.close()
@@ -632,7 +636,7 @@
             fileobj.seek(0)
             reader = csv.DictReader(fileobj,
                                     fieldnames=["f1", "f2"], restkey="_rest")
-            self.assertEqual(reader.next(), {"f1": '1', "f2": '2',
+            self.assertEqual(next(reader), {"f1": '1', "f2": '2',
                                              "_rest": ["abc", "4", "5", "6"]})
         finally:
             fileobj.close()
@@ -645,7 +649,7 @@
             fileobj.write("f1,f2\r\n1,2,abc,4,5,6\r\n")
             fileobj.seek(0)
             reader = csv.DictReader(fileobj, restkey="_rest")
-            self.assertEqual(reader.next(), {"f1": '1', "f2": '2',
+            self.assertEqual(next(reader), {"f1": '1', "f2": '2',
                                              "_rest": ["abc", "4", "5", "6"]})
         finally:
             fileobj.close()
@@ -660,9 +664,9 @@
             reader = csv.DictReader(fileobj,
                                     fieldnames="1 2 3 4 5 6".split(),
                                     restval="DEFAULT")
-            self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
+            self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
                                              "4": '4', "5": '5', "6": '6'})
-            self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
+            self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
                                              "4": 'DEFAULT', "5": 'DEFAULT',
                                              "6": 'DEFAULT'})
         finally:
@@ -678,7 +682,7 @@
 
         reader = csv.DictReader(sample,
                                 fieldnames="i1 float i2 s1 s2".split())
-        self.assertEqual(reader.next(), {"i1": '2147483648',
+        self.assertEqual(next(reader), {"i1": '2147483648',
                                          "float": '43.0e12',
                                          "i2": '17',
                                          "s1": 'abc',
@@ -688,16 +692,16 @@
         reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n",
                                  "1,2,abc,4,5,6\r\n"],
                                 fieldnames="1 2 3 4 5 6".split())
-        self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
+        self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
                                          "4": '4', "5": '5', "6": '6'})
-        self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
+        self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
                                          "4": '4', "5": '5', "6": '6'})
 
     def test_read_semi_sep(self):
         reader = csv.DictReader(["1;2;abc;4;5;6\r\n"],
                                 fieldnames="1 2 3 4 5 6".split(),
                                 delimiter=';')
-        self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
+        self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
                                          "4": '4', "5": '5', "6": '6'})
 
 class TestArrayWrites(unittest.TestCase):
@@ -905,7 +909,7 @@
         def test_create_read(self):
             delta = 0
             lastrc = sys.gettotalrefcount()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
@@ -921,7 +925,7 @@
             delta = 0
             lastrc = sys.gettotalrefcount()
             s = NUL()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
@@ -937,7 +941,7 @@
             delta = 0
             rows = ["a,b,c\r\n"]*5
             lastrc = sys.gettotalrefcount()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()
@@ -954,7 +958,7 @@
             rows = [[1,2,3]]*5
             s = NUL()
             lastrc = sys.gettotalrefcount()
-            for i in xrange(20):
+            for i in range(20):
                 gc.collect()
                 self.assertEqual(gc.garbage, [])
                 rc = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_ctypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ctypes.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_ctypes.py	Wed Jul 11 15:40:56 2007
@@ -1,12 +1,12 @@
 import unittest
 
-from test.test_support import run_suite
+from test.test_support import run_unittest
 import ctypes.test
 
 def test_main():
     skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
     suites = [unittest.makeSuite(t) for t in testcases]
-    run_suite(unittest.TestSuite(suites))
+    run_unittest(unittest.TestSuite(suites))
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_curses.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_curses.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_curses.py	Wed Jul 11 15:40:56 2007
@@ -129,6 +129,12 @@
     stdscr.touchline(5,5,0)
     stdscr.vline('a', 3)
     stdscr.vline('a', 3, curses.A_STANDOUT)
+    stdscr.chgat(5, 2, 3, curses.A_BLINK)
+    stdscr.chgat(3, curses.A_BOLD)
+    stdscr.chgat(5, 8, curses.A_UNDERLINE)
+    stdscr.chgat(curses.A_BLINK)
+    stdscr.refresh()
+
     stdscr.vline(1,1, 'a', 3)
     stdscr.vline(1,1, 'a', 3, curses.A_STANDOUT)
 
@@ -241,12 +247,21 @@
     except curses.panel.error:
         pass
 
+def test_resize_term(stdscr):
+    if hasattr(curses, 'resizeterm'):
+        lines, cols = curses.LINES, curses.COLS
+        curses.resizeterm(lines - 1, cols + 1)
+
+        if curses.LINES != lines - 1 or curses.COLS != cols + 1:
+            raise RuntimeError, "Expected resizeterm to update LINES and COLS"
+
 def main(stdscr):
     curses.savetty()
     try:
         module_funcs(stdscr)
         window_funcs(stdscr)
         test_userptr_without_set(stdscr)
+        test_resize_term(stdscr)
     finally:
         curses.resetty()
 

Modified: python/branches/p3yk-noslice/Lib/test/test_datetime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_datetime.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_datetime.py	Wed Jul 11 15:40:56 2007
@@ -3,6 +3,7 @@
 See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
 """
 
+import os
 import sys
 import pickle
 import unittest
@@ -20,9 +21,9 @@
 from datetime import date, datetime
 
 pickle_choices = [(pickler, unpickler, proto)
-                  for pickler in pickle, cPickle
+                  for pickler in (pickle, cPickle)
                   if pickler is not None
-                  for unpickler in pickle, cPickle
+                  for unpickler in (pickle, cPickle)
                   if unpickler is not None
                   for proto in range(3)]
 if cPickle is None:
@@ -135,7 +136,7 @@
 # Base clase for testing a particular aspect of timedelta, time, date and
 # datetime comparisons.
 
-class HarmlessMixedComparison(unittest.TestCase):
+class HarmlessMixedComparison:
     # Test that __eq__ and __ne__ don't complain for mixed-type comparisons.
 
     # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a
@@ -174,7 +175,7 @@
 #############################################################################
 # timedelta tests
 
-class TestTimeDelta(HarmlessMixedComparison):
+class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
 
     theclass = timedelta
 
@@ -521,7 +522,7 @@
 class SubclassDate(date):
     sub_var = 1
 
-class TestDate(HarmlessMixedComparison):
+class TestDate(HarmlessMixedComparison, unittest.TestCase):
     # Tests here should pass for both dates and datetimes, except for a
     # few tests that TestDateTime overrides.
 
@@ -568,7 +569,7 @@
 
         # Check first and last days of year spottily across the whole
         # range of years supported.
-        for year in xrange(MINYEAR, MAXYEAR+1, 7):
+        for year in range(MINYEAR, MAXYEAR+1, 7):
             # Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
             d = self.theclass(year, 1, 1)
             n = d.toordinal()
@@ -829,8 +830,7 @@
             320  348  376
             325  353  381
         """
-        iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split())
-        iso_long_years.sort()
+        iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split()))
         L = []
         for i in range(400):
             d = self.theclass(2000+i, 12, 31)
@@ -1452,6 +1452,21 @@
             self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
                               insane)
 
+    def test_negative_float_fromtimestamp(self):
+        # Windows doesn't accept negative timestamps
+        if os.name == "nt":
+            return
+        # The result is tz-dependent; at least test that this doesn't
+        # fail (like it did before bug 1646728 was fixed).
+        self.theclass.fromtimestamp(-1.05)
+
+    def test_negative_float_utcfromtimestamp(self):
+        # Windows doesn't accept negative timestamps
+        if os.name == "nt":
+            return
+        d = self.theclass.utcfromtimestamp(-1.05)
+        self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
+
     def test_utcnow(self):
         import time
 
@@ -1607,7 +1622,7 @@
 class SubclassTime(time):
     sub_var = 1
 
-class TestTime(HarmlessMixedComparison):
+class TestTime(HarmlessMixedComparison, unittest.TestCase):
 
     theclass = time
 
@@ -1890,7 +1905,7 @@
 # A mixin for classes with a tzinfo= argument.  Subclasses must define
 # theclass as a class atribute, and theclass(1, 1, 1, tzinfo=whatever)
 # must be legit (which is true for time and datetime).
-class TZInfoBase(unittest.TestCase):
+class TZInfoBase:
 
     def test_argument_passing(self):
         cls = self.theclass
@@ -2050,7 +2065,7 @@
 
 
 # Testing time objects with a non-None tzinfo.
-class TestTimeTZ(TestTime, TZInfoBase):
+class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
     theclass = time
 
     def test_empty(self):
@@ -2298,7 +2313,7 @@
 
 # Testing datetime objects with a non-None tzinfo.
 
-class TestDateTimeTZ(TestDateTime, TZInfoBase):
+class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
     theclass = datetime
 
     def test_trivial(self):
@@ -3259,45 +3274,8 @@
         self.assertEqual(as_datetime, datetime_sc)
         self.assertEqual(datetime_sc, as_datetime)
 
-def test_suite():
-    allsuites = [unittest.makeSuite(klass, 'test')
-                 for klass in (TestModule,
-                               TestTZInfo,
-                               TestTimeDelta,
-                               TestDateOnly,
-                               TestDate,
-                               TestDateTime,
-                               TestTime,
-                               TestTimeTZ,
-                               TestDateTimeTZ,
-                               TestTimezoneConversions,
-                               Oddballs,
-                              )
-                ]
-    return unittest.TestSuite(allsuites)
-
 def test_main():
-    import gc
-    import sys
-
-    thesuite = test_suite()
-    lastrc = None
-    while True:
-        test_support.run_suite(thesuite)
-        if 1:       # change to 0, under a debug build, for some leak detection
-            break
-        gc.collect()
-        if gc.garbage:
-            raise SystemError("gc.garbage not empty after test run: %r" %
-                              gc.garbage)
-        if hasattr(sys, 'gettotalrefcount'):
-            thisrc = sys.gettotalrefcount()
-            print('*' * 10, 'total refs:', thisrc, end=' ', file=sys.stderr)
-            if lastrc:
-                print('delta:', thisrc - lastrc, file=sys.stderr)
-            else:
-                print(file=sys.stderr)
-            lastrc = thisrc
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_dbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dbm.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_dbm.py	Wed Jul 11 15:40:56 2007
@@ -17,7 +17,7 @@
         try:
             os.unlink(filename + suffix)
         except OSError as e:
-            (errno, strerror) = e
+            (errno, strerror) = e.errno, e.strerror
             # if we can't delete the file because of permissions,
             # nothing will work, so skip the test
             if errno == 1:

Modified: python/branches/p3yk-noslice/Lib/test/test_decimal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_decimal.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_decimal.py	Wed Jul 11 15:40:56 2007
@@ -39,7 +39,7 @@
     threading = None
 
 # Useful Test Constant
-Signals = getcontext().flags.keys()
+Signals = tuple(getcontext().flags.keys())
 
 # Tests are built around these assumed context defaults.
 # test_main() restores the original context.
@@ -171,7 +171,7 @@
             return self.eval_equation(s)
 
     def eval_directive(self, s):
-        funct, value = map(lambda x: x.strip().lower(), s.split(':'))
+        funct, value = (x.strip().lower() for x in s.split(':'))
         if funct == 'rounding':
             value = RoundingDict[value]
         else:
@@ -842,7 +842,7 @@
         self.assertNotEqual(da, object)
 
         # sortable
-        a = map(Decimal, xrange(100))
+        a = list(map(Decimal, range(100)))
         b =  a[:]
         random.shuffle(a)
         a.sort()

Modified: python/branches/p3yk-noslice/Lib/test/test_decorators.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_decorators.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_decorators.py	Wed Jul 11 15:40:56 2007
@@ -27,7 +27,7 @@
 def dbcheck(exprstr, globals=None, locals=None):
     "Decorator to implement debugging assertions"
     def decorate(func):
-        expr = compile(exprstr, "dbcheck-%s" % func.func_name, "eval")
+        expr = compile(exprstr, "dbcheck-%s" % func.__name__, "eval")
         def check(*args, **kwds):
             if not eval(expr, globals, locals):
                 raise DbcheckError(exprstr, func, args, kwds)
@@ -40,12 +40,12 @@
 def countcalls(counts):
     "Decorator to count calls to a function"
     def decorate(func):
-        func_name = func.func_name
+        func_name = func.__name__
         counts[func_name] = 0
         def call(*args, **kwds):
             counts[func_name] += 1
             return func(*args, **kwds)
-        call.func_name = func_name
+        call.__name__ = func_name
         return call
     return decorate
 
@@ -63,7 +63,7 @@
         except TypeError:
             # Unhashable argument
             return func(*args)
-    call.func_name = func.func_name
+    call.__name__ = func.__name__
     return call
 
 # -----------------------------------------------
@@ -131,7 +131,7 @@
         @countcalls(counts)
         def double(x):
             return x * 2
-        self.assertEqual(double.func_name, 'double')
+        self.assertEqual(double.__name__, 'double')
 
         self.assertEqual(counts, dict(double=0))
 
@@ -266,8 +266,44 @@
         self.assertEqual(bar(), 42)
         self.assertEqual(actions, expected_actions)
 
+class TestClassDecorators(unittest.TestCase):
+
+    def test_simple(self):
+        def plain(x):
+            x.extra = 'Hello'
+            return x
+        @plain
+        class C(object): pass
+        self.assertEqual(C.extra, 'Hello')
+
+    def test_double(self):
+        def ten(x):
+            x.extra = 10
+            return x
+        def add_five(x):
+            x.extra += 5
+            return x
+
+        @add_five
+        @ten
+        class C(object): pass
+        self.assertEqual(C.extra, 15)
+
+    def test_order(self):
+        def applied_first(x):
+            x.extra = 'first'
+            return x
+        def applied_second(x):
+            x.extra = 'second'
+            return x
+        @applied_second
+        @applied_first
+        class C(object): pass
+        self.assertEqual(C.extra, 'second')
+
 def test_main():
     test_support.run_unittest(TestDecorators)
+    test_support.run_unittest(TestClassDecorators)
 
 if __name__=="__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_defaultdict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_defaultdict.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_defaultdict.py	Wed Jul 11 15:40:56 2007
@@ -132,6 +132,15 @@
         self.assertEqual(d2.default_factory, list)
         self.assertEqual(d2, d1)
 
+    def test_keyerror_without_factory(self):
+        d1 = defaultdict()
+        try:
+            d1[(1,)]
+        except KeyError as err:
+            self.assertEqual(err.args[0], (1,))
+        else:
+            self.fail("expected KeyError")
+
 
 def test_main():
     test_support.run_unittest(TestDefaultDict)

Modified: python/branches/p3yk-noslice/Lib/test/test_deque.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_deque.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_deque.py	Wed Jul 11 15:40:56 2007
@@ -29,23 +29,23 @@
 class TestBasic(unittest.TestCase):
 
     def test_basics(self):
-        d = deque(xrange(100))
-        d.__init__(xrange(100, 200))
-        for i in xrange(200, 400):
+        d = deque(range(100))
+        d.__init__(range(100, 200))
+        for i in range(200, 400):
             d.append(i)
-        for i in reversed(xrange(-200, 0)):
+        for i in reversed(range(-200, 0)):
             d.appendleft(i)
-        self.assertEqual(list(d), range(-200, 400))
+        self.assertEqual(list(d), list(range(-200, 400)))
         self.assertEqual(len(d), 600)
 
-        left = [d.popleft() for i in xrange(250)]
-        self.assertEqual(left, range(-200, 50))
-        self.assertEqual(list(d), range(50, 400))
+        left = [d.popleft() for i in range(250)]
+        self.assertEqual(left, list(range(-200, 50)))
+        self.assertEqual(list(d), list(range(50, 400)))
 
-        right = [d.pop() for i in xrange(250)]
+        right = [d.pop() for i in range(250)]
         right.reverse()
-        self.assertEqual(right, range(150, 400))
-        self.assertEqual(list(d), range(50, 150))
+        self.assertEqual(right, list(range(150, 400)))
+        self.assertEqual(list(d), list(range(50, 150)))
 
     def test_comparisons(self):
         d = deque('xabc'); d.popleft()
@@ -82,15 +82,15 @@
 
     def test_getitem(self):
         n = 200
-        d = deque(xrange(n))
-        l = range(n)
-        for i in xrange(n):
+        d = deque(range(n))
+        l = list(range(n))
+        for i in range(n):
             d.popleft()
             l.pop(0)
             if random.random() < 0.5:
                 d.append(i)
                 l.append(i)
-            for j in xrange(1-len(l), len(l)):
+            for j in range(1-len(l), len(l)):
                 assert d[j] == l[j]
 
         d = deque('superman')
@@ -102,22 +102,22 @@
 
     def test_setitem(self):
         n = 200
-        d = deque(xrange(n))
-        for i in xrange(n):
+        d = deque(range(n))
+        for i in range(n):
             d[i] = 10 * i
-        self.assertEqual(list(d), [10*i for i in xrange(n)])
+        self.assertEqual(list(d), [10*i for i in range(n)])
         l = list(d)
-        for i in xrange(1-n, 0, -1):
+        for i in range(1-n, 0, -1):
             d[i] = 7*i
             l[i] = 7*i
         self.assertEqual(list(d), l)
 
     def test_delitem(self):
         n = 500         # O(n**2) test, don't make this too big
-        d = deque(xrange(n))
+        d = deque(range(n))
         self.assertRaises(IndexError, d.__delitem__, -n-1)
         self.assertRaises(IndexError, d.__delitem__, n)
-        for i in xrange(n):
+        for i in range(n):
             self.assertEqual(len(d), n-i)
             j = random.randrange(-len(d), len(d))
             val = d[j]
@@ -140,11 +140,11 @@
         d.rotate()              # check default to 1
         self.assertEqual(tuple(d), s)
 
-        for i in xrange(n*3):
+        for i in range(n*3):
             d = deque(s)
             e = deque(d)
             d.rotate(i)         # check vs. rot(1) n times
-            for j in xrange(i):
+            for j in range(i):
                 e.rotate(1)
             self.assertEqual(tuple(d), tuple(e))
             d.rotate(-i)        # check that it works in reverse
@@ -152,11 +152,11 @@
             e.rotate(n-i)       # check that it wraps forward
             self.assertEqual(tuple(e), s)
 
-        for i in xrange(n*3):
+        for i in range(n*3):
             d = deque(s)
             e = deque(d)
             d.rotate(-i)
-            for j in xrange(i):
+            for j in range(i):
                 e.rotate(-1)    # check vs. rot(-1) n times
             self.assertEqual(tuple(d), tuple(e))
             d.rotate(i)         # check that it works in reverse
@@ -168,7 +168,7 @@
         e = deque(s)
         e.rotate(BIG+17)        # verify on long series of rotates
         dr = d.rotate
-        for i in xrange(BIG+17):
+        for i in range(BIG+17):
             dr()
         self.assertEqual(tuple(d), tuple(e))
 
@@ -201,7 +201,7 @@
         self.assertRaises(IndexError, d.popleft)
 
     def test_clear(self):
-        d = deque(xrange(100))
+        d = deque(range(100))
         self.assertEqual(len(d), 100)
         d.clear()
         self.assertEqual(len(d), 0)
@@ -234,14 +234,14 @@
             self.assertEqual(d, deque())
 
     def test_repr(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         e = eval(repr(d))
         self.assertEqual(list(d), list(e))
         d.append(d)
         self.assert_('...' in repr(d))
 
     def test_print(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         d.append(d)
         try:
             fo = open(test_support.TESTFN, "wb")
@@ -262,33 +262,34 @@
 
     def test_long_steadystate_queue_popleft(self):
         for size in (0, 1, 2, 100, 1000):
-            d = deque(xrange(size))
+            d = deque(range(size))
             append, pop = d.append, d.popleft
-            for i in xrange(size, BIG):
+            for i in range(size, BIG):
                 append(i)
                 x = pop()
                 if x != i - size:
                     self.assertEqual(x, i-size)
-            self.assertEqual(list(d), range(BIG-size, BIG))
+            self.assertEqual(list(d), list(range(BIG-size, BIG)))
 
     def test_long_steadystate_queue_popright(self):
         for size in (0, 1, 2, 100, 1000):
-            d = deque(reversed(xrange(size)))
+            d = deque(reversed(range(size)))
             append, pop = d.appendleft, d.pop
-            for i in xrange(size, BIG):
+            for i in range(size, BIG):
                 append(i)
                 x = pop()
                 if x != i - size:
                     self.assertEqual(x, i-size)
-            self.assertEqual(list(reversed(list(d))), range(BIG-size, BIG))
+            self.assertEqual(list(reversed(list(d))),
+                             list(range(BIG-size, BIG)))
 
     def test_big_queue_popleft(self):
         pass
         d = deque()
         append, pop = d.append, d.popleft
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in xrange(BIG):
+        for i in range(BIG):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
@@ -296,9 +297,9 @@
     def test_big_queue_popright(self):
         d = deque()
         append, pop = d.appendleft, d.pop
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in xrange(BIG):
+        for i in range(BIG):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
@@ -306,9 +307,9 @@
     def test_big_stack_right(self):
         d = deque()
         append, pop = d.append, d.pop
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in reversed(xrange(BIG)):
+        for i in reversed(range(BIG)):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
@@ -317,22 +318,22 @@
     def test_big_stack_left(self):
         d = deque()
         append, pop = d.appendleft, d.popleft
-        for i in xrange(BIG):
+        for i in range(BIG):
             append(i)
-        for i in reversed(xrange(BIG)):
+        for i in reversed(range(BIG)):
             x = pop()
             if x != i:
                 self.assertEqual(x, i)
         self.assertEqual(len(d), 0)
 
     def test_roundtrip_iter_init(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         e = deque(d)
         self.assertNotEqual(id(d), id(e))
         self.assertEqual(list(d), list(e))
 
     def test_pickle(self):
-        d = deque(xrange(200))
+        d = deque(range(200))
         for i in (0, 1, 2):
             s = pickle.dumps(d, i)
             e = pickle.loads(s)
@@ -366,7 +367,7 @@
         self.assertEqual(list(d), list(e))
 
     def test_reversed(self):
-        for s in ('abcd', xrange(2000)):
+        for s in ('abcd', range(2000)):
             self.assertEqual(list(reversed(deque(s))), list(reversed(s)))
 
     def test_gc_doesnt_blowup(self):
@@ -374,14 +375,14 @@
         # This used to assert-fail in deque_traverse() under a debug
         # build, or run wild with a NULL pointer in a release build.
         d = deque()
-        for i in xrange(100):
+        for i in range(100):
             d.append(1)
             gc.collect()
 
 class TestVariousIteratorArgs(unittest.TestCase):
 
     def test_constructor(self):
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (seq_tests.Sequence, seq_tests.IterFunc,
                       seq_tests.IterGen, seq_tests.IterFuncStop,
                       seq_tests.itermulti, seq_tests.iterfunc):
@@ -394,13 +395,13 @@
         d = deque('abcdefg')
         it = iter(d)
         d.pop()
-        self.assertRaises(RuntimeError, it.next)
+        self.assertRaises(RuntimeError, next, it)
 
     def test_runtime_error_on_empty_deque(self):
         d = deque()
         it = iter(d)
         d.append(10)
-        self.assertRaises(RuntimeError, it.next)
+        self.assertRaises(RuntimeError, next, it)
 
 class Deque(deque):
     pass
@@ -412,23 +413,23 @@
 class TestSubclass(unittest.TestCase):
 
     def test_basics(self):
-        d = Deque(xrange(100))
-        d.__init__(xrange(100, 200))
-        for i in xrange(200, 400):
+        d = Deque(range(100))
+        d.__init__(range(100, 200))
+        for i in range(200, 400):
             d.append(i)
-        for i in reversed(xrange(-200, 0)):
+        for i in reversed(range(-200, 0)):
             d.appendleft(i)
-        self.assertEqual(list(d), range(-200, 400))
+        self.assertEqual(list(d), list(range(-200, 400)))
         self.assertEqual(len(d), 600)
 
-        left = [d.popleft() for i in xrange(250)]
-        self.assertEqual(left, range(-200, 50))
-        self.assertEqual(list(d), range(50, 400))
+        left = [d.popleft() for i in range(250)]
+        self.assertEqual(left, list(range(-200, 50)))
+        self.assertEqual(list(d), list(range(50, 400)))
 
-        right = [d.pop() for i in xrange(250)]
+        right = [d.pop() for i in range(250)]
         right.reverse()
-        self.assertEqual(right, range(150, 400))
-        self.assertEqual(list(d), range(50, 150))
+        self.assertEqual(right, list(range(150, 400)))
+        self.assertEqual(list(d), list(range(50, 150)))
 
         d.clear()
         self.assertEqual(len(d), 0)
@@ -567,7 +568,7 @@
 ...     while pending:
 ...         task = pending.popleft()
 ...         try:
-...             yield task.next()
+...             yield next(task)
 ...         except StopIteration:
 ...             continue
 ...         pending.append(task)
@@ -575,7 +576,7 @@
 
 >>> for value in roundrobin('abc', 'd', 'efgh'):
 ...     print(value)
-... 
+...
 a
 d
 e
@@ -618,7 +619,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_descr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_descr.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_descr.py	Wed Jul 11 15:40:56 2007
@@ -3,6 +3,7 @@
 from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout
 from copy import deepcopy
 import warnings
+import types
 
 warnings.filterwarnings("ignore",
          r'complex divmod\(\), // and % are deprecated$',
@@ -616,9 +617,8 @@
     vereq(a[100:200], (100,200))
 
 def metaclass():
-    if verbose: print("Testing __metaclass__...")
-    class C:
-        __metaclass__ = type
+    if verbose: print("Testing metaclass...")
+    class C(metaclass=type):
         def __init__(self):
             self.__state = 0
         def getstate(self):
@@ -629,9 +629,10 @@
     vereq(a.getstate(), 0)
     a.setstate(10)
     vereq(a.getstate(), 10)
-    class D:
-        class __metaclass__(type):
-            def myself(cls): return cls
+    class _metaclass(type):
+        def myself(cls): return cls
+    class D(metaclass=_metaclass):
+        pass
     vereq(D.myself(), D)
     d = D()
     verify(d.__class__ is D)
@@ -639,8 +640,8 @@
         def __new__(cls, name, bases, dict):
             dict['__spam__'] = 1
             return type.__new__(cls, name, bases, dict)
-    class C:
-        __metaclass__ = M1
+    class C(metaclass=M1):
+        pass
     vereq(C.__spam__, 1)
     c = C()
     vereq(c.__spam__, 1)
@@ -663,8 +664,7 @@
                     continue
                 setattr(it, key, self.dict[key].__get__(it, self))
             return it
-    class C:
-        __metaclass__ = M2
+    class C(metaclass=M2):
         def spam(self):
             return 42
     vereq(C.name, 'C')
@@ -690,8 +690,7 @@
                 name = "__super"
             setattr(cls, name, super(cls))
             return cls
-    class A:
-        __metaclass__ = autosuper
+    class A(metaclass=autosuper):
         def meth(self):
             return "A"
     class B(A):
@@ -729,8 +728,7 @@
                 dict[key] = property(get, set)
             return super(autoproperty, metaclass).__new__(metaclass,
                                                         name, bases, dict)
-    class A:
-        __metaclass__ = autoproperty
+    class A(metaclass=autoproperty):
         def _get_x(self):
             return -self.__x
         def _set_x(self, x):
@@ -744,8 +742,7 @@
     class multimetaclass(autoproperty, autosuper):
         # Merge of multiple cooperating metaclasses
         pass
-    class A:
-        __metaclass__ = multimetaclass
+    class A(metaclass=multimetaclass):
         def _get_x(self):
             return "A"
     class B(A):
@@ -764,8 +761,8 @@
         counter = 0
         def __init__(self, *args):
             T.counter += 1
-    class C:
-        __metaclass__ = T
+    class C(metaclass=T):
+        pass
     vereq(T.counter, 1)
     a = C()
     vereq(type(a), C)
@@ -777,6 +774,22 @@
     except TypeError: pass
     else: raise TestFailed, "calling object w/o call method should raise TypeError"
 
+    # Testing code to find most derived baseclass
+    class A(type):
+        def __new__(*args, **kwargs):
+            return type.__new__(*args, **kwargs)
+
+    class B(object):
+        pass
+
+    class C(object, metaclass=A):
+        pass
+
+    # The most derived metaclass of D is A rather than type.
+    class D(B, C):
+        pass
+
+
 def pymods():
     if verbose: print("Testing Python subclass of module...")
     log = []
@@ -802,6 +815,16 @@
                 ("getattr", "foo"),
                 ("delattr", "foo")])
 
+    # http://python.org/sf/1174712
+    try:
+        class Module(types.ModuleType, str):
+            pass
+    except TypeError:
+        pass
+    else:
+        raise TestFailed("inheriting from ModuleType and str at the "
+                          "same time should fail")
+
 def multi():
     if verbose: print("Testing multiple inheritance...")
     class C(object):
@@ -1076,6 +1099,45 @@
         raise TestFailed, "[''] slots not caught"
     class C(object):
         __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
+    # XXX(nnorwitz): was there supposed to be something tested
+    # from the class above?
+
+    # Test a single string is not expanded as a sequence.
+    class C(object):
+        __slots__ = "abc"
+    c = C()
+    c.abc = 5
+    vereq(c.abc, 5)
+
+    # Test unicode slot names
+    try:
+        unicode
+    except NameError:
+        pass
+    else:
+        # Test a single unicode string is not expanded as a sequence.
+        class C(object):
+            __slots__ = unicode("abc")
+        c = C()
+        c.abc = 5
+        vereq(c.abc, 5)
+
+        # _unicode_to_string used to modify slots in certain circumstances
+        slots = (unicode("foo"), unicode("bar"))
+        class C(object):
+            __slots__ = slots
+        x = C()
+        x.foo = 5
+        vereq(x.foo, 5)
+        veris(type(slots[0]), unicode)
+        # this used to leak references
+        try:
+            class C(object):
+                __slots__ = [unichr(128)]
+        except (TypeError, UnicodeEncodeError):
+            pass
+        else:
+            raise TestFailed, "[unichr(128)] slots not caught"
 
     # Test leaks
     class Counted(object):
@@ -1130,7 +1192,7 @@
             return 0
     g = G()
     orig_objects = len(gc.get_objects())
-    for i in xrange(10):
+    for i in range(10):
         g==g
     new_objects = len(gc.get_objects())
     vereq(orig_objects, new_objects)
@@ -1273,8 +1335,8 @@
     # Test comparison of classes with dynamic metaclasses
     class dynamicmetaclass(type):
         pass
-    class someclass:
-        __metaclass__ = dynamicmetaclass
+    class someclass(metaclass=dynamicmetaclass):
+        pass
     verify(someclass != object)
 
 def errors():
@@ -1322,6 +1384,22 @@
     else:
         verify(0, "__slots__ = [1] should be illegal")
 
+    class M1(type):
+        pass
+    class M2(type):
+        pass
+    class A1(object, metaclass=M1):
+        pass
+    class A2(object, metaclass=M2):
+        pass
+    try:
+        class B(A1, A2):
+            pass
+    except TypeError:
+        pass
+    else:
+        verify(0, "finding the most derived metaclass should have failed")
+
 def classmethods():
     if verbose: print("Testing class methods...")
     class C(object):
@@ -1505,36 +1583,39 @@
             L = type.mro(cls)
             L.reverse()
             return L
-    class X(D,B,C,A):
-        __metaclass__ = PerverseMetaType
+    class X(D,B,C,A, metaclass=PerverseMetaType):
+        pass
     vereq(X.__mro__, (object, A, C, B, D, X))
     vereq(X().f(), "A")
 
     try:
-        class X(object):
-            class __metaclass__(type):
-                def mro(self):
-                    return [self, dict, object]
+        class _metaclass(type):
+            def mro(self):
+                return [self, dict, object]
+        class X(object, metaclass=_metaclass):
+            pass
     except TypeError:
         pass
     else:
         raise TestFailed, "devious mro() return not caught"
 
     try:
-        class X(object):
-            class __metaclass__(type):
-                def mro(self):
-                    return [1]
+        class _metaclass(type):
+            def mro(self):
+                return [1]
+        class X(object, metaclass=_metaclass):
+            pass
     except TypeError:
         pass
     else:
         raise TestFailed, "non-class mro() return not caught"
 
     try:
-        class X(object):
-            class __metaclass__(type):
-                def mro(self):
-                    return 1
+        class _metaclass(type):
+            def mro(self):
+                return 1
+        class X(object, metaclass=_metaclass):
+            pass
     except TypeError:
         pass
     else:
@@ -1851,13 +1932,13 @@
     for attr in "__doc__", "fget", "fset", "fdel":
         try:
             setattr(raw, attr, 42)
-        except TypeError as msg:
+        except AttributeError as msg:
             if str(msg).find('readonly') < 0:
                 raise TestFailed("when setting readonly attr %r on a "
-                                 "property, got unexpected TypeError "
+                                 "property, got unexpected AttributeError "
                                  "msg %r" % (attr, str(msg)))
         else:
-            raise TestFailed("expected TypeError from trying to set "
+            raise TestFailed("expected AttributeError from trying to set "
                              "readonly %r attr on a property" % attr)
 
     class D(object):
@@ -2036,17 +2117,14 @@
     class octlong(int):
         __slots__ = []
         def __str__(self):
-            s = oct(self)
-            if s[-1] == 'L':
-                s = s[:-1]
-            return s
+            return oct(self)
         def __add__(self, other):
             return self.__class__(super(octlong, self).__add__(other))
         __radd__ = __add__
-    vereq(str(octlong(3) + 5), "010")
+    vereq(str(octlong(3) + 5), "0o10")
     # (Note that overriding __radd__ here only seems to work
     # because the example uses a short int left argument.)
-    vereq(str(5 + octlong(3000)), "05675")
+    vereq(str(5 + octlong(3000)), "0o5675")
     a = octlong(12345)
     vereq(a, 12345)
     vereq(int(a), 12345)
@@ -2086,7 +2164,6 @@
         __slots__ = ['prec']
         def __init__(self, value=0.0, prec=12):
             self.prec = int(prec)
-            float.__init__(self, value)
         def __repr__(self):
             return "%.*g" % (self.prec, self)
     vereq(repr(precfloat(1.1)), "1.1")
@@ -2287,24 +2364,24 @@
     class sublist(list):
         pass
     a = sublist(range(5))
-    vereq(a, range(5))
+    vereq(a, list(range(5)))
     a.append("hello")
-    vereq(a, range(5) + ["hello"])
+    vereq(a, list(range(5)) + ["hello"])
     a[5] = 5
-    vereq(a, range(6))
+    vereq(a, list(range(6)))
     a.extend(range(6, 20))
-    vereq(a, range(20))
+    vereq(a, list(range(20)))
     a[-5:] = []
-    vereq(a, range(15))
+    vereq(a, list(range(15)))
     del a[10:15]
     vereq(len(a), 10)
-    vereq(a, range(10))
-    vereq(list(a), range(10))
+    vereq(a, list(range(10)))
+    vereq(list(a), list(range(10)))
     vereq(a[0], 0)
     vereq(a[9], 9)
     vereq(a[-10], 0)
     vereq(a[-1], 9)
-    vereq(a[:5], range(5))
+    vereq(a[:5], list(range(5)))
 
     class CountedInput(file):
         """Counts lines read by self.readline().
@@ -2336,7 +2413,7 @@
         f.writelines(lines)
         f.close()
         f = CountedInput(TESTFN)
-        for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
+        for (i, expected) in zip(list(range(1, 5)) + [4], lines + 2 * [""]):
             got = f.readline()
             vereq(expected, got)
             vereq(f.lineno, i)
@@ -2363,7 +2440,7 @@
     vereq(str(object=500), '500')
     vereq(unicode(string='abc', errors='strict'), u'abc')
     vereq(tuple(sequence=range(3)), (0, 1, 2))
-    vereq(list(sequence=(0, 1, 2)), range(3))
+    vereq(list(sequence=(0, 1, 2)), list(range(3)))
     # note: as of Python 2.3, dict() no longer has an "items" keyword arg
 
     for constructor in (int, float, int, complex, str, unicode,
@@ -2376,49 +2453,6 @@
             raise TestFailed("expected TypeError from bogus keyword "
                              "argument to %r" % constructor)
 
-def restricted():
-    # XXX This test is disabled because rexec is not deemed safe
-    return
-    import rexec
-    if verbose:
-        print("Testing interaction with restricted execution ...")
-
-    sandbox = rexec.RExec()
-
-    code1 = """f = open(%r, 'w')""" % TESTFN
-    code2 = """f = open(%r, 'w')""" % TESTFN
-    code3 = """\
-f = open(%r)
-t = type(f)  # a sneaky way to get the file() constructor
-f.close()
-f = t(%r, 'w')  # rexec can't catch this by itself
-""" % (TESTFN, TESTFN)
-
-    f = open(TESTFN, 'w')  # Create the file so code3 can find it.
-    f.close()
-
-    try:
-        for code in code1, code2, code3:
-            try:
-                sandbox.r_exec(code)
-            except IOError as msg:
-                if str(msg).find("restricted") >= 0:
-                    outcome = "OK"
-                else:
-                    outcome = "got an exception, but not an expected one"
-            else:
-                outcome = "expected a restricted-execution exception"
-
-            if outcome != "OK":
-                raise TestFailed("%s, in %r" % (outcome, code))
-
-    finally:
-        try:
-            import os
-            os.unlink(TESTFN)
-        except:
-            pass
-
 def str_subclass_as_dict_key():
     if verbose:
         print("Testing a str subclass used as dict key ..")
@@ -2638,6 +2672,51 @@
     cant(o, type(1))
     cant(o, type(None))
     del o
+    class G(object):
+        __slots__ = ["a", "b"]
+    class H(object):
+        __slots__ = ["b", "a"]
+    try:
+        unicode
+    except NameError:
+        class I(object):
+            __slots__ = ["a", "b"]
+    else:
+        class I(object):
+            __slots__ = [unicode("a"), unicode("b")]
+    class J(object):
+        __slots__ = ["c", "b"]
+    class K(object):
+        __slots__ = ["a", "b", "d"]
+    class L(H):
+        __slots__ = ["e"]
+    class M(I):
+        __slots__ = ["e"]
+    class N(J):
+        __slots__ = ["__weakref__"]
+    class P(J):
+        __slots__ = ["__dict__"]
+    class Q(J):
+        pass
+    class R(J):
+        __slots__ = ["__dict__", "__weakref__"]
+
+    for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
+        x = cls()
+        x.a = 1
+        x.__class__ = cls2
+        verify(x.__class__ is cls2,
+               "assigning %r as __class__ for %r silently failed" % (cls2, x))
+        vereq(x.a, 1)
+        x.__class__ = cls
+        verify(x.__class__ is cls,
+               "assigning %r as __class__ for %r silently failed" % (cls, x))
+        vereq(x.a, 1)
+    for cls in G, J, K, L, M, N, P, R, list, Int:
+        for cls2 in G, J, K, L, M, N, P, R, list, Int:
+            if cls is cls2:
+                continue
+            cant(cls(), cls2)
 
 def setdict():
     if verbose: print("Testing __dict__ assignment...")
@@ -2656,8 +2735,73 @@
     cant(a, [])
     cant(a, 1)
     del a.__dict__ # Deleting __dict__ is allowed
-    # Classes don't allow __dict__ assignment
-    cant(C, {})
+
+    class Base(object):
+        pass
+    def verify_dict_readonly(x):
+        """
+        x has to be an instance of a class inheriting from Base.
+        """
+        cant(x, {})
+        try:
+            del x.__dict__
+        except (AttributeError, TypeError):
+            pass
+        else:
+            raise TestFailed, "shouldn't allow del %r.__dict__" % x
+        dict_descr = Base.__dict__["__dict__"]
+        try:
+            dict_descr.__set__(x, {})
+        except (AttributeError, TypeError):
+            pass
+        else:
+            raise TestFailed, "dict_descr allowed access to %r's dict" % x
+
+    # Classes don't allow __dict__ assignment and have readonly dicts
+    class Meta1(type, Base):
+        pass
+    class Meta2(Base, type):
+        pass
+    class D(object):
+        __metaclass__ = Meta1
+    class E(object):
+        __metaclass__ = Meta2
+    for cls in C, D, E:
+        verify_dict_readonly(cls)
+        class_dict = cls.__dict__
+        try:
+            class_dict["spam"] = "eggs"
+        except TypeError:
+            pass
+        else:
+            raise TestFailed, "%r's __dict__ can be modified" % cls
+
+    # Modules also disallow __dict__ assignment
+    class Module1(types.ModuleType, Base):
+        pass
+    class Module2(Base, types.ModuleType):
+        pass
+    for ModuleType in Module1, Module2:
+        mod = ModuleType("spam")
+        verify_dict_readonly(mod)
+        mod.__dict__["spam"] = "eggs"
+
+    # Exception's __dict__ can be replaced, but not deleted
+    class Exception1(Exception, Base):
+        pass
+    class Exception2(Base, Exception):
+        pass
+    for ExceptionType in Exception, Exception1, Exception2:
+        e = ExceptionType()
+        e.__dict__ = {"a": 1}
+        vereq(e.a, 1)
+        try:
+            del e.__dict__
+        except (TypeError, AttributeError):
+            pass
+        else:
+            raise TestFaied, "%r's __dict__ can be deleted" % e
+
 
 def pickles():
     if verbose:
@@ -3381,7 +3525,7 @@
         def __init__(self, x):
             self.x = x
     o = None
-    for i in xrange(50000):
+    for i in range(50000):
         o = trash(o)
     del o
 
@@ -3568,11 +3712,11 @@
     class E(D):
         pass
 
-    class F(D):
-        __metaclass__ = WorkOnce
+    class F(D, metaclass=WorkOnce):
+        pass
 
-    class G(D):
-        __metaclass__ = WorkAlways
+    class G(D, metaclass=WorkAlways):
+        pass
 
     # Immediate subclasses have their mro's adjusted in alphabetical
     # order, so E's will get adjusted before adjusting F's fails.  We
@@ -3683,15 +3827,15 @@
 
 def dict_type_with_metaclass():
     if verbose:
-        print("Testing type of __dict__ when __metaclass__ set...")
+        print("Testing type of __dict__ when metaclass set...")
 
     class B(object):
         pass
     class M(type):
         pass
-    class C:
+    class C(metaclass=M):
         # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
-        __metaclass__ = M
+        pass
     veris(type(C.__dict__), type(B.__dict__))
 
 def meth_class_get():
@@ -3838,7 +3982,7 @@
 def wrapper_segfault():
     # SF 927248: deeply nested wrappers could cause stack overflow
     f = lambda:None
-    for i in xrange(1000000):
+    for i in range(1000000):
         f = f.__call__
     f = None
 
@@ -3949,7 +4093,8 @@
     N1 = sys.maxint + 1    # might trigger OverflowErrors instead of TypeErrors
     N2 = sys.maxint         # if sizeof(int) < sizeof(long), might trigger
                             #   ValueErrors instead of TypeErrors
-    for metaclass in [type, types.ClassType]:
+    if 1:
+        metaclass = type
         for name, expr, iexpr in [
                 ('__add__',      'x + y',                   'x += y'),
                 ('__sub__',      'x - y',                   'x -= y'),
@@ -4039,7 +4184,6 @@
     supers()
     inherits()
     keywords()
-    restricted()
     str_subclass_as_dict_key()
     classic_comparisons()
     rich_comparisons()

Modified: python/branches/p3yk-noslice/Lib/test/test_descrtut.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_descrtut.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_descrtut.py	Wed Jul 11 15:40:56 2007
@@ -240,7 +240,7 @@
 static methods in C++ or Java. Here's an example:
 
     >>> class C:
-    ... 
+    ...
     ...     @staticmethod
     ...     def foo(x, y):
     ...         print("staticmethod", x, y)

Modified: python/branches/p3yk-noslice/Lib/test/test_dict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dict.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_dict.py	Wed Jul 11 15:40:56 2007
@@ -144,7 +144,7 @@
                         self.i = 1
                     def __iter__(self):
                         return self
-                    def next(self):
+                    def __next__(self):
                         if self.i:
                             self.i = 0
                             return 'a'
@@ -161,7 +161,7 @@
                         self.i = ord('a')
                     def __iter__(self):
                         return self
-                    def next(self):
+                    def __next__(self):
                         if self.i <= ord('z'):
                             rtn = chr(self.i)
                             self.i += 1
@@ -175,7 +175,7 @@
         class badseq(object):
             def __iter__(self):
                 return self
-            def next(self):
+            def __next__(self):
                 raise Exc()
 
         self.assertRaises(Exc, {}.update, badseq())
@@ -225,7 +225,7 @@
         class BadSeq(object):
             def __iter__(self):
                 return self
-            def next(self):
+            def __next__(self):
                 raise Exc()
 
         self.assertRaises(Exc, dict.fromkeys, BadSeq())
@@ -425,7 +425,7 @@
         except RuntimeError as err:
             self.assertEqual(err.args, (42,))
         else:
-            self.fail_("e[42] didn't raise RuntimeError")
+            self.fail("e[42] didn't raise RuntimeError")
         class F(dict):
             def __init__(self):
                 # An instance variable __missing__ should have no effect
@@ -436,7 +436,7 @@
         except KeyError as err:
             self.assertEqual(err.args, (42,))
         else:
-            self.fail_("f[42] didn't raise KeyError")
+            self.fail("f[42] didn't raise KeyError")
         class G(dict):
             pass
         g = G()
@@ -445,7 +445,7 @@
         except KeyError as err:
             self.assertEqual(err.args, (42,))
         else:
-            self.fail_("g[42] didn't raise KeyError")
+            self.fail("g[42] didn't raise KeyError")
 
     def test_tuple_keyerror(self):
         # SF #1576657
@@ -457,6 +457,76 @@
         else:
             self.fail("missing KeyError")
 
+    def test_bad_key(self):
+        # Dictionary lookups should fail if __cmp__() raises an exception.
+        class CustomException(Exception):
+            pass
+
+        class BadDictKey:
+            def __hash__(self):
+                return hash(self.__class__)
+
+            def __eq__(self, other):
+                if isinstance(other, self.__class__):
+                    raise CustomException
+                return other
+
+        d = {}
+        x1 = BadDictKey()
+        x2 = BadDictKey()
+        d[x1] = 1
+        for stmt in ['d[x2] = 2',
+                     'z = d[x2]',
+                     'x2 in d',
+                     'd.get(x2)',
+                     'd.setdefault(x2, 42)',
+                     'd.pop(x2)',
+                     'd.update({x2: 2})']:
+            try:
+                exec(stmt, locals())
+            except CustomException:
+                pass
+            else:
+                self.fail("Statement %r didn't raise exception" % stmt)
+
+    def test_resize1(self):
+        # Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
+        # This version got an assert failure in debug build, infinite loop in
+        # release build.  Unfortunately, provoking this kind of stuff requires
+        # a mix of inserts and deletes hitting exactly the right hash codes in
+        # exactly the right order, and I can't think of a randomized approach
+        # that would be *likely* to hit a failing case in reasonable time.
+
+        d = {}
+        for i in range(5):
+            d[i] = i
+        for i in range(5):
+            del d[i]
+        for i in range(5, 9):  # i==8 was the problem
+            d[i] = i
+
+    def test_resize2(self):
+        # Another dict resizing bug (SF bug #1456209).
+        # This caused Segmentation faults or Illegal instructions.
+
+        class X(object):
+            def __hash__(self):
+                return 5
+            def __eq__(self, other):
+                if resizing:
+                    d.clear()
+                return False
+        d = {}
+        resizing = False
+        d[X()] = 1
+        d[X()] = 2
+        d[X()] = 3
+        d[X()] = 4
+        d[X()] = 5
+        # now trigger a resize
+        resizing = True
+        d[9] = 6
+
 
 from test import mapping_tests
 

Modified: python/branches/p3yk-noslice/Lib/test/test_difflib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_difflib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_difflib.py	Wed Jul 11 15:40:56 2007
@@ -16,9 +16,9 @@
     def test_comparing_empty_lists(self):
         # Check fix for bug #979794
         group_gen = difflib.SequenceMatcher(None, [], []).get_grouped_opcodes()
-        self.assertRaises(StopIteration, group_gen.next)
+        self.assertRaises(StopIteration, next, group_gen)
         diff_gen = difflib.unified_diff([], [])
-        self.assertRaises(StopIteration, diff_gen.next)
+        self.assertRaises(StopIteration, next, diff_gen)
 
 patch914575_from1 = """
    1. Beautiful is beTTer than ugly.

Modified: python/branches/p3yk-noslice/Lib/test/test_dis.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dis.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_dis.py	Wed Jul 11 15:40:56 2007
@@ -1,11 +1,11 @@
-from test.test_support import verify, verbose, TestFailed, run_unittest
+# Minimal tests for dis module
+
+from test.test_support import verbose, run_unittest
+import unittest
 import sys
 import dis
 import StringIO
 
-# Minimal tests for dis module
-
-import unittest
 
 def _f(a):
     print(a)
@@ -19,8 +19,8 @@
 
  %-4d        10 LOAD_CONST               1 (1)
              13 RETURN_VALUE
-"""%(_f.func_code.co_firstlineno + 1,
-     _f.func_code.co_firstlineno + 2)
+"""%(_f.__code__.co_firstlineno + 1,
+     _f.__code__.co_firstlineno + 2)
 
 
 def bug708901():
@@ -43,9 +43,9 @@
         >>   25 POP_BLOCK
         >>   26 LOAD_CONST               0 (None)
              29 RETURN_VALUE
-"""%(bug708901.func_code.co_firstlineno + 1,
-     bug708901.func_code.co_firstlineno + 2,
-     bug708901.func_code.co_firstlineno + 3)
+"""%(bug708901.__code__.co_firstlineno + 1,
+     bug708901.__code__.co_firstlineno + 2,
+     bug708901.__code__.co_firstlineno + 3)
 
 
 def bug1333982(x=[]):
@@ -78,9 +78,9 @@
 
  %-4d        48 LOAD_CONST               0 (None)
              51 RETURN_VALUE
-"""%(bug1333982.func_code.co_firstlineno + 1,
-     bug1333982.func_code.co_firstlineno + 2,
-     bug1333982.func_code.co_firstlineno + 3)
+"""%(bug1333982.__code__.co_firstlineno + 1,
+     bug1333982.__code__.co_firstlineno + 2,
+     bug1333982.__code__.co_firstlineno + 3)
 
 _BIG_LINENO_FORMAT = """\
 %3d           0 LOAD_GLOBAL              0 (spam)
@@ -89,6 +89,18 @@
               7 RETURN_VALUE
 """
 
+dis_module_expected_results = """\
+Disassembly of f:
+  4           0 LOAD_CONST               0 (None)
+              3 RETURN_VALUE
+
+Disassembly of g:
+  5           0 LOAD_CONST               0 (None)
+              3 RETURN_VALUE
+
+"""
+
+
 class DisTests(unittest.TestCase):
     def do_disassembly_test(self, func, expected):
         s = StringIO.StringIO()
@@ -127,10 +139,15 @@
         self.do_disassembly_test(bug708901, dis_bug708901)
 
     def test_bug_1333982(self):
+        # XXX: re-enable this test!
         # This one is checking bytecodes generated for an `assert` statement,
         # so fails if the tests are run with -O.  Skip this test then.
-        if __debug__:
-            self.do_disassembly_test(bug1333982, dis_bug1333982)
+        pass # Test has been disabled due to change in the way
+             # list comps are handled. The byte code now includes
+             # a memory address and a file location, so they change from
+             # run to run.
+        # if __debug__:
+        #    self.do_disassembly_test(bug1333982, dis_bug1333982)
 
     def test_big_linenos(self):
         def func(count):
@@ -140,18 +157,21 @@
             return namespace['foo']
 
         # Test all small ranges
-        for i in xrange(1, 300):
+        for i in range(1, 300):
             expected = _BIG_LINENO_FORMAT % (i + 2)
             self.do_disassembly_test(func(i), expected)
 
         # Test some larger ranges too
-        for i in xrange(300, 5000, 10):
+        for i in range(300, 5000, 10):
             expected = _BIG_LINENO_FORMAT % (i + 2)
             self.do_disassembly_test(func(i), expected)
 
+    def test_big_linenos(self):
+        from test import dis_module
+        self.do_disassembly_test(dis_module, dis_module_expected_results)
+
 def test_main():
     run_unittest(DisTests)
 
-
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_doctest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_doctest.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_doctest.py	Wed Jul 11 15:40:56 2007
@@ -34,8 +34,8 @@
     >>> sc = SampleClass(3)
     >>> for i in range(10):
     ...     sc = sc.double()
-    ...     print(sc.get(), end=' ')
-    6 12 24 48 96 192 384 768 1536 3072 
+    ...     print(' ', sc.get(), sep='', end='')
+     6 12 24 48 96 192 384 768 1536 3072
     """
     def __init__(self, val):
         """
@@ -571,7 +571,7 @@
     ...
     ...     >>> for x in range(10):
     ...     ...     print(x, end=' ')
-    ...     0 1 2 3 4 5 6 7 8 9 
+    ...     0 1 2 3 4 5 6 7 8 9
     ...     >>> x//2
     ...     6
     ...     '''
@@ -996,7 +996,7 @@
     (0, 1)
 
     An example from the docs:
-    >>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE
+    >>> print(list(range(20))) #doctest: +NORMALIZE_WHITESPACE
     [0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
     10,  11, 12, 13, 14, 15, 16, 17, 18, 19]
 
@@ -1004,7 +1004,7 @@
 output to match any substring in the actual output:
 
     >>> def f(x):
-    ...     '>>> print(range(15))\n[0, 1, 2, ..., 14]\n'
+    ...     '>>> print(list(range(15)))\n[0, 1, 2, ..., 14]\n'
 
     >>> # Without the flag:
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1013,7 +1013,7 @@
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(15))
+        print(list(range(15)))
     Expected:
         [0, 1, 2, ..., 14]
     Got:
@@ -1044,10 +1044,10 @@
 
     Examples from the docs:
 
-    >>> print(range(20)) # doctest:+ELLIPSIS
+    >>> print(list(range(20))) # doctest:+ELLIPSIS
     [0, 1, ..., 18, 19]
 
-    >>> print(range(20)) # doctest: +ELLIPSIS
+    >>> print(list(range(20))) # doctest: +ELLIPSIS
     ...                 # doctest: +NORMALIZE_WHITESPACE
     [0,    1, ...,   18,    19]
 
@@ -1302,10 +1302,10 @@
 example with a comment of the form ``# doctest: +OPTION``:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # should fail: no ellipsis
+    ...     >>> print(list(range(10)))      # should fail: no ellipsis
     ...     [0, 1, ..., 9]
     ...
-    ...     >>> print(range(10))      # doctest: +ELLIPSIS
+    ...     >>> print(list(range(10)))      # doctest: +ELLIPSIS
     ...     [0, 1, ..., 9]
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1314,7 +1314,7 @@
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # should fail: no ellipsis
+        print(list(range(10)))      # should fail: no ellipsis
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1325,11 +1325,11 @@
 comment of the form ``# doctest: -OPTION``:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))
+    ...     >>> print(list(range(10)))
     ...     [0, 1, ..., 9]
     ...
     ...     >>> # should fail: no ellipsis
-    ...     >>> print(range(10))      # doctest: -ELLIPSIS
+    ...     >>> print(list(range(10)))      # doctest: -ELLIPSIS
     ...     [0, 1, ..., 9]
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1339,7 +1339,7 @@
     **********************************************************************
     File ..., line 6, in f
     Failed example:
-        print(range(10))      # doctest: -ELLIPSIS
+        print(list(range(10)))      # doctest: -ELLIPSIS
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1350,13 +1350,13 @@
 do not change the options for surrounding examples:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail: no ellipsis
+    ...     >>> print(list(range(10)))      # Should fail: no ellipsis
     ...     [0, 1, ..., 9]
     ...
-    ...     >>> print(range(10))      # doctest: +ELLIPSIS
+    ...     >>> print(list(range(10)))      # doctest: +ELLIPSIS
     ...     [0, 1, ..., 9]
     ...
-    ...     >>> print(range(10))      # Should fail: no ellipsis
+    ...     >>> print(list(range(10)))      # Should fail: no ellipsis
     ...     [0, 1, ..., 9]
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
@@ -1365,7 +1365,7 @@
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail: no ellipsis
+        print(list(range(10)))      # Should fail: no ellipsis
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1373,7 +1373,7 @@
     **********************************************************************
     File ..., line 8, in f
     Failed example:
-        print(range(10))      # Should fail: no ellipsis
+        print(list(range(10)))      # Should fail: no ellipsis
     Expected:
         [0, 1, ..., 9]
     Got:
@@ -1384,9 +1384,9 @@
 may be separated by whitespace, commas, or both:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail
+    ...     >>> print(list(range(10)))      # Should fail
     ...     [0, 1,  ...,   9]
-    ...     >>> print(range(10))      # Should succeed
+    ...     >>> print(list(range(10)))      # Should succeed
     ...     ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
     ...     [0, 1,  ...,   9]
     ...     '''
@@ -1396,7 +1396,7 @@
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail
+        print(list(range(10)))      # Should fail
     Expected:
         [0, 1,  ...,   9]
     Got:
@@ -1404,9 +1404,9 @@
     (1, 2)
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail
+    ...     >>> print(list(range(10)))      # Should fail
     ...     [0, 1,  ...,   9]
-    ...     >>> print(range(10))      # Should succeed
+    ...     >>> print(list(range(10)))      # Should succeed
     ...     ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
     ...     [0, 1,  ...,   9]
     ...     '''
@@ -1416,7 +1416,7 @@
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail
+        print(list(range(10)))      # Should fail
     Expected:
         [0, 1,  ...,   9]
     Got:
@@ -1424,9 +1424,9 @@
     (1, 2)
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))      # Should fail
+    ...     >>> print(list(range(10)))      # Should fail
     ...     [0, 1,  ...,   9]
-    ...     >>> print(range(10))      # Should succeed
+    ...     >>> print(list(range(10)))      # Should succeed
     ...     ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
     ...     [0, 1,  ...,   9]
     ...     '''
@@ -1436,7 +1436,7 @@
     **********************************************************************
     File ..., line 2, in f
     Failed example:
-        print(range(10))      # Should fail
+        print(list(range(10)))      # Should fail
     Expected:
         [0, 1,  ...,   9]
     Got:
@@ -1447,7 +1447,7 @@
 long as a continuation prompt is used:
 
     >>> def f(x): r'''
-    ...     >>> print(range(10))
+    ...     >>> print(list(range(10)))
     ...     ... # doctest: +ELLIPSIS
     ...     [0, 1, ..., 9]
     ...     '''
@@ -1460,12 +1460,12 @@
 
     >>> def f(x): r'''
     ...     >>> for x in range(10): # doctest: +ELLIPSIS
-    ...     ...     print(x, end=' ')
-    ...     0 1 2 ... 9 
+    ...     ...     print(' ', x, end='', sep='')
+    ...      0 1 2 ... 9
     ...
     ...     >>> for x in range(10):
-    ...     ...     print(x, end=' ') # doctest: +ELLIPSIS
-    ...     0 1 2 ... 9 
+    ...     ...     print(' ', x, end='', sep='') # doctest: +ELLIPSIS
+    ...      0 1 2 ... 9
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
     >>> doctest.DocTestRunner(verbose=False).run(test)
@@ -1478,7 +1478,7 @@
     ...     Should fail (option directive not on the last line):
     ...         >>> for x in range(10): # doctest: +ELLIPSIS
     ...         ...     print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
-    ...         0  1    2...9 
+    ...         0  1    2...9
     ...     '''
     >>> test = doctest.DocTestFinder().find(f)[0]
     >>> doctest.DocTestRunner(verbose=False).run(test)
@@ -2409,7 +2409,7 @@
 def test_coverage(coverdir):
     tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                          trace=0, count=1)
-    tracer.run('reload(doctest); test_main()')
+    tracer.run('test_main()')
     r = tracer.results()
     print('Writing coverage results...')
     r.write_results(show_missing=True, summary=True,

Modified: python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py	Wed Jul 11 15:40:56 2007
@@ -44,17 +44,17 @@
             return
 
         try:
-            old_umask = os.umask(0002)
-            f = dumbdbm.open(_fname, 'c', 0637)
+            old_umask = os.umask(0o002)
+            f = dumbdbm.open(_fname, 'c', 0o637)
             f.close()
         finally:
             os.umask(old_umask)
 
-        expected_mode = 0635
+        expected_mode = 0o635
         if os.name != 'posix':
             # Windows only supports setting the read-only attribute.
             # This shouldn't fail, but doesn't work like Unix either.
-            expected_mode = 0666
+            expected_mode = 0o666
 
         import stat
         st = os.stat(_fname + '.dat')

Modified: python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py	Wed Jul 11 15:40:56 2007
@@ -153,7 +153,7 @@
             print()
             print("*** Testing multiple thread creation "\
             "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
-        for count in xrange(thread_count):
+        for count in range(thread_count):
             if DELAY:
                 local_delay = round(random.random(), 1)
             else:

Modified: python/branches/p3yk-noslice/Lib/test/test_email.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_email.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_email.py	Wed Jul 11 15:40:56 2007
@@ -4,10 +4,10 @@
 import unittest
 # The specific tests now live in Lib/email/test
 from email.test.test_email import suite
-from test.test_support import run_suite
+from test import test_support
 
 def test_main():
-    run_suite(suite())
+    test_support.run_unittest(suite())
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_email_codecs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_email_codecs.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_email_codecs.py	Wed Jul 11 15:40:56 2007
@@ -9,7 +9,7 @@
 def test_main():
     suite = test_email_codecs.suite()
     suite.addTest(test_email_codecs_renamed.suite())
-    test_support.run_suite(suite)
+    test_support.run_unittest(suite)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_email_renamed.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_email_renamed.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_email_renamed.py	Wed Jul 11 15:40:56 2007
@@ -4,10 +4,10 @@
 import unittest
 # The specific tests now live in Lib/email/test
 from email.test.test_email_renamed import suite
-from test.test_support import run_suite
+from test import test_support
 
 def test_main():
-    run_suite(suite())
+    test_support.run_unittest(suite())
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_enumerate.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_enumerate.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_enumerate.py	Wed Jul 11 15:40:56 2007
@@ -17,7 +17,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
@@ -37,7 +37,7 @@
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
@@ -50,11 +50,11 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         3 // 0
 
 class N:
-    'Iterator missing next()'
+    'Iterator missing __next__()'
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
@@ -76,17 +76,17 @@
     def test_getitemseqn(self):
         self.assertEqual(list(self.enum(G(self.seq))), self.res)
         e = self.enum(G(''))
-        self.assertRaises(StopIteration, e.next)
+        self.assertRaises(StopIteration, next, e)
 
     def test_iteratorseqn(self):
         self.assertEqual(list(self.enum(I(self.seq))), self.res)
         e = self.enum(I(''))
-        self.assertRaises(StopIteration, e.next)
+        self.assertRaises(StopIteration, next, e)
 
     def test_iteratorgenerator(self):
         self.assertEqual(list(self.enum(Ig(self.seq))), self.res)
         e = self.enum(Ig(''))
-        self.assertRaises(StopIteration, e.next)
+        self.assertRaises(StopIteration, next, e)
 
     def test_noniterable(self):
         self.assertRaises(TypeError, self.enum, X(self.seq))
@@ -134,18 +134,18 @@
                 raise StopIteration
             def __len__(self):
                 return 5
-        for data in 'abc', range(5), tuple(enumerate('abc')), A(), xrange(1,17,5):
+        for data in 'abc', range(5), tuple(enumerate('abc')), A(), range(1,17,5):
             self.assertEqual(list(data)[::-1], list(reversed(data)))
         self.assertRaises(TypeError, reversed, {})
 
-    def test_xrange_optimization(self):
-        x = xrange(1)
+    def test_range_optimization(self):
+        x = range(1)
         self.assertEqual(type(reversed(x)), type(iter(x)))
 
     def test_len(self):
         # This is an implementation detail, not an interface requirement
         from test.test_iterlen import len
-        for s in ('hello', tuple('hello'), list('hello'), xrange(5)):
+        for s in ('hello', tuple('hello'), list('hello'), range(5)):
             self.assertEqual(len(reversed(s)), len(s))
             r = reversed(s)
             list(r)
@@ -205,7 +205,7 @@
     import sys
     if verbose and hasattr(sys, "gettotalrefcount"):
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*testclasses)
             counts[i] = sys.gettotalrefcount()
         print(counts)

Modified: python/branches/p3yk-noslice/Lib/test/test_exceptions.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_exceptions.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_exceptions.py	Wed Jul 11 15:40:56 2007
@@ -9,21 +9,13 @@
 except ImportError:
     cPickle = None
 
-from test.test_support import TESTFN, unlink, run_unittest
+from test.test_support import (TESTFN, unlink, run_unittest,
+                                guard_warnings_filter)
 
 # XXX This is not really enough, each *operation* should be tested!
 
 class ExceptionTests(unittest.TestCase):
 
-    def testReload(self):
-        # Reloading the built-in exceptions module failed prior to Py2.2, while it
-        # should act the same as reloading built-in sys.
-        try:
-            import exceptions
-            reload(exceptions)
-        except ImportError as e:
-            self.fail("reloading exceptions: %s" % e)
-
     def raise_catch(self, exc, excname):
         try:
             raise exc, "spam"
@@ -212,70 +204,73 @@
         # test that exception attributes are happy
 
         exceptionList = [
-            (BaseException, (), {'message' : '', 'args' : ()}),
-            (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
+            (BaseException, (), {'args' : ()}),
+            (BaseException, (1, ), {'args' : (1,)}),
             (BaseException, ('foo',),
-                {'message' : 'foo', 'args' : ('foo',)}),
+                {'args' : ('foo',)}),
             (BaseException, ('foo', 1),
-                {'message' : '', 'args' : ('foo', 1)}),
+                {'args' : ('foo', 1)}),
             (SystemExit, ('foo',),
-                {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
+                {'args' : ('foo',), 'code' : 'foo'}),
             (IOError, ('foo',),
-                {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
+                {'args' : ('foo',), 'filename' : None,
                  'errno' : None, 'strerror' : None}),
             (IOError, ('foo', 'bar'),
-                {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
+                {'args' : ('foo', 'bar'), 'filename' : None,
                  'errno' : 'foo', 'strerror' : 'bar'}),
             (IOError, ('foo', 'bar', 'baz'),
-                {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
+                {'args' : ('foo', 'bar'), 'filename' : 'baz',
                  'errno' : 'foo', 'strerror' : 'bar'}),
             (IOError, ('foo', 'bar', 'baz', 'quux'),
-                {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
+                {'args' : ('foo', 'bar', 'baz', 'quux')}),
             (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
-                {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
+                {'args' : ('errnoStr', 'strErrorStr'),
                  'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
                  'filename' : 'filenameStr'}),
             (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
-                {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
+                {'args' : (1, 'strErrorStr'), 'errno' : 1,
                  'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
+            (SyntaxError, (), {'msg' : None, 'text' : None,
+                'filename' : None, 'lineno' : None, 'offset' : None,
+                'print_file_and_line' : None}),
             (SyntaxError, ('msgStr',),
-                {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
+                {'args' : ('msgStr',), 'text' : None,
                  'print_file_and_line' : None, 'msg' : 'msgStr',
                  'filename' : None, 'lineno' : None, 'offset' : None}),
             (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
                            'textStr')),
-                {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
+                {'offset' : 'offsetStr', 'text' : 'textStr',
                  'args' : ('msgStr', ('filenameStr', 'linenoStr',
                                       'offsetStr', 'textStr')),
                  'print_file_and_line' : None, 'msg' : 'msgStr',
                  'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
             (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
                            'textStr', 'print_file_and_lineStr'),
-                {'message' : '', 'text' : None,
+                {'text' : None,
                  'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
                            'textStr', 'print_file_and_lineStr'),
                  'print_file_and_line' : None, 'msg' : 'msgStr',
                  'filename' : None, 'lineno' : None, 'offset' : None}),
-            (UnicodeError, (), {'message' : '', 'args' : (),}),
+            (UnicodeError, (), {'args' : (),}),
             (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
-                {'message' : '', 'args' : ('ascii', u'a', 0, 1,
+                {'args' : ('ascii', u'a', 0, 1,
                                            'ordinal not in range'),
                  'encoding' : 'ascii', 'object' : u'a',
                  'start' : 0, 'reason' : 'ordinal not in range'}),
             (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
-                {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
+                {'args' : ('ascii', '\xff', 0, 1,
                                            'ordinal not in range'),
                  'encoding' : 'ascii', 'object' : '\xff',
                  'start' : 0, 'reason' : 'ordinal not in range'}),
             (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
-                {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
+                {'args' : (u'\u3042', 0, 1, 'ouch'),
                  'object' : u'\u3042', 'reason' : 'ouch',
                  'start' : 0, 'end' : 1}),
         ]
         try:
             exceptionList.append(
                 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
-                    {'message' : '', 'args' : (1, 'strErrorStr'),
+                    {'args' : (1, 'strErrorStr'),
                      'strerror' : 'strErrorStr', 'winerror' : 1,
                      'errno' : 22, 'filename' : 'filenameStr'})
             )
@@ -289,7 +284,7 @@
                 if type(e) is not exc:
                     raise
                 # Verify module name
-                self.assertEquals(type(e).__module__, 'exceptions')
+                self.assertEquals(type(e).__module__, '__builtin__')
                 # Verify no ref leaks in Exc_str()
                 s = str(e)
                 for checkArgName in expected:
@@ -311,13 +306,6 @@
                                               'pickled "%r", attribute "%s' %
                                               (e, checkArgName))
 
-    def testSlicing(self):
-        # Test that you can slice an exception directly instead of requiring
-        # going through the 'args' attribute.
-        args = (1, 2, 3)
-        exc = BaseException(*args)
-        self.failUnlessEqual(exc[:], args)
-
     def testKeywordArgs(self):
         # test that builtin exception don't take keyword args,
         # but user-defined subclasses can if they want
@@ -353,7 +341,7 @@
 
     def testExceptionCleanup(self):
         # Make sure "except V as N" exceptions are cleaned up properly
-        
+
         try:
             raise Exception()
         except Exception as e:

Modified: python/branches/p3yk-noslice/Lib/test/test_extcall.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_extcall.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_extcall.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,6 @@
 from test.test_support import verify, verbose, TestFailed, sortdict
 from UserList import UserList
+from UserDict import UserDict
 
 def e(a, b):
     print(a, b)
@@ -25,6 +26,12 @@
 f(1, 2, 3, *(4, 5), **{'a':6, 'b':7})
 f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b':9})
 
+
+f(1, 2, 3, **UserDict(a=4, b=5))
+f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7))
+f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9))
+
+
 # Verify clearing of SF bug #733667
 try:
     e(c=3)
@@ -103,7 +110,7 @@
         self.c = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.c == 4:
             raise StopIteration
         c = self.c
@@ -256,8 +263,7 @@
         for vararg in ['', 'v']:
             for kwarg in ['', 'k']:
                 name = 'z' + args + defargs + vararg + kwarg
-                arglist = list(args) + map(
-                    lambda x: '%s="%s"' % (x, x), defargs)
+                arglist = list(args) + ['%s="%s"' % (x, x) for x in defargs]
                 if vararg: arglist.append('*' + vararg)
                 if kwarg: arglist.append('**' + kwarg)
                 decl = (('def %s(%s): print("ok %s", a, b, d, e, v, ' +
@@ -274,6 +280,6 @@
         for kwargs in ['', 'a', 'd', 'ad', 'abde']:
             kwdict = {}
             for k in kwargs: kwdict[k] = k + k
-            print(func.func_name, args, sortdict(kwdict), '->', end=' ')
+            print(func.__name__, args, sortdict(kwdict), '->', end=' ')
             try: func(*args, **kwdict)
             except TypeError as err: print(err)

Modified: python/branches/p3yk-noslice/Lib/test/test_file.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_file.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_file.py	Wed Jul 11 15:40:56 2007
@@ -95,7 +95,7 @@
         self.assert_(f.closed)
 
     def testMethods(self):
-        methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
+        methods = ['fileno', 'flush', 'isatty', '__next__', 'read', 'readinto',
                    'readline', 'readlines', 'seek', 'tell', 'truncate',
                    'write', '__iter__']
         if sys.platform.startswith('atheos'):
@@ -156,7 +156,7 @@
         try:
             f = open(TESTFN, bad_mode)
         except ValueError as msg:
-            if msg[0] != 0:
+            if msg.args[0] != 0:
                 s = str(msg)
                 if s.find(TESTFN) != -1 or s.find(bad_mode) == -1:
                     self.fail("bad error message for invalid mode: %s" % s)
@@ -248,7 +248,7 @@
             # Test for appropriate errors mixing read* and iteration
             for methodname, args in methods:
                 f = open(TESTFN, 'rb')
-                if f.next() != filler:
+                if next(f) != filler:
                     self.fail, "Broken testfile"
                 meth = getattr(f, methodname)
                 try:
@@ -269,7 +269,7 @@
             # between 4 and 16384 (inclusive).
             f = open(TESTFN, 'rb')
             for i in range(nchunks):
-                f.next()
+                next(f)
             testline = testlines.pop(0)
             try:
                 line = f.readline()

Modified: python/branches/p3yk-noslice/Lib/test/test_fileinput.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_fileinput.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_fileinput.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,9 @@
 Nick Mathewson
 '''
 
-from test.test_support import verify, verbose, TESTFN, TestFailed
+import unittest
+from test.test_support import verbose, TESTFN, run_unittest
+from test.test_support import unlink as safe_unlink
 import sys, os, re
 from StringIO import StringIO
 from fileinput import FileInput, hook_encoded
@@ -22,206 +24,202 @@
     f.close()
     return name
 
-pat = re.compile(r'LINE (\d+) OF FILE (\d+)')
-
 def remove_tempfiles(*names):
     for name in names:
-        try:
-            os.unlink(name)
-        except:
-            pass
+        safe_unlink(name)
 
-def runTests(t1, t2, t3, t4, bs=0, round=0):
-    start = 1 + round*6
-    if verbose:
-        print('%s. Simple iteration (bs=%s)' % (start+0, bs))
-    fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
-    lines = list(fi)
-    fi.close()
-    verify(len(lines) == 31)
-    verify(lines[4] == 'Line 5 of file 1\n')
-    verify(lines[30] == 'Line 1 of file 4\n')
-    verify(fi.lineno() == 31)
-    verify(fi.filename() == t4)
-
-    if verbose:
-        print('%s. Status variables (bs=%s)' % (start+1, bs))
-    fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
-    s = "x"
-    while s and s != 'Line 6 of file 2\n':
-        s = fi.readline()
-    verify(fi.filename() == t2)
-    verify(fi.lineno() == 21)
-    verify(fi.filelineno() == 6)
-    verify(not fi.isfirstline())
-    verify(not fi.isstdin())
-
-    if verbose:
-        print('%s. Nextfile (bs=%s)' % (start+2, bs))
-    fi.nextfile()
-    verify(fi.readline() == 'Line 1 of file 3\n')
-    verify(fi.lineno() == 22)
-    fi.close()
-
-    if verbose:
-        print('%s. Stdin (bs=%s)' % (start+3, bs))
-    fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
-    savestdin = sys.stdin
-    try:
-        sys.stdin = StringIO("Line 1 of stdin\nLine 2 of stdin\n")
+class BufferSizesTests(unittest.TestCase):
+    def test_buffer_sizes(self):
+        # First, run the tests with default and teeny buffer size.
+        for round, bs in (0, 0), (1, 30):
+            try:
+                t1 = writeTmp(1, ["Line %s of file 1\n" % (i+1) for i in range(15)])
+                t2 = writeTmp(2, ["Line %s of file 2\n" % (i+1) for i in range(10)])
+                t3 = writeTmp(3, ["Line %s of file 3\n" % (i+1) for i in range(5)])
+                t4 = writeTmp(4, ["Line %s of file 4\n" % (i+1) for i in range(1)])
+                self.buffer_size_test(t1, t2, t3, t4, bs, round)
+            finally:
+                remove_tempfiles(t1, t2, t3, t4)
+
+    def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0):
+        pat = re.compile(r'LINE (\d+) OF FILE (\d+)')
+
+        start = 1 + round*6
+        if verbose:
+            print('%s. Simple iteration (bs=%s)' % (start+0, bs))
+        fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
         lines = list(fi)
-        verify(len(lines) == 33)
-        verify(lines[32] == 'Line 2 of stdin\n')
-        verify(fi.filename() == '<stdin>')
+        fi.close()
+        self.assertEqual(len(lines), 31)
+        self.assertEqual(lines[4], 'Line 5 of file 1\n')
+        self.assertEqual(lines[30], 'Line 1 of file 4\n')
+        self.assertEqual(fi.lineno(), 31)
+        self.assertEqual(fi.filename(), t4)
+
+        if verbose:
+            print('%s. Status variables (bs=%s)' % (start+1, bs))
+        fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
+        s = "x"
+        while s and s != 'Line 6 of file 2\n':
+            s = fi.readline()
+        self.assertEqual(fi.filename(), t2)
+        self.assertEqual(fi.lineno(), 21)
+        self.assertEqual(fi.filelineno(), 6)
+        self.failIf(fi.isfirstline())
+        self.failIf(fi.isstdin())
+
+        if verbose:
+            print('%s. Nextfile (bs=%s)' % (start+2, bs))
         fi.nextfile()
-    finally:
-        sys.stdin = savestdin
+        self.assertEqual(fi.readline(), 'Line 1 of file 3\n')
+        self.assertEqual(fi.lineno(), 22)
+        fi.close()
 
-    if verbose:
-        print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
-    fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
-    verify(fi.lineno() == 0)
-    verify(fi.filename() == None)
-    fi.nextfile()
-    verify(fi.lineno() == 0)
-    verify(fi.filename() == None)
-
-    if verbose:
-        print('%s. Inplace (bs=%s)' % (start+5, bs))
-    savestdout = sys.stdout
-    try:
-        fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
+        if verbose:
+            print('%s. Stdin (bs=%s)' % (start+3, bs))
+        fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
+        savestdin = sys.stdin
+        try:
+            sys.stdin = StringIO("Line 1 of stdin\nLine 2 of stdin\n")
+            lines = list(fi)
+            self.assertEqual(len(lines), 33)
+            self.assertEqual(lines[32], 'Line 2 of stdin\n')
+            self.assertEqual(fi.filename(), '<stdin>')
+            fi.nextfile()
+        finally:
+            sys.stdin = savestdin
+
+        if verbose:
+            print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
+        fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
+        self.assertEqual(fi.lineno(), 0)
+        self.assertEqual(fi.filename(), None)
+        fi.nextfile()
+        self.assertEqual(fi.lineno(), 0)
+        self.assertEqual(fi.filename(), None)
+
+        if verbose:
+            print('%s. Inplace (bs=%s)' % (start+5, bs))
+        savestdout = sys.stdout
+        try:
+            fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
+            for line in fi:
+                line = line[:-1].upper()
+                print(line)
+            fi.close()
+        finally:
+            sys.stdout = savestdout
+
+        fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
         for line in fi:
-            line = line[:-1].upper()
-            print(line)
+            self.assertEqual(line[-1], '\n')
+            m = pat.match(line[:-1])
+            self.assertNotEqual(m, None)
+            self.assertEqual(int(m.group(1)), fi.filelineno())
         fi.close()
-    finally:
-        sys.stdout = savestdout
 
-    fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
-    for line in fi:
-        verify(line[-1] == '\n')
-        m = pat.match(line[:-1])
-        verify(m != None)
-        verify(int(m.group(1)) == fi.filelineno())
-    fi.close()
-
-
-def writeFiles():
-    global t1, t2, t3, t4
-    t1 = writeTmp(1, ["Line %s of file 1\n" % (i+1) for i in range(15)])
-    t2 = writeTmp(2, ["Line %s of file 2\n" % (i+1) for i in range(10)])
-    t3 = writeTmp(3, ["Line %s of file 3\n" % (i+1) for i in range(5)])
-    t4 = writeTmp(4, ["Line %s of file 4\n" % (i+1) for i in range(1)])
-
-# First, run the tests with default and teeny buffer size.
-for round, bs in (0, 0), (1, 30):
-    try:
-        writeFiles()
-        runTests(t1, t2, t3, t4, bs, round)
-    finally:
-        remove_tempfiles(t1, t2, t3, t4)
-
-# Next, check for proper behavior with 0-byte files.
-if verbose:
-    print("13. 0-byte files")
-try:
-    t1 = writeTmp(1, [""])
-    t2 = writeTmp(2, [""])
-    t3 = writeTmp(3, ["The only line there is.\n"])
-    t4 = writeTmp(4, [""])
-    fi = FileInput(files=(t1, t2, t3, t4))
-    line = fi.readline()
-    verify(line == 'The only line there is.\n')
-    verify(fi.lineno() == 1)
-    verify(fi.filelineno() == 1)
-    verify(fi.filename() == t3)
-    line = fi.readline()
-    verify(not line)
-    verify(fi.lineno() == 1)
-    verify(fi.filelineno() == 0)
-    verify(fi.filename() == t4)
-    fi.close()
-finally:
-    remove_tempfiles(t1, t2, t3, t4)
-
-if verbose:
-    print("14. Files that don't end with newline")
-try:
-    t1 = writeTmp(1, ["A\nB\nC"])
-    t2 = writeTmp(2, ["D\nE\nF"])
-    fi = FileInput(files=(t1, t2))
-    lines = list(fi)
-    verify(lines == ["A\n", "B\n", "C", "D\n", "E\n", "F"])
-    verify(fi.filelineno() == 3)
-    verify(fi.lineno() == 6)
-finally:
-    remove_tempfiles(t1, t2)
-
-if verbose:
-    print("15. Unicode filenames")
-try:
-    t1 = writeTmp(1, ["A\nB"])
-    encoding = sys.getfilesystemencoding()
-    if encoding is None:
-        encoding = 'ascii'
-    fi = FileInput(files=unicode(t1, encoding))
-    lines = list(fi)
-    verify(lines == ["A\n", "B"])
-finally:
-    remove_tempfiles(t1)
-
-if verbose:
-    print("16. fileno()")
-try:
-    t1 = writeTmp(1, ["A\nB"])
-    t2 = writeTmp(2, ["C\nD"])
-    fi = FileInput(files=(t1, t2))
-    verify(fi.fileno() == -1)
-    line = fi.next()
-    verify(fi.fileno() != -1)
-    fi.nextfile()
-    verify(fi.fileno() == -1)
-    line = list(fi)
-    verify(fi.fileno() == -1)
-finally:
-    remove_tempfiles(t1, t2)
-
-if verbose:
-    print("17. Specify opening mode")
-try:
-    # invalid mode, should raise ValueError
-    fi = FileInput(mode="w")
-    raise TestFailed("FileInput should reject invalid mode argument")
-except ValueError:
-    pass
-try:
-    # try opening in universal newline mode
-    t1 = writeTmp(1, ["A\nB\r\nC\rD"], mode="wb")
-    fi = FileInput(files=t1, mode="U")
-    lines = list(fi)
-    verify(lines == ["A\n", "B\n", "C\n", "D"])
-finally:
-    remove_tempfiles(t1)
-
-if verbose:
-    print("18. Test file opening hook")
-try:
-    # cannot use openhook and inplace mode
-    fi = FileInput(inplace=1, openhook=lambda f,m: None)
-    raise TestFailed("FileInput should raise if both inplace "
-                     "and openhook arguments are given")
-except ValueError:
-    pass
-try:
-    fi = FileInput(openhook=1)
-    raise TestFailed("FileInput should check openhook for being callable")
-except ValueError:
-    pass
-try:
-    t1 = writeTmp(1, ["A\nB"], mode="wb")
-    fi = FileInput(files=t1, openhook=hook_encoded("rot13"))
-    lines = list(fi)
-    verify(lines == ["N\n", "O"])
-finally:
-    remove_tempfiles(t1)
+class FileInputTests(unittest.TestCase):
+    def test_zero_byte_files(self):
+        try:
+            t1 = writeTmp(1, [""])
+            t2 = writeTmp(2, [""])
+            t3 = writeTmp(3, ["The only line there is.\n"])
+            t4 = writeTmp(4, [""])
+            fi = FileInput(files=(t1, t2, t3, t4))
+
+            line = fi.readline()
+            self.assertEqual(line, 'The only line there is.\n')
+            self.assertEqual(fi.lineno(), 1)
+            self.assertEqual(fi.filelineno(), 1)
+            self.assertEqual(fi.filename(), t3)
+
+            line = fi.readline()
+            self.failIf(line)
+            self.assertEqual(fi.lineno(), 1)
+            self.assertEqual(fi.filelineno(), 0)
+            self.assertEqual(fi.filename(), t4)
+            fi.close()
+        finally:
+            remove_tempfiles(t1, t2, t3, t4)
+
+    def test_files_that_dont_end_with_newline(self):
+        try:
+            t1 = writeTmp(1, ["A\nB\nC"])
+            t2 = writeTmp(2, ["D\nE\nF"])
+            fi = FileInput(files=(t1, t2))
+            lines = list(fi)
+            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
+            self.assertEqual(fi.filelineno(), 3)
+            self.assertEqual(fi.lineno(), 6)
+        finally:
+            remove_tempfiles(t1, t2)
+
+    def test_unicode_filenames(self):
+        try:
+            t1 = writeTmp(1, ["A\nB"])
+            encoding = sys.getfilesystemencoding()
+            if encoding is None:
+                encoding = 'ascii'
+            fi = FileInput(files=unicode(t1, encoding))
+            lines = list(fi)
+            self.assertEqual(lines, ["A\n", "B"])
+        finally:
+            remove_tempfiles(t1)
+
+    def test_fileno(self):
+        try:
+            t1 = writeTmp(1, ["A\nB"])
+            t2 = writeTmp(2, ["C\nD"])
+            fi = FileInput(files=(t1, t2))
+            self.assertEqual(fi.fileno(), -1)
+            line =next( fi)
+            self.assertNotEqual(fi.fileno(), -1)
+            fi.nextfile()
+            self.assertEqual(fi.fileno(), -1)
+            line = list(fi)
+            self.assertEqual(fi.fileno(), -1)
+        finally:
+            remove_tempfiles(t1, t2)
+
+    def test_opening_mode(self):
+        try:
+            # invalid mode, should raise ValueError
+            fi = FileInput(mode="w")
+            self.fail("FileInput should reject invalid mode argument")
+        except ValueError:
+            pass
+        try:
+            # try opening in universal newline mode
+            t1 = writeTmp(1, ["A\nB\r\nC\rD"], mode="wb")
+            fi = FileInput(files=t1, mode="U")
+            lines = list(fi)
+            self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"])
+        finally:
+            remove_tempfiles(t1)
+
+    def test_file_opening_hook(self):
+        try:
+            # cannot use openhook and inplace mode
+            fi = FileInput(inplace=1, openhook=lambda f, m: None)
+            self.fail("FileInput should raise if both inplace "
+                             "and openhook arguments are given")
+        except ValueError:
+            pass
+        try:
+            fi = FileInput(openhook=1)
+            self.fail("FileInput should check openhook for being callable")
+        except ValueError:
+            pass
+        try:
+            t1 = writeTmp(1, ["A\nB"], mode="wb")
+            fi = FileInput(files=t1, openhook=hook_encoded("rot13"))
+            lines = list(fi)
+            self.assertEqual(lines, ["N\n", "O"])
+        finally:
+            remove_tempfiles(t1)
+
+def test_main():
+    run_unittest(BufferSizesTests, FileInputTests)
+
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_format.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_format.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_format.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,7 @@
 from test.test_support import verbose, have_unicode, TestFailed
 import sys
+from test.test_support import MAX_Py_ssize_t
+maxsize = MAX_Py_ssize_t
 
 # test string formatting operator (I am not sure if this is being tested
 # elsewhere but, surely, some of the given cases are *not* tested because
@@ -120,7 +122,7 @@
 # same, except no 0 flag
 testboth("%#+27.23X", big, " +0X001234567890ABCDEF12345")
 
-big = 012345670123456701234567012345670  # 32 octal digits
+big = 0o12345670123456701234567012345670  # 32 octal digits
 testboth("%o", big, "12345670123456701234567012345670")
 testboth("%o", -big, "-12345670123456701234567012345670")
 testboth("%5o", -big, "-12345670123456701234567012345670")
@@ -140,25 +142,26 @@
 testboth("%34.33o", big, " 012345670123456701234567012345670")
 testboth("%-34.33o", big, "012345670123456701234567012345670 ")
 testboth("%o", big, "12345670123456701234567012345670")
-testboth("%#o", big, "012345670123456701234567012345670")
-testboth("%#o", -big, "-012345670123456701234567012345670")
-testboth("%#.34o", -big, "-0012345670123456701234567012345670")
-testboth("%#+.34o", big, "+0012345670123456701234567012345670")
-testboth("%# .34o", big, " 0012345670123456701234567012345670")
-testboth("%#+.34o", big, "+0012345670123456701234567012345670")
-testboth("%#-+.34o", big, "+0012345670123456701234567012345670")
-testboth("%#-+37.34o", big, "+0012345670123456701234567012345670  ")
-testboth("%#+37.34o", big, "  +0012345670123456701234567012345670")
+testboth("%#o", big, "0o12345670123456701234567012345670")
+testboth("%#o", -big, "-0o12345670123456701234567012345670")
+testboth("%#.34o", -big, "-0o0012345670123456701234567012345670")
+testboth("%#+.34o", big, "+0o0012345670123456701234567012345670")
+testboth("%# .34o", big, " 0o0012345670123456701234567012345670")
+testboth("%#-+.34o", big, "+0o0012345670123456701234567012345670")
+testboth("%#-+39.34o", big, "+0o0012345670123456701234567012345670  ")
+testboth("%#+39.34o", big, "  +0o0012345670123456701234567012345670")
 # next one gets one leading zero from precision
 testboth("%.33o", big, "012345670123456701234567012345670")
-# base marker shouldn't change that, since "0" is redundant
-testboth("%#.33o", big, "012345670123456701234567012345670")
-# but reduce precision, and base marker should add a zero
-testboth("%#.32o", big, "012345670123456701234567012345670")
-# one leading zero from precision, and another from "0" flag & width
+# one leading zero from precision
+testboth("%#.33o", big, "0o012345670123456701234567012345670")
+# leading zero vanishes
+testboth("%#.32o", big, "0o12345670123456701234567012345670")
+# one leading zero from precision, and another from '0' flag & width
 testboth("%034.33o", big, "0012345670123456701234567012345670")
-# base marker shouldn't change that
-testboth("%0#34.33o", big, "0012345670123456701234567012345670")
+# max width includes base marker; padding zeroes come after marker
+testboth("%0#38.33o", big, "0o000012345670123456701234567012345670")
+# padding spaces come before marker
+testboth("%#36.33o", big, " 0o012345670123456701234567012345670")
 
 # Some small ints, in both Python int and long flavors).
 testboth("%d", 42, "42")
@@ -169,10 +172,10 @@
 testboth("%#x", 1, "0x1")
 testboth("%#X", 1, "0X1")
 testboth("%#X", 1, "0X1")
-testboth("%#o", 1, "01")
-testboth("%#o", 1, "01")
-testboth("%#o", 0, "0")
-testboth("%#o", 0, "0")
+testboth("%#o", 1, "0o1")
+testboth("%#o", 1, "0o1")
+testboth("%#o", 0, "0o0")
+testboth("%#o", 0, "0o0")
 testboth("%o", 0, "0")
 testboth("%o", 0, "0")
 testboth("%d", 0, "0")
@@ -187,10 +190,10 @@
 testboth("%x", 0x42, "42")
 testboth("%x", -0x42, "-42")
 
-testboth("%o", 042, "42")
-testboth("%o", -042, "-42")
-testboth("%o", 042, "42")
-testboth("%o", -042, "-42")
+testboth("%o", 0o42, "42")
+testboth("%o", -0o42, "-42")
+testboth("%o", 0o42, "42")
+testboth("%o", -0o42, "-42")
 
 # Test exception for unknown format characters
 if verbose:
@@ -230,19 +233,11 @@
 test_exc(u'no format', u'1', TypeError,
          "not all arguments converted during string formatting")
 
-class Foobar(int):
-    def __oct__(self):
-        # Returning a non-string should not blow up.
-        return self + 1
-
-test_exc('%o', Foobar(), TypeError,
-         "expected string or Unicode object, int found")
-
-if sys.maxint == 2**31-1:
+if maxsize == 2**31-1:
     # crashes 2.2.1 and earlier:
     try:
-        "%*d"%(sys.maxint, -127)
+        "%*d"%(maxsize, -127)
     except MemoryError:
         pass
     else:
-        raise TestFailed, '"%*d"%(sys.maxint, -127) should fail'
+        raise TestFailed, '"%*d"%(maxsize, -127) should fail'

Modified: python/branches/p3yk-noslice/Lib/test/test_funcattrs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_funcattrs.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_funcattrs.py	Wed Jul 11 15:40:56 2007
@@ -47,7 +47,7 @@
 
 d = {'hello': 'world'}
 b.__dict__ = d
-if b.func_dict is not d:
+if b.__dict__ is not d:
     raise TestFailed, 'func.__dict__ assignment to dictionary failed'
 if b.hello != 'world':
     raise TestFailed, 'attribute after func.__dict__ assignment failed'
@@ -179,12 +179,12 @@
 else: raise TestFailed
 
 try:
-    del another.func_dict
+    del another.__dict__
 except TypeError: pass
 else: raise TestFailed
 
 try:
-    another.func_dict = None
+    another.__dict__ = None
 except TypeError: pass
 else: raise TestFailed
 
@@ -195,7 +195,7 @@
 
 # This isn't specifically related to function attributes, but it does test a
 # core dump regression in funcobject.c
-del another.func_defaults
+del another.__defaults__
 
 def foo():
     pass
@@ -212,7 +212,7 @@
 d={}
 d[foo] = 1
 
-foo.func_code = temp.func_code
+foo.__code__ = temp.__code__
 
 d[foo]
 
@@ -236,45 +236,31 @@
 def test_func_closure():
     a = 12
     def f(): print(a)
-    c = f.func_closure
+    c = f.__closure__
     verify(isinstance(c, tuple))
     verify(len(c) == 1)
     verify(c[0].__class__.__name__ == "cell") # don't have a type object handy
-    cantset(f, "func_closure", c)
+    cantset(f, "__closure__", c)
 
 def test_func_doc():
     def f(): pass
     verify(f.__doc__ is None)
-    verify(f.func_doc is None)
     f.__doc__ = "hello"
     verify(f.__doc__ == "hello")
-    verify(f.func_doc == "hello")
     del f.__doc__
     verify(f.__doc__ is None)
-    verify(f.func_doc is None)
-    f.func_doc = "world"
-    verify(f.__doc__ == "world")
-    verify(f.func_doc == "world")
-    del f.func_doc
-    verify(f.func_doc is None)
-    verify(f.__doc__ is None)
 
 def test_func_globals():
     def f(): pass
-    verify(f.func_globals is globals())
-    cantset(f, "func_globals", globals())
+    verify(f.__globals__ is globals())
+    cantset(f, "__globals__", globals())
 
 def test_func_name():
     def f(): pass
     verify(f.__name__ == "f")
-    verify(f.func_name == "f")
     f.__name__ = "g"
     verify(f.__name__ == "g")
-    verify(f.func_name == "g")
-    f.func_name = "h"
-    verify(f.__name__ == "h")
-    verify(f.func_name == "h")
-    cantset(f, "func_globals", 1)
+    cantset(f, "__globals__", 1)
     cantset(f, "__name__", 1)
     # test that you can access func.__name__ in restricted mode
     s = """def f(): pass\nf.__name__"""
@@ -288,25 +274,25 @@
     def f1(): print(a)
     def g1(): print(b)
     def f2(): print(a, b)
-    verify(type(f.func_code) is types.CodeType)
-    f.func_code = g.func_code
-    cantset(f, "func_code", None)
+    verify(type(f.__code__) is types.CodeType)
+    f.__code__ = g.__code__
+    cantset(f, "__code__", None)
     # can't change the number of free vars
-    cantset(f,  "func_code", f1.func_code, exception=ValueError)
-    cantset(f1, "func_code",  f.func_code, exception=ValueError)
-    cantset(f1, "func_code", f2.func_code, exception=ValueError)
-    f1.func_code = g1.func_code
+    cantset(f,  "__code__", f1.__code__, exception=ValueError)
+    cantset(f1, "__code__",  f.__code__, exception=ValueError)
+    cantset(f1, "__code__", f2.__code__, exception=ValueError)
+    f1.__code__ = g1.__code__
 
 def test_func_defaults():
     def f(a, b): return (a, b)
-    verify(f.func_defaults is None)
-    f.func_defaults = (1, 2)
-    verify(f.func_defaults == (1, 2))
+    verify(f.__defaults__ is None)
+    f.__defaults__ = (1, 2)
+    verify(f.__defaults__ == (1, 2))
     verify(f(10) == (10, 2))
     def g(a=1, b=2): return (a, b)
-    verify(g.func_defaults == (1, 2))
-    del g.func_defaults
-    verify(g.func_defaults is None)
+    verify(g.__defaults__ == (1, 2))
+    del g.__defaults__
+    verify(g.__defaults__ is None)
     try:
         g()
     except TypeError:
@@ -317,18 +303,13 @@
 def test_func_dict():
     def f(): pass
     a = f.__dict__
-    b = f.func_dict
     verify(a == {})
-    verify(a is b)
     f.hello = 'world'
     verify(a == {'hello': 'world'})
-    verify(f.func_dict is a is f.__dict__)
-    f.func_dict = {}
-    verify(not hasattr(f, "hello"))
+    verify(a is f.__dict__)
     f.__dict__ = {'world': 'hello'}
     verify(f.world == "hello")
-    verify(f.__dict__ is f.func_dict == {'world': 'hello'})
-    cantset(f, "func_dict", None)
+    verify(f.__dict__ == {'world': 'hello'})
     cantset(f, "__dict__", None)
 
 def test_im_class():

Modified: python/branches/p3yk-noslice/Lib/test/test_functools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_functools.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_functools.py	Wed Jul 11 15:40:56 2007
@@ -19,6 +19,7 @@
     """capture all positional and keyword arguments"""
     return args, kw
 
+
 class TestPartial(unittest.TestCase):
 
     thetype = functools.partial
@@ -28,7 +29,7 @@
         self.assertEqual(p(3, 4, b=30, c=40),
                          ((1, 2, 3, 4), dict(a=10, b=30, c=40)))
         p = self.thetype(map, lambda x: x*10)
-        self.assertEqual(p([1,2,3,4]), [10, 20, 30, 40])
+        self.assertEqual(list(p([1,2,3,4])), [10, 20, 30, 40])
 
     def test_attributes(self):
         p = self.thetype(capture, 1, 2, a=10, b=20)
@@ -134,7 +135,7 @@
         self.assertRaises(ReferenceError, getattr, p, 'func')
 
     def test_with_bound_and_unbound_methods(self):
-        data = map(str, range(10))
+        data = list(map(str, range(10)))
         join = self.thetype(str.join, '')
         self.assertEqual(join(data), '0123456789')
         join = self.thetype(''.join)
@@ -285,7 +286,7 @@
                     self.sofar.append(n*n)
                     n += 1
                 return self.sofar[i]
-    
+
         self.assertEqual(self.func(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc')
         self.assertEqual(
             self.func(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []),
@@ -321,7 +322,7 @@
                     return i
                 else:
                     raise IndexError
-    
+
         from operator import add
         self.assertEqual(self.func(add, SequenceClass(5)), 10)
         self.assertEqual(self.func(add, SequenceClass(5), 42), 52)
@@ -333,7 +334,7 @@
         d = {"one": 1, "two": 2, "three": 3}
         self.assertEqual(self.func(add, d), "".join(d.keys()))
 
-    
+
 
 
 def test_main(verbose=None):
@@ -352,7 +353,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_future2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_future2.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_future2.py	Wed Jul 11 15:40:56 2007
@@ -1,6 +1,6 @@
 """This is a test"""
 
-from __future__ import nested_scopes; import string
+from __future__ import nested_scopes; import site
 
 def f(x):
     def g(y):

Modified: python/branches/p3yk-noslice/Lib/test/test_gc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_gc.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_gc.py	Wed Jul 11 15:40:56 2007
@@ -1,390 +1,11 @@
-from test.test_support import verify, verbose, TestFailed, vereq
+import unittest
+from test.test_support import verbose, run_unittest
 import sys
 import gc
 import weakref
 
-def expect(actual, expected, name):
-    if actual != expected:
-        raise TestFailed, "test_%s: actual %r, expected %r" % (
-            name, actual, expected)
-
-def expect_nonzero(actual, name):
-    if actual == 0:
-        raise TestFailed, "test_%s: unexpected zero" % name
-
-def run_test(name, thunk):
-    if verbose:
-        print("testing %s..." % name, end=' ')
-    thunk()
-    if verbose:
-        print("ok")
-
-def test_list():
-    l = []
-    l.append(l)
-    gc.collect()
-    del l
-    expect(gc.collect(), 1, "list")
-
-def test_dict():
-    d = {}
-    d[1] = d
-    gc.collect()
-    del d
-    expect(gc.collect(), 1, "dict")
-
-def test_tuple():
-    # since tuples are immutable we close the loop with a list
-    l = []
-    t = (l,)
-    l.append(t)
-    gc.collect()
-    del t
-    del l
-    expect(gc.collect(), 2, "tuple")
-
-def test_class():
-    class A:
-        pass
-    A.a = A
-    gc.collect()
-    del A
-    expect_nonzero(gc.collect(), "class")
-
-def test_newstyleclass():
-    class A(object):
-        pass
-    gc.collect()
-    del A
-    expect_nonzero(gc.collect(), "staticclass")
-
-def test_instance():
-    class A:
-        pass
-    a = A()
-    a.a = a
-    gc.collect()
-    del a
-    expect_nonzero(gc.collect(), "instance")
-
-def test_newinstance():
-    class A(object):
-        pass
-    a = A()
-    a.a = a
-    gc.collect()
-    del a
-    expect_nonzero(gc.collect(), "newinstance")
-    class B(list):
-        pass
-    class C(B, A):
-        pass
-    a = C()
-    a.a = a
-    gc.collect()
-    del a
-    expect_nonzero(gc.collect(), "newinstance(2)")
-    del B, C
-    expect_nonzero(gc.collect(), "newinstance(3)")
-    A.a = A()
-    del A
-    expect_nonzero(gc.collect(), "newinstance(4)")
-    expect(gc.collect(), 0, "newinstance(5)")
-
-def test_method():
-    # Tricky: self.__init__ is a bound method, it references the instance.
-    class A:
-        def __init__(self):
-            self.init = self.__init__
-    a = A()
-    gc.collect()
-    del a
-    expect_nonzero(gc.collect(), "method")
-
-def test_finalizer():
-    # A() is uncollectable if it is part of a cycle, make sure it shows up
-    # in gc.garbage.
-    class A:
-        def __del__(self): pass
-    class B:
-        pass
-    a = A()
-    a.a = a
-    id_a = id(a)
-    b = B()
-    b.b = b
-    gc.collect()
-    del a
-    del b
-    expect_nonzero(gc.collect(), "finalizer")
-    for obj in gc.garbage:
-        if id(obj) == id_a:
-            del obj.a
-            break
-    else:
-        raise TestFailed, "didn't find obj in garbage (finalizer)"
-    gc.garbage.remove(obj)
-
-def test_finalizer_newclass():
-    # A() is uncollectable if it is part of a cycle, make sure it shows up
-    # in gc.garbage.
-    class A(object):
-        def __del__(self): pass
-    class B(object):
-        pass
-    a = A()
-    a.a = a
-    id_a = id(a)
-    b = B()
-    b.b = b
-    gc.collect()
-    del a
-    del b
-    expect_nonzero(gc.collect(), "finalizer")
-    for obj in gc.garbage:
-        if id(obj) == id_a:
-            del obj.a
-            break
-    else:
-        raise TestFailed, "didn't find obj in garbage (finalizer)"
-    gc.garbage.remove(obj)
-
-def test_function():
-    # Tricky: f -> d -> f, code should call d.clear() after the exec to
-    # break the cycle.
-    d = {}
-    exec("def f(): pass\n", d)
-    gc.collect()
-    del d
-    expect(gc.collect(), 2, "function")
-
-def test_frame():
-    def f():
-        frame = sys._getframe()
-    gc.collect()
-    f()
-    expect(gc.collect(), 1, "frame")
-
-
-def test_saveall():
-    # Verify that cyclic garbage like lists show up in gc.garbage if the
-    # SAVEALL option is enabled.
-
-    # First make sure we don't save away other stuff that just happens to
-    # be waiting for collection.
-    gc.collect()
-    vereq(gc.garbage, []) # if this fails, someone else created immortal trash
-
-    L = []
-    L.append(L)
-    id_L = id(L)
-
-    debug = gc.get_debug()
-    gc.set_debug(debug | gc.DEBUG_SAVEALL)
-    del L
-    gc.collect()
-    gc.set_debug(debug)
-
-    vereq(len(gc.garbage), 1)
-    obj = gc.garbage.pop()
-    vereq(id(obj), id_L)
-
-def test_del():
-    # __del__ methods can trigger collection, make this to happen
-    thresholds = gc.get_threshold()
-    gc.enable()
-    gc.set_threshold(1)
-
-    class A:
-        def __del__(self):
-            dir(self)
-    a = A()
-    del a
-
-    gc.disable()
-    gc.set_threshold(*thresholds)
-
-def test_del_newclass():
-    # __del__ methods can trigger collection, make this to happen
-    thresholds = gc.get_threshold()
-    gc.enable()
-    gc.set_threshold(1)
-
-    class A(object):
-        def __del__(self):
-            dir(self)
-    a = A()
-    del a
-
-    gc.disable()
-    gc.set_threshold(*thresholds)
-
-def test_get_count():
-    gc.collect()
-    expect(gc.get_count(), (0, 0, 0), "get_count()")
-    a = dict()
-    expect(gc.get_count(), (1, 0, 0), "get_count()")
-
-def test_collect_generations():
-    gc.collect()
-    a = dict()
-    gc.collect(0)
-    expect(gc.get_count(), (0, 1, 0), "collect(0)")
-    gc.collect(1)
-    expect(gc.get_count(), (0, 0, 1), "collect(1)")
-    gc.collect(2)
-    expect(gc.get_count(), (0, 0, 0), "collect(1)")
-
-class Ouch:
-    n = 0
-    def __del__(self):
-        Ouch.n = Ouch.n + 1
-        if Ouch.n % 17 == 0:
-            gc.collect()
-
-def test_trashcan():
-    # "trashcan" is a hack to prevent stack overflow when deallocating
-    # very deeply nested tuples etc.  It works in part by abusing the
-    # type pointer and refcount fields, and that can yield horrible
-    # problems when gc tries to traverse the structures.
-    # If this test fails (as it does in 2.0, 2.1 and 2.2), it will
-    # most likely die via segfault.
-
-    # Note:  In 2.3 the possibility for compiling without cyclic gc was
-    # removed, and that in turn allows the trashcan mechanism to work
-    # via much simpler means (e.g., it never abuses the type pointer or
-    # refcount fields anymore).  Since it's much less likely to cause a
-    # problem now, the various constants in this expensive (we force a lot
-    # of full collections) test are cut back from the 2.2 version.
-    gc.enable()
-    N = 150
-    for count in range(2):
-        t = []
-        for i in range(N):
-            t = [t, Ouch()]
-        u = []
-        for i in range(N):
-            u = [u, Ouch()]
-        v = {}
-        for i in range(N):
-            v = {1: v, 2: Ouch()}
-    gc.disable()
-
-class Boom:
-    def __getattr__(self, someattribute):
-        del self.attr
-        raise AttributeError
-
-def test_boom():
-    a = Boom()
-    b = Boom()
-    a.attr = b
-    b.attr = a
-
-    gc.collect()
-    garbagelen = len(gc.garbage)
-    del a, b
-    # a<->b are in a trash cycle now.  Collection will invoke Boom.__getattr__
-    # (to see whether a and b have __del__ methods), and __getattr__ deletes
-    # the internal "attr" attributes as a side effect.  That causes the
-    # trash cycle to get reclaimed via refcounts falling to 0, thus mutating
-    # the trash graph as a side effect of merely asking whether __del__
-    # exists.  This used to (before 2.3b1) crash Python.  Now __getattr__
-    # isn't called.
-    expect(gc.collect(), 4, "boom")
-    expect(len(gc.garbage), garbagelen, "boom")
-
-class Boom2:
-    def __init__(self):
-        self.x = 0
-
-    def __getattr__(self, someattribute):
-        self.x += 1
-        if self.x > 1:
-            del self.attr
-        raise AttributeError
-
-def test_boom2():
-    a = Boom2()
-    b = Boom2()
-    a.attr = b
-    b.attr = a
-
-    gc.collect()
-    garbagelen = len(gc.garbage)
-    del a, b
-    # Much like test_boom(), except that __getattr__ doesn't break the
-    # cycle until the second time gc checks for __del__.  As of 2.3b1,
-    # there isn't a second time, so this simply cleans up the trash cycle.
-    # We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get reclaimed
-    # this way.
-    expect(gc.collect(), 4, "boom2")
-    expect(len(gc.garbage), garbagelen, "boom2")
-
-# boom__new and boom2_new are exactly like boom and boom2, except use
-# new-style classes.
-
-class Boom_New(object):
-    def __getattr__(self, someattribute):
-        del self.attr
-        raise AttributeError
-
-def test_boom_new():
-    a = Boom_New()
-    b = Boom_New()
-    a.attr = b
-    b.attr = a
-
-    gc.collect()
-    garbagelen = len(gc.garbage)
-    del a, b
-    expect(gc.collect(), 4, "boom_new")
-    expect(len(gc.garbage), garbagelen, "boom_new")
-
-class Boom2_New(object):
-    def __init__(self):
-        self.x = 0
-
-    def __getattr__(self, someattribute):
-        self.x += 1
-        if self.x > 1:
-            del self.attr
-        raise AttributeError
-
-def test_boom2_new():
-    a = Boom2_New()
-    b = Boom2_New()
-    a.attr = b
-    b.attr = a
-
-    gc.collect()
-    garbagelen = len(gc.garbage)
-    del a, b
-    expect(gc.collect(), 4, "boom2_new")
-    expect(len(gc.garbage), garbagelen, "boom2_new")
-
-def test_get_referents():
-    alist = [1, 3, 5]
-    got = gc.get_referents(alist)
-    got.sort()
-    expect(got, alist, "get_referents")
-
-    atuple = tuple(alist)
-    got = gc.get_referents(atuple)
-    got.sort()
-    expect(got, alist, "get_referents")
-
-    adict = {1: 3, 5: 7}
-    expected = [1, 3, 5, 7]
-    got = gc.get_referents(adict)
-    got.sort()
-    expect(got, expected, "get_referents")
-
-    got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
-    got.sort()
-    expect(got, [0, 0] + range(5), "get_referents")
-
-    expect(gc.get_referents(1, 'a', 4j), [], "get_referents")
+### Support code
+###############################################################################
 
 # Bug 1055820 has several tests of longstanding bugs involving weakrefs and
 # cyclic gc.
@@ -410,217 +31,556 @@
         # gc collects it.
         self.wr = weakref.ref(C1055820(666), it_happened)
 
-def test_bug1055820b():
-    # Corresponds to temp2b.py in the bug report.
 
-    ouch = []
-    def callback(ignored):
-        ouch[:] = [wr() for wr in WRs]
-
-    Cs = [C1055820(i) for i in range(2)]
-    WRs = [weakref.ref(c, callback) for c in Cs]
-    c = None
-
-    gc.collect()
-    expect(len(ouch), 0, "bug1055820b")
-    # Make the two instances trash, and collect again.  The bug was that
-    # the callback materialized a strong reference to an instance, but gc
-    # cleared the instance's dict anyway.
-    Cs = None
-    gc.collect()
-    expect(len(ouch), 2, "bug1055820b")  # else the callbacks didn't run
-    for x in ouch:
-        # If the callback resurrected one of these guys, the instance
-        # would be damaged, with an empty __dict__.
-        expect(x, None, "bug1055820b")
-
-def test_bug1055820c():
-    # Corresponds to temp2c.py in the bug report.  This is pretty elaborate.
-
-    c0 = C1055820(0)
-    # Move c0 into generation 2.
-    gc.collect()
-
-    c1 = C1055820(1)
-    c1.keep_c0_alive = c0
-    del c0.loop # now only c1 keeps c0 alive
-
-    c2 = C1055820(2)
-    c2wr = weakref.ref(c2) # no callback!
-
-    ouch = []
-    def callback(ignored):
-        ouch[:] = [c2wr()]
-
-    # The callback gets associated with a wr on an object in generation 2.
-    c0wr = weakref.ref(c0, callback)
-
-    c0 = c1 = c2 = None
-
-    # What we've set up:  c0, c1, and c2 are all trash now.  c0 is in
-    # generation 2.  The only thing keeping it alive is that c1 points to it.
-    # c1 and c2 are in generation 0, and are in self-loops.  There's a global
-    # weakref to c2 (c2wr), but that weakref has no callback.  There's also
-    # a global weakref to c0 (c0wr), and that does have a callback, and that
-    # callback references c2 via c2wr().
-    #
-    #               c0 has a wr with callback, which references c2wr
-    #               ^
-    #               |
-    #               |     Generation 2 above dots
-    #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
-    #               |     Generation 0 below dots
-    #               |
-    #               |
-    #            ^->c1   ^->c2 has a wr but no callback
-    #            |  |    |  |
-    #            <--v    <--v
-    #
-    # So this is the nightmare:  when generation 0 gets collected, we see that
-    # c2 has a callback-free weakref, and c1 doesn't even have a weakref.
-    # Collecting generation 0 doesn't see c0 at all, and c0 is the only object
-    # that has a weakref with a callback.  gc clears c1 and c2.  Clearing c1
-    # has the side effect of dropping the refcount on c0 to 0, so c0 goes
-    # away (despite that it's in an older generation) and c0's wr callback
-    # triggers.  That in turn materializes a reference to c2 via c2wr(), but
-    # c2 gets cleared anyway by gc.
-
-    # We want to let gc happen "naturally", to preserve the distinction
-    # between generations.
-    junk = []
-    i = 0
-    detector = GC_Detector()
-    while not detector.gc_happened:
-        i += 1
-        if i > 10000:
-            raise TestFailed("gc didn't happen after 10000 iterations")
-        expect(len(ouch), 0, "bug1055820c")
-        junk.append([])  # this will eventually trigger gc
-
-    expect(len(ouch), 1, "bug1055820c")  # else the callback wasn't invoked
-    for x in ouch:
-        # If the callback resurrected c2, the instance would be damaged,
-        # with an empty __dict__.
-        expect(x, None, "bug1055820c")
-
-def test_bug1055820d():
-    # Corresponds to temp2d.py in the bug report.  This is very much like
-    # test_bug1055820c, but uses a __del__ method instead of a weakref
-    # callback to sneak in a resurrection of cyclic trash.
-
-    ouch = []
-    class D(C1055820):
-        def __del__(self):
-            ouch[:] = [c2wr()]
+### Tests
+###############################################################################
 
-    d0 = D(0)
-    # Move all the above into generation 2.
-    gc.collect()
-
-    c1 = C1055820(1)
-    c1.keep_d0_alive = d0
-    del d0.loop # now only c1 keeps d0 alive
-
-    c2 = C1055820(2)
-    c2wr = weakref.ref(c2) # no callback!
-
-    d0 = c1 = c2 = None
-
-    # What we've set up:  d0, c1, and c2 are all trash now.  d0 is in
-    # generation 2.  The only thing keeping it alive is that c1 points to it.
-    # c1 and c2 are in generation 0, and are in self-loops.  There's a global
-    # weakref to c2 (c2wr), but that weakref has no callback.  There are no
-    # other weakrefs.
-    #
-    #               d0 has a __del__ method that references c2wr
-    #               ^
-    #               |
-    #               |     Generation 2 above dots
-    #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
-    #               |     Generation 0 below dots
-    #               |
-    #               |
-    #            ^->c1   ^->c2 has a wr but no callback
-    #            |  |    |  |
-    #            <--v    <--v
-    #
-    # So this is the nightmare:  when generation 0 gets collected, we see that
-    # c2 has a callback-free weakref, and c1 doesn't even have a weakref.
-    # Collecting generation 0 doesn't see d0 at all.  gc clears c1 and c2.
-    # Clearing c1 has the side effect of dropping the refcount on d0 to 0, so
-    # d0 goes away (despite that it's in an older generation) and d0's __del__
-    # triggers.  That in turn materializes a reference to c2 via c2wr(), but
-    # c2 gets cleared anyway by gc.
-
-    # We want to let gc happen "naturally", to preserve the distinction
-    # between generations.
-    detector = GC_Detector()
-    junk = []
-    i = 0
-    while not detector.gc_happened:
-        i += 1
-        if i > 10000:
-            raise TestFailed("gc didn't happen after 10000 iterations")
-        expect(len(ouch), 0, "bug1055820d")
-        junk.append([])  # this will eventually trigger gc
-
-    expect(len(ouch), 1, "bug1055820d")  # else __del__ wasn't invoked
-    for x in ouch:
-        # If __del__ resurrected c2, the instance would be damaged, with an
-        # empty __dict__.
-        expect(x, None, "bug1055820d")
-
-
-def test_all():
-    gc.collect() # Delete 2nd generation garbage
-    run_test("lists", test_list)
-    run_test("dicts", test_dict)
-    run_test("tuples", test_tuple)
-    run_test("classes", test_class)
-    run_test("new style classes", test_newstyleclass)
-    run_test("instances", test_instance)
-    run_test("new instances", test_newinstance)
-    run_test("methods", test_method)
-    run_test("functions", test_function)
-    run_test("frames", test_frame)
-    run_test("finalizers", test_finalizer)
-    run_test("finalizers (new class)", test_finalizer_newclass)
-    run_test("__del__", test_del)
-    run_test("__del__ (new class)", test_del_newclass)
-    run_test("get_count()", test_get_count)
-    run_test("collect(n)", test_collect_generations)
-    run_test("saveall", test_saveall)
-    run_test("trashcan", test_trashcan)
-    run_test("boom", test_boom)
-    run_test("boom2", test_boom2)
-    run_test("boom_new", test_boom_new)
-    run_test("boom2_new", test_boom2_new)
-    run_test("get_referents", test_get_referents)
-    run_test("bug1055820b", test_bug1055820b)
+class GCTests(unittest.TestCase):
+    def test_list(self):
+        l = []
+        l.append(l)
+        gc.collect()
+        del l
+        self.assertEqual(gc.collect(), 1)
+
+    def test_dict(self):
+        d = {}
+        d[1] = d
+        gc.collect()
+        del d
+        self.assertEqual(gc.collect(), 1)
+
+    def test_tuple(self):
+        # since tuples are immutable we close the loop with a list
+        l = []
+        t = (l,)
+        l.append(t)
+        gc.collect()
+        del t
+        del l
+        self.assertEqual(gc.collect(), 2)
+
+    def test_class(self):
+        class A:
+            pass
+        A.a = A
+        gc.collect()
+        del A
+        self.assertNotEqual(gc.collect(), 0)
+
+    def test_newstyleclass(self):
+        class A(object):
+            pass
+        gc.collect()
+        del A
+        self.assertNotEqual(gc.collect(), 0)
+
+    def test_instance(self):
+        class A:
+            pass
+        a = A()
+        a.a = a
+        gc.collect()
+        del a
+        self.assertNotEqual(gc.collect(), 0)
+
+    def test_newinstance(self):
+        class A(object):
+            pass
+        a = A()
+        a.a = a
+        gc.collect()
+        del a
+        self.assertNotEqual(gc.collect(), 0)
+        class B(list):
+            pass
+        class C(B, A):
+            pass
+        a = C()
+        a.a = a
+        gc.collect()
+        del a
+        self.assertNotEqual(gc.collect(), 0)
+        del B, C
+        self.assertNotEqual(gc.collect(), 0)
+        A.a = A()
+        del A
+        self.assertNotEqual(gc.collect(), 0)
+        self.assertEqual(gc.collect(), 0)
+
+    def test_method(self):
+        # Tricky: self.__init__ is a bound method, it references the instance.
+        class A:
+            def __init__(self):
+                self.init = self.__init__
+        a = A()
+        gc.collect()
+        del a
+        self.assertNotEqual(gc.collect(), 0)
+
+    def test_finalizer(self):
+        # A() is uncollectable if it is part of a cycle, make sure it shows up
+        # in gc.garbage.
+        class A:
+            def __del__(self): pass
+        class B:
+            pass
+        a = A()
+        a.a = a
+        id_a = id(a)
+        b = B()
+        b.b = b
+        gc.collect()
+        del a
+        del b
+        self.assertNotEqual(gc.collect(), 0)
+        for obj in gc.garbage:
+            if id(obj) == id_a:
+                del obj.a
+                break
+        else:
+            self.fail("didn't find obj in garbage (finalizer)")
+        gc.garbage.remove(obj)
+
+    def test_finalizer_newclass(self):
+        # A() is uncollectable if it is part of a cycle, make sure it shows up
+        # in gc.garbage.
+        class A(object):
+            def __del__(self): pass
+        class B(object):
+            pass
+        a = A()
+        a.a = a
+        id_a = id(a)
+        b = B()
+        b.b = b
+        gc.collect()
+        del a
+        del b
+        self.assertNotEqual(gc.collect(), 0)
+        for obj in gc.garbage:
+            if id(obj) == id_a:
+                del obj.a
+                break
+        else:
+            self.fail("didn't find obj in garbage (finalizer)")
+        gc.garbage.remove(obj)
+
+    def test_function(self):
+        # Tricky: f -> d -> f, code should call d.clear() after the exec to
+        # break the cycle.
+        d = {}
+        exec("def f(): pass\n", d)
+        gc.collect()
+        del d
+        self.assertEqual(gc.collect(), 2)
+
+    def test_frame(self):
+        def f():
+            frame = sys._getframe()
+        gc.collect()
+        f()
+        self.assertEqual(gc.collect(), 1)
+
+    def test_saveall(self):
+        # Verify that cyclic garbage like lists show up in gc.garbage if the
+        # SAVEALL option is enabled.
+
+        # First make sure we don't save away other stuff that just happens to
+        # be waiting for collection.
+        gc.collect()
+        # if this fails, someone else created immortal trash
+        self.assertEqual(gc.garbage, [])
+
+        L = []
+        L.append(L)
+        id_L = id(L)
+
+        debug = gc.get_debug()
+        gc.set_debug(debug | gc.DEBUG_SAVEALL)
+        del L
+        gc.collect()
+        gc.set_debug(debug)
+
+        self.assertEqual(len(gc.garbage), 1)
+        obj = gc.garbage.pop()
+        self.assertEqual(id(obj), id_L)
+
+    def test_del(self):
+        # __del__ methods can trigger collection, make this to happen
+        thresholds = gc.get_threshold()
+        gc.enable()
+        gc.set_threshold(1)
+
+        class A:
+            def __del__(self):
+                dir(self)
+        a = A()
+        del a
 
-    gc.enable()
-    try:
-        run_test("bug1055820c", test_bug1055820c)
-    finally:
         gc.disable()
+        gc.set_threshold(*thresholds)
 
-    gc.enable()
-    try:
-        run_test("bug1055820d", test_bug1055820d)
-    finally:
+    def test_del_newclass(self):
+        # __del__ methods can trigger collection, make this to happen
+        thresholds = gc.get_threshold()
+        gc.enable()
+        gc.set_threshold(1)
+
+        class A(object):
+            def __del__(self):
+                dir(self)
+        a = A()
+        del a
+
+        gc.disable()
+        gc.set_threshold(*thresholds)
+
+    def test_get_count(self):
+        gc.collect()
+        self.assertEqual(gc.get_count(), (0, 0, 0))
+        a = dict()
+        self.assertEqual(gc.get_count(), (1, 0, 0))
+
+    def test_collect_generations(self):
+        gc.collect()
+        a = dict()
+        gc.collect(0)
+        self.assertEqual(gc.get_count(), (0, 1, 0))
+        gc.collect(1)
+        self.assertEqual(gc.get_count(), (0, 0, 1))
+        gc.collect(2)
+        self.assertEqual(gc.get_count(), (0, 0, 0))
+
+    def test_trashcan(self):
+        class Ouch:
+            n = 0
+            def __del__(self):
+                Ouch.n = Ouch.n + 1
+                if Ouch.n % 17 == 0:
+                    gc.collect()
+
+        # "trashcan" is a hack to prevent stack overflow when deallocating
+        # very deeply nested tuples etc.  It works in part by abusing the
+        # type pointer and refcount fields, and that can yield horrible
+        # problems when gc tries to traverse the structures.
+        # If this test fails (as it does in 2.0, 2.1 and 2.2), it will
+        # most likely die via segfault.
+
+        # Note:  In 2.3 the possibility for compiling without cyclic gc was
+        # removed, and that in turn allows the trashcan mechanism to work
+        # via much simpler means (e.g., it never abuses the type pointer or
+        # refcount fields anymore).  Since it's much less likely to cause a
+        # problem now, the various constants in this expensive (we force a lot
+        # of full collections) test are cut back from the 2.2 version.
+        gc.enable()
+        N = 150
+        for count in range(2):
+            t = []
+            for i in range(N):
+                t = [t, Ouch()]
+            u = []
+            for i in range(N):
+                u = [u, Ouch()]
+            v = {}
+            for i in range(N):
+                v = {1: v, 2: Ouch()}
+        gc.disable()
+
+    def test_boom(self):
+        class Boom:
+            def __getattr__(self, someattribute):
+                del self.attr
+                raise AttributeError
+
+        a = Boom()
+        b = Boom()
+        a.attr = b
+        b.attr = a
+
+        gc.collect()
+        garbagelen = len(gc.garbage)
+        del a, b
+        # a<->b are in a trash cycle now.  Collection will invoke
+        # Boom.__getattr__ (to see whether a and b have __del__ methods), and
+        # __getattr__ deletes the internal "attr" attributes as a side effect.
+        # That causes the trash cycle to get reclaimed via refcounts falling to
+        # 0, thus mutating the trash graph as a side effect of merely asking
+        # whether __del__ exists.  This used to (before 2.3b1) crash Python.
+        # Now __getattr__ isn't called.
+        self.assertEqual(gc.collect(), 4)
+        self.assertEqual(len(gc.garbage), garbagelen)
+
+    def test_boom2(self):
+        class Boom2:
+            def __init__(self):
+                self.x = 0
+
+            def __getattr__(self, someattribute):
+                self.x += 1
+                if self.x > 1:
+                    del self.attr
+                raise AttributeError
+
+        a = Boom2()
+        b = Boom2()
+        a.attr = b
+        b.attr = a
+
+        gc.collect()
+        garbagelen = len(gc.garbage)
+        del a, b
+        # Much like test_boom(), except that __getattr__ doesn't break the
+        # cycle until the second time gc checks for __del__.  As of 2.3b1,
+        # there isn't a second time, so this simply cleans up the trash cycle.
+        # We expect a, b, a.__dict__ and b.__dict__ (4 objects) to get
+        # reclaimed this way.
+        self.assertEqual(gc.collect(), 4)
+        self.assertEqual(len(gc.garbage), garbagelen)
+
+    def test_boom_new(self):
+        # boom__new and boom2_new are exactly like boom and boom2, except use
+        # new-style classes.
+
+        class Boom_New(object):
+            def __getattr__(self, someattribute):
+                del self.attr
+                raise AttributeError
+
+        a = Boom_New()
+        b = Boom_New()
+        a.attr = b
+        b.attr = a
+
+        gc.collect()
+        garbagelen = len(gc.garbage)
+        del a, b
+        self.assertEqual(gc.collect(), 4)
+        self.assertEqual(len(gc.garbage), garbagelen)
+
+    def test_boom2_new(self):
+        class Boom2_New(object):
+            def __init__(self):
+                self.x = 0
+
+            def __getattr__(self, someattribute):
+                self.x += 1
+                if self.x > 1:
+                    del self.attr
+                raise AttributeError
+
+        a = Boom2_New()
+        b = Boom2_New()
+        a.attr = b
+        b.attr = a
+
+        gc.collect()
+        garbagelen = len(gc.garbage)
+        del a, b
+        self.assertEqual(gc.collect(), 4)
+        self.assertEqual(len(gc.garbage), garbagelen)
+
+    def test_get_referents(self):
+        alist = [1, 3, 5]
+        got = gc.get_referents(alist)
+        got.sort()
+        self.assertEqual(got, alist)
+
+        atuple = tuple(alist)
+        got = gc.get_referents(atuple)
+        got.sort()
+        self.assertEqual(got, alist)
+
+        adict = {1: 3, 5: 7}
+        expected = [1, 3, 5, 7]
+        got = gc.get_referents(adict)
+        got.sort()
+        self.assertEqual(got, expected)
+
+        got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0))
+        got.sort()
+        self.assertEqual(got, [0, 0] + list(range(5)))
+
+        self.assertEqual(gc.get_referents(1, 'a', 4j), [])
+
+    def test_bug1055820b(self):
+        # Corresponds to temp2b.py in the bug report.
+
+        ouch = []
+        def callback(ignored):
+            ouch[:] = [wr() for wr in WRs]
+
+        Cs = [C1055820(i) for i in range(2)]
+        WRs = [weakref.ref(c, callback) for c in Cs]
+        c = None
+
+        gc.collect()
+        self.assertEqual(len(ouch), 0)
+        # Make the two instances trash, and collect again.  The bug was that
+        # the callback materialized a strong reference to an instance, but gc
+        # cleared the instance's dict anyway.
+        Cs = None
+        gc.collect()
+        self.assertEqual(len(ouch), 2)  # else the callbacks didn't run
+        for x in ouch:
+            # If the callback resurrected one of these guys, the instance
+            # would be damaged, with an empty __dict__.
+            self.assertEqual(x, None)
+
+class GCTogglingTests(unittest.TestCase):
+    def setUp(self):
+        gc.enable()
+
+    def tearDown(self):
         gc.disable()
 
-def test():
-    if verbose:
-        print("disabling automatic collection")
+    def test_bug1055820c(self):
+        # Corresponds to temp2c.py in the bug report.  This is pretty
+        # elaborate.
+
+        c0 = C1055820(0)
+        # Move c0 into generation 2.
+        gc.collect()
+
+        c1 = C1055820(1)
+        c1.keep_c0_alive = c0
+        del c0.loop # now only c1 keeps c0 alive
+
+        c2 = C1055820(2)
+        c2wr = weakref.ref(c2) # no callback!
+
+        ouch = []
+        def callback(ignored):
+            ouch[:] = [c2wr()]
+
+        # The callback gets associated with a wr on an object in generation 2.
+        c0wr = weakref.ref(c0, callback)
+
+        c0 = c1 = c2 = None
+
+        # What we've set up:  c0, c1, and c2 are all trash now.  c0 is in
+        # generation 2.  The only thing keeping it alive is that c1 points to
+        # it. c1 and c2 are in generation 0, and are in self-loops.  There's a
+        # global weakref to c2 (c2wr), but that weakref has no callback.
+        # There's also a global weakref to c0 (c0wr), and that does have a
+        # callback, and that callback references c2 via c2wr().
+        #
+        #               c0 has a wr with callback, which references c2wr
+        #               ^
+        #               |
+        #               |     Generation 2 above dots
+        #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
+        #               |     Generation 0 below dots
+        #               |
+        #               |
+        #            ^->c1   ^->c2 has a wr but no callback
+        #            |  |    |  |
+        #            <--v    <--v
+        #
+        # So this is the nightmare:  when generation 0 gets collected, we see
+        # that c2 has a callback-free weakref, and c1 doesn't even have a
+        # weakref.  Collecting generation 0 doesn't see c0 at all, and c0 is
+        # the only object that has a weakref with a callback.  gc clears c1
+        # and c2.  Clearing c1 has the side effect of dropping the refcount on
+        # c0 to 0, so c0 goes away (despite that it's in an older generation)
+        # and c0's wr callback triggers.  That in turn materializes a reference
+        # to c2 via c2wr(), but c2 gets cleared anyway by gc.
+
+        # We want to let gc happen "naturally", to preserve the distinction
+        # between generations.
+        junk = []
+        i = 0
+        detector = GC_Detector()
+        while not detector.gc_happened:
+            i += 1
+            if i > 10000:
+                self.fail("gc didn't happen after 10000 iterations")
+            self.assertEqual(len(ouch), 0)
+            junk.append([])  # this will eventually trigger gc
+
+        self.assertEqual(len(ouch), 1)  # else the callback wasn't invoked
+        for x in ouch:
+            # If the callback resurrected c2, the instance would be damaged,
+            # with an empty __dict__.
+            self.assertEqual(x, None)
+
+    def test_bug1055820d(self):
+        # Corresponds to temp2d.py in the bug report.  This is very much like
+        # test_bug1055820c, but uses a __del__ method instead of a weakref
+        # callback to sneak in a resurrection of cyclic trash.
+
+        ouch = []
+        class D(C1055820):
+            def __del__(self):
+                ouch[:] = [c2wr()]
+
+        d0 = D(0)
+        # Move all the above into generation 2.
+        gc.collect()
+
+        c1 = C1055820(1)
+        c1.keep_d0_alive = d0
+        del d0.loop # now only c1 keeps d0 alive
+
+        c2 = C1055820(2)
+        c2wr = weakref.ref(c2) # no callback!
+
+        d0 = c1 = c2 = None
+
+        # What we've set up:  d0, c1, and c2 are all trash now.  d0 is in
+        # generation 2.  The only thing keeping it alive is that c1 points to
+        # it.  c1 and c2 are in generation 0, and are in self-loops.  There's
+        # a global weakref to c2 (c2wr), but that weakref has no callback.
+        # There are no other weakrefs.
+        #
+        #               d0 has a __del__ method that references c2wr
+        #               ^
+        #               |
+        #               |     Generation 2 above dots
+        #. . . . . . . .|. . . . . . . . . . . . . . . . . . . . . . . .
+        #               |     Generation 0 below dots
+        #               |
+        #               |
+        #            ^->c1   ^->c2 has a wr but no callback
+        #            |  |    |  |
+        #            <--v    <--v
+        #
+        # So this is the nightmare:  when generation 0 gets collected, we see
+        # that c2 has a callback-free weakref, and c1 doesn't even have a
+        # weakref.  Collecting generation 0 doesn't see d0 at all.  gc clears
+        # c1 and c2.  Clearing c1 has the side effect of dropping the refcount
+        # on d0 to 0, so d0 goes away (despite that it's in an older
+        # generation) and d0's __del__ triggers.  That in turn materializes
+        # a reference to c2 via c2wr(), but c2 gets cleared anyway by gc.
+
+        # We want to let gc happen "naturally", to preserve the distinction
+        # between generations.
+        detector = GC_Detector()
+        junk = []
+        i = 0
+        while not detector.gc_happened:
+            i += 1
+            if i > 10000:
+                self.fail("gc didn't happen after 10000 iterations")
+            self.assertEqual(len(ouch), 0)
+            junk.append([])  # this will eventually trigger gc
+
+        self.assertEqual(len(ouch), 1)  # else __del__ wasn't invoked
+        for x in ouch:
+            # If __del__ resurrected c2, the instance would be damaged, with an
+            # empty __dict__.
+            self.assertEqual(x, None)
+
+def test_main():
     enabled = gc.isenabled()
     gc.disable()
-    verify(not gc.isenabled())
+    assert not gc.isenabled()
     debug = gc.get_debug()
     gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak
 
     try:
-        test_all()
+        gc.collect() # Delete 2nd generation garbage
+        run_unittest(GCTests, GCTogglingTests)
     finally:
         gc.set_debug(debug)
         # test gc.enable() even if GC is disabled by default
@@ -628,9 +588,9 @@
             print("restoring automatic collection")
         # make sure to always test gc.enable()
         gc.enable()
-        verify(gc.isenabled())
+        assert gc.isenabled()
         if not enabled:
             gc.disable()
 
-
-test()
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_generators.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_generators.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_generators.py	Wed Jul 11 15:40:56 2007
@@ -10,14 +10,14 @@
     1
     2
     >>> g = f()
-    >>> g.next()
+    >>> next(g)
     1
-    >>> g.next()
+    >>> next(g)
     2
 
 "Falling off the end" stops the generator:
 
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
       File "<stdin>", line 2, in g
@@ -31,14 +31,14 @@
     ...     yield 2 # never reached
     ...
     >>> g = f()
-    >>> g.next()
+    >>> next(g)
     1
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
       File "<stdin>", line 3, in f
     StopIteration
-    >>> g.next() # once stopped, can't be resumed
+    >>> next(g) # once stopped, can't be resumed
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
@@ -51,13 +51,13 @@
     ...     yield 2 # never reached
     ...
     >>> g = f()
-    >>> g.next()
+    >>> next(g)
     1
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
@@ -105,7 +105,7 @@
 
     >>> def creator():
     ...     r = yrange(5)
-    ...     print("creator", r.next())
+    ...     print("creator", next(r))
     ...     return r
     ...
     >>> def caller():
@@ -141,10 +141,10 @@
     running:
 
     >>> def g():
-    ...     i = me.next()
+    ...     i = next(me)
     ...     yield i
     >>> me = g()
-    >>> me.next()
+    >>> next(me)
     Traceback (most recent call last):
      ...
       File "<string>", line 2, in g
@@ -185,13 +185,13 @@
     ...     yield f()  # the zero division exception propagates
     ...     yield 42   # and we'll never get here
     >>> k = g()
-    >>> k.next()
+    >>> next(k)
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
       File "<stdin>", line 2, in g
       File "<stdin>", line 2, in f
     ZeroDivisionError: integer division or modulo by zero
-    >>> k.next()  # and the generator cannot be resumed
+    >>> next(k)  # and the generator cannot be resumed
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
     StopIteration
@@ -343,7 +343,7 @@
 ...         for c in gcomb(rest, k):
 ...             yield c
 
->>> seq = range(1, 5)
+>>> seq = list(range(1, 5))
 >>> for k in range(len(seq) + 2):
 ...     print("%d-combs of %s:" % (k, seq))
 ...     for c in gcomb(seq, k):
@@ -382,9 +382,9 @@
 >>> type(i)
 <type 'generator'>
 >>> [s for s in dir(i) if not s.startswith('_')]
-['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
->>> print(i.next.__doc__)
-x.next() -> the next value, or raise StopIteration
+['close', 'gi_frame', 'gi_running', 'send', 'throw']
+>>> print(i.__next__.__doc__)
+x.__next__() <==> next(x)
 >>> iter(i) is i
 True
 >>> import types
@@ -400,13 +400,13 @@
 >>> i.gi_running = 42
 Traceback (most recent call last):
   ...
-TypeError: readonly attribute
+AttributeError: readonly attribute
 >>> def g():
 ...     yield me.gi_running
 >>> me = g()
 >>> me.gi_running
 0
->>> me.next()
+>>> next(me)
 1
 >>> me.gi_running
 0
@@ -429,7 +429,7 @@
 ...             yield x
 ...
 ...     def find(self):
-...         return self.generator.next()
+...         return next(self.generator)
 ...
 ...     def union(self, parent):
 ...         if self.parent:
@@ -493,7 +493,7 @@
 Build up to a recursive Sieve of Eratosthenes generator.
 
 >>> def firstn(g, n):
-...     return [g.next() for i in range(n)]
+...     return [next(g) for i in range(n)]
 
 >>> def intsfrom(i):
 ...     while 1:
@@ -512,7 +512,7 @@
 [1, 2, 4, 5, 7, 8]
 
 >>> def sieve(ints):
-...     prime = ints.next()
+...     prime = next(ints)
 ...     yield prime
 ...     not_divisible_by_prime = exclude_multiples(prime, ints)
 ...     for p in sieve(not_divisible_by_prime):
@@ -536,19 +536,19 @@
 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
 
 >>> def merge(g, h):
-...     ng = g.next()
-...     nh = h.next()
+...     ng = next(g)
+...     nh = next(h)
 ...     while 1:
 ...         if ng < nh:
 ...             yield ng
-...             ng = g.next()
+...             ng = next(g)
 ...         elif ng > nh:
 ...             yield nh
-...             nh = h.next()
+...             nh = next(h)
 ...         else:
 ...             yield ng
-...             ng = g.next()
-...             nh = h.next()
+...             ng = next(g)
+...             nh = next(h)
 
 The following works, but is doing a whale of a lot of redundant work --
 it's not clear how to get the internal uses of m235 to share a single
@@ -589,7 +589,7 @@
 >>> class LazyList:
 ...     def __init__(self, g):
 ...         self.sofar = []
-...         self.fetch = g.next
+...         self.fetch = g.__next__
 ...
 ...     def __getitem__(self, i):
 ...         sofar, fetch = self.sofar, self.fetch
@@ -626,10 +626,10 @@
 ...
 ...     def sum(g, h):
 ...         while 1:
-...             yield g.next() + h.next()
+...             yield next(g) + next(h)
 ...
 ...     def tail(g):
-...         g.next()    # throw first away
+...         next(g)    # throw first away
 ...         for x in g:
 ...             yield x
 ...
@@ -705,12 +705,12 @@
 ...
 ...     def _isum(g, h):
 ...         while 1:
-...             yield g.next() + h.next()
+...             yield next(g) + next(h)
 ...
 ...     def _fib():
 ...         yield 1
 ...         yield 2
-...         fibTail.next() # throw first away
+...         next(fibTail) # throw first away
 ...         for res in _isum(fibHead, fibTail):
 ...             yield res
 ...
@@ -890,13 +890,13 @@
 ...             yield i
 ...
 >>> g = f()
->>> print(g.next())
+>>> print(next(g))
 0
->>> print(g.next())
+>>> print(next(g))
 1
->>> print(g.next())
+>>> print(next(g))
 2
->>> print(g.next())
+>>> print(next(g))
 Traceback (most recent call last):
 StopIteration
 """
@@ -1013,7 +1013,7 @@
         # Descend.
         try:
             while i < n:
-                it = iters[i] = gs[i]().next
+                it = iters[i] = gs[i]().__next__
                 values[i] = it()
                 i += 1
         except _StopIteration:
@@ -1463,7 +1463,7 @@
 ...     print((yield 1))
 ...     yield 2
 >>> g = f()
->>> g.next()
+>>> next(g)
 1
 >>> g.send(42)
 42
@@ -1506,7 +1506,7 @@
 ...         seq.append(count)
 >>> seq = []
 >>> c = coroutine(seq)
->>> c.next()
+>>> next(c)
 >>> print(seq)
 []
 >>> c.send(10)
@@ -1558,7 +1558,7 @@
 ...             print("caught ValueError (%s)" % (v))
 >>> import sys
 >>> g = f()
->>> g.next()
+>>> next(g)
 
 >>> g.throw(ValueError) # type only
 caught ValueError ()
@@ -1642,7 +1642,7 @@
 ...         print("exiting")
 
 >>> g = f()
->>> g.next()
+>>> next(g)
 >>> g.close()
 exiting
 >>> g.close()  # should be no-op now
@@ -1652,7 +1652,7 @@
 >>> def f(): yield      # an even simpler generator
 >>> f().close()         # close before opening
 >>> g = f()
->>> g.next()
+>>> next(g)
 >>> g.close()           # close normally
 
 And finalization:
@@ -1663,7 +1663,7 @@
 ...         print("exiting")
 
 >>> g = f()
->>> g.next()
+>>> next(g)
 >>> del g
 exiting
 
@@ -1675,7 +1675,7 @@
 ...     except GeneratorExit:
 ...         yield "foo!"
 >>> g = f()
->>> g.next()
+>>> next(g)
 >>> g.close()
 Traceback (most recent call last):
   ...
@@ -1688,10 +1688,10 @@
 >>> import sys, StringIO
 >>> old, sys.stderr = sys.stderr, StringIO.StringIO()
 >>> g = f()
->>> g.next()
+>>> next(g)
 >>> del g
 >>> sys.stderr.getvalue().startswith(
-...     "Exception exceptions.RuntimeError: 'generator ignored GeneratorExit' in "
+...     "Exception RuntimeError: 'generator ignored GeneratorExit' in "
 ... )
 True
 >>> sys.stderr = old
@@ -1704,7 +1704,7 @@
 ...     except GeneratorExit:
 ...         raise TypeError("fie!")
 >>> g = f()
->>> g.next()
+>>> next(g)
 >>> g.close()
 Traceback (most recent call last):
   ...
@@ -1760,7 +1760,7 @@
 ...     class gen:
 ...         def __iter__(self):
 ...             return self
-...         def next(self):
+...         def __next__(self):
 ...             return self.item
 ...     g = gen()
 ...     head, tail = itertools.tee(g)
@@ -1771,7 +1771,7 @@
 Make sure to also test the involvement of the tee-internal teedataobject,
 which stores returned items.
 
->>> item = it.next()
+>>> item = next(it)
 
 
 
@@ -1808,7 +1808,7 @@
 ...     del l
 ...     err = sys.stderr.getvalue().strip()
 ...     err.startswith(
-...         "Exception exceptions.RuntimeError: RuntimeError() in <"
+...         "Exception RuntimeError: RuntimeError() in <"
 ...     )
 ...     err.endswith("> ignored")
 ...     len(err.splitlines())

Modified: python/branches/p3yk-noslice/Lib/test/test_genexps.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_genexps.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_genexps.py	Wed Jul 11 15:40:56 2007
@@ -34,24 +34,24 @@
 Test direct calls to next()
 
     >>> g = (i*i for i in range(3))
-    >>> g.next()
+    >>> next(g)
     0
-    >>> g.next()
+    >>> next(g)
     1
-    >>> g.next()
+    >>> next(g)
     4
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<pyshell#21>", line 1, in -toplevel-
-        g.next()
+        next(g)
     StopIteration
 
 Does it stay stopped?
 
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<pyshell#21>", line 1, in -toplevel-
-        g.next()
+        next(g)
     StopIteration
     >>> list(g)
     []
@@ -59,16 +59,16 @@
 Test running gen when defining function is out of scope
 
     >>> def f(n):
-    ...     return (i*i for i in xrange(n))
+    ...     return (i*i for i in range(n))
     >>> list(f(10))
     [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
 
     >>> def f(n):
-    ...     return ((i,j) for i in xrange(3) for j in xrange(n))
+    ...     return ((i,j) for i in range(3) for j in range(n))
     >>> list(f(4))
     [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
     >>> def f(n):
-    ...     return ((i,j) for i in xrange(3) for j in xrange(4) if j in xrange(n))
+    ...     return ((i,j) for i in range(3) for j in range(4) if j in range(n))
     >>> list(f(4))
     [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
     >>> list(f(2))
@@ -77,21 +77,21 @@
 Verify that parenthesis are required in a statement
 
     >>> def f(n):
-    ...     return i*i for i in xrange(n)
+    ...     return i*i for i in range(n)
     Traceback (most recent call last):
        ...
     SyntaxError: invalid syntax
 
 Verify that parenthesis are required when used as a keyword argument value
 
-    >>> dict(a = i for i in xrange(10))
+    >>> dict(a = i for i in range(10))
     Traceback (most recent call last):
        ...
     SyntaxError: invalid syntax
 
 Verify that parenthesis are required when used as a keyword argument value
 
-    >>> dict(a = (i for i in xrange(10))) #doctest: +ELLIPSIS
+    >>> dict(a = (i for i in range(10))) #doctest: +ELLIPSIS
     {'a': <generator object at ...>}
 
 Verify early binding for the outermost for-expression
@@ -128,7 +128,7 @@
 
 Verify re-use of tuples (a side benefit of using genexps over listcomps)
 
-    >>> tupleids = map(id, ((i,i) for i in xrange(10)))
+    >>> tupleids = list(map(id, ((i,i) for i in range(10))))
     >>> int(max(tupleids) - min(tupleids))
     0
 
@@ -149,7 +149,7 @@
 
 Make a generator that acts like range()
 
-    >>> yrange = lambda n:  (i for i in xrange(n))
+    >>> yrange = lambda n:  (i for i in range(n))
     >>> list(yrange(10))
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
@@ -157,7 +157,7 @@
 
     >>> def creator():
     ...     r = yrange(5)
-    ...     print("creator", r.next())
+    ...     print("creator", next(r))
     ...     return r
     >>> def caller():
     ...     r = creator()
@@ -181,48 +181,48 @@
 
 Verify that a gen exp cannot be resumed while it is actively running:
 
-    >>> g = (me.next() for i in xrange(10))
+    >>> g = (next(me) for i in range(10))
     >>> me = g
-    >>> me.next()
+    >>> next(me)
     Traceback (most recent call last):
       File "<pyshell#30>", line 1, in -toplevel-
-        me.next()
+        next(me)
       File "<pyshell#28>", line 1, in <generator expression>
-        g = (me.next() for i in xrange(10))
+        g = (next(me) for i in range(10))
     ValueError: generator already executing
 
 Verify exception propagation
 
     >>> g = (10 // i for i in (5, 0, 2))
-    >>> g.next()
+    >>> next(g)
     2
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<pyshell#37>", line 1, in -toplevel-
-        g.next()
+        next(g)
       File "<pyshell#35>", line 1, in <generator expression>
         g = (10 // i for i in (5, 0, 2))
     ZeroDivisionError: integer division or modulo by zero
-    >>> g.next()
+    >>> next(g)
     Traceback (most recent call last):
       File "<pyshell#38>", line 1, in -toplevel-
-        g.next()
+        next(g)
     StopIteration
 
 Make sure that None is a valid return value
 
-    >>> list(None for i in xrange(10))
+    >>> list(None for i in range(10))
     [None, None, None, None, None, None, None, None, None, None]
 
 Check that generator attributes are present
 
     >>> g = (i*i for i in range(3))
-    >>> expected = set(['gi_frame', 'gi_running', 'next'])
+    >>> expected = set(['gi_frame', 'gi_running'])
     >>> set(attr for attr in dir(g) if not attr.startswith('__')) >= expected
     True
 
-    >>> print(g.next.__doc__)
-    x.next() -> the next value, or raise StopIteration
+    >>> print(g.__next__.__doc__)
+    x.__next__() <==> next(x)
     >>> import types
     >>> isinstance(g, types.GeneratorType)
     True
@@ -238,7 +238,7 @@
     >>> me = g
     >>> me.gi_running
     0
-    >>> me.next()
+    >>> next(me)
     1
     >>> me.gi_running
     0
@@ -270,7 +270,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_doctest(test_genexps, verbose)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_getopt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_getopt.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_getopt.py	Wed Jul 11 15:40:56 2007
@@ -1,180 +1,179 @@
 # test_getopt.py
 # David Goodger <dgoodger at bigfoot.com> 2000-08-19
 
+from test.test_support import verbose, run_doctest, run_unittest
+import unittest
+
 import getopt
-from getopt import GetoptError
-from test.test_support import verify, verbose, run_doctest
 import os
 
-def expectException(teststr, expected, failure=AssertionError):
-    """Executes a statement passed in teststr, and raises an exception
-       (failure) if the expected exception is *not* raised."""
-    try:
-        exec(teststr)
-    except expected:
-        pass
-    else:
-        raise failure
-
-old_posixly_correct = os.environ.get("POSIXLY_CORRECT")
-if old_posixly_correct is not None:
-    del os.environ["POSIXLY_CORRECT"]
-
-if verbose:
-    print('Running tests on getopt.short_has_arg')
-verify(getopt.short_has_arg('a', 'a:'))
-verify(not getopt.short_has_arg('a', 'a'))
-expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError)
-expectException("tmp = getopt.short_has_arg('a', '')", GetoptError)
-
-if verbose:
-    print('Running tests on getopt.long_has_args')
-has_arg, option = getopt.long_has_args('abc', ['abc='])
-verify(has_arg)
-verify(option == 'abc')
-has_arg, option = getopt.long_has_args('abc', ['abc'])
-verify(not has_arg)
-verify(option == 'abc')
-has_arg, option = getopt.long_has_args('abc', ['abcd'])
-verify(not has_arg)
-verify(option == 'abcd')
-expectException("has_arg, option = getopt.long_has_args('abc', ['def'])",
-                GetoptError)
-expectException("has_arg, option = getopt.long_has_args('abc', [])",
-                GetoptError)
-expectException("has_arg, option = " + \
-                     "getopt.long_has_args('abc', ['abcd','abcde'])",
-                GetoptError)
-
-if verbose:
-    print('Running tests on getopt.do_shorts')
-opts, args = getopt.do_shorts([], 'a', 'a', [])
-verify(opts == [('-a', '')])
-verify(args == [])
-opts, args = getopt.do_shorts([], 'a1', 'a:', [])
-verify(opts == [('-a', '1')])
-verify(args == [])
-#opts, args = getopt.do_shorts([], 'a=1', 'a:', [])
-#verify(opts == [('-a', '1')])
-#verify(args == [])
-opts, args = getopt.do_shorts([], 'a', 'a:', ['1'])
-verify(opts == [('-a', '1')])
-verify(args == [])
-opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2'])
-verify(opts == [('-a', '1')])
-verify(args == ['2'])
-expectException("opts, args = getopt.do_shorts([], 'a1', 'a', [])",
-                GetoptError)
-expectException("opts, args = getopt.do_shorts([], 'a', 'a:', [])",
-                GetoptError)
-
-if verbose:
-    print('Running tests on getopt.do_longs')
-opts, args = getopt.do_longs([], 'abc', ['abc'], [])
-verify(opts == [('--abc', '')])
-verify(args == [])
-opts, args = getopt.do_longs([], 'abc=1', ['abc='], [])
-verify(opts == [('--abc', '1')])
-verify(args == [])
-opts, args = getopt.do_longs([], 'abc=1', ['abcd='], [])
-verify(opts == [('--abcd', '1')])
-verify(args == [])
-opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], [])
-verify(opts == [('--abc', '')])
-verify(args == [])
-# Much like the preceding, except with a non-alpha character ("-") in
-# option name that precedes "="; failed in
-# http://sourceforge.net/bugs/?func=detailbug&bug_id=126863&group_id=5470
-opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], [])
-verify(opts == [('--foo', '42')])
-verify(args == [])
-expectException("opts, args = getopt.do_longs([], 'abc=1', ['abc'], [])",
-                GetoptError)
-expectException("opts, args = getopt.do_longs([], 'abc', ['abc='], [])",
-                GetoptError)
-
-# note: the empty string between '-a' and '--beta' is significant:
-# it simulates an empty string option argument ('-a ""') on the command line.
-cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a', '',
-           '--beta', 'arg1', 'arg2']
-
-if verbose:
-    print('Running tests on getopt.getopt')
-opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
-verify(opts == [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''),
-                ('-a', '3'), ('-a', ''), ('--beta', '')] )
-# Note ambiguity of ('-b', '') and ('-a', '') above. This must be
-# accounted for in the code that calls getopt().
-verify(args == ['arg1', 'arg2'])
-
-expectException(
-    "opts, args = getopt.getopt(cmdline, 'a:b', ['alpha', 'beta'])",
-    GetoptError)
-
-# Test handling of GNU style scanning mode.
-if verbose:
-    print('Running tests on getopt.gnu_getopt')
-cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
-# GNU style
-opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
-verify(opts == [('-a', ''), ('-b', '1'), ('--alpha', ''), ('--beta', '2')])
-verify(args == ['arg1'])
-# Posix style via +
-opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta='])
-verify(opts == [('-a', '')])
-verify(args == ['arg1', '-b', '1', '--alpha', '--beta=2'])
-# Posix style via POSIXLY_CORRECT
-os.environ["POSIXLY_CORRECT"] = "1"
-opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
-verify(opts == [('-a', '')])
-verify(args == ['arg1', '-b', '1', '--alpha', '--beta=2'])
-
-
-if old_posixly_correct is None:
-    del os.environ["POSIXLY_CORRECT"]
-else:
-    os.environ["POSIXLY_CORRECT"] = old_posixly_correct
-
-#------------------------------------------------------------------------------
-
-libreftest = """
-Examples from the Library Reference:  Doc/lib/libgetopt.tex
-
-An example using only Unix style options:
-
-
->>> import getopt
->>> args = '-a -b -cfoo -d bar a1 a2'.split()
->>> args
-['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
->>> optlist, args = getopt.getopt(args, 'abc:d:')
->>> optlist
-[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
->>> args
-['a1', 'a2']
-
-Using long option names is equally easy:
-
-
->>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
->>> args = s.split()
->>> args
-['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
->>> optlist, args = getopt.getopt(args, 'x', [
-...     'condition=', 'output-file=', 'testing'])
->>> optlist
-[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
->>> args
-['a1', 'a2']
-
-"""
-
-__test__ = {'libreftest' : libreftest}
+sentinel = object()
+
+class GetoptTests(unittest.TestCase):
+    def setUp(self):
+        self.old_posixly_correct = os.environ.get("POSIXLY_CORRECT", sentinel)
+        if self.old_posixly_correct is not sentinel:
+            del os.environ["POSIXLY_CORRECT"]
+
+    def tearDown(self):
+        if self.old_posixly_correct is sentinel:
+            os.environ.pop("POSIXLY_CORRECT", None)
+        else:
+            os.environ["POSIXLY_CORRECT"] = self.old_posixly_correct
+
+    def assertError(self, *args, **kwargs):
+        self.assertRaises(getopt.GetoptError, *args, **kwargs)
+
+    def test_short_has_arg(self):
+        self.failUnless(getopt.short_has_arg('a', 'a:'))
+        self.failIf(getopt.short_has_arg('a', 'a'))
+        self.assertError(getopt.short_has_arg, 'a', 'b')
+
+    def test_long_has_args(self):
+        has_arg, option = getopt.long_has_args('abc', ['abc='])
+        self.failUnless(has_arg)
+        self.assertEqual(option, 'abc')
+
+        has_arg, option = getopt.long_has_args('abc', ['abc'])
+        self.failIf(has_arg)
+        self.assertEqual(option, 'abc')
+
+        has_arg, option = getopt.long_has_args('abc', ['abcd'])
+        self.failIf(has_arg)
+        self.assertEqual(option, 'abcd')
+
+        self.assertError(getopt.long_has_args, 'abc', ['def'])
+        self.assertError(getopt.long_has_args, 'abc', [])
+        self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde'])
+
+    def test_do_shorts(self):
+        opts, args = getopt.do_shorts([], 'a', 'a', [])
+        self.assertEqual(opts, [('-a', '')])
+        self.assertEqual(args, [])
+
+        opts, args = getopt.do_shorts([], 'a1', 'a:', [])
+        self.assertEqual(opts, [('-a', '1')])
+        self.assertEqual(args, [])
+
+        #opts, args = getopt.do_shorts([], 'a=1', 'a:', [])
+        #self.assertEqual(opts, [('-a', '1')])
+        #self.assertEqual(args, [])
+
+        opts, args = getopt.do_shorts([], 'a', 'a:', ['1'])
+        self.assertEqual(opts, [('-a', '1')])
+        self.assertEqual(args, [])
+
+        opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2'])
+        self.assertEqual(opts, [('-a', '1')])
+        self.assertEqual(args, ['2'])
+
+        self.assertError(getopt.do_shorts, [], 'a1', 'a', [])
+        self.assertError(getopt.do_shorts, [], 'a', 'a:', [])
+
+    def test_do_longs(self):
+        opts, args = getopt.do_longs([], 'abc', ['abc'], [])
+        self.assertEqual(opts, [('--abc', '')])
+        self.assertEqual(args, [])
+
+        opts, args = getopt.do_longs([], 'abc=1', ['abc='], [])
+        self.assertEqual(opts, [('--abc', '1')])
+        self.assertEqual(args, [])
+
+        opts, args = getopt.do_longs([], 'abc=1', ['abcd='], [])
+        self.assertEqual(opts, [('--abcd', '1')])
+        self.assertEqual(args, [])
+
+        opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], [])
+        self.assertEqual(opts, [('--abc', '')])
+        self.assertEqual(args, [])
+
+        # Much like the preceding, except with a non-alpha character ("-") in
+        # option name that precedes "="; failed in
+        # http://python.org/sf/126863
+        opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], [])
+        self.assertEqual(opts, [('--foo', '42')])
+        self.assertEqual(args, [])
+
+        self.assertError(getopt.do_longs, [], 'abc=1', ['abc'], [])
+        self.assertError(getopt.do_longs, [], 'abc', ['abc='], [])
+
+    def test_getopt(self):
+        # note: the empty string between '-a' and '--beta' is significant:
+        # it simulates an empty string option argument ('-a ""') on the
+        # command line.
+        cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a',
+                   '', '--beta', 'arg1', 'arg2']
+
+        opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
+        self.assertEqual(opts, [('-a', '1'), ('-b', ''),
+                                ('--alpha', '2'), ('--beta', ''),
+                                ('-a', '3'), ('-a', ''), ('--beta', '')])
+        # Note ambiguity of ('-b', '') and ('-a', '') above. This must be
+        # accounted for in the code that calls getopt().
+        self.assertEqual(args, ['arg1', 'arg2'])
+
+        self.assertError(getopt.getopt, cmdline, 'a:b', ['alpha', 'beta'])
+
+    def test_gnu_getopt(self):
+        # Test handling of GNU style scanning mode.
+        cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
+
+        # GNU style
+        opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
+        self.assertEqual(args, ['arg1'])
+        self.assertEqual(opts, [('-a', ''), ('-b', '1'),
+                                ('--alpha', ''), ('--beta', '2')])
+
+        # Posix style via +
+        opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta='])
+        self.assertEqual(opts, [('-a', '')])
+        self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
+
+        # Posix style via POSIXLY_CORRECT
+        os.environ["POSIXLY_CORRECT"] = "1"
+        opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
+        self.assertEqual(opts, [('-a', '')])
+        self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
+
+    def test_libref_examples(self):
+        s = """
+        Examples from the Library Reference:  Doc/lib/libgetopt.tex
+
+        An example using only Unix style options:
+
+
+        >>> import getopt
+        >>> args = '-a -b -cfoo -d bar a1 a2'.split()
+        >>> args
+        ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
+        >>> optlist, args = getopt.getopt(args, 'abc:d:')
+        >>> optlist
+        [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
+        >>> args
+        ['a1', 'a2']
+
+        Using long option names is equally easy:
+
+
+        >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
+        >>> args = s.split()
+        >>> args
+        ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
+        >>> optlist, args = getopt.getopt(args, 'x', [
+        ...     'condition=', 'output-file=', 'testing'])
+        >>> optlist
+        [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
+        >>> args
+        ['a1', 'a2']
+        """
+
+        import new
+        m = new.module("libreftest", s)
+        run_doctest(m, verbose)
 
-import sys
-run_doctest(sys.modules[__name__], verbose)
 
-#------------------------------------------------------------------------------
+def test_main():
+    run_unittest(GetoptTests)
 
-if verbose:
-    print("Module getopt: tests completed successfully.")
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_gettext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_gettext.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_gettext.py	Wed Jul 11 15:40:56 2007
@@ -4,7 +4,7 @@
 import gettext
 import unittest
 
-from test.test_support import run_suite
+from test import test_support
 
 
 # TODO:
@@ -336,19 +336,8 @@
            'John Doe <jdoe at example.com>\nJane Foobar <jfoobar at example.com>')
 
 
-def suite():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(GettextTestCase1))
-    suite.addTest(unittest.makeSuite(GettextTestCase2))
-    suite.addTest(unittest.makeSuite(PluralFormsTestCase))
-    suite.addTest(unittest.makeSuite(UnicodeTranslationsTest))
-    suite.addTest(unittest.makeSuite(WeirdMetadataTest))
-    return suite
-
-
 def test_main():
-    run_suite(suite())
-
+    test_support.run_unittest(__name__)
 
 if __name__ == '__main__':
     test_main()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_gl.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_gl.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,150 +0,0 @@
-#! /usr/bin/env python
-"""Very simple test script for the SGI gl library extension module
-    taken mostly from the documentation.
-    Roger E. Masse
-"""
-from test.test_support import verbose, TestSkipped
-import gl, GL, time
-
-glattrs = ['RGBcolor', 'RGBcursor', 'RGBmode', 'RGBrange', 'RGBwritemask',
-'__doc__', '__name__', 'addtopup', 'altgetmatrix', 'arc', 'arcf',
-'arcfi', 'arcfs', 'arci', 'arcs', 'attachcursor', 'backbuffer',
-'backface', 'bbox2', 'bbox2i', 'bbox2s', 'bgnclosedline', 'bgnline',
-'bgnpoint', 'bgnpolygon', 'bgnsurface', 'bgntmesh', 'bgntrim',
-'blankscreen', 'blanktime', 'blendfunction', 'blink', 'c3f', 'c3i',
-'c3s', 'c4f', 'c4i', 'c4s', 'callobj', 'charstr', 'chunksize', 'circ',
-'circf', 'circfi', 'circfs', 'circi', 'circs', 'clear',
-'clearhitcode', 'clkoff', 'clkon', 'closeobj', 'cmode', 'cmov',
-'cmov2', 'cmov2i', 'cmov2s', 'cmovi', 'cmovs', 'color', 'colorf',
-'compactify', 'concave', 'cpack', 'crv', 'crvn', 'curorigin',
-'cursoff', 'curson', 'curstype', 'curvebasis', 'curveit',
-'curveprecision', 'cyclemap', 'czclear', 'defbasis', 'defcursor',
-'deflinestyle', 'delobj', 'deltag', 'depthcue', 'devport', 'dglclose',
-'dglopen', 'dither', 'dopup', 'doublebuffer', 'draw', 'draw2',
-'draw2i', 'draw2s', 'drawi', 'drawmode', 'draws', 'editobj',
-'endclosedline', 'endfullscrn', 'endline', 'endpick', 'endpoint',
-'endpolygon', 'endpupmode', 'endselect', 'endsurface', 'endtmesh',
-'endtrim', 'finish', 'font', 'foreground', 'freepup', 'frontbuffer',
-'fudge', 'fullscrn', 'gRGBcolor', 'gRGBmask', 'gammaramp', 'gbegin',
-'gconfig', 'genobj', 'gentag', 'getbackface', 'getbuffer',
-'getbutton', 'getcmmode', 'getcolor', 'getcpos', 'getcursor',
-'getdcm', 'getdepth', 'getdescender', 'getdisplaymode', 'getdrawmode',
-'getfont', 'getgdesc', 'getgpos', 'getheight', 'gethitcode',
-'getlsbackup', 'getlsrepeat', 'getlstyle', 'getlwidth', 'getmap',
-'getmatrix', 'getmcolor', 'getmmode', 'getmonitor',
-'getnurbsproperty', 'getopenobj', 'getorigin', 'getothermonitor',
-'getpattern', 'getplanes', 'getport', 'getresetls', 'getscrmask',
-'getshade', 'getsize', 'getsm', 'gettp', 'getvaluator', 'getvideo',
-'getviewport', 'getwritemask', 'getzbuffer', 'gewrite', 'gflush',
-'ginit', 'glcompat', 'greset', 'gselect', 'gsync', 'gversion',
-'iconsize', 'icontitle', 'imakebackground', 'initnames', 'ismex',
-'isobj', 'isqueued', 'istag', 'keepaspect', 'lRGBrange', 'lampoff',
-'lampon', 'linesmooth', 'linewidth', 'lmbind', 'lmcolor', 'lmdef',
-'loadmatrix', 'loadname', 'logicop', 'lookat', 'lrectread',
-'lrectwrite', 'lsbackup', 'lsetdepth', 'lshaderange', 'lsrepeat',
-'makeobj', 'maketag', 'mapcolor', 'mapw', 'mapw2', 'maxsize',
-'minsize', 'mmode', 'move', 'move2', 'move2i', 'move2s', 'movei',
-'moves', 'multimap', 'multmatrix', 'n3f', 'newpup', 'newtag',
-'noborder', 'noise', 'noport', 'normal', 'nurbscurve', 'nurbssurface',
-'nvarray', 'objdelete', 'objinsert', 'objreplace', 'onemap', 'ortho',
-'ortho2', 'overlay', 'packrect', 'pagecolor', 'pagewritemask',
-'passthrough', 'patch', 'patchbasis', 'patchcurves', 'patchprecision',
-'pclos', 'pdr', 'pdr2', 'pdr2i', 'pdr2s', 'pdri', 'pdrs',
-'perspective', 'pick', 'picksize', 'pixmode', 'pmv', 'pmv2', 'pmv2i',
-'pmv2s', 'pmvi', 'pmvs', 'pnt', 'pnt2', 'pnt2i', 'pnt2s', 'pnti',
-'pnts', 'pntsmooth', 'polarview', 'polf', 'polf2', 'polf2i', 'polf2s',
-'polfi', 'polfs', 'poly', 'poly2', 'poly2i', 'poly2s', 'polyi',
-'polys', 'popattributes', 'popmatrix', 'popname', 'popviewport',
-'prefposition', 'prefsize', 'pupmode', 'pushattributes', 'pushmatrix',
-'pushname', 'pushviewport', 'pwlcurve', 'qdevice', 'qenter', 'qgetfd',
-'qread', 'qreset', 'qtest', 'rcrv', 'rcrvn', 'rdr', 'rdr2', 'rdr2i',
-'rdr2s', 'rdri', 'rdrs', 'readdisplay', 'readsource', 'rect',
-'rectcopy', 'rectf', 'rectfi', 'rectfs', 'recti', 'rects', 'rectzoom',
-'resetls', 'reshapeviewport', 'ringbell', 'rmv', 'rmv2', 'rmv2i',
-'rmv2s', 'rmvi', 'rmvs', 'rot', 'rotate', 'rpatch', 'rpdr', 'rpdr2',
-'rpdr2i', 'rpdr2s', 'rpdri', 'rpdrs', 'rpmv', 'rpmv2', 'rpmv2i',
-'rpmv2s', 'rpmvi', 'rpmvs', 'sbox', 'sboxf', 'sboxfi', 'sboxfs',
-'sboxi', 'sboxs', 'scale', 'screenspace', 'scrmask', 'setbell',
-'setcursor', 'setdepth', 'setlinestyle', 'setmap', 'setmonitor',
-'setnurbsproperty', 'setpattern', 'setpup', 'setshade', 'setvaluator',
-'setvideo', 'shademodel', 'shaderange', 'singlebuffer', 'smoothline',
-'spclos', 'splf', 'splf2', 'splf2i', 'splf2s', 'splfi', 'splfs',
-'stepunit', 'strwidth', 'subpixel', 'swapbuffers', 'swapinterval',
-'swaptmesh', 'swinopen', 'textcolor', 'textinit', 'textport',
-'textwritemask', 'tie', 'tpoff', 'tpon', 'translate', 'underlay',
-'unpackrect', 'unqdevice', 'v2d', 'v2f', 'v2i', 'v2s', 'v3d', 'v3f',
-'v3i', 'v3s', 'v4d', 'v4f', 'v4i', 'v4s', 'varray', 'videocmd',
-'viewport', 'vnarray', 'winattach', 'winclose', 'winconstraints',
-'windepth', 'window', 'winget', 'winmove', 'winopen', 'winpop',
-'winposition', 'winpush', 'winset', 'wintitle', 'wmpack', 'writemask',
-'writepixels', 'xfpt', 'xfpt2', 'xfpt2i', 'xfpt2s', 'xfpt4', 'xfpt4i',
-'xfpt4s', 'xfpti', 'xfpts', 'zbuffer', 'zclear', 'zdraw', 'zfunction',
-'zsource', 'zwritemask']
-
-def main():
-    # insure that we at least have an X display before continuing.
-    import os
-    try:
-        display = os.environ['DISPLAY']
-    except:
-        raise TestSkipped, "No $DISPLAY -- skipping gl test"
-
-    # touch all the attributes of gl without doing anything
-    if verbose:
-        print('Touching gl module attributes...')
-    for attr in glattrs:
-        if verbose:
-            print('touching: ', attr)
-        getattr(gl, attr)
-
-    # create a small 'Crisscross' window
-    if verbose:
-        print('Creating a small "CrissCross" window...')
-        print('foreground')
-    gl.foreground()
-    if verbose:
-        print('prefposition')
-    gl.prefposition(500, 900, 500, 900)
-    if verbose:
-        print('winopen "CrissCross"')
-    w = gl.winopen('CrissCross')
-    if verbose:
-        print('clear')
-    gl.clear()
-    if verbose:
-        print('ortho2')
-    gl.ortho2(0.0, 400.0, 0.0, 400.0)
-    if verbose:
-        print('color WHITE')
-    gl.color(GL.WHITE)
-    if verbose:
-        print('color RED')
-    gl.color(GL.RED)
-    if verbose:
-        print('bgnline')
-    gl.bgnline()
-    if verbose:
-        print('v2f')
-    gl.v2f(0.0, 0.0)
-    gl.v2f(400.0, 400.0)
-    if verbose:
-        print('endline')
-    gl.endline()
-    if verbose:
-        print('bgnline')
-    gl.bgnline()
-    if verbose:
-        print('v2i')
-    gl.v2i(400, 0)
-    gl.v2i(0, 400)
-    if verbose:
-        print('endline')
-    gl.endline()
-    if verbose:
-        print('Displaying window for 2 seconds...')
-    time.sleep(2)
-    if verbose:
-        print('winclose')
-    gl.winclose(w)
-
-main()

Modified: python/branches/p3yk-noslice/Lib/test/test_glob.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_glob.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_glob.py	Wed Jul 11 15:40:56 2007
@@ -52,6 +52,16 @@
         eq(self.glob('aab'), [self.norm('aab')])
         eq(self.glob('zymurgy'), [])
 
+        # test return types are unicode, but only if os.listdir
+        # returns unicode filenames
+        uniset = set([unicode])
+        tmp = os.listdir(u'.')
+        if set(type(x) for x in tmp) == uniset:
+            u1 = glob.glob(u'*')
+            u2 = glob.glob(u'./*')
+            self.assertEquals(set(type(r) for r in u1), uniset)
+            self.assertEquals(set(type(r) for r in u2), uniset)
+
     def test_glob_one_directory(self):
         eq = self.assertSequencesEqual_noorder
         eq(self.glob('a*'), map(self.norm, ['a', 'aab', 'aaa']))

Modified: python/branches/p3yk-noslice/Lib/test/test_grammar.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_grammar.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_grammar.py	Wed Jul 11 15:40:56 2007
@@ -27,26 +27,32 @@
         self.assertEquals(x, 0, 'backslash ending comment')
 
     def testPlainIntegers(self):
+        self.assertEquals(type(000), type(0))
         self.assertEquals(0xff, 255)
-        self.assertEquals(0377, 255)
-        self.assertEquals(2147483647, 017777777777)
+        self.assertEquals(0o377, 255)
+        self.assertEquals(2147483647, 0o17777777777)
+        self.assertEquals(0b1001, 9)
         from sys import maxint
         if maxint == 2147483647:
-            self.assertEquals(-2147483647-1, -020000000000)
+            self.assertEquals(-2147483647-1, -0o20000000000)
             # XXX -2147483648
-            self.assert_(037777777777 > 0)
+            self.assert_(0o37777777777 > 0)
             self.assert_(0xffffffff > 0)
-            for s in '2147483648', '040000000000', '0x100000000':
+            self.assert_(0b1111111111111111111111111111111 > 0)
+            for s in ('2147483648', '0o40000000000', '0x100000000',
+                      '0b10000000000000000000000000000000'):
                 try:
                     x = eval(s)
                 except OverflowError:
                     self.fail("OverflowError on huge integer literal %r" % s)
         elif maxint == 9223372036854775807:
-            self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
-            self.assert_(01777777777777777777777 > 0)
+            self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
+            self.assert_(0o1777777777777777777777 > 0)
             self.assert_(0xffffffffffffffff > 0)
-            for s in '9223372036854775808', '02000000000000000000000', \
-                     '0x10000000000000000':
+            self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
+            for s in '9223372036854775808', '0o2000000000000000000000', \
+                     '0x10000000000000000', \
+                     '0b100000000000000000000000000000000000000000000000000000000000000':
                 try:
                     x = eval(s)
                 except OverflowError:
@@ -56,13 +62,13 @@
 
     def testLongIntegers(self):
         x = 0
-        x = 0
-        x = 0xffffffffffffffff
         x = 0xffffffffffffffff
-        x = 077777777777777777
-        x = 077777777777777777
-        x = 123456789012345678901234567890
+        x = 0Xffffffffffffffff
+        x = 0o77777777777777777
+        x = 0O77777777777777777
         x = 123456789012345678901234567890
+        x = 0b100000000000000000000000000000000000000000000000000000000000000000000
+        x = 0B111111111111111111111111111111111111111111111111111111111111111111111
 
     def testFloats(self):
         x = 3.14
@@ -121,6 +127,7 @@
     def testEllipsis(self):
         x = ...
         self.assert_(x is Ellipsis)
+        self.assertRaises(SyntaxError, eval, ".. .")
 
 class GrammarTests(unittest.TestCase):
 
@@ -143,51 +150,32 @@
         ### decorators: decorator+
         ### parameters: '(' [typedargslist] ')'
         ### typedargslist: ((tfpdef ['=' test] ',')*
-        ###                ('*' [tname] (',' tname ['=' test])* [',' '**' tname] | '**' tname)
+        ###                ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
         ###                | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
-        ### tname: NAME [':' test]
-        ### tfpdef: tname | '(' tfplist ')'
-        ### tfplist: tfpdef (',' tfpdef)* [',']
+        ### tfpdef: NAME [':' test]
         ### varargslist: ((vfpdef ['=' test] ',')*
-        ###              ('*' [vname] (',' vname ['=' test])*  [',' '**' vname] | '**' vname)
+        ###              ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] | '**' vfpdef)
         ###              | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
-        ### vname: NAME
-        ### vfpdef: vname | '(' vfplist ')'
-        ### vfplist: vfpdef (',' vfpdef)* [',']
+        ### vfpdef: NAME
         def f1(): pass
         f1()
         f1(*())
         f1(*(), **{})
         def f2(one_argument): pass
         def f3(two, arguments): pass
-        def f4(two, (compound, (argument, list))): pass
-        def f5((compound, first), two): pass
-        self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
-        self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
-        if sys.platform.startswith('java'):
-            self.assertEquals(f4.func_code.co_varnames,
-                   ('two', '(compound, (argument, list))', 'compound', 'argument',
-                                'list',))
-            self.assertEquals(f5.func_code.co_varnames,
-                   ('(compound, first)', 'two', 'compound', 'first'))
-        else:
-            self.assertEquals(f4.func_code.co_varnames,
-                  ('two', '.1', 'compound', 'argument',  'list'))
-            self.assertEquals(f5.func_code.co_varnames,
-                  ('.0', 'two', 'compound', 'first'))
+        self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
+        self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
         def a1(one_arg,): pass
         def a2(two, args,): pass
         def v0(*rest): pass
         def v1(a, *rest): pass
         def v2(a, b, *rest): pass
-        def v3(a, (b, c), *rest): return a, b, c, rest
 
         f1()
         f2(1)
         f2(1,)
         f3(1, 2)
         f3(1, 2,)
-        f4(1, (2, (3, 4)))
         v0()
         v0(1)
         v0(1,)
@@ -202,17 +190,7 @@
         v2(1,2,3)
         v2(1,2,3,4)
         v2(1,2,3,4,5,6,7,8,9,0)
-        v3(1,(2,3))
-        v3(1,(2,3),4)
-        v3(1,(2,3),4,5,6,7,8,9,0)
-
-        # ceval unpacks the formal arguments into the first argcount names;
-        # thus, the names nested inside tuples must appear after these names.
-        if sys.platform.startswith('java'):
-            self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
-        else:
-            self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
-        self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
+
         def d01(a=1): pass
         d01()
         d01(1)
@@ -285,10 +263,6 @@
         d22v(*(1, 2, 3, 4))
         d22v(1, 2, *(3, 4, 5))
         d22v(1, *(2, 3), **{'d': 4})
-        def d31v((x)): pass
-        d31v(1)
-        def d32v((x,)): pass
-        d32v((1,))
         # keyword only argument tests
         def pos0key1(*, key): return key
         pos0key1(key=100)
@@ -302,25 +276,37 @@
 
         # argument annotation tests
         def f(x) -> list: pass
-        self.assertEquals(f.func_annotations, {'return': list})
+        self.assertEquals(f.__annotations__, {'return': list})
         def f(x:int): pass
-        self.assertEquals(f.func_annotations, {'x': int})
+        self.assertEquals(f.__annotations__, {'x': int})
         def f(*x:str): pass
-        self.assertEquals(f.func_annotations, {'x': str})
+        self.assertEquals(f.__annotations__, {'x': str})
         def f(**x:float): pass
-        self.assertEquals(f.func_annotations, {'x': float})
+        self.assertEquals(f.__annotations__, {'x': float})
         def f(x, y:1+2): pass
-        self.assertEquals(f.func_annotations, {'y': 3})
-        def f(a, (b:1, c:2, d)): pass
-        self.assertEquals(f.func_annotations, {'b': 1, 'c': 2})
-        def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass
-        self.assertEquals(f.func_annotations,
+        self.assertEquals(f.__annotations__, {'y': 3})
+        def f(a, b:1, c:2, d): pass
+        self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
+        def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
+        self.assertEquals(f.__annotations__,
                           {'b': 1, 'c': 2, 'e': 3, 'g': 6})
-        def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
+        def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
               **k:11) -> 12: pass
-        self.assertEquals(f.func_annotations,
+        self.assertEquals(f.__annotations__,
                           {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
                            'k': 11, 'return': 12})
+        # Check for SF Bug #1697248 - mixing decorators and a return annotation
+        def null(x): return x
+        @null
+        def f(x) -> list: pass
+        self.assertEquals(f.__annotations__, {'return': list})
+
+        # test MAKE_CLOSURE with a variety of oparg's
+        closure = 1
+        def f(): return closure
+        def f(x=1): return closure
+        def f(*, k=1): return closure
+        def f() -> int: return closure
 
     def testLambdef(self):
         ### lambdef: 'lambda' [varargslist] ':' test
@@ -351,7 +337,7 @@
             x = 1; pass; del x;
         foo()
 
-    ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt 
+    ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
     # Tested below
 
     def testExprStmt(self):
@@ -777,9 +763,9 @@
     def testGenexps(self):
         # generator expression tests
         g = ([x for x in range(10)] for x in range(1))
-        self.assertEqual(g.next(), [x for x in range(10)])
+        self.assertEqual(next(g), [x for x in range(10)])
         try:
-            g.next()
+            next(g)
             self.fail('should produce StopIteration exception')
         except StopIteration:
             pass
@@ -787,7 +773,7 @@
         a = 1
         try:
             g = (a for d in a)
-            g.next()
+            next(g)
             self.fail('should produce TypeError')
         except TypeError:
             pass
@@ -835,7 +821,8 @@
             print(x)
             return ret
 
-        self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
+        # the next line is not allowed anymore
+        #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
         self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
         self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
         self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)

Modified: python/branches/p3yk-noslice/Lib/test/test_grp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_grp.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_grp.py	Wed Jul 11 15:40:56 2007
@@ -54,8 +54,8 @@
         namei = 0
         fakename = allnames[namei]
         while fakename in bynames:
-            chars = map(None, fakename)
-            for i in xrange(len(chars)):
+            chars = list(fakename)
+            for i in range(len(chars)):
                 if chars[i] == 'z':
                     chars[i] = 'A'
                     break
@@ -71,7 +71,7 @@
                 except IndexError:
                     # should never happen... if so, just forget it
                     break
-            fakename = ''.join(map(None, chars))
+            fakename = ''.join(chars)
 
         self.assertRaises(KeyError, grp.getgrnam, fakename)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_hash.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_hash.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_hash.py	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,7 @@
     def same_hash(self, *objlist):
         # Hash each object given and fail if
         # the hash values are not all the same.
-        hashed = map(hash, objlist)
+        hashed = list(map(hash, objlist))
         for h in hashed[1:]:
             if h != hashed[0]:
                 self.fail("hashed values differ: %r" % (objlist,))

Modified: python/branches/p3yk-noslice/Lib/test/test_heapq.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_heapq.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_heapq.py	Wed Jul 11 15:40:56 2007
@@ -90,7 +90,7 @@
 
     def test_heapsort(self):
         # Exercise everything with repeated heapsort checks
-        for trial in xrange(100):
+        for trial in range(100):
             size = random.randrange(50)
             data = [random.randrange(25) for i in range(size)]
             if trial & 1:     # Half of the time, use heapify
@@ -105,7 +105,7 @@
 
     def test_merge(self):
         inputs = []
-        for i in xrange(random.randrange(5)):
+        for i in range(random.randrange(5)):
             row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
             inputs.append(row)
         self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs)))
@@ -130,16 +130,17 @@
         data = [(random.randrange(2000), i) for i in range(1000)]
         for f in (None, lambda x:  x[0] * 547 % 2000):
             for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
-                self.assertEqual(nsmallest(n, data), sorted(data)[:n])
-                self.assertEqual(nsmallest(n, data, key=f),
+                self.assertEqual(list(nsmallest(n, data)), sorted(data)[:n])
+                self.assertEqual(list(nsmallest(n, data, key=f)),
                                  sorted(data, key=f)[:n])
 
     def test_nlargest(self):
         data = [(random.randrange(2000), i) for i in range(1000)]
         for f in (None, lambda x:  x[0] * 547 % 2000):
             for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
-                self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n])
-                self.assertEqual(nlargest(n, data, key=f),
+                self.assertEqual(list(nlargest(n, data)),
+                                 sorted(data, reverse=True)[:n])
+                self.assertEqual(list(nlargest(n, data, key=f)),
                                  sorted(data, key=f, reverse=True)[:n])
 
 
@@ -180,7 +181,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
@@ -200,14 +201,14 @@
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
         return v
 
 class N:
-    'Iterator missing next()'
+    'Iterator missing __next__()'
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
@@ -221,7 +222,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         3 // 0
 
 class S:
@@ -230,7 +231,7 @@
         pass
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         raise StopIteration
 
 from itertools import chain, imap
@@ -277,10 +278,10 @@
 
     def test_iterable_args(self):
         for f in  (nlargest, nsmallest):
-            for s in ("123", "", range(1000), (1, 1.2), xrange(2000,2200,5)):
+            for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
                 for g in (G, I, Ig, L, R):
-                    self.assertEqual(f(2, g(s)), f(2,s))
-                self.assertEqual(f(2, S(s)), [])
+                    self.assertEqual(list(f(2, g(s))), list(f(2,s)))
+                self.assertEqual(list(f(2, S(s))), [])
                 self.assertRaises(TypeError, f, 2, X(s))
                 self.assertRaises(TypeError, f, 2, N(s))
                 self.assertRaises(ZeroDivisionError, f, 2, E(s))
@@ -300,7 +301,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_hexoct.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_hexoct.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_hexoct.py	Wed Jul 11 15:40:56 2007
@@ -65,49 +65,49 @@
     def test_oct_baseline(self):
         # Baseline tests
         self.assertEqual(00, 0)
-        self.assertEqual(020, 16)
+        self.assertEqual(0o20, 16)
         if platform_long_is_32_bits:
-            self.assertEqual(017777777777, 2147483647)
+            self.assertEqual(0o17777777777, 2147483647)
         else:
-            self.assertEqual(0777777777777777777777, 9223372036854775807)
+            self.assertEqual(0o777777777777777777777, 9223372036854775807)
         # Ditto with a minus sign and parentheses
         self.assertEqual(-(00), 0)
-        self.assertEqual(-(020), -16)
+        self.assertEqual(-(0o20), -16)
         if platform_long_is_32_bits:
-            self.assertEqual(-(017777777777), -2147483647)
+            self.assertEqual(-(0o17777777777), -2147483647)
         else:
-            self.assertEqual(-(0777777777777777777777), -9223372036854775807)
+            self.assertEqual(-(0o777777777777777777777), -9223372036854775807)
         # Ditto with a minus sign and NO parentheses
         self.assertEqual(-00, 0)
-        self.assertEqual(-020, -16)
+        self.assertEqual(-0o20, -16)
         if platform_long_is_32_bits:
-            self.assertEqual(-017777777777, -2147483647)
+            self.assertEqual(-0o17777777777, -2147483647)
         else:
-            self.assertEqual(-0777777777777777777777, -9223372036854775807)
+            self.assertEqual(-0o777777777777777777777, -9223372036854775807)
 
     def test_oct_unsigned(self):
         if platform_long_is_32_bits:
             # Positive constants
-            self.assertEqual(020000000000, 2147483648)
-            self.assertEqual(037777777777, 4294967295)
+            self.assertEqual(0o20000000000, 2147483648)
+            self.assertEqual(0o37777777777, 4294967295)
             # Ditto with a minus sign and parentheses
-            self.assertEqual(-(020000000000), -2147483648)
-            self.assertEqual(-(037777777777), -4294967295)
+            self.assertEqual(-(0o20000000000), -2147483648)
+            self.assertEqual(-(0o37777777777), -4294967295)
             # Ditto with a minus sign and NO parentheses
             # This failed in Python 2.2 through 2.2.2 and in 2.3a1
-            self.assertEqual(-020000000000, -2147483648)
-            self.assertEqual(-037777777777, -4294967295)
+            self.assertEqual(-0o20000000000, -2147483648)
+            self.assertEqual(-0o37777777777, -4294967295)
         else:
             # Positive constants
-            self.assertEqual(01000000000000000000000, 9223372036854775808)
-            self.assertEqual(01777777777777777777777, 18446744073709551615)
+            self.assertEqual(0o1000000000000000000000, 9223372036854775808)
+            self.assertEqual(0o1777777777777777777777, 18446744073709551615)
             # Ditto with a minus sign and parentheses
-            self.assertEqual(-(01000000000000000000000), -9223372036854775808)
-            self.assertEqual(-(01777777777777777777777), -18446744073709551615)
+            self.assertEqual(-(0o1000000000000000000000), -9223372036854775808)
+            self.assertEqual(-(0o1777777777777777777777), -18446744073709551615)
             # Ditto with a minus sign and NO parentheses
             # This failed in Python 2.2 through 2.2.2 and in 2.3a1
-            self.assertEqual(-01000000000000000000000, -9223372036854775808)
-            self.assertEqual(-01777777777777777777777, -18446744073709551615)
+            self.assertEqual(-0o1000000000000000000000, -9223372036854775808)
+            self.assertEqual(-0o1777777777777777777777, -18446744073709551615)
 
 def test_main():
     test_support.run_unittest(TextHexOct)

Modified: python/branches/p3yk-noslice/Lib/test/test_hmac.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_hmac.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_hmac.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 import hmac
-import sha
+from hashlib import sha1
 import unittest
 from test import test_support
 
@@ -43,7 +43,7 @@
 
     def test_sha_vectors(self):
         def shatest(key, data, digest):
-            h = hmac.HMAC(key, data, digestmod=sha)
+            h = hmac.HMAC(key, data, digestmod=sha1)
             self.assertEqual(h.hexdigest().upper(), digest.upper())
 
         shatest(chr(0x0b) * 20,
@@ -95,11 +95,11 @@
 
     def test_withmodule(self):
         # Constructor call with text and digest module.
-        import sha
+        from hashlib import sha1
         try:
-            h = hmac.HMAC("key", "", sha)
+            h = hmac.HMAC("key", "", sha1)
         except:
-            self.fail("Constructor call with sha module raised exception.")
+            self.fail("Constructor call with hashlib.sha1 raised exception.")
 
 class SanityTestCase(unittest.TestCase):
 

Modified: python/branches/p3yk-noslice/Lib/test/test_hotshot.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_hotshot.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_hotshot.py	Wed Jul 11 15:40:56 2007
@@ -85,8 +85,8 @@
             x = 1
         def g():
             f()
-        f_lineno = f.func_code.co_firstlineno
-        g_lineno = g.func_code.co_firstlineno
+        f_lineno = f.__code__.co_firstlineno
+        g_lineno = g.__code__.co_firstlineno
         events = [(ENTER, ("test_hotshot", g_lineno, "g")),
                   (LINE,  ("test_hotshot", g_lineno+1, "g")),
                   (ENTER, ("test_hotshot", f_lineno, "f")),

Modified: python/branches/p3yk-noslice/Lib/test/test_htmlparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_htmlparser.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_htmlparser.py	Wed Jul 11 15:40:56 2007
@@ -309,6 +309,11 @@
             ("endtag", "script"),
             ])
 
+    def test_entityrefs_in_attributes(self):
+        self._run_check("<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>", [
+                ("starttag", "html", [("foo", u"\u20AC&aa&unsupported;")])
+                ])
+
 
 def test_main():
     test_support.run_unittest(HTMLParserTestCase)

Modified: python/branches/p3yk-noslice/Lib/test/test_httplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_httplib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_httplib.py	Wed Jul 11 15:40:56 2007
@@ -1,6 +1,7 @@
 import httplib
 import StringIO
 import sys
+import socket
 
 from unittest import TestCase
 
@@ -149,8 +150,60 @@
     def test_responses(self):
         self.assertEquals(httplib.responses[httplib.NOT_FOUND], "Not Found")
 
+PORT = 50003
+HOST = "localhost"
+
+class TimeoutTest(TestCase):
+
+    def setUp(self):
+        self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+        global PORT
+        PORT = test_support.bind_port(self.serv, HOST, PORT)
+        self.serv.listen(5)
+
+    def tearDown(self):
+        self.serv.close()
+        self.serv = None
+
+    def testTimeoutAttribute(self):
+        '''This will prove that the timeout gets through
+        HTTPConnection and into the socket.
+        '''
+        # default
+        httpConn = httplib.HTTPConnection(HOST, PORT)
+        httpConn.connect()
+        self.assertTrue(httpConn.sock.gettimeout() is None)
+        httpConn.close()
+
+        # a value
+        httpConn = httplib.HTTPConnection(HOST, PORT, timeout=30)
+        httpConn.connect()
+        self.assertEqual(httpConn.sock.gettimeout(), 30)
+        httpConn.close()
+
+        # None, having other default
+        previous = socket.getdefaulttimeout()
+        socket.setdefaulttimeout(30)
+        try:
+            httpConn = httplib.HTTPConnection(HOST, PORT, timeout=None)
+            httpConn.connect()
+        finally:
+            socket.setdefaulttimeout(previous)
+        self.assertEqual(httpConn.sock.gettimeout(), 30)
+        httpConn.close()
+
+
+class HTTPSTimeoutTest(TestCase):
+# XXX Here should be tests for HTTPS, there isn't any right now!
+
+    def test_attributes(self):
+        # simple test to check it's storing it
+        h = httplib.HTTPSConnection(HOST, PORT, timeout=30)
+        self.assertEqual(h.timeout, 30)
+
 def test_main(verbose=None):
-    test_support.run_unittest(HeaderTests, OfflineTest, BasicTest)
+    test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, HTTPSTimeoutTest)
 
 if __name__ == '__main__':
     test_main()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_imageop.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_imageop.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,177 +0,0 @@
-#! /usr/bin/env python
-
-"""Test script for the imageop module.  This has the side
-   effect of partially testing the imgfile module as well.
-   Roger E. Masse
-"""
-
-from test.test_support import verbose, unlink
-
-import imageop, uu, os
-
-import warnings
-warnings.filterwarnings("ignore",
-                        "the rgbimg module is deprecated",
-                        DeprecationWarning,
-                        ".*test_imageop")
-
-def main(use_rgbimg=1):
-
-    # Create binary test files
-    uu.decode(get_qualified_path('testrgb'+os.extsep+'uue'), 'test'+os.extsep+'rgb')
-
-    if use_rgbimg:
-        image, width, height = getrgbimage('test'+os.extsep+'rgb')
-    else:
-        image, width, height = getimage('test'+os.extsep+'rgb')
-
-    # Return the selected part of image, which should by width by height
-    # in size and consist of pixels of psize bytes.
-    if verbose:
-        print('crop')
-    newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
-
-    # Return image scaled to size newwidth by newheight. No interpolation
-    # is done, scaling is done by simple-minded pixel duplication or removal.
-    # Therefore, computer-generated images or dithered images will
-    # not look nice after scaling.
-    if verbose:
-        print('scale')
-    scaleimage = imageop.scale(image, 4, width, height, 1, 1)
-
-    # Run a vertical low-pass filter over an image. It does so by computing
-    # each destination pixel as the average of two vertically-aligned source
-    # pixels. The main use of this routine is to forestall excessive flicker
-    # if the image two vertically-aligned source pixels,  hence the name.
-    if verbose:
-        print('tovideo')
-    videoimage = imageop.tovideo (image, 4, width, height)
-
-    # Convert an rgb image to an 8 bit rgb
-    if verbose:
-        print('rgb2rgb8')
-    greyimage = imageop.rgb2rgb8(image, width, height)
-
-    # Convert an 8 bit rgb image to a 24 bit rgb image
-    if verbose:
-        print('rgb82rgb')
-    image = imageop.rgb82rgb(greyimage, width, height)
-
-    # Convert an rgb image to an 8 bit greyscale image
-    if verbose:
-        print('rgb2grey')
-    greyimage = imageop.rgb2grey(image, width, height)
-
-    # Convert an 8 bit greyscale image to a 24 bit rgb image
-    if verbose:
-        print('grey2rgb')
-    image = imageop.grey2rgb(greyimage, width, height)
-
-    # Convert a 8-bit deep greyscale image to a 1-bit deep image by
-    # thresholding all the pixels. The resulting image is tightly packed
-    # and is probably only useful as an argument to mono2grey.
-    if verbose:
-        print('grey2mono')
-    monoimage = imageop.grey2mono (greyimage, width, height, 0)
-
-    # monoimage, width, height = getimage('monotest.rgb')
-    # Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
-    # All pixels that are zero-valued on input get value p0 on output and
-    # all one-value input pixels get value p1 on output. To convert a
-    # monochrome  black-and-white image to greyscale pass the values 0 and
-    # 255 respectively.
-    if verbose:
-        print('mono2grey')
-    greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
-
-    # Convert an 8-bit greyscale image to a 1-bit monochrome image using a
-    # (simple-minded) dithering algorithm.
-    if verbose:
-        print('dither2mono')
-    monoimage = imageop.dither2mono (greyimage, width, height)
-
-    # Convert an 8-bit greyscale image to a 4-bit greyscale image without
-    # dithering.
-    if verbose:
-        print('grey2grey4')
-    grey4image = imageop.grey2grey4 (greyimage, width, height)
-
-    # Convert an 8-bit greyscale image to a 2-bit greyscale image without
-    # dithering.
-    if verbose:
-        print('grey2grey2')
-    grey2image = imageop.grey2grey2 (greyimage, width, height)
-
-    # Convert an 8-bit greyscale image to a 2-bit greyscale image with
-    # dithering. As for dither2mono, the dithering algorithm is currently
-    # very simple.
-    if verbose:
-        print('dither2grey2')
-    grey2image = imageop.dither2grey2 (greyimage, width, height)
-
-    # Convert a 4-bit greyscale image to an 8-bit greyscale image.
-    if verbose:
-        print('grey42grey')
-    greyimage = imageop.grey42grey (grey4image, width, height)
-
-    # Convert a 2-bit greyscale image to an 8-bit greyscale image.
-    if verbose:
-        print('grey22grey')
-    image = imageop.grey22grey (grey2image, width, height)
-
-    # Cleanup
-    unlink('test'+os.extsep+'rgb')
-
-def getrgbimage(name):
-    """return a tuple consisting of image (in 'imgfile' format but
-    using rgbimg instead) width and height"""
-
-    import rgbimg
-
-    try:
-        sizes = rgbimg.sizeofimage(name)
-    except rgbimg.error:
-        name = get_qualified_path(name)
-        sizes = rgbimg.sizeofimage(name)
-    if verbose:
-        print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)))
-
-    image = rgbimg.longimagedata(name)
-    return (image, sizes[0], sizes[1])
-
-def getimage(name):
-    """return a tuple consisting of
-       image (in 'imgfile' format) width and height
-    """
-
-    import imgfile
-
-    try:
-        sizes = imgfile.getsizes(name)
-    except imgfile.error:
-        name = get_qualified_path(name)
-        sizes = imgfile.getsizes(name)
-    if verbose:
-        print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes)))
-
-    image = imgfile.read(name)
-    return (image, sizes[0], sizes[1])
-
-def get_qualified_path(name):
-    """ return a more qualified path to name"""
-    import sys
-    import os
-    path = sys.path
-    try:
-        path = [os.path.dirname(__file__)] + path
-    except NameError:
-        pass
-    for dir in path:
-        fullname = os.path.join(dir, name)
-        if os.path.exists(fullname):
-            return fullname
-    return name
-
-# rgbimg (unlike imgfile) is portable to platforms other than SGI.
-# So we prefer to use it.
-main(use_rgbimg=1)

Deleted: /python/branches/p3yk-noslice/Lib/test/test_imgfile.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_imgfile.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,116 +0,0 @@
-#! /usr/bin/env python
-
-"""Simple test script for imgfile.c
-   Roger E. Masse
-"""
-
-from test.test_support import verbose, unlink, findfile
-
-import imgfile, uu, os
-
-
-def main():
-
-    uu.decode(findfile('testrgb.uue'), 'test.rgb')
-    uu.decode(findfile('greyrgb.uue'), 'greytest.rgb')
-
-    # Test a 3 byte color image
-    testimage('test.rgb')
-
-    # Test a 1 byte greyscale image
-    testimage('greytest.rgb')
-
-    unlink('test.rgb')
-    unlink('greytest.rgb')
-
-def testimage(name):
-    """Run through the imgfile's battery of possible methods
-       on the image passed in name.
-    """
-
-    import sys
-    import os
-
-    outputfile = '/tmp/deleteme'
-
-    # try opening the name directly
-    try:
-        # This function returns a tuple (x, y, z) where x and y are the size
-        # of the image in pixels and z is the number of bytes per pixel. Only
-        # 3 byte RGB pixels and 1 byte greyscale pixels are supported.
-        sizes = imgfile.getsizes(name)
-    except imgfile.error:
-        # get a more qualified path component of the script...
-        if __name__ == '__main__':
-            ourname = sys.argv[0]
-        else: # ...or the full path of the module
-            ourname = sys.modules[__name__].__file__
-
-        parts = ourname.split(os.sep)
-        parts[-1] = name
-        name = os.sep.join(parts)
-        sizes = imgfile.getsizes(name)
-    if verbose:
-        print('Opening test image: %s, sizes: %s' % (name, str(sizes)))
-    # This function reads and decodes the image on the specified file,
-    # and returns it as a python string. The string has either 1 byte
-    # greyscale pixels or 4 byte RGBA pixels. The bottom left pixel
-    # is the first in the string. This format is suitable to pass
-    # to gl.lrectwrite, for instance.
-    image = imgfile.read(name)
-
-    # This function writes the RGB or greyscale data in data to
-    # image file file. x and y give the size of the image, z is
-    # 1 for 1 byte greyscale images or 3 for RGB images (which
-    # are stored as 4 byte values of which only the lower three
-    # bytes are used). These are the formats returned by gl.lrectread.
-    if verbose:
-        print('Writing output file')
-    imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2])
-
-
-    if verbose:
-        print('Opening scaled test image: %s, sizes: %s' % (name, str(sizes)))
-    # This function is identical to read but it returns an image that
-    # is scaled to the given x and y sizes. If the filter and blur
-    # parameters are omitted scaling is done by simply dropping
-    # or duplicating pixels, so the result will be less than perfect,
-    # especially for computer-generated images.  Alternatively,
-    # you can specify a filter to use to smoothen the image after
-    # scaling. The filter forms supported are 'impulse', 'box',
-    # 'triangle', 'quadratic' and 'gaussian'. If a filter is
-    # specified blur is an optional parameter specifying the
-    # blurriness of the filter. It defaults to 1.0.  readscaled
-    # makes no attempt to keep the aspect ratio correct, so that
-    # is the users' responsibility.
-    if verbose:
-        print('Filtering with "impulse"')
-    simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0)
-
-    # This function sets a global flag which defines whether the
-    # scan lines of the image are read or written from bottom to
-    # top (flag is zero, compatible with SGI GL) or from top to
-    # bottom(flag is one, compatible with X). The default is zero.
-    if verbose:
-        print('Switching to X compatibility')
-    imgfile.ttob (1)
-
-    if verbose:
-        print('Filtering with "triangle"')
-    simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0)
-    if verbose:
-        print('Switching back to SGI compatibility')
-    imgfile.ttob (0)
-
-    if verbose: print('Filtering with "quadratic"')
-    simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'quadratic')
-    if verbose: print('Filtering with "gaussian"')
-    simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0)
-
-    if verbose:
-        print('Writing output file')
-    imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2])
-
-    os.unlink(outputfile)
-
-main()

Modified: python/branches/p3yk-noslice/Lib/test/test_import.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_import.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_import.py	Wed Jul 11 15:40:56 2007
@@ -6,6 +6,7 @@
 import sys
 import py_compile
 import warnings
+from test.test_support import unlink
 
 
 def remove_files(name):
@@ -63,22 +64,9 @@
                 self.assertEquals(mod.b, b,
                     "module loaded (%s) but contents invalid" % mod)
             finally:
-                os.unlink(source)
-
-            try:
-                try:
-                    reload(mod)
-                except ImportError as err:
-                    self.fail("import from .pyc/.pyo failed: %s" % err)
-            finally:
-                try:
-                    os.unlink(pyc)
-                except OSError:
-                    pass
-                try:
-                    os.unlink(pyo)
-                except OSError:
-                    pass
+                unlink(source)
+                unlink(pyc)
+                unlink(pyo)
                 del sys.modules[TESTFN]
 
         sys.path.insert(0, os.curdir)
@@ -136,6 +124,8 @@
         # New in 2.4, we shouldn't be able to import that no matter how often
         # we try.
         sys.path.insert(0, os.curdir)
+        if TESTFN in sys.modules:
+            del sys.modules[TESTFN]
         try:
             for i in 1, 2, 3:
                 try:
@@ -149,50 +139,6 @@
             sys.path.pop(0)
             remove_files(TESTFN)
 
-    def test_failing_reload(self):
-        # A failing reload should leave the module object in sys.modules.
-        source = TESTFN + os.extsep + "py"
-        f = open(source, "w")
-        print("a = 1", file=f)
-        print("b = 2", file=f)
-        f.close()
-
-        sys.path.insert(0, os.curdir)
-        try:
-            mod = __import__(TESTFN)
-            self.assert_(TESTFN in sys.modules, "expected module in sys.modules")
-            self.assertEquals(mod.a, 1, "module has wrong attribute values")
-            self.assertEquals(mod.b, 2, "module has wrong attribute values")
-
-            # On WinXP, just replacing the .py file wasn't enough to
-            # convince reload() to reparse it.  Maybe the timestamp didn't
-            # move enough.  We force it to get reparsed by removing the
-            # compiled file too.
-            remove_files(TESTFN)
-
-            # Now damage the module.
-            f = open(source, "w")
-            print("a = 10", file=f)
-            print("b = 20//0", file=f)
-            f.close()
-
-            self.assertRaises(ZeroDivisionError, reload, mod)
-
-            # But we still expect the module to be in sys.modules.
-            mod = sys.modules.get(TESTFN)
-            self.failIf(mod is None, "expected module to still be in sys.modules")
-
-            # We should have replaced a w/ 10, but the old b value should
-            # stick.
-            self.assertEquals(mod.a, 10, "module has wrong attribute values")
-            self.assertEquals(mod.b, 2, "module has wrong attribute values")
-
-        finally:
-            sys.path.pop(0)
-            remove_files(TESTFN)
-            if TESTFN in sys.modules:
-                del sys.modules[TESTFN]
-
     def test_import_name_binding(self):
         # import x.y.z binds x in the current namespace
         import test as x

Modified: python/branches/p3yk-noslice/Lib/test/test_importhooks.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_importhooks.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_importhooks.py	Wed Jul 11 15:40:56 2007
@@ -190,10 +190,6 @@
         import reloadmodule
         self.failIf(hasattr(reloadmodule,'reloaded'))
 
-        TestImporter.modules['reloadmodule'] = (False, reload_co)
-        reload(reloadmodule)
-        self.failUnless(hasattr(reloadmodule,'reloaded'))
-
         import hooktestpackage.newrel
         self.assertEqual(hooktestpackage.newrel.get_name(),
                          "hooktestpackage.newrel")
@@ -251,7 +247,7 @@
         i = ImpWrapper()
         sys.meta_path.append(i)
         sys.path_hooks.append(ImpWrapper)
-        mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc")
+        mnames = ("colorsys", "urlparse", "distutils.core")
         for mname in mnames:
             parent = mname.split(".")[0]
             for n in list(sys.modules.keys()):

Modified: python/branches/p3yk-noslice/Lib/test/test_index.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_index.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_index.py	Wed Jul 11 15:40:56 2007
@@ -1,6 +1,7 @@
 import unittest
 from test import test_support
 import operator
+import sys
 from sys import maxint
 
 class oldstyle:
@@ -49,7 +50,7 @@
         self.assertEqual(self.n.__index__(), 5)
 
     def test_subclasses(self):
-        r = range(10)
+        r = list(range(10))
         self.assertEqual(r[TrapInt(5):TrapInt(10)], r[5:10])
         self.assertEqual(r[TrapLong(5):TrapLong(10)], r[5:10])
         self.assertEqual(slice(TrapInt()).indices(0), (0,0,1))
@@ -164,14 +165,6 @@
     seq = u"this is a test"
 
 
-class XRangeTestCase(unittest.TestCase):
-
-    def test_xrange(self):
-        n = newstyle()
-        n.ind = 5
-        self.assertEqual(xrange(1, 20)[n], 6)
-        self.assertEqual(xrange(1, 20).__getitem__(n), 6)
-
 class OverflowTestCase(unittest.TestCase):
 
     def setUp(self):
@@ -185,7 +178,7 @@
     def _getitem_helper(self, base):
         class GetItem(base):
             def __len__(self):
-                return maxint
+                return maxint #cannot return long here
             def __getitem__(self, key):
                 return key
         x = GetItem()
@@ -213,7 +206,6 @@
         TupleTestCase,
         StringTestCase,
         UnicodeTestCase,
-        XRangeTestCase,
         OverflowTestCase,
     )
 

Modified: python/branches/p3yk-noslice/Lib/test/test_inspect.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_inspect.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_inspect.py	Wed Jul 11 15:40:56 2007
@@ -25,7 +25,7 @@
 try:
     1/0
 except:
-    tb = sys.exc_traceback
+    tb = sys.exc_info()[2]
 
 git = mod.StupidGit()
 
@@ -43,7 +43,7 @@
 
 class TestPredicates(IsTestBase):
     def test_thirteen(self):
-        count = len(filter(lambda x:x.startswith('is'), dir(inspect)))
+        count = len([x for x in dir(inspect) if x.startswith('is')])
         # Doc/lib/libinspect.tex claims there are 13 such functions
         expected = 13
         err_msg = "There are %d (not %d) is* functions" % (count, expected)
@@ -53,7 +53,7 @@
         self.istest(inspect.isbuiltin, 'sys.exit')
         self.istest(inspect.isbuiltin, '[].append')
         self.istest(inspect.isclass, 'mod.StupidGit')
-        self.istest(inspect.iscode, 'mod.spam.func_code')
+        self.istest(inspect.iscode, 'mod.spam.__code__')
         self.istest(inspect.isframe, 'tb.tb_frame')
         self.istest(inspect.isfunction, 'mod.spam')
         self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
@@ -116,11 +116,11 @@
 
     def test_previous_frame(self):
         args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
-        self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
+        self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f'])
         self.assertEqual(varargs, 'g')
         self.assertEqual(varkw, 'h')
         self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
-             '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
+             '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})')
 
 class GetSourceBase(unittest.TestCase):
     # Subclasses must override.
@@ -210,7 +210,7 @@
         m.__file__ = "<string>" # hopefully not a real filename...
         m.__loader__ = "dummy"  # pretend the filename is understood by a loader
         exec("def x(): pass", m.__dict__)
-        self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
+        self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>')
         del sys.modules[name]
         inspect.getmodule(compile('a=10','','single'))
 
@@ -218,7 +218,7 @@
     fodderFile = mod2
 
     def test_wrapped_decorator(self):
-        self.assertSourceEqual(mod2.wrapped, 14, 17)
+        self.assertSourceEqual(mod2.wrapped, 16, 17)
 
     def test_replacing_decorator(self):
         self.assertSourceEqual(mod2.gone, 9, 10)
@@ -321,9 +321,9 @@
         self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)')
 
         self.assertArgSpecEquals(mod.spam,
-                                 ['a', 'b', 'c', 'd', ['e', ['f']]],
-                                 'g', 'h', (3, (4, (5,))),
-                                 '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
+                                 ['a', 'b', 'c', 'd', 'e', 'f'],
+                                 'g', 'h', (3, 4, 5),
+                                 '(a, b, c, d=3, e=4, f=5, *g, **h)')
 
     def test_getargspec_method(self):
         class A(object):
@@ -331,13 +331,6 @@
                 pass
         self.assertArgSpecEquals(A.m, ['self'])
 
-    def test_getargspec_sublistofone(self):
-        def sublistOfOne((foo,)): return 1
-        self.assertArgSpecEquals(sublistOfOne, [['foo']])
-
-        def fakeSublistOfOne((foo)): return 1
-        self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
-
     def test_classify_newstyle(self):
         class A(object):
 

Modified: python/branches/p3yk-noslice/Lib/test/test_isinstance.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_isinstance.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_isinstance.py	Wed Jul 11 15:40:56 2007
@@ -15,8 +15,7 @@
     # (leading to an "undetected error" in the debug build).  Set up is,
     # isinstance(inst, cls) where:
     #
-    # - inst isn't an InstanceType
-    # - cls isn't a ClassType, a TypeType, or a TupleType
+    # - cls isn't a a type, or a tuple
     # - cls has a __bases__ attribute
     # - inst has a __class__ attribute
     # - inst.__class__ as no __bases__ attribute
@@ -260,7 +259,7 @@
     # Make sure that calling isinstance with a deeply nested tuple for its
     # argument will raise RuntimeError eventually.
     tuple_arg = (compare_to,)
-    for cnt in xrange(sys.getrecursionlimit()+5):
+    for cnt in range(sys.getrecursionlimit()+5):
         tuple_arg = (tuple_arg,)
         fxn(arg, tuple_arg)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_iter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_iter.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_iter.py	Wed Jul 11 15:40:56 2007
@@ -22,7 +22,7 @@
     def __init__(self, n):
         self.n = n
         self.i = 0
-    def next(self):
+    def __next__(self):
         res = self.i
         if res >= self.n:
             raise StopIteration
@@ -53,7 +53,7 @@
         res = []
         while 1:
             try:
-                val = it.next()
+                val = next(it)
             except StopIteration:
                 break
             res.append(val)
@@ -68,18 +68,18 @@
 
     # Test basic use of iter() function
     def test_iter_basic(self):
-        self.check_iterator(iter(range(10)), range(10))
+        self.check_iterator(iter(range(10)), list(range(10)))
 
     # Test that iter(iter(x)) is the same as iter(x)
     def test_iter_idempotency(self):
-        seq = range(10)
+        seq = list(range(10))
         it = iter(seq)
         it2 = iter(it)
         self.assert_(it is it2)
 
     # Test that for loops over iterators work
     def test_iter_for_loop(self):
-        self.check_for_loop(iter(range(10)), range(10))
+        self.check_for_loop(iter(range(10)), list(range(10)))
 
     # Test several independent iterators over the same list
     def test_iter_independence(self):
@@ -106,19 +106,19 @@
 
     # Test a class with __iter__ in a for loop
     def test_iter_class_for(self):
-        self.check_for_loop(IteratingSequenceClass(10), range(10))
+        self.check_for_loop(IteratingSequenceClass(10), list(range(10)))
 
     # Test a class with __iter__ with explicit iter()
     def test_iter_class_iter(self):
-        self.check_iterator(iter(IteratingSequenceClass(10)), range(10))
+        self.check_iterator(iter(IteratingSequenceClass(10)), list(range(10)))
 
     # Test for loop on a sequence class without __iter__
     def test_seq_class_for(self):
-        self.check_for_loop(SequenceClass(10), range(10))
+        self.check_for_loop(SequenceClass(10), list(range(10)))
 
     # Test iter() on a sequence class without __iter__
     def test_seq_class_iter(self):
-        self.check_iterator(iter(SequenceClass(10)), range(10))
+        self.check_iterator(iter(SequenceClass(10)), list(range(10)))
 
     # Test two-argument iter() with callable instance
     def test_iter_callable(self):
@@ -131,7 +131,7 @@
                 if i > 100:
                     raise IndexError # Emergency stop
                 return i
-        self.check_iterator(iter(C(), 10), range(10))
+        self.check_iterator(iter(C(), 10), list(range(10)))
 
     # Test two-argument iter() with function
     def test_iter_function(self):
@@ -139,7 +139,7 @@
             i = state[0]
             state[0] = i+1
             return i
-        self.check_iterator(iter(spam, 10), range(10))
+        self.check_iterator(iter(spam, 10), list(range(10)))
 
     # Test two-argument iter() with function that raises StopIteration
     def test_iter_function_stop(self):
@@ -149,7 +149,7 @@
                 raise StopIteration
             state[0] = i+1
             return i
-        self.check_iterator(iter(spam, 20), range(10))
+        self.check_iterator(iter(spam, 20), list(range(10)))
 
     # Test exception propagation through function iterator
     def test_exception_function(self):
@@ -164,7 +164,7 @@
             for x in iter(spam, 20):
                 res.append(x)
         except RuntimeError:
-            self.assertEqual(res, range(10))
+            self.assertEqual(res, list(range(10)))
         else:
             self.fail("should have raised RuntimeError")
 
@@ -180,7 +180,7 @@
             for x in MySequenceClass(20):
                 res.append(x)
         except RuntimeError:
-            self.assertEqual(res, range(10))
+            self.assertEqual(res, list(range(10)))
         else:
             self.fail("should have raised RuntimeError")
 
@@ -191,11 +191,11 @@
                 if i == 10:
                     raise StopIteration
                 return SequenceClass.__getitem__(self, i)
-        self.check_for_loop(MySequenceClass(20), range(10))
+        self.check_for_loop(MySequenceClass(20), list(range(10)))
 
     # Test a big range
     def test_iter_big_range(self):
-        self.check_for_loop(iter(range(10000)), range(10000))
+        self.check_for_loop(iter(range(10000)), list(range(10000)))
 
     # Test an empty list
     def test_iter_empty(self):
@@ -203,11 +203,11 @@
 
     # Test a tuple
     def test_iter_tuple(self):
-        self.check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), range(10))
+        self.check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10)))
 
-    # Test an xrange
-    def test_iter_xrange(self):
-        self.check_for_loop(iter(xrange(10)), range(10))
+    # Test a range
+    def test_iter_range(self):
+        self.check_for_loop(iter(range(10)), list(range(10)))
 
     # Test a string
     def test_iter_string(self):
@@ -248,10 +248,9 @@
 
     # Test list()'s use of iterators.
     def test_builtin_list(self):
-        self.assertEqual(list(SequenceClass(5)), range(5))
+        self.assertEqual(list(SequenceClass(5)), list(range(5)))
         self.assertEqual(list(SequenceClass(0)), [])
         self.assertEqual(list(()), [])
-        self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1))
 
         d = {"one": 1, "two": 2, "three": 3}
         self.assertEqual(list(d), list(d.keys()))
@@ -313,13 +312,14 @@
 
     # Test filter()'s use of iterators.
     def test_builtin_filter(self):
-        self.assertEqual(filter(None, SequenceClass(5)), range(1, 5))
-        self.assertEqual(filter(None, SequenceClass(0)), [])
-        self.assertEqual(filter(None, ()), ())
-        self.assertEqual(filter(None, "abc"), "abc")
+        self.assertEqual(list(filter(None, SequenceClass(5))),
+                         list(range(1, 5)))
+        self.assertEqual(list(filter(None, SequenceClass(0))), [])
+        self.assertEqual(list(filter(None, ())), [])
+        self.assertEqual(list(filter(None, "abc")), ["a", "b", "c"])
 
         d = {"one": 1, "two": 2, "three": 3}
-        self.assertEqual(filter(None, d), list(d.keys()))
+        self.assertEqual(list(filter(None, d)), list(d.keys()))
 
         self.assertRaises(TypeError, filter, None, list)
         self.assertRaises(TypeError, filter, None, 42)
@@ -342,7 +342,7 @@
                         self.i = 0
                     def __iter__(self):
                         return self
-                    def next(self):
+                    def __next__(self):
                         i = self.i
                         self.i = i + 1
                         if i < len(self.vals):
@@ -352,8 +352,8 @@
                 return SeqIter(self.vals)
 
         seq = Seq(*([bTrue, bFalse] * 25))
-        self.assertEqual(filter(lambda x: not x, seq), [bFalse]*25)
-        self.assertEqual(filter(lambda x: not x, iter(seq)), [bFalse]*25)
+        self.assertEqual(list(filter(lambda x: not x, seq)), [bFalse]*25)
+        self.assertEqual(list(filter(lambda x: not x, iter(seq))), [bFalse]*25)
 
     # Test max() and min()'s use of iterators.
     def test_builtin_max_min(self):
@@ -389,20 +389,24 @@
 
     # Test map()'s use of iterators.
     def test_builtin_map(self):
-        self.assertEqual(map(None, SequenceClass(5)), range(5))
-        self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6))
+        self.assertEqual(list(map(None, SequenceClass(5))),
+                         [(0,), (1,), (2,), (3,), (4,)])
+        self.assertEqual(list(map(lambda x: x+1, SequenceClass(5))),
+                         list(range(1, 6)))
 
         d = {"one": 1, "two": 2, "three": 3}
-        self.assertEqual(map(None, d), list(d.keys()))
-        self.assertEqual(map(lambda k, d=d: (k, d[k]), d), list(d.items()))
+        self.assertEqual(list(map(None, d)), [(k,) for k in d])
+        self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)),
+                         list(d.items()))
         dkeys = list(d.keys())
         expected = [(i < len(d) and dkeys[i] or None,
                      i,
                      i < len(d) and dkeys[i] or None)
-                    for i in range(5)]
-        self.assertEqual(map(None, d,
-                                   SequenceClass(5),
-                                   iter(d.keys())),
+                    for i in range(3)]
+        self.assertEqual(list(map(None,
+                                  d,
+                                  SequenceClass(5),
+                                  iter(d.keys()))),
                          expected)
 
         f = open(TESTFN, "w")
@@ -413,7 +417,7 @@
             f.close()
         f = open(TESTFN, "r")
         try:
-            self.assertEqual(map(len, f), range(1, 21, 2))
+            self.assertEqual(list(map(len, f)), list(range(1, 21, 2)))
         finally:
             f.close()
             try:
@@ -447,7 +451,7 @@
             def __iter__(self):
                 return self
 
-            def next(self):
+            def __next__(self):
                 i = self.i
                 self.i = i+1
                 return i
@@ -470,7 +474,7 @@
             except OSError:
                 pass
 
-        self.assertEqual(list(zip(xrange(5))), [(i,) for i in range(5)])
+        self.assertEqual(list(zip(range(5))), [(i,) for i in range(5)])
 
         # Classes that lie about their lengths.
         class NoGuessLen5:
@@ -514,12 +518,12 @@
             def __iter__(self):
                 return self
 
-            def next(self):
+            def __next__(self):
                 i = self.i
                 self.i = i+1
                 if i == 2:
                     return unicode("fooled you!")
-                return self.it.next()
+                return next(self.it)
 
         f = open(TESTFN, "w")
         try:
@@ -682,7 +686,7 @@
                     self.finish = finish
                     self.i = self.start
 
-                def next(self):
+                def __next__(self):
                     if self.i >= self.finish:
                         raise StopIteration
                     result = str(self.i) + '\n'
@@ -799,16 +803,16 @@
 
     def test_sinkstate_list(self):
         # This used to fail
-        a = range(5)
+        a = list(range(5))
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         a.extend(range(5, 10))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_tuple(self):
         a = (0, 1, 2, 3, 4)
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_string(self):
@@ -821,7 +825,7 @@
         # This used to fail
         a = SequenceClass(5)
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         a.n = 10
         self.assertEqual(list(b), [])
 
@@ -834,7 +838,7 @@
                 raise AssertionError, "shouldn't have gotten this far"
             return i
         b = iter(spam, 5)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_dict(self):
@@ -851,13 +855,13 @@
             for i in range(5):
                 yield i
         b = gen()
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_range(self):
-        a = xrange(5)
+        a = range(5)
         b = iter(a)
-        self.assertEqual(list(b), range(5))
+        self.assertEqual(list(b), list(range(5)))
         self.assertEqual(list(b), [])
 
     def test_sinkstate_enumerate(self):

Modified: python/branches/p3yk-noslice/Lib/test/test_iterlen.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_iterlen.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_iterlen.py	Wed Jul 11 15:40:56 2007
@@ -9,14 +9,14 @@
 
 A complication is that an iterable and iterator can be the same object. To
 maintain the invariant, an iterator needs to dynamically update its length.
-For instance, an iterable such as xrange(10) always reports its length as ten,
-but it=iter(xrange(10)) starts at ten, and then goes to nine after it.next().
+For instance, an iterable such as range(10) always reports its length as ten,
+but it=iter(range(10)) starts at ten, and then goes to nine after next(it).
 Having this capability means that map() can ignore the distinction between
 map(func, iterable) and map(func, iter(iterable)).
 
 When the iterable is immutable, the implementation can straight-forwardly
 report the original length minus the cumulative number of calls to next().
-This is the case for tuples, xrange objects, and itertools.repeat().
+This is the case for tuples, range objects, and itertools.repeat().
 
 Some containers become temporarily immutable during iteration.  This includes
 dicts, sets, and collections.deque.  Their implementation is equally simple
@@ -65,11 +65,11 @@
 
     def test_invariant(self):
         it = self.it
-        for i in reversed(xrange(1, n+1)):
+        for i in reversed(range(1, n+1)):
             self.assertEqual(len(it), i)
-            it.next()
+            next(it)
         self.assertEqual(len(it), 0)
-        self.assertRaises(StopIteration, it.next)
+        self.assertRaises(StopIteration, next, it)
         self.assertEqual(len(it), 0)
 
 class TestTemporarilyImmutable(TestInvariantWithoutMutations):
@@ -80,10 +80,10 @@
 
         it = self.it
         self.assertEqual(len(it), n)
-        it.next()
+        next(it)
         self.assertEqual(len(it), n-1)
         self.mutate()
-        self.assertRaises(RuntimeError, it.next)
+        self.assertRaises(RuntimeError, next, it)
         self.assertEqual(len(it), 0)
 
 ## ------- Concrete Type Tests -------
@@ -100,59 +100,59 @@
 class TestXrange(TestInvariantWithoutMutations):
 
     def setUp(self):
-        self.it = iter(xrange(n))
+        self.it = iter(range(n))
 
 class TestXrangeCustomReversed(TestInvariantWithoutMutations):
 
     def setUp(self):
-        self.it = reversed(xrange(n))
+        self.it = reversed(range(n))
 
 class TestTuple(TestInvariantWithoutMutations):
 
     def setUp(self):
-        self.it = iter(tuple(xrange(n)))
+        self.it = iter(tuple(range(n)))
 
 ## ------- Types that should not be mutated during iteration -------
 
 class TestDeque(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = deque(xrange(n))
+        d = deque(range(n))
         self.it = iter(d)
         self.mutate = d.pop
 
 class TestDequeReversed(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = deque(xrange(n))
+        d = deque(range(n))
         self.it = reversed(d)
         self.mutate = d.pop
 
 class TestDictKeys(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = dict.fromkeys(xrange(n))
+        d = dict.fromkeys(range(n))
         self.it = iter(d)
         self.mutate = d.popitem
 
 class TestDictItems(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = dict.fromkeys(xrange(n))
+        d = dict.fromkeys(range(n))
         self.it = iter(d.items())
         self.mutate = d.popitem
 
 class TestDictValues(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = dict.fromkeys(xrange(n))
+        d = dict.fromkeys(range(n))
         self.it = iter(d.values())
         self.mutate = d.popitem
 
 class TestSet(TestTemporarilyImmutable):
 
     def setUp(self):
-        d = set(xrange(n))
+        d = set(range(n))
         self.it = iter(d)
         self.mutate = d.pop
 
@@ -164,17 +164,17 @@
         self.it = iter(range(n))
 
     def test_mutation(self):
-        d = range(n)
+        d = list(range(n))
         it = iter(d)
-        it.next()
-        it.next()
+        next(it)
+        next(it)
         self.assertEqual(len(it), n-2)
         d.append(n)
         self.assertEqual(len(it), n-1)  # grow with append
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 class TestListReversed(TestInvariantWithoutMutations):
@@ -183,17 +183,17 @@
         self.it = reversed(range(n))
 
     def test_mutation(self):
-        d = range(n)
+        d = list(range(n))
         it = reversed(d)
-        it.next()
-        it.next()
+        next(it)
+        next(it)
         self.assertEqual(len(it), n-2)
         d.append(n)
         self.assertEqual(len(it), n-2)  # ignore append
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])  # confirm invariant
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 class TestSeqIter(TestInvariantWithoutMutations):
@@ -204,15 +204,15 @@
     def test_mutation(self):
         d = UserList(range(n))
         it = iter(d)
-        it.next()
-        it.next()
+        next(it)
+        next(it)
         self.assertEqual(len(it), n-2)
         d.append(n)
         self.assertEqual(len(it), n-1)  # grow with append
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 class TestSeqIterReversed(TestInvariantWithoutMutations):
@@ -223,15 +223,15 @@
     def test_mutation(self):
         d = UserList(range(n))
         it = reversed(d)
-        it.next()
-        it.next()
+        next(it)
+        next(it)
         self.assertEqual(len(it), n-2)
         d.append(n)
         self.assertEqual(len(it), n-2)  # ignore append
         d[1:] = []
         self.assertEqual(len(it), 0)
         self.assertEqual(list(it), [])  # confirm invariant
-        d.extend(xrange(20))
+        d.extend(range(20))
         self.assertEqual(len(it), 0)
 
 

Modified: python/branches/p3yk-noslice/Lib/test/test_itertools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_itertools.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_itertools.py	Wed Jul 11 15:40:56 2007
@@ -34,7 +34,7 @@
     'Class emulating an empty iterable.'
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         raise StopIteration
 
 def take(n, seq):
@@ -58,12 +58,12 @@
         self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10))
         c = count(3)
         self.assertEqual(repr(c), 'count(3)')
-        c.next()
+        next(c)
         self.assertEqual(repr(c), 'count(4)')
         c = count(-9)
         self.assertEqual(repr(c), 'count(-9)')
-        c.next()
-        self.assertEqual(c.next(), -8)
+        next(c)
+        self.assertEqual(next(c), -8)
 
     def test_cycle(self):
         self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
@@ -121,7 +121,7 @@
         r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
         self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
 
-        # iter.next failure
+        # iter.__next__ failure
         class ExpectedError(Exception):
             pass
         def delayed_raise(n=0):
@@ -131,9 +131,9 @@
         def gulp(iterable, keyp=None, func=list):
             return [func(g) for k, g in groupby(iterable, keyp)]
 
-        # iter.next failure on outer object
+        # iter.__next__ failure on outer object
         self.assertRaises(ExpectedError, gulp, delayed_raise(0))
-        # iter.next failure on inner object
+        # iter.__next__ failure on inner object
         self.assertRaises(ExpectedError, gulp, delayed_raise(1))
 
         # __cmp__ failure
@@ -169,7 +169,7 @@
         self.assertRaises(TypeError, ifilter, lambda x:x)
         self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
         self.assertRaises(TypeError, ifilter, isEven, 3)
-        self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
+        self.assertRaises(TypeError, next, ifilter(range(6), range(6)))
 
     def test_ifilterfalse(self):
         self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
@@ -179,7 +179,7 @@
         self.assertRaises(TypeError, ifilterfalse, lambda x:x)
         self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
         self.assertRaises(TypeError, ifilterfalse, isEven, 3)
-        self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
+        self.assertRaises(TypeError, next, ifilterfalse(range(6), range(6)))
 
     def test_izip(self):
         # XXX This is rather silly now that builtin zip() calls izip()...
@@ -197,9 +197,9 @@
                          lzip('abc', 'def'))
         self.assertEqual([pair for pair in izip('abc', 'def')],
                          lzip('abc', 'def'))
-        ids = map(id, izip('abc', 'def'))
+        ids = list(map(id, izip('abc', 'def')))
         self.assertEqual(min(ids), max(ids))
-        ids = map(id, list(izip('abc', 'def')))
+        ids = list(map(id, list(izip('abc', 'def'))))
         self.assertEqual(len(dict.fromkeys(ids)), len(ids))
 
     def test_iziplongest(self):
@@ -210,25 +210,27 @@
                 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
                 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
             ]:
-            target = map(None, *args)
+            target = [tuple([arg[i] if i < len(arg) else None for arg in args])
+                      for i in range(max(map(len, args)))]
             self.assertEqual(list(izip_longest(*args)), target)
             self.assertEqual(list(izip_longest(*args, **{})), target)
             target = [tuple((e is None and 'X' or e) for e in t) for t in target]   # Replace None fills with 'X'
             self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
-        
+
         self.assertEqual(take(3,izip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input
 
         self.assertEqual(list(izip_longest()), list(zip()))
         self.assertEqual(list(izip_longest([])), list(zip([])))
         self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef')))
-    
-        self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict
+
+        self.assertEqual(list(izip_longest('abc', 'defg', **{})),
+                         list(map(None, list('abc')+[None], 'defg'))) # empty keyword dict
         self.assertRaises(TypeError, izip_longest, 3)
         self.assertRaises(TypeError, izip_longest, range(3), 3)
 
         for stmt in [
             "izip_longest('abc', fv=1)",
-            "izip_longest('abc', fillvalue=1, bogus_keyword=None)",            
+            "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
         ]:
             try:
                 eval(stmt, globals(), locals())
@@ -236,19 +238,19 @@
                 pass
             else:
                 self.fail('Did not raise Type in:  ' + stmt)
-        
+
         # Check tuple re-use (implementation detail)
         self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
                          list(zip('abc', 'def')))
         self.assertEqual([pair for pair in izip_longest('abc', 'def')],
                          list(zip('abc', 'def')))
-        ids = map(id, izip_longest('abc', 'def'))
+        ids = list(map(id, izip_longest('abc', 'def')))
         self.assertEqual(min(ids), max(ids))
-        ids = map(id, list(izip_longest('abc', 'def')))
+        ids = list(map(id, list(izip_longest('abc', 'def'))))
         self.assertEqual(len(dict.fromkeys(ids)), len(ids))
 
     def test_repeat(self):
-        self.assertEqual(lzip(xrange(3),repeat('a')),
+        self.assertEqual(lzip(range(3),repeat('a')),
                          [(0, 'a'), (1, 'a'), (2, 'a')])
         self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
         self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
@@ -276,9 +278,9 @@
         self.assertEqual(list(imap(operator.pow, [])), [])
         self.assertRaises(TypeError, imap)
         self.assertRaises(TypeError, imap, operator.neg)
-        self.assertRaises(TypeError, imap(10, range(5)).next)
-        self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
-        self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
+        self.assertRaises(TypeError, next, imap(10, range(5)))
+        self.assertRaises(ValueError, next, imap(errfunc, [4], [5]))
+        self.assertRaises(TypeError, next, imap(onearg, [4], [5]))
 
     def test_starmap(self):
         self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
@@ -289,9 +291,9 @@
         self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]]))
         self.assertRaises(TypeError, starmap)
         self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
-        self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
-        self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
-        self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
+        self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
+        self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
+        self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
 
     def test_islice(self):
         for args in [          # islice(args) should agree with range(args)
@@ -301,39 +303,41 @@
                 (10, 3),
                 (20,)
                 ]:
-            self.assertEqual(list(islice(xrange(100), *args)), range(*args))
+            self.assertEqual(list(islice(range(100), *args)),
+                             list(range(*args)))
 
         for args, tgtargs in [  # Stop when seqn is exhausted
                 ((10, 110, 3), ((10, 100, 3))),
                 ((10, 110), ((10, 100))),
                 ((110,), (100,))
                 ]:
-            self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
+            self.assertEqual(list(islice(range(100), *args)),
+                             list(range(*tgtargs)))
 
         # Test stop=None
-        self.assertEqual(list(islice(xrange(10), None)), range(10))
-        self.assertEqual(list(islice(xrange(10), None, None)), range(10))
-        self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
-        self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
-        self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
+        self.assertEqual(list(islice(range(10), None)), list(range(10)))
+        self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
+        self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
+        self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
+        self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
 
         # Test number of items consumed     SF #1171417
         it = iter(range(10))
-        self.assertEqual(list(islice(it, 3)), range(3))
-        self.assertEqual(list(it), range(3, 10))
+        self.assertEqual(list(islice(it, 3)), list(range(3)))
+        self.assertEqual(list(it), list(range(3, 10)))
 
         # Test invalid arguments
-        self.assertRaises(TypeError, islice, xrange(10))
-        self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
-        self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
-        self.assertRaises(ValueError, islice, xrange(10), 'a')
-        self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
-        self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
-        self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
+        self.assertRaises(TypeError, islice, range(10))
+        self.assertRaises(TypeError, islice, range(10), 1, 2, 3, 4)
+        self.assertRaises(ValueError, islice, range(10), -5, 10, 1)
+        self.assertRaises(ValueError, islice, range(10), 1, -5, -1)
+        self.assertRaises(ValueError, islice, range(10), 1, 10, -1)
+        self.assertRaises(ValueError, islice, range(10), 1, 10, 0)
+        self.assertRaises(ValueError, islice, range(10), 'a')
+        self.assertRaises(ValueError, islice, range(10), 'a', 1)
+        self.assertRaises(ValueError, islice, range(10), 1, 'a')
+        self.assertRaises(ValueError, islice, range(10), 'a', 1, 1)
+        self.assertRaises(ValueError, islice, range(10), 1, 'a', 1)
         self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
 
     def test_takewhile(self):
@@ -344,11 +348,11 @@
         self.assertRaises(TypeError, takewhile)
         self.assertRaises(TypeError, takewhile, operator.pow)
         self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
-        self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
-        self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
+        self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
+        self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
         t = takewhile(bool, [1, 1, 1, 0, 0, 0])
         self.assertEqual(list(t), [1, 1, 1])
-        self.assertRaises(StopIteration, t.next)
+        self.assertRaises(StopIteration, next, t)
 
     def test_dropwhile(self):
         data = [1, 3, 5, 20, 2, 4, 6, 8]
@@ -358,13 +362,13 @@
         self.assertRaises(TypeError, dropwhile)
         self.assertRaises(TypeError, dropwhile, operator.pow)
         self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
-        self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
-        self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
+        self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
+        self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
 
     def test_tee(self):
         n = 200
         def irange(n):
-            for i in xrange(n):
+            for i in range(n):
                 yield i
 
         a, b = tee([])        # test empty iterator
@@ -375,31 +379,31 @@
         self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
 
         a, b = tee(irange(n)) # test 0% interleaved
-        self.assertEqual(list(a), range(n))
-        self.assertEqual(list(b), range(n))
+        self.assertEqual(list(a), list(range(n)))
+        self.assertEqual(list(b), list(range(n)))
 
         a, b = tee(irange(n)) # test dealloc of leading iterator
-        for i in xrange(100):
-            self.assertEqual(a.next(), i)
+        for i in range(100):
+            self.assertEqual(next(a), i)
         del a
-        self.assertEqual(list(b), range(n))
+        self.assertEqual(list(b), list(range(n)))
 
         a, b = tee(irange(n)) # test dealloc of trailing iterator
-        for i in xrange(100):
-            self.assertEqual(a.next(), i)
+        for i in range(100):
+            self.assertEqual(next(a), i)
         del b
-        self.assertEqual(list(a), range(100, n))
+        self.assertEqual(list(a), list(range(100, n)))
 
-        for j in xrange(5):   # test randomly interleaved
+        for j in range(5):   # test randomly interleaved
             order = [0]*n + [1]*n
             random.shuffle(order)
             lists = ([], [])
             its = tee(irange(n))
             for i in order:
-                value = its[i].next()
+                value = next(its[i])
                 lists[i].append(value)
-            self.assertEqual(lists[0], range(n))
-            self.assertEqual(lists[1], range(n))
+            self.assertEqual(lists[0], list(range(n)))
+            self.assertEqual(lists[1], list(range(n)))
 
         # test argument format checking
         self.assertRaises(TypeError, tee)
@@ -413,22 +417,22 @@
         self.assertEqual(list(c), list('def'))
 
         # test long-lagged and multi-way split
-        a, b, c = tee(xrange(2000), 3)
-        for i in xrange(100):
-            self.assertEqual(a.next(), i)
-        self.assertEqual(list(b), range(2000))
-        self.assertEqual([c.next(), c.next()], range(2))
-        self.assertEqual(list(a), range(100,2000))
-        self.assertEqual(list(c), range(2,2000))
+        a, b, c = tee(range(2000), 3)
+        for i in range(100):
+            self.assertEqual(next(a), i)
+        self.assertEqual(list(b), list(range(2000)))
+        self.assertEqual([next(c), next(c)], list(range(2)))
+        self.assertEqual(list(a), list(range(100,2000)))
+        self.assertEqual(list(c), list(range(2,2000)))
 
         # test values of n
         self.assertRaises(TypeError, tee, 'abc', 'invalid')
         self.assertRaises(ValueError, tee, [], -1)
-        for n in xrange(5):
+        for n in range(5):
             result = tee('abc', n)
             self.assertEqual(type(result), tuple)
             self.assertEqual(len(result), n)
-            self.assertEqual(map(list, result), [list('abc')]*n)
+            self.assertEqual([list(x) for x in result], [list('abc')]*n)
 
         # tee pass-through to copyable iterator
         a, b = tee('abc')
@@ -444,40 +448,40 @@
         self.assert_(list(t1) == list(t2) == list(t3) == list('abc'))
 
         # test that tee objects are weak referencable
-        a, b = tee(xrange(10))
+        a, b = tee(range(10))
         p = proxy(a)
         self.assertEqual(getattr(p, '__class__'), type(b))
         del a
         self.assertRaises(ReferenceError, getattr, p, '__class__')
 
     def test_StopIteration(self):
-        self.assertRaises(StopIteration, izip().next)
+        self.assertRaises(StopIteration, next, izip())
 
         for f in (chain, cycle, izip, groupby):
-            self.assertRaises(StopIteration, f([]).next)
-            self.assertRaises(StopIteration, f(StopNow()).next)
+            self.assertRaises(StopIteration, next, f([]))
+            self.assertRaises(StopIteration, next, f(StopNow()))
 
-        self.assertRaises(StopIteration, islice([], None).next)
-        self.assertRaises(StopIteration, islice(StopNow(), None).next)
+        self.assertRaises(StopIteration, next, islice([], None))
+        self.assertRaises(StopIteration, next, islice(StopNow(), None))
 
         p, q = tee([])
-        self.assertRaises(StopIteration, p.next)
-        self.assertRaises(StopIteration, q.next)
+        self.assertRaises(StopIteration, next, p)
+        self.assertRaises(StopIteration, next, q)
         p, q = tee(StopNow())
-        self.assertRaises(StopIteration, p.next)
-        self.assertRaises(StopIteration, q.next)
+        self.assertRaises(StopIteration, next, p)
+        self.assertRaises(StopIteration, next, q)
 
-        self.assertRaises(StopIteration, repeat(None, 0).next)
+        self.assertRaises(StopIteration, next, repeat(None, 0))
 
         for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
-            self.assertRaises(StopIteration, f(lambda x:x, []).next)
-            self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
+            self.assertRaises(StopIteration, next, f(lambda x:x, []))
+            self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))
 
 class TestGC(unittest.TestCase):
 
     def makecycle(self, iterator, container):
         container.append(iterator)
-        iterator.next()
+        next(iterator)
         del container, iterator
 
     def test_chain(self):
@@ -547,7 +551,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
@@ -567,14 +571,14 @@
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
         return v
 
 class N:
-    'Iterator missing next()'
+    'Iterator missing __next__()'
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
@@ -588,7 +592,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         3 // 0
 
 class S:
@@ -597,7 +601,7 @@
         pass
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         raise StopIteration
 
 def L(seqn):
@@ -608,7 +612,7 @@
 class TestVariousIteratorArgs(unittest.TestCase):
 
     def test_chain(self):
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 self.assertEqual(list(chain(g(s))), list(g(s)))
                 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
@@ -617,7 +621,7 @@
             self.assertRaises(ZeroDivisionError, list, chain(E(s)))
 
     def test_cycle(self):
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 tgtlen = len(s) * 3
                 expected = list(g(s))*3
@@ -628,7 +632,7 @@
             self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
 
     def test_groupby(self):
-        for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
+        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
             self.assertRaises(TypeError, groupby, X(s))
@@ -636,23 +640,25 @@
             self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
 
     def test_ifilter(self):
-        for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
+        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
-                self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
+                self.assertEqual(list(ifilter(isEven, g(s))),
+                                 [x for x in g(s) if isEven(x)])
             self.assertRaises(TypeError, ifilter, isEven, X(s))
             self.assertRaises(TypeError, ifilter, isEven, N(s))
             self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
 
     def test_ifilterfalse(self):
-        for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
+        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
-                self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
+                self.assertEqual(list(ifilterfalse(isEven, g(s))),
+                                 [x for x in g(s) if isOdd(x)])
             self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
             self.assertRaises(TypeError, ifilterfalse, isEven, N(s))
             self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
 
     def test_izip(self):
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 self.assertEqual(list(izip(g(s))), lzip(g(s)))
                 self.assertEqual(list(izip(g(s), g(s))), lzip(g(s), g(s)))
@@ -661,7 +667,7 @@
             self.assertRaises(ZeroDivisionError, list, izip(E(s)))
 
     def test_iziplongest(self):
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 self.assertEqual(list(izip_longest(g(s))), list(zip(g(s))))
                 self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s))))
@@ -670,16 +676,18 @@
             self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
 
     def test_imap(self):
-        for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
+        for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
             for g in (G, I, Ig, S, L, R):
-                self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
-                self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
+                self.assertEqual(list(imap(onearg, g(s))),
+                                 [onearg(x) for x in g(s)])
+                self.assertEqual(list(imap(operator.pow, g(s), g(s))),
+                                 [x**x for x in g(s)])
             self.assertRaises(TypeError, imap, onearg, X(s))
             self.assertRaises(TypeError, imap, onearg, N(s))
             self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
 
     def test_islice(self):
-        for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
             self.assertRaises(TypeError, islice, X(s), 10)
@@ -687,16 +695,17 @@
             self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
 
     def test_starmap(self):
-        for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
+        for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
             for g in (G, I, Ig, S, L, R):
                 ss = lzip(s, s)
-                self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
+                self.assertEqual(list(starmap(operator.pow, g(ss))),
+                                 [x**x for x in g(s)])
             self.assertRaises(TypeError, starmap, operator.pow, X(ss))
             self.assertRaises(TypeError, starmap, operator.pow, N(ss))
             self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
 
     def test_takewhile(self):
-        for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
+        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 tgt = []
                 for elem in g(s):
@@ -708,7 +717,7 @@
             self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
 
     def test_dropwhile(self):
-        for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
+        for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 tgt = []
                 for elem in g(s):
@@ -720,7 +729,7 @@
             self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
 
     def test_tee(self):
-        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+        for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):
                 it1, it2 = tee(g(s))
                 self.assertEqual(list(it1), list(g(s)))
@@ -748,13 +757,13 @@
             def g(value, first=[1]):
                 if first:
                     del first[:]
-                    f(z.next())
+                    f(next(z))
                 return value
             items = list(tuple2)
             items[1:1] = list(tuple1)
             gen = imap(g, items)
             z = izip(*[gen]*len(tuple1))
-            z.next()
+            next(z)
 
         def f(t):
             global T
@@ -818,15 +827,15 @@
 >>> amounts = [120.15, 764.05, 823.14]
 >>> for checknum, amount in izip(count(1200), amounts):
 ...     print('Check %d is for $%.2f' % (checknum, amount))
-... 
+...
 Check 1200 is for $120.15
 Check 1201 is for $764.05
 Check 1202 is for $823.14
 
 >>> import operator
->>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
+>>> for cube in imap(operator.pow, range(1,4), repeat(3)):
 ...    print(cube)
-... 
+...
 1
 8
 27
@@ -834,7 +843,7 @@
 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
 >>> for name in islice(reportlines, 3, None, 2):
 ...    print(name.title())
-... 
+...
 Alex
 Laura
 Martin
@@ -845,8 +854,8 @@
 >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
 >>> di = sorted(sorted(d.items()), key=itemgetter(1))
 >>> for k, g in groupby(di, itemgetter(1)):
-...     print(k, map(itemgetter(0), g))
-... 
+...     print(k, list(map(itemgetter(0), g)))
+...
 1 ['a', 'c', 'e']
 2 ['b', 'd', 'f']
 3 ['g']
@@ -855,9 +864,9 @@
 # is differencing with a range so that consecutive numbers all appear in
 # same group.
 >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
->>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
-...     print(map(operator.itemgetter(1), g))
-... 
+>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
+...     print(list(map(operator.itemgetter(1), g)))
+...
 [1]
 [4, 5, 6]
 [10]
@@ -930,7 +939,7 @@
 ...     "s -> (s0,s1), (s1,s2), (s2, s3), ..."
 ...     a, b = tee(iterable)
 ...     try:
-...         b.next()
+...         next(b)
 ...     except StopIteration:
 ...         pass
 ...     return izip(a, b)
@@ -968,7 +977,7 @@
 >>> no([1, 2, 5, 9], lambda x: x%2==0)
 False
 
->>> quantify(xrange(99), lambda x: x%2==0)
+>>> quantify(range(99), lambda x: x%2==0)
 50
 
 >>> a = [[1, 2, 3], [4, 5, 6]]
@@ -1014,7 +1023,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_keywordonlyarg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_keywordonlyarg.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_keywordonlyarg.py	Wed Jul 11 15:40:56 2007
@@ -71,7 +71,7 @@
             fundef3 += "i%d, "%i
         fundef3 += "lastarg):\n  pass\n"
         compile(fundef3, "<test>", "single")
- 
+
     def testSyntaxErrorForFunctionCall(self):
         self.assertRaisesSyntaxError("f(p, k=1, p2)")
         self.assertRaisesSyntaxError("f(p, *(1,2), k1=100)")
@@ -135,12 +135,12 @@
         def foo(p1,p2=0, *, k1, k2=0):
             return p1 + p2 + k1 + k2
 
-        self.assertEquals(2, foo.func_code.co_kwonlyargcount)
-        self.assertEquals({"k2":0}, foo.func_kwdefaults)
-        foo.func_kwdefaults = {"k1":0}
+        self.assertEquals(2, foo.__code__.co_kwonlyargcount)
+        self.assertEquals({"k2":0}, foo.__kwdefaults__)
+        foo.__kwdefaults__ = {"k1":0}
         try:
             foo(1,k1=10)
-            self.fail("func_kwdefaults is not properly changed")
+            self.fail("__kwdefaults__ is not properly changed")
         except TypeError:
             pass
 

Modified: python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py	Wed Jul 11 15:40:56 2007
@@ -28,7 +28,7 @@
     try:
         a = linuxaudiodev.open('w')
     except linuxaudiodev.error as msg:
-        if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
+        if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
             raise TestSkipped, msg
         raise TestFailed, msg
 

Modified: python/branches/p3yk-noslice/Lib/test/test_list.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_list.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_list.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,7 @@
     type2test = list
 
     def test_truth(self):
-        super(ListTest, self).test_truth()
+        super().test_truth()
         self.assert_(not [])
         self.assert_([42])
 
@@ -13,7 +13,7 @@
         self.assert_([] is not [])
 
     def test_len(self):
-        super(ListTest, self).test_len()
+        super().test_len()
         self.assertEqual(len([]), 0)
         self.assertEqual(len([0]), 1)
         self.assertEqual(len([0, 1, 2]), 3)
@@ -26,7 +26,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(ListTest)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_locale.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_locale.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_locale.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 oldlocale = locale.setlocale(locale.LC_NUMERIC)
 
 if sys.platform.startswith("win"):
-    tlocs = ("en",)
+    tlocs = ("En", "English")
 else:
     tlocs = ("en_US.UTF-8", "en_US.US-ASCII", "en_US")
 

Modified: python/branches/p3yk-noslice/Lib/test/test_logging.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_logging.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_logging.py	Wed Jul 11 15:40:56 2007
@@ -25,7 +25,7 @@
 """
 
 import select
-import os, sys, string, struct, types, pickle, cStringIO
+import os, sys, struct, pickle, cStringIO
 import socket, tempfile, threading, time
 import logging, logging.handlers, logging.config
 from test.test_support import run_with_locale
@@ -355,7 +355,7 @@
     logger.info("Info message")
     message("-- logging at WARNING, 3 messages should be seen --")
     logger.warn("Warn message")
-    for i in xrange(102):
+    for i in range(102):
         message(MSG % i)
         logger.info("Info index = %d", i)
     mh.close()
@@ -455,11 +455,10 @@
 """
 
 # config2 has a subtle configuration error that should be reported
-config2 = string.replace(config1, "sys.stdout", "sys.stbout")
+config2 = config1.replace("sys.stdout", "sys.stbout")
 
 # config3 has a less subtle configuration error
-config3 = string.replace(
-    config1, "formatter=form1", "formatter=misspelled_name")
+config3 = config1.replace("formatter=form1", "formatter=misspelled_name")
 
 def test4():
     for i in range(4):
@@ -555,6 +554,8 @@
         except KeyError:
             logging.exception("just testing")
         os.remove(fn)
+        hdlr = logging.getLogger().handlers[0]
+        logging.getLogger().handlers.remove(hdlr)
     finally:
         logging._acquireLock()
         try:

Modified: python/branches/p3yk-noslice/Lib/test/test_long.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_long.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_long.py	Wed Jul 11 15:40:56 2007
@@ -23,9 +23,7 @@
 MAXDIGITS = 15
 
 # build some special values
-special = map(int, [0, 1, 2, BASE, BASE >> 1])
-special.append(0x5555555555555555)
-special.append(0xaaaaaaaaaaaaaaaa)
+special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
 #  some solid strings of one bits
 p2 = 4  # 0 and 1 already added
 for i in range(2*SHIFT):
@@ -33,8 +31,7 @@
     p2 = p2 << 1
 del p2
 # add complements & negations
-special = special + map(lambda x: ~x, special) + \
-                    map(lambda x: -x, special)
+special += [~x for x in special] + [-x for x in special]
 
 
 class LongTest(unittest.TestCase):
@@ -71,7 +68,7 @@
 
     def getran2(ndigits):
         answer = 0
-        for i in xrange(ndigits):
+        for i in range(ndigits):
             answer = (answer << SHIFT) | random.randint(0, MASK)
         if random.random() < 0.5:
             answer = -answer
@@ -92,8 +89,8 @@
             self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
 
     def test_division(self):
-        digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
-                                               KARATSUBA_CUTOFF + 14)
+        digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
+                                                      KARATSUBA_CUTOFF + 14))
         digits.append(KARATSUBA_CUTOFF * 3)
         for lenx in digits:
             x = self.getran(lenx)
@@ -102,7 +99,8 @@
                 self.check_division(x, y)
 
     def test_karatsuba(self):
-        digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)
+        digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
+                                                KARATSUBA_CUTOFF + 10))
         digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
 
         bits = [digit * SHIFT for digit in digits]
@@ -140,7 +138,7 @@
         eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
         eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
         eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
-        for n in xrange(2*SHIFT):
+        for n in range(2*SHIFT):
             p2 = 2 ** n
             eq(x << n >> n, x,
                 Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
@@ -184,7 +182,7 @@
     def test_bitop_identities(self):
         for x in special:
             self.check_bitop_identities_1(x)
-        digits = xrange(1, MAXDIGITS+1)
+        digits = range(1, MAXDIGITS+1)
         for lenx in digits:
             x = self.getran(lenx)
             self.check_bitop_identities_1(x)
@@ -194,9 +192,6 @@
                 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
 
     def slow_format(self, x, base):
-        if (x, base) == (0, 8):
-            # this is an oddball!
-            return "0"
         digits = []
         sign = 0
         if x < 0:
@@ -207,7 +202,7 @@
         digits.reverse()
         digits = digits or [0]
         return '-'[:sign] + \
-               {8: '0', 10: '', 16: '0x'}[base] + \
+               {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
                "".join(map(lambda i: "0123456789abcdef"[i], digits))
 
     def check_format_1(self, x):
@@ -229,8 +224,8 @@
     def test_format(self):
         for x in special:
             self.check_format_1(x)
-        for i in xrange(10):
-            for lenx in xrange(1, MAXDIGITS+1):
+        for i in range(10):
+            for lenx in range(1, MAXDIGITS+1):
                 x = self.getran(lenx)
                 self.check_format_1(x)
 
@@ -388,7 +383,7 @@
 
         LOG10E = math.log10(math.e)
 
-        for exp in range(10) + [100, 1000, 10000]:
+        for exp in list(range(10)) + [100, 1000, 10000]:
             value = 10 ** exp
             log10 = math.log10(value)
             self.assertAlmostEqual(log10, exp)

Modified: python/branches/p3yk-noslice/Lib/test/test_long_future.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_long_future.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_long_future.py	Wed Jul 11 15:40:56 2007
@@ -3,53 +3,53 @@
 # test_long.py instead.  In the meantime, it's too obscure to try to
 # trick just part of test_long into using future division.
 
-from test.test_support import TestFailed, verify, verbose
+import unittest
+from test.test_support import run_unittest
 
-def test_true_division():
-    if verbose:
-        print("long true division")
-    huge = 1 << 40000
-    mhuge = -huge
-    verify(huge / huge == 1.0)
-    verify(mhuge / mhuge == 1.0)
-    verify(huge / mhuge == -1.0)
-    verify(mhuge / huge == -1.0)
-    verify(1 / huge == 0.0)
-    verify(1 / huge == 0.0)
-    verify(1 / mhuge == 0.0)
-    verify(1 / mhuge == 0.0)
-    verify((666 * huge + (huge >> 1)) / huge == 666.5)
-    verify((666 * mhuge + (mhuge >> 1)) / mhuge == 666.5)
-    verify((666 * huge + (huge >> 1)) / mhuge == -666.5)
-    verify((666 * mhuge + (mhuge >> 1)) / huge == -666.5)
-    verify(huge / (huge << 1) == 0.5)
-    verify((1000000 * huge) / huge == 1000000)
-
-    namespace = {'huge': huge, 'mhuge': mhuge}
-
-    for overflow in ["float(huge)", "float(mhuge)",
-                     "huge / 1", "huge / 2", "huge / -1", "huge / -2",
-                     "mhuge / 100", "mhuge / 100"]:
-        try:
-            eval(overflow, namespace)
-        except OverflowError:
-            pass
-        else:
-            raise TestFailed("expected OverflowError from %r" % overflow)
-
-    for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
-                     "100 / mhuge", "100 / mhuge"]:
-        result = eval(underflow, namespace)
-        if result != 0.0:
-            raise TestFailed("expected underflow to 0 from %r" % underflow)
-
-    for zero in ["huge / 0", "huge / 0",
-                 "mhuge / 0", "mhuge / 0"]:
-        try:
-            eval(zero, namespace)
-        except ZeroDivisionError:
-            pass
-        else:
-            raise TestFailed("expected ZeroDivisionError from %r" % zero)
+class TrueDivisionTests(unittest.TestCase):
+    def test(self):
+        huge = 1 << 40000
+        mhuge = -huge
+        self.assertEqual(huge / huge, 1.0)
+        self.assertEqual(mhuge / mhuge, 1.0)
+        self.assertEqual(huge / mhuge, -1.0)
+        self.assertEqual(mhuge / huge, -1.0)
+        self.assertEqual(1 / huge, 0.0)
+        self.assertEqual(1 / huge, 0.0)
+        self.assertEqual(1 / mhuge, 0.0)
+        self.assertEqual(1 / mhuge, 0.0)
+        self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
+        self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
+        self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
+        self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
+        self.assertEqual(huge / (huge << 1), 0.5)
+        self.assertEqual((1000000 * huge) / huge, 1000000)
+
+        namespace = {'huge': huge, 'mhuge': mhuge}
+
+        for overflow in ["float(huge)", "float(mhuge)",
+                         "huge / 1", "huge / 2", "huge / -1", "huge / -2",
+                         "mhuge / 100", "mhuge / 200"]:
+            # XXX(cwinter) this test doesn't pass when converted to
+            # use assertRaises.
+            try:
+                eval(overflow, namespace)
+                self.fail("expected OverflowError from %r" % overflow)
+            except OverflowError:
+                pass
+
+        for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
+                         "100 / mhuge", "200 / mhuge"]:
+            result = eval(underflow, namespace)
+            self.assertEqual(result, 0.0,
+                             "expected underflow to 0 from %r" % underflow)
+
+        for zero in ["huge / 0", "mhuge / 0"]:
+            self.assertRaises(ZeroDivisionError, eval, zero, namespace)
 
-test_true_division()
+
+def test_main():
+    run_unittest(TrueDivisionTests)
+
+if __name__ == "__main__":
+    test_main()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_macfs.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_macfs.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,78 +0,0 @@
-# Copyright (C) 2003 Python Software Foundation
-
-import unittest
-import warnings
-warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
-import macfs
-import os
-import sys
-import tempfile
-from test import test_support
-
-class TestMacfs(unittest.TestCase):
-
-    def setUp(self):
-        fp = open(test_support.TESTFN, 'w')
-        fp.write('hello world\n')
-        fp.close()
-
-    def tearDown(self):
-        try:
-            os.unlink(test_support.TESTFN)
-        except:
-            pass
-
-    def test_fsspec(self):
-        fss = macfs.FSSpec(test_support.TESTFN)
-        self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname())
-
-    def test_fsref(self):
-        fsr = macfs.FSRef(test_support.TESTFN)
-        self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
-
-    def test_fsref_unicode(self):
-        if sys.getfilesystemencoding():
-            testfn_unicode = unicode(test_support.TESTFN)
-            fsr = macfs.FSRef(testfn_unicode)
-            self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
-
-    def test_coercion(self):
-        fss = macfs.FSSpec(test_support.TESTFN)
-        fsr = macfs.FSRef(test_support.TESTFN)
-        fss2 = fsr.as_fsspec()
-        fsr2 = fss.as_fsref()
-        self.assertEqual(fss.as_pathname(), fss2.as_pathname())
-        self.assertEqual(fsr.as_pathname(), fsr2.as_pathname())
-
-    def test_dates(self):
-        import time
-        fss = macfs.FSSpec(test_support.TESTFN)
-        now = int(time.time())
-        fss.SetDates(now, now+1, now+2)
-        dates = fss.GetDates()
-        self.assertEqual(dates, (now, now+1, now+2))
-
-    def test_ctor_type(self):
-        fss = macfs.FSSpec(test_support.TESTFN)
-        fss.SetCreatorType('Pyth', 'TEXT')
-        filecr, filetp = fss.GetCreatorType()
-        self.assertEqual((filecr, filetp), ('Pyth', 'TEXT'))
-
-    def test_alias(self):
-        fss = macfs.FSSpec(test_support.TESTFN)
-        alias = fss.NewAlias()
-        fss2, changed = alias.Resolve()
-        self.assertEqual(changed, 0)
-        self.assertEqual(fss.as_pathname(), fss2.as_pathname())
-
-
-    def test_fss_alias(self):
-        fss = macfs.FSSpec(test_support.TESTFN)
-
-
-def test_main():
-    test_support.run_unittest(TestMacfs)
-
-
-if __name__ == '__main__':
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_macostools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_macostools.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_macostools.py	Wed Jul 11 15:40:56 2007
@@ -51,7 +51,11 @@
 
     def test_touched(self):
         # This really only tests that nothing unforeseen happens.
-        macostools.touched(test_support.TESTFN)
+        import warnings
+        with test_support.guard_warnings_filter():
+            warnings.filterwarnings('ignore', 'macostools.touched*',
+                                    DeprecationWarning)
+            macostools.touched(test_support.TESTFN)
 
     def test_copy(self):
         try:

Modified: python/branches/p3yk-noslice/Lib/test/test_macpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_macpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_macpath.py	Wed Jul 11 15:40:56 2007
@@ -48,7 +48,7 @@
         splitext = macpath.splitext
         self.assertEquals(splitext(":foo.ext"), (':foo', '.ext'))
         self.assertEquals(splitext("foo:foo.ext"), ('foo:foo', '.ext'))
-        self.assertEquals(splitext(".ext"), ('', '.ext'))
+        self.assertEquals(splitext(".ext"), ('.ext', ''))
         self.assertEquals(splitext("foo.ext:foo"), ('foo.ext:foo', ''))
         self.assertEquals(splitext(":foo.ext:"), (':foo.ext:', ''))
         self.assertEquals(splitext(""), ('', ''))

Modified: python/branches/p3yk-noslice/Lib/test/test_mailbox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mailbox.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_mailbox.py	Wed Jul 11 15:40:56 2007
@@ -54,6 +54,7 @@
 
     def setUp(self):
         self._path = test_support.TESTFN
+        self._delete_recursively(self._path)
         self._box = self._factory(self._path)
 
     def tearDown(self):
@@ -207,7 +208,7 @@
         for value in method():
             self.fail("Not empty")
         keys, values = [], []
-        for i in xrange(repetitions):
+        for i in range(repetitions):
             keys.append(self._box.add(self._template % i))
             values.append(self._template % i)
         if do_keys and not do_values:
@@ -253,11 +254,11 @@
     def test_len(self, repetitions=10):
         # Get message count
         keys = []
-        for i in xrange(repetitions):
+        for i in range(repetitions):
             self.assert_(len(self._box) == i)
             keys.append(self._box.add(self._template % i))
             self.assert_(len(self._box) == i + 1)
-        for i in xrange(repetitions):
+        for i in range(repetitions):
             self.assert_(len(self._box) == repetitions - i)
             self._box.remove(keys[i])
             self.assert_(len(self._box) == repetitions - i - 1)
@@ -292,7 +293,7 @@
     def test_clear(self, iterations=10):
         # Remove all messages using clear()
         keys = []
-        for i in xrange(iterations):
+        for i in range(iterations):
             self._box.add(self._template % i)
         for i, key in enumerate(keys):
             self.assert_(self._box.get_string(key) == self._template % i)
@@ -322,10 +323,10 @@
     def test_popitem(self, iterations=10):
         # Get and remove an arbitrary (key, message) using popitem()
         keys = []
-        for i in xrange(10):
+        for i in range(10):
             keys.append(self._box.add(self._template % i))
         seen = []
-        for i in xrange(10):
+        for i in range(10):
             key, msg = self._box.popitem()
             self.assert_(key in keys)
             self.assert_(key not in seen)
@@ -386,7 +387,7 @@
         self._test_flush_or_close(self._box.close)
 
     def _test_flush_or_close(self, method):
-        contents = [self._template % i for i in xrange(3)]
+        contents = [self._template % i for i in range(3)]
         self._box.add(contents[0])
         self._box.add(contents[1])
         self._box.add(contents[2])
@@ -598,7 +599,7 @@
         pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)"
                              r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
         previous_groups = None
-        for x in xrange(repetitions):
+        for x in range(repetitions):
             tmp_file = self._box._create_tmp()
             head, tail = os.path.split(tmp_file.name)
             self.assertEqual(head, os.path.abspath(os.path.join(self._path,
@@ -686,7 +687,7 @@
         self._box.close()
         self._delete_recursively(self._path)
         for lock_remnant in glob.glob(self._path + '.*'):
-            os.remove(lock_remnant)
+            test_support.unlink(lock_remnant)
 
     def test_add_from_string(self):
         # Add a string starting with 'From ' to the mailbox
@@ -702,7 +703,7 @@
 
     def test_open_close_open(self):
         # Open and inspect previously-created mailbox
-        values = [self._template % i for i in xrange(3)]
+        values = [self._template % i for i in range(3)]
         for value in values:
             self._box.add(value)
         self._box.close()
@@ -717,7 +718,7 @@
     def test_add_and_close(self):
         # Verifying that closing a mailbox doesn't change added items
         self._box.add(_sample_message)
-        for i in xrange(3):
+        for i in range(3):
             self._box.add(self._template % i)
         self._box.add(_sample_message)
         self._box._file.flush()
@@ -735,10 +736,12 @@
         pid = os.fork()
         if pid == 0:
             # In the child, lock the mailbox.
-            self._box.lock()
-            time.sleep(2)
-            self._box.unlock()
-            os._exit(0)
+            try:
+                self._box.lock()
+                time.sleep(2)
+                self._box.unlock()
+            finally:
+                os._exit(0)
 
         # In the parent, sleep a bit to give the child time to acquire
         # the lock.
@@ -907,7 +910,7 @@
         self._box.close()
         self._delete_recursively(self._path)
         for lock_remnant in glob.glob(self._path + '.*'):
-            os.remove(lock_remnant)
+            test_support.unlink(lock_remnant)
 
     def test_labels(self):
         # Get labels from the mailbox
@@ -1516,11 +1519,11 @@
         # Iterate by line
         proxy.seek(0)
         iterator = iter(proxy)
-        self.assert_(iterator.next() == 'foo' + os.linesep)
-        self.assert_(iterator.next() == 'bar' + os.linesep)
-        self.assert_(iterator.next() == 'fred' + os.linesep)
-        self.assert_(iterator.next() == 'bob')
-        self.assertRaises(StopIteration, lambda: iterator.next())
+        self.assert_(next(iterator) == 'foo' + os.linesep)
+        self.assert_(next(iterator) == 'bar' + os.linesep)
+        self.assert_(next(iterator) == 'fred' + os.linesep)
+        self.assert_(next(iterator) == 'bob')
+        self.assertRaises(StopIteration, next, iterator)
 
     def _test_seek_and_tell(self, proxy):
         # Seek and use tell to check position
@@ -1666,7 +1669,7 @@
         self._msgfiles = []
 
     def tearDown(self):
-        map(os.unlink, self._msgfiles)
+        list(map(os.unlink, self._msgfiles))
         os.rmdir(os.path.join(self._dir, "cur"))
         os.rmdir(os.path.join(self._dir, "tmp"))
         os.rmdir(os.path.join(self._dir, "new"))

Modified: python/branches/p3yk-noslice/Lib/test/test_marshal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_marshal.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_marshal.py	Wed Jul 11 15:40:56 2007
@@ -144,7 +144,7 @@
 
 class CodeTestCase(unittest.TestCase):
     def test_code(self):
-        co = ExceptionTestCase.test_exceptions.func_code
+        co = ExceptionTestCase.test_exceptions.__code__
         new = marshal.loads(marshal.dumps(co))
         self.assertEqual(co, new)
 
@@ -220,6 +220,30 @@
             except Exception:
                 pass
 
+    def test_loads_recursion(self):
+        s = 'c' + ('X' * 4*4) + '{' * 2**20
+        self.assertRaises(ValueError, marshal.loads, s)
+
+    def test_recursion_limit(self):
+        # Create a deeply nested structure.
+        head = last = []
+        # The max stack depth should match the value in Python/marshal.c.
+        MAX_MARSHAL_STACK_DEPTH = 2000
+        for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
+            last.append([0])
+            last = last[-1]
+
+        # Verify we don't blow out the stack with dumps/load.
+        data = marshal.dumps(head)
+        new_head = marshal.loads(data)
+        # Don't use == to compare objects, it can exceed the recursion limit.
+        self.assertEqual(len(new_head), len(head))
+        self.assertEqual(len(new_head[0]), len(head[0]))
+        self.assertEqual(len(new_head[-1]), len(head[-1]))
+
+        last.append([0])
+        self.assertRaises(ValueError, marshal.dumps, head)
+
 def test_main():
     test_support.run_unittest(IntTestCase,
                               FloatTestCase,

Modified: python/branches/p3yk-noslice/Lib/test/test_math.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_math.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_math.py	Wed Jul 11 15:40:56 2007
@@ -105,10 +105,11 @@
     def testFrexp(self):
         self.assertRaises(TypeError, math.frexp)
 
-        def testfrexp(name, (mant, exp), (emant, eexp)):
+        def testfrexp(name, result, expected):
+            (mant, exp), (emant, eexp) = result, expected
             if abs(mant-emant) > eps or exp != eexp:
                 self.fail('%s returned %r, expected %r'%\
-                          (name, (mant, exp), (emant,eexp)))
+                          (name, result, expected))
 
         testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
         testfrexp('frexp(0)', math.frexp(0), (0, 0))
@@ -145,10 +146,11 @@
     def testModf(self):
         self.assertRaises(TypeError, math.modf)
 
-        def testmodf(name, (v1, v2), (e1, e2)):
+        def testmodf(name, result, expected):
+            (v1, v2), (e1, e2) = result, expected
             if abs(v1-e1) > eps or abs(v2-e2):
                 self.fail('%s returned %r, expected %r'%\
-                          (name, (v1,v2), (e1,e2)))
+                          (name, result, expected))
 
         testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
         testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))

Deleted: /python/branches/p3yk-noslice/Lib/test/test_md5.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_md5.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,58 +0,0 @@
-# Testing md5 module
-
-import unittest
-from md5 import md5
-from test import test_support
-
-def hexstr(s):
-    import string
-    h = string.hexdigits
-    r = ''
-    for c in s:
-        i = ord(c)
-        r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
-    return r
-
-class MD5_Test(unittest.TestCase):
-
-    def md5test(self, s, expected):
-        self.assertEqual(hexstr(md5(s).digest()), expected)
-        self.assertEqual(md5(s).hexdigest(), expected)
-
-    def test_basics(self):
-        eq = self.md5test
-        eq('', 'd41d8cd98f00b204e9800998ecf8427e')
-        eq('a', '0cc175b9c0f1b6a831c399e269772661')
-        eq('abc', '900150983cd24fb0d6963f7d28e17f72')
-        eq('message digest', 'f96b697d7cb7938d525a2f31aaf161d0')
-        eq('abcdefghijklmnopqrstuvwxyz', 'c3fcd3d76192e4007dfb496cca67e13b')
-        eq('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
-           'd174ab98d277d9f5a5611c2c9f419d9f')
-        eq('12345678901234567890123456789012345678901234567890123456789012345678901234567890',
-           '57edf4a22be3c955ac49da2e2107b67a')
-
-    def test_hexdigest(self):
-        # hexdigest is new with Python 2.0
-        m = md5('testing the hexdigest method')
-        h = m.hexdigest()
-        self.assertEqual(hexstr(m.digest()), h)
-
-    def test_large_update(self):
-        aas = 'a' * 64
-        bees = 'b' * 64
-        cees = 'c' * 64
-
-        m1 = md5()
-        m1.update(aas)
-        m1.update(bees)
-        m1.update(cees)
-
-        m2 = md5()
-        m2.update(aas + bees + cees)
-        self.assertEqual(m1.digest(), m2.digest())
-
-def test_main():
-    test_support.run_unittest(MD5_Test)
-
-if __name__ == '__main__':
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_mhlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mhlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_mhlib.py	Wed Jul 11 15:40:56 2007
@@ -121,7 +121,7 @@
                       'Date': '29 July 2001'}, "Hullo, Mrs. Premise!\n")
 
         # A folder with many messages
-        for i in range(5, 101)+range(101, 201, 2):
+        for i in list(range(5, 101))+list(range(101, 201, 2)):
             writeMessage('wide', i,
                          {'From': 'nowhere', 'Subject': 'message #%s' % i},
                          "This is message number %s\n" % i)
@@ -179,18 +179,17 @@
 
         folders = mh.listallfolders()
         folders.sort()
-        tfolders = map(normF, ['deep', 'deep/f1', 'deep/f2', 'deep/f2/f3',
-                                'inbox', 'wide'])
-        tfolders.sort()
+        tfolders = sorted(map(normF, ['deep', 'deep/f1', 'deep/f2',
+                                      'deep/f2/f3', 'inbox', 'wide']))
         eq(folders, tfolders)
 
         folders = mh.listsubfolders('deep')
         folders.sort()
-        eq(folders, map(normF, ['deep/f1', 'deep/f2']))
+        eq(folders, list(map(normF, ['deep/f1', 'deep/f2'])))
 
         folders = mh.listallsubfolders('deep')
         folders.sort()
-        eq(folders, map(normF, ['deep/f1', 'deep/f2', 'deep/f2/f3']))
+        eq(folders, list(map(normF, ['deep/f1', 'deep/f2', 'deep/f2/f3'])))
         eq(mh.listsubfolders(normF('deep/f2')), [normF('deep/f2/f3')])
 
         eq(mh.listsubfolders('inbox'), [])
@@ -203,7 +202,7 @@
 
         f = mh.openfolder('wide')
         all = f.listmessages()
-        eq(all, range(5, 101)+range(101, 201, 2))
+        eq(all, list(range(5, 101))+list(range(101, 201, 2)))
         eq(f.getcurrent(), 55)
         f.setcurrent(99)
         eq(readFile(os.path.join(_mhpath, 'wide', '.mh_sequences')),
@@ -212,21 +211,21 @@
         def seqeq(seq, val):
             eq(f.parsesequence(seq), val)
 
-        seqeq('5-55', range(5, 56))
-        seqeq('90-108', range(90, 101)+range(101, 109, 2))
-        seqeq('90-108', range(90, 101)+range(101, 109, 2))
-
-        seqeq('10:10', range(10, 20))
-        seqeq('10:+10', range(10, 20))
-        seqeq('101:10', range(101, 121, 2))
+        seqeq('5-55', list(range(5, 56)))
+        seqeq('90-108', list(range(90, 101))+list(range(101, 109, 2)))
+        seqeq('90-108', list(range(90, 101))+list(range(101, 109, 2)))
+
+        seqeq('10:10', list(range(10, 20)))
+        seqeq('10:+10', list(range(10, 20)))
+        seqeq('101:10', list(range(101, 121, 2)))
 
         seqeq('cur', [99])
         seqeq('.', [99])
         seqeq('prev', [98])
         seqeq('next', [100])
         seqeq('cur:-3', [97, 98, 99])
-        seqeq('first-cur', range(5, 100))
-        seqeq('150-last', range(151, 201, 2))
+        seqeq('first-cur', list(range(5, 100)))
+        seqeq('150-last', list(range(151, 201, 2)))
         seqeq('prev-next', [98, 99, 100])
 
         lowprimes = [5, 7, 11, 13, 17, 19, 23, 29]

Modified: python/branches/p3yk-noslice/Lib/test/test_mimetools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mimetools.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_mimetools.py	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
 
     def test_boundary(self):
         s = set([""])
-        for i in xrange(100):
+        for i in range(100):
             nb = mimetools.choose_boundary()
             self.assert_(nb not in s)
             s.add(nb)

Modified: python/branches/p3yk-noslice/Lib/test/test_minidom.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_minidom.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_minidom.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,8 @@
 import pickle
 import traceback
 from StringIO import StringIO
-from test.test_support import verbose
+from test.test_support import verbose, run_unittest, TestSkipped
+import unittest
 
 import xml.dom
 import xml.dom.minidom
@@ -22,680 +23,9 @@
 tstfile = os.path.join(os.path.dirname(base), "test"+os.extsep+"xml")
 del base
 
-def confirm(test, testname = "Test"):
-    if not test:
-        print("Failed " + testname)
-        raise Exception
-
-def testParseFromFile():
-    dom = parse(StringIO(open(tstfile).read()))
-    dom.unlink()
-    confirm(isinstance(dom,Document))
-
-def testGetElementsByTagName():
-    dom = parse(tstfile)
-    confirm(dom.getElementsByTagName("LI") == \
-            dom.documentElement.getElementsByTagName("LI"))
-    dom.unlink()
-
-def testInsertBefore():
-    dom = parseString("<doc><foo/></doc>")
-    root = dom.documentElement
-    elem = root.childNodes[0]
-    nelem = dom.createElement("element")
-    root.insertBefore(nelem, elem)
-    confirm(len(root.childNodes) == 2
-            and root.childNodes.length == 2
-            and root.childNodes[0] is nelem
-            and root.childNodes.item(0) is nelem
-            and root.childNodes[1] is elem
-            and root.childNodes.item(1) is elem
-            and root.firstChild is nelem
-            and root.lastChild is elem
-            and root.toxml() == "<doc><element/><foo/></doc>"
-            , "testInsertBefore -- node properly placed in tree")
-    nelem = dom.createElement("element")
-    root.insertBefore(nelem, None)
-    confirm(len(root.childNodes) == 3
-            and root.childNodes.length == 3
-            and root.childNodes[1] is elem
-            and root.childNodes.item(1) is elem
-            and root.childNodes[2] is nelem
-            and root.childNodes.item(2) is nelem
-            and root.lastChild is nelem
-            and nelem.previousSibling is elem
-            and root.toxml() == "<doc><element/><foo/><element/></doc>"
-            , "testInsertBefore -- node properly placed in tree")
-    nelem2 = dom.createElement("bar")
-    root.insertBefore(nelem2, nelem)
-    confirm(len(root.childNodes) == 4
-            and root.childNodes.length == 4
-            and root.childNodes[2] is nelem2
-            and root.childNodes.item(2) is nelem2
-            and root.childNodes[3] is nelem
-            and root.childNodes.item(3) is nelem
-            and nelem2.nextSibling is nelem
-            and nelem.previousSibling is nelem2
-            and root.toxml() == "<doc><element/><foo/><bar/><element/></doc>"
-            , "testInsertBefore -- node properly placed in tree")
-    dom.unlink()
-
-def _create_fragment_test_nodes():
-    dom = parseString("<doc/>")
-    orig = dom.createTextNode("original")
-    c1 = dom.createTextNode("foo")
-    c2 = dom.createTextNode("bar")
-    c3 = dom.createTextNode("bat")
-    dom.documentElement.appendChild(orig)
-    frag = dom.createDocumentFragment()
-    frag.appendChild(c1)
-    frag.appendChild(c2)
-    frag.appendChild(c3)
-    return dom, orig, c1, c2, c3, frag
-
-def testInsertBeforeFragment():
-    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
-    dom.documentElement.insertBefore(frag, None)
-    confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3),
-            "insertBefore(<fragment>, None)")
-    frag.unlink()
-    dom.unlink()
-    #
-    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
-    dom.documentElement.insertBefore(frag, orig)
-    confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3, orig),
-            "insertBefore(<fragment>, orig)")
-    frag.unlink()
-    dom.unlink()
-
-def testAppendChild():
-    dom = parse(tstfile)
-    dom.documentElement.appendChild(dom.createComment(u"Hello"))
-    confirm(dom.documentElement.childNodes[-1].nodeName == "#comment")
-    confirm(dom.documentElement.childNodes[-1].data == "Hello")
-    dom.unlink()
-
-def testAppendChildFragment():
-    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
-    dom.documentElement.appendChild(frag)
-    confirm(tuple(dom.documentElement.childNodes) == (orig, c1, c2, c3),
-            "appendChild(<fragment>)")
-    frag.unlink()
-    dom.unlink()
-
-def testReplaceChildFragment():
-    dom, orig, c1, c2, c3, frag = _create_fragment_test_nodes()
-    dom.documentElement.replaceChild(frag, orig)
-    orig.unlink()
-    confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3),
-            "replaceChild(<fragment>)")
-    frag.unlink()
-    dom.unlink()
-
-def testLegalChildren():
-    dom = Document()
-    elem = dom.createElement('element')
-    text = dom.createTextNode('text')
-
-    try: dom.appendChild(text)
-    except xml.dom.HierarchyRequestErr: pass
-    else:
-        print("dom.appendChild didn't raise HierarchyRequestErr")
-
-    dom.appendChild(elem)
-    try: dom.insertBefore(text, elem)
-    except xml.dom.HierarchyRequestErr: pass
-    else:
-        print("dom.appendChild didn't raise HierarchyRequestErr")
-
-    try: dom.replaceChild(text, elem)
-    except xml.dom.HierarchyRequestErr: pass
-    else:
-        print("dom.appendChild didn't raise HierarchyRequestErr")
-
-    nodemap = elem.attributes
-    try: nodemap.setNamedItem(text)
-    except xml.dom.HierarchyRequestErr: pass
-    else:
-        print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr")
-
-    try: nodemap.setNamedItemNS(text)
-    except xml.dom.HierarchyRequestErr: pass
-    else:
-        print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr")
-
-    elem.appendChild(text)
-    dom.unlink()
-
-def testNamedNodeMapSetItem():
-    dom = Document()
-    elem = dom.createElement('element')
-    attrs = elem.attributes
-    attrs["foo"] = "bar"
-    a = attrs.item(0)
-    confirm(a.ownerDocument is dom,
-            "NamedNodeMap.__setitem__() sets ownerDocument")
-    confirm(a.ownerElement is elem,
-            "NamedNodeMap.__setitem__() sets ownerElement")
-    confirm(a.value == "bar",
-            "NamedNodeMap.__setitem__() sets value")
-    confirm(a.nodeValue == "bar",
-            "NamedNodeMap.__setitem__() sets nodeValue")
-    elem.unlink()
-    dom.unlink()
-
-def testNonZero():
-    dom = parse(tstfile)
-    confirm(dom)# should not be zero
-    dom.appendChild(dom.createComment("foo"))
-    confirm(not dom.childNodes[-1].childNodes)
-    dom.unlink()
-
-def testUnlink():
-    dom = parse(tstfile)
-    dom.unlink()
-
-def testElement():
-    dom = Document()
-    dom.appendChild(dom.createElement("abc"))
-    confirm(dom.documentElement)
-    dom.unlink()
-
-def testAAA():
-    dom = parseString("<abc/>")
-    el = dom.documentElement
-    el.setAttribute("spam", "jam2")
-    confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA")
-    a = el.getAttributeNode("spam")
-    confirm(a.ownerDocument is dom,
-            "setAttribute() sets ownerDocument")
-    confirm(a.ownerElement is dom.documentElement,
-            "setAttribute() sets ownerElement")
-    dom.unlink()
-
-def testAAB():
-    dom = parseString("<abc/>")
-    el = dom.documentElement
-    el.setAttribute("spam", "jam")
-    el.setAttribute("spam", "jam2")
-    confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB")
-    dom.unlink()
-
-def testAddAttr():
-    dom = Document()
-    child = dom.appendChild(dom.createElement("abc"))
-
-    child.setAttribute("def", "ghi")
-    confirm(child.getAttribute("def") == "ghi")
-    confirm(child.attributes["def"].value == "ghi")
-
-    child.setAttribute("jkl", "mno")
-    confirm(child.getAttribute("jkl") == "mno")
-    confirm(child.attributes["jkl"].value == "mno")
-
-    confirm(len(child.attributes) == 2)
-
-    child.setAttribute("def", "newval")
-    confirm(child.getAttribute("def") == "newval")
-    confirm(child.attributes["def"].value == "newval")
-
-    confirm(len(child.attributes) == 2)
-    dom.unlink()
-
-def testDeleteAttr():
-    dom = Document()
-    child = dom.appendChild(dom.createElement("abc"))
-
-    confirm(len(child.attributes) == 0)
-    child.setAttribute("def", "ghi")
-    confirm(len(child.attributes) == 1)
-    del child.attributes["def"]
-    confirm(len(child.attributes) == 0)
-    dom.unlink()
-
-def testRemoveAttr():
-    dom = Document()
-    child = dom.appendChild(dom.createElement("abc"))
-
-    child.setAttribute("def", "ghi")
-    confirm(len(child.attributes) == 1)
-    child.removeAttribute("def")
-    confirm(len(child.attributes) == 0)
-
-    dom.unlink()
-
-def testRemoveAttrNS():
-    dom = Document()
-    child = dom.appendChild(
-            dom.createElementNS("http://www.python.org", "python:abc"))
-    child.setAttributeNS("http://www.w3.org", "xmlns:python",
-                                            "http://www.python.org")
-    child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
-    confirm(len(child.attributes) == 2)
-    child.removeAttributeNS("http://www.python.org", "abcattr")
-    confirm(len(child.attributes) == 1)
-
-    dom.unlink()
-
-def testRemoveAttributeNode():
-    dom = Document()
-    child = dom.appendChild(dom.createElement("foo"))
-    child.setAttribute("spam", "jam")
-    confirm(len(child.attributes) == 1)
-    node = child.getAttributeNode("spam")
-    child.removeAttributeNode(node)
-    confirm(len(child.attributes) == 0
-            and child.getAttributeNode("spam") is None)
-
-    dom.unlink()
-
-def testChangeAttr():
-    dom = parseString("<abc/>")
-    el = dom.documentElement
-    el.setAttribute("spam", "jam")
-    confirm(len(el.attributes) == 1)
-    el.setAttribute("spam", "bam")
-    # Set this attribute to be an ID and make sure that doesn't change
-    # when changing the value:
-    el.setIdAttribute("spam")
-    confirm(len(el.attributes) == 1
-            and el.attributes["spam"].value == "bam"
-            and el.attributes["spam"].nodeValue == "bam"
-            and el.getAttribute("spam") == "bam"
-            and el.getAttributeNode("spam").isId)
-    el.attributes["spam"] = "ham"
-    confirm(len(el.attributes) == 1
-            and el.attributes["spam"].value == "ham"
-            and el.attributes["spam"].nodeValue == "ham"
-            and el.getAttribute("spam") == "ham"
-            and el.attributes["spam"].isId)
-    el.setAttribute("spam2", "bam")
-    confirm(len(el.attributes) == 2
-            and el.attributes["spam"].value == "ham"
-            and el.attributes["spam"].nodeValue == "ham"
-            and el.getAttribute("spam") == "ham"
-            and el.attributes["spam2"].value == "bam"
-            and el.attributes["spam2"].nodeValue == "bam"
-            and el.getAttribute("spam2") == "bam")
-    el.attributes["spam2"] = "bam2"
-    confirm(len(el.attributes) == 2
-            and el.attributes["spam"].value == "ham"
-            and el.attributes["spam"].nodeValue == "ham"
-            and el.getAttribute("spam") == "ham"
-            and el.attributes["spam2"].value == "bam2"
-            and el.attributes["spam2"].nodeValue == "bam2"
-            and el.getAttribute("spam2") == "bam2")
-    dom.unlink()
-
-def testGetAttrList():
-    pass
-
-def testGetAttrValues(): pass
-
-def testGetAttrLength(): pass
-
-def testGetAttribute(): pass
-
-def testGetAttributeNS(): pass
-
-def testGetAttributeNode(): pass
-
-def testGetElementsByTagNameNS():
-    d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
-    <minidom:myelem/>
-    </foo>"""
-    dom = parseString(d)
-    elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom", "myelem")
-    confirm(len(elems) == 1
-            and elems[0].namespaceURI == "http://pyxml.sf.net/minidom"
-            and elems[0].localName == "myelem"
-            and elems[0].prefix == "minidom"
-            and elems[0].tagName == "minidom:myelem"
-            and elems[0].nodeName == "minidom:myelem")
-    dom.unlink()
-
-def get_empty_nodelist_from_elements_by_tagName_ns_helper(doc, nsuri, lname):
-    nodelist = doc.getElementsByTagNameNS(nsuri, lname)
-    confirm(len(nodelist) == 0)
-
-def testGetEmptyNodeListFromElementsByTagNameNS():
-    doc = parseString('<doc/>')
-    get_empty_nodelist_from_elements_by_tagName_ns_helper(
-        doc, 'http://xml.python.org/namespaces/a', 'localname')
-    get_empty_nodelist_from_elements_by_tagName_ns_helper(
-        doc, '*', 'splat')
-    get_empty_nodelist_from_elements_by_tagName_ns_helper(
-        doc, 'http://xml.python.org/namespaces/a', '*')
-
-    doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>')
-    get_empty_nodelist_from_elements_by_tagName_ns_helper(
-        doc, "http://xml.python.org/splat", "not-there")
-    get_empty_nodelist_from_elements_by_tagName_ns_helper(
-        doc, "*", "not-there")
-    get_empty_nodelist_from_elements_by_tagName_ns_helper(
-        doc, "http://somewhere.else.net/not-there", "e")
-
-def testElementReprAndStr():
-    dom = Document()
-    el = dom.appendChild(dom.createElement("abc"))
-    string1 = repr(el)
-    string2 = str(el)
-    confirm(string1 == string2)
-    dom.unlink()
-
-# commented out until Fredrick's fix is checked in
-def _testElementReprAndStrUnicode():
-    dom = Document()
-    el = dom.appendChild(dom.createElement(u"abc"))
-    string1 = repr(el)
-    string2 = str(el)
-    confirm(string1 == string2)
-    dom.unlink()
-
-# commented out until Fredrick's fix is checked in
-def _testElementReprAndStrUnicodeNS():
-    dom = Document()
-    el = dom.appendChild(
-        dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
-    string1 = repr(el)
-    string2 = str(el)
-    confirm(string1 == string2)
-    confirm(string1.find("slash:abc") != -1)
-    dom.unlink()
-
-def testAttributeRepr():
-    dom = Document()
-    el = dom.appendChild(dom.createElement(u"abc"))
-    node = el.setAttribute("abc", "def")
-    confirm(str(node) == repr(node))
-    dom.unlink()
-
-def testTextNodeRepr(): pass
-
-def testWriteXML():
-    str = '<?xml version="1.0" ?><a b="c"/>'
-    dom = parseString(str)
-    domstr = dom.toxml()
-    dom.unlink()
-    confirm(str == domstr)
-
-def testAltNewline():
-    str = '<?xml version="1.0" ?>\n<a b="c"/>\n'
-    dom = parseString(str)
-    domstr = dom.toprettyxml(newl="\r\n")
-    dom.unlink()
-    confirm(domstr == str.replace("\n", "\r\n"))
-
-def testProcessingInstruction():
-    dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
-    pi = dom.documentElement.firstChild
-    confirm(pi.target == "mypi"
-            and pi.data == "data \t\n "
-            and pi.nodeName == "mypi"
-            and pi.nodeType == Node.PROCESSING_INSTRUCTION_NODE
-            and pi.attributes is None
-            and not pi.hasChildNodes()
-            and len(pi.childNodes) == 0
-            and pi.firstChild is None
-            and pi.lastChild is None
-            and pi.localName is None
-            and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE)
-
-def testProcessingInstructionRepr(): pass
-
-def testTextRepr(): pass
-
-def testWriteText(): pass
-
-def testDocumentElement(): pass
-
-def testTooManyDocumentElements():
-    doc = parseString("<doc/>")
-    elem = doc.createElement("extra")
-    try:
-        doc.appendChild(elem)
-    except xml.dom.HierarchyRequestErr:
-        pass
-    else:
-        print("Failed to catch expected exception when" \
-              " adding extra document element.")
-    elem.unlink()
-    doc.unlink()
-
-def testCreateElementNS(): pass
-
-def testCreateAttributeNS(): pass
-
-def testParse(): pass
-
-def testParseString(): pass
-
-def testComment(): pass
-
-def testAttrListItem(): pass
-
-def testAttrListItems(): pass
-
-def testAttrListItemNS(): pass
-
-def testAttrListKeys(): pass
-
-def testAttrListKeysNS(): pass
-
-def testRemoveNamedItem():
-    doc = parseString("<doc a=''/>")
-    e = doc.documentElement
-    attrs = e.attributes
-    a1 = e.getAttributeNode("a")
-    a2 = attrs.removeNamedItem("a")
-    confirm(a1.isSameNode(a2))
-    try:
-        attrs.removeNamedItem("a")
-    except xml.dom.NotFoundErr:
-        pass
-
-def testRemoveNamedItemNS():
-    doc = parseString("<doc xmlns:a='http://xml.python.org/' a:b=''/>")
-    e = doc.documentElement
-    attrs = e.attributes
-    a1 = e.getAttributeNodeNS("http://xml.python.org/", "b")
-    a2 = attrs.removeNamedItemNS("http://xml.python.org/", "b")
-    confirm(a1.isSameNode(a2))
-    try:
-        attrs.removeNamedItemNS("http://xml.python.org/", "b")
-    except xml.dom.NotFoundErr:
-        pass
-
-def testAttrListValues(): pass
-
-def testAttrListLength(): pass
-
-def testAttrList__getitem__(): pass
-
-def testAttrList__setitem__(): pass
-
-def testSetAttrValueandNodeValue(): pass
-
-def testParseElement(): pass
-
-def testParseAttributes(): pass
-
-def testParseElementNamespaces(): pass
-
-def testParseAttributeNamespaces(): pass
-
-def testParseProcessingInstructions(): pass
-
-def testChildNodes(): pass
-
-def testFirstChild(): pass
-
-def testHasChildNodes(): pass
-
-def testCloneElementShallow():
-    dom, clone = _setupCloneElement(0)
-    confirm(len(clone.childNodes) == 0
-            and clone.childNodes.length == 0
-            and clone.parentNode is None
-            and clone.toxml() == '<doc attr="value"/>'
-            , "testCloneElementShallow")
-    dom.unlink()
-
-def testCloneElementDeep():
-    dom, clone = _setupCloneElement(1)
-    confirm(len(clone.childNodes) == 1
-            and clone.childNodes.length == 1
-            and clone.parentNode is None
-            and clone.toxml() == '<doc attr="value"><foo/></doc>'
-            , "testCloneElementDeep")
-    dom.unlink()
-
-def _setupCloneElement(deep):
-    dom = parseString("<doc attr='value'><foo/></doc>")
-    root = dom.documentElement
-    clone = root.cloneNode(deep)
-    _testCloneElementCopiesAttributes(
-        root, clone, "testCloneElement" + (deep and "Deep" or "Shallow"))
-    # mutilate the original so shared data is detected
-    root.tagName = root.nodeName = "MODIFIED"
-    root.setAttribute("attr", "NEW VALUE")
-    root.setAttribute("added", "VALUE")
-    return dom, clone
-
-def _testCloneElementCopiesAttributes(e1, e2, test):
-    attrs1 = e1.attributes
-    attrs2 = e2.attributes
-    keys1 = sorted(attrs1.keys())
-    keys2 = sorted(attrs2.keys())
-    confirm(keys1 == keys2, "clone of element has same attribute keys")
-    for i in range(len(keys1)):
-        a1 = attrs1.item(i)
-        a2 = attrs2.item(i)
-        confirm(a1 is not a2
-                and a1.value == a2.value
-                and a1.nodeValue == a2.nodeValue
-                and a1.namespaceURI == a2.namespaceURI
-                and a1.localName == a2.localName
-                , "clone of attribute node has proper attribute values")
-        confirm(a2.ownerElement is e2,
-                "clone of attribute node correctly owned")
-
-def testCloneDocumentShallow():
-    doc = parseString("<?xml version='1.0'?>\n"
-                      "<!-- comment -->"
-                      "<!DOCTYPE doc [\n"
-                      "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
-                      "]>\n"
-                      "<doc attr='value'/>")
-    doc2 = doc.cloneNode(0)
-    confirm(doc2 is None,
-            "testCloneDocumentShallow:"
-            " shallow cloning of documents makes no sense!")
-
-def testCloneDocumentDeep():
-    doc = parseString("<?xml version='1.0'?>\n"
-                      "<!-- comment -->"
-                      "<!DOCTYPE doc [\n"
-                      "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
-                      "]>\n"
-                      "<doc attr='value'/>")
-    doc2 = doc.cloneNode(1)
-    confirm(not (doc.isSameNode(doc2) or doc2.isSameNode(doc)),
-            "testCloneDocumentDeep: document objects not distinct")
-    confirm(len(doc.childNodes) == len(doc2.childNodes),
-            "testCloneDocumentDeep: wrong number of Document children")
-    confirm(doc2.documentElement.nodeType == Node.ELEMENT_NODE,
-            "testCloneDocumentDeep: documentElement not an ELEMENT_NODE")
-    confirm(doc2.documentElement.ownerDocument.isSameNode(doc2),
-            "testCloneDocumentDeep: documentElement owner is not new document")
-    confirm(not doc.documentElement.isSameNode(doc2.documentElement),
-            "testCloneDocumentDeep: documentElement should not be shared")
-    if doc.doctype is not None:
-        # check the doctype iff the original DOM maintained it
-        confirm(doc2.doctype.nodeType == Node.DOCUMENT_TYPE_NODE,
-                "testCloneDocumentDeep: doctype not a DOCUMENT_TYPE_NODE")
-        confirm(doc2.doctype.ownerDocument.isSameNode(doc2))
-        confirm(not doc.doctype.isSameNode(doc2.doctype))
-
-def testCloneDocumentTypeDeepOk():
-    doctype = create_nonempty_doctype()
-    clone = doctype.cloneNode(1)
-    confirm(clone is not None
-            and clone.nodeName == doctype.nodeName
-            and clone.name == doctype.name
-            and clone.publicId == doctype.publicId
-            and clone.systemId == doctype.systemId
-            and len(clone.entities) == len(doctype.entities)
-            and clone.entities.item(len(clone.entities)) is None
-            and len(clone.notations) == len(doctype.notations)
-            and clone.notations.item(len(clone.notations)) is None
-            and len(clone.childNodes) == 0)
-    for i in range(len(doctype.entities)):
-        se = doctype.entities.item(i)
-        ce = clone.entities.item(i)
-        confirm((not se.isSameNode(ce))
-                and (not ce.isSameNode(se))
-                and ce.nodeName == se.nodeName
-                and ce.notationName == se.notationName
-                and ce.publicId == se.publicId
-                and ce.systemId == se.systemId
-                and ce.encoding == se.encoding
-                and ce.actualEncoding == se.actualEncoding
-                and ce.version == se.version)
-    for i in range(len(doctype.notations)):
-        sn = doctype.notations.item(i)
-        cn = clone.notations.item(i)
-        confirm((not sn.isSameNode(cn))
-                and (not cn.isSameNode(sn))
-                and cn.nodeName == sn.nodeName
-                and cn.publicId == sn.publicId
-                and cn.systemId == sn.systemId)
-
-def testCloneDocumentTypeDeepNotOk():
-    doc = create_doc_with_doctype()
-    clone = doc.doctype.cloneNode(1)
-    confirm(clone is None, "testCloneDocumentTypeDeepNotOk")
-
-def testCloneDocumentTypeShallowOk():
-    doctype = create_nonempty_doctype()
-    clone = doctype.cloneNode(0)
-    confirm(clone is not None
-            and clone.nodeName == doctype.nodeName
-            and clone.name == doctype.name
-            and clone.publicId == doctype.publicId
-            and clone.systemId == doctype.systemId
-            and len(clone.entities) == 0
-            and clone.entities.item(0) is None
-            and len(clone.notations) == 0
-            and clone.notations.item(0) is None
-            and len(clone.childNodes) == 0)
-
-def testCloneDocumentTypeShallowNotOk():
-    doc = create_doc_with_doctype()
-    clone = doc.doctype.cloneNode(0)
-    confirm(clone is None, "testCloneDocumentTypeShallowNotOk")
-
-def check_import_document(deep, testName):
-    doc1 = parseString("<doc/>")
-    doc2 = parseString("<doc/>")
-    try:
-        doc1.importNode(doc2, deep)
-    except xml.dom.NotSupportedErr:
-        pass
-    else:
-        raise Exception(testName +
-                        ": expected NotSupportedErr when importing a document")
-
-def testImportDocumentShallow():
-    check_import_document(0, "testImportDocumentShallow")
-
-def testImportDocumentDeep():
-    check_import_document(1, "testImportDocumentDeep")
-
 # The tests of DocumentType importing use these helpers to construct
 # the documents to work with, since not all DOM builders actually
 # create the DocumentType nodes.
-
 def create_doc_without_doctype(doctype=None):
     return getDOMImplementation().createDocument(None, "doc", doctype)
 
@@ -722,673 +52,1263 @@
     doctype.notations.item(0).ownerDocument = doc
     return doc
 
-def testImportDocumentTypeShallow():
-    src = create_doc_with_doctype()
-    target = create_doc_without_doctype()
-    try:
-        imported = target.importNode(src.doctype, 0)
-    except xml.dom.NotSupportedErr:
-        pass
-    else:
-        raise Exception(
-            "testImportDocumentTypeShallow: expected NotSupportedErr")
-
-def testImportDocumentTypeDeep():
-    src = create_doc_with_doctype()
-    target = create_doc_without_doctype()
-    try:
-        imported = target.importNode(src.doctype, 1)
-    except xml.dom.NotSupportedErr:
-        pass
-    else:
-        raise Exception(
-            "testImportDocumentTypeDeep: expected NotSupportedErr")
-
-# Testing attribute clones uses a helper, and should always be deep,
-# even if the argument to cloneNode is false.
-def check_clone_attribute(deep, testName):
-    doc = parseString("<doc attr='value'/>")
-    attr = doc.documentElement.getAttributeNode("attr")
-    assert attr is not None
-    clone = attr.cloneNode(deep)
-    confirm(not clone.isSameNode(attr))
-    confirm(not attr.isSameNode(clone))
-    confirm(clone.ownerElement is None,
-            testName + ": ownerElement should be None")
-    confirm(clone.ownerDocument.isSameNode(attr.ownerDocument),
-            testName + ": ownerDocument does not match")
-    confirm(clone.specified,
-            testName + ": cloned attribute must have specified == True")
-
-def testCloneAttributeShallow():
-    check_clone_attribute(0, "testCloneAttributeShallow")
-
-def testCloneAttributeDeep():
-    check_clone_attribute(1, "testCloneAttributeDeep")
-
-def check_clone_pi(deep, testName):
-    doc = parseString("<?target data?><doc/>")
-    pi = doc.firstChild
-    assert pi.nodeType == Node.PROCESSING_INSTRUCTION_NODE
-    clone = pi.cloneNode(deep)
-    confirm(clone.target == pi.target
-            and clone.data == pi.data)
-
-def testClonePIShallow():
-    check_clone_pi(0, "testClonePIShallow")
-
-def testClonePIDeep():
-    check_clone_pi(1, "testClonePIDeep")
-
-def testNormalize():
-    doc = parseString("<doc/>")
-    root = doc.documentElement
-    root.appendChild(doc.createTextNode("first"))
-    root.appendChild(doc.createTextNode("second"))
-    confirm(len(root.childNodes) == 2
-            and root.childNodes.length == 2, "testNormalize -- preparation")
-    doc.normalize()
-    confirm(len(root.childNodes) == 1
-            and root.childNodes.length == 1
-            and root.firstChild is root.lastChild
-            and root.firstChild.data == "firstsecond"
-            , "testNormalize -- result")
-    doc.unlink()
-
-    doc = parseString("<doc/>")
-    root = doc.documentElement
-    root.appendChild(doc.createTextNode(""))
-    doc.normalize()
-    confirm(len(root.childNodes) == 0
-            and root.childNodes.length == 0,
-            "testNormalize -- single empty node removed")
-    doc.unlink()
-
-def testSiblings():
-    doc = parseString("<doc><?pi?>text?<elm/></doc>")
-    root = doc.documentElement
-    (pi, text, elm) = root.childNodes
-
-    confirm(pi.nextSibling is text and
-            pi.previousSibling is None and
-            text.nextSibling is elm and
-            text.previousSibling is pi and
-            elm.nextSibling is None and
-            elm.previousSibling is text, "testSiblings")
-
-    doc.unlink()
-
-def testParents():
-    doc = parseString("<doc><elm1><elm2/><elm2><elm3/></elm2></elm1></doc>")
-    root = doc.documentElement
-    elm1 = root.childNodes[0]
-    (elm2a, elm2b) = elm1.childNodes
-    elm3 = elm2b.childNodes[0]
-
-    confirm(root.parentNode is doc and
-            elm1.parentNode is root and
-            elm2a.parentNode is elm1 and
-            elm2b.parentNode is elm1 and
-            elm3.parentNode is elm2b, "testParents")
-
-    doc.unlink()
-
-def testNodeListItem():
-    doc = parseString("<doc><e/><e/></doc>")
-    children = doc.childNodes
-    docelem = children[0]
-    confirm(children[0] is children.item(0)
-            and children.item(1) is None
-            and docelem.childNodes.item(0) is docelem.childNodes[0]
-            and docelem.childNodes.item(1) is docelem.childNodes[1]
-            and docelem.childNodes.item(0).childNodes.item(0) is None,
-            "test NodeList.item()")
-    doc.unlink()
-
-def testSAX2DOM():
-    from xml.dom import pulldom
-
-    sax2dom = pulldom.SAX2DOM()
-    sax2dom.startDocument()
-    sax2dom.startElement("doc", {})
-    sax2dom.characters("text")
-    sax2dom.startElement("subelm", {})
-    sax2dom.characters("text")
-    sax2dom.endElement("subelm")
-    sax2dom.characters("text")
-    sax2dom.endElement("doc")
-    sax2dom.endDocument()
-
-    doc = sax2dom.document
-    root = doc.documentElement
-    (text1, elm1, text2) = root.childNodes
-    text3 = elm1.childNodes[0]
-
-    confirm(text1.previousSibling is None and
-            text1.nextSibling is elm1 and
-            elm1.previousSibling is text1 and
-            elm1.nextSibling is text2 and
-            text2.previousSibling is elm1 and
-            text2.nextSibling is None and
-            text3.previousSibling is None and
-            text3.nextSibling is None, "testSAX2DOM - siblings")
-
-    confirm(root.parentNode is doc and
-            text1.parentNode is root and
-            elm1.parentNode is root and
-            text2.parentNode is root and
-            text3.parentNode is elm1, "testSAX2DOM - parents")
-
-    doc.unlink()
-
-def testEncodings():
-    doc = parseString('<foo>&#x20ac;</foo>')
-    confirm(doc.toxml() == u'<?xml version="1.0" ?><foo>\u20ac</foo>'
-            and doc.toxml('utf-8') == '<?xml version="1.0" encoding="utf-8"?><foo>\xe2\x82\xac</foo>'
-            and doc.toxml('iso-8859-15') == '<?xml version="1.0" encoding="iso-8859-15"?><foo>\xa4</foo>',
-            "testEncodings - encoding EURO SIGN")
-
-    # Verify that character decoding errors throw exceptions instead of crashing
-    try:
-        doc = parseString('<fran\xe7ais>Comment \xe7a va ? Tr\xe8s bien ?</fran\xe7ais>')
-    except UnicodeDecodeError:
-        pass
-    else:
-        print('parsing with bad encoding should raise a UnicodeDecodeError')
+class MinidomTest(unittest.TestCase):
+    def tearDown(self):
+        try:
+            Node.allnodes
+        except AttributeError:
+            # We don't actually have the minidom from the standard library,
+            # but are picking up the PyXML version from site-packages.
+            pass
+        else:
+            self.confirm(len(Node.allnodes) == 0,
+                    "assertion: len(Node.allnodes) == 0")
+            if len(Node.allnodes):
+                print("Garbage left over:")
+                if verbose:
+                    print(list(Node.allnodes.items())[0:10])
+                else:
+                    # Don't print specific nodes if repeatable results
+                    # are needed
+                    print(len(Node.allnodes))
+            Node.allnodes = {}
+
+    def confirm(self, test, testname = "Test"):
+        self.assertTrue(test, testname)
 
-    doc.unlink()
+    def checkWholeText(self, node, s):
+        t = node.wholeText
+        self.confirm(t == s, "looking for %s, found %s" % (repr(s), repr(t)))
+
+    def testParseFromFile(self):
+        dom = parse(StringIO(open(tstfile).read()))
+        dom.unlink()
+        self.confirm(isinstance(dom, Document))
+
+    def testGetElementsByTagName(self):
+        dom = parse(tstfile)
+        self.confirm(dom.getElementsByTagName("LI") == \
+                dom.documentElement.getElementsByTagName("LI"))
+        dom.unlink()
+
+    def testInsertBefore(self):
+        dom = parseString("<doc><foo/></doc>")
+        root = dom.documentElement
+        elem = root.childNodes[0]
+        nelem = dom.createElement("element")
+        root.insertBefore(nelem, elem)
+        self.confirm(len(root.childNodes) == 2
+                and root.childNodes.length == 2
+                and root.childNodes[0] is nelem
+                and root.childNodes.item(0) is nelem
+                and root.childNodes[1] is elem
+                and root.childNodes.item(1) is elem
+                and root.firstChild is nelem
+                and root.lastChild is elem
+                and root.toxml() == "<doc><element/><foo/></doc>"
+                , "testInsertBefore -- node properly placed in tree")
+        nelem = dom.createElement("element")
+        root.insertBefore(nelem, None)
+        self.confirm(len(root.childNodes) == 3
+                and root.childNodes.length == 3
+                and root.childNodes[1] is elem
+                and root.childNodes.item(1) is elem
+                and root.childNodes[2] is nelem
+                and root.childNodes.item(2) is nelem
+                and root.lastChild is nelem
+                and nelem.previousSibling is elem
+                and root.toxml() == "<doc><element/><foo/><element/></doc>"
+                , "testInsertBefore -- node properly placed in tree")
+        nelem2 = dom.createElement("bar")
+        root.insertBefore(nelem2, nelem)
+        self.confirm(len(root.childNodes) == 4
+                and root.childNodes.length == 4
+                and root.childNodes[2] is nelem2
+                and root.childNodes.item(2) is nelem2
+                and root.childNodes[3] is nelem
+                and root.childNodes.item(3) is nelem
+                and nelem2.nextSibling is nelem
+                and nelem.previousSibling is nelem2
+                and root.toxml() ==
+                "<doc><element/><foo/><bar/><element/></doc>"
+                , "testInsertBefore -- node properly placed in tree")
+        dom.unlink()
+
+    def _create_fragment_test_nodes(self):
+        dom = parseString("<doc/>")
+        orig = dom.createTextNode("original")
+        c1 = dom.createTextNode("foo")
+        c2 = dom.createTextNode("bar")
+        c3 = dom.createTextNode("bat")
+        dom.documentElement.appendChild(orig)
+        frag = dom.createDocumentFragment()
+        frag.appendChild(c1)
+        frag.appendChild(c2)
+        frag.appendChild(c3)
+        return dom, orig, c1, c2, c3, frag
+
+    def testInsertBeforeFragment(self):
+        dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
+        dom.documentElement.insertBefore(frag, None)
+        self.confirm(tuple(dom.documentElement.childNodes) ==
+                     (orig, c1, c2, c3),
+                     "insertBefore(<fragment>, None)")
+        frag.unlink()
+        dom.unlink()
+
+        dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
+        dom.documentElement.insertBefore(frag, orig)
+        self.confirm(tuple(dom.documentElement.childNodes) ==
+                     (c1, c2, c3, orig),
+                     "insertBefore(<fragment>, orig)")
+        frag.unlink()
+        dom.unlink()
+
+    def testAppendChild(self):
+        dom = parse(tstfile)
+        dom.documentElement.appendChild(dom.createComment(u"Hello"))
+        self.confirm(dom.documentElement.childNodes[-1].nodeName == "#comment")
+        self.confirm(dom.documentElement.childNodes[-1].data == "Hello")
+        dom.unlink()
+
+    def testAppendChildFragment(self):
+        dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
+        dom.documentElement.appendChild(frag)
+        self.confirm(tuple(dom.documentElement.childNodes) ==
+                     (orig, c1, c2, c3),
+                     "appendChild(<fragment>)")
+        frag.unlink()
+        dom.unlink()
+
+    def testReplaceChildFragment(self):
+        dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
+        dom.documentElement.replaceChild(frag, orig)
+        orig.unlink()
+        self.confirm(tuple(dom.documentElement.childNodes) == (c1, c2, c3),
+                "replaceChild(<fragment>)")
+        frag.unlink()
+        dom.unlink()
+
+    def testLegalChildren(self):
+        dom = Document()
+        elem = dom.createElement('element')
+        text = dom.createTextNode('text')
+        self.assertRaises(xml.dom.HierarchyRequestErr, dom.appendChild, text)
+
+        dom.appendChild(elem)
+        self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text,
+                          elem)
+        self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text,
+                          elem)
+
+        nodemap = elem.attributes
+        self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem,
+                          text)
+        self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS,
+                          text)
+
+        elem.appendChild(text)
+        dom.unlink()
+
+    def testNamedNodeMapSetItem(self):
+        dom = Document()
+        elem = dom.createElement('element')
+        attrs = elem.attributes
+        attrs["foo"] = "bar"
+        a = attrs.item(0)
+        self.confirm(a.ownerDocument is dom,
+                "NamedNodeMap.__setitem__() sets ownerDocument")
+        self.confirm(a.ownerElement is elem,
+                "NamedNodeMap.__setitem__() sets ownerElement")
+        self.confirm(a.value == "bar",
+                "NamedNodeMap.__setitem__() sets value")
+        self.confirm(a.nodeValue == "bar",
+                "NamedNodeMap.__setitem__() sets nodeValue")
+        elem.unlink()
+        dom.unlink()
+
+    def testNonZero(self):
+        dom = parse(tstfile)
+        self.confirm(dom)# should not be zero
+        dom.appendChild(dom.createComment("foo"))
+        self.confirm(not dom.childNodes[-1].childNodes)
+        dom.unlink()
+
+    def testUnlink(self):
+        dom = parse(tstfile)
+        dom.unlink()
+
+    def testElement(self):
+        dom = Document()
+        dom.appendChild(dom.createElement("abc"))
+        self.confirm(dom.documentElement)
+        dom.unlink()
+
+    def testAAA(self):
+        dom = parseString("<abc/>")
+        el = dom.documentElement
+        el.setAttribute("spam", "jam2")
+        self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAA")
+        a = el.getAttributeNode("spam")
+        self.confirm(a.ownerDocument is dom,
+                "setAttribute() sets ownerDocument")
+        self.confirm(a.ownerElement is dom.documentElement,
+                "setAttribute() sets ownerElement")
+        dom.unlink()
+
+    def testAAB(self):
+        dom = parseString("<abc/>")
+        el = dom.documentElement
+        el.setAttribute("spam", "jam")
+        el.setAttribute("spam", "jam2")
+        self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB")
+        dom.unlink()
+
+    def testAddAttr(self):
+        dom = Document()
+        child = dom.appendChild(dom.createElement("abc"))
+
+        child.setAttribute("def", "ghi")
+        self.confirm(child.getAttribute("def") == "ghi")
+        self.confirm(child.attributes["def"].value == "ghi")
+
+        child.setAttribute("jkl", "mno")
+        self.confirm(child.getAttribute("jkl") == "mno")
+        self.confirm(child.attributes["jkl"].value == "mno")
+
+        self.confirm(len(child.attributes) == 2)
+
+        child.setAttribute("def", "newval")
+        self.confirm(child.getAttribute("def") == "newval")
+        self.confirm(child.attributes["def"].value == "newval")
+
+        self.confirm(len(child.attributes) == 2)
+        dom.unlink()
+
+    def testDeleteAttr(self):
+        dom = Document()
+        child = dom.appendChild(dom.createElement("abc"))
+
+        self.confirm(len(child.attributes) == 0)
+        child.setAttribute("def", "ghi")
+        self.confirm(len(child.attributes) == 1)
+        del child.attributes["def"]
+        self.confirm(len(child.attributes) == 0)
+        dom.unlink()
+
+    def testRemoveAttr(self):
+        dom = Document()
+        child = dom.appendChild(dom.createElement("abc"))
+
+        child.setAttribute("def", "ghi")
+        self.confirm(len(child.attributes) == 1)
+        child.removeAttribute("def")
+        self.confirm(len(child.attributes) == 0)
+        dom.unlink()
+
+    def testRemoveAttrNS(self):
+        dom = Document()
+        child = dom.appendChild(
+                dom.createElementNS("http://www.python.org", "python:abc"))
+        child.setAttributeNS("http://www.w3.org", "xmlns:python",
+                                                "http://www.python.org")
+        child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
+        self.confirm(len(child.attributes) == 2)
+        child.removeAttributeNS("http://www.python.org", "abcattr")
+        self.confirm(len(child.attributes) == 1)
+        dom.unlink()
+
+    def testRemoveAttributeNode(self):
+        dom = Document()
+        child = dom.appendChild(dom.createElement("foo"))
+        child.setAttribute("spam", "jam")
+        self.confirm(len(child.attributes) == 1)
+        node = child.getAttributeNode("spam")
+        child.removeAttributeNode(node)
+        self.confirm(len(child.attributes) == 0
+                and child.getAttributeNode("spam") is None)
+        dom.unlink()
+
+    def testChangeAttr(self):
+        dom = parseString("<abc/>")
+        el = dom.documentElement
+        el.setAttribute("spam", "jam")
+        self.confirm(len(el.attributes) == 1)
+        el.setAttribute("spam", "bam")
+        # Set this attribute to be an ID and make sure that doesn't change
+        # when changing the value:
+        el.setIdAttribute("spam")
+        self.confirm(len(el.attributes) == 1
+                and el.attributes["spam"].value == "bam"
+                and el.attributes["spam"].nodeValue == "bam"
+                and el.getAttribute("spam") == "bam"
+                and el.getAttributeNode("spam").isId)
+        el.attributes["spam"] = "ham"
+        self.confirm(len(el.attributes) == 1
+                and el.attributes["spam"].value == "ham"
+                and el.attributes["spam"].nodeValue == "ham"
+                and el.getAttribute("spam") == "ham"
+                and el.attributes["spam"].isId)
+        el.setAttribute("spam2", "bam")
+        self.confirm(len(el.attributes) == 2
+                and el.attributes["spam"].value == "ham"
+                and el.attributes["spam"].nodeValue == "ham"
+                and el.getAttribute("spam") == "ham"
+                and el.attributes["spam2"].value == "bam"
+                and el.attributes["spam2"].nodeValue == "bam"
+                and el.getAttribute("spam2") == "bam")
+        el.attributes["spam2"] = "bam2"
+        self.confirm(len(el.attributes) == 2
+                and el.attributes["spam"].value == "ham"
+                and el.attributes["spam"].nodeValue == "ham"
+                and el.getAttribute("spam") == "ham"
+                and el.attributes["spam2"].value == "bam2"
+                and el.attributes["spam2"].nodeValue == "bam2"
+                and el.getAttribute("spam2") == "bam2")
+        dom.unlink()
 
-class UserDataHandler:
-    called = 0
-    def handle(self, operation, key, data, src, dst):
-        dst.setUserData(key, data + 1, self)
-        src.setUserData(key, None, None)
-        self.called = 1
-
-def testUserData():
-    dom = Document()
-    n = dom.createElement('e')
-    confirm(n.getUserData("foo") is None)
-    n.setUserData("foo", None, None)
-    confirm(n.getUserData("foo") is None)
-    n.setUserData("foo", 12, 12)
-    n.setUserData("bar", 13, 13)
-    confirm(n.getUserData("foo") == 12)
-    confirm(n.getUserData("bar") == 13)
-    n.setUserData("foo", None, None)
-    confirm(n.getUserData("foo") is None)
-    confirm(n.getUserData("bar") == 13)
-
-    handler = UserDataHandler()
-    n.setUserData("bar", 12, handler)
-    c = n.cloneNode(1)
-    confirm(handler.called
-            and n.getUserData("bar") is None
-            and c.getUserData("bar") == 13)
-    n.unlink()
-    c.unlink()
-    dom.unlink()
-
-def testRenameAttribute():
-    doc = parseString("<doc a='v'/>")
-    elem = doc.documentElement
-    attrmap = elem.attributes
-    attr = elem.attributes['a']
-
-    # Simple renaming
-    attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "b")
-    confirm(attr.name == "b"
-            and attr.nodeName == "b"
-            and attr.localName is None
-            and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
-            and attr.prefix is None
-            and attr.value == "v"
-            and elem.getAttributeNode("a") is None
-            and elem.getAttributeNode("b").isSameNode(attr)
-            and attrmap["b"].isSameNode(attr)
-            and attr.ownerDocument.isSameNode(doc)
-            and attr.ownerElement.isSameNode(elem))
-
-    # Rename to have a namespace, no prefix
-    attr = doc.renameNode(attr, "http://xml.python.org/ns", "c")
-    confirm(attr.name == "c"
-            and attr.nodeName == "c"
-            and attr.localName == "c"
-            and attr.namespaceURI == "http://xml.python.org/ns"
-            and attr.prefix is None
-            and attr.value == "v"
-            and elem.getAttributeNode("a") is None
-            and elem.getAttributeNode("b") is None
-            and elem.getAttributeNode("c").isSameNode(attr)
-            and elem.getAttributeNodeNS(
-                "http://xml.python.org/ns", "c").isSameNode(attr)
-            and attrmap["c"].isSameNode(attr)
-            and attrmap[("http://xml.python.org/ns", "c")].isSameNode(attr))
-
-    # Rename to have a namespace, with prefix
-    attr = doc.renameNode(attr, "http://xml.python.org/ns2", "p:d")
-    confirm(attr.name == "p:d"
-            and attr.nodeName == "p:d"
-            and attr.localName == "d"
-            and attr.namespaceURI == "http://xml.python.org/ns2"
-            and attr.prefix == "p"
-            and attr.value == "v"
-            and elem.getAttributeNode("a") is None
-            and elem.getAttributeNode("b") is None
-            and elem.getAttributeNode("c") is None
-            and elem.getAttributeNodeNS(
-                "http://xml.python.org/ns", "c") is None
-            and elem.getAttributeNode("p:d").isSameNode(attr)
-            and elem.getAttributeNodeNS(
-                "http://xml.python.org/ns2", "d").isSameNode(attr)
-            and attrmap["p:d"].isSameNode(attr)
-            and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr))
-
-    # Rename back to a simple non-NS node
-    attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "e")
-    confirm(attr.name == "e"
-            and attr.nodeName == "e"
-            and attr.localName is None
-            and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
-            and attr.prefix is None
-            and attr.value == "v"
-            and elem.getAttributeNode("a") is None
-            and elem.getAttributeNode("b") is None
-            and elem.getAttributeNode("c") is None
-            and elem.getAttributeNode("p:d") is None
-            and elem.getAttributeNodeNS(
-                "http://xml.python.org/ns", "c") is None
-            and elem.getAttributeNode("e").isSameNode(attr)
-            and attrmap["e"].isSameNode(attr))
-
-    try:
-        doc.renameNode(attr, "http://xml.python.org/ns", "xmlns")
-    except xml.dom.NamespaceErr:
+    def testGetAttrList(self):
         pass
-    else:
-        print("expected NamespaceErr")
 
-    checkRenameNodeSharedConstraints(doc, attr)
-    doc.unlink()
+    def testGetAttrValues(self): pass
 
-def testRenameElement():
-    doc = parseString("<doc/>")
-    elem = doc.documentElement
-
-    # Simple renaming
-    elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "a")
-    confirm(elem.tagName == "a"
-            and elem.nodeName == "a"
-            and elem.localName is None
-            and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
-            and elem.prefix is None
-            and elem.ownerDocument.isSameNode(doc))
-
-    # Rename to have a namespace, no prefix
-    elem = doc.renameNode(elem, "http://xml.python.org/ns", "b")
-    confirm(elem.tagName == "b"
-            and elem.nodeName == "b"
-            and elem.localName == "b"
-            and elem.namespaceURI == "http://xml.python.org/ns"
-            and elem.prefix is None
-            and elem.ownerDocument.isSameNode(doc))
-
-    # Rename to have a namespace, with prefix
-    elem = doc.renameNode(elem, "http://xml.python.org/ns2", "p:c")
-    confirm(elem.tagName == "p:c"
-            and elem.nodeName == "p:c"
-            and elem.localName == "c"
-            and elem.namespaceURI == "http://xml.python.org/ns2"
-            and elem.prefix == "p"
-            and elem.ownerDocument.isSameNode(doc))
-
-    # Rename back to a simple non-NS node
-    elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "d")
-    confirm(elem.tagName == "d"
-            and elem.nodeName == "d"
-            and elem.localName is None
-            and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
-            and elem.prefix is None
-            and elem.ownerDocument.isSameNode(doc))
-
-    checkRenameNodeSharedConstraints(doc, elem)
-    doc.unlink()
-
-def checkRenameNodeSharedConstraints(doc, node):
-    # Make sure illegal NS usage is detected:
-    try:
-        doc.renameNode(node, "http://xml.python.org/ns", "xmlns:foo")
-    except xml.dom.NamespaceErr:
-        pass
-    else:
-        print("expected NamespaceErr")
+    def testGetAttrLength(self): pass
 
-    doc2 = parseString("<doc/>")
-    try:
-        doc2.renameNode(node, xml.dom.EMPTY_NAMESPACE, "foo")
-    except xml.dom.WrongDocumentErr:
-        pass
-    else:
-        print("expected WrongDocumentErr")
+    def testGetAttribute(self): pass
 
-def testRenameOther():
-    # We have to create a comment node explicitly since not all DOM
-    # builders used with minidom add comments to the DOM.
-    doc = xml.dom.minidom.getDOMImplementation().createDocument(
-        xml.dom.EMPTY_NAMESPACE, "e", None)
-    node = doc.createComment("comment")
-    try:
-        doc.renameNode(node, xml.dom.EMPTY_NAMESPACE, "foo")
-    except xml.dom.NotSupportedErr:
-        pass
-    else:
-        print("expected NotSupportedErr when renaming comment node")
-    doc.unlink()
-
-def checkWholeText(node, s):
-    t = node.wholeText
-    confirm(t == s, "looking for %s, found %s" % (repr(s), repr(t)))
-
-def testWholeText():
-    doc = parseString("<doc>a</doc>")
-    elem = doc.documentElement
-    text = elem.childNodes[0]
-    assert text.nodeType == Node.TEXT_NODE
-
-    checkWholeText(text, "a")
-    elem.appendChild(doc.createTextNode("b"))
-    checkWholeText(text, "ab")
-    elem.insertBefore(doc.createCDATASection("c"), text)
-    checkWholeText(text, "cab")
-
-    # make sure we don't cross other nodes
-    splitter = doc.createComment("comment")
-    elem.appendChild(splitter)
-    text2 = doc.createTextNode("d")
-    elem.appendChild(text2)
-    checkWholeText(text, "cab")
-    checkWholeText(text2, "d")
-
-    x = doc.createElement("x")
-    elem.replaceChild(x, splitter)
-    splitter = x
-    checkWholeText(text, "cab")
-    checkWholeText(text2, "d")
-
-    x = doc.createProcessingInstruction("y", "z")
-    elem.replaceChild(x, splitter)
-    splitter = x
-    checkWholeText(text, "cab")
-    checkWholeText(text2, "d")
-
-    elem.removeChild(splitter)
-    checkWholeText(text, "cabd")
-    checkWholeText(text2, "cabd")
-
-def testPatch1094164 ():
-    doc = parseString("<doc><e/></doc>")
-    elem = doc.documentElement
-    e = elem.firstChild
-    confirm(e.parentNode is elem, "Before replaceChild()")
-    # Check that replacing a child with itself leaves the tree unchanged
-    elem.replaceChild(e, e)
-    confirm(e.parentNode is elem, "After replaceChild()")
+    def testGetAttributeNS(self): pass
 
+    def testGetAttributeNode(self): pass
+
+    def testGetElementsByTagNameNS(self):
+        d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
+        <minidom:myelem/>
+        </foo>"""
+        dom = parseString(d)
+        elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom",
+                                           "myelem")
+        self.confirm(len(elems) == 1
+                and elems[0].namespaceURI == "http://pyxml.sf.net/minidom"
+                and elems[0].localName == "myelem"
+                and elems[0].prefix == "minidom"
+                and elems[0].tagName == "minidom:myelem"
+                and elems[0].nodeName == "minidom:myelem")
+        dom.unlink()
+
+    def get_empty_nodelist_from_elements_by_tagName_ns_helper(self, doc, nsuri,
+                                                              lname):
+        nodelist = doc.getElementsByTagNameNS(nsuri, lname)
+        self.confirm(len(nodelist) == 0)
+
+    def testGetEmptyNodeListFromElementsByTagNameNS(self):
+        doc = parseString('<doc/>')
+        self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
+            doc, 'http://xml.python.org/namespaces/a', 'localname')
+        self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
+            doc, '*', 'splat')
+        self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
+            doc, 'http://xml.python.org/namespaces/a', '*')
+
+        doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>')
+        self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
+            doc, "http://xml.python.org/splat", "not-there")
+        self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
+            doc, "*", "not-there")
+        self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
+            doc, "http://somewhere.else.net/not-there", "e")
+
+    def testElementReprAndStr(self):
+        dom = Document()
+        el = dom.appendChild(dom.createElement("abc"))
+        string1 = repr(el)
+        string2 = str(el)
+        self.confirm(string1 == string2)
+        dom.unlink()
+
+    def testElementReprAndStrUnicode(self):
+        dom = Document()
+        el = dom.appendChild(dom.createElement(u"abc"))
+        string1 = repr(el)
+        string2 = str(el)
+        self.confirm(string1 == string2)
+        dom.unlink()
+
+    def testElementReprAndStrUnicodeNS(self):
+        dom = Document()
+        el = dom.appendChild(
+            dom.createElementNS(u"http://www.slashdot.org", u"slash:abc"))
+        string1 = repr(el)
+        string2 = str(el)
+        self.confirm(string1 == string2)
+        self.confirm(string1.find("slash:abc") != -1)
+        dom.unlink()
+
+    def testAttributeRepr(self):
+        dom = Document()
+        el = dom.appendChild(dom.createElement(u"abc"))
+        node = el.setAttribute("abc", "def")
+        self.confirm(str(node) == repr(node))
+        dom.unlink()
+
+    def testTextNodeRepr(self): pass
+
+    def testWriteXML(self):
+        str = '<?xml version="1.0" ?><a b="c"/>'
+        dom = parseString(str)
+        domstr = dom.toxml()
+        dom.unlink()
+        self.confirm(str == domstr)
+
+    def testAltNewline(self):
+        str = '<?xml version="1.0" ?>\n<a b="c"/>\n'
+        dom = parseString(str)
+        domstr = dom.toprettyxml(newl="\r\n")
+        dom.unlink()
+        self.confirm(domstr == str.replace("\n", "\r\n"))
+
+    def testProcessingInstruction(self):
+        dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
+        pi = dom.documentElement.firstChild
+        self.confirm(pi.target == "mypi"
+                and pi.data == "data \t\n "
+                and pi.nodeName == "mypi"
+                and pi.nodeType == Node.PROCESSING_INSTRUCTION_NODE
+                and pi.attributes is None
+                and not pi.hasChildNodes()
+                and len(pi.childNodes) == 0
+                and pi.firstChild is None
+                and pi.lastChild is None
+                and pi.localName is None
+                and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE)
+
+    def testProcessingInstructionRepr(self): pass
+
+    def testTextRepr(self): pass
+
+    def testWriteText(self): pass
+
+    def testDocumentElement(self): pass
+
+    def testTooManyDocumentElements(self):
+        doc = parseString("<doc/>")
+        elem = doc.createElement("extra")
+        # Should raise an exception when adding an extra document element.
+        self.assertRaises(xml.dom.HierarchyRequestErr, doc.appendChild, elem)
+        elem.unlink()
+        doc.unlink()
+
+    def testCreateElementNS(self): pass
+
+    def testCreateAttributeNS(self): pass
+
+    def testParse(self): pass
+
+    def testParseString(self): pass
+
+    def testComment(self): pass
+
+    def testAttrListItem(self): pass
+
+    def testAttrListItems(self): pass
+
+    def testAttrListItemNS(self): pass
+
+    def testAttrListKeys(self): pass
+
+    def testAttrListKeysNS(self): pass
+
+    def testRemoveNamedItem(self):
+        doc = parseString("<doc a=''/>")
+        e = doc.documentElement
+        attrs = e.attributes
+        a1 = e.getAttributeNode("a")
+        a2 = attrs.removeNamedItem("a")
+        self.confirm(a1.isSameNode(a2))
+        self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItem, "a")
+
+    def testRemoveNamedItemNS(self):
+        doc = parseString("<doc xmlns:a='http://xml.python.org/' a:b=''/>")
+        e = doc.documentElement
+        attrs = e.attributes
+        a1 = e.getAttributeNodeNS("http://xml.python.org/", "b")
+        a2 = attrs.removeNamedItemNS("http://xml.python.org/", "b")
+        self.confirm(a1.isSameNode(a2))
+        self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS,
+                          "http://xml.python.org/", "b")
+
+    def testAttrListValues(self): pass
+
+    def testAttrListLength(self): pass
+
+    def testAttrList__getitem__(self): pass
+
+    def testAttrList__setitem__(self): pass
+
+    def testSetAttrValueandNodeValue(self): pass
+
+    def testParseElement(self): pass
+
+    def testParseAttributes(self): pass
+
+    def testParseElementNamespaces(self): pass
+
+    def testParseAttributeNamespaces(self): pass
+
+    def testParseProcessingInstructions(self): pass
+
+    def testChildNodes(self): pass
+
+    def testFirstChild(self): pass
+
+    def testHasChildNodes(self): pass
+
+    def _testCloneElementCopiesAttributes(self, e1, e2, test):
+        attrs1 = e1.attributes
+        attrs2 = e2.attributes
+        keys1 = list(attrs1.keys())
+        keys2 = list(attrs2.keys())
+        keys1.sort()
+        keys2.sort()
+        self.confirm(keys1 == keys2, "clone of element has same attribute keys")
+        for i in range(len(keys1)):
+            a1 = attrs1.item(i)
+            a2 = attrs2.item(i)
+            self.confirm(a1 is not a2
+                    and a1.value == a2.value
+                    and a1.nodeValue == a2.nodeValue
+                    and a1.namespaceURI == a2.namespaceURI
+                    and a1.localName == a2.localName
+                    , "clone of attribute node has proper attribute values")
+            self.confirm(a2.ownerElement is e2,
+                    "clone of attribute node correctly owned")
+
+    def _setupCloneElement(self, deep):
+        dom = parseString("<doc attr='value'><foo/></doc>")
+        root = dom.documentElement
+        clone = root.cloneNode(deep)
+        self._testCloneElementCopiesAttributes(
+            root, clone, "testCloneElement" + (deep and "Deep" or "Shallow"))
+        # mutilate the original so shared data is detected
+        root.tagName = root.nodeName = "MODIFIED"
+        root.setAttribute("attr", "NEW VALUE")
+        root.setAttribute("added", "VALUE")
+        return dom, clone
+
+    def testCloneElementShallow(self):
+        dom, clone = self._setupCloneElement(0)
+        self.confirm(len(clone.childNodes) == 0
+                and clone.childNodes.length == 0
+                and clone.parentNode is None
+                and clone.toxml() == '<doc attr="value"/>'
+                , "testCloneElementShallow")
+        dom.unlink()
+
+    def testCloneElementDeep(self):
+        dom, clone = self._setupCloneElement(1)
+        self.confirm(len(clone.childNodes) == 1
+                and clone.childNodes.length == 1
+                and clone.parentNode is None
+                and clone.toxml() == '<doc attr="value"><foo/></doc>'
+                , "testCloneElementDeep")
+        dom.unlink()
+
+    def testCloneDocumentShallow(self):
+        doc = parseString("<?xml version='1.0'?>\n"
+                    "<!-- comment -->"
+                    "<!DOCTYPE doc [\n"
+                    "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
+                    "]>\n"
+                    "<doc attr='value'/>")
+        doc2 = doc.cloneNode(0)
+        self.confirm(doc2 is None,
+                "testCloneDocumentShallow:"
+                " shallow cloning of documents makes no sense!")
+
+    def testCloneDocumentDeep(self):
+        doc = parseString("<?xml version='1.0'?>\n"
+                    "<!-- comment -->"
+                    "<!DOCTYPE doc [\n"
+                    "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
+                    "]>\n"
+                    "<doc attr='value'/>")
+        doc2 = doc.cloneNode(1)
+        self.confirm(not (doc.isSameNode(doc2) or doc2.isSameNode(doc)),
+                "testCloneDocumentDeep: document objects not distinct")
+        self.confirm(len(doc.childNodes) == len(doc2.childNodes),
+                "testCloneDocumentDeep: wrong number of Document children")
+        self.confirm(doc2.documentElement.nodeType == Node.ELEMENT_NODE,
+                "testCloneDocumentDeep: documentElement not an ELEMENT_NODE")
+        self.confirm(doc2.documentElement.ownerDocument.isSameNode(doc2),
+            "testCloneDocumentDeep: documentElement owner is not new document")
+        self.confirm(not doc.documentElement.isSameNode(doc2.documentElement),
+                "testCloneDocumentDeep: documentElement should not be shared")
+        if doc.doctype is not None:
+            # check the doctype iff the original DOM maintained it
+            self.confirm(doc2.doctype.nodeType == Node.DOCUMENT_TYPE_NODE,
+                    "testCloneDocumentDeep: doctype not a DOCUMENT_TYPE_NODE")
+            self.confirm(doc2.doctype.ownerDocument.isSameNode(doc2))
+            self.confirm(not doc.doctype.isSameNode(doc2.doctype))
+
+    def testCloneDocumentTypeDeepOk(self):
+        doctype = create_nonempty_doctype()
+        clone = doctype.cloneNode(1)
+        self.confirm(clone is not None
+                and clone.nodeName == doctype.nodeName
+                and clone.name == doctype.name
+                and clone.publicId == doctype.publicId
+                and clone.systemId == doctype.systemId
+                and len(clone.entities) == len(doctype.entities)
+                and clone.entities.item(len(clone.entities)) is None
+                and len(clone.notations) == len(doctype.notations)
+                and clone.notations.item(len(clone.notations)) is None
+                and len(clone.childNodes) == 0)
+        for i in range(len(doctype.entities)):
+            se = doctype.entities.item(i)
+            ce = clone.entities.item(i)
+            self.confirm((not se.isSameNode(ce))
+                    and (not ce.isSameNode(se))
+                    and ce.nodeName == se.nodeName
+                    and ce.notationName == se.notationName
+                    and ce.publicId == se.publicId
+                    and ce.systemId == se.systemId
+                    and ce.encoding == se.encoding
+                    and ce.actualEncoding == se.actualEncoding
+                    and ce.version == se.version)
+        for i in range(len(doctype.notations)):
+            sn = doctype.notations.item(i)
+            cn = clone.notations.item(i)
+            self.confirm((not sn.isSameNode(cn))
+                    and (not cn.isSameNode(sn))
+                    and cn.nodeName == sn.nodeName
+                    and cn.publicId == sn.publicId
+                    and cn.systemId == sn.systemId)
+
+    def testCloneDocumentTypeDeepNotOk(self):
+        doc = create_doc_with_doctype()
+        clone = doc.doctype.cloneNode(1)
+        self.confirm(clone is None, "testCloneDocumentTypeDeepNotOk")
+
+    def testCloneDocumentTypeShallowOk(self):
+        doctype = create_nonempty_doctype()
+        clone = doctype.cloneNode(0)
+        self.confirm(clone is not None
+                and clone.nodeName == doctype.nodeName
+                and clone.name == doctype.name
+                and clone.publicId == doctype.publicId
+                and clone.systemId == doctype.systemId
+                and len(clone.entities) == 0
+                and clone.entities.item(0) is None
+                and len(clone.notations) == 0
+                and clone.notations.item(0) is None
+                and len(clone.childNodes) == 0)
+
+    def testCloneDocumentTypeShallowNotOk(self):
+        doc = create_doc_with_doctype()
+        clone = doc.doctype.cloneNode(0)
+        self.confirm(clone is None, "testCloneDocumentTypeShallowNotOk")
+
+    def check_import_document(self, deep, testName):
+        doc1 = parseString("<doc/>")
+        doc2 = parseString("<doc/>")
+        self.assertRaises(xml.dom.NotSupportedErr, doc1.importNode, doc2, deep)
+
+    def testImportDocumentShallow(self):
+        self.check_import_document(0, "testImportDocumentShallow")
+
+    def testImportDocumentDeep(self):
+        self.check_import_document(1, "testImportDocumentDeep")
+
+    def testImportDocumentTypeShallow(self):
+        src = create_doc_with_doctype()
+        target = create_doc_without_doctype()
+        self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
+                          src.doctype, 0)
+
+    def testImportDocumentTypeDeep(self):
+        src = create_doc_with_doctype()
+        target = create_doc_without_doctype()
+        self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
+                          src.doctype, 1)
+
+    # Testing attribute clones uses a helper, and should always be deep,
+    # even if the argument to cloneNode is false.
+    def check_clone_attribute(self, deep, testName):
+        doc = parseString("<doc attr='value'/>")
+        attr = doc.documentElement.getAttributeNode("attr")
+        self.failIfEqual(attr, None)
+        clone = attr.cloneNode(deep)
+        self.confirm(not clone.isSameNode(attr))
+        self.confirm(not attr.isSameNode(clone))
+        self.confirm(clone.ownerElement is None,
+                testName + ": ownerElement should be None")
+        self.confirm(clone.ownerDocument.isSameNode(attr.ownerDocument),
+                testName + ": ownerDocument does not match")
+        self.confirm(clone.specified,
+                testName + ": cloned attribute must have specified == True")
+
+    def testCloneAttributeShallow(self):
+        self.check_clone_attribute(0, "testCloneAttributeShallow")
+
+    def testCloneAttributeDeep(self):
+        self.check_clone_attribute(1, "testCloneAttributeDeep")
+
+    def check_clone_pi(self, deep, testName):
+        doc = parseString("<?target data?><doc/>")
+        pi = doc.firstChild
+        self.assertEquals(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE)
+        clone = pi.cloneNode(deep)
+        self.confirm(clone.target == pi.target
+                and clone.data == pi.data)
+
+    def testClonePIShallow(self):
+        self.check_clone_pi(0, "testClonePIShallow")
+
+    def testClonePIDeep(self):
+        self.check_clone_pi(1, "testClonePIDeep")
+
+    def testNormalize(self):
+        doc = parseString("<doc/>")
+        root = doc.documentElement
+        root.appendChild(doc.createTextNode("first"))
+        root.appendChild(doc.createTextNode("second"))
+        self.confirm(len(root.childNodes) == 2
+                and root.childNodes.length == 2,
+                "testNormalize -- preparation")
+        doc.normalize()
+        self.confirm(len(root.childNodes) == 1
+                and root.childNodes.length == 1
+                and root.firstChild is root.lastChild
+                and root.firstChild.data == "firstsecond"
+                , "testNormalize -- result")
+        doc.unlink()
+
+        doc = parseString("<doc/>")
+        root = doc.documentElement
+        root.appendChild(doc.createTextNode(""))
+        doc.normalize()
+        self.confirm(len(root.childNodes) == 0
+                and root.childNodes.length == 0,
+                "testNormalize -- single empty node removed")
+        doc.unlink()
+
+    def testSiblings(self):
+        doc = parseString("<doc><?pi?>text?<elm/></doc>")
+        root = doc.documentElement
+        (pi, text, elm) = root.childNodes
+
+        self.confirm(pi.nextSibling is text and
+                pi.previousSibling is None and
+                text.nextSibling is elm and
+                text.previousSibling is pi and
+                elm.nextSibling is None and
+                elm.previousSibling is text, "testSiblings")
+
+        doc.unlink()
+
+    def testParents(self):
+        doc = parseString(
+            "<doc><elm1><elm2/><elm2><elm3/></elm2></elm1></doc>")
+        root = doc.documentElement
+        elm1 = root.childNodes[0]
+        (elm2a, elm2b) = elm1.childNodes
+        elm3 = elm2b.childNodes[0]
+
+        self.confirm(root.parentNode is doc and
+                elm1.parentNode is root and
+                elm2a.parentNode is elm1 and
+                elm2b.parentNode is elm1 and
+                elm3.parentNode is elm2b, "testParents")
+        doc.unlink()
+
+    def testNodeListItem(self):
+        doc = parseString("<doc><e/><e/></doc>")
+        children = doc.childNodes
+        docelem = children[0]
+        self.confirm(children[0] is children.item(0)
+                and children.item(1) is None
+                and docelem.childNodes.item(0) is docelem.childNodes[0]
+                and docelem.childNodes.item(1) is docelem.childNodes[1]
+                and docelem.childNodes.item(0).childNodes.item(0) is None,
+                "test NodeList.item()")
+        doc.unlink()
+
+    def testSAX2DOM(self):
+        from xml.dom import pulldom
+
+        sax2dom = pulldom.SAX2DOM()
+        sax2dom.startDocument()
+        sax2dom.startElement("doc", {})
+        sax2dom.characters("text")
+        sax2dom.startElement("subelm", {})
+        sax2dom.characters("text")
+        sax2dom.endElement("subelm")
+        sax2dom.characters("text")
+        sax2dom.endElement("doc")
+        sax2dom.endDocument()
+
+        doc = sax2dom.document
+        root = doc.documentElement
+        (text1, elm1, text2) = root.childNodes
+        text3 = elm1.childNodes[0]
+
+        self.confirm(text1.previousSibling is None and
+                text1.nextSibling is elm1 and
+                elm1.previousSibling is text1 and
+                elm1.nextSibling is text2 and
+                text2.previousSibling is elm1 and
+                text2.nextSibling is None and
+                text3.previousSibling is None and
+                text3.nextSibling is None, "testSAX2DOM - siblings")
+
+        self.confirm(root.parentNode is doc and
+                text1.parentNode is root and
+                elm1.parentNode is root and
+                text2.parentNode is root and
+                text3.parentNode is elm1, "testSAX2DOM - parents")
+        doc.unlink()
+
+    def testEncodings(self):
+        doc = parseString('<foo>&#x20ac;</foo>')
+        self.confirm(doc.toxml() == u'<?xml version="1.0" ?><foo>\u20ac</foo>'
+                and doc.toxml('utf-8') ==
+                '<?xml version="1.0" encoding="utf-8"?><foo>\xe2\x82\xac</foo>'
+                and doc.toxml('iso-8859-15') ==
+                '<?xml version="1.0" encoding="iso-8859-15"?><foo>\xa4</foo>',
+                "testEncodings - encoding EURO SIGN")
+
+        # Verify that character decoding errors throw exceptions instead
+        # of crashing
+        self.assertRaises(UnicodeDecodeError, parseString,
+                '<fran\xe7ais>Comment \xe7a va ? Tr\xe8s bien ?</fran\xe7ais>')
+
+        doc.unlink()
+
+    class UserDataHandler:
+        called = 0
+        def handle(self, operation, key, data, src, dst):
+            dst.setUserData(key, data + 1, self)
+            src.setUserData(key, None, None)
+            self.called = 1
+
+    def testUserData(self):
+        dom = Document()
+        n = dom.createElement('e')
+        self.confirm(n.getUserData("foo") is None)
+        n.setUserData("foo", None, None)
+        self.confirm(n.getUserData("foo") is None)
+        n.setUserData("foo", 12, 12)
+        n.setUserData("bar", 13, 13)
+        self.confirm(n.getUserData("foo") == 12)
+        self.confirm(n.getUserData("bar") == 13)
+        n.setUserData("foo", None, None)
+        self.confirm(n.getUserData("foo") is None)
+        self.confirm(n.getUserData("bar") == 13)
+
+        handler = self.UserDataHandler()
+        n.setUserData("bar", 12, handler)
+        c = n.cloneNode(1)
+        self.confirm(handler.called
+                and n.getUserData("bar") is None
+                and c.getUserData("bar") == 13)
+        n.unlink()
+        c.unlink()
+        dom.unlink()
+
+    def checkRenameNodeSharedConstraints(self, doc, node):
+        # Make sure illegal NS usage is detected:
+        self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, node,
+                          "http://xml.python.org/ns", "xmlns:foo")
+        doc2 = parseString("<doc/>")
+        self.assertRaises(xml.dom.WrongDocumentErr, doc2.renameNode, node,
+                          xml.dom.EMPTY_NAMESPACE, "foo")
 
+    def testRenameAttribute(self):
+        doc = parseString("<doc a='v'/>")
+        elem = doc.documentElement
+        attrmap = elem.attributes
+        attr = elem.attributes['a']
 
-def testReplaceWholeText():
-    def setup():
-        doc = parseString("<doc>a<e/>d</doc>")
+        # Simple renaming
+        attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "b")
+        self.confirm(attr.name == "b"
+                and attr.nodeName == "b"
+                and attr.localName is None
+                and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
+                and attr.prefix is None
+                and attr.value == "v"
+                and elem.getAttributeNode("a") is None
+                and elem.getAttributeNode("b").isSameNode(attr)
+                and attrmap["b"].isSameNode(attr)
+                and attr.ownerDocument.isSameNode(doc)
+                and attr.ownerElement.isSameNode(elem))
+
+        # Rename to have a namespace, no prefix
+        attr = doc.renameNode(attr, "http://xml.python.org/ns", "c")
+        self.confirm(attr.name == "c"
+                and attr.nodeName == "c"
+                and attr.localName == "c"
+                and attr.namespaceURI == "http://xml.python.org/ns"
+                and attr.prefix is None
+                and attr.value == "v"
+                and elem.getAttributeNode("a") is None
+                and elem.getAttributeNode("b") is None
+                and elem.getAttributeNode("c").isSameNode(attr)
+                and elem.getAttributeNodeNS(
+                    "http://xml.python.org/ns", "c").isSameNode(attr)
+                and attrmap["c"].isSameNode(attr)
+                and attrmap[("http://xml.python.org/ns", "c")].isSameNode(attr))
+
+        # Rename to have a namespace, with prefix
+        attr = doc.renameNode(attr, "http://xml.python.org/ns2", "p:d")
+        self.confirm(attr.name == "p:d"
+                and attr.nodeName == "p:d"
+                and attr.localName == "d"
+                and attr.namespaceURI == "http://xml.python.org/ns2"
+                and attr.prefix == "p"
+                and attr.value == "v"
+                and elem.getAttributeNode("a") is None
+                and elem.getAttributeNode("b") is None
+                and elem.getAttributeNode("c") is None
+                and elem.getAttributeNodeNS(
+                    "http://xml.python.org/ns", "c") is None
+                and elem.getAttributeNode("p:d").isSameNode(attr)
+                and elem.getAttributeNodeNS(
+                    "http://xml.python.org/ns2", "d").isSameNode(attr)
+                and attrmap["p:d"].isSameNode(attr)
+                and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr))
+
+        # Rename back to a simple non-NS node
+        attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "e")
+        self.confirm(attr.name == "e"
+                and attr.nodeName == "e"
+                and attr.localName is None
+                and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
+                and attr.prefix is None
+                and attr.value == "v"
+                and elem.getAttributeNode("a") is None
+                and elem.getAttributeNode("b") is None
+                and elem.getAttributeNode("c") is None
+                and elem.getAttributeNode("p:d") is None
+                and elem.getAttributeNodeNS(
+                    "http://xml.python.org/ns", "c") is None
+                and elem.getAttributeNode("e").isSameNode(attr)
+                and attrmap["e"].isSameNode(attr))
+
+        self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, attr,
+                          "http://xml.python.org/ns", "xmlns")
+        self.checkRenameNodeSharedConstraints(doc, attr)
+        doc.unlink()
+
+    def testRenameElement(self):
+        doc = parseString("<doc/>")
+        elem = doc.documentElement
+
+        # Simple renaming
+        elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "a")
+        self.confirm(elem.tagName == "a"
+                and elem.nodeName == "a"
+                and elem.localName is None
+                and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
+                and elem.prefix is None
+                and elem.ownerDocument.isSameNode(doc))
+
+        # Rename to have a namespace, no prefix
+        elem = doc.renameNode(elem, "http://xml.python.org/ns", "b")
+        self.confirm(elem.tagName == "b"
+                and elem.nodeName == "b"
+                and elem.localName == "b"
+                and elem.namespaceURI == "http://xml.python.org/ns"
+                and elem.prefix is None
+                and elem.ownerDocument.isSameNode(doc))
+
+        # Rename to have a namespace, with prefix
+        elem = doc.renameNode(elem, "http://xml.python.org/ns2", "p:c")
+        self.confirm(elem.tagName == "p:c"
+                and elem.nodeName == "p:c"
+                and elem.localName == "c"
+                and elem.namespaceURI == "http://xml.python.org/ns2"
+                and elem.prefix == "p"
+                and elem.ownerDocument.isSameNode(doc))
+
+        # Rename back to a simple non-NS node
+        elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "d")
+        self.confirm(elem.tagName == "d"
+                and elem.nodeName == "d"
+                and elem.localName is None
+                and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
+                and elem.prefix is None
+                and elem.ownerDocument.isSameNode(doc))
+
+        self.checkRenameNodeSharedConstraints(doc, elem)
+        doc.unlink()
+
+    def testRenameOther(self):
+        # We have to create a comment node explicitly since not all DOM
+        # builders used with minidom add comments to the DOM.
+        doc = xml.dom.minidom.getDOMImplementation().createDocument(
+            xml.dom.EMPTY_NAMESPACE, "e", None)
+        node = doc.createComment("comment")
+        self.assertRaises(xml.dom.NotSupportedErr, doc.renameNode, node,
+                          xml.dom.EMPTY_NAMESPACE, "foo")
+        doc.unlink()
+
+    def testWholeText(self):
+        doc = parseString("<doc>a</doc>")
+        elem = doc.documentElement
+        text = elem.childNodes[0]
+        self.assertEquals(text.nodeType, Node.TEXT_NODE)
+
+        self.checkWholeText(text, "a")
+        elem.appendChild(doc.createTextNode("b"))
+        self.checkWholeText(text, "ab")
+        elem.insertBefore(doc.createCDATASection("c"), text)
+        self.checkWholeText(text, "cab")
+
+        # make sure we don't cross other nodes
+        splitter = doc.createComment("comment")
+        elem.appendChild(splitter)
+        text2 = doc.createTextNode("d")
+        elem.appendChild(text2)
+        self.checkWholeText(text, "cab")
+        self.checkWholeText(text2, "d")
+
+        x = doc.createElement("x")
+        elem.replaceChild(x, splitter)
+        splitter = x
+        self.checkWholeText(text, "cab")
+        self.checkWholeText(text2, "d")
+
+        x = doc.createProcessingInstruction("y", "z")
+        elem.replaceChild(x, splitter)
+        splitter = x
+        self.checkWholeText(text, "cab")
+        self.checkWholeText(text2, "d")
+
+        elem.removeChild(splitter)
+        self.checkWholeText(text, "cabd")
+        self.checkWholeText(text2, "cabd")
+
+    def testPatch1094164(self):
+        doc = parseString("<doc><e/></doc>")
         elem = doc.documentElement
-        text1 = elem.firstChild
-        text2 = elem.lastChild
-        splitter = text1.nextSibling
-        elem.insertBefore(doc.createTextNode("b"), splitter)
-        elem.insertBefore(doc.createCDATASection("c"), text1)
-        return doc, elem, text1, splitter, text2
-
-    doc, elem, text1, splitter, text2 = setup()
-    text = text1.replaceWholeText("new content")
-    checkWholeText(text, "new content")
-    checkWholeText(text2, "d")
-    confirm(len(elem.childNodes) == 3)
-
-    doc, elem, text1, splitter, text2 = setup()
-    text = text2.replaceWholeText("new content")
-    checkWholeText(text, "new content")
-    checkWholeText(text1, "cab")
-    confirm(len(elem.childNodes) == 5)
-
-    doc, elem, text1, splitter, text2 = setup()
-    text = text1.replaceWholeText("")
-    checkWholeText(text2, "d")
-    confirm(text is None
-            and len(elem.childNodes) == 2)
-
-def testSchemaType():
-    doc = parseString(
-        "<!DOCTYPE doc [\n"
-        "  <!ENTITY e1 SYSTEM 'http://xml.python.org/e1'>\n"
-        "  <!ENTITY e2 SYSTEM 'http://xml.python.org/e2'>\n"
-        "  <!ATTLIST doc id   ID       #IMPLIED \n"
-        "                ref  IDREF    #IMPLIED \n"
-        "                refs IDREFS   #IMPLIED \n"
-        "                enum (a|b)    #IMPLIED \n"
-        "                ent  ENTITY   #IMPLIED \n"
-        "                ents ENTITIES #IMPLIED \n"
-        "                nm   NMTOKEN  #IMPLIED \n"
-        "                nms  NMTOKENS #IMPLIED \n"
-        "                text CDATA    #IMPLIED \n"
-        "    >\n"
-        "]><doc id='name' notid='name' text='splat!' enum='b'"
-        "       ref='name' refs='name name' ent='e1' ents='e1 e2'"
-        "       nm='123' nms='123 abc' />")
-    elem = doc.documentElement
-    # We don't want to rely on any specific loader at this point, so
-    # just make sure we can get to all the names, and that the
-    # DTD-based namespace is right.  The names can vary by loader
-    # since each supports a different level of DTD information.
-    t = elem.schemaType
-    confirm(t.name is None
-            and t.namespace == xml.dom.EMPTY_NAMESPACE)
-    names = "id notid text enum ref refs ent ents nm nms".split()
-    for name in names:
-        a = elem.getAttributeNode(name)
-        t = a.schemaType
-        confirm(hasattr(t, "name")
+        e = elem.firstChild
+        self.confirm(e.parentNode is elem, "Before replaceChild()")
+        # Check that replacing a child with itself leaves the tree unchanged
+        elem.replaceChild(e, e)
+        self.confirm(e.parentNode is elem, "After replaceChild()")
+
+    def testReplaceWholeText(self):
+        def setup():
+            doc = parseString("<doc>a<e/>d</doc>")
+            elem = doc.documentElement
+            text1 = elem.firstChild
+            text2 = elem.lastChild
+            splitter = text1.nextSibling
+            elem.insertBefore(doc.createTextNode("b"), splitter)
+            elem.insertBefore(doc.createCDATASection("c"), text1)
+            return doc, elem, text1, splitter, text2
+
+        doc, elem, text1, splitter, text2 = setup()
+        text = text1.replaceWholeText("new content")
+        self.checkWholeText(text, "new content")
+        self.checkWholeText(text2, "d")
+        self.confirm(len(elem.childNodes) == 3)
+
+        doc, elem, text1, splitter, text2 = setup()
+        text = text2.replaceWholeText("new content")
+        self.checkWholeText(text, "new content")
+        self.checkWholeText(text1, "cab")
+        self.confirm(len(elem.childNodes) == 5)
+
+        doc, elem, text1, splitter, text2 = setup()
+        text = text1.replaceWholeText("")
+        self.checkWholeText(text2, "d")
+        self.confirm(text is None
+                and len(elem.childNodes) == 2)
+
+    def testSchemaType(self):
+        doc = parseString(
+            "<!DOCTYPE doc [\n"
+            "  <!ENTITY e1 SYSTEM 'http://xml.python.org/e1'>\n"
+            "  <!ENTITY e2 SYSTEM 'http://xml.python.org/e2'>\n"
+            "  <!ATTLIST doc id   ID       #IMPLIED \n"
+            "                ref  IDREF    #IMPLIED \n"
+            "                refs IDREFS   #IMPLIED \n"
+            "                enum (a|b)    #IMPLIED \n"
+            "                ent  ENTITY   #IMPLIED \n"
+            "                ents ENTITIES #IMPLIED \n"
+            "                nm   NMTOKEN  #IMPLIED \n"
+            "                nms  NMTOKENS #IMPLIED \n"
+            "                text CDATA    #IMPLIED \n"
+            "    >\n"
+            "]><doc id='name' notid='name' text='splat!' enum='b'"
+            "       ref='name' refs='name name' ent='e1' ents='e1 e2'"
+            "       nm='123' nms='123 abc' />")
+        elem = doc.documentElement
+        # We don't want to rely on any specific loader at this point, so
+        # just make sure we can get to all the names, and that the
+        # DTD-based namespace is right.  The names can vary by loader
+        # since each supports a different level of DTD information.
+        t = elem.schemaType
+        self.confirm(t.name is None
                 and t.namespace == xml.dom.EMPTY_NAMESPACE)
+        names = "id notid text enum ref refs ent ents nm nms".split()
+        for name in names:
+            a = elem.getAttributeNode(name)
+            t = a.schemaType
+            self.confirm(hasattr(t, "name")
+                    and t.namespace == xml.dom.EMPTY_NAMESPACE)
+
+    def testSetIdAttribute(self):
+        doc = parseString("<doc a1='v' a2='w'/>")
+        e = doc.documentElement
+        a1 = e.getAttributeNode("a1")
+        a2 = e.getAttributeNode("a2")
+        self.confirm(doc.getElementById("v") is None
+                and not a1.isId
+                and not a2.isId)
+        e.setIdAttribute("a1")
+        self.confirm(e.isSameNode(doc.getElementById("v"))
+                and a1.isId
+                and not a2.isId)
+        e.setIdAttribute("a2")
+        self.confirm(e.isSameNode(doc.getElementById("v"))
+                and e.isSameNode(doc.getElementById("w"))
+                and a1.isId
+                and a2.isId)
+        # replace the a1 node; the new node should *not* be an ID
+        a3 = doc.createAttribute("a1")
+        a3.value = "v"
+        e.setAttributeNode(a3)
+        self.confirm(doc.getElementById("v") is None
+                and e.isSameNode(doc.getElementById("w"))
+                and not a1.isId
+                and a2.isId
+                and not a3.isId)
+        # renaming an attribute should not affect its ID-ness:
+        doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
+        self.confirm(e.isSameNode(doc.getElementById("w"))
+                and a2.isId)
+
+    def testSetIdAttributeNS(self):
+        NS1 = "http://xml.python.org/ns1"
+        NS2 = "http://xml.python.org/ns2"
+        doc = parseString("<doc"
+                          " xmlns:ns1='" + NS1 + "'"
+                          " xmlns:ns2='" + NS2 + "'"
+                          " ns1:a1='v' ns2:a2='w'/>")
+        e = doc.documentElement
+        a1 = e.getAttributeNodeNS(NS1, "a1")
+        a2 = e.getAttributeNodeNS(NS2, "a2")
+        self.confirm(doc.getElementById("v") is None
+                and not a1.isId
+                and not a2.isId)
+        e.setIdAttributeNS(NS1, "a1")
+        self.confirm(e.isSameNode(doc.getElementById("v"))
+                and a1.isId
+                and not a2.isId)
+        e.setIdAttributeNS(NS2, "a2")
+        self.confirm(e.isSameNode(doc.getElementById("v"))
+                and e.isSameNode(doc.getElementById("w"))
+                and a1.isId
+                and a2.isId)
+        # replace the a1 node; the new node should *not* be an ID
+        a3 = doc.createAttributeNS(NS1, "a1")
+        a3.value = "v"
+        e.setAttributeNode(a3)
+        self.confirm(e.isSameNode(doc.getElementById("w")))
+        self.confirm(not a1.isId)
+        self.confirm(a2.isId)
+        self.confirm(not a3.isId)
+        self.confirm(doc.getElementById("v") is None)
+        # renaming an attribute should not affect its ID-ness:
+        doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
+        self.confirm(e.isSameNode(doc.getElementById("w"))
+                and a2.isId)
+
+    def testSetIdAttributeNode(self):
+        NS1 = "http://xml.python.org/ns1"
+        NS2 = "http://xml.python.org/ns2"
+        doc = parseString("<doc"
+                          " xmlns:ns1='" + NS1 + "'"
+                          " xmlns:ns2='" + NS2 + "'"
+                          " ns1:a1='v' ns2:a2='w'/>")
+        e = doc.documentElement
+        a1 = e.getAttributeNodeNS(NS1, "a1")
+        a2 = e.getAttributeNodeNS(NS2, "a2")
+        self.confirm(doc.getElementById("v") is None
+                and not a1.isId
+                and not a2.isId)
+        e.setIdAttributeNode(a1)
+        self.confirm(e.isSameNode(doc.getElementById("v"))
+                and a1.isId
+                and not a2.isId)
+        e.setIdAttributeNode(a2)
+        self.confirm(e.isSameNode(doc.getElementById("v"))
+                and e.isSameNode(doc.getElementById("w"))
+                and a1.isId
+                and a2.isId)
+        # replace the a1 node; the new node should *not* be an ID
+        a3 = doc.createAttributeNS(NS1, "a1")
+        a3.value = "v"
+        e.setAttributeNode(a3)
+        self.confirm(e.isSameNode(doc.getElementById("w")))
+        self.confirm(not a1.isId)
+        self.confirm(a2.isId)
+        self.confirm(not a3.isId)
+        self.confirm(doc.getElementById("v") is None)
+        # renaming an attribute should not affect its ID-ness:
+        doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
+        self.confirm(e.isSameNode(doc.getElementById("w"))
+                and a2.isId)
+
+    def testPickledDocument(self):
+        doc = parseString("<?xml version='1.0' encoding='us-ascii'?>\n"
+                    "<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'"
+                    " 'http://xml.python.org/system' [\n"
+                    "  <!ELEMENT e EMPTY>\n"
+                    "  <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
+                    "]><doc attr='value'> text\n"
+                    "<?pi sample?> <!-- comment --> <e/> </doc>")
+        s = pickle.dumps(doc)
+        doc2 = pickle.loads(s)
+        stack = [(doc, doc2)]
+        while stack:
+            n1, n2 = stack.pop()
+            self.confirm(n1.nodeType == n2.nodeType
+                    and len(n1.childNodes) == len(n2.childNodes)
+                    and n1.nodeName == n2.nodeName
+                    and not n1.isSameNode(n2)
+                    and not n2.isSameNode(n1))
+            if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
+                len(n1.entities)
+                len(n2.entities)
+                len(n1.notations)
+                len(n2.notations)
+                self.confirm(len(n1.entities) == len(n2.entities)
+                        and len(n1.notations) == len(n2.notations))
+                for i in range(len(n1.notations)):
+                    no1 = n1.notations.item(i)
+                    no2 = n1.notations.item(i)
+                    self.confirm(no1.name == no2.name
+                            and no1.publicId == no2.publicId
+                            and no1.systemId == no2.systemId)
+                    statck.append((no1, no2))
+                for i in range(len(n1.entities)):
+                    e1 = n1.entities.item(i)
+                    e2 = n2.entities.item(i)
+                    self.confirm(e1.notationName == e2.notationName
+                            and e1.publicId == e2.publicId
+                            and e1.systemId == e2.systemId)
+                    stack.append((e1, e2))
+            if n1.nodeType != Node.DOCUMENT_NODE:
+                self.confirm(n1.ownerDocument.isSameNode(doc)
+                        and n2.ownerDocument.isSameNode(doc2))
+            for i in range(len(n1.childNodes)):
+                stack.append((n1.childNodes[i], n2.childNodes[i]))
 
-def testSetIdAttribute():
-    doc = parseString("<doc a1='v' a2='w'/>")
-    e = doc.documentElement
-    a1 = e.getAttributeNode("a1")
-    a2 = e.getAttributeNode("a2")
-    confirm(doc.getElementById("v") is None
-            and not a1.isId
-            and not a2.isId)
-    e.setIdAttribute("a1")
-    confirm(e.isSameNode(doc.getElementById("v"))
-            and a1.isId
-            and not a2.isId)
-    e.setIdAttribute("a2")
-    confirm(e.isSameNode(doc.getElementById("v"))
-            and e.isSameNode(doc.getElementById("w"))
-            and a1.isId
-            and a2.isId)
-    # replace the a1 node; the new node should *not* be an ID
-    a3 = doc.createAttribute("a1")
-    a3.value = "v"
-    e.setAttributeNode(a3)
-    confirm(doc.getElementById("v") is None
-            and e.isSameNode(doc.getElementById("w"))
-            and not a1.isId
-            and a2.isId
-            and not a3.isId)
-    # renaming an attribute should not affect its ID-ness:
-    doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
-    confirm(e.isSameNode(doc.getElementById("w"))
-            and a2.isId)
-
-def testSetIdAttributeNS():
-    NS1 = "http://xml.python.org/ns1"
-    NS2 = "http://xml.python.org/ns2"
-    doc = parseString("<doc"
-                      " xmlns:ns1='" + NS1 + "'"
-                      " xmlns:ns2='" + NS2 + "'"
-                      " ns1:a1='v' ns2:a2='w'/>")
-    e = doc.documentElement
-    a1 = e.getAttributeNodeNS(NS1, "a1")
-    a2 = e.getAttributeNodeNS(NS2, "a2")
-    confirm(doc.getElementById("v") is None
-            and not a1.isId
-            and not a2.isId)
-    e.setIdAttributeNS(NS1, "a1")
-    confirm(e.isSameNode(doc.getElementById("v"))
-            and a1.isId
-            and not a2.isId)
-    e.setIdAttributeNS(NS2, "a2")
-    confirm(e.isSameNode(doc.getElementById("v"))
-            and e.isSameNode(doc.getElementById("w"))
-            and a1.isId
-            and a2.isId)
-    # replace the a1 node; the new node should *not* be an ID
-    a3 = doc.createAttributeNS(NS1, "a1")
-    a3.value = "v"
-    e.setAttributeNode(a3)
-    confirm(e.isSameNode(doc.getElementById("w")))
-    confirm(not a1.isId)
-    confirm(a2.isId)
-    confirm(not a3.isId)
-    confirm(doc.getElementById("v") is None)
-    # renaming an attribute should not affect its ID-ness:
-    doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
-    confirm(e.isSameNode(doc.getElementById("w"))
-            and a2.isId)
-
-def testSetIdAttributeNode():
-    NS1 = "http://xml.python.org/ns1"
-    NS2 = "http://xml.python.org/ns2"
-    doc = parseString("<doc"
-                      " xmlns:ns1='" + NS1 + "'"
-                      " xmlns:ns2='" + NS2 + "'"
-                      " ns1:a1='v' ns2:a2='w'/>")
-    e = doc.documentElement
-    a1 = e.getAttributeNodeNS(NS1, "a1")
-    a2 = e.getAttributeNodeNS(NS2, "a2")
-    confirm(doc.getElementById("v") is None
-            and not a1.isId
-            and not a2.isId)
-    e.setIdAttributeNode(a1)
-    confirm(e.isSameNode(doc.getElementById("v"))
-            and a1.isId
-            and not a2.isId)
-    e.setIdAttributeNode(a2)
-    confirm(e.isSameNode(doc.getElementById("v"))
-            and e.isSameNode(doc.getElementById("w"))
-            and a1.isId
-            and a2.isId)
-    # replace the a1 node; the new node should *not* be an ID
-    a3 = doc.createAttributeNS(NS1, "a1")
-    a3.value = "v"
-    e.setAttributeNode(a3)
-    confirm(e.isSameNode(doc.getElementById("w")))
-    confirm(not a1.isId)
-    confirm(a2.isId)
-    confirm(not a3.isId)
-    confirm(doc.getElementById("v") is None)
-    # renaming an attribute should not affect its ID-ness:
-    doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
-    confirm(e.isSameNode(doc.getElementById("w"))
-            and a2.isId)
-
-def testPickledDocument():
-    doc = parseString("<?xml version='1.0' encoding='us-ascii'?>\n"
-                      "<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'"
-                      " 'http://xml.python.org/system' [\n"
-                      "  <!ELEMENT e EMPTY>\n"
-                      "  <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
-                      "]><doc attr='value'> text\n"
-                      "<?pi sample?> <!-- comment --> <e/> </doc>")
-    s = pickle.dumps(doc)
-    doc2 = pickle.loads(s)
-    stack = [(doc, doc2)]
-    while stack:
-        n1, n2 = stack.pop()
-        confirm(n1.nodeType == n2.nodeType
-                and len(n1.childNodes) == len(n2.childNodes)
-                and n1.nodeName == n2.nodeName
-                and not n1.isSameNode(n2)
-                and not n2.isSameNode(n1))
-        if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
-            len(n1.entities)
-            len(n2.entities)
-            len(n1.notations)
-            len(n2.notations)
-            confirm(len(n1.entities) == len(n2.entities)
-                    and len(n1.notations) == len(n2.notations))
-            for i in range(len(n1.notations)):
-                no1 = n1.notations.item(i)
-                no2 = n1.notations.item(i)
-                confirm(no1.name == no2.name
-                        and no1.publicId == no2.publicId
-                        and no1.systemId == no2.systemId)
-                statck.append((no1, no2))
-            for i in range(len(n1.entities)):
-                e1 = n1.entities.item(i)
-                e2 = n2.entities.item(i)
-                confirm(e1.notationName == e2.notationName
-                        and e1.publicId == e2.publicId
-                        and e1.systemId == e2.systemId)
-                stack.append((e1, e2))
-        if n1.nodeType != Node.DOCUMENT_NODE:
-            confirm(n1.ownerDocument.isSameNode(doc)
-                    and n2.ownerDocument.isSameNode(doc2))
-        for i in range(len(n1.childNodes)):
-            stack.append((n1.childNodes[i], n2.childNodes[i]))
-
-
-# --- MAIN PROGRAM
-
-names = sorted(globals().keys())
-
-failed = []
-
-try:
-    Node.allnodes
-except AttributeError:
-    # We don't actually have the minidom from the standard library,
-    # but are picking up the PyXML version from site-packages.
-    def check_allnodes():
-        pass
-else:
-    def check_allnodes():
-        confirm(len(Node.allnodes) == 0,
-                "assertion: len(Node.allnodes) == 0")
-        if len(Node.allnodes):
-            print("Garbage left over:")
-            if verbose:
-                print(Node.allnodes.items()[0:10])
-            else:
-                # Don't print specific nodes if repeatable results
-                # are needed
-                print(len(Node.allnodes))
-        Node.allnodes = {}
-
-for name in names:
-    if name.startswith("test"):
-        func = globals()[name]
-        try:
-            func()
-            check_allnodes()
-        except:
-            failed.append(name)
-            print("Test Failed: ", name)
-            sys.stdout.flush()
-            traceback.print_exception(*sys.exc_info())
-            print(repr(sys.exc_info()[1]))
-            Node.allnodes = {}
+def test_main():
+    run_unittest(MinidomTest)
 
-if failed:
-    print("\n\n\n**** Check for failures in these tests:")
-    for name in failed:
-        print("  " + name)
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_mmap.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mmap.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_mmap.py	Wed Jul 11 15:40:56 2007
@@ -299,10 +299,10 @@
     def test_anonymous(self):
         # anonymous mmap.mmap(-1, PAGE)
         m = mmap.mmap(-1, PAGESIZE)
-        for x in xrange(PAGESIZE):
+        for x in range(PAGESIZE):
             self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero")
 
-        for x in xrange(PAGESIZE):
+        for x in range(PAGESIZE):
             m[x] = ch = chr(x & 255)
             self.assertEqual(m[x], ch)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_module.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_module.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_module.py	Wed Jul 11 15:40:56 2007
@@ -1,48 +1,61 @@
 # Test the module type
-
-from test.test_support import verify, vereq, verbose, TestFailed
+import unittest
+from test.test_support import verbose, run_unittest
 
 import sys
-module = type(sys)
+ModuleType = type(sys)
+
+class ModuleTests(unittest.TestCase):
+    def test_uninitialized(self):
+        # An uninitialized module has no __dict__ or __name__,
+        # and __doc__ is None
+        foo = ModuleType.__new__(ModuleType)
+        self.failUnless(foo.__dict__ is None)
+        try:
+            s = foo.__name__
+            self.fail("__name__ = %s" % repr(s))
+        except AttributeError:
+            pass
+        self.assertEqual(foo.__doc__, ModuleType.__doc__)
+
+    def test_no_docstring(self):
+        # Regularly initialized module, no docstring
+        foo = ModuleType("foo")
+        self.assertEqual(foo.__name__, "foo")
+        self.assertEqual(foo.__doc__, None)
+        self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": None})
+
+    def test_ascii_docstring(self):
+        # ASCII docstring
+        foo = ModuleType("foo", "foodoc")
+        self.assertEqual(foo.__name__, "foo")
+        self.assertEqual(foo.__doc__, "foodoc")
+        self.assertEqual(foo.__dict__,
+                         {"__name__": "foo", "__doc__": "foodoc"})
+
+    def test_unicode_docstring(self):
+        # Unicode docstring
+        foo = ModuleType("foo", u"foodoc\u1234")
+        self.assertEqual(foo.__name__, "foo")
+        self.assertEqual(foo.__doc__, u"foodoc\u1234")
+        self.assertEqual(foo.__dict__,
+                         {"__name__": "foo", "__doc__": u"foodoc\u1234"})
+
+    def test_reinit(self):
+        # Reinitialization should not replace the __dict__
+        foo = ModuleType("foo", u"foodoc\u1234")
+        foo.bar = 42
+        d = foo.__dict__
+        foo.__init__("foo", "foodoc")
+        self.assertEqual(foo.__name__, "foo")
+        self.assertEqual(foo.__doc__, "foodoc")
+        self.assertEqual(foo.bar, 42)
+        self.assertEqual(foo.__dict__,
+              {"__name__": "foo", "__doc__": "foodoc", "bar": 42})
+        self.failUnless(foo.__dict__ is d)
 
-# An uninitialized module has no __dict__ or __name__, and __doc__ is None
-foo = module.__new__(module)
-verify(foo.__dict__ is None)
-try:
-    s = foo.__name__
-except AttributeError:
-    pass
-else:
-    raise TestFailed, "__name__ = %s" % repr(s)
-vereq(foo.__doc__, module.__doc__)
-
-# Regularly initialized module, no docstring
-foo = module("foo")
-vereq(foo.__name__, "foo")
-vereq(foo.__doc__, None)
-vereq(foo.__dict__, {"__name__": "foo", "__doc__": None})
-
-# ASCII docstring
-foo = module("foo", "foodoc")
-vereq(foo.__name__, "foo")
-vereq(foo.__doc__, "foodoc")
-vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc"})
-
-# Unicode docstring
-foo = module("foo", u"foodoc\u1234")
-vereq(foo.__name__, "foo")
-vereq(foo.__doc__, u"foodoc\u1234")
-vereq(foo.__dict__, {"__name__": "foo", "__doc__": u"foodoc\u1234"})
-
-# Reinitialization should not replace the __dict__
-foo.bar = 42
-d = foo.__dict__
-foo.__init__("foo", "foodoc")
-vereq(foo.__name__, "foo")
-vereq(foo.__doc__, "foodoc")
-vereq(foo.bar, 42)
-vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42})
-verify(foo.__dict__ is d)
+def test_main():
+    run_unittest(ModuleTests)
 
-if verbose:
-    print("All OK")
+if __name__ == '__main__':
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_modulefinder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_modulefinder.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_modulefinder.py	Wed Jul 11 15:40:56 2007
@@ -87,7 +87,7 @@
     "a.module",
     ["a", "a.module",
      "b", "b.x", "b.y", "b.z",
-     "__future__", "sys", "exceptions"],
+     "__future__", "sys", "gc"],
     ["blahblah", "z"], [],
     """\
 mymodule.py
@@ -96,11 +96,11 @@
                                 from __future__ import absolute_import
                                 import sys # sys
                                 import blahblah # fails
-                                import exceptions # exceptions
+                                import gc # gc
                                 import b.x # b.x
                                 from b import y # b.y
                                 from b.z import * # b.z.*
-a/exceptions.py
+a/gc.py
 a/sys.py
                                 import mymodule
 a/b/__init__.py
@@ -123,7 +123,7 @@
      "a.b.c", "a.b.c.moduleC",
      "a.b.c.d", "a.b.c.e",
      "a.b.x",
-     "exceptions"],
+     "gc"],
     [], [],
     """\
 mymodule.py
@@ -131,8 +131,8 @@
                                 from .b import y, z # a.b.y, a.b.z
 a/module.py
                                 from __future__ import absolute_import # __future__
-                                import exceptions # exceptions
-a/exceptions.py
+                                import gc # gc
+a/gc.py
 a/sys.py
 a/b/__init__.py
                                 from ..b import x # a.b.x
@@ -170,7 +170,7 @@
 a/another.py
 a/module.py
                                 from .b import y, z # a.b.y, a.b.z
-a/exceptions.py
+a/gc.py
 a/sys.py
 a/b/__init__.py
                                 from .c import moduleC # a.b.c.moduleC

Modified: python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py	Wed Jul 11 15:40:56 2007
@@ -136,11 +136,21 @@
         self.assertRaises(UnicodeDecodeError, decoder.decode, '', True)
         self.assertEqual(decoder.decode('B@$'), u'\u4e16')
 
+class Test_StreamReader(unittest.TestCase):
+    def test_bug1728403(self):
+        try:
+            open(TESTFN, 'w').write('\xa1')
+            f = codecs.open(TESTFN, encoding='cp949')
+            self.assertRaises(UnicodeDecodeError, f.read, 2)
+        finally:
+            try: f.close()
+            except: pass
+            os.unlink(TESTFN)
 
 class Test_StreamWriter(unittest.TestCase):
     if len(u'\U00012345') == 2: # UCS2
         def test_gb18030(self):
-            s= StringIO.StringIO()
+            s = StringIO.StringIO()
             c = codecs.getwriter('gb18030')(s)
             c.write(u'123')
             self.assertEqual(s.getvalue(), '123')
@@ -206,7 +216,7 @@
         self.failIf('\x0e' in u'\N{SOFT HYPHEN}'.encode('iso-2022-jp-2'))
         for encoding in ('iso-2022-jp-2004', 'iso-2022-jp-3'):
             e = u'\u3406'.encode(encoding)
-            self.failIf(filter(lambda x: x >= '\x80', e))
+            self.failIf(list(filter(lambda x: x >= '\x80', e)))
 
     def test_bug1572832(self):
         if sys.maxunicode >= 0x10000:
@@ -214,18 +224,12 @@
         else:
             myunichr = lambda x: unichr(0xD7C0+(x>>10)) + unichr(0xDC00+(x&0x3FF))
 
-        for x in xrange(0x10000, 0x110000):
+        for x in range(0x10000, 0x110000):
             # Any ISO 2022 codec will cause the segfault
             myunichr(x).encode('iso_2022_jp', 'ignore')
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(Test_MultibyteCodec))
-    suite.addTest(unittest.makeSuite(Test_IncrementalEncoder))
-    suite.addTest(unittest.makeSuite(Test_IncrementalDecoder))
-    suite.addTest(unittest.makeSuite(Test_StreamWriter))
-    suite.addTest(unittest.makeSuite(Test_ISO2022))
-    test_support.run_suite(suite)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py	Wed Jul 11 15:40:56 2007
@@ -145,7 +145,7 @@
 
     def test_incrementalencoder(self):
         UTF8Reader = codecs.getreader('utf-8')
-        for sizehint in [None] + range(1, 33) + \
+        for sizehint in [None] + list(range(1, 33)) + \
                         [64, 128, 256, 512, 1024]:
             istream = UTF8Reader(StringIO(self.tstring[1]))
             ostream = StringIO()
@@ -165,7 +165,7 @@
 
     def test_incrementaldecoder(self):
         UTF8Writer = codecs.getwriter('utf-8')
-        for sizehint in [None, -1] + range(1, 33) + \
+        for sizehint in [None, -1] + list(range(1, 33)) + \
                         [64, 128, 256, 512, 1024]:
             istream = StringIO(self.tstring[0])
             ostream = UTF8Writer(StringIO())
@@ -203,7 +203,7 @@
     def test_streamreader(self):
         UTF8Writer = codecs.getwriter('utf-8')
         for name in ["read", "readline", "readlines"]:
-            for sizehint in [None, -1] + range(1, 33) + \
+            for sizehint in [None, -1] + list(range(1, 33)) + \
                             [64, 128, 256, 512, 1024]:
                 istream = self.reader(StringIO(self.tstring[0]))
                 ostream = UTF8Writer(StringIO())
@@ -223,7 +223,7 @@
         readfuncs = ('read', 'readline', 'readlines')
         UTF8Reader = codecs.getreader('utf-8')
         for name in readfuncs:
-            for sizehint in [None] + range(1, 33) + \
+            for sizehint in [None] + list(range(1, 33)) + \
                             [64, 128, 256, 512, 1024]:
                 istream = UTF8Reader(StringIO(self.tstring[1]))
                 ostream = self.writer(StringIO())

Modified: python/branches/p3yk-noslice/Lib/test/test_mutants.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mutants.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_mutants.py	Wed Jul 11 15:40:56 2007
@@ -113,7 +113,7 @@
 
 def fill_dict(d, candidates, numentries):
     d.clear()
-    for i in xrange(numentries):
+    for i in range(numentries):
         d[Horrid(random.choice(candidates))] = \
             Horrid(random.choice(candidates))
     return list(d.keys())
@@ -152,7 +152,7 @@
 # leak).
 
 def test(n):
-    for i in xrange(n):
+    for i in range(n):
         test_one(random.randrange(1, 100))
 
 # See last comment block for clues about good values for n.

Modified: python/branches/p3yk-noslice/Lib/test/test_new.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_new.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_new.py	Wed Jul 11 15:40:56 2007
@@ -79,18 +79,18 @@
                 return x + y
             return g
         g = f(4)
-        new.function(f.func_code, {}, "blah")
-        g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure)
+        new.function(f.__code__, {}, "blah")
+        g2 = new.function(g.__code__, {}, "blah", (2,), g.__closure__)
         self.assertEqual(g2(), 6)
-        g3 = new.function(g.func_code, {}, "blah", None, g.func_closure)
+        g3 = new.function(g.__code__, {}, "blah", None, g.__closure__)
         self.assertEqual(g3(5), 9)
         def test_closure(func, closure, exc):
-            self.assertRaises(exc, new.function, func.func_code, {}, "", None, closure)
+            self.assertRaises(exc, new.function, func.__code__, {}, "", None, closure)
 
         test_closure(g, None, TypeError) # invalid closure
         test_closure(g, (1,), TypeError) # non-cell in closure
         test_closure(g, (1, 1), ValueError) # closure is wrong size
-        test_closure(f, g.func_closure, ValueError) # no closure needed
+        test_closure(f, g.__closure__, ValueError) # no closure needed
 
     # Note: Jython will never have new.code()
     if hasattr(new, 'code'):
@@ -98,7 +98,7 @@
             # bogus test of new.code()
             def f(a): pass
 
-            c = f.func_code
+            c = f.__code__
             argcount = c.co_argcount
             kwonlyargcount = c.co_kwonlyargcount
             nlocals = c.co_nlocals

Modified: python/branches/p3yk-noslice/Lib/test/test_normalization.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_normalization.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_normalization.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,6 @@
-from test.test_support import (verbose, TestFailed, TestSkipped, verify,
-                               open_urlresource)
+from test.test_support import run_unittest, open_urlresource
+import unittest
+
 import sys
 import os
 from unicodedata import normalize
@@ -29,60 +30,67 @@
             raise RangeError
     return u"".join([unichr(x) for x in data])
 
-def test_main():
-    part1_data = {}
-    for line in open_urlresource(TESTDATAURL):
-        if '#' in line:
-            line = line.split('#')[0]
-        line = line.strip()
-        if not line:
-            continue
-        if line.startswith("@Part"):
-            part = line.split()[0]
-            continue
-        if part == "@Part3":
-            # XXX we don't support PRI #29 yet, so skip these tests for now
-            continue
-        try:
-            c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]]
-        except RangeError:
-            # Skip unsupported characters;
-            # try atleast adding c1 if we are in part1
+class NormalizationTest(unittest.TestCase):
+    def test_main(self):
+        part1_data = {}
+        for line in open_urlresource(TESTDATAURL):
+            if '#' in line:
+                line = line.split('#')[0]
+            line = line.strip()
+            if not line:
+                continue
+            if line.startswith("@Part"):
+                part = line.split()[0]
+                continue
+            if part == "@Part3":
+                # XXX we don't support PRI #29 yet, so skip these tests for now
+                continue
+            try:
+                c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]]
+            except RangeError:
+                # Skip unsupported characters;
+                # try atleast adding c1 if we are in part1
+                if part == "@Part1":
+                    try:
+                        c1 = unistr(line.split(';')[0])
+                    except RangeError:
+                        pass
+                    else:
+                        part1_data[c1] = 1
+                continue
+
+            # Perform tests
+            self.failUnless(c2 ==  NFC(c1) ==  NFC(c2) ==  NFC(c3), line)
+            self.failUnless(c4 ==  NFC(c4) ==  NFC(c5), line)
+            self.failUnless(c3 ==  NFD(c1) ==  NFD(c2) ==  NFD(c3), line)
+            self.failUnless(c5 ==  NFD(c4) ==  NFD(c5), line)
+            self.failUnless(c4 == NFKC(c1) == NFKC(c2) == \
+                            NFKC(c3) == NFKC(c4) == NFKC(c5),
+                            line)
+            self.failUnless(c5 == NFKD(c1) == NFKD(c2) == \
+                            NFKD(c3) == NFKD(c4) == NFKD(c5),
+                            line)
+
+            # Record part 1 data
             if part == "@Part1":
-                try:
-                    c1=unistr(line.split(';')[0])
-                except RangeError:
-                    pass
-                else:
-                    part1_data[c1] = 1
-            continue
-
-        if verbose:
-            print(line)
-
-        # Perform tests
-        verify(c2 ==  NFC(c1) ==  NFC(c2) ==  NFC(c3), line)
-        verify(c4 ==  NFC(c4) ==  NFC(c5), line)
-        verify(c3 ==  NFD(c1) ==  NFD(c2) ==  NFD(c3), line)
-        verify(c5 ==  NFD(c4) ==  NFD(c5), line)
-        verify(c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5),
-               line)
-        verify(c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5),
-               line)
-
-        # Record part 1 data
-        if part == "@Part1":
-            part1_data[c1] = 1
-
-    # Perform tests for all other data
-    for c in range(sys.maxunicode+1):
-        X = unichr(c)
-        if X in part1_data:
-            continue
-        assert X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c
+                part1_data[c1] = 1
 
-    # Check for bug 834676
-    normalize('NFC',u'\ud55c\uae00')
+        # Perform tests for all other data
+        for c in range(sys.maxunicode+1):
+            X = unichr(c)
+            if X in part1_data:
+                continue
+            self.failUnless(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c)
+
+    def test_bug_834676(self):
+        # Check for bug 834676
+        normalize('NFC', u'\ud55c\uae00')
+
+
+def test_main():
+    # Hit the exception early
+    open_urlresource(TESTDATAURL)
+    run_unittest(NormalizationTest)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_ntpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ntpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_ntpath.py	Wed Jul 11 15:40:56 2007
@@ -18,13 +18,14 @@
 
 tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
 tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext'))
-tester('ntpath.splitext(".ext")', ('', '.ext'))
+tester('ntpath.splitext(".ext")', ('.ext', ''))
 tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
 tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
 tester('ntpath.splitext("")', ('', ''))
 tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
 tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
 tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
+tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d'))
 
 tester('ntpath.splitdrive("c:\\foo\\bar")',
        ('c:', '\\foo\\bar'))
@@ -133,6 +134,13 @@
     tester('ntpath.expandvars("${{foo}}")', "baz1}")
     tester('ntpath.expandvars("$foo$foo")', "barbar")
     tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
+    tester('ntpath.expandvars("%foo% bar")', "bar bar")
+    tester('ntpath.expandvars("%foo%bar")', "barbar")
+    tester('ntpath.expandvars("%foo%%foo%")', "barbar")
+    tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
+    tester('ntpath.expandvars("%?bar%")', "%?bar%")
+    tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
+    tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
 finally:
     os.environ.clear()
     os.environ.update(oldenv)
@@ -149,6 +157,16 @@
 else:
     tester('ntpath.abspath("C:\\")', "C:\\")
 
+currentdir = os.path.split(os.getcwd())[-1]
+tester('ntpath.relpath("a")', 'a')
+tester('ntpath.relpath(os.path.abspath("a"))', 'a')
+tester('ntpath.relpath("a/b")', 'a\\b')
+tester('ntpath.relpath("../a/b")', '..\\a\\b')
+tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
+tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
+tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
+tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
+
 if errors:
     raise TestFailed(str(errors) + " errors.")
 elif verbose:

Modified: python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py	Wed Jul 11 15:40:56 2007
@@ -35,7 +35,7 @@
         self._msgfiles = []
 
     def tearDown(self):
-        map(os.unlink, self._msgfiles)
+        list(map(os.unlink, self._msgfiles))
         os.rmdir(os.path.join(self._dir, "cur"))
         os.rmdir(os.path.join(self._dir, "tmp"))
         os.rmdir(os.path.join(self._dir, "new"))

Deleted: /python/branches/p3yk-noslice/Lib/test/test_operations.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_operations.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,77 +0,0 @@
-# Python test set -- part 3, built-in operations.
-
-
-print('3. Operations')
-print('XXX Mostly not yet implemented')
-
-
-print('3.1 Dictionary lookups fail if __cmp__() raises an exception')
-
-class BadDictKey:
-
-    def __hash__(self):
-        return hash(self.__class__)
-
-    def __eq__(self, other):
-        if isinstance(other, self.__class__):
-            print("raising error")
-            raise RuntimeError, "gotcha"
-        return other
-
-d = {}
-x1 = BadDictKey()
-x2 = BadDictKey()
-d[x1] = 1
-for stmt in ['d[x2] = 2',
-             'z = d[x2]',
-             'x2 in d',
-             'd.get(x2)',
-             'd.setdefault(x2, 42)',
-             'd.pop(x2)',
-             'd.update({x2: 2})']:
-    try:
-        exec(stmt)
-    except RuntimeError:
-        print("%s: caught the RuntimeError outside" % (stmt,))
-    else:
-        print("%s: No exception passed through!" % (stmt,)) # old CPython behavior
-
-
-# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
-# This version got an assert failure in debug build, infinite loop in
-# release build.  Unfortunately, provoking this kind of stuff requires
-# a mix of inserts and deletes hitting exactly the right hash codes in
-# exactly the right order, and I can't think of a randomized approach
-# that would be *likely* to hit a failing case in reasonable time.
-
-d = {}
-for i in range(5):
-    d[i] = i
-for i in range(5):
-    del d[i]
-for i in range(5, 9):  # i==8 was the problem
-    d[i] = i
-
-
-# Another dict resizing bug (SF bug #1456209).
-# This caused Segmentation faults or Illegal instructions.
-
-class X(object):
-    def __hash__(self):
-        return 5
-    def __eq__(self, other):
-        if resizing:
-            d.clear()
-        return False
-d = {}
-resizing = False
-d[X()] = 1
-d[X()] = 2
-d[X()] = 3
-d[X()] = 4
-d[X()] = 5
-# now trigger a resize
-resizing = True
-d[9] = 6
-
-print('resize bugs not triggered.')

Modified: python/branches/p3yk-noslice/Lib/test/test_operator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_operator.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_operator.py	Wed Jul 11 15:40:56 2007
@@ -1,3 +1,4 @@
+import sys
 import operator
 import unittest
 
@@ -138,11 +139,13 @@
         self.assert_(a == [4, 2, 1])
 
     def test_delslice(self):
-        a = range(10)
+        a = list(range(10))
         self.failUnlessRaises(TypeError, operator.delslice, a)
         self.failUnlessRaises(TypeError, operator.delslice, a, None, None)
         self.failUnless(operator.delslice(a, 2, 8) is None)
         self.assert_(a == [0, 1, 8, 9])
+        operator.delslice(a, 0, test_support.sys.maxint)
+        self.assert_(a == [])
 
     def test_floordiv(self):
         self.failUnlessRaises(TypeError, operator.floordiv, 5)
@@ -161,10 +164,12 @@
         self.failUnless(operator.getitem(a, 2) == 2)
 
     def test_getslice(self):
-        a = range(10)
+        a = list(range(10))
         self.failUnlessRaises(TypeError, operator.getslice)
         self.failUnlessRaises(TypeError, operator.getslice, a, None, None)
         self.failUnless(operator.getslice(a, 4, 6) == [4, 5])
+        b = operator.getslice(a, 0, test_support.sys.maxint)
+        self.assert_(b == a)
 
     def test_indexOf(self):
         self.failUnlessRaises(TypeError, operator.indexOf)
@@ -177,17 +182,6 @@
         self.failUnlessRaises(TypeError, operator.invert, None)
         self.failUnless(operator.inv(4) == -5)
 
-    def test_isCallable(self):
-        self.failUnlessRaises(TypeError, operator.isCallable)
-        class C:
-            pass
-        def check(self, o, v):
-            self.assert_(operator.isCallable(o) == callable(o) == v)
-        check(self, 4, 0)
-        check(self, operator.isCallable, 1)
-        check(self, C, 1)
-        check(self, C(), 0)
-
     def test_isMappingType(self):
         self.failUnlessRaises(TypeError, operator.isMappingType)
         self.failIf(operator.isMappingType(1))
@@ -207,7 +201,7 @@
         self.failUnlessRaises(TypeError, operator.isSequenceType)
         self.failUnless(operator.isSequenceType(dir()))
         self.failUnless(operator.isSequenceType(()))
-        self.failUnless(operator.isSequenceType(xrange(10)))
+        self.failUnless(operator.isSequenceType(range(10)))
         self.failUnless(operator.isSequenceType('yeahbuddy'))
         self.failIf(operator.isSequenceType(3))
         class Dict(dict): pass
@@ -260,7 +254,7 @@
         self.assertRaises(TypeError, operator.pow, 1, 2, 3)
 
     def test_repeat(self):
-        a = range(3)
+        a = list(range(3))
         self.failUnlessRaises(TypeError, operator.repeat)
         self.failUnlessRaises(TypeError, operator.repeat, a, None)
         self.failUnless(operator.repeat(a, 2) == a+a)
@@ -296,11 +290,9 @@
         self.failUnlessRaises(TypeError, operator.contains, None, None)
         self.failUnless(operator.contains(range(4), 2))
         self.failIf(operator.contains(range(4), 5))
-        self.failUnless(operator.sequenceIncludes(range(4), 2))
-        self.failIf(operator.sequenceIncludes(range(4), 5))
 
     def test_setitem(self):
-        a = range(3)
+        a = list(range(3))
         self.failUnlessRaises(TypeError, operator.setitem, a)
         self.failUnlessRaises(TypeError, operator.setitem, a, None, None)
         self.failUnless(operator.setitem(a, 0, 2) is None)
@@ -308,11 +300,13 @@
         self.assertRaises(IndexError, operator.setitem, a, 4, 2)
 
     def test_setslice(self):
-        a = range(4)
+        a = list(range(4))
         self.failUnlessRaises(TypeError, operator.setslice, a)
         self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None)
         self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None)
         self.assert_(a == [0, 2, 1, 3])
+        operator.setslice(a, 0, test_support.sys.maxint, [])
+        self.assert_(a == [])
 
     def test_sub(self):
         self.failUnlessRaises(TypeError, operator.sub)
@@ -400,12 +394,12 @@
         # example used in the docs
         inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
         getcount = operator.itemgetter(1)
-        self.assertEqual(map(getcount, inventory), [3, 2, 5, 1])
+        self.assertEqual(list(map(getcount, inventory)), [3, 2, 5, 1])
         self.assertEqual(sorted(inventory, key=getcount),
             [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])
 
         # multiple gets
-        data = map(str, range(20))
+        data = list(map(str, range(20)))
         self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))
         self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)
 
@@ -466,7 +460,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_optparse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_optparse.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_optparse.py	Wed Jul 11 15:40:56 2007
@@ -12,7 +12,6 @@
 import os
 import re
 import copy
-import types
 import unittest
 
 from StringIO import StringIO
@@ -27,12 +26,6 @@
 from optparse import _match_abbrev
 from optparse import _parse_num
 
-# Do the right thing with boolean values for all known Python versions.
-try:
-    True, False
-except NameError:
-    (True, False) = (1, 0)
-
 retype = type(re.compile(''))
 
 class InterceptedError(Exception):
@@ -177,7 +170,7 @@
 
         except InterceptedError as err:
             self.assert_(
-                type(output) is types.StringType,
+                isinstance(output, str),
                 "expected output to be an ordinary string, not %r"
                 % type(output))
 
@@ -438,18 +431,12 @@
         self.parser.add_option("-s", type="str")
         self.assertEquals(self.parser.get_option("-s").type, "string")
 
-    def test_new_type_object(self):
+    def test_type_object(self):
         self.parser.add_option("-s", type=str)
         self.assertEquals(self.parser.get_option("-s").type, "string")
         self.parser.add_option("-x", type=int)
         self.assertEquals(self.parser.get_option("-x").type, "int")
 
-    def test_old_type_object(self):
-        self.parser.add_option("-s", type=types.StringType)
-        self.assertEquals(self.parser.get_option("-s").type, "string")
-        self.parser.add_option("-x", type=types.IntType)
-        self.assertEquals(self.parser.get_option("-x").type, "int")
-
 
 # Custom type for testing processing of default values.
 _time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 }
@@ -1476,7 +1463,7 @@
                 os.environ['COLUMNS'] = orig_columns
 
     def assertHelpEquals(self, expected_output):
-        if type(expected_output) is types.UnicodeType:
+        if isinstance(expected_output, unicode):
             encoding = self.parser._get_encoding(sys.stdout)
             expected_output = expected_output.encode(encoding, "replace")
 
@@ -1631,18 +1618,8 @@
                              "option -l: invalid integer value: '0x12x'")
 
 
-def _testclasses():
-    mod = sys.modules[__name__]
-    return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
-
-def suite():
-    suite = unittest.TestSuite()
-    for testclass in _testclasses():
-        suite.addTest(unittest.makeSuite(testclass))
-    return suite
-
 def test_main():
-    test_support.run_suite(suite())
+    test_support.run_unittest(__name__)
 
 if __name__ == '__main__':
-    unittest.main()
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_os.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_os.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_os.py	Wed Jul 11 15:40:56 2007
@@ -143,7 +143,7 @@
         try:
             result.st_mode = 1
             self.fail("No exception thrown")
-        except TypeError:
+        except AttributeError:
             pass
 
         try:
@@ -201,7 +201,7 @@
         try:
             result.f_bfree = 1
             self.fail("No exception thrown")
-        except TypeError:
+        except AttributeError:
             pass
 
         try:
@@ -240,6 +240,15 @@
             os.utime(self.fname, (t1, t1))
             self.assertEquals(os.stat(self.fname).st_mtime, t1)
 
+        def test_1686475(self):
+            # Verify that an open file can be stat'ed
+            try:
+                os.stat(r"c:\pagefile.sys")
+            except WindowsError as e:
+                if e == 2: # file does not exist; cannot run test
+                    return
+                self.fail("Could not stat pagefile.sys")
+
 from test import mapping_tests
 
 class EnvironTests(mapping_tests.BasicTestMappingProtocol):
@@ -272,78 +281,107 @@
         from os.path import join
 
         # Build:
-        #     TESTFN/               a file kid and two directory kids
+        #     TESTFN/
+        #       TEST1/              a file kid and two directory kids
         #         tmp1
         #         SUB1/             a file kid and a directory kid
-        #             tmp2
-        #             SUB11/        no kids
-        #         SUB2/             just a file kid
-        #             tmp3
-        sub1_path = join(test_support.TESTFN, "SUB1")
+        #           tmp2
+        #           SUB11/          no kids
+        #         SUB2/             a file kid and a dirsymlink kid
+        #           tmp3
+        #           link/           a symlink to TESTFN.2
+        #       TEST2/
+        #         tmp4              a lone file
+        walk_path = join(test_support.TESTFN, "TEST1")
+        sub1_path = join(walk_path, "SUB1")
         sub11_path = join(sub1_path, "SUB11")
-        sub2_path = join(test_support.TESTFN, "SUB2")
-        tmp1_path = join(test_support.TESTFN, "tmp1")
+        sub2_path = join(walk_path, "SUB2")
+        tmp1_path = join(walk_path, "tmp1")
         tmp2_path = join(sub1_path, "tmp2")
         tmp3_path = join(sub2_path, "tmp3")
+        link_path = join(sub2_path, "link")
+        t2_path = join(test_support.TESTFN, "TEST2")
+        tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
 
         # Create stuff.
         os.makedirs(sub11_path)
         os.makedirs(sub2_path)
-        for path in tmp1_path, tmp2_path, tmp3_path:
+        os.makedirs(t2_path)
+        for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
             f = open(path, "w")
             f.write("I'm " + path + " and proud of it.  Blame test_os.\n")
             f.close()
+        if hasattr(os, "symlink"):
+            os.symlink(os.path.abspath(t2_path), link_path)
+            sub2_tree = (sub2_path, ["link"], ["tmp3"])
+        else:
+            sub2_tree = (sub2_path, [], ["tmp3"])
 
         # Walk top-down.
-        all = list(os.walk(test_support.TESTFN))
+        all = list(os.walk(walk_path))
         self.assertEqual(len(all), 4)
         # We can't know which order SUB1 and SUB2 will appear in.
         # Not flipped:  TESTFN, SUB1, SUB11, SUB2
         #     flipped:  TESTFN, SUB2, SUB1, SUB11
         flipped = all[0][1][0] != "SUB1"
         all[0][1].sort()
-        self.assertEqual(all[0], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
+        self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
         self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
         self.assertEqual(all[2 + flipped], (sub11_path, [], []))
-        self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"]))
+        self.assertEqual(all[3 - 2 * flipped], sub2_tree)
 
         # Prune the search.
         all = []
-        for root, dirs, files in os.walk(test_support.TESTFN):
+        for root, dirs, files in os.walk(walk_path):
             all.append((root, dirs, files))
             # Don't descend into SUB1.
             if 'SUB1' in dirs:
                 # Note that this also mutates the dirs we appended to all!
                 dirs.remove('SUB1')
         self.assertEqual(len(all), 2)
-        self.assertEqual(all[0], (test_support.TESTFN, ["SUB2"], ["tmp1"]))
-        self.assertEqual(all[1], (sub2_path, [], ["tmp3"]))
+        self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
+        self.assertEqual(all[1], sub2_tree)
 
         # Walk bottom-up.
-        all = list(os.walk(test_support.TESTFN, topdown=False))
+        all = list(os.walk(walk_path, topdown=False))
         self.assertEqual(len(all), 4)
         # We can't know which order SUB1 and SUB2 will appear in.
         # Not flipped:  SUB11, SUB1, SUB2, TESTFN
         #     flipped:  SUB2, SUB11, SUB1, TESTFN
         flipped = all[3][1][0] != "SUB1"
         all[3][1].sort()
-        self.assertEqual(all[3], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
+        self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
         self.assertEqual(all[flipped], (sub11_path, [], []))
         self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
-        self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"]))
+        self.assertEqual(all[2 - 2 * flipped], sub2_tree)
+
+        if hasattr(os, "symlink"):
+            # Walk, following symlinks.
+            for root, dirs, files in os.walk(walk_path, followlinks=True):
+                if root == link_path:
+                    self.assertEqual(dirs, [])
+                    self.assertEqual(files, ["tmp4"])
+                    break
+            else:
+                self.fail("Didn't follow symlink with followlinks=True")
 
+    def tearDown(self):
         # Tear everything down.  This is a decent use for bottom-up on
         # Windows, which doesn't have a recursive delete command.  The
         # (not so) subtlety is that rmdir will fail unless the dir's
         # kids are removed first, so bottom up is essential.
         for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
             for name in files:
-                os.remove(join(root, name))
+                os.remove(os.path.join(root, name))
             for name in dirs:
-                os.rmdir(join(root, name))
+                dirname = os.path.join(root, name)
+                if not os.path.islink(dirname):
+                    os.rmdir(dirname)
+                else:
+                    os.remove(dirname)
         os.rmdir(test_support.TESTFN)
 
-class MakedirTests (unittest.TestCase):
+class MakedirTests(unittest.TestCase):
     def setUp(self):
         os.mkdir(test_support.TESTFN)
 
@@ -362,9 +400,6 @@
                             'dir5', 'dir6')
         os.makedirs(path)
 
-
-
-
     def tearDown(self):
         path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
                             'dir4', 'dir5', 'dir6')
@@ -376,7 +411,7 @@
 
         os.removedirs(path)
 
-class DevNullTests (unittest.TestCase):
+class DevNullTests(unittest.TestCase):
     def test_devnull(self):
         f = open(os.devnull, 'w')
         f.write('hello')
@@ -385,7 +420,7 @@
         self.assertEqual(f.read(), '')
         f.close()
 
-class URandomTests (unittest.TestCase):
+class URandomTests(unittest.TestCase):
     def test_urandom(self):
         try:
             self.assertEqual(len(os.urandom(1)), 1)
@@ -395,6 +430,10 @@
         except NotImplementedError:
             pass
 
+class ExecTests(unittest.TestCase):
+    def test_execvpe_with_bad_program(self):
+        self.assertRaises(OSError, os.execvpe, 'no such app-', [], None)
+
 class Win32ErrorTests(unittest.TestCase):
     def test_rename(self):
         self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
@@ -431,6 +470,7 @@
         MakedirTests,
         DevNullTests,
         URandomTests,
+        ExecTests,
         Win32ErrorTests
     )
 

Modified: python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,7 @@
 from test import test_support
 test_support.requires('audio')
 
-from test.test_support import verbose, findfile, TestFailed, TestSkipped
+from test.test_support import verbose, findfile, TestSkipped
 
 import errno
 import fcntl
@@ -12,6 +12,7 @@
 import sunaudio
 import time
 import audioop
+import unittest
 
 # Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a
 # fairly recent addition to OSS.
@@ -33,131 +34,143 @@
     fp.close()
 
     if enc != SND_FORMAT_MULAW_8:
-        print("Expect .au file with 8-bit mu-law samples")
-        return
+        raise RuntimeError("Expect .au file with 8-bit mu-law samples")
 
     # Convert the data to 16-bit signed.
     data = audioop.ulaw2lin(data, 2)
     return (data, rate, 16, nchannels)
 
-# version of assert that still works with -O
-def _assert(expr, message=None):
-    if not expr:
-        raise AssertionError(message or "assertion failed")
+class OSSAudioDevTests(unittest.TestCase):
 
-def play_sound_file(data, rate, ssize, nchannels):
-    try:
-        dsp = ossaudiodev.open('w')
-    except IOError as msg:
-        if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
-            raise TestSkipped, msg
-        raise TestFailed, msg
-
-    # at least check that these methods can be invoked
-    dsp.bufsize()
-    dsp.obufcount()
-    dsp.obuffree()
-    dsp.getptr()
-    dsp.fileno()
-
-    # Make sure the read-only attributes work.
-    _assert(dsp.closed is False, "dsp.closed is not False")
-    _assert(dsp.name == "/dev/dsp")
-    _assert(dsp.mode == 'w', "bad dsp.mode: %r" % dsp.mode)
-
-    # And make sure they're really read-only.
-    for attr in ('closed', 'name', 'mode'):
+    def play_sound_file(self, data, rate, ssize, nchannels):
         try:
-            setattr(dsp, attr, 42)
-            raise RuntimeError("dsp.%s not read-only" % attr)
-        except TypeError:
-            pass
-
-    # Compute expected running time of sound sample (in seconds).
-    expected_time = float(len(data)) / (ssize/8) / nchannels / rate
-
-    # set parameters based on .au file headers
-    dsp.setparameters(AFMT_S16_NE, nchannels, rate)
-    print(("playing test sound file (expected running time: %.2f sec)"
-           % expected_time))
-    t1 = time.time()
-    dsp.write(data)
-    dsp.close()
-    t2 = time.time()
-    elapsed_time = t2 - t1
-
-    percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
-    _assert(percent_diff <= 10.0, \
-            ("elapsed time (%.2f sec) > 10%% off of expected time (%.2f sec)"
-             % (elapsed_time, expected_time)))
-
-def test_setparameters(dsp):
-    # Two configurations for testing:
-    #   config1 (8-bit, mono, 8 kHz) should work on even the most
-    #      ancient and crufty sound card, but maybe not on special-
-    #      purpose high-end hardware
-    #   config2 (16-bit, stereo, 44.1kHz) should work on all but the
-    #      most ancient and crufty hardware
-    config1 = (ossaudiodev.AFMT_U8, 1, 8000)
-    config2 = (AFMT_S16_NE, 2, 44100)
-
-    for config in [config1, config2]:
-        (fmt, channels, rate) = config
-        if (dsp.setfmt(fmt) == fmt and
-            dsp.channels(channels) == channels and
-            dsp.speed(rate) == rate):
-            break
-    else:
-        raise RuntimeError("unable to set audio sampling parameters: "
-                           "you must have really weird audio hardware")
+            dsp = ossaudiodev.open('w')
+        except IOError as msg:
+            if msg.args[0] in (errno.EACCES, errno.ENOENT,
+                               errno.ENODEV, errno.EBUSY):
+                raise TestSkipped(msg)
+            raise
+
+        # at least check that these methods can be invoked
+        dsp.bufsize()
+        dsp.obufcount()
+        dsp.obuffree()
+        dsp.getptr()
+        dsp.fileno()
+
+        # Make sure the read-only attributes work.
+        self.failUnless(dsp.close)
+        self.assertEqual(dsp.name, "/dev/dsp")
+        self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode)
+
+        # And make sure they're really read-only.
+        for attr in ('closed', 'name', 'mode'):
+            try:
+                setattr(dsp, attr, 42)
+            except TypeError:
+                pass
+            else:
+                self.fail("dsp.%s not read-only" % attr)
+
+        # Compute expected running time of sound sample (in seconds).
+        expected_time = float(len(data)) / (ssize/8) / nchannels / rate
+
+        # set parameters based on .au file headers
+        dsp.setparameters(AFMT_S16_NE, nchannels, rate)
+        print ("playing test sound file (expected running time: %.2f sec)"
+               % expected_time)
+        t1 = time.time()
+        dsp.write(data)
+        dsp.close()
+        t2 = time.time()
+        elapsed_time = t2 - t1
+
+        percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
+        self.failUnless(percent_diff <= 10.0,
+                        "elapsed time > 10% off of expected time")
+
+    def set_parameters(self, dsp):
+        # Two configurations for testing:
+        #   config1 (8-bit, mono, 8 kHz) should work on even the most
+        #      ancient and crufty sound card, but maybe not on special-
+        #      purpose high-end hardware
+        #   config2 (16-bit, stereo, 44.1kHz) should work on all but the
+        #      most ancient and crufty hardware
+        config1 = (ossaudiodev.AFMT_U8, 1, 8000)
+        config2 = (AFMT_S16_NE, 2, 44100)
+
+        for config in [config1, config2]:
+            (fmt, channels, rate) = config
+            if (dsp.setfmt(fmt) == fmt and
+                dsp.channels(channels) == channels and
+                dsp.speed(rate) == rate):
+                break
+        else:
+            raise RuntimeError("unable to set audio sampling parameters: "
+                               "you must have really weird audio hardware")
 
-    # setparameters() should be able to set this configuration in
-    # either strict or non-strict mode.
-    result = dsp.setparameters(fmt, channels, rate, False)
-    _assert(result == (fmt, channels, rate),
-            "setparameters%r: returned %r" % (config, result))
-    result = dsp.setparameters(fmt, channels, rate, True)
-    _assert(result == (fmt, channels, rate),
-            "setparameters%r: returned %r" % (config, result))
-
-def test_bad_setparameters(dsp):
-
-    # Now try some configurations that are presumably bogus: eg. 300
-    # channels currently exceeds even Hollywood's ambitions, and
-    # negative sampling rate is utter nonsense.  setparameters() should
-    # accept these in non-strict mode, returning something other than
-    # was requested, but should barf in strict mode.
-    fmt = AFMT_S16_NE
-    rate = 44100
-    channels = 2
-    for config in [(fmt, 300, rate),       # ridiculous nchannels
-                   (fmt, -5, rate),        # impossible nchannels
-                   (fmt, channels, -50),   # impossible rate
-                  ]:
-        (fmt, channels, rate) = config
+        # setparameters() should be able to set this configuration in
+        # either strict or non-strict mode.
         result = dsp.setparameters(fmt, channels, rate, False)
-        _assert(result != config,
-                "setparameters: unexpectedly got requested configuration")
+        self.assertEqual(result, (fmt, channels, rate),
+                         "setparameters%r: returned %r" % (config, result))
 
+        result = dsp.setparameters(fmt, channels, rate, True)
+        self.assertEqual(result, (fmt, channels, rate),
+                         "setparameters%r: returned %r" % (config, result))
+
+    def set_bad_parameters(self, dsp):
+
+        # Now try some configurations that are presumably bogus: eg. 300
+        # channels currently exceeds even Hollywood's ambitions, and
+        # negative sampling rate is utter nonsense.  setparameters() should
+        # accept these in non-strict mode, returning something other than
+        # was requested, but should barf in strict mode.
+        fmt = AFMT_S16_NE
+        rate = 44100
+        channels = 2
+        for config in [(fmt, 300, rate),       # ridiculous nchannels
+                       (fmt, -5, rate),        # impossible nchannels
+                       (fmt, channels, -50),   # impossible rate
+                      ]:
+            (fmt, channels, rate) = config
+            result = dsp.setparameters(fmt, channels, rate, False)
+            self.failIfEqual(result, config,
+                             "unexpectedly got requested configuration")
+
+            try:
+                result = dsp.setparameters(fmt, channels, rate, True)
+            except ossaudiodev.OSSAudioError as err:
+                pass
+            else:
+                self.fail("expected OSSAudioError")
+
+    def test_playback(self):
+        sound_info = read_sound_file(findfile('audiotest.au'))
+        self.play_sound_file(*sound_info)
+
+    def test_set_parameters(self):
+        dsp = ossaudiodev.open("w")
         try:
-            result = dsp.setparameters(fmt, channels, rate, True)
-            raise AssertionError("setparameters: expected OSSAudioError")
-        except ossaudiodev.OSSAudioError as err:
-            print("setparameters: got OSSAudioError as expected")
-
-def test():
-    (data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
-    play_sound_file(data, rate, ssize, nchannels)
+            self.set_parameters(dsp)
 
-    dsp = ossaudiodev.open("w")
-    try:
-        test_setparameters(dsp)
+            # Disabled because it fails under Linux 2.6 with ALSA's OSS
+            # emulation layer.
+            #self.set_bad_parameters(dsp)
+        finally:
+            dsp.close()
+            self.failUnless(dsp.closed)
 
-        # Disabled because it fails under Linux 2.6 with ALSA's OSS
-        # emulation layer.
-        #test_bad_setparameters(dsp)
-    finally:
-        dsp.close()
-        _assert(dsp.closed is True, "dsp.closed is not True")
 
-test()
+def test_main():
+    try:
+        dsp = ossaudiodev.open('w')
+    except IOError as msg:
+        if msg.args[0] in (errno.EACCES, errno.ENOENT,
+                           errno.ENODEV, errno.EBUSY):
+            raise TestSkipped(msg)
+        raise
+    test_support.run_unittest(__name__)
+
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_peepholer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_peepholer.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_peepholer.py	Wed Jul 11 15:40:56 2007
@@ -39,16 +39,29 @@
             asm = dis_single(line)
             self.assert_(elem in asm)
 
-    def test_none_as_constant(self):
-        # LOAD_GLOBAL None  -->  LOAD_CONST None
+    def test_global_as_constant(self):
+        # LOAD_GLOBAL None/True/False  -->  LOAD_CONST None/True/False
         def f(x):
             None
+            None
             return x
-        asm = disassemble(f)
-        for elem in ('LOAD_GLOBAL',):
-            self.assert_(elem not in asm)
-        for elem in ('LOAD_CONST', '(None)'):
-            self.assert_(elem in asm)
+        def g(x):
+            True
+            return x
+        def h(x):
+            False
+            return x
+        for func, name in ((f, 'None'), (g, 'True'), (h, 'False')):
+            asm = disassemble(func)
+            for elem in ('LOAD_GLOBAL',):
+                self.assert_(elem not in asm)
+            for elem in ('LOAD_CONST', '('+name+')'):
+                self.assert_(elem in asm)
+        def f():
+            'Adding a docstring made this test fail in Py2.5.0'
+            return None
+        self.assert_('LOAD_CONST' in disassemble(f))
+        self.assert_('LOAD_GLOBAL' not in disassemble(f))
 
     def test_while_one(self):
         # Skip over:  LOAD_CONST trueconst  JUMP_IF_FALSE xx  POP_TOP
@@ -196,6 +209,14 @@
         self.assertEqual(asm.split().count('JUMP_ABSOLUTE'), 1)
         self.assertEqual(asm.split().count('RETURN_VALUE'), 2)
 
+    def test_make_function_doesnt_bail(self):
+        def f():
+            def g()->1+1:
+                pass
+            return g
+        asm = disassemble(f)
+        self.assert_('BINARY_ADD' not in asm)
+
 
 def test_main(verbose=None):
     import sys
@@ -207,7 +228,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_pep247.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pep247.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pep247.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,7 @@
 # hashing algorithms.
 #
 
-import md5, sha, hmac
+import hmac
 
 def check_hash_module(module, key=None):
     assert hasattr(module, 'digest_size'), "Must have digest_size"
@@ -45,6 +45,4 @@
 
 
 if __name__ == '__main__':
-    check_hash_module(md5)
-    check_hash_module(sha)
     check_hash_module(hmac, key='abc')

Modified: python/branches/p3yk-noslice/Lib/test/test_pep352.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pep352.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pep352.py	Wed Jul 11 15:40:56 2007
@@ -1,11 +1,11 @@
 import unittest
 import __builtin__
-import exceptions
 import warnings
 from test.test_support import run_unittest, guard_warnings_filter
 import os
 from platform import system as platform_system
 
+
 class ExceptionClassTests(unittest.TestCase):
 
     """Tests for anything relating to exception objects themselves (e.g.,
@@ -15,13 +15,21 @@
         self.failUnless(issubclass(Exception, object))
 
     def verify_instance_interface(self, ins):
-        for attr in ("args", "message", "__str__", "__repr__", "__getitem__"):
-            self.failUnless(hasattr(ins, attr), "%s missing %s attribute" %
-                    (ins.__class__.__name__, attr))
+        for attr in ("args", "__str__", "__repr__"):
+            self.failUnless(hasattr(ins, attr),
+                    "%s missing %s attribute" %
+                        (ins.__class__.__name__, attr))
 
     def test_inheritance(self):
         # Make sure the inheritance hierarchy matches the documentation
-        exc_set = set(x for x in dir(exceptions) if not x.startswith('_'))
+        exc_set = set()
+        for object_ in __builtin__.__dict__.values():
+            try:
+                if issubclass(object_, BaseException):
+                    exc_set.add(object_.__name__)
+            except TypeError:
+                pass
+
         inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
                                                 'exception_hierarchy.txt'))
         try:
@@ -30,7 +38,8 @@
                 last_exc = getattr(__builtin__, superclass_name)
             except AttributeError:
                 self.fail("base class %s not a built-in" % superclass_name)
-            self.failUnless(superclass_name in exc_set)
+            self.failUnless(superclass_name in exc_set,
+                            '%s not found' % superclass_name)
             exc_set.discard(superclass_name)
             superclasses = []  # Loop will insert base exception
             last_depth = 0
@@ -72,8 +81,7 @@
             inheritance_tree.close()
         self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
 
-    interface_tests = ("length", "args", "message", "str", "unicode", "repr",
-            "indexing")
+    interface_tests = ("length", "args", "str", "unicode", "repr")
 
     def interface_test_driver(self, results):
         for test_name, (given, expected) in zip(self.interface_tests, results):
@@ -84,9 +92,9 @@
         # Make sure interface works properly when given a single argument
         arg = "spam"
         exc = Exception(arg)
-        results = ([len(exc.args), 1], [exc.args[0], arg], [exc.message, arg],
-                [str(exc), str(arg)], [unicode(exc), unicode(arg)],
-            [repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0], arg])
+        results = ([len(exc.args), 1], [exc.args[0], arg],
+                   [str(exc), str(arg)], [unicode(exc), unicode(arg)],
+            [repr(exc), exc.__class__.__name__ + repr(exc.args)])
         self.interface_test_driver(results)
 
     def test_interface_multi_arg(self):
@@ -95,24 +103,55 @@
         args = tuple(range(arg_count))
         exc = Exception(*args)
         results = ([len(exc.args), arg_count], [exc.args, args],
-                [exc.message, ''], [str(exc), str(args)],
+                [str(exc), str(args)],
                 [unicode(exc), unicode(args)],
-                [repr(exc), exc.__class__.__name__ + repr(exc.args)],
-                [exc[-1], args[-1]])
+                [repr(exc), exc.__class__.__name__ + repr(exc.args)])
         self.interface_test_driver(results)
 
     def test_interface_no_arg(self):
         # Make sure that with no args that interface is correct
         exc = Exception()
-        results = ([len(exc.args), 0], [exc.args, tuple()], [exc.message, ''],
+        results = ([len(exc.args), 0], [exc.args, tuple()],
                 [str(exc), ''], [unicode(exc), u''],
-                [repr(exc), exc.__class__.__name__ + '()'], [True, True])
+                [repr(exc), exc.__class__.__name__ + '()'])
         self.interface_test_driver(results)
 
+
 class UsageTests(unittest.TestCase):
 
     """Test usage of exceptions"""
 
+    def raise_fails(self, object_):
+        """Make sure that raising 'object_' triggers a TypeError."""
+        try:
+            raise object_
+        except TypeError:
+            return  # What is expected.
+        self.fail("TypeError expected for raising %s" % type(object_))
+
+    def catch_fails(self, object_):
+        """Catching 'object_' should raise a TypeError."""
+        try:
+            try:
+                raise Exception
+            except object_:
+                pass
+        except TypeError:
+            pass
+        except Exception:
+            self.fail("TypeError expected when catching %s" % type(object_))
+
+        try:
+            try:
+                raise Exception
+            except (object_,):
+                pass
+        except TypeError:
+            return
+        except Exception:
+            self.fail("TypeError expected when catching %s as specified in a "
+                        "tuple" % type(object_))
+
     def test_raise_new_style_non_exception(self):
         # You cannot raise a new-style class that does not inherit from
         # BaseException; the ability was not possible until BaseException's
@@ -120,56 +159,28 @@
         # inherit from it.
         class NewStyleClass(object):
             pass
-        try:
-            raise NewStyleClass
-        except TypeError:
-            pass
-        except:
-            self.fail("able to raise new-style class")
-        try:
-            raise NewStyleClass()
-        except TypeError:
-            pass
-        except:
-            self.fail("able to raise new-style class instance")
+        self.raise_fails(NewStyleClass)
+        self.raise_fails(NewStyleClass())
 
     def test_raise_string(self):
         # Raising a string raises TypeError.
-        try:
-            raise "spam"
-        except TypeError:
+        self.raise_fails("spam")
+
+    def test_catch_non_BaseException(self):
+        # Tryinng to catch an object that does not inherit from BaseException
+        # is not allowed.
+        class NonBaseException(object):
             pass
-        except:
-            self.fail("was able to raise a string exception")
+        self.catch_fails(NonBaseException)
+        self.catch_fails(NonBaseException())
+
+    def test_catch_BaseException_instance(self):
+        # Catching an instance of a BaseException subclass won't work.
+        self.catch_fails(BaseException())
 
     def test_catch_string(self):
-        # Catching a string should trigger a DeprecationWarning.
-        with guard_warnings_filter():
-            warnings.resetwarnings()
-            warnings.filterwarnings("error")
-            str_exc = "spam"
-            try:
-                try:
-                    raise StandardError
-                except str_exc:
-                    pass
-            except DeprecationWarning:
-                pass
-            except StandardError:
-                self.fail("catching a string exception did not raise "
-                            "DeprecationWarning")
-            # Make sure that even if the string exception is listed in a tuple
-            # that a warning is raised.
-            try:
-                try:
-                    raise StandardError
-                except (AssertionError, str_exc):
-                    pass
-            except DeprecationWarning:
-                pass
-            except StandardError:
-                self.fail("catching a string exception specified in a tuple did "
-                            "not raise DeprecationWarning")
+        # Catching a string is bad.
+        self.catch_fails("spam")
 
 def test_main():
     run_unittest(ExceptionClassTests, UsageTests)

Modified: python/branches/p3yk-noslice/Lib/test/test_pkg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pkg.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pkg.py	Wed Jul 11 15:40:56 2007
@@ -120,9 +120,6 @@
 """
 import t3.sub.subsub
 print(t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__)
-reload(t3)
-reload(t3.sub)
-reload(t3.sub.subsub)
 """),
 
     ("t4", [

Deleted: /python/branches/p3yk-noslice/Lib/test/test_popen2.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_popen2.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,78 +0,0 @@
-#! /usr/bin/env python
-"""Test script for popen2.py
-   Christian Tismer
-"""
-
-import os
-import sys
-from test.test_support import TestSkipped, reap_children
-
-# popen2 contains its own testing routine
-# which is especially useful to see if open files
-# like stdin can be read successfully by a forked
-# subprocess.
-
-def main():
-    print("Test popen2 module:")
-    if (sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos') \
-           and __name__ != '__main__':
-        #  Locks get messed up or something.  Generally we're supposed
-        #  to avoid mixing "posix" fork & exec with native threads, and
-        #  they may be right about that after all.
-        raise TestSkipped, "popen2() doesn't work during import on " + sys.platform
-    try:
-        from os import popen
-    except ImportError:
-        # if we don't have os.popen, check that
-        # we have os.fork.  if not, skip the test
-        # (by raising an ImportError)
-        from os import fork
-    import popen2
-    popen2._test()
-
-
-def _test():
-    # same test as popen2._test(), but using the os.popen*() API
-    print("Testing os module:")
-    import popen2
-    # When the test runs, there shouldn't be any open pipes
-    popen2._cleanup()
-    assert not popen2._active, "Active pipes when test starts " + repr([c.cmd for c in popen2._active])
-    cmd  = "cat"
-    teststr = "ab cd\n"
-    if os.name == "nt":
-        cmd = "more"
-    # "more" doesn't act the same way across Windows flavors,
-    # sometimes adding an extra newline at the start or the
-    # end.  So we strip whitespace off both ends for comparison.
-    expected = teststr.strip()
-    print("testing popen2...")
-    w, r = os.popen2(cmd)
-    w.write(teststr)
-    w.close()
-    got = r.read()
-    if got.strip() != expected:
-        raise ValueError("wrote %r read %r" % (teststr, got))
-    print("testing popen3...")
-    try:
-        w, r, e = os.popen3([cmd])
-    except:
-        w, r, e = os.popen3(cmd)
-    w.write(teststr)
-    w.close()
-    got = r.read()
-    if got.strip() != expected:
-        raise ValueError("wrote %r read %r" % (teststr, got))
-    got = e.read()
-    if got:
-        raise ValueError("unexpected %r on stderr" % (got,))
-    for inst in popen2._active[:]:
-        inst.wait()
-    popen2._cleanup()
-    if popen2._active:
-        raise ValueError("_active not empty")
-    print("All OK")
-
-main()
-_test()
-reap_children()

Modified: python/branches/p3yk-noslice/Lib/test/test_posixpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_posixpath.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_posixpath.py	Wed Jul 11 15:40:56 2007
@@ -2,15 +2,29 @@
 from test import test_support
 
 import posixpath, os
-from posixpath import realpath, abspath, join, dirname, basename
+from posixpath import realpath, abspath, join, dirname, basename, relpath
 
 # An absolute path to a temporary filename for testing. We can't rely on TESTFN
 # being an absolute path, so we need this.
 
 ABSTFN = abspath(test_support.TESTFN)
 
+def safe_rmdir(dirname):
+    try:
+        os.rmdir(dirname)
+    except OSError:
+        pass
+
 class PosixPathTest(unittest.TestCase):
 
+    def setUp(self):
+        self.tearDown()
+
+    def tearDown(self):
+        for suffix in ["", "1", "2"]:
+            test_support.unlink(test_support.TESTFN + suffix)
+            safe_rmdir(test_support.TESTFN + suffix)
+
     def assertIs(self, a, b):
         self.assert_(a is b)
 
@@ -43,15 +57,27 @@
 
         self.assertRaises(TypeError, posixpath.split)
 
-    def test_splitext(self):
-        self.assertEqual(posixpath.splitext("foo.ext"), ("foo", ".ext"))
-        self.assertEqual(posixpath.splitext("/foo/foo.ext"), ("/foo/foo", ".ext"))
-        self.assertEqual(posixpath.splitext(".ext"), ("", ".ext"))
-        self.assertEqual(posixpath.splitext("/foo.ext/foo"), ("/foo.ext/foo", ""))
-        self.assertEqual(posixpath.splitext("foo.ext/"), ("foo.ext/", ""))
-        self.assertEqual(posixpath.splitext(""), ("", ""))
-        self.assertEqual(posixpath.splitext("foo.bar.ext"), ("foo.bar", ".ext"))
+    def splitextTest(self, path, filename, ext):
+        self.assertEqual(posixpath.splitext(path), (filename, ext))
+        self.assertEqual(posixpath.splitext("/" + path), ("/" + filename, ext))
+        self.assertEqual(posixpath.splitext("abc/" + path), ("abc/" + filename, ext))
+        self.assertEqual(posixpath.splitext("abc.def/" + path), ("abc.def/" + filename, ext))
+        self.assertEqual(posixpath.splitext("/abc.def/" + path), ("/abc.def/" + filename, ext))
+        self.assertEqual(posixpath.splitext(path + "/"), (filename + ext + "/", ""))
 
+    def test_splitext(self):
+        self.splitextTest("foo.bar", "foo", ".bar")
+        self.splitextTest("foo.boo.bar", "foo.boo", ".bar")
+        self.splitextTest("foo.boo.biff.bar", "foo.boo.biff", ".bar")
+        self.splitextTest(".csh.rc", ".csh", ".rc")
+        self.splitextTest("nodots", "nodots", "")
+        self.splitextTest(".cshrc", ".cshrc", "")
+        self.splitextTest("...manydots", "...manydots", "")
+        self.splitextTest("...manydots.ext", "...manydots", ".ext")
+        self.splitextTest(".", ".", "")
+        self.splitextTest("..", "..", "")
+        self.splitextTest("........", "........", "")
+        self.splitextTest("", "", "")
         self.assertRaises(TypeError, posixpath.splitext)
 
     def test_isabs(self):
@@ -104,6 +130,16 @@
             "/home/swen/spam"
         )
 
+        testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd', 'aXc', 'abd', 'ab', 'aX', 'abcX']
+        for s1 in testlist:
+            for s2 in testlist:
+                p = posixpath.commonprefix([s1, s2])
+                self.assert_(s1.startswith(p))
+                self.assert_(s2.startswith(p))
+                if s1 != s2:
+                    n = len(p)
+                    self.assertNotEqual(s1[n:n+1], s2[n:n+1])
+
     def test_getsize(self):
         f = open(test_support.TESTFN, "wb")
         try:
@@ -113,7 +149,6 @@
         finally:
             if not f.closed:
                 f.close()
-            os.remove(test_support.TESTFN)
 
     def test_time(self):
         f = open(test_support.TESTFN, "wb")
@@ -135,7 +170,6 @@
         finally:
             if not f.closed:
                 f.close()
-            os.remove(test_support.TESTFN)
 
     def test_islink(self):
         self.assertIs(posixpath.islink(test_support.TESTFN + "1"), False)
@@ -154,14 +188,6 @@
         finally:
             if not f.close():
                 f.close()
-            try:
-                os.remove(test_support.TESTFN + "1")
-            except os.error:
-                pass
-            try:
-                os.remove(test_support.TESTFN + "2")
-            except os.error:
-                pass
 
         self.assertRaises(TypeError, posixpath.islink)
 
@@ -176,10 +202,6 @@
         finally:
             if not f.close():
                 f.close()
-            try:
-                os.remove(test_support.TESTFN)
-            except os.error:
-                pass
 
         self.assertRaises(TypeError, posixpath.exists)
 
@@ -197,14 +219,6 @@
         finally:
             if not f.close():
                 f.close()
-            try:
-                os.remove(test_support.TESTFN)
-            except os.error:
-                pass
-            try:
-                os.rmdir(test_support.TESTFN)
-            except os.error:
-                pass
 
         self.assertRaises(TypeError, posixpath.isdir)
 
@@ -222,67 +236,51 @@
         finally:
             if not f.close():
                 f.close()
-            try:
-                os.remove(test_support.TESTFN)
-            except os.error:
-                pass
-            try:
-                os.rmdir(test_support.TESTFN)
-            except os.error:
-                pass
 
         self.assertRaises(TypeError, posixpath.isdir)
 
-        def test_samefile(self):
-            f = open(test_support.TESTFN + "1", "wb")
-            try:
-                f.write("foo")
-                f.close()
+    def test_samefile(self):
+        f = open(test_support.TESTFN + "1", "wb")
+        try:
+            f.write("foo")
+            f.close()
+            self.assertIs(
+                posixpath.samefile(
+                    test_support.TESTFN + "1",
+                    test_support.TESTFN + "1"
+                ),
+                True
+            )
+            # If we don't have links, assume that os.stat doesn't return resonable
+            # inode information and thus, that samefile() doesn't work
+            if hasattr(os, "symlink"):
+                os.symlink(
+                    test_support.TESTFN + "1",
+                    test_support.TESTFN + "2"
+                )
                 self.assertIs(
                     posixpath.samefile(
                         test_support.TESTFN + "1",
-                        test_support.TESTFN + "1"
+                        test_support.TESTFN + "2"
                     ),
                     True
                 )
-                # If we don't have links, assume that os.stat doesn't return resonable
-                # inode information and thus, that samefile() doesn't work
-                if hasattr(os, "symlink"):
-                    os.symlink(
+                os.remove(test_support.TESTFN + "2")
+                f = open(test_support.TESTFN + "2", "wb")
+                f.write("bar")
+                f.close()
+                self.assertIs(
+                    posixpath.samefile(
                         test_support.TESTFN + "1",
                         test_support.TESTFN + "2"
-                    )
-                    self.assertIs(
-                        posixpath.samefile(
-                            test_support.TESTFN + "1",
-                            test_support.TESTFN + "2"
-                        ),
-                        True
-                    )
-                    os.remove(test_support.TESTFN + "2")
-                    f = open(test_support.TESTFN + "2", "wb")
-                    f.write("bar")
-                    f.close()
-                    self.assertIs(
-                        posixpath.samefile(
-                            test_support.TESTFN + "1",
-                            test_support.TESTFN + "2"
-                        ),
-                        False
-                    )
-            finally:
-                if not f.close():
-                    f.close()
-                try:
-                    os.remove(test_support.TESTFN + "1")
-                except os.error:
-                    pass
-                try:
-                    os.remove(test_support.TESTFN + "2")
-                except os.error:
-                    pass
+                    ),
+                    False
+                )
+        finally:
+            if not f.close():
+                f.close()
 
-            self.assertRaises(TypeError, posixpath.samefile)
+        self.assertRaises(TypeError, posixpath.samefile)
 
     def test_samestat(self):
         f = open(test_support.TESTFN + "1", "wb")
@@ -322,14 +320,6 @@
         finally:
             if not f.close():
                 f.close()
-            try:
-                os.remove(test_support.TESTFN + "1")
-            except os.error:
-                pass
-            try:
-                os.remove(test_support.TESTFN + "2")
-            except os.error:
-                pass
 
         self.assertRaises(TypeError, posixpath.samestat)
 
@@ -409,7 +399,7 @@
                 os.symlink(ABSTFN+"1", ABSTFN)
                 self.assertEqual(realpath(ABSTFN), ABSTFN+"1")
             finally:
-                self.safe_remove(ABSTFN)
+                test_support.unlink(ABSTFN)
 
         def test_realpath_symlink_loops(self):
             # Bug #930024, return the path unchanged if we get into an infinite
@@ -429,9 +419,9 @@
                 self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
             finally:
                 os.chdir(old_path)
-                self.safe_remove(ABSTFN)
-                self.safe_remove(ABSTFN+"1")
-                self.safe_remove(ABSTFN+"2")
+                test_support.unlink(ABSTFN)
+                test_support.unlink(ABSTFN+"1")
+                test_support.unlink(ABSTFN+"2")
 
         def test_realpath_resolve_parents(self):
             # We also need to resolve any symlinks in the parents of a relative
@@ -448,9 +438,9 @@
                 self.assertEqual(realpath("a"), ABSTFN + "/y/a")
             finally:
                 os.chdir(old_path)
-                self.safe_remove(ABSTFN + "/k")
-                self.safe_rmdir(ABSTFN + "/y")
-                self.safe_rmdir(ABSTFN)
+                test_support.unlink(ABSTFN + "/k")
+                safe_rmdir(ABSTFN + "/y")
+                safe_rmdir(ABSTFN)
 
         def test_realpath_resolve_before_normalizing(self):
             # Bug #990669: Symbolic links should be resolved before we
@@ -474,10 +464,10 @@
                 self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k")
             finally:
                 os.chdir(old_path)
-                self.safe_remove(ABSTFN + "/link-y")
-                self.safe_rmdir(ABSTFN + "/k/y")
-                self.safe_rmdir(ABSTFN + "/k")
-                self.safe_rmdir(ABSTFN)
+                test_support.unlink(ABSTFN + "/link-y")
+                safe_rmdir(ABSTFN + "/k/y")
+                safe_rmdir(ABSTFN + "/k")
+                safe_rmdir(ABSTFN)
 
         def test_realpath_resolve_first(self):
             # Bug #1213894: The first component of the path, if not absolute,
@@ -495,20 +485,24 @@
                 self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
             finally:
                 os.chdir(old_path)
-                self.safe_remove(ABSTFN + "link")
-                self.safe_rmdir(ABSTFN + "/k")
-                self.safe_rmdir(ABSTFN)
-
-        # Convenience functions for removing temporary files.
-        def pass_os_error(self, func, filename):
-            try: func(filename)
-            except OSError: pass
+                test_support.unlink(ABSTFN + "link")
+                safe_rmdir(ABSTFN + "/k")
+                safe_rmdir(ABSTFN)
 
-        def safe_remove(self, filename):
-            self.pass_os_error(os.remove, filename)
-
-        def safe_rmdir(self, dirname):
-            self.pass_os_error(os.rmdir, dirname)
+    def test_relpath(self):
+        (real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar")
+        try:
+            curdir = os.path.split(os.getcwd())[-1]
+            self.assertRaises(ValueError, posixpath.relpath, "")
+            self.assertEqual(posixpath.relpath("a"), "a")
+            self.assertEqual(posixpath.relpath(posixpath.abspath("a")), "a")
+            self.assertEqual(posixpath.relpath("a/b"), "a/b")
+            self.assertEqual(posixpath.relpath("../a/b"), "../a/b")
+            self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a")
+            self.assertEqual(posixpath.relpath("a/b", "../c"), "../"+curdir+"/a/b")
+            self.assertEqual(posixpath.relpath("a", "b/c"), "../../a")
+        finally:
+            os.getcwd = real_getcwd
 
 def test_main():
     test_support.run_unittest(PosixPathTest)

Modified: python/branches/p3yk-noslice/Lib/test/test_pow.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pow.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pow.py	Wed Jul 11 15:40:56 2007
@@ -14,12 +14,12 @@
                 self.assertEquals(pow(type(i), 3), i*i*i)
 
             pow2 = 1
-            for i in range(0,31):
+            for i in range(0, 31):
                 self.assertEquals(pow(2, i), pow2)
                 if i != 30 : pow2 = pow2*2
 
             for othertype in int, int:
-                for i in range(-10, 0) + range(1, 10):
+                for i in list(range(-10, 0)) + list(range(1, 10)):
                     ii = type(i)
                     for j in range(1, 11):
                         jj = -othertype(j)

Modified: python/branches/p3yk-noslice/Lib/test/test_pprint.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pprint.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pprint.py	Wed Jul 11 15:40:56 2007
@@ -33,8 +33,8 @@
 class QueryTestCase(unittest.TestCase):
 
     def setUp(self):
-        self.a = range(100)
-        self.b = range(200)
+        self.a = list(range(100))
+        self.b = list(range(200))
         self.a[-12] = self.b
 
     def test_basic(self):

Modified: python/branches/p3yk-noslice/Lib/test/test_profilehooks.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_profilehooks.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_profilehooks.py	Wed Jul 11 15:40:56 2007
@@ -324,7 +324,7 @@
     if hasattr(function, "f_code"):
         code = function.f_code
     else:
-        code = function.func_code
+        code = function.__code__
     return code.co_firstlineno, code.co_name
 
 

Modified: python/branches/p3yk-noslice/Lib/test/test_pty.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pty.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pty.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,11 @@
-import pty, os, sys, signal
-from test.test_support import verbose, TestFailed, TestSkipped
+import errno
+import fcntl
+import pty
+import os
+import sys
+import signal
+from test.test_support import verbose, TestSkipped, run_unittest
+import unittest
 
 TEST_STRING_1 = "I wish to buy a fish license.\n"
 TEST_STRING_2 = "For my pet fish, Eric.\n"
@@ -11,6 +17,7 @@
     def debug(msg):
         pass
 
+
 def normalize_output(data):
     # Some operating systems do conversions on newline.  We could possibly
     # fix that by doing the appropriate termios.tcsetattr()s.  I couldn't
@@ -32,116 +39,158 @@
 
     return data
 
+
 # Marginal testing of pty suite. Cannot do extensive 'do or fail' testing
 # because pty code is not too portable.
+# XXX(nnorwitz):  these tests leak fds when there is an error.
+class PtyTest(unittest.TestCase):
+    def setUp(self):
+        # isatty() and close() can hang on some platforms.  Set an alarm
+        # before running the test to make sure we don't hang forever.
+        self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig)
+        signal.alarm(10)
+
+    def tearDown(self):
+        # remove alarm, restore old alarm handler
+        signal.alarm(0)
+        signal.signal(signal.SIGALRM, self.old_alarm)
+
+    def handle_sig(self, sig, frame):
+        self.fail("isatty hung")
+
+    def test_basic(self):
+        try:
+            debug("Calling master_open()")
+            master_fd, slave_name = pty.master_open()
+            debug("Got master_fd '%d', slave_name '%s'" %
+                  (master_fd, slave_name))
+            debug("Calling slave_open(%r)" % (slave_name,))
+            slave_fd = pty.slave_open(slave_name)
+            debug("Got slave_fd '%d'" % slave_fd)
+        except OSError:
+            # " An optional feature could not be imported " ... ?
+            raise TestSkipped, "Pseudo-terminals (seemingly) not functional."
+
+        self.assertTrue(os.isatty(slave_fd), 'slave_fd is not a tty')
+
+        # Solaris requires reading the fd before anything is returned.
+        # My guess is that since we open and close the slave fd
+        # in master_open(), we need to read the EOF.
+
+        # Ensure the fd is non-blocking in case there's nothing to read.
+        orig_flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
+        fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
+        try:
+            s1 = os.read(master_fd, 1024)
+            self.assertEquals('', s1)
+        except OSError as e:
+            if e.errno != errno.EAGAIN:
+                raise
+        # Restore the original flags.
+        fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags)
+
+        debug("Writing to slave_fd")
+        os.write(slave_fd, TEST_STRING_1)
+        s1 = os.read(master_fd, 1024)
+        self.assertEquals('I wish to buy a fish license.\n',
+                          normalize_output(s1))
+
+        debug("Writing chunked output")
+        os.write(slave_fd, TEST_STRING_2[:5])
+        os.write(slave_fd, TEST_STRING_2[5:])
+        s2 = os.read(master_fd, 1024)
+        self.assertEquals('For my pet fish, Eric.\n', normalize_output(s2))
+
+        os.close(slave_fd)
+        os.close(master_fd)
+
+
+    def test_fork(self):
+        debug("calling pty.fork()")
+        pid, master_fd = pty.fork()
+        if pid == pty.CHILD:
+            # stdout should be connected to a tty.
+            if not os.isatty(1):
+                debug("Child's fd 1 is not a tty?!")
+                os._exit(3)
+
+            # After pty.fork(), the child should already be a session leader.
+            # (on those systems that have that concept.)
+            debug("In child, calling os.setsid()")
+            try:
+                os.setsid()
+            except OSError:
+                # Good, we already were session leader
+                debug("Good: OSError was raised.")
+                pass
+            except AttributeError:
+                # Have pty, but not setsid()?
+                debug("No setsid() available?")
+                pass
+            except:
+                # We don't want this error to propagate, escaping the call to
+                # os._exit() and causing very peculiar behavior in the calling
+                # regrtest.py !
+                # Note: could add traceback printing here.
+                debug("An unexpected error was raised.")
+                os._exit(1)
+            else:
+                debug("os.setsid() succeeded! (bad!)")
+                os._exit(2)
+            os._exit(4)
+        else:
+            debug("Waiting for child (%d) to finish." % pid)
+            # In verbose mode, we have to consume the debug output from the
+            # child or the child will block, causing this test to hang in the
+            # parent's waitpid() call.  The child blocks after a
+            # platform-dependent amount of data is written to its fd.  On
+            # Linux 2.6, it's 4000 bytes and the child won't block, but on OS
+            # X even the small writes in the child above will block it.  Also
+            # on Linux, the read() will throw an OSError (input/output error)
+            # when it tries to read past the end of the buffer but the child's
+            # already exited, so catch and discard those exceptions.  It's not
+            # worth checking for EIO.
+            while True:
+                try:
+                    data = os.read(master_fd, 80)
+                except OSError:
+                    break
+                if not data:
+                    break
+                sys.stdout.write(data.replace('\r\n', '\n'))
+
+            ##line = os.read(master_fd, 80)
+            ##lines = line.replace('\r\n', '\n').split('\n')
+            ##if False and lines != ['In child, calling os.setsid()',
+            ##             'Good: OSError was raised.', '']:
+            ##    raise TestFailed("Unexpected output from child: %r" % line)
+
+            (pid, status) = os.waitpid(pid, 0)
+            res = status >> 8
+            debug("Child (%d) exited with status %d (%d)." % (pid, res, status))
+            if res == 1:
+                self.fail("Child raised an unexpected exception in os.setsid()")
+            elif res == 2:
+                self.fail("pty.fork() failed to make child a session leader.")
+            elif res == 3:
+                self.fail("Child spawned by pty.fork() did not have a tty as stdout")
+            elif res != 4:
+                self.fail("pty.fork() failed for unknown reasons.")
+
+            ##debug("Reading from master_fd now that the child has exited")
+            ##try:
+            ##    s1 = os.read(master_fd, 1024)
+            ##except os.error:
+            ##    pass
+            ##else:
+            ##    raise TestFailed("Read from master_fd did not raise exception")
+
+        os.close(master_fd)
 
-def test_basic_pty():
-    try:
-        debug("Calling master_open()")
-        master_fd, slave_name = pty.master_open()
-        debug("Got master_fd '%d', slave_name '%s'"%(master_fd, slave_name))
-        debug("Calling slave_open(%r)"%(slave_name,))
-        slave_fd = pty.slave_open(slave_name)
-        debug("Got slave_fd '%d'"%slave_fd)
-    except OSError:
-        # " An optional feature could not be imported " ... ?
-        raise TestSkipped, "Pseudo-terminals (seemingly) not functional."
-
-    if not os.isatty(slave_fd):
-        raise TestFailed, "slave_fd is not a tty"
-
-    debug("Writing to slave_fd")
-    os.write(slave_fd, TEST_STRING_1)
-    s1 = os.read(master_fd, 1024)
-    sys.stdout.write(normalize_output(s1))
-
-    debug("Writing chunked output")
-    os.write(slave_fd, TEST_STRING_2[:5])
-    os.write(slave_fd, TEST_STRING_2[5:])
-    s2 = os.read(master_fd, 1024)
-    sys.stdout.write(normalize_output(s2))
-
-    os.close(slave_fd)
-    os.close(master_fd)
-
-def handle_sig(sig, frame):
-    raise TestFailed, "isatty hung"
-
-# isatty() and close() can hang on some platforms
-# set an alarm before running the test to make sure we don't hang forever
-old_alarm = signal.signal(signal.SIGALRM, handle_sig)
-signal.alarm(10)
-
-try:
-    test_basic_pty()
-finally:
-    # remove alarm, restore old alarm handler
-    signal.alarm(0)
-    signal.signal(signal.SIGALRM, old_alarm)
-
-# basic pty passed.
-
-debug("calling pty.fork()")
-pid, master_fd = pty.fork()
-if pid == pty.CHILD:
-    # stdout should be connected to a tty.
-    if not os.isatty(1):
-        debug("Child's fd 1 is not a tty?!")
-        os._exit(3)
-
-    # After pty.fork(), the child should already be a session leader.
-    # (on those systems that have that concept.)
-    debug("In child, calling os.setsid()")
-    try:
-        os.setsid()
-    except OSError:
-        # Good, we already were session leader
-        debug("Good: OSError was raised.")
-        pass
-    except AttributeError:
-        # Have pty, but not setsid() ?
-        debug("No setsid() available ?")
-        pass
-    except:
-        # We don't want this error to propagate, escaping the call to
-        # os._exit() and causing very peculiar behavior in the calling
-        # regrtest.py !
-        # Note: could add traceback printing here.
-        debug("An unexpected error was raised.")
-        os._exit(1)
-    else:
-        debug("os.setsid() succeeded! (bad!)")
-        os._exit(2)
-    os._exit(4)
-else:
-    debug("Waiting for child (%d) to finish."%pid)
-    ##line = os.read(master_fd, 80)
-    ##lines = line.replace('\r\n', '\n').split('\n')
-    ##if False and lines != ['In child, calling os.setsid()',
-    ##             'Good: OSError was raised.', '']:
-    ##    raise TestFailed("Unexpected output from child: %r" % line)
-
-    (pid, status) = os.waitpid(pid, 0)
-    res = status >> 8
-    debug("Child (%d) exited with status %d (%d)."%(pid, res, status))
-    if res == 1:
-        raise TestFailed, "Child raised an unexpected exception in os.setsid()"
-    elif res == 2:
-        raise TestFailed, "pty.fork() failed to make child a session leader."
-    elif res == 3:
-        raise TestFailed, "Child spawned by pty.fork() did not have a tty as stdout"
-    elif res != 4:
-        raise TestFailed, "pty.fork() failed for unknown reasons."
-
-    ##debug("Reading from master_fd now that the child has exited")
-    ##try:
-    ##    s1 = os.read(master_fd, 1024)
-    ##except os.error:
-    ##    pass
-    ##else:
-    ##    raise TestFailed("Read from master_fd did not raise exception")
-
+        # pty.fork() passed.
 
-os.close(master_fd)
+def test_main(verbose=None):
+    run_unittest(PtyTest)
 
-# pty.fork() passed.
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_pwd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pwd.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pwd.py	Wed Jul 11 15:40:56 2007
@@ -59,8 +59,8 @@
         namei = 0
         fakename = allnames[namei]
         while fakename in bynames:
-            chars = map(None, fakename)
-            for i in xrange(len(chars)):
+            chars = list(fakename)
+            for i in range(len(chars)):
                 if chars[i] == 'z':
                     chars[i] = 'A'
                     break
@@ -76,7 +76,7 @@
                 except IndexError:
                     # should never happen... if so, just forget it
                     break
-            fakename = ''.join(map(None, chars))
+            fakename = ''.join(chars)
 
         self.assertRaises(KeyError, pwd.getpwnam, fakename)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_pyclbr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pyclbr.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pyclbr.py	Wed Jul 11 15:40:56 2007
@@ -4,17 +4,13 @@
 '''
 from test.test_support import run_unittest
 import unittest, sys
-from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
+from types import FunctionType, MethodType, BuiltinFunctionType
 import pyclbr
 from unittest import TestCase
 
 StaticMethodType = type(staticmethod(lambda: None))
 ClassMethodType = type(classmethod(lambda c: None))
 
-# This next line triggers an error on old versions of pyclbr.
-
-from commands import getstatus
-
 # Here we test the python class browser code.
 #
 # The main function in this suite, 'testModule', compares the output
@@ -99,7 +95,7 @@
                     continue   # skip functions that came from somewhere else
                 self.assertEquals(py_item.__module__, value.module)
             else:
-                self.failUnless(isinstance(py_item, (ClassType, type)))
+                self.failUnless(isinstance(py_item, type))
                 if py_item.__module__ != moduleName:
                     continue   # skip classes that came from somewhere else
 
@@ -137,14 +133,14 @@
 
         # Now check for missing stuff.
         def defined_in(item, module):
-            if isinstance(item, ClassType):
+            if isinstance(item, type):
                 return item.__module__ == module.__name__
             if isinstance(item, FunctionType):
-                return item.func_globals is module.__dict__
+                return item.__globals__ is module.__dict__
             return False
         for name in dir(module):
             item = getattr(module, name)
-            if isinstance(item,  (ClassType, FunctionType)):
+            if isinstance(item,  (type, FunctionType)):
                 if defined_in(item, module):
                     self.assertHaskey(dict, name, ignore)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_pyexpat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pyexpat.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_pyexpat.py	Wed Jul 11 15:40:56 2007
@@ -1,108 +1,40 @@
-# Very simple test - Parse a file and print what happens
-
 # XXX TypeErrors on calling handlers, or on bad return values from a
 # handler, are obscure and unhelpful.
 
+import StringIO
+import unittest
+
 import pyexpat
 from xml.parsers import expat
 
-from test.test_support import sortdict, TestFailed
+from test.test_support import sortdict, run_unittest
 
-class Outputter:
-    def StartElementHandler(self, name, attrs):
-        print('Start element:\n\t' + repr(name), sortdict(attrs))
 
-    def EndElementHandler(self, name):
-        print('End element:\n\t' + repr(name))
+class SetAttributeTest(unittest.TestCase):
+    def setUp(self):
+        self.parser = expat.ParserCreate(namespace_separator='!')
+        self.set_get_pairs = [
+            [0, 0],
+            [1, 1],
+            [2, 1],
+            [0, 0],
+            ]
+
+    def test_returns_unicode(self):
+        for x, y in self.set_get_pairs:
+            self.parser.returns_unicode = x
+            self.assertEquals(self.parser.returns_unicode, y)
+
+    def test_ordered_attributes(self):
+        for x, y in self.set_get_pairs:
+            self.parser.ordered_attributes = x
+            self.assertEquals(self.parser.ordered_attributes, y)
+
+    def test_specified_attributes(self):
+        for x, y in self.set_get_pairs:
+            self.parser.specified_attributes = x
+            self.assertEquals(self.parser.specified_attributes, y)
 
-    def CharacterDataHandler(self, data):
-        data = data.strip()
-        if data:
-            print('Character data:')
-            print('\t' + repr(data))
-
-    def ProcessingInstructionHandler(self, target, data):
-        print('PI:\n\t' + repr(target), repr(data))
-
-    def StartNamespaceDeclHandler(self, prefix, uri):
-        print('NS decl:\n\t' + repr(prefix), repr(uri))
-
-    def EndNamespaceDeclHandler(self, prefix):
-        print('End of NS decl:\n\t' + repr(prefix))
-
-    def StartCdataSectionHandler(self):
-        print('Start of CDATA section')
-
-    def EndCdataSectionHandler(self):
-        print('End of CDATA section')
-
-    def CommentHandler(self, text):
-        print('Comment:\n\t' + repr(text))
-
-    def NotationDeclHandler(self, *args):
-        name, base, sysid, pubid = args
-        print('Notation declared:', args)
-
-    def UnparsedEntityDeclHandler(self, *args):
-        entityName, base, systemId, publicId, notationName = args
-        print('Unparsed entity decl:\n\t' + str(args))
-
-    def NotStandaloneHandler(self, userData):
-        print('Not standalone')
-        return 1
-
-    def ExternalEntityRefHandler(self, *args):
-        context, base, sysId, pubId = args
-        print('External entity ref:', args[1:])
-        return 1
-
-    def DefaultHandler(self, userData):
-        pass
-
-    def DefaultHandlerExpand(self, userData):
-        pass
-
-
-def confirm(ok):
-    if ok:
-        print("OK.")
-    else:
-        print("Not OK.")
-
-out = Outputter()
-parser = expat.ParserCreate(namespace_separator='!')
-
-# Test getting/setting returns_unicode
-parser.returns_unicode = 0; confirm(parser.returns_unicode == 0)
-parser.returns_unicode = 1; confirm(parser.returns_unicode == 1)
-parser.returns_unicode = 2; confirm(parser.returns_unicode == 1)
-parser.returns_unicode = 0; confirm(parser.returns_unicode == 0)
-
-# Test getting/setting ordered_attributes
-parser.ordered_attributes = 0; confirm(parser.ordered_attributes == 0)
-parser.ordered_attributes = 1; confirm(parser.ordered_attributes == 1)
-parser.ordered_attributes = 2; confirm(parser.ordered_attributes == 1)
-parser.ordered_attributes = 0; confirm(parser.ordered_attributes == 0)
-
-# Test getting/setting specified_attributes
-parser.specified_attributes = 0; confirm(parser.specified_attributes == 0)
-parser.specified_attributes = 1; confirm(parser.specified_attributes == 1)
-parser.specified_attributes = 2; confirm(parser.specified_attributes == 1)
-parser.specified_attributes = 0; confirm(parser.specified_attributes == 0)
-
-HANDLER_NAMES = [
-    'StartElementHandler', 'EndElementHandler',
-    'CharacterDataHandler', 'ProcessingInstructionHandler',
-    'UnparsedEntityDeclHandler', 'NotationDeclHandler',
-    'StartNamespaceDeclHandler', 'EndNamespaceDeclHandler',
-    'CommentHandler', 'StartCdataSectionHandler',
-    'EndCdataSectionHandler',
-    'DefaultHandler', 'DefaultHandlerExpand',
-    #'NotStandaloneHandler',
-    'ExternalEntityRefHandler'
-    ]
-for name in HANDLER_NAMES:
-    setattr(parser, name, getattr(out, name))
 
 data = '''\
 <?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
@@ -126,108 +58,228 @@
 </root>
 '''
 
-# Produce UTF-8 output
-parser.returns_unicode = 0
-try:
-    parser.Parse(data, 1)
-except expat.error:
-    print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
-    print('** Line', parser.ErrorLineNumber)
-    print('** Column', parser.ErrorColumnNumber)
-    print('** Byte', parser.ErrorByteIndex)
-
-# Try the parse again, this time producing Unicode output
-parser = expat.ParserCreate(namespace_separator='!')
-parser.returns_unicode = 1
-
-for name in HANDLER_NAMES:
-    setattr(parser, name, getattr(out, name))
-try:
-    parser.Parse(data, 1)
-except expat.error:
-    print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
-    print('** Line', parser.ErrorLineNumber)
-    print('** Column', parser.ErrorColumnNumber)
-    print('** Byte', parser.ErrorByteIndex)
-
-# Try parsing a file
-parser = expat.ParserCreate(namespace_separator='!')
-parser.returns_unicode = 1
 
-for name in HANDLER_NAMES:
-    setattr(parser, name, getattr(out, name))
-import StringIO
-file = StringIO.StringIO(data)
-try:
-    parser.ParseFile(file)
-except expat.error:
-    print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
-    print('** Line', parser.ErrorLineNumber)
-    print('** Column', parser.ErrorColumnNumber)
-    print('** Byte', parser.ErrorByteIndex)
-
-
-# Tests that make sure we get errors when the namespace_separator value
-# is illegal, and that we don't for good values:
-print()
-print("Testing constructor for proper handling of namespace_separator values:")
-expat.ParserCreate()
-expat.ParserCreate(namespace_separator=None)
-expat.ParserCreate(namespace_separator=' ')
-print("Legal values tested o.k.")
-try:
-    expat.ParserCreate(namespace_separator=42)
-except TypeError as e:
-    print("Caught expected TypeError:")
-    print(e)
-else:
-    print("Failed to catch expected TypeError.")
-
-try:
-    expat.ParserCreate(namespace_separator='too long')
-except ValueError as e:
-    print("Caught expected ValueError:")
-    print(e)
-else:
-    print("Failed to catch expected ValueError.")
-
-# ParserCreate() needs to accept a namespace_separator of zero length
-# to satisfy the requirements of RDF applications that are required
-# to simply glue together the namespace URI and the localname.  Though
-# considered a wart of the RDF specifications, it needs to be supported.
-#
-# See XML-SIG mailing list thread starting with
-# http://mail.python.org/pipermail/xml-sig/2001-April/005202.html
-#
-expat.ParserCreate(namespace_separator='') # too short
-
-# Test the interning machinery.
-p = expat.ParserCreate()
-L = []
-def collector(name, *args):
-    L.append(name)
-p.StartElementHandler = collector
-p.EndElementHandler = collector
-p.Parse("<e> <e/> <e></e> </e>", 1)
-tag = L[0]
-if len(L) != 6:
-    print("L should only contain 6 entries; found", len(L))
-for entry in L:
-    if tag is not entry:
-        print("expected L to contain many references to the same string", end=' ')
-        print("(it didn't)")
-        print("L =", repr(L))
-        break
+# Produce UTF-8 output
+class ParseTest(unittest.TestCase):
+    class Outputter:
+        def __init__(self):
+            self.out = []
+
+        def StartElementHandler(self, name, attrs):
+            self.out.append('Start element: ' + repr(name) + ' ' +
+                            sortdict(attrs))
+
+        def EndElementHandler(self, name):
+            self.out.append('End element: ' + repr(name))
+
+        def CharacterDataHandler(self, data):
+            data = data.strip()
+            if data:
+                self.out.append('Character data: ' + repr(data))
+
+        def ProcessingInstructionHandler(self, target, data):
+            self.out.append('PI: ' + repr(target) + ' ' + repr(data))
+
+        def StartNamespaceDeclHandler(self, prefix, uri):
+            self.out.append('NS decl: ' + repr(prefix) + ' ' + repr(uri))
+
+        def EndNamespaceDeclHandler(self, prefix):
+            self.out.append('End of NS decl: ' + repr(prefix))
+
+        def StartCdataSectionHandler(self):
+            self.out.append('Start of CDATA section')
+
+        def EndCdataSectionHandler(self):
+            self.out.append('End of CDATA section')
+
+        def CommentHandler(self, text):
+            self.out.append('Comment: ' + repr(text))
+
+        def NotationDeclHandler(self, *args):
+            name, base, sysid, pubid = args
+            self.out.append('Notation declared: %s' %(args,))
+
+        def UnparsedEntityDeclHandler(self, *args):
+            entityName, base, systemId, publicId, notationName = args
+            self.out.append('Unparsed entity decl: %s' %(args,))
+
+        def NotStandaloneHandler(self, userData):
+            self.out.append('Not standalone')
+            return 1
+
+        def ExternalEntityRefHandler(self, *args):
+            context, base, sysId, pubId = args
+            self.out.append('External entity ref: %s' %(args[1:],))
+            return 1
+
+        def DefaultHandler(self, userData):
+            pass
+
+        def DefaultHandlerExpand(self, userData):
+            pass
+
+    handler_names = [
+        'StartElementHandler', 'EndElementHandler',
+        'CharacterDataHandler', 'ProcessingInstructionHandler',
+        'UnparsedEntityDeclHandler', 'NotationDeclHandler',
+        'StartNamespaceDeclHandler', 'EndNamespaceDeclHandler',
+        'CommentHandler', 'StartCdataSectionHandler',
+        'EndCdataSectionHandler',
+        'DefaultHandler', 'DefaultHandlerExpand',
+        #'NotStandaloneHandler',
+        'ExternalEntityRefHandler'
+        ]
+
+    def test_utf8(self):
+
+        out = self.Outputter()
+        parser = expat.ParserCreate(namespace_separator='!')
+        for name in self.handler_names:
+            setattr(parser, name, getattr(out, name))
+        parser.returns_unicode = 0
+        parser.Parse(data, 1)
+
+        # Verify output
+        op = out.out
+        self.assertEquals(op[0], 'PI: \'xml-stylesheet\' \'href="stylesheet.css"\'')
+        self.assertEquals(op[1], "Comment: ' comment data '")
+        self.assertEquals(op[2], "Notation declared: ('notation', None, 'notation.jpeg', None)")
+        self.assertEquals(op[3], "Unparsed entity decl: ('unparsed_entity', None, 'entity.file', None, 'notation')")
+        self.assertEquals(op[4], "Start element: 'root' {'attr1': 'value1', 'attr2': 'value2\\xe1\\xbd\\x80'}")
+        self.assertEquals(op[5], "NS decl: 'myns' 'http://www.python.org/namespace'")
+        self.assertEquals(op[6], "Start element: 'http://www.python.org/namespace!subelement' {}")
+        self.assertEquals(op[7], "Character data: 'Contents of subelements'")
+        self.assertEquals(op[8], "End element: 'http://www.python.org/namespace!subelement'")
+        self.assertEquals(op[9], "End of NS decl: 'myns'")
+        self.assertEquals(op[10], "Start element: 'sub2' {}")
+        self.assertEquals(op[11], 'Start of CDATA section')
+        self.assertEquals(op[12], "Character data: 'contents of CDATA section'")
+        self.assertEquals(op[13], 'End of CDATA section')
+        self.assertEquals(op[14], "End element: 'sub2'")
+        self.assertEquals(op[15], "External entity ref: (None, 'entity.file', None)")
+        self.assertEquals(op[16], "End element: 'root'")
+
+    def test_unicode(self):
+        # Try the parse again, this time producing Unicode output
+        out = self.Outputter()
+        parser = expat.ParserCreate(namespace_separator='!')
+        parser.returns_unicode = 1
+        for name in self.handler_names:
+            setattr(parser, name, getattr(out, name))
+
+        parser.Parse(data, 1)
+
+        op = out.out
+        self.assertEquals(op[0], 'PI: u\'xml-stylesheet\' u\'href="stylesheet.css"\'')
+        self.assertEquals(op[1], "Comment: u' comment data '")
+        self.assertEquals(op[2], "Notation declared: (u'notation', None, u'notation.jpeg', None)")
+        self.assertEquals(op[3], "Unparsed entity decl: (u'unparsed_entity', None, u'entity.file', None, u'notation')")
+        self.assertEquals(op[4], "Start element: u'root' {u'attr1': u'value1', u'attr2': u'value2\\u1f40'}")
+        self.assertEquals(op[5], "NS decl: u'myns' u'http://www.python.org/namespace'")
+        self.assertEquals(op[6], "Start element: u'http://www.python.org/namespace!subelement' {}")
+        self.assertEquals(op[7], "Character data: u'Contents of subelements'")
+        self.assertEquals(op[8], "End element: u'http://www.python.org/namespace!subelement'")
+        self.assertEquals(op[9], "End of NS decl: u'myns'")
+        self.assertEquals(op[10], "Start element: u'sub2' {}")
+        self.assertEquals(op[11], 'Start of CDATA section')
+        self.assertEquals(op[12], "Character data: u'contents of CDATA section'")
+        self.assertEquals(op[13], 'End of CDATA section')
+        self.assertEquals(op[14], "End element: u'sub2'")
+        self.assertEquals(op[15], "External entity ref: (None, u'entity.file', None)")
+        self.assertEquals(op[16], "End element: u'root'")
+
+    def test_parse_file(self):
+        # Try parsing a file
+        out = self.Outputter()
+        parser = expat.ParserCreate(namespace_separator='!')
+        parser.returns_unicode = 1
+        for name in self.handler_names:
+            setattr(parser, name, getattr(out, name))
+        file = StringIO.StringIO(data)
+
+        parser.ParseFile(file)
+
+        op = out.out
+        self.assertEquals(op[0], 'PI: u\'xml-stylesheet\' u\'href="stylesheet.css"\'')
+        self.assertEquals(op[1], "Comment: u' comment data '")
+        self.assertEquals(op[2], "Notation declared: (u'notation', None, u'notation.jpeg', None)")
+        self.assertEquals(op[3], "Unparsed entity decl: (u'unparsed_entity', None, u'entity.file', None, u'notation')")
+        self.assertEquals(op[4], "Start element: u'root' {u'attr1': u'value1', u'attr2': u'value2\\u1f40'}")
+        self.assertEquals(op[5], "NS decl: u'myns' u'http://www.python.org/namespace'")
+        self.assertEquals(op[6], "Start element: u'http://www.python.org/namespace!subelement' {}")
+        self.assertEquals(op[7], "Character data: u'Contents of subelements'")
+        self.assertEquals(op[8], "End element: u'http://www.python.org/namespace!subelement'")
+        self.assertEquals(op[9], "End of NS decl: u'myns'")
+        self.assertEquals(op[10], "Start element: u'sub2' {}")
+        self.assertEquals(op[11], 'Start of CDATA section')
+        self.assertEquals(op[12], "Character data: u'contents of CDATA section'")
+        self.assertEquals(op[13], 'End of CDATA section')
+        self.assertEquals(op[14], "End element: u'sub2'")
+        self.assertEquals(op[15], "External entity ref: (None, u'entity.file', None)")
+        self.assertEquals(op[16], "End element: u'root'")
+
+
+class NamespaceSeparatorTest(unittest.TestCase):
+    def test_legal(self):
+        # Tests that make sure we get errors when the namespace_separator value
+        # is illegal, and that we don't for good values:
+        expat.ParserCreate()
+        expat.ParserCreate(namespace_separator=None)
+        expat.ParserCreate(namespace_separator=' ')
+
+    def test_illegal(self):
+        try:
+            expat.ParserCreate(namespace_separator=42)
+            self.fail()
+        except TypeError as e:
+            self.assertEquals(str(e),
+                'ParserCreate() argument 2 must be string or None, not int')
+
+        try:
+            expat.ParserCreate(namespace_separator='too long')
+            self.fail()
+        except ValueError as e:
+            self.assertEquals(str(e),
+                'namespace_separator must be at most one character, omitted, or None')
+
+    def test_zero_length(self):
+        # ParserCreate() needs to accept a namespace_separator of zero length
+        # to satisfy the requirements of RDF applications that are required
+        # to simply glue together the namespace URI and the localname.  Though
+        # considered a wart of the RDF specifications, it needs to be supported.
+        #
+        # See XML-SIG mailing list thread starting with
+        # http://mail.python.org/pipermail/xml-sig/2001-April/005202.html
+        #
+        expat.ParserCreate(namespace_separator='') # too short
+
+
+class InterningTest(unittest.TestCase):
+    def test(self):
+        # Test the interning machinery.
+        p = expat.ParserCreate()
+        L = []
+        def collector(name, *args):
+            L.append(name)
+        p.StartElementHandler = collector
+        p.EndElementHandler = collector
+        p.Parse("<e> <e/> <e></e> </e>", 1)
+        tag = L[0]
+        self.assertEquals(len(L), 6)
+        for entry in L:
+            # L should have the same string repeated over and over.
+            self.assertTrue(tag is entry)
 
-# Tests of the buffer_text attribute.
-import sys
 
-class TextCollector:
-    def __init__(self, parser):
+class BufferTextTest(unittest.TestCase):
+    def setUp(self):
         self.stuff = []
+        self.parser = expat.ParserCreate()
+        self.parser.buffer_text = 1
+        self.parser.CharacterDataHandler = self.CharacterDataHandler
 
     def check(self, expected, label):
-        require(self.stuff == expected,
+        self.assertEquals(self.stuff, expected,
                 "%s\nstuff    = %r\nexpected = %r"
                 % (label, self.stuff, map(unicode, expected)))
 
@@ -238,9 +290,9 @@
         self.stuff.append("<%s>" % name)
         bt = attrs.get("buffer-text")
         if bt == "yes":
-            parser.buffer_text = 1
+            self.parser.buffer_text = 1
         elif bt == "no":
-            parser.buffer_text = 0
+            self.parser.buffer_text = 0
 
     def EndElementHandler(self, name):
         self.stuff.append("</%s>" % name)
@@ -248,95 +300,91 @@
     def CommentHandler(self, data):
         self.stuff.append("<!--%s-->" % data)
 
-def require(cond, label):
-    # similar to confirm(), but no extraneous output
-    if not cond:
-        raise TestFailed(label)
-
-def setup(handlers=[]):
-    parser = expat.ParserCreate()
-    require(not parser.buffer_text,
-            "buffer_text not disabled by default")
-    parser.buffer_text = 1
-    handler = TextCollector(parser)
-    parser.CharacterDataHandler = handler.CharacterDataHandler
-    for name in handlers:
-        setattr(parser, name, getattr(handler, name))
-    return parser, handler
-
-parser, handler = setup()
-require(parser.buffer_text,
-        "text buffering either not acknowledged or not enabled")
-parser.Parse("<a>1<b/>2<c/>3</a>", 1)
-handler.check(["123"],
-              "buffered text not properly collapsed")
-
-# XXX This test exposes more detail of Expat's text chunking than we
-# XXX like, but it tests what we need to concisely.
-parser, handler = setup(["StartElementHandler"])
-parser.Parse("<a>1<b buffer-text='no'/>2\n3<c buffer-text='yes'/>4\n5</a>", 1)
-handler.check(["<a>", "1", "<b>", "2", "\n", "3", "<c>", "4\n5"],
-              "buffering control not reacting as expected")
-
-parser, handler = setup()
-parser.Parse("<a>1<b/>&lt;2&gt;<c/>&#32;\n&#x20;3</a>", 1)
-handler.check(["1<2> \n 3"],
-              "buffered text not properly collapsed")
-
-parser, handler = setup(["StartElementHandler"])
-parser.Parse("<a>1<b/>2<c/>3</a>", 1)
-handler.check(["<a>", "1", "<b>", "2", "<c>", "3"],
-              "buffered text not properly split")
-
-parser, handler = setup(["StartElementHandler", "EndElementHandler"])
-parser.CharacterDataHandler = None
-parser.Parse("<a>1<b/>2<c/>3</a>", 1)
-handler.check(["<a>", "<b>", "</b>", "<c>", "</c>", "</a>"],
-              "huh?")
-
-parser, handler = setup(["StartElementHandler", "EndElementHandler"])
-parser.Parse("<a>1<b></b>2<c/>3</a>", 1)
-handler.check(["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "</a>"],
-              "huh?")
-
-parser, handler = setup(["CommentHandler", "EndElementHandler",
-                         "StartElementHandler"])
-parser.Parse("<a>1<b/>2<c></c>345</a> ", 1)
-handler.check(["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
-              "buffered text not properly split")
-
-parser, handler = setup(["CommentHandler", "EndElementHandler",
-                         "StartElementHandler"])
-parser.Parse("<a>1<b/>2<c></c>3<!--abc-->4<!--def-->5</a> ", 1)
-handler.check(["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3",
-               "<!--abc-->", "4", "<!--def-->", "5", "</a>"],
-              "buffered text not properly split")
+    def setHandlers(self, handlers=[]):
+        for name in handlers:
+            setattr(self.parser, name, getattr(self, name))
+
+    def test_default_to_disabled(self):
+        parser = expat.ParserCreate()
+        self.assertFalse(parser.buffer_text)
+
+    def test_buffering_enabled(self):
+        # Make sure buffering is turned on
+        self.assertTrue(self.parser.buffer_text)
+        self.parser.Parse("<a>1<b/>2<c/>3</a>", 1)
+        self.assertEquals(self.stuff, ['123'],
+                          "buffered text not properly collapsed")
+
+    def test1(self):
+        # XXX This test exposes more detail of Expat's text chunking than we
+        # XXX like, but it tests what we need to concisely.
+        self.setHandlers(["StartElementHandler"])
+        self.parser.Parse("<a>1<b buffer-text='no'/>2\n3<c buffer-text='yes'/>4\n5</a>", 1)
+        self.assertEquals(self.stuff,
+                          ["<a>", "1", "<b>", "2", "\n", "3", "<c>", "4\n5"],
+                          "buffering control not reacting as expected")
+
+    def test2(self):
+        self.parser.Parse("<a>1<b/>&lt;2&gt;<c/>&#32;\n&#x20;3</a>", 1)
+        self.assertEquals(self.stuff, ["1<2> \n 3"],
+                          "buffered text not properly collapsed")
+
+    def test3(self):
+        self.setHandlers(["StartElementHandler"])
+        self.parser.Parse("<a>1<b/>2<c/>3</a>", 1)
+        self.assertEquals(self.stuff, ["<a>", "1", "<b>", "2", "<c>", "3"],
+                          "buffered text not properly split")
+
+    def test4(self):
+        self.setHandlers(["StartElementHandler", "EndElementHandler"])
+        self.parser.CharacterDataHandler = None
+        self.parser.Parse("<a>1<b/>2<c/>3</a>", 1)
+        self.assertEquals(self.stuff,
+                          ["<a>", "<b>", "</b>", "<c>", "</c>", "</a>"])
+
+    def test5(self):
+        self.setHandlers(["StartElementHandler", "EndElementHandler"])
+        self.parser.Parse("<a>1<b></b>2<c/>3</a>", 1)
+        self.assertEquals(self.stuff,
+            ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "</a>"])
+
+    def test6(self):
+        self.setHandlers(["CommentHandler", "EndElementHandler",
+                    "StartElementHandler"])
+        self.parser.Parse("<a>1<b/>2<c></c>345</a> ", 1)
+        self.assertEquals(self.stuff,
+            ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
+            "buffered text not properly split")
+
+    def test7(self):
+        self.setHandlers(["CommentHandler", "EndElementHandler",
+                    "StartElementHandler"])
+        self.parser.Parse("<a>1<b/>2<c></c>3<!--abc-->4<!--def-->5</a> ", 1)
+        self.assertEquals(self.stuff,
+                          ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3",
+                           "<!--abc-->", "4", "<!--def-->", "5", "</a>"],
+                          "buffered text not properly split")
+
 
 # Test handling of exception from callback:
-def StartElementHandler(name, attrs):
-    raise RuntimeError(name)
+class HandlerExceptionTest(unittest.TestCase):
+    def StartElementHandler(self, name, attrs):
+        raise RuntimeError(name)
 
-parser = expat.ParserCreate()
-parser.StartElementHandler = StartElementHandler
+    def test(self):
+        parser = expat.ParserCreate()
+        parser.StartElementHandler = self.StartElementHandler
+        try:
+            parser.Parse("<a><b><c/></b></a>", 1)
+            self.fail()
+        except RuntimeError as e:
+            self.assertEquals(e.args[0], 'a',
+                              "Expected RuntimeError for element 'a', but" + \
+                              " found %r" % e.args[0])
 
-try:
-    parser.Parse("<a><b><c/></b></a>", 1)
-except RuntimeError as e:
-    if e.args[0] != "a":
-        print("Expected RuntimeError for element 'a'; found %r" % e.args[0])
-else:
-    print("Expected RuntimeError for 'a'")
 
 # Test Current* members:
-class PositionTest:
-
-    def __init__(self, expected_list, parser):
-        self.parser = parser
-        self.parser.StartElementHandler = self.StartElementHandler
-        self.parser.EndElementHandler = self.EndElementHandler
-        self.expected_list = expected_list
-        self.upto = 0
-
+class PositionTest(unittest.TestCase):
     def StartElementHandler(self, name, attrs):
         self.check_pos('s')
 
@@ -348,41 +396,54 @@
                self.parser.CurrentByteIndex,
                self.parser.CurrentLineNumber,
                self.parser.CurrentColumnNumber)
-        require(self.upto < len(self.expected_list),
-                'too many parser events')
+        self.assertTrue(self.upto < len(self.expected_list),
+                        'too many parser events')
         expected = self.expected_list[self.upto]
-        require(pos == expected,
-                'expected position %s, got %s' % (expected, pos))
+        self.assertEquals(pos, expected,
+                'Expected position %s, got position %s' %(pos, expected))
         self.upto += 1
 
+    def test(self):
+        self.parser = expat.ParserCreate()
+        self.parser.StartElementHandler = self.StartElementHandler
+        self.parser.EndElementHandler = self.EndElementHandler
+        self.upto = 0
+        self.expected_list = [('s', 0, 1, 0), ('s', 5, 2, 1), ('s', 11, 3, 2),
+                              ('e', 15, 3, 6), ('e', 17, 4, 1), ('e', 22, 5, 0)]
+
+        xml = '<a>\n <b>\n  <c/>\n </b>\n</a>'
+        self.parser.Parse(xml, 1)
+
+
+class sf1296433Test(unittest.TestCase):
+    def test_parse_only_xml_data(self):
+        # http://python.org/sf/1296433
+        #
+        xml = "<?xml version='1.0' encoding='iso8859'?><s>%s</s>" % ('a' * 1025)
+        # this one doesn't crash
+        #xml = "<?xml version='1.0'?><s>%s</s>" % ('a' * 10000)
+
+        class SpecificException(Exception):
+            pass
+
+        def handler(text):
+            raise SpecificException
+
+        parser = expat.ParserCreate()
+        parser.CharacterDataHandler = handler
+
+        self.assertRaises(Exception, parser.Parse, xml)
+
 
-parser = expat.ParserCreate()
-handler = PositionTest([('s', 0, 1, 0), ('s', 5, 2, 1), ('s', 11, 3, 2),
-                        ('e', 15, 3, 6), ('e', 17, 4, 1), ('e', 22, 5, 0)],
-                       parser)
-parser.Parse('''<a>
- <b>
-  <c/>
- </b>
-</a>''', 1)
-
-
-def test_parse_only_xml_data():
-    # http://python.org/sf/1296433
-    #
-    xml = "<?xml version='1.0' encoding='iso8859'?><s>%s</s>" % ('a' * 1025)
-    # this one doesn't crash
-    #xml = "<?xml version='1.0'?><s>%s</s>" % ('a' * 10000)
-
-    def handler(text):
-        raise Exception
-
-    parser = expat.ParserCreate()
-    parser.CharacterDataHandler = handler
-
-    try:
-        parser.Parse(xml)
-    except:
-        pass
+def test_main():
+    run_unittest(SetAttributeTest,
+                 ParseTest,
+                 NamespaceSeparatorTest,
+                 InterningTest,
+                 BufferTextTest,
+                 HandlerExceptionTest,
+                 PositionTest,
+                 sf1296433Test)
 
-test_parse_only_xml_data()
+if __name__ == "__main__":
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_queue.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_queue.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_queue.py	Wed Jul 11 15:40:56 2007
@@ -243,7 +243,7 @@
     cum = 0
     for i in (0,1):
         threading.Thread(target=worker, args=(q,)).start()
-    for i in xrange(100):
+    for i in range(100):
         q.put(i)
     q.join()
     verify(cum==sum(range(100)), "q.join() did not block until all tasks were done")

Modified: python/branches/p3yk-noslice/Lib/test/test_random.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_random.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_random.py	Wed Jul 11 15:40:56 2007
@@ -15,7 +15,7 @@
 
     def randomlist(self, n):
         """Helper function to make a list of random numbers"""
-        return [self.gen.random() for i in xrange(n)]
+        return [self.gen.random() for i in range(n)]
 
     def test_autoseed(self):
         self.gen.seed()
@@ -37,7 +37,7 @@
         for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
                     3.14, 1+2j, 'a', tuple('abc')]:
             self.gen.seed(arg)
-        for arg in [range(3), dict(one=1)]:
+        for arg in [list(range(3)), dict(one=1)]:
             self.assertRaises(TypeError, self.gen.seed, arg)
         self.assertRaises(TypeError, self.gen.seed, 1, 2)
         self.assertRaises(TypeError, type(self.gen), [])
@@ -61,8 +61,8 @@
         # For the entire allowable range of 0 <= k <= N, validate that
         # the sample is of the correct length and contains only unique items
         N = 100
-        population = xrange(N)
-        for k in xrange(N+1):
+        population = range(N)
+        for k in range(N+1):
             s = self.gen.sample(population, k)
             self.assertEqual(len(s), k)
             uniq = set(s)
@@ -80,10 +80,10 @@
             if n == 0:
                 return 1
             return n * factorial(n - 1)
-        for k in xrange(n):
+        for k in range(n):
             expected = factorial(n) // factorial(n-k)
             perms = {}
-            for i in xrange(trials):
+            for i in range(trials):
                 perms[tuple(self.gen.sample(pop, k))] = None
                 if len(perms) == expected:
                     break
@@ -94,7 +94,7 @@
         # SF bug #801342 -- population can be any iterable defining __len__()
         self.gen.sample(set(range(20)), 2)
         self.gen.sample(range(20), 2)
-        self.gen.sample(xrange(20), 2)
+        self.gen.sample(range(20), 2)
         self.gen.sample(str('abcdefghijklmnopqrst'), 2)
         self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
 
@@ -102,21 +102,23 @@
         self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
 
         # SF bug #1460340 -- random.sample can raise KeyError
-        a = dict.fromkeys(range(10)+range(10,100,2)+range(100,110))
+        a = dict.fromkeys(list(range(10)) +
+                          list(range(10,100,2)) +
+                          list(range(100,110)))
         self.gen.sample(a, 3)
 
         # A followup to bug #1460340:  sampling from a dict could return
         # a subset of its keys or of its values, depending on the size of
         # the subset requested.
         N = 30
-        d = dict((i, complex(i, i)) for i in xrange(N))
-        for k in xrange(N+1):
+        d = dict((i, complex(i, i)) for i in range(N))
+        for k in range(N+1):
             samp = self.gen.sample(d, k)
             # Verify that we got ints back (keys); the values are complex.
             for x in samp:
                 self.assert_(type(x) is int)
         samp.sort()
-        self.assertEqual(samp, range(N))
+        self.assertEqual(samp, list(range(N)))
 
     def test_gauss(self):
         # Ensure that the seed() method initializes all the hidden state.  In
@@ -137,9 +139,9 @@
 
     def test_pickling(self):
         state = pickle.dumps(self.gen)
-        origseq = [self.gen.random() for i in xrange(10)]
+        origseq = [self.gen.random() for i in range(10)]
         newgen = pickle.loads(state)
-        restoredseq = [newgen.random() for i in xrange(10)]
+        restoredseq = [newgen.random() for i in range(10)]
         self.assertEqual(origseq, restoredseq)
 
 class WichmannHill_TestBasicOps(TestBasicOps):
@@ -156,7 +158,7 @@
         r1 = self.gen.random()
         # now do it the slow way
         self.gen.setstate(s)
-        for i in xrange(N):
+        for i in range(N):
             self.gen.random()
         r2 = self.gen.random()
         self.assertEqual(r1, r2)
@@ -215,7 +217,7 @@
         # This should pass whenever a C double has 53 bit precision.
         span = 2 ** 53
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             cum |= int(self.gen.random() * span)
         self.assertEqual(cum, span-1)
 
@@ -224,7 +226,7 @@
         # in stages so that all bit positions are active.
         span = 2 ** 500
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             r = self.gen.randrange(span)
             self.assert_(0 <= r < span)
             cum |= r
@@ -241,18 +243,18 @@
     def test_rangelimits(self):
         for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
             self.assertEqual(set(range(start,stop)),
-                set([self.gen.randrange(start,stop) for i in xrange(100)]))
+                set([self.gen.randrange(start,stop) for i in range(100)]))
 
     def test_genrandbits(self):
         # Verify ranges
-        for k in xrange(1, 1000):
+        for k in range(1, 1000):
             self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
 
         # Verify all bits active
         getbits = self.gen.getrandbits
         for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
             cum = 0
-            for i in xrange(100):
+            for i in range(100):
                 cum |= getbits(span)
             self.assertEqual(cum, 2**span-1)
 
@@ -267,7 +269,7 @@
         # check bitcount transition points:  2**i and 2**(i+1)-1
         # show that: k = int(1.001 + _log(n, 2))
         # is equal to or one greater than the number of bits in n
-        for i in xrange(1, 1000):
+        for i in range(1, 1000):
             n = 1 << i # check an exact power of two
             numbits = i+1
             k = int(1.00001 + _log(n, 2))
@@ -367,7 +369,7 @@
         # This should pass whenever a C double has 53 bit precision.
         span = 2 ** 53
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             cum |= int(self.gen.random() * span)
         self.assertEqual(cum, span-1)
 
@@ -376,7 +378,7 @@
         # in stages so that all bit positions are active.
         span = 2 ** 500
         cum = 0
-        for i in xrange(100):
+        for i in range(100):
             r = self.gen.randrange(span)
             self.assert_(0 <= r < span)
             cum |= r
@@ -393,7 +395,7 @@
     def test_rangelimits(self):
         for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
             self.assertEqual(set(range(start,stop)),
-                set([self.gen.randrange(start,stop) for i in xrange(100)]))
+                set([self.gen.randrange(start,stop) for i in range(100)]))
 
     def test_genrandbits(self):
         # Verify cross-platform repeatability
@@ -401,14 +403,14 @@
         self.assertEqual(self.gen.getrandbits(100),
                          97904845777343510404718956115)
         # Verify ranges
-        for k in xrange(1, 1000):
+        for k in range(1, 1000):
             self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
 
         # Verify all bits active
         getbits = self.gen.getrandbits
         for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
             cum = 0
-            for i in xrange(100):
+            for i in range(100):
                 cum |= getbits(span)
             self.assertEqual(cum, 2**span-1)
 
@@ -423,7 +425,7 @@
         # check bitcount transition points:  2**i and 2**(i+1)-1
         # show that: k = int(1.001 + _log(n, 2))
         # is equal to or one greater than the number of bits in n
-        for i in xrange(1, 1000):
+        for i in range(1, 1000):
             n = 1 << i # check an exact power of two
             numbits = i+1
             k = int(1.00001 + _log(n, 2))
@@ -455,7 +457,7 @@
 def gamma(z, cof=_gammacoeff, g=7):
     z -= 1.0
     sum = cof[0]
-    for i in xrange(1,len(cof)):
+    for i in range(1,len(cof)):
         sum += cof[i] / (z+i)
     z += 0.5
     return (z+g)**z / exp(z+g) * sqrt(2*pi) * sum
@@ -464,7 +466,7 @@
     def test_zeroinputs(self):
         # Verify that distributions can handle a series of zero inputs'
         g = random.Random()
-        x = [g.random() for i in xrange(50)] + [0.0]*5
+        x = [g.random() for i in range(50)] + [0.0]*5
         g.random = x[:].pop; g.uniform(1,10)
         g.random = x[:].pop; g.paretovariate(1.0)
         g.random = x[:].pop; g.expovariate(1.0)
@@ -483,7 +485,7 @@
         # Only works for distributions which do not consume variates in pairs
         g = random.Random()
         N = 5000
-        x = [i/float(N) for i in xrange(1,N)]
+        x = [i/float(N) for i in range(1,N)]
         for variate, args, mu, sigmasqrd in [
                 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
                 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
@@ -493,7 +495,7 @@
                                   gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
             g.random = x[:].pop
             y = []
-            for i in xrange(len(x)):
+            for i in range(len(x)):
                 try:
                     y.append(variate(*args))
                 except IndexError:
@@ -544,7 +546,7 @@
     import sys
     if verbose and hasattr(sys, "gettotalrefcount"):
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*testclasses)
             counts[i] = sys.gettotalrefcount()
         print(counts)

Modified: python/branches/p3yk-noslice/Lib/test/test_re.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_re.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_re.py	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,7 @@
 import sys
 sys.path = ['.'] + sys.path
 
-from test.test_support import verbose, run_unittest
+from test.test_support import verbose, run_unittest, guard_warnings_filter
 import re
 from re import Scanner
 import sys, os, traceback
@@ -418,6 +418,12 @@
             pass # cPickle not found -- skip it
         else:
             self.pickle_test(cPickle)
+        # old pickles expect the _compile() reconstructor in sre module
+        import warnings
+        with guard_warnings_filter():
+            warnings.filterwarnings("ignore", "The sre module is deprecated",
+                                    DeprecationWarning)
+            from sre import _compile
 
     def pickle_test(self, pickle):
         oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
@@ -586,8 +592,8 @@
 
     def test_bug_581080(self):
         iter = re.finditer(r"\s", "a b")
-        self.assertEqual(iter.next().span(), (1,2))
-        self.assertRaises(StopIteration, iter.next)
+        self.assertEqual(next(iter).span(), (1,2))
+        self.assertRaises(StopIteration, next, iter)
 
         scanner = re.compile(r"\s").scanner("a b")
         self.assertEqual(scanner.search().span(), (1, 2))
@@ -595,10 +601,17 @@
 
     def test_bug_817234(self):
         iter = re.finditer(r".*", "asdf")
-        self.assertEqual(iter.next().span(), (0, 4))
-        self.assertEqual(iter.next().span(), (4, 4))
-        self.assertRaises(StopIteration, iter.next)
-
+        self.assertEqual(next(iter).span(), (0, 4))
+        self.assertEqual(next(iter).span(), (4, 4))
+        self.assertRaises(StopIteration, next, iter)
+
+    def test_empty_array(self):
+        # SF buf 1647541
+        import array
+        for typecode in 'cbBuhHiIlLfd':
+            a = array.array(typecode)
+            self.assertEqual(re.compile("bla").match(a), None)
+            self.assertEqual(re.compile("").match(a).groups(), ())
 
 def run_re_tests():
     from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR

Modified: python/branches/p3yk-noslice/Lib/test/test_repr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_repr.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_repr.py	Wed Jul 11 15:40:56 2007
@@ -10,6 +10,7 @@
 
 from test.test_support import run_unittest
 from repr import repr as r # Don't shadow builtin repr
+from repr import Repr
 
 
 def nestedTuple(nesting):
@@ -34,6 +35,18 @@
         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
@@ -135,11 +148,11 @@
         self.failUnless(repr(''.split).startswith(
             '<built-in method split of str object at 0x'))
 
-    def test_xrange(self):
+    def test_range(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)')
+        eq(repr(range(1)), 'range(1)')
+        eq(repr(range(1, 2)), 'range(1, 2)')
+        eq(repr(range(1, 4, 3)), 'range(1, 4, 3)')
 
     def test_nesting(self):
         eq = self.assertEquals

Deleted: /python/branches/p3yk-noslice/Lib/test/test_rgbimg.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_rgbimg.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,70 +0,0 @@
-# Testing rgbimg module
-
-import warnings
-warnings.filterwarnings("ignore",
-                        "the rgbimg module is deprecated",
-                        DeprecationWarning,
-                        ".*test_rgbimg$")
-import rgbimg
-
-import os, uu
-
-from test.test_support import verbose, unlink, findfile
-
-class error(Exception):
-    pass
-
-print('RGBimg test suite:')
-
-def testimg(rgb_file, raw_file):
-    rgb_file = findfile(rgb_file)
-    raw_file = findfile(raw_file)
-    width, height = rgbimg.sizeofimage(rgb_file)
-    rgb = rgbimg.longimagedata(rgb_file)
-    if len(rgb) != width * height * 4:
-        raise error, 'bad image length'
-    raw = open(raw_file, 'rb').read()
-    if rgb != raw:
-        raise error, \
-              'images don\'t match for '+rgb_file+' and '+raw_file
-    for depth in [1, 3, 4]:
-        rgbimg.longstoimage(rgb, width, height, depth, '@.rgb')
-    os.unlink('@.rgb')
-
-table = [
-    ('testrgb'+os.extsep+'uue', 'test'+os.extsep+'rgb'),
-    ('testimg'+os.extsep+'uue', 'test'+os.extsep+'rawimg'),
-    ('testimgr'+os.extsep+'uue', 'test'+os.extsep+'rawimg'+os.extsep+'rev'),
-    ]
-for source, target in table:
-    source = findfile(source)
-    target = findfile(target)
-    if verbose:
-        print("uudecoding", source, "->", target, "...")
-    uu.decode(source, target)
-
-if verbose:
-    print("testing...")
-
-ttob = rgbimg.ttob(0)
-if ttob != 0:
-    raise error, 'ttob should start out as zero'
-
-testimg('test'+os.extsep+'rgb', 'test'+os.extsep+'rawimg')
-
-ttob = rgbimg.ttob(1)
-if ttob != 0:
-    raise error, 'ttob should be zero'
-
-testimg('test'+os.extsep+'rgb', 'test'+os.extsep+'rawimg'+os.extsep+'rev')
-
-ttob = rgbimg.ttob(0)
-if ttob != 1:
-    raise error, 'ttob should be one'
-
-ttob = rgbimg.ttob(0)
-if ttob != 0:
-    raise error, 'ttob should be zero'
-
-for source, target in table:
-    unlink(findfile(target))

Modified: python/branches/p3yk-noslice/Lib/test/test_richcmp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_richcmp.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_richcmp.py	Wed Jul 11 15:40:56 2007
@@ -105,7 +105,7 @@
             realres = op(a, b)
             # can't use assertEqual(realres, expres) here
             self.assertEqual(len(realres), len(expres))
-            for i in xrange(len(realres)):
+            for i in range(len(realres)):
                 # results are bool, so we can use "is" here
                 self.assert_(realres[i] is expres[i])
 
@@ -119,7 +119,7 @@
         for opname in opmap:
             self.checkfail(ValueError, opname, a, b)
 
-        a = range(5)
+        a = list(range(5))
         b = 5 * [2]
         # try mixed arguments (but not (a, b) as that won't return a bool vector)
         args = [(a, Vector(b)), (Vector(a), b), (Vector(a), Vector(b))]
@@ -142,8 +142,8 @@
         # Check that comparisons involving Number objects
         # give the same results give as comparing the
         # corresponding ints
-        for a in xrange(3):
-            for b in xrange(3):
+        for a in range(3):
+            for b in range(3):
                 for typea in (int, Number):
                     for typeb in (int, Number):
                         if typea==typeb==int:

Modified: python/branches/p3yk-noslice/Lib/test/test_robotparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_robotparser.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_robotparser.py	Wed Jul 11 15:40:56 2007
@@ -135,8 +135,8 @@
 RobotTest(7, doc, good, bad)
 
 def test_main():
-    test_support.run_suite(tests)
+    test_support.run_unittest(tests)
 
 if __name__=='__main__':
     test_support.Verbose = 1
-    test_support.run_suite(tests)
+    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_sax.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sax.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_sax.py	Wed Jul 11 15:40:56 2007
@@ -13,26 +13,66 @@
 from xml.sax.expatreader import create_parser
 from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
 from cStringIO import StringIO
-from test.test_support import verify, verbose, TestFailed, findfile
+from test.test_support import findfile, run_unittest
+import unittest
 import os
 
-# ===== Utilities
-
-tests = 0
-failures = []
-
-def confirm(outcome, name):
-    global tests
+ns_uri = "http://www.python.org/xml-ns/saxtest/"
 
-    tests = tests + 1
-    if outcome:
-        if verbose:
-            print("Passed", name)
-    else:
-        failures.append(name)
+class XmlTestBase(unittest.TestCase):
+    def verify_empty_attrs(self, attrs):
+        self.assertRaises(KeyError, attrs.getValue, "attr")
+        self.assertRaises(KeyError, attrs.getValueByQName, "attr")
+        self.assertRaises(KeyError, attrs.getNameByQName, "attr")
+        self.assertRaises(KeyError, attrs.getQNameByName, "attr")
+        self.assertRaises(KeyError, attrs.__getitem__, "attr")
+        self.assertEquals(attrs.getLength(), 0)
+        self.assertEquals(attrs.getNames(), [])
+        self.assertEquals(attrs.getQNames(), [])
+        self.assertEquals(len(attrs), 0)
+        self.assertFalse("attr" in attrs)
+        self.assertEquals(list(attrs.keys()), [])
+        self.assertEquals(attrs.get("attrs"), None)
+        self.assertEquals(attrs.get("attrs", 25), 25)
+        self.assertEquals(list(attrs.items()), [])
+        self.assertEquals(list(attrs.values()), [])
+
+    def verify_empty_nsattrs(self, attrs):
+        self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr"))
+        self.assertRaises(KeyError, attrs.getValueByQName, "ns:attr")
+        self.assertRaises(KeyError, attrs.getNameByQName, "ns:attr")
+        self.assertRaises(KeyError, attrs.getQNameByName, (ns_uri, "attr"))
+        self.assertRaises(KeyError, attrs.__getitem__, (ns_uri, "attr"))
+        self.assertEquals(attrs.getLength(), 0)
+        self.assertEquals(attrs.getNames(), [])
+        self.assertEquals(attrs.getQNames(), [])
+        self.assertEquals(len(attrs), 0)
+        self.assertFalse((ns_uri, "attr") in attrs)
+        self.assertEquals(list(attrs.keys()), [])
+        self.assertEquals(attrs.get((ns_uri, "attr")), None)
+        self.assertEquals(attrs.get((ns_uri, "attr"), 25), 25)
+        self.assertEquals(list(attrs.items()), [])
+        self.assertEquals(list(attrs.values()), [])
+
+    def verify_attrs_wattr(self, attrs):
+        self.assertEquals(attrs.getLength(), 1)
+        self.assertEquals(attrs.getNames(), ["attr"])
+        self.assertEquals(attrs.getQNames(), ["attr"])
+        self.assertEquals(len(attrs), 1)
+        self.assertTrue("attr" in attrs)
+        self.assertEquals(list(attrs.keys()), ["attr"])
+        self.assertEquals(attrs.get("attr"), "val")
+        self.assertEquals(attrs.get("attr", 25), "val")
+        self.assertEquals(list(attrs.items()), [("attr", "val")])
+        self.assertEquals(list(attrs.values()), ["val"])
+        self.assertEquals(attrs.getValue("attr"), "val")
+        self.assertEquals(attrs.getValueByQName("attr"), "val")
+        self.assertEquals(attrs.getNameByQName("attr"), "attr")
+        self.assertEquals(attrs["attr"], "val")
+        self.assertEquals(attrs.getQNameByName("attr"), "attr")
 
-def test_make_parser2():
-    try:
+class MakeParserTest(unittest.TestCase):
+    def test_make_parser2(self):
         # Creating parsers several times in a row should succeed.
         # Testing this because there have been failures of this kind
         # before.
@@ -48,10 +88,6 @@
         p = make_parser()
         from xml.sax import make_parser
         p = make_parser()
-    except:
-        return 0
-    else:
-        return p
 
 
 # ===========================================================================
@@ -60,215 +96,214 @@
 #
 # ===========================================================================
 
-# ===== escape
-
-def test_escape_basic():
-    return escape("Donald Duck & Co") == "Donald Duck &amp; Co"
-
-def test_escape_all():
-    return escape("<Donald Duck & Co>") == "&lt;Donald Duck &amp; Co&gt;"
-
-def test_escape_extra():
-    return escape("Hei på deg", {"å" : "&aring;"}) == "Hei p&aring; deg"
-
-# ===== unescape
-
-def test_unescape_basic():
-    return unescape("Donald Duck &amp; Co") == "Donald Duck & Co"
-
-def test_unescape_all():
-    return unescape("&lt;Donald Duck &amp; Co&gt;") == "<Donald Duck & Co>"
-
-def test_unescape_extra():
-    return unescape("Hei på deg", {"å" : "&aring;"}) == "Hei p&aring; deg"
-
-def test_unescape_amp_extra():
-    return unescape("&amp;foo;", {"&foo;": "splat"}) == "&foo;"
+class SaxutilsTest(unittest.TestCase):
+    # ===== escape
+    def test_escape_basic(self):
+        self.assertEquals(escape("Donald Duck & Co"), "Donald Duck &amp; Co")
+
+    def test_escape_all(self):
+        self.assertEquals(escape("<Donald Duck & Co>"),
+                          "&lt;Donald Duck &amp; Co&gt;")
+
+    def test_escape_extra(self):
+        self.assertEquals(escape("Hei på deg", {"å" : "&aring;"}),
+                          "Hei p&aring; deg")
+
+    # ===== unescape
+    def test_unescape_basic(self):
+        self.assertEquals(unescape("Donald Duck &amp; Co"), "Donald Duck & Co")
+
+    def test_unescape_all(self):
+        self.assertEquals(unescape("&lt;Donald Duck &amp; Co&gt;"),
+                          "<Donald Duck & Co>")
+
+    def test_unescape_extra(self):
+        self.assertEquals(unescape("Hei på deg", {"å" : "&aring;"}),
+                          "Hei p&aring; deg")
+
+    def test_unescape_amp_extra(self):
+        self.assertEquals(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;")
+
+    # ===== quoteattr
+    def test_quoteattr_basic(self):
+        self.assertEquals(quoteattr("Donald Duck & Co"),
+                          '"Donald Duck &amp; Co"')
+
+    def test_single_quoteattr(self):
+        self.assertEquals(quoteattr('Includes "double" quotes'),
+                          '\'Includes "double" quotes\'')
+
+    def test_double_quoteattr(self):
+        self.assertEquals(quoteattr("Includes 'single' quotes"),
+                          "\"Includes 'single' quotes\"")
+
+    def test_single_double_quoteattr(self):
+        self.assertEquals(quoteattr("Includes 'single' and \"double\" quotes"),
+                    "\"Includes 'single' and &quot;double&quot; quotes\"")
 
-# ===== quoteattr
-
-def test_quoteattr_basic():
-    return quoteattr("Donald Duck & Co") == '"Donald Duck &amp; Co"'
-
-def test_single_quoteattr():
-    return (quoteattr('Includes "double" quotes')
-            == '\'Includes "double" quotes\'')
-
-def test_double_quoteattr():
-    return (quoteattr("Includes 'single' quotes")
-            == "\"Includes 'single' quotes\"")
-
-def test_single_double_quoteattr():
-    return (quoteattr("Includes 'single' and \"double\" quotes")
-            == "\"Includes 'single' and &quot;double&quot; quotes\"")
-
-# ===== make_parser
-
-def test_make_parser():
-    try:
+    # ===== make_parser
+    def test_make_parser(self):
         # Creating a parser should succeed - it should fall back
         # to the expatreader
         p = make_parser(['xml.parsers.no_such_parser'])
-    except:
-        return 0
-    else:
-        return p
 
 
 # ===== XMLGenerator
 
 start = '<?xml version="1.0" encoding="iso-8859-1"?>\n'
 
-def test_xmlgen_basic():
-    result = StringIO()
-    gen = XMLGenerator(result)
-    gen.startDocument()
-    gen.startElement("doc", {})
-    gen.endElement("doc")
-    gen.endDocument()
-
-    return result.getvalue() == start + "<doc></doc>"
-
-def test_xmlgen_content():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startElement("doc", {})
-    gen.characters("huhei")
-    gen.endElement("doc")
-    gen.endDocument()
-
-    return result.getvalue() == start + "<doc>huhei</doc>"
-
-def test_xmlgen_pi():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.processingInstruction("test", "data")
-    gen.startElement("doc", {})
-    gen.endElement("doc")
-    gen.endDocument()
-
-    return result.getvalue() == start + "<?test data?><doc></doc>"
-
-def test_xmlgen_content_escape():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startElement("doc", {})
-    gen.characters("<huhei&")
-    gen.endElement("doc")
-    gen.endDocument()
-
-    return result.getvalue() == start + "<doc>&lt;huhei&amp;</doc>"
-
-def test_xmlgen_attr_escape():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startElement("doc", {"a": '"'})
-    gen.startElement("e", {"a": "'"})
-    gen.endElement("e")
-    gen.startElement("e", {"a": "'\""})
-    gen.endElement("e")
-    gen.startElement("e", {"a": "\n\r\t"})
-    gen.endElement("e")
-    gen.endElement("doc")
-    gen.endDocument()
-
-    return result.getvalue() == start + ("<doc a='\"'><e a=\"'\"></e>"
-                                         "<e a=\"'&quot;\"></e>"
-                                         "<e a=\"&#10;&#13;&#9;\"></e></doc>")
-
-def test_xmlgen_ignorable():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startElement("doc", {})
-    gen.ignorableWhitespace(" ")
-    gen.endElement("doc")
-    gen.endDocument()
+class XmlgenTest(unittest.TestCase):
+    def test_xmlgen_basic(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+        gen.startDocument()
+        gen.startElement("doc", {})
+        gen.endElement("doc")
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start + "<doc></doc>")
+
+    def test_xmlgen_content(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startElement("doc", {})
+        gen.characters("huhei")
+        gen.endElement("doc")
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start + "<doc>huhei</doc>")
+
+    def test_xmlgen_pi(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.processingInstruction("test", "data")
+        gen.startElement("doc", {})
+        gen.endElement("doc")
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start + "<?test data?><doc></doc>")
+
+    def test_xmlgen_content_escape(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startElement("doc", {})
+        gen.characters("<huhei&")
+        gen.endElement("doc")
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(),
+            start + "<doc>&lt;huhei&amp;</doc>")
+
+    def test_xmlgen_attr_escape(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startElement("doc", {"a": '"'})
+        gen.startElement("e", {"a": "'"})
+        gen.endElement("e")
+        gen.startElement("e", {"a": "'\""})
+        gen.endElement("e")
+        gen.startElement("e", {"a": "\n\r\t"})
+        gen.endElement("e")
+        gen.endElement("doc")
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start +
+            ("<doc a='\"'><e a=\"'\"></e>"
+             "<e a=\"'&quot;\"></e>"
+             "<e a=\"&#10;&#13;&#9;\"></e></doc>"))
+
+    def test_xmlgen_ignorable(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startElement("doc", {})
+        gen.ignorableWhitespace(" ")
+        gen.endElement("doc")
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start + "<doc> </doc>")
+
+    def test_xmlgen_ns(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startPrefixMapping("ns1", ns_uri)
+        gen.startElementNS((ns_uri, "doc"), "ns1:doc", {})
+        # add an unqualified name
+        gen.startElementNS((None, "udoc"), None, {})
+        gen.endElementNS((None, "udoc"), None)
+        gen.endElementNS((ns_uri, "doc"), "ns1:doc")
+        gen.endPrefixMapping("ns1")
+        gen.endDocument()
 
-    return result.getvalue() == start + "<doc> </doc>"
-
-ns_uri = "http://www.python.org/xml-ns/saxtest/"
-
-def test_xmlgen_ns():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startPrefixMapping("ns1", ns_uri)
-    gen.startElementNS((ns_uri, "doc"), "ns1:doc", {})
-    # add an unqualified name
-    gen.startElementNS((None, "udoc"), None, {})
-    gen.endElementNS((None, "udoc"), None)
-    gen.endElementNS((ns_uri, "doc"), "ns1:doc")
-    gen.endPrefixMapping("ns1")
-    gen.endDocument()
-
-    return result.getvalue() == start + \
+        self.assertEquals(result.getvalue(), start + \
            ('<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' %
-                                         ns_uri)
+                                         ns_uri))
 
-def test_1463026_1():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'})
-    gen.endElementNS((None, 'a'), 'a')
-    gen.endDocument()
-
-    return result.getvalue() == start+'<a b="c"></a>'
-
-def test_1463026_2():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startPrefixMapping(None, 'qux')
-    gen.startElementNS(('qux', 'a'), 'a', {})
-    gen.endElementNS(('qux', 'a'), 'a')
-    gen.endPrefixMapping(None)
-    gen.endDocument()
-
-    return result.getvalue() == start+'<a xmlns="qux"></a>'
-
-def test_1463026_3():
-    result = StringIO()
-    gen = XMLGenerator(result)
-
-    gen.startDocument()
-    gen.startPrefixMapping('my', 'qux')
-    gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'})
-    gen.endElementNS(('qux', 'a'), 'a')
-    gen.endPrefixMapping('my')
-    gen.endDocument()
-
-    return result.getvalue() == start+'<my:a xmlns:my="qux" b="c"></my:a>'
-    
-# ===== Xmlfilterbase
-
-def test_filter_basic():
-    result = StringIO()
-    gen = XMLGenerator(result)
-    filter = XMLFilterBase()
-    filter.setContentHandler(gen)
-
-    filter.startDocument()
-    filter.startElement("doc", {})
-    filter.characters("content")
-    filter.ignorableWhitespace(" ")
-    filter.endElement("doc")
-    filter.endDocument()
+    def test_1463026_1(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'})
+        gen.endElementNS((None, 'a'), 'a')
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start+'<a b="c"></a>')
+
+    def test_1463026_2(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startPrefixMapping(None, 'qux')
+        gen.startElementNS(('qux', 'a'), 'a', {})
+        gen.endElementNS(('qux', 'a'), 'a')
+        gen.endPrefixMapping(None)
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(), start+'<a xmlns="qux"></a>')
+
+    def test_1463026_3(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+
+        gen.startDocument()
+        gen.startPrefixMapping('my', 'qux')
+        gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'})
+        gen.endElementNS(('qux', 'a'), 'a')
+        gen.endPrefixMapping('my')
+        gen.endDocument()
+
+        self.assertEquals(result.getvalue(),
+            start+'<my:a xmlns:my="qux" b="c"></my:a>')
+
+
+class XMLFilterBaseTest(unittest.TestCase):
+    def test_filter_basic(self):
+        result = StringIO()
+        gen = XMLGenerator(result)
+        filter = XMLFilterBase()
+        filter.setContentHandler(gen)
+
+        filter.startDocument()
+        filter.startElement("doc", {})
+        filter.characters("content")
+        filter.ignorableWhitespace(" ")
+        filter.endElement("doc")
+        filter.endDocument()
 
-    return result.getvalue() == start + "<doc>content </doc>"
+        self.assertEquals(result.getvalue(), start + "<doc>content </doc>")
 
 # ===========================================================================
 #
@@ -276,229 +311,233 @@
 #
 # ===========================================================================
 
-# ===== XMLReader support
+xml_test_out = open(findfile("test"+os.extsep+"xml"+os.extsep+"out")).read()
+
+class ExpatReaderTest(XmlTestBase):
 
-def test_expat_file():
-    parser = create_parser()
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
+    # ===== XMLReader support
 
-    parser.setContentHandler(xmlgen)
-    parser.parse(open(findfile("test"+os.extsep+"xml")))
+    def test_expat_file(self):
+        parser = create_parser()
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
 
-    return result.getvalue() == xml_test_out
+        parser.setContentHandler(xmlgen)
+        parser.parse(open(findfile("test"+os.extsep+"xml")))
 
-# ===== DTDHandler support
+        self.assertEquals(result.getvalue(), xml_test_out)
 
-class TestDTDHandler:
+    # ===== DTDHandler support
 
-    def __init__(self):
-        self._notations = []
-        self._entities  = []
+    class TestDTDHandler:
 
-    def notationDecl(self, name, publicId, systemId):
-        self._notations.append((name, publicId, systemId))
+        def __init__(self):
+            self._notations = []
+            self._entities  = []
 
-    def unparsedEntityDecl(self, name, publicId, systemId, ndata):
-        self._entities.append((name, publicId, systemId, ndata))
+        def notationDecl(self, name, publicId, systemId):
+            self._notations.append((name, publicId, systemId))
 
-def test_expat_dtdhandler():
-    parser = create_parser()
-    handler = TestDTDHandler()
-    parser.setDTDHandler(handler)
+        def unparsedEntityDecl(self, name, publicId, systemId, ndata):
+            self._entities.append((name, publicId, systemId, ndata))
 
-    parser.feed('<!DOCTYPE doc [\n')
-    parser.feed('  <!ENTITY img SYSTEM "expat.gif" NDATA GIF>\n')
-    parser.feed('  <!NOTATION GIF PUBLIC "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN">\n')
-    parser.feed(']>\n')
-    parser.feed('<doc></doc>')
-    parser.close()
+    def test_expat_dtdhandler(self):
+        parser = create_parser()
+        handler = self.TestDTDHandler()
+        parser.setDTDHandler(handler)
 
-    return handler._notations == [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)] and \
-           handler._entities == [("img", None, "expat.gif", "GIF")]
+        parser.feed('<!DOCTYPE doc [\n')
+        parser.feed('  <!ENTITY img SYSTEM "expat.gif" NDATA GIF>\n')
+        parser.feed('  <!NOTATION GIF PUBLIC "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN">\n')
+        parser.feed(']>\n')
+        parser.feed('<doc></doc>')
+        parser.close()
 
-# ===== EntityResolver support
+        self.assertEquals(handler._notations,
+            [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)])
+        self.assertEquals(handler._entities, [("img", None, "expat.gif", "GIF")])
 
-class TestEntityResolver:
+    # ===== EntityResolver support
 
-    def resolveEntity(self, publicId, systemId):
-        inpsrc = InputSource()
-        inpsrc.setByteStream(StringIO("<entity/>"))
-        return inpsrc
+    class TestEntityResolver:
 
-def test_expat_entityresolver():
-    parser = create_parser()
-    parser.setEntityResolver(TestEntityResolver())
-    result = StringIO()
-    parser.setContentHandler(XMLGenerator(result))
+        def resolveEntity(self, publicId, systemId):
+            inpsrc = InputSource()
+            inpsrc.setByteStream(StringIO("<entity/>"))
+            return inpsrc
 
-    parser.feed('<!DOCTYPE doc [\n')
-    parser.feed('  <!ENTITY test SYSTEM "whatever">\n')
-    parser.feed(']>\n')
-    parser.feed('<doc>&test;</doc>')
-    parser.close()
+    def test_expat_entityresolver(self):
+        parser = create_parser()
+        parser.setEntityResolver(self.TestEntityResolver())
+        result = StringIO()
+        parser.setContentHandler(XMLGenerator(result))
 
-    return result.getvalue() == start + "<doc><entity></entity></doc>"
+        parser.feed('<!DOCTYPE doc [\n')
+        parser.feed('  <!ENTITY test SYSTEM "whatever">\n')
+        parser.feed(']>\n')
+        parser.feed('<doc>&test;</doc>')
+        parser.close()
 
-# ===== Attributes support
+        self.assertEquals(result.getvalue(), start +
+                          "<doc><entity></entity></doc>")
 
-class AttrGatherer(ContentHandler):
+    # ===== Attributes support
 
-    def startElement(self, name, attrs):
-        self._attrs = attrs
+    class AttrGatherer(ContentHandler):
 
-    def startElementNS(self, name, qname, attrs):
-        self._attrs = attrs
+        def startElement(self, name, attrs):
+            self._attrs = attrs
 
-def test_expat_attrs_empty():
-    parser = create_parser()
-    gather = AttrGatherer()
-    parser.setContentHandler(gather)
+        def startElementNS(self, name, qname, attrs):
+            self._attrs = attrs
 
-    parser.feed("<doc/>")
-    parser.close()
+    def test_expat_attrs_empty(self):
+        parser = create_parser()
+        gather = self.AttrGatherer()
+        parser.setContentHandler(gather)
 
-    return verify_empty_attrs(gather._attrs)
+        parser.feed("<doc/>")
+        parser.close()
 
-def test_expat_attrs_wattr():
-    parser = create_parser()
-    gather = AttrGatherer()
-    parser.setContentHandler(gather)
+        self.verify_empty_attrs(gather._attrs)
 
-    parser.feed("<doc attr='val'/>")
-    parser.close()
+    def test_expat_attrs_wattr(self):
+        parser = create_parser()
+        gather = self.AttrGatherer()
+        parser.setContentHandler(gather)
 
-    return verify_attrs_wattr(gather._attrs)
+        parser.feed("<doc attr='val'/>")
+        parser.close()
 
-def test_expat_nsattrs_empty():
-    parser = create_parser(1)
-    gather = AttrGatherer()
-    parser.setContentHandler(gather)
+        self.verify_attrs_wattr(gather._attrs)
 
-    parser.feed("<doc/>")
-    parser.close()
+    def test_expat_nsattrs_empty(self):
+        parser = create_parser(1)
+        gather = self.AttrGatherer()
+        parser.setContentHandler(gather)
 
-    return verify_empty_nsattrs(gather._attrs)
+        parser.feed("<doc/>")
+        parser.close()
 
-def test_expat_nsattrs_wattr():
-    parser = create_parser(1)
-    gather = AttrGatherer()
-    parser.setContentHandler(gather)
+        self.verify_empty_nsattrs(gather._attrs)
 
-    parser.feed("<doc xmlns:ns='%s' ns:attr='val'/>" % ns_uri)
-    parser.close()
+    def test_expat_nsattrs_wattr(self):
+        parser = create_parser(1)
+        gather = self.AttrGatherer()
+        parser.setContentHandler(gather)
 
-    attrs = gather._attrs
+        parser.feed("<doc xmlns:ns='%s' ns:attr='val'/>" % ns_uri)
+        parser.close()
 
-    return attrs.getLength() == 1 and \
-           attrs.getNames() == [(ns_uri, "attr")] and \
-           (attrs.getQNames() == [] or attrs.getQNames() == ["ns:attr"]) and \
-           len(attrs) == 1 and \
-           (ns_uri, "attr") in attrs and \
-           list(attrs.keys()) == [(ns_uri, "attr")] and \
-           attrs.get((ns_uri, "attr")) == "val" and \
-           attrs.get((ns_uri, "attr"), 25) == "val" and \
-           list(attrs.items()) == [((ns_uri, "attr"), "val")] and \
-           list(attrs.values()) == ["val"] and \
-           attrs.getValue((ns_uri, "attr")) == "val" and \
-           attrs[(ns_uri, "attr")] == "val"
+        attrs = gather._attrs
 
-# ===== InputSource support
+        self.assertEquals(attrs.getLength(), 1)
+        self.assertEquals(attrs.getNames(), [(ns_uri, "attr")])
+        self.assertTrue((attrs.getQNames() == [] or
+                         attrs.getQNames() == ["ns:attr"]))
+        self.assertEquals(len(attrs), 1)
+        self.assertTrue((ns_uri, "attr") in attrs)
+        self.assertEquals(attrs.get((ns_uri, "attr")), "val")
+        self.assertEquals(attrs.get((ns_uri, "attr"), 25), "val")
+        self.assertEquals(list(attrs.items()), [((ns_uri, "attr"), "val")])
+        self.assertEquals(list(attrs.values()), ["val"])
+        self.assertEquals(attrs.getValue((ns_uri, "attr")), "val")
+        self.assertEquals(attrs[(ns_uri, "attr")], "val")
 
-xml_test_out = open(findfile("test"+os.extsep+"xml"+os.extsep+"out")).read()
+    # ===== InputSource support
+
+    def test_expat_inpsource_filename(self):
+        parser = create_parser()
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+
+        parser.setContentHandler(xmlgen)
+        parser.parse(findfile("test"+os.extsep+"xml"))
+
+        self.assertEquals(result.getvalue(), xml_test_out)
+
+    def test_expat_inpsource_sysid(self):
+        parser = create_parser()
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+
+        parser.setContentHandler(xmlgen)
+        parser.parse(InputSource(findfile("test"+os.extsep+"xml")))
+
+        self.assertEquals(result.getvalue(), xml_test_out)
+
+    def test_expat_inpsource_stream(self):
+        parser = create_parser()
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+
+        parser.setContentHandler(xmlgen)
+        inpsrc = InputSource()
+        inpsrc.setByteStream(open(findfile("test"+os.extsep+"xml")))
+        parser.parse(inpsrc)
+
+        self.assertEquals(result.getvalue(), xml_test_out)
+
+    # ===== IncrementalParser support
 
-def test_expat_inpsource_filename():
-    parser = create_parser()
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-
-    parser.setContentHandler(xmlgen)
-    parser.parse(findfile("test"+os.extsep+"xml"))
-
-    return result.getvalue() == xml_test_out
-
-def test_expat_inpsource_sysid():
-    parser = create_parser()
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-
-    parser.setContentHandler(xmlgen)
-    parser.parse(InputSource(findfile("test"+os.extsep+"xml")))
-
-    return result.getvalue() == xml_test_out
-
-def test_expat_inpsource_stream():
-    parser = create_parser()
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-
-    parser.setContentHandler(xmlgen)
-    inpsrc = InputSource()
-    inpsrc.setByteStream(open(findfile("test"+os.extsep+"xml")))
-    parser.parse(inpsrc)
-
-    return result.getvalue() == xml_test_out
-
-# ===== IncrementalParser support
-
-def test_expat_incremental():
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-    parser = create_parser()
-    parser.setContentHandler(xmlgen)
-
-    parser.feed("<doc>")
-    parser.feed("</doc>")
-    parser.close()
-
-    return result.getvalue() == start + "<doc></doc>"
-
-def test_expat_incremental_reset():
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-    parser = create_parser()
-    parser.setContentHandler(xmlgen)
-
-    parser.feed("<doc>")
-    parser.feed("text")
-
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-    parser.setContentHandler(xmlgen)
-    parser.reset()
-
-    parser.feed("<doc>")
-    parser.feed("text")
-    parser.feed("</doc>")
-    parser.close()
-
-    return result.getvalue() == start + "<doc>text</doc>"
-
-# ===== Locator support
-
-def test_expat_locator_noinfo():
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-    parser = create_parser()
-    parser.setContentHandler(xmlgen)
-
-    parser.feed("<doc>")
-    parser.feed("</doc>")
-    parser.close()
-
-    return parser.getSystemId() is None and \
-           parser.getPublicId() is None and \
-           parser.getLineNumber() == 1
-
-def test_expat_locator_withinfo():
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-    parser = create_parser()
-    parser.setContentHandler(xmlgen)
-    parser.parse(findfile("test.xml"))
+    def test_expat_incremental(self):
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+        parser = create_parser()
+        parser.setContentHandler(xmlgen)
+
+        parser.feed("<doc>")
+        parser.feed("</doc>")
+        parser.close()
+
+        self.assertEquals(result.getvalue(), start + "<doc></doc>")
+
+    def test_expat_incremental_reset(self):
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+        parser = create_parser()
+        parser.setContentHandler(xmlgen)
+
+        parser.feed("<doc>")
+        parser.feed("text")
+
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+        parser.setContentHandler(xmlgen)
+        parser.reset()
+
+        parser.feed("<doc>")
+        parser.feed("text")
+        parser.feed("</doc>")
+        parser.close()
+
+        self.assertEquals(result.getvalue(), start + "<doc>text</doc>")
+
+    # ===== Locator support
+
+    def test_expat_locator_noinfo(self):
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+        parser = create_parser()
+        parser.setContentHandler(xmlgen)
+
+        parser.feed("<doc>")
+        parser.feed("</doc>")
+        parser.close()
+
+        self.assertEquals(parser.getSystemId(), None)
+        self.assertEquals(parser.getPublicId(), None)
+        self.assertEquals(parser.getLineNumber(), 1)
+
+    def test_expat_locator_withinfo(self):
+        result = StringIO()
+        xmlgen = XMLGenerator(result)
+        parser = create_parser()
+        parser.setContentHandler(xmlgen)
+        parser.parse(findfile("test.xml"))
 
-    return parser.getSystemId() == findfile("test.xml") and \
-           parser.getPublicId() is None
+        self.assertEquals(parser.getSystemId(), findfile("test.xml"))
+        self.assertEquals(parser.getPublicId(), None)
 
 
 # ===========================================================================
@@ -507,63 +546,59 @@
 #
 # ===========================================================================
 
-def test_expat_inpsource_location():
-    parser = create_parser()
-    parser.setContentHandler(ContentHandler()) # do nothing
-    source = InputSource()
-    source.setByteStream(StringIO("<foo bar foobar>"))   #ill-formed
-    name = "a file name"
-    source.setSystemId(name)
-    try:
-        parser.parse(source)
-    except SAXException as e:
-        return e.getSystemId() == name
-
-def test_expat_incomplete():
-    parser = create_parser()
-    parser.setContentHandler(ContentHandler()) # do nothing
-    try:
-        parser.parse(StringIO("<foo>"))
-    except SAXParseException:
-        return 1 # ok, error found
-    else:
-        return 0
-
-def test_sax_parse_exception_str():
-    # pass various values from a locator to the SAXParseException to
-    # make sure that the __str__() doesn't fall apart when None is
-    # passed instead of an integer line and column number
-    #
-    # use "normal" values for the locator:
-    str(SAXParseException("message", None,
-                          DummyLocator(1, 1)))
-    # use None for the line number:
-    str(SAXParseException("message", None,
-                          DummyLocator(None, 1)))
-    # use None for the column number:
-    str(SAXParseException("message", None,
-                          DummyLocator(1, None)))
-    # use None for both:
-    str(SAXParseException("message", None,
-                          DummyLocator(None, None)))
-    return 1
-
-class DummyLocator:
-    def __init__(self, lineno, colno):
-        self._lineno = lineno
-        self._colno = colno
-
-    def getPublicId(self):
-        return "pubid"
+class ErrorReportingTest(unittest.TestCase):
+    def test_expat_inpsource_location(self):
+        parser = create_parser()
+        parser.setContentHandler(ContentHandler()) # do nothing
+        source = InputSource()
+        source.setByteStream(StringIO("<foo bar foobar>"))   #ill-formed
+        name = "a file name"
+        source.setSystemId(name)
+        try:
+            parser.parse(source)
+            self.fail()
+        except SAXException as e:
+            self.assertEquals(e.getSystemId(), name)
+
+    def test_expat_incomplete(self):
+        parser = create_parser()
+        parser.setContentHandler(ContentHandler()) # do nothing
+        self.assertRaises(SAXParseException, parser.parse, StringIO("<foo>"))
+
+    def test_sax_parse_exception_str(self):
+        # pass various values from a locator to the SAXParseException to
+        # make sure that the __str__() doesn't fall apart when None is
+        # passed instead of an integer line and column number
+        #
+        # use "normal" values for the locator:
+        str(SAXParseException("message", None,
+                              self.DummyLocator(1, 1)))
+        # use None for the line number:
+        str(SAXParseException("message", None,
+                              self.DummyLocator(None, 1)))
+        # use None for the column number:
+        str(SAXParseException("message", None,
+                              self.DummyLocator(1, None)))
+        # use None for both:
+        str(SAXParseException("message", None,
+                              self.DummyLocator(None, None)))
+
+    class DummyLocator:
+        def __init__(self, lineno, colno):
+            self._lineno = lineno
+            self._colno = colno
+
+        def getPublicId(self):
+            return "pubid"
 
-    def getSystemId(self):
-        return "sysid"
+        def getSystemId(self):
+            return "sysid"
 
-    def getLineNumber(self):
-        return self._lineno
+        def getLineNumber(self):
+            return self._lineno
 
-    def getColumnNumber(self):
-        return self._colno
+        def getColumnNumber(self):
+            return self._colno
 
 # ===========================================================================
 #
@@ -571,217 +606,91 @@
 #
 # ===========================================================================
 
-# ===== AttributesImpl
+class XmlReaderTest(XmlTestBase):
 
-def verify_empty_attrs(attrs):
-    try:
-        attrs.getValue("attr")
-        gvk = 0
-    except KeyError:
-        gvk = 1
-
-    try:
-        attrs.getValueByQName("attr")
-        gvqk = 0
-    except KeyError:
-        gvqk = 1
-
-    try:
-        attrs.getNameByQName("attr")
-        gnqk = 0
-    except KeyError:
-        gnqk = 1
-
-    try:
-        attrs.getQNameByName("attr")
-        gqnk = 0
-    except KeyError:
-        gqnk = 1
-
-    try:
-        attrs["attr"]
-        gik = 0
-    except KeyError:
-        gik = 1
-
-    return attrs.getLength() == 0 and \
-           attrs.getNames() == [] and \
-           attrs.getQNames() == [] and \
-           len(attrs) == 0 and \
-           "attr" not in  attrs and \
-           attrs.keys() == [] and \
-           attrs.get("attrs") is None and \
-           attrs.get("attrs", 25) == 25 and \
-           attrs.items() == [] and \
-           attrs.values() == [] and \
-           gvk and gvqk and gnqk and gik and gqnk
-
-def verify_attrs_wattr(attrs):
-    return attrs.getLength() == 1 and \
-           attrs.getNames() == ["attr"] and \
-           attrs.getQNames() == ["attr"] and \
-           len(attrs) == 1 and \
-           "attr" in attrs and \
-           attrs.keys() == ["attr"] and \
-           attrs.get("attr") == "val" and \
-           attrs.get("attr", 25) == "val" and \
-           attrs.items() == [("attr", "val")] and \
-           attrs.values() == ["val"] and \
-           attrs.getValue("attr") == "val" and \
-           attrs.getValueByQName("attr") == "val" and \
-           attrs.getNameByQName("attr") == "attr" and \
-           attrs["attr"] == "val" and \
-           attrs.getQNameByName("attr") == "attr"
-
-def test_attrs_empty():
-    return verify_empty_attrs(AttributesImpl({}))
-
-def test_attrs_wattr():
-    return verify_attrs_wattr(AttributesImpl({"attr" : "val"}))
-
-# ===== AttributesImpl
-
-def verify_empty_nsattrs(attrs):
-    try:
-        attrs.getValue((ns_uri, "attr"))
-        gvk = 0
-    except KeyError:
-        gvk = 1
-
-    try:
-        attrs.getValueByQName("ns:attr")
-        gvqk = 0
-    except KeyError:
-        gvqk = 1
-
-    try:
-        attrs.getNameByQName("ns:attr")
-        gnqk = 0
-    except KeyError:
-        gnqk = 1
-
-    try:
-        attrs.getQNameByName((ns_uri, "attr"))
-        gqnk = 0
-    except KeyError:
-        gqnk = 1
-
-    try:
-        attrs[(ns_uri, "attr")]
-        gik = 0
-    except KeyError:
-        gik = 1
-
-    return attrs.getLength() == 0 and \
-           attrs.getNames() == [] and \
-           attrs.getQNames() == [] and \
-           len(attrs) == 0 and \
-           (ns_uri, "attr") not in attrs and \
-           attrs.keys() == [] and \
-           attrs.get((ns_uri, "attr")) is None and \
-           attrs.get((ns_uri, "attr"), 25) == 25 and \
-           attrs.items() == [] and \
-           attrs.values() == [] and \
-           gvk and gvqk and gnqk and gik and gqnk
-
-def test_nsattrs_empty():
-    return verify_empty_nsattrs(AttributesNSImpl({}, {}))
-
-def test_nsattrs_wattr():
-    attrs = AttributesNSImpl({(ns_uri, "attr") : "val"},
-                             {(ns_uri, "attr") : "ns:attr"})
-
-    return attrs.getLength() == 1 and \
-           attrs.getNames() == [(ns_uri, "attr")] and \
-           attrs.getQNames() == ["ns:attr"] and \
-           len(attrs) == 1 and \
-           (ns_uri, "attr") in attrs and \
-           attrs.keys() == [(ns_uri, "attr")] and \
-           attrs.get((ns_uri, "attr")) == "val" and \
-           attrs.get((ns_uri, "attr"), 25) == "val" and \
-           attrs.items() == [((ns_uri, "attr"), "val")] and \
-           attrs.values() == ["val"] and \
-           attrs.getValue((ns_uri, "attr")) == "val" and \
-           attrs.getValueByQName("ns:attr") == "val" and \
-           attrs.getNameByQName("ns:attr") == (ns_uri, "attr") and \
-           attrs[(ns_uri, "attr")] == "val" and \
-           attrs.getQNameByName((ns_uri, "attr")) == "ns:attr"
-
-
-# During the development of Python 2.5, an attempt to move the "xml"
-# package implementation to a new package ("xmlcore") proved painful.
-# The goal of this change was to allow applications to be able to
-# obtain and rely on behavior in the standard library implementation
-# of the XML support without needing to be concerned about the
-# availability of the PyXML implementation.
-#
-# While the existing import hackery in Lib/xml/__init__.py can cause
-# PyXML's _xmlpus package to supplant the "xml" package, that only
-# works because either implementation uses the "xml" package name for
-# imports.
-#
-# The move resulted in a number of problems related to the fact that
-# the import machinery's "package context" is based on the name that's
-# being imported rather than the __name__ of the actual package
-# containment; it wasn't possible for the "xml" package to be replaced
-# by a simple module that indirected imports to the "xmlcore" package.
-#
-# The following two tests exercised bugs that were introduced in that
-# attempt.  Keeping these tests around will help detect problems with
-# other attempts to provide reliable access to the standard library's
-# implementation of the XML support.
-
-def test_sf_1511497():
-    # Bug report: http://www.python.org/sf/1511497
-    import sys
-    old_modules = sys.modules.copy()
-    for modname in list(sys.modules.keys()):
-        if modname.startswith("xml."):
-            del sys.modules[modname]
-    try:
-        import xml.sax.expatreader
-        module = xml.sax.expatreader
-        return module.__name__ == "xml.sax.expatreader"
-    finally:
-        sys.modules.update(old_modules)
-
-def test_sf_1513611():
-    # Bug report: http://www.python.org/sf/1513611
-    sio = StringIO("invalid")
-    parser = make_parser()
-    from xml.sax import SAXParseException
-    try:
-        parser.parse(sio)
-    except SAXParseException:
-        return True
-    else:
-        return False
-
-# ===== Main program
-
-def make_test_output():
-    parser = create_parser()
-    result = StringIO()
-    xmlgen = XMLGenerator(result)
-
-    parser.setContentHandler(xmlgen)
-    parser.parse(findfile("test"+os.extsep+"xml"))
-
-    outf = open(findfile("test"+os.extsep+"xml"+os.extsep+"out"), "w")
-    outf.write(result.getvalue())
-    outf.close()
-
-items = sorted(locals().items())
-for (name, value) in items:
-    if name[ : 5] == "test_":
-        confirm(value(), name)
-# We delete the items variable so that the assignment to items above
-# doesn't pick up the old value of items (which messes with attempts
-# to find reference leaks).
-del items
-
-if verbose:
-    print("%d tests, %d failures" % (tests, len(failures)))
-if failures:
-    raise TestFailed("%d of %d tests failed: %s"
-                     % (len(failures), tests, ", ".join(failures)))
+    # ===== AttributesImpl
+    def test_attrs_empty(self):
+        self.verify_empty_attrs(AttributesImpl({}))
+
+    def test_attrs_wattr(self):
+        self.verify_attrs_wattr(AttributesImpl({"attr" : "val"}))
+
+    def test_nsattrs_empty(self):
+        self.verify_empty_nsattrs(AttributesNSImpl({}, {}))
+
+    def test_nsattrs_wattr(self):
+        attrs = AttributesNSImpl({(ns_uri, "attr") : "val"},
+                                 {(ns_uri, "attr") : "ns:attr"})
+
+        self.assertEquals(attrs.getLength(), 1)
+        self.assertEquals(attrs.getNames(), [(ns_uri, "attr")])
+        self.assertEquals(attrs.getQNames(), ["ns:attr"])
+        self.assertEquals(len(attrs), 1)
+        self.assertTrue((ns_uri, "attr") in attrs)
+        self.assertEquals(list(attrs.keys()), [(ns_uri, "attr")])
+        self.assertEquals(attrs.get((ns_uri, "attr")), "val")
+        self.assertEquals(attrs.get((ns_uri, "attr"), 25), "val")
+        self.assertEquals(list(attrs.items()), [((ns_uri, "attr"), "val")])
+        self.assertEquals(list(attrs.values()), ["val"])
+        self.assertEquals(attrs.getValue((ns_uri, "attr")), "val")
+        self.assertEquals(attrs.getValueByQName("ns:attr"), "val")
+        self.assertEquals(attrs.getNameByQName("ns:attr"), (ns_uri, "attr"))
+        self.assertEquals(attrs[(ns_uri, "attr")], "val")
+        self.assertEquals(attrs.getQNameByName((ns_uri, "attr")), "ns:attr")
+
+
+    # During the development of Python 2.5, an attempt to move the "xml"
+    # package implementation to a new package ("xmlcore") proved painful.
+    # The goal of this change was to allow applications to be able to
+    # obtain and rely on behavior in the standard library implementation
+    # of the XML support without needing to be concerned about the
+    # availability of the PyXML implementation.
+    #
+    # While the existing import hackery in Lib/xml/__init__.py can cause
+    # PyXML's _xmlpus package to supplant the "xml" package, that only
+    # works because either implementation uses the "xml" package name for
+    # imports.
+    #
+    # The move resulted in a number of problems related to the fact that
+    # the import machinery's "package context" is based on the name that's
+    # being imported rather than the __name__ of the actual package
+    # containment; it wasn't possible for the "xml" package to be replaced
+    # by a simple module that indirected imports to the "xmlcore" package.
+    #
+    # The following two tests exercised bugs that were introduced in that
+    # attempt.  Keeping these tests around will help detect problems with
+    # other attempts to provide reliable access to the standard library's
+    # implementation of the XML support.
+
+    def test_sf_1511497(self):
+        # Bug report: http://www.python.org/sf/1511497
+        import sys
+        old_modules = sys.modules.copy()
+        for modname in list(sys.modules.keys()):
+            if modname.startswith("xml."):
+                del sys.modules[modname]
+        try:
+            import xml.sax.expatreader
+            module = xml.sax.expatreader
+            self.assertEquals(module.__name__, "xml.sax.expatreader")
+        finally:
+            sys.modules.update(old_modules)
+
+    def test_sf_1513611(self):
+        # Bug report: http://www.python.org/sf/1513611
+        sio = StringIO("invalid")
+        parser = make_parser()
+        from xml.sax import SAXParseException
+        self.assertRaises(SAXParseException, parser.parse, sio)
+
+
+def unittest_main():
+    run_unittest(MakeParserTest,
+                 SaxutilsTest,
+                 XmlgenTest,
+                 ExpatReaderTest,
+                 ErrorReportingTest,
+                 XmlReaderTest)
+
+if __name__ == "__main__":
+    unittest_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_scope.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_scope.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_scope.py	Wed Jul 11 15:40:56 2007
@@ -187,25 +187,25 @@
         check_syntax_error(self, """\
 def unoptimized_clash1(strip):
     def f(s):
-        from string import *
-        return strip(s) # ambiguity: free or local
+        from sys import *
+        return getrefcount(s) # ambiguity: free or local
     return f
 """)
 
         check_syntax_error(self, """\
 def unoptimized_clash2():
-    from string import *
+    from sys import *
     def f(s):
-        return strip(s) # ambiguity: global or local
+        return getrefcount(s) # ambiguity: global or local
     return f
 """)
 
         check_syntax_error(self, """\
 def unoptimized_clash2():
-    from string import *
+    from sys import *
     def g():
         def f(s):
-            return strip(s) # ambiguity: global or local
+            return getrefcount(s) # ambiguity: global or local
         return f
 """)
 
@@ -219,24 +219,24 @@
         check_syntax_error(self, """\
 def f():
     def g():
-        from string import *
-        return strip # global or local?
+        from sys import *
+        return getrefcount # global or local?
 """)
 
         # and verify a few cases that should work
 
         exec("""
 def noproblem1():
-    from string import *
+    from sys import *
     f = lambda x:x
 
 def noproblem2():
-    from string import *
+    from sys import *
     def f(x):
         return x + 1
 
 def noproblem3():
-    from string import *
+    from sys import *
     def f(x):
         global y
         y = x
@@ -323,13 +323,6 @@
 
         self.assertEqual(makeReturner2(a=11)()['a'], 11)
 
-        def makeAddPair((a, b)):
-            def addPair((c, d)):
-                return (a + c, b + d)
-            return addPair
-
-        self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202))
-
     def testScopeOfGlobalStmt(self):
 # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
 
@@ -477,6 +470,39 @@
         del d['h']
         self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})
 
+    def testLocalsClass(self):
+        # This test verifies that calling locals() does not pollute
+        # the local namespace of the class with free variables.  Old
+        # versions of Python had a bug, where a free variable being
+        # passed through a class namespace would be inserted into
+        # locals() by locals() or exec or a trace function.
+        #
+        # The real bug lies in frame code that copies variables
+        # between fast locals and the locals dict, e.g. when executing
+        # a trace function.
+
+        def f(x):
+            class C:
+                x = 12
+                def m(self):
+                    return x
+                locals()
+            return C
+
+        self.assertEqual(f(1).x, 12)
+
+        def f(x):
+            class C:
+                y = x
+                def m(self):
+                    return x
+                z = list(locals())
+            return C
+
+        varnames = f(1).z
+        self.assert_("x" not in varnames)
+        self.assert_("y" in varnames)
+
     def testBoundAndFree(self):
         # var is bound and free in class
 
@@ -518,10 +544,10 @@
             return lambda: x + 1
 
         g = f(3)
-        self.assertRaises(TypeError, eval, g.func_code)
+        self.assertRaises(TypeError, eval, g.__code__)
 
         try:
-            exec(g.func_code, {})
+            exec(g.__code__, {})
         except TypeError:
             pass
         else:
@@ -555,6 +581,90 @@
 
         f(4)()
 
+    def testNonLocalFunction(self):
+
+        def f(x):
+            def inc():
+                nonlocal x
+                x += 1
+                return x
+            def dec():
+                nonlocal x
+                x -= 1
+                return x
+            return inc, dec
+
+        inc, dec = f(0)
+        self.assertEqual(inc(), 1)
+        self.assertEqual(inc(), 2)
+        self.assertEqual(dec(), 1)
+        self.assertEqual(dec(), 0)
+
+    def testNonLocalMethod(self):
+
+        def f(x):
+            class c:
+                def inc(self):
+                    nonlocal x
+                    x += 1
+                    return x
+                def dec(self):
+                    nonlocal x
+                    x -= 1
+                    return x
+            return c()
+
+        c = f(0)
+        self.assertEqual(c.inc(), 1)
+        self.assertEqual(c.inc(), 2)
+        self.assertEqual(c.dec(), 1)
+        self.assertEqual(c.dec(), 0)
+
+    def testNonLocalClass(self):
+
+        def f(x):
+            class c:
+                nonlocal x
+                x += 1
+                def get(self):
+                    return x
+            return c()
+
+        c = f(0)
+        self.assertEqual(c.get(), 1)
+        self.assert_("x" not in c.__class__.__dict__)
+
+
+    def testNonLocalGenerator(self):
+
+        def f(x):
+            def g(y):
+                nonlocal x
+                for i in range(y):
+                    x += 1
+                    yield x
+            return g
+
+        g = f(0)
+        self.assertEqual(list(g(5)), [1, 2, 3, 4, 5])
+
+    def testNestedNonLocal(self):
+
+        def f(x):
+            def g():
+                nonlocal x
+                x -= 2
+                def h():
+                    nonlocal x
+                    x += 4
+                    return x
+                return h
+            return g
+
+        g = f(1)
+        h = g()
+        self.assertEqual(h(), 3)
+
 
 def test_main():
     run_unittest(ScopeTests)

Modified: python/branches/p3yk-noslice/Lib/test/test_set.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_set.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_set.py	Wed Jul 11 15:40:56 2007
@@ -227,7 +227,7 @@
         # Create a nest of cycles to exercise overall ref count check
         class A:
             pass
-        s = set(A() for i in xrange(1000))
+        s = set(A() for i in range(1000))
         for elem in s:
             elem.cycle = s
             elem.sub = elem
@@ -283,15 +283,22 @@
 
     def test_do_not_rehash_dict_keys(self):
         n = 10
-        d = dict.fromkeys(map(HashCountingInt, xrange(n)))
+        d = dict.fromkeys(map(HashCountingInt, range(n)))
         self.assertEqual(sum(elem.hash_count for elem in d), n)
         s = self.thetype(d)
         self.assertEqual(sum(elem.hash_count for elem in d), n)
         s.difference(d)
-        self.assertEqual(sum(elem.hash_count for elem in d), n)    
+        self.assertEqual(sum(elem.hash_count for elem in d), n)
         if hasattr(s, 'symmetric_difference_update'):
             s.symmetric_difference_update(d)
-        self.assertEqual(sum(elem.hash_count for elem in d), n)      
+        self.assertEqual(sum(elem.hash_count for elem in d), n)
+        d2 = dict.fromkeys(set(d))
+        self.assertEqual(sum(elem.hash_count for elem in d), n)
+        d3 = dict.fromkeys(frozenset(d))
+        self.assertEqual(sum(elem.hash_count for elem in d), n)
+        d3 = dict.fromkeys(frozenset(d), 123)
+        self.assertEqual(sum(elem.hash_count for elem in d), n)
+        self.assertEqual(d3, dict.fromkeys(d, 123))
 
 class TestSet(TestJointOps):
     thetype = set
@@ -370,7 +377,7 @@
         s.discard(self.thetype(self.word))
 
     def test_pop(self):
-        for i in xrange(len(self.s)):
+        for i in range(len(self.s)):
             elem = self.s.pop()
             self.assert_(elem not in self.s)
         self.assertRaises(KeyError, self.s.pop)
@@ -518,7 +525,7 @@
         f = frozenset()
         efs = [frozenset(), frozenset([]), frozenset(()), frozenset(''),
                frozenset(), frozenset([]), frozenset(()), frozenset(''),
-               frozenset(xrange(0)), frozenset(frozenset()),
+               frozenset(range(0)), frozenset(frozenset()),
                frozenset(f), f]
         # All of the empty frozensets should have just one id()
         self.assertEqual(len(set(map(id, efs))), 1)
@@ -534,9 +541,9 @@
 
         # make sure that all permutations give the same hash value
         n = 100
-        seq = [randrange(n) for i in xrange(n)]
+        seq = [randrange(n) for i in range(n)]
         results = set()
-        for i in xrange(200):
+        for i in range(200):
             shuffle(seq)
             results.add(hash(self.thetype(seq)))
         self.assertEqual(len(results), 1)
@@ -546,7 +553,7 @@
         self.assertEqual(id(self.s), id(dup))
 
     def test_frozen_as_dictkey(self):
-        seq = range(10) + list('abcdefg') + ['apple']
+        seq = list(range(10)) + list('abcdefg') + ['apple']
         key1 = self.thetype(seq)
         key2 = self.thetype(reversed(seq))
         self.assertEqual(key1, key2)
@@ -564,7 +571,7 @@
         hashvalues = set()
         addhashvalue = hashvalues.add
         elemmasks = [(i+1, 1<<i) for i in range(n)]
-        for i in xrange(2**n):
+        for i in range(2**n):
             addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i])))
         self.assertEqual(len(hashvalues), 2**n)
 
@@ -594,7 +601,7 @@
         F = Frozenset()
         efs = [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
                Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
-               Frozenset(xrange(0)), Frozenset(Frozenset()),
+               Frozenset(range(0)), Frozenset(Frozenset()),
                Frozenset(frozenset()), f, F, Frozenset(f), Frozenset(F)]
         # All empty frozenset subclass instances should have different ids
         self.assertEqual(len(set(map(id, efs))), len(efs))
@@ -768,7 +775,7 @@
         set([1,2,3])
         set((1,2,3))
         set({'one':1, 'two':2, 'three':3})
-        set(xrange(3))
+        set(range(3))
         set('abc')
         set(gooditer())
 
@@ -1261,7 +1268,7 @@
 class TestOnlySetsGenerator(TestOnlySetsInBinaryOps):
     def setUp(self):
         def gen():
-            for i in xrange(0, 10, 2):
+            for i in range(0, 10, 2):
                 yield i
         self.set   = set((1, 2, 3))
         self.other = gen()
@@ -1382,7 +1389,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
@@ -1402,14 +1409,14 @@
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
-    def next(self):
+    def __next__(self):
         if self.i >= len(self.seqn): raise StopIteration
         v = self.seqn[self.i]
         self.i += 1
         return v
 
 class N:
-    'Iterator missing next()'
+    'Iterator missing __next__()'
     def __init__(self, seqn):
         self.seqn = seqn
         self.i = 0
@@ -1423,7 +1430,7 @@
         self.i = 0
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         3 // 0
 
 class S:
@@ -1432,7 +1439,7 @@
         pass
     def __iter__(self):
         return self
-    def next(self):
+    def __next__(self):
         raise StopIteration
 
 from itertools import chain, imap
@@ -1444,7 +1451,7 @@
 
     def test_constructor(self):
         for cons in (set, frozenset):
-            for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+            for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
                 for g in (G, I, Ig, S, L, R):
                     self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr))
                 self.assertRaises(TypeError, cons , X(s))
@@ -1453,7 +1460,7 @@
 
     def test_inline_methods(self):
         s = set('november')
-        for data in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5), 'december'):
+        for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
             for meth in (s.union, s.intersection, s.difference, s.symmetric_difference):
                 for g in (G, I, Ig, L, R):
                     expected = meth(data)
@@ -1464,7 +1471,7 @@
                 self.assertRaises(ZeroDivisionError, meth, E(s))
 
     def test_inplace_methods(self):
-        for data in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5), 'december'):
+        for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
             for methname in ('update', 'intersection_update',
                              'difference_update', 'symmetric_difference_update'):
                 for g in (G, I, Ig, S, L, R):
@@ -1522,7 +1529,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_sha.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_sha.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,52 +0,0 @@
-# Testing sha module (NIST's Secure Hash Algorithm)
-
-# use the three examples from Federal Information Processing Standards
-# Publication 180-1, Secure Hash Standard,  1995 April 17
-# http://www.itl.nist.gov/div897/pubs/fip180-1.htm
-
-import sha
-import unittest
-from test import test_support
-
-
-class SHATestCase(unittest.TestCase):
-    def check(self, data, digest):
-        # Check digest matches the expected value
-        obj = sha.new(data)
-        computed = obj.hexdigest()
-        self.assert_(computed == digest)
-
-        # Verify that the value doesn't change between two consecutive
-        # digest operations.
-        computed_again = obj.hexdigest()
-        self.assert_(computed == computed_again)
-
-        # Check hexdigest() output matches digest()'s output
-        digest = obj.digest()
-        hexd = ""
-        for c in digest:
-            hexd += '%02x' % ord(c)
-        self.assert_(computed == hexd)
-
-    def test_case_1(self):
-        self.check("abc",
-                   "a9993e364706816aba3e25717850c26c9cd0d89d")
-
-    def test_case_2(self):
-        self.check("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
-                   "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
-
-    def test_case_3(self):
-        self.check("a" * 1000000,
-                   "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
-
-    def test_case_4(self):
-        self.check(chr(0xAA) * 80,
-                   '4ca0ef38f1794b28a8f8ee110ee79d48ce13be25')
-
-def test_main():
-    test_support.run_unittest(SHATestCase)
-
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_slice.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_slice.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_slice.py	Wed Jul 11 15:40:56 2007
@@ -2,6 +2,7 @@
 
 import unittest
 from test import test_support
+from cPickle import loads, dumps
 
 import sys
 
@@ -88,10 +89,28 @@
         )
         self.assertEqual(slice(-100, 100, 2).indices(10), (0, 10,  2))
 
-        self.assertEqual(range(10)[::sys.maxint - 1], [0])
+        self.assertEqual(list(range(10))[::sys.maxint - 1], [0])
 
         self.assertRaises(OverflowError, slice(None).indices, 1<<100)
 
+    def test_setslice_without_getslice(self):
+        tmp = []
+        class X(object):
+            def __setitem__(self, idx, value):
+                tmp.append((idx, value))
+
+        x = X()
+        x[1:2] = 42
+        self.assertEquals(tmp, [(slice(1, 2), 42)])
+
+    def test_pickle(self):
+        s = slice(10, 20, 3)
+        for protocol in (0,1,2):
+            t = loads(dumps(s, protocol))
+            self.assertEqual(s, t)
+            self.assertEqual(s.indices(15), t.indices(15))
+            self.assertNotEqual(id(s), id(t))
+
 def test_main():
     test_support.run_unittest(SliceTest)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_socket.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_socket.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_socket.py	Wed Jul 11 15:40:56 2007
@@ -75,7 +75,7 @@
 
     Note, the server setup function cannot call any blocking
     functions that rely on the client thread during setup,
-    unless serverExplicityReady() is called just before
+    unless serverExplicitReady() is called just before
     the blocking call (such as in setting up a client/server
     connection and performing the accept() in setUp().
     """
@@ -125,7 +125,7 @@
         self.server_ready.wait()
         self.client_ready.set()
         self.clientSetUp()
-        if not callable(test_func):
+        if not hasattr(test_func, '__call__'):
             raise TypeError, "test_func must be a callable function"
         try:
             test_func()
@@ -597,6 +597,13 @@
     def _testRecvFrom(self):
         self.cli.sendto(MSG, 0, (HOST, PORT))
 
+    def testRecvFromNegative(self):
+        # Negative lengths passed to recvfrom should give ValueError.
+        self.assertRaises(ValueError, self.serv.recvfrom, -1)
+
+    def _testRecvFromNegative(self):
+        self.cli.sendto(MSG, 0, (HOST, PORT))
+
 class TCPCloserTest(ThreadedTCPSocketTest):
 
     def testClose(self):
@@ -810,6 +817,98 @@
     bufsize = 2 # Exercise the buffering code
 
 
+class NetworkConnectionTest(object):
+    """Prove network connection."""
+    def clientSetUp(self):
+        self.cli = socket.create_connection((HOST, PORT))
+        self.serv_conn = self.cli
+
+class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
+    """Tests that NetworkConnection does not break existing TCP functionality.
+    """
+
+class NetworkConnectionNoServer(unittest.TestCase):
+    def testWithoutServer(self):
+        self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT)))
+
+class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
+
+    def __init__(self, methodName='runTest'):
+        SocketTCPTest.__init__(self, methodName=methodName)
+        ThreadableTest.__init__(self)
+
+    def clientSetUp(self):
+        pass
+
+    def clientTearDown(self):
+        self.cli.close()
+        self.cli = None
+        ThreadableTest.clientTearDown(self)
+
+    def _justAccept(self):
+        conn, addr = self.serv.accept()
+
+    testFamily = _justAccept
+    def _testFamily(self):
+        self.cli = socket.create_connection((HOST, PORT), timeout=30)
+        self.assertEqual(self.cli.family, 2)
+
+    testTimeoutDefault = _justAccept
+    def _testTimeoutDefault(self):
+        self.cli = socket.create_connection((HOST, PORT))
+        self.assertTrue(self.cli.gettimeout() is None)
+
+    testTimeoutValueNamed = _justAccept
+    def _testTimeoutValueNamed(self):
+        self.cli = socket.create_connection((HOST, PORT), timeout=30)
+        self.assertEqual(self.cli.gettimeout(), 30)
+
+    testTimeoutValueNonamed = _justAccept
+    def _testTimeoutValueNonamed(self):
+        self.cli = socket.create_connection((HOST, 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, PORT), timeout=None)
+        finally:
+            socket.setdefaulttimeout(previous)
+        self.assertEqual(self.cli.gettimeout(), 30)
+
+
+class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
+
+    def __init__(self, methodName='runTest'):
+        SocketTCPTest.__init__(self, methodName=methodName)
+        ThreadableTest.__init__(self)
+
+    def clientSetUp(self):
+        pass
+
+    def clientTearDown(self):
+        self.cli.close()
+        self.cli = None
+        ThreadableTest.clientTearDown(self)
+
+    def testInsideTimeout(self):
+        conn, addr = self.serv.accept()
+        time.sleep(3)
+        conn.send("done!")
+    testOutsideTimeout = testInsideTimeout
+
+    def _testInsideTimeout(self):
+        self.cli = sock = socket.create_connection((HOST, PORT))
+        data = sock.recv(5)
+        self.assertEqual(data, "done!")
+
+    def _testOutsideTimeout(self):
+        self.cli = sock = socket.create_connection((HOST, PORT), timeout=1)
+        self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
+
+
 class Urllib2FileobjectTest(unittest.TestCase):
 
     # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that
@@ -977,7 +1076,7 @@
 
 def test_main():
     tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
-             TestExceptions, BufferIOTest]
+             TestExceptions, BufferIOTest, BasicTCPTest2]
     if sys.platform != 'mac':
         tests.extend([ BasicUDPTest, UDPTimeoutTest ])
 
@@ -988,6 +1087,9 @@
         LineBufferedFileObjectClassTestCase,
         SmallBufferedFileObjectClassTestCase,
         Urllib2FileobjectTest,
+        NetworkConnectionNoServer,
+        NetworkConnectionAttributesTest,
+        NetworkConnectionBehaviourTest,
     ])
     if hasattr(socket, "socketpair"):
         tests.append(BasicSocketPairTest)

Modified: python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py	Wed Jul 11 15:40:56 2007
@@ -1,128 +1,221 @@
 # Test just the SSL support in the socket module, in a moderately bogus way.
 
 import sys
+import unittest
 from test import test_support
 import socket
 import errno
+import threading
+import subprocess
+import time
+import os
+import urllib
 
-# Optionally test SSL support.  This requires the 'network' resource as given
-# on the regrtest command line.
-skip_expected = not (test_support.is_resource_enabled('network') and
-                     hasattr(socket, "ssl"))
+# Optionally test SSL support, if we have it in the tested platform
+skip_expected = not hasattr(socket, "ssl")
 
-def test_basic():
-    test_support.requires('network')
+class ConnectedTests(unittest.TestCase):
 
-    import urllib
-
-    if test_support.verbose:
-        print("test_basic ...")
-
-    socket.RAND_status()
-    try:
-        socket.RAND_egd(1)
-    except TypeError:
-        pass
-    else:
-        print("didn't raise TypeError")
-    socket.RAND_add("this is a random string", 75.0)
+    def testBasic(self):
+        socket.RAND_status()
+        try:
+            socket.RAND_egd(1)
+        except TypeError:
+            pass
+        else:
+            print("didn't raise TypeError")
+        socket.RAND_add("this is a random string", 75.0)
 
-    f = urllib.urlopen('https://sf.net')
-    buf = f.read()
-    f.close()
-
-def test_timeout():
-    test_support.requires('network')
-
-    def error_msg(extra_msg):
-        print("""\
-    WARNING:  an attempt to connect to %r %s, in
-    test_timeout.  That may be legitimate, but is not the outcome we hoped
-    for.  If this message is seen often, test_timeout should be changed to
-    use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr)
-
-    if test_support.verbose:
-        print("test_timeout ...")
-
-    # A service which issues a welcome banner (without need to write
-    # anything).
-    # XXX ("gmail.org", 995) has been unreliable so far, from time to time
-    # XXX non-responsive for hours on end (& across all buildbot slaves,
-    # XXX so that's not just a local thing).
-    ADDR = "gmail.org", 995
+        with test_support.transient_internet():
+            f = urllib.urlopen('https://sf.net')
+        buf = f.read()
+        f.close()
+
+    def testTimeout(self):
+        def error_msg(extra_msg):
+            print("""\
+        WARNING:  an attempt to connect to %r %s, in
+        test_timeout.  That may be legitimate, but is not the outcome we
+        hoped for.  If this message is seen often, test_timeout should be
+        changed to use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr)
+
+        # A service which issues a welcome banner (without need to write
+        # anything).
+        # XXX ("gmail.org", 995) has been unreliable so far, from time to
+        # XXX time non-responsive for hours on end (& across all buildbot
+        # XXX slaves, so that's not just a local thing).
+        ADDR = "gmail.org", 995
 
-    s = socket.socket()
-    s.settimeout(30.0)
-    try:
-        s.connect(ADDR)
-    except socket.timeout:
-        error_msg('timed out')
-        return
-    except socket.error as exc:  # In case connection is refused.
-        if exc.args[0] == errno.ECONNREFUSED:
-            error_msg('was refused')
+        s = socket.socket()
+        s.settimeout(30.0)
+        try:
+            s.connect(ADDR)
+        except socket.timeout:
+            error_msg('timed out')
             return
-        else:
-            raise
+        except socket.error as exc:  # In case connection is refused.
+            if exc.args[0] == errno.ECONNREFUSED:
+                error_msg('was refused')
+                return
+            else:
+                raise
+
+        ss = socket.ssl(s)
+        # Read part of return welcome banner twice.
+        ss.read(1)
+        ss.read(1)
+        s.close()
+
+class BasicTests(unittest.TestCase):
+
+    def testRudeShutdown(self):
+        # Some random port to connect to.
+        PORT = [9934]
+
+        listener_ready = threading.Event()
+        listener_gone = threading.Event()
+
+        # `listener` runs in a thread.  It opens a socket listening on
+        # PORT, and sits in an accept() until the main thread connects.
+        # Then it rudely closes the socket, and sets Event `listener_gone`
+        # to let the main thread know the socket is gone.
+        def listener():
+            s = socket.socket()
+            PORT[0] = test_support.bind_port(s, '', PORT[0])
+            s.listen(5)
+            listener_ready.set()
+            s.accept()
+            s = None # reclaim the socket object, which also closes it
+            listener_gone.set()
+
+        def connector():
+            listener_ready.wait()
+            s = socket.socket()
+            s.connect(('localhost', PORT[0]))
+            listener_gone.wait()
+            try:
+                ssl_sock = socket.ssl(s)
+            except socket.sslerror:
+                pass
+            else:
+                raise test_support.TestFailed(
+                      'connecting to closed SSL socket should have failed')
 
-    ss = socket.ssl(s)
-    # Read part of return welcome banner twice.
-    ss.read(1)
-    ss.read(1)
-    s.close()
-
-def test_rude_shutdown():
-    if test_support.verbose:
-        print("test_rude_shutdown ...")
+        t = threading.Thread(target=listener)
+        t.start()
+        connector()
+        t.join()
 
-    try:
-        import threading
-    except ImportError:
-        return
-
-    # Some random port to connect to.
-    PORT = [9934]
-
-    listener_ready = threading.Event()
-    listener_gone = threading.Event()
-
-    # `listener` runs in a thread.  It opens a socket listening on PORT, and
-    # sits in an accept() until the main thread connects.  Then it rudely
-    # closes the socket, and sets Event `listener_gone` to let the main thread
-    # know the socket is gone.
-    def listener():
+class OpenSSLTests(unittest.TestCase):
+
+    def testBasic(self):
         s = socket.socket()
-        PORT[0] = test_support.bind_port(s, '', PORT[0])
-        s.listen(5)
-        listener_ready.set()
-        s.accept()
-        s = None # reclaim the socket object, which also closes it
-        listener_gone.set()
+        s.connect(("localhost", 4433))
+        ss = socket.ssl(s)
+        ss.write("Foo\n")
+        i = ss.read(4)
+        self.assertEqual(i, "Foo\n")
+        s.close()
+
+    def testMethods(self):
+        # read & write is already tried in the Basic test
+        # now we'll try to get the server info about certificates
+        # this came from the certificate I used, one I found in /usr/share/openssl
+        info = "/C=PT/ST=Queensland/L=Lisboa/O=Neuronio, Lda./OU=Desenvolvimento/CN=brutus.neuronio.pt/emailAddress=sampo at iki.fi"
 
-    def connector():
-        listener_ready.wait()
         s = socket.socket()
-        s.connect(('localhost', PORT[0]))
-        listener_gone.wait()
+        s.connect(("localhost", 4433))
+        ss = socket.ssl(s)
+        cert = ss.server()
+        self.assertEqual(cert, info)
+        cert = ss.issuer()
+        self.assertEqual(cert, info)
+        s.close()
+
+
+class OpenSSLServer(threading.Thread):
+    def __init__(self):
+        self.s = None
+        self.keepServing = True
+        self._external()
+        if self.haveServer:
+            threading.Thread.__init__(self)
+
+    def _external(self):
+        # let's find the .pem files
+        curdir = os.path.dirname(__file__) or os.curdir
+        cert_file = os.path.join(curdir, "ssl_cert.pem")
+        if not os.access(cert_file, os.F_OK):
+            raise ValueError("No cert file found! (tried %r)" % cert_file)
+        key_file = os.path.join(curdir, "ssl_key.pem")
+        if not os.access(key_file, os.F_OK):
+            raise ValueError("No key file found! (tried %r)" % key_file)
+
         try:
-            ssl_sock = socket.ssl(s)
-        except socket.sslerror:
-            pass
+            cmd = "openssl s_server -cert %s -key %s -quiet" % (cert_file, key_file)
+            self.s = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE,
+                                       stdout=subprocess.PIPE,
+                                       stderr=subprocess.STDOUT)
+            time.sleep(1)
+        except:
+            self.haveServer = False
         else:
-            raise test_support.TestFailed(
-                      'connecting to closed SSL socket should have failed')
-
-    t = threading.Thread(target=listener)
-    t.start()
-    connector()
-    t.join()
+            # let's try if it is actually up
+            try:
+                s = socket.socket()
+                s.connect(("localhost", 4433))
+                s.close()
+                if self.s.stdout.readline() != "ERROR\n":
+                    raise ValueError
+            except:
+                self.haveServer = False
+            else:
+                self.haveServer = True
+
+    def run(self):
+        while self.keepServing:
+            time.sleep(.5)
+            l = self.s.stdout.readline()
+            self.s.stdin.write(l)
+
+    def shutdown(self):
+        self.keepServing = False
+        if not self.s:
+            return
+        if sys.platform == "win32":
+            subprocess.TerminateProcess(int(self.s._handle), -1)
+        else:
+            os.kill(self.s.pid, 15)
 
 def test_main():
     if not hasattr(socket, "ssl"):
         raise test_support.TestSkipped("socket module has no ssl support")
-    test_rude_shutdown()
-    test_basic()
-    test_timeout()
+
+    tests = [BasicTests]
+
+    if test_support.is_resource_enabled('network'):
+        tests.append(ConnectedTests)
+
+    # in these platforms we can kill the openssl process
+    if sys.platform in ("sunos5", "darwin", "linux1",
+                        "linux2", "win32", "hp-ux11"):
+
+        server = OpenSSLServer()
+        if server.haveServer:
+            tests.append(OpenSSLTests)
+            server.start()
+    else:
+        server = None
+
+    thread_info = test_support.threading_setup()
+
+    try:
+        test_support.run_unittest(*tests)
+    finally:
+        if server is not None and server.haveServer:
+            server.shutdown()
+
+    test_support.threading_cleanup(*thread_info)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_socketserver.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_socketserver.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_socketserver.py	Wed Jul 11 15:40:56 2007
@@ -74,6 +74,7 @@
         self.__addr = addr
         self.__svrcls = svrcls
         self.__hdlrcls = hdlrcls
+        self.ready = threading.Event()
     def run(self):
         class svrcls(MyMixinServer, self.__svrcls):
             pass
@@ -81,9 +82,13 @@
         svr = svrcls(self.__addr, self.__hdlrcls)
         # pull the address out of the server in case it changed
         # this can happen if another process is using the port
-        addr = getattr(svr, 'server_address')
+        addr = svr.server_address
         if addr:
             self.__addr = addr
+            if self.__addr != svr.socket.getsockname():
+                raise RuntimeError('server_address was %s, expected %s' %
+                                       (self.__addr, svr.socket.getsockname()))
+        self.ready.set()
         if verbose: print("thread: serving three times")
         svr.serve_a_few()
         if verbose: print("thread: done")
@@ -136,7 +141,9 @@
         t.start()
         if verbose: print("server running")
         for i in range(NREQ):
-            time.sleep(DELAY)
+            t.ready.wait(10*DELAY)
+            if not t.ready.isSet():
+                raise RuntimeError("Server not ready within a reasonable time")
             if verbose: print("test client", i)
             testfunc(proto, addr)
         if verbose: print("waiting for server")

Modified: python/branches/p3yk-noslice/Lib/test/test_sort.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sort.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_sort.py	Wed Jul 11 15:40:56 2007
@@ -75,7 +75,7 @@
                 return "Stable(%d, %d)" % (self.key, self.index)
 
         for n in sizes:
-            x = range(n)
+            x = list(range(n))
             if verbose:
                 print("Testing size", n)
 
@@ -115,7 +115,7 @@
                 Complains.maybe_complain = False
                 check("exception during sort left some permutation", x, s)
 
-            s = [Stable(random.randrange(10), i) for i in xrange(n)]
+            s = [Stable(random.randrange(10), i) for i in range(n)]
             augmented = [(e, e.index) for e in s]
             augmented.sort()    # forced stable because ties broken by index
             x = [e for e, i in augmented] # a stable sort of s
@@ -144,10 +144,10 @@
     def test_cmpNone(self):
         # Testing None as a comparison function.
 
-        L = range(50)
+        L = list(range(50))
         random.shuffle(L)
         L.sort(None)
-        self.assertEqual(L, range(50))
+        self.assertEqual(L, list(range(50)))
 
     def test_undetected_mutation(self):
         # Python 2.4a1 did not always detect mutation
@@ -182,9 +182,9 @@
         self.assertRaises(TypeError, data.sort, None, lambda x,y: 0)
 
     def test_stability(self):
-        data = [(random.randrange(100), i) for i in xrange(200)]
+        data = [(random.randrange(100), i) for i in range(200)]
         copy = data[:]
-        data.sort(key=lambda (x,y): x)  # sort on the random first field
+        data.sort(key=lambda t: t[0])   # sort on the random first field
         copy.sort()                     # sort using both fields
         self.assertEqual(data, copy)    # should get the same result
 
@@ -204,13 +204,13 @@
 
     def test_key_with_exception(self):
         # Verify that the wrapper has been removed
-        data = range(-2,2)
+        data = list(range(-2, 2))
         dup = data[:]
         self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1/x)
         self.assertEqual(data, dup)
 
     def test_key_with_mutation(self):
-        data = range(10)
+        data = list(range(10))
         def k(x):
             del data[:]
             data[:] = range(20)
@@ -218,7 +218,7 @@
         self.assertRaises(ValueError, data.sort, key=k)
 
     def test_key_with_mutating_del(self):
-        data = range(10)
+        data = list(range(10))
         class SortKiller(object):
             def __init__(self, x):
                 pass
@@ -230,7 +230,7 @@
         self.assertRaises(ValueError, data.sort, key=SortKiller)
 
     def test_key_with_mutating_del_and_exception(self):
-        data = range(10)
+        data = list(range(10))
         ## dup = data[:]
         class SortKiller(object):
             def __init__(self, x):
@@ -238,7 +238,7 @@
                     raise RuntimeError
             def __del__(self):
                 del data[:]
-                data[:] = range(20)
+                data[:] = list(range(20))
         self.assertRaises(RuntimeError, data.sort, key=SortKiller)
         ## major honking subtlety: we *can't* do:
         ##
@@ -250,14 +250,14 @@
         ## date (this cost some brain cells to figure out...).
 
     def test_reverse(self):
-        data = range(100)
+        data = list(range(100))
         random.shuffle(data)
         data.sort(reverse=True)
-        self.assertEqual(data, range(99,-1,-1))
+        self.assertEqual(data, list(range(99,-1,-1)))
         self.assertRaises(TypeError, data.sort, "wrong type")
 
     def test_reverse_stability(self):
-        data = [(random.randrange(100), i) for i in xrange(200)]
+        data = [(random.randrange(100), i) for i in range(200)]
         copy1 = data[:]
         copy2 = data[:]
         data.sort(cmp=lambda x,y: cmp(x[0],y[0]), reverse=True)
@@ -281,7 +281,7 @@
     if verbose and hasattr(sys, "gettotalrefcount"):
         import gc
         counts = [None] * 5
-        for i in xrange(len(counts)):
+        for i in range(len(counts)):
             test_support.run_unittest(*test_classes)
             gc.collect()
             counts[i] = sys.gettotalrefcount()

Modified: python/branches/p3yk-noslice/Lib/test/test_str.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_str.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_str.py	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,7 @@
+
 import unittest
+import struct
+import sys
 from test import test_support, string_tests
 
 
@@ -22,10 +25,10 @@
     def test_iterators(self):
         # Make sure str objects have an __iter__ method
         it = "abc".__iter__()
-        self.assertEqual(it.next(), "a")
-        self.assertEqual(it.next(), "b")
-        self.assertEqual(it.next(), "c")
-        self.assertRaises(StopIteration, it.next)
+        self.assertEqual(next(it), "a")
+        self.assertEqual(next(it), "b")
+        self.assertEqual(next(it), "c")
+        self.assertRaises(StopIteration, next, it)
 
     def test_conversion(self):
         # Make sure __str__() behaves properly
@@ -90,6 +93,15 @@
         self.assertEqual(str(Foo9("foo")), "string")
         self.assertEqual(unicode(Foo9("foo")), u"not unicode")
 
+    def test_expandtabs_overflows_gracefully(self):
+        # This test only affects 32-bit platforms because expandtabs can only take
+        # an int as the max value, not a 64-bit C long.  If expandtabs is changed
+        # to take a 64-bit long, this test should apply to all platforms.
+        if sys.maxint > (1 << 32) or struct.calcsize('P') != 4:
+            return
+        self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxint)
+
+
 def test_main():
     test_support.run_unittest(StrTest)
 

Modified: python/branches/p3yk-noslice/Lib/test/test_string.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_string.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_string.py	Wed Jul 11 15:40:56 2007
@@ -1,67 +1,5 @@
 import unittest, string
-from test import test_support, string_tests
-from UserList import UserList
-
-class StringTest(
-    string_tests.CommonTest,
-    string_tests.MixinStrStringUserStringTest
-    ):
-
-    type2test = str
-
-    def checkequal(self, result, object, methodname, *args):
-        realresult = getattr(string, methodname)(object, *args)
-        self.assertEqual(
-            result,
-            realresult
-        )
-
-    def checkraises(self, exc, object, methodname, *args):
-        self.assertRaises(
-            exc,
-            getattr(string, methodname),
-            object,
-            *args
-        )
-
-    def checkcall(self, object, methodname, *args):
-        getattr(string, methodname)(object, *args)
-
-    def test_join(self):
-        # These are the same checks as in string_test.ObjectTest.test_join
-        # but the argument order ist different
-        self.checkequal('a b c d', ['a', 'b', 'c', 'd'], 'join', ' ')
-        self.checkequal('abcd', ('a', 'b', 'c', 'd'), 'join', '')
-        self.checkequal('w x y z', string_tests.Sequence(), 'join', ' ')
-        self.checkequal('abc', ('abc',), 'join', 'a')
-        self.checkequal('z', UserList(['z']), 'join', 'a')
-        if test_support.have_unicode:
-            self.checkequal(unicode('a.b.c'), ['a', 'b', 'c'], 'join', unicode('.'))
-            self.checkequal(unicode('a.b.c'), [unicode('a'), 'b', 'c'], 'join', '.')
-            self.checkequal(unicode('a.b.c'), ['a', unicode('b'), 'c'], 'join', '.')
-            self.checkequal(unicode('a.b.c'), ['a', 'b', unicode('c')], 'join', '.')
-            self.checkraises(TypeError, ['a', unicode('b'), 3], 'join', '.')
-        for i in [5, 25, 125]:
-            self.checkequal(
-                ((('a' * i) + '-') * i)[:-1],
-                ['a' * i] * i, 'join', '-')
-            self.checkequal(
-                ((('a' * i) + '-') * i)[:-1],
-                ('a' * i,) * i, 'join', '-')
-
-        self.checkraises(TypeError, string_tests.BadSeq1(), 'join', ' ')
-        self.checkequal('a b c', string_tests.BadSeq2(), 'join', ' ')
-        try:
-            def f():
-                yield 4 + ""
-            self.fixtype(' ').join(f())
-        except TypeError as e:
-            if '+' not in str(e):
-                self.fail('join() ate exception message')
-        else:
-            self.fail('exception not raised')
-
-
+from test import test_support
 
 
 class ModuleTest(unittest.TestCase):
@@ -77,37 +15,14 @@
         string.punctuation
         string.printable
 
-    def test_atoi(self):
-        self.assertEqual(string.atoi(" 1 "), 1)
-        self.assertRaises(ValueError, string.atoi, " 1x")
-        self.assertRaises(ValueError, string.atoi, " x1 ")
-
-    def test_atol(self):
-        self.assertEqual(string.atol("  1  "), 1)
-        self.assertRaises(ValueError, string.atol, "  1x ")
-        self.assertRaises(ValueError, string.atol, "  x1 ")
-
-    def test_atof(self):
-        self.assertAlmostEqual(string.atof("  1  "), 1.0)
-        self.assertRaises(ValueError, string.atof, "  1x ")
-        self.assertRaises(ValueError, string.atof, "  x1 ")
-
     def test_maketrans(self):
         transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
 
         self.assertEqual(string.maketrans('abc', 'xyz'), transtable)
         self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzq')
 
-    def test_capwords(self):
-        self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
-        self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
-        self.assertEqual(string.capwords('abc\t   def  \nghi'), 'Abc Def Ghi')
-        self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
-        self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
-        self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
-
 def test_main():
-    test_support.run_unittest(StringTest, ModuleTest)
+    test_support.run_unittest(ModuleTest)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_stringprep.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_stringprep.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_stringprep.py	Wed Jul 11 15:40:56 2007
@@ -1,88 +1,96 @@
 # To fully test this module, we would need a copy of the stringprep tables.
 # Since we don't have them, this test checks only a few codepoints.
 
-from test.test_support import verify, vereq
+import unittest
+from test import test_support
 
-import stringprep
 from stringprep import *
 
-verify(in_table_a1(u"\u0221"))
-verify(not in_table_a1(u"\u0222"))
+class StringprepTests(unittest.TestCase):
+    def test(self):
+        self.failUnless(in_table_a1(u"\u0221"))
+        self.failIf(in_table_a1(u"\u0222"))
 
-verify(in_table_b1(u"\u00ad"))
-verify(not in_table_b1(u"\u00ae"))
+        self.failUnless(in_table_b1(u"\u00ad"))
+        self.failIf(in_table_b1(u"\u00ae"))
 
-verify(map_table_b2(u"\u0041"), u"\u0061")
-verify(map_table_b2(u"\u0061"), u"\u0061")
+        self.failUnless(map_table_b2(u"\u0041"), u"\u0061")
+        self.failUnless(map_table_b2(u"\u0061"), u"\u0061")
 
-verify(map_table_b3(u"\u0041"), u"\u0061")
-verify(map_table_b3(u"\u0061"), u"\u0061")
+        self.failUnless(map_table_b3(u"\u0041"), u"\u0061")
+        self.failUnless(map_table_b3(u"\u0061"), u"\u0061")
 
-verify(in_table_c11(u"\u0020"))
-verify(not in_table_c11(u"\u0021"))
+        self.failUnless(in_table_c11(u"\u0020"))
+        self.failIf(in_table_c11(u"\u0021"))
 
-verify(in_table_c12(u"\u00a0"))
-verify(not in_table_c12(u"\u00a1"))
+        self.failUnless(in_table_c12(u"\u00a0"))
+        self.failIf(in_table_c12(u"\u00a1"))
 
-verify(in_table_c12(u"\u00a0"))
-verify(not in_table_c12(u"\u00a1"))
+        self.failUnless(in_table_c12(u"\u00a0"))
+        self.failIf(in_table_c12(u"\u00a1"))
 
-verify(in_table_c11_c12(u"\u00a0"))
-verify(not in_table_c11_c12(u"\u00a1"))
+        self.failUnless(in_table_c11_c12(u"\u00a0"))
+        self.failIf(in_table_c11_c12(u"\u00a1"))
 
-verify(in_table_c21(u"\u001f"))
-verify(not in_table_c21(u"\u0020"))
+        self.failUnless(in_table_c21(u"\u001f"))
+        self.failIf(in_table_c21(u"\u0020"))
 
-verify(in_table_c22(u"\u009f"))
-verify(not in_table_c22(u"\u00a0"))
+        self.failUnless(in_table_c22(u"\u009f"))
+        self.failIf(in_table_c22(u"\u00a0"))
 
-verify(in_table_c21_c22(u"\u009f"))
-verify(not in_table_c21_c22(u"\u00a0"))
+        self.failUnless(in_table_c21_c22(u"\u009f"))
+        self.failIf(in_table_c21_c22(u"\u00a0"))
 
-verify(in_table_c3(u"\ue000"))
-verify(not in_table_c3(u"\uf900"))
+        self.failUnless(in_table_c3(u"\ue000"))
+        self.failIf(in_table_c3(u"\uf900"))
 
-verify(in_table_c4(u"\uffff"))
-verify(not in_table_c4(u"\u0000"))
+        self.failUnless(in_table_c4(u"\uffff"))
+        self.failIf(in_table_c4(u"\u0000"))
 
-verify(in_table_c5(u"\ud800"))
-verify(not in_table_c5(u"\ud7ff"))
+        self.failUnless(in_table_c5(u"\ud800"))
+        self.failIf(in_table_c5(u"\ud7ff"))
 
-verify(in_table_c6(u"\ufff9"))
-verify(not in_table_c6(u"\ufffe"))
+        self.failUnless(in_table_c6(u"\ufff9"))
+        self.failIf(in_table_c6(u"\ufffe"))
 
-verify(in_table_c7(u"\u2ff0"))
-verify(not in_table_c7(u"\u2ffc"))
+        self.failUnless(in_table_c7(u"\u2ff0"))
+        self.failIf(in_table_c7(u"\u2ffc"))
 
-verify(in_table_c8(u"\u0340"))
-verify(not in_table_c8(u"\u0342"))
+        self.failUnless(in_table_c8(u"\u0340"))
+        self.failIf(in_table_c8(u"\u0342"))
 
-# C.9 is not in the bmp
-# verify(in_table_c9(u"\U000E0001"))
-# verify(not in_table_c8(u"\U000E0002"))
+        # C.9 is not in the bmp
+        # self.failUnless(in_table_c9(u"\U000E0001"))
+        # self.failIf(in_table_c8(u"\U000E0002"))
 
-verify(in_table_d1(u"\u05be"))
-verify(not in_table_d1(u"\u05bf"))
+        self.failUnless(in_table_d1(u"\u05be"))
+        self.failIf(in_table_d1(u"\u05bf"))
 
-verify(in_table_d2(u"\u0041"))
-verify(not in_table_d2(u"\u0040"))
+        self.failUnless(in_table_d2(u"\u0041"))
+        self.failIf(in_table_d2(u"\u0040"))
 
-# This would generate a hash of all predicates. However, running
-# it is quite expensive, and only serves to detect changes in the
-# unicode database. Instead, stringprep.py asserts the version of
-# the database.
+        # This would generate a hash of all predicates. However, running
+        # it is quite expensive, and only serves to detect changes in the
+        # unicode database. Instead, stringprep.py asserts the version of
+        # the database.
 
-# import hashlib
-# predicates = [k for k in dir(stringprep) if k.startswith("in_table")]
-# predicates.sort()
-# for p in predicates:
-#     f = getattr(stringprep, p)
-#     # Collect all BMP code points
-#     data = ["0"] * 0x10000
-#     for i in range(0x10000):
-#         if f(unichr(i)):
-#             data[i] = "1"
-#     data = "".join(data)
-#     h = hashlib.sha1()
-#     h.update(data)
-#     print p, h.hexdigest()
+        # import hashlib
+        # predicates = [k for k in dir(stringprep) if k.startswith("in_table")]
+        # predicates.sort()
+        # for p in predicates:
+        #     f = getattr(stringprep, p)
+        #     # Collect all BMP code points
+        #     data = ["0"] * 0x10000
+        #     for i in range(0x10000):
+        #         if f(unichr(i)):
+        #             data[i] = "1"
+        #     data = "".join(data)
+        #     h = hashlib.sha1()
+        #     h.update(data)
+        #     print p, h.hexdigest()
+
+def test_main():
+    test_support.run_unittest(StringprepTests)
+
+if __name__ == '__main__':
+    test_main()

Deleted: /python/branches/p3yk-noslice/Lib/test/test_strop.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_strop.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,134 +0,0 @@
-import warnings
-warnings.filterwarnings("ignore", "strop functions are obsolete;",
-                        DeprecationWarning,
-                        r'test.test_strop|unittest')
-import strop
-import unittest
-from test import test_support
-
-
-class StropFunctionTestCase(unittest.TestCase):
-
-    def test_atoi(self):
-        self.assert_(strop.atoi(" 1 ") == 1)
-        self.assertRaises(ValueError, strop.atoi, " 1x")
-        self.assertRaises(ValueError, strop.atoi, " x1 ")
-
-    def test_atol(self):
-        self.assert_(strop.atol(" 1 ") == 1)
-        self.assertRaises(ValueError, strop.atol, " 1x")
-        self.assertRaises(ValueError, strop.atol, " x1 ")
-
-    def test_atof(self):
-        self.assert_(strop.atof(" 1 ") == 1.0)
-        self.assertRaises(ValueError, strop.atof, " 1x")
-        self.assertRaises(ValueError, strop.atof, " x1 ")
-
-    def test_capitalize(self):
-        self.assert_(strop.capitalize(" hello ") == " hello ")
-        self.assert_(strop.capitalize("hello ") == "Hello ")
-
-    def test_find(self):
-        self.assert_(strop.find("abcdefghiabc", "abc") == 0)
-        self.assert_(strop.find("abcdefghiabc", "abc", 1) == 9)
-        self.assert_(strop.find("abcdefghiabc", "def", 4) == -1)
-
-    def test_rfind(self):
-        self.assert_(strop.rfind("abcdefghiabc", "abc") == 9)
-
-    def test_lower(self):
-        self.assert_(strop.lower("HeLLo") == "hello")
-
-    def test_upper(self):
-        self.assert_(strop.upper("HeLLo") == "HELLO")
-
-    def test_swapcase(self):
-        self.assert_(strop.swapcase("HeLLo cOmpUteRs") == "hEllO CoMPuTErS")
-
-    def test_strip(self):
-        self.assert_(strop.strip(" \t\n hello \t\n ") == "hello")
-
-    def test_lstrip(self):
-        self.assert_(strop.lstrip(" \t\n hello \t\n ") == "hello \t\n ")
-
-    def test_rstrip(self):
-        self.assert_(strop.rstrip(" \t\n hello \t\n ") == " \t\n hello")
-
-    def test_replace(self):
-        replace = strop.replace
-        self.assert_(replace("one!two!three!", '!', '@', 1)
-                     == "one at two!three!")
-        self.assert_(replace("one!two!three!", '!', '@', 2)
-                     == "one at two@three!")
-        self.assert_(replace("one!two!three!", '!', '@', 3)
-                     == "one at two@three@")
-        self.assert_(replace("one!two!three!", '!', '@', 4)
-                     == "one at two@three@")
-
-        # CAUTION: a replace count of 0 means infinity only to strop,
-        # not to the string .replace() method or to the
-        # string.replace() function.
-
-        self.assert_(replace("one!two!three!", '!', '@', 0)
-                     == "one at two@three@")
-        self.assert_(replace("one!two!three!", '!', '@')
-                     == "one at two@three@")
-        self.assert_(replace("one!two!three!", 'x', '@')
-                     == "one!two!three!")
-        self.assert_(replace("one!two!three!", 'x', '@', 2)
-                     == "one!two!three!")
-
-    def test_split(self):
-        split = strop.split
-        self.assert_(split("this is the split function")
-                     == ['this', 'is', 'the', 'split', 'function'])
-        self.assert_(split("a|b|c|d", '|') == ['a', 'b', 'c', 'd'])
-        self.assert_(split("a|b|c|d", '|', 2) == ['a', 'b', 'c|d'])
-        self.assert_(split("a b c d", None, 1) == ['a', 'b c d'])
-        self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d'])
-        self.assert_(split("a b c d", None, 3) == ['a', 'b', 'c', 'd'])
-        self.assert_(split("a b c d", None, 4) == ['a', 'b', 'c', 'd'])
-        self.assert_(split("a b c d", None, 0) == ['a', 'b', 'c', 'd'])
-        self.assert_(split("a  b  c  d", None, 2) ==  ['a', 'b', 'c  d'])
-
-    def test_join(self):
-        self.assert_(strop.join(['a', 'b', 'c', 'd']) == 'a b c d')
-        self.assert_(strop.join(('a', 'b', 'c', 'd'), '') == 'abcd')
-        self.assert_(strop.join(Sequence()) == 'w x y z')
-
-        # try a few long ones
-        self.assert_(strop.join(['x' * 100] * 100, ':')
-                     == (('x' * 100) + ":") * 99 + "x" * 100)
-        self.assert_(strop.join(('x' * 100,) * 100, ':')
-                     == (('x' * 100) + ":") * 99 + "x" * 100)
-
-    def test_maketrans(self):
-        self.assert_(strop.maketrans("abc", "xyz") == transtable)
-        self.assertRaises(ValueError, strop.maketrans, "abc", "xyzq")
-
-    def test_translate(self):
-        self.assert_(strop.translate("xyzabcdef", transtable, "def")
-                     == "xyzxyz")
-
-    def test_data_attributes(self):
-        strop.lowercase
-        strop.uppercase
-        strop.whitespace
-
-
-transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
-
-
-# join() now works with any sequence type.
-class Sequence:
-    def __init__(self): self.seq = 'wxyz'
-    def __len__(self): return len(self.seq)
-    def __getitem__(self, i): return self.seq[i]
-
-
-def test_main():
-    test_support.run_unittest(StropFunctionTestCase)
-
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_strptime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_strptime.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_strptime.py	Wed Jul 11 15:40:56 2007
@@ -190,6 +190,15 @@
                         "locale data that contains regex metacharacters is not"
                         " properly escaped")
 
+    def test_whitespace_substitution(self):
+        # When pattern contains whitespace, make sure it is taken into account
+        # so as to not allow to subpatterns to end up next to each other and
+        # "steal" characters from each other.
+        pattern = self.time_re.pattern('%j %H')
+        self.failUnless(not re.match(pattern, "180"))
+        self.failUnless(re.match(pattern, "18 0"))
+
+
 class StrptimeTests(unittest.TestCase):
     """Tests for _strptime.strptime."""
 
@@ -463,8 +472,8 @@
                                         "of the year")
         test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
                                         "ending on Monday")
-        test_helper((2007, 01, 07), "First Sunday of 2007")
-        test_helper((2007, 01, 14), "Second Sunday of 2007")
+        test_helper((2007, 1, 7), "First Sunday of 2007")
+        test_helper((2007, 1, 14), "Second Sunday of 2007")
         test_helper((2006, 12, 31), "Last Sunday of 2006")
         test_helper((2006, 12, 24), "Second to last Sunday of 2006")
 
@@ -505,6 +514,35 @@
         self.failIfEqual(locale_time_id,
                          id(_strptime._TimeRE_cache.locale_time))
 
+    def test_TimeRE_recreation(self):
+        # The TimeRE instance should be recreated upon changing the locale.
+        locale_info = locale.getlocale(locale.LC_TIME)
+        try:
+            locale.setlocale(locale.LC_TIME, ('en_US', 'UTF8'))
+        except locale.Error:
+            return
+        try:
+            _strptime.strptime('10', '%d')
+            # Get id of current cache object.
+            first_time_re_id = id(_strptime._TimeRE_cache)
+            try:
+                # Change the locale and force a recreation of the cache.
+                locale.setlocale(locale.LC_TIME, ('de_DE', 'UTF8'))
+                _strptime.strptime('10', '%d')
+                # Get the new cache object's id.
+                second_time_re_id = id(_strptime._TimeRE_cache)
+                # They should not be equal.
+                self.failIfEqual(first_time_re_id, second_time_re_id)
+            # Possible test locale is not supported while initial locale is.
+            # If this is the case just suppress the exception and fall-through
+            # to the reseting to the original locale.
+            except locale.Error:
+                pass
+        # Make sure we don't trample on the locale setting once we leave the
+        # test.
+        finally:
+            locale.setlocale(locale.LC_TIME, locale_info)
+
 
 def test_main():
     test_support.run_unittest(

Modified: python/branches/p3yk-noslice/Lib/test/test_struct.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_struct.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_struct.py	Wed Jul 11 15:40:56 2007
@@ -54,7 +54,7 @@
             # Grrr, we need this function to warn every time.  Without removing
             # the warningregistry, running test_tarfile then test_struct would fail
             # on 64-bit platforms.
-            globals = func.func_globals
+            globals = func.__globals__
             if '__warningregistry__' in globals:
                 del globals['__warningregistry__']
             warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning)
@@ -558,18 +558,18 @@
         vereq(s.unpack_from(data), ('abcd',))
         vereq(s.unpack_from(data, 2), ('cd01',))
         vereq(s.unpack_from(data, 4), ('0123',))
-        for i in xrange(6):
+        for i in range(6):
             vereq(s.unpack_from(data, i), (data[i:i+4],))
-        for i in xrange(6, len(test_string) + 1):
+        for i in range(6, len(test_string) + 1):
             simple_err(s.unpack_from, data, i)
     for cls in (str, buffer):
         data = cls(test_string)
         vereq(struct.unpack_from(fmt, data), ('abcd',))
         vereq(struct.unpack_from(fmt, data, 2), ('cd01',))
         vereq(struct.unpack_from(fmt, data, 4), ('0123',))
-        for i in xrange(6):
+        for i in range(6):
             vereq(struct.unpack_from(fmt, data, i), (data[i:i+4],))
-        for i in xrange(6, len(test_string) + 1):
+        for i in range(6, len(test_string) + 1):
             simple_err(struct.unpack_from, fmt, data, i)
 
 def test_pack_into():
@@ -614,53 +614,61 @@
     assertRaises(struct.error, pack_into, small_buf, 0, test_string)
     assertRaises(struct.error, pack_into, small_buf, 2, test_string)
 
+def test_unpack_with_buffer():
+    # SF bug 1563759: struct.unpack doens't support buffer protocol objects
+    data1 = array.array('B', '\x12\x34\x56\x78')
+    data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
+    for data in [data1, data2]:
+        value, = struct.unpack('>I', data)
+        vereq(value, 0x12345678)
 
 # Test methods to pack and unpack from buffers rather than strings.
 test_unpack_from()
 test_pack_into()
 test_pack_into_fn()
+test_unpack_with_buffer()
 
 def test_bool():
     for prefix in tuple("<>!=")+('',):
         false = (), [], [], '', 0
         true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2
-        
+
         falseFormat = prefix + 't' * len(false)
         if verbose:
             print('trying bool pack/unpack on', false, 'using format', falseFormat)
         packedFalse = struct.pack(falseFormat, *false)
         unpackedFalse = struct.unpack(falseFormat, packedFalse)
-        
+
         trueFormat = prefix + 't' * len(true)
         if verbose:
             print('trying bool pack/unpack on', true, 'using format', trueFormat)
         packedTrue = struct.pack(trueFormat, *true)
         unpackedTrue = struct.unpack(trueFormat, packedTrue)
-        
+
         if len(true) != len(unpackedTrue):
             raise TestFailed('unpacked true array is not of same size as input')
         if len(false) != len(unpackedFalse):
             raise TestFailed('unpacked false array is not of same size as input')
-        
+
         for t in unpackedFalse:
             if t is not False:
                 raise TestFailed('%r did not unpack as False' % t)
         for t in unpackedTrue:
             if t is not True:
                 raise TestFailed('%r did not unpack as false' % t)
-    
+
         if prefix and verbose:
             print('trying size of bool with format %r' % (prefix+'t'))
         packed = struct.pack(prefix+'t', 1)
-        
+
         if len(packed) != struct.calcsize(prefix+'t'):
             raise TestFailed('packed length is not equal to calculated size')
-        
+
         if len(packed) != 1 and prefix:
             raise TestFailed('encoded bool is not one byte: %r' % packed)
         elif not prefix and verbose:
             print('size of bool in native format is %i' % (len(packed)))
-        
+
         for c in '\x01\x7f\xff\x0f\xf0':
             if struct.unpack('>t', c)[0] is not True:
                 raise TestFailed('%c did not unpack as True' % c)

Modified: python/branches/p3yk-noslice/Lib/test/test_structmembers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_structmembers.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_structmembers.py	Wed Jul 11 15:40:56 2007
@@ -2,9 +2,10 @@
     CHAR_MAX, CHAR_MIN, UCHAR_MAX, \
     SHRT_MAX, SHRT_MIN, USHRT_MAX, \
     INT_MAX, INT_MIN, UINT_MAX, \
-    LONG_MAX, LONG_MIN, ULONG_MAX
+    LONG_MAX, LONG_MIN, ULONG_MAX, \
+    LLONG_MAX, LLONG_MIN, ULLONG_MAX
 
-import warnings, exceptions, unittest, test.test_warnings
+import warnings, unittest
 from test import test_support
 
 ts=test_structmembersType(1,2,3,4,5,6,7,8,9.99999,10.1010101010)
@@ -39,34 +40,56 @@
         ts.T_ULONG=ULONG_MAX
         self.assertEquals(ts.T_ULONG, ULONG_MAX)
 
-class TestWarnings(test.test_warnings.TestModule):
-    def has_warned(self):
-        self.assertEqual(test.test_warnings.msg.category,
-                         exceptions.RuntimeWarning.__name__)
+        ## T_LONGLONG and T_ULONGLONG may not be present on some platforms
+        if hasattr(ts, 'T_LONGLONG'):
+            ts.T_LONGLONG=LLONG_MAX
+            self.assertEquals(ts.T_LONGLONG, LLONG_MAX)
+            ts.T_LONGLONG=LLONG_MIN
+            self.assertEquals(ts.T_LONGLONG, LLONG_MIN)
+
+            ts.T_ULONGLONG=ULLONG_MAX
+            self.assertEquals(ts.T_ULONGLONG, ULLONG_MAX)
+
+            ## make sure these will accept a plain int as well as a long
+            ts.T_LONGLONG=3
+            self.assertEquals(ts.T_LONGLONG, 3)
+            ts.T_ULONGLONG=4
+            self.assertEquals(ts.T_ULONGLONG, 4)
+
+
+class TestWarnings(unittest.TestCase):
+    def has_warned(self, w):
+        self.assert_(w.category is RuntimeWarning)
 
     def test_byte_max(self):
-        ts.T_BYTE=CHAR_MAX+1
-        self.has_warned()
+        with test_support.catch_warning() as w:
+            ts.T_BYTE=CHAR_MAX+1
+            self.has_warned(w)
 
     def test_byte_min(self):
-        ts.T_BYTE=CHAR_MIN-1
-        self.has_warned()
+        with test_support.catch_warning() as w:
+            ts.T_BYTE=CHAR_MIN-1
+            self.has_warned(w)
 
     def test_ubyte_max(self):
-        ts.T_UBYTE=UCHAR_MAX+1
-        self.has_warned()
+        with test_support.catch_warning() as w:
+            ts.T_UBYTE=UCHAR_MAX+1
+            self.has_warned(w)
 
     def test_short_max(self):
-        ts.T_SHORT=SHRT_MAX+1
-        self.has_warned()
+        with test_support.catch_warning() as w:
+            ts.T_SHORT=SHRT_MAX+1
+            self.has_warned(w)
 
     def test_short_min(self):
-        ts.T_SHORT=SHRT_MIN-1
-        self.has_warned()
+        with test_support.catch_warning() as w:
+            ts.T_SHORT=SHRT_MIN-1
+            self.has_warned(w)
 
     def test_ushort_max(self):
-        ts.T_USHORT=USHRT_MAX+1
-        self.has_warned()
+        with test_support.catch_warning() as w:
+            ts.T_USHORT=USHRT_MAX+1
+            self.has_warned(w)
 
 
 

Modified: python/branches/p3yk-noslice/Lib/test/test_structseq.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_structseq.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_structseq.py	Wed Jul 11 15:40:56 2007
@@ -13,17 +13,17 @@
 
         # Check that slicing works the same way; at one point, slicing t[i:j] with
         # 0 < i < j could produce NULLs in the result.
-        for i in xrange(-len(t), len(t)):
+        for i in range(-len(t), len(t)):
             self.assertEqual(t[i:], astuple[i:])
-            for j in xrange(-len(t), len(t)):
+            for j in range(-len(t), len(t)):
                 self.assertEqual(t[i:j], astuple[i:j])
 
-        for j in xrange(-len(t), len(t)):
+        for j in range(-len(t), len(t)):
             self.assertEqual(t[:j], astuple[:j])
 
         self.assertRaises(IndexError, t.__getitem__, -len(t)-1)
         self.assertRaises(IndexError, t.__getitem__, len(t))
-        for i in xrange(-len(t), len(t)-1):
+        for i in range(-len(t), len(t)-1):
             self.assertEqual(t[i], astuple[i])
 
     def test_repr(self):
@@ -33,13 +33,13 @@
     def test_concat(self):
         t1 = time.gmtime()
         t2 = t1 + tuple(t1)
-        for i in xrange(len(t1)):
+        for i in range(len(t1)):
             self.assertEqual(t2[i], t2[i+len(t1)])
 
     def test_repeat(self):
         t1 = time.gmtime()
         t2 = 3 * t1
-        for i in xrange(len(t1)):
+        for i in range(len(t1)):
             self.assertEqual(t2[i], t2[i+len(t1)])
             self.assertEqual(t2[i], t2[i+2*len(t1)])
 

Modified: python/branches/p3yk-noslice/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_subprocess.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_subprocess.py	Wed Jul 11 15:40:56 2007
@@ -533,7 +533,7 @@
             os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
                         sys.executable)
             os.close(f)
-            os.chmod(fname, 0700)
+            os.chmod(fname, 0o700)
             p = subprocess.Popen(fname)
             p.wait()
             os.remove(fname)
@@ -575,7 +575,7 @@
             os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" %
                         sys.executable)
             os.close(f)
-            os.chmod(fname, 0700)
+            os.chmod(fname, 0o700)
             rc = subprocess.call(fname)
             os.remove(fname)
             self.assertEqual(rc, 47)
@@ -617,8 +617,16 @@
             self.assertRaises(ValueError, subprocess.call,
                               [sys.executable,
                                "-c", "import sys; sys.exit(47)"],
+                              stdout=subprocess.PIPE,
                               close_fds=True)
 
+        def test_close_fds(self):
+            # close file descriptors
+            rc = subprocess.call([sys.executable, "-c",
+                                  "import sys; sys.exit(47)"],
+                                  close_fds=True)
+            self.assertEqual(rc, 47)
+
         def test_shell_sequence(self):
             # Run command through the shell (sequence)
             newenv = os.environ.copy()

Modified: python/branches/p3yk-noslice/Lib/test/test_sundry.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sundry.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_sundry.py	Wed Jul 11 15:40:56 2007
@@ -1,77 +1,114 @@
 """Do a minimal test of all the modules that aren't otherwise tested."""
 
+from test.test_support import guard_warnings_filter
+import sys
 import warnings
-warnings.filterwarnings('ignore', r".*posixfile module",
-                        DeprecationWarning, 'posixfile$')
 
-warnings.filterwarnings("ignore",
-                        "the gopherlib module is deprecated",
-                        DeprecationWarning,
-                        ".*test_sundry")
-
-from test.test_support import verbose
-
-import BaseHTTPServer
-import DocXMLRPCServer
-import CGIHTTPServer
-import SimpleHTTPServer
-import SimpleXMLRPCServer
-import aifc
-import audiodev
-import bdb
-import cgitb
-import cmd
-import code
-import compileall
-import encodings
-import formatter
-import ftplib
-import getpass
-import gopherlib
-import htmlentitydefs
-import ihooks
-import imghdr
-import imputil
-import keyword
-import linecache
-import macurl2path
-import mailcap
-import mimify
-import mutex
-import nntplib
-import nturl2path
-import opcode
-import os2emxpath
-import pdb
-import pipes
-#import poplib
-import posixfile
-import pstats
-import py_compile
-import pydoc
-import rexec
-import rlcompleter
-import sched
-import smtplib
-import sndhdr
-import statvfs
-import stringold
-import sunau
-import sunaudio
-import symbol
-import tabnanny
-import telnetlib
-import timeit
-import toaiff
-import token
-try:
-    import tty     # not available on Windows
-except ImportError:
-    if verbose:
-        print("skipping tty")
-
-# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
-# can screw up all sorts of things (esp. if it prints!).
-#import user
-import webbrowser
-import xml
+with guard_warnings_filter():
+    from test.test_support import verbose
+
+    import BaseHTTPServer
+    import DocXMLRPCServer
+    import CGIHTTPServer
+    import SimpleHTTPServer
+    import SimpleXMLRPCServer
+    import aifc
+    import audiodev
+    import bdb
+    import cgitb
+    import cmd
+    import code
+    import compileall
+
+    import distutils.archive_util
+    import distutils.bcppcompiler
+    import distutils.ccompiler
+    import distutils.cmd
+    import distutils.core
+    import distutils.cygwinccompiler
+    import distutils.dep_util
+    import distutils.dir_util
+    import distutils.emxccompiler
+    import distutils.errors
+    import distutils.extension
+    import distutils.file_util
+    import distutils.filelist
+    import distutils.log
+    if sys.platform.startswith('win'):
+        import distutils.msvccompiler
+    import distutils.mwerkscompiler
+    import distutils.sysconfig
+    import distutils.text_file
+    import distutils.unixccompiler
+    import distutils.util
+    import distutils.version
+
+    import distutils.command.bdist_dumb
+    if sys.platform.startswith('win'):
+        import distutils.command.bdist_msi
+    import distutils.command.bdist
+    import distutils.command.bdist_rpm
+    import distutils.command.bdist_wininst
+    import distutils.command.build_clib
+    import distutils.command.build_ext
+    import distutils.command.build
+    import distutils.command.build_py
+    import distutils.command.build_scripts
+    import distutils.command.clean
+    import distutils.command.config
+    import distutils.command.install_data
+    import distutils.command.install_egg_info
+    import distutils.command.install_headers
+    import distutils.command.install_lib
+    import distutils.command.install
+    import distutils.command.install_scripts
+    import distutils.command.register
+    import distutils.command.sdist
+    import distutils.command.upload
+
+    import encodings
+    import formatter
+    import ftplib
+    import getpass
+    import htmlentitydefs
+    import ihooks
+    import imghdr
+    import imputil
+    import keyword
+    import linecache
+    import macurl2path
+    import mailcap
+    import mutex
+    import nntplib
+    import nturl2path
+    import opcode
+    import os2emxpath
+    import pdb
+    import pipes
+    import pstats
+    import py_compile
+    import pydoc
+    import rlcompleter
+    import sched
+    import smtplib
+    import sndhdr
+    import statvfs
+    import sunau
+    import sunaudio
+    import symbol
+    import tabnanny
+    import telnetlib
+    import timeit
+    import toaiff
+    import token
+    try:
+        import tty     # not available on Windows
+    except ImportError:
+        if verbose:
+            print("skipping tty")
+
+    # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
+    # can screw up all sorts of things (esp. if it prints!).
+    #import user
+    import webbrowser
+    import xml

Modified: python/branches/p3yk-noslice/Lib/test/test_support.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_support.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_support.py	Wed Jul 11 15:40:56 2007
@@ -1,11 +1,17 @@
 """Supporting definitions for the Python regression tests."""
 
 if __name__ != 'test.test_support':
-    raise ImportError, 'test_support must be imported from the test package'
+    raise ImportError('test_support must be imported from the test package')
 
-from contextlib import contextmanager
+import contextlib
+import errno
+import socket
 import sys
+import os
+import os.path
 import warnings
+import types
+import unittest
 
 class Error(Exception):
     """Base class for regression test exceptions."""
@@ -54,7 +60,6 @@
         pass
 
 def unlink(filename):
-    import os
     try:
         os.unlink(filename)
     except OSError:
@@ -64,7 +69,6 @@
     '''"Forget" a module was ever imported by removing it from sys.modules and
     deleting any .pyc and .pyo files.'''
     unload(modname)
-    import os
     for dirname in sys.path:
         unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
         # Deleting the .pyo file cannot be within the 'try' for the .pyc since
@@ -96,7 +100,6 @@
     tests and we don't try multiple ports, the test can fails.  This
     makes the test more robust."""
 
-    import socket, errno
     # some random ports that hopefully no one is listening on.
     for port in [preferred_port, 9907, 10243, 32999]:
         try:
@@ -107,7 +110,7 @@
             if err != errno.EADDRINUSE:
                 raise
             print('  WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
-    raise TestFailed, 'unable to find port to listen on'
+    raise TestFailed('unable to find port to listen on')
 
 FUZZ = 1e-6
 
@@ -135,7 +138,6 @@
 
 is_jython = sys.platform.startswith('java')
 
-import os
 # Filename used for testing
 if os.name == 'java':
     # Jython disallows @ in module names
@@ -197,13 +199,12 @@
 if fp is not None:
     fp.close()
     unlink(TESTFN)
-del os, fp
+del fp
 
 def findfile(file, here=__file__):
     """Try to find a file on sys.path and the working directory.  If it is not
     found the argument passed to the function is returned (this does not
     necessarily signal failure; could still be the legitimate path)."""
-    import os
     if os.path.isabs(file):
         return file
     path = sys.path
@@ -235,7 +236,7 @@
     """
 
     if not (a == b):
-        raise TestFailed, "%r == %r" % (a, b)
+        raise TestFailed("%r == %r" % (a, b))
 
 def sortdict(dict):
     "Like repr(dict), but in sorted order."
@@ -254,8 +255,8 @@
 
 def open_urlresource(url):
     import urllib, urlparse
-    import os.path
 
+    requires('urlfetch')
     filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
 
     for path in [os.path.curdir, os.path.pardir]:
@@ -263,12 +264,11 @@
         if os.path.exists(fn):
             return open(fn)
 
-    requires('urlfetch')
     print('\tfetching %s ...' % url, file=get_original_stdout())
     fn, _ = urllib.urlretrieve(url, filename)
     return open(fn)
 
- at contextmanager
+ at contextlib.contextmanager
 def guard_warnings_filter():
     """Guard the warnings filter from being permanently changed."""
     original_filters = warnings.filters[:]
@@ -277,14 +277,49 @@
     finally:
         warnings.filters = original_filters
 
+class WarningMessage(object):
+    "Holds the result of the latest showwarning() call"
+    def __init__(self):
+        self.message = None
+        self.category = None
+        self.filename = None
+        self.lineno = None
+
+    def _showwarning(self, message, category, filename, lineno, file=None):
+        self.message = message
+        self.category = category
+        self.filename = filename
+        self.lineno = lineno
+
+ at contextlib.contextmanager
+def catch_warning():
+    """
+    Guard the warnings filter from being permanently changed and record the
+    data of the last warning that has been issued.
+
+    Use like this:
+
+        with catch_warning as w:
+            warnings.warn("foo")
+            assert str(w.message) == "foo"
+    """
+    warning = WarningMessage()
+    original_filters = warnings.filters[:]
+    original_showwarning = warnings.showwarning
+    warnings.showwarning = warning._showwarning
+    try:
+        yield warning
+    finally:
+        warnings.showwarning = original_showwarning
+        warnings.filters = original_filters
+
 class EnvironmentVarGuard(object):
 
     """Class to help protect the environment variable properly.  Can be used as
     a context manager."""
 
     def __init__(self):
-        from os import environ
-        self._environ = environ
+        self._environ = os.environ
         self._unset = set()
         self._reset = dict()
 
@@ -309,6 +344,40 @@
         for unset in self._unset:
             del self._environ[unset]
 
+class TransientResource(object):
+
+    """Raise ResourceDenied if an exception is raised while the context manager
+    is in effect that matches the specified exception and attributes."""
+
+    def __init__(self, exc, **kwargs):
+        self.exc = exc
+        self.attrs = kwargs
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type_=None, value=None, traceback=None):
+        """If type_ is a subclass of self.exc and value has attributes matching
+        self.attrs, raise ResourceDenied.  Otherwise let the exception
+        propagate (if any)."""
+        if type_ is not None and issubclass(self.exc, type_):
+            for attr, attr_value in self.attrs.items():
+                if not hasattr(value, attr):
+                    break
+                if getattr(value, attr) != attr_value:
+                    break
+            else:
+                raise ResourceDenied("an optional resource is not available")
+
+
+def transient_internet():
+    """Return a context manager that raises ResourceDenied when various issues
+    with the Internet connection manifest themselves as exceptions."""
+    time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
+    socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
+    ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
+    return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
+
 
 #=======================================================================
 # Decorator for running a function in a different locale, correctly resetting
@@ -341,7 +410,7 @@
             finally:
                 if locale and orig_locale:
                     locale.setlocale(category, orig_locale)
-        inner.func_name = func.func_name
+        inner.__name__ = func.__name__
         inner.__doc__ = func.__doc__
         return inner
     return decorator
@@ -429,10 +498,7 @@
     return wrapper
 
 #=======================================================================
-# Preliminary PyUNIT integration.
-
-import unittest
-
+# unittest integration.
 
 class BasicTestRunner:
     def run(self, test):
@@ -441,7 +507,7 @@
         return result
 
 
-def run_suite(suite, testclass=None):
+def _run_suite(suite):
     """Run tests from a unittest.TestSuite-derived class."""
     if verbose:
         runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
@@ -455,28 +521,26 @@
         elif len(result.failures) == 1 and not result.errors:
             err = result.failures[0][1]
         else:
-            if testclass is None:
-                msg = "errors occurred; run in verbose mode for details"
-            else:
-                msg = "errors occurred in %s.%s" \
-                      % (testclass.__module__, testclass.__name__)
+            msg = "errors occurred; run in verbose mode for details"
             raise TestFailed(msg)
         raise TestFailed(err)
 
 
 def run_unittest(*classes):
     """Run tests from unittest.TestCase-derived classes."""
+    valid_types = (unittest.TestSuite, unittest.TestCase)
     suite = unittest.TestSuite()
     for cls in classes:
-        if isinstance(cls, (unittest.TestSuite, unittest.TestCase)):
+        if isinstance(cls, str):
+            if cls in sys.modules:
+                suite.addTest(unittest.findTestCases(sys.modules[cls]))
+            else:
+                raise ValueError("str arguments must be keys in sys.modules")
+        elif isinstance(cls, valid_types):
             suite.addTest(cls)
         else:
             suite.addTest(unittest.makeSuite(cls))
-    if len(classes)==1:
-        testclass = classes[0]
-    else:
-        testclass = None
-    run_suite(suite, testclass)
+    _run_suite(suite)
 
 
 #=======================================================================
@@ -542,7 +606,6 @@
 
     # Reap all our dead child processes so we don't leave zombies around.
     # These hog resources and might be causing some of the buildbots to die.
-    import os
     if hasattr(os, 'waitpid'):
         any_process = -1
         while True:

Modified: python/branches/p3yk-noslice/Lib/test/test_syntax.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_syntax.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_syntax.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,7 @@
 >>> def f(x):
 ...     global x
 Traceback (most recent call last):
-SyntaxError: name 'x' is local and global
+SyntaxError: name 'x' is parameter and global
 
 The tests are all raise SyntaxErrors.  They were created by checking
 each C call that raises SyntaxError.  There are several modules that
@@ -27,15 +27,13 @@
 
 Errors from set_context():
 
-TODO(jhylton): "assignment to None" is inconsistent with other messages
-
 >>> obj.None = 1
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[1]>, line 1)
+SyntaxError: invalid syntax
 
 >>> None = 1
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[2]>, line 1)
+SyntaxError: assignment to keyword (<doctest test.test_syntax[2]>, line 1)
 
 It's a syntax error to assign to the empty tuple.  Why isn't it an
 error to assign to the empty list?  It will always raise some error at
@@ -95,7 +93,7 @@
 >>> def f(None=1):
 ...     pass
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[14]>, line 1)
+SyntaxError: invalid syntax
 
 
 From ast_for_arguments():
@@ -108,17 +106,17 @@
 >>> def f(x, None):
 ...     pass
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[16]>, line 1)
+SyntaxError: invalid syntax
 
 >>> def f(*None):
 ...     pass
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[17]>, line 1)
+SyntaxError: invalid syntax
 
 >>> def f(**None):
 ...     pass
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[18]>, line 1)
+SyntaxError: invalid syntax
 
 
 From ast_for_funcdef():
@@ -126,7 +124,7 @@
 >>> def None(x):
 ...     pass
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[19]>, line 1)
+SyntaxError: invalid syntax
 
 
 From ast_for_call():
@@ -231,7 +229,7 @@
 SyntaxError: augmented assignment to generator expression not possible (<doctest test.test_syntax[31]>, line 1)
 >>> None += 1
 Traceback (most recent call last):
-SyntaxError: assignment to None (<doctest test.test_syntax[32]>, line 1)
+SyntaxError: assignment to keyword (<doctest test.test_syntax[32]>, line 1)
 >>> f() += 1
 Traceback (most recent call last):
 SyntaxError: illegal expression for augmented assignment (<doctest test.test_syntax[33]>, line 1)
@@ -367,6 +365,101 @@
      ...
    SystemError: too many statically nested blocks
 
+Misuse of the nonlocal statement can lead to a few unique syntax errors.
+
+   >>> def f(x):
+   ...     nonlocal x
+   Traceback (most recent call last):
+     ...
+   SyntaxError: name 'x' is parameter and nonlocal
+
+   >>> def f():
+   ...     global x
+   ...     nonlocal x
+   Traceback (most recent call last):
+     ...
+   SyntaxError: name 'x' is nonlocal and global
+
+   >>> def f():
+   ...     nonlocal x
+   Traceback (most recent call last):
+     ...
+   SyntaxError: no binding for nonlocal 'x' found
+
+From SF bug #1705365
+   >>> nonlocal x
+   Traceback (most recent call last):
+     ...
+   SyntaxError: nonlocal declaration not allowed at module level
+
+TODO(jhylton): Figure out how to test SyntaxWarning with doctest.
+
+##   >>> def f(x):
+##   ...     def f():
+##   ...         print(x)
+##   ...         nonlocal x
+##   Traceback (most recent call last):
+##     ...
+##   SyntaxWarning: name 'x' is assigned to before nonlocal declaration
+
+##   >>> def f():
+##   ...     x = 1
+##   ...     nonlocal x
+##   Traceback (most recent call last):
+##     ...
+##   SyntaxWarning: name 'x' is assigned to before nonlocal declaration
+
+
+This tests assignment-context; there was a bug in Python 2.5 where compiling
+a complex 'if' (one with 'elif') would fail to notice an invalid suite,
+leading to spurious errors.
+
+   >>> if 1:
+   ...   x() = 1
+   ... elif 1:
+   ...   pass
+   Traceback (most recent call last):
+     ...
+   SyntaxError: can't assign to function call (<doctest test.test_syntax[48]>, line 2)
+
+   >>> if 1:
+   ...   pass
+   ... elif 1:
+   ...   x() = 1
+   Traceback (most recent call last):
+     ...
+   SyntaxError: can't assign to function call (<doctest test.test_syntax[49]>, line 4)
+
+   >>> if 1:
+   ...   x() = 1
+   ... elif 1:
+   ...   pass
+   ... else:
+   ...   pass
+   Traceback (most recent call last):
+     ...
+   SyntaxError: can't assign to function call (<doctest test.test_syntax[50]>, line 2)
+
+   >>> if 1:
+   ...   pass
+   ... elif 1:
+   ...   x() = 1
+   ... else:
+   ...   pass
+   Traceback (most recent call last):
+     ...
+   SyntaxError: can't assign to function call (<doctest test.test_syntax[51]>, line 4)
+
+   >>> if 1:
+   ...   pass
+   ... elif 1:
+   ...   pass
+   ... else:
+   ...   x() = 1
+   Traceback (most recent call last):
+     ...
+   SyntaxError: can't assign to function call (<doctest test.test_syntax[52]>, line 6)
+
 """
 
 import re

Modified: python/branches/p3yk-noslice/Lib/test/test_sys.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sys.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_sys.py	Wed Jul 11 15:40:56 2007
@@ -63,47 +63,6 @@
     # FIXME: testing the code for a lost or replaced excepthook in
     # Python/pythonrun.c::PyErr_PrintEx() is tricky.
 
-    def test_exc_clear(self):
-        self.assertRaises(TypeError, sys.exc_clear, 42)
-
-        # Verify that exc_info is present and matches exc, then clear it, and
-        # check that it worked.
-        def clear_check(exc):
-            typ, value, traceback = sys.exc_info()
-            self.assert_(typ is not None)
-            self.assert_(value is exc)
-            self.assert_(traceback is not None)
-
-            sys.exc_clear()
-
-            typ, value, traceback = sys.exc_info()
-            self.assert_(typ is None)
-            self.assert_(value is None)
-            self.assert_(traceback is None)
-
-        def clear():
-            try:
-                raise ValueError, 42
-            except ValueError as exc:
-                clear_check(exc)
-
-        # Raise an exception and check that it can be cleared
-        clear()
-
-        # Verify that a frame currently handling an exception is
-        # unaffected by calling exc_clear in a nested frame.
-        try:
-            raise ValueError, 13
-        except ValueError as exc:
-            typ1, value1, traceback1 = sys.exc_info()
-            clear()
-            typ2, value2, traceback2 = sys.exc_info()
-
-            self.assert_(typ1 is typ2)
-            self.assert_(value1 is exc)
-            self.assert_(value1 is value2)
-            self.assert_(traceback1 is traceback2)
-
     def test_exit(self):
         self.assertRaises(TypeError, sys.exit, 42, 42)
 
@@ -230,7 +189,7 @@
         self.assertRaises(TypeError, sys._getframe, 42, 42)
         self.assertRaises(ValueError, sys._getframe, 2000000000)
         self.assert_(
-            SysModuleTest.test_getframe.im_func.func_code \
+            SysModuleTest.test_getframe.im_func.__code__ \
             is sys._getframe().f_code
         )
 

Modified: python/branches/p3yk-noslice/Lib/test/test_tarfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_tarfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_tarfile.py	Wed Jul 11 15:40:56 2007
@@ -1,8 +1,12 @@
+# -*- coding: iso-8859-15 -*-
+
 import sys
 import os
 import shutil
 import tempfile
 import StringIO
+from hashlib import md5
+import errno
 
 import unittest
 import tarfile
@@ -20,452 +24,593 @@
 except ImportError:
     bz2 = None
 
+def md5sum(data):
+    return md5(data).hexdigest()
+
 def path(path):
     return test_support.findfile(path)
 
-testtar = path("testtar.tar")
-tempdir = os.path.join(tempfile.gettempdir(), "testtar" + os.extsep + "dir")
-tempname = test_support.TESTFN
-membercount = 12
-
-def tarname(comp=""):
-    if not comp:
-        return testtar
-    return os.path.join(tempdir, "%s%s%s" % (testtar, os.extsep, comp))
+TEMPDIR = os.path.join(tempfile.gettempdir(), "test_tarfile_tmp")
+tarname = path("testtar.tar")
+gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
+bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
+tmpname = os.path.join(TEMPDIR, "tmp.tar")
 
-def dirname():
-    if not os.path.exists(tempdir):
-        os.mkdir(tempdir)
-    return tempdir
+md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
+md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
 
-def tmpname():
-    return tempname
 
+class ReadTest(unittest.TestCase):
 
-class BaseTest(unittest.TestCase):
-    comp = ''
-    mode = 'r'
-    sep = ':'
+    tarname = tarname
+    mode = "r:"
 
     def setUp(self):
-        mode = self.mode + self.sep + self.comp
-        self.tar = tarfile.open(tarname(self.comp), mode)
+        self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
 
     def tearDown(self):
         self.tar.close()
 
-class ReadTest(BaseTest):
 
-    def test(self):
-        """Test member extraction.
-        """
-        members = 0
-        for tarinfo in self.tar:
-            members += 1
-            if not tarinfo.isreg():
-                continue
-            f = self.tar.extractfile(tarinfo)
-            self.assert_(len(f.read()) == tarinfo.size,
-                         "size read does not match expected size")
-            f.close()
-
-        self.assert_(members == membercount,
-                     "could not find all members")
-
-    def test_sparse(self):
-        """Test sparse member extraction.
-        """
-        if self.sep != "|":
-            f1 = self.tar.extractfile("S-SPARSE")
-            f2 = self.tar.extractfile("S-SPARSE-WITH-NULLS")
-            self.assert_(f1.read() == f2.read(),
-                         "_FileObject failed on sparse file member")
-
-    def test_readlines(self):
-        """Test readlines() method of _FileObject.
-        """
-        if self.sep != "|":
-            filename = "0-REGTYPE-TEXT"
-            self.tar.extract(filename, dirname())
-            f = open(os.path.join(dirname(), filename), "rU")
-            lines1 = f.readlines()
-            f.close()
-            lines2 = self.tar.extractfile(filename).readlines()
-            self.assert_(lines1 == lines2,
-                         "_FileObject.readline() does not work correctly")
-
-    def test_iter(self):
-        # Test iteration over ExFileObject.
-        if self.sep != "|":
-            filename = "0-REGTYPE-TEXT"
-            self.tar.extract(filename, dirname())
-            f = open(os.path.join(dirname(), filename), "rU")
-            lines1 = f.readlines()
-            f.close()
-            lines2 = [line for line in self.tar.extractfile(filename)]
-            self.assert_(lines1 == lines2,
-                         "ExFileObject iteration does not work correctly")
-
-    def test_seek(self):
-        """Test seek() method of _FileObject, incl. random reading.
-        """
-        if self.sep != "|":
-            filename = "0-REGTYPE-TEXT"
-            self.tar.extract(filename, dirname())
-            f = open(os.path.join(dirname(), filename), "rb")
-            data = f.read()
-            f.close()
-
-            tarinfo = self.tar.getmember(filename)
-            fobj = self.tar.extractfile(tarinfo)
-
-            text = fobj.read()
-            fobj.seek(0)
-            self.assert_(0 == fobj.tell(),
-                         "seek() to file's start failed")
-            fobj.seek(2048, 0)
-            self.assert_(2048 == fobj.tell(),
-                         "seek() to absolute position failed")
-            fobj.seek(-1024, 1)
-            self.assert_(1024 == fobj.tell(),
-                         "seek() to negative relative position failed")
-            fobj.seek(1024, 1)
-            self.assert_(2048 == fobj.tell(),
-                         "seek() to positive relative position failed")
-            s = fobj.read(10)
-            self.assert_(s == data[2048:2058],
-                         "read() after seek failed")
-            fobj.seek(0, 2)
-            self.assert_(tarinfo.size == fobj.tell(),
-                         "seek() to file's end failed")
-            self.assert_(fobj.read() == "",
-                         "read() at file's end did not return empty string")
-            fobj.seek(-tarinfo.size, 2)
-            self.assert_(0 == fobj.tell(),
-                         "relative seek() to file's start failed")
-            fobj.seek(512)
-            s1 = fobj.readlines()
-            fobj.seek(512)
-            s2 = fobj.readlines()
-            self.assert_(s1 == s2,
-                         "readlines() after seek failed")
-            fobj.seek(0)
-            self.assert_(len(fobj.readline()) == fobj.tell(),
-                         "tell() after readline() failed")
-            fobj.seek(512)
-            self.assert_(len(fobj.readline()) + 512 == fobj.tell(),
-                         "tell() after seek() and readline() failed")
-            fobj.seek(0)
-            line = fobj.readline()
-            self.assert_(fobj.read() == data[len(line):],
-                         "read() after readline() failed")
-            fobj.close()
+class UstarReadTest(ReadTest):
 
-    def test_old_dirtype(self):
-        """Test old style dirtype member (bug #1336623).
-        """
-        # Old tars create directory members using a REGTYPE
-        # header with a "/" appended to the filename field.
+    def test_fileobj_regular_file(self):
+        tarinfo = self.tar.getmember("ustar/regtype")
+        fobj = self.tar.extractfile(tarinfo)
+        data = fobj.read()
+        self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
+                "regular file extraction failed")
+
+    def test_fileobj_readlines(self):
+        self.tar.extract("ustar/regtype", TEMPDIR)
+        tarinfo = self.tar.getmember("ustar/regtype")
+        fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
+        fobj2 = self.tar.extractfile(tarinfo)
+
+        lines1 = fobj1.readlines()
+        lines2 = fobj2.readlines()
+        self.assert_(lines1 == lines2,
+                "fileobj.readlines() failed")
+        self.assert_(len(lines2) == 114,
+                "fileobj.readlines() failed")
+        self.assert_(lines2[83] == \
+                "I will gladly admit that Python is not the fastest running scripting language.\n",
+                "fileobj.readlines() failed")
+
+    def test_fileobj_iter(self):
+        self.tar.extract("ustar/regtype", TEMPDIR)
+        tarinfo = self.tar.getmember("ustar/regtype")
+        fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
+        fobj2 = self.tar.extractfile(tarinfo)
+        lines1 = fobj1.readlines()
+        lines2 = [line for line in fobj2]
+        self.assert_(lines1 == lines2,
+                     "fileobj.__iter__() failed")
+
+    def test_fileobj_seek(self):
+        self.tar.extract("ustar/regtype", TEMPDIR)
+        fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
+        data = fobj.read()
+        fobj.close()
 
-        # Create an old tar style directory entry.
-        filename = tmpname()
-        tarinfo = tarfile.TarInfo("directory/")
-        tarinfo.type = tarfile.REGTYPE
+        tarinfo = self.tar.getmember("ustar/regtype")
+        fobj = self.tar.extractfile(tarinfo)
 
-        fobj = open(filename, "w")
-        fobj.write(tarinfo.tobuf())
+        text = fobj.read()
+        fobj.seek(0)
+        self.assert_(0 == fobj.tell(),
+                     "seek() to file's start failed")
+        fobj.seek(2048, 0)
+        self.assert_(2048 == fobj.tell(),
+                     "seek() to absolute position failed")
+        fobj.seek(-1024, 1)
+        self.assert_(1024 == fobj.tell(),
+                     "seek() to negative relative position failed")
+        fobj.seek(1024, 1)
+        self.assert_(2048 == fobj.tell(),
+                     "seek() to positive relative position failed")
+        s = fobj.read(10)
+        self.assert_(s == data[2048:2058],
+                     "read() after seek failed")
+        fobj.seek(0, 2)
+        self.assert_(tarinfo.size == fobj.tell(),
+                     "seek() to file's end failed")
+        self.assert_(fobj.read() == "",
+                     "read() at file's end did not return empty string")
+        fobj.seek(-tarinfo.size, 2)
+        self.assert_(0 == fobj.tell(),
+                     "relative seek() to file's start failed")
+        fobj.seek(512)
+        s1 = fobj.readlines()
+        fobj.seek(512)
+        s2 = fobj.readlines()
+        self.assert_(s1 == s2,
+                     "readlines() after seek failed")
+        fobj.seek(0)
+        self.assert_(len(fobj.readline()) == fobj.tell(),
+                     "tell() after readline() failed")
+        fobj.seek(512)
+        self.assert_(len(fobj.readline()) + 512 == fobj.tell(),
+                     "tell() after seek() and readline() failed")
+        fobj.seek(0)
+        line = fobj.readline()
+        self.assert_(fobj.read() == data[len(line):],
+                     "read() after readline() failed")
         fobj.close()
 
-        try:
-            # Test if it is still a directory entry when
-            # read back.
-            tar = tarfile.open(filename)
-            tarinfo = tar.getmembers()[0]
-            tar.close()
 
-            self.assert_(tarinfo.type == tarfile.DIRTYPE)
-            self.assert_(tarinfo.name.endswith("/"))
-        finally:
-            try:
-                os.unlink(filename)
-            except:
-                pass
-
-class ReadStreamTest(ReadTest):
-    sep = "|"
-
-    def test(self):
-        """Test member extraction, and for StreamError when
-           seeking backwards.
-        """
-        ReadTest.test(self)
-        tarinfo = self.tar.getmembers()[0]
-        f = self.tar.extractfile(tarinfo)
-        self.assertRaises(tarfile.StreamError, f.read)
+class MiscReadTest(ReadTest):
 
-    def test_stream(self):
-        """Compare the normal tar and the stream tar.
-        """
-        stream = self.tar
-        tar = tarfile.open(tarname(), 'r')
-
-        while 1:
-            t1 = tar.next()
-            t2 = stream.next()
-            if t1 is None:
-                break
-            self.assert_(t2 is not None, "stream.next() failed.")
+    def test_no_filename(self):
+        fobj = open(self.tarname, "rb")
+        tar = tarfile.open(fileobj=fobj, mode=self.mode)
+        self.assertEqual(tar.name, os.path.abspath(fobj.name))
+
+    def test_fail_comp(self):
+        # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
+        if self.mode == "r:":
+            return
+        self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
+        fobj = open(tarname, "rb")
+        self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
+
+    def test_v7_dirtype(self):
+        # Test old style dirtype member (bug #1336623):
+        # Old V7 tars create directory members using an AREGTYPE
+        # header with a "/" appended to the filename field.
+        tarinfo = self.tar.getmember("misc/dirtype-old-v7")
+        self.assert_(tarinfo.type == tarfile.DIRTYPE,
+                "v7 dirtype failed")
 
-            if t2.islnk() or t2.issym():
-                self.assertRaises(tarfile.StreamError, stream.extractfile, t2)
-                continue
-            v1 = tar.extractfile(t1)
-            v2 = stream.extractfile(t2)
-            if v1 is None:
+    def test_check_members(self):
+        for tarinfo in self.tar:
+            self.assert_(int(tarinfo.mtime) == 0o7606136617,
+                    "wrong mtime for %s" % tarinfo.name)
+            if not tarinfo.name.startswith("ustar/"):
                 continue
-            self.assert_(v2 is not None, "stream.extractfile() failed")
-            self.assert_(v1.read() == v2.read(), "stream extraction failed")
+            self.assert_(tarinfo.uname == "tarfile",
+                    "wrong uname for %s" % tarinfo.name)
 
-        tar.close()
-        stream.close()
+    def test_find_members(self):
+        self.assert_(self.tar.getmembers()[-1].name == "misc/eof",
+                "could not find all members")
+
+    def test_extract_hardlink(self):
+        # Test hardlink extraction (e.g. bug #857297).
+        tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
 
-class ReadDetectTest(ReadTest):
+        tar.extract("ustar/regtype", TEMPDIR)
+        try:
+            tar.extract("ustar/lnktype", TEMPDIR)
+        except EnvironmentError as e:
+            if e.errno == errno.ENOENT:
+                self.fail("hardlink not extracted properly")
 
-    def setUp(self):
-        self.tar = tarfile.open(tarname(self.comp), self.mode)
+        data = open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb").read()
+        self.assertEqual(md5sum(data), md5_regtype)
 
-class ReadDetectFileobjTest(ReadTest):
+        try:
+            tar.extract("ustar/symtype", TEMPDIR)
+        except EnvironmentError as e:
+            if e.errno == errno.ENOENT:
+                self.fail("symlink not extracted properly")
 
-    def setUp(self):
-        name = tarname(self.comp)
-        self.tar = tarfile.open(name, mode=self.mode,
-                                fileobj=open(name, "rb"))
+        data = open(os.path.join(TEMPDIR, "ustar/symtype"), "rb").read()
+        self.assertEqual(md5sum(data), md5_regtype)
 
-class ReadAsteriskTest(ReadTest):
 
-    def setUp(self):
-        mode = self.mode + self.sep + "*"
-        self.tar = tarfile.open(tarname(self.comp), mode)
+class StreamReadTest(ReadTest):
 
-class ReadStreamAsteriskTest(ReadStreamTest):
+    mode="r|"
 
-    def setUp(self):
-        mode = self.mode + self.sep + "*"
-        self.tar = tarfile.open(tarname(self.comp), mode)
+    def test_fileobj_regular_file(self):
+        tarinfo = self.tar.next() # get "regtype" (can't use getmember)
+        fobj = self.tar.extractfile(tarinfo)
+        data = fobj.read()
+        self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
+                "regular file extraction failed")
 
-class WriteTest(BaseTest):
-    mode = 'w'
+    def test_provoke_stream_error(self):
+        tarinfos = self.tar.getmembers()
+        f = self.tar.extractfile(tarinfos[0]) # read the first member
+        self.assertRaises(tarfile.StreamError, f.read)
 
-    def setUp(self):
-        mode = self.mode + self.sep + self.comp
-        self.src = tarfile.open(tarname(self.comp), 'r')
-        self.dstname = tmpname()
-        self.dst = tarfile.open(self.dstname, mode)
+    def test_compare_members(self):
+        tar1 = tarfile.open(tarname, encoding="iso8859-1")
+        tar2 = self.tar
+
+        while True:
+            t1 = tar1.next()
+            t2 = tar2.next()
+            if t1 is None:
+                break
+            self.assert_(t2 is not None, "stream.next() failed.")
 
-    def tearDown(self):
-        self.src.close()
-        self.dst.close()
+            if t2.islnk() or t2.issym():
+                self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
+                continue
 
-    def test_posix(self):
-        self.dst.posix = 1
-        self._test()
+            v1 = tar1.extractfile(t1)
+            v2 = tar2.extractfile(t2)
+            if v1 is None:
+                continue
+            self.assert_(v2 is not None, "stream.extractfile() failed")
+            self.assert_(v1.read() == v2.read(), "stream extraction failed")
 
-    def test_nonposix(self):
-        self.dst.posix = 0
-        self._test()
+        tar1.close()
 
-    def test_small(self):
-        self.dst.add(os.path.join(os.path.dirname(__file__),"cfgparser.1"))
-        self.dst.close()
-        self.assertNotEqual(os.stat(self.dstname).st_size, 0)
-
-    def _test(self):
-        for tarinfo in self.src:
-            if not tarinfo.isreg():
-                continue
-            f = self.src.extractfile(tarinfo)
-            if self.dst.posix and len(tarinfo.name) > tarfile.LENGTH_NAME and "/" not in tarinfo.name:
-                self.assertRaises(ValueError, self.dst.addfile,
-                                 tarinfo, f)
-            else:
-                self.dst.addfile(tarinfo, f)
 
-    def test_add_self(self):
-        dstname = os.path.abspath(self.dstname)
+class DetectReadTest(unittest.TestCase):
 
-        self.assertEqual(self.dst.name, dstname, "archive name must be absolute")
+    def _testfunc_file(self, name, mode):
+        try:
+            tarfile.open(name, mode)
+        except tarfile.ReadError:
+            self.fail()
 
-        self.dst.add(dstname)
-        self.assertEqual(self.dst.getnames(), [], "added the archive to itself")
+    def _testfunc_fileobj(self, name, mode):
+        try:
+            tarfile.open(name, mode, fileobj=open(name, "rb"))
+        except tarfile.ReadError:
+            self.fail()
 
-        cwd = os.getcwd()
-        os.chdir(dirname())
-        self.dst.add(dstname)
-        os.chdir(cwd)
-        self.assertEqual(self.dst.getnames(), [], "added the archive to itself")
+    def _test_modes(self, testfunc):
+        testfunc(tarname, "r")
+        testfunc(tarname, "r:")
+        testfunc(tarname, "r:*")
+        testfunc(tarname, "r|")
+        testfunc(tarname, "r|*")
 
+        if gzip:
+            self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
+            self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
+            self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
+            self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
+
+            testfunc(gzipname, "r")
+            testfunc(gzipname, "r:*")
+            testfunc(gzipname, "r:gz")
+            testfunc(gzipname, "r|*")
+            testfunc(gzipname, "r|gz")
 
-class AppendTest(unittest.TestCase):
-    # Test append mode (cp. patch #1652681).
+        if bz2:
+            self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
+            self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
+            self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
+            self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
+
+            testfunc(bz2name, "r")
+            testfunc(bz2name, "r:*")
+            testfunc(bz2name, "r:bz2")
+            testfunc(bz2name, "r|*")
+            testfunc(bz2name, "r|bz2")
+
+    def test_detect_file(self):
+        self._test_modes(self._testfunc_file)
+
+    def test_detect_fileobj(self):
+        self._test_modes(self._testfunc_fileobj)
+
+
+class MemberReadTest(ReadTest):
+
+    def _test_member(self, tarinfo, chksum=None, **kwargs):
+        if chksum is not None:
+            self.assert_(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
+                    "wrong md5sum for %s" % tarinfo.name)
+
+        kwargs["mtime"] = 0o7606136617
+        kwargs["uid"] = 1000
+        kwargs["gid"] = 100
+        if "old-v7" not in tarinfo.name:
+            # V7 tar can't handle alphabetic owners.
+            kwargs["uname"] = "tarfile"
+            kwargs["gname"] = "tarfile"
+        for k, v in kwargs.items():
+            self.assert_(getattr(tarinfo, k) == v,
+                    "wrong value in %s field of %s" % (k, tarinfo.name))
+
+    def test_find_regtype(self):
+        tarinfo = self.tar.getmember("ustar/regtype")
+        self._test_member(tarinfo, size=7011, chksum=md5_regtype)
+
+    def test_find_conttype(self):
+        tarinfo = self.tar.getmember("ustar/conttype")
+        self._test_member(tarinfo, size=7011, chksum=md5_regtype)
+
+    def test_find_dirtype(self):
+        tarinfo = self.tar.getmember("ustar/dirtype")
+        self._test_member(tarinfo, size=0)
+
+    def test_find_dirtype_with_size(self):
+        tarinfo = self.tar.getmember("ustar/dirtype-with-size")
+        self._test_member(tarinfo, size=255)
+
+    def test_find_lnktype(self):
+        tarinfo = self.tar.getmember("ustar/lnktype")
+        self._test_member(tarinfo, size=0, linkname="ustar/regtype")
+
+    def test_find_symtype(self):
+        tarinfo = self.tar.getmember("ustar/symtype")
+        self._test_member(tarinfo, size=0, linkname="regtype")
+
+    def test_find_blktype(self):
+        tarinfo = self.tar.getmember("ustar/blktype")
+        self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
+
+    def test_find_chrtype(self):
+        tarinfo = self.tar.getmember("ustar/chrtype")
+        self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
+
+    def test_find_fifotype(self):
+        tarinfo = self.tar.getmember("ustar/fifotype")
+        self._test_member(tarinfo, size=0)
+
+    def test_find_sparse(self):
+        tarinfo = self.tar.getmember("ustar/sparse")
+        self._test_member(tarinfo, size=86016, chksum=md5_sparse)
+
+    def test_find_umlauts(self):
+        tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
+        self._test_member(tarinfo, size=7011, chksum=md5_regtype)
+
+    def test_find_ustar_longname(self):
+        name = "ustar/" + "12345/" * 39 + "1234567/longname"
+        self.assert_(name in self.tar.getnames())
+
+    def test_find_regtype_oldv7(self):
+        tarinfo = self.tar.getmember("misc/regtype-old-v7")
+        self._test_member(tarinfo, size=7011, chksum=md5_regtype)
+
+    def test_find_pax_umlauts(self):
+        self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
+        tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
+        self._test_member(tarinfo, size=7011, chksum=md5_regtype)
+
+
+class LongnameTest(ReadTest):
+
+    def test_read_longname(self):
+        # Test reading of longname (bug #1471427).
+        longname = self.subdir + "/" + "123/" * 125 + "longname"
+        try:
+            tarinfo = self.tar.getmember(longname)
+        except KeyError:
+            self.fail("longname not found")
+        self.assert_(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
 
-    def setUp(self):
-        self.tarname = tmpname()
-        if os.path.exists(self.tarname):
-            os.remove(self.tarname)
+    def test_read_longlink(self):
+        longname = self.subdir + "/" + "123/" * 125 + "longname"
+        longlink = self.subdir + "/" + "123/" * 125 + "longlink"
+        try:
+            tarinfo = self.tar.getmember(longlink)
+        except KeyError:
+            self.fail("longlink not found")
+        self.assert_(tarinfo.linkname == longname, "linkname wrong")
 
-    def _add_testfile(self, fileobj=None):
-        tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
-        tar.addfile(tarfile.TarInfo("bar"))
+    def test_truncated_longname(self):
+        longname = self.subdir + "/" + "123/" * 125 + "longname"
+        tarinfo = self.tar.getmember(longname)
+        offset = tarinfo.offset
+        self.tar.fileobj.seek(offset)
+        fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
+        self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
+
+    def test_header_offset(self):
+        # Test if the start offset of the TarInfo object includes
+        # the preceding extended header.
+        longname = self.subdir + "/" + "123/" * 125 + "longname"
+        offset = self.tar.getmember(longname).offset
+        fobj = open(tarname)
+        fobj.seek(offset)
+        tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
+        self.assertEqual(tarinfo.type, self.longnametype)
+
+
+class GNUReadTest(LongnameTest):
+
+    subdir = "gnu"
+    longnametype = tarfile.GNUTYPE_LONGNAME
+
+    def test_sparse_file(self):
+        tarinfo1 = self.tar.getmember("ustar/sparse")
+        fobj1 = self.tar.extractfile(tarinfo1)
+        tarinfo2 = self.tar.getmember("gnu/sparse")
+        fobj2 = self.tar.extractfile(tarinfo2)
+        self.assert_(fobj1.read() == fobj2.read(),
+                "sparse file extraction failed")
+
+
+class PaxReadTest(LongnameTest):
+
+    subdir = "pax"
+    longnametype = tarfile.XHDTYPE
+
+    def test_pax_global_headers(self):
+        tar = tarfile.open(tarname, encoding="iso8859-1")
+
+        tarinfo = tar.getmember("pax/regtype1")
+        self.assertEqual(tarinfo.uname, "foo")
+        self.assertEqual(tarinfo.gname, "bar")
+        self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
+
+        tarinfo = tar.getmember("pax/regtype2")
+        self.assertEqual(tarinfo.uname, "")
+        self.assertEqual(tarinfo.gname, "bar")
+        self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
+
+        tarinfo = tar.getmember("pax/regtype3")
+        self.assertEqual(tarinfo.uname, "tarfile")
+        self.assertEqual(tarinfo.gname, "tarfile")
+        self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
+
+    def test_pax_number_fields(self):
+        # All following number fields are read from the pax header.
+        tar = tarfile.open(tarname, encoding="iso8859-1")
+        tarinfo = tar.getmember("pax/regtype4")
+        self.assertEqual(tarinfo.size, 7011)
+        self.assertEqual(tarinfo.uid, 123)
+        self.assertEqual(tarinfo.gid, 123)
+        self.assertEqual(tarinfo.mtime, 1041808783.0)
+        self.assertEqual(type(tarinfo.mtime), float)
+        self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
+        self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
+
+
+class WriteTest(unittest.TestCase):
+
+    mode = "w:"
+
+    def test_100_char_name(self):
+        # The name field in a tar header stores strings of at most 100 chars.
+        # If a string is shorter than 100 chars it has to be padded with '\0',
+        # which implies that a string of exactly 100 chars is stored without
+        # a trailing '\0'.
+        name = "0123456789" * 10
+        tar = tarfile.open(tmpname, self.mode)
+        t = tarfile.TarInfo(name)
+        tar.addfile(t)
         tar.close()
 
-    def _create_testtar(self):
-        src = tarfile.open(tarname())
-        t = src.getmember("0-REGTYPE")
-        t.name = "foo"
-        f = src.extractfile(t)
-        tar = tarfile.open(self.tarname, "w")
-        tar.addfile(t, f)
+        tar = tarfile.open(tmpname)
+        self.assert_(tar.getnames()[0] == name,
+                "failed to store 100 char filename")
         tar.close()
 
-    def _test(self, names=["bar"], fileobj=None):
-        tar = tarfile.open(self.tarname, fileobj=fileobj)
-        self.assert_(tar.getnames() == names)
-
-    def test_non_existing(self):
-        self._add_testfile()
-        self._test()
-
-    def test_empty(self):
-        open(self.tarname, "wb").close()
-        self._add_testfile()
-        self._test()
+    def test_tar_size(self):
+        # Test for bug #1013882.
+        tar = tarfile.open(tmpname, self.mode)
+        path = os.path.join(TEMPDIR, "file")
+        fobj = open(path, "wb")
+        fobj.write("aaa")
+        fobj.close()
+        tar.add(path)
+        tar.close()
+        self.assert_(os.path.getsize(tmpname) > 0,
+                "tarfile is empty")
 
-    def test_empty_fileobj(self):
-        fobj = StringIO.StringIO()
-        self._add_testfile(fobj)
-        fobj.seek(0)
-        self._test(fileobj=fobj)
+    # The test_*_size tests test for bug #1167128.
+    def test_file_size(self):
+        tar = tarfile.open(tmpname, self.mode)
 
-    def test_fileobj(self):
-        self._create_testtar()
-        data = open(self.tarname, "rb").read()
-        fobj = StringIO.StringIO(data)
-        self._add_testfile(fobj)
-        fobj.seek(0)
-        self._test(names=["foo", "bar"], fileobj=fobj)
-
-    def test_existing(self):
-        self._create_testtar()
-        self._add_testfile()
-        self._test(names=["foo", "bar"])
+        path = os.path.join(TEMPDIR, "file")
+        fobj = open(path, "wb")
+        fobj.close()
+        tarinfo = tar.gettarinfo(path)
+        self.assertEqual(tarinfo.size, 0)
 
+        fobj = open(path, "wb")
+        fobj.write("aaa")
+        fobj.close()
+        tarinfo = tar.gettarinfo(path)
+        self.assertEqual(tarinfo.size, 3)
 
-class Write100Test(BaseTest):
-    # The name field in a tar header stores strings of at most 100 chars.
-    # If a string is shorter than 100 chars it has to be padded with '\0',
-    # which implies that a string of exactly 100 chars is stored without
-    # a trailing '\0'.
+        tar.close()
 
-    def setUp(self):
-        self.name = "01234567890123456789012345678901234567890123456789"
-        self.name += "01234567890123456789012345678901234567890123456789"
+    def test_directory_size(self):
+        path = os.path.join(TEMPDIR, "directory")
+        os.mkdir(path)
+        try:
+            tar = tarfile.open(tmpname, self.mode)
+            tarinfo = tar.gettarinfo(path)
+            self.assertEqual(tarinfo.size, 0)
+        finally:
+            os.rmdir(path)
 
-        self.tar = tarfile.open(tmpname(), "w")
-        t = tarfile.TarInfo(self.name)
-        self.tar.addfile(t)
-        self.tar.close()
+    def test_link_size(self):
+        if hasattr(os, "link"):
+            link = os.path.join(TEMPDIR, "link")
+            target = os.path.join(TEMPDIR, "link_target")
+            open(target, "wb").close()
+            os.link(target, link)
+            try:
+                tar = tarfile.open(tmpname, self.mode)
+                tarinfo = tar.gettarinfo(link)
+                self.assertEqual(tarinfo.size, 0)
+            finally:
+                os.remove(target)
+                os.remove(link)
 
-        self.tar = tarfile.open(tmpname())
+    def test_symlink_size(self):
+        if hasattr(os, "symlink"):
+            path = os.path.join(TEMPDIR, "symlink")
+            os.symlink("link_target", path)
+            try:
+                tar = tarfile.open(tmpname, self.mode)
+                tarinfo = tar.gettarinfo(path)
+                self.assertEqual(tarinfo.size, 0)
+            finally:
+                os.remove(path)
 
-    def tearDown(self):
-        self.tar.close()
+    def test_add_self(self):
+        # Test for #1257255.
+        dstname = os.path.abspath(tmpname)
 
-    def test(self):
-        self.assertEqual(self.tar.getnames()[0], self.name,
-                "failed to store 100 char filename")
+        tar = tarfile.open(tmpname, self.mode)
+        self.assert_(tar.name == dstname, "archive name must be absolute")
 
+        tar.add(dstname)
+        self.assert_(tar.getnames() == [], "added the archive to itself")
 
-class WriteSize0Test(BaseTest):
-    mode = 'w'
+        cwd = os.getcwd()
+        os.chdir(TEMPDIR)
+        tar.add(dstname)
+        os.chdir(cwd)
+        self.assert_(tar.getnames() == [], "added the archive to itself")
 
-    def setUp(self):
-        self.tmpdir = dirname()
-        self.dstname = tmpname()
-        self.dst = tarfile.open(self.dstname, "w")
+    def test_exclude(self):
+        tempdir = os.path.join(TEMPDIR, "exclude")
+        os.mkdir(tempdir)
+        try:
+            for name in ("foo", "bar", "baz"):
+                name = os.path.join(tempdir, name)
+                open(name, "wb").close()
 
-    def tearDown(self):
-        self.dst.close()
+            def exclude(name):
+                return os.path.isfile(name)
 
-    def test_file(self):
-        path = os.path.join(self.tmpdir, "file")
-        f = open(path, "w")
-        f.close()
-        tarinfo = self.dst.gettarinfo(path)
-        self.assertEqual(tarinfo.size, 0)
-        f = open(path, "w")
-        f.write("aaa")
-        f.close()
-        tarinfo = self.dst.gettarinfo(path)
-        self.assertEqual(tarinfo.size, 3)
+            tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
+            tar.add(tempdir, arcname="empty_dir", exclude=exclude)
+            tar.close()
 
-    def test_directory(self):
-        path = os.path.join(self.tmpdir, "directory")
-        if os.path.exists(path):
-            # This shouldn't be necessary, but is <wink> if a previous
-            # run was killed in mid-stream.
-            shutil.rmtree(path)
-        os.mkdir(path)
-        tarinfo = self.dst.gettarinfo(path)
-        self.assertEqual(tarinfo.size, 0)
+            tar = tarfile.open(tmpname, "r")
+            self.assertEqual(len(tar.getmembers()), 1)
+            self.assertEqual(tar.getnames()[0], "empty_dir")
+        finally:
+            shutil.rmtree(tempdir)
 
-    def test_symlink(self):
-        if hasattr(os, "symlink"):
-            path = os.path.join(self.tmpdir, "symlink")
-            os.symlink("link_target", path)
-            tarinfo = self.dst.gettarinfo(path)
-            self.assertEqual(tarinfo.size, 0)
 
+class StreamWriteTest(unittest.TestCase):
 
-class WriteStreamTest(WriteTest):
-    sep = '|'
+    mode = "w|"
 
-    def test_padding(self):
-        self.dst.close()
+    def test_stream_padding(self):
+        # Test for bug #1543303.
+        tar = tarfile.open(tmpname, self.mode)
+        tar.close()
 
-        if self.comp == "gz":
-            f = gzip.GzipFile(self.dstname)
-            s = f.read()
-            f.close()
-        elif self.comp == "bz2":
-            f = bz2.BZ2Decompressor()
-            s = open(self.dstname).read()
-            s = f.decompress(s)
-            self.assertEqual(len(f.unused_data), 0, "trailing data")
+        if self.mode.endswith("gz"):
+            fobj = gzip.GzipFile(tmpname)
+            data = fobj.read()
+            fobj.close()
+        elif self.mode.endswith("bz2"):
+            dec = bz2.BZ2Decompressor()
+            data = open(tmpname, "rb").read()
+            data = dec.decompress(data)
+            self.assert_(len(dec.unused_data) == 0,
+                    "found trailing data")
         else:
-            f = open(self.dstname)
-            s = f.read()
-            f.close()
+            fobj = open(tmpname, "rb")
+            data = fobj.read()
+            fobj.close()
 
-        self.assertEqual(s.count("\0"), tarfile.RECORDSIZE,
+        self.assert_(data.count("\0") == tarfile.RECORDSIZE,
                          "incorrect zero padding")
 
 
-class WriteGNULongTest(unittest.TestCase):
-    """This testcase checks for correct creation of GNU Longname
-       and Longlink extensions.
-
-       It creates a tarfile and adds empty members with either
-       long names, long linknames or both and compares the size
-       of the tarfile with the expected size.
-
-       It checks for SF bug #812325 in TarFile._create_gnulong().
-
-       While I was writing this testcase, I noticed a second bug
-       in the same method:
-       Long{names,links} weren't null-terminated which lead to
-       bad tarfiles when their length was a multiple of 512. This
-       is tested as well.
-    """
+class GNUWriteTest(unittest.TestCase):
+    # This testcase checks for correct creation of GNU Longname
+    # and Longlink extended headers (cp. bug #812325).
 
     def _length(self, s):
         blocks, remainder = divmod(len(s) + 1, 512)
@@ -474,19 +619,17 @@
         return blocks * 512
 
     def _calc_size(self, name, link=None):
-        # initial tar header
+        # Initial tar header
         count = 512
 
         if len(name) > tarfile.LENGTH_NAME:
-            # gnu longname extended header + longname
+            # GNU longname extended header + longname
             count += 512
             count += self._length(name)
-
         if link is not None and len(link) > tarfile.LENGTH_LINK:
-            # gnu longlink extended header + longlink
+            # GNU longlink extended header + longlink
             count += 512
             count += self._length(link)
-
         return count
 
     def _test(self, name, link=None):
@@ -495,17 +638,17 @@
             tarinfo.linkname = link
             tarinfo.type = tarfile.LNKTYPE
 
-        tar = tarfile.open(tmpname(), "w")
-        tar.posix = False
+        tar = tarfile.open(tmpname, "w")
+        tar.format = tarfile.GNU_FORMAT
         tar.addfile(tarinfo)
 
         v1 = self._calc_size(name, link)
         v2 = tar.offset
-        self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
+        self.assert_(v1 == v2, "GNU longname/longlink creation failed")
 
         tar.close()
 
-        tar = tarfile.open(tmpname())
+        tar = tarfile.open(tmpname)
         member = tar.next()
         self.failIf(member is None, "unable to read longname member")
         self.assert_(tarinfo.name == member.name and \
@@ -542,268 +685,442 @@
         self._test(("longnam/" * 127) + "longname_",
                    ("longlnk/" * 127) + "longlink_")
 
-class ReadGNULongTest(unittest.TestCase):
+
+class HardlinkTest(unittest.TestCase):
+    # Test the creation of LNKTYPE (hardlink) members in an archive.
 
     def setUp(self):
-        self.tar = tarfile.open(tarname())
+        self.foo = os.path.join(TEMPDIR, "foo")
+        self.bar = os.path.join(TEMPDIR, "bar")
+
+        fobj = open(self.foo, "wb")
+        fobj.write("foo")
+        fobj.close()
+
+        os.link(self.foo, self.bar)
+
+        self.tar = tarfile.open(tmpname, "w")
+        self.tar.add(self.foo)
 
     def tearDown(self):
-        self.tar.close()
+        os.remove(self.foo)
+        os.remove(self.bar)
 
-    def test_1471427(self):
-        """Test reading of longname (bug #1471427).
-        """
-        name = "test/" * 20 + "0-REGTYPE"
-        try:
-            tarinfo = self.tar.getmember(name)
-        except KeyError:
-            tarinfo = None
-        self.assert_(tarinfo is not None, "longname not found")
-        self.assert_(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
+    def test_add_twice(self):
+        # The same name will be added as a REGTYPE every
+        # time regardless of st_nlink.
+        tarinfo = self.tar.gettarinfo(self.foo)
+        self.assert_(tarinfo.type == tarfile.REGTYPE,
+                "add file as regular failed")
 
-    def test_read_name(self):
-        name = ("0-LONGNAME-" * 10)[:101]
-        try:
-            tarinfo = self.tar.getmember(name)
-        except KeyError:
-            tarinfo = None
-        self.assert_(tarinfo is not None, "longname not found")
+    def test_add_hardlink(self):
+        tarinfo = self.tar.gettarinfo(self.bar)
+        self.assert_(tarinfo.type == tarfile.LNKTYPE,
+                "add file as hardlink failed")
 
-    def test_read_link(self):
-        link = ("1-LONGLINK-" * 10)[:101]
-        name = ("0-LONGNAME-" * 10)[:101]
-        try:
-            tarinfo = self.tar.getmember(link)
-        except KeyError:
-            tarinfo = None
-        self.assert_(tarinfo is not None, "longlink not found")
-        self.assert_(tarinfo.linkname == name, "linkname wrong")
+    def test_dereference_hardlink(self):
+        self.tar.dereference = True
+        tarinfo = self.tar.gettarinfo(self.bar)
+        self.assert_(tarinfo.type == tarfile.REGTYPE,
+                "dereferencing hardlink failed")
 
-    def test_truncated_longname(self):
-        f = open(tarname())
-        fobj = StringIO.StringIO(f.read(1024))
-        f.close()
-        tar = tarfile.open(name="foo.tar", fileobj=fobj)
-        self.assert_(len(tar.getmembers()) == 0, "")
+
+class PaxWriteTest(GNUWriteTest):
+
+    def _test(self, name, link=None):
+        # See GNUWriteTest.
+        tarinfo = tarfile.TarInfo(name)
+        if link:
+            tarinfo.linkname = link
+            tarinfo.type = tarfile.LNKTYPE
+
+        tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
+        tar.addfile(tarinfo)
         tar.close()
 
+        tar = tarfile.open(tmpname)
+        if link:
+            l = tar.getmembers()[0].linkname
+            self.assert_(link == l, "PAX longlink creation failed")
+        else:
+            n = tar.getmembers()[0].name
+            self.assert_(name == n, "PAX longname creation failed")
 
-class ExtractHardlinkTest(BaseTest):
+    def test_pax_global_header(self):
+        pax_headers = {
+                u"foo": u"bar",
+                u"uid": u"0",
+                u"mtime": u"1.23",
+                u"test": u"äöü",
+                u"äöü": u"test"}
+
+        tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, \
+                pax_headers=pax_headers)
+        tar.addfile(tarfile.TarInfo("test"))
+        tar.close()
 
-    def test_hardlink(self):
-        """Test hardlink extraction (bug #857297)
-        """
-        # Prevent errors from being caught
-        self.tar.errorlevel = 1
+        # Test if the global header was written correctly.
+        tar = tarfile.open(tmpname, encoding="iso8859-1")
+        self.assertEqual(tar.pax_headers, pax_headers)
+        self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
+
+        # Test if all the fields are unicode.
+        for key, val in tar.pax_headers.items():
+            self.assert_(type(key) is unicode)
+            self.assert_(type(val) is unicode)
+            if key in tarfile.PAX_NUMBER_FIELDS:
+                try:
+                    tarfile.PAX_NUMBER_FIELDS[key](val)
+                except (TypeError, ValueError):
+                    self.fail("unable to convert pax header field")
+
+    def test_pax_extended_header(self):
+        # The fields from the pax header have priority over the
+        # TarInfo.
+        pax_headers = {u"path": u"foo", u"uid": u"123"}
+
+        tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
+        t = tarfile.TarInfo()
+        t.name = u"äöü"     # non-ASCII
+        t.uid = 8**8        # too large
+        t.pax_headers = pax_headers
+        tar.addfile(t)
+        tar.close()
 
-        self.tar.extract("0-REGTYPE", dirname())
-        try:
-            # Extract 1-LNKTYPE which is a hardlink to 0-REGTYPE
-            self.tar.extract("1-LNKTYPE", dirname())
-        except EnvironmentError as e:
-            import errno
-            if e.errno == errno.ENOENT:
-                self.fail("hardlink not extracted properly")
+        tar = tarfile.open(tmpname, encoding="iso8859-1")
+        t = tar.getmembers()[0]
+        self.assertEqual(t.pax_headers, pax_headers)
+        self.assertEqual(t.name, "foo")
+        self.assertEqual(t.uid, 123)
 
-class CreateHardlinkTest(BaseTest):
-    """Test the creation of LNKTYPE (hardlink) members in an archive.
-       In this respect tarfile.py mimics the behaviour of GNU tar: If
-       a file has a st_nlink > 1, it will be added a REGTYPE member
-       only the first time.
-    """
 
-    def setUp(self):
-        self.tar = tarfile.open(tmpname(), "w")
+class UstarUnicodeTest(unittest.TestCase):
+    # All *UnicodeTests FIXME
 
-        self.foo = os.path.join(dirname(), "foo")
-        self.bar = os.path.join(dirname(), "bar")
+    format = tarfile.USTAR_FORMAT
 
-        if os.path.exists(self.foo):
-            os.remove(self.foo)
-        if os.path.exists(self.bar):
-            os.remove(self.bar)
-
-        f = open(self.foo, "w")
-        f.write("foo")
-        f.close()
-        self.tar.add(self.foo)
+    def test_iso8859_1_filename(self):
+        self._test_unicode_filename("iso8859-1")
 
-    def test_add_twice(self):
-        # If st_nlink == 1 then the same file will be added as
-        # REGTYPE every time.
-        tarinfo = self.tar.gettarinfo(self.foo)
-        self.assertEqual(tarinfo.type, tarfile.REGTYPE,
-                "add file as regular failed")
+    def test_utf7_filename(self):
+        self._test_unicode_filename("utf7")
 
-    def test_add_hardlink(self):
-        # If st_nlink > 1 then the same file will be added as
-        # LNKTYPE.
-        os.link(self.foo, self.bar)
-        tarinfo = self.tar.gettarinfo(self.foo)
-        self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
-                "add file as hardlink failed")
+    def test_utf8_filename(self):
+        self._test_unicode_filename("utf8")
 
-        tarinfo = self.tar.gettarinfo(self.bar)
-        self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
-                "add file as hardlink failed")
+    def _test_unicode_filename(self, encoding):
+        tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
+        name = u"äöü"
+        tar.addfile(tarfile.TarInfo(name))
+        tar.close()
 
-    def test_dereference_hardlink(self):
-        self.tar.dereference = True
-        os.link(self.foo, self.bar)
-        tarinfo = self.tar.gettarinfo(self.bar)
-        self.assertEqual(tarinfo.type, tarfile.REGTYPE,
-                "dereferencing hardlink failed")
+        tar = tarfile.open(tmpname, encoding=encoding)
+        self.assert_(type(tar.getnames()[0]) is not unicode)
+        self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
+        tar.close()
 
+    def test_unicode_filename_error(self):
+        tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
+        tarinfo = tarfile.TarInfo()
+
+        tarinfo.name = "äöü"
+        if self.format == tarfile.PAX_FORMAT:
+            self.assertRaises(UnicodeError, tar.addfile, tarinfo)
+        else:
+            tar.addfile(tarinfo)
 
-# Gzip TestCases
-class ReadTestGzip(ReadTest):
-    comp = "gz"
-class ReadStreamTestGzip(ReadStreamTest):
-    comp = "gz"
-class WriteTestGzip(WriteTest):
-    comp = "gz"
-class WriteStreamTestGzip(WriteStreamTest):
-    comp = "gz"
-class ReadDetectTestGzip(ReadDetectTest):
-    comp = "gz"
-class ReadDetectFileobjTestGzip(ReadDetectFileobjTest):
-    comp = "gz"
-class ReadAsteriskTestGzip(ReadAsteriskTest):
-    comp = "gz"
-class ReadStreamAsteriskTestGzip(ReadStreamAsteriskTest):
-    comp = "gz"
-
-# Filemode test cases
-
-class FileModeTest(unittest.TestCase):
-    def test_modes(self):
-        self.assertEqual(tarfile.filemode(0755), '-rwxr-xr-x')
-        self.assertEqual(tarfile.filemode(07111), '---s--s--t')
-
-class HeaderErrorTest(unittest.TestCase):
-
-    def test_truncated_header(self):
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "")
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "filename\0")
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 511)
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 513)
-
-    def test_empty_header(self):
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 512)
-
-    def test_invalid_header(self):
-        buf = tarfile.TarInfo("filename").tobuf()
-        buf = buf[:148] + "foo\0\0\0\0\0" + buf[156:] # invalid number field.
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, buf)
-
-    def test_bad_checksum(self):
-        buf = tarfile.TarInfo("filename").tobuf()
-        b = buf[:148] + "        " + buf[156:] # clear the checksum field.
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b)
-        b = "a" + buf[1:] # manipulate the buffer, so checksum won't match.
-        self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b)
+        tarinfo.name = u"äöü"
+        self.assertRaises(UnicodeError, tar.addfile, tarinfo)
 
-class OpenFileobjTest(BaseTest):
-    # Test for SF bug #1496501.
+        tarinfo.name = "foo"
+        tarinfo.uname = u"äöü"
+        self.assertRaises(UnicodeError, tar.addfile, tarinfo)
+
+    def test_unicode_argument(self):
+        tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
+        for t in tar:
+            self.assert_(type(t.name) is str)
+            self.assert_(type(t.linkname) is str)
+            self.assert_(type(t.uname) is str)
+            self.assert_(type(t.gname) is str)
+        tar.close()
 
-    def test_opener(self):
-        fobj = StringIO.StringIO("foo\n")
-        try:
-            tarfile.open("", "r", fileobj=fobj)
-        except tarfile.ReadError:
-            self.assertEqual(fobj.tell(), 0, "fileobj's position has moved")
+    def test_uname_unicode(self):
+        for name in (u"äöü", "äöü"):
+            t = tarfile.TarInfo("foo")
+            t.uname = name
+            t.gname = name
+
+            fobj = StringIO.StringIO()
+            tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
+            tar.addfile(t)
+            tar.close()
+            fobj.seek(0)
 
-if bz2:
-    # Bzip2 TestCases
-    class ReadTestBzip2(ReadTestGzip):
-        comp = "bz2"
-    class ReadStreamTestBzip2(ReadStreamTestGzip):
-        comp = "bz2"
-    class WriteTestBzip2(WriteTest):
-        comp = "bz2"
-    class WriteStreamTestBzip2(WriteStreamTestGzip):
-        comp = "bz2"
-    class ReadDetectTestBzip2(ReadDetectTest):
-        comp = "bz2"
-    class ReadDetectFileobjTestBzip2(ReadDetectFileobjTest):
-        comp = "bz2"
-    class ReadAsteriskTestBzip2(ReadAsteriskTest):
-        comp = "bz2"
-    class ReadStreamAsteriskTestBzip2(ReadStreamAsteriskTest):
-        comp = "bz2"
-
-# If importing gzip failed, discard the Gzip TestCases.
-if not gzip:
-    del ReadTestGzip
-    del ReadStreamTestGzip
-    del WriteTestGzip
-    del WriteStreamTestGzip
+            tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
+            t = tar.getmember("foo")
+            self.assertEqual(t.uname, "äöü")
+            self.assertEqual(t.gname, "äöü")
 
-def test_main():
-    # Create archive.
-    f = open(tarname(), "rb")
-    fguts = f.read()
-    f.close()
-    if gzip:
-        # create testtar.tar.gz
-        tar = gzip.open(tarname("gz"), "wb")
-        tar.write(fguts)
+
+class GNUUnicodeTest(UstarUnicodeTest):
+
+    format = tarfile.GNU_FORMAT
+
+
+class PaxUnicodeTest(UstarUnicodeTest):
+
+    format = tarfile.PAX_FORMAT
+
+    def _create_unicode_name(self, name):
+        tar = tarfile.open(tmpname, "w", format=self.format)
+        t = tarfile.TarInfo()
+        t.pax_headers["path"] = name
+        tar.addfile(t)
         tar.close()
-    if bz2:
-        # create testtar.tar.bz2
-        tar = bz2.BZ2File(tarname("bz2"), "wb")
-        tar.write(fguts)
+
+    def test_error_handlers(self):
+        # Test if the unicode error handlers work correctly for characters
+        # that cannot be expressed in a given encoding.
+        self._create_unicode_name(u"äöü")
+
+        for handler, name in (("utf-8", u"äöü".encode("utf8")),
+                    ("replace", "???"), ("ignore", "")):
+            tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
+                    errors=handler)
+            self.assertEqual(tar.getnames()[0], name)
+
+        self.assertRaises(UnicodeError, tarfile.open, tmpname,
+                encoding="ascii", errors="strict")
+
+    def test_error_handler_utf8(self):
+        # Create a pathname that has one component representable using
+        # iso8859-1 and the other only in iso8859-15.
+        self._create_unicode_name(u"äöü/¤")
+
+        tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
+                errors="utf-8")
+        self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
+
+
+class AppendTest(unittest.TestCase):
+    # Test append mode (cp. patch #1652681).
+
+    def setUp(self):
+        self.tarname = tmpname
+        if os.path.exists(self.tarname):
+            os.remove(self.tarname)
+
+    def _add_testfile(self, fileobj=None):
+        tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
+        tar.addfile(tarfile.TarInfo("bar"))
+        tar.close()
+
+    def _create_testtar(self, mode="w:"):
+        src = tarfile.open(tarname, encoding="iso8859-1")
+        t = src.getmember("ustar/regtype")
+        t.name = "foo"
+        f = src.extractfile(t)
+        tar = tarfile.open(self.tarname, mode)
+        tar.addfile(t, f)
         tar.close()
 
+    def _test(self, names=["bar"], fileobj=None):
+        tar = tarfile.open(self.tarname, fileobj=fileobj)
+        self.assertEqual(tar.getnames(), names)
+
+    def test_non_existing(self):
+        self._add_testfile()
+        self._test()
+
+    def test_empty(self):
+        open(self.tarname, "w").close()
+        self._add_testfile()
+        self._test()
+
+    def test_empty_fileobj(self):
+        fobj = StringIO.StringIO()
+        self._add_testfile(fobj)
+        fobj.seek(0)
+        self._test(fileobj=fobj)
+
+    def test_fileobj(self):
+        self._create_testtar()
+        data = open(self.tarname).read()
+        fobj = StringIO.StringIO(data)
+        self._add_testfile(fobj)
+        fobj.seek(0)
+        self._test(names=["foo", "bar"], fileobj=fobj)
+
+    def test_existing(self):
+        self._create_testtar()
+        self._add_testfile()
+        self._test(names=["foo", "bar"])
+
+    def test_append_gz(self):
+        if gzip is None:
+            return
+        self._create_testtar("w:gz")
+        self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
+
+    def test_append_bz2(self):
+        if bz2 is None:
+            return
+        self._create_testtar("w:bz2")
+        self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
+
+
+class LimitsTest(unittest.TestCase):
+
+    def test_ustar_limits(self):
+        # 100 char name
+        tarinfo = tarfile.TarInfo("0123456789" * 10)
+        tarinfo.tobuf(tarfile.USTAR_FORMAT)
+
+        # 101 char name that cannot be stored
+        tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
+        self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
+
+        # 256 char name with a slash at pos 156
+        tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
+        tarinfo.tobuf(tarfile.USTAR_FORMAT)
+
+        # 256 char name that cannot be stored
+        tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
+        self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
+
+        # 512 char name
+        tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
+        self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
+
+        # 512 char linkname
+        tarinfo = tarfile.TarInfo("longlink")
+        tarinfo.linkname = "123/" * 126 + "longname"
+        self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
+
+        # uid > 8 digits
+        tarinfo = tarfile.TarInfo("name")
+        tarinfo.uid = 0o10000000
+        self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
+
+    def test_gnu_limits(self):
+        tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
+        tarinfo.tobuf(tarfile.GNU_FORMAT)
+
+        tarinfo = tarfile.TarInfo("longlink")
+        tarinfo.linkname = "123/" * 126 + "longname"
+        tarinfo.tobuf(tarfile.GNU_FORMAT)
+
+        # uid >= 256 ** 7
+        tarinfo = tarfile.TarInfo("name")
+        tarinfo.uid = 0o4000000000000000000
+        self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
+
+    def test_pax_limits(self):
+        tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
+        tarinfo.tobuf(tarfile.PAX_FORMAT)
+
+        tarinfo = tarfile.TarInfo("longlink")
+        tarinfo.linkname = "123/" * 126 + "longname"
+        tarinfo.tobuf(tarfile.PAX_FORMAT)
+
+        tarinfo = tarfile.TarInfo("name")
+        tarinfo.uid = 0o4000000000000000000
+        tarinfo.tobuf(tarfile.PAX_FORMAT)
+
+
+class GzipMiscReadTest(MiscReadTest):
+    tarname = gzipname
+    mode = "r:gz"
+class GzipUstarReadTest(UstarReadTest):
+    tarname = gzipname
+    mode = "r:gz"
+class GzipStreamReadTest(StreamReadTest):
+    tarname = gzipname
+    mode = "r|gz"
+class GzipWriteTest(WriteTest):
+    mode = "w:gz"
+class GzipStreamWriteTest(StreamWriteTest):
+    mode = "w|gz"
+
+
+class Bz2MiscReadTest(MiscReadTest):
+    tarname = bz2name
+    mode = "r:bz2"
+class Bz2UstarReadTest(UstarReadTest):
+    tarname = bz2name
+    mode = "r:bz2"
+class Bz2StreamReadTest(StreamReadTest):
+    tarname = bz2name
+    mode = "r|bz2"
+class Bz2WriteTest(WriteTest):
+    mode = "w:bz2"
+class Bz2StreamWriteTest(StreamWriteTest):
+    mode = "w|bz2"
+
+def test_main():
+    if not os.path.exists(TEMPDIR):
+        os.mkdir(TEMPDIR)
+
     tests = [
-        FileModeTest,
-        HeaderErrorTest,
-        OpenFileobjTest,
-        ReadTest,
-        ReadStreamTest,
-        ReadDetectTest,
-        ReadDetectFileobjTest,
-        ReadAsteriskTest,
-        ReadStreamAsteriskTest,
+        UstarReadTest,
+        MiscReadTest,
+        StreamReadTest,
+        DetectReadTest,
+        MemberReadTest,
+        GNUReadTest,
+        PaxReadTest,
         WriteTest,
+        StreamWriteTest,
+        GNUWriteTest,
+        PaxWriteTest,
+        UstarUnicodeTest,
+        GNUUnicodeTest,
+        PaxUnicodeTest,
         AppendTest,
-        Write100Test,
-        WriteSize0Test,
-        WriteStreamTest,
-        WriteGNULongTest,
-        ReadGNULongTest,
+        LimitsTest,
     ]
 
     if hasattr(os, "link"):
-        tests.append(ExtractHardlinkTest)
-        tests.append(CreateHardlinkTest)
+        tests.append(HardlinkTest)
+
+    fobj = open(tarname, "rb")
+    data = fobj.read()
+    fobj.close()
 
     if gzip:
-        tests.extend([
-            ReadTestGzip, ReadStreamTestGzip,
-            WriteTestGzip, WriteStreamTestGzip,
-            ReadDetectTestGzip, ReadDetectFileobjTestGzip,
-            ReadAsteriskTestGzip, ReadStreamAsteriskTestGzip
-        ])
+        # Create testtar.tar.gz and add gzip-specific tests.
+        tar = gzip.open(gzipname, "wb")
+        tar.write(data)
+        tar.close()
+
+        tests += [
+            GzipMiscReadTest,
+            GzipUstarReadTest,
+            GzipStreamReadTest,
+            GzipWriteTest,
+            GzipStreamWriteTest,
+        ]
 
     if bz2:
-        tests.extend([
-            ReadTestBzip2, ReadStreamTestBzip2,
-            WriteTestBzip2, WriteStreamTestBzip2,
-            ReadDetectTestBzip2, ReadDetectFileobjTestBzip2,
-            ReadAsteriskTestBzip2, ReadStreamAsteriskTestBzip2
-        ])
+        # Create testtar.tar.bz2 and add bz2-specific tests.
+        tar = bz2.BZ2File(bz2name, "wb")
+        tar.write(data)
+        tar.close()
+
+        tests += [
+            Bz2MiscReadTest,
+            Bz2UstarReadTest,
+            Bz2StreamReadTest,
+            Bz2WriteTest,
+            Bz2StreamWriteTest,
+        ]
+
     try:
         test_support.run_unittest(*tests)
     finally:
-        if gzip:
-            os.remove(tarname("gz"))
-        if bz2:
-            os.remove(tarname("bz2"))
-        if os.path.exists(dirname()):
-            shutil.rmtree(dirname())
-        if os.path.exists(tmpname()):
-            os.remove(tmpname())
+        if os.path.exists(TEMPDIR):
+            shutil.rmtree(TEMPDIR)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_tempfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_tempfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_tempfile.py	Wed Jul 11 15:40:56 2007
@@ -81,7 +81,8 @@
             "gettempprefix" : 1,
             "gettempdir" : 1,
             "tempdir" : 1,
-            "template" : 1
+            "template" : 1,
+            "SpooledTemporaryFile" : 1
         }
 
         unexp = []
@@ -102,7 +103,7 @@
 
     def test_get_six_char_str(self):
         # _RandomNameSequence returns a six-character string
-        s = self.r.next()
+        s = next(self.r)
         self.nameCheck(s, '', '', '')
 
     def test_many(self):
@@ -110,8 +111,8 @@
 
         dict = {}
         r = self.r
-        for i in xrange(TEST_FILES):
-            s = r.next()
+        for i in range(TEST_FILES):
+            s = next(r)
             self.nameCheck(s, '', '', '')
             self.failIf(s in dict)
             dict[s] = 1
@@ -244,7 +245,7 @@
 
     def test_basic_many(self):
         # _mkstemp_inner can create many files (stochastic)
-        extant = range(TEST_FILES)
+        extant = list(range(TEST_FILES))
         for i in extant:
             extant[i] = self.do_create(pre="aa")
 
@@ -263,7 +264,7 @@
 
         file = self.do_create()
         mode = stat.S_IMODE(os.stat(file.name).st_mode)
-        expected = 0600
+        expected = 0o600
         if sys.platform in ('win32', 'os2emx', 'mac'):
             # There's no distinction among 'user', 'group' and 'world';
             # replicate the 'user' bits.
@@ -456,7 +457,7 @@
 
     def test_basic_many(self):
         # mkdtemp can create many directories (stochastic)
-        extant = range(TEST_FILES)
+        extant = list(range(TEST_FILES))
         try:
             for i in extant:
                 extant[i] = self.do_create(pre="aa")
@@ -481,8 +482,8 @@
         dir = self.do_create()
         try:
             mode = stat.S_IMODE(os.stat(dir).st_mode)
-            mode &= 0777 # Mask off sticky bits inherited from /tmp
-            expected = 0700
+            mode &= 0o777 # Mask off sticky bits inherited from /tmp
+            expected = 0o700
             if sys.platform in ('win32', 'os2emx', 'mac'):
                 # There's no distinction among 'user', 'group' and 'world';
                 # replicate the 'user' bits.
@@ -516,7 +517,7 @@
             self.name = tempfile.mktemp(dir=dir, prefix=pre, suffix=suf)
             # Create the file.  This will raise an exception if it's
             # mysteriously appeared in the meanwhile.
-            os.close(os.open(self.name, self._bflags, 0600))
+            os.close(os.open(self.name, self._bflags, 0o600))
 
         def __del__(self):
             self._unlink(self.name)
@@ -540,7 +541,7 @@
 
     def test_many(self):
         # mktemp can choose many usable file names (stochastic)
-        extant = range(TEST_FILES)
+        extant = list(range(TEST_FILES))
         for i in extant:
             extant[i] = self.do_create(pre="aa")
 
@@ -561,11 +562,12 @@
 class test_NamedTemporaryFile(TC):
     """Test NamedTemporaryFile()."""
 
-    def do_create(self, dir=None, pre="", suf=""):
+    def do_create(self, dir=None, pre="", suf="", delete=True):
         if dir is None:
             dir = tempfile.gettempdir()
         try:
-            file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf)
+            file = tempfile.NamedTemporaryFile(dir=dir, prefix=pre, suffix=suf,
+                                               delete=delete)
         except:
             self.failOnException("NamedTemporaryFile")
 
@@ -599,6 +601,22 @@
         finally:
             os.rmdir(dir)
 
+    def test_dis_del_on_close(self):
+        # Tests that delete-on-close can be disabled
+        dir = tempfile.mkdtemp()
+        tmp = None
+        try:
+            f = tempfile.NamedTemporaryFile(dir=dir, delete=False)
+            tmp = f.name
+            f.write('blat')
+            f.close()
+            self.failUnless(os.path.exists(f.name),
+                        "NamedTemporaryFile %s missing after close" % f.name)
+        finally:
+            if tmp is not None:
+                os.unlink(tmp)
+            os.rmdir(dir)
+
     def test_multiple_close(self):
         # A NamedTemporaryFile can be closed many times without error
 
@@ -615,6 +633,107 @@
 
 test_classes.append(test_NamedTemporaryFile)
 
+class test_SpooledTemporaryFile(TC):
+    """Test SpooledTemporaryFile()."""
+
+    def do_create(self, max_size=0, dir=None, pre="", suf=""):
+        if dir is None:
+            dir = tempfile.gettempdir()
+        try:
+            file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
+        except:
+            self.failOnException("SpooledTemporaryFile")
+
+        return file
+
+
+    def test_basic(self):
+        # SpooledTemporaryFile can create files
+        f = self.do_create()
+        self.failIf(f._rolled)
+        f = self.do_create(max_size=100, pre="a", suf=".txt")
+        self.failIf(f._rolled)
+
+    def test_del_on_close(self):
+        # A SpooledTemporaryFile is deleted when closed
+        dir = tempfile.mkdtemp()
+        try:
+            f = tempfile.SpooledTemporaryFile(max_size=10, dir=dir)
+            self.failIf(f._rolled)
+            f.write('blat ' * 5)
+            self.failUnless(f._rolled)
+            filename = f.name
+            f.close()
+            self.failIf(os.path.exists(filename),
+                        "SpooledTemporaryFile %s exists after close" % filename)
+        finally:
+            os.rmdir(dir)
+
+    def test_rewrite_small(self):
+        # A SpooledTemporaryFile can be written to multiple within the max_size
+        f = self.do_create(max_size=30)
+        self.failIf(f._rolled)
+        for i in range(5):
+            f.seek(0, 0)
+            f.write('x' * 20)
+        self.failIf(f._rolled)
+
+    def test_write_sequential(self):
+        # A SpooledTemporaryFile should hold exactly max_size bytes, and roll
+        # over afterward
+        f = self.do_create(max_size=30)
+        self.failIf(f._rolled)
+        f.write('x' * 20)
+        self.failIf(f._rolled)
+        f.write('x' * 10)
+        self.failIf(f._rolled)
+        f.write('x')
+        self.failUnless(f._rolled)
+
+    def test_sparse(self):
+        # A SpooledTemporaryFile that is written late in the file will extend
+        # when that occurs
+        f = self.do_create(max_size=30)
+        self.failIf(f._rolled)
+        f.seek(100, 0)
+        self.failIf(f._rolled)
+        f.write('x')
+        self.failUnless(f._rolled)
+
+    def test_fileno(self):
+        # A SpooledTemporaryFile should roll over to a real file on fileno()
+        f = self.do_create(max_size=30)
+        self.failIf(f._rolled)
+        self.failUnless(f.fileno() > 0)
+        self.failUnless(f._rolled)
+
+    def test_multiple_close(self):
+        # A SpooledTemporaryFile can be closed many times without error
+        f = tempfile.SpooledTemporaryFile()
+        f.write('abc\n')
+        f.close()
+        try:
+            f.close()
+            f.close()
+        except:
+            self.failOnException("close")
+
+    def test_bound_methods(self):
+        # It should be OK to steal a bound method from a SpooledTemporaryFile
+        # and use it independently; when the file rolls over, those bound
+        # methods should continue to function
+        f = self.do_create(max_size=30)
+        read = f.read
+        write = f.write
+        seek = f.seek
+
+        write("a" * 35)
+        write("b" * 35)
+        seek(0, 0)
+        self.failUnless(read(70) == 'a'*35 + 'b'*35)
+
+test_classes.append(test_SpooledTemporaryFile)
+
 
 class test_TemporaryFile(TC):
     """Test TemporaryFile()."""

Modified: python/branches/p3yk-noslice/Lib/test/test_textwrap.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_textwrap.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_textwrap.py	Wed Jul 11 15:40:56 2007
@@ -328,6 +328,14 @@
         self.check_wrap(text, 30,
                         [" This is a sentence with", "leading whitespace."])
 
+    def test_no_drop_whitespace(self):
+        # SF patch #1581073
+        text = " This is a    sentence with     much whitespace."
+        self.check_wrap(text, 10,
+                        [" This is a", "    ", "sentence ",
+                         "with     ", "much white", "space."],
+                        drop_whitespace=False)
+
     if test_support.have_unicode:
         def test_unicode(self):
             # *Very* simple test of wrapping Unicode strings.  I'm sure

Modified: python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py	Wed Jul 11 15:40:56 2007
@@ -10,22 +10,20 @@
 By default, NUM_THREADS == 20 and FILES_PER_THREAD == 50.  This is enough to
 create about 150 failures per run under Win98SE in 2.0, and runs pretty
 quickly. Guido reports needing to boost FILES_PER_THREAD to 500 before
-provoking a 2.0 failure under Linux.  Run the test alone to boost either
-via cmdline switches:
-
--f  FILES_PER_THREAD (int)
--t  NUM_THREADS (int)
+provoking a 2.0 failure under Linux.
 """
 
-NUM_THREADS = 20        # change w/ -t option
-FILES_PER_THREAD = 50   # change w/ -f option
+NUM_THREADS = 20
+FILES_PER_THREAD = 50
 
 import thread # If this fails, we can't test this module
 import threading
-from test.test_support import TestFailed, threading_setup, threading_cleanup
+import tempfile
+
+from test.test_support import threading_setup, threading_cleanup, run_unittest
+import unittest
 import StringIO
 from traceback import print_exc
-import tempfile
 
 startEvent = threading.Event()
 
@@ -46,41 +44,36 @@
             else:
                 self.ok_count += 1
 
-def test_main():
-    threads = []
-    thread_info = threading_setup()
 
-    print("Creating")
-    for i in range(NUM_THREADS):
-        t = TempFileGreedy()
-        threads.append(t)
-        t.start()
-
-    print("Starting")
-    startEvent.set()
-
-    print("Reaping")
-    ok = errors = 0
-    for t in threads:
-        t.join()
-        ok += t.ok_count
-        errors += t.error_count
-        if t.error_count:
-            print('%s errors:\n%s' % (t.getName(), t.errors.getvalue()))
-
-    msg = "Done: errors %d ok %d" % (errors, ok)
-    print(msg)
-    if errors:
-        raise TestFailed(msg)
+class ThreadedTempFileTest(unittest.TestCase):
+    def test_main(self):
+        threads = []
+        thread_info = threading_setup()
+
+        for i in range(NUM_THREADS):
+            t = TempFileGreedy()
+            threads.append(t)
+            t.start()
+
+        startEvent.set()
+
+        ok = 0
+        errors = []
+        for t in threads:
+            t.join()
+            ok += t.ok_count
+            if t.error_count:
+                errors.append(str(t.getName()) + str(t.errors.getvalue()))
+
+        threading_cleanup(*thread_info)
+
+        msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok,
+            '\n'.join(errors))
+        self.assertEquals(errors, [], msg)
+        self.assertEquals(ok, NUM_THREADS * FILES_PER_THREAD)
 
-    threading_cleanup(*thread_info)
+def test_main():
+    run_unittest(ThreadedTempFileTest)
 
 if __name__ == "__main__":
-    import sys, getopt
-    opts, args = getopt.getopt(sys.argv[1:], "t:f:")
-    for o, v in opts:
-        if o == "-f":
-            FILES_PER_THREAD = int(v)
-        elif o == "-t":
-            NUM_THREADS = int(v)
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_threading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threading.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_threading.py	Wed Jul 11 15:40:56 2007
@@ -3,6 +3,7 @@
 import test.test_support
 from test.test_support import verbose
 import random
+import sys
 import threading
 import thread
 import time
@@ -201,8 +202,47 @@
             t.join()
         # else the thread is still running, and we have no way to kill it
 
+class ThreadingExceptionTests(unittest.TestCase):
+    # A RuntimeError should be raised if Thread.start() is called
+    # multiple times.
+    def test_start_thread_again(self):
+        thread = threading.Thread()
+        thread.start()
+        self.assertRaises(RuntimeError, thread.start)
+
+    def test_releasing_unacquired_rlock(self):
+        rlock = threading.RLock()
+        self.assertRaises(RuntimeError, rlock.release)
+
+    def test_waiting_on_unacquired_condition(self):
+        cond = threading.Condition()
+        self.assertRaises(RuntimeError, cond.wait)
+
+    def test_notify_on_unacquired_condition(self):
+        cond = threading.Condition()
+        self.assertRaises(RuntimeError, cond.notify)
+
+    def test_semaphore_with_negative_value(self):
+        self.assertRaises(ValueError, threading.Semaphore, value = -1)
+        self.assertRaises(ValueError, threading.Semaphore, value = -sys.maxint)
+
+    def test_joining_current_thread(self):
+        currentThread = threading.currentThread()
+        self.assertRaises(RuntimeError, currentThread.join);
+
+    def test_joining_inactive_thread(self):
+        thread = threading.Thread()
+        self.assertRaises(RuntimeError, thread.join)
+
+    def test_daemonize_active_thread(self):
+        thread = threading.Thread()
+        thread.start()
+        self.assertRaises(RuntimeError, thread.setDaemon, True)
+
+
 def test_main():
-    test.test_support.run_unittest(ThreadTests)
+    test.test_support.run_unittest(ThreadTests,
+                                   ThreadingExceptionTests)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_threading_local.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threading_local.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_threading_local.py	Wed Jul 11 15:40:56 2007
@@ -20,7 +20,7 @@
                                    setUp=setUp, tearDown=tearDown)
                       )
 
-    test_support.run_suite(suite)
+    test_support.run_unittest(suite)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_threadsignals.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threadsignals.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_threadsignals.py	Wed Jul 11 15:40:56 2007
@@ -14,7 +14,7 @@
 signalled_all=thread.allocate_lock()
 
 
-def registerSignals((for_usr1, for_usr2, for_alrm)):
+def registerSignals(for_usr1, for_usr2, for_alrm):
     usr1 = signal.signal(signal.SIGUSR1, for_usr1)
     usr2 = signal.signal(signal.SIGUSR2, for_usr2)
     alrm = signal.signal(signal.SIGALRM, for_alrm)
@@ -74,11 +74,11 @@
                           signal.SIGUSR2 : {'tripped': 0, 'tripped_by': 0 },
                           signal.SIGALRM : {'tripped': 0, 'tripped_by': 0 } }
 
-    oldsigs = registerSignals((handle_signals, handle_signals, handle_signals))
+    oldsigs = registerSignals(handle_signals, handle_signals, handle_signals)
     try:
         run_unittest(ThreadSignals)
     finally:
-        registerSignals(oldsigs)
+        registerSignals(*oldsigs)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_tokenize.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_tokenize.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_tokenize.py	Wed Jul 11 15:40:56 2007
@@ -19,7 +19,7 @@
 
 >>> dump_tokens("if False:\\n"
 ...             "    # NL\\n"
-...             "    True = False # NEWLINE\\n")
+...             "    a    = False # NEWLINE\\n")
 NAME        'if'          (1, 0) (1, 2)
 NAME        'False'       (1, 3) (1, 8)
 OP          ':'           (1, 8) (1, 9)
@@ -27,7 +27,7 @@
 COMMENT     '# NL'        (2, 4) (2, 8)
 NL          '\\n'          (2, 8) (2, 9)
 INDENT      '    '        (3, 0) (3, 4)
-NAME        'True'        (3, 4) (3, 8)
+NAME        'a'           (3, 4) (3, 5)
 OP          '='           (3, 9) (3, 10)
 NAME        'False'       (3, 11) (3, 16)
 COMMENT     '# NEWLINE'   (3, 17) (3, 26)
@@ -103,7 +103,7 @@
 
     t1 = [tok[:2] for tok in fulltok]
     newtext = untokenize(t1)
-    readline = iter(newtext.splitlines(1)).next
+    readline = iter(newtext.splitlines(1)).__next__
     t2 = [tok[:2] for tok in generate_tokens(readline)]
     if t1 != t2:
         raise TestFailed("untokenize() roundtrip failed for %r" % f)
@@ -224,7 +224,7 @@
     This function exists solely to test the tokenization of the RARROW
     operator.
 
-    >>> tokenize(iter(['->']).next)   #doctest: +NORMALIZE_WHITESPACE
+    >>> tokenize(iter(['->']).__next__)   #doctest: +NORMALIZE_WHITESPACE
     1,0-1,2:\tOP\t'->'
     2,0-2,0:\tENDMARKER\t''
     """

Modified: python/branches/p3yk-noslice/Lib/test/test_trace.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_trace.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_trace.py	Wed Jul 11 15:40:56 2007
@@ -226,14 +226,14 @@
         sys.settrace(tracer.trace)
         func()
         sys.settrace(None)
-        self.compare_events(func.func_code.co_firstlineno,
+        self.compare_events(func.__code__.co_firstlineno,
                             tracer.events, func.events)
 
     def run_test2(self, func):
         tracer = Tracer()
         func(tracer.trace)
         sys.settrace(None)
-        self.compare_events(func.func_code.co_firstlineno,
+        self.compare_events(func.__code__.co_firstlineno,
                             tracer.events, func.events)
 
     def test_01_basic(self):
@@ -285,7 +285,7 @@
         handled OK."""
         self.raiseOnEvent = event
         try:
-            for i in xrange(sys.getrecursionlimit() + 1):
+            for i in range(sys.getrecursionlimit() + 1):
                 sys.settrace(self.trace)
                 try:
                     self.f()
@@ -313,7 +313,7 @@
 
         def g(frame, why, extra):
             if (why == 'line' and
-                frame.f_lineno == f.func_code.co_firstlineno + 2):
+                frame.f_lineno == f.__code__.co_firstlineno + 2):
                 raise RuntimeError, "i am crashing"
             return g
 
@@ -344,7 +344,7 @@
         self.done = False
 
     def trace(self, frame, event, arg):
-        if not self.done and frame.f_code == self.function.func_code:
+        if not self.done and frame.f_code == self.function.__code__:
             firstLine = frame.f_code.co_firstlineno
             if frame.f_lineno == firstLine + self.jumpFrom:
                 # Cope with non-integer self.jumpTo (because of

Modified: python/branches/p3yk-noslice/Lib/test/test_traceback.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_traceback.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_traceback.py	Wed Jul 11 15:40:56 2007
@@ -52,58 +52,13 @@
         self.assert_("^" in err[2])
         self.assert_(err[1].find(")") == err[2].find("^"))
 
-    def test_bug737473(self):
-        import sys, os, tempfile, time
-
-        savedpath = sys.path[:]
-        testdir = tempfile.mkdtemp()
-        try:
-            sys.path.insert(0, testdir)
-            testfile = os.path.join(testdir, 'test_bug737473.py')
-            print("""
-def test():
-    raise ValueError""", file=open(testfile, 'w'))
-
-            if 'test_bug737473' in sys.modules:
-                del sys.modules['test_bug737473']
-            import test_bug737473
-
-            try:
-                test_bug737473.test()
-            except ValueError:
-                # this loads source code to linecache
-                traceback.extract_tb(sys.exc_traceback)
-
-            # If this test runs too quickly, test_bug737473.py's mtime
-            # attribute will remain unchanged even if the file is rewritten.
-            # Consequently, the file would not reload.  So, added a sleep()
-            # delay to assure that a new, distinct timestamp is written.
-            # Since WinME with FAT32 has multisecond resolution, more than
-            # three seconds are needed for this test to pass reliably :-(
-            time.sleep(4)
-
-            print("""
-def test():
-    raise NotImplementedError""", file=open(testfile, 'w'))
-            reload(test_bug737473)
-            try:
-                test_bug737473.test()
-            except NotImplementedError:
-                src = traceback.extract_tb(sys.exc_traceback)[-1][-1]
-                self.failUnlessEqual(src, 'raise NotImplementedError')
-        finally:
-            sys.path[:] = savedpath
-            for f in os.listdir(testdir):
-                os.unlink(os.path.join(testdir, f))
-            os.rmdir(testdir)
-
     def test_members(self):
         # Covers Python/structmember.c::listmembers()
         try:
             1/0
         except:
             import sys
-            sys.exc_traceback.__members__
+            sys.exc_info()[2].__members__
 
     def test_base_exception(self):
         # Test that exceptions derived from BaseException are formatted right
@@ -118,9 +73,11 @@
         err = traceback.format_exception_only(X, X())
         self.assertEqual(len(err), 1)
         str_value = '<unprintable %s object>' % X.__name__
-        self.assertEqual(err[0], "%s.%s: %s\n" % (X.__module__,
-                                                  X.__name__,
-                                                  str_value))
+        if X.__module__ in ('__main__', '__builtin__'):
+            str_name = X.__name__
+        else:
+            str_name = '.'.join([X.__module__, X.__name__])
+        self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value))
 
     def test_without_exception(self):
         err = traceback.format_exception_only(None, None)

Deleted: /python/branches/p3yk-noslice/Lib/test/test_transformer.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_transformer.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,35 +0,0 @@
-import unittest
-from test import test_support
-from compiler import transformer, ast
-from compiler import compile
-
-class Tests(unittest.TestCase):
-
-    def testMultipleLHS(self):
-        """ Test multiple targets on the left hand side. """
-
-        snippets = ['a, b = 1, 2',
-                    '(a, b) = 1, 2',
-                    '((a, b), c) = (1, 2), 3']
-
-        for s in snippets:
-            a = transformer.parse(s)
-            assert isinstance(a, ast.Module)
-            child1 = a.getChildNodes()[0]
-            assert isinstance(child1, ast.Stmt)
-            child2 = child1.getChildNodes()[0]
-            assert isinstance(child2, ast.Assign)
-
-            # This actually tests the compiler, but it's a way to assure the ast
-            # is correct
-            c = compile(s, '<string>', 'single')
-            vals = {}
-            exec(c, vals)
-            assert vals['a'] == 1
-            assert vals['b'] == 2
-
-def test_main():
-    test_support.run_unittest(Tests)
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_tuple.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_tuple.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_tuple.py	Wed Jul 11 15:40:56 2007
@@ -5,30 +5,30 @@
     type2test = tuple
 
     def test_constructors(self):
-        super(TupleTest, self).test_len()
+        super().test_len()
         # calling built-in types without argument must return empty
         self.assertEqual(tuple(), ())
 
     def test_truth(self):
-        super(TupleTest, self).test_truth()
+        super().test_truth()
         self.assert_(not ())
         self.assert_((42, ))
 
     def test_len(self):
-        super(TupleTest, self).test_len()
+        super().test_len()
         self.assertEqual(len(()), 0)
         self.assertEqual(len((0,)), 1)
         self.assertEqual(len((0, 1, 2)), 3)
 
     def test_iadd(self):
-        super(TupleTest, self).test_iadd()
+        super().test_iadd()
         u = (0, 1)
         u2 = u
         u += (2, 3)
         self.assert_(u is not u2)
 
     def test_imul(self):
-        super(TupleTest, self).test_imul()
+        super().test_imul()
         u = (0, 1)
         u2 = u
         u *= 3
@@ -39,7 +39,7 @@
         def f():
             for i in range(1000):
                 yield i
-        self.assertEqual(list(tuple(f())), range(1000))
+        self.assertEqual(list(tuple(f())), list(range(1000)))
 
     def test_hash(self):
         # See SF bug 942952:  Weakness in tuple hash
@@ -58,7 +58,7 @@
         #      is sorely suspect.
 
         N=50
-        base = range(N)
+        base = list(range(N))
         xp = [(i, j) for i in base for j in base]
         inps = base + [(i, j) for i in base for j in xp] + \
                      [(i, j) for i in xp for j in base] + xp + list(zip(base))

Modified: python/branches/p3yk-noslice/Lib/test/test_ucn.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ucn.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_ucn.py	Wed Jul 11 15:40:56 2007
@@ -61,7 +61,7 @@
     def test_ascii_letters(self):
         import unicodedata
 
-        for char in "".join(map(chr, xrange(ord("a"), ord("z")))):
+        for char in "".join(map(chr, range(ord("a"), ord("z")))):
             name = "LATIN SMALL LETTER %s" % char.upper()
             code = unicodedata.lookup(name)
             self.assertEqual(unicodedata.name(code), name)
@@ -95,7 +95,7 @@
     def test_bmp_characters(self):
         import unicodedata
         count = 0
-        for code in xrange(0x10000):
+        for code in range(0x10000):
             char = unichr(code)
             name = unicodedata.name(char, None)
             if name is not None:

Modified: python/branches/p3yk-noslice/Lib/test/test_unicode.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unicode.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_unicode.py	Wed Jul 11 15:40:56 2007
@@ -6,7 +6,7 @@
 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
 
 """#"
-import unittest, sys, string, codecs, new
+import unittest, sys, struct, codecs, new
 from test import test_support, string_tests
 
 # Error handling (bad decoder return)
@@ -90,7 +90,7 @@
                 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
                 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
                 "\\xfe\\xff'")
-            testrepr = repr(u''.join(map(unichr, xrange(256))))
+            testrepr = repr(u''.join(map(unichr, range(256))))
             self.assertEqual(testrepr, latin1repr)
             # Test repr works on wide unicode escapes without overflow.
             self.assertEqual(repr(u"\U00010000" * 39 + u"\uffff" * 4096),
@@ -99,10 +99,10 @@
     def test_iterators(self):
         # Make sure unicode objects have an __iter__ method
         it = u"\u1111\u2222\u3333".__iter__()
-        self.assertEqual(it.next(), u"\u1111")
-        self.assertEqual(it.next(), u"\u2222")
-        self.assertEqual(it.next(), u"\u3333")
-        self.assertRaises(StopIteration, it.next)
+        self.assertEqual(next(it), u"\u1111")
+        self.assertEqual(next(it), u"\u2222")
+        self.assertEqual(next(it), u"\u3333")
+        self.assertRaises(StopIteration, next, it)
 
     def test_count(self):
         string_tests.CommonTest.test_count(self)
@@ -631,7 +631,7 @@
         self.assertEqual(u'hello'.encode('latin-1'), 'hello')
 
         # Roundtrip safety for BMP (just the first 1024 chars)
-        for c in xrange(1024):
+        for c in range(1024):
             u = unichr(c)
             for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
                              'utf-16-be', 'raw_unicode_escape',
@@ -639,13 +639,13 @@
                 self.assertEqual(unicode(u.encode(encoding),encoding), u)
 
         # Roundtrip safety for BMP (just the first 256 chars)
-        for c in xrange(256):
+        for c in range(256):
             u = unichr(c)
             for encoding in ('latin-1',):
                 self.assertEqual(unicode(u.encode(encoding),encoding), u)
 
         # Roundtrip safety for BMP (just the first 128 chars)
-        for c in xrange(128):
+        for c in range(128):
             u = unichr(c)
             for encoding in ('ascii',):
                 self.assertEqual(unicode(u.encode(encoding),encoding), u)
@@ -661,13 +661,14 @@
         # This excludes surrogates: in the full range, there would be
         # a surrogate pair (\udbff\udc00), which gets converted back
         # to a non-BMP character (\U0010fc00)
-        u = u''.join(map(unichr, range(0,0xd800)+range(0xe000,0x10000)))
+        u = u''.join(map(unichr, list(range(0,0xd800)) +
+                                 list(range(0xe000,0x10000))))
         for encoding in ('utf-8',):
             self.assertEqual(unicode(u.encode(encoding),encoding), u)
 
     def test_codecs_charmap(self):
         # 0-127
-        s = ''.join(map(chr, xrange(128)))
+        s = ''.join(map(chr, range(128)))
         for encoding in (
             'cp037', 'cp1026',
             'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
@@ -695,7 +696,7 @@
             self.assertEqual(unicode(s, encoding).encode(encoding), s)
 
         # 128-255
-        s = ''.join(map(chr, xrange(128, 256)))
+        s = ''.join(map(chr, range(128, 256)))
         for encoding in (
             'cp037', 'cp1026',
             'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
@@ -824,12 +825,17 @@
         self.assertEqual(repr(s1()), '\\n')
         self.assertEqual(repr(s2()), '\\n')
 
-
-
+    def test_expandtabs_overflows_gracefully(self):
+        # This test only affects 32-bit platforms because expandtabs can only take
+        # an int as the max value, not a 64-bit C long.  If expandtabs is changed
+        # to take a 64-bit long, this test should apply to all platforms.
+        if sys.maxint > (1 << 32) or struct.calcsize('P') != 4:
+            return
+        self.assertRaises(OverflowError, u't\tt\t'.expandtabs, sys.maxint)
 
 
 def test_main():
-    test_support.run_unittest(UnicodeTest)
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_unicode_file.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unicode_file.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_unicode_file.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,7 @@
 import unicodedata
 
 import unittest
-from test.test_support import run_suite, TestSkipped, TESTFN_UNICODE
+from test.test_support import run_unittest, TestSkipped, TESTFN_UNICODE
 from test.test_support import TESTFN_ENCODING, TESTFN_UNICODE_UNENCODEABLE
 try:
     TESTFN_ENCODED = TESTFN_UNICODE.encode(TESTFN_ENCODING)
@@ -48,7 +48,7 @@
         self.failUnless(os.path.exists(os.path.abspath(filename)))
         self.failUnless(os.path.isfile(os.path.abspath(filename)))
         self.failUnless(os.access(os.path.abspath(filename), os.R_OK))
-        os.chmod(filename, 0777)
+        os.chmod(filename, 0o777)
         os.utime(filename, None)
         os.utime(filename, (time.time(), time.time()))
         # Copy/rename etc tests using the same filename
@@ -205,9 +205,7 @@
                                False)
 
 def test_main():
-    suite = unittest.TestSuite()
-    suite.addTest(unittest.makeSuite(TestUnicodeFiles))
-    run_suite(suite)
+    run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_unicodedata.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unicodedata.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_unicodedata.py	Wed Jul 11 15:40:56 2007
@@ -193,7 +193,7 @@
         # i.e. if a character has a decimal value,
         # its numeric value should be the same.
         count = 0
-        for i in xrange(0x10000):
+        for i in range(0x10000):
             c = unichr(i)
             dec = self.db.decimal(c, -1)
             if dec != -1:
@@ -206,7 +206,7 @@
         # i.e. if a character has a digit value,
         # its numeric value should be the same.
         count = 0
-        for i in xrange(0x10000):
+        for i in range(0x10000):
             c = unichr(i)
             dec = self.db.digit(c, -1)
             if dec != -1:

Modified: python/branches/p3yk-noslice/Lib/test/test_unittest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unittest.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_unittest.py	Wed Jul 11 15:40:56 2007
@@ -1,31 +1,2304 @@
 """Test script for unittest.
 
-This just includes tests for new features.  We really need a
-full set of tests.
+By Collin Winter <collinw at gmail.com>
+
+Still need testing:
+    TestCase.{assert,fail}* methods (some are tested implicitly)
 """
 
+from test import test_support
 import unittest
+from unittest import TestCase
+
+### Support code
+################################################################
+
+class LoggingResult(unittest.TestResult):
+    def __init__(self, log):
+        self._events = log
+        super().__init__()
+
+    def startTest(self, test):
+        self._events.append('startTest')
+        super().startTest(test)
+
+    def stopTest(self, test):
+        self._events.append('stopTest')
+        super().stopTest(test)
+
+    def addFailure(self, *args):
+        self._events.append('addFailure')
+        super().addFailure(*args)
+
+    def addError(self, *args):
+        self._events.append('addError')
+        super().addError(*args)
+
+class TestEquality(object):
+    # Check for a valid __eq__ implementation
+    def test_eq(self):
+        for obj_1, obj_2 in self.eq_pairs:
+            self.assertEqual(obj_1, obj_2)
+            self.assertEqual(obj_2, obj_1)
+
+    # Check for a valid __ne__ implementation
+    def test_ne(self):
+        for obj_1, obj_2 in self.ne_pairs:
+            self.failIfEqual(obj_1, obj_2)
+            self.failIfEqual(obj_2, obj_1)
+
+class TestHashing(object):
+    # Check for a valid __hash__ implementation
+    def test_hash(self):
+        for obj_1, obj_2 in self.eq_pairs:
+            try:
+                assert hash(obj_1) == hash(obj_2)
+            except KeyboardInterrupt:
+                raise
+            except AssertionError:
+                self.fail("%s and %s do not hash equal" % (obj_1, obj_2))
+            except Exception as e:
+                self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
+
+        for obj_1, obj_2 in self.ne_pairs:
+            try:
+                assert hash(obj_1) != hash(obj_2)
+            except KeyboardInterrupt:
+                raise
+            except AssertionError:
+                self.fail("%s and %s hash equal, but shouldn't" % (obj_1, obj_2))
+            except Exception as e:
+                self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
+
+
+################################################################
+### /Support code
+
+class Test_TestLoader(TestCase):
+
+    ### Tests for TestLoader.loadTestsFromTestCase
+    ################################################################
+
+    # "Return a suite of all tests cases contained in the TestCase-derived
+    # class testCaseClass"
+    def test_loadTestsFromTestCase(self):
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+
+        tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
+
+        loader = unittest.TestLoader()
+        self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
+
+    # "Return a suite of all tests cases contained in the TestCase-derived
+    # class testCaseClass"
+    #
+    # Make sure it does the right thing even if no tests were found
+    def test_loadTestsFromTestCase__no_matches(self):
+        class Foo(unittest.TestCase):
+            def foo_bar(self): pass
+
+        empty_suite = unittest.TestSuite()
+
+        loader = unittest.TestLoader()
+        self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
+
+    # "Return a suite of all tests cases contained in the TestCase-derived
+    # class testCaseClass"
+    #
+    # What happens if loadTestsFromTestCase() is given an object
+    # that isn't a subclass of TestCase? Specifically, what happens
+    # if testCaseClass is a subclass of TestSuite?
+    #
+    # This is checked for specifically in the code, so we better add a
+    # test for it.
+    def test_loadTestsFromTestCase__TestSuite_subclass(self):
+        class NotATestCase(unittest.TestSuite):
+            pass
+
+        loader = unittest.TestLoader()
+        try:
+            loader.loadTestsFromTestCase(NotATestCase)
+        except TypeError:
+            pass
+        else:
+            self.fail('Should raise TypeError')
+
+    # "Return a suite of all tests cases contained in the TestCase-derived
+    # class testCaseClass"
+    #
+    # Make sure loadTestsFromTestCase() picks up the default test method
+    # name (as specified by TestCase), even though the method name does
+    # not match the default TestLoader.testMethodPrefix string
+    def test_loadTestsFromTestCase__default_method_name(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                pass
+
+        loader = unittest.TestLoader()
+        # This has to be false for the test to succeed
+        self.failIf('runTest'.startswith(loader.testMethodPrefix))
+
+        suite = loader.loadTestsFromTestCase(Foo)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [Foo('runTest')])
+
+    ################################################################
+    ### /Tests for TestLoader.loadTestsFromTestCase
+
+    ### Tests for TestLoader.loadTestsFromModule
+    ################################################################
+
+    # "This method searches `module` for classes derived from TestCase"
+    def test_loadTestsFromModule__TestCase_subclass(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromModule(m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        expected = [loader.suiteClass([MyTestCase('test')])]
+        self.assertEqual(list(suite), expected)
+
+    # "This method searches `module` for classes derived from TestCase"
+    #
+    # What happens if no tests are found (no TestCase instances)?
+    def test_loadTestsFromModule__no_TestCase_instances(self):
+        import new
+        m = new.module('m')
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromModule(m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [])
+
+    # "This method searches `module` for classes derived from TestCase"
+    #
+    # What happens if no tests are found (TestCases instances, but no tests)?
+    def test_loadTestsFromModule__no_TestCase_tests(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromModule(m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        self.assertEqual(list(suite), [loader.suiteClass()])
+
+    # "This method searches `module` for classes derived from TestCase"s
+    #
+    # What happens if loadTestsFromModule() is given something other
+    # than a module?
+    #
+    # XXX Currently, it succeeds anyway. This flexibility
+    # should either be documented or loadTestsFromModule() should
+    # raise a TypeError
+    #
+    # XXX Certain people are using this behaviour. We'll add a test for it
+    def test_loadTestsFromModule__not_a_module(self):
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+
+        class NotAModule(object):
+            test_2 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromModule(NotAModule)
+
+        reference = [unittest.TestSuite([MyTestCase('test')])]
+        self.assertEqual(list(suite), reference)
+
+    ################################################################
+    ### /Tests for TestLoader.loadTestsFromModule()
+
+    ### Tests for TestLoader.loadTestsFromName()
+    ################################################################
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # Is ValueError raised in response to an empty name?
+    def test_loadTestsFromName__empty_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromName('')
+        except ValueError as e:
+            self.assertEqual(str(e), "Empty module name")
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # What happens when the name contains invalid characters?
+    def test_loadTestsFromName__malformed_name(self):
+        loader = unittest.TestLoader()
+
+        # XXX Should this raise ValueError or ImportError?
+        try:
+            loader.loadTestsFromName('abc () //')
+        except ValueError:
+            pass
+        except ImportError:
+            pass
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to a
+    # module"
+    #
+    # What happens when a module by that name can't be found?
+    def test_loadTestsFromName__unknown_module_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromName('sdasfasfasdf')
+        except ImportError as e:
+            self.assertEqual(str(e), "No module named sdasfasfasdf")
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # What happens when the module is found, but the attribute can't?
+    def test_loadTestsFromName__unknown_attr_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromName('unittest.sdasfasfasdf')
+        except AttributeError as e:
+            self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # What happens when we provide the module, but the attribute can't be
+    # found?
+    def test_loadTestsFromName__relative_unknown_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromName('sdasfasfasdf', unittest)
+        except AttributeError as e:
+            self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # Does loadTestsFromName raise ValueError when passed an empty
+    # name relative to a provided module?
+    #
+    # XXX Should probably raise a ValueError instead of an AttributeError
+    def test_loadTestsFromName__relative_empty_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromName('', unittest)
+        except AttributeError as e:
+            pass
+        else:
+            self.fail("Failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # What happens when an impossible name is given, relative to the provided
+    # `module`?
+    def test_loadTestsFromName__relative_malformed_name(self):
+        loader = unittest.TestLoader()
+
+        # XXX Should this raise AttributeError or ValueError?
+        try:
+            loader.loadTestsFromName('abc () //', unittest)
+        except ValueError:
+            pass
+        except AttributeError:
+            pass
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
+
+    # "The method optionally resolves name relative to the given module"
+    #
+    # Does loadTestsFromName raise TypeError when the `module` argument
+    # isn't a module object?
+    #
+    # XXX Accepts the not-a-module object, ignorning the object's type
+    # This should raise an exception or the method name should be changed
+    #
+    # XXX Some people are relying on this, so keep it for now
+    def test_loadTestsFromName__relative_not_a_module(self):
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+
+        class NotAModule(object):
+            test_2 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromName('test_2', NotAModule)
+
+        reference = [MyTestCase('test')]
+        self.assertEqual(list(suite), reference)
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # Does it raise an exception if the name resolves to an invalid
+    # object?
+    def test_loadTestsFromName__relative_bad_object(self):
+        import new
+        m = new.module('m')
+        m.testcase_1 = object()
+
+        loader = unittest.TestLoader()
+        try:
+            loader.loadTestsFromName('testcase_1', m)
+        except TypeError:
+            pass
+        else:
+            self.fail("Should have raised TypeError")
+
+    # "The specifier name is a ``dotted name'' that may
+    # resolve either to ... a test case class"
+    def test_loadTestsFromName__relative_TestCase_subclass(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromName('testcase_1', m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [MyTestCase('test')])
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    def test_loadTestsFromName__relative_TestSuite(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testsuite = unittest.TestSuite([MyTestCase('test')])
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromName('testsuite', m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        self.assertEqual(list(suite), [MyTestCase('test')])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a test method within a test case class"
+    def test_loadTestsFromName__relative_testmethod(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromName('testcase_1.test', m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        self.assertEqual(list(suite), [MyTestCase('test')])
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # Does loadTestsFromName() raise the proper exception when trying to
+    # resolve "a test method within a test case class" that doesn't exist
+    # for the given name (relative to a provided module)?
+    def test_loadTestsFromName__relative_invalid_testmethod(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        try:
+            loader.loadTestsFromName('testcase_1.testfoo', m)
+        except AttributeError as e:
+            self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
+        else:
+            self.fail("Failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a ... TestSuite instance"
+    def test_loadTestsFromName__callable__TestSuite(self):
+        import new
+        m = new.module('m')
+        testcase_1 = unittest.FunctionTestCase(lambda: None)
+        testcase_2 = unittest.FunctionTestCase(lambda: None)
+        def return_TestSuite():
+            return unittest.TestSuite([testcase_1, testcase_2])
+        m.return_TestSuite = return_TestSuite
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromName('return_TestSuite', m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [testcase_1, testcase_2])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a TestCase ... instance"
+    def test_loadTestsFromName__callable__TestCase_instance(self):
+        import new
+        m = new.module('m')
+        testcase_1 = unittest.FunctionTestCase(lambda: None)
+        def return_TestCase():
+            return testcase_1
+        m.return_TestCase = return_TestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromName('return_TestCase', m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [testcase_1])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a TestCase or TestSuite instance"
+    #
+    # What happens if the callable returns something else?
+    def test_loadTestsFromName__callable__wrong_type(self):
+        import new
+        m = new.module('m')
+        def return_wrong():
+            return 6
+        m.return_wrong = return_wrong
+
+        loader = unittest.TestLoader()
+        try:
+            suite = loader.loadTestsFromName('return_wrong', m)
+        except TypeError:
+            pass
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
+
+    # "The specifier can refer to modules and packages which have not been
+    # imported; they will be imported as a side-effect"
+    def test_loadTestsFromName__module_not_loaded(self):
+        # We're going to try to load this module as a side-effect, so it
+        # better not be loaded before we try.
+        #
+        # Why pick audioop? Google shows it isn't used very often, so there's
+        # a good chance that it won't be imported when this test is run
+        module_name = 'audioop'
+
+        import sys
+        if module_name in sys.modules:
+            del sys.modules[module_name]
+
+        loader = unittest.TestLoader()
+        try:
+            suite = loader.loadTestsFromName(module_name)
+
+            self.failUnless(isinstance(suite, loader.suiteClass))
+            self.assertEqual(list(suite), [])
+
+            # audioop should now be loaded, thanks to loadTestsFromName()
+            self.failUnless(module_name in sys.modules)
+        finally:
+            if module_name in sys.modules:
+                del sys.modules[module_name]
+
+    ################################################################
+    ### Tests for TestLoader.loadTestsFromName()
+
+    ### Tests for TestLoader.loadTestsFromNames()
+    ################################################################
+
+    # "Similar to loadTestsFromName(), but takes a sequence of names rather
+    # than a single name."
+    #
+    # What happens if that sequence of names is empty?
+    def test_loadTestsFromNames__empty_name_list(self):
+        loader = unittest.TestLoader()
+
+        suite = loader.loadTestsFromNames([])
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [])
+
+    # "Similar to loadTestsFromName(), but takes a sequence of names rather
+    # than a single name."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # What happens if that sequence of names is empty?
+    #
+    # XXX Should this raise a ValueError or just return an empty TestSuite?
+    def test_loadTestsFromNames__relative_empty_name_list(self):
+        loader = unittest.TestLoader()
+
+        suite = loader.loadTestsFromNames([], unittest)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+        self.assertEqual(list(suite), [])
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # Is ValueError raised in response to an empty name?
+    def test_loadTestsFromNames__empty_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromNames([''])
+        except ValueError as e:
+            self.assertEqual(str(e), "Empty module name")
+        else:
+            self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # What happens when presented with an impossible module name?
+    def test_loadTestsFromNames__malformed_name(self):
+        loader = unittest.TestLoader()
+
+        # XXX Should this raise ValueError or ImportError?
+        try:
+            loader.loadTestsFromNames(['abc () //'])
+        except ValueError:
+            pass
+        except ImportError:
+            pass
+        else:
+            self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # What happens when no module can be found for the given name?
+    def test_loadTestsFromNames__unknown_module_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromNames(['sdasfasfasdf'])
+        except ImportError as e:
+            self.assertEqual(str(e), "No module named sdasfasfasdf")
+        else:
+            self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # What happens when the module can be found, but not the attribute?
+    def test_loadTestsFromNames__unknown_attr_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
+        except AttributeError as e:
+            self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
+        else:
+            self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # What happens when given an unknown attribute on a specified `module`
+    # argument?
+    def test_loadTestsFromNames__unknown_name_relative_1(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
+        except AttributeError as e:
+            self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # Do unknown attributes (relative to a provided module) still raise an
+    # exception even in the presence of valid attribute names?
+    def test_loadTestsFromNames__unknown_name_relative_2(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
+        except AttributeError as e:
+            self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
+        else:
+            self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # What happens when faced with the empty string?
+    #
+    # XXX This currently raises AttributeError, though ValueError is probably
+    # more appropriate
+    def test_loadTestsFromNames__relative_empty_name(self):
+        loader = unittest.TestLoader()
+
+        try:
+            loader.loadTestsFromNames([''], unittest)
+        except AttributeError:
+            pass
+        else:
+            self.fail("Failed to raise ValueError")
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    # ...
+    # "The method optionally resolves name relative to the given module"
+    #
+    # What happens when presented with an impossible attribute name?
+    def test_loadTestsFromNames__relative_malformed_name(self):
+        loader = unittest.TestLoader()
+
+        # XXX Should this raise AttributeError or ValueError?
+        try:
+            loader.loadTestsFromNames(['abc () //'], unittest)
+        except AttributeError:
+            pass
+        except ValueError:
+            pass
+        else:
+            self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
+
+    # "The method optionally resolves name relative to the given module"
+    #
+    # Does loadTestsFromNames() make sure the provided `module` is in fact
+    # a module?
+    #
+    # XXX This validation is currently not done. This flexibility should
+    # either be documented or a TypeError should be raised.
+    def test_loadTestsFromNames__relative_not_a_module(self):
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+
+        class NotAModule(object):
+            test_2 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['test_2'], NotAModule)
+
+        reference = [unittest.TestSuite([MyTestCase('test')])]
+        self.assertEqual(list(suite), reference)
+
+    # "The specifier name is a ``dotted name'' that may resolve either to
+    # a module, a test case class, a TestSuite instance, a test method
+    # within a test case class, or a callable object which returns a
+    # TestCase or TestSuite instance."
+    #
+    # Does it raise an exception if the name resolves to an invalid
+    # object?
+    def test_loadTestsFromNames__relative_bad_object(self):
+        import new
+        m = new.module('m')
+        m.testcase_1 = object()
+
+        loader = unittest.TestLoader()
+        try:
+            loader.loadTestsFromNames(['testcase_1'], m)
+        except TypeError:
+            pass
+        else:
+            self.fail("Should have raised TypeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a test case class"
+    def test_loadTestsFromNames__relative_TestCase_subclass(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['testcase_1'], m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        expected = loader.suiteClass([MyTestCase('test')])
+        self.assertEqual(list(suite), [expected])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a TestSuite instance"
+    def test_loadTestsFromNames__relative_TestSuite(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testsuite = unittest.TestSuite([MyTestCase('test')])
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['testsuite'], m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        self.assertEqual(list(suite), [m.testsuite])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to ... a
+    # test method within a test case class"
+    def test_loadTestsFromNames__relative_testmethod(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['testcase_1.test'], m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        ref_suite = unittest.TestSuite([MyTestCase('test')])
+        self.assertEqual(list(suite), [ref_suite])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to ... a
+    # test method within a test case class"
+    #
+    # Does the method gracefully handle names that initially look like they
+    # resolve to "a test method within a test case class" but don't?
+    def test_loadTestsFromNames__relative_invalid_testmethod(self):
+        import new
+        m = new.module('m')
+        class MyTestCase(unittest.TestCase):
+            def test(self):
+                pass
+        m.testcase_1 = MyTestCase
+
+        loader = unittest.TestLoader()
+        try:
+            loader.loadTestsFromNames(['testcase_1.testfoo'], m)
+        except AttributeError as e:
+            self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
+        else:
+            self.fail("Failed to raise AttributeError")
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a ... TestSuite instance"
+    def test_loadTestsFromNames__callable__TestSuite(self):
+        import new
+        m = new.module('m')
+        testcase_1 = unittest.FunctionTestCase(lambda: None)
+        testcase_2 = unittest.FunctionTestCase(lambda: None)
+        def return_TestSuite():
+            return unittest.TestSuite([testcase_1, testcase_2])
+        m.return_TestSuite = return_TestSuite
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['return_TestSuite'], m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        expected = unittest.TestSuite([testcase_1, testcase_2])
+        self.assertEqual(list(suite), [expected])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a TestCase ... instance"
+    def test_loadTestsFromNames__callable__TestCase_instance(self):
+        import new
+        m = new.module('m')
+        testcase_1 = unittest.FunctionTestCase(lambda: None)
+        def return_TestCase():
+            return testcase_1
+        m.return_TestCase = return_TestCase
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['return_TestCase'], m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        ref_suite = unittest.TestSuite([testcase_1])
+        self.assertEqual(list(suite), [ref_suite])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a TestCase or TestSuite instance"
+    #
+    # Are staticmethods handled correctly?
+    def test_loadTestsFromNames__callable__call_staticmethod(self):
+        import new
+        m = new.module('m')
+        class Test1(unittest.TestCase):
+            def test(self):
+                pass
+
+        testcase_1 = Test1('test')
+        class Foo(unittest.TestCase):
+            @staticmethod
+            def foo():
+                return testcase_1
+        m.Foo = Foo
+
+        loader = unittest.TestLoader()
+        suite = loader.loadTestsFromNames(['Foo.foo'], m)
+        self.failUnless(isinstance(suite, loader.suiteClass))
+
+        ref_suite = unittest.TestSuite([testcase_1])
+        self.assertEqual(list(suite), [ref_suite])
+
+    # "The specifier name is a ``dotted name'' that may resolve ... to
+    # ... a callable object which returns a TestCase or TestSuite instance"
+    #
+    # What happens when the callable returns something else?
+    def test_loadTestsFromNames__callable__wrong_type(self):
+        import new
+        m = new.module('m')
+        def return_wrong():
+            return 6
+        m.return_wrong = return_wrong
+
+        loader = unittest.TestLoader()
+        try:
+            suite = loader.loadTestsFromNames(['return_wrong'], m)
+        except TypeError:
+            pass
+        else:
+            self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
+
+    # "The specifier can refer to modules and packages which have not been
+    # imported; they will be imported as a side-effect"
+    def test_loadTestsFromNames__module_not_loaded(self):
+        # We're going to try to load this module as a side-effect, so it
+        # better not be loaded before we try.
+        #
+        # Why pick audioop? Google shows it isn't used very often, so there's
+        # a good chance that it won't be imported when this test is run
+        module_name = 'audioop'
+
+        import sys
+        if module_name in sys.modules:
+            del sys.modules[module_name]
+
+        loader = unittest.TestLoader()
+        try:
+            suite = loader.loadTestsFromNames([module_name])
+
+            self.failUnless(isinstance(suite, loader.suiteClass))
+            self.assertEqual(list(suite), [unittest.TestSuite()])
+
+            # audioop should now be loaded, thanks to loadTestsFromName()
+            self.failUnless(module_name in sys.modules)
+        finally:
+            if module_name in sys.modules:
+                del sys.modules[module_name]
+
+    ################################################################
+    ### /Tests for TestLoader.loadTestsFromNames()
+
+    ### Tests for TestLoader.getTestCaseNames()
+    ################################################################
+
+    # "Return a sorted sequence of method names found within testCaseClass"
+    #
+    # Test.foobar is defined to make sure getTestCaseNames() respects
+    # loader.testMethodPrefix
+    def test_getTestCaseNames(self):
+        class Test(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foobar(self): pass
+
+        loader = unittest.TestLoader()
+
+        self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
+
+    # "Return a sorted sequence of method names found within testCaseClass"
+    #
+    # Does getTestCaseNames() behave appropriately if no tests are found?
+    def test_getTestCaseNames__no_tests(self):
+        class Test(unittest.TestCase):
+            def foobar(self): pass
+
+        loader = unittest.TestLoader()
+
+        self.assertEqual(loader.getTestCaseNames(Test), [])
+
+    # "Return a sorted sequence of method names found within testCaseClass"
+    #
+    # Are not-TestCases handled gracefully?
+    #
+    # XXX This should raise a TypeError, not return a list
+    #
+    # XXX It's too late in the 2.5 release cycle to fix this, but it should
+    # probably be revisited for 2.6
+    def test_getTestCaseNames__not_a_TestCase(self):
+        class BadCase(int):
+            def test_foo(self):
+                pass
+
+        loader = unittest.TestLoader()
+        names = loader.getTestCaseNames(BadCase)
+
+        self.assertEqual(names, ['test_foo'])
+
+    # "Return a sorted sequence of method names found within testCaseClass"
+    #
+    # Make sure inherited names are handled.
+    #
+    # TestP.foobar is defined to make sure getTestCaseNames() respects
+    # loader.testMethodPrefix
+    def test_getTestCaseNames__inheritance(self):
+        class TestP(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foobar(self): pass
+
+        class TestC(TestP):
+            def test_1(self): pass
+            def test_3(self): pass
+
+        loader = unittest.TestLoader()
+
+        names = ['test_1', 'test_2', 'test_3']
+        self.assertEqual(loader.getTestCaseNames(TestC), names)
+
+    ################################################################
+    ### /Tests for TestLoader.getTestCaseNames()
+
+    ### Tests for TestLoader.testMethodPrefix
+    ################################################################
+
+    # "String giving the prefix of method names which will be interpreted as
+    # test methods"
+    #
+    # Implicit in the documentation is that testMethodPrefix is respected by
+    # all loadTestsFrom* methods.
+    def test_testMethodPrefix__loadTestsFromTestCase(self):
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+
+        tests_1 = unittest.TestSuite([Foo('foo_bar')])
+        tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
+
+        loader = unittest.TestLoader()
+        loader.testMethodPrefix = 'foo'
+        self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
+
+        loader.testMethodPrefix = 'test'
+        self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
+
+    # "String giving the prefix of method names which will be interpreted as
+    # test methods"
+    #
+    # Implicit in the documentation is that testMethodPrefix is respected by
+    # all loadTestsFrom* methods.
+    def test_testMethodPrefix__loadTestsFromModule(self):
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+        m.Foo = Foo
+
+        tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
+        tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
+
+        loader = unittest.TestLoader()
+        loader.testMethodPrefix = 'foo'
+        self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
+
+        loader.testMethodPrefix = 'test'
+        self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
+
+    # "String giving the prefix of method names which will be interpreted as
+    # test methods"
+    #
+    # Implicit in the documentation is that testMethodPrefix is respected by
+    # all loadTestsFrom* methods.
+    def test_testMethodPrefix__loadTestsFromName(self):
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+        m.Foo = Foo
+
+        tests_1 = unittest.TestSuite([Foo('foo_bar')])
+        tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
+
+        loader = unittest.TestLoader()
+        loader.testMethodPrefix = 'foo'
+        self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
+
+        loader.testMethodPrefix = 'test'
+        self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
+
+    # "String giving the prefix of method names which will be interpreted as
+    # test methods"
+    #
+    # Implicit in the documentation is that testMethodPrefix is respected by
+    # all loadTestsFrom* methods.
+    def test_testMethodPrefix__loadTestsFromNames(self):
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+        m.Foo = Foo
+
+        tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
+        tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
+        tests_2 = unittest.TestSuite([tests_2])
+
+        loader = unittest.TestLoader()
+        loader.testMethodPrefix = 'foo'
+        self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
+
+        loader.testMethodPrefix = 'test'
+        self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
+
+    # "The default value is 'test'"
+    def test_testMethodPrefix__default_value(self):
+        loader = unittest.TestLoader()
+        self.failUnless(loader.testMethodPrefix == 'test')
+
+    ################################################################
+    ### /Tests for TestLoader.testMethodPrefix
+
+    ### Tests for TestLoader.sortTestMethodsUsing
+    ################################################################
+
+    # "Function to be used to compare method names when sorting them in
+    # getTestCaseNames() and all the loadTestsFromX() methods"
+    def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
+        def reversed_cmp(x, y):
+            return -cmp(x, y)
+
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+
+        loader = unittest.TestLoader()
+        loader.sortTestMethodsUsing = reversed_cmp
+
+        tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
+        self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
+
+    # "Function to be used to compare method names when sorting them in
+    # getTestCaseNames() and all the loadTestsFromX() methods"
+    def test_sortTestMethodsUsing__loadTestsFromModule(self):
+        def reversed_cmp(x, y):
+            return -cmp(x, y)
+
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+        m.Foo = Foo
+
+        loader = unittest.TestLoader()
+        loader.sortTestMethodsUsing = reversed_cmp
+
+        tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
+        self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
+
+    # "Function to be used to compare method names when sorting them in
+    # getTestCaseNames() and all the loadTestsFromX() methods"
+    def test_sortTestMethodsUsing__loadTestsFromName(self):
+        def reversed_cmp(x, y):
+            return -cmp(x, y)
+
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+        m.Foo = Foo
+
+        loader = unittest.TestLoader()
+        loader.sortTestMethodsUsing = reversed_cmp
+
+        tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
+        self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
+
+    # "Function to be used to compare method names when sorting them in
+    # getTestCaseNames() and all the loadTestsFromX() methods"
+    def test_sortTestMethodsUsing__loadTestsFromNames(self):
+        def reversed_cmp(x, y):
+            return -cmp(x, y)
+
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+        m.Foo = Foo
+
+        loader = unittest.TestLoader()
+        loader.sortTestMethodsUsing = reversed_cmp
+
+        tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
+        self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
+
+    # "Function to be used to compare method names when sorting them in
+    # getTestCaseNames()"
+    #
+    # Does it actually affect getTestCaseNames()?
+    def test_sortTestMethodsUsing__getTestCaseNames(self):
+        def reversed_cmp(x, y):
+            return -cmp(x, y)
+
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+
+        loader = unittest.TestLoader()
+        loader.sortTestMethodsUsing = reversed_cmp
+
+        test_names = ['test_2', 'test_1']
+        self.assertEqual(loader.getTestCaseNames(Foo), test_names)
+
+    # "The default value is the built-in cmp() function"
+    def test_sortTestMethodsUsing__default_value(self):
+        loader = unittest.TestLoader()
+        self.failUnless(loader.sortTestMethodsUsing is cmp)
+
+    # "it can be set to None to disable the sort."
+    #
+    # XXX How is this different from reassigning cmp? Are the tests returned
+    # in a random order or something? This behaviour should die
+    def test_sortTestMethodsUsing__None(self):
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+
+        loader = unittest.TestLoader()
+        loader.sortTestMethodsUsing = None
+
+        test_names = ['test_2', 'test_1']
+        self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
+
+    ################################################################
+    ### /Tests for TestLoader.sortTestMethodsUsing
+
+    ### Tests for TestLoader.suiteClass
+    ################################################################
+
+    # "Callable object that constructs a test suite from a list of tests."
+    def test_suiteClass__loadTestsFromTestCase(self):
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+
+        tests = [Foo('test_1'), Foo('test_2')]
+
+        loader = unittest.TestLoader()
+        loader.suiteClass = list
+        self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
+
+    # It is implicit in the documentation for TestLoader.suiteClass that
+    # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
+    def test_suiteClass__loadTestsFromModule(self):
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+        m.Foo = Foo
+
+        tests = [[Foo('test_1'), Foo('test_2')]]
+
+        loader = unittest.TestLoader()
+        loader.suiteClass = list
+        self.assertEqual(loader.loadTestsFromModule(m), tests)
+
+    # It is implicit in the documentation for TestLoader.suiteClass that
+    # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
+    def test_suiteClass__loadTestsFromName(self):
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+        m.Foo = Foo
+
+        tests = [Foo('test_1'), Foo('test_2')]
+
+        loader = unittest.TestLoader()
+        loader.suiteClass = list
+        self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
+
+    # It is implicit in the documentation for TestLoader.suiteClass that
+    # all TestLoader.loadTestsFrom* methods respect it. Let's make sure
+    def test_suiteClass__loadTestsFromNames(self):
+        import new
+        m = new.module('m')
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+            def foo_bar(self): pass
+        m.Foo = Foo
+
+        tests = [[Foo('test_1'), Foo('test_2')]]
+
+        loader = unittest.TestLoader()
+        loader.suiteClass = list
+        self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
+
+    # "The default value is the TestSuite class"
+    def test_suiteClass__default_value(self):
+        loader = unittest.TestLoader()
+        self.failUnless(loader.suiteClass is unittest.TestSuite)
+
+    ################################################################
+    ### /Tests for TestLoader.suiteClass
+
+### Support code for Test_TestSuite
+################################################################
+
+class Foo(unittest.TestCase):
+    def test_1(self): pass
+    def test_2(self): pass
+    def test_3(self): pass
+    def runTest(self): pass
+
+def _mk_TestSuite(*names):
+    return unittest.TestSuite(Foo(n) for n in names)
+
+################################################################
+### /Support code for Test_TestSuite
+
+class Test_TestSuite(TestCase, TestEquality):
+
+    ### Set up attributes needed by inherited tests
+    ################################################################
+
+    # Used by TestEquality.test_eq
+    eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
+               ,(unittest.TestSuite(), unittest.TestSuite([]))
+               ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
+
+    # Used by TestEquality.test_ne
+    ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
+               ,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
+               ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
+               ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
+
+    ################################################################
+    ### /Set up attributes needed by inherited tests
+
+    ### Tests for TestSuite.__init__
+    ################################################################
+
+    # "class TestSuite([tests])"
+    #
+    # The tests iterable should be optional
+    def test_init__tests_optional(self):
+        suite = unittest.TestSuite()
+
+        self.assertEqual(suite.countTestCases(), 0)
+
+    # "class TestSuite([tests])"
+    # ...
+    # "If tests is given, it must be an iterable of individual test cases
+    # or other test suites that will be used to build the suite initially"
+    #
+    # TestSuite should deal with empty tests iterables by allowing the
+    # creation of an empty suite
+    def test_init__empty_tests(self):
+        suite = unittest.TestSuite([])
+
+        self.assertEqual(suite.countTestCases(), 0)
+
+    # "class TestSuite([tests])"
+    # ...
+    # "If tests is given, it must be an iterable of individual test cases
+    # or other test suites that will be used to build the suite initially"
+    #
+    # TestSuite should allow any iterable to provide tests
+    def test_init__tests_from_any_iterable(self):
+        def tests():
+            yield unittest.FunctionTestCase(lambda: None)
+            yield unittest.FunctionTestCase(lambda: None)
+
+        suite_1 = unittest.TestSuite(tests())
+        self.assertEqual(suite_1.countTestCases(), 2)
+
+        suite_2 = unittest.TestSuite(suite_1)
+        self.assertEqual(suite_2.countTestCases(), 2)
+
+        suite_3 = unittest.TestSuite(set(suite_1))
+        self.assertEqual(suite_3.countTestCases(), 2)
+
+    # "class TestSuite([tests])"
+    # ...
+    # "If tests is given, it must be an iterable of individual test cases
+    # or other test suites that will be used to build the suite initially"
+    #
+    # Does TestSuite() also allow other TestSuite() instances to be present
+    # in the tests iterable?
+    def test_init__TestSuite_instances_in_tests(self):
+        def tests():
+            ftc = unittest.FunctionTestCase(lambda: None)
+            yield unittest.TestSuite([ftc])
+            yield unittest.FunctionTestCase(lambda: None)
+
+        suite = unittest.TestSuite(tests())
+        self.assertEqual(suite.countTestCases(), 2)
+
+    ################################################################
+    ### /Tests for TestSuite.__init__
+
+    # Container types should support the iter protocol
+    def test_iter(self):
+        test1 = unittest.FunctionTestCase(lambda: None)
+        test2 = unittest.FunctionTestCase(lambda: None)
+        suite = unittest.TestSuite((test1, test2))
+
+        self.assertEqual(list(suite), [test1, test2])
+
+    # "Return the number of tests represented by the this test object.
+    # ...this method is also implemented by the TestSuite class, which can
+    # return larger [greater than 1] values"
+    #
+    # Presumably an empty TestSuite returns 0?
+    def test_countTestCases_zero_simple(self):
+        suite = unittest.TestSuite()
+
+        self.assertEqual(suite.countTestCases(), 0)
+
+    # "Return the number of tests represented by the this test object.
+    # ...this method is also implemented by the TestSuite class, which can
+    # return larger [greater than 1] values"
+    #
+    # Presumably an empty TestSuite (even if it contains other empty
+    # TestSuite instances) returns 0?
+    def test_countTestCases_zero_nested(self):
+        class Test1(unittest.TestCase):
+            def test(self):
+                pass
+
+        suite = unittest.TestSuite([unittest.TestSuite()])
+
+        self.assertEqual(suite.countTestCases(), 0)
+
+    # "Return the number of tests represented by the this test object.
+    # ...this method is also implemented by the TestSuite class, which can
+    # return larger [greater than 1] values"
+    def test_countTestCases_simple(self):
+        test1 = unittest.FunctionTestCase(lambda: None)
+        test2 = unittest.FunctionTestCase(lambda: None)
+        suite = unittest.TestSuite((test1, test2))
+
+        self.assertEqual(suite.countTestCases(), 2)
+
+    # "Return the number of tests represented by the this test object.
+    # ...this method is also implemented by the TestSuite class, which can
+    # return larger [greater than 1] values"
+    #
+    # Make sure this holds for nested TestSuite instances, too
+    def test_countTestCases_nested(self):
+        class Test1(unittest.TestCase):
+            def test1(self): pass
+            def test2(self): pass
+
+        test2 = unittest.FunctionTestCase(lambda: None)
+        test3 = unittest.FunctionTestCase(lambda: None)
+        child = unittest.TestSuite((Test1('test2'), test2))
+        parent = unittest.TestSuite((test3, child, Test1('test1')))
+
+        self.assertEqual(parent.countTestCases(), 4)
+
+    # "Run the tests associated with this suite, collecting the result into
+    # the test result object passed as result."
+    #
+    # And if there are no tests? What then?
+    def test_run__empty_suite(self):
+        events = []
+        result = LoggingResult(events)
+
+        suite = unittest.TestSuite()
+
+        suite.run(result)
+
+        self.assertEqual(events, [])
+
+    # "Note that unlike TestCase.run(), TestSuite.run() requires the
+    # "result object to be passed in."
+    def test_run__requires_result(self):
+        suite = unittest.TestSuite()
+
+        try:
+            suite.run()
+        except TypeError:
+            pass
+        else:
+            self.fail("Failed to raise TypeError")
+
+    # "Run the tests associated with this suite, collecting the result into
+    # the test result object passed as result."
+    def test_run(self):
+        events = []
+        result = LoggingResult(events)
+
+        class LoggingCase(unittest.TestCase):
+            def run(self, result):
+                events.append('run %s' % self._testMethodName)
+
+            def test1(self): pass
+            def test2(self): pass
+
+        tests = [LoggingCase('test1'), LoggingCase('test2')]
+
+        unittest.TestSuite(tests).run(result)
+
+        self.assertEqual(events, ['run test1', 'run test2'])
+
+    # "Add a TestCase ... to the suite"
+    def test_addTest__TestCase(self):
+        class Foo(unittest.TestCase):
+            def test(self): pass
+
+        test = Foo('test')
+        suite = unittest.TestSuite()
+
+        suite.addTest(test)
+
+        self.assertEqual(suite.countTestCases(), 1)
+        self.assertEqual(list(suite), [test])
+
+    # "Add a ... TestSuite to the suite"
+    def test_addTest__TestSuite(self):
+        class Foo(unittest.TestCase):
+            def test(self): pass
+
+        suite_2 = unittest.TestSuite([Foo('test')])
+
+        suite = unittest.TestSuite()
+        suite.addTest(suite_2)
+
+        self.assertEqual(suite.countTestCases(), 1)
+        self.assertEqual(list(suite), [suite_2])
+
+    # "Add all the tests from an iterable of TestCase and TestSuite
+    # instances to this test suite."
+    #
+    # "This is equivalent to iterating over tests, calling addTest() for
+    # each element"
+    def test_addTests(self):
+        class Foo(unittest.TestCase):
+            def test_1(self): pass
+            def test_2(self): pass
+
+        test_1 = Foo('test_1')
+        test_2 = Foo('test_2')
+        inner_suite = unittest.TestSuite([test_2])
+
+        def gen():
+            yield test_1
+            yield test_2
+            yield inner_suite
+
+        suite_1 = unittest.TestSuite()
+        suite_1.addTests(gen())
+
+        self.assertEqual(list(suite_1), list(gen()))
+
+        # "This is equivalent to iterating over tests, calling addTest() for
+        # each element"
+        suite_2 = unittest.TestSuite()
+        for t in gen():
+            suite_2.addTest(t)
+
+        self.assertEqual(suite_1, suite_2)
+
+    # "Add all the tests from an iterable of TestCase and TestSuite
+    # instances to this test suite."
+    #
+    # What happens if it doesn't get an iterable?
+    def test_addTest__noniterable(self):
+        suite = unittest.TestSuite()
+
+        try:
+            suite.addTests(5)
+        except TypeError:
+            pass
+        else:
+            self.fail("Failed to raise TypeError")
+
+    def test_addTest__noncallable(self):
+        suite = unittest.TestSuite()
+        self.assertRaises(TypeError, suite.addTest, 5)
+
+    def test_addTest__casesuiteclass(self):
+        suite = unittest.TestSuite()
+        self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
+        self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
+
+    def test_addTests__string(self):
+        suite = unittest.TestSuite()
+        self.assertRaises(TypeError, suite.addTests, "foo")
+
+
+class Test_FunctionTestCase(TestCase):
+
+    # "Return the number of tests represented by the this test object. For
+    # TestCase instances, this will always be 1"
+    def test_countTestCases(self):
+        test = unittest.FunctionTestCase(lambda: None)
+
+        self.assertEqual(test.countTestCases(), 1)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if setUp() raises
+    # an exception.
+    def test_run_call_order__error_in_setUp(self):
+        events = []
+        result = LoggingResult(events)
+
+        def setUp():
+            events.append('setUp')
+            raise RuntimeError('raised by setUp')
+
+        def test():
+            events.append('test')
+
+        def tearDown():
+            events.append('tearDown')
+
+        expected = ['startTest', 'setUp', 'addError', 'stopTest']
+        unittest.FunctionTestCase(test, setUp, tearDown).run(result)
+        self.assertEqual(events, expected)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if the test raises
+    # an error (as opposed to a failure).
+    def test_run_call_order__error_in_test(self):
+        events = []
+        result = LoggingResult(events)
+
+        def setUp():
+            events.append('setUp')
+
+        def test():
+            events.append('test')
+            raise RuntimeError('raised by test')
+
+        def tearDown():
+            events.append('tearDown')
+
+        expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
+                    'stopTest']
+        unittest.FunctionTestCase(test, setUp, tearDown).run(result)
+        self.assertEqual(events, expected)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if the test signals
+    # a failure (as opposed to an error).
+    def test_run_call_order__failure_in_test(self):
+        events = []
+        result = LoggingResult(events)
+
+        def setUp():
+            events.append('setUp')
+
+        def test():
+            events.append('test')
+            self.fail('raised by test')
+
+        def tearDown():
+            events.append('tearDown')
+
+        expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
+                    'stopTest']
+        unittest.FunctionTestCase(test, setUp, tearDown).run(result)
+        self.assertEqual(events, expected)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if tearDown() raises
+    # an exception.
+    def test_run_call_order__error_in_tearDown(self):
+        events = []
+        result = LoggingResult(events)
+
+        def setUp():
+            events.append('setUp')
+
+        def test():
+            events.append('test')
+
+        def tearDown():
+            events.append('tearDown')
+            raise RuntimeError('raised by tearDown')
+
+        expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
+                    'stopTest']
+        unittest.FunctionTestCase(test, setUp, tearDown).run(result)
+        self.assertEqual(events, expected)
+
+    # "Return a string identifying the specific test case."
+    #
+    # Because of the vague nature of the docs, I'm not going to lock this
+    # test down too much. Really all that can be asserted is that the id()
+    # will be a string (either 8-byte or unicode -- again, because the docs
+    # just say "string")
+    def test_id(self):
+        test = unittest.FunctionTestCase(lambda: None)
+
+        self.failUnless(isinstance(test.id(), basestring))
+
+    # "Returns a one-line description of the test, or None if no description
+    # has been provided. The default implementation of this method returns
+    # the first line of the test method's docstring, if available, or None."
+    def test_shortDescription__no_docstring(self):
+        test = unittest.FunctionTestCase(lambda: None)
+
+        self.assertEqual(test.shortDescription(), None)
+
+    # "Returns a one-line description of the test, or None if no description
+    # has been provided. The default implementation of this method returns
+    # the first line of the test method's docstring, if available, or None."
+    def test_shortDescription__singleline_docstring(self):
+        desc = "this tests foo"
+        test = unittest.FunctionTestCase(lambda: None, description=desc)
+
+        self.assertEqual(test.shortDescription(), "this tests foo")
+
+class Test_TestResult(TestCase):
+    # Note: there are not separate tests for TestResult.wasSuccessful(),
+    # TestResult.errors, TestResult.failures, TestResult.testsRun or
+    # TestResult.shouldStop because these only have meaning in terms of
+    # other TestResult methods.
+    #
+    # Accordingly, tests for the aforenamed attributes are incorporated
+    # in with the tests for the defining methods.
+    ################################################################
+
+    def test_init(self):
+        result = unittest.TestResult()
+
+        self.failUnless(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 0)
+        self.assertEqual(len(result.failures), 0)
+        self.assertEqual(result.testsRun, 0)
+        self.assertEqual(result.shouldStop, False)
+
+    # "This method can be called to signal that the set of tests being
+    # run should be aborted by setting the TestResult's shouldStop
+    # attribute to True."
+    def test_stop(self):
+        result = unittest.TestResult()
+
+        result.stop()
+
+        self.assertEqual(result.shouldStop, True)
+
+    # "Called when the test case test is about to be run. The default
+    # implementation simply increments the instance's testsRun counter."
+    def test_startTest(self):
+        class Foo(unittest.TestCase):
+            def test_1(self):
+                pass
+
+        test = Foo('test_1')
+
+        result = unittest.TestResult()
+
+        result.startTest(test)
+
+        self.failUnless(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 0)
+        self.assertEqual(len(result.failures), 0)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(result.shouldStop, False)
+
+        result.stopTest(test)
+
+    # "Called after the test case test has been executed, regardless of
+    # the outcome. The default implementation does nothing."
+    def test_stopTest(self):
+        class Foo(unittest.TestCase):
+            def test_1(self):
+                pass
+
+        test = Foo('test_1')
+
+        result = unittest.TestResult()
+
+        result.startTest(test)
+
+        self.failUnless(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 0)
+        self.assertEqual(len(result.failures), 0)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(result.shouldStop, False)
+
+        result.stopTest(test)
+
+        # Same tests as above; make sure nothing has changed
+        self.failUnless(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 0)
+        self.assertEqual(len(result.failures), 0)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(result.shouldStop, False)
+
+    # "addSuccess(test)"
+    # ...
+    # "Called when the test case test succeeds"
+    # ...
+    # "wasSuccessful() - Returns True if all tests run so far have passed,
+    # otherwise returns False"
+    # ...
+    # "testsRun - The total number of tests run so far."
+    # ...
+    # "errors - A list containing 2-tuples of TestCase instances and
+    # formatted tracebacks. Each tuple represents a test which raised an
+    # unexpected exception. Contains formatted
+    # tracebacks instead of sys.exc_info() results."
+    # ...
+    # "failures - A list containing 2-tuples of TestCase instances and
+    # formatted tracebacks. Each tuple represents a test where a failure was
+    # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
+    # methods. Contains formatted tracebacks instead
+    # of sys.exc_info() results."
+    def test_addSuccess(self):
+        class Foo(unittest.TestCase):
+            def test_1(self):
+                pass
+
+        test = Foo('test_1')
+
+        result = unittest.TestResult()
+
+        result.startTest(test)
+        result.addSuccess(test)
+        result.stopTest(test)
+
+        self.failUnless(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 0)
+        self.assertEqual(len(result.failures), 0)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(result.shouldStop, False)
+
+    # "addFailure(test, err)"
+    # ...
+    # "Called when the test case test signals a failure. err is a tuple of
+    # the form returned by sys.exc_info(): (type, value, traceback)"
+    # ...
+    # "wasSuccessful() - Returns True if all tests run so far have passed,
+    # otherwise returns False"
+    # ...
+    # "testsRun - The total number of tests run so far."
+    # ...
+    # "errors - A list containing 2-tuples of TestCase instances and
+    # formatted tracebacks. Each tuple represents a test which raised an
+    # unexpected exception. Contains formatted
+    # tracebacks instead of sys.exc_info() results."
+    # ...
+    # "failures - A list containing 2-tuples of TestCase instances and
+    # formatted tracebacks. Each tuple represents a test where a failure was
+    # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
+    # methods. Contains formatted tracebacks instead
+    # of sys.exc_info() results."
+    def test_addFailure(self):
+        import sys
+
+        class Foo(unittest.TestCase):
+            def test_1(self):
+                pass
+
+        test = Foo('test_1')
+        try:
+            test.fail("foo")
+        except:
+            exc_info_tuple = sys.exc_info()
+
+        result = unittest.TestResult()
+
+        result.startTest(test)
+        result.addFailure(test, exc_info_tuple)
+        result.stopTest(test)
+
+        self.failIf(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 0)
+        self.assertEqual(len(result.failures), 1)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(result.shouldStop, False)
+
+        test_case, formatted_exc = result.failures[0]
+        self.failUnless(test_case is test)
+        self.failUnless(isinstance(formatted_exc, str))
+
+    # "addError(test, err)"
+    # ...
+    # "Called when the test case test raises an unexpected exception err
+    # is a tuple of the form returned by sys.exc_info():
+    # (type, value, traceback)"
+    # ...
+    # "wasSuccessful() - Returns True if all tests run so far have passed,
+    # otherwise returns False"
+    # ...
+    # "testsRun - The total number of tests run so far."
+    # ...
+    # "errors - A list containing 2-tuples of TestCase instances and
+    # formatted tracebacks. Each tuple represents a test which raised an
+    # unexpected exception. Contains formatted
+    # tracebacks instead of sys.exc_info() results."
+    # ...
+    # "failures - A list containing 2-tuples of TestCase instances and
+    # formatted tracebacks. Each tuple represents a test where a failure was
+    # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
+    # methods. Contains formatted tracebacks instead
+    # of sys.exc_info() results."
+    def test_addError(self):
+        import sys
+
+        class Foo(unittest.TestCase):
+            def test_1(self):
+                pass
+
+        test = Foo('test_1')
+        try:
+            raise TypeError()
+        except:
+            exc_info_tuple = sys.exc_info()
+
+        result = unittest.TestResult()
+
+        result.startTest(test)
+        result.addError(test, exc_info_tuple)
+        result.stopTest(test)
+
+        self.failIf(result.wasSuccessful())
+        self.assertEqual(len(result.errors), 1)
+        self.assertEqual(len(result.failures), 0)
+        self.assertEqual(result.testsRun, 1)
+        self.assertEqual(result.shouldStop, False)
+
+        test_case, formatted_exc = result.errors[0]
+        self.failUnless(test_case is test)
+        self.failUnless(isinstance(formatted_exc, str))
+
+### Support code for Test_TestCase
+################################################################
+
+class Foo(unittest.TestCase):
+    def runTest(self): pass
+    def test1(self): pass
+
+class Bar(Foo):
+    def test2(self): pass
+
+################################################################
+### /Support code for Test_TestCase
+
+class Test_TestCase(TestCase, TestEquality, TestHashing):
+
+    ### Set up attributes used by inherited tests
+    ################################################################
+
+    # Used by TestHashing.test_hash and TestEquality.test_eq
+    eq_pairs = [(Foo('test1'), Foo('test1'))]
+
+    # Used by TestEquality.test_ne
+    ne_pairs = [(Foo('test1'), Foo('runTest'))
+               ,(Foo('test1'), Bar('test1'))
+               ,(Foo('test1'), Bar('test2'))]
+
+    ################################################################
+    ### /Set up attributes used by inherited tests
+
+
+    # "class TestCase([methodName])"
+    # ...
+    # "Each instance of TestCase will run a single test method: the
+    # method named methodName."
+    # ...
+    # "methodName defaults to "runTest"."
+    #
+    # Make sure it really is optional, and that it defaults to the proper
+    # thing.
+    def test_init__no_test_name(self):
+        class Test(unittest.TestCase):
+            def runTest(self): raise MyException()
+            def test(self): pass
+
+        self.assertEqual(Test().id()[-13:], '.Test.runTest')
+
+    # "class TestCase([methodName])"
+    # ...
+    # "Each instance of TestCase will run a single test method: the
+    # method named methodName."
+    def test_init__test_name__valid(self):
+        class Test(unittest.TestCase):
+            def runTest(self): raise MyException()
+            def test(self): pass
+
+        self.assertEqual(Test('test').id()[-10:], '.Test.test')
+
+    # "class TestCase([methodName])"
+    # ...
+    # "Each instance of TestCase will run a single test method: the
+    # method named methodName."
+    def test_init__test_name__invalid(self):
+        class Test(unittest.TestCase):
+            def runTest(self): raise MyException()
+            def test(self): pass
+
+        try:
+            Test('testfoo')
+        except ValueError:
+            pass
+        else:
+            self.fail("Failed to raise ValueError")
+
+    # "Return the number of tests represented by the this test object. For
+    # TestCase instances, this will always be 1"
+    def test_countTestCases(self):
+        class Foo(unittest.TestCase):
+            def test(self): pass
+
+        self.assertEqual(Foo('test').countTestCases(), 1)
+
+    # "Return the default type of test result object to be used to run this
+    # test. For TestCase instances, this will always be
+    # unittest.TestResult;  subclasses of TestCase should
+    # override this as necessary."
+    def test_defaultTestResult(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                pass
+
+        result = Foo().defaultTestResult()
+        self.assertEqual(type(result), unittest.TestResult)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if setUp() raises
+    # an exception.
+    def test_run_call_order__error_in_setUp(self):
+        events = []
+        result = LoggingResult(events)
+
+        class Foo(unittest.TestCase):
+            def setUp(self):
+                events.append('setUp')
+                raise RuntimeError('raised by Foo.setUp')
+
+            def test(self):
+                events.append('test')
+
+            def tearDown(self):
+                events.append('tearDown')
+
+        Foo('test').run(result)
+        expected = ['startTest', 'setUp', 'addError', 'stopTest']
+        self.assertEqual(events, expected)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if the test raises
+    # an error (as opposed to a failure).
+    def test_run_call_order__error_in_test(self):
+        events = []
+        result = LoggingResult(events)
+
+        class Foo(unittest.TestCase):
+            def setUp(self):
+                events.append('setUp')
+
+            def test(self):
+                events.append('test')
+                raise RuntimeError('raised by Foo.test')
+
+            def tearDown(self):
+                events.append('tearDown')
+
+        expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
+                    'stopTest']
+        Foo('test').run(result)
+        self.assertEqual(events, expected)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if the test signals
+    # a failure (as opposed to an error).
+    def test_run_call_order__failure_in_test(self):
+        events = []
+        result = LoggingResult(events)
+
+        class Foo(unittest.TestCase):
+            def setUp(self):
+                events.append('setUp')
+
+            def test(self):
+                events.append('test')
+                self.fail('raised by Foo.test')
+
+            def tearDown(self):
+                events.append('tearDown')
+
+        expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
+                    'stopTest']
+        Foo('test').run(result)
+        self.assertEqual(events, expected)
+
+    # "When a setUp() method is defined, the test runner will run that method
+    # prior to each test. Likewise, if a tearDown() method is defined, the
+    # test runner will invoke that method after each test. In the example,
+    # setUp() was used to create a fresh sequence for each test."
+    #
+    # Make sure the proper call order is maintained, even if tearDown() raises
+    # an exception.
+    def test_run_call_order__error_in_tearDown(self):
+        events = []
+        result = LoggingResult(events)
+
+        class Foo(unittest.TestCase):
+            def setUp(self):
+                events.append('setUp')
+
+            def test(self):
+                events.append('test')
+
+            def tearDown(self):
+                events.append('tearDown')
+                raise RuntimeError('raised by Foo.tearDown')
+
+        Foo('test').run(result)
+        expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
+                    'stopTest']
+        self.assertEqual(events, expected)
+
+    # "This class attribute gives the exception raised by the test() method.
+    # If a test framework needs to use a specialized exception, possibly to
+    # carry additional information, it must subclass this exception in
+    # order to ``play fair'' with the framework.  The initial value of this
+    # attribute is AssertionError"
+    def test_failureException__default(self):
+        class Foo(unittest.TestCase):
+            def test(self):
+                pass
+
+        self.failUnless(Foo('test').failureException is AssertionError)
+
+    # "This class attribute gives the exception raised by the test() method.
+    # If a test framework needs to use a specialized exception, possibly to
+    # carry additional information, it must subclass this exception in
+    # order to ``play fair'' with the framework."
+    #
+    # Make sure TestCase.run() respects the designated failureException
+    def test_failureException__subclassing__explicit_raise(self):
+        events = []
+        result = LoggingResult(events)
+
+        class Foo(unittest.TestCase):
+            def test(self):
+                raise RuntimeError()
+
+            failureException = RuntimeError
+
+        self.failUnless(Foo('test').failureException is RuntimeError)
+
+
+        Foo('test').run(result)
+        expected = ['startTest', 'addFailure', 'stopTest']
+        self.assertEqual(events, expected)
+
+    # "This class attribute gives the exception raised by the test() method.
+    # If a test framework needs to use a specialized exception, possibly to
+    # carry additional information, it must subclass this exception in
+    # order to ``play fair'' with the framework."
+    #
+    # Make sure TestCase.run() respects the designated failureException
+    def test_failureException__subclassing__implicit_raise(self):
+        events = []
+        result = LoggingResult(events)
+
+        class Foo(unittest.TestCase):
+            def test(self):
+                self.fail("foo")
+
+            failureException = RuntimeError
+
+        self.failUnless(Foo('test').failureException is RuntimeError)
+
+
+        Foo('test').run(result)
+        expected = ['startTest', 'addFailure', 'stopTest']
+        self.assertEqual(events, expected)
+
+    # "The default implementation does nothing."
+    def test_setUp(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                pass
+
+        # ... and nothing should happen
+        Foo().setUp()
+
+    # "The default implementation does nothing."
+    def test_tearDown(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                pass
+
+        # ... and nothing should happen
+        Foo().tearDown()
+
+    # "Return a string identifying the specific test case."
+    #
+    # Because of the vague nature of the docs, I'm not going to lock this
+    # test down too much. Really all that can be asserted is that the id()
+    # will be a string (either 8-byte or unicode -- again, because the docs
+    # just say "string")
+    def test_id(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                pass
+
+        self.failUnless(isinstance(Foo().id(), basestring))
+
+    # "Returns a one-line description of the test, or None if no description
+    # has been provided. The default implementation of this method returns
+    # the first line of the test method's docstring, if available, or None."
+    def test_shortDescription__no_docstring(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                pass
+
+        self.assertEqual(Foo().shortDescription(), None)
+
+    # "Returns a one-line description of the test, or None if no description
+    # has been provided. The default implementation of this method returns
+    # the first line of the test method's docstring, if available, or None."
+    def test_shortDescription__singleline_docstring(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                "this tests foo"
+                pass
+
+        self.assertEqual(Foo().shortDescription(), "this tests foo")
+
+    # "Returns a one-line description of the test, or None if no description
+    # has been provided. The default implementation of this method returns
+    # the first line of the test method's docstring, if available, or None."
+    def test_shortDescription__multiline_docstring(self):
+        class Foo(unittest.TestCase):
+            def runTest(self):
+                """this tests foo
+                blah, bar and baz are also tested"""
+                pass
+
+        self.assertEqual(Foo().shortDescription(), "this tests foo")
+
+    # "If result is omitted or None, a temporary result object is created
+    # and used, but is not made available to the caller"
+    def test_run__uses_defaultTestResult(self):
+        events = []
+
+        class Foo(unittest.TestCase):
+            def test(self):
+                events.append('test')
+
+            def defaultTestResult(self):
+                return LoggingResult(events)
 
-def test_TestSuite_iter():
-    """
-    >>> test1 = unittest.FunctionTestCase(lambda: None)
-    >>> test2 = unittest.FunctionTestCase(lambda: None)
-    >>> suite = unittest.TestSuite((test1, test2))
-    >>> tests = []
-    >>> for test in suite:
-    ...     tests.append(test)
-    >>> tests == [test1, test2]
-    True
-    """
+        # Make run() find a result object on its own
+        Foo('test').run()
 
+        expected = ['startTest', 'test', 'stopTest']
+        self.assertEqual(events, expected)
 
 ######################################################################
 ## Main
 ######################################################################
 
 def test_main():
-    from test import test_support, test_unittest
-    test_support.run_doctest(test_unittest, verbosity=True)
+    test_support.run_unittest(Test_TestCase, Test_TestLoader,
+        Test_TestSuite, Test_TestResult, Test_FunctionTestCase)
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_univnewlines.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_univnewlines.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_univnewlines.py	Wed Jul 11 15:40:56 2007
@@ -28,7 +28,6 @@
 # before end-of-file.
 DATA_MIXED = "\n".join(DATA_TEMPLATE) + "\r"
 DATA_SPLIT = [x + "\n" for x in DATA_TEMPLATE]
-del x
 
 class TestGenericUnivNewlines(unittest.TestCase):
     # use a class variable DATA to define the data to write to the file
@@ -83,7 +82,7 @@
         namespace = {}
         execfile(test_support.TESTFN, namespace)
         func = namespace['line3']
-        self.assertEqual(func.func_code.co_firstlineno, 3)
+        self.assertEqual(func.__code__.co_firstlineno, 3)
         self.assertEqual(namespace['line4'], FATX)
 
 

Modified: python/branches/p3yk-noslice/Lib/test/test_unpack.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unpack.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_unpack.py	Wed Jul 11 15:40:56 2007
@@ -55,7 +55,7 @@
     >>> a, b, c = 7
     Traceback (most recent call last):
       ...
-    TypeError: unpack non-sequence
+    TypeError: 'int' object is not iterable
 
 Unpacking tuple of wrong size
 

Modified: python/branches/p3yk-noslice/Lib/test/test_urllib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_urllib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_urllib.py	Wed Jul 11 15:40:56 2007
@@ -8,6 +8,10 @@
 import mimetools
 import tempfile
 import StringIO
+import ftplib
+import threading
+import socket
+import time
 
 def hexescape(char):
     """Escape char as RFC 2396 specifies"""
@@ -122,6 +126,15 @@
         finally:
             self.unfakehttp()
 
+    def test_empty_socket(self):
+        """urlopen() raises IOError if the underlying socket does not send any
+        data. (#1680230) """
+        self.fakehttp('')
+        try:
+            self.assertRaises(IOError, urllib.urlopen, 'http://something')
+        finally:
+            self.unfakehttp()
+
 class urlretrieve_FileTests(unittest.TestCase):
     """Test urllib.urlretrieve() on local files"""
 
@@ -295,7 +308,7 @@
 
     def test_default_safe(self):
         # Test '/' is default value for 'safe' parameter
-        self.assertEqual(urllib.quote.func_defaults[0], '/')
+        self.assertEqual(urllib.quote.__defaults__[0], '/')
 
     def test_safe(self):
         # Test setting 'safe' parameter does what it should do
@@ -532,6 +545,76 @@
                          "url2pathname() failed; %s != %s" %
                          (expect, result))
 
+# Just commented them out.
+# Can't really tell why keep failing in windows and sparc.
+# Everywhere else they work ok, but on those machines, someteimes
+# fail in one of the tests, sometimes in other. I have a linux, and
+# the tests go ok.
+# If anybody has one of the problematic enviroments, please help!
+# .   Facundo
+#
+# def server(evt):
+#     serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+#     serv.settimeout(3)
+#     serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+#     serv.bind(("", 9093))
+#     serv.listen(5)
+#     try:
+#         conn, addr = serv.accept()
+#         conn.send("1 Hola mundo\n")
+#         cantdata = 0
+#         while cantdata < 13:
+#             data = conn.recv(13-cantdata)
+#             cantdata += len(data)
+#             time.sleep(.3)
+#         conn.send("2 No more lines\n")
+#         conn.close()
+#     except socket.timeout:
+#         pass
+#     finally:
+#         serv.close()
+#         evt.set()
+#
+# class FTPWrapperTests(unittest.TestCase):
+#
+#     def setUp(self):
+#         ftplib.FTP.port = 9093
+#         self.evt = threading.Event()
+#         threading.Thread(target=server, args=(self.evt,)).start()
+#         time.sleep(.1)
+#
+#     def tearDown(self):
+#         self.evt.wait()
+#
+#     def testBasic(self):
+#         # connects
+#         ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
+#         ftp.ftp.sock.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)
+#         self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
+#         ftp.ftp.sock.close()
+#
+#     def testTimeoutNone(self):
+#         # None, having other default
+#         previous = socket.getdefaulttimeout()
+#         socket.setdefaulttimeout(30)
+#         try:
+#             ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
+#         finally:
+#             socket.setdefaulttimeout(previous)
+#         self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
+#         ftp.ftp.close()
+#
+
 
 
 def test_main():
@@ -542,7 +625,8 @@
         QuotingTests,
         UnquotingTests,
         urlencode_Tests,
-        Pathname_Tests
+        Pathname_Tests,
+        #FTPWrapperTests,
     )
 
 

Modified: python/branches/p3yk-noslice/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_urllib2.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_urllib2.py	Wed Jul 11 15:40:56 2007
@@ -544,7 +544,7 @@
 
         class NullFTPHandler(urllib2.FTPHandler):
             def __init__(self, data): self.data = data
-            def connect_ftp(self, user, passwd, host, port, dirs):
+            def connect_ftp(self, user, passwd, host, port, dirs, timeout=None):
                 self.user, self.passwd = user, passwd
                 self.host, self.port = host, port
                 self.dirs = dirs
@@ -567,7 +567,9 @@
              "localhost", ftplib.FTP_PORT, "A",
              [], "baz.gif", None),  # XXX really this should guess image/gif
             ]:
-            r = h.ftp_open(Request(url))
+            req = Request(url)
+            req.timeout = None
+            r = h.ftp_open(req)
             # ftp authentication not yet implemented by FTPHandler
             self.assert_(h.user == h.passwd == "")
             self.assertEqual(h.host, socket.gethostbyname(host))
@@ -625,11 +627,11 @@
 
         for url in [
             "file://localhost:80%s" % urlpath,
-# XXXX bug: these fail with socket.gaierror, should be URLError
-##             "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
-##                                    os.getcwd(), TESTFN),
-##             "file://somerandomhost.ontheinternet.com%s/%s" %
-##             (os.getcwd(), TESTFN),
+            "file:///file_does_not_exist.txt",
+            "file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
+                                   os.getcwd(), TESTFN),
+            "file://somerandomhost.ontheinternet.com%s/%s" %
+            (os.getcwd(), TESTFN),
             ]:
             try:
                 f = open(TESTFN, "wb")
@@ -682,8 +684,9 @@
                 self.req_headers = []
                 self.data = None
                 self.raise_on_endheaders = False
-            def __call__(self, host):
+            def __call__(self, host, timeout=None):
                 self.host = host
+                self.timeout = timeout
                 return self
             def set_debuglevel(self, level):
                 self.level = level
@@ -706,6 +709,7 @@
         url = "http://example.com/"
         for method, data in [("GET", None), ("POST", "blah")]:
             req = Request(url, data, {"Foo": "bar"})
+            req.timeout = None
             req.add_unredirected_header("Spam", "eggs")
             http = MockHTTPClass()
             r = h.do_open(http, req)
@@ -765,16 +769,24 @@
 
         url = "http://example.com/"
         req = Request(url)
-        # 200 OK is passed through
+        # all 2xx are passed through
         r = MockResponse(200, "OK", {}, "", url)
         newr = h.http_response(req, r)
         self.assert_(r is newr)
         self.assert_(not hasattr(o, "proto"))  # o.error not called
+        r = MockResponse(202, "Accepted", {}, "", url)
+        newr = h.http_response(req, r)
+        self.assert_(r is newr)
+        self.assert_(not hasattr(o, "proto"))  # o.error not called
+        r = MockResponse(206, "Partial content", {}, "", url)
+        newr = h.http_response(req, r)
+        self.assert_(r is newr)
+        self.assert_(not hasattr(o, "proto"))  # o.error not called
         # anything else calls o.error (and MockOpener returns None, here)
-        r = MockResponse(201, "Created", {}, "", url)
+        r = MockResponse(502, "Bad gateway", {}, "", url)
         self.assert_(h.http_response(req, r) is None)
         self.assertEqual(o.proto, "http")  # o.error called
-        self.assertEqual(o.args, (req, r, 201, "Created", {}))
+        self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
 
     def test_cookies(self):
         cj = MockCookieJar()

Modified: python/branches/p3yk-noslice/Lib/test/test_urllib2net.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_urllib2net.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_urllib2net.py	Wed Jul 11 15:40:56 2007
@@ -173,19 +173,6 @@
             ]
         self._test_urls(urls, self._extra_handlers())
 
-    def test_gopher(self):
-        import warnings
-        warnings.filterwarnings("ignore",
-                                "the gopherlib module is deprecated",
-                                DeprecationWarning,
-                                "urllib2$")
-        urls = [
-            # Thanks to Fred for finding these!
-            'gopher://gopher.lib.ncsu.edu./11/library/stacks/Alex',
-            'gopher://gopher.vt.edu.:10010/10/33',
-            ]
-        self._test_urls(urls, self._extra_handlers())
-
     def test_file(self):
         TESTFN = test_support.TESTFN
         f = open(TESTFN, 'w')
@@ -264,7 +251,8 @@
                            (expected_err, url, req, err))
                     self.assert_(isinstance(err, expected_err), msg)
             else:
-                buf = f.read()
+                with test_support.transient_internet():
+                    buf = f.read()
                 f.close()
                 debug("read %d bytes" % len(buf))
             debug("******** next url coming up...")
@@ -273,14 +261,55 @@
     def _extra_handlers(self):
         handlers = []
 
-        handlers.append(urllib2.GopherHandler)
-
         cfh = urllib2.CacheFTPHandler()
         cfh.setTimeout(1)
         handlers.append(cfh)
 
         return handlers
 
+class TimeoutTest(unittest.TestCase):
+    def test_http_basic(self):
+        u = urllib2.urlopen("http://www.python.org")
+        self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
+
+    def test_http_NoneWithdefault(self):
+        prev = socket.getdefaulttimeout()
+        socket.setdefaulttimeout(60)
+        try:
+            u = urllib2.urlopen("http://www.python.org", timeout=None)
+            self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60)
+        finally:
+            socket.setdefaulttimeout(prev)
+
+    def test_http_Value(self):
+        u = urllib2.urlopen("http://www.python.org", timeout=120)
+        self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120)
+
+    def test_http_NoneNodefault(self):
+        u = urllib2.urlopen("http://www.python.org", timeout=None)
+        self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
+
+    def test_ftp_basic(self):
+        u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/")
+        self.assertTrue(u.fp.fp._sock.gettimeout() is None)
+
+    def test_ftp_NoneWithdefault(self):
+        prev = socket.getdefaulttimeout()
+        socket.setdefaulttimeout(60)
+        try:
+            u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/", timeout=None)
+            self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
+        finally:
+            socket.setdefaulttimeout(prev)
+
+    def test_ftp_NoneNodefault(self):
+        u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/", timeout=None)
+        self.assertTrue(u.fp.fp._sock.gettimeout() is None)
+
+    def test_ftp_Value(self):
+        u = urllib2.urlopen("ftp://ftp.mirror.nl/pub/mirror/gnu/", timeout=60)
+        self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
+
 
 def test_main():
     test_support.requires("network")
@@ -289,6 +318,7 @@
                               AuthTests,
                               OtherNetworkTests,
                               CloseSocketTest,
+                              TimeoutTest,
                               )
 
 if __name__ == "__main__":

Modified: python/branches/p3yk-noslice/Lib/test/test_userdict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_userdict.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_userdict.py	Wed Jul 11 15:40:56 2007
@@ -118,7 +118,7 @@
             self.assertEqual(u0.get(i), d0.get(i))
 
         # Test "in" iteration.
-        for i in xrange(20):
+        for i in range(20):
             u2[i] = str(i)
         ikeys = []
         for k in u2:
@@ -171,7 +171,7 @@
         except RuntimeError as err:
             self.assertEqual(err.args, (42,))
         else:
-            self.fail_("e[42] didn't raise RuntimeError")
+            self.fail("e[42] didn't raise RuntimeError")
         class F(UserDict.UserDict):
             def __init__(self):
                 # An instance variable __missing__ should have no effect
@@ -183,7 +183,7 @@
         except KeyError as err:
             self.assertEqual(err.args, (42,))
         else:
-            self.fail_("f[42] didn't raise KeyError")
+            self.fail("f[42] didn't raise KeyError")
         class G(UserDict.UserDict):
             pass
         g = G()
@@ -192,7 +192,7 @@
         except KeyError as err:
             self.assertEqual(err.args, (42,))
         else:
-            self.fail_("g[42] didn't raise KeyError")
+            self.fail("g[42] didn't raise KeyError")
 
 ##########################
 # Test Dict Mixin

Modified: python/branches/p3yk-noslice/Lib/test/test_userlist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_userlist.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_userlist.py	Wed Jul 11 15:40:56 2007
@@ -20,7 +20,7 @@
         self.assertEqual(u2, list("spameggs"))
 
     def test_iadd(self):
-        super(UserListTest, self).test_iadd()
+        super().test_iadd()
         u = [0, 1]
         u += UserList([0, 1])
         self.assertEqual(u, [0, 1, 0, 1])
@@ -41,7 +41,7 @@
         class T(self.type2test):
             def __getitem__(self, key):
                 return str(key) + '!!!'
-        self.assertEqual(iter(T((1,2))).next(), "0!!!")
+        self.assertEqual(next(iter(T((1,2)))), "0!!!")
 
 def test_main():
     test_support.run_unittest(UserListTest)

Modified: python/branches/p3yk-noslice/Lib/test/test_uu.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_uu.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_uu.py	Wed Jul 11 15:40:56 2007
@@ -24,21 +24,21 @@
         inp = cStringIO.StringIO(plaintext)
         out = cStringIO.StringIO()
         uu.encode(inp, out, "t1")
-        self.assertEqual(out.getvalue(), encodedtextwrapped % (0666, "t1"))
+        self.assertEqual(out.getvalue(), encodedtextwrapped % (0o666, "t1"))
         inp = cStringIO.StringIO(plaintext)
         out = cStringIO.StringIO()
-        uu.encode(inp, out, "t1", 0644)
-        self.assertEqual(out.getvalue(), encodedtextwrapped % (0644, "t1"))
+        uu.encode(inp, out, "t1", 0o644)
+        self.assertEqual(out.getvalue(), encodedtextwrapped % (0o644, "t1"))
 
     def test_decode(self):
-        inp = cStringIO.StringIO(encodedtextwrapped % (0666, "t1"))
+        inp = cStringIO.StringIO(encodedtextwrapped % (0o666, "t1"))
         out = cStringIO.StringIO()
         uu.decode(inp, out)
         self.assertEqual(out.getvalue(), plaintext)
         inp = cStringIO.StringIO(
             "UUencoded files may contain many lines,\n" +
             "even some that have 'begin' in them.\n" +
-            encodedtextwrapped % (0666, "t1")
+            encodedtextwrapped % (0o666, "t1")
         )
         out = cStringIO.StringIO()
         uu.decode(inp, out)
@@ -75,14 +75,14 @@
     def test_encode(self):
         sys.stdin = cStringIO.StringIO(plaintext)
         sys.stdout = cStringIO.StringIO()
-        uu.encode("-", "-", "t1", 0666)
+        uu.encode("-", "-", "t1", 0o666)
         self.assertEqual(
             sys.stdout.getvalue(),
-            encodedtextwrapped % (0666, "t1")
+            encodedtextwrapped % (0o666, "t1")
         )
 
     def test_decode(self):
-        sys.stdin = cStringIO.StringIO(encodedtextwrapped % (0666, "t1"))
+        sys.stdin = cStringIO.StringIO(encodedtextwrapped % (0o666, "t1"))
         sys.stdout = cStringIO.StringIO()
         uu.decode("-", "-")
         self.assertEqual(sys.stdout.getvalue(), plaintext)
@@ -120,21 +120,21 @@
 
             fin = open(self.tmpin, 'rb')
             fout = open(self.tmpout, 'w')
-            uu.encode(fin, fout, self.tmpin, mode=0644)
+            uu.encode(fin, fout, self.tmpin, mode=0o644)
             fin.close()
             fout.close()
 
             fout = open(self.tmpout, 'r')
             s = fout.read()
             fout.close()
-            self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin))
+            self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin))
 
             # in_file and out_file as filenames
-            uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644)
+            uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644)
             fout = open(self.tmpout, 'r')
             s = fout.read()
             fout.close()
-            self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin))
+            self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin))
 
         finally:
             self._kill(fin)
@@ -143,7 +143,7 @@
     def test_decode(self):
         try:
             f = open(self.tmpin, 'w')
-            f.write(encodedtextwrapped % (0644, self.tmpout))
+            f.write(encodedtextwrapped % (0o644, self.tmpout))
             f.close()
 
             f = open(self.tmpin, 'r')
@@ -161,7 +161,7 @@
     def test_decodetwice(self):
         # Verify that decode() will refuse to overwrite an existing file
         try:
-            f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout))
+            f = cStringIO.StringIO(encodedtextwrapped % (0o644, self.tmpout))
 
             f = open(self.tmpin, 'r')
             uu.decode(f)

Modified: python/branches/p3yk-noslice/Lib/test/test_warnings.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_warnings.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_warnings.py	Wed Jul 11 15:40:56 2007
@@ -3,95 +3,97 @@
 import unittest
 from test import test_support
 
-# The warnings module isn't easily tested, because it relies on module
-# globals to store configuration information.  setUp() and tearDown()
-# preserve the current settings to avoid bashing them while running tests.
-
-# To capture the warning messages, a replacement for showwarning() is
-# used to save warning information in a global variable.
-
-class WarningMessage:
-    "Holds results of latest showwarning() call"
-    pass
-
-def showwarning(message, category, filename, lineno, file=None):
-    msg.message = str(message)
-    msg.category = category.__name__
-    msg.filename = os.path.basename(filename)
-    msg.lineno = lineno
+from test import warning_tests
 
 class TestModule(unittest.TestCase):
-
     def setUp(self):
-        global msg
-        msg = WarningMessage()
-        self._filters = warnings.filters[:]
-        self._showwarning = warnings.showwarning
-        warnings.showwarning = showwarning
-        self.ignored = [w[2].__name__ for w in self._filters
+        self.ignored = [w[2].__name__ for w in warnings.filters
             if w[0]=='ignore' and w[1] is None and w[3] is None]
 
-    def tearDown(self):
-        warnings.filters = self._filters[:]
-        warnings.showwarning = self._showwarning
-
     def test_warn_default_category(self):
-        for i in range(4):
-            text = 'multi %d' %i    # Different text on each call
-            warnings.warn(text)
-            self.assertEqual(msg.message, text)
-            self.assertEqual(msg.category, 'UserWarning')
+        with test_support.catch_warning() as w:
+            for i in range(4):
+                text = 'multi %d' %i    # Different text on each call
+                warnings.warn(text)
+                self.assertEqual(str(w.message), text)
+                self.assert_(w.category is UserWarning)
 
     def test_warn_specific_category(self):
-        text = 'None'
-        for category in [DeprecationWarning, FutureWarning,
-                    PendingDeprecationWarning, RuntimeWarning,
-                    SyntaxWarning, UserWarning, Warning]:
-            if category.__name__ in self.ignored:
-                text = 'filtered out' + category.__name__
-                warnings.warn(text, category)
-                self.assertNotEqual(msg.message, text)
-            else:
-                text = 'unfiltered %s' % category.__name__
-                warnings.warn(text, category)
-                self.assertEqual(msg.message, text)
-                self.assertEqual(msg.category, category.__name__)
+        with test_support.catch_warning() as w:
+            text = 'None'
+            for category in [DeprecationWarning, FutureWarning,
+                        PendingDeprecationWarning, RuntimeWarning,
+                        SyntaxWarning, UserWarning, Warning]:
+                if category.__name__ in self.ignored:
+                    text = 'filtered out' + category.__name__
+                    warnings.warn(text, category)
+                    self.assertNotEqual(w.message, text)
+                else:
+                    text = 'unfiltered %s' % category.__name__
+                    warnings.warn(text, category)
+                    self.assertEqual(str(w.message), text)
+                    self.assert_(w.category is category)
 
     def test_filtering(self):
+        with test_support.catch_warning() as w:
+            warnings.filterwarnings("error", "", Warning, "", 0)
+            self.assertRaises(UserWarning, warnings.warn, 'convert to error')
+
+            warnings.resetwarnings()
+            text = 'handle normally'
+            warnings.warn(text)
+            self.assertEqual(str(w.message), text)
+            self.assert_(w.category is UserWarning)
 
-        warnings.filterwarnings("error", "", Warning, "", 0)
-        self.assertRaises(UserWarning, warnings.warn, 'convert to error')
+            warnings.filterwarnings("ignore", "", Warning, "", 0)
+            text = 'filtered out'
+            warnings.warn(text)
+            self.assertNotEqual(str(w.message), text)
 
-        warnings.resetwarnings()
-        text = 'handle normally'
-        warnings.warn(text)
-        self.assertEqual(msg.message, text)
-        self.assertEqual(msg.category, 'UserWarning')
-
-        warnings.filterwarnings("ignore", "", Warning, "", 0)
-        text = 'filtered out'
-        warnings.warn(text)
-        self.assertNotEqual(msg.message, text)
-
-        warnings.resetwarnings()
-        warnings.filterwarnings("error", "hex*", Warning, "", 0)
-        self.assertRaises(UserWarning, warnings.warn, 'hex/oct')
-        text = 'nonmatching text'
-        warnings.warn(text)
-        self.assertEqual(msg.message, text)
-        self.assertEqual(msg.category, 'UserWarning')
+            warnings.resetwarnings()
+            warnings.filterwarnings("error", "hex*", Warning, "", 0)
+            self.assertRaises(UserWarning, warnings.warn, 'hex/oct')
+            text = 'nonmatching text'
+            warnings.warn(text)
+            self.assertEqual(str(w.message), text)
+            self.assert_(w.category is UserWarning)
 
     def test_options(self):
         # Uses the private _setoption() function to test the parsing
         # of command-line warning arguments
-        self.assertRaises(warnings._OptionError,
-                          warnings._setoption, '1:2:3:4:5:6')
-        self.assertRaises(warnings._OptionError,
-                          warnings._setoption, 'bogus::Warning')
-        self.assertRaises(warnings._OptionError,
-                          warnings._setoption, 'ignore:2::4:-5')
-        warnings._setoption('error::Warning::0')
-        self.assertRaises(UserWarning, warnings.warn, 'convert to error')
+        with test_support.guard_warnings_filter():
+            self.assertRaises(warnings._OptionError,
+                              warnings._setoption, '1:2:3:4:5:6')
+            self.assertRaises(warnings._OptionError,
+                              warnings._setoption, 'bogus::Warning')
+            self.assertRaises(warnings._OptionError,
+                              warnings._setoption, 'ignore:2::4:-5')
+            warnings._setoption('error::Warning::0')
+            self.assertRaises(UserWarning, warnings.warn, 'convert to error')
+
+    def test_filename(self):
+        with test_support.catch_warning() as w:
+            warning_tests.inner("spam1")
+            self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
+            warning_tests.outer("spam2")
+            self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
+
+    def test_stacklevel(self):
+        # Test stacklevel argument
+        # make sure all messages are different, so the warning won't be skipped
+        with test_support.catch_warning() as w:
+            warning_tests.inner("spam3", stacklevel=1)
+            self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
+            warning_tests.outer("spam4", stacklevel=1)
+            self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
+
+            warning_tests.inner("spam5", stacklevel=2)
+            self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
+            warning_tests.outer("spam6", stacklevel=2)
+            self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
+
+            warning_tests.inner("spam7", stacklevel=9999)
+            self.assertEqual(os.path.basename(w.filename), "sys")
 
 
 def test_main(verbose=None):

Modified: python/branches/p3yk-noslice/Lib/test/test_weakref.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_weakref.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_weakref.py	Wed Jul 11 15:40:56 2007
@@ -104,9 +104,9 @@
         def check(proxy):
             proxy.bar
 
-        self.assertRaises(weakref.ReferenceError, check, ref1)
-        self.assertRaises(weakref.ReferenceError, check, ref2)
-        self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C()))
+        self.assertRaises(ReferenceError, check, ref1)
+        self.assertRaises(ReferenceError, check, ref2)
+        self.assertRaises(ReferenceError, bool, weakref.proxy(C()))
         self.assert_(self.cbcalled == 2)
 
     def check_basic_ref(self, factory):
@@ -651,10 +651,10 @@
         class MyRef(weakref.ref):
             def __init__(self, ob, callback=None, value=42):
                 self.value = value
-                super(MyRef, self).__init__(ob, callback)
+                super().__init__(ob, callback)
             def __call__(self):
                 self.called = True
-                return super(MyRef, self).__call__()
+                return super().__call__()
         o = Object("foo")
         mr = MyRef(o, value=24)
         self.assert_(mr() is o)
@@ -740,15 +740,15 @@
         items2 = dict.copy().items()
         items1.sort()
         items2.sort()
-        self.assert_(items1 == items2,
+        self.assertEqual(items1, items2,
                      "cloning of weak-valued dictionary did not work!")
         del items1, items2
-        self.assert_(len(dict) == self.COUNT)
+        self.assertEqual(len(dict), self.COUNT)
         del objects[0]
-        self.assert_(len(dict) == (self.COUNT - 1),
+        self.assertEqual(len(dict), self.COUNT - 1,
                      "deleting object did not cause dictionary update")
         del objects, o
-        self.assert_(len(dict) == 0,
+        self.assertEqual(len(dict), 0,
                      "deleting the values did not clear the dictionary")
         # regression on SF bug #447152:
         dict = weakref.WeakValueDictionary()
@@ -841,7 +841,7 @@
         items = dict.items()
         for item in dict.items():
             items.remove(item)
-        self.assert_(len(items) == 0, "iteritems() did not touch all items")
+        self.assert_(len(items) == 0, "items() did not touch all items")
 
         # key iterator, via __iter__():
         keys = list(dict.keys())
@@ -875,14 +875,14 @@
 
     def make_weak_keyed_dict(self):
         dict = weakref.WeakKeyDictionary()
-        objects = map(Object, range(self.COUNT))
+        objects = list(map(Object, range(self.COUNT)))
         for o in objects:
             dict[o] = o.arg
         return dict, objects
 
     def make_weak_valued_dict(self):
         dict = weakref.WeakValueDictionary()
-        objects = map(Object, range(self.COUNT))
+        objects = list(map(Object, range(self.COUNT)))
         for o in objects:
             dict[o.arg] = o
         return dict, objects
@@ -1091,7 +1091,7 @@
 >>> import weakref
 >>> class ExtendedRef(weakref.ref):
 ...     def __init__(self, ob, callback=None, **annotations):
-...         super(ExtendedRef, self).__init__(ob, callback)
+...         super().__init__(ob, callback)
 ...         self.__counter = 0
 ...         for k, v in annotations.items():
 ...             setattr(self, k, v)
@@ -1099,12 +1099,12 @@
 ...         '''Return a pair containing the referent and the number of
 ...         times the reference has been called.
 ...         '''
-...         ob = super(ExtendedRef, self).__call__()
+...         ob = super().__call__()
 ...         if ob is not None:
 ...             self.__counter += 1
 ...             ob = (ob, self.__counter)
 ...         return ob
-... 
+...
 >>> class A:   # not in docs from here, just testing the ExtendedRef
 ...     pass
 ...

Modified: python/branches/p3yk-noslice/Lib/test/test_winsound.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_winsound.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_winsound.py	Wed Jul 11 15:40:56 2007
@@ -19,7 +19,7 @@
         winsound.Beep(32767, 75)
 
     def test_increasingfrequency(self):
-        for i in xrange(100, 2000, 100):
+        for i in range(100, 2000, 100):
             winsound.Beep(i, 75)
 
 class MessageBeepTest(unittest.TestCase):

Modified: python/branches/p3yk-noslice/Lib/test/test_wsgiref.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_wsgiref.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_wsgiref.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 from __future__ import nested_scopes    # Backward compat for 2.1
-from unittest import TestSuite, TestCase, makeSuite
+from unittest import TestCase
 from wsgiref.util import setup_testing_defaults
 from wsgiref.headers import Headers
 from wsgiref.handlers import BaseHandler, BaseCGIHandler
@@ -11,6 +11,7 @@
 from SocketServer import BaseServer
 import re, sys
 
+from test import test_support
 
 class MockServer(WSGIServer):
     """Non-socket HTTP server"""
@@ -108,13 +109,13 @@
         it = make_it()
         if not iter(it) is it: raise AssertionError
         for item in match:
-            if not it.next()==item: raise AssertionError
+            if not next(it) == item: raise AssertionError
         try:
-            it.next()
+            next(it)
         except StopIteration:
             pass
         else:
-            raise AssertionError("Too many items from .next()",it)
+            raise AssertionError("Too many items from .__next__()", it)
 
 
 
@@ -575,11 +576,7 @@
 # This epilogue is needed for compatibility with the Python 2.5 regrtest module
 
 def test_main():
-    import unittest
-    from test.test_support import run_suite
-    run_suite(
-        unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])
-    )
+    test_support.run_unittest(__name__)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_xdrlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xdrlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_xdrlib.py	Wed Jul 11 15:40:56 2007
@@ -44,7 +44,7 @@
         self.assertAlmostEqual(up.unpack_float(), 1.9)
         self.assertAlmostEqual(up.unpack_double(), 1.9)
         self.assertEqual(up.unpack_string(), s)
-        self.assertEqual(up.unpack_list(up.unpack_uint), range(5))
+        self.assertEqual(up.unpack_list(up.unpack_uint), list(range(5)))
         self.assertEqual(up.unpack_array(up.unpack_string), a)
         up.done()
         self.assertRaises(EOFError, up.unpack_uint)

Modified: python/branches/p3yk-noslice/Lib/test/test_xml_etree.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xml_etree.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_xml_etree.py	Wed Jul 11 15:40:56 2007
@@ -36,7 +36,7 @@
     """
 
 def check_method(method):
-    if not callable(method):
+    if not hasattr(method, '__call__'):
         print(method, "not callable")
 
 def serialize(ET, elem, encoding=None):
@@ -53,7 +53,7 @@
     return elem.tag
 
 def summarize_list(seq):
-    return map(summarize, seq)
+    return list(map(summarize, seq))
 
 def interface():
     """

Modified: python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py	Wed Jul 11 15:40:56 2007
@@ -34,7 +34,7 @@
     """
 
 def check_method(method):
-    if not callable(method):
+    if not hasattr(method, '__call__'):
         print(method, "not callable")
 
 def serialize(ET, elem, encoding=None):
@@ -51,7 +51,7 @@
     return elem.tag
 
 def summarize_list(seq):
-    return map(summarize, seq)
+    return list(map(summarize, seq))
 
 def interface():
     """

Deleted: /python/branches/p3yk-noslice/Lib/test/test_xmllib.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_xmllib.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,51 +0,0 @@
-'''Test module to thest the xmllib module.
-   Sjoerd Mullender
-'''
-
-testdoc = """\
-<?xml version="1.0" encoding="UTF-8" standalone='yes' ?>
-<!-- comments aren't allowed before the <?xml?> tag,
-     but they are allowed before the <!DOCTYPE> tag -->
-<?processing instructions are allowed in the same places as comments ?>
-<!DOCTYPE greeting [
-  <!ELEMENT greeting (#PCDATA)>
-]>
-<greeting>Hello, world!</greeting>
-"""
-
-nsdoc = "<foo xmlns='URI' attr='val'/>"
-
-import warnings
-warnings.filterwarnings("ignore", ".* xmllib .* obsolete.*",
-                        DeprecationWarning, r'xmllib$')
-
-from test import test_support
-import unittest
-import xmllib
-
-class XMLParserTestCase(unittest.TestCase):
-
-    def test_simple(self):
-        parser = xmllib.XMLParser()
-        for c in testdoc:
-            parser.feed(c)
-        parser.close()
-
-    def test_default_namespace(self):
-        class H(xmllib.XMLParser):
-            def unknown_starttag(self, name, attr):
-                self.name, self.attr = name, attr
-        h=H()
-        h.feed(nsdoc)
-        h.close()
-        # The default namespace applies to elements...
-        self.assertEquals(h.name, "URI foo")
-        # but not to attributes
-        self.assertEquals(h.attr, {'attr':'val'})
-
-
-def test_main():
-    test_support.run_unittest(XMLParserTestCase)
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py	Wed Jul 11 15:40:56 2007
@@ -17,14 +17,14 @@
           'ashortlong': 2,
           'anotherlist': ['.zyx.41'],
           'abase64': xmlrpclib.Binary("my dog has fleas"),
-          'boolean': xmlrpclib.False,
+          'boolean': False,
           'unicode': u'\u4000\u6000\u8000',
           u'ukey\u4000': 'regular value',
           'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
           'datetime2': xmlrpclib.DateTime(
-                        (2005, 02, 10, 11, 41, 23, 0, 1, -1)),
+                        (2005, 2, 10, 11, 41, 23, 0, 1, -1)),
           'datetime3': xmlrpclib.DateTime(
-                        datetime.datetime(2005, 02, 10, 11, 41, 23)),
+                        datetime.datetime(2005, 2, 10, 11, 41, 23)),
           }]
 
 class XMLRPCTestCase(unittest.TestCase):
@@ -38,7 +38,7 @@
         # by the marshalling code.  This can't be done via test_dump_load()
         # since with use_datetime set to 1 the unmarshaller would create
         # datetime objects for the 'datetime[123]' keys as well
-        dt = datetime.datetime(2005, 02, 10, 11, 41, 23)
+        dt = datetime.datetime(2005, 2, 10, 11, 41, 23)
         s = xmlrpclib.dumps((dt,))
         (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
         self.assertEquals(newdt, dt)
@@ -51,7 +51,7 @@
         # This checks that an unwrapped datetime.date object can be handled
         # by the marshalling code.  This can't be done via test_dump_load()
         # since the unmarshaller produces a datetime object
-        d = datetime.datetime(2005, 02, 10, 11, 41, 23).date()
+        d = datetime.datetime(2005, 2, 10, 11, 41, 23).date()
         s = xmlrpclib.dumps((d,))
         (newd,), m = xmlrpclib.loads(s, use_datetime=1)
         self.assertEquals(newd.date(), d)
@@ -65,7 +65,7 @@
         # This checks that an unwrapped datetime.time object can be handled
         # by the marshalling code.  This can't be done via test_dump_load()
         # since the unmarshaller produces a datetime object
-        t = datetime.datetime(2005, 02, 10, 11, 41, 23).time()
+        t = datetime.datetime(2005, 2, 10, 11, 41, 23).time()
         s = xmlrpclib.dumps((t,))
         (newt,), m = xmlrpclib.loads(s, use_datetime=1)
         today = datetime.datetime.now().date().strftime("%Y%m%d")
@@ -133,10 +133,11 @@
                   """
 
         # sys.setdefaultencoding() normally doesn't exist after site.py is
-        # loaded.  reload(sys) is the way to get it back.
+        # loaded.  Re-initializing sys again is the way to get it back. :-(
         old_encoding = sys.getdefaultencoding()
         setdefaultencoding_existed = hasattr(sys, "setdefaultencoding")
-        reload(sys) # ugh!
+        import imp
+        imp.init_builtin('sys')
         sys.setdefaultencoding("iso-8859-1")
         try:
             (s, d), m = xmlrpclib.loads(utf8)

Modified: python/branches/p3yk-noslice/Lib/test/test_xrange.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xrange.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_xrange.py	Wed Jul 11 15:40:56 2007
@@ -9,56 +9,52 @@
 
 class XrangeTest(unittest.TestCase):
     def test_xrange(self):
-        self.assertEqual(list(xrange(3)), [0, 1, 2])
-        self.assertEqual(list(xrange(1, 5)), [1, 2, 3, 4])
-        self.assertEqual(list(xrange(0)), [])
-        self.assertEqual(list(xrange(-3)), [])
-        self.assertEqual(list(xrange(1, 10, 3)), [1, 4, 7])
-        self.assertEqual(list(xrange(5, -5, -3)), [5, 2, -1, -4])
+        self.assertEqual(list(range(3)), [0, 1, 2])
+        self.assertEqual(list(range(1, 5)), [1, 2, 3, 4])
+        self.assertEqual(list(range(0)), [])
+        self.assertEqual(list(range(-3)), [])
+        self.assertEqual(list(range(1, 10, 3)), [1, 4, 7])
+        self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4])
 
         a = 10
         b = 100
         c = 50
 
-        self.assertEqual(list(xrange(a, a+2)), [a, a+1])
-        self.assertEqual(list(xrange(a+2, a, -1)), [a+2, a+1])
-        self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2])
+        self.assertEqual(list(range(a, a+2)), [a, a+1])
+        self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1])
+        self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2])
 
-        seq = list(xrange(a, b, c))
+        seq = list(range(a, b, c))
         self.assert_(a in seq)
         self.assert_(b not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = list(xrange(b, a, -c))
+        seq = list(range(b, a, -c))
         self.assert_(b in seq)
         self.assert_(a not in seq)
         self.assertEqual(len(seq), 2)
 
-        seq = list(xrange(-a, -b, -c))
+        seq = list(range(-a, -b, -c))
         self.assert_(-a in seq)
         self.assert_(-b not in seq)
         self.assertEqual(len(seq), 2)
 
-        self.assertRaises(TypeError, xrange)
-        self.assertRaises(TypeError, xrange, 1, 2, 3, 4)
-        self.assertRaises(ValueError, xrange, 1, 2, 0)
+        self.assertRaises(TypeError, range)
+        self.assertRaises(TypeError, range, 1, 2, 3, 4)
+        self.assertRaises(ValueError, range, 1, 2, 0)
 
-        self.assertRaises(TypeError, xrange, 0.0, 2, 1)
-        self.assertRaises(TypeError, xrange, 1, 2.0, 1)
-        self.assertRaises(TypeError, xrange, 1, 2, 1.0)
-        self.assertRaises(TypeError, xrange, 1e100, 1e101, 1e101)
+        self.assertRaises(TypeError, range, 0.0, 2, 1)
+        self.assertRaises(TypeError, range, 1, 2.0, 1)
+        self.assertRaises(TypeError, range, 1, 2, 1.0)
+        self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
 
-        self.assertRaises(TypeError, xrange, 0, "spam")
-        self.assertRaises(TypeError, xrange, 0, 42, "spam")
+        self.assertRaises(TypeError, range, 0, "spam")
+        self.assertRaises(TypeError, range, 0, 42, "spam")
 
-        self.assertEqual(len(xrange(0, sys.maxint, sys.maxint-1)), 2)
+        self.assertEqual(len(range(0, sys.maxint, sys.maxint-1)), 2)
 
-        self.assertRaises(OverflowError, xrange, -sys.maxint, sys.maxint)
-        self.assertRaises(OverflowError, xrange, 0, 2*sys.maxint)
-
-        r = xrange(-sys.maxint, sys.maxint, 2)
+        r = range(-sys.maxint, sys.maxint, 2)
         self.assertEqual(len(r), sys.maxint)
-        self.assertRaises(OverflowError, xrange, -sys.maxint-1, sys.maxint, 2)
 
 def test_main():
     test.test_support.run_unittest(XrangeTest)

Modified: python/branches/p3yk-noslice/Lib/test/test_zipfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zipfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_zipfile.py	Wed Jul 11 15:40:56 2007
@@ -4,26 +4,30 @@
 except ImportError:
     zlib = None
 
-import zipfile, os, unittest, sys, shutil
+import zipfile, os, unittest, sys, shutil, struct
 
 from StringIO import StringIO
 from tempfile import TemporaryFile
+from random import randint, random
 
+import test.test_support as support
 from test.test_support import TESTFN, run_unittest
 
 TESTFN2 = TESTFN + "2"
+FIXEDTEST_SIZE = 10
 
 class TestsWithSourceFile(unittest.TestCase):
     def setUp(self):
-        line_gen = ("Test of zipfile line %d." % i for i in range(0, 1000))
-        self.data = '\n'.join(line_gen)
+        self.line_gen = ("Zipfile test line %d. random float: %f" % (i, random())
+                          for i in range(FIXEDTEST_SIZE))
+        self.data = '\n'.join(self.line_gen) + '\n'
 
         # Make a source file with some lines
         fp = open(TESTFN, "wb")
         fp.write(self.data)
         fp.close()
 
-    def zipTest(self, f, compression):
+    def makeTestArchive(self, f, compression):
         # Create the ZIP archive
         zipfp = zipfile.ZipFile(f, "w", compression)
         zipfp.write(TESTFN, "another"+os.extsep+"name")
@@ -31,6 +35,9 @@
         zipfp.writestr("strfile", self.data)
         zipfp.close()
 
+    def zipTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
         # Read the ZIP archive
         zipfp = zipfile.ZipFile(f, "r", compression)
         self.assertEqual(zipfp.read(TESTFN), self.data)
@@ -85,22 +92,144 @@
 
         # Check that testzip doesn't raise an exception
         zipfp.testzip()
+        zipfp.close()
 
+    def testStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipTest(f, zipfile.ZIP_STORED)
+
+    def zipOpenTest(self, f, compression):
+        self.makeTestArchive(f, compression)
 
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r", compression)
+        zipdata1 = []
+        zipopen1 = zipfp.open(TESTFN)
+        while 1:
+            read_data = zipopen1.read(256)
+            if not read_data:
+                break
+            zipdata1.append(read_data)
+
+        zipdata2 = []
+        zipopen2 = zipfp.open("another"+os.extsep+"name")
+        while 1:
+            read_data = zipopen2.read(256)
+            if not read_data:
+                break
+            zipdata2.append(read_data)
+
+        self.assertEqual(''.join(zipdata1), self.data)
+        self.assertEqual(''.join(zipdata2), self.data)
         zipfp.close()
 
+    def testOpenStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipOpenTest(f, zipfile.ZIP_STORED)
 
+    def zipRandomOpenTest(self, f, compression):
+        self.makeTestArchive(f, compression)
 
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r", compression)
+        zipdata1 = []
+        zipopen1 = zipfp.open(TESTFN)
+        while 1:
+            read_data = zipopen1.read(randint(1, 1024))
+            if not read_data:
+                break
+            zipdata1.append(read_data)
 
-    def testStored(self):
+        self.assertEqual(''.join(zipdata1), self.data)
+        zipfp.close()
+
+    def testRandomOpenStored(self):
         for f in (TESTFN2, TemporaryFile(), StringIO()):
-            self.zipTest(f, zipfile.ZIP_STORED)
+            self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
+
+    def zipReadlineTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        zipopen = zipfp.open(TESTFN)
+        for line in self.line_gen:
+            linedata = zipopen.readline()
+            self.assertEqual(linedata, line + '\n')
+
+        zipfp.close()
+
+    def zipReadlinesTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        ziplines = zipfp.open(TESTFN).readlines()
+        for line, zipline in zip(self.line_gen, ziplines):
+            self.assertEqual(zipline, line + '\n')
+
+        zipfp.close()
+
+    def zipIterlinesTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
+            self.assertEqual(zipline, line + '\n')
+
+        zipfp.close()
+
+    def testReadlineStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipReadlineTest(f, zipfile.ZIP_STORED)
+
+    def testReadlinesStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipReadlinesTest(f, zipfile.ZIP_STORED)
+
+    def testIterlinesStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipIterlinesTest(f, zipfile.ZIP_STORED)
 
     if zlib:
         def testDeflated(self):
             for f in (TESTFN2, TemporaryFile(), StringIO()):
                 self.zipTest(f, zipfile.ZIP_DEFLATED)
 
+        def testOpenDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
+
+        def testRandomOpenDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
+
+        def testReadlineDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
+
+        def testReadlinesDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
+
+        def testIterlinesDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
+
+        def testLowCompression(self):
+            # Checks for cases where compressed data is larger than original
+            # Create the ZIP archive
+            zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
+            zipfp.writestr("strfile", '12')
+            zipfp.close()
+
+            # Get an open object for strfile
+            zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
+            openobj = zipfp.open("strfile")
+            self.assertEqual(openobj.read(1), '1')
+            self.assertEqual(openobj.read(1), '2')
+
     def testAbsoluteArcnames(self):
         zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
         zipfp.write(TESTFN, "/absolute")
@@ -110,7 +239,6 @@
         self.assertEqual(zipfp.namelist(), ["absolute"])
         zipfp.close()
 
-
     def tearDown(self):
         os.remove(TESTFN)
         os.remove(TESTFN2)
@@ -123,7 +251,7 @@
         self._limit = zipfile.ZIP64_LIMIT
         zipfile.ZIP64_LIMIT = 5
 
-        line_gen = ("Test of zipfile line %d." % i for i in range(0, 1000))
+        line_gen = ("Test of zipfile line %d." % i for i in range(0, FIXEDTEST_SIZE))
         self.data = '\n'.join(line_gen)
 
         # Make a source file with some lines
@@ -310,10 +438,10 @@
     def testCreateNonExistentFileForAppend(self):
         if os.path.exists(TESTFN):
             os.unlink(TESTFN)
-            
+
         filename = 'testfile.txt'
         content = 'hello, world. this is some content.'
-        
+
         try:
             zf = zipfile.ZipFile(TESTFN, 'a')
             zf.writestr(filename, content)
@@ -326,9 +454,7 @@
         zf = zipfile.ZipFile(TESTFN, 'r')
         self.assertEqual(zf.read(filename), content)
         zf.close()
-        
-        os.unlink(TESTFN)
-        
+
     def testCloseErroneousFile(self):
         # This test checks that the ZipFile constructor closes the file object
         # it opens if there's an error in the file.  If it doesn't, the traceback
@@ -342,7 +468,25 @@
         try:
             zf = zipfile.ZipFile(TESTFN)
         except zipfile.BadZipfile:
-            os.unlink(TESTFN)
+            pass
+
+    def testIsZipErroneousFile(self):
+        # This test checks that the is_zipfile function correctly identifies
+        # a file that is not a zip file
+        fp = open(TESTFN, "w")
+        fp.write("this is not a legal zip file\n")
+        fp.close()
+        chk = zipfile.is_zipfile(TESTFN)
+        self.assert_(chk is False)
+
+    def testIsZipValidFile(self):
+        # This test checks that the is_zipfile function correctly identifies
+        # a file that is a zip file
+        zipf = zipfile.ZipFile(TESTFN, mode="w")
+        zipf.writestr("foo.txt", "O, for a Muse of Fire!")
+        zipf.close()
+        chk = zipfile.is_zipfile(TESTFN)
+        self.assert_(chk is True)
 
     def testNonExistentFileRaisesIOError(self):
         # make sure we don't raise an AttributeError when a partially-constructed
@@ -371,6 +515,9 @@
         # and report that the first file in the archive was corrupt.
         self.assertRaises(RuntimeError, zipf.testzip)
 
+    def tearDown(self):
+        support.unlink(TESTFN)
+        support.unlink(TESTFN2)
 
 class DecryptionTests(unittest.TestCase):
     # This test checks that ZIP decryption works. Since the library does not
@@ -406,15 +553,265 @@
     def testBadPassword(self):
         self.zip.setpassword("perl")
         self.assertRaises(RuntimeError, self.zip.read, "test.txt")
-            
+
     def testGoodPassword(self):
         self.zip.setpassword("python")
         self.assertEquals(self.zip.read("test.txt"), self.plain)
 
+
+class TestsWithRandomBinaryFiles(unittest.TestCase):
+    def setUp(self):
+        datacount = randint(16, 64)*1024 + randint(1, 1024)
+        self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in range(datacount)))
+
+        # Make a source file with some lines
+        fp = open(TESTFN, "wb")
+        fp.write(self.data)
+        fp.close()
+
+    def tearDown(self):
+        support.unlink(TESTFN)
+        support.unlink(TESTFN2)
+
+    def makeTestArchive(self, f, compression):
+        # Create the ZIP archive
+        zipfp = zipfile.ZipFile(f, "w", compression)
+        zipfp.write(TESTFN, "another"+os.extsep+"name")
+        zipfp.write(TESTFN, TESTFN)
+        zipfp.close()
+
+    def zipTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r", compression)
+        testdata = zipfp.read(TESTFN)
+        self.assertEqual(len(testdata), len(self.data))
+        self.assertEqual(testdata, self.data)
+        self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
+        zipfp.close()
+
+    def testStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipTest(f, zipfile.ZIP_STORED)
+
+    def zipOpenTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r", compression)
+        zipdata1 = []
+        zipopen1 = zipfp.open(TESTFN)
+        while 1:
+            read_data = zipopen1.read(256)
+            if not read_data:
+                break
+            zipdata1.append(read_data)
+
+        zipdata2 = []
+        zipopen2 = zipfp.open("another"+os.extsep+"name")
+        while 1:
+            read_data = zipopen2.read(256)
+            if not read_data:
+                break
+            zipdata2.append(read_data)
+
+        testdata1 = ''.join(zipdata1)
+        self.assertEqual(len(testdata1), len(self.data))
+        self.assertEqual(testdata1, self.data)
+
+        testdata2 = ''.join(zipdata2)
+        self.assertEqual(len(testdata1), len(self.data))
+        self.assertEqual(testdata1, self.data)
+        zipfp.close()
+
+    def testOpenStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipOpenTest(f, zipfile.ZIP_STORED)
+
+    def zipRandomOpenTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r", compression)
+        zipdata1 = []
+        zipopen1 = zipfp.open(TESTFN)
+        while 1:
+            read_data = zipopen1.read(randint(1, 1024))
+            if not read_data:
+                break
+            zipdata1.append(read_data)
+
+        testdata = ''.join(zipdata1)
+        self.assertEqual(len(testdata), len(self.data))
+        self.assertEqual(testdata, self.data)
+        zipfp.close()
+
+    def testRandomOpenStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
+
+class TestsWithMultipleOpens(unittest.TestCase):
+    def setUp(self):
+        # Create the ZIP archive
+        zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
+        zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
+        zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
+        zipfp.close()
+
+    def testSameFile(self):
+        # Verify that (when the ZipFile is in control of creating file objects)
+        # multiple open() calls can be made without interfering with each other.
+        zipf = zipfile.ZipFile(TESTFN2, mode="r")
+        zopen1 = zipf.open('ones')
+        zopen2 = zipf.open('ones')
+        data1 = zopen1.read(500)
+        data2 = zopen2.read(500)
+        data1 += zopen1.read(500)
+        data2 += zopen2.read(500)
+        self.assertEqual(data1, data2)
+        zipf.close()
+
+    def testDifferentFile(self):
+        # Verify that (when the ZipFile is in control of creating file objects)
+        # multiple open() calls can be made without interfering with each other.
+        zipf = zipfile.ZipFile(TESTFN2, mode="r")
+        zopen1 = zipf.open('ones')
+        zopen2 = zipf.open('twos')
+        data1 = zopen1.read(500)
+        data2 = zopen2.read(500)
+        data1 += zopen1.read(500)
+        data2 += zopen2.read(500)
+        self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
+        self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
+        zipf.close()
+
+    def testInterleaved(self):
+        # Verify that (when the ZipFile is in control of creating file objects)
+        # multiple open() calls can be made without interfering with each other.
+        zipf = zipfile.ZipFile(TESTFN2, mode="r")
+        zopen1 = zipf.open('ones')
+        data1 = zopen1.read(500)
+        zopen2 = zipf.open('twos')
+        data2 = zopen2.read(500)
+        data1 += zopen1.read(500)
+        data2 += zopen2.read(500)
+        self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
+        self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
+        zipf.close()
+
+    def tearDown(self):
+        os.remove(TESTFN2)
+
+
+class UniversalNewlineTests(unittest.TestCase):
+    def setUp(self):
+        self.line_gen = ["Test of zipfile line %d." % i for i in range(FIXEDTEST_SIZE)]
+        self.seps = ('\r', '\r\n', '\n')
+        self.arcdata, self.arcfiles = {}, {}
+        for n, s in enumerate(self.seps):
+            self.arcdata[s] = s.join(self.line_gen) + s
+            self.arcfiles[s] = '%s-%d' % (TESTFN, n)
+            open(self.arcfiles[s], "wb").write(self.arcdata[s])
+
+    def makeTestArchive(self, f, compression):
+        # Create the ZIP archive
+        zipfp = zipfile.ZipFile(f, "w", compression)
+        for fn in self.arcfiles.values():
+            zipfp.write(fn, fn)
+        zipfp.close()
+
+    def readTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        for sep, fn in self.arcfiles.items():
+            zipdata = zipfp.open(fn, "rU").read()
+            self.assertEqual(self.arcdata[sep], zipdata)
+
+        zipfp.close()
+
+    def readlineTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        for sep, fn in self.arcfiles.items():
+            zipopen = zipfp.open(fn, "rU")
+            for line in self.line_gen:
+                linedata = zipopen.readline()
+                self.assertEqual(linedata, line + '\n')
+
+        zipfp.close()
+
+    def readlinesTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        for sep, fn in self.arcfiles.items():
+            ziplines = zipfp.open(fn, "rU").readlines()
+            for line, zipline in zip(self.line_gen, ziplines):
+                self.assertEqual(zipline, line + '\n')
+
+        zipfp.close()
+
+    def iterlinesTest(self, f, compression):
+        self.makeTestArchive(f, compression)
+
+        # Read the ZIP archive
+        zipfp = zipfile.ZipFile(f, "r")
+        for sep, fn in self.arcfiles.items():
+            for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
+                self.assertEqual(zipline, line + '\n')
+
+        zipfp.close()
+
+    def testReadStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.readTest(f, zipfile.ZIP_STORED)
+
+    def testReadlineStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.readlineTest(f, zipfile.ZIP_STORED)
+
+    def testReadlinesStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.readlinesTest(f, zipfile.ZIP_STORED)
+
+    def testIterlinesStored(self):
+        for f in (TESTFN2, TemporaryFile(), StringIO()):
+            self.iterlinesTest(f, zipfile.ZIP_STORED)
+
+    if zlib:
+        def testReadDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.readTest(f, zipfile.ZIP_DEFLATED)
+
+        def testReadlineDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.readlineTest(f, zipfile.ZIP_DEFLATED)
+
+        def testReadlinesDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.readlinesTest(f, zipfile.ZIP_DEFLATED)
+
+        def testIterlinesDeflated(self):
+            for f in (TESTFN2, TemporaryFile(), StringIO()):
+                self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
+
+    def tearDown(self):
+        for sep, fn in self.arcfiles.items():
+            os.remove(fn)
+        support.unlink(TESTFN)
+        support.unlink(TESTFN2)
+
+
 def test_main():
-    run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, 
-                 PyZipFileTests, DecryptionTests)
-    #run_unittest(TestZip64InSmallFiles)
+    run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
+                 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
+                 UniversalNewlineTests, TestsWithRandomBinaryFiles)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/p3yk-noslice/Lib/test/test_zipfile64.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zipfile64.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_zipfile64.py	Wed Jul 11 15:40:56 2007
@@ -33,9 +33,7 @@
 class TestsWithSourceFile(unittest.TestCase):
     def setUp(self):
         # Create test data.
-        # xrange() is important here -- don't want to create immortal space
-        # for a million ints.
-        line_gen = ("Test of zipfile line %d." % i for i in xrange(1000000))
+        line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
         self.data = '\n'.join(line_gen)
 
         # And write it to a file.

Modified: python/branches/p3yk-noslice/Lib/test/test_zipimport.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zipimport.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_zipimport.py	Wed Jul 11 15:40:56 2007
@@ -364,7 +364,7 @@
         finally:
             # If we leave "the read-only bit" set on Windows, nothing can
             # delete TESTMOD, and later tests suffer bogus failures.
-            os.chmod(TESTMOD, 0666)
+            os.chmod(TESTMOD, 0o666)
             test_support.unlink(TESTMOD)
 
     def testNotZipFile(self):

Modified: python/branches/p3yk-noslice/Lib/test/test_zlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/test_zlib.py	Wed Jul 11 15:40:56 2007
@@ -3,22 +3,6 @@
 import zlib
 import random
 
-# print test_support.TESTFN
-
-def getbuf():
-    # This was in the original.  Avoid non-repeatable sources.
-    # Left here (unused) in case something wants to be done with it.
-    import imp
-    try:
-        t = imp.find_module('test_zlib')
-        file = t[0]
-    except ImportError:
-        file = open(__file__)
-    buf = file.read() * 8
-    file.close()
-    return buf
-
-
 
 class ChecksumTestCase(unittest.TestCase):
     # checksum test cases
@@ -461,21 +445,3 @@
 
 if __name__ == "__main__":
     test_main()
-
-def test(tests=''):
-    if not tests: tests = 'o'
-    testcases = []
-    if 'k' in tests: testcases.append(ChecksumTestCase)
-    if 'x' in tests: testcases.append(ExceptionTestCase)
-    if 'c' in tests: testcases.append(CompressTestCase)
-    if 'o' in tests: testcases.append(CompressObjectTestCase)
-    test_support.run_unittest(*testcases)
-
-if False:
-    import sys
-    sys.path.insert(1, '/Py23Src/python/dist/src/Lib/test')
-    import test_zlib as tz
-    ts, ut = tz.test_support, tz.unittest
-    su = ut.TestSuite()
-    su.addTest(ut.makeSuite(tz.CompressTestCase))
-    ts.run_suite(su)

Modified: python/branches/p3yk-noslice/Lib/test/testtar.tar
==============================================================================
Binary files. No diff available.

Modified: python/branches/p3yk-noslice/Lib/test/tf_inherit_check.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/tf_inherit_check.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/tf_inherit_check.py	Wed Jul 11 15:40:56 2007
@@ -19,7 +19,7 @@
             sys.stderr.write("fd %d is open in child" % fd)
         sys.exit(1)
 
-except StandardError:
+except Exception:
     if verbose:
         raise
     sys.exit(1)

Modified: python/branches/p3yk-noslice/Lib/test/time_hashlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/time_hashlib.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/time_hashlib.py	Wed Jul 11 15:40:56 2007
@@ -14,7 +14,7 @@
 
     localCF = creatorFunc
     start = time.time()
-    for f in xrange(iterations):
+    for f in range(iterations):
         x = localCF(longStr).digest()
     end = time.time()
 
@@ -22,7 +22,7 @@
 
 def test_create():
     start = time.time()
-    for f in xrange(20000):
+    for f in range(20000):
         d = creatorFunc()
     end = time.time()
 
@@ -30,7 +30,7 @@
 
 def test_zero():
     start = time.time()
-    for f in xrange(20000):
+    for f in range(20000):
         x = creatorFunc().digest()
     end = time.time()
 
@@ -55,7 +55,7 @@
     import _hashlib
     exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
     print("testing speed of _hashlib.new(%r)" % sys.argv[2])
-elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
+elif hasattr(hashlib, hName) and hasattr(getattr(hashlib, hName), '__call__'):
     creatorFunc = getattr(hashlib, hName)
     print("testing speed of hashlib."+hName, getattr(hashlib, hName))
 else:

Modified: python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt	(original)
+++ python/branches/p3yk-noslice/Lib/test/tokenize_tests.txt	Wed Jul 11 15:40:56 2007
@@ -37,21 +37,21 @@
 
 # Ordinary integers
 0xff != 255
-0377 != 255
-2147483647   != 017777777777
--2147483647-1 != 020000000000
-037777777777 != -1
-0xffffffff != -1
+0o377 != 255
+2147483647   != 0o17777777777
+-2147483647-1 != 0o20000000000
+0o37777777777 != -1
+0xffffffff != -1; 0o37777777777 != -1; -0o1234567 == 0O001234567; 0b10101 == 0B00010101
 
 # Long integers
-x = 0L
-x = 0l
-x = 0xffffffffffffffffL
-x = 0xffffffffffffffffl
-x = 077777777777777777L
-x = 077777777777777777l
-x = 123456789012345678901234567890L
-x = 123456789012345678901234567890l
+x = 0
+x = 0
+x = 0xffffffffffffffff
+x = 0xffffffffffffffff
+x = 0o77777777777777777
+x = 0B11101010111111111
+x = 123456789012345678901234567890
+x = 123456789012345678901234567890
 
 # Floating-point numbers
 x = 3.14

Modified: python/branches/p3yk-noslice/Lib/test/xmltests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/xmltests.py	(original)
+++ python/branches/p3yk-noslice/Lib/test/xmltests.py	Wed Jul 11 15:40:56 2007
@@ -17,5 +17,4 @@
 runtest("test.test_sax")
 runtest("test.test_xml_etree")
 runtest("test.test_xml_etree_c")
-runtest("test.test_xmllib")
 runtest("test.test_xmlrpc")

Modified: python/branches/p3yk-noslice/Lib/textwrap.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/textwrap.py	(original)
+++ python/branches/p3yk-noslice/Lib/textwrap.py	Wed Jul 11 15:40:56 2007
@@ -9,14 +9,6 @@
 
 import string, re
 
-# Do the right thing with boolean values for all known Python versions
-# (so this module can be copied to projects that don't depend on Python
-# 2.3, e.g. Optik and Docutils).
-try:
-    True, False
-except NameError:
-    (True, False) = (1, 0)
-
 __all__ = ['TextWrapper', 'wrap', 'fill']
 
 # Hardcode the recognized whitespace characters to the US-ASCII
@@ -63,14 +55,16 @@
       break_long_words (default: true)
         Break words longer than 'width'.  If false, those words will not
         be broken, and some lines might be longer than 'width'.
+      drop_whitespace (default: true)
+        Drop leading and trailing whitespace from lines.
     """
 
     whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
 
     unicode_whitespace_trans = {}
     uspace = ord(u' ')
-    for x in map(ord, _whitespace):
-        unicode_whitespace_trans[x] = uspace
+    for x in _whitespace:
+        unicode_whitespace_trans[ord(x)] = uspace
 
     # This funky little regex is just the trick for splitting
     # text up into word-wrappable chunks.  E.g.
@@ -98,7 +92,8 @@
                  expand_tabs=True,
                  replace_whitespace=True,
                  fix_sentence_endings=False,
-                 break_long_words=True):
+                 break_long_words=True,
+                 drop_whitespace=True):
         self.width = width
         self.initial_indent = initial_indent
         self.subsequent_indent = subsequent_indent
@@ -106,6 +101,7 @@
         self.replace_whitespace = replace_whitespace
         self.fix_sentence_endings = fix_sentence_endings
         self.break_long_words = break_long_words
+        self.drop_whitespace = drop_whitespace
 
 
     # -- Private methods -----------------------------------------------
@@ -140,7 +136,7 @@
           'use', ' ', 'the', ' ', '-b', ' ', 'option!'
         """
         chunks = self.wordsep_re.split(text)
-        chunks = filter(None, chunks)
+        chunks = [c for c in chunks if c]
         return chunks
 
     def _fix_sentence_endings(self, chunks):
@@ -228,7 +224,7 @@
 
             # First chunk on line is whitespace -- drop it, unless this
             # is the very beginning of the text (ie. no lines started yet).
-            if chunks[-1].strip() == '' and lines:
+            if self.drop_whitespace and chunks[-1].strip() == '' and lines:
                 del chunks[-1]
 
             while chunks:
@@ -249,7 +245,7 @@
                 self._handle_long_word(chunks, cur_line, cur_len, width)
 
             # If the last chunk on this line is all whitespace, drop it.
-            if cur_line and cur_line[-1].strip() == '':
+            if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
                 del cur_line[-1]
 
             # Convert current line back to a string and store it in list

Modified: python/branches/p3yk-noslice/Lib/threading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/threading.py	(original)
+++ python/branches/p3yk-noslice/Lib/threading.py	Wed Jul 11 15:40:56 2007
@@ -111,8 +111,8 @@
     __enter__ = acquire
 
     def release(self):
-        me = currentThread()
-        assert self.__owner is me, "release() of un-acquire()d lock"
+        if self.__owner is not currentThread():
+            raise RuntimeError("cannot release un-aquired lock")
         self.__count = count = self.__count - 1
         if not count:
             self.__owner = None
@@ -128,10 +128,9 @@
 
     # Internal methods used by condition variables
 
-    def _acquire_restore(self, (count, owner)):
+    def _acquire_restore(self, state):
         self.__block.acquire()
-        self.__count = count
-        self.__owner = owner
+        self.__count, self.__owner = state
         if __debug__:
             self._note("%s._acquire_restore()", self)
 
@@ -204,7 +203,8 @@
             return True
 
     def wait(self, timeout=None):
-        assert self._is_owned(), "wait() of un-acquire()d lock"
+        if not self._is_owned():
+            raise RuntimeError("cannot wait on un-aquired lock")
         waiter = _allocate_lock()
         waiter.acquire()
         self.__waiters.append(waiter)
@@ -245,7 +245,8 @@
             self._acquire_restore(saved_state)
 
     def notify(self, n=1):
-        assert self._is_owned(), "notify() of un-acquire()d lock"
+        if not self._is_owned():
+            raise RuntimeError("cannot notify on un-aquired lock")
         __waiters = self.__waiters
         waiters = __waiters[:n]
         if not waiters:
@@ -273,7 +274,8 @@
     # After Tim Peters' semaphore class, but not quite the same (no maximum)
 
     def __init__(self, value=1, verbose=None):
-        assert value >= 0, "Semaphore initial value must be >= 0"
+        if value < 0:
+            raise ValueError("semaphore initial value must be >= 0")
         _Verbose.__init__(self, verbose)
         self.__cond = Condition(Lock())
         self.__value = value
@@ -424,8 +426,10 @@
         return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
 
     def start(self):
-        assert self.__initialized, "Thread.__init__() not called"
-        assert not self.__started, "thread already started"
+        if not self.__initialized:
+            raise RuntimeError("thread.__init__() not called")
+        if self.__started:
+            raise RuntimeError("thread already started")
         if __debug__:
             self._note("%s.start(): starting thread", self)
         _active_limbo_lock.acquire()
@@ -545,9 +549,13 @@
             _active_limbo_lock.release()
 
     def join(self, timeout=None):
-        assert self.__initialized, "Thread.__init__() not called"
-        assert self.__started, "cannot join thread before it is started"
-        assert self is not currentThread(), "cannot join current thread"
+        if not self.__initialized:
+            raise RuntimeError("Thread.__init__() not called")
+        if not self.__started:
+            raise RuntimeError("cannot join thread before it is started")
+        if self is currentThread():
+            raise RuntimeError("cannot join current thread")
+
         if __debug__:
             if not self.__stopped:
                 self._note("%s.join(): waiting until thread stops", self)
@@ -590,8 +598,10 @@
         return self.__daemonic
 
     def setDaemon(self, daemonic):
-        assert self.__initialized, "Thread.__init__() not called"
-        assert not self.__started, "cannot set daemon status of active thread"
+        if not self.__initialized:
+            raise RuntimeError("Thread.__init__() not called")
+        if self.__started:
+            raise RuntimeError("cannot set daemon status of active thread");
         self.__daemonic = daemonic
 
 # The timer class was contributed by Itamar Shtull-Trauring

Modified: python/branches/p3yk-noslice/Lib/timeit.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/timeit.py	(original)
+++ python/branches/p3yk-noslice/Lib/timeit.py	Wed Jul 11 15:40:56 2007
@@ -90,6 +90,17 @@
     """Helper to reindent a multi-line statement."""
     return src.replace("\n", "\n" + " "*indent)
 
+def _template_func(setup, func):
+    """Create a timer function. Used if the "statement" is a callable."""
+    def inner(_it, _timer):
+        setup()
+        _t0 = _timer()
+        for _i in _it:
+            func()
+        _t1 = _timer()
+        return _t1 - _t0
+    return inner
+
 class Timer:
     """Class for timing execution speed of small code snippets.
 
@@ -109,14 +120,32 @@
     def __init__(self, stmt="pass", setup="pass", timer=default_timer):
         """Constructor.  See class doc string."""
         self.timer = timer
-        stmt = reindent(stmt, 8)
-        setup = reindent(setup, 4)
-        src = template % {'stmt': stmt, 'setup': setup}
-        self.src = src # Save for traceback display
-        code = compile(src, dummy_src_name, "exec")
         ns = {}
-        exec(code, globals(), ns)
-        self.inner = ns["inner"]
+        if isinstance(stmt, basestring):
+            stmt = reindent(stmt, 8)
+            if isinstance(setup, basestring):
+                setup = reindent(setup, 4)
+                src = template % {'stmt': stmt, 'setup': setup}
+            elif hasattr(setup, '__call__'):
+                src = template % {'stmt': stmt, 'setup': '_setup()'}
+                ns['_setup'] = setup
+            else:
+                raise ValueError("setup is neither a string nor callable")
+            self.src = src # Save for traceback display
+            code = compile(src, dummy_src_name, "exec")
+            exec(code, globals(), ns)
+            self.inner = ns["inner"]
+        elif hasattr(stmt, '__call__'):
+            self.src = None
+            if isinstance(setup, basestring):
+                _setup = setup
+                def setup():
+                    exec(_setup, globals(), ns)
+            elif not hasattr(setup, '__call__'):
+                raise ValueError("setup is neither a string nor callable")
+            self.inner = _template_func(setup, stmt)
+        else:
+            raise ValueError("stmt is neither a string nor callable")
 
     def print_exc(self, file=None):
         """Helper to print a traceback from the timed code.
@@ -136,10 +165,13 @@
         sent; it defaults to sys.stderr.
         """
         import linecache, traceback
-        linecache.cache[dummy_src_name] = (len(self.src),
-                                           None,
-                                           self.src.split("\n"),
-                                           dummy_src_name)
+        if self.src is not None:
+            linecache.cache[dummy_src_name] = (len(self.src),
+                                               None,
+                                               self.src.split("\n"),
+                                               dummy_src_name)
+        # else the source is already stored somewhere else
+
         traceback.print_exc(file=file)
 
     def timeit(self, number=default_number):
@@ -189,6 +221,16 @@
             r.append(t)
         return r
 
+def timeit(stmt="pass", setup="pass", timer=default_timer,
+           number=default_number):
+    """Convenience function to create Timer object and call timeit method."""
+    return Timer(stmt, setup, timer).timeit(number)
+
+def repeat(stmt="pass", setup="pass", timer=default_timer,
+           repeat=default_repeat, number=default_number):
+    """Convenience function to create Timer object and call repeat method."""
+    return Timer(stmt, setup, timer).repeat(repeat, number)
+
 def main(args=None):
     """Main program, used when run as a script.
 

Modified: python/branches/p3yk-noslice/Lib/token.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/token.py	(original)
+++ python/branches/p3yk-noslice/Lib/token.py	Wed Jul 11 15:40:56 2007
@@ -61,9 +61,10 @@
 DOUBLESLASHEQUAL = 49
 AT = 50
 RARROW = 51
-OP = 52
-ERRORTOKEN = 53
-N_TOKENS = 54
+ELLIPSIS = 52
+OP = 53
+ERRORTOKEN = 54
+N_TOKENS = 55
 NT_OFFSET = 256
 #--end constants--
 
@@ -108,8 +109,7 @@
             name, val = match.group(1, 2)
             val = int(val)
             tokens[val] = name          # reverse so we can sort them...
-    keys = tokens.keys()
-    keys.sort()
+    keys = sorted(tokens.keys())
     # load the output skeleton from the target:
     try:
         fp = open(outFileName)

Modified: python/branches/p3yk-noslice/Lib/tokenize.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/tokenize.py	(original)
+++ python/branches/p3yk-noslice/Lib/tokenize.py	Wed Jul 11 15:40:56 2007
@@ -32,7 +32,6 @@
 import token
 __all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize",
            "generate_tokens", "NL", "untokenize"]
-del x
 del token
 
 COMMENT = N_TOKENS
@@ -50,10 +49,11 @@
 Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
 Name = r'[a-zA-Z_]\w*'
 
-Hexnumber = r'0[xX][\da-fA-F]*[lL]?'
-Octnumber = r'0[0-7]*[lL]?'
-Decnumber = r'[1-9]\d*[lL]?'
-Intnumber = group(Hexnumber, Octnumber, Decnumber)
+Hexnumber = r'0[xX][\da-fA-F]*'
+Binnumber = r'0[bB][01]*'
+Octnumber = r'0[oO][0-7]*'
+Decnumber = r'(?:0+|[1-9]\d*)'
+Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
 Exponent = r'[eE][-+]?\d+'
 Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
 Expfloat = r'\d+' + Exponent
@@ -83,7 +83,7 @@
                  r"~")
 
 Bracket = '[][(){}]'
-Special = group(r'\r?\n', r'[:;.,@]')
+Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
 Funny = group(Operator, Bracket, Special)
 
 PlainToken = group(Number, Funny, String, Name)
@@ -132,7 +132,8 @@
 
 class StopTokenizing(Exception): pass
 
-def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
+def printtoken(type, token, startrowcol, endrowcol, line): # for testing
+    (srow, scol), (erow, ecol) = startrowcol, endrowcol
     print("%d,%d-%d,%d:\t%s\t%s" % \
         (srow, scol, erow, ecol, tok_name[type], repr(token)))
 
@@ -229,7 +230,7 @@
         # Output text will tokenize the back to the input
         t1 = [tok[:2] for tok in generate_tokens(f.readline)]
         newcode = untokenize(t1)
-        readline = iter(newcode.splitlines(1)).next
+        readline = iter(newcode.splitlines(1)).__next__
         t2 = [tok[:2] for tokin generate_tokens(readline)]
         assert t1 == t2
     """
@@ -243,7 +244,7 @@
     readline() method of built-in file objects. Each call to the function
     should return one line of input as a string.  Alternately, readline
     can be a callable function terminating with StopIteration:
-        readline = open(myfile).next    # Example of alternate readline
+        readline = open(myfile).__next__    # Example of alternate readline
 
     The generator produces 5-tuples with these members: the token type; the
     token string; a 2-tuple (srow, scol) of ints specifying the row and
@@ -334,8 +335,8 @@
                 spos, epos, pos = (lnum, start), (lnum, end), end
                 token, initial = line[start:end], line[start]
 
-                if initial in numchars or \
-                   (initial == '.' and token != '.'):      # ordinary number
+                if (initial in numchars or                  # ordinary number
+                    (initial == '.' and token != '.' and token != '...')):
                     yield (NUMBER, token, spos, epos, line)
                 elif initial in '\r\n':
                     yield (NL if parenlev > 0 else NEWLINE,

Modified: python/branches/p3yk-noslice/Lib/trace.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/trace.py	(original)
+++ python/branches/p3yk-noslice/Lib/trace.py	Wed Jul 11 15:40:56 2007
@@ -532,7 +532,7 @@
             ## use of gc.get_referrers() was suggested by Michael Hudson
             # all functions which refer to this code object
             funcs = [f for f in gc.get_referrers(code)
-                         if hasattr(f, "func_doc")]
+                         if hasattr(f, "__doc__")]
             # require len(func) == 1 to avoid ambiguity caused by calls to
             # new.function(): "In the face of ambiguity, refuse the
             # temptation to guess."

Modified: python/branches/p3yk-noslice/Lib/traceback.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/traceback.py	(original)
+++ python/branches/p3yk-noslice/Lib/traceback.py	Wed Jul 11 15:40:56 2007
@@ -169,7 +169,7 @@
 
     stype = etype.__name__
     smod = etype.__module__
-    if smod not in ("exceptions", "__main__", "__builtin__"):
+    if smod not in ("__main__", "__builtin__"):
         stype = smod + '.' + stype
 
     if not issubclass(etype, SyntaxError):
@@ -178,7 +178,7 @@
     # It was a syntax error; show exactly where the problem was found.
     lines = []
     try:
-        msg, (filename, lineno, offset, badline) = value
+        msg, (filename, lineno, offset, badline) = value.args
     except Exception:
         pass
     else:

Modified: python/branches/p3yk-noslice/Lib/types.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/types.py	(original)
+++ python/branches/p3yk-noslice/Lib/types.py	Wed Jul 11 15:40:56 2007
@@ -7,7 +7,7 @@
 # Iterators in Python aren't a matter of type but of protocol.  A large
 # and changing number of builtin types implement *some* flavor of
 # iterator.  Don't check the type!  Use hasattr to check for both
-# "__iter__" and "next" attributes instead.
+# "__iter__" and "__next__" attributes instead.
 
 NoneType = type(None)
 TypeType = type
@@ -42,11 +42,7 @@
 def _f(): pass
 FunctionType = type(_f)
 LambdaType = type(lambda: None)         # Same as FunctionType
-try:
-    CodeType = type(_f.func_code)
-except RuntimeError:
-    # Execution in restricted environment
-    pass
+CodeType = type(_f.__code__)
 
 def _g():
     yield 1
@@ -54,7 +50,7 @@
 
 class _C:
     def _m(self): pass
-ClassType = type(_C)
+ClassType = type
 UnboundMethodType = type(_C._m)         # Same as MethodType
 MethodType = type(_C()._m)
 
@@ -63,19 +59,13 @@
 
 ModuleType = type(sys)
 FileType = file
-XRangeType = xrange
 
 try:
     raise TypeError
 except TypeError:
-    try:
-        tb = sys.exc_info()[2]
-        TracebackType = type(tb)
-        FrameType = type(tb.tb_frame)
-    except AttributeError:
-        # In the restricted environment, exc_info returns (None, None,
-        # None) Then, tb.tb_frame gives an attribute error
-        pass
+    tb = sys.exc_info()[2]
+    TracebackType = type(tb)
+    FrameType = type(tb.tb_frame)
     tb = None; del tb
 
 SliceType = slice

Modified: python/branches/p3yk-noslice/Lib/unittest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/unittest.py	(original)
+++ python/branches/p3yk-noslice/Lib/unittest.py	Wed Jul 11 15:40:56 2007
@@ -25,7 +25,7 @@
 
 Further information is available in the bundled documentation, and from
 
-  http://pyunit.sourceforge.net/
+  http://docs.python.org/lib/module-unittest.html
 
 Copyright (c) 1999-2003 Steve Purcell
 This module is free software, and you may redistribute it and/or modify
@@ -65,28 +65,9 @@
 
 
 ##############################################################################
-# Backward compatibility
-##############################################################################
-if sys.version_info[:2] < (2, 2):
-    False, True = 0, 1
-    def isinstance(obj, clsinfo):
-        import __builtin__
-        if type(clsinfo) in (tuple, list):
-            for cls in clsinfo:
-                if cls is type: cls = types.ClassType
-                if __builtin__.isinstance(obj, cls):
-                    return 1
-            return 0
-        else: return __builtin__.isinstance(obj, clsinfo)
-
-
-##############################################################################
 # Test framework core
 ##############################################################################
 
-# All classes defined herein are 'new-style' classes, allowing use of 'super()'
-__metaclass__ = type
-
 def _strclass(cls):
     return "%s.%s" % (cls.__module__, cls.__name__)
 
@@ -107,7 +88,7 @@
         self.failures = []
         self.errors = []
         self.testsRun = 0
-        self.shouldStop = 0
+        self.shouldStop = False
 
     def startTest(self, test):
         "Called when the given test is about to be run"
@@ -235,6 +216,18 @@
     def id(self):
         return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
 
+    def __eq__(self, other):
+        if type(self) is not type(other):
+            return False
+
+        return self._testMethodName == other._testMethodName
+
+    def __ne__(self, other):
+        return not self == other
+
+    def __hash__(self):
+        return hash((type(self), self._testMethodName))
+
     def __str__(self):
         return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
 
@@ -291,10 +284,7 @@
            minimised; usually the top level of the traceback frame is not
            needed.
         """
-        exctype, excvalue, tb = sys.exc_info()
-        if sys.platform[:4] == 'java': ## tracebacks look different in Jython
-            return (exctype, excvalue, tb)
-        return (exctype, excvalue, tb)
+        return sys.exc_info()
 
     def fail(self, msg=None):
         """Fail immediately, with the given message."""
@@ -401,6 +391,14 @@
 
     __str__ = __repr__
 
+    def __eq__(self, other):
+        if type(self) is not type(other):
+            return False
+        return self._tests == other._tests
+
+    def __ne__(self, other):
+        return not self == other
+
     def __iter__(self):
         return iter(self._tests)
 
@@ -411,9 +409,17 @@
         return cases
 
     def addTest(self, test):
+        # sanity checks
+        if not hasattr(test, '__call__'):
+            raise TypeError("the test to add must be callable")
+        if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
+            raise TypeError("TestCases and TestSuites must be instantiated "
+                            "before passing them to addTest()")
         self._tests.append(test)
 
     def addTests(self, tests):
+        if isinstance(tests, basestring):
+            raise TypeError("tests must be an iterable of tests, not a string")
         for test in tests:
             self.addTest(test)
 
@@ -436,7 +442,7 @@
     """A test case that wraps a test function.
 
     This is useful for slipping pre-existing test functions into the
-    PyUnit framework. Optionally, set-up and tidy-up functions can be
+    unittest framework. Optionally, set-up and tidy-up functions can be
     supplied. As with TestCase, the tidy-up ('tearDown') function will
     always be called if the set-up ('setUp') function ran successfully.
     """
@@ -463,6 +469,22 @@
     def id(self):
         return self.__testFunc.__name__
 
+    def __eq__(self, other):
+        if type(self) is not type(other):
+            return False
+
+        return self.__setUpFunc == other.__setUpFunc and \
+               self.__tearDownFunc == other.__tearDownFunc and \
+               self.__testFunc == other.__testFunc and \
+               self.__description == other.__description
+
+    def __ne__(self, other):
+        return not self == other
+
+    def __hash__(self):
+        return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
+                                           self.__testFunc, self.__description))
+
     def __str__(self):
         return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
 
@@ -482,7 +504,7 @@
 
 class TestLoader:
     """This class is responsible for loading tests according to various
-    criteria and returning them wrapped in a Test
+    criteria and returning them wrapped in a TestSuite
     """
     testMethodPrefix = 'test'
     sortTestMethodsUsing = cmp
@@ -502,8 +524,7 @@
         tests = []
         for name in dir(module):
             obj = getattr(module, name)
-            if (isinstance(obj, (type, types.ClassType)) and
-                issubclass(obj, TestCase)):
+            if isinstance(obj, type) and issubclass(obj, TestCase):
                 tests.append(self.loadTestsFromTestCase(obj))
         return self.suiteClass(tests)
 
@@ -533,21 +554,25 @@
 
         if type(obj) == types.ModuleType:
             return self.loadTestsFromModule(obj)
-        elif (isinstance(obj, (type, types.ClassType)) and
-              issubclass(obj, TestCase)):
+        elif isinstance(obj, type) and issubclass(obj, TestCase):
             return self.loadTestsFromTestCase(obj)
-        elif type(obj) == types.UnboundMethodType:
-            return parent(obj.__name__)
+        elif (isinstance(obj, types.UnboundMethodType) and
+              isinstance(parent, type) and
+              issubclass(parent, TestCase)):
+            return TestSuite([parent(obj.__name__)])
         elif isinstance(obj, TestSuite):
             return obj
-        elif callable(obj):
+        elif hasattr(obj, '__call__'):
             test = obj()
-            if not isinstance(test, (TestCase, TestSuite)):
-                raise ValueError, \
-                      "calling %s returned %s, not a test" % (obj,test)
-            return test
+            if isinstance(test, TestSuite):
+                return test
+            elif isinstance(test, TestCase):
+                return TestSuite([test])
+            else:
+                raise TypeError("calling %s returned %s, not a test" %
+                                (obj, test))
         else:
-            raise ValueError, "don't know how to make test from: %s" % obj
+            raise TypeError("don't know how to make test from: %s" % obj)
 
     def loadTestsFromNames(self, names, module=None):
         """Return a suite of all tests cases found using the given sequence
@@ -560,12 +585,8 @@
         """Return a sorted sequence of method names found within testCaseClass
         """
         def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
-            return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
-        testFnNames = filter(isTestMethod, dir(testCaseClass))
-        for baseclass in testCaseClass.__bases__:
-            for testFnName in self.getTestCaseNames(baseclass):
-                if testFnName not in testFnNames:  # handle overridden methods
-                    testFnNames.append(testFnName)
+            return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
+        testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
         if self.sortTestMethodsUsing:
             testFnNames.sort(self.sortTestMethodsUsing)
         return testFnNames
@@ -704,7 +725,7 @@
         self.stream.writeln()
         if not result.wasSuccessful():
             self.stream.write("FAILED (")
-            failed, errored = map(len, (result.failures, result.errors))
+            failed, errored = len(result.failures), len(result.errors)
             if failed:
                 self.stream.write("failures=%d" % failed)
             if errored:
@@ -741,7 +762,8 @@
                                                in MyTestCase
 """
     def __init__(self, module='__main__', defaultTest=None,
-                 argv=None, testRunner=None, testLoader=defaultTestLoader):
+                 argv=None, testRunner=TextTestRunner,
+                 testLoader=defaultTestLoader):
         if type(module) == type(''):
             self.module = __import__(module)
             for part in module.split('.')[1:]:
@@ -791,9 +813,16 @@
                                                        self.module)
 
     def runTests(self):
-        if self.testRunner is None:
-            self.testRunner = TextTestRunner(verbosity=self.verbosity)
-        result = self.testRunner.run(self.test)
+        if isinstance(self.testRunner, type):
+            try:
+                testRunner = self.testRunner(verbosity=self.verbosity)
+            except TypeError:
+                # didn't accept the verbosity argument
+                testRunner = self.testRunner()
+        else:
+            # it is assumed to be a TestRunner instance
+            testRunner = self.testRunner
+        result = testRunner.run(self.test)
         sys.exit(not result.wasSuccessful())
 
 main = TestProgram

Modified: python/branches/p3yk-noslice/Lib/urllib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/urllib.py	(original)
+++ python/branches/p3yk-noslice/Lib/urllib.py	Wed Jul 11 15:40:56 2007
@@ -22,7 +22,6 @@
 (mimetools.Message objects are queried with the getheader() method.)
 """
 
-import string
 import socket
 import os
 import time
@@ -35,7 +34,7 @@
            "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
            "splittype", "splithost", "splituser", "splitpasswd", "splitport",
            "splitnport", "splitquery", "splitattr", "splitvalue",
-           "splitgophertype", "getproxies"]
+           "getproxies"]
 
 __version__ = '1.17'    # XXX This version is not always updated :-(
 
@@ -327,6 +326,11 @@
             h.send(data)
         errcode, errmsg, headers = h.getreply()
         fp = h.getfile()
+        if errcode == -1:
+            if fp: fp.close()
+            # something went wrong with the HTTP status line
+            raise IOError, ('http protocol error', 0,
+                            'got a bad status line', None)
         if errcode == 200:
             return addinfourl(fp, headers, "http:" + url)
         else:
@@ -414,6 +418,11 @@
                 h.send(data)
             errcode, errmsg, headers = h.getreply()
             fp = h.getfile()
+            if errcode == -1:
+                if fp: fp.close()
+                # something went wrong with the HTTP status line
+                raise IOError, ('http protocol error', 0,
+                                'got a bad status line', None)
             if errcode == 200:
                 return addinfourl(fp, headers, "https:" + url)
             else:
@@ -423,24 +432,6 @@
                     return self.http_error(url, fp, errcode, errmsg, headers,
                                            data)
 
-    def open_gopher(self, url):
-        """Use Gopher protocol."""
-        if not isinstance(url, str):
-            raise IOError, ('gopher error', 'proxy support for gopher protocol currently not implemented')
-        import gopherlib
-        host, selector = splithost(url)
-        if not host: raise IOError, ('gopher error', 'no host given')
-        host = unquote(host)
-        type, selector = splitgophertype(selector)
-        selector, query = splitquery(selector)
-        selector = unquote(selector)
-        if query:
-            query = unquote(query)
-            fp = gopherlib.send_query(selector, query, host)
-        else:
-            fp = gopherlib.send_selector(selector, host)
-        return addinfourl(fp, noheaders(), "gopher:" + url)
-
     def open_file(self, url):
         """Use local file or FTP depending on form of URL."""
         if not isinstance(url, str):
@@ -768,11 +759,9 @@
 
     def prompt_user_passwd(self, host, realm):
         """Override this in a GUI environment!"""
-        import getpass, sys
+        import getpass
         try:
-            sys.stdout.write("Enter username for %s at %s: " % (realm, host))
-            sys.stdout.flush()
-            user = sys.stdin.readline()
+            user = input("Enter username for %s at %s: " % (realm, host))
             passwd = getpass.getpass("Enter password for %s in %s at %s: " %
                 (user, realm, host))
             return user, passwd
@@ -828,19 +817,20 @@
 class ftpwrapper:
     """Class used by open_ftp() for cache of open FTP connections."""
 
-    def __init__(self, user, passwd, host, port, dirs):
+    def __init__(self, user, passwd, host, port, dirs, timeout=None):
         self.user = user
         self.passwd = passwd
         self.host = host
         self.port = port
         self.dirs = dirs
+        self.timeout = timeout
         self.init()
 
     def init(self):
         import ftplib
         self.busy = 0
         self.ftp = ftplib.FTP()
-        self.ftp.connect(self.host, self.port)
+        self.ftp.connect(self.host, self.port, self.timeout)
         self.ftp.login(self.user, self.passwd)
         for dir in self.dirs:
             self.ftp.cwd(dir)
@@ -905,8 +895,8 @@
             self.fileno = lambda: None
         if hasattr(self.fp, "__iter__"):
             self.__iter__ = self.fp.__iter__
-            if hasattr(self.fp, "next"):
-                self.next = self.fp.next
+            if hasattr(self.fp, "__next__"):
+                self.__next__ = self.fp.__next__
 
     def __repr__(self):
         return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
@@ -972,7 +962,6 @@
 # splitattr('/path;attr1=value1;attr2=value2;...') ->
 #   '/path', ['attr1=value1', 'attr2=value2', ...]
 # splitvalue('attr=value') --> 'attr', 'value'
-# splitgophertype('/Xselector') --> 'X', 'selector'
 # unquote('abc%20def') -> 'abc def'
 # quote('abc def') -> 'abc%20def')
 
@@ -1132,19 +1121,13 @@
     if match: return match.group(1, 2)
     return attr, None
 
-def splitgophertype(selector):
-    """splitgophertype('/Xselector') --> 'X', 'selector'."""
-    if selector[:1] == '/' and selector[1:2]:
-        return selector[1], selector[2:]
-    return None, selector
-
 _hextochr = dict(('%02x' % i, chr(i)) for i in range(256))
 _hextochr.update(('%02X' % i, chr(i)) for i in range(256))
 
 def unquote(s):
     """unquote('abc%20def') -> 'abc def'."""
     res = s.split('%')
-    for i in xrange(1, len(res)):
+    for i in range(1, len(res)):
         item = res[i]
         try:
             res[i] = _hextochr[item[:2]] + item[2:]
@@ -1467,13 +1450,13 @@
 
 # Test program
 def test(args=[]):
+    import string
     if not args:
         args = [
             '/etc/passwd',
             'file:/etc/passwd',
             'file://localhost/etc/passwd',
-            'ftp://ftp.python.org/pub/python/README',
-##          'gopher://gopher.micro.umn.edu/1/',
+            'ftp://ftp.gnu.org/pub/README',
             'http://www.python.org/index.html',
             ]
         if hasattr(URLopener, "open_https"):

Modified: python/branches/p3yk-noslice/Lib/urllib2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/urllib2.py	(original)
+++ python/branches/p3yk-noslice/Lib/urllib2.py	Wed Jul 11 15:40:56 2007
@@ -14,36 +14,36 @@
 HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
 deals with digest authentication.
 
-urlopen(url, data=None) -- basic usage is the same as original
+urlopen(url, data=None) -- Basic usage is the same as original
 urllib.  pass the url and optionally data to post to an HTTP URL, and
 get a file-like object back.  One difference is that you can also pass
 a Request instance instead of URL.  Raises a URLError (subclass of
 IOError); for HTTP errors, raises an HTTPError, which can also be
 treated as a valid response.
 
-build_opener -- function that creates a new OpenerDirector instance.
-will install the default handlers.  accepts one or more Handlers as
+build_opener -- Function that creates a new OpenerDirector instance.
+Will install the default handlers.  Accepts one or more Handlers as
 arguments, either instances or Handler classes that it will
-instantiate.  if one of the argument is a subclass of the default
+instantiate.  If one of the argument is a subclass of the default
 handler, the argument will be installed instead of the default.
 
-install_opener -- installs a new opener as the default opener.
+install_opener -- Installs a new opener as the default opener.
 
 objects of interest:
 OpenerDirector --
 
-Request -- an object that encapsulates the state of a request.  the
-state can be a simple as the URL.  it can also include extra HTTP
+Request -- An object that encapsulates the state of a request.  The
+state can be as simple as the URL.  It can also include extra HTTP
 headers, e.g. a User-Agent.
 
 BaseHandler --
 
 exceptions:
-URLError-- a subclass of IOError, individual protocols have their own
-specific subclass
+URLError -- A subclass of IOError, individual protocols have their own
+specific subclass.
 
-HTTPError-- also a valid HTTP response, so you can treat an HTTP error
-as an exceptional event or valid response
+HTTPError -- Also a valid HTTP response, so you can treat an HTTP error
+as an exceptional event or valid response.
 
 internals:
 BaseHandler and parent
@@ -55,7 +55,10 @@
 
 # set up authentication info
 authinfo = urllib2.HTTPBasicAuthHandler()
-authinfo.add_password('realm', 'host', 'username', 'password')
+authinfo.add_password(realm='PDQ Application',
+                      uri='https://mahler:8092/site-updates.py',
+                      user='klem',
+                      passwd='geheim$parole')
 
 proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
 
@@ -104,7 +107,7 @@
     from StringIO import StringIO
 
 from urllib import (unwrap, unquote, splittype, splithost, quote,
-     addinfourl, splitport, splitgophertype, splitquery,
+     addinfourl, splitport, splitquery,
      splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue)
 
 # support for FileHandler, proxies via environment variables
@@ -114,11 +117,11 @@
 __version__ = sys.version[:3]
 
 _opener = None
-def urlopen(url, data=None):
+def urlopen(url, data=None, timeout=None):
     global _opener
     if _opener is None:
         _opener = build_opener()
-    return _opener.open(url, data)
+    return _opener.open(url, data, timeout)
 
 def install_opener(opener):
     global _opener
@@ -161,9 +164,6 @@
     def __str__(self):
         return 'HTTP Error %s: %s' % (self.code, self.msg)
 
-class GopherError(URLError):
-    pass
-
 # copied from cookielib.py
 _cut_port_re = re.compile(r":\d+$")
 def request_host(request):
@@ -334,7 +334,8 @@
             added = True
 
         if added:
-            # XXX why does self.handlers need to be sorted?
+            # the handlers must work in an specific order, the order
+            # is specified in a Handler attribute
             bisect.insort(self.handlers, handler)
             handler.add_parent(self)
 
@@ -354,7 +355,7 @@
             if result is not None:
                 return result
 
-    def open(self, fullurl, data=None):
+    def open(self, fullurl, data=None, timeout=None):
         # accept a URL or a Request object
         if isinstance(fullurl, basestring):
             req = Request(fullurl, data)
@@ -363,6 +364,7 @@
             if data is not None:
                 req.add_data(data)
 
+        req.timeout = timeout
         protocol = req.get_type()
 
         # pre-process request
@@ -430,9 +432,8 @@
     If any of the handlers passed as arguments are subclasses of the
     default handlers, the default handlers will not be used.
     """
-    import types
     def isclass(obj):
-        return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
+        return isinstance(obj, type) or hasattr(obj, "__bases__")
 
     opener = OpenerDirector()
     default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
@@ -486,7 +487,9 @@
     def http_response(self, request, response):
         code, msg, hdrs = response.code, response.msg, response.info()
 
-        if code not in (200, 206):
+        # According to RFC 2616, "2xx" code indicates that the client's
+        # request was successfully received, understood, and accepted.
+        if not (200 <= code < 300):
             response = self.parent.error(
                 'http', request, response, code, msg, hdrs)
 
@@ -766,11 +769,10 @@
 
 class AbstractBasicAuthHandler:
 
-    rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
+    # XXX this allows for multiple auth-schemes, but will stupidly pick
+    # the last one with a realm specified.
 
-    # XXX there can actually be multiple auth-schemes in a
-    # www-authenticate header.  should probably be a lot more careful
-    # in parsing them to extract multiple alternatives
+    rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
 
     # XXX could pre-emptively send auth info already accepted (RFC 2617,
     # end of section 2, and section 1.2 immediately after "credentials"
@@ -946,7 +948,7 @@
             respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
         else:
             # XXX handle auth-int.
-            pass
+            raise URLError("qop '%s' is not supported." % qop)
 
         # XXX should the partial digests be encoded too?
 
@@ -1055,7 +1057,7 @@
         if not host:
             raise URLError('no host given')
 
-        h = http_class(host) # will parse host:port
+        h = http_class(host, timeout=req.timeout) # will parse host:port
         h.set_debuglevel(self._debuglevel)
 
         headers = dict(req.headers)
@@ -1214,21 +1216,31 @@
         host = req.get_host()
         file = req.get_selector()
         localfile = url2pathname(file)
-        stats = os.stat(localfile)
-        size = stats.st_size
-        modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
-        mtype = mimetypes.guess_type(file)[0]
-        headers = mimetools.Message(StringIO(
-            'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
-            (mtype or 'text/plain', size, modified)))
-        if host:
-            host, port = splitport(host)
-        if not host or \
-           (not port and socket.gethostbyname(host) in self.get_names()):
-            return addinfourl(open(localfile, 'rb'),
-                              headers, 'file:'+file)
+        try:
+            stats = os.stat(localfile)
+            size = stats.st_size
+            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
+            mtype = mimetypes.guess_type(file)[0]
+            headers = mimetools.Message(StringIO(
+                'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
+                (mtype or 'text/plain', size, modified)))
+            if host:
+                host, port = splitport(host)
+            if not host or \
+                (not port and _safe_gethostbyname(host) in self.get_names()):
+                return addinfourl(open(localfile, 'rb'),
+                                  headers, 'file:'+file)
+        except OSError as msg:
+            # urllib2 users shouldn't expect OSErrors coming from urlopen()
+            raise URLError(msg)
         raise URLError('file not on local host')
 
+def _safe_gethostbyname(host):
+    try:
+        return socket.gethostbyname(host)
+    except socket.gaierror:
+        return None
+
 class FTPHandler(BaseHandler):
     def ftp_open(self, req):
         import ftplib
@@ -1258,12 +1270,12 @@
             raise URLError(msg)
         path, attrs = splitattr(req.get_selector())
         dirs = path.split('/')
-        dirs = map(unquote, dirs)
+        dirs = list(map(unquote, dirs))
         dirs, file = dirs[:-1], dirs[-1]
         if dirs and not dirs[0]:
             dirs = dirs[1:]
         try:
-            fw = self.connect_ftp(user, passwd, host, port, dirs)
+            fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
             type = file and 'I' or 'D'
             for attr in attrs:
                 attr, value = splitvalue(attr)
@@ -1283,8 +1295,8 @@
         except ftplib.all_errors as msg:
             raise IOError, ('ftp error', msg), sys.exc_info()[2]
 
-    def connect_ftp(self, user, passwd, host, port, dirs):
-        fw = ftpwrapper(user, passwd, host, port, dirs)
+    def connect_ftp(self, user, passwd, host, port, dirs, timeout):
+        fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
 ##        fw.ftp.set_debuglevel(1)
         return fw
 
@@ -1304,12 +1316,12 @@
     def setMaxConns(self, m):
         self.max_conns = m
 
-    def connect_ftp(self, user, passwd, host, port, dirs):
-        key = user, host, port, '/'.join(dirs)
+    def connect_ftp(self, user, passwd, host, port, dirs, timeout):
+        key = user, host, port, '/'.join(dirs), timeout
         if key in self.cache:
             self.timeout[key] = time.time() + self.delay
         else:
-            self.cache[key] = ftpwrapper(user, passwd, host, port, dirs)
+            self.cache[key] = ftpwrapper(user, passwd, host, port, dirs, timeout)
             self.timeout[key] = time.time() + self.delay
         self.check_cache()
         return self.cache[key]
@@ -1333,22 +1345,3 @@
                     del self.timeout[k]
                     break
             self.soonest = min(list(self.timeout.values()))
-
-class GopherHandler(BaseHandler):
-    def gopher_open(self, req):
-        # XXX can raise socket.error
-        import gopherlib  # this raises DeprecationWarning in 2.5
-        host = req.get_host()
-        if not host:
-            raise GopherError('no host given')
-        host = unquote(host)
-        selector = req.get_selector()
-        type, selector = splitgophertype(selector)
-        selector, query = splitquery(selector)
-        selector = unquote(selector)
-        if query:
-            query = unquote(query)
-            fp = gopherlib.send_query(selector, query, host)
-        else:
-            fp = gopherlib.send_selector(selector, host)
-        return addinfourl(fp, noheaders(), req.get_full_url())

Modified: python/branches/p3yk-noslice/Lib/urlparse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/urlparse.py	(original)
+++ python/branches/p3yk-noslice/Lib/urlparse.py	Wed Jul 11 15:40:56 2007
@@ -220,16 +220,18 @@
     _parse_cache[key] = v
     return v
 
-def urlunparse((scheme, netloc, url, params, query, fragment)):
+def urlunparse(components):
     """Put a parsed URL back together again.  This may result in a
     slightly different, but equivalent URL, if the URL that was parsed
     originally had redundant delimiters, e.g. a ? with an empty query
     (the draft states that these are equivalent)."""
+    scheme, netloc, url, params, query, fragment = components
     if params:
         url = "%s;%s" % (url, params)
     return urlunsplit((scheme, netloc, url, query, fragment))
 
-def urlunsplit((scheme, netloc, url, query, fragment)):
+def urlunsplit(components):
+    scheme, netloc, url, query, fragment = components
     if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
         if url and url[:1] != '/': url = '/' + url
         url = '//' + (netloc or '') + url

Modified: python/branches/p3yk-noslice/Lib/uu.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/uu.py	(original)
+++ python/branches/p3yk-noslice/Lib/uu.py	Wed Jul 11 15:40:56 2007
@@ -68,11 +68,11 @@
     if name is None:
         name = '-'
     if mode is None:
-        mode = 0666
+        mode = 0o666
     #
     # Write the data
     #
-    out_file.write('begin %o %s\n' % ((mode&0777),name))
+    out_file.write('begin %o %s\n' % ((mode & 0o777),name))
     data = in_file.read(45)
     while len(data) > 0:
         out_file.write(binascii.b2a_uu(data))

Modified: python/branches/p3yk-noslice/Lib/uuid.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/uuid.py	(original)
+++ python/branches/p3yk-noslice/Lib/uuid.py	Wed Jul 11 15:40:56 2007
@@ -535,8 +535,8 @@
 
 def uuid3(namespace, name):
     """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
-    import md5
-    hash = md5.md5(namespace.bytes + name).digest()
+    from hashlib import md5
+    hash = md5(namespace.bytes + name).digest()
     return UUID(bytes=hash[:16], version=3)
 
 def uuid4():
@@ -558,8 +558,8 @@
 
 def uuid5(namespace, name):
     """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
-    import sha
-    hash = sha.sha(namespace.bytes + name).digest()
+    from hashlib import sha1
+    hash = sha1(namespace.bytes + name).digest()
     return UUID(bytes=hash[:16], version=5)
 
 # The following standard UUIDs are for use with uuid3() or uuid5().

Modified: python/branches/p3yk-noslice/Lib/warnings.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/warnings.py	(original)
+++ python/branches/p3yk-noslice/Lib/warnings.py	Wed Jul 11 15:40:56 2007
@@ -3,7 +3,7 @@
 # Note: function level imports should *not* be used
 # in this module as it may cause import lock deadlock.
 # See bug 683658.
-import sys, types
+import sys
 import linecache
 
 __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
@@ -151,8 +151,7 @@
     assert action in ("error", "ignore", "always", "default", "module",
                       "once"), "invalid action: %r" % (action,)
     assert isinstance(message, basestring), "message must be a string"
-    assert isinstance(category, (type, types.ClassType)), \
-           "category must be a class"
+    assert isinstance(category, type), "category must be a class"
     assert issubclass(category, Warning), "category must be a Warning subclass"
     assert isinstance(module, basestring), "module must be a string"
     assert isinstance(lineno, int) and lineno >= 0, \

Modified: python/branches/p3yk-noslice/Lib/wave.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/wave.py	(original)
+++ python/branches/p3yk-noslice/Lib/wave.py	Wed Jul 11 15:40:56 2007
@@ -159,7 +159,12 @@
             f = __builtin__.open(f, 'rb')
             self._i_opened_the_file = f
         # else, assume it is an open file object already
-        self.initfp(f)
+        try:
+            self.initfp(f)
+        except:
+            if self._i_opened_the_file:
+                f.close()
+            raise
 
     def __del__(self):
         self.close()
@@ -256,9 +261,9 @@
     #
 
     def _read_fmt_chunk(self, chunk):
-        wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack('<hhllh', chunk.read(14))
+        wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from('<hhllh', chunk.read(14))
         if wFormatTag == WAVE_FORMAT_PCM:
-            sampwidth = struct.unpack('<h', chunk.read(2))[0]
+            sampwidth = struct.unpack_from('<h', chunk.read(2))[0]
             self._sampwidth = (sampwidth + 7) // 8
         else:
             raise Error, 'unknown format: %r' % (wFormatTag,)
@@ -297,7 +302,12 @@
         if isinstance(f, basestring):
             f = __builtin__.open(f, 'wb')
             self._i_opened_the_file = f
-        self.initfp(f)
+        try:
+            self.initfp(f)
+        except:
+            if self._i_opened_the_file:
+                f.close()
+            raise
 
     def initfp(self, file):
         self._file = file
@@ -374,7 +384,8 @@
     def getcompname(self):
         return self._compname
 
-    def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)):
+    def setparams(self, params):
+        nchannels, sampwidth, framerate, nframes, comptype, compname = params
         if self._datawritten:
             raise Error, 'cannot change parameters after starting to write'
         self.setnchannels(nchannels)

Modified: python/branches/p3yk-noslice/Lib/weakref.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/weakref.py	(original)
+++ python/branches/p3yk-noslice/Lib/weakref.py	Wed Jul 11 15:40:56 2007
@@ -20,8 +20,6 @@
      ProxyType,
      ReferenceType)
 
-from exceptions import ReferenceError
-
 
 ProxyTypes = (ProxyType, CallableProxyType)
 
@@ -206,7 +204,7 @@
         return self
 
     def __init__(self, ob, callback, key):
-        super(KeyedRef,  self).__init__(ob, callback)
+        super().__init__(ob, callback)
 
 
 class WeakKeyDictionary(UserDict.UserDict):

Modified: python/branches/p3yk-noslice/Lib/webbrowser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/webbrowser.py	(original)
+++ python/branches/p3yk-noslice/Lib/webbrowser.py	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,9 @@
 #! /usr/bin/env python
 """Interfaces for launching and remotely controlling Web browsers."""
+# Maintained by Georg Brandl.
 
 import os
+import shlex
 import sys
 import stat
 import subprocess
@@ -32,7 +34,11 @@
     for browser in alternatives:
         if '%s' in browser:
             # User gave us a command line, split it into name and args
-            return GenericBrowser(browser.split())
+            browser = shlex.split(browser)
+            if browser[-1] == '&':
+                return BackgroundBrowser(browser[:-1])
+            else:
+                return GenericBrowser(browser)
         else:
             # User gave us a browser name or path.
             try:
@@ -155,6 +161,7 @@
     def __init__(self, name):
         if isinstance(name, basestring):
             self.name = name
+            self.args = ["%s"]
         else:
             # name should be a list with arguments
             self.name = name[0]
@@ -437,19 +444,16 @@
 # a console terminal or an X display to run.
 
 def register_X_browsers():
-    # The default Gnome browser
-    if _iscommand("gconftool-2"):
-        # get the web browser string from gconftool
-        gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command 2>/dev/null'
-        out = os.popen(gc)
-        commd = out.read().strip()
-        retncode = out.close()
-
-        # if successful, register it
-        if retncode is None and commd:
-            register("gnome", None, BackgroundBrowser(commd.split()))
 
-    # First, the Mozilla/Netscape browsers
+    # The default GNOME browser
+    if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gnome-open"):
+        register("gnome-open", None, BackgroundBrowser("gnome-open"))
+
+    # The default KDE browser
+    if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"):
+        register("kfmclient", Konqueror, Konqueror("kfmclient"))
+
+    # The Mozilla/Netscape browsers
     for browser in ("mozilla-firefox", "firefox",
                     "mozilla-firebird", "firebird",
                     "seamonkey", "mozilla", "netscape"):
@@ -508,17 +512,28 @@
 if sys.platform[:3] == "win":
     class WindowsDefault(BaseBrowser):
         def open(self, url, new=0, autoraise=1):
-            os.startfile(url)
-            return True # Oh, my...
+            try:
+                os.startfile(url)
+            except WindowsError:
+                # [Error 22] No application is associated with the specified
+                # file for this operation: '<URL>'
+                return False
+            else:
+                return True
 
     _tryorder = []
     _browsers = {}
-    # Prefer mozilla/netscape/opera if present
+
+    # First try to use the default Windows browser
+    register("windows-default", WindowsDefault)
+
+    # Detect some common Windows browsers, fallback to IE
+    iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
+                            "Internet Explorer\\IEXPLORE.EXE")
     for browser in ("firefox", "firebird", "seamonkey", "mozilla",
-                    "netscape", "opera"):
+                    "netscape", "opera", iexplore):
         if _iscommand(browser):
             register(browser, None, BackgroundBrowser(browser))
-    register("windows-default", WindowsDefault)
 
 #
 # Platform support for MacOS

Modified: python/branches/p3yk-noslice/Lib/wsgiref/handlers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/wsgiref/handlers.py	(original)
+++ python/branches/p3yk-noslice/Lib/wsgiref/handlers.py	Wed Jul 11 15:40:56 2007
@@ -8,23 +8,6 @@
 
 __all__ = ['BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler']
 
-try:
-    dict
-except NameError:
-    def dict(items):
-        d = {}
-        for k,v in items:
-            d[k] = v
-        return d
-
-try:
-    True
-    False
-except NameError:
-    True = not None
-    False = not True
-
-
 # Weekday and month names for HTTP date/time formatting; always English!
 _weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
 _monthname = [None, # Dummy so we can use 1-based month numbers

Modified: python/branches/p3yk-noslice/Lib/wsgiref/headers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/wsgiref/headers.py	(original)
+++ python/branches/p3yk-noslice/Lib/wsgiref/headers.py	Wed Jul 11 15:40:56 2007
@@ -5,8 +5,6 @@
 written by Barry Warsaw.
 """
 
-from types import ListType, TupleType
-
 # Regular expression that matches `special' characters in parameters, the
 # existance of which force quoting of the parameter value.
 import re
@@ -44,7 +42,7 @@
     """Manage a collection of HTTP response headers"""
 
     def __init__(self,headers):
-        if type(headers) is not ListType:
+        if not isinstance(headers, list):
             raise TypeError("Headers must be a list of name/value tuples")
         self._headers = headers
 

Modified: python/branches/p3yk-noslice/Lib/wsgiref/util.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/wsgiref/util.py	(original)
+++ python/branches/p3yk-noslice/Lib/wsgiref/util.py	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         data = self.filelike.read(self.blksize)
         if data:
             return data

Modified: python/branches/p3yk-noslice/Lib/wsgiref/validate.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/wsgiref/validate.py	(original)
+++ python/branches/p3yk-noslice/Lib/wsgiref/validate.py	Wed Jul 11 15:40:56 2007
@@ -98,7 +98,7 @@
   - That it is not a string (it should be a list of a single string; a
     string will work, but perform horribly).
 
-  - That .next() returns a string
+  - That .__next__() returns a string
 
   - That the iterator is not iterated over until start_response has
     been called (that can signal either a server or application
@@ -113,7 +113,6 @@
 
 import re
 import sys
-from types import DictType, StringType, TupleType, ListType
 import warnings
 
 header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
@@ -191,20 +190,20 @@
     def read(self, *args):
         assert_(len(args) <= 1)
         v = self.input.read(*args)
-        assert_(type(v) is type(""))
+        assert_(isinstance(v, str))
         return v
 
     def readline(self):
         v = self.input.readline()
-        assert_(type(v) is type(""))
+        assert_(isinstance(v, str))
         return v
 
     def readlines(self, *args):
         assert_(len(args) <= 1)
         lines = self.input.readlines(*args)
-        assert_(type(lines) is type([]))
+        assert_(isinstance(lines, list))
         for line in lines:
-            assert_(type(line) is type(""))
+            assert_(isinstance(line, str))
         return lines
 
     def __iter__(self):
@@ -223,7 +222,7 @@
         self.errors = wsgi_errors
 
     def write(self, s):
-        assert_(type(s) is type(""))
+        assert_(isinstance(s, str))
         self.errors.write(s)
 
     def flush(self):
@@ -242,7 +241,7 @@
         self.writer = wsgi_writer
 
     def __call__(self, s):
-        assert_(type(s) is type(""))
+        assert_(isinstance(s, str))
         self.writer(s)
 
 class PartialIteratorWrapper:
@@ -265,10 +264,10 @@
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         assert_(not self.closed,
             "Iterator read after closed")
-        v = self.iterator.next()
+        v = next(self.iterator)
         if self.check_start_response is not None:
             assert_(self.check_start_response,
                 "The application returns and we started iterating over its body, but start_response has not yet been called")
@@ -288,7 +287,7 @@
             "Iterator garbage collected without being closed")
 
 def check_environ(environ):
-    assert_(type(environ) is DictType,
+    assert_(isinstance(environ, dict),
         "Environment is not of the right type: %r (environment: %r)"
         % (type(environ), environ))
 
@@ -315,11 +314,11 @@
         if '.' in key:
             # Extension, we don't care about its type
             continue
-        assert_(type(environ[key]) is StringType,
+        assert_(isinstance(environ[key], str),
             "Environmental variable %s is not a string: %r (value: %r)"
             % (key, type(environ[key]), environ[key]))
 
-    assert_(type(environ['wsgi.version']) is TupleType,
+    assert_(isinstance(environ['wsgi.version'], tuple),
         "wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
     assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
         "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
@@ -365,7 +364,7 @@
             % (wsgi_errors, attr))
 
 def check_status(status):
-    assert_(type(status) is StringType,
+    assert_(isinstance(status, str),
         "Status must be a string (not %r)" % status)
     # Implicitly check that we can turn it into an integer:
     status_code = status.split(None, 1)[0]
@@ -380,12 +379,12 @@
             % status, WSGIWarning)
 
 def check_headers(headers):
-    assert_(type(headers) is ListType,
+    assert_(isinstance(headers, list),
         "Headers (%r) must be of type list: %r"
         % (headers, type(headers)))
     header_names = {}
     for item in headers:
-        assert_(type(item) is TupleType,
+        assert_(isinstance(item, tuple),
             "Individual headers (%r) must be of type tuple: %r"
             % (item, type(item)))
         assert_(len(item) == 2)
@@ -419,7 +418,7 @@
         assert_(0, "No Content-Type header found in headers (%s)" % headers)
 
 def check_exc_info(exc_info):
-    assert_(exc_info is None or type(exc_info) is type(()),
+    assert_(exc_info is None or isinstance(exc_info, tuple),
         "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
     # More exc_info checks?
 

Modified: python/branches/p3yk-noslice/Lib/xml/dom/domreg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/dom/domreg.py	(original)
+++ python/branches/p3yk-noslice/Lib/xml/dom/domreg.py	Wed Jul 11 15:40:56 2007
@@ -72,7 +72,7 @@
     for creator in well_known_implementations.keys():
         try:
             dom = getDOMImplementation(name = creator)
-        except StandardError: # typically ImportError, or AttributeError
+        except Exception: # typically ImportError, or AttributeError
             continue
         if _good_enough(dom, features):
             return dom

Modified: python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py	(original)
+++ python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py	Wed Jul 11 15:40:56 2007
@@ -228,7 +228,7 @@
             return rc
         raise IndexError
 
-    def next(self):
+    def __next__(self):
         rc = self.getEvent()
         if rc:
             return rc

Modified: python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py	(original)
+++ python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py	Wed Jul 11 15:40:56 2007
@@ -109,7 +109,7 @@
 # structure, and convert it from and to XML.
 ##
 
-import string, sys, re
+import sys, re
 
 from . import ElementPath
 
@@ -762,7 +762,7 @@
             if text is None:
                 text = "&#%d;" % ord(char)
             append(text)
-        return string.join(out, "")
+        return "".join(out)
     try:
         return _encode(pattern.sub(escape_entities, text), "ascii")
     except TypeError:
@@ -772,7 +772,7 @@
 # the following functions assume an ascii-compatible encoding
 # (or "utf-16")
 
-def _escape_cdata(text, encoding=None, replace=string.replace):
+def _escape_cdata(text, encoding=None):
     # escape character data
     try:
         if encoding:
@@ -780,14 +780,14 @@
                 text = _encode(text, encoding)
             except UnicodeError:
                 return _encode_entity(text)
-        text = replace(text, "&", "&amp;")
-        text = replace(text, "<", "&lt;")
-        text = replace(text, ">", "&gt;")
+        text = text.replace("&", "&amp;")
+        text = text.replace("<", "&lt;")
+        text = text.replace(">", "&gt;")
         return text
     except (TypeError, AttributeError):
         _raise_serialization_error(text)
 
-def _escape_attrib(text, encoding=None, replace=string.replace):
+def _escape_attrib(text, encoding=None):
     # escape attribute value
     try:
         if encoding:
@@ -795,11 +795,11 @@
                 text = _encode(text, encoding)
             except UnicodeError:
                 return _encode_entity(text)
-        text = replace(text, "&", "&amp;")
-        text = replace(text, "'", "&apos;") # FIXME: overkill
-        text = replace(text, "\"", "&quot;")
-        text = replace(text, "<", "&lt;")
-        text = replace(text, ">", "&gt;")
+        text = text.replace("&", "&amp;")
+        text = text.replace("'", "&apos;") # FIXME: overkill
+        text = text.replace("\"", "&quot;")
+        text = text.replace("<", "&lt;")
+        text = text.replace(">", "&gt;")
         return text
     except (TypeError, AttributeError):
         _raise_serialization_error(text)
@@ -809,7 +809,7 @@
     # tag and namespace declaration, if any
     if isinstance(tag, QName):
         tag = tag.text
-    namespace_uri, tag = string.split(tag[1:], "}", 1)
+    namespace_uri, tag = tag[1:].split("}", 1)
     prefix = namespaces.get(namespace_uri)
     if prefix is None:
         prefix = _namespace_map.get(namespace_uri)
@@ -893,7 +893,7 @@
                     append((event, None))
                 parser.EndNamespaceDeclHandler = handler
 
-    def next(self):
+    def __next__(self):
         while 1:
             try:
                 item = self._events[self._index]
@@ -923,7 +923,7 @@
             return self
     except NameError:
         def __getitem__(self, index):
-            return self.next()
+            return self.__next__()
 
 ##
 # Parses an XML document from a string constant.  This function can
@@ -982,7 +982,7 @@
     file = dummy()
     file.write = data.append
     ElementTree(element).write(file, encoding)
-    return string.join(data, "")
+    return "".join(data)
 
 ##
 # Generic element structure builder.  This builder converts a sequence
@@ -1021,7 +1021,7 @@
     def _flush(self):
         if self._data:
             if self._last is not None:
-                text = string.join(self._data, "")
+                text = "".join(self._data)
                 if self._tail:
                     assert self._last.tail is None, "internal error (tail)"
                     self._last.tail = text
@@ -1182,7 +1182,7 @@
             if prefix == ">":
                 self._doctype = None
                 return
-            text = string.strip(text)
+            text = text.strip()
             if not text:
                 return
             self._doctype.append(text)

Modified: python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py	(original)
+++ python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py	Wed Jul 11 15:40:56 2007
@@ -3,15 +3,10 @@
 convenience of application and driver writers.
 """
 
-import os, urlparse, urllib, types
+import os, urlparse, urllib
 from . import handler
 from . import xmlreader
 
-try:
-    _StringTypes = [types.StringType, types.UnicodeType]
-except AttributeError:
-    _StringTypes = [types.StringType]
-
 # See whether the xmlcharrefreplace error handler is
 # supported
 try:
@@ -277,7 +272,7 @@
     """This function takes an InputSource and an optional base URL and
     returns a fully resolved InputSource object ready for reading."""
 
-    if type(source) in _StringTypes:
+    if isinstance(source, basestring):
         source = xmlreader.InputSource(source)
     elif hasattr(source, "read"):
         f = source

Deleted: /python/branches/p3yk-noslice/Lib/xmllib.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/xmllib.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,929 +0,0 @@
-"""A parser for XML, using the derived class as static DTD."""
-
-# Author: Sjoerd Mullender.
-
-import re
-import string
-
-import warnings
-warnings.warn("The xmllib module is obsolete.  Use xml.sax instead.", DeprecationWarning)
-del warnings
-
-version = '0.3'
-
-class Error(RuntimeError):
-    pass
-
-# Regular expressions used for parsing
-
-_S = '[ \t\r\n]+'                       # white space
-_opS = '[ \t\r\n]*'                     # optional white space
-_Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*'    # valid XML name
-_QStr = "(?:'[^']*'|\"[^\"]*\")"        # quoted XML string
-illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content
-interesting = re.compile('[]&<]')
-
-amp = re.compile('&')
-ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]')
-entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]')
-charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])')
-space = re.compile(_S + '$')
-newline = re.compile('\n')
-
-attrfind = re.compile(
-    _S + '(?P<name>' + _Name + ')'
-    '(' + _opS + '=' + _opS +
-    '(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?')
-starttagopen = re.compile('<' + _Name)
-starttagend = re.compile(_opS + '(?P<slash>/?)>')
-starttagmatch = re.compile('<(?P<tagname>'+_Name+')'
-                      '(?P<attrs>(?:'+attrfind.pattern+')*)'+
-                      starttagend.pattern)
-endtagopen = re.compile('</')
-endbracket = re.compile(_opS + '>')
-endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>')
-tagfind = re.compile(_Name)
-cdataopen = re.compile(r'<!\[CDATA\[')
-cdataclose = re.compile(r'\]\]>')
-# this matches one of the following:
-# SYSTEM SystemLiteral
-# PUBLIC PubidLiteral SystemLiteral
-_SystemLiteral = '(?P<%s>'+_QStr+')'
-_PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \
-                        "'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')"
-_ExternalId = '(?:SYSTEM|' \
-                 'PUBLIC'+_S+_PublicLiteral%'pubid'+ \
-              ')'+_S+_SystemLiteral%'syslit'
-doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')'
-                     '(?:'+_S+_ExternalId+')?'+_opS)
-xmldecl = re.compile('<\?xml'+_S+
-                     'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+
-                     '(?:'+_S+'encoding'+_opS+'='+_opS+
-                        "(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|"
-                        '"[A-Za-z][-A-Za-z0-9._]*"))?'
-                     '(?:'+_S+'standalone'+_opS+'='+_opS+
-                        '(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+
-                     _opS+'\?>')
-procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS)
-procclose = re.compile(_opS + r'\?>')
-commentopen = re.compile('<!--')
-commentclose = re.compile('-->')
-doubledash = re.compile('--')
-attrtrans = string.maketrans(' \r\n\t', '    ')
-
-# definitions for XML namespaces
-_NCName = '[a-zA-Z_][-a-zA-Z0-9._]*'    # XML Name, minus the ":"
-ncname = re.compile(_NCName + '$')
-qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix
-                   '(?P<local>' + _NCName + ')$')
-
-xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$')
-
-# XML parser base class -- find tags and call handler functions.
-# Usage: p = XMLParser(); p.feed(data); ...; p.close().
-# The dtd is defined by deriving a class which defines methods with
-# special names to handle tags: start_foo and end_foo to handle <foo>
-# and </foo>, respectively.  The data between tags is passed to the
-# parser by calling self.handle_data() with some data as argument (the
-# data may be split up in arbitrary chunks).
-
-class XMLParser:
-    attributes = {}                     # default, to be overridden
-    elements = {}                       # default, to be overridden
-
-    # parsing options, settable using keyword args in __init__
-    __accept_unquoted_attributes = 0
-    __accept_missing_endtag_name = 0
-    __map_case = 0
-    __accept_utf8 = 0
-    __translate_attribute_references = 1
-
-    # Interface -- initialize and reset this instance
-    def __init__(self, **kw):
-        self.__fixed = 0
-        if 'accept_unquoted_attributes' in kw:
-            self.__accept_unquoted_attributes = kw['accept_unquoted_attributes']
-        if 'accept_missing_endtag_name' in kw:
-            self.__accept_missing_endtag_name = kw['accept_missing_endtag_name']
-        if 'map_case' in kw:
-            self.__map_case = kw['map_case']
-        if 'accept_utf8' in kw:
-            self.__accept_utf8 = kw['accept_utf8']
-        if 'translate_attribute_references' in kw:
-            self.__translate_attribute_references = kw['translate_attribute_references']
-        self.reset()
-
-    def __fixelements(self):
-        self.__fixed = 1
-        self.elements = {}
-        self.__fixdict(self.__dict__)
-        self.__fixclass(self.__class__)
-
-    def __fixclass(self, kl):
-        self.__fixdict(kl.__dict__)
-        for k in kl.__bases__:
-            self.__fixclass(k)
-
-    def __fixdict(self, dict):
-        for key in dict.keys():
-            if key[:6] == 'start_':
-                tag = key[6:]
-                start, end = self.elements.get(tag, (None, None))
-                if start is None:
-                    self.elements[tag] = getattr(self, key), end
-            elif key[:4] == 'end_':
-                tag = key[4:]
-                start, end = self.elements.get(tag, (None, None))
-                if end is None:
-                    self.elements[tag] = start, getattr(self, key)
-
-    # Interface -- reset this instance.  Loses all unprocessed data
-    def reset(self):
-        self.rawdata = ''
-        self.stack = []
-        self.nomoretags = 0
-        self.literal = 0
-        self.lineno = 1
-        self.__at_start = 1
-        self.__seen_doctype = None
-        self.__seen_starttag = 0
-        self.__use_namespaces = 0
-        self.__namespaces = {'xml':None}   # xml is implicitly declared
-        # backward compatibility hack: if elements not overridden,
-        # fill it in ourselves
-        if self.elements is XMLParser.elements:
-            self.__fixelements()
-
-    # For derived classes only -- enter literal mode (CDATA) till EOF
-    def setnomoretags(self):
-        self.nomoretags = self.literal = 1
-
-    # For derived classes only -- enter literal mode (CDATA)
-    def setliteral(self, *args):
-        self.literal = 1
-
-    # Interface -- feed some data to the parser.  Call this as
-    # often as you want, with as little or as much text as you
-    # want (may include '\n').  (This just saves the text, all the
-    # processing is done by goahead().)
-    def feed(self, data):
-        self.rawdata = self.rawdata + data
-        self.goahead(0)
-
-    # Interface -- handle the remaining data
-    def close(self):
-        self.goahead(1)
-        if self.__fixed:
-            self.__fixed = 0
-            # remove self.elements so that we don't leak
-            del self.elements
-
-    # Interface -- translate references
-    def translate_references(self, data, all = 1):
-        if not self.__translate_attribute_references:
-            return data
-        i = 0
-        while 1:
-            res = amp.search(data, i)
-            if res is None:
-                return data
-            s = res.start(0)
-            res = ref.match(data, s)
-            if res is None:
-                self.syntax_error("bogus `&'")
-                i = s+1
-                continue
-            i = res.end(0)
-            str = res.group(1)
-            rescan = 0
-            if str[0] == '#':
-                if str[1] == 'x':
-                    str = chr(int(str[2:], 16))
-                else:
-                    str = chr(int(str[1:]))
-                if data[i - 1] != ';':
-                    self.syntax_error("`;' missing after char reference")
-                    i = i-1
-            elif all:
-                if str in self.entitydefs:
-                    str = self.entitydefs[str]
-                    rescan = 1
-                elif data[i - 1] != ';':
-                    self.syntax_error("bogus `&'")
-                    i = s + 1 # just past the &
-                    continue
-                else:
-                    self.syntax_error("reference to unknown entity `&%s;'" % str)
-                    str = '&' + str + ';'
-            elif data[i - 1] != ';':
-                self.syntax_error("bogus `&'")
-                i = s + 1 # just past the &
-                continue
-
-            # when we get here, str contains the translated text and i points
-            # to the end of the string that is to be replaced
-            data = data[:s] + str + data[i:]
-            if rescan:
-                i = s
-            else:
-                i = s + len(str)
-
-    # Interface - return a dictionary of all namespaces currently valid
-    def getnamespace(self):
-        nsdict = {}
-        for t, d, nst in self.stack:
-            nsdict.update(d)
-        return nsdict
-
-    # Internal -- handle data as far as reasonable.  May leave state
-    # and data to be processed by a subsequent call.  If 'end' is
-    # true, force handling all data as if followed by EOF marker.
-    def goahead(self, end):
-        rawdata = self.rawdata
-        i = 0
-        n = len(rawdata)
-        while i < n:
-            if i > 0:
-                self.__at_start = 0
-            if self.nomoretags:
-                data = rawdata[i:n]
-                self.handle_data(data)
-                self.lineno = self.lineno + data.count('\n')
-                i = n
-                break
-            res = interesting.search(rawdata, i)
-            if res:
-                j = res.start(0)
-            else:
-                j = n
-            if i < j:
-                data = rawdata[i:j]
-                if self.__at_start and space.match(data) is None:
-                    self.syntax_error('illegal data at start of file')
-                self.__at_start = 0
-                if not self.stack and space.match(data) is None:
-                    self.syntax_error('data not in content')
-                if not self.__accept_utf8 and illegal.search(data):
-                    self.syntax_error('illegal character in content')
-                self.handle_data(data)
-                self.lineno = self.lineno + data.count('\n')
-            i = j
-            if i == n: break
-            if rawdata[i] == '<':
-                if starttagopen.match(rawdata, i):
-                    if self.literal:
-                        data = rawdata[i]
-                        self.handle_data(data)
-                        self.lineno = self.lineno + data.count('\n')
-                        i = i+1
-                        continue
-                    k = self.parse_starttag(i)
-                    if k < 0: break
-                    self.__seen_starttag = 1
-                    self.lineno = self.lineno + rawdata[i:k].count('\n')
-                    i = k
-                    continue
-                if endtagopen.match(rawdata, i):
-                    k = self.parse_endtag(i)
-                    if k < 0: break
-                    self.lineno = self.lineno + rawdata[i:k].count('\n')
-                    i =  k
-                    continue
-                if commentopen.match(rawdata, i):
-                    if self.literal:
-                        data = rawdata[i]
-                        self.handle_data(data)
-                        self.lineno = self.lineno + data.count('\n')
-                        i = i+1
-                        continue
-                    k = self.parse_comment(i)
-                    if k < 0: break
-                    self.lineno = self.lineno + rawdata[i:k].count('\n')
-                    i = k
-                    continue
-                if cdataopen.match(rawdata, i):
-                    k = self.parse_cdata(i)
-                    if k < 0: break
-                    self.lineno = self.lineno + rawdata[i:k].count('\n')
-                    i = k
-                    continue
-                res = xmldecl.match(rawdata, i)
-                if res:
-                    if not self.__at_start:
-                        self.syntax_error("<?xml?> declaration not at start of document")
-                    version, encoding, standalone = res.group('version',
-                                                              'encoding',
-                                                              'standalone')
-                    if version[1:-1] != '1.0':
-                        raise Error('only XML version 1.0 supported')
-                    if encoding: encoding = encoding[1:-1]
-                    if standalone: standalone = standalone[1:-1]
-                    self.handle_xml(encoding, standalone)
-                    i = res.end(0)
-                    continue
-                res = procopen.match(rawdata, i)
-                if res:
-                    k = self.parse_proc(i)
-                    if k < 0: break
-                    self.lineno = self.lineno + rawdata[i:k].count('\n')
-                    i = k
-                    continue
-                res = doctype.match(rawdata, i)
-                if res:
-                    if self.literal:
-                        data = rawdata[i]
-                        self.handle_data(data)
-                        self.lineno = self.lineno + data.count('\n')
-                        i = i+1
-                        continue
-                    if self.__seen_doctype:
-                        self.syntax_error('multiple DOCTYPE elements')
-                    if self.__seen_starttag:
-                        self.syntax_error('DOCTYPE not at beginning of document')
-                    k = self.parse_doctype(res)
-                    if k < 0: break
-                    self.__seen_doctype = res.group('name')
-                    if self.__map_case:
-                        self.__seen_doctype = self.__seen_doctype.lower()
-                    self.lineno = self.lineno + rawdata[i:k].count('\n')
-                    i = k
-                    continue
-            elif rawdata[i] == '&':
-                if self.literal:
-                    data = rawdata[i]
-                    self.handle_data(data)
-                    i = i+1
-                    continue
-                res = charref.match(rawdata, i)
-                if res is not None:
-                    i = res.end(0)
-                    if rawdata[i-1] != ';':
-                        self.syntax_error("`;' missing in charref")
-                        i = i-1
-                    if not self.stack:
-                        self.syntax_error('data not in content')
-                    self.handle_charref(res.group('char')[:-1])
-                    self.lineno = self.lineno + res.group(0).count('\n')
-                    continue
-                res = entityref.match(rawdata, i)
-                if res is not None:
-                    i = res.end(0)
-                    if rawdata[i-1] != ';':
-                        self.syntax_error("`;' missing in entityref")
-                        i = i-1
-                    name = res.group('name')
-                    if self.__map_case:
-                        name = name.lower()
-                    if name in self.entitydefs:
-                        self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:]
-                        n = len(rawdata)
-                        i = res.start(0)
-                    else:
-                        self.unknown_entityref(name)
-                    self.lineno = self.lineno + res.group(0).count('\n')
-                    continue
-            elif rawdata[i] == ']':
-                if self.literal:
-                    data = rawdata[i]
-                    self.handle_data(data)
-                    i = i+1
-                    continue
-                if n-i < 3:
-                    break
-                if cdataclose.match(rawdata, i):
-                    self.syntax_error("bogus `]]>'")
-                self.handle_data(rawdata[i])
-                i = i+1
-                continue
-            else:
-                raise Error('neither < nor & ??')
-            # We get here only if incomplete matches but
-            # nothing else
-            break
-        # end while
-        if i > 0:
-            self.__at_start = 0
-        if end and i < n:
-            data = rawdata[i]
-            self.syntax_error("bogus `%s'" % data)
-            if not self.__accept_utf8 and illegal.search(data):
-                self.syntax_error('illegal character in content')
-            self.handle_data(data)
-            self.lineno = self.lineno + data.count('\n')
-            self.rawdata = rawdata[i+1:]
-            return self.goahead(end)
-        self.rawdata = rawdata[i:]
-        if end:
-            if not self.__seen_starttag:
-                self.syntax_error('no elements in file')
-            if self.stack:
-                self.syntax_error('missing end tags')
-                while self.stack:
-                    self.finish_endtag(self.stack[-1][0])
-
-    # Internal -- parse comment, return length or -1 if not terminated
-    def parse_comment(self, i):
-        rawdata = self.rawdata
-        if rawdata[i:i+4] != '<!--':
-            raise Error('unexpected call to handle_comment')
-        res = commentclose.search(rawdata, i+4)
-        if res is None:
-            return -1
-        if doubledash.search(rawdata, i+4, res.start(0)):
-            self.syntax_error("`--' inside comment")
-        if rawdata[res.start(0)-1] == '-':
-            self.syntax_error('comment cannot end in three dashes')
-        if not self.__accept_utf8 and \
-           illegal.search(rawdata, i+4, res.start(0)):
-            self.syntax_error('illegal character in comment')
-        self.handle_comment(rawdata[i+4: res.start(0)])
-        return res.end(0)
-
-    # Internal -- handle DOCTYPE tag, return length or -1 if not terminated
-    def parse_doctype(self, res):
-        rawdata = self.rawdata
-        n = len(rawdata)
-        name = res.group('name')
-        if self.__map_case:
-            name = name.lower()
-        pubid, syslit = res.group('pubid', 'syslit')
-        if pubid is not None:
-            pubid = pubid[1:-1]         # remove quotes
-            pubid = ' '.join(pubid.split()) # normalize
-        if syslit is not None: syslit = syslit[1:-1] # remove quotes
-        j = k = res.end(0)
-        if k >= n:
-            return -1
-        if rawdata[k] == '[':
-            level = 0
-            k = k+1
-            dq = sq = 0
-            while k < n:
-                c = rawdata[k]
-                if not sq and c == '"':
-                    dq = not dq
-                elif not dq and c == "'":
-                    sq = not sq
-                elif sq or dq:
-                    pass
-                elif level <= 0 and c == ']':
-                    res = endbracket.match(rawdata, k+1)
-                    if res is None:
-                        return -1
-                    self.handle_doctype(name, pubid, syslit, rawdata[j+1:k])
-                    return res.end(0)
-                elif c == '<':
-                    level = level + 1
-                elif c == '>':
-                    level = level - 1
-                    if level < 0:
-                        self.syntax_error("bogus `>' in DOCTYPE")
-                k = k+1
-        res = endbracketfind.match(rawdata, k)
-        if res is None:
-            return -1
-        if endbracket.match(rawdata, k) is None:
-            self.syntax_error('garbage in DOCTYPE')
-        self.handle_doctype(name, pubid, syslit, None)
-        return res.end(0)
-
-    # Internal -- handle CDATA tag, return length or -1 if not terminated
-    def parse_cdata(self, i):
-        rawdata = self.rawdata
-        if rawdata[i:i+9] != '<![CDATA[':
-            raise Error('unexpected call to parse_cdata')
-        res = cdataclose.search(rawdata, i+9)
-        if res is None:
-            return -1
-        if not self.__accept_utf8 and \
-           illegal.search(rawdata, i+9, res.start(0)):
-            self.syntax_error('illegal character in CDATA')
-        if not self.stack:
-            self.syntax_error('CDATA not in content')
-        self.handle_cdata(rawdata[i+9:res.start(0)])
-        return res.end(0)
-
-    __xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None}
-    # Internal -- handle a processing instruction tag
-    def parse_proc(self, i):
-        rawdata = self.rawdata
-        end = procclose.search(rawdata, i)
-        if end is None:
-            return -1
-        j = end.start(0)
-        if not self.__accept_utf8 and illegal.search(rawdata, i+2, j):
-            self.syntax_error('illegal character in processing instruction')
-        res = tagfind.match(rawdata, i+2)
-        if res is None:
-            raise Error('unexpected call to parse_proc')
-        k = res.end(0)
-        name = res.group(0)
-        if self.__map_case:
-            name = name.lower()
-        if name == 'xml:namespace':
-            self.syntax_error('old-fashioned namespace declaration')
-            self.__use_namespaces = -1
-            # namespace declaration
-            # this must come after the <?xml?> declaration (if any)
-            # and before the <!DOCTYPE> (if any).
-            if self.__seen_doctype or self.__seen_starttag:
-                self.syntax_error('xml:namespace declaration too late in document')
-            attrdict, namespace, k = self.parse_attributes(name, k, j)
-            if namespace:
-                self.syntax_error('namespace declaration inside namespace declaration')
-            for attrname in attrdict.keys():
-                if not attrname in self.__xml_namespace_attributes:
-                    self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname)
-            if not 'ns' in attrdict or not 'prefix' in attrdict:
-                self.syntax_error('xml:namespace without required attributes')
-            prefix = attrdict.get('prefix')
-            if ncname.match(prefix) is None:
-                self.syntax_error('xml:namespace illegal prefix value')
-                return end.end(0)
-            if prefix in self.__namespaces:
-                self.syntax_error('xml:namespace prefix not unique')
-            self.__namespaces[prefix] = attrdict['ns']
-        else:
-            if name.lower() == 'xml':
-                self.syntax_error('illegal processing instruction target name')
-            self.handle_proc(name, rawdata[k:j])
-        return end.end(0)
-
-    # Internal -- parse attributes between i and j
-    def parse_attributes(self, tag, i, j):
-        rawdata = self.rawdata
-        attrdict = {}
-        namespace = {}
-        while i < j:
-            res = attrfind.match(rawdata, i)
-            if res is None:
-                break
-            attrname, attrvalue = res.group('name', 'value')
-            if self.__map_case:
-                attrname = attrname.lower()
-            i = res.end(0)
-            if attrvalue is None:
-                self.syntax_error("no value specified for attribute `%s'" % attrname)
-                attrvalue = attrname
-            elif attrvalue[:1] == "'" == attrvalue[-1:] or \
-                 attrvalue[:1] == '"' == attrvalue[-1:]:
-                attrvalue = attrvalue[1:-1]
-            elif not self.__accept_unquoted_attributes:
-                self.syntax_error("attribute `%s' value not quoted" % attrname)
-            res = xmlns.match(attrname)
-            if res is not None:
-                # namespace declaration
-                ncname = res.group('ncname')
-                namespace[ncname or ''] = attrvalue or None
-                if not self.__use_namespaces:
-                    self.__use_namespaces = len(self.stack)+1
-                continue
-            if '<' in attrvalue:
-                self.syntax_error("`<' illegal in attribute value")
-            if attrname in attrdict:
-                self.syntax_error("attribute `%s' specified twice" % attrname)
-            attrvalue = attrvalue.translate(attrtrans)
-            attrdict[attrname] = self.translate_references(attrvalue)
-        return attrdict, namespace, i
-
-    # Internal -- handle starttag, return length or -1 if not terminated
-    def parse_starttag(self, i):
-        rawdata = self.rawdata
-        # i points to start of tag
-        end = endbracketfind.match(rawdata, i+1)
-        if end is None:
-            return -1
-        tag = starttagmatch.match(rawdata, i)
-        if tag is None or tag.end(0) != end.end(0):
-            self.syntax_error('garbage in starttag')
-            return end.end(0)
-        nstag = tagname = tag.group('tagname')
-        if self.__map_case:
-            nstag = tagname = nstag.lower()
-        if not self.__seen_starttag and self.__seen_doctype and \
-           tagname != self.__seen_doctype:
-            self.syntax_error('starttag does not match DOCTYPE')
-        if self.__seen_starttag and not self.stack:
-            self.syntax_error('multiple elements on top level')
-        k, j = tag.span('attrs')
-        attrdict, nsdict, k = self.parse_attributes(tagname, k, j)
-        self.stack.append((tagname, nsdict, nstag))
-        if self.__use_namespaces:
-            res = qname.match(tagname)
-        else:
-            res = None
-        if res is not None:
-            prefix, nstag = res.group('prefix', 'local')
-            if prefix is None:
-                prefix = ''
-            ns = None
-            for t, d, nst in self.stack:
-                if prefix in d:
-                    ns = d[prefix]
-            if ns is None and prefix != '':
-                ns = self.__namespaces.get(prefix)
-            if ns is not None:
-                nstag = ns + ' ' + nstag
-            elif prefix != '':
-                nstag = prefix + ':' + nstag # undo split
-            self.stack[-1] = tagname, nsdict, nstag
-        # translate namespace of attributes
-        attrnamemap = {} # map from new name to old name (used for error reporting)
-        for key in attrdict.keys():
-            attrnamemap[key] = key
-        if self.__use_namespaces:
-            nattrdict = {}
-            for key, val in attrdict.items():
-                okey = key
-                res = qname.match(key)
-                if res is not None:
-                    aprefix, key = res.group('prefix', 'local')
-                    if self.__map_case:
-                        key = key.lower()
-                    if aprefix is not None:
-                        ans = None
-                        for t, d, nst in self.stack:
-                            if aprefix in d:
-                                ans = d[aprefix]
-                        if ans is None:
-                            ans = self.__namespaces.get(aprefix)
-                        if ans is not None:
-                            key = ans + ' ' + key
-                        else:
-                            key = aprefix + ':' + key
-                nattrdict[key] = val
-                attrnamemap[key] = okey
-            attrdict = nattrdict
-        attributes = self.attributes.get(nstag)
-        if attributes is not None:
-            for key in attrdict.keys():
-                if not key in attributes:
-                    self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname))
-            for key, val in attributes.items():
-                if val is not None and not key in attrdict:
-                    attrdict[key] = val
-        method = self.elements.get(nstag, (None, None))[0]
-        self.finish_starttag(nstag, attrdict, method)
-        if tag.group('slash') == '/':
-            self.finish_endtag(tagname)
-        return tag.end(0)
-
-    # Internal -- parse endtag
-    def parse_endtag(self, i):
-        rawdata = self.rawdata
-        end = endbracketfind.match(rawdata, i+1)
-        if end is None:
-            return -1
-        res = tagfind.match(rawdata, i+2)
-        if res is None:
-            if self.literal:
-                self.handle_data(rawdata[i])
-                return i+1
-            if not self.__accept_missing_endtag_name:
-                self.syntax_error('no name specified in end tag')
-            tag = self.stack[-1][0]
-            k = i+2
-        else:
-            tag = res.group(0)
-            if self.__map_case:
-                tag = tag.lower()
-            if self.literal:
-                if not self.stack or tag != self.stack[-1][0]:
-                    self.handle_data(rawdata[i])
-                    return i+1
-            k = res.end(0)
-        if endbracket.match(rawdata, k) is None:
-            self.syntax_error('garbage in end tag')
-        self.finish_endtag(tag)
-        return end.end(0)
-
-    # Internal -- finish processing of start tag
-    def finish_starttag(self, tagname, attrdict, method):
-        if method is not None:
-            self.handle_starttag(tagname, method, attrdict)
-        else:
-            self.unknown_starttag(tagname, attrdict)
-
-    # Internal -- finish processing of end tag
-    def finish_endtag(self, tag):
-        self.literal = 0
-        if not tag:
-            self.syntax_error('name-less end tag')
-            found = len(self.stack) - 1
-            if found < 0:
-                self.unknown_endtag(tag)
-                return
-        else:
-            found = -1
-            for i in range(len(self.stack)):
-                if tag == self.stack[i][0]:
-                    found = i
-            if found == -1:
-                self.syntax_error('unopened end tag')
-                return
-        while len(self.stack) > found:
-            if found < len(self.stack) - 1:
-                self.syntax_error('missing close tag for %s' % self.stack[-1][2])
-            nstag = self.stack[-1][2]
-            method = self.elements.get(nstag, (None, None))[1]
-            if method is not None:
-                self.handle_endtag(nstag, method)
-            else:
-                self.unknown_endtag(nstag)
-            if self.__use_namespaces == len(self.stack):
-                self.__use_namespaces = 0
-            del self.stack[-1]
-
-    # Overridable -- handle xml processing instruction
-    def handle_xml(self, encoding, standalone):
-        pass
-
-    # Overridable -- handle DOCTYPE
-    def handle_doctype(self, tag, pubid, syslit, data):
-        pass
-
-    # Overridable -- handle start tag
-    def handle_starttag(self, tag, method, attrs):
-        method(attrs)
-
-    # Overridable -- handle end tag
-    def handle_endtag(self, tag, method):
-        method()
-
-    # Example -- handle character reference, no need to override
-    def handle_charref(self, name):
-        try:
-            if name[0] == 'x':
-                n = int(name[1:], 16)
-            else:
-                n = int(name)
-        except ValueError:
-            self.unknown_charref(name)
-            return
-        if not 0 <= n <= 255:
-            self.unknown_charref(name)
-            return
-        self.handle_data(chr(n))
-
-    # Definition of entities -- derived classes may override
-    entitydefs = {'lt': '&#60;',        # must use charref
-                  'gt': '&#62;',
-                  'amp': '&#38;',       # must use charref
-                  'quot': '&#34;',
-                  'apos': '&#39;',
-                  }
-
-    # Example -- handle data, should be overridden
-    def handle_data(self, data):
-        pass
-
-    # Example -- handle cdata, could be overridden
-    def handle_cdata(self, data):
-        pass
-
-    # Example -- handle comment, could be overridden
-    def handle_comment(self, data):
-        pass
-
-    # Example -- handle processing instructions, could be overridden
-    def handle_proc(self, name, data):
-        pass
-
-    # Example -- handle relatively harmless syntax errors, could be overridden
-    def syntax_error(self, message):
-        raise Error('Syntax error at line %d: %s' % (self.lineno, message))
-
-    # To be overridden -- handlers for unknown objects
-    def unknown_starttag(self, tag, attrs): pass
-    def unknown_endtag(self, tag): pass
-    def unknown_charref(self, ref): pass
-    def unknown_entityref(self, name):
-        self.syntax_error("reference to unknown entity `&%s;'" % name)
-
-
-class TestXMLParser(XMLParser):
-
-    def __init__(self, **kw):
-        self.testdata = ""
-        XMLParser.__init__(self, **kw)
-
-    def handle_xml(self, encoding, standalone):
-        self.flush()
-        print('xml: encoding =',encoding,'standalone =',standalone)
-
-    def handle_doctype(self, tag, pubid, syslit, data):
-        self.flush()
-        print('DOCTYPE:',tag, repr(data))
-
-    def handle_data(self, data):
-        self.testdata = self.testdata + data
-        if len(repr(self.testdata)) >= 70:
-            self.flush()
-
-    def flush(self):
-        data = self.testdata
-        if data:
-            self.testdata = ""
-            print('data:', repr(data))
-
-    def handle_cdata(self, data):
-        self.flush()
-        print('cdata:', repr(data))
-
-    def handle_proc(self, name, data):
-        self.flush()
-        print('processing:',name,repr(data))
-
-    def handle_comment(self, data):
-        self.flush()
-        r = repr(data)
-        if len(r) > 68:
-            r = r[:32] + '...' + r[-32:]
-        print('comment:', r)
-
-    def syntax_error(self, message):
-        print('error at line %d:' % self.lineno, message)
-
-    def unknown_starttag(self, tag, attrs):
-        self.flush()
-        if not attrs:
-            print('start tag: <' + tag + '>')
-        else:
-            print('start tag: <' + tag, end=' ')
-            for name, value in attrs.items():
-                print(name + '=' + '"' + value + '"', end=' ')
-            print('>')
-
-    def unknown_endtag(self, tag):
-        self.flush()
-        print('end tag: </' + tag + '>')
-
-    def unknown_entityref(self, ref):
-        self.flush()
-        print('*** unknown entity ref: &' + ref + ';')
-
-    def unknown_charref(self, ref):
-        self.flush()
-        print('*** unknown char ref: &#' + ref + ';')
-
-    def close(self):
-        XMLParser.close(self)
-        self.flush()
-
-def test(args = None):
-    import sys, getopt
-    from time import time
-
-    if not args:
-        args = sys.argv[1:]
-
-    opts, args = getopt.getopt(args, 'st')
-    klass = TestXMLParser
-    do_time = 0
-    for o, a in opts:
-        if o == '-s':
-            klass = XMLParser
-        elif o == '-t':
-            do_time = 1
-
-    if args:
-        file = args[0]
-    else:
-        file = 'test.xml'
-
-    if file == '-':
-        f = sys.stdin
-    else:
-        try:
-            f = open(file, 'r')
-        except IOError as msg:
-            print(file, ":", msg)
-            sys.exit(1)
-
-    data = f.read()
-    if f is not sys.stdin:
-        f.close()
-
-    x = klass()
-    t0 = time()
-    try:
-        if do_time:
-            x.feed(data)
-            x.close()
-        else:
-            for c in data:
-                x.feed(c)
-            x.close()
-    except Error as msg:
-        t1 = time()
-        print(msg)
-        if do_time:
-            print('total time: %g' % (t1-t0))
-        sys.exit(1)
-    t1 = time()
-    if do_time:
-        print('total time: %g' % (t1-t0))
-
-
-if __name__ == '__main__':
-    test()

Modified: python/branches/p3yk-noslice/Lib/xmlrpclib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xmlrpclib.py	(original)
+++ python/branches/p3yk-noslice/Lib/xmlrpclib.py	Wed Jul 11 15:40:56 2007
@@ -136,9 +136,7 @@
                  name (None if not present).
 """
 
-import re, string, time, operator
-
-from types import *
+import re, time, operator
 
 # --------------------------------------------------------------------
 # Internal stuff
@@ -164,10 +162,10 @@
         data = unicode(data, encoding)
     return data
 
-def escape(s, replace=string.replace):
-    s = replace(s, "&", "&amp;")
-    s = replace(s, "<", "&lt;")
-    return replace(s, ">", "&gt;",)
+def escape(s):
+    s = s.replace("&", "&amp;")
+    s = s.replace("<", "&lt;")
+    return s.replace(">", "&gt;",)
 
 if unicode:
     def _stringify(string):
@@ -283,8 +281,6 @@
 #              all other values are interpreted as False.
 
 boolean = Boolean = bool
-# to avoid breaking code which references xmlrpclib.{True,False}
-True, False = True, False
 
 ##
 # Wrapper for XML-RPC DateTime values.  This converts a time value to
@@ -306,7 +302,7 @@
     """
 
     def __init__(self, value=0):
-        if not isinstance(value, StringType):
+        if not isinstance(value, str):
             if datetime and isinstance(value, datetime.datetime):
                 self.value = value.strftime("%Y%m%dT%H:%M:%S")
                 return
@@ -317,7 +313,7 @@
                 today = datetime.datetime.now().strftime("%Y%m%d")
                 self.value = value.strftime(today+"T%H:%M:%S")
                 return
-            if not isinstance(value, (TupleType, time.struct_time)):
+            if not isinstance(value, (tuple, time.struct_time)):
                 if value == 0:
                     value = time.time()
                 value = time.localtime(value)
@@ -346,8 +342,7 @@
         return "<DateTime %s at %x>" % (repr(self.value), id(self))
 
     def decode(self, data):
-        data = str(data)
-        self.value = string.strip(data)
+        self.value = str(data).strip()
 
     def encode(self, out):
         out.write("<value><dateTime.iso8601>")
@@ -513,24 +508,6 @@
             self._parser.Parse("", 1) # end of data
             del self._target, self._parser # get rid of circular references
 
-class SlowParser:
-    """Default XML parser (based on xmllib.XMLParser)."""
-    # this is about 10 times slower than sgmlop, on roundtrip
-    # testing.
-    def __init__(self, target):
-        import xmllib # lazy subclassing (!)
-        if xmllib.XMLParser not in SlowParser.__bases__:
-            SlowParser.__bases__ = (xmllib.XMLParser,)
-        self.handle_xml = target.xml
-        self.unknown_starttag = target.start
-        self.handle_data = target.data
-        self.handle_cdata = target.data
-        self.unknown_endtag = target.end
-        try:
-            xmllib.XMLParser.__init__(self, accept_utf8=1)
-        except TypeError:
-            xmllib.XMLParser.__init__(self) # pre-2.0
-
 # --------------------------------------------------------------------
 # XML-RPC marshalling and unmarshalling code
 
@@ -586,7 +563,7 @@
                 dump(v, write)
                 write("</param>\n")
             write("</params>\n")
-        result = string.join(out, "")
+        result = "".join(out)
         return result
 
     def __dump(self, value, write):
@@ -613,7 +590,7 @@
         if not self.allow_none:
             raise TypeError, "cannot marshal None unless allow_none is enabled"
         write("<value><nil/></value>")
-    dispatch[NoneType] = dump_nil
+    dispatch[type(None)] = dump_nil
 
     def dump_int(self, value, write):
         # in case ints are > 32 bits
@@ -622,7 +599,7 @@
         write("<value><int>")
         write(str(value))
         write("</int></value>\n")
-    dispatch[IntType] = dump_int
+    #dispatch[int] = dump_int
 
     if _bool_is_builtin:
         def dump_bool(self, value, write):
@@ -637,19 +614,19 @@
         write("<value><int>")
         write(str(int(value)))
         write("</int></value>\n")
-    dispatch[LongType] = dump_long
+    dispatch[int] = dump_long
 
     def dump_double(self, value, write):
         write("<value><double>")
         write(repr(value))
         write("</double></value>\n")
-    dispatch[FloatType] = dump_double
+    dispatch[float] = dump_double
 
     def dump_string(self, value, write, escape=escape):
         write("<value><string>")
         write(escape(value))
         write("</string></value>\n")
-    dispatch[StringType] = dump_string
+    dispatch[str] = dump_string
 
     if unicode:
         def dump_unicode(self, value, write, escape=escape):
@@ -657,7 +634,7 @@
             write("<value><string>")
             write(escape(value))
             write("</string></value>\n")
-        dispatch[UnicodeType] = dump_unicode
+        dispatch[unicode] = dump_unicode
 
     def dump_array(self, value, write):
         i = id(value)
@@ -670,8 +647,8 @@
             dump(v, write)
         write("</data></array></value>\n")
         del self.memo[i]
-    dispatch[TupleType] = dump_array
-    dispatch[ListType] = dump_array
+    dispatch[tuple] = dump_array
+    dispatch[list] = dump_array
 
     def dump_struct(self, value, write, escape=escape):
         i = id(value)
@@ -682,8 +659,8 @@
         write("<value><struct>\n")
         for k, v in value.items():
             write("<member>\n")
-            if type(k) is not StringType:
-                if unicode and type(k) is UnicodeType:
+            if not isinstance(k, str):
+                if unicode and isinstance(k, unicode):
                     k = k.encode(self.encoding)
                 else:
                     raise TypeError, "dictionary key must be string"
@@ -692,7 +669,7 @@
             write("</member>\n")
         write("</struct></value>\n")
         del self.memo[i]
-    dispatch[DictType] = dump_struct
+    dispatch[dict] = dump_struct
 
     if datetime:
         def dump_datetime(self, value, write):
@@ -786,14 +763,14 @@
     def data(self, text):
         self._data.append(text)
 
-    def end(self, tag, join=string.join):
+    def end(self, tag):
         # call the appropriate end tag handler
         try:
             f = self.dispatch[tag]
         except KeyError:
             pass # unknown tag ?
         else:
-            return f(self, join(self._data, ""))
+            return f(self, "".join(self._data))
 
     #
     # accelerator support
@@ -1040,12 +1017,10 @@
     where necessary.
     """
 
-    assert isinstance(params, TupleType) or isinstance(params, Fault),\
-           "argument must be tuple or Fault instance"
-
+    assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
     if isinstance(params, Fault):
         methodresponse = 1
-    elif methodresponse and isinstance(params, TupleType):
+    elif methodresponse and isinstance(params, tuple):
         assert len(params) == 1, "response tuple must be a singleton"
 
     if not encoding:
@@ -1066,7 +1041,7 @@
     # standard XML-RPC wrappings
     if methodname:
         # a method call
-        if not isinstance(methodname, StringType):
+        if not isinstance(methodname, str):
             methodname = methodname.encode(encoding)
         data = (
             xmlheader,
@@ -1085,7 +1060,7 @@
             )
     else:
         return data # return as is
-    return string.join(data, "")
+    return "".join(data)
 
 ##
 # Convert an XML-RPC packet to a Python object.  If the XML-RPC packet
@@ -1201,7 +1176,7 @@
     def get_host_info(self, host):
 
         x509 = {}
-        if isinstance(host, TupleType):
+        if isinstance(host, tuple):
             host, x509 = host
 
         import urllib
@@ -1210,7 +1185,7 @@
         if auth:
             import base64
             auth = base64.encodestring(urllib.unquote(auth))
-            auth = string.join(string.split(auth), "") # get rid of whitespace
+            auth = "".join(auth.split()) # get rid of whitespace
             extra_headers = [
                 ("Authorization", "Basic " + auth)
                 ]
@@ -1251,7 +1226,7 @@
         host, extra_headers, x509 = self.get_host_info(host)
         connection.putheader("Host", host)
         if extra_headers:
-            if isinstance(extra_headers, DictType):
+            if isinstance(extra_headers, dict):
                 extra_headers = extra_headers.items()
             for key, value in extra_headers:
                 connection.putheader(key, value)

Modified: python/branches/p3yk-noslice/Lib/zipfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/zipfile.py	(original)
+++ python/branches/p3yk-noslice/Lib/zipfile.py	Wed Jul 11 15:40:56 2007
@@ -348,13 +348,213 @@
 
     def __call__(self, c):
         """Decrypt a single character."""
-        c = ord(c)
+        # XXX When this is called with a byte instead of a char, ord()
+        # isn't needed.  Don't die in that case.  In the future we should
+        # just leave this out, once we're always using bytes.
+        try:
+            c = ord(c)
+        except TypeError:
+            pass
         k = self.key2 | 2
         c = c ^ (((k * (k^1)) >> 8) & 255)
         c = chr(c)
         self._UpdateKeys(c)
         return c
 
+class ZipExtFile:
+    """File-like object for reading an archive member.
+       Is returned by ZipFile.open().
+    """
+
+    def __init__(self, fileobj, zipinfo, decrypt=None):
+        self.fileobj = fileobj
+        self.decrypter = decrypt
+        self.bytes_read = 0
+        self.rawbuffer = ''
+        self.readbuffer = ''
+        self.linebuffer = ''
+        self.eof = False
+        self.univ_newlines = False
+        self.nlSeps = ("\n", )
+        self.lastdiscard = ''
+
+        self.compress_type = zipinfo.compress_type
+        self.compress_size = zipinfo.compress_size
+
+        self.closed  = False
+        self.mode    = "r"
+        self.name = zipinfo.filename
+
+        # read from compressed files in 64k blocks
+        self.compreadsize = 64*1024
+        if self.compress_type == ZIP_DEFLATED:
+            self.dc = zlib.decompressobj(-15)
+
+    def set_univ_newlines(self, univ_newlines):
+        self.univ_newlines = univ_newlines
+
+        # pick line separator char(s) based on universal newlines flag
+        self.nlSeps = ("\n", )
+        if self.univ_newlines:
+            self.nlSeps = ("\r\n", "\r", "\n")
+
+    def __iter__(self):
+        return self
+
+    def __next__(self):
+        nextline = self.readline()
+        if not nextline:
+            raise StopIteration()
+
+        return nextline
+
+    def close(self):
+        self.closed = True
+
+    def _checkfornewline(self):
+        nl, nllen = -1, -1
+        if self.linebuffer:
+            # ugly check for cases where half of an \r\n pair was
+            # read on the last pass, and the \r was discarded.  In this
+            # case we just throw away the \n at the start of the buffer.
+            if (self.lastdiscard, self.linebuffer[0]) == ('\r','\n'):
+                self.linebuffer = self.linebuffer[1:]
+
+            for sep in self.nlSeps:
+                nl = self.linebuffer.find(sep)
+                if nl >= 0:
+                    nllen = len(sep)
+                    return nl, nllen
+
+        return nl, nllen
+
+    def readline(self, size = -1):
+        """Read a line with approx. size. If size is negative,
+           read a whole line.
+        """
+        if size < 0:
+            size = sys.maxint
+        elif size == 0:
+            return ''
+
+        # check for a newline already in buffer
+        nl, nllen = self._checkfornewline()
+
+        if nl >= 0:
+            # the next line was already in the buffer
+            nl = min(nl, size)
+        else:
+            # no line break in buffer - try to read more
+            size -= len(self.linebuffer)
+            while nl < 0 and size > 0:
+                buf = self.read(min(size, 100))
+                if not buf:
+                    break
+                self.linebuffer += buf
+                size -= len(buf)
+
+                # check for a newline in buffer
+                nl, nllen = self._checkfornewline()
+
+            # we either ran out of bytes in the file, or
+            # met the specified size limit without finding a newline,
+            # so return current buffer
+            if nl < 0:
+                s = self.linebuffer
+                self.linebuffer = ''
+                return s
+
+        buf = self.linebuffer[:nl]
+        self.lastdiscard = self.linebuffer[nl:nl + nllen]
+        self.linebuffer = self.linebuffer[nl + nllen:]
+
+        # line is always returned with \n as newline char (except possibly
+        # for a final incomplete line in the file, which is handled above).
+        return buf + "\n"
+
+    def readlines(self, sizehint = -1):
+        """Return a list with all (following) lines. The sizehint parameter
+        is ignored in this implementation.
+        """
+        result = []
+        while True:
+            line = self.readline()
+            if not line: break
+            result.append(line)
+        return result
+
+    def read(self, size = None):
+        # act like file() obj and return empty string if size is 0
+        if size == 0:
+            return ''
+
+        # determine read size
+        bytesToRead = self.compress_size - self.bytes_read
+
+        # adjust read size for encrypted files since the first 12 bytes
+        # are for the encryption/password information
+        if self.decrypter is not None:
+            bytesToRead -= 12
+
+        if size is not None and size >= 0:
+            if self.compress_type == ZIP_STORED:
+                lr = len(self.readbuffer)
+                bytesToRead = min(bytesToRead, size - lr)
+            elif self.compress_type == ZIP_DEFLATED:
+                if len(self.readbuffer) > size:
+                    # the user has requested fewer bytes than we've already
+                    # pulled through the decompressor; don't read any more
+                    bytesToRead = 0
+                else:
+                    # user will use up the buffer, so read some more
+                    lr = len(self.rawbuffer)
+                    bytesToRead = min(bytesToRead, self.compreadsize - lr)
+
+        # avoid reading past end of file contents
+        if bytesToRead + self.bytes_read > self.compress_size:
+            bytesToRead = self.compress_size - self.bytes_read
+
+        # try to read from file (if necessary)
+        if bytesToRead > 0:
+            bytes = self.fileobj.read(bytesToRead)
+            self.bytes_read += len(bytes)
+            self.rawbuffer += bytes
+
+            # handle contents of raw buffer
+            if self.rawbuffer:
+                newdata = self.rawbuffer
+                self.rawbuffer = ''
+
+                # decrypt new data if we were given an object to handle that
+                if newdata and self.decrypter is not None:
+                    newdata = ''.join(map(self.decrypter, newdata))
+
+                # decompress newly read data if necessary
+                if newdata and self.compress_type == ZIP_DEFLATED:
+                    newdata = self.dc.decompress(newdata)
+                    self.rawbuffer = self.dc.unconsumed_tail
+                    if self.eof and len(self.rawbuffer) == 0:
+                        # we're out of raw bytes (both from the file and
+                        # the local buffer); flush just to make sure the
+                        # decompressor is done
+                        newdata += self.dc.flush()
+                        # prevent decompressor from being used again
+                        self.dc = None
+
+                self.readbuffer += newdata
+
+
+        # return what the user asked for
+        if size is None or len(self.readbuffer) <= size:
+            bytes = self.readbuffer
+            self.readbuffer = ''
+        else:
+            bytes = self.readbuffer[:size]
+            self.readbuffer = self.readbuffer[size:]
+
+        return bytes
+
+
 class ZipFile:
     """ Class with methods to open, read, write, close, list zip files.
 
@@ -534,73 +734,75 @@
 
     def read(self, name, pwd=None):
         """Return file bytes (as a string) for name."""
-        if self.mode not in ("r", "a"):
-            raise RuntimeError, 'read() requires mode "r" or "a"'
+        return self.open(name, "r", pwd).read()
+
+    def open(self, name, mode="r", pwd=None):
+        """Return file-like object for 'name'."""
+        if mode not in ("r", "U", "rU"):
+            raise RuntimeError, 'open() requires mode "r", "U", or "rU"'
         if not self.fp:
             raise RuntimeError, \
                   "Attempt to read ZIP archive that was already closed"
+
+        # Only open a new file for instances where we were not
+        # given a file object in the constructor
+        if self._filePassed:
+            zef_file = self.fp
+        else:
+            zef_file = open(self.filename, 'rb')
+
+        # Get info object for name
         zinfo = self.getinfo(name)
-        is_encrypted = zinfo.flag_bits & 0x1
-        if is_encrypted:
-            if not pwd:
-                pwd = self.pwd
-            if not pwd:
-                raise RuntimeError, "File %s is encrypted, " \
-                      "password required for extraction" % name
-        filepos = self.fp.tell()
 
-        self.fp.seek(zinfo.header_offset, 0)
+        filepos = zef_file.tell()
+
+        zef_file.seek(zinfo.header_offset, 0)
 
         # Skip the file header:
-        fheader = self.fp.read(30)
+        fheader = zef_file.read(30)
         if fheader[0:4] != stringFileHeader:
             raise BadZipfile, "Bad magic number for file header"
 
         fheader = struct.unpack(structFileHeader, fheader)
-        fname = self.fp.read(fheader[_FH_FILENAME_LENGTH])
+        fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
         if fheader[_FH_EXTRA_FIELD_LENGTH]:
-            self.fp.read(fheader[_FH_EXTRA_FIELD_LENGTH])
+            zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
 
         if fname != zinfo.orig_filename:
             raise BadZipfile, \
                       'File name in directory "%s" and header "%s" differ.' % (
                           zinfo.orig_filename, fname)
 
-        bytes = self.fp.read(zinfo.compress_size)
-        # Go with decryption
+        # check for encrypted flag & handle password
+        is_encrypted = zinfo.flag_bits & 0x1
+        zd = None
         if is_encrypted:
+            if not pwd:
+                pwd = self.pwd
+            if not pwd:
+                raise RuntimeError, "File %s is encrypted, " \
+                      "password required for extraction" % name
+
             zd = _ZipDecrypter(pwd)
             # The first 12 bytes in the cypher stream is an encryption header
             #  used to strengthen the algorithm. The first 11 bytes are
             #  completely random, while the 12th contains the MSB of the CRC,
             #  and is used to check the correctness of the password.
-            h = map(zd, bytes[0:12])
+            bytes = zef_file.read(12)
+            h = list(map(zd, bytes[0:12]))
             if ord(h[11]) != ((zinfo.CRC>>24)&255):
                 raise RuntimeError, "Bad password for file %s" % name
-            bytes = "".join(map(zd, bytes[12:]))
-        # Go with decompression
-        self.fp.seek(filepos, 0)
-        if zinfo.compress_type == ZIP_STORED:
-            pass
-        elif zinfo.compress_type == ZIP_DEFLATED:
-            if not zlib:
-                raise RuntimeError, \
-                      "De-compression requires the (missing) zlib module"
-            # zlib compress/decompress code by Jeremy Hylton of CNRI
-            dc = zlib.decompressobj(-15)
-            bytes = dc.decompress(bytes)
-            # need to feed in unused pad byte so that zlib won't choke
-            ex = dc.decompress('Z') + dc.flush()
-            if ex:
-                bytes = bytes + ex
-        else:
-            raise BadZipfile, \
-                  "Unsupported compression method %d for file %s" % \
-            (zinfo.compress_type, name)
-        crc = binascii.crc32(bytes)
-        if crc != zinfo.CRC:
-            raise BadZipfile, "Bad CRC-32 for file %s" % name
-        return bytes
+
+        # build and return a ZipExtFile
+        if zd is None:
+            zef = ZipExtFile(zef_file, zinfo)
+        else:
+            zef = ZipExtFile(zef_file, zinfo, zd)
+
+        # set universal newlines on ZipExtFile if necessary
+        if "U" in mode:
+            zef.set_univ_newlines(True)
+        return zef
 
     def _writecheck(self, zinfo):
         """Check for errors before writing a file to the archive."""

Modified: python/branches/p3yk-noslice/Makefile.pre.in
==============================================================================
--- python/branches/p3yk-noslice/Makefile.pre.in	(original)
+++ python/branches/p3yk-noslice/Makefile.pre.in	Wed Jul 11 15:40:56 2007
@@ -714,7 +714,7 @@
 PLATMACPATH=:plat-mac:plat-mac/lib-scriptpackages
 LIBSUBDIRS=	lib-tk site-packages test test/output test/data \
 		test/decimaltestdata \
-		encodings compiler hotshot \
+		encodings hotshot \
 		email email/mime email/test email/test/data \
 		sqlite3 sqlite3/test \
 		logging bsddb bsddb/test csv wsgiref \

Modified: python/branches/p3yk-noslice/Misc/ACKS
==============================================================================
--- python/branches/p3yk-noslice/Misc/ACKS	(original)
+++ python/branches/p3yk-noslice/Misc/ACKS	Wed Jul 11 15:40:56 2007
@@ -29,12 +29,14 @@
 Donovan Baarda
 Attila Babo
 Alfonso Baciero
+Dwayne Bailey
 Stig Bakken
 Greg Ball
 Luigi Ballabio
 Michael J. Barber
 Chris Barker
 Quentin Barnes
+Richard Barran
 Cesar Eduardo Barros
 Des Barry
 Ulf Bartelt
@@ -106,6 +108,7 @@
 Brett Cannon
 Mike Carlton
 Terry Carroll
+Brian Leair
 Luke Kenneth Casson Leighton
 Donn Cave
 Per Cederqvist
@@ -154,8 +157,11 @@
 Jonathan Dasteel
 John DeGood
 Vincent Delft
+Erik Demaine
 Roger Dev
+Raghuram Devarakonda
 Toby Dickenson
+Mark Dickinson
 Yves Dionne
 Daniel Dittmar
 Walter Dörwald
@@ -200,6 +206,7 @@
 Niels Ferguson
 Sebastian Fernandez
 Vincent Fiack
+Tomer Filiba
 Russell Finn
 Nils Fischbeck
 Frederik Fix
@@ -216,6 +223,7 @@
 Peter Funk
 Geoff Furnish
 Lele Gaifax
+Santiago Gala
 Yitzchak Gale
 Raymund Galvin
 Nitin Ganatra
@@ -239,6 +247,7 @@
 Eddy De Greef
 Duncan Grisby
 Dag Gruneau
+Thomas Güttler
 Michael Guravage
 Lars Gustäbel
 Barry Haddow
@@ -270,6 +279,7 @@
 Ivan Herman
 Jürgen Hermann
 Gary Herron
+Thomas Herve
 Bernhard Herzog
 Magnus L. Hetland
 Raymond Hettinger
@@ -324,6 +334,7 @@
 Gregory K. Johnson
 Simon Johnston
 Evan Jones
+Jeremy Jones
 Richard Jones
 Irmen de Jong
 Lucas de Jonge
@@ -353,9 +364,11 @@
 Lenny Kneler
 Pat Knight
 Greg Kochanski
+Damon Kohler
 Joseph Koshy
 Bob Kras
 Holger Krekel
+Fabian Kreutz
 Hannu Krosing
 Andrew Kuchling
 Vladimir Kushnir
@@ -383,6 +396,7 @@
 Martin Ligr
 Christopher Lindblad
 Eric Lindvall
+Bjorn Lindqvist
 Per Lindqvist
 Nick Lockwood
 Stephanie Lockwood
@@ -408,6 +422,7 @@
 Doug Marien
 Alex Martelli
 Anthony Martin
+Sébastien Martini
 Roger Masse
 Nick Mathewson
 Graham Matthews
@@ -415,6 +430,7 @@
 Greg McFarlane
 Michael McLay
 Gordon McMillan
+Damien Miller
 Jay T. Miller
 Chris McDonough
 Andrew McNamara
@@ -427,8 +443,10 @@
 Steven Miale
 Trent Mick
 Chad Miller
+Damien Miller
 Roman Milner
 Dom Mitchell
+Dustin J. Mitchell
 Doug Moen
 Paul Moore
 The Dragon De Monsyne
@@ -468,6 +486,7 @@
 Mike Pall
 Todd R. Palmer
 Jan Palus
+Peter Parente
 Alexandre Parenteau
 Dan Parisien
 Harri Pasanen
@@ -555,6 +574,7 @@
 Gregor Schmid
 Ralf Schmitt
 Peter Schneider-Kamp
+Arvin Schnell
 Chad J. Schroeder
 Sam Schulenburg
 Stefan Schwarzer
@@ -565,6 +585,7 @@
 Žiga Seilnach
 Fred Sells
 Jiwon Seo
+Jerry Seutter
 Denis Severson
 Ha Shao
 Bruce Sherwood
@@ -640,8 +661,10 @@
 Roger Upole
 Michael Urman
 Hector Urtubia
+Atul Varma
 Dmitry Vasiliev
 Frank Vercruesse
+Mike Verdone
 Jaap Vermeulen
 Al Vezza
 Jacques A. Vidrine
@@ -688,6 +711,7 @@
 Richard Wolff
 Gordon Worley
 Thomas Wouters
+Heiko Wundram
 Doug Wyatt
 Ka-Ping Yee
 Bob Yodlowski

Modified: python/branches/p3yk-noslice/Misc/BeOS-NOTES
==============================================================================
--- python/branches/p3yk-noslice/Misc/BeOS-NOTES	(original)
+++ python/branches/p3yk-noslice/Misc/BeOS-NOTES	Wed Jul 11 15:40:56 2007
@@ -39,5 +39,4 @@
    make install
 
 
-- Donn Cave (donn at oz.net)
-  October 4, 2000
+Maintainer: Mikael Jansson (mail at mikael.jansson.be)

Modified: python/branches/p3yk-noslice/Misc/BeOS-setup.py
==============================================================================
--- python/branches/p3yk-noslice/Misc/BeOS-setup.py	(original)
+++ python/branches/p3yk-noslice/Misc/BeOS-setup.py	Wed Jul 11 15:40:56 2007
@@ -168,8 +168,6 @@
         if platform in ['Darwin1.2', 'beos']:
             math_libs = []
 
-        # XXX Omitted modules: gl, pure, dl, SGI-specific modules
-
         #
         # The following modules are all pretty straightforward, and compile
         # on pretty much any POSIXish platform.
@@ -188,8 +186,6 @@
         # math library functions, e.g. sin()
         exts.append( Extension('math',  ['mathmodule.c'],
                                libraries=math_libs) )
-        # fast string operations implemented in C
-        exts.append( Extension('strop', ['stropmodule.c']) )
         # time operations and variables
         exts.append( Extension('time', ['timemodule.c'],
                                libraries=math_libs) )
@@ -244,9 +240,6 @@
         # Lance Ellinghaus's syslog daemon interface
         exts.append( Extension('syslog', ['syslogmodule.c']) )
 
-        # George Neville-Neil's timing module:
-        exts.append( Extension('timing', ['timingmodule.c']) )
-
         #
         # Here ends the simple stuff.  From here on, modules need certain
         # libraries, are platform-specific, or present other surprises.
@@ -342,15 +335,8 @@
         if self.compiler.find_library_file(lib_dirs, 'db'):
             dblib = ['db']
 
-        db185_incs = find_file('db_185.h', inc_dirs,
-                               ['/usr/include/db3', '/usr/include/db2'])
         db_inc = find_file('db.h', inc_dirs, ['/usr/include/db1'])
-        if db185_incs is not None:
-            exts.append( Extension('bsddb', ['bsddbmodule.c'],
-                                   include_dirs = db185_incs,
-                                   define_macros=[('HAVE_DB_185_H',1)],
-                                   libraries = dblib ) )
-        elif db_inc is not None:
+        db_inc is not None:
             exts.append( Extension('bsddb', ['bsddbmodule.c'],
                                    include_dirs = db_inc,
                                    libraries = dblib) )

Modified: python/branches/p3yk-noslice/Misc/NEWS
==============================================================================
--- python/branches/p3yk-noslice/Misc/NEWS	(original)
+++ python/branches/p3yk-noslice/Misc/NEWS	Wed Jul 11 15:40:56 2007
@@ -16,11 +16,9 @@
 
 - Weed really old/weird stuff from the library.
 
-- Unify range() and xrange().
+- Use io.py instead of C stdio everywhere.
 
-- Rework the standard I/O library to use bytes for binary files.
-
-- Make strings all Unicode.
+- Make strings all Unicode (see branches/py3k-struni).
 
 - Get rid of various compatibility-related flags (e.g. division flags).
 
@@ -28,6 +26,59 @@
 Core and Builtins
 -----------------
 
+- Removed the __oct__ and __hex__ special methods and added a bin()
+  builtin function.
+
+- PEP 3127: octal literals now start with "0o". Old-style octal literals
+  are invalid. There are binary literals with a prefix of "0b".
+  This also affects int(x, 0).
+
+- None, True, False are now keywords.
+
+- PEP 3119: isinstance() and issubclass() can be overridden.
+
+- Remove BaseException.message.
+
+- Remove tuple parameter unpacking (PEP 3113).
+
+- Remove the f_restricted attribute from frames.  This naturally leads to teh
+  removal of PyEval_GetRestricted() and PyFrame_IsRestricted().
+
+- PEP 3132 was accepted. That means that you can do ``a, *b = range(5)``
+  to assign 0 to a and [1, 2, 3, 4] to b.
+
+- range() now returns an iterator rather than a list.  Floats are not allowed.
+  xrange() is no longer defined.
+
+- Patch #1660500: hide iteration variable in list comps, add set comps
+  and use common code to handle compilation of iterative expressions
+
+- By default, != returns the opposite of ==, unless the latter returns
+  NotImplemented.
+
+- Patch #1680961: sys.exitfunc has been removed and replaced with a private
+  C-level API.
+
+- PEP 3115: new metaclasses: the metaclass is now specified as a
+  keyword arg in the class statement, which can now use the full syntax of
+  a parameter list. Also, the metaclass can implement a __prepare__ function
+  which will be called to create the dictionary for the new class namespace.
+
+- The long-deprecated argument "pend" of PyFloat_FromString() has been
+  removed.
+
+- 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__().
+
+- Removed indexing/slicing on BaseException.
+
+- input() became raw_input(): the name input() now implements the
+  functionality formerly known as raw_input(); the name raw_input()
+  is no longer defined.
+
+- Classes listed in an 'except' clause must inherit from BaseException.
+
 - PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone;
   and .keys(), .items(), .values() return dict views.
 
@@ -52,6 +103,21 @@
 
 - Added function annotations per PEP 3107.
 
+- Added nonlocal declaration from PEP 3104
+
+  >>> def f(x):
+  ...     def inc():
+  ...         nonlocal x
+  ...         x += 1
+  ...         return x
+  ...     return inc
+  ...
+  >>> inc = f(0)
+  >>> inc()
+  1
+  >>> inc()
+  2
+
 - Moved intern() to sys.intern().
 
 - exec is now a function.
@@ -77,49 +143,63 @@
 - Absolute import is the default behavior for 'import foo' etc.
 
 - Removed support for syntax:
-  backticks (`x`), <>
+  backticks (ie, `x`), <>
 
 - Removed these Python builtins:
-  apply(), coerce(), input(), raw_input()
+  apply(), callable(), coerce(), file(), reduce(), reload()
 
 - Removed these Python methods:
   {}.has_key
 
-- Removed these Python slots:
-  __coerce__, __div__, __idiv__, __rdiv__
-
-- Removed these attributes from Python modules:
-  * operator module: div, idiv, __div__, __idiv__
-
-- Removed these C APIs:
-  PyNumber_Coerce(), PyNumber_CoerceEx() 
-
-- Removed these C slots/fields:
-  nb_divide, nb_inplace_divide
-
-- Removed these macros:
-  staticforward, statichere, PyArg_GetInt, PyArg_NoArgs
-
-- Removed these typedefs:
-  intargfunc, intintargfunc, intobjargproc, intintobjargproc,
-  getreadbufferproc, getwritebufferproc, getsegcountproc, getcharbufferproc
-
 - Removed these opcodes:
   BINARY_DIVIDE, INPLACE_DIVIDE, UNARY_CONVERT
 
+- Remove C API support for restricted execution.
+
 - zip returns an iterator
 
 - Additions:
   set literals, ellipsis literal
 
+- Added class decorators per PEP 3129.
+
 
 Extension Modules
 -----------------
 
+- Remove the imageop module.  Obsolete long with its unit tests becoming
+  useless from the removal of rgbimg and imgfile.
+
+- Removed these attributes from Python modules:
+  * operator module: div, idiv, __div__, __idiv__, isCallable, sequenceIncludes
+  * sys module: exc_clear(), exc_type, exc_value, exc_traceback
+
+
 Library
 -------
 
-- Removed all traces of the sets module.
+- Remove the compiler package.  Use of the _ast module and (an eventual)
+  AST -> bytecode mechanism.
+
+- Removed these modules:
+  * Bastion, bsddb185, exceptions, md5, MimeWriter, mimify, popen2, rexec,
+    sets, sha, stringold, strop, timing, xmllib.
+
+- Remove obsolete IRIX modules: al/AL, cd/CD, cddb, cdplayer, cl/CL, DEVICE,
+  ERRNO, FILE, fl/FL, flp, fm, GET, gl/GL, GLWS, IN, imgfile, IOCTL, jpeg,
+  panel, panelparser, readcd, sgi, sv/SV, torgb, WAIT.
+
+- Remove obsolete functions:
+  * commands.getstatus(), os.popen*,
+
+- Remove functions in the string module that are also string methods.
+
+- Remove support for long obsolete platforms: plat-aix3, plat-irix5.
+
+- Remove xmlrpclib.SlowParser.  It was based on xmllib.
+
+- Patch #1680961: atexit has been reimplemented in C.
+
 
 Build
 -----
@@ -127,6 +207,23 @@
 C API
 -----
 
+- Removed these Python slots:
+  __coerce__, __div__, __idiv__, __rdiv__
+
+- Removed these C APIs:
+  PyNumber_Coerce(), PyNumber_CoerceEx() 
+
+- Removed these C slots/fields:
+  nb_divide, nb_inplace_divide
+
+- Removed these macros:
+  staticforward, statichere, PyArg_GetInt, PyArg_NoArgs
+
+- Removed these typedefs:
+  intargfunc, intintargfunc, intobjargproc, intintobjargproc,
+  getreadbufferproc, getwritebufferproc, getsegcountproc, getcharbufferproc
+
+
 Tests
 -----
 
@@ -136,6 +233,9 @@
 Mac
 ---
 
+- The cfmfile was removed.
+
+
 New platforms
 -------------
 
@@ -143,3 +243,4 @@
 -----------
 
 **(For information about older versions, consult the HISTORY file.)**
+

Modified: python/branches/p3yk-noslice/Misc/Vim/python.vim
==============================================================================
--- python/branches/p3yk-noslice/Misc/Vim/python.vim	(original)
+++ python/branches/p3yk-noslice/Misc/Vim/python.vim	Wed Jul 11 15:40:56 2007
@@ -88,7 +88,7 @@
   syn keyword pythonException    MemoryError NameError NotImplementedError
   syn keyword pythonException    OSError OverflowError PendingDeprecationWarning
   syn keyword pythonException    ReferenceError RuntimeError RuntimeWarning
-  syn keyword pythonException    StandardError StopIteration SyntaxError
+  syn keyword pythonException    StopIteration SyntaxError
   syn keyword pythonException    SyntaxWarning SystemError SystemExit TabError
   syn keyword pythonException    TypeError UnboundLocalError UnicodeDecodeError
   syn keyword pythonException    UnicodeEncodeError UnicodeError

Modified: python/branches/p3yk-noslice/Misc/Vim/vim_syntax.py
==============================================================================
--- python/branches/p3yk-noslice/Misc/Vim/vim_syntax.py	(original)
+++ python/branches/p3yk-noslice/Misc/Vim/vim_syntax.py	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,6 @@
 from __future__ import with_statement
+# XXX(nnorwitz): what versions of python is this file supposed to work with?
+# It uses the old print statement not in py3k.
 
 import keyword
 import exceptions
@@ -139,7 +141,7 @@
             overflow = None
         while total_len < fill_len:
             try:
-                new_item = it.next()
+                new_item = next(it)
                 buffer_.append(new_item)
                 total_len += len(new_item) + 1
             except StopIteration:
@@ -188,7 +190,7 @@
                                             FILL - len(prefix) - len(indent))
                         try:
                             while True:
-                                print>>FILE, indent + prefix + stmt_iter.next()
+                                print>>FILE, indent + prefix + next(stmt_iter)
                         except StopIteration:
                             print>>FILE, ''
                     else:

Modified: python/branches/p3yk-noslice/Misc/build.sh
==============================================================================
--- python/branches/p3yk-noslice/Misc/build.sh	(original)
+++ python/branches/p3yk-noslice/Misc/build.sh	Wed Jul 11 15:40:56 2007
@@ -46,19 +46,20 @@
 
 FAILURE_SUBJECT="Python Regression Test Failures"
 #FAILURE_MAILTO="YOUR_ACCOUNT at gmail.com"
-FAILURE_MAILTO="python-checkins at python.org"
+FAILURE_MAILTO="python-3000-checkins at python.org"
+#FAILURE_CC="optional--uncomment and set to desired address"
 
 REMOTE_SYSTEM="neal at dinsdale.python.org"
-REMOTE_DIR="/data/ftp.python.org/pub/docs.python.org/dev/"
+REMOTE_DIR="/data/ftp.python.org/pub/docs.python.org/dev/3.0"
 RESULT_FILE="$DIR/build/index.html"
-INSTALL_DIR="/tmp/python-test/local"
+INSTALL_DIR="/tmp/python-test-3.0/local"
 RSYNC_OPTS="-aC -e ssh"
 
 # Always run the installed version of Python.
 PYTHON=$INSTALL_DIR/bin/python
 
 # Python options and regression test program that should always be run.
-REGRTEST_ARGS="-E -tt $INSTALL_DIR/lib/python2.6/test/regrtest.py"
+REGRTEST_ARGS="-E -tt $INSTALL_DIR/lib/python3.0/test/regrtest.py"
 
 REFLOG="build/reflog.txt.out"
 # These tests are not stable and falsely report leaks sometimes.
@@ -66,14 +67,18 @@
 # 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_(XXX)"  # Currently no tests should report spurious leaks.
+LEAKY_TESTS="test_(cmd_line|popen2|socket|threading_local|urllib2_localnet)"
+
+# These tests always fail, so skip them so we don't get false positives.
+_ALWAYS_SKIP=""
+ALWAYS_SKIP="-x $_ALWAYS_SKIP"
 
 # Skip these tests altogether when looking for leaks.  These tests
 # do not need to be stored above in LEAKY_TESTS too.
 # test_compiler almost never finishes with the same number of refs
 # since it depends on other modules, skip it.
 # test_logging causes hangs, skip it.
-LEAKY_SKIPS="-x test_compiler test_logging"
+LEAKY_SKIPS="-x test_compiler test_logging $_ALWAYS_SKIP"
 
 # Change this flag to "yes" for old releases to only update/build the docs.
 BUILD_DISABLED="no"
@@ -91,7 +96,12 @@
 
 mail_on_failure() {
     if [ "$NUM_FAILURES" != "0" ]; then
-        mutt -s "$FAILURE_SUBJECT $1 ($NUM_FAILURES)" $FAILURE_MAILTO < $2
+        dest=$FAILURE_MAILTO
+        # FAILURE_CC is optional.
+        if [ "$FAILURE_CC" != "" ]; then
+            dest="$dest -c $FAILURE_CC"
+        fi
+        mutt -s "$FAILURE_SUBJECT $1 ($NUM_FAILURES)" $dest < $2
     fi
 }
 
@@ -162,20 +172,20 @@
             update_status "Installing" "$F" $start
 
             if [ ! -x $PYTHON ]; then
-                ln -s ${PYTHON}2.* $PYTHON
+                ln -s ${PYTHON}3.* $PYTHON
             fi
 
             ## make and run basic tests
             F=make-test.out
             start=`current_time`
-            $PYTHON $REGRTEST_ARGS >& build/$F
+            $PYTHON $REGRTEST_ARGS $ALWAYS_SKIP >& build/$F
             NUM_FAILURES=`grep -ic " failed:" build/$F`
             update_status "Testing basics ($NUM_FAILURES failures)" "$F" $start
             mail_on_failure "basics" build/$F
 
             F=make-test-opt.out
             start=`current_time`
-            $PYTHON -O $REGRTEST_ARGS >& build/$F
+            $PYTHON -O $REGRTEST_ARGS $ALWAYS_SKIP >& build/$F
             NUM_FAILURES=`grep -ic " failed:" build/$F`
             update_status "Testing opt ($NUM_FAILURES failures)" "$F" $start
             mail_on_failure "opt" build/$F
@@ -186,7 +196,7 @@
             ## ensure that the reflog exists so the grep doesn't fail
             touch $REFLOG
             $PYTHON $REGRTEST_ARGS -R 4:3:$REFLOG -u network $LEAKY_SKIPS >& build/$F
-            NUM_FAILURES=`egrep -vc "$LEAKY_TESTS" $REFLOG`
+            NUM_FAILURES=`egrep -vc "($LEAKY_TESTS|sum=0)" $REFLOG`
             update_status "Testing refleaks ($NUM_FAILURES failures)" "$F" $start
             mail_on_failure "refleak" $REFLOG
 
@@ -195,7 +205,7 @@
             start=`current_time`
             ## skip curses when running from cron since there's no terminal
             ## skip sound since it's not setup on the PSF box (/dev/dsp)
-            $PYTHON $REGRTEST_ARGS -uall -x test_curses test_linuxaudiodev test_ossaudiodev >& build/$F
+            $PYTHON $REGRTEST_ARGS -uall -x test_curses test_linuxaudiodev test_ossaudiodev $_ALWAYS_SKIP >& build/$F
             NUM_FAILURES=`grep -ic " failed:" build/$F`
             update_status "Testing all except curses and sound ($NUM_FAILURES failures)" "$F" $start
             mail_on_failure "all" build/$F
@@ -208,8 +218,19 @@
 cd $DIR/Doc
 F="make-doc.out"
 start=`current_time`
-make >& ../build/$F
-err=$?
+# Doc/commontex/boilerplate.tex is expected to always have an outstanding
+# modification for the date.  When a release is cut, a conflict occurs.
+# This allows us to detect this problem and not try to build the docs
+# which will definitely fail with a conflict. 
+CONFLICTED_FILE=commontex/boilerplate.tex
+conflict_count=`grep -c "<<<" $CONFLICTED_FILE`
+if [ $conflict_count != 0 ]; then
+    echo "Conflict detected in $CONFLICTED_FILE.  Doc build skipped." > ../build/$F
+    err=1
+else
+    make >& ../build/$F
+    err=$?
+fi
 update_status "Making doc" "$F" $start
 if [ $err != 0 ]; then
     NUM_FAILURES=1
@@ -224,4 +245,3 @@
 rsync $RSYNC_OPTS html/* $REMOTE_SYSTEM:$REMOTE_DIR
 cd ../build
 rsync $RSYNC_OPTS index.html *.out $REMOTE_SYSTEM:$REMOTE_DIR/results/
-

Modified: python/branches/p3yk-noslice/Misc/cheatsheet
==============================================================================
--- python/branches/p3yk-noslice/Misc/cheatsheet	(original)
+++ python/branches/p3yk-noslice/Misc/cheatsheet	Wed Jul 11 15:40:56 2007
@@ -41,6 +41,7 @@
 -h      print this help message and exit
 -i      Inspect interactively after running script (also PYTHONINSPECT=x) and
         force prompts, even if stdin appears not to be a terminal
+-m mod  run library module as a script (terminates option list
 -O      optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
 -OO     remove doc-strings in addition to the -O optimizations
 -Q arg  division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
@@ -721,7 +722,7 @@
     return [result] -- Exits from function (or method) and returns result (use a tuple to
                        return more than one value). If no result given, then returns None.
     yield result    -- Freezes the execution frame of a generator and returns the result
-                       to the iterator's .next() method.  Upon the next call to next(),
+                       to the iterator's .__next__() method.  Upon the next call to __next__(),
                        resumes execution at the frozen point with all of the local variables
                        still intact.
 
@@ -778,8 +779,8 @@
 class, the class name is printed, then a colon and a space, and
 finally the instance converted to a string using the built-in function
 str().
-All built-in exception classes derives from StandardError, itself
-derived from Exception.
+All built-in exception classes derives from Exception, itself
+derived from BaseException.
 
 Name Space Statements
 
@@ -926,7 +927,6 @@
 abs(x)              Return the absolute value of number x.
 bool(x)             Returns True when the argument x is true and False otherwise.
 buffer(obj)         Creates a buffer reference to an object.
-callable(x)         Returns True if x callable, else False.
 chr(i)              Returns one-character string whose ASCII code isinteger i
 classmethod(f)      Converts a function f, into a method with the class as the
                     first argument.  Useful for creating alternative constructors.
@@ -934,14 +934,14 @@
 compile(string,     from which the code was read, or eg. '<string>'if not read
 filename, kind)     from file.kind can be 'eval' if string is a single stmt, or
                     'single' which prints the output of expression statements
-                    thatevaluate to something else than None, or be 'exec'.
+                    that evaluate to something else than None, or be 'exec'.
 complex(real[,      Builds a complex object (can also be done using J or j
 image])             suffix,e.g. 1+3J)
 delattr(obj, name)  deletes attribute named name of object obj <=> del obj.name
                     If no args, returns the list of names in current
 dict([items])       Create a new dictionary from the specified item list.
-dir([object])       localsymbol table. With a module, class or class
-                    instanceobject as arg, returns list of names in its attr.
+dir([object])       local symbol table. With a module, class or class
+                    instance object as arg, returns list of names in its attr.
                     dict.
 divmod(a,b)         Returns tuple of (a/b, a%b)
 enumerate(seq)      Return a iterator giving:  (0, seq[0]), (1, seq[1]), ...
@@ -956,7 +956,7 @@
 float(x)            Converts a number or a string to floating point.
 getattr(object,     [<default> arg added in 1.5.2]Gets attribute called name
 name[, default]))   from object,e.g. getattr(x, 'f') <=> x.f). If not found,
-                    raisesAttributeError or returns default if specified.
+                    raises AttributeError or returns default if specified.
 globals()           Returns a dictionary containing current global variables.
 hasattr(object,     Returns true if object has attr called name.
 name)
@@ -966,9 +966,7 @@
 id(object)          Returns a unique 'identity' integer for an object.
 int(x[, base])      base paramenter specifies base from which to convert string
                     values.
-intern(aString)     Enters aString in the table of "interned strings"
-                    andreturns the string. Interned strings are 'immortals'.
-isinstance(obj,     returns true if obj is an instance of class. Ifissubclass
+isinstance(obj,     Returns true if obj is an instance of class. Ifissubclass
 class)              (A,B) then isinstance(x,A) => isinstance(x,B)
 issubclass(class1,  returns true if class1 is derived from class2
 class2)
@@ -1001,26 +999,24 @@
   [, buffering]])
 pow(x, y [, z])     Returns x to power y [modulo z]. See also ** operator.
 property()          Created a property with access controlled by functions.
-range(start [,end   Returns list of ints from >= start and < end.With 1 arg,
-[, step]])          list from 0..arg-1With 2 args, list from start..end-1With 3
-                    args, list from start up to end by step
-reload(module)      after fixing it. If module was syntacticallycorrect but had
-                    an error in initialization, mustimport it one more time
-                    before calling reload().
-                    Returns a string containing a printable and if possible
-repr(object)        evaluable representation of an object. 
+range(start [,end   Returns list of ints from >= start and < end. With 1 arg,
+[, step]])          list from 0..arg-1. With 2 args, list from start..end-1.
+                    With 3 args, list from start up to end by step
+                    after fixing it.
+repr(object)        Returns a string containing a printable and if possible
+                    evaluable representation of an object. 
                     Class redefinable (__repr__). See also str().
 round(x, n=0)       Returns the floating point value x rounded to n digitsafter
                     the decimal point.
-setattr(object,     This is the counterpart of getattr().setattr(o, 'foobar',
-name, value)        3) <=> o.foobar = 3Creates attribute if it doesn't exist!
+setattr(object,     This is the counterpart of getattr(). setattr(o, 'foobar',
+name, value)        3) <=> o.foobar = 3. Creates attribute if it doesn't exist!
 slice([start,] stop Returns a slice object representing a range, with R/
-[, step])           Oattributes: start, stop, step.
-                    Returns a string containing a nicely
+[, step])           O attributes: start, stop, step.
 staticmethod()      Convert a function to method with no self or class
                     argument.  Useful for methods associated with a class that
                     do not need access to an object's internal state.
-str(object)         printablerepresentation of an object. Class overridable
+str(object)         Returns a string containing a nicely
+                    printable representation of an object. Class overridable
                     (__str__).See also repr().
 super(type)         Create an unbound super object.  Used to call cooperative
                     superclass methods.
@@ -1042,12 +1038,8 @@
 vars([object])      instance object as argumentreturns a dictionary
                     corresponding to the object'ssymbol table. Useful with "%"
                     formatting operator.
-xrange(start [, end Like range(), but doesn't actually store entire listall at
-[, step]])          once. Good to use in "for" loops when there is abig range
-                    and little memory.
-zip(seq1[, seq2,    Returns a list of tuples where each tuple contains the nth
-...])               element of each of the argument sequences.
-
+zip(seq1[, seq2,    Returns an iterator of tuples where each tuple contains
+...])               the nth element of each of the argument sequences.
 
 
 
@@ -1058,10 +1050,7 @@
     SystemExit
          On 'sys.exit()'
     StopIteration
-         Signal the end from iterator.next()
-    StandardError
-                 Base class for all built-in exceptions; derived from Exception
-    root class.
+         Signal the end from iterator.__next__()
         ArithmeticError
                  Base class for OverflowError, ZeroDivisionError,
     FloatingPointError
@@ -1314,10 +1303,6 @@
                      in C that are linked into this interpreter.
 check_interval       How often to check for thread switches or signals(measured
                      in number of virtual machine instructions)
-exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead.
-exc_traceback
-exitfunc             User can set to a parameterless fcn. It will getcalled
-                     before interpreter exits.
 last_type,           Set only when an exception not handled andinterpreter
 last_value,          prints an error. Used by debuggers.
 last_traceback
@@ -1350,7 +1335,7 @@
 setprofile(func)   Sets a profile function for performance profiling.
                    Info on exception currently being handled; this is atuple
                    (exc_type, exc_value, exc_traceback).Warning: assigning the
-exc_info()         traceback return value to a loca variable in a
+exc_info()         traceback return value to a local variable in a
                    function handling an exception will cause a circular
                    reference.
 setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII.
@@ -1857,7 +1842,6 @@
 dumbdbm          A dumb and slow but simple dbm clone.
 [DEL:dump:DEL]   [DEL:Print python code that reconstructs a variable.:DEL]
 email            Comprehensive support for internet email.
-exceptions       Class based built-in exception hierarchy.
 filecmp          File comparison.
 fileinput        Helper class to quickly write a loop over all standard input
                  files.
@@ -1872,7 +1856,6 @@
                  www.pauahtun.org/pub/getargspy.zip
 getpass          Utilities to get a password and/or the current user name.
 glob             filename globbing.
-gopherlib        Gopher protocol client interface.
 [DEL:grep:DEL]   [DEL:'grep' utilities.:DEL]
 gzip             Read & write gzipped files.
 heapq            Priority queue implemented using lists organized as heaps.
@@ -1887,7 +1870,6 @@
 imputil          Privides a way of writing customised import hooks.
 inspect          Tool for probing live Python objects.
 keyword          List of Python keywords.
-knee             A Python re-implementation of hierarchical module import.
 linecache        Cache lines from files.
 linuxaudiodev    Lunix /dev/audio support.
 locale           Support for number formatting using the current locale
@@ -1900,8 +1882,6 @@
 mhlib            MH (mailbox) interface.
 mimetools        Various tools used by MIME-reading or MIME-writing programs.
 mimetypes        Guess the MIME type of a file.
-MimeWriter       Generic MIME writer.
-mimify           Mimification and unmimification of mail messages.
 mmap             Interface to memory-mapped files - they behave like mutable
                  strings./font>
 multifile        Class to make multi-file messages easier to handle.
@@ -1919,9 +1899,7 @@
                  Cimplementation exists in built-in module: cPickle).
 pipes            Conversion pipeline templates.
 pkgunil          Utilities for working with Python packages.
-popen2           variations on pipe open.
 poplib           A POP3 client class. Based on the J. Myers POP3 draft.
-posixfile        Extended (posix) file operations.
 posixpath        Common operations on POSIX pathnames.
 pprint           Support to pretty-print lists, tuples, & dictionaries
                  recursively.
@@ -1934,7 +1912,6 @@
 pyclbr           Parse a Python file and retrieve classes and methods.
 Queue            A multi-producer, multi-consumer queue.
 quopri           Conversions to/from quoted-printable transport encoding.
-rand             Don't use unless you want compatibility with C's rand().
 random           Random variable generators
 re               Regular Expressions.
 repr             Redo repr() but with limits on most sizes.
@@ -1943,7 +1920,6 @@
 rlcompleter      Word completion for GNU readline 2.0.
 robotparser      Parse robots.txt files, useful for web spiders.
 sched            A generally useful event scheduler class.
-sets             Module for a set datatype.
 sgmllib          A parser for SGML.
 shelve           Manage shelves of pickled objects.
 shlex            Lexical analyzer class for simple shell-like syntaxes.
@@ -1955,7 +1931,6 @@
 sndhdr           Several routines that help recognizing sound.
 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
                  os.statvfs()and os.fstatvfs() (if they exist).
 string           A collection of string operations.
@@ -2054,12 +2029,6 @@
             sha         Interface to the SHA message digest algorithm
             HMAC        Keyed-Hashing for Message Authentication -- RFC 2104.
 
-* Stdwin * Standard Window System
-
-            stdwin              Standard Window System interface
-            stdwinevents        Stdwin event, command, and selection constants
-            rect                Rectangle manipulation operations
-
 * SGI IRIX * (4 & 5)
 
             al          SGI audio facilities

Modified: python/branches/p3yk-noslice/Misc/developers.txt
==============================================================================
--- python/branches/p3yk-noslice/Misc/developers.txt	(original)
+++ python/branches/p3yk-noslice/Misc/developers.txt	Wed Jul 11 15:40:56 2007
@@ -17,6 +17,29 @@
 Permissions History
 -------------------
 
+- Senthil Kumaran  was given SVN access on June 16 2007
+  by MvL, for his Summer-of-Code project, mentored by
+  Skip Montanaro.
+
+- Alexandre Vassalotti was given SVN access on May 21 2007
+  by MvL, for his Summer-of-Code project, mentored by
+  Brett Cannon.
+
+- Travis Oliphant was given SVN access on 17 Apr 2007 by MvL,
+  for implementing the extended buffer protocol.
+
+- Ziga Seilnacht was given SVN access on 09 Mar 2007 by MvL,
+  for general maintenance.
+
+- Pete Shinners was given SVN access on 04 Mar 2007 by NCN,
+  for PEP 3101 work in the sandbox.
+
+- Pat Maupin and Eric V. Smith were given SVN access on 28 Feb 2007 by NCN,
+  for PEP 3101 work in the sandbox.
+
+- Steven Bethard (SF name "bediviere") added to the SourceForge Python
+  project 26 Feb 2007, by NCN, as a tracker tech.
+
 - Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python
   project 06 Jan 2007, by NCN, as a tracker tech.  He will maintain asyncore.
 
@@ -148,3 +171,4 @@
 RDH:  Raymond Hettinger
 TGP:  Tim Peters
 DJG:  David Goodger
+MvL:  Martin v. Loewis

Modified: python/branches/p3yk-noslice/Misc/python-config.in
==============================================================================
--- python/branches/p3yk-noslice/Misc/python-config.in	(original)
+++ python/branches/p3yk-noslice/Misc/python-config.in	Wed Jul 11 15:40:56 2007
@@ -45,7 +45,9 @@
 elif opt in ('--libs', '--ldflags'):
     libs = getvar('LIBS').split() + getvar('SYSLIBS').split()
     libs.append('-lpython'+pyver)
-    if opt == '--ldflags':
+    # add the prefix/lib/pythonX.Y/config dir, but only if there is no
+    # shared library in prefix/lib/.
+    if opt == '--ldflags' and not getvar('Py_ENABLE_SHARED'):
         libs.insert(0, '-L' + getvar('LIBPL'))
     print ' '.join(libs)
 

Modified: python/branches/p3yk-noslice/Misc/python-mode.el
==============================================================================
--- python/branches/p3yk-noslice/Misc/python-mode.el	(original)
+++ python/branches/p3yk-noslice/Misc/python-mode.el	Wed Jul 11 15:40:56 2007
@@ -369,7 +369,7 @@
 			  "NotImplementedError" "OSError" "OverflowError"
 			  "OverflowWarning" "PendingDeprecationWarning"
 			  "ReferenceError" "RuntimeError" "RuntimeWarning"
-			  "StandardError" "StopIteration" "SyntaxError"
+			  "StopIteration" "SyntaxError"
 			  "SyntaxWarning" "SystemError" "SystemExit"
 			  "TabError" "True" "TypeError" "UnboundLocalError"
 			  "UnicodeDecodeError" "UnicodeEncodeError"

Modified: python/branches/p3yk-noslice/Misc/valgrind-python.supp
==============================================================================
--- python/branches/p3yk-noslice/Misc/valgrind-python.supp	(original)
+++ python/branches/p3yk-noslice/Misc/valgrind-python.supp	Wed Jul 11 15:40:56 2007
@@ -134,6 +134,15 @@
 ###
 
 {
+   Generic ubuntu ld problems
+   Memcheck:Addr8
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+}
+
+{
    Generic gentoo ld problems
    Memcheck:Cond
    obj:/lib/ld-2.3.4.so

Modified: python/branches/p3yk-noslice/Modules/Setup.dist
==============================================================================
--- python/branches/p3yk-noslice/Modules/Setup.dist	(original)
+++ python/branches/p3yk-noslice/Modules/Setup.dist	Wed Jul 11 15:40:56 2007
@@ -133,18 +133,6 @@
 # The Python symtable module depends on .h files that setup.py doesn't track
 _symtable symtablemodule.c
 
-# The SGI specific GL module:
-
-GLHACK=-Dclear=__GLclear
-#gl glmodule.c cgensupport.c -I$(srcdir) $(GLHACK) -lgl -lX11
-
-# Pure module.  Cannot be linked dynamically.
-# -DWITH_QUANTIFY, -DWITH_PURIFY, or -DWITH_ALL_PURE
-#WHICH_PURE_PRODUCTS=-DWITH_ALL_PURE
-#PURE_INCLS=-I/usr/local/include
-#PURE_STUBLIBS=-L/usr/local/lib -lpurify_stubs -lquantify_stubs
-#pure puremodule.c $(WHICH_PURE_PRODUCTS) $(PURE_INCLS) $(PURE_STUBLIBS)
-
 # Uncommenting the following line tells makesetup that all following
 # modules are to be built as shared libraries (see above for more
 # detail; also note that *static* reverses this effect):
@@ -175,7 +163,7 @@
 #_random _randommodule.c	# Random number generator
 #collections collectionsmodule.c # Container types
 #itertools itertoolsmodule.c	# Functions creating iterators for efficient looping 
-#strop stropmodule.c		# String manipulations
+#atexit atexitmodule.c      # Register functions to be run at interpreter-shutdown
 
 #unicodedata unicodedata.c    # static Unicode character database
 
@@ -230,8 +218,6 @@
 # These represent audio samples or images as strings:
 
 #audioop audioop.c	# Operations on audio samples
-#imageop imageop.c	# Operations on images
-#rgbimg rgbimgmodule.c	# Read SGI RGB image files (but coded portably)
 
 
 # Note that the _md5 and _sha modules are normally only built if the
@@ -249,42 +235,6 @@
 #_sha shamodule.c
 
 
-# SGI IRIX specific modules -- off by default.
-
-# These module work on any SGI machine:
-
-# *** gl must be enabled higher up in this file ***
-#fm fmmodule.c $(GLHACK) -lfm -lgl		# Font Manager
-#sgi sgimodule.c			# sgi.nap() and a few more
-
-# This module requires the header file
-# /usr/people/4Dgifts/iristools/include/izoom.h:
-#imgfile imgfile.c -limage -lgutil -lgl -lm	# Image Processing Utilities
-
-
-# These modules require the Multimedia Development Option (I think):
-
-#al almodule.c -laudio			# Audio Library
-#cd cdmodule.c -lcdaudio -lds -lmediad	# CD Audio Library
-#cl clmodule.c -lcl -lawareaudio	# Compression Library
-#sv svmodule.c yuvconvert.c -lsvideo -lXext -lX11	# Starter Video
-
-
-# The FORMS library, by Mark Overmars, implements user interface
-# components such as dialogs and buttons using SGI's GL and FM
-# libraries.  You must ftp the FORMS library separately from
-# ftp://ftp.cs.ruu.nl/pub/SGI/FORMS.  It was tested with FORMS 2.2a.
-# NOTE: if you want to be able to use FORMS and curses simultaneously
-# (or both link them statically into the same binary), you must
-# compile all of FORMS with the cc option "-Dclear=__GLclear".
-
-# The FORMS variable must point to the FORMS subdirectory of the forms
-# toplevel directory:
-
-#FORMS=/ufs/guido/src/forms/FORMS
-#fl flmodule.c -I$(FORMS) $(GLHACK) $(FORMS)/libforms.a -lfm -lgl
-
-
 # SunOS specific modules -- off by default:
 
 #sunaudiodev sunaudiodev.c
@@ -296,11 +246,6 @@
 #linuxaudiodev linuxaudiodev.c
 
 
-# George Neville-Neil's timing module:
-
-#timing timingmodule.c
-
-
 # The _tkinter module.
 #
 # The command for _tkinter is long and site specific.  Please
@@ -408,17 +353,6 @@
 #DBLIB=$(DB)/lib
 #_bsddb _bsddb.c -I$(DBINC) -L$(DBLIB) -ldb-$(DBLIBVER)
 
-# Historical Berkeley DB 1.85
-#
-# This module is deprecated; the 1.85 version of the Berkeley DB library has
-# bugs that can cause data corruption. If you can, use later versions of the
-# library instead, available from <http://www.sleepycat.com/>.
-
-#DB=/depot/sundry/src/berkeley-db/db.1.85
-#DBPORT=$(DB)/PORT/irix.5.3
-#bsddb185 bsddbmodule.c -I$(DBPORT)/include -I$(DBPORT) $(DBPORT)/libdb.a
-
-
 
 # Helper module for various ascii-encoders
 #binascii binascii.c

Modified: python/branches/p3yk-noslice/Modules/_bsddb.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_bsddb.c	(original)
+++ python/branches/p3yk-noslice/Modules/_bsddb.c	Wed Jul 11 15:40:56 2007
@@ -749,6 +749,24 @@
 
     Py_XDECREF(v);
 }
+
+/* The same, when the value is a time_t */
+static void _addTimeTToDict(PyObject* dict, char *name, time_t value)
+{
+    PyObject* v;
+	/* if the value fits in regular int, use that. */
+#ifdef HAVE_LONG_LONG
+	if (sizeof(time_t) > sizeof(long))
+		v = PyLong_FromLongLong((PY_LONG_LONG) value);
+	else
+#endif
+		v = PyInt_FromLong((long) value);
+    if (!v || PyDict_SetItemString(dict, name, v))
+        PyErr_Clear();
+
+    Py_XDECREF(v);
+}
+
 #if (DBVER >= 43)
 /* add an db_seq_t to a dictionary using the given name as a key */
 static void _addDb_seq_tToDict(PyObject* dict, char *name, db_seq_t value)
@@ -1695,6 +1713,7 @@
     PyObject* dataobj;
     PyObject* retval = NULL;
     DBT key, data;
+    void *orig_data;
     DB_TXN *txn = NULL;
     static char* kwnames[] = { "key", "data", "txn", "flags", NULL };
 
@@ -1714,13 +1733,12 @@
     }
 
     flags |= DB_GET_BOTH;
+    orig_data = data.data;
 
     if (CHECK_DBFLAG(self, DB_THREAD)) {
         /* Tell BerkeleyDB to malloc the return value (thread safe) */
+        /* XXX(nnorwitz): At least 4.4.20 and 4.5.20 require this flag. */
         data.flags = DB_DBT_MALLOC;
-        /* TODO: Is this flag needed?  We're passing a data object that should
-                 match what's in the DB, so there should be no need to malloc.
-                 We run the risk of freeing something twice!  Check this. */
     }
 
     MYDB_BEGIN_ALLOW_THREADS;
@@ -1734,8 +1752,13 @@
         retval = Py_None;
     }
     else if (!err) {
+        /* XXX(nnorwitz): can we do: retval = dataobj; Py_INCREF(retval); */
         retval = PyString_FromStringAndSize((char*)data.data, data.size);
-        FREE_DBT(data); /* Only if retrieval was successful */
+
+        /* Even though the flags require DB_DBT_MALLOC, data is not always
+           allocated.  4.4: allocated, 4.5: *not* allocated. :-( */
+        if (data.data != orig_data)
+            FREE_DBT(data);
     }
 
     FREE_DBT(key);
@@ -4633,8 +4656,9 @@
     }
 
 #define MAKE_ENTRY(name)  _addIntToDict(d, #name, sp->st_##name)
+#define MAKE_TIME_T_ENTRY(name)_addTimeTToDict(d, #name, sp->st_##name)
 
-    MAKE_ENTRY(time_ckp);
+    MAKE_TIME_T_ENTRY(time_ckp);
     MAKE_ENTRY(last_txnid);
     MAKE_ENTRY(maxtxns);
     MAKE_ENTRY(nactive);
@@ -4647,6 +4671,7 @@
     MAKE_ENTRY(region_nowait);
 
 #undef MAKE_ENTRY
+#undef MAKE_TIME_T_ENTRY
     free(sp);
     return d;
 }
@@ -5991,6 +6016,10 @@
      * from both DBError and KeyError, since the API only supports
      * using one base class. */
     PyDict_SetItemString(d, "KeyError", PyExc_KeyError);
+    { 
+	    PyObject *builtin_mod = PyImport_ImportModule("__builtin__");
+	    PyDict_SetItemString(d, "__builtins__", builtin_mod);
+    }
     PyRun_String("class DBNotFoundError(DBError, KeyError): pass\n"
 	         "class DBKeyEmptyError(DBError, KeyError): pass",
                  Py_file_input, d, d);

Modified: python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c	Wed Jul 11 15:40:56 2007
@@ -339,24 +339,6 @@
 			     ((PyTypeObject *)type)->tp_name, ob_name);
 		return NULL;
 	}
-#if 1
-/* XXX Remove this section ??? */
-	/* tuple returned by byref: */
-	/* ('i', addr, obj) */
-	if (PyTuple_Check(value)) {
-		PyObject *ob;
-		StgDictObject *dict;
-
-		dict = PyType_stgdict(type);
-		ob = PyTuple_GetItem(value, 2);
-		if (dict && ob &&
-		    0 == PyObject_IsInstance(value, dict->proto)) {
-			Py_INCREF(value);
-			return value;
-		}
-	}
-/* ... and leave the rest */
-#endif
 
 	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
 	if (as_parameter) {
@@ -807,7 +789,7 @@
 CharArray_set_value(CDataObject *self, PyObject *value)
 {
 	char *ptr;
-	int size;
+	Py_ssize_t size;
 
 	if (PyUnicode_Check(value)) {
 		value = PyUnicode_AsEncodedString(value,
@@ -862,7 +844,7 @@
 static int
 WCharArray_set_value(CDataObject *self, PyObject *value)
 {
-	int result = 0;
+	Py_ssize_t result = 0;
 
 	if (PyString_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
@@ -886,14 +868,12 @@
 	result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
 				      (wchar_t *)self->b_ptr,
 				      self->b_size/sizeof(wchar_t));
-	if (result >= 0 && (unsigned)result < self->b_size/sizeof(wchar_t))
+	if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
 		((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
-	if (result > 0)
-		result = 0;
   done:
 	Py_DECREF(value);
 
-	return result;
+	return result >= 0 ? 0 : -1;
 }
 
 static PyGetSetDef WCharArray_getsets[] = {
@@ -984,7 +964,7 @@
 	PyObject *typedict;
 	int length;
 
-	int itemsize, itemalign;
+	Py_ssize_t itemsize, itemalign;
 
 	typedict = PyTuple_GetItem(args, 2);
 	if (!typedict)
@@ -1020,6 +1000,12 @@
 	}
 
 	itemsize = itemdict->size;
+	if (length * itemsize < 0) {
+		PyErr_SetString(PyExc_OverflowError,
+				"array too large");
+		return NULL;
+	}
+
 	itemalign = itemdict->align;
 
 	stgdict->size = itemsize * length;
@@ -1119,7 +1105,7 @@
 
 */
 
-static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv";
+static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOvt";
 
 static PyObject *
 c_wchar_p_from_param(PyObject *type, PyObject *value)
@@ -1749,8 +1735,8 @@
 converters_from_argtypes(PyObject *ob)
 {
 	PyObject *converters;
-	int i;
-	int nArgs;
+	Py_ssize_t i;
+	Py_ssize_t nArgs;
 
 	ob = PySequence_Tuple(ob); /* new reference */
 	if (!ob) {
@@ -1783,7 +1769,12 @@
 	Py_XDECREF(converters);
 	Py_DECREF(ob);
 	PyErr_Format(PyExc_TypeError,
-		     "item %d in _argtypes_ has no from_param method", i+1);
+#if (PY_VERSION_HEX < 0x02050000)
+		     "item %d in _argtypes_ has no from_param method",
+#else
+		     "item %zd in _argtypes_ has no from_param method",
+#endif
+		     i+1);
 	return NULL;
 }
 
@@ -2194,21 +2185,32 @@
 	0,					/* tp_free */
 };
 
-static void CData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
+static int CData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
 {
 	if ((size_t)dict->size <= sizeof(obj->b_value)) {
 		/* No need to call malloc, can use the default buffer */
 		obj->b_ptr = (char *)&obj->b_value;
+		/* The b_needsfree flag does not mean that we actually did
+		   call PyMem_Malloc to allocate the memory block; instead it
+		   means we are the *owner* of the memory and are responsible
+		   for freeing resources associated with the memory.  This is
+		   also the reason that b_needsfree is exposed to Python.
+		 */
 		obj->b_needsfree = 1;
 	} else {
 		/* In python 2.4, and ctypes 0.9.6, the malloc call took about
 		   33% of the creation time for c_int().
 		*/
 		obj->b_ptr = (char *)PyMem_Malloc(dict->size);
+		if (obj->b_ptr == NULL) {
+			PyErr_NoMemory();
+			return -1;
+		}
 		obj->b_needsfree = 1;
 		memset(obj->b_ptr, 0, dict->size);
 	}
 	obj->b_size = dict->size;
+	return 0;
 }
 
 PyObject *
@@ -2240,7 +2242,10 @@
 		cmem->b_base = (CDataObject *)base;
 		cmem->b_index = index;
 	} else { /* copy contents of adr */
-		CData_MallocBuffer(cmem, dict);
+		if (-1 == CData_MallocBuffer(cmem, dict)) {
+			return NULL;
+			Py_DECREF(cmem);
+		}
 		memcpy(cmem->b_ptr, adr, dict->size);
 		cmem->b_index = index;
 	}
@@ -2453,7 +2458,10 @@
 	obj->b_objects = NULL;
 	obj->b_length = dict->length;
 			
-	CData_MallocBuffer(obj, dict);
+	if (-1 == CData_MallocBuffer(obj, dict)) {
+		Py_DECREF(obj);
+		return NULL;
+	}
 	return (PyObject *)obj;
 }
 /*****************************************************************/
@@ -2586,18 +2594,18 @@
 #ifdef MS_WIN32
 static PPROC FindAddress(void *handle, char *name, PyObject *type)
 {
+#ifdef MS_WIN64
+	/* win64 has no stdcall calling conv, so it should
+	   also not have the name mangling of it.
+	*/
+	return (PPROC)GetProcAddress(handle, name);
+#else
 	PPROC address;
 	char *mangled_name;
 	int i;
 	StgDictObject *dict;
 
 	address = (PPROC)GetProcAddress(handle, name);
-#ifdef _WIN64
-	/* win64 has no stdcall calling conv, so it should
-	   also not have the name mangling of it.
-	*/
-	return address;
-#else
 	if (address)
 		return address;
 	if (((size_t)name & ~0xFFFF) == 0) {
@@ -2629,7 +2637,7 @@
 
 /* Return 1 if usable, 0 else and exception set. */
 static int
-_check_outarg_type(PyObject *arg, int index)
+_check_outarg_type(PyObject *arg, Py_ssize_t index)
 {
 	StgDictObject *dict;
 
@@ -2650,7 +2658,7 @@
 
 	PyErr_Format(PyExc_TypeError,
 		     "'out' parameter %d must be a pointer type, not %s",
-		     index,
+		     Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
 		     PyType_Check(arg) ?
 		     ((PyTypeObject *)arg)->tp_name :
 		     arg->ob_type->tp_name);
@@ -2661,7 +2669,7 @@
 static int
 _validate_paramflags(PyTypeObject *type, PyObject *paramflags)
 {
-	int i, len;
+	Py_ssize_t i, len;
 	StgDictObject *dict;
 	PyObject *argtypes;
 
@@ -3046,12 +3054,12 @@
 	PyObject *paramflags = self->paramflags;
 	PyObject *callargs;
 	StgDictObject *dict;
-	int i, len;
+	Py_ssize_t i, len;
 	int inargs_index = 0;
 	/* It's a little bit difficult to determine how many arguments the
 	function call requires/accepts.  For simplicity, we count the consumed
 	args and compare this to the number of supplied args. */
-	int actual_args;
+	Py_ssize_t actual_args;
 
 	*poutmask = 0;
 	*pinoutmask = 0;
@@ -3088,7 +3096,7 @@
 		/* This way seems to be ~2 us faster than the PyArg_ParseTuple
 		   calls below. */
 		/* We HAVE already checked that the tuple can be parsed with "i|zO", so... */
-		int tsize = PyTuple_GET_SIZE(item);
+		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;
 		defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
@@ -3188,7 +3196,11 @@
 		   message is misleading.  See unittests/test_paramflags.py
 		 */
 		PyErr_Format(PyExc_TypeError,
+#if (PY_VERSION_HEX < 0x02050000)
 			     "call takes exactly %d arguments (%d given)",
+#else
+			     "call takes exactly %d arguments (%zd given)",
+#endif
 			     inargs_index, actual_args);
 		goto error;
 	}
@@ -3334,8 +3346,10 @@
 		return NULL;
 
 	if (converters) {
-		int required = PyTuple_GET_SIZE(converters);
-		int actual = PyTuple_GET_SIZE(callargs);
+		int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
+					        Py_ssize_t, int);
+		int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
+					      Py_ssize_t, int);
 
 		if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
 			/* For cdecl functions, we allow more actual arguments
@@ -3674,8 +3688,8 @@
 static int
 Array_init(CDataObject *self, PyObject *args, PyObject *kw)
 {
-	int i;
-	int n;
+	Py_ssize_t i;
+	Py_ssize_t n;
 
 	if (!PyTuple_Check(args)) {
 		PyErr_SetString(PyExc_TypeError,
@@ -3696,7 +3710,7 @@
 Array_item(PyObject *_self, Py_ssize_t index)
 {
 	CDataObject *self = (CDataObject *)_self;
-	int offset, size;
+	Py_ssize_t offset, size;
 	StgDictObject *stgdict;
 
 
@@ -3836,7 +3850,7 @@
 Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
 {
 	CDataObject *self = (CDataObject *)_self;
-	int size, offset;
+	Py_ssize_t size, offset;
 	StgDictObject *stgdict;
 	char *ptr;
 
@@ -3865,7 +3879,7 @@
 Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value)
 {
 	CDataObject *self = (CDataObject *)_self;
-	int i, len;
+	Py_ssize_t i, len;
 
 	if (value == NULL) {
 		PyErr_SetString(PyExc_TypeError,
@@ -4295,7 +4309,7 @@
 Pointer_item(PyObject *_self, Py_ssize_t index)
 {
 	CDataObject *self = (CDataObject *)_self;
-	int size;
+	Py_ssize_t size;
 	Py_ssize_t offset;
 	StgDictObject *stgdict, *itemdict;
 	PyObject *proto;
@@ -4326,7 +4340,7 @@
 Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
 {
 	CDataObject *self = (CDataObject *)_self;
-	int size;
+	Py_ssize_t size;
 	Py_ssize_t offset;
 	StgDictObject *stgdict, *itemdict;
 	PyObject *proto;
@@ -4765,9 +4779,9 @@
 #endif
 
 static PyObject *
-string_at(const char *ptr, Py_ssize_t size)
+string_at(const char *ptr, int size)
 {
-	if (size == 0)
+	if (size == -1)
 		return PyString_FromString(ptr);
 	return PyString_FromStringAndSize(ptr, size);
 }
@@ -4852,9 +4866,10 @@
 static PyObject *
 wstring_at(const wchar_t *ptr, int size)
 {
-	if (size == 0)
-		size = wcslen(ptr);
-	return PyUnicode_FromWideChar(ptr, size);
+	Py_ssize_t ssize = size;
+	if (ssize == -1)
+		ssize = wcslen(ptr);
+	return PyUnicode_FromWideChar(ptr, ssize);
 }
 #endif
 
@@ -5054,7 +5069,7 @@
     return (PyObject *)unicode;
 }
 
-int My_PyUnicode_AsWideChar(PyUnicodeObject *unicode,
+Py_ssize_t My_PyUnicode_AsWideChar(PyUnicodeObject *unicode,
 			    register wchar_t *w,
 			    Py_ssize_t size)
 {

Modified: python/branches/p3yk-noslice/Modules/_ctypes/callbacks.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/callbacks.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/callbacks.c	Wed Jul 11 15:40:56 2007
@@ -124,10 +124,10 @@
 			      PyObject *converters,
 			      void **pArgs)
 {
-	int i;
+	Py_ssize_t i;
 	PyObject *result;
 	PyObject *arglist = NULL;
-	int nArgs;
+	Py_ssize_t nArgs;
 #ifdef WITH_THREAD
 	PyGILState_STATE state = PyGILState_Ensure();
 #endif
@@ -265,7 +265,7 @@
 {
 	int result;
 	ffi_info *p;
-	int nArgs, i;
+	Py_ssize_t nArgs, i;
 	ffi_abi cc;
 
 	nArgs = PySequence_Size(converters);
@@ -308,7 +308,8 @@
 	if (is_cdecl == 0)
 		cc = FFI_STDCALL;
 #endif
-	result = ffi_prep_cif(&p->cif, cc, nArgs,
+	result = ffi_prep_cif(&p->cif, cc,
+			      Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
 			      GetType(restype),
 			      &p->atypes[0]);
 	if (result != FFI_OK) {
@@ -384,8 +385,27 @@
 		return E_FAIL;
 	}
 
-	result = PyObject_CallFunction(func,
-				       "iii", rclsid, riid, ppv);
+	{
+		PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
+		PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
+		PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
+		if (!py_rclsid || !py_riid || !py_ppv) {
+			Py_XDECREF(py_rclsid);
+			Py_XDECREF(py_riid);
+			Py_XDECREF(py_ppv);
+			Py_DECREF(func);
+			PyErr_WriteUnraisable(context ? context : Py_None);
+			return E_FAIL;
+		}
+		result = PyObject_CallFunctionObjArgs(func,
+						      py_rclsid,
+						      py_riid,
+						      py_ppv,
+						      NULL);
+		Py_DECREF(py_rclsid);
+		Py_DECREF(py_riid);
+		Py_DECREF(py_ppv);
+	}
 	Py_DECREF(func);
 	if (!result) {
 		PyErr_WriteUnraisable(context ? context : Py_None);

Modified: python/branches/p3yk-noslice/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/callproc.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/callproc.c	Wed Jul 11 15:40:56 2007
@@ -64,6 +64,7 @@
 
 #ifdef MS_WIN32
 #include <windows.h>
+#include <tchar.h>
 #else
 #include "ctypes_dlfcn.h"
 #endif
@@ -97,9 +98,9 @@
 			  0,
 			  NULL);
 	if (n) {
-		while (isspace(lpMsgBuf[n-1]))
+		while (_istspace(lpMsgBuf[n-1]))
 			--n;
-		lpMsgBuf[n] = '\0'; /* rstrip() */
+		lpMsgBuf[n] = _T('\0'); /* rstrip() */
 	}
 	return lpMsgBuf;
 }
@@ -360,13 +361,13 @@
 	case 'z':
 	case 'Z':
 	case 'P':
-		sprintf(buffer, "<cparam '%c' (%08lx)>",
-			self->tag, (long)self->value.p);
+		sprintf(buffer, "<cparam '%c' (%p)>",
+			self->tag, self->value.p);
 		break;
 
 	default:
-		sprintf(buffer, "<cparam '%c' at %08lx>",
-			self->tag, (long)self);
+		sprintf(buffer, "<cparam '%c' at %p>",
+			self->tag, self);
 		break;
 	}
 	return PyString_FromString(buffer);
@@ -463,7 +464,7 @@
 /*
  * Convert a single Python object into a PyCArgObject and return it.
  */
-static int ConvParam(PyObject *obj, int index, struct argument *pa)
+static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
 {
 	StgDictObject *dict;
 	pa->keep = NULL; /* so we cannot forget it later */
@@ -532,8 +533,10 @@
 		size += 1; /* terminating NUL */
 		size *= sizeof(wchar_t);
 		pa->value.p = PyMem_Malloc(size);
-		if (!pa->value.p)
+		if (!pa->value.p) {
+			PyErr_NoMemory();
 			return -1;
+		}
 		memset(pa->value.p, 0, size);
 		pa->keep = PyCObject_FromVoidPtr(pa->value.p, PyMem_Free);
 		if (!pa->keep) {
@@ -563,7 +566,8 @@
 			return result;
 		}
 		PyErr_Format(PyExc_TypeError,
-			     "Don't know how to convert parameter %d", index);
+			     "Don't know how to convert parameter %d", 
+			     Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
 		return -1;
 	}
 }
@@ -903,7 +907,7 @@
 		    PyObject *restype,
 		    PyObject *checker)
 {
-	int i, n, argcount, argtype_count;
+	Py_ssize_t i, n, argcount, argtype_count;
 	void *resbuf;
 	struct argument *args, *pa;
 	ffi_type **atypes;
@@ -993,7 +997,10 @@
 	}
 
 	if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
-					 rtype, resbuf, argcount))
+					 rtype, resbuf,
+					 Py_SAFE_DOWNCAST(argcount,
+							  Py_ssize_t,
+							  int)))
 		goto cleanup;
 
 #ifdef WORDS_BIGENDIAN
@@ -1033,6 +1040,15 @@
 	return retval;
 }
 
+static int
+_parse_voidp(PyObject *obj, void **address)
+{
+	*address = PyLong_AsVoidPtr(obj);
+	if (*address == NULL)
+		return 0;
+	return 1;
+}
+
 #ifdef MS_WIN32
 
 #ifdef _UNICODE
@@ -1119,10 +1135,10 @@
 Free the handle of an executable previously loaded by LoadLibrary.\n";
 static PyObject *free_library(PyObject *self, PyObject *args)
 {
-	HMODULE hMod;
-	if (!PyArg_ParseTuple(args, "i:FreeLibrary", &hMod))
+	void *hMod;
+	if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
 		return NULL;
-	if (!FreeLibrary(hMod))
+	if (!FreeLibrary((HMODULE)hMod))
 		return PyErr_SetFromWindowsErr(GetLastError());
 	Py_INCREF(Py_None);
 	return Py_None;
@@ -1241,11 +1257,11 @@
 
 static PyObject *py_dl_close(PyObject *self, PyObject *args)
 {
-	int handle;
+	void *handle;
 
-	if (!PyArg_ParseTuple(args, "i:dlclose", &handle))
+	if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
 		return NULL;
-	if (dlclose((void*)handle)) {
+	if (dlclose(handle)) {
 		PyErr_SetString(PyExc_OSError,
 				       ctypes_dlerror());
 		return NULL;
@@ -1257,10 +1273,11 @@
 static PyObject *py_dl_sym(PyObject *self, PyObject *args)
 {
 	char *name;
-	int handle;
+	void *handle;
 	void *ptr;
 
-	if (!PyArg_ParseTuple(args, "is:dlsym", &handle, &name))
+	if (!PyArg_ParseTuple(args, "O&s:dlsym",
+			      &_parse_voidp, &handle, &name))
 		return NULL;
 	ptr = ctypes_dlsym((void*)handle, name);
 	if (!ptr) {
@@ -1268,7 +1285,7 @@
 				       ctypes_dlerror());
 		return NULL;
 	}
-	return Py_BuildValue("i", ptr);
+	return PyLong_FromVoidPtr(ptr);
 }
 #endif
 
@@ -1280,13 +1297,13 @@
 static PyObject *
 call_function(PyObject *self, PyObject *args)
 {
-	int func;
+	void *func;
 	PyObject *arguments;
 	PyObject *result;
 
 	if (!PyArg_ParseTuple(args,
-			      "iO!",
-			      &func,
+			      "O&O!",
+			      &_parse_voidp, &func,
 			      &PyTuple_Type, &arguments))
 		return NULL;
 
@@ -1311,13 +1328,13 @@
 static PyObject *
 call_cdeclfunction(PyObject *self, PyObject *args)
 {
-	int func;
+	void *func;
 	PyObject *arguments;
 	PyObject *result;
 
 	if (!PyArg_ParseTuple(args,
-			      "iO!",
-			      &func,
+			      "O&O!",
+			      &_parse_voidp, &func,
 			      &PyTuple_Type, &arguments))
 		return NULL;
 
@@ -1349,10 +1366,10 @@
 
 	dict = PyType_stgdict(obj);
 	if (dict)
-		return PyInt_FromLong(dict->size);
+		return PyInt_FromSsize_t(dict->size);
 
 	if (CDataObject_Check(obj))
-		return PyInt_FromLong(((CDataObject *)obj)->b_size);
+		return PyInt_FromSsize_t(((CDataObject *)obj)->b_size);
 	PyErr_SetString(PyExc_TypeError,
 			"this type has no size");
 	return NULL;
@@ -1370,11 +1387,11 @@
 
 	dict = PyType_stgdict(obj);
 	if (dict)
-		return PyInt_FromLong(dict->align);
+		return PyInt_FromSsize_t(dict->align);
 
 	dict = PyObject_stgdict(obj);
 	if (dict)
-		return PyInt_FromLong(dict->align);
+		return PyInt_FromSsize_t(dict->align);
 
 	PyErr_SetString(PyExc_TypeError,
 			"no alignment info");

Modified: python/branches/p3yk-noslice/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/cfield.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/cfield.c	Wed Jul 11 15:40:56 2007
@@ -35,14 +35,14 @@
  * prev_desc points to the type of the previous bitfield, if any.
  */
 PyObject *
-CField_FromDesc(PyObject *desc, int index,
-		int *pfield_size, int bitsize, int *pbitofs,
-		int *psize, int *poffset, int *palign,
+CField_FromDesc(PyObject *desc, Py_ssize_t index,
+		Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
+		Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
 		int pack, int big_endian)
 {
 	CFieldObject *self;
 	PyObject *proto;
-	int size, align, length;
+	Py_ssize_t size, align, length;
 	SETFUNC setfunc = NULL;
 	GETFUNC getfunc = NULL;
 	StgDictObject *dict;
@@ -147,7 +147,7 @@
 		else
 			align = dict->align;
 		if (align && *poffset % align) {
-			int delta = align - (*poffset % align);
+			Py_ssize_t delta = align - (*poffset % align);
 			*psize += delta;
 			*poffset += delta;
 		}
@@ -220,21 +220,13 @@
 static PyObject *
 CField_get_offset(PyObject *self, void *data)
 {
-#if (PY_VERSION_HEX < 0x02050000)
-	return PyInt_FromLong(((CFieldObject *)self)->offset);
-#else
 	return PyInt_FromSsize_t(((CFieldObject *)self)->offset);
-#endif
 }
 
 static PyObject *
 CField_get_size(PyObject *self, void *data)
 {
-#if (PY_VERSION_HEX < 0x02050000)
-	return PyInt_FromLong(((CFieldObject *)self)->size);
-#else
 	return PyInt_FromSsize_t(((CFieldObject *)self)->size);
-#endif
 }
 
 static PyGetSetDef CField_getset[] = {
@@ -268,8 +260,8 @@
 CField_repr(CFieldObject *self)
 {
 	PyObject *result;
-	int bits = self->size >> 16;
-	int size = self->size & 0xFFFF;
+	Py_ssize_t bits = self->size >> 16;
+	Py_ssize_t size = self->size & 0xFFFF;
 	const char *name;
 
 	name = ((PyTypeObject *)self->proto)->tp_name;
@@ -279,7 +271,7 @@
 #if (PY_VERSION_HEX < 0x02050000)
 			"<Field type=%s, ofs=%d:%d, bits=%d>",
 #else
-			"<Field type=%s, ofs=%zd:%d, bits=%d>",
+			"<Field type=%s, ofs=%zd:%zd, bits=%zd>",
 #endif
 			name, self->offset, size, bits);
 	else
@@ -287,7 +279,7 @@
 #if (PY_VERSION_HEX < 0x02050000)
 			"<Field type=%s, ofs=%d, size=%d>",
 #else
-			"<Field type=%s, ofs=%zd, size=%d>",
+			"<Field type=%s, ofs=%zd, size=%zd>",
 #endif
 			name, self->offset, size);
 	return result;
@@ -519,7 +511,7 @@
  */
 
 static PyObject *
-b_set(void *ptr, PyObject *value, unsigned size)
+b_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	if (get_long(value, &val) < 0)
@@ -530,7 +522,7 @@
 
 
 static PyObject *
-b_get(void *ptr, unsigned size)
+b_get(void *ptr, Py_ssize_t size)
 {
 	signed char val = *(signed char *)ptr;
 	GET_BITFIELD(val, size);
@@ -538,7 +530,7 @@
 }
 
 static PyObject *
-B_set(void *ptr, PyObject *value, unsigned size)
+B_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	if (get_ulong(value, &val) < 0)
@@ -550,7 +542,7 @@
 
 
 static PyObject *
-B_get(void *ptr, unsigned size)
+B_get(void *ptr, Py_ssize_t size)
 {
 	unsigned char val = *(unsigned char *)ptr;
 	GET_BITFIELD(val, size);
@@ -558,7 +550,7 @@
 }
 
 static PyObject *
-h_set(void *ptr, PyObject *value, unsigned size)
+h_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	short x;
@@ -572,7 +564,7 @@
 
 
 static PyObject *
-h_set_sw(void *ptr, PyObject *value, unsigned size)
+h_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	short field;
@@ -587,7 +579,7 @@
 }
 
 static PyObject *
-h_get(void *ptr, unsigned size)
+h_get(void *ptr, Py_ssize_t size)
 {
 	short val;
 	memcpy(&val, ptr, sizeof(val));
@@ -596,7 +588,7 @@
 }
 
 static PyObject *
-h_get_sw(void *ptr, unsigned size)
+h_get_sw(void *ptr, Py_ssize_t size)
 {
 	short val;
 	memcpy(&val, ptr, sizeof(val));
@@ -606,7 +598,7 @@
 }
 
 static PyObject *
-H_set(void *ptr, PyObject *value, unsigned size)
+H_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	unsigned short x;
@@ -619,7 +611,7 @@
 }
 
 static PyObject *
-H_set_sw(void *ptr, PyObject *value, unsigned size)
+H_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	unsigned short field;
@@ -635,7 +627,7 @@
 
 
 static PyObject *
-H_get(void *ptr, unsigned size)
+H_get(void *ptr, Py_ssize_t size)
 {
 	unsigned short val;
 	memcpy(&val, ptr, sizeof(val));
@@ -644,7 +636,7 @@
 }
 
 static PyObject *
-H_get_sw(void *ptr, unsigned size)
+H_get_sw(void *ptr, Py_ssize_t size)
 {
 	unsigned short val;
 	memcpy(&val, ptr, sizeof(val));
@@ -654,7 +646,7 @@
 }
 
 static PyObject *
-i_set(void *ptr, PyObject *value, unsigned size)
+i_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	int x;
@@ -667,7 +659,7 @@
 }
 
 static PyObject *
-i_set_sw(void *ptr, PyObject *value, unsigned size)
+i_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	int field;
@@ -683,7 +675,7 @@
 
 
 static PyObject *
-i_get(void *ptr, unsigned size)
+i_get(void *ptr, Py_ssize_t size)
 {
 	int val;
 	memcpy(&val, ptr, sizeof(val));
@@ -692,7 +684,7 @@
 }
 
 static PyObject *
-i_get_sw(void *ptr, unsigned size)
+i_get_sw(void *ptr, Py_ssize_t size)
 {
 	int val;
 	memcpy(&val, ptr, sizeof(val));
@@ -704,7 +696,7 @@
 #ifdef MS_WIN32
 /* short BOOL - VARIANT_BOOL */
 static PyObject *
-vBOOL_set(void *ptr, PyObject *value, unsigned size)
+vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	switch (PyObject_IsTrue(value)) {
 	case -1:
@@ -719,14 +711,43 @@
 }
 
 static PyObject *
-vBOOL_get(void *ptr, unsigned size)
+vBOOL_get(void *ptr, Py_ssize_t size)
 {
 	return PyBool_FromLong((long)*(short int *)ptr);
 }
 #endif
 
+#ifdef HAVE_C99_BOOL
+#define BOOL_TYPE _Bool
+#else
+#define BOOL_TYPE char
+#undef SIZEOF__BOOL
+#define SIZEOF__BOOL 1
+#endif
+
+static PyObject *
+t_set(void *ptr, PyObject *value, Py_ssize_t size)
+{
+	switch (PyObject_IsTrue(value)) {
+	case -1:
+		return NULL;
+	case 0:
+		*(BOOL_TYPE *)ptr = 0;
+		_RET(value);
+	default:
+		*(BOOL_TYPE *)ptr = 1;
+		_RET(value);
+	}
+}
+
 static PyObject *
-I_set(void *ptr, PyObject *value, unsigned size)
+t_get(void *ptr, Py_ssize_t size)
+{
+	return PyBool_FromLong((long)*(BOOL_TYPE *)ptr);
+}
+
+static PyObject *
+I_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	unsigned int x;
@@ -739,7 +760,7 @@
 }
 
 static PyObject *
-I_set_sw(void *ptr, PyObject *value, unsigned size)
+I_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	unsigned int field;
@@ -754,7 +775,7 @@
 
 
 static PyObject *
-I_get(void *ptr, unsigned size)
+I_get(void *ptr, Py_ssize_t size)
 {
 	unsigned int val;
 	memcpy(&val, ptr, sizeof(val));
@@ -763,7 +784,7 @@
 }
 
 static PyObject *
-I_get_sw(void *ptr, unsigned size)
+I_get_sw(void *ptr, Py_ssize_t size)
 {
 	unsigned int val;
 	memcpy(&val, ptr, sizeof(val));
@@ -773,7 +794,7 @@
 }
 
 static PyObject *
-l_set(void *ptr, PyObject *value, unsigned size)
+l_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	long x;
@@ -786,7 +807,7 @@
 }
 
 static PyObject *
-l_set_sw(void *ptr, PyObject *value, unsigned size)
+l_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	long val;
 	long field;
@@ -802,7 +823,7 @@
 
 
 static PyObject *
-l_get(void *ptr, unsigned size)
+l_get(void *ptr, Py_ssize_t size)
 {
 	long val;
 	memcpy(&val, ptr, sizeof(val));
@@ -811,7 +832,7 @@
 }
 
 static PyObject *
-l_get_sw(void *ptr, unsigned size)
+l_get_sw(void *ptr, Py_ssize_t size)
 {
 	long val;
 	memcpy(&val, ptr, sizeof(val));
@@ -821,7 +842,7 @@
 }
 
 static PyObject *
-L_set(void *ptr, PyObject *value, unsigned size)
+L_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	unsigned long x;
@@ -834,7 +855,7 @@
 }
 
 static PyObject *
-L_set_sw(void *ptr, PyObject *value, unsigned size)
+L_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned long val;
 	unsigned long field;
@@ -850,7 +871,7 @@
 
 
 static PyObject *
-L_get(void *ptr, unsigned size)
+L_get(void *ptr, Py_ssize_t size)
 {
 	unsigned long val;
 	memcpy(&val, ptr, sizeof(val));
@@ -859,7 +880,7 @@
 }
 
 static PyObject *
-L_get_sw(void *ptr, unsigned size)
+L_get_sw(void *ptr, Py_ssize_t size)
 {
 	unsigned long val;
 	memcpy(&val, ptr, sizeof(val));
@@ -870,7 +891,7 @@
 
 #ifdef HAVE_LONG_LONG
 static PyObject *
-q_set(void *ptr, PyObject *value, unsigned size)
+q_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	PY_LONG_LONG val;
 	PY_LONG_LONG x;
@@ -883,7 +904,7 @@
 }
 
 static PyObject *
-q_set_sw(void *ptr, PyObject *value, unsigned size)
+q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	PY_LONG_LONG val;
 	PY_LONG_LONG field;
@@ -898,7 +919,7 @@
 }
 
 static PyObject *
-q_get(void *ptr, unsigned size)
+q_get(void *ptr, Py_ssize_t size)
 {
 	PY_LONG_LONG val;
 	memcpy(&val, ptr, sizeof(val));
@@ -907,7 +928,7 @@
 }
 
 static PyObject *
-q_get_sw(void *ptr, unsigned size)
+q_get_sw(void *ptr, Py_ssize_t size)
 {
 	PY_LONG_LONG val;
 	memcpy(&val, ptr, sizeof(val));
@@ -917,7 +938,7 @@
 }
 
 static PyObject *
-Q_set(void *ptr, PyObject *value, unsigned size)
+Q_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned PY_LONG_LONG val;
 	unsigned PY_LONG_LONG x;
@@ -930,7 +951,7 @@
 }
 
 static PyObject *
-Q_set_sw(void *ptr, PyObject *value, unsigned size)
+Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	unsigned PY_LONG_LONG val;
 	unsigned PY_LONG_LONG field;
@@ -945,7 +966,7 @@
 }
 
 static PyObject *
-Q_get(void *ptr, unsigned size)
+Q_get(void *ptr, Py_ssize_t size)
 {
 	unsigned PY_LONG_LONG val;
 	memcpy(&val, ptr, sizeof(val));
@@ -954,7 +975,7 @@
 }
 
 static PyObject *
-Q_get_sw(void *ptr, unsigned size)
+Q_get_sw(void *ptr, Py_ssize_t size)
 {
 	unsigned PY_LONG_LONG val;
 	memcpy(&val, ptr, sizeof(val));
@@ -971,7 +992,7 @@
 
 
 static PyObject *
-d_set(void *ptr, PyObject *value, unsigned size)
+d_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	double x;
 
@@ -987,7 +1008,7 @@
 }
 
 static PyObject *
-d_get(void *ptr, unsigned size)
+d_get(void *ptr, Py_ssize_t size)
 {
 	double val;
 	memcpy(&val, ptr, sizeof(val));
@@ -995,7 +1016,7 @@
 }
 
 static PyObject *
-d_set_sw(void *ptr, PyObject *value, unsigned size)
+d_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	double x;
 
@@ -1017,7 +1038,7 @@
 }
 
 static PyObject *
-d_get_sw(void *ptr, unsigned size)
+d_get_sw(void *ptr, Py_ssize_t size)
 {
 #ifdef WORDS_BIGENDIAN
 	return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1));
@@ -1027,7 +1048,7 @@
 }
 
 static PyObject *
-f_set(void *ptr, PyObject *value, unsigned size)
+f_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	float x;
 
@@ -1043,7 +1064,7 @@
 }
 
 static PyObject *
-f_get(void *ptr, unsigned size)
+f_get(void *ptr, Py_ssize_t size)
 {
 	float val;
 	memcpy(&val, ptr, sizeof(val));
@@ -1051,7 +1072,7 @@
 }
 
 static PyObject *
-f_set_sw(void *ptr, PyObject *value, unsigned size)
+f_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	float x;
 
@@ -1073,7 +1094,7 @@
 }
 
 static PyObject *
-f_get_sw(void *ptr, unsigned size)
+f_get_sw(void *ptr, Py_ssize_t size)
 {
 #ifdef WORDS_BIGENDIAN
 	return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1));
@@ -1093,7 +1114,7 @@
   Py_DECREF on destruction.  Maybe only when b_needsfree is non-zero.
 */
 static PyObject *
-O_get(void *ptr, unsigned size)
+O_get(void *ptr, Py_ssize_t size)
 {
 	PyObject *ob = *(PyObject **)ptr;
 	if (ob == NULL) {
@@ -1108,7 +1129,7 @@
 }
 
 static PyObject *
-O_set(void *ptr, PyObject *value, unsigned size)
+O_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	/* Hm, does the memory block need it's own refcount or not? */
 	*(PyObject **)ptr = value;
@@ -1118,7 +1139,7 @@
 
 
 static PyObject *
-c_set(void *ptr, PyObject *value, unsigned size)
+c_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	if (!PyString_Check(value) || (1 != PyString_Size(value))) {
 		PyErr_Format(PyExc_TypeError,
@@ -1131,7 +1152,7 @@
 
 
 static PyObject *
-c_get(void *ptr, unsigned size)
+c_get(void *ptr, Py_ssize_t size)
 {
 	return PyString_FromStringAndSize((char *)ptr, 1);
 }
@@ -1139,9 +1160,9 @@
 #ifdef CTYPES_UNICODE
 /* u - a single wchar_t character */
 static PyObject *
-u_set(void *ptr, PyObject *value, unsigned size)
+u_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
-	int len;
+	Py_ssize_t len;
 
 	if (PyString_Check(value)) {
 		value = PyUnicode_FromEncodedObject(value,
@@ -1173,17 +1194,17 @@
 
 
 static PyObject *
-u_get(void *ptr, unsigned size)
+u_get(void *ptr, Py_ssize_t size)
 {
 	return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
 }
 
 /* U - a unicode string */
 static PyObject *
-U_get(void *ptr, unsigned size)
+U_get(void *ptr, Py_ssize_t size)
 {
 	PyObject *result;
-	unsigned int len;
+	Py_ssize_t len;
 	Py_UNICODE *p;
 
 	size /= sizeof(wchar_t); /* we count character units here, not bytes */
@@ -1211,9 +1232,9 @@
 }
 
 static PyObject *
-U_set(void *ptr, PyObject *value, unsigned length)
+U_set(void *ptr, PyObject *value, Py_ssize_t length)
 {
-	unsigned int size;
+	Py_ssize_t size;
 
 	/* It's easier to calculate in characters than in bytes */
 	length /= sizeof(wchar_t);
@@ -1234,7 +1255,11 @@
 	size = PyUnicode_GET_SIZE(value);
 	if (size > length) {
 		PyErr_Format(PyExc_ValueError,
+#if (PY_VERSION_HEX < 0x02050000)
 			     "string too long (%d, maximum length %d)",
+#else
+			     "string too long (%zd, maximum length %zd)",
+#endif
 			     size, length);
 		Py_DECREF(value);
 		return NULL;
@@ -1248,9 +1273,10 @@
 #endif
 
 static PyObject *
-s_get(void *ptr, unsigned size)
+s_get(void *ptr, Py_ssize_t size)
 {
 	PyObject *result;
+	size_t slen;
 
 	result = PyString_FromString((char *)ptr);
 	if (!result)
@@ -1258,7 +1284,8 @@
 	/* chop off at the first NUL character, if any.
 	 * On error, result will be deallocated and set to NULL.
 	 */
-	size = min(size, strlen(PyString_AS_STRING(result)));
+	slen = strlen(PyString_AS_STRING(result));
+	size = min(size, (Py_ssize_t)slen);
 	if (result->ob_refcnt == 1) {
 		/* shorten the result */
 		_PyString_Resize(&result, size);
@@ -1269,10 +1296,10 @@
 }
 
 static PyObject *
-s_set(void *ptr, PyObject *value, unsigned length)
+s_set(void *ptr, PyObject *value, Py_ssize_t length)
 {
 	char *data;
-	unsigned size;
+	Py_ssize_t size;
 
 	data = PyString_AsString(value);
 	if (!data)
@@ -1285,7 +1312,11 @@
 		++size;
 	} else if (size > length) {
 		PyErr_Format(PyExc_ValueError,
+#if (PY_VERSION_HEX < 0x02050000)
 			     "string too long (%d, maximum length %d)",
+#else
+			     "string too long (%zd, maximum length %zd)",
+#endif
 			     size, length);
 		return NULL;
 	}
@@ -1295,7 +1326,7 @@
 }
 
 static PyObject *
-z_set(void *ptr, PyObject *value, unsigned size)
+z_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	if (value == Py_None) {
 		*(char **)ptr = NULL;
@@ -1329,7 +1360,7 @@
 }
 
 static PyObject *
-z_get(void *ptr, unsigned size)
+z_get(void *ptr, Py_ssize_t size)
 {
 	/* XXX What about invalid pointers ??? */
 	if (*(void **)ptr) {
@@ -1337,7 +1368,7 @@
 		if (IsBadStringPtrA(*(char **)ptr, -1)) {
 			PyErr_Format(PyExc_ValueError,
 				     "invalid string pointer %p",
-				     ptr);
+				     *(char **)ptr);
 			return NULL;
 		}
 #endif
@@ -1350,7 +1381,7 @@
 
 #ifdef CTYPES_UNICODE
 static PyObject *
-Z_set(void *ptr, PyObject *value, unsigned size)
+Z_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	if (value == Py_None) {
 		*(wchar_t **)ptr = NULL;
@@ -1397,7 +1428,7 @@
 		size *= sizeof(wchar_t);
 		buffer = (wchar_t *)PyMem_Malloc(size);
 		if (!buffer)
-			return NULL;
+			return PyErr_NoMemory();
 		memset(buffer, 0, size);
 		keep = PyCObject_FromVoidPtr(buffer, PyMem_Free);
 		if (!keep) {
@@ -1418,13 +1449,21 @@
 }
 
 static PyObject *
-Z_get(void *ptr, unsigned size)
+Z_get(void *ptr, Py_ssize_t size)
 {
 	wchar_t *p;
 	p = *(wchar_t **)ptr;
-	if (p)
+	if (p) {
+#if defined(MS_WIN32) && !defined(_WIN32_WCE)
+		if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) {
+			PyErr_Format(PyExc_ValueError,
+				     "invalid string pointer %p",
+				     *(wchar_t **)ptr);
+			return NULL;
+		}
+#endif
 		return PyUnicode_FromWideChar(p, wcslen(p));
-	else {
+	} else {
 		Py_INCREF(Py_None);
 		return Py_None;
 	}
@@ -1432,19 +1471,10 @@
 #endif
 
 #ifdef MS_WIN32
-/* We cannot use SysFreeString as the PyCObject_FromVoidPtr
-   because of different calling convention
-*/
-static void _my_SysFreeString(void *p)
-{
-	SysFreeString((BSTR)p);
-}
-
 static PyObject *
-BSTR_set(void *ptr, PyObject *value, unsigned size)
+BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	BSTR bstr;
-	PyObject *result;
 
 	/* convert value into a PyUnicodeObject or NULL */
 	if (Py_None == value) {
@@ -1466,30 +1496,31 @@
 
 	/* create a BSTR from value */
 	if (value) {
+		Py_ssize_t size = PyUnicode_GET_SIZE(value);
+		if ((unsigned) size != size) {
+			PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
+			return NULL;
+		}
 		bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
-					 PyUnicode_GET_SIZE(value));
+					 (unsigned)size);
 		Py_DECREF(value);
 	} else
 		bstr = NULL;
 
-	if (bstr) {
-		result = PyCObject_FromVoidPtr((void *)bstr, _my_SysFreeString);
-		if (result == NULL) {
-			SysFreeString(bstr);
-			return NULL;
-		}
-	} else {
-		result = Py_None;
-		Py_INCREF(result);
-	}
-
+	/* free the previous contents, if any */
+	if (*(BSTR *)ptr)
+		SysFreeString(*(BSTR *)ptr);
+	
+	/* and store it */
 	*(BSTR *)ptr = bstr;
-	return result;
+
+	/* We don't need to keep any other object */
+	_RET(value);
 }
 
 
 static PyObject *
-BSTR_get(void *ptr, unsigned size)
+BSTR_get(void *ptr, Py_ssize_t size)
 {
 	BSTR p;
 	p = *(BSTR *)ptr;
@@ -1506,7 +1537,7 @@
 #endif
 
 static PyObject *
-P_set(void *ptr, PyObject *value, unsigned size)
+P_set(void *ptr, PyObject *value, Py_ssize_t size)
 {
 	void *v;
 	if (value == Py_None) {
@@ -1539,7 +1570,7 @@
 }
 
 static PyObject *
-P_get(void *ptr, unsigned size)
+P_get(void *ptr, Py_ssize_t size)
 {
 	if (*(void **)ptr == NULL) {
 		Py_INCREF(Py_None);
@@ -1585,6 +1616,17 @@
 	{ 'X', BSTR_set, BSTR_get, &ffi_type_pointer},
 	{ 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort},
 #endif
+#if SIZEOF__BOOL == 1
+	{ 't', t_set, t_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */
+#elif SIZEOF__BOOL == SIZEOF_SHORT
+	{ 't', t_set, t_get, &ffi_type_ushort},
+#elif SIZEOF__BOOL == SIZEOF_INT
+	{ 't', t_set, t_get, &ffi_type_uint, I_set_sw, I_get_sw},
+#elif SIZEOF__BOOL == SIZEOF_LONG
+	{ 't', t_set, t_get, &ffi_type_ulong, L_set_sw, L_get_sw},
+#elif SIZEOF__BOOL == SIZEOF_LONG_LONG
+	{ 't', t_set, t_get, &ffi_type_ulong, Q_set_sw, Q_get_sw},
+#endif /* SIZEOF__BOOL */
 	{ 'O', O_set, O_get, &ffi_type_pointer},
 	{ 0, NULL, NULL, NULL},
 };

Modified: python/branches/p3yk-noslice/Modules/_ctypes/ctypes.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/ctypes.h	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/ctypes.h	Wed Jul 11 15:40:56 2007
@@ -4,6 +4,7 @@
 
 #if (PY_VERSION_HEX < 0x02050000)
 typedef int Py_ssize_t;
+#define PyInt_FromSsize_t PyInt_FromLong
 #endif
 
 #ifndef MS_WIN32
@@ -25,8 +26,8 @@
 
 typedef struct tagPyCArgObject PyCArgObject;
 typedef struct tagCDataObject CDataObject;
-typedef PyObject *(* GETFUNC)(void *, unsigned size);
-typedef PyObject *(* SETFUNC)(void *, PyObject *value, unsigned size);
+typedef PyObject *(* GETFUNC)(void *, Py_ssize_t size);
+typedef PyObject *(* SETFUNC)(void *, PyObject *value, Py_ssize_t size);
 typedef PyCArgObject *(* PARAMFUNC)(CDataObject *obj);
 
 /* A default buffer in CDataObject, which can be used for small C types.  If
@@ -131,9 +132,9 @@
 
 
 extern PyObject *
-CField_FromDesc(PyObject *desc, int index,
-		int *pfield_size, int bitsize, int *pbitofs,
-		int *psize, int *poffset, int *palign,
+CField_FromDesc(PyObject *desc, Py_ssize_t index,
+		Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
+		Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
 		int pack, int is_big_endian);
 
 extern PyObject *CData_AtAddress(PyObject *type, void *buf);
@@ -304,7 +305,7 @@
 		void *p;
 	} value;
 	PyObject *obj;
-	int size; /* for the 'V' tag */
+	Py_ssize_t size; /* for the 'V' tag */
 };
 
 extern PyTypeObject PyCArg_Type;
@@ -381,7 +382,7 @@
 #  define PyUnicode_AsWideChar My_PyUnicode_AsWideChar
 
 extern PyObject *My_PyUnicode_FromWideChar(const wchar_t *, Py_ssize_t);
-extern int My_PyUnicode_AsWideChar(PyUnicodeObject *, wchar_t *, Py_ssize_t);
+extern Py_ssize_t My_PyUnicode_AsWideChar(PyUnicodeObject *, wchar_t *, Py_ssize_t);
 
 #endif
 

Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure	Wed Jul 11 15:40:56 2007
@@ -934,7 +934,7 @@
     else
       echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
     fi
-    cd "$ac_popdir"
+    cd $ac_popdir
   done
 fi
 
@@ -1973,7 +1973,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2031,7 +2032,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2147,7 +2149,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2201,7 +2204,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2246,7 +2250,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2290,7 +2295,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2617,7 +2623,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2787,7 +2794,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -2854,7 +2862,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3038,7 +3047,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3101,7 +3111,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3279,7 +3290,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3396,7 +3408,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3569,7 +3582,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3770,7 +3784,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3833,7 +3848,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -3914,7 +3930,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4055,7 +4072,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4191,7 +4209,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4253,7 +4272,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4293,7 +4313,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4349,7 +4370,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4389,7 +4411,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4453,7 +4476,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4484,8 +4508,10 @@
 esac
 else
   if test "$cross_compiling" = yes; then
-  { { echo "$as_me:$LINENO: error: internal error: not reached in cross-compile" >&5
-echo "$as_me: error: internal error: not reached in cross-compile" >&2;}
+  { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&2;}
    { (exit 1); exit 1; }; }
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -4597,7 +4623,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4659,7 +4686,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4699,7 +4727,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4755,7 +4784,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4795,7 +4825,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4859,7 +4890,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -4890,8 +4922,10 @@
 esac
 else
   if test "$cross_compiling" = yes; then
-  { { echo "$as_me:$LINENO: error: internal error: not reached in cross-compile" >&5
-echo "$as_me: error: internal error: not reached in cross-compile" >&2;}
+  { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&2;}
    { (exit 1); exit 1; }; }
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -4986,6 +5020,479 @@
 fi
 
 
+echo "$as_me:$LINENO: checking for _Bool support" >&5
+echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6
+have_c99_bool=no
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+_Bool x; x = (_Bool)0;
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_C99_BOOL 1
+_ACEOF
+
+  have_c99_bool=yes
+
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+echo "$as_me:$LINENO: result: $have_c99_bool" >&5
+echo "${ECHO_T}$have_c99_bool" >&6
+if test "$have_c99_bool" = yes ; then
+echo "$as_me:$LINENO: checking for _Bool" >&5
+echo $ECHO_N "checking for _Bool... $ECHO_C" >&6
+if test "${ac_cv_type__Bool+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+if ((_Bool *) 0)
+  return 0;
+if (sizeof (_Bool))
+  return 0;
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_type__Bool=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type__Bool=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5
+echo "${ECHO_T}$ac_cv_type__Bool" >&6
+
+echo "$as_me:$LINENO: checking size of _Bool" >&5
+echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6
+if test "${ac_cv_sizeof__Bool+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test "$ac_cv_type__Bool" = yes; then
+  # The cast to unsigned long works around a bug in the HP C Compiler
+  # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
+  # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
+  # This bug is HP SR number 8606223364.
+  if test "$cross_compiling" = yes; then
+  # Depending upon the size, compute the lo and hi bounds.
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) >= 0)];
+test_array [0] = 0
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_lo=0 ac_mid=0
+  while :; do
+    cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) <= $ac_mid)];
+test_array [0] = 0
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_hi=$ac_mid; break
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_lo=`expr $ac_mid + 1`
+		    if test $ac_lo -le $ac_mid; then
+		      ac_lo= ac_hi=
+		      break
+		    fi
+		    ac_mid=`expr 2 '*' $ac_mid + 1`
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+  done
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) < 0)];
+test_array [0] = 0
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_hi=-1 ac_mid=-1
+  while :; do
+    cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) >= $ac_mid)];
+test_array [0] = 0
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_lo=$ac_mid; break
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_hi=`expr '(' $ac_mid ')' - 1`
+		       if test $ac_mid -le $ac_hi; then
+			 ac_lo= ac_hi=
+			 break
+		       fi
+		       ac_mid=`expr 2 '*' $ac_mid`
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+  done
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_lo= ac_hi=
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+# Binary search between lo and hi bounds.
+while test "x$ac_lo" != "x$ac_hi"; do
+  ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo`
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long) (sizeof (_Bool))) <= $ac_mid)];
+test_array [0] = 0
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  (eval $ac_compile) 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } &&
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; } &&
+	 { ac_try='test -s conftest.$ac_objext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_hi=$ac_mid
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_lo=`expr '(' $ac_mid ')' + 1`
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+case $ac_lo in
+?*) ac_cv_sizeof__Bool=$ac_lo;;
+'') { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool), 77
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute sizeof (_Bool), 77
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; } ;;
+esac
+else
+  if test "$cross_compiling" = yes; then
+  { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run test program while cross compiling
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+long longval () { return (long) (sizeof (_Bool)); }
+unsigned long ulongval () { return (long) (sizeof (_Bool)); }
+#include <stdio.h>
+#include <stdlib.h>
+int
+main ()
+{
+
+  FILE *f = fopen ("conftest.val", "w");
+  if (! f)
+    exit (1);
+  if (((long) (sizeof (_Bool))) < 0)
+    {
+      long i = longval ();
+      if (i != ((long) (sizeof (_Bool))))
+	exit (1);
+      fprintf (f, "%ld\n", i);
+    }
+  else
+    {
+      unsigned long i = ulongval ();
+      if (i != ((long) (sizeof (_Bool))))
+	exit (1);
+      fprintf (f, "%lu\n", i);
+    }
+  exit (ferror (f) || fclose (f) != 0);
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  (eval $ac_link) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+  ac_cv_sizeof__Bool=`cat conftest.val`
+else
+  echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+{ { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool), 77
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute sizeof (_Bool), 77
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+fi
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+fi
+rm -f conftest.val
+else
+  ac_cv_sizeof__Bool=0
+fi
+fi
+echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5
+echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6
+cat >>confdefs.h <<_ACEOF
+#define SIZEOF__BOOL $ac_cv_sizeof__Bool
+_ACEOF
+
+
+fi
+
 echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5
 echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6
 if test "${ac_cv_c_bigendian+set}" = set; then
@@ -5021,7 +5528,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -5063,7 +5571,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -5120,7 +5629,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -5252,7 +5762,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -5318,7 +5829,8 @@
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } &&
-	 { ac_try='test -z "$ac_c_werror_flag"			 || test ! -s conftest.err'
+	 { ac_try='test -z "$ac_c_werror_flag"
+			 || test ! -s conftest.err'
   { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
   (eval $ac_try) 2>&5
   ac_status=$?
@@ -6277,6 +6789,11 @@
 
 
 
+  if test x"$ac_file" != x-; then
+    { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    rm -f "$ac_file"
+  fi
   # Let's still pretend it is `configure' which instantiates (i.e., don't
   # use $as_me), people would be surprised to read:
   #    /* config.h.  Generated by config.status.  */
@@ -6315,12 +6832,6 @@
 	 fi;;
       esac
     done` || { (exit 1); exit 1; }
-
-  if test x"$ac_file" != x-; then
-    { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    rm -f "$ac_file"
-  fi
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF
   sed "$ac_vpsub

Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure.ac
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure.ac	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi/configure.ac	Wed Jul 11 15:40:56 2007
@@ -106,6 +106,17 @@
 fi
 AC_SUBST(HAVE_LONG_DOUBLE)
 
+AC_MSG_CHECKING(for _Bool support)
+have_c99_bool=no
+AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [
+  AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) 
+  have_c99_bool=yes
+])
+AC_MSG_RESULT($have_c99_bool)
+if test "$have_c99_bool" = yes ; then
+AC_CHECK_SIZEOF(_Bool, 1)
+fi
+
 AC_C_BIGENDIAN
 AH_VERBATIM([WORDS_BIGENDIAN],
 [

Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi/fficonfig.h.in
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi/fficonfig.h.in	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi/fficonfig.h.in	Wed Jul 11 15:40:56 2007
@@ -28,6 +28,9 @@
    */
 #undef HAVE_AS_SPARC_UA_PCREL
 
+/* Define this if you have the type _Bool. */
+#undef HAVE_C99_BOOL
+
 /* Define if __attribute__((visibility("hidden"))) is supported. */
 #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
 
@@ -103,6 +106,9 @@
 /* The size of a `long double', as computed by sizeof. */
 #undef SIZEOF_LONG_DOUBLE
 
+/* The size of a `_Bool', as computed by sizeof. */
+#undef SIZEOF__BOOL
+
 /* If using the C implementation of alloca, define if you know the
    direction of stack growth for your system; otherwise it will be
    automatically deduced at run-time.

Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi.c	Wed Jul 11 15:40:56 2007
@@ -174,7 +174,7 @@
 			  /*@out@*/ extended_cif *, 
 			  unsigned, unsigned, 
 			  /*@out@*/ unsigned *, 
-			  void (*fn)());
+			  void (*fn)(void));
 /*@=declundef@*/
 /*@=exportheader@*/
 
@@ -185,13 +185,13 @@
 			  /*@out@*/ extended_cif *,
 			  unsigned, unsigned,
 			  /*@out@*/ unsigned *,
-			  void (*fn)());
+			  void (*fn)(void));
 /*@=declundef@*/
 /*@=exportheader@*/
 #endif /* X86_WIN32 */
 
 void ffi_call(/*@dependent@*/ ffi_cif *cif, 
-	      void (*fn)(), 
+	      void (*fn)(void), 
 	      /*@out@*/ void *rvalue, 
 	      /*@dependent@*/ void **avalue)
 {
@@ -405,7 +405,7 @@
 	      /*@out@*/ extended_cif *, 
 	      unsigned, unsigned, 
 	      /*@out@*/ unsigned *, 
-	      void (*fn)());
+	      void (*fn)(void));
 
 #ifdef X86_WIN32
 extern void
@@ -413,12 +413,12 @@
 	      /*@out@*/ extended_cif *,
 	      unsigned, unsigned,
 	      /*@out@*/ unsigned *,
-	      void (*fn)());
+	      void (*fn)(void));
 #endif /* X86_WIN32 */
 
 void
 ffi_raw_call(/*@dependent@*/ ffi_cif *cif, 
-	     void (*fn)(), 
+	     void (*fn)(void), 
 	     /*@out@*/ void *rvalue, 
 	     /*@dependent@*/ ffi_raw *fake_avalue)
 {

Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi64.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi64.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi/src/x86/ffi64.c	Wed Jul 11 15:40:56 2007
@@ -42,7 +42,7 @@
 };
 
 extern void ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags,
-			     void *raddr, void (*fnaddr)(), unsigned ssecount);
+			     void *raddr, void (*fnaddr)(void), unsigned ssecount);
 
 /* All reference to register classes here is identical to the code in
    gcc/config/i386/i386.c. Do *not* change one without the other.  */
@@ -339,7 +339,7 @@
 }
 
 void
-ffi_call (ffi_cif *cif, void (*fn)(), void *rvalue, void **avalue)
+ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
 {
   enum x86_64_reg_class classes[MAX_CLASSES];
   char *stack, *argp;

Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffitarget.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffitarget.h	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffitarget.h	Wed Jul 11 15:40:56 2007
@@ -36,7 +36,11 @@
 /* ---- Generic type definitions ----------------------------------------- */
 
 #ifndef LIBFFI_ASM
+#ifndef _WIN64
 typedef unsigned long          ffi_arg;
+#else
+typedef unsigned __int64       ffi_arg;
+#endif
 typedef signed long            ffi_sarg;
 
 typedef enum ffi_abi {

Modified: python/branches/p3yk-noslice/Modules/_ctypes/stgdict.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/stgdict.c	(original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/stgdict.c	Wed Jul 11 15:40:56 2007
@@ -50,7 +50,7 @@
 StgDict_clone(StgDictObject *dst, StgDictObject *src)
 {
 	char *d, *s;
-	int size;
+	Py_ssize_t size;
 
 	StgDict_clear(dst);
 	PyMem_Free(dst->ffi_type_pointer.elements);
@@ -72,8 +72,10 @@
 		return 0;
 	size = sizeof(ffi_type *) * (src->length + 1);
 	dst->ffi_type_pointer.elements = PyMem_Malloc(size);
-	if (dst->ffi_type_pointer.elements == NULL)
+	if (dst->ffi_type_pointer.elements == NULL) {
+		PyErr_NoMemory();
 		return -1;
+	}
 	memcpy(dst->ffi_type_pointer.elements,
 	       src->ffi_type_pointer.elements,
 	       size);
@@ -283,13 +285,13 @@
 StructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct)
 {
 	StgDictObject *stgdict, *basedict;
-	int len, offset, size, align, i;
-	int union_size, total_align;
-	int field_size = 0;
+	Py_ssize_t len, offset, size, align, i;
+	Py_ssize_t union_size, total_align;
+	Py_ssize_t field_size = 0;
 	int bitofs;
 	PyObject *isPacked;
 	int pack = 0;
-	int ffi_ofs;
+	Py_ssize_t ffi_ofs;
 	int big_endian;
 
 	/* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
@@ -355,6 +357,10 @@
 		total_align = align ? align : 1;
 		stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
 		stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
+		if (stgdict->ffi_type_pointer.elements == NULL) {
+			PyErr_NoMemory();
+			return -1;
+		}
 		memset(stgdict->ffi_type_pointer.elements, 0,
 		       sizeof(ffi_type *) * (basedict->length + len + 1));
 		memcpy(stgdict->ffi_type_pointer.elements,
@@ -369,6 +375,10 @@
 		total_align = 1;
 		stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
 		stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
+		if (stgdict->ffi_type_pointer.elements == NULL) {
+			PyErr_NoMemory();
+			return -1;
+		}
 		memset(stgdict->ffi_type_pointer.elements, 0,
 		       sizeof(ffi_type *) * (len + 1));
 		ffi_ofs = 0;
@@ -392,7 +402,11 @@
 		if (dict == NULL) {
 			Py_DECREF(pair);
 			PyErr_Format(PyExc_TypeError,
+#if (PY_VERSION_HEX < 0x02050000)
 				     "second item in _fields_ tuple (index %d) must be a C type",
+#else
+				     "second item in _fields_ tuple (index %zd) must be a C type",
+#endif
 				     i);
 			return -1;
 		}
@@ -470,7 +484,9 @@
 	/* Adjust the size according to the alignment requirements */
 	size = ((size + total_align - 1) / total_align) * total_align;
 
-	stgdict->ffi_type_pointer.alignment = total_align;
+	stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
+							       Py_ssize_t,
+							       unsigned short);
 	stgdict->ffi_type_pointer.size = size;
 
 	stgdict->size = size;

Modified: python/branches/p3yk-noslice/Modules/_cursesmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_cursesmodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/_cursesmodule.c	Wed Jul 11 15:40:56 2007
@@ -35,19 +35,22 @@
 
 /*
 
-A number of SysV or ncurses functions don't have wrappers yet; if you need
-a given function, add it and send a patch.  Here's a list of currently
-unsupported functions:
+A number of SysV or ncurses functions don't have wrappers yet; if you
+need a given function, add it and send a patch.  See
+http://www.python.org/dev/patches/ for instructions on how to submit
+patches to Python.
 
-	addchnstr addchstr chgat color_set define_key
+Here's a list of currently unsupported functions:
+
+	addchnstr addchstr color_set define_key
 	del_curterm delscreen dupwin inchnstr inchstr innstr keyok
-	mcprint mvaddchnstr mvaddchstr mvchgat mvcur mvinchnstr
-	mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr mvwchgat
+	mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr
+	mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr 
 	mvwinchnstr mvwinchstr mvwinnstr newterm
 	restartterm ripoffline scr_dump
 	scr_init scr_restore scr_set scrl set_curterm set_term setterm
 	tgetent tgetflag tgetnum tgetstr tgoto timeout tputs
-	vidattr vidputs waddchnstr waddchstr wchgat
+	vidattr vidputs waddchnstr waddchstr
 	wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl
 
 Low-priority: 
@@ -620,6 +623,56 @@
 }
 #endif
 
+/* chgat, added by Fabian Kreutz <fabian.kreutz at gmx.net> */
+
+static PyObject *
+PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args)
+{
+  int rtn;
+  int x, y;
+  int num = -1;
+  short color;
+  attr_t attr = A_NORMAL;
+  int use_xy = FALSE;
+
+  switch (PyTuple_Size(args)) {
+  case 1:
+    if (!PyArg_ParseTuple(args,"l;attr", &attr))
+      return NULL;
+    break;
+  case 2:
+    if (!PyArg_ParseTuple(args,"il;n,attr", &num, &attr))
+      return NULL;
+    break;
+  case 3:
+    if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &attr))
+      return NULL;
+    use_xy = TRUE;
+    break;
+  case 4:
+    if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &attr))
+      return NULL;
+    use_xy = TRUE;
+    break;
+  default:
+    PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments");
+    return NULL;
+  }
+
+  color = (short)((attr >> 8) & 0xff);
+  attr = attr - (color << 8);
+
+  if (use_xy == TRUE) {
+    rtn = mvwchgat(self->win,y,x,num,attr,color,NULL);
+    touchline(self->win,y,1);
+  } else {
+    getyx(self->win,y,x);
+    rtn = wchgat(self->win,num,attr,color,NULL);
+    touchline(self->win,y,1);
+  }
+  return PyCursesCheckERR(rtn, "chgat");
+}
+
 
 static PyObject *
 PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args)
@@ -1246,7 +1299,7 @@
 PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args)
 {
   int beg, num;
-  if (!PyArg_ParseTuple(args,"ii;beg,num", &beg, &num))
+  if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num))
     return NULL;
   return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln");
 }
@@ -1428,6 +1481,7 @@
 	{"attron",          (PyCFunction)PyCursesWindow_wattron, METH_VARARGS},
 	{"attrset",         (PyCFunction)PyCursesWindow_wattrset, METH_VARARGS},
 	{"bkgd",            (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS},
+	{"chgat",           (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS},
 	{"bkgdset",         (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS},
 	{"border",          (PyCFunction)PyCursesWindow_Border, METH_VARARGS},
 	{"box",             (PyCFunction)PyCursesWindow_Box, METH_VARARGS},
@@ -1479,7 +1533,7 @@
 	{"overwrite",       (PyCFunction)PyCursesWindow_Overwrite,
          METH_VARARGS},
 	{"putwin",          (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS},
-	{"redrawln",        (PyCFunction)PyCursesWindow_RedrawLine},
+	{"redrawln",        (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS},
 	{"redrawwin",       (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS},
 	{"refresh",         (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS},
 #ifndef STRICT_SYSV_CURSES
@@ -2196,19 +2250,72 @@
   }
 }
 
+/* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES
+ * and _curses.COLS */
+static int
+update_lines_cols(void)
+{
+  PyObject *o;
+  PyObject *m = PyImport_ImportModule("curses");
+
+  if (!m)
+    return 0;
+
+  o = PyInt_FromLong(LINES);
+  if (!o) {
+    Py_DECREF(m);
+    return 0;
+  }
+  if (PyObject_SetAttrString(m, "LINES", o)) {
+    Py_DECREF(m);
+    Py_DECREF(o);
+    return 0;
+  }
+  if (PyDict_SetItemString(ModDict, "LINES", o)) {
+    Py_DECREF(m);
+    Py_DECREF(o);
+    return 0;
+  }
+  Py_DECREF(o);
+  o = PyInt_FromLong(COLS);
+  if (!o) {
+    Py_DECREF(m);
+    return 0;
+  }
+  if (PyObject_SetAttrString(m, "COLS", o)) {
+    Py_DECREF(m);
+    Py_DECREF(o);
+    return 0;
+  }
+  if (PyDict_SetItemString(ModDict, "COLS", o)) {
+    Py_DECREF(m);
+    Py_DECREF(o);
+    return 0;
+  }
+  Py_DECREF(o);
+  Py_DECREF(m);
+  return 1;
+}
+
 #ifdef HAVE_CURSES_RESIZETERM
 static PyObject *
 PyCurses_ResizeTerm(PyObject *self, PyObject *args)
 {
   int lines;
   int columns;
+  PyObject *result;
 
   PyCursesInitialised
 
   if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns))
     return NULL;
 
-  return PyCursesCheckERR(resizeterm(lines, columns), "resizeterm");
+  result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm");
+  if (!result)
+    return NULL;
+  if (!update_lines_cols())
+    return NULL;
+  return result;
 }
 
 #endif
@@ -2220,12 +2327,19 @@
   int lines;
   int columns;
 
+  PyObject *result;
+
   PyCursesInitialised
 
   if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns))
     return NULL;
 
-  return PyCursesCheckERR(resize_term(lines, columns), "resize_term");
+  result = PyCursesCheckERR(resize_term(lines, columns), "resize_term");
+  if (!result)
+    return NULL;
+  if (!update_lines_cols())
+    return NULL;
+  return result;
 }
 #endif /* HAVE_CURSES_RESIZE_TERM */
 

Modified: python/branches/p3yk-noslice/Modules/_localemodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_localemodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/_localemodule.c	Wed Jul 11 15:40:56 2007
@@ -96,21 +96,18 @@
 static void
 fixup_ulcase(void)
 {
-    PyObject *mods, *strop, *string, *ulo;
+    PyObject *mods, *string, *ulo;
     unsigned char ul[256];
     int n, c;
 
-    /* find the string and strop modules */
+    /* find the string module */
     mods = PyImport_GetModuleDict();
     if (!mods)
         return;
     string = PyDict_GetItemString(mods, "string");
     if (string)
         string = PyModule_GetDict(string);
-    strop=PyDict_GetItemString(mods, "strop");
-    if (strop)
-        strop = PyModule_GetDict(strop);
-    if (!string && !strop)
+    if (!string)
         return;
 
     /* create uppercase map string */
@@ -124,8 +121,6 @@
         return;
     if (string)
         PyDict_SetItemString(string, "uppercase", ulo);
-    if (strop)
-        PyDict_SetItemString(strop, "uppercase", ulo);
     Py_DECREF(ulo);
 
     /* create lowercase string */
@@ -139,8 +134,6 @@
         return;
     if (string)
         PyDict_SetItemString(string, "lowercase", ulo);
-    if (strop)
-        PyDict_SetItemString(strop, "lowercase", ulo);
     Py_DECREF(ulo);
 
     /* create letters string */
@@ -360,7 +353,7 @@
     buf = PyMem_Malloc(n1);
     if (!buf)
         return PyErr_NoMemory();
-    n2 = strxfrm(buf, s, n1);
+    n2 = strxfrm(buf, s, n1) + 1;
     if (n2 > n1) {
         /* more space needed */
         buf = PyMem_Realloc(buf, n2);

Modified: python/branches/p3yk-noslice/Modules/_sqlite/cache.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/cache.c	(original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/cache.c	Wed Jul 11 15:40:56 2007
@@ -243,6 +243,7 @@
         }
         template = PyString_FromString("%s <- %s ->%s\n");
         if (!template) {
+            Py_DECREF(fmt_args);
             return NULL;
         }
         display_str = PyString_Format(template, fmt_args);

Modified: python/branches/p3yk-noslice/Modules/_sqlite/module.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/module.c	(original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/module.c	Wed Jul 11 15:40:56 2007
@@ -287,12 +287,12 @@
 
     /*** Create DB-API Exception hierarchy */
 
-    if (!(pysqlite_Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
+    if (!(pysqlite_Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_Exception, NULL))) {
         goto error;
     }
     PyDict_SetItemString(dict, "Error", pysqlite_Error);
 
-    if (!(pysqlite_Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
+    if (!(pysqlite_Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_Exception, NULL))) {
         goto error;
     }
     PyDict_SetItemString(dict, "Warning", pysqlite_Warning);

Modified: python/branches/p3yk-noslice/Modules/_struct.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_struct.c	(original)
+++ python/branches/p3yk-noslice/Modules/_struct.c	Wed Jul 11 15:40:56 2007
@@ -847,7 +847,7 @@
 	} while (--i > 0);
 	/* Extend the sign bit. */
 	if (SIZEOF_LONG_LONG > f->size)
-		x |= -(x & (1L << ((8 * f->size) - 1)));
+		x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
 	if (x >= LONG_MIN && x <= LONG_MAX)
 		return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
 	return PyLong_FromLongLong(x);
@@ -1083,7 +1083,7 @@
 	} while (i > 0);
 	/* Extend the sign bit. */
 	if (SIZEOF_LONG_LONG > f->size)
-		x |= -(x & (1L << ((8 * f->size) - 1)));
+		x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
 	if (x >= LONG_MIN && x <= LONG_MAX)
 		return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
 	return PyLong_FromLongLong(x);
@@ -1523,26 +1523,44 @@
 
 
 PyDoc_STRVAR(s_unpack__doc__,
-"S.unpack(str) -> (v1, v2, ...)\n\
+"S.unpack(buffer) -> (v1, v2, ...)\n\
 \n\
 Return tuple containing values unpacked according to this Struct's format.\n\
-Requires len(str) == self.size. See struct.__doc__ for more on format\n\
+Requires len(buffer) == self.size. See struct.__doc__ for more on format\n\
 strings.");
 
 static PyObject *
 s_unpack(PyObject *self, PyObject *inputstr)
 {
+	char *start;
+	Py_ssize_t len;
+	PyObject *args=NULL, *result;
 	PyStructObject *soself = (PyStructObject *)self;
 	assert(PyStruct_Check(self));
 	assert(soself->s_codes != NULL);
-	if (inputstr == NULL || !PyString_Check(inputstr) ||
-		PyString_GET_SIZE(inputstr) != soself->s_size) {
-		PyErr_Format(StructError,
-			"unpack requires a string argument of length %zd",
-			soself->s_size);
-		return 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));
 	}
-	return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
+	args = PyTuple_Pack(1, inputstr);
+	if (args == NULL)
+		return NULL;
+	if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
+		goto fail;
+	if (soself->s_size != len)
+		goto fail;
+	result = s_unpack_internal(soself, start);
+	Py_DECREF(args);
+	return result;
+
+fail:
+	Py_XDECREF(args);
+	PyErr_Format(StructError,
+		"unpack requires a string argument of length %zd",
+		soself->s_size);
+	return NULL;
 }
 
 PyDoc_STRVAR(s_unpack_from__doc__,
@@ -1769,7 +1787,7 @@
 	{"pack",	s_pack,		METH_VARARGS, s_pack__doc__},
 	{"pack_into",	s_pack_into,	METH_VARARGS, s_pack_into__doc__},
 	{"unpack",	s_unpack,       METH_O, s_unpack__doc__},
-	{"unpack_from",	(PyCFunction)s_unpack_from, METH_KEYWORDS,
+	{"unpack_from",	(PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
 			s_unpack_from__doc__},
 	{NULL,	 NULL}		/* sentinel */
 };

Modified: python/branches/p3yk-noslice/Modules/_testcapimodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_testcapimodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/_testcapimodule.c	Wed Jul 11 15:40:56 2007
@@ -728,7 +728,7 @@
 		e->tv_sec -=1;
 		e->tv_usec += 1000000;
 	}
-	printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, e->tv_usec);
+	printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
 }
 
 static PyObject *
@@ -888,6 +888,10 @@
 	unsigned long ulong_member;
 	float float_member;
 	double double_member;
+#ifdef HAVE_LONG_LONG
+	PY_LONG_LONG longlong_member;
+	unsigned PY_LONG_LONG ulonglong_member;
+#endif
 } all_structmembers;
 
 typedef struct {
@@ -906,23 +910,40 @@
 	{"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
 	{"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
 	{"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
+#ifdef HAVE_LONG_LONG
+	{"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
+	{"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
+#endif
 	{NULL}
 };
 
 
 static PyObject *test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs){
 	static char *keywords[]={"T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", "T_INT", "T_UINT",
-		"T_LONG", "T_ULONG", "T_FLOAT", "T_DOUBLE", NULL};
+		"T_LONG", "T_ULONG", "T_FLOAT", "T_DOUBLE",
+		#ifdef HAVE_LONG_LONG	
+		"T_LONGLONG", "T_ULONGLONG",
+		#endif
+		NULL};
+	static char *fmt="|bBhHiIlkfd"
+		#ifdef HAVE_LONG_LONG
+		"LK"
+		#endif
+		;
 	test_structmembers *ob=PyObject_New(test_structmembers, type);
 	if (ob==NULL)
 		return NULL;
 	memset(&ob->structmembers, 0, sizeof(all_structmembers));
-	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|bBhHiIlkfd", keywords,
+	if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
 		&ob->structmembers.byte_member, &ob->structmembers.ubyte_member,
 		&ob->structmembers.short_member, &ob->structmembers.ushort_member,
 		&ob->structmembers.int_member, &ob->structmembers.uint_member, 
 		&ob->structmembers.long_member, &ob->structmembers.ulong_member,
-		&ob->structmembers.float_member, &ob->structmembers.double_member)){
+		&ob->structmembers.float_member, &ob->structmembers.double_member
+		#ifdef HAVE_LONG_LONG
+		,&ob->structmembers.longlong_member, &ob->structmembers.ulonglong_member
+		#endif
+		)){
 		Py_DECREF(ob);
 		return NULL;
 		}
@@ -1005,6 +1026,9 @@
 	PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
 	PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
 	PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
+	PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
+	PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
+	PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
 	PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
 	PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
 

Modified: python/branches/p3yk-noslice/Modules/_tkinter.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_tkinter.c	(original)
+++ python/branches/p3yk-noslice/Modules/_tkinter.c	Wed Jul 11 15:40:56 2007
@@ -1285,6 +1285,12 @@
 	/* Could add TCL_EVAL_GLOBAL if wrapped by GlobalCall... */
 	int flags = TCL_EVAL_DIRECT;
 
+	/* If args is a single tuple, replace with contents of tuple */
+	if (1 == PyTuple_Size(args)){
+		PyObject* item = PyTuple_GetItem(args, 0);
+		if (PyTuple_Check(item))
+			args = item;
+	}
 #ifdef WITH_THREAD
 	if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
 		/* We cannot call the command directly. Instead, we must
@@ -2698,8 +2704,8 @@
 {
 	{"willdispatch",       Tkapp_WillDispatch, METH_NOARGS},
 	{"wantobjects",	       Tkapp_WantObjects, METH_VARARGS},
-	{"call", 	       Tkapp_Call, METH_OLDARGS},
-	{"globalcall", 	       Tkapp_GlobalCall, METH_OLDARGS},
+	{"call", 	       Tkapp_Call, METH_VARARGS},
+	{"globalcall", 	       Tkapp_GlobalCall, METH_VARARGS},
 	{"eval", 	       Tkapp_Eval, METH_VARARGS},
 	{"globaleval", 	       Tkapp_GlobalEval, METH_VARARGS},
 	{"evalfile", 	       Tkapp_EvalFile, METH_VARARGS},
@@ -2720,7 +2726,7 @@
 	{"exprboolean",        Tkapp_ExprBoolean, METH_VARARGS},
 	{"splitlist", 	       Tkapp_SplitList, METH_VARARGS},
 	{"split", 	       Tkapp_Split, METH_VARARGS},
-	{"merge", 	       Tkapp_Merge, METH_OLDARGS},
+	{"merge", 	       Tkapp_Merge, METH_VARARGS},
 	{"createcommand",      Tkapp_CreateCommand, METH_VARARGS},
 	{"deletecommand",      Tkapp_DeleteCommand, METH_VARARGS},
 #ifdef HAVE_CREATEFILEHANDLER

Deleted: /python/branches/p3yk-noslice/Modules/almodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/almodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,3226 +0,0 @@
-
-#define OLD_INTERFACE		/* define for pre-Irix 6 interface */
-
-#include "Python.h"
-#include "stringobject.h"
-#include <audio.h>
-#include <stdarg.h>
-
-#ifndef AL_NO_ELEM
-#ifndef OLD_INTERFACE
-#define OLD_INTERFACE
-#endif /* OLD_INTERFACE */
-#endif /* AL_NO_ELEM */
-
-static PyObject *ErrorObject;
-
-/* ----------------------------------------------------- */
-
-/* Declarations for objects of type port */
-
-typedef struct {
-	PyObject_HEAD
-	/* XXXX Add your own stuff here */
-	ALport port;
-} alpobject;
-
-static PyTypeObject Alptype;
-
-
-
-/* ---------------------------------------------------------------- */
-
-/* Declarations for objects of type config */
-
-typedef struct {
-	PyObject_HEAD
-	/* XXXX Add your own stuff here */
-	ALconfig config;
-} alcobject;
-
-static PyTypeObject Alctype;
-
-
-static void
-ErrorHandler(long code, const char *fmt, ...)
-{
-	va_list args;
-	char buf[128];
-
-	va_start(args, fmt);
-	vsprintf(buf, fmt, args);
-	va_end(args);
-	PyErr_SetString(ErrorObject, buf);
-}
-
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-
-static PyObject *
-param2python(int resource, int param, ALvalue value, ALparamInfo *pinfo)
-{
-	ALparamInfo info;
-
-	if (pinfo == NULL) {
-		pinfo = &info;
-		if (alGetParamInfo(resource, param, &info) < 0)
-			return NULL;
-	}
-	switch (pinfo->elementType) {
-	case AL_PTR_ELEM:
-		/* XXXX don't know how to handle this */
-	case AL_NO_ELEM:
-		Py_INCREF(Py_None);
-		return Py_None;
-	case AL_INT32_ELEM:
-	case AL_RESOURCE_ELEM:
-	case AL_ENUM_ELEM:
-		return PyInt_FromLong((long) value.i);
-	case AL_INT64_ELEM:
-		return PyLong_FromLongLong(value.ll);
-	case AL_FIXED_ELEM:
-		return PyFloat_FromDouble(alFixedToDouble(value.ll));
-	case AL_CHAR_ELEM:
-		if (value.ptr == NULL) {
-			Py_INCREF(Py_None);
-			return Py_None;
-		}
-		return PyString_FromString((char *) value.ptr);
-	default:
-		PyErr_SetString(ErrorObject, "unknown element type");
-		return NULL;
-	}
-}
-
-static int
-python2elem(PyObject *item, void *ptr, int elementType)
-{
-	switch (elementType) {
-	case AL_INT32_ELEM:
-	case AL_RESOURCE_ELEM:
-	case AL_ENUM_ELEM:
-		if (!PyInt_Check(item)) {
-			PyErr_BadArgument();
-			return -1;
-		}
-		*((int *) ptr) = PyInt_AsLong(item);
-		break;
-	case AL_INT64_ELEM:
-		if (PyInt_Check(item))
-			*((long long *) ptr) = PyInt_AsLong(item);
-		else if (PyLong_Check(item))
-			*((long long *) ptr) = PyLong_AsLongLong(item);
-		else {
-			PyErr_BadArgument();
-			return -1;
-		}
-		break;
-	case AL_FIXED_ELEM:
-		if (PyInt_Check(item))
-			*((long long *) ptr) = alDoubleToFixed((double) PyInt_AsLong(item));
-		else if (PyFloat_Check(item))
-			*((long long *) ptr) = alDoubleToFixed(PyFloat_AsDouble(item));
-		else {
-			PyErr_BadArgument();
-			return -1;
-		}
-		break;
-	default:
-		PyErr_SetString(ErrorObject, "unknown element type");
-		return -1;
-	}
-	return 0;
-}
-
-static int
-python2param(int resource, ALpv *param, PyObject *value, ALparamInfo *pinfo)
-{
-	ALparamInfo info;
-	int i, stepsize;
-	PyObject *item;
-
-	if (pinfo == NULL) {
-		pinfo = &info;
-		if (alGetParamInfo(resource, param->param, &info) < 0)
-			return -1;
-	}
-	switch (pinfo->valueType) {
-	case AL_STRING_VAL:
-		if (pinfo->elementType != AL_CHAR_ELEM) {
-			PyErr_SetString(ErrorObject, "unknown element type");
-			return -1;
-		}
-		if (!PyString_Check(value)) {
-			PyErr_BadArgument();
-			return -1;
-		}
-		param->value.ptr = PyString_AS_STRING(value);
-		param->sizeIn = PyString_GET_SIZE(value)+1; /*account for NUL*/
-		break;
-	case AL_SET_VAL:
-	case AL_VECTOR_VAL:
-		if (!PyList_Check(value) && !PyTuple_Check(value)) {
-			PyErr_BadArgument();
-			return -1;
-		}
-		switch (pinfo->elementType) {
-		case AL_INT32_ELEM:
-		case AL_RESOURCE_ELEM:
-		case AL_ENUM_ELEM:
-			param->sizeIn = PySequence_Size(value);
-			param->value.ptr = PyMem_NEW(int, param->sizeIn);
-			stepsize = sizeof(int);
-			break;
-		case AL_INT64_ELEM:
-		case AL_FIXED_ELEM:
-			param->sizeIn = PySequence_Size(value);
-			param->value.ptr = PyMem_NEW(long long, param->sizeIn);
-			stepsize = sizeof(long long);
-			break;
-		}
-		for (i = 0; i < param->sizeIn; i++) {
-			item = PySequence_GetItem(value, i);
-			if (python2elem(item, (void *) ((char *) param->value.ptr + i*stepsize), pinfo->elementType) < 0) {
-				PyMem_DEL(param->value.ptr);
-				return -1;
-			}
-		}
-		break;
-	case AL_SCALAR_VAL:
-		switch (pinfo->elementType) {
-		case AL_INT32_ELEM:
-		case AL_RESOURCE_ELEM:
-		case AL_ENUM_ELEM:
-			return python2elem(value, (void *) &param->value.i,
-					   pinfo->elementType);
-		case AL_INT64_ELEM:
-		case AL_FIXED_ELEM:
-			return python2elem(value, (void *) &param->value.ll,
-					   pinfo->elementType);
-		default:
-			PyErr_SetString(ErrorObject, "unknown element type");
-			return -1;
-		}
-	}
-	return 0;
-}
-
-static int
-python2params(int resource1, int resource2, PyObject *list, ALpv **pvsp, ALparamInfo **pinfop)
-{
-	PyObject *item;
-	ALpv *pvs;
-	ALparamInfo *pinfo;
-	int npvs, i;
-
-	npvs = PyList_Size(list);
-	pvs = PyMem_NEW(ALpv, npvs);
-	pinfo = PyMem_NEW(ALparamInfo, npvs);
-	for (i = 0; i < npvs; i++) {
-		item = PyList_GetItem(list, i);
-		if (!PyArg_ParseTuple(item, "iO", &pvs[i].param, &item))
-			goto error;
-		if (alGetParamInfo(resource1, pvs[i].param, &pinfo[i]) < 0 &&
-		    alGetParamInfo(resource2, pvs[i].param, &pinfo[i]) < 0)
-			goto error;
-		if (python2param(resource1, &pvs[i], item, &pinfo[i]) < 0)
-			goto error;
-	}
-
-	*pvsp = pvs;
-	*pinfop = pinfo;
-	return npvs;
-
-  error:
-	/* XXXX we should clean up everything */
-	if (pvs)
-		PyMem_DEL(pvs);
-	if (pinfo)
-		PyMem_DEL(pinfo);
-	return -1;
-}
-
-/* -------------------------------------------------------- */
-
-
-static PyObject *
-SetConfig(alcobject *self, PyObject *args, int (*func)(ALconfig, int))
-{
-	int par;
-
-	if (!PyArg_ParseTuple(args, "i:SetConfig", &par))
-		return NULL;
-
-	if ((*func)(self->config, par) == -1)
-		return NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-GetConfig(alcobject *self, PyObject *args, int (*func)(ALconfig))
-{	
-	int par;
-
-	if (!PyArg_ParseTuple(args, ":GetConfig"))
-		return NULL;
-	
-	if ((par = (*func)(self->config)) == -1)
-		return NULL;
-
-	return PyInt_FromLong((long) par);
-}
-
-PyDoc_STRVAR(alc_SetWidth__doc__,
-"alSetWidth: set the wordsize for integer audio data.");
-
-static PyObject *
-alc_SetWidth(alcobject *self, PyObject *args)
-{
-	return SetConfig(self, args, alSetWidth);
-}
-
-
-PyDoc_STRVAR(alc_GetWidth__doc__,
-"alGetWidth: get the wordsize for integer audio data.");
-
-static PyObject *
-alc_GetWidth(alcobject *self, PyObject *args)
-{
-	return GetConfig(self, args, alGetWidth);
-}
-
-
-PyDoc_STRVAR(alc_SetSampFmt__doc__,
-"alSetSampFmt: set the sample format setting in an audio ALconfig "
-"structure.");
-
-static PyObject *
-alc_SetSampFmt(alcobject *self, PyObject *args)
-{
-	return SetConfig(self, args, alSetSampFmt);
-}
-
-
-PyDoc_STRVAR(alc_GetSampFmt__doc__,
-"alGetSampFmt: get the sample format setting in an audio ALconfig "
-"structure.");
-
-static PyObject *
-alc_GetSampFmt(alcobject *self, PyObject *args)
-{
-	return GetConfig(self, args, alGetSampFmt);
-}
-
-
-PyDoc_STRVAR(alc_SetChannels__doc__,
-"alSetChannels: set the channel settings in an audio ALconfig.");
-
-static PyObject *
-alc_SetChannels(alcobject *self, PyObject *args)
-{
-	return SetConfig(self, args, alSetChannels);
-}
-
-
-PyDoc_STRVAR(alc_GetChannels__doc__,
-"alGetChannels: get the channel settings in an audio ALconfig.");
-
-static PyObject *
-alc_GetChannels(alcobject *self, PyObject *args)
-{
-	return GetConfig(self, args, alGetChannels);
-}
-
-
-PyDoc_STRVAR(alc_SetFloatMax__doc__,
-"alSetFloatMax: set the maximum value of floating point sample data.");
-
-static PyObject *
-alc_SetFloatMax(alcobject *self, PyObject *args)
-{
-	double maximum_value;
-
-	if (!PyArg_ParseTuple(args, "d:SetFloatMax", &maximum_value))
-		return NULL;
-	if (alSetFloatMax(self->config, maximum_value) < 0)
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-PyDoc_STRVAR(alc_GetFloatMax__doc__,
-"alGetFloatMax: get the maximum value of floating point sample data.");
-
-static PyObject *
-alc_GetFloatMax(alcobject *self, PyObject *args)
-{
-	double maximum_value;
-
-	if (!PyArg_ParseTuple(args, ":GetFloatMax"))
-		return NULL;
-	if ((maximum_value = alGetFloatMax(self->config)) == 0)
-		return NULL;
-	return PyFloat_FromDouble(maximum_value);
-}
-
-
-PyDoc_STRVAR(alc_SetDevice__doc__,
-"alSetDevice: set the device setting in an audio ALconfig structure.");
-
-static PyObject *
-alc_SetDevice(alcobject *self, PyObject *args)
-{
-	return SetConfig(self, args, alSetDevice);
-}
-
-
-PyDoc_STRVAR(alc_GetDevice__doc__,
-"alGetDevice: get the device setting in an audio ALconfig structure.");
-
-static PyObject *
-alc_GetDevice(alcobject *self, PyObject *args)
-{
-	return GetConfig(self, args, alGetDevice);
-}
-
-
-PyDoc_STRVAR(alc_SetQueueSize__doc__,
-"alSetQueueSize: set audio port buffer size.");
-
-static PyObject *
-alc_SetQueueSize(alcobject *self, PyObject *args)
-{
-	return SetConfig(self, args, alSetQueueSize);
-}
-
-
-PyDoc_STRVAR(alc_GetQueueSize__doc__,
-"alGetQueueSize: get audio port buffer size.");
-
-static PyObject *
-alc_GetQueueSize(alcobject *self, PyObject *args)
-{
-	return GetConfig(self, args, alGetQueueSize);
-}
-
-#endif /* AL_NO_ELEM */
-
-static PyObject *
-setconfig(alcobject *self, PyObject *args, int (*func)(ALconfig, long))
-{
-	long par;
-
-	if (!PyArg_ParseTuple(args, "l:SetConfig", &par))
-		return NULL;
-
-	if ((*func)(self->config, par) == -1)
-		return NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-getconfig(alcobject *self, PyObject *args, long (*func)(ALconfig))
-{	
-	long par;
-
-	if (!PyArg_ParseTuple(args, ":GetConfig"))
-		return NULL;
-	
-	if ((par = (*func)(self->config)) == -1)
-		return NULL;
-
-	return PyInt_FromLong((long) par);
-}
-
-static PyObject *
-alc_setqueuesize (alcobject *self, PyObject *args)
-{
-	return setconfig(self, args, ALsetqueuesize);
-}
-
-static PyObject *
-alc_getqueuesize (alcobject *self, PyObject *args)
-{
-	return getconfig(self, args, ALgetqueuesize);
-}
-
-static PyObject *
-alc_setwidth (alcobject *self, PyObject *args)
-{
-	return setconfig(self, args, ALsetwidth);
-}
-
-static PyObject *
-alc_getwidth (alcobject *self, PyObject *args)
-{
-	return getconfig(self, args, ALgetwidth);	
-}
-
-static PyObject *
-alc_getchannels (alcobject *self, PyObject *args)
-{
-	return getconfig(self, args, ALgetchannels);	
-}
-
-static PyObject *
-alc_setchannels (alcobject *self, PyObject *args)
-{
-	return setconfig(self, args, ALsetchannels);
-}
-
-#ifdef AL_405
-
-static PyObject *
-alc_getsampfmt (alcobject *self, PyObject *args)
-{
-	return getconfig(self, args, ALgetsampfmt);	
-}
-
-static PyObject *
-alc_setsampfmt (alcobject *self, PyObject *args)
-{
-	return setconfig(self, args, ALsetsampfmt);
-}
-
-static PyObject *
-alc_getfloatmax(alcobject *self, PyObject *args)
-{
-	double arg;
-
-	if (!PyArg_ParseTuple(args, ":GetFloatMax"))
-		return 0;
-	if ((arg = ALgetfloatmax(self->config)) == 0)
-		return NULL;
-	return PyFloat_FromDouble(arg);
-}
-
-static PyObject *
-alc_setfloatmax(alcobject *self, PyObject *args)
-{
-	double arg;
-
-	if (!PyArg_ParseTuple(args, "d:SetFloatMax", &arg))
-		return 0;
-	if (ALsetfloatmax(self->config, arg) == -1)
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-#endif /* AL_405 */
-	
-static struct PyMethodDef alc_methods[] = {
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-	{"SetWidth",	(PyCFunction)alc_SetWidth,	METH_VARARGS,	alc_SetWidth__doc__},
-	{"GetWidth",	(PyCFunction)alc_GetWidth,	METH_VARARGS,	alc_GetWidth__doc__},
-	{"SetSampFmt",	(PyCFunction)alc_SetSampFmt,	METH_VARARGS,	alc_SetSampFmt__doc__},
-	{"GetSampFmt",	(PyCFunction)alc_GetSampFmt,	METH_VARARGS,	alc_GetSampFmt__doc__},
-	{"SetChannels",	(PyCFunction)alc_SetChannels,	METH_VARARGS,	alc_SetChannels__doc__},
-	{"GetChannels",	(PyCFunction)alc_GetChannels,	METH_VARARGS,	alc_GetChannels__doc__},
-	{"SetFloatMax",	(PyCFunction)alc_SetFloatMax,	METH_VARARGS,	alc_SetFloatMax__doc__},
-	{"GetFloatMax",	(PyCFunction)alc_GetFloatMax,	METH_VARARGS,	alc_GetFloatMax__doc__},
-	{"SetDevice",	(PyCFunction)alc_SetDevice,	METH_VARARGS,	alc_SetDevice__doc__},
-	{"GetDevice",	(PyCFunction)alc_GetDevice,	METH_VARARGS,	alc_GetDevice__doc__},
-	{"SetQueueSize",	(PyCFunction)alc_SetQueueSize,	METH_VARARGS,	alc_SetQueueSize__doc__},
-	{"GetQueueSize",	(PyCFunction)alc_GetQueueSize,	METH_VARARGS,	alc_GetQueueSize__doc__},
-#endif /* AL_NO_ELEM */
-	{"getqueuesize",	(PyCFunction)alc_getqueuesize,	METH_VARARGS},
-	{"setqueuesize",	(PyCFunction)alc_setqueuesize,	METH_VARARGS},
-	{"getwidth",		(PyCFunction)alc_getwidth,	METH_VARARGS},
-	{"setwidth",		(PyCFunction)alc_setwidth,	METH_VARARGS},
-	{"getchannels",		(PyCFunction)alc_getchannels,	METH_VARARGS},
-	{"setchannels",		(PyCFunction)alc_setchannels,	METH_VARARGS},
-#ifdef AL_405
-	{"getsampfmt",		(PyCFunction)alc_getsampfmt,	METH_VARARGS},
-	{"setsampfmt",		(PyCFunction)alc_setsampfmt,	METH_VARARGS},
-	{"getfloatmax",		(PyCFunction)alc_getfloatmax,	METH_VARARGS},
-	{"setfloatmax",		(PyCFunction)alc_setfloatmax,	METH_VARARGS},
-#endif /* AL_405 */
-
-	{NULL,		NULL}		/* sentinel */
-};
-
-/* ---------- */
-
-
-static PyObject *
-newalcobject(ALconfig config)
-{
-	alcobject *self;
-	
-	self = PyObject_New(alcobject, &Alctype);
-	if (self == NULL)
-		return NULL;
-	/* XXXX Add your own initializers here */
-	self->config = config;
-	return (PyObject *) self;
-}
-
-
-static void
-alc_dealloc(alcobject *self)
-{
-	/* XXXX Add your own cleanup code here */
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-	(void) alFreeConfig(self->config);	/* ignore errors */
-#else
-	(void) ALfreeconfig(self->config);	/* ignore errors */
-#endif
-	PyObject_Del(self);
-}
-
-static PyObject *
-alc_getattr(alcobject *self, char *name)
-{
-	/* XXXX Add your own getattr code here */
-	return Py_FindMethod(alc_methods, (PyObject *)self, name);
-}
-
-PyDoc_STRVAR(Alctype__doc__, "");
-
-static PyTypeObject Alctype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,				/*ob_size*/
-	"al.config",			/*tp_name*/
-	sizeof(alcobject),		/*tp_basicsize*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)alc_dealloc,	/*tp_dealloc*/
-	(printfunc)0,		/*tp_print*/
-	(getattrfunc)alc_getattr,	/*tp_getattr*/
-	(setattrfunc)0,	/*tp_setattr*/
-	(cmpfunc)0,		/*tp_compare*/
-	(reprfunc)0,		/*tp_repr*/
-	0,			/*tp_as_number*/
-	0,		/*tp_as_sequence*/
-	0,		/*tp_as_mapping*/
-	(hashfunc)0,		/*tp_hash*/
-	(ternaryfunc)0,		/*tp_call*/
-	(reprfunc)0,		/*tp_str*/
-
-	/* Space for future expansion */
-	0L,0L,0L,0L,
-	Alctype__doc__ /* Documentation string */
-};
-
-/* End of code for config objects */
-/* ---------------------------------------------------------------- */
-
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-
-PyDoc_STRVAR(alp_SetConfig__doc__,
-"alSetConfig: set the ALconfig of an audio ALport.");
-
-static PyObject *
-alp_SetConfig(alpobject *self, PyObject *args)
-{
-	alcobject *config;
-	if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
-		return NULL;
-	if (alSetConfig(self->port, config->config) < 0)
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-PyDoc_STRVAR(alp_GetConfig__doc__,
-"alGetConfig: get the ALconfig of an audio ALport.");
-
-static PyObject *
-alp_GetConfig(alpobject *self, PyObject *args)
-{
-	ALconfig config;
-	if (!PyArg_ParseTuple(args, ":GetConfig"))
-		return NULL;
-	if ((config = alGetConfig(self->port)) == NULL)
-		return NULL;
-	return newalcobject(config);
-}
-
-
-PyDoc_STRVAR(alp_GetResource__doc__,
-"alGetResource: get the resource associated with an audio port.");
-
-static PyObject *
-alp_GetResource(alpobject *self, PyObject *args)
-{
-	int resource;
-
-	if (!PyArg_ParseTuple(args, ":GetResource"))
-		return NULL;
-	if ((resource = alGetResource(self->port)) == 0)
-		return NULL;
-	return PyInt_FromLong((long) resource);
-}
-
-
-PyDoc_STRVAR(alp_GetFD__doc__,
-"alGetFD: get the file descriptor for an audio port.");
-
-static PyObject *
-alp_GetFD(alpobject *self, PyObject *args)
-{
-	int fd;
-
-	if (!PyArg_ParseTuple(args, ":GetFD"))
-		return NULL;
-
-	if ((fd = alGetFD(self->port)) < 0)
-		return NULL;
-
-	return PyInt_FromLong((long) fd);
-}
-
-
-PyDoc_STRVAR(alp_GetFilled__doc__,
-"alGetFilled: return the number of filled sample frames in "
-"an audio port.");
-
-static PyObject *
-alp_GetFilled(alpobject *self, PyObject *args)
-{
-	int filled;
-
-	if (!PyArg_ParseTuple(args, ":GetFilled"))
-		return NULL;
-	if ((filled = alGetFilled(self->port)) < 0)
-		return NULL;
-	return PyInt_FromLong((long) filled);
-}
-
-
-PyDoc_STRVAR(alp_GetFillable__doc__,
-"alGetFillable: report the number of unfilled sample frames "
-"in an audio port.");
-
-static PyObject *
-alp_GetFillable(alpobject *self, PyObject *args)
-{
-	int fillable;
-
-	if (!PyArg_ParseTuple(args, ":GetFillable"))
-		return NULL;
-	if ((fillable = alGetFillable(self->port)) < 0)
-		return NULL;
-	return PyInt_FromLong((long) fillable);
-}
-
-
-PyDoc_STRVAR(alp_ReadFrames__doc__,
-"alReadFrames: read sample frames from an audio port.");
-
-static PyObject *
-alp_ReadFrames(alpobject *self, PyObject *args)
-{
-	int framecount;
-	PyObject *v;
-	int size;
-	int ch;
-	ALconfig c;
-
-	if (!PyArg_ParseTuple(args, "i:ReadFrames", &framecount))
-		return NULL;
-	if (framecount < 0) {
-		PyErr_SetString(ErrorObject, "negative framecount");
-		return NULL;
-	}
-	c = alGetConfig(self->port);
-	switch (alGetSampFmt(c)) {
-	case AL_SAMPFMT_TWOSCOMP:
-		switch (alGetWidth(c)) {
-		case AL_SAMPLE_8:
-			size = 1;
-			break;
-		case AL_SAMPLE_16:
-			size = 2;
-			break;
-		case AL_SAMPLE_24:
-			size = 4;
-			break;
-		default:
-			PyErr_SetString(ErrorObject, "can't determine width");
-			alFreeConfig(c);
-			return NULL;
-		}
-		break;
-	case AL_SAMPFMT_FLOAT:
-		size = 4;
-		break;
-	case AL_SAMPFMT_DOUBLE:
-		size = 8;
-		break;
-	default:
-		PyErr_SetString(ErrorObject, "can't determine format");
-		alFreeConfig(c);
-		return NULL;
-	}
-	ch = alGetChannels(c);
-	alFreeConfig(c);
-	if (ch < 0) {
-		PyErr_SetString(ErrorObject, "can't determine # of channels");
-		return NULL;
-	}
-	size *= ch;
-	v = PyString_FromStringAndSize((char *) NULL, size * framecount);
-	if (v == NULL)
-		return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	alReadFrames(self->port, (void *) PyString_AS_STRING(v), framecount);
-	Py_END_ALLOW_THREADS
-
-	return v;
-}
-
-
-PyDoc_STRVAR(alp_DiscardFrames__doc__,
-"alDiscardFrames: discard audio from an audio port.");
-
-static PyObject *
-alp_DiscardFrames(alpobject *self, PyObject *args)
-{
-	int framecount;
-
-	if (!PyArg_ParseTuple(args, "i:DiscardFrames", &framecount))
-		return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	framecount = alDiscardFrames(self->port, framecount);
-	Py_END_ALLOW_THREADS
-
-	if (framecount < 0)
-		return NULL;
-
-	return PyInt_FromLong((long) framecount);
-}
-
-
-PyDoc_STRVAR(alp_ZeroFrames__doc__,
-"alZeroFrames: write zero-valued sample frames to an audio port.");
-
-static PyObject *
-alp_ZeroFrames(alpobject *self, PyObject *args)
-{
-	int framecount;
-
-	if (!PyArg_ParseTuple(args, "i:ZeroFrames", &framecount))
-		return NULL;
-
-	if (framecount < 0) {
-		PyErr_SetString(ErrorObject, "negative framecount");
-		return NULL;
-	}
-
-	Py_BEGIN_ALLOW_THREADS
-	alZeroFrames(self->port, framecount);
-	Py_END_ALLOW_THREADS
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-PyDoc_STRVAR(alp_SetFillPoint__doc__,
-"alSetFillPoint: set low- or high-water mark for an audio port.");
-
-static PyObject *
-alp_SetFillPoint(alpobject *self, PyObject *args)
-{
-	int fillpoint;
-
-	if (!PyArg_ParseTuple(args, "i:SetFillPoint", &fillpoint))
-		return NULL;
-
-	if (alSetFillPoint(self->port, fillpoint) < 0)
-		return NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-PyDoc_STRVAR(alp_GetFillPoint__doc__,
-"alGetFillPoint: get low- or high-water mark for an audio port.");
-
-static PyObject *
-alp_GetFillPoint(alpobject *self, PyObject *args)
-{
-	int fillpoint;
-
-	if (!PyArg_ParseTuple(args, ":GetFillPoint"))
-		return NULL;
-
-	if ((fillpoint = alGetFillPoint(self->port)) < 0)
-		return NULL;
-
-	return PyInt_FromLong((long) fillpoint);
-}
-
-
-PyDoc_STRVAR(alp_GetFrameNumber__doc__,
-"alGetFrameNumber: get the absolute sample frame number "
-"associated with a port.");
-
-static PyObject *
-alp_GetFrameNumber(alpobject *self, PyObject *args)
-{
-	stamp_t fnum;
-
-	if (!PyArg_ParseTuple(args, ":GetFrameNumber"))
-		return NULL;
-
-	if (alGetFrameNumber(self->port, &fnum) < 0)
-		return NULL;
-
-	return PyLong_FromLongLong((long long) fnum);
-}
-
-
-PyDoc_STRVAR(alp_GetFrameTime__doc__,
-"alGetFrameTime: get the time at which a sample frame came "
-"in or will go out.");
-
-static PyObject *
-alp_GetFrameTime(alpobject *self, PyObject *args)
-{
-	stamp_t fnum, time;
-	PyObject *ret, *v0, *v1;
-
-	if (!PyArg_ParseTuple(args, ":GetFrameTime"))
-		return NULL;
-	if (alGetFrameTime(self->port, &fnum, &time) < 0)
-		return NULL;
-	v0 = PyLong_FromLongLong((long long) fnum);
-	v1 = PyLong_FromLongLong((long long) time);
-	if (PyErr_Occurred()) {
-		Py_XDECREF(v0);
-		Py_XDECREF(v1);
-		return NULL;
-	}
-	ret = PyTuple_Pack(2, v0, v1);
-	Py_DECREF(v0);
-	Py_DECREF(v1);
-	return ret;
-}
-
-
-PyDoc_STRVAR(alp_WriteFrames__doc__,
-"alWriteFrames: write sample frames to an audio port.");
-
-static PyObject *
-alp_WriteFrames(alpobject *self, PyObject *args)
-{
-	char *samples;
-	int length;
-	int size, ch;
-	ALconfig c;
-
-	if (!PyArg_ParseTuple(args, "s#:WriteFrames", &samples, &length))
-		return NULL;
-	c = alGetConfig(self->port);
-	switch (alGetSampFmt(c)) {
-	case AL_SAMPFMT_TWOSCOMP:
-		switch (alGetWidth(c)) {
-		case AL_SAMPLE_8:
-			size = 1;
-			break;
-		case AL_SAMPLE_16:
-			size = 2;
-			break;
-		case AL_SAMPLE_24:
-			size = 4;
-			break;
-		default:
-			PyErr_SetString(ErrorObject, "can't determine width");
-			alFreeConfig(c);
-			return NULL;
-		}
-		break;
-	case AL_SAMPFMT_FLOAT:
-		size = 4;
-		break;
-	case AL_SAMPFMT_DOUBLE:
-		size = 8;
-		break;
-	default:
-		PyErr_SetString(ErrorObject, "can't determine format");
-		alFreeConfig(c);
-		return NULL;
-	}
-	ch = alGetChannels(c);
-	alFreeConfig(c);
-	if (ch < 0) {
-		PyErr_SetString(ErrorObject, "can't determine # of channels");
-		return NULL;
-	}
-	size *= ch;
-	if (length % size != 0) {
-		PyErr_SetString(ErrorObject,
-				"buffer length not whole number of frames");
-		return NULL;
-	}
-
-	Py_BEGIN_ALLOW_THREADS
-	alWriteFrames(self->port, (void *) samples, length / size);
-	Py_END_ALLOW_THREADS
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-PyDoc_STRVAR(alp_ClosePort__doc__, "alClosePort: close an audio port.");
-
-static PyObject *
-alp_ClosePort(alpobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":ClosePort"))
-		return NULL;
-	if (alClosePort(self->port) < 0)
-		return NULL;
-	self->port = NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-#endif /* AL_NO_ELEM */
-
-#ifdef OLD_INTERFACE
-static PyObject *
-alp_closeport(alpobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":ClosePort"))
-		return NULL;
-	if (ALcloseport(self->port) < 0)
-		return NULL;
-	self->port = NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-alp_getfd(alpobject *self, PyObject *args)
-{
-	int fd;
-
-	if (!PyArg_ParseTuple(args, ":GetFD"))
-		return NULL;
-	if ((fd = ALgetfd(self-> port)) == -1)
-		return NULL;
-	return PyInt_FromLong(fd);
-}
-
-static PyObject *
-alp_getfilled(alpobject *self, PyObject *args)
-{
-	long count;
-
-	if (!PyArg_ParseTuple(args, ":GetFilled"))
-		return NULL;
-	if ((count = ALgetfilled(self-> port)) == -1)
-		return NULL;
-	return PyInt_FromLong(count);
-}
-
-static PyObject *
-alp_getfillable(alpobject *self, PyObject *args)
-{
-	long count;
-
-	if (!PyArg_ParseTuple(args, ":GetFillable"))
-		return NULL;
-	if ((count = ALgetfillable(self-> port)) == -1)
-		return NULL;
-	return PyInt_FromLong (count);
-}
-
-static PyObject *
-alp_readsamps(alpobject *self, PyObject *args)
-{
-	long count;
-	PyObject *v;
-	ALconfig c;
-	int width;
-	int ret;
-
-	if (!PyArg_ParseTuple(args, "l:readsamps", &count))
-		return NULL;
-
-	if (count <= 0) {
-		PyErr_SetString(ErrorObject, "al.readsamps : arg <= 0");
-		return NULL;
-	}
-
-	c = ALgetconfig(self->port);
-#ifdef AL_405
-	width = ALgetsampfmt(c);
-	if (width == AL_SAMPFMT_FLOAT)
-		width = sizeof(float);
-	else if (width == AL_SAMPFMT_DOUBLE)
-		width = sizeof(double);
-	else
-		width = ALgetwidth(c);
-#else
-	width = ALgetwidth(c);
-#endif /* AL_405 */
-	ALfreeconfig(c);
-	v = PyString_FromStringAndSize((char *)NULL, width * count);
-	if (v == NULL)
-		return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	ret = ALreadsamps(self->port, (void *) PyString_AsString(v), count);
-	Py_END_ALLOW_THREADS
-	if (ret == -1) {
-		Py_DECREF(v);
-		return NULL;
-	}
-
-	return (v);
-}
-
-static PyObject *
-alp_writesamps(alpobject *self, PyObject *args)
-{
-	char *buf;
-	int size, width;
-	ALconfig c;
-	int ret;
-
-	if (!PyArg_ParseTuple(args, "s#:writesamps", &buf, &size))
-		return NULL;
-
-	c = ALgetconfig(self->port);
-#ifdef AL_405
-	width = ALgetsampfmt(c);
-	if (width == AL_SAMPFMT_FLOAT)
-		width = sizeof(float);
-	else if (width == AL_SAMPFMT_DOUBLE)
-		width = sizeof(double);
-	else
-		width = ALgetwidth(c);
-#else
-	width = ALgetwidth(c);
-#endif /* AL_405 */
-	ALfreeconfig(c);
-	Py_BEGIN_ALLOW_THREADS
-	ret = ALwritesamps (self->port, (void *) buf, (long) size / width);
-	Py_END_ALLOW_THREADS
-	if (ret == -1)
-		return NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-alp_getfillpoint(alpobject *self, PyObject *args)
-{
-	long count;
-
-	if (!PyArg_ParseTuple(args, ":GetFillPoint"))
-		return NULL;
-	if ((count = ALgetfillpoint(self->port)) == -1)
-		return NULL;
-	return PyInt_FromLong(count);
-}
-
-static PyObject *
-alp_setfillpoint(alpobject *self, PyObject *args)
-{
-	long count;
-
-	if (!PyArg_ParseTuple(args, "l:SetFillPoint", &count))
-		return NULL;
-	if (ALsetfillpoint(self->port, count) == -1)
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-alp_setconfig(alpobject *self, PyObject *args)
-{
-	alcobject *config;
-
-	if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
-		return NULL;
-	if (ALsetconfig(self->port, config->config) == -1)
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-alp_getconfig(alpobject *self, PyObject *args)
-{
-	ALconfig config;
-
-	if (!PyArg_ParseTuple(args, ":GetConfig"))
-		return NULL;
-	config = ALgetconfig(self->port);
-	if (config == NULL)
-		return NULL;
-	return newalcobject(config);
-}
-
-#ifdef AL_405
-static PyObject *
-alp_getstatus(alpobject *self, PyObject *args)
-{
-	PyObject *list, *v;
-	long *PVbuffer;
-	long length;
-	int i;
-	
-	if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list))
-		return NULL;
-	length = PyList_Size(list);
-	PVbuffer = PyMem_NEW(long, length);
-	if (PVbuffer == NULL)
-		return PyErr_NoMemory();
-	for (i = 0; i < length; i++) {
-		v = PyList_GetItem(list, i);
-		if (!PyInt_Check(v)) {
-			PyMem_DEL(PVbuffer);
-			PyErr_BadArgument();
-			return NULL;
-		}
-		PVbuffer[i] = PyInt_AsLong(v);
-	}
-
-	if (ALgetstatus(self->port, PVbuffer, length) == -1)
-		return NULL;
-
-	for (i = 0; i < length; i++)
-		PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
-
-	PyMem_DEL(PVbuffer);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-#endif /* AL_405 */
-
-#endif /* OLD_INTERFACE */
-
-static struct PyMethodDef alp_methods[] = {
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-	{"SetConfig",	(PyCFunction)alp_SetConfig,	METH_VARARGS,	alp_SetConfig__doc__},
-	{"GetConfig",	(PyCFunction)alp_GetConfig,	METH_VARARGS,	alp_GetConfig__doc__},
-	{"GetResource",	(PyCFunction)alp_GetResource,	METH_VARARGS,	alp_GetResource__doc__},
-	{"GetFD",	(PyCFunction)alp_GetFD,	METH_VARARGS,	alp_GetFD__doc__},
-	{"GetFilled",	(PyCFunction)alp_GetFilled,	METH_VARARGS,	alp_GetFilled__doc__},
-	{"GetFillable",	(PyCFunction)alp_GetFillable,	METH_VARARGS,	alp_GetFillable__doc__},
-	{"ReadFrames",	(PyCFunction)alp_ReadFrames,	METH_VARARGS,	alp_ReadFrames__doc__},
-	{"DiscardFrames",	(PyCFunction)alp_DiscardFrames,	METH_VARARGS,	alp_DiscardFrames__doc__},
-	{"ZeroFrames",	(PyCFunction)alp_ZeroFrames,	METH_VARARGS,	alp_ZeroFrames__doc__},
-	{"SetFillPoint",	(PyCFunction)alp_SetFillPoint,	METH_VARARGS,	alp_SetFillPoint__doc__},
-	{"GetFillPoint",	(PyCFunction)alp_GetFillPoint,	METH_VARARGS,	alp_GetFillPoint__doc__},
-	{"GetFrameNumber",	(PyCFunction)alp_GetFrameNumber,	METH_VARARGS,	alp_GetFrameNumber__doc__},
-	{"GetFrameTime",	(PyCFunction)alp_GetFrameTime,	METH_VARARGS,	alp_GetFrameTime__doc__},
-	{"WriteFrames",	(PyCFunction)alp_WriteFrames,	METH_VARARGS,	alp_WriteFrames__doc__},
-	{"ClosePort",	(PyCFunction)alp_ClosePort,	METH_VARARGS,	alp_ClosePort__doc__},
-#endif /* AL_NO_ELEM */
-#ifdef OLD_INTERFACE
-	{"closeport",		(PyCFunction)alp_closeport,	METH_VARARGS},
-	{"getfd",		(PyCFunction)alp_getfd,	METH_VARARGS},
-        {"fileno",		(PyCFunction)alp_getfd,	METH_VARARGS},
-	{"getfilled",		(PyCFunction)alp_getfilled,	METH_VARARGS},
-	{"getfillable",		(PyCFunction)alp_getfillable,	METH_VARARGS},
-	{"readsamps",		(PyCFunction)alp_readsamps,	METH_VARARGS},
-	{"writesamps",		(PyCFunction)alp_writesamps,	METH_VARARGS},
-	{"setfillpoint",	(PyCFunction)alp_setfillpoint,	METH_VARARGS},
-	{"getfillpoint",	(PyCFunction)alp_getfillpoint,	METH_VARARGS},
-	{"setconfig",		(PyCFunction)alp_setconfig,	METH_VARARGS},
-	{"getconfig",		(PyCFunction)alp_getconfig,	METH_VARARGS},
-#ifdef AL_405
-	{"getstatus",		(PyCFunction)alp_getstatus,	METH_VARARGS},
-#endif /* AL_405 */	    
-#endif /* OLD_INTERFACE */
- 
-	{NULL,		NULL}		/* sentinel */
-};
-
-/* ---------- */
-
-
-static PyObject *
-newalpobject(ALport port)
-{
-	alpobject *self;
-	
-	self = PyObject_New(alpobject, &Alptype);
-	if (self == NULL)
-		return NULL;
-	/* XXXX Add your own initializers here */
-	self->port = port;
-	return (PyObject *) self;
-}
-
-
-static void
-alp_dealloc(alpobject *self)
-{
-	/* XXXX Add your own cleanup code here */
-	if (self->port) {
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-		alClosePort(self->port);
-#else
-		ALcloseport(self->port);
-#endif
-	}
-	PyObject_Del(self);
-}
-
-static PyObject *
-alp_getattr(alpobject *self, char *name)
-{
-	/* XXXX Add your own getattr code here */
-	if (self->port == NULL) {
-		PyErr_SetString(ErrorObject, "port already closed");
-		return NULL;
-	}
-	return Py_FindMethod(alp_methods, (PyObject *)self, name);
-}
-
-PyDoc_STRVAR(Alptype__doc__, "");
-
-static PyTypeObject Alptype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,				/*ob_size*/
-	"al.port",			/*tp_name*/
-	sizeof(alpobject),		/*tp_basicsize*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)alp_dealloc,	/*tp_dealloc*/
-	(printfunc)0,		/*tp_print*/
-	(getattrfunc)alp_getattr,	/*tp_getattr*/
-	(setattrfunc)0,	/*tp_setattr*/
-	(cmpfunc)0,		/*tp_compare*/
-	(reprfunc)0,		/*tp_repr*/
-	0,			/*tp_as_number*/
-	0,		/*tp_as_sequence*/
-	0,		/*tp_as_mapping*/
-	(hashfunc)0,		/*tp_hash*/
-	(ternaryfunc)0,		/*tp_call*/
-	(reprfunc)0,		/*tp_str*/
-
-	/* Space for future expansion */
-	0L,0L,0L,0L,
-	Alptype__doc__ /* Documentation string */
-};
-
-/* End of code for port objects */
-/* -------------------------------------------------------- */
-
-
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-
-PyDoc_STRVAR(al_NewConfig__doc__,
-"alNewConfig: create and initialize an audio ALconfig structure.");
-
-static PyObject *
-al_NewConfig(PyObject *self, PyObject *args)
-{
-	ALconfig config;
-
-	if (!PyArg_ParseTuple(args, ":NewConfig"))
-		return NULL;
-	if ((config = alNewConfig()) == NULL)
-		return NULL;
-	return newalcobject(config);
-}
-
-PyDoc_STRVAR(al_OpenPort__doc__,
-"alOpenPort: open an audio port.");
-
-static PyObject *
-al_OpenPort(PyObject *self, PyObject *args)
-{
-	ALport port;
-	char *name, *dir;
-	alcobject *config = NULL;
-
-	if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
-		return NULL;
-	if ((port = alOpenPort(name, dir, config ? config->config : NULL)) == NULL)
-		return NULL;
-	return newalpobject(port);
-}
-
-PyDoc_STRVAR(al_Connect__doc__,
-"alConnect: connect two audio I/O resources.");
-
-static PyObject *
-al_Connect(PyObject *self, PyObject *args)
-{
-	int source, dest, nprops = 0, id, i;
-	ALpv *props = NULL;
-	ALparamInfo *propinfo = NULL;
-	PyObject *propobj = NULL;
-
-	if (!PyArg_ParseTuple(args, "ii|O!:Connect", &source, &dest, &PyList_Type, &propobj))
-		return NULL;
-	if (propobj != NULL) {
-		nprops = python2params(source, dest, propobj, &props, &propinfo);
-		if (nprops < 0)
-			return NULL;
-	}
-
-	id = alConnect(source, dest, props, nprops);
-
-	if (props) {
-		for (i = 0; i < nprops; i++) {
-			switch (propinfo[i].valueType) {
-			case AL_SET_VAL:
-			case AL_VECTOR_VAL:
-				PyMem_DEL(props[i].value.ptr);
-				break;
-			}
-		}
-		PyMem_DEL(props);
-		PyMem_DEL(propinfo);
-	}
-
-	if (id < 0)
-		return NULL;
-	return PyInt_FromLong((long) id);
-}
-
-PyDoc_STRVAR(al_Disconnect__doc__,
-"alDisconnect: delete a connection between two audio I/O resources.");
-
-static PyObject *
-al_Disconnect(PyObject *self, PyObject *args)
-{
-	int res;
-
-	if (!PyArg_ParseTuple(args, "i:Disconnect", &res))
-		return NULL;
-	if (alDisconnect(res) < 0)
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-PyDoc_STRVAR(al_GetParams__doc__,
-"alGetParams: get the values of audio resource parameters.");
-
-static PyObject *
-al_GetParams(PyObject *self, PyObject *args)
-{
-	int resource;
-	PyObject *pvslist, *item = NULL, *v = NULL;
-	ALpv *pvs;
-	int i, j, npvs;
-	ALparamInfo *pinfo;
-
-	if (!PyArg_ParseTuple(args, "iO!:GetParams", &resource, &PyList_Type, &pvslist))
-		return NULL;
-	npvs = PyList_Size(pvslist);
-	pvs = PyMem_NEW(ALpv, npvs);
-	pinfo = PyMem_NEW(ALparamInfo, npvs);
-	for (i = 0; i < npvs; i++) {
-		item = PyList_GetItem(pvslist, i);
-		if (!PyInt_Check(item)) {
-			item = NULL;
-			PyErr_SetString(ErrorObject, "list of integers expected");
-			goto error;
-		}
-		pvs[i].param = (int) PyInt_AsLong(item);
-		item = NULL;	/* not needed anymore */
-		if (alGetParamInfo(resource, pvs[i].param, &pinfo[i]) < 0)
-			goto error;
-		switch (pinfo[i].valueType) {
-		case AL_NO_VAL:
-			break;
-		case AL_MATRIX_VAL:
-			pinfo[i].maxElems *= pinfo[i].maxElems2;
-			/* fall through */
-		case AL_STRING_VAL:
-		case AL_SET_VAL:
-		case AL_VECTOR_VAL:
-			switch (pinfo[i].elementType) {
-			case AL_INT32_ELEM:
-			case AL_RESOURCE_ELEM:
-			case AL_ENUM_ELEM:
-				pvs[i].value.ptr = PyMem_NEW(int, pinfo[i].maxElems);
-				pvs[i].sizeIn = pinfo[i].maxElems;
-				break;
-			case AL_INT64_ELEM:
-			case AL_FIXED_ELEM:
-				pvs[i].value.ptr = PyMem_NEW(long long, pinfo[i].maxElems);
-				pvs[i].sizeIn = pinfo[i].maxElems;
-				break;
-			case AL_CHAR_ELEM:
-				pvs[i].value.ptr = PyMem_NEW(char, 32);
-				pvs[i].sizeIn = 32;
-				break;
-			case AL_NO_ELEM:
-			case AL_PTR_ELEM:
-			default:
-				PyErr_SetString(ErrorObject, "internal error");
-				goto error;
-			}
-			break;
-		case AL_SCALAR_VAL:
-			break;
-		default:
-			PyErr_SetString(ErrorObject, "internal error");
-			goto error;
-		}
-		if (pinfo[i].valueType == AL_MATRIX_VAL) {
-			pinfo[i].maxElems /= pinfo[i].maxElems2;
-			pvs[i].sizeIn /= pinfo[i].maxElems2;
-			pvs[i].size2In = pinfo[i].maxElems2;
-		}
-	}
-	if (alGetParams(resource, pvs, npvs) < 0)
-		goto error;
-	if (!(v = PyList_New(npvs)))
-		goto error;
-	for (i = 0; i < npvs; i++) {
-		if (pvs[i].sizeOut < 0) {
-			char buf[32];
-			PyOS_snprintf(buf, sizeof(buf),
-				      "problem with param %d", i);
-			PyErr_SetString(ErrorObject, buf);
-			goto error;
-		}
-		switch (pinfo[i].valueType) {
-		case AL_NO_VAL:
-			item = Py_None;
-			Py_INCREF(item);
-			break;
-		case AL_STRING_VAL:
-			item = PyString_FromString(pvs[i].value.ptr);
-			PyMem_DEL(pvs[i].value.ptr);
-			break;
-		case AL_MATRIX_VAL:
-			/* XXXX this is not right */
-			pvs[i].sizeOut *= pvs[i].size2Out;
-			/* fall through */
-		case AL_SET_VAL:
-		case AL_VECTOR_VAL:
-			item = PyList_New(pvs[i].sizeOut);
-			for (j = 0; j < pvs[i].sizeOut; j++) {
-				switch (pinfo[i].elementType) {
-				case AL_INT32_ELEM:
-				case AL_RESOURCE_ELEM:
-				case AL_ENUM_ELEM:
-					PyList_SetItem(item, j, PyInt_FromLong((long) ((int *) pvs[i].value.ptr)[j]));
-					break;
-				case AL_INT64_ELEM:
-					PyList_SetItem(item, j, PyLong_FromLongLong(((long long *) pvs[i].value.ptr)[j]));
-					break;
-				case AL_FIXED_ELEM:
-					PyList_SetItem(item, j, PyFloat_FromDouble(alFixedToDouble(((long long *) pvs[i].value.ptr)[j])));
-					break;
-				default:
-					PyErr_SetString(ErrorObject, "internal error");
-					goto error;
-				}
-			}
-			PyMem_DEL(pvs[i].value.ptr);
-			break;
-		case AL_SCALAR_VAL:
-			item = param2python(resource, pvs[i].param, pvs[i].value, &pinfo[i]);
-			break;
-		}
-		if (PyErr_Occurred() ||
-		    PyList_SetItem(v, i, Py_BuildValue("(iO)", pvs[i].param,
-						       item)) < 0 ||
-		    PyErr_Occurred())
-			goto error;
-		Py_DECREF(item);
-	}
-	PyMem_DEL(pvs);
-	PyMem_DEL(pinfo);
-	return v;
-
-  error:
-	Py_XDECREF(v);
-	Py_XDECREF(item);
-	if (pvs)
-		PyMem_DEL(pvs);
-	if (pinfo)
-		PyMem_DEL(pinfo);
-	return NULL;
-}
-
-PyDoc_STRVAR(al_SetParams__doc__,
-"alSetParams: set the values of audio resource parameters.");
-
-static PyObject *
-al_SetParams(PyObject *self, PyObject *args)
-{
-	int resource;
-	PyObject *pvslist;
-	ALpv *pvs;
-	ALparamInfo *pinfo;
-	int npvs, i;
-
-	if (!PyArg_ParseTuple(args, "iO!:SetParams", &resource, &PyList_Type, &pvslist))
-		return NULL;
-	npvs = python2params(resource, -1, pvslist, &pvs, &pinfo);
-	if (npvs < 0)
-		return NULL;
-
-	if (alSetParams(resource, pvs, npvs) < 0)
-		goto error;
-
-	/* cleanup */
-	for (i = 0; i < npvs; i++) {
-		switch (pinfo[i].valueType) {
-		case AL_SET_VAL:
-		case AL_VECTOR_VAL:
-			PyMem_DEL(pvs[i].value.ptr);
-			break;
-		}
-	}
-	PyMem_DEL(pvs);
-	PyMem_DEL(pinfo);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-
-  error:
-	/* XXXX we should clean up everything */
-	if (pvs)
-		PyMem_DEL(pvs);
-	if (pinfo)
-		PyMem_DEL(pinfo);
-	return NULL;
-}
-
-PyDoc_STRVAR(al_QueryValues__doc__,
-"alQueryValues: get the set of possible values for a parameter.");
-
-static PyObject *
-al_QueryValues(PyObject *self, PyObject *args)
-{
-	int resource, param;
-	ALvalue *return_set = NULL;
-	int setsize = 32, qualsize = 0, nvals, i;
-	ALpv *quals = NULL;
-	ALparamInfo pinfo;
-	ALparamInfo *qualinfo = NULL;
-	PyObject *qualobj = NULL;
-	PyObject *res = NULL, *item;
-
-	if (!PyArg_ParseTuple(args, "ii|O!:QueryValues", &resource, &param,
-			      &PyList_Type, &qualobj))
-		return NULL;
-	if (qualobj != NULL) {
-		qualsize = python2params(resource, param, qualobj, &quals, &qualinfo);
-		if (qualsize < 0)
-			return NULL;
-	}
-	setsize = 32;
-	return_set = PyMem_NEW(ALvalue, setsize);
-	if (return_set == NULL) {
-		PyErr_NoMemory();
-		goto cleanup;
-	}
-
-  retry:
-	nvals = alQueryValues(resource, param, return_set, setsize, quals, qualsize);
-	if (nvals < 0)
-		goto cleanup;
-	if (nvals > setsize) {
-		setsize = nvals;
-		PyMem_RESIZE(return_set, ALvalue, setsize);
-		if (return_set == NULL) {
-			PyErr_NoMemory();
-			goto cleanup;
-		}
-		goto retry;
-	}
-
-	if (alGetParamInfo(resource, param, &pinfo) < 0)
-		goto cleanup;
-
-	res = PyList_New(nvals);
-	if (res == NULL)
-		goto cleanup;
-	for (i = 0; i < nvals; i++) {
-		item = param2python(resource, param, return_set[i], &pinfo);
-		if (item == NULL ||
-		    PyList_SetItem(res, i, item) < 0) {
-			Py_DECREF(res);
-			res = NULL;
-			goto cleanup;
-		}
-	}
-
-  cleanup:
-	if (return_set)
-		PyMem_DEL(return_set);
-	if (quals) {
-		for (i = 0; i < qualsize; i++) {
-			switch (qualinfo[i].valueType) {
-			case AL_SET_VAL:
-			case AL_VECTOR_VAL:
-				PyMem_DEL(quals[i].value.ptr);
-				break;
-			}
-		}
-		PyMem_DEL(quals);
-		PyMem_DEL(qualinfo);
-	}
-
-	return res;
-}
-
-PyDoc_STRVAR(al_GetParamInfo__doc__,
-"alGetParamInfo: get information about a parameter on "
-"a particular audio resource.");
-
-static PyObject *
-al_GetParamInfo(PyObject *self, PyObject *args)
-{
-	int res, param;
-	ALparamInfo pinfo;
-	PyObject *v, *item;
-
-	if (!PyArg_ParseTuple(args, "ii:GetParamInfo", &res, &param))
-		return NULL;
-	if (alGetParamInfo(res, param, &pinfo) < 0)
-		return NULL;
-	v = PyDict_New();
-	if (!v) return NULL;
-
-	item = PyInt_FromLong((long) pinfo.resource);
-	PyDict_SetItemString(v, "resource", item);
-	Py_DECREF(item);
-
-	item = PyInt_FromLong((long) pinfo.param);
-	PyDict_SetItemString(v, "param", item);
-	Py_DECREF(item);
-
-	item = PyInt_FromLong((long) pinfo.valueType);
-	PyDict_SetItemString(v, "valueType", item);
-	Py_DECREF(item);
-
-	if (pinfo.valueType != AL_NO_VAL && pinfo.valueType != AL_SCALAR_VAL) {
-		/* multiple values */
-		item = PyInt_FromLong((long) pinfo.maxElems);
-		PyDict_SetItemString(v, "maxElems", item);
-		Py_DECREF(item);
-
-		if (pinfo.valueType == AL_MATRIX_VAL) {
-			/* 2 dimensional */
-			item = PyInt_FromLong((long) pinfo.maxElems2);
-			PyDict_SetItemString(v, "maxElems2", item);
-			Py_DECREF(item);
-		}
-	}
-
-	item = PyInt_FromLong((long) pinfo.elementType);
-	PyDict_SetItemString(v, "elementType", item);
-	Py_DECREF(item);
-
-	item = PyString_FromString(pinfo.name);
-	PyDict_SetItemString(v, "name", item);
-	Py_DECREF(item);
-
-	item = param2python(res, param, pinfo.initial, &pinfo);
-	PyDict_SetItemString(v, "initial", item);
-	Py_DECREF(item);
-
-	if (pinfo.elementType != AL_ENUM_ELEM &&
-	    pinfo.elementType != AL_RESOURCE_ELEM &&
-	    pinfo.elementType != AL_CHAR_ELEM) {
-		/* range param */
-		item = param2python(res, param, pinfo.min, &pinfo);
-		PyDict_SetItemString(v, "min", item);
-		Py_DECREF(item);
-
-		item = param2python(res, param, pinfo.max, &pinfo);
-		PyDict_SetItemString(v, "max", item);
-		Py_DECREF(item);
-
-		item = param2python(res, param, pinfo.minDelta, &pinfo);
-		PyDict_SetItemString(v, "minDelta", item);
-		Py_DECREF(item);
-
-		item = param2python(res, param, pinfo.maxDelta, &pinfo);
-		PyDict_SetItemString(v, "maxDelta", item);
-		Py_DECREF(item);
-
-		item = PyInt_FromLong((long) pinfo.specialVals);
-		PyDict_SetItemString(v, "specialVals", item);
-		Py_DECREF(item);
-	}
-
-	return v;
-}
-
-PyDoc_STRVAR(al_GetResourceByName__doc__,
-"alGetResourceByName: find an audio resource by name.");
-
-static PyObject *
-al_GetResourceByName(PyObject *self, PyObject *args)
-{
-	int res, start_res, type;
-	char *name;
-
-	if (!PyArg_ParseTuple(args, "isi:GetResourceByName", &start_res, &name, &type))
-		return NULL;
-	if ((res = alGetResourceByName(start_res, name, type)) == 0)
-		return NULL;
-	return PyInt_FromLong((long) res);
-}
-
-PyDoc_STRVAR(al_IsSubtype__doc__,
-"alIsSubtype: indicate if one resource type is a subtype of another.");
-
-static PyObject *
-al_IsSubtype(PyObject *self, PyObject *args)
-{
-	int type, subtype;
-
-	if (!PyArg_ParseTuple(args, "ii:IsSubtype", &type, &subtype))
-		return NULL;
-	return PyInt_FromLong((long) alIsSubtype(type, subtype));
-}
-
-PyDoc_STRVAR(al_SetErrorHandler__doc__, "");
-
-static PyObject *
-al_SetErrorHandler(PyObject *self, PyObject *args)
-{
-
-	if (!PyArg_ParseTuple(args, ":SetErrorHandler"))
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-#endif /* AL_NO_ELEM */
-
-#ifdef OLD_INTERFACE
-
-static PyObject *
-al_openport(PyObject *self, PyObject *args)
-{
-	char *name, *dir;
-	ALport port;
-	alcobject *config = NULL;
-
-	if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
-		return NULL;
-	if ((port = ALopenport(name, dir, config ? config->config : NULL)) == NULL)
-		return NULL;
-	return newalpobject(port);
-}
-
-static PyObject *
-al_newconfig(PyObject *self, PyObject *args)
-{
-	ALconfig config;
-
-	if (!PyArg_ParseTuple(args, ":NewConfig"))
-		return NULL;
-	if ((config = ALnewconfig ()) == NULL)
-		return NULL;
-	return newalcobject(config);
-}
-
-static PyObject *
-al_queryparams(PyObject *self, PyObject *args)
-{
-	long device;
-	long length;
-	long *PVbuffer;
-	long PVdummy[2];
-	PyObject *v = NULL;
-	int i;
-
-	if (!PyArg_ParseTuple(args, "l:queryparams", &device))
-		return NULL;
-	if ((length = ALqueryparams(device, PVdummy, 2L)) == -1)
-		return NULL;
-	if ((PVbuffer = PyMem_NEW(long, length)) == NULL)
-		return PyErr_NoMemory();
-	if (ALqueryparams(device, PVbuffer, length) >= 0 &&
-	    (v = PyList_New((int)length)) != NULL) {
-		for (i = 0; i < length; i++)
-			PyList_SetItem(v, i, PyInt_FromLong(PVbuffer[i]));
-	}
-	PyMem_DEL(PVbuffer);
-	return v;
-}
-
-static PyObject *
-doParams(PyObject *args, int (*func)(long, long *, long), int modified)
-{
-	long device;
-	PyObject *list, *v;
-	long *PVbuffer;
-	long length;
-	int i;
-	
-	if (!PyArg_ParseTuple(args, "lO!", &device, &PyList_Type, &list))
-		return NULL;
-	length = PyList_Size(list);
-	PVbuffer = PyMem_NEW(long, length);
-	if (PVbuffer == NULL)
-		return PyErr_NoMemory();
-	for (i = 0; i < length; i++) {
-		v = PyList_GetItem(list, i);
-		if (!PyInt_Check(v)) {
-			PyMem_DEL(PVbuffer);
-			PyErr_BadArgument();
-			return NULL;
-		}
-		PVbuffer[i] = PyInt_AsLong(v);
-	}
-
-	if ((*func)(device, PVbuffer, length) == -1) {
-		PyMem_DEL(PVbuffer);
-		return NULL;
-	}
-
-	if (modified) {
-		for (i = 0; i < length; i++)
-			PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
-	}
-
-	PyMem_DEL(PVbuffer);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-al_getparams(PyObject *self, PyObject *args)
-{
-	return doParams(args, ALgetparams, 1);
-}
-
-static PyObject *
-al_setparams(PyObject *self, PyObject *args)
-{
-	return doParams(args, ALsetparams, 0);
-}
-
-static PyObject *
-al_getname(PyObject *self, PyObject *args)
-{
-	long device, descriptor;
-	char *name;
-
-	if (!PyArg_ParseTuple(args, "ll:getname", &device, &descriptor))
-		return NULL;
-	if ((name = ALgetname(device, descriptor)) == NULL)
-		return NULL;
-	return PyString_FromString(name);
-}
-
-static PyObject *
-al_getdefault(PyObject *self, PyObject *args)
-{
-	long device, descriptor, value;
-
-	if (!PyArg_ParseTuple(args, "ll:getdefault", &device, &descriptor))
-		return NULL;
-	if ((value = ALgetdefault(device, descriptor)) == -1)
-		return NULL;
-	return PyLong_FromLong(value);
-}
-
-static PyObject *
-al_getminmax(PyObject *self, PyObject *args)
-{
-	long device, descriptor, min, max;
-
-	if (!PyArg_ParseTuple(args, "ll:getminmax", &device, &descriptor))
-		return NULL;
-	min = -1;
-	max = -1;
-	if (ALgetminmax(device, descriptor, &min, &max) == -1)
-		return NULL;
-	return Py_BuildValue("ll", min, max);
-}
-
-#endif /* OLD_INTERFACE */
-
-/* List of methods defined in the module */
-
-static struct PyMethodDef al_methods[] = {
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-	{"NewConfig",	(PyCFunction)al_NewConfig,	METH_VARARGS,	al_NewConfig__doc__},
-	{"OpenPort",	(PyCFunction)al_OpenPort,	METH_VARARGS,	al_OpenPort__doc__},
-	{"Connect",	(PyCFunction)al_Connect,	METH_VARARGS,	al_Connect__doc__},
-	{"Disconnect",	(PyCFunction)al_Disconnect,	METH_VARARGS,	al_Disconnect__doc__},
-	{"GetParams",	(PyCFunction)al_GetParams,	METH_VARARGS,	al_GetParams__doc__},
-	{"SetParams",	(PyCFunction)al_SetParams,	METH_VARARGS,	al_SetParams__doc__},
-	{"QueryValues",	(PyCFunction)al_QueryValues,	METH_VARARGS,	al_QueryValues__doc__},
-	{"GetParamInfo",	(PyCFunction)al_GetParamInfo,	METH_VARARGS,	al_GetParamInfo__doc__},
-	{"GetResourceByName",	(PyCFunction)al_GetResourceByName,	METH_VARARGS,	al_GetResourceByName__doc__},
-	{"IsSubtype",	(PyCFunction)al_IsSubtype,	METH_VARARGS,	al_IsSubtype__doc__},
-#if 0
-	/* this one not supported */
-	{"SetErrorHandler",	(PyCFunction)al_SetErrorHandler,	METH_VARARGS,	al_SetErrorHandler__doc__},
-#endif
-#endif /* AL_NO_ELEM */
-#ifdef OLD_INTERFACE
-	{"openport",		(PyCFunction)al_openport,	METH_VARARGS},
-	{"newconfig",		(PyCFunction)al_newconfig,	METH_VARARGS},
-	{"queryparams",		(PyCFunction)al_queryparams,	METH_VARARGS},
-	{"getparams",		(PyCFunction)al_getparams,	METH_VARARGS},
-	{"setparams",		(PyCFunction)al_setparams,	METH_VARARGS},
-	{"getname",		(PyCFunction)al_getname,	METH_VARARGS},
-	{"getdefault",		(PyCFunction)al_getdefault,	METH_VARARGS},
-	{"getminmax",		(PyCFunction)al_getminmax,	METH_VARARGS},
-#endif /* OLD_INTERFACE */
-
-	{NULL,	 (PyCFunction)NULL, 0, NULL}		/* sentinel */
-};
-
-
-/* Initialization function for the module (*must* be called inital) */
-
-PyDoc_STRVAR(al_module_documentation, "");
-
-void
-inital(void)
-{
-	PyObject *m, *d, *x;
-
-	/* Create the module and add the functions */
-	m = Py_InitModule4("al", al_methods,
-		al_module_documentation,
-		(PyObject*)NULL,PYTHON_API_VERSION);
-	if (m == NULL)
-		return;
-
-	/* Add some symbolic constants to the module */
-	d = PyModule_GetDict(m);
-	ErrorObject = PyErr_NewException("al.error", NULL, NULL);
-	PyDict_SetItemString(d, "error", ErrorObject);
-
-	/* XXXX Add constants here */
-#ifdef AL_4CHANNEL
-	x =  PyInt_FromLong((long) AL_4CHANNEL);
-	if (x == NULL || PyDict_SetItemString(d, "FOURCHANNEL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ADAT_IF_TYPE
-	x =  PyInt_FromLong((long) AL_ADAT_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "ADAT_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ADAT_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_ADAT_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "ADAT_MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_AES_IF_TYPE
-	x =  PyInt_FromLong((long) AL_AES_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "AES_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_AES_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_AES_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "AES_MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ANALOG_IF_TYPE
-	x =  PyInt_FromLong((long) AL_ANALOG_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "ANALOG_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ASSOCIATE
-	x =  PyInt_FromLong((long) AL_ASSOCIATE);
-	if (x == NULL || PyDict_SetItemString(d, "ASSOCIATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_BUFFER_NULL
-	x =  PyInt_FromLong((long) AL_BAD_BUFFER_NULL);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_NULL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_BUFFERLENGTH
-	x =  PyInt_FromLong((long) AL_BAD_BUFFERLENGTH);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_BUFFERLENGTH_NEG
-	x =  PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_NEG);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_BUFFERLENGTH_ODD
-	x =  PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_ODD);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_CHANNELS
-	x =  PyInt_FromLong((long) AL_BAD_CHANNELS);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_CHANNELS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_CONFIG
-	x =  PyInt_FromLong((long) AL_BAD_CONFIG);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_CONFIG", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_COUNT_NEG
-	x =  PyInt_FromLong((long) AL_BAD_COUNT_NEG);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_COUNT_NEG", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_DEVICE
-	x =  PyInt_FromLong((long) AL_BAD_DEVICE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_DEVICE_ACCESS
-	x =  PyInt_FromLong((long) AL_BAD_DEVICE_ACCESS);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE_ACCESS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_DIRECTION
-	x =  PyInt_FromLong((long) AL_BAD_DIRECTION);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_DIRECTION", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_FILLPOINT
-	x =  PyInt_FromLong((long) AL_BAD_FILLPOINT);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_FILLPOINT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_FLOATMAX
-	x =  PyInt_FromLong((long) AL_BAD_FLOATMAX);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_FLOATMAX", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_ILLEGAL_STATE
-	x =  PyInt_FromLong((long) AL_BAD_ILLEGAL_STATE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_ILLEGAL_STATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_NO_PORTS
-	x =  PyInt_FromLong((long) AL_BAD_NO_PORTS);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_NO_PORTS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_NOT_FOUND
-	x =  PyInt_FromLong((long) AL_BAD_NOT_FOUND);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_FOUND", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_NOT_IMPLEMENTED
-	x =  PyInt_FromLong((long) AL_BAD_NOT_IMPLEMENTED);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_IMPLEMENTED", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_OUT_OF_MEM
-	x =  PyInt_FromLong((long) AL_BAD_OUT_OF_MEM);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_OUT_OF_MEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_PARAM
-	x =  PyInt_FromLong((long) AL_BAD_PARAM);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_PERMISSIONS
-	x =  PyInt_FromLong((long) AL_BAD_PERMISSIONS);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PERMISSIONS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_PORT
-	x =  PyInt_FromLong((long) AL_BAD_PORT);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PORT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_PORTSTYLE
-	x =  PyInt_FromLong((long) AL_BAD_PORTSTYLE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PORTSTYLE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_PVBUFFER
-	x =  PyInt_FromLong((long) AL_BAD_PVBUFFER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_QSIZE
-	x =  PyInt_FromLong((long) AL_BAD_QSIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_QSIZE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_RATE
-	x =  PyInt_FromLong((long) AL_BAD_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_RATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_RESOURCE
-	x =  PyInt_FromLong((long) AL_BAD_RESOURCE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_RESOURCE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_SAMPFMT
-	x =  PyInt_FromLong((long) AL_BAD_SAMPFMT);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_SAMPFMT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_TRANSFER_SIZE
-	x =  PyInt_FromLong((long) AL_BAD_TRANSFER_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_TRANSFER_SIZE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_BAD_WIDTH
-	x =  PyInt_FromLong((long) AL_BAD_WIDTH);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_WIDTH", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CHANNEL_MODE
-	x =  PyInt_FromLong((long) AL_CHANNEL_MODE);
-	if (x == NULL || PyDict_SetItemString(d, "CHANNEL_MODE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CHANNELS
-	x =  PyInt_FromLong((long) AL_CHANNELS);
-	if (x == NULL || PyDict_SetItemString(d, "CHANNELS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CHAR_ELEM
-	x =  PyInt_FromLong((long) AL_CHAR_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "CHAR_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CLOCK_GEN
-	x =  PyInt_FromLong((long) AL_CLOCK_GEN);
-	if (x == NULL || PyDict_SetItemString(d, "CLOCK_GEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CLOCKGEN_TYPE
-	x =  PyInt_FromLong((long) AL_CLOCKGEN_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "CLOCKGEN_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CONNECT
-	x =  PyInt_FromLong((long) AL_CONNECT);
-	if (x == NULL || PyDict_SetItemString(d, "CONNECT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CONNECTION_TYPE
-	x =  PyInt_FromLong((long) AL_CONNECTION_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "CONNECTION_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CONNECTIONS
-	x =  PyInt_FromLong((long) AL_CONNECTIONS);
-	if (x == NULL || PyDict_SetItemString(d, "CONNECTIONS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_CRYSTAL_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_CRYSTAL_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "CRYSTAL_MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DEFAULT_DEVICE
-	x =  PyInt_FromLong((long) AL_DEFAULT_DEVICE);
-	if (x == NULL || PyDict_SetItemString(d, "DEFAULT_DEVICE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DEFAULT_INPUT
-	x =  PyInt_FromLong((long) AL_DEFAULT_INPUT);
-	if (x == NULL || PyDict_SetItemString(d, "DEFAULT_INPUT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DEFAULT_OUTPUT
-	x =  PyInt_FromLong((long) AL_DEFAULT_OUTPUT);
-	if (x == NULL || PyDict_SetItemString(d, "DEFAULT_OUTPUT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DEST
-	x =  PyInt_FromLong((long) AL_DEST);
-	if (x == NULL || PyDict_SetItemString(d, "DEST", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DEVICE_TYPE
-	x =  PyInt_FromLong((long) AL_DEVICE_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "DEVICE_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DEVICES
-	x =  PyInt_FromLong((long) AL_DEVICES);
-	if (x == NULL || PyDict_SetItemString(d, "DEVICES", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DIGITAL_IF_TYPE
-	x =  PyInt_FromLong((long) AL_DIGITAL_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "DIGITAL_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DIGITAL_INPUT_RATE
-	x =  PyInt_FromLong((long) AL_DIGITAL_INPUT_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "DIGITAL_INPUT_RATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_DISCONNECT
-	x =  PyInt_FromLong((long) AL_DISCONNECT);
-	if (x == NULL || PyDict_SetItemString(d, "DISCONNECT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ENUM_ELEM
-	x =  PyInt_FromLong((long) AL_ENUM_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "ENUM_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ENUM_VALUE
-	x =  PyInt_FromLong((long) AL_ENUM_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_INPUT_OVERFLOW
-	x =  PyInt_FromLong((long) AL_ERROR_INPUT_OVERFLOW);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_INPUT_OVERFLOW", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_LENGTH
-	x =  PyInt_FromLong((long) AL_ERROR_LENGTH);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_LENGTH", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_LOCATION_LSP
-	x =  PyInt_FromLong((long) AL_ERROR_LOCATION_LSP);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_LSP", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_LOCATION_MSP
-	x =  PyInt_FromLong((long) AL_ERROR_LOCATION_MSP);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_MSP", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_NUMBER
-	x =  PyInt_FromLong((long) AL_ERROR_NUMBER);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_NUMBER", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_OUTPUT_UNDERFLOW
-	x =  PyInt_FromLong((long) AL_ERROR_OUTPUT_UNDERFLOW);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_OUTPUT_UNDERFLOW", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_ERROR_TYPE
-	x =  PyInt_FromLong((long) AL_ERROR_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "ERROR_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_FIXED_ELEM
-	x =  PyInt_FromLong((long) AL_FIXED_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "FIXED_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_FIXED_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_FIXED_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "FIXED_MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_GAIN
-	x =  PyInt_FromLong((long) AL_GAIN);
-	if (x == NULL || PyDict_SetItemString(d, "GAIN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_GAIN_REF
-	x =  PyInt_FromLong((long) AL_GAIN_REF);
-	if (x == NULL || PyDict_SetItemString(d, "GAIN_REF", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_HRB_TYPE
-	x =  PyInt_FromLong((long) AL_HRB_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "HRB_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_COUNT
-	x =  PyInt_FromLong((long) AL_INPUT_COUNT);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_COUNT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_DEVICE_TYPE
-	x =  PyInt_FromLong((long) AL_INPUT_DEVICE_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_DEVICE_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_DIGITAL
-	x =  PyInt_FromLong((long) AL_INPUT_DIGITAL);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_DIGITAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_HRB_TYPE
-	x =  PyInt_FromLong((long) AL_INPUT_HRB_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_HRB_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_LINE
-	x =  PyInt_FromLong((long) AL_INPUT_LINE);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_LINE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_MIC
-	x =  PyInt_FromLong((long) AL_INPUT_MIC);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_MIC", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_PORT_TYPE
-	x =  PyInt_FromLong((long) AL_INPUT_PORT_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_PORT_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_RATE
-	x =  PyInt_FromLong((long) AL_INPUT_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_RATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INPUT_SOURCE
-	x =  PyInt_FromLong((long) AL_INPUT_SOURCE);
-	if (x == NULL || PyDict_SetItemString(d, "INPUT_SOURCE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INT32_ELEM
-	x =  PyInt_FromLong((long) AL_INT32_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "INT32_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INT64_ELEM
-	x =  PyInt_FromLong((long) AL_INT64_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "INT64_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INTERFACE
-	x =  PyInt_FromLong((long) AL_INTERFACE);
-	if (x == NULL || PyDict_SetItemString(d, "INTERFACE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INTERFACE_TYPE
-	x =  PyInt_FromLong((long) AL_INTERFACE_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "INTERFACE_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INVALID_PARAM
-	x =  PyInt_FromLong((long) AL_INVALID_PARAM);
-	if (x == NULL || PyDict_SetItemString(d, "INVALID_PARAM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_INVALID_VALUE
-	x =  PyInt_FromLong((long) AL_INVALID_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "INVALID_VALUE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_JITTER
-	x =  PyInt_FromLong((long) AL_JITTER);
-	if (x == NULL || PyDict_SetItemString(d, "JITTER", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LABEL
-	x =  PyInt_FromLong((long) AL_LABEL);
-	if (x == NULL || PyDict_SetItemString(d, "LABEL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LEFT_INPUT_ATTEN
-	x =  PyInt_FromLong((long) AL_LEFT_INPUT_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "LEFT_INPUT_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LEFT_MONITOR_ATTEN
-	x =  PyInt_FromLong((long) AL_LEFT_MONITOR_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "LEFT_MONITOR_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LEFT_SPEAKER_GAIN
-	x =  PyInt_FromLong((long) AL_LEFT_SPEAKER_GAIN);
-	if (x == NULL || PyDict_SetItemString(d, "LEFT_SPEAKER_GAIN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LEFT1_INPUT_ATTEN
-	x =  PyInt_FromLong((long) AL_LEFT1_INPUT_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "LEFT1_INPUT_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LEFT2_INPUT_ATTEN
-	x =  PyInt_FromLong((long) AL_LEFT2_INPUT_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "LEFT2_INPUT_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LINE_IF_TYPE
-	x =  PyInt_FromLong((long) AL_LINE_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "LINE_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_LOCKED
-	x =  PyInt_FromLong((long) AL_LOCKED);
-	if (x == NULL || PyDict_SetItemString(d, "LOCKED", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MASTER_CLOCK
-	x =  PyInt_FromLong((long) AL_MASTER_CLOCK);
-	if (x == NULL || PyDict_SetItemString(d, "MASTER_CLOCK", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MATRIX_VAL
-	x =  PyInt_FromLong((long) AL_MATRIX_VAL);
-	if (x == NULL || PyDict_SetItemString(d, "MATRIX_VAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_ERROR
-	x =  PyInt_FromLong((long) AL_MAX_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_ERROR", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_EVENT_PARAM
-	x =  PyInt_FromLong((long) AL_MAX_EVENT_PARAM);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_EVENT_PARAM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_PBUFSIZE
-	x =  PyInt_FromLong((long) AL_MAX_PBUFSIZE);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_PBUFSIZE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_PORTS
-	x =  PyInt_FromLong((long) AL_MAX_PORTS);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_PORTS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_RESOURCE_ID
-	x =  PyInt_FromLong((long) AL_MAX_RESOURCE_ID);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_RESOURCE_ID", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_SETSIZE
-	x =  PyInt_FromLong((long) AL_MAX_SETSIZE);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_SETSIZE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MAX_STRLEN
-	x =  PyInt_FromLong((long) AL_MAX_STRLEN);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_STRLEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MIC_IF_TYPE
-	x =  PyInt_FromLong((long) AL_MIC_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "MIC_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MONITOR_CTL
-	x =  PyInt_FromLong((long) AL_MONITOR_CTL);
-	if (x == NULL || PyDict_SetItemString(d, "MONITOR_CTL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MONITOR_OFF
-	x =  PyInt_FromLong((long) AL_MONITOR_OFF);
-	if (x == NULL || PyDict_SetItemString(d, "MONITOR_OFF", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MONITOR_ON
-	x =  PyInt_FromLong((long) AL_MONITOR_ON);
-	if (x == NULL || PyDict_SetItemString(d, "MONITOR_ON", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MONO
-	x =  PyInt_FromLong((long) AL_MONO);
-	if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_MUTE
-	x =  PyInt_FromLong((long) AL_MUTE);
-	if (x == NULL || PyDict_SetItemString(d, "MUTE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NAME
-	x =  PyInt_FromLong((long) AL_NAME);
-	if (x == NULL || PyDict_SetItemString(d, "NAME", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NEG_INFINITY
-	x =  PyInt_FromLong((long) AL_NEG_INFINITY);
-	if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NEG_INFINITY_BIT
-	x =  PyInt_FromLong((long) AL_NEG_INFINITY_BIT);
-	if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY_BIT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NO_CHANGE
-	x =  PyInt_FromLong((long) AL_NO_CHANGE);
-	if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NO_CHANGE_BIT
-	x =  PyInt_FromLong((long) AL_NO_CHANGE_BIT);
-	if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE_BIT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NO_ELEM
-	x =  PyInt_FromLong((long) AL_NO_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "NO_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NO_ERRORS
-	x =  PyInt_FromLong((long) AL_NO_ERRORS);
-	if (x == NULL || PyDict_SetItemString(d, "NO_ERRORS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NO_OP
-	x =  PyInt_FromLong((long) AL_NO_OP);
-	if (x == NULL || PyDict_SetItemString(d, "NO_OP", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NO_VAL
-	x =  PyInt_FromLong((long) AL_NO_VAL);
-	if (x == NULL || PyDict_SetItemString(d, "NO_VAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NULL_INTERFACE
-	x =  PyInt_FromLong((long) AL_NULL_INTERFACE);
-	if (x == NULL || PyDict_SetItemString(d, "NULL_INTERFACE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_NULL_RESOURCE
-	x =  PyInt_FromLong((long) AL_NULL_RESOURCE);
-	if (x == NULL || PyDict_SetItemString(d, "NULL_RESOURCE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_OPTICAL_IF_TYPE
-	x =  PyInt_FromLong((long) AL_OPTICAL_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "OPTICAL_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_OUTPUT_COUNT
-	x =  PyInt_FromLong((long) AL_OUTPUT_COUNT);
-	if (x == NULL || PyDict_SetItemString(d, "OUTPUT_COUNT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_OUTPUT_DEVICE_TYPE
-	x =  PyInt_FromLong((long) AL_OUTPUT_DEVICE_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "OUTPUT_DEVICE_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_OUTPUT_HRB_TYPE
-	x =  PyInt_FromLong((long) AL_OUTPUT_HRB_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "OUTPUT_HRB_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_OUTPUT_PORT_TYPE
-	x =  PyInt_FromLong((long) AL_OUTPUT_PORT_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "OUTPUT_PORT_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_OUTPUT_RATE
-	x =  PyInt_FromLong((long) AL_OUTPUT_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "OUTPUT_RATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PARAM_BIT
-	x =  PyInt_FromLong((long) AL_PARAM_BIT);
-	if (x == NULL || PyDict_SetItemString(d, "PARAM_BIT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PARAMS
-	x =  PyInt_FromLong((long) AL_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "PARAMS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PORT_COUNT
-	x =  PyInt_FromLong((long) AL_PORT_COUNT);
-	if (x == NULL || PyDict_SetItemString(d, "PORT_COUNT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PORT_TYPE
-	x =  PyInt_FromLong((long) AL_PORT_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "PORT_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PORTS
-	x =  PyInt_FromLong((long) AL_PORTS);
-	if (x == NULL || PyDict_SetItemString(d, "PORTS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PORTSTYLE_DIRECT
-	x =  PyInt_FromLong((long) AL_PORTSTYLE_DIRECT);
-	if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_DIRECT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PORTSTYLE_SERIAL
-	x =  PyInt_FromLong((long) AL_PORTSTYLE_SERIAL);
-	if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_SERIAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PRINT_ERRORS
-	x =  PyInt_FromLong((long) AL_PRINT_ERRORS);
-	if (x == NULL || PyDict_SetItemString(d, "PRINT_ERRORS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_PTR_ELEM
-	x =  PyInt_FromLong((long) AL_PTR_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "PTR_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RANGE_VALUE
-	x =  PyInt_FromLong((long) AL_RANGE_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE
-	x =  PyInt_FromLong((long) AL_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "RATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_11025
-	x =  PyInt_FromLong((long) AL_RATE_11025);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_11025", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_16000
-	x =  PyInt_FromLong((long) AL_RATE_16000);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_16000", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_22050
-	x =  PyInt_FromLong((long) AL_RATE_22050);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_22050", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_32000
-	x =  PyInt_FromLong((long) AL_RATE_32000);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_32000", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_44100
-	x =  PyInt_FromLong((long) AL_RATE_44100);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_44100", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_48000
-	x =  PyInt_FromLong((long) AL_RATE_48000);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_48000", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_8000
-	x =  PyInt_FromLong((long) AL_RATE_8000);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_8000", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_AES_1
-	x =  PyInt_FromLong((long) AL_RATE_AES_1);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_AES_1s
-	x =  PyInt_FromLong((long) AL_RATE_AES_1s);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1s", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_AES_2
-	x =  PyInt_FromLong((long) AL_RATE_AES_2);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_AES_2", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_AES_3
-	x =  PyInt_FromLong((long) AL_RATE_AES_3);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_AES_3", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_AES_4
-	x =  PyInt_FromLong((long) AL_RATE_AES_4);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_AES_4", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_AES_6
-	x =  PyInt_FromLong((long) AL_RATE_AES_6);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_AES_6", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_FRACTION_D
-	x =  PyInt_FromLong((long) AL_RATE_FRACTION_D);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_D", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_FRACTION_N
-	x =  PyInt_FromLong((long) AL_RATE_FRACTION_N);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_N", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_INPUTRATE
-	x =  PyInt_FromLong((long) AL_RATE_INPUTRATE);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_INPUTRATE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_NO_DIGITAL_INPUT
-	x =  PyInt_FromLong((long) AL_RATE_NO_DIGITAL_INPUT);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_NO_DIGITAL_INPUT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_UNACQUIRED
-	x =  PyInt_FromLong((long) AL_RATE_UNACQUIRED);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_UNACQUIRED", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RATE_UNDEFINED
-	x =  PyInt_FromLong((long) AL_RATE_UNDEFINED);
-	if (x == NULL || PyDict_SetItemString(d, "RATE_UNDEFINED", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_REF_0DBV
-	x =  PyInt_FromLong((long) AL_REF_0DBV);
-	if (x == NULL || PyDict_SetItemString(d, "REF_0DBV", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_REF_NONE
-	x =  PyInt_FromLong((long) AL_REF_NONE);
-	if (x == NULL || PyDict_SetItemString(d, "REF_NONE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESERVED1_TYPE
-	x =  PyInt_FromLong((long) AL_RESERVED1_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "RESERVED1_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESERVED2_TYPE
-	x =  PyInt_FromLong((long) AL_RESERVED2_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "RESERVED2_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESERVED3_TYPE
-	x =  PyInt_FromLong((long) AL_RESERVED3_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "RESERVED3_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESERVED4_TYPE
-	x =  PyInt_FromLong((long) AL_RESERVED4_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "RESERVED4_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESOURCE
-	x =  PyInt_FromLong((long) AL_RESOURCE);
-	if (x == NULL || PyDict_SetItemString(d, "RESOURCE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESOURCE_ELEM
-	x =  PyInt_FromLong((long) AL_RESOURCE_ELEM);
-	if (x == NULL || PyDict_SetItemString(d, "RESOURCE_ELEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RESOURCE_TYPE
-	x =  PyInt_FromLong((long) AL_RESOURCE_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "RESOURCE_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RIGHT_INPUT_ATTEN
-	x =  PyInt_FromLong((long) AL_RIGHT_INPUT_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "RIGHT_INPUT_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RIGHT_MONITOR_ATTEN
-	x =  PyInt_FromLong((long) AL_RIGHT_MONITOR_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "RIGHT_MONITOR_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RIGHT_SPEAKER_GAIN
-	x =  PyInt_FromLong((long) AL_RIGHT_SPEAKER_GAIN);
-	if (x == NULL || PyDict_SetItemString(d, "RIGHT_SPEAKER_GAIN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RIGHT1_INPUT_ATTEN
-	x =  PyInt_FromLong((long) AL_RIGHT1_INPUT_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "RIGHT1_INPUT_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_RIGHT2_INPUT_ATTEN
-	x =  PyInt_FromLong((long) AL_RIGHT2_INPUT_ATTEN);
-	if (x == NULL || PyDict_SetItemString(d, "RIGHT2_INPUT_ATTEN", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SAMPFMT_DOUBLE
-	x =  PyInt_FromLong((long) AL_SAMPFMT_DOUBLE);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_DOUBLE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SAMPFMT_FLOAT
-	x =  PyInt_FromLong((long) AL_SAMPFMT_FLOAT);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_FLOAT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SAMPFMT_TWOSCOMP
-	x =  PyInt_FromLong((long) AL_SAMPFMT_TWOSCOMP);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_TWOSCOMP", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SAMPLE_16
-	x =  PyInt_FromLong((long) AL_SAMPLE_16);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPLE_16", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SAMPLE_24
-	x =  PyInt_FromLong((long) AL_SAMPLE_24);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPLE_24", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SAMPLE_8
-	x =  PyInt_FromLong((long) AL_SAMPLE_8);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPLE_8", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SCALAR_VAL
-	x =  PyInt_FromLong((long) AL_SCALAR_VAL);
-	if (x == NULL || PyDict_SetItemString(d, "SCALAR_VAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SET_VAL
-	x =  PyInt_FromLong((long) AL_SET_VAL);
-	if (x == NULL || PyDict_SetItemString(d, "SET_VAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SHORT_NAME
-	x =  PyInt_FromLong((long) AL_SHORT_NAME);
-	if (x == NULL || PyDict_SetItemString(d, "SHORT_NAME", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SMPTE272M_IF_TYPE
-	x =  PyInt_FromLong((long) AL_SMPTE272M_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "SMPTE272M_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SOURCE
-	x =  PyInt_FromLong((long) AL_SOURCE);
-	if (x == NULL || PyDict_SetItemString(d, "SOURCE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SPEAKER_IF_TYPE
-	x =  PyInt_FromLong((long) AL_SPEAKER_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "SPEAKER_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SPEAKER_MUTE_CTL
-	x =  PyInt_FromLong((long) AL_SPEAKER_MUTE_CTL);
-	if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_CTL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SPEAKER_MUTE_OFF
-	x =  PyInt_FromLong((long) AL_SPEAKER_MUTE_OFF);
-	if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_OFF", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SPEAKER_MUTE_ON
-	x =  PyInt_FromLong((long) AL_SPEAKER_MUTE_ON);
-	if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_ON", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SPEAKER_PLUS_LINE_IF_TYPE
-	x =  PyInt_FromLong((long) AL_SPEAKER_PLUS_LINE_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "SPEAKER_PLUS_LINE_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_STEREO
-	x =  PyInt_FromLong((long) AL_STEREO);
-	if (x == NULL || PyDict_SetItemString(d, "STEREO", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_STRING_VAL
-	x =  PyInt_FromLong((long) AL_STRING_VAL);
-	if (x == NULL || PyDict_SetItemString(d, "STRING_VAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SUBSYSTEM
-	x =  PyInt_FromLong((long) AL_SUBSYSTEM);
-	if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SUBSYSTEM_TYPE
-	x =  PyInt_FromLong((long) AL_SUBSYSTEM_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SYNC_INPUT_TO_AES
-	x =  PyInt_FromLong((long) AL_SYNC_INPUT_TO_AES);
-	if (x == NULL || PyDict_SetItemString(d, "SYNC_INPUT_TO_AES", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SYNC_OUTPUT_TO_AES
-	x =  PyInt_FromLong((long) AL_SYNC_OUTPUT_TO_AES);
-	if (x == NULL || PyDict_SetItemString(d, "SYNC_OUTPUT_TO_AES", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SYSTEM
-	x =  PyInt_FromLong((long) AL_SYSTEM);
-	if (x == NULL || PyDict_SetItemString(d, "SYSTEM", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_SYSTEM_TYPE
-	x =  PyInt_FromLong((long) AL_SYSTEM_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "SYSTEM_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_TEST_IF_TYPE
-	x =  PyInt_FromLong((long) AL_TEST_IF_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "TEST_IF_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_TYPE
-	x =  PyInt_FromLong((long) AL_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_TYPE_BIT
-	x =  PyInt_FromLong((long) AL_TYPE_BIT);
-	if (x == NULL || PyDict_SetItemString(d, "TYPE_BIT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_UNUSED_COUNT
-	x =  PyInt_FromLong((long) AL_UNUSED_COUNT);
-	if (x == NULL || PyDict_SetItemString(d, "UNUSED_COUNT", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_UNUSED_PORTS
-	x =  PyInt_FromLong((long) AL_UNUSED_PORTS);
-	if (x == NULL || PyDict_SetItemString(d, "UNUSED_PORTS", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_VARIABLE_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_VARIABLE_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "VARIABLE_MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_VECTOR_VAL
-	x =  PyInt_FromLong((long) AL_VECTOR_VAL);
-	if (x == NULL || PyDict_SetItemString(d, "VECTOR_VAL", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_VIDEO_MCLK_TYPE
-	x =  PyInt_FromLong((long) AL_VIDEO_MCLK_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "VIDEO_MCLK_TYPE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-#ifdef AL_WORDSIZE
-	x =  PyInt_FromLong((long) AL_WORDSIZE);
-	if (x == NULL || PyDict_SetItemString(d, "WORDSIZE", x) < 0)
-		goto error;
-	Py_DECREF(x);
-#endif
-
-#ifdef AL_NO_ELEM		/* IRIX 6 */
-	(void) alSetErrorHandler(ErrorHandler);
-#endif /* AL_NO_ELEM */
-#ifdef OLD_INTERFACE
-	(void) ALseterrorhandler(ErrorHandler);
-#endif /* OLD_INTERFACE */
-	
-  error:
-	return;
-}

Modified: python/branches/p3yk-noslice/Modules/arraymodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/arraymodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/arraymodule.c	Wed Jul 11 15:40:56 2007
@@ -1147,12 +1147,19 @@
 		dict = Py_None;
 		Py_INCREF(dict);
 	}
-	result = Py_BuildValue("O(cs#)O", 
-		array->ob_type, 
-		array->ob_descr->typecode,
-		array->ob_item,
-		array->ob_size * array->ob_descr->itemsize,
-		dict);
+	if (array->ob_size > 0) {
+		result = Py_BuildValue("O(cs#)O", 
+			array->ob_type, 
+			array->ob_descr->typecode,
+			array->ob_item,
+			array->ob_size * array->ob_descr->itemsize,
+			dict);
+	} else {
+		result = Py_BuildValue("O(c)O", 
+			array->ob_type, 
+			array->ob_descr->typecode,
+			dict);
+	}
 	Py_DECREF(dict);
 	return result;
 }
@@ -1252,12 +1259,11 @@
 {
 	FILE *fp;
 
+        if (self->ob_size == 0)
+		goto done;
+
 	fp = PyFile_AsFile(f);
-	if (fp == NULL) {
-		PyErr_SetString(PyExc_TypeError, "arg must be open file");
-		return NULL;
-	}
-	if (self->ob_size > 0) {
+	if (fp != NULL) {
 		if (fwrite(self->ob_item, self->ob_descr->itemsize,
 			   self->ob_size, fp) != (size_t)self->ob_size) {
 			PyErr_SetFromErrno(PyExc_IOError);
@@ -1265,6 +1271,31 @@
 			return NULL;
 		}
 	}
+	else {
+		Py_ssize_t nbytes = self->ob_size * self->ob_descr->itemsize;
+		/* Write 64K blocks at a time */
+		/* XXX Make the block size settable */
+		int BLOCKSIZE = 64*1024;
+		Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
+		Py_ssize_t i;
+		for (i = 0; i < nblocks; i++) {
+			char* ptr = self->ob_item + i*BLOCKSIZE;
+			Py_ssize_t size = BLOCKSIZE;
+			PyObject *bytes, *res;
+			if (i*BLOCKSIZE + size > nbytes)
+				size = nbytes - i*BLOCKSIZE;
+			bytes = PyBytes_FromStringAndSize(ptr, size);
+			if (bytes == NULL)
+				return NULL;
+			res = PyObject_CallMethod(f, "write", "O",
+						  bytes);
+			Py_DECREF(bytes);
+			if (res == NULL)
+				return NULL;
+		}
+	}
+
+  done:
 	Py_INCREF(Py_None);
 	return Py_None;
 }
@@ -1787,6 +1818,8 @@
 	(objobjargproc)array_ass_subscr
 };
 
+static const void *emptybuf = "";
+
 static Py_ssize_t
 array_buffer_getreadbuf(arrayobject *self, Py_ssize_t index, const void **ptr)
 {
@@ -1796,6 +1829,8 @@
 		return -1;
 	}
 	*ptr = (void *)self->ob_item;
+	if (*ptr == NULL)
+		*ptr = emptybuf;
 	return self->ob_size*self->ob_descr->itemsize;
 }
 
@@ -1808,6 +1843,8 @@
 		return -1;
 	}
 	*ptr = (void *)self->ob_item;
+	if (*ptr == NULL)
+		*ptr = emptybuf;
 	return self->ob_size*self->ob_descr->itemsize;
 }
 

Modified: python/branches/p3yk-noslice/Modules/binascii.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/binascii.c	(original)
+++ python/branches/p3yk-noslice/Modules/binascii.c	Wed Jul 11 15:40:56 2007
@@ -1150,7 +1150,7 @@
 	/* XXX: this function has the side effect of converting all of
 	 * the end of lines to be the same depending on this detection
 	 * here */
-	p = (unsigned char *) strchr((char *)data, '\n');
+	p = (unsigned char *) memchr(data, '\n', datalen);
 	if ((p != NULL) && (p > data) && (*(p-1) == '\r'))
 		crlf = 1;
 
@@ -1160,12 +1160,14 @@
 		if ((data[in] > 126) ||
 		    (data[in] == '=') ||
 		    (header && data[in] == '_') ||
-		    ((data[in] == '.') && (linelen == 1)) ||
+		    ((data[in] == '.') && (linelen == 0) &&
+		     (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
 		    (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
 		    ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
 		    ((data[in] < 33) &&
 		     (data[in] != '\r') && (data[in] != '\n') &&
-		     (quotetabs && ((data[in] != '\t') || (data[in] != ' ')))))
+		     (quotetabs ||
+		     	(!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
 		{
 			if ((linelen + 3) >= MAXLINESIZE) {
 				linelen = 0;
@@ -1230,12 +1232,14 @@
 		if ((data[in] > 126) ||
 		    (data[in] == '=') ||
 		    (header && data[in] == '_') ||
-		    ((data[in] == '.') && (linelen == 1)) ||
+		    ((data[in] == '.') && (linelen == 0) &&
+		     (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
 		    (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
 		    ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
 		    ((data[in] < 33) &&
 		     (data[in] != '\r') && (data[in] != '\n') &&
-		     (quotetabs && ((data[in] != '\t') || (data[in] != ' ')))))
+		     (quotetabs ||
+		     	(!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
 		{
 			if ((linelen + 3 )>= MAXLINESIZE) {
 				odata[out++] = '=';

Deleted: /python/branches/p3yk-noslice/Modules/bsddbmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/bsddbmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,858 +0,0 @@
-/* Berkeley DB interface.
-   Author: Michael McLay
-   Hacked: Guido van Rossum
-   Btree and Recno additions plus sequence methods: David Ely
-   Hacked by Gustavo Niemeyer <niemeyer at conectiva.com> fixing recno
-   support.
-
-   XXX To do:
-   - provide a way to access the various hash functions
-   - support more open flags
-
-   The windows port of the Berkeley DB code is hard to find on the web:
-   www.nightmare.com/software.html
-*/
-
-#include "Python.h"
-#ifdef WITH_THREAD
-#include "pythread.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#ifdef HAVE_DB_185_H
-#include <db_185.h>
-#else
-#include <db.h>
-#endif
-/* Please don't include internal header files of the Berkeley db package
-   (it messes up the info required in the Setup file) */
-
-typedef struct {
-	PyObject_HEAD
-	DB *di_bsddb;
-	int di_size;	/* -1 means recompute */
-	int di_type;
-#ifdef WITH_THREAD
-	PyThread_type_lock di_lock;
-#endif
-} bsddbobject;
-
-static PyTypeObject Bsddbtype;
-
-#define is_bsddbobject(v) ((v)->ob_type == &Bsddbtype)
-#define check_bsddbobject_open(v, r) if ((v)->di_bsddb == NULL) \
-               { PyErr_SetString(BsddbError, \
-				 "BSDDB object has already been closed"); \
-                 return r; }
-
-static PyObject *BsddbError;
-
-static PyObject *
-newdbhashobject(char *file, int flags, int mode,
-		int bsize, int ffactor, int nelem, int cachesize,
-		int hash, int lorder)
-{
-	bsddbobject *dp;
-	HASHINFO info;
-
-	if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
-		return NULL;
-
-	info.bsize = bsize;
-	info.ffactor = ffactor;
-	info.nelem = nelem;
-	info.cachesize = cachesize;
-	info.hash = NULL; /* XXX should derive from hash argument */
-	info.lorder = lorder;
-
-#ifdef O_BINARY
-	flags |= O_BINARY;
-#endif
-	Py_BEGIN_ALLOW_THREADS
-	dp->di_bsddb = dbopen(file, flags, mode, DB_HASH, &info);
-	Py_END_ALLOW_THREADS
-	if (dp->di_bsddb == NULL) {
-		PyErr_SetFromErrno(BsddbError);
-#ifdef WITH_THREAD
-		dp->di_lock = NULL;
-#endif
-		Py_DECREF(dp);
-		return NULL;
-	}
-
-	dp->di_size = -1;
-	dp->di_type = DB_HASH;
-
-#ifdef WITH_THREAD
-	dp->di_lock = PyThread_allocate_lock();
-	if (dp->di_lock == NULL) {
-		PyErr_SetString(BsddbError, "can't allocate lock");
-		Py_DECREF(dp);
-		return NULL;
-	}
-#endif
-
-	return (PyObject *)dp;
-}
-
-static PyObject *
-newdbbtobject(char *file, int flags, int mode,
-	      int btflags, int cachesize, int maxkeypage,
-	      int minkeypage, int psize, int lorder)
-{
-	bsddbobject *dp;
-	BTREEINFO info;
-
-	if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
-		return NULL;
-
-	info.flags = btflags;
-	info.cachesize = cachesize;
-	info.maxkeypage = maxkeypage;
-	info.minkeypage = minkeypage;
-	info.psize = psize;
-	info.lorder = lorder;
-	info.compare = 0; /* Use default comparison functions, for now..*/
-	info.prefix = 0;
-
-#ifdef O_BINARY
-	flags |= O_BINARY;
-#endif
-	Py_BEGIN_ALLOW_THREADS
-	dp->di_bsddb = dbopen(file, flags, mode, DB_BTREE, &info);
-	Py_END_ALLOW_THREADS
-	if (dp->di_bsddb == NULL) {
-		PyErr_SetFromErrno(BsddbError);
-#ifdef WITH_THREAD
-		dp->di_lock = NULL;
-#endif
-		Py_DECREF(dp);
-		return NULL;
-	}
-
-	dp->di_size = -1;
-	dp->di_type = DB_BTREE;
-
-#ifdef WITH_THREAD
-	dp->di_lock = PyThread_allocate_lock();
-	if (dp->di_lock == NULL) {
-		PyErr_SetString(BsddbError, "can't allocate lock");
-		Py_DECREF(dp);
-		return NULL;
-	}
-#endif
-
-	return (PyObject *)dp;
-}
-
-static PyObject *
-newdbrnobject(char *file, int flags, int mode,
-	      int rnflags, int cachesize, int psize, int lorder,
-	      size_t reclen, u_char bval, char *bfname)
-{
-	bsddbobject *dp;
-	RECNOINFO info;
-	int fd;
-
-	if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
-		return NULL;
-
-	info.flags = rnflags;
-	info.cachesize = cachesize;
-	info.psize = psize;
-	info.lorder = lorder;
-	info.reclen = reclen;
-	info.bval = bval;
-	info.bfname = bfname;
-
-#ifdef O_BINARY
-	flags |= O_BINARY;
-#endif
-	/* This is a hack to avoid a dbopen() bug that happens when
-	 * it fails. */
-	fd = open(file, flags);
-	if (fd == -1) {
-		dp->di_bsddb = NULL;
-	}
-	else {
-		close(fd);
-		Py_BEGIN_ALLOW_THREADS
-		dp->di_bsddb = dbopen(file, flags, mode, DB_RECNO, &info);
-		Py_END_ALLOW_THREADS
-	}
-	if (dp->di_bsddb == NULL) {
-		PyErr_SetFromErrno(BsddbError);
-#ifdef WITH_THREAD
-		dp->di_lock = NULL;
-#endif
-		Py_DECREF(dp);
-		return NULL;
-	}
-
-	dp->di_size = -1;
-	dp->di_type = DB_RECNO;
-
-#ifdef WITH_THREAD
-	dp->di_lock = PyThread_allocate_lock();
-	if (dp->di_lock == NULL) {
-		PyErr_SetString(BsddbError, "can't allocate lock");
-		Py_DECREF(dp);
-		return NULL;
-	}
-#endif
-
-	return (PyObject *)dp;
-}
-
-static void
-bsddb_dealloc(bsddbobject *dp)
-{
-#ifdef WITH_THREAD
-	if (dp->di_lock) {
-		PyThread_acquire_lock(dp->di_lock, 0);
-		PyThread_release_lock(dp->di_lock);
-		PyThread_free_lock(dp->di_lock);
-		dp->di_lock = NULL;
-	}
-#endif
-	if (dp->di_bsddb != NULL) {
-		int status;
-		Py_BEGIN_ALLOW_THREADS
-		status = (dp->di_bsddb->close)(dp->di_bsddb);
-		Py_END_ALLOW_THREADS
-		if (status != 0)
-			fprintf(stderr,
-				"Python bsddb: close errno %d in dealloc\n",
-				errno);
-	}
-	PyObject_Del(dp);
-}
-
-#ifdef WITH_THREAD
-#define BSDDB_BGN_SAVE(_dp) \
-	Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(_dp->di_lock,1);
-#define BSDDB_END_SAVE(_dp) \
-	PyThread_release_lock(_dp->di_lock); Py_END_ALLOW_THREADS
-#else
-#define BSDDB_BGN_SAVE(_dp) Py_BEGIN_ALLOW_THREADS 
-#define BSDDB_END_SAVE(_dp) Py_END_ALLOW_THREADS
-#endif
-
-static Py_ssize_t
-bsddb_length(bsddbobject *dp)
-{
-	check_bsddbobject_open(dp, -1);
-	if (dp->di_size < 0) {
-		DBT krec, drec;
-		int status;
-		int size = 0;
-		BSDDB_BGN_SAVE(dp)
-		for (status = (dp->di_bsddb->seq)(dp->di_bsddb,
-						  &krec, &drec,R_FIRST);
-		     status == 0;
-		     status = (dp->di_bsddb->seq)(dp->di_bsddb,
-						  &krec, &drec, R_NEXT))
-			size++;
-		BSDDB_END_SAVE(dp)
-		if (status < 0) {
-			PyErr_SetFromErrno(BsddbError);
-			return -1;
-		}
-		dp->di_size = size;
-	}
-	return dp->di_size;
-}
-
-static PyObject *
-bsddb_subscript(bsddbobject *dp, PyObject *key)
-{
-	int status;
-	DBT krec, drec;
-	char *data,buf[4096];
-	int size;
-	PyObject *result;
-	recno_t recno;
-	
-	if (dp->di_type == DB_RECNO) {
-		if (!PyArg_Parse(key, "i", &recno)) {
-			PyErr_SetString(PyExc_TypeError,
-					"key type must be integer");
-			return NULL;
-		}
-		krec.data = &recno;
-		krec.size = sizeof(recno);
-	}
-	else {
-		if (!PyArg_Parse(key, "s#", &data, &size)) {
-			PyErr_SetString(PyExc_TypeError,
-					"key type must be string");
-			return NULL;
-		}
-		krec.data = data;
-		krec.size = size;
-	}
-        check_bsddbobject_open(dp, NULL);
-
-	BSDDB_BGN_SAVE(dp)
-	status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
-	if (status == 0) {
-		if (drec.size > sizeof(buf)) data = malloc(drec.size);
-		else data = buf;
-		if (data!=NULL) memcpy(data,drec.data,drec.size);
-	}
-	BSDDB_END_SAVE(dp)
-	if (data==NULL) return PyErr_NoMemory();
-	if (status != 0) {
-		if (status < 0)
-			PyErr_SetFromErrno(BsddbError);
-		else
-			PyErr_SetObject(PyExc_KeyError, key);
-		return NULL;
-	}
-
-	result = PyString_FromStringAndSize(data, (int)drec.size);
-	if (data != buf) free(data);
-	return result;
-}
-
-static int
-bsddb_ass_sub(bsddbobject *dp, PyObject *key, PyObject *value)
-{
-	int status;
-	DBT krec, drec;
-	char *data;
-	int size;
-	recno_t recno;
-
-	if (dp->di_type == DB_RECNO) {
-		if (!PyArg_Parse(key, "i", &recno)) {
-			PyErr_SetString(PyExc_TypeError,
-					"bsddb key type must be integer");
-			return -1;
-		}
-		krec.data = &recno;
-		krec.size = sizeof(recno);
-	}
-	else {
-		if (!PyArg_Parse(key, "s#", &data, &size)) {
-			PyErr_SetString(PyExc_TypeError,
-					"bsddb key type must be string");
-			return -1;
-		}
-		krec.data = data;
-		krec.size = size;
-	}
-	check_bsddbobject_open(dp, -1);
-	dp->di_size = -1;
-	if (value == NULL) {
-		BSDDB_BGN_SAVE(dp)
-		status = (dp->di_bsddb->del)(dp->di_bsddb, &krec, 0);
-		BSDDB_END_SAVE(dp)
-	}
-	else {
-		if (!PyArg_Parse(value, "s#", &data, &size)) {
-			PyErr_SetString(PyExc_TypeError,
-					"bsddb value type must be string");
-			return -1;
-		}
-		drec.data = data;
-		drec.size = size;
-		BSDDB_BGN_SAVE(dp)
-		status = (dp->di_bsddb->put)(dp->di_bsddb, &krec, &drec, 0);
-		BSDDB_END_SAVE(dp)
-	}
-	if (status != 0) {
-		if (status < 0)
-			PyErr_SetFromErrno(BsddbError);
-		else
-			PyErr_SetObject(PyExc_KeyError, key);
-		return -1;
-	}
-	return 0;
-}
-
-static PyMappingMethods bsddb_as_mapping = {
-	(lenfunc)bsddb_length,		/*mp_length*/
-	(binaryfunc)bsddb_subscript,	/*mp_subscript*/
-	(objobjargproc)bsddb_ass_sub,	/*mp_ass_subscript*/
-};
-
-static PyObject *
-bsddb_close(bsddbobject *dp)
-{
-	if (dp->di_bsddb != NULL) {
-		int status;
-		BSDDB_BGN_SAVE(dp)
-		status = (dp->di_bsddb->close)(dp->di_bsddb);
-		BSDDB_END_SAVE(dp)
-		if (status != 0) {
-			dp->di_bsddb = NULL;
-			PyErr_SetFromErrno(BsddbError);
-			return NULL;
-		}
-	}
-	dp->di_bsddb = NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-bsddb_keys(bsddbobject *dp)
-{
-	PyObject *list, *item=NULL;
-	DBT krec, drec;
-	char *data=NULL,buf[4096];
-	int status;
-	int err;
-
-	check_bsddbobject_open(dp, NULL);
-	list = PyList_New(0);
-	if (list == NULL)
-		return NULL;
-	BSDDB_BGN_SAVE(dp)
-	status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_FIRST);
-	if (status == 0) {
-		if (krec.size > sizeof(buf)) data = malloc(krec.size);
-		else data = buf;
-		if (data != NULL) memcpy(data,krec.data,krec.size);
-	}
-	BSDDB_END_SAVE(dp)
-	if (status == 0 && data==NULL) return PyErr_NoMemory();
-	while (status == 0) {
-		if (dp->di_type == DB_RECNO)
-			item = PyInt_FromLong(*((int*)data));
-		else
-			item = PyString_FromStringAndSize(data,
-							  (int)krec.size);
-		if (data != buf) free(data);
-		if (item == NULL) {
-			Py_DECREF(list);
-			return NULL;
-		}
-		err = PyList_Append(list, item);
-		Py_DECREF(item);
-		if (err != 0) {
-			Py_DECREF(list);
-			return NULL;
-		}
-		BSDDB_BGN_SAVE(dp)
-		status = (dp->di_bsddb->seq)
-			(dp->di_bsddb, &krec, &drec, R_NEXT);
-		if (status == 0) {
-			if (krec.size > sizeof(buf))
-				data = malloc(krec.size);
-			else data = buf;
-			if (data != NULL)
-				memcpy(data,krec.data,krec.size);
-		}
-		BSDDB_END_SAVE(dp)
-		if (data == NULL) return PyErr_NoMemory();
-	}
-	if (status < 0) {
-		PyErr_SetFromErrno(BsddbError);
-		Py_DECREF(list);
-		return NULL;
-	}
-	if (dp->di_size < 0)
-		dp->di_size = PyList_Size(list); /* We just did the work */
-	return list;
-}
-
-static PyObject *
-bsddb_contains(bsddbobject *dp, PyObject *args)
-{
-	DBT krec, drec;
-	int status;
-	char *data;
-	int size;
-	recno_t recno;
-
-	if (dp->di_type == DB_RECNO) {
-		if (!PyArg_ParseTuple(args, "i;key type must be integer",
-				      &recno)) {
-			return NULL;
-		}
-		krec.data = &recno;
-		krec.size = sizeof(recno);
-	}
-	else {
-		if (!PyArg_ParseTuple(args, "s#;key type must be string",
-				      &data, &size)) {
-			return NULL;
-		}
-		krec.data = data;
-		krec.size = size;
-	}
-	check_bsddbobject_open(dp, NULL);
-
-	BSDDB_BGN_SAVE(dp)
-	status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
-	BSDDB_END_SAVE(dp)
-	if (status < 0) {
-		PyErr_SetFromErrno(BsddbError);
-		return NULL;
-	}
-
-	return PyInt_FromLong(status == 0);
-}
-
-static PyObject *
-bsddb_set_location(bsddbobject *dp, PyObject *key)
-{
-	int status;
-	DBT krec, drec;
-	char *data,buf[4096];
-	int size;
-	PyObject *result;
-	recno_t recno;
-
-	if (dp->di_type == DB_RECNO) {
-		if (!PyArg_ParseTuple(key, "i;key type must be integer",
-				      &recno)) {
-			return NULL;
-		}
-		krec.data = &recno;
-		krec.size = sizeof(recno);
-	}
-	else {
-		if (!PyArg_ParseTuple(key, "s#;key type must be string",
-				      &data, &size)) {
-			return NULL;
-		}
-		krec.data = data;
-		krec.size = size;
-	}
-	check_bsddbobject_open(dp, NULL);
-
-	BSDDB_BGN_SAVE(dp)
-	status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_CURSOR);
-	if (status == 0) {
-		if (drec.size > sizeof(buf)) data = malloc(drec.size);
-		else data = buf;
-		if (data!=NULL) memcpy(data,drec.data,drec.size);
-	}
-	BSDDB_END_SAVE(dp)
-	if (data==NULL) return PyErr_NoMemory();
-	if (status != 0) {
-		if (status < 0)
-			PyErr_SetFromErrno(BsddbError);
-		else
-			PyErr_SetObject(PyExc_KeyError, key);
-		return NULL;
-	}
-
-	if (dp->di_type == DB_RECNO)
-		result = Py_BuildValue("is#", *((int*)krec.data),
-				       data, drec.size);
-	else
-		result = Py_BuildValue("s#s#", krec.data, krec.size,
-				       data, drec.size);
-	if (data != buf) free(data);
-	return result;
-}
-
-static PyObject *
-bsddb_seq(bsddbobject *dp, int sequence_request)
-{
-	int status;
-	DBT krec, drec;
-	char *kdata=NULL,kbuf[4096];
-	char *ddata=NULL,dbuf[4096];
-	PyObject *result;
-
-	check_bsddbobject_open(dp, NULL);
-	krec.data = 0;
-	krec.size = 0;
-
-	BSDDB_BGN_SAVE(dp)
-	status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec,
-				     &drec, sequence_request);
-	if (status == 0) {
-		if (krec.size > sizeof(kbuf)) kdata = malloc(krec.size);
-		else kdata = kbuf;
-		if (kdata != NULL) memcpy(kdata,krec.data,krec.size);
-		if (drec.size > sizeof(dbuf)) ddata = malloc(drec.size);
-		else ddata = dbuf;
-		if (ddata != NULL) memcpy(ddata,drec.data,drec.size);
-	}
-	BSDDB_END_SAVE(dp)
-	if (status == 0) {
-		if ((kdata == NULL) || (ddata == NULL)) 
-			return PyErr_NoMemory();
-	}
-	else { 
-		/* (status != 0) */  
-		if (status < 0)
-			PyErr_SetFromErrno(BsddbError);
-		else
-			PyErr_SetString(PyExc_KeyError, "no key/data pairs");
-		return NULL;
-	}
-
-	if (dp->di_type == DB_RECNO)
-		result = Py_BuildValue("is#", *((int*)kdata),
-				       ddata, drec.size);
-	else
-		result = Py_BuildValue("s#s#", kdata, krec.size,
-				       ddata, drec.size);
-	if (kdata != kbuf) free(kdata);
-	if (ddata != dbuf) free(ddata);
-	return result;
-}
-
-static PyObject *
-bsddb_next(bsddbobject *dp)
-{
-	return bsddb_seq(dp, R_NEXT);
-}
-static PyObject *
-bsddb_previous(bsddbobject *dp)
-{
-	return bsddb_seq(dp, R_PREV);
-}
-static PyObject *
-bsddb_first(bsddbobject *dp)
-{
-	return bsddb_seq(dp, R_FIRST);
-}
-static PyObject *
-bsddb_last(bsddbobject *dp)
-{
-	return bsddb_seq(dp, R_LAST);
-}
-static PyObject *
-bsddb_sync(bsddbobject *dp)
-{
-	int status;
-
-	check_bsddbobject_open(dp, NULL);
-	BSDDB_BGN_SAVE(dp)
-	status = (dp->di_bsddb->sync)(dp->di_bsddb, 0);
-	BSDDB_END_SAVE(dp)
-	if (status != 0) {
-		PyErr_SetFromErrno(BsddbError);
-		return NULL;
-	}
-	return PyInt_FromLong(status = 0);
-}
-static PyMethodDef bsddb_methods[] = {
-	{"close",		(PyCFunction)bsddb_close, METH_NOARGS},
-	{"keys",		(PyCFunction)bsddb_keys, METH_NOARGS},
-	{"__contains__",	(PyCFunction)bsddb_contains, METH_VARARGS},
-	{"set_location",	(PyCFunction)bsddb_set_location, METH_VARARGS},
-	{"next",		(PyCFunction)bsddb_next, METH_NOARGS},
-	{"previous",	(PyCFunction)bsddb_previous, METH_NOARGS},
-	{"first",		(PyCFunction)bsddb_first, METH_NOARGS},
-	{"last",		(PyCFunction)bsddb_last, METH_NOARGS},
-	{"sync",		(PyCFunction)bsddb_sync, METH_NOARGS},
-	{NULL,	       	NULL}		/* sentinel */
-};
-
-static PyObject *
-bsddb_getattr(PyObject *dp, char *name)
-{
-	return Py_FindMethod(bsddb_methods, dp, name);
-}
-
-static PyTypeObject Bsddbtype = {
-	PyObject_HEAD_INIT(NULL)
-	0,
-	"bsddb.bsddb",
-	sizeof(bsddbobject),
-	0,
-	(destructor)bsddb_dealloc, /*tp_dealloc*/
-	0,			/*tp_print*/
-	(getattrfunc)bsddb_getattr, /*tp_getattr*/
-	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
-	0,			/*tp_repr*/
-	0,			/*tp_as_number*/
-	0,			/*tp_as_sequence*/
-	&bsddb_as_mapping,	/*tp_as_mapping*/
-};
-
-static PyObject *
-bsdhashopen(PyObject *self, PyObject *args)
-{
-	char *file;
-	char *flag = NULL;
-	int flags = O_RDONLY;
-	int mode = 0666;
-	int bsize = 0;
-	int ffactor = 0;
-	int nelem = 0;
-	int cachesize = 0;
-	int hash = 0; /* XXX currently ignored */
-	int lorder = 0;
-
-	if (!PyArg_ParseTuple(args, "z|siiiiiii:hashopen",
-			      &file, &flag, &mode,
-			      &bsize, &ffactor, &nelem, &cachesize,
-			      &hash, &lorder))
-		return NULL;
-	if (flag != NULL) {
-		/* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
-		if (flag[0] == 'r')
-			flags = O_RDONLY;
-		else if (flag[0] == 'w')
-			flags = O_RDWR;
-		else if (flag[0] == 'c')
-			flags = O_RDWR|O_CREAT;
-		else if (flag[0] == 'n')
-			flags = O_RDWR|O_CREAT|O_TRUNC;
-		else {
-			PyErr_SetString(BsddbError,
-				"Flag should begin with 'r', 'w', 'c' or 'n'");
-			return NULL;
-		}
-		if (flag[1] == 'l') {
-#if defined(O_EXLOCK) && defined(O_SHLOCK)
-			if (flag[0] == 'r')
-				flags |= O_SHLOCK;
-			else
-				flags |= O_EXLOCK;
-#else
-			PyErr_SetString(BsddbError,
-				     "locking not supported on this platform");
-			return NULL;
-#endif
-		}
-	}
-	return newdbhashobject(file, flags, mode,
-			       bsize, ffactor, nelem, cachesize, hash, lorder);
-}
-
-static PyObject *
-bsdbtopen(PyObject *self, PyObject *args)
-{
-	char *file;
-	char *flag = NULL;
-	int flags = O_RDONLY;
-	int mode = 0666;
-	int cachesize = 0;
-	int maxkeypage = 0;
-	int minkeypage = 0;
-	int btflags = 0;
-	unsigned int psize = 0;
-	int lorder = 0;
-
-	if (!PyArg_ParseTuple(args, "z|siiiiiii:btopen",
-			      &file, &flag, &mode,
-			      &btflags, &cachesize, &maxkeypage, &minkeypage,
-			      &psize, &lorder))
-		return NULL;
-	if (flag != NULL) {
-		/* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
-		if (flag[0] == 'r')
-			flags = O_RDONLY;
-		else if (flag[0] == 'w')
-			flags = O_RDWR;
-		else if (flag[0] == 'c')
-			flags = O_RDWR|O_CREAT;
-		else if (flag[0] == 'n')
-			flags = O_RDWR|O_CREAT|O_TRUNC;
-		else {
-			PyErr_SetString(BsddbError,
-			       "Flag should begin with 'r', 'w', 'c' or 'n'");
-			return NULL;
-		}
-		if (flag[1] == 'l') {
-#if defined(O_EXLOCK) && defined(O_SHLOCK)
-			if (flag[0] == 'r')
-				flags |= O_SHLOCK;
-			else
-				flags |= O_EXLOCK;
-#else
-			PyErr_SetString(BsddbError,
-				    "locking not supported on this platform");
-			return NULL;
-#endif
-		}
-	}
-	return newdbbtobject(file, flags, mode,
-			     btflags, cachesize, maxkeypage, minkeypage,
-			     psize, lorder);
-}
-
-static PyObject *
-bsdrnopen(PyObject *self, PyObject *args)
-{
-	char *file;
-	char *flag = NULL;
-	int flags = O_RDONLY;
-	int mode = 0666;
-	int cachesize = 0;
-	int rnflags = 0;
-	unsigned int psize = 0;
-	int lorder = 0;
-	size_t reclen = 0;
-	char  *bval = "";
-	char *bfname = NULL;
-
-	if (!PyArg_ParseTuple(args, "z|siiiiiiss:rnopen",
-			      &file, &flag, &mode,
-			      &rnflags, &cachesize, &psize, &lorder,
-			      &reclen, &bval, &bfname))
-		return NULL;
-
-	if (flag != NULL) {
-		/* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
-		if (flag[0] == 'r')
-			flags = O_RDONLY;
-		else if (flag[0] == 'w')
-			flags = O_RDWR;
-		else if (flag[0] == 'c')
-			flags = O_RDWR|O_CREAT;
-		else if (flag[0] == 'n')
-			flags = O_RDWR|O_CREAT|O_TRUNC;
-		else {
-			PyErr_SetString(BsddbError,
-			       "Flag should begin with 'r', 'w', 'c' or 'n'");
-			return NULL;
-		}
-		if (flag[1] == 'l') {
-#if defined(O_EXLOCK) && defined(O_SHLOCK)
-			if (flag[0] == 'r')
-				flags |= O_SHLOCK;
-			else
-				flags |= O_EXLOCK;
-#else
-			PyErr_SetString(BsddbError,
-				    "locking not supported on this platform");
-			return NULL;
-#endif
-		}
-		else if (flag[1] != '\0') {
-			PyErr_SetString(BsddbError,
-				       "Flag char 2 should be 'l' or absent");
-			return NULL;
-		}
-	}
-	return newdbrnobject(file, flags, mode, rnflags, cachesize,
-			     psize, lorder, reclen, bval[0], bfname);
-}
-
-static PyMethodDef bsddbmodule_methods[] = {
-	{"hashopen",	(PyCFunction)bsdhashopen, METH_VARARGS},
-	{"btopen",	(PyCFunction)bsdbtopen, METH_VARARGS},
-	{"rnopen",	(PyCFunction)bsdrnopen, METH_VARARGS},
-	/* strictly for use by dbhhash!!! */
-	{"open",	(PyCFunction)bsdhashopen, METH_VARARGS},
-	{0,		0},
-};
-
-PyMODINIT_FUNC
-initbsddb185(void) {
-	PyObject *m, *d;
-
-	Bsddbtype.ob_type = &PyType_Type;
-	m = Py_InitModule("bsddb185", bsddbmodule_methods);
-	if (m == NULL)
-		return;
-	d = PyModule_GetDict(m);
-	BsddbError = PyErr_NewException("bsddb.error", NULL, NULL);
-	if (BsddbError != NULL)
-		PyDict_SetItemString(d, "error", BsddbError);
-}

Modified: python/branches/p3yk-noslice/Modules/bz2module.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/bz2module.c	(original)
+++ python/branches/p3yk-noslice/Modules/bz2module.c	Wed Jul 11 15:40:56 2007
@@ -1553,6 +1553,8 @@
 			Util_CatchBZ2Error(bzerror);
 			goto error;
 		}
+		if (bzs->avail_in == 0)
+			break; /* no more input data */
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
 			if (_PyString_Resize(&ret, bufsize) < 0) {
@@ -1562,8 +1564,6 @@
 			bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
 						    - totalout);
 			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
-		} else if (bzs->avail_in == 0) {
-			break;
 		}
 	}
 
@@ -1845,6 +1845,8 @@
 			Util_CatchBZ2Error(bzerror);
 			goto error;
 		}
+		if (bzs->avail_in == 0)
+			break; /* no more input data */
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
 			if (_PyString_Resize(&ret, bufsize) < 0) {
@@ -1855,8 +1857,6 @@
 			bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
 						    - totalout);
 			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
-		} else if (bzs->avail_in == 0) {
-			break;
 		}
 	}
 
@@ -2134,6 +2134,13 @@
 			Py_DECREF(ret);
 			return NULL;
 		}
+		if (bzs->avail_in == 0) {
+			BZ2_bzDecompressEnd(bzs);
+			PyErr_SetString(PyExc_ValueError,
+					"couldn't find end of stream");
+			Py_DECREF(ret);
+			return NULL;
+		}
 		if (bzs->avail_out == 0) {
 			bufsize = Util_NewBufferSize(bufsize);
 			if (_PyString_Resize(&ret, bufsize) < 0) {
@@ -2143,12 +2150,6 @@
 			}
 			bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
 			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
-		} else if (bzs->avail_in == 0) {
-			BZ2_bzDecompressEnd(bzs);
-			PyErr_SetString(PyExc_ValueError,
-					"couldn't find end of stream");
-			Py_DECREF(ret);
-			return NULL;
 		}
 	}
 

Modified: python/branches/p3yk-noslice/Modules/cPickle.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/cPickle.c	(original)
+++ python/branches/p3yk-noslice/Modules/cPickle.c	Wed Jul 11 15:40:56 2007
@@ -533,11 +533,12 @@
 		self->buf_size = size;
 	}
 	else if (n > self->buf_size) {
-		self->buf = (char *)realloc(self->buf, n);
-		if (!self->buf)  {
+		char *newbuf = (char *)realloc(self->buf, n);
+		if (!newbuf)  {
 			PyErr_NoMemory();
 			return -1;
 		}
+		self->buf = newbuf;
 		self->buf_size = n;
 	}
 
@@ -576,6 +577,7 @@
 	i = 0;
 	while (1) {
 		int bigger;
+		char *newbuf;
 		for (; i < (self->buf_size - 1); i++) {
 			if (feof(self->fp) ||
 			    (self->buf[i] = getc(self->fp)) == '\n') {
@@ -589,11 +591,12 @@
 			PyErr_NoMemory();
 			return -1;
 		}
-		self->buf = (char *)realloc(self->buf, bigger);
-		if (!self->buf)  {
+		newbuf = (char *)realloc(self->buf, bigger);
+		if (!newbuf)  {
 			PyErr_NoMemory();
 			return -1;
 		}
+		self->buf = newbuf;
 		self->buf_size = bigger;
 	}
 }
@@ -1028,7 +1031,7 @@
 	Py_ssize_t size;
 	int res = -1;
 	PyObject *repr = NULL;
-	int val = PyInt_AsLong(args);
+	long val = PyInt_AsLong(args);
 	static char l = LONG;
 
 	if (val == -1 && PyErr_Occurred()) {
@@ -2708,21 +2711,8 @@
 		}
 	}
 
-	if (PyEval_GetRestricted()) {
-		/* Restricted execution, get private tables */
-		PyObject *m = PyImport_Import(copy_reg_str);
-
-		if (m == NULL)
-			goto err;
-		self->dispatch_table = PyObject_GetAttr(m, dispatch_table_str);
-		Py_DECREF(m);
-		if (self->dispatch_table == NULL)
-			goto err;
-	}
-	else {
-		self->dispatch_table = dispatch_table;
-		Py_INCREF(dispatch_table);
-	}
+	self->dispatch_table = dispatch_table;
+	Py_INCREF(dispatch_table);
 	PyObject_GC_Track(self);
 
 	return self;
@@ -4199,17 +4189,19 @@
 	*/
 
 	if ((self->num_marks + 1) >= self->marks_size) {
+		int *marks;
 		s=self->marks_size+20;
 		if (s <= self->num_marks) s=self->num_marks + 1;
 		if (self->marks == NULL)
-			self->marks=(int *)malloc(s * sizeof(int));
+			marks=(int *)malloc(s * sizeof(int));
 		else
-			self->marks=(int *)realloc(self->marks,
+			marks=(int *)realloc(self->marks,
 						   s * sizeof(int));
-		if (! self->marks) {
+		if (!marks) {
 			PyErr_NoMemory();
 			return -1;
 		}
+		self->marks = marks;
 		self->marks_size = s;
 	}
 

Modified: python/branches/p3yk-noslice/Modules/cStringIO.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/cStringIO.c	(original)
+++ python/branches/p3yk-noslice/Modules/cStringIO.c	Wed Jul 11 15:40:56 2007
@@ -348,13 +348,17 @@
         }
 
         if (position > self->buf_size) {
+                  char *newbuf;
                   self->buf_size*=2;
                   if (self->buf_size <= position) self->buf_size=position+1;
-		  self->buf = (char*) realloc(self->buf,self->buf_size);
-                  if (!self->buf) {
+		  newbuf = (char*) realloc(self->buf,self->buf_size);
+                  if (!newbuf) {
+                      free(self->buf);
+                      self->buf = 0;
                       self->buf_size=self->pos=0;
                       return PyErr_NoMemory();
                     }
+                  self->buf = newbuf;
           }
         else if (position < 0) position=0;
 
@@ -375,6 +379,7 @@
 O_cwrite(PyObject *self, const char *c, Py_ssize_t  l) {
         Py_ssize_t newl;
         Oobject *oself;
+        char *newbuf;
 
         if (!IO__opencheck(IOOOBJECT(self))) return -1;
         oself = (Oobject *)self;
@@ -386,12 +391,15 @@
 		    assert(newl + 1 < INT_MAX);
                     oself->buf_size = (int)(newl+1);
 	    }
-            oself->buf = (char*)realloc(oself->buf, oself->buf_size);
-	    if (!oself->buf) {
+            newbuf = (char*)realloc(oself->buf, oself->buf_size);
+	    if (!newbuf) {
                     PyErr_SetString(PyExc_MemoryError,"out of memory");
+                    free(oself->buf);
+                    oself->buf = 0;
                     oself->buf_size = oself->pos = 0;
                     return -1;
               }
+            oself->buf = newbuf;
           }
 
         memcpy(oself->buf+oself->pos,c,l);

Deleted: /python/branches/p3yk-noslice/Modules/cdmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/cdmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,796 +0,0 @@
-/* CD module -- interface to Mark Callow's and Roger Chickering's */
- /* CD Audio Library (CD). */
-
-#include <sys/types.h>
-#include <cdaudio.h>
-#include "Python.h"
-
-#define NCALLBACKS	8
-
-typedef struct {
-	PyObject_HEAD
-	CDPLAYER *ob_cdplayer;
-} cdplayerobject;
-
-static PyObject *CdError;		/* exception cd.error */
-
-static PyObject *
-CD_allowremoval(cdplayerobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":allowremoval"))
-		return NULL;
-
-	CDallowremoval(self->ob_cdplayer);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_preventremoval(cdplayerobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":preventremoval"))
-		return NULL;
-
-	CDpreventremoval(self->ob_cdplayer);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_bestreadsize(cdplayerobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":bestreadsize"))
-		return NULL;
-
-	return PyInt_FromLong((long) CDbestreadsize(self->ob_cdplayer));
-}
-
-static PyObject *
-CD_close(cdplayerobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":close"))
-		return NULL;
-
-	if (!CDclose(self->ob_cdplayer)) {
-		PyErr_SetFromErrno(CdError); /* XXX - ??? */
-		return NULL;
-	}
-	self->ob_cdplayer = NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_eject(cdplayerobject *self, PyObject *args)
-{
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, ":eject"))
-		return NULL;
-
-	if (!CDeject(self->ob_cdplayer)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "eject failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyObject *
-CD_getstatus(cdplayerobject *self, PyObject *args)
-{
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, ":getstatus"))
-		return NULL;
-
-	if (!CDgetstatus(self->ob_cdplayer, &status)) {
-		PyErr_SetFromErrno(CdError); /* XXX - ??? */
-		return NULL;
-	}
-
-	return Py_BuildValue("(ii(iii)(iii)(iii)iiii)", status.state,
-		       status.track, status.min, status.sec, status.frame,
-		       status.abs_min, status.abs_sec, status.abs_frame,
-		       status.total_min, status.total_sec, status.total_frame,
-		       status.first, status.last, status.scsi_audio,
-		       status.cur_block);
-}
-	
-static PyObject *
-CD_gettrackinfo(cdplayerobject *self, PyObject *args)
-{
-	int track;
-	CDTRACKINFO info;
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, "i:gettrackinfo", &track))
-		return NULL;
-
-	if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "gettrackinfo failed");
-		return NULL;
-	}
-
-	return Py_BuildValue("((iii)(iii))",
-		       info.start_min, info.start_sec, info.start_frame,
-		       info.total_min, info.total_sec, info.total_frame);
-}
-	
-static PyObject *
-CD_msftoblock(cdplayerobject *self, PyObject *args)
-{
-	int min, sec, frame;
-
-	if (!PyArg_ParseTuple(args, "iii:msftoblock", &min, &sec, &frame))
-		return NULL;
-
-	return PyInt_FromLong((long) CDmsftoblock(self->ob_cdplayer,
-						min, sec, frame));
-}
-	
-static PyObject *
-CD_play(cdplayerobject *self, PyObject *args)
-{
-	int start, play;
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, "ii:play", &start, &play))
-		return NULL;
-
-	if (!CDplay(self->ob_cdplayer, start, play)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "play failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyObject *
-CD_playabs(cdplayerobject *self, PyObject *args)
-{
-	int min, sec, frame, play;
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, "iiii:playabs", &min, &sec, &frame, &play))
-		return NULL;
-
-	if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "playabs failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyObject *
-CD_playtrack(cdplayerobject *self, PyObject *args)
-{
-	int start, play;
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, "ii:playtrack", &start, &play))
-		return NULL;
-
-	if (!CDplaytrack(self->ob_cdplayer, start, play)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "playtrack failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyObject *
-CD_playtrackabs(cdplayerobject *self, PyObject *args)
-{
-	int track, min, sec, frame, play;
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, "iiiii:playtrackabs", &track, &min, &sec,
-			      &frame, &play))
-		return NULL;
-
-	if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "playtrackabs failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyObject *
-CD_readda(cdplayerobject *self, PyObject *args)
-{
-	int numframes, n;
-	PyObject *result;
-
-	if (!PyArg_ParseTuple(args, "i:readda", &numframes))
-		return NULL;
-
-	result = PyString_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
-	if (result == NULL)
-		return NULL;
-
-	n = CDreadda(self->ob_cdplayer,
-		       (CDFRAME *) PyString_AsString(result), numframes);
-	if (n == -1) {
-		Py_DECREF(result);
-		PyErr_SetFromErrno(CdError);
-		return NULL;
-	}
-	if (n < numframes)
-		_PyString_Resize(&result, n * sizeof(CDFRAME));
-
-	return result;
-}
-
-static PyObject *
-CD_seek(cdplayerobject *self, PyObject *args)
-{
-	int min, sec, frame;
-	long PyTryBlock;
-
-	if (!PyArg_ParseTuple(args, "iii:seek", &min, &sec, &frame))
-		return NULL;
-
-	PyTryBlock = CDseek(self->ob_cdplayer, min, sec, frame);
-	if (PyTryBlock == -1) {
-		PyErr_SetFromErrno(CdError);
-		return NULL;
-	}
-
-	return PyInt_FromLong(PyTryBlock);
-}
-	
-static PyObject *
-CD_seektrack(cdplayerobject *self, PyObject *args)
-{
-	int track;
-	long PyTryBlock;
-
-	if (!PyArg_ParseTuple(args, "i:seektrack", &track))
-		return NULL;
-
-	PyTryBlock = CDseektrack(self->ob_cdplayer, track);
-	if (PyTryBlock == -1) {
-		PyErr_SetFromErrno(CdError);
-		return NULL;
-	}
-
-	return PyInt_FromLong(PyTryBlock);
-}
-	
-static PyObject *
-CD_seekblock(cdplayerobject *self, PyObject *args)
-{
-	unsigned long PyTryBlock;
-
-	if (!PyArg_ParseTuple(args, "l:seekblock", &PyTryBlock))
-		return NULL;
-
-	PyTryBlock = CDseekblock(self->ob_cdplayer, PyTryBlock);
-	if (PyTryBlock == (unsigned long) -1) {
-		PyErr_SetFromErrno(CdError);
-		return NULL;
-	}
-
-	return PyInt_FromLong(PyTryBlock);
-}
-	
-static PyObject *
-CD_stop(cdplayerobject *self, PyObject *args)
-{
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, ":stop"))
-		return NULL;
-
-	if (!CDstop(self->ob_cdplayer)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "stop failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyObject *
-CD_togglepause(cdplayerobject *self, PyObject *args)
-{
-	CDSTATUS status;
-
-	if (!PyArg_ParseTuple(args, ":togglepause"))
-		return NULL;
-
-	if (!CDtogglepause(self->ob_cdplayer)) {
-		if (CDgetstatus(self->ob_cdplayer, &status) &&
-		    status.state == CD_NODISC)
-			PyErr_SetString(CdError, "no disc in player");
-		else
-			PyErr_SetString(CdError, "togglepause failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-	
-static PyMethodDef cdplayer_methods[] = {
-	{"allowremoval",	(PyCFunction)CD_allowremoval,	METH_VARARGS},
-	{"bestreadsize",	(PyCFunction)CD_bestreadsize,	METH_VARARGS},
-	{"close",		(PyCFunction)CD_close,		METH_VARARGS},
-	{"eject",		(PyCFunction)CD_eject,		METH_VARARGS},
-	{"getstatus",		(PyCFunction)CD_getstatus,		METH_VARARGS},
-	{"gettrackinfo",	(PyCFunction)CD_gettrackinfo,	METH_VARARGS},
-	{"msftoblock",		(PyCFunction)CD_msftoblock,		METH_VARARGS},
-	{"play",		(PyCFunction)CD_play,		METH_VARARGS},
-	{"playabs",		(PyCFunction)CD_playabs,		METH_VARARGS},
-	{"playtrack",		(PyCFunction)CD_playtrack,		METH_VARARGS},
-	{"playtrackabs",	(PyCFunction)CD_playtrackabs,	METH_VARARGS},
-	{"preventremoval",	(PyCFunction)CD_preventremoval,	METH_VARARGS},
-	{"readda",		(PyCFunction)CD_readda,		METH_VARARGS},
-	{"seek",		(PyCFunction)CD_seek,		METH_VARARGS},
-	{"seekblock",		(PyCFunction)CD_seekblock,		METH_VARARGS},
-	{"seektrack",		(PyCFunction)CD_seektrack,		METH_VARARGS},
-	{"stop",		(PyCFunction)CD_stop,		METH_VARARGS},
-	{"togglepause",		(PyCFunction)CD_togglepause,   	METH_VARARGS},
-	{NULL,			NULL} 		/* sentinel */
-};
-
-static void
-cdplayer_dealloc(cdplayerobject *self)
-{
-	if (self->ob_cdplayer != NULL)
-		CDclose(self->ob_cdplayer);
-	PyObject_Del(self);
-}
-
-static PyObject *
-cdplayer_getattr(cdplayerobject *self, char *name)
-{
-	if (self->ob_cdplayer == NULL) {
-		PyErr_SetString(PyExc_RuntimeError, "no player active");
-		return NULL;
-	}
-	return Py_FindMethod(cdplayer_methods, (PyObject *)self, name);
-}
-
-PyTypeObject CdPlayertype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,			/*ob_size*/
-	"cd.cdplayer",	/*tp_name*/
-	sizeof(cdplayerobject),	/*tp_size*/
-	0,			/*tp_itemsize*/
-	/* methods */
-	(destructor)cdplayer_dealloc, /*tp_dealloc*/
-	0,			/*tp_print*/
-	(getattrfunc)cdplayer_getattr, /*tp_getattr*/
-	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
-	0,			/*tp_repr*/
-};
-
-static PyObject *
-newcdplayerobject(CDPLAYER *cdp)
-{
-	cdplayerobject *p;
-
-	p = PyObject_New(cdplayerobject, &CdPlayertype);
-	if (p == NULL)
-		return NULL;
-	p->ob_cdplayer = cdp;
-	return (PyObject *) p;
-}
-
-static PyObject *
-CD_open(PyObject *self, PyObject *args)
-{
-	char *dev, *direction;
-	CDPLAYER *cdp;
-
-	/*
-	 * Variable number of args.
-	 * First defaults to "None", second defaults to "r".
-	 */
-	dev = NULL;
-	direction = "r";
-	if (!PyArg_ParseTuple(args, "|zs:open", &dev, &direction))
-		return NULL;
-
-	cdp = CDopen(dev, direction);
-	if (cdp == NULL) {
-		PyErr_SetFromErrno(CdError);
-		return NULL;
-	}
-
-	return newcdplayerobject(cdp);
-}
-
-typedef struct {
-	PyObject_HEAD
-	CDPARSER *ob_cdparser;
-	struct {
-		PyObject *ob_cdcallback;
-		PyObject *ob_cdcallbackarg;
-	} ob_cdcallbacks[NCALLBACKS];
-} cdparserobject;
-
-static void
-CD_callback(void *arg, CDDATATYPES type, void *data)
-{
-	PyObject *result, *args, *v = NULL;
-	char *p;
-	int i;
-	cdparserobject *self;
-
-	self = (cdparserobject *) arg;
-	args = PyTuple_New(3);
-	if (args == NULL)
-		return;
-	Py_INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
-	PyTuple_SetItem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg);
-	PyTuple_SetItem(args, 1, PyInt_FromLong((long) type));
-	switch (type) {
-	case cd_audio:
-		v = PyString_FromStringAndSize(data, CDDA_DATASIZE);
-		break;
-	case cd_pnum:
-	case cd_index:
-		v = PyInt_FromLong(((CDPROGNUM *) data)->value);
-		break;
-	case cd_ptime:
-	case cd_atime:
-#define ptr ((struct cdtimecode *) data)
-		v = Py_BuildValue("(iii)",
-			    ptr->mhi * 10 + ptr->mlo,
-			    ptr->shi * 10 + ptr->slo,
-			    ptr->fhi * 10 + ptr->flo);
-#undef ptr
-		break;
-	case cd_catalog:
-		v = PyString_FromStringAndSize(NULL, 13);
-		p = PyString_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);
-		CDsbtoa(p, ptr->country, 2);
-		p += 2;
-		CDsbtoa(p, ptr->owner, 3);
-		p += 3;
-		*p++ = ptr->year[0] + '0';
-		*p++ = ptr->year[1] + '0';
-		*p++ = ptr->serial[0] + '0';
-		*p++ = ptr->serial[1] + '0';
-		*p++ = ptr->serial[2] + '0';
-		*p++ = ptr->serial[3] + '0';
-		*p++ = ptr->serial[4] + '0';
-#undef ptr
-		break;
-	case cd_control:
-		v = PyInt_FromLong((long) *((unchar *) data));
-		break;
-	}
-	PyTuple_SetItem(args, 2, v);
-	if (PyErr_Occurred()) {
-		Py_DECREF(args);
-		return;
-	}
-	
-	result = PyEval_CallObject(self->ob_cdcallbacks[type].ob_cdcallback,
-				   args);
-	Py_DECREF(args);
-	Py_XDECREF(result);
-}
-
-static PyObject *
-CD_deleteparser(cdparserobject *self, PyObject *args)
-{
-	int i;
-
-	if (!PyArg_ParseTuple(args, ":deleteparser"))
-		return NULL;
-
-	CDdeleteparser(self->ob_cdparser);
-	self->ob_cdparser = NULL;
-
-	/* no sense in keeping the callbacks, so remove them */
-	for (i = 0; i < NCALLBACKS; i++) {
-		Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
-		self->ob_cdcallbacks[i].ob_cdcallback = NULL;
-		Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
-		self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_parseframe(cdparserobject *self, PyObject *args)
-{
-	char *cdfp;
-	int length;
-	CDFRAME *p;
-
-	if (!PyArg_ParseTuple(args, "s#:parseframe", &cdfp, &length))
-		return NULL;
-
-	if (length % sizeof(CDFRAME) != 0) {
-		PyErr_SetString(PyExc_TypeError, "bad length");
-		return NULL;
-	}
-
-	p = (CDFRAME *) cdfp;
-	while (length > 0) {
-		CDparseframe(self->ob_cdparser, p);
-		length -= sizeof(CDFRAME);
-		p++;
-		if (PyErr_Occurred())
-			return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_removecallback(cdparserobject *self, PyObject *args)
-{
-	int type;
-
-	if (!PyArg_ParseTuple(args, "i:removecallback", &type))
-		return NULL;
-
-	if (type < 0 || type >= NCALLBACKS) {
-		PyErr_SetString(PyExc_TypeError, "bad type");
-		return NULL;
-	}
-
-	CDremovecallback(self->ob_cdparser, (CDDATATYPES) type);
-
-	Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
-	self->ob_cdcallbacks[type].ob_cdcallback = NULL;
-
-	Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
-	self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_resetparser(cdparserobject *self, PyObject *args)
-{
-	if (!PyArg_ParseTuple(args, ":resetparser"))
-		return NULL;
-
-	CDresetparser(self->ob_cdparser);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-CD_addcallback(cdparserobject *self, PyObject *args)
-{
-	int type;
-	PyObject *func, *funcarg;
-
-	/* XXX - more work here */
-	if (!PyArg_ParseTuple(args, "iOO:addcallback", &type, &func, &funcarg))
-		return NULL;
-
-	if (type < 0 || type >= NCALLBACKS) {
-		PyErr_SetString(PyExc_TypeError, "argument out of range");
-		return NULL;
-	}
-
-#ifdef CDsetcallback
-	CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
-		      (void *) self);
-#else
-	CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
-		      (void *) self);
-#endif
-	Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
-	Py_INCREF(func);
-	self->ob_cdcallbacks[type].ob_cdcallback = func;
-	Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
-	Py_INCREF(funcarg);
-	self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg;
-
-/*
-	if (type == cd_audio) {
-		sigfpe_[_UNDERFL].repls = _ZERO;
-		handle_sigfpes(_ON, _EN_UNDERFL, NULL,
-		                        _ABORT_ON_ERROR, NULL);
-	}
-*/
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyMethodDef cdparser_methods[] = {
-	{"addcallback",		(PyCFunction)CD_addcallback,   	METH_VARARGS},
-	{"deleteparser",	(PyCFunction)CD_deleteparser,	METH_VARARGS},
-	{"parseframe",		(PyCFunction)CD_parseframe,	METH_VARARGS},
-	{"removecallback",	(PyCFunction)CD_removecallback,	METH_VARARGS},
-	{"resetparser",		(PyCFunction)CD_resetparser,	METH_VARARGS},
-		                                /* backward compatibility */
-	{"setcallback",		(PyCFunction)CD_addcallback,   	METH_VARARGS},
-	{NULL,			NULL} 		/* sentinel */
-};
-
-static void
-cdparser_dealloc(cdparserobject *self)
-{
-	int i;
-
-	for (i = 0; i < NCALLBACKS; i++) {
-		Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
-		self->ob_cdcallbacks[i].ob_cdcallback = NULL;
-		Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
-		self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
-	}
-	CDdeleteparser(self->ob_cdparser);
-	PyObject_Del(self);
-}
-
-static PyObject *
-cdparser_getattr(cdparserobject *self, char *name)
-{
-	if (self->ob_cdparser == NULL) {
-		PyErr_SetString(PyExc_RuntimeError, "no parser active");
-		return NULL;
-	}
-
-	return Py_FindMethod(cdparser_methods, (PyObject *)self, name);
-}
-
-PyTypeObject CdParsertype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,			/*ob_size*/
-	"cd.cdparser",		/*tp_name*/
-	sizeof(cdparserobject),	/*tp_size*/
-	0,			/*tp_itemsize*/
-	/* methods */
-	(destructor)cdparser_dealloc, /*tp_dealloc*/
-	0,			/*tp_print*/
-	(getattrfunc)cdparser_getattr, /*tp_getattr*/
-	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
-	0,			/*tp_repr*/
-};
-
-static PyObject *
-newcdparserobject(CDPARSER *cdp)
-{
-	cdparserobject *p;
-	int i;
-
-	p = PyObject_New(cdparserobject, &CdParsertype);
-	if (p == NULL)
-		return NULL;
-	p->ob_cdparser = cdp;
-	for (i = 0; i < NCALLBACKS; i++) {
-		p->ob_cdcallbacks[i].ob_cdcallback = NULL;
-		p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
-	}
-	return (PyObject *) p;
-}
-
-static PyObject *
-CD_createparser(PyObject *self, PyObject *args)
-{
-	CDPARSER *cdp;
-
-	if (!PyArg_ParseTuple(args, ":createparser"))
-		return NULL;
-	cdp = CDcreateparser();
-	if (cdp == NULL) {
-		PyErr_SetString(CdError, "createparser failed");
-		return NULL;
-	}
-
-	return newcdparserobject(cdp);
-}
-
-static PyObject *
-CD_msftoframe(PyObject *self, PyObject *args)
-{
-	int min, sec, frame;
-
-	if (!PyArg_ParseTuple(args, "iii:msftoframe", &min, &sec, &frame))
-		return NULL;
-
-	return PyInt_FromLong((long) CDmsftoframe(min, sec, frame));
-}
-	
-static PyMethodDef CD_methods[] = {
-	{"open",		(PyCFunction)CD_open,		METH_VARARGS},
-	{"createparser",	(PyCFunction)CD_createparser,	METH_VARARGS},
-	{"msftoframe",		(PyCFunction)CD_msftoframe,	METH_VARARGS},
-	{NULL,		NULL}	/* Sentinel */
-};
-
-void
-initcd(void)
-{
-	PyObject *m, *d;
-
-	m = Py_InitModule("cd", CD_methods);
-	if (m == NULL)
-		return;
-	d = PyModule_GetDict(m);
-
-	CdError = PyErr_NewException("cd.error", NULL, NULL);
-	PyDict_SetItemString(d, "error", CdError);
-
-	/* Identifiers for the different types of callbacks from the parser */
-	PyDict_SetItemString(d, "audio", PyInt_FromLong((long) cd_audio));
-	PyDict_SetItemString(d, "pnum", PyInt_FromLong((long) cd_pnum));
-	PyDict_SetItemString(d, "index", PyInt_FromLong((long) cd_index));
-	PyDict_SetItemString(d, "ptime", PyInt_FromLong((long) cd_ptime));
-	PyDict_SetItemString(d, "atime", PyInt_FromLong((long) cd_atime));
-	PyDict_SetItemString(d, "catalog", PyInt_FromLong((long) cd_catalog));
-	PyDict_SetItemString(d, "ident", PyInt_FromLong((long) cd_ident));
-	PyDict_SetItemString(d, "control", PyInt_FromLong((long) cd_control));
-
-	/* Block size information for digital audio data */
-	PyDict_SetItemString(d, "DATASIZE",
-			   PyInt_FromLong((long) CDDA_DATASIZE));
-	PyDict_SetItemString(d, "BLOCKSIZE",
-			   PyInt_FromLong((long) CDDA_BLOCKSIZE));
-
-	/* Possible states for the cd player */
-	PyDict_SetItemString(d, "ERROR", PyInt_FromLong((long) CD_ERROR));
-	PyDict_SetItemString(d, "NODISC", PyInt_FromLong((long) CD_NODISC));
-	PyDict_SetItemString(d, "READY", PyInt_FromLong((long) CD_READY));
-	PyDict_SetItemString(d, "PLAYING", PyInt_FromLong((long) CD_PLAYING));
-	PyDict_SetItemString(d, "PAUSED", PyInt_FromLong((long) CD_PAUSED));
-	PyDict_SetItemString(d, "STILL", PyInt_FromLong((long) CD_STILL));
-#ifdef CD_CDROM			/* only newer versions of the library */
-	PyDict_SetItemString(d, "CDROM", PyInt_FromLong((long) CD_CDROM));
-#endif
-}

Deleted: /python/branches/p3yk-noslice/Modules/cgen.py
==============================================================================
--- /python/branches/p3yk-noslice/Modules/cgen.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,520 +0,0 @@
-########################################################################
-# Copyright (c) 2000, BeOpen.com.
-# Copyright (c) 1995-2000, Corporation for National Research Initiatives.
-# Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
-# All rights reserved.
-#
-# See the file "Misc/COPYRIGHT" for information on usage and
-# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-########################################################################
-
-# Python script to parse cstubs file for gl and generate C stubs.
-# usage: python cgen.py <cstubs >glmodule.c
-#
-# NOTE: You  must first make a python binary without the "GL" option
-#       before you can run this, when building Python for the first time.
-#       See comments in the Makefile.
-#
-# XXX BUG return arrays generate wrong code
-# XXX need to change error returns into gotos to free mallocked arrays
-
-
-import string
-import sys
-
-
-# Function to print to stderr
-#
-def err(*args):
-    savestdout = sys.stdout
-    try:
-        sys.stdout = sys.stderr
-        for i in args:
-            print i,
-        print
-    finally:
-        sys.stdout = savestdout
-
-
-# The set of digits that form a number
-#
-digits = '0123456789'
-
-
-# Function to extract a string of digits from the front of the string.
-# Returns the leading string of digits and the remaining string.
-# If no number is found, returns '' and the original string.
-#
-def getnum(s):
-    n = ''
-    while s and s[0] in digits:
-        n = n + s[0]
-        s = s[1:]
-    return n, s
-
-
-# Function to check if a string is a number
-#
-def isnum(s):
-    if not s: return False
-    for c in s:
-        if not c in digits: return False
-    return True
-
-
-# Allowed function return types
-#
-return_types = ['void', 'short', 'long']
-
-
-# Allowed function argument types
-#
-arg_types = ['char', 'string', 'short', 'u_short', 'float', 'long', 'double']
-
-
-# Need to classify arguments as follows
-#       simple input variable
-#       simple output variable
-#       input array
-#       output array
-#       input giving size of some array
-#
-# Array dimensions can be specified as follows
-#       constant
-#       argN
-#       constant * argN
-#       retval
-#       constant * retval
-#
-# The dimensions given as constants * something are really
-# arrays of points where points are 2- 3- or 4-tuples
-#
-# We have to consider three lists:
-#       python input arguments
-#       C stub arguments (in & out)
-#       python output arguments (really return values)
-#
-# There is a mapping from python input arguments to the input arguments
-# of the C stub, and a further mapping from C stub arguments to the
-# python return values
-
-
-# Exception raised by checkarg() and generate()
-#
-arg_error = 'bad arg'
-
-
-# Function to check one argument.
-# Arguments: the type and the arg "name" (really mode plus subscript).
-# Raises arg_error if something's wrong.
-# Return type, mode, factor, rest of subscript; factor and rest may be empty.
-#
-def checkarg(type, arg):
-    #
-    # Turn "char *x" into "string x".
-    #
-    if type == 'char' and arg[0] == '*':
-        type = 'string'
-        arg = arg[1:]
-    #
-    # Check that the type is supported.
-    #
-    if type not in arg_types:
-        raise arg_error, ('bad type', type)
-    if type[:2] == 'u_':
-        type = 'unsigned ' + type[2:]
-    #
-    # Split it in the mode (first character) and the rest.
-    #
-    mode, rest = arg[:1], arg[1:]
-    #
-    # The mode must be 's' for send (= input) or 'r' for return argument.
-    #
-    if mode not in ('r', 's'):
-        raise arg_error, ('bad arg mode', mode)
-    #
-    # Is it a simple argument: if so, we are done.
-    #
-    if not rest:
-        return type, mode, '', ''
-    #
-    # Not a simple argument; must be an array.
-    # The 'rest' must be a subscript enclosed in [ and ].
-    # The subscript must be one of the following forms,
-    # otherwise we don't handle it (where N is a number):
-    #       N
-    #       argN
-    #       retval
-    #       N*argN
-    #       N*retval
-    #
-    if rest[:1] != '[' or rest[-1:] != ']':
-        raise arg_error, ('subscript expected', rest)
-    sub = rest[1:-1]
-    #
-    # Is there a leading number?
-    #
-    num, sub = getnum(sub)
-    if num:
-        # There is a leading number
-        if not sub:
-            # The subscript is just a number
-            return type, mode, num, ''
-        if sub[:1] == '*':
-            # There is a factor prefix
-            sub = sub[1:]
-        else:
-            raise arg_error, ('\'*\' expected', sub)
-    if sub == 'retval':
-        # size is retval -- must be a reply argument
-        if mode != 'r':
-            raise arg_error, ('non-r mode with [retval]', mode)
-    elif not isnum(sub) and (sub[:3] != 'arg' or not isnum(sub[3:])):
-        raise arg_error, ('bad subscript', sub)
-    #
-    return type, mode, num, sub
-
-
-# List of functions for which we have generated stubs
-#
-functions = []
-
-
-# Generate the stub for the given function, using the database of argument
-# information build by successive calls to checkarg()
-#
-def generate(type, func, database):
-    #
-    # Check that we can handle this case:
-    # no variable size reply arrays yet
-    #
-    n_in_args = 0
-    n_out_args = 0
-    #
-    for a_type, a_mode, a_factor, a_sub in database:
-        if a_mode == 's':
-            n_in_args = n_in_args + 1
-        elif a_mode == 'r':
-            n_out_args = n_out_args + 1
-        else:
-            # Can't happen
-            raise arg_error, ('bad a_mode', a_mode)
-        if (a_mode == 'r' and a_sub) or a_sub == 'retval':
-            err('Function', func, 'too complicated:',
-                a_type, a_mode, a_factor, a_sub)
-            print '/* XXX Too complicated to generate code for */'
-            return
-    #
-    functions.append(func)
-    #
-    # Stub header
-    #
-    print
-    print 'static PyObject *'
-    print 'gl_' + func + '(self, args)'
-    print '\tPyObject *self;'
-    print '\tPyObject *args;'
-    print '{'
-    #
-    # Declare return value if any
-    #
-    if type != 'void':
-        print '\t' + type, 'retval;'
-    #
-    # Declare arguments
-    #
-    for i in range(len(database)):
-        a_type, a_mode, a_factor, a_sub = database[i]
-        print '\t' + a_type,
-        brac = ket = ''
-        if a_sub and not isnum(a_sub):
-            if a_factor:
-                brac = '('
-                ket = ')'
-            print brac + '*',
-        print 'arg' + repr(i+1) + ket,
-        if a_sub and isnum(a_sub):
-            print '[', a_sub, ']',
-        if a_factor:
-            print '[', a_factor, ']',
-        print ';'
-    #
-    # Find input arguments derived from array sizes
-    #
-    for i in range(len(database)):
-        a_type, a_mode, a_factor, a_sub = database[i]
-        if a_mode == 's' and a_sub[:3] == 'arg' and isnum(a_sub[3:]):
-            # Sending a variable-length array
-            n = eval(a_sub[3:])
-            if 1 <= n <= len(database):
-                b_type, b_mode, b_factor, b_sub = database[n-1]
-                if b_mode == 's':
-                    database[n-1] = b_type, 'i', a_factor, repr(i)
-                    n_in_args = n_in_args - 1
-    #
-    # Assign argument positions in the Python argument list
-    #
-    in_pos = []
-    i_in = 0
-    for i in range(len(database)):
-        a_type, a_mode, a_factor, a_sub = database[i]
-        if a_mode == 's':
-            in_pos.append(i_in)
-            i_in = i_in + 1
-        else:
-            in_pos.append(-1)
-    #
-    # Get input arguments
-    #
-    for i in range(len(database)):
-        a_type, a_mode, a_factor, a_sub = database[i]
-        if a_type[:9] == 'unsigned ':
-            xtype = a_type[9:]
-        else:
-            xtype = a_type
-        if a_mode == 'i':
-            #
-            # Implicit argument;
-            # a_factor is divisor if present,
-            # a_sub indicates which arg (`database index`)
-            #
-            j = eval(a_sub)
-            print '\tif',
-            print '(!geti' + xtype + 'arraysize(args,',
-            print repr(n_in_args) + ',',
-            print repr(in_pos[j]) + ',',
-            if xtype != a_type:
-                print '('+xtype+' *)',
-            print '&arg' + repr(i+1) + '))'
-            print '\t\treturn NULL;'
-            if a_factor:
-                print '\targ' + repr(i+1),
-                print '= arg' + repr(i+1),
-                print '/', a_factor + ';'
-        elif a_mode == 's':
-            if a_sub and not isnum(a_sub):
-                # Allocate memory for varsize array
-                print '\tif ((arg' + repr(i+1), '=',
-                if a_factor:
-                    print '('+a_type+'(*)['+a_factor+'])',
-                print 'PyMem_NEW(' + a_type, ',',
-                if a_factor:
-                    print a_factor, '*',
-                print a_sub, ')) == NULL)'
-                print '\t\treturn PyErr_NoMemory();'
-            print '\tif',
-            if a_factor or a_sub: # Get a fixed-size array array
-                print '(!geti' + xtype + 'array(args,',
-                print repr(n_in_args) + ',',
-                print repr(in_pos[i]) + ',',
-                if a_factor: print a_factor,
-                if a_factor and a_sub: print '*',
-                if a_sub: print a_sub,
-                print ',',
-                if (a_sub and a_factor) or xtype != a_type:
-                    print '('+xtype+' *)',
-                print 'arg' + repr(i+1) + '))'
-            else: # Get a simple variable
-                print '(!geti' + xtype + 'arg(args,',
-                print repr(n_in_args) + ',',
-                print repr(in_pos[i]) + ',',
-                if xtype != a_type:
-                    print '('+xtype+' *)',
-                print '&arg' + repr(i+1) + '))'
-            print '\t\treturn NULL;'
-    #
-    # Begin of function call
-    #
-    if type != 'void':
-        print '\tretval =', func + '(',
-    else:
-        print '\t' + func + '(',
-    #
-    # Argument list
-    #
-    for i in range(len(database)):
-        if i > 0: print ',',
-        a_type, a_mode, a_factor, a_sub = database[i]
-        if a_mode == 'r' and not a_factor:
-            print '&',
-        print 'arg' + repr(i+1),
-    #
-    # End of function call
-    #
-    print ');'
-    #
-    # Free varsize arrays
-    #
-    for i in range(len(database)):
-        a_type, a_mode, a_factor, a_sub = database[i]
-        if a_mode == 's' and a_sub and not isnum(a_sub):
-            print '\tPyMem_DEL(arg' + repr(i+1) + ');'
-    #
-    # Return
-    #
-    if n_out_args:
-        #
-        # Multiple return values -- construct a tuple
-        #
-        if type != 'void':
-            n_out_args = n_out_args + 1
-        if n_out_args == 1:
-            for i in range(len(database)):
-                a_type, a_mode, a_factor, a_sub = database[i]
-                if a_mode == 'r':
-                    break
-            else:
-                raise arg_error, 'expected r arg not found'
-            print '\treturn',
-            print mkobject(a_type, 'arg' + repr(i+1)) + ';'
-        else:
-            print '\t{ PyObject *v = PyTuple_New(',
-            print n_out_args, ');'
-            print '\t  if (v == NULL) return NULL;'
-            i_out = 0
-            if type != 'void':
-                print '\t  PyTuple_SetItem(v,',
-                print repr(i_out) + ',',
-                print mkobject(type, 'retval') + ');'
-                i_out = i_out + 1
-            for i in range(len(database)):
-                a_type, a_mode, a_factor, a_sub = database[i]
-                if a_mode == 'r':
-                    print '\t  PyTuple_SetItem(v,',
-                    print repr(i_out) + ',',
-                    s = mkobject(a_type, 'arg' + repr(i+1))
-                    print s + ');'
-                    i_out = i_out + 1
-            print '\t  return v;'
-            print '\t}'
-    else:
-        #
-        # Simple function return
-        # Return None or return value
-        #
-        if type == 'void':
-            print '\tPy_INCREF(Py_None);'
-            print '\treturn Py_None;'
-        else:
-            print '\treturn', mkobject(type, 'retval') + ';'
-    #
-    # Stub body closing brace
-    #
-    print '}'
-
-
-# Subroutine to return a function call to mknew<type>object(<arg>)
-#
-def mkobject(type, arg):
-    if type[:9] == 'unsigned ':
-        type = type[9:]
-        return 'mknew' + type + 'object((' + type + ') ' + arg + ')'
-    return 'mknew' + type + 'object(' + arg + ')'
-
-
-defined_archs = []
-
-# usage: cgen [ -Dmach ... ] [ file ]
-for arg in sys.argv[1:]:
-    if arg[:2] == '-D':
-        defined_archs.append(arg[2:])
-    else:
-        # Open optional file argument
-        sys.stdin = open(arg, 'r')
-
-
-# Input line number
-lno = 0
-
-
-# Input is divided in two parts, separated by a line containing '%%'.
-#       <part1>         -- literally copied to stdout
-#       <part2>         -- stub definitions
-
-# Variable indicating the current input part.
-#
-part = 1
-
-# Main loop over the input
-#
-while 1:
-    try:
-        line = raw_input()
-    except EOFError:
-        break
-    #
-    lno = lno+1
-    words = string.split(line)
-    #
-    if part == 1:
-        #
-        # In part 1, copy everything literally
-        # except look for a line of just '%%'
-        #
-        if words == ['%%']:
-            part = part + 1
-        else:
-            #
-            # Look for names of manually written
-            # stubs: a single percent followed by the name
-            # of the function in Python.
-            # The stub name is derived by prefixing 'gl_'.
-            #
-            if words and words[0][0] == '%':
-                func = words[0][1:]
-                if (not func) and words[1:]:
-                    func = words[1]
-                if func:
-                    functions.append(func)
-            else:
-                print line
-        continue
-    if not words:
-        continue                # skip empty line
-    elif words[0] == 'if':
-        # if XXX rest
-        # if !XXX rest
-        if words[1][0] == '!':
-            if words[1][1:] in defined_archs:
-                continue
-        elif words[1] not in defined_archs:
-            continue
-        words = words[2:]
-    if words[0] == '#include':
-        print line
-    elif words[0][:1] == '#':
-        pass                    # ignore comment
-    elif words[0] not in return_types:
-        err('Line', lno, ': bad return type :', words[0])
-    elif len(words) < 2:
-        err('Line', lno, ': no funcname :', line)
-    else:
-        if len(words) % 2 != 0:
-            err('Line', lno, ': odd argument list :', words[2:])
-        else:
-            database = []
-            try:
-                for i in range(2, len(words), 2):
-                    x = checkarg(words[i], words[i+1])
-                    database.append(x)
-                print
-                print '/*',
-                for w in words: print w,
-                print '*/'
-                generate(words[0], words[1], database)
-            except arg_error, msg:
-                err('Line', lno, ':', msg)
-
-
-print
-print 'static struct PyMethodDef gl_methods[] = {'
-for func in functions:
-    print '\t{"' + func + '", gl_' + func + '},'
-print '\t{NULL, NULL} /* Sentinel */'
-print '};'
-print
-print 'void'
-print 'initgl()'
-print '{'
-print '\t(void) Py_InitModule("gl", gl_methods);'
-print '}'

Deleted: /python/branches/p3yk-noslice/Modules/cgensupport.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/cgensupport.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,310 +0,0 @@
-
-/* Functions used by cgen output */
-
-#include "Python.h"
-#include "cgensupport.h"
-
-
-/* Functions to extract arguments.
-   These needs to know the total number of arguments supplied,
-   since the argument list is a tuple only of there is more than
-   one argument. */
-
-int
-PyArg_GetObject(register PyObject *args, int nargs, int i, PyObject **p_arg)
-{
-	if (nargs != 1) {
-		if (args == NULL || !PyTuple_Check(args) ||
-				nargs != PyTuple_Size(args) ||
-				i < 0 || i >= nargs) {
-			return PyErr_BadArgument();
-		}
-		else {
-			args = PyTuple_GetItem(args, i);
-		}
-	}
-	if (args == NULL) {
-		return PyErr_BadArgument();
-	}
-	*p_arg = args;
-	return 1;
-}
-
-int
-PyArg_GetLong(register PyObject *args, int nargs, int i, long *p_arg)
-{
-	if (nargs != 1) {
-		if (args == NULL || !PyTuple_Check(args) ||
-				nargs != PyTuple_Size(args) ||
-				i < 0 || i >= nargs) {
-			return PyErr_BadArgument();
-		}
-		args = PyTuple_GetItem(args, i);
-	}
-	if (args == NULL || !PyInt_Check(args)) {
-		return PyErr_BadArgument();
-	}
-	*p_arg = PyInt_AsLong(args);
-	return 1;
-}
-
-int
-PyArg_GetShort(register PyObject *args, int nargs, int i, short *p_arg)
-{
-	long x;
-	if (!PyArg_GetLong(args, nargs, i, &x))
-		return 0;
-	*p_arg = (short) x;
-	return 1;
-}
-
-static int
-extractdouble(register PyObject *v, double *p_arg)
-{
-	if (v == NULL) {
-		/* Fall through to error return at end of function */
-	}
-	else if (PyFloat_Check(v)) {
-		*p_arg = PyFloat_AS_DOUBLE((PyFloatObject *)v);
-		return 1;
-	}
-	else if (PyInt_Check(v)) {
-		*p_arg = PyInt_AS_LONG((PyIntObject *)v);
-		return 1;
-	}
-	else if (PyLong_Check(v)) {
-		*p_arg = PyLong_AsDouble(v);
-		return 1;
-	}
-	return PyErr_BadArgument();
-}
-
-static int
-extractfloat(register PyObject *v, float *p_arg)
-{
-	if (v == NULL) {
-		/* Fall through to error return at end of function */
-	}
-	else if (PyFloat_Check(v)) {
-		*p_arg = (float) PyFloat_AS_DOUBLE((PyFloatObject *)v);
-		return 1;
-	}
-	else if (PyInt_Check(v)) {
-		*p_arg = (float) PyInt_AS_LONG((PyIntObject *)v);
-		return 1;
-	}
-	else if (PyLong_Check(v)) {
-		*p_arg = (float) PyLong_AsDouble(v);
-		return 1;
-	}
-	return PyErr_BadArgument();
-}
-
-int
-PyArg_GetFloat(register PyObject *args, int nargs, int i, float *p_arg)
-{
-	PyObject *v;
-	float x;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (!extractfloat(v, &x))
-		return 0;
-	*p_arg = x;
-	return 1;
-}
-
-int
-PyArg_GetString(PyObject *args, int nargs, int i, string *p_arg)
-{
-	PyObject *v;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (!PyString_Check(v)) {
-		return PyErr_BadArgument();
-	}
-	*p_arg = PyString_AsString(v);
-	return 1;
-}
-
-int
-PyArg_GetChar(PyObject *args, int nargs, int i, char *p_arg)
-{
-	string x;
-	if (!PyArg_GetString(args, nargs, i, &x))
-		return 0;
-	if (x[0] == '\0' || x[1] != '\0') {
-		/* Not exactly one char */
-		return PyErr_BadArgument();
-	}
-	*p_arg = x[0];
-	return 1;
-}
-
-int
-PyArg_GetLongArraySize(PyObject *args, int nargs, int i, long *p_arg)
-{
-	PyObject *v;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (PyTuple_Check(v)) {
-		*p_arg = PyTuple_Size(v);
-		return 1;
-	}
-	if (PyList_Check(v)) {
-		*p_arg = PyList_Size(v);
-		return 1;
-	}
-	return PyErr_BadArgument();
-}
-
-int
-PyArg_GetShortArraySize(PyObject *args, int nargs, int i, short *p_arg)
-{
-	long x;
-	if (!PyArg_GetLongArraySize(args, nargs, i, &x))
-		return 0;
-	*p_arg = (short) x;
-	return 1;
-}
-
-/* XXX The following four are too similar.  Should share more code. */
-
-int
-PyArg_GetLongArray(PyObject *args, int nargs, int i, int n, long *p_arg)
-{
-	PyObject *v, *w;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (PyTuple_Check(v)) {
-		if (PyTuple_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyTuple_GetItem(v, i);
-			if (!PyInt_Check(w)) {
-				return PyErr_BadArgument();
-			}
-			p_arg[i] = PyInt_AsLong(w);
-		}
-		return 1;
-	}
-	else if (PyList_Check(v)) {
-		if (PyList_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyList_GetItem(v, i);
-			if (!PyInt_Check(w)) {
-				return PyErr_BadArgument();
-			}
-			p_arg[i] = PyInt_AsLong(w);
-		}
-		return 1;
-	}
-	else {
-		return PyErr_BadArgument();
-	}
-}
-
-int
-PyArg_GetShortArray(PyObject *args, int nargs, int i, int n, short *p_arg)
-{
-	PyObject *v, *w;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (PyTuple_Check(v)) {
-		if (PyTuple_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyTuple_GetItem(v, i);
-			if (!PyInt_Check(w)) {
-				return PyErr_BadArgument();
-			}
-			p_arg[i] = (short) PyInt_AsLong(w);
-		}
-		return 1;
-	}
-	else if (PyList_Check(v)) {
-		if (PyList_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyList_GetItem(v, i);
-			if (!PyInt_Check(w)) {
-				return PyErr_BadArgument();
-			}
-			p_arg[i] = (short) PyInt_AsLong(w);
-		}
-		return 1;
-	}
-	else {
-		return PyErr_BadArgument();
-	}
-}
-
-int
-PyArg_GetDoubleArray(PyObject *args, int nargs, int i, int n, double *p_arg)
-{
-	PyObject *v, *w;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (PyTuple_Check(v)) {
-		if (PyTuple_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyTuple_GetItem(v, i);
-			if (!extractdouble(w, &p_arg[i]))
-				return 0;
-		}
-		return 1;
-	}
-	else if (PyList_Check(v)) {
-		if (PyList_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyList_GetItem(v, i);
-			if (!extractdouble(w, &p_arg[i]))
-				return 0;
-		}
-		return 1;
-	}
-	else {
-		return PyErr_BadArgument();
-	}
-}
-
-int
-PyArg_GetFloatArray(PyObject *args, int nargs, int i, int n, float *p_arg)
-{
-	PyObject *v, *w;
-	if (!PyArg_GetObject(args, nargs, i, &v))
-		return 0;
-	if (PyTuple_Check(v)) {
-		if (PyTuple_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyTuple_GetItem(v, i);
-			if (!extractfloat(w, &p_arg[i]))
-				return 0;
-		}
-		return 1;
-	}
-	else if (PyList_Check(v)) {
-		if (PyList_Size(v) != n) {
-			return PyErr_BadArgument();
-		}
-		for (i = 0; i < n; i++) {
-			w = PyList_GetItem(v, i);
-			if (!extractfloat(w, &p_arg[i]))
-				return 0;
-		}
-		return 1;
-	}
-	else {
-		return PyErr_BadArgument();
-	}
-}

Deleted: /python/branches/p3yk-noslice/Modules/cgensupport.h
==============================================================================
--- /python/branches/p3yk-noslice/Modules/cgensupport.h	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,64 +0,0 @@
-#ifndef Py_CGENSUPPORT_H
-#define Py_CGENSUPPORT_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Definitions used by cgen output */
-
-/* XXX This file is obsolete.  It is *only* used by glmodule.c. */
-
-typedef char *string;
-
-#define mknewlongobject(x) PyInt_FromLong(x)
-#define mknewshortobject(x) PyInt_FromLong((long)x)
-#define mknewfloatobject(x) PyFloat_FromDouble(x)
-#define mknewcharobject(ch) Py_BuildValue("c", ch)
-
-#define getichararg PyArg_GetChar
-#define getidoublearray PyArg_GetDoubleArray
-#define getifloatarg PyArg_GetFloat
-#define getifloatarray PyArg_GetFloatArray
-#define getilongarg PyArg_GetLong
-#define getilongarray PyArg_GetLongArray
-#define getilongarraysize PyArg_GetLongArraySize
-#define getiobjectarg PyArg_GetObject
-#define getishortarg PyArg_GetShort
-#define getishortarray PyArg_GetShortArray
-#define getishortarraysize PyArg_GetShortArraySize
-#define getistringarg PyArg_GetString
-
-extern int PyArg_GetObject(PyObject *args, int nargs,
-			   int i, PyObject **p_a);
-extern int PyArg_GetLong(PyObject *args, int nargs,
-			 int i, long *p_a);
-extern int PyArg_GetShort(PyObject *args, int nargs,
-			  int i, short *p_a);
-extern int PyArg_GetFloat(PyObject *args, int nargs,
-			  int i, float *p_a);
-extern int PyArg_GetString(PyObject *args, int nargs,
-			   int i, string *p_a);
-extern int PyArg_GetChar(PyObject *args, int nargs,
-			 int i, char *p_a);
-extern int PyArg_GetLongArray(PyObject *args, int nargs,
-			    int i, int n, long *p_a);
-extern int PyArg_GetShortArray(PyObject *args, int nargs,
-			    int i, int n, short *p_a);
-extern int PyArg_GetDoubleArray(PyObject *args, int nargs,
-				int i, int n, double *p_a);
-extern int PyArg_GetFloatArray(PyObject *args, int nargs,
-			       int i, int n, float *p_a);
-extern int PyArg_GetLongArraySize(PyObject *args, int nargs,
-				  int i, long *p_a);
-extern int PyArg_GetShortArraySize(PyObject *args, int nargs,
-				int i, short *p_a);
-extern int PyArg_GetDoubleArraySize(PyObject *args, int nargs,
-				    int i, double *p_a);
-extern int PyArg_GetFloatArraySize(PyObject *args, int nargs,
-				   int i, float *p_a);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !Py_CGENSUPPORT_H */

Modified: python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c	(original)
+++ python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c	Wed Jul 11 15:40:56 2007
@@ -1214,6 +1214,8 @@
 	cres = NULL;
 
 	for (;;) {
+		int endoffile;
+
 		if (sizehint < 0)
 			cres = PyObject_CallMethod(self->stream,
 					(char *)method, NULL);
@@ -1230,6 +1232,8 @@
 			goto errorexit;
 		}
 
+		endoffile = (PyString_GET_SIZE(cres) == 0);
+
 		if (self->pendingsize > 0) {
 			PyObject *ctr;
 			char *ctrdata;
@@ -1257,7 +1261,7 @@
 				(MultibyteStatefulDecoderContext *)self, &buf))
 			goto errorexit;
 
-		if (rsize == 0 || sizehint < 0) { /* end of file */
+		if (endoffile || sizehint < 0) {
 			if (buf.inbuf < buf.inbuf_end &&
 			    multibytecodec_decerror(self->codec, &self->state,
 					&buf, self->errors, MBERR_TOOFEW))

Deleted: /python/branches/p3yk-noslice/Modules/clmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/clmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,2559 +0,0 @@
-
-
-/* Cl objects */
-
-#define CLDEBUG
-
-#include <stdarg.h>
-#include <cl.h>
-#if defined(CL_JPEG_SOFTWARE) && !defined(CL_JPEG_COSMO)
-#include <dmedia/cl_cosmo.h>
-#endif
-#include "Python.h"
-
-typedef struct {
-	PyObject_HEAD
-	int ob_isCompressor;	/* Compressor or Decompressor */
-	CL_Handle ob_compressorHdl;
-	int *ob_paramtypes;
-	int ob_nparams;
-} clobject;
-
-static PyObject *ClError;		/* exception cl.error */
-
-static int error_handler_called = 0;
-
-/*
- * We want to use the function prototypes that are available in the C
- * compiler on the SGI.  Because of that, we need to declare the first
- * argument of the compressor and decompressor methods as "object *",
- * even though they are really "clobject *".  Therefore we cast the
- * argument to the proper type using this macro.
- */
-#define SELF	((clobject *) self)
-
-/********************************************************************
-			  Utility routines.
-********************************************************************/
-static void
-cl_ErrorHandler(CL_Handle handle, int code, const char *fmt, ...)
-{
-	va_list ap;
-	char errbuf[BUFSIZ];	/* hopefully big enough */
-	char *p;
-
-	if (PyErr_Occurred())	/* don't change existing error */
-		return;
-	error_handler_called = 1;
-	va_start(ap, fmt);
-	vsprintf(errbuf, fmt, ap);
-	va_end(ap);
-	p = &errbuf[strlen(errbuf) - 1]; /* swat the line feed */
-	if (*p == '\n')
-		*p = 0;
-	PyErr_SetString(ClError, errbuf);
-}
-
-/*
- * This assumes that params are always in the range 0 to some maximum.
- */
-static int
-param_type_is_float(clobject *self, int param)
-{
-	int bufferlength;
-
-	if (self->ob_paramtypes == NULL) {
-		error_handler_called = 0;
-		bufferlength = clQueryParams(self->ob_compressorHdl, 0, 0);
-		if (error_handler_called)
-			return -1;
-
-		self->ob_paramtypes = PyMem_NEW(int, bufferlength);
-		if (self->ob_paramtypes == NULL)
-			return -1;
-		self->ob_nparams = bufferlength / 2;
-
-		(void) clQueryParams(self->ob_compressorHdl,
-				     self->ob_paramtypes, bufferlength);
-		if (error_handler_called) {
-			PyMem_DEL(self->ob_paramtypes);
-			self->ob_paramtypes = NULL;
-			return -1;
-		}
-	}
-
-	if (param < 0 || param >= self->ob_nparams)
-		return -1;
-
-	if (self->ob_paramtypes[param*2 + 1] == CL_FLOATING_ENUM_VALUE ||
-	    self->ob_paramtypes[param*2 + 1] == CL_FLOATING_RANGE_VALUE)
-		return 1;
-	else
-		return 0;
-}
-
-/********************************************************************
-	       Single image compression/decompression.
-********************************************************************/
-static PyObject *
-cl_CompressImage(PyObject *self, PyObject *args)
-{
-	int compressionScheme, width, height, originalFormat;
-	float compressionRatio;
-	int frameBufferSize, compressedBufferSize;
-	char *frameBuffer;
-	PyObject *compressedBuffer;
-
-	if (!PyArg_ParseTuple(args, "iiiifs#", &compressionScheme,
-			 &width, &height,
-			 &originalFormat, &compressionRatio, &frameBuffer,
-			 &frameBufferSize))
-		return NULL;
-
-  retry:
-	compressedBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
-	if (compressedBuffer == NULL)
-		return NULL;
-
-	compressedBufferSize = frameBufferSize;
-	error_handler_called = 0;
-	if (clCompressImage(compressionScheme, width, height, originalFormat,
-			    compressionRatio, (void *) frameBuffer,
-			    &compressedBufferSize,
-			    (void *) PyString_AsString(compressedBuffer))
-	    == FAILURE || error_handler_called) {
-		Py_DECREF(compressedBuffer);
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "clCompressImage failed");
-		return NULL;
-	}
-
-	if (compressedBufferSize > frameBufferSize) {
-		frameBufferSize = compressedBufferSize;
-		Py_DECREF(compressedBuffer);
-		goto retry;
-	}
-
-	if (compressedBufferSize < frameBufferSize)
-		_PyString_Resize(&compressedBuffer, compressedBufferSize);
-
-	return compressedBuffer;
-}
-
-static PyObject *
-cl_DecompressImage(PyObject *self, PyObject *args)
-{
-	int compressionScheme, width, height, originalFormat;
-	char *compressedBuffer;
-	int compressedBufferSize, frameBufferSize;
-	PyObject *frameBuffer;
-
-	if (!PyArg_ParseTuple(args, "iiiis#", &compressionScheme, &width, &height,
-			 &originalFormat, &compressedBuffer,
-			 &compressedBufferSize))
-		return NULL;
-
-	frameBufferSize = width * height * CL_BytesPerPixel(originalFormat);
-
-	frameBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
-	if (frameBuffer == NULL)
-		return NULL;
-
-	error_handler_called = 0;
-	if (clDecompressImage(compressionScheme, width, height, originalFormat,
-			      compressedBufferSize, compressedBuffer,
-			      (void *) PyString_AsString(frameBuffer))
-	    == FAILURE || error_handler_called) {
-		Py_DECREF(frameBuffer);
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "clDecompressImage failed");
-		return NULL;
-	}
-
-	return frameBuffer;
-}
-
-/********************************************************************
-		Sequential compression/decompression.
-********************************************************************/
-#define CheckCompressor(self)	if ((self)->ob_compressorHdl == NULL) { \
-	PyErr_SetString(PyExc_RuntimeError, "(de)compressor not active"); \
-	return NULL; \
-}
-
-static PyObject *
-doClose(clobject *self, int (*close_func)(CL_Handle))
-{
-	CheckCompressor(self);
-
-	error_handler_called = 0;
-	if ((*close_func)(self->ob_compressorHdl) == FAILURE ||
-	    error_handler_called) {
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "close failed");
-		return NULL;
-	}
-
-	self->ob_compressorHdl = NULL;
-
-	if (self->ob_paramtypes)
-		PyMem_DEL(self->ob_paramtypes);
-	self->ob_paramtypes = NULL;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-clm_CloseCompressor(PyObject *self)
-{
-	return doClose(SELF, clCloseCompressor);
-}
-
-static PyObject *
-clm_CloseDecompressor(PyObject *self)
-{
-	return doClose(SELF, clCloseDecompressor);
-}
-
-static PyObject *
-clm_Compress(PyObject *self, PyObject *args)
-{
-	int numberOfFrames;
-	int frameBufferSize, compressedBufferSize, size;
-	char *frameBuffer;
-	PyObject *data;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "(is#)", &numberOfFrames,
-			 &frameBuffer, &frameBufferSize))
-		return NULL;
-
-	error_handler_called = 0;
-	size = clGetParam(SELF->ob_compressorHdl, CL_COMPRESSED_BUFFER_SIZE);
-	compressedBufferSize = size;
-	if (error_handler_called)
-		return NULL;
-
-	data = PyString_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 ||
-	    error_handler_called) {
-		Py_DECREF(data);
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "compress failed");
-		return NULL;
-	}
-
-	if (compressedBufferSize < size)
-		if (_PyString_Resize(&data, compressedBufferSize))
-			return NULL;
-
-	if (compressedBufferSize > size) {
-		/* we didn't get all "compressed" data */
-		Py_DECREF(data);
-		PyErr_SetString(ClError,
-				"compressed data is more than fitted");
-		return NULL;
-	}
-
-	return data;
-}
-
-static PyObject *
-clm_Decompress(PyObject *self, PyObject *args)
-{
-	PyObject *data;
-	int numberOfFrames;
-	char *compressedData;
-	int compressedDataSize, dataSize;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "(is#)", &numberOfFrames, &compressedData,
-			 &compressedDataSize))
-		return NULL;
-
-	error_handler_called = 0;
-	dataSize = clGetParam(SELF->ob_compressorHdl, CL_FRAME_BUFFER_SIZE);
-	if (error_handler_called)
-		return NULL;
-
-	data = PyString_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 ||
-	    error_handler_called) {
-		Py_DECREF(data);
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "decompress failed");
-		return NULL;
-	}
-
-	return data;
-}
-
-static PyObject *
-doParams(clobject *self, PyObject *args, int (*func)(CL_Handle, int *, int),
-	 int modified)
-{
-	PyObject *list, *v;
-	int *PVbuffer;
-	int length;
-	int i;
-	float number;
-	
-	CheckCompressor(self);
-
-	if (!PyArg_Parse(args, "O", &list))
-		return NULL;
-	if (!PyList_Check(list)) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	length = PyList_Size(list);
-	PVbuffer = PyMem_NEW(int, length);
-	if (PVbuffer == NULL)
-		return PyErr_NoMemory();
-	for (i = 0; i < length; i++) {
-		v = PyList_GetItem(list, i);
-		if (PyFloat_Check(v)) {
-			number = PyFloat_AsDouble(v);
-			PVbuffer[i] = CL_TypeIsInt(number);
-		} else if (PyInt_Check(v)) {
-			PVbuffer[i] = PyInt_AsLong(v);
-			if ((i & 1) &&
-			    param_type_is_float(self, PVbuffer[i-1]) > 0) {
-				number = PVbuffer[i];
-				PVbuffer[i] = CL_TypeIsInt(number);
-			}
-		} else {
-			PyMem_DEL(PVbuffer);
-			PyErr_BadArgument();
-			return NULL;
-		}
-	}
-
-	error_handler_called = 0;
-	(*func)(self->ob_compressorHdl, PVbuffer, length);
-	if (error_handler_called) {
-		PyMem_DEL(PVbuffer);
-		return NULL;
-	}
-
-	if (modified) {
-		for (i = 0; i < length; i++) {
-			if ((i & 1) &&
-			    param_type_is_float(self, PVbuffer[i-1]) > 0) {
-				number = CL_TypeIsFloat(PVbuffer[i]);
-				v = PyFloat_FromDouble(number);
-			} else
-				v = PyInt_FromLong(PVbuffer[i]);
-			PyList_SetItem(list, i, v);
-		}
-	}
-
-	PyMem_DEL(PVbuffer);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-clm_GetParams(PyObject *self, PyObject *args)
-{
-	return doParams(SELF, args, clGetParams, 1);
-}
-
-static PyObject *
-clm_SetParams(PyObject *self, PyObject *args)
-{
-	return doParams(SELF, args, clSetParams, 0);
-}
-
-static PyObject *
-do_get(clobject *self, PyObject *args, int (*func)(CL_Handle, int))
-{
-	int paramID, value;
-	float fvalue;
-
-	CheckCompressor(self);
-
-	if (!PyArg_Parse(args, "i", &paramID))
-		return NULL;
-
-	error_handler_called = 0;
-	value = (*func)(self->ob_compressorHdl, paramID);
-	if (error_handler_called)
-		return NULL;
-
-	if (param_type_is_float(self, paramID) > 0) {
-		fvalue = CL_TypeIsFloat(value);
-		return PyFloat_FromDouble(fvalue);
-	}
-
-	return PyInt_FromLong(value);
-}
-
-static PyObject *
-clm_GetParam(PyObject *self, PyObject *args)
-{
-	return do_get(SELF, args, clGetParam);
-}
-
-static PyObject *
-clm_GetDefault(PyObject *self, PyObject *args)
-{
-	return do_get(SELF, args, clGetDefault);
-}
-
-static PyObject *
-clm_SetParam(PyObject *self, PyObject *args)
-{
-	int paramID, value;
-	float fvalue;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "(ii)", &paramID, &value)) {
-		PyErr_Clear();
-		if (!PyArg_Parse(args, "(if)", &paramID, &fvalue)) {
-			PyErr_Clear();
-			PyErr_SetString(PyExc_TypeError,
-			       "bad argument list (format '(ii)' or '(if)')");
-			return NULL;
-		}
-		value = CL_TypeIsInt(fvalue);
-	} else {
-		if (param_type_is_float(SELF, paramID) > 0) {
-			fvalue = value;
-			value = CL_TypeIsInt(fvalue);
-		}
-	}
-
- 	error_handler_called = 0;
-	value = clSetParam(SELF->ob_compressorHdl, paramID, value);
-	if (error_handler_called)
-		return NULL;
-
-	if (param_type_is_float(SELF, paramID) > 0)
-		return PyFloat_FromDouble(CL_TypeIsFloat(value));
-	else
-		return PyInt_FromLong(value);
-}
-
-static PyObject *
-clm_GetParamID(PyObject *self, PyObject *args)
-{
-	char *name;
-	int value;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "s", &name))
-		return NULL;
-
-	error_handler_called = 0;
-	value = clGetParamID(SELF->ob_compressorHdl, name);
-	if (value == FAILURE || error_handler_called) {
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "getparamid failed");
-		return NULL;
-	}
-
-	return PyInt_FromLong(value);
-}
-
-static PyObject *
-clm_QueryParams(PyObject *self)
-{
-	int bufferlength;
-	int *PVbuffer;
-	PyObject *list;
-	int i;
-
-	CheckCompressor(SELF);
-
-	error_handler_called = 0;
-	bufferlength = clQueryParams(SELF->ob_compressorHdl, 0, 0);
-	if (error_handler_called)
-		return NULL;
-
-	PVbuffer = PyMem_NEW(int, bufferlength);
-	if (PVbuffer == NULL)
-		return PyErr_NoMemory();
-
-	bufferlength = clQueryParams(SELF->ob_compressorHdl, PVbuffer,
-				     bufferlength);
-	if (error_handler_called) {
-		PyMem_DEL(PVbuffer);
-		return NULL;
-	}
-
-	list = PyList_New(bufferlength);
-	if (list == NULL) {
-		PyMem_DEL(PVbuffer);
-		return NULL;
-	}
-
-	for (i = 0; i < bufferlength; i++) {
-		if (i & 1)
-			PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
-		else if (PVbuffer[i] == 0) {
-			Py_INCREF(Py_None);
-			PyList_SetItem(list, i, Py_None);
-		} else
-			PyList_SetItem(list, i,
-				   PyString_FromString((char *) PVbuffer[i]));
-	}
-
-	PyMem_DEL(PVbuffer);
-
-	return list;
-}
-
-static PyObject *
-clm_GetMinMax(PyObject *self, PyObject *args)
-{
-	int param, min, max;
-	float fmin, fmax;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "i", &param))
-		return NULL;
-
-	clGetMinMax(SELF->ob_compressorHdl, param, &min, &max);
-
-	if (param_type_is_float(SELF, param) > 0) {
-		fmin = CL_TypeIsFloat(min);
-		fmax = CL_TypeIsFloat(max);
-		return Py_BuildValue("(ff)", fmin, fmax);
-	}
-
-	return Py_BuildValue("(ii)", min, max);
-}
-
-static PyObject *
-clm_GetName(PyObject *self, PyObject *args)
-{
-	int param;
-	char *name;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "i", &param))
-		return NULL;
-
-	error_handler_called = 0;
-	name = clGetName(SELF->ob_compressorHdl, param);
-	if (name == NULL || error_handler_called) {
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "getname failed");
-		return NULL;
-	}
-
-	return PyString_FromString(name);
-}
-
-static PyObject *
-clm_QuerySchemeFromHandle(PyObject *self)
-{
-	CheckCompressor(SELF);
-	return PyInt_FromLong(clQuerySchemeFromHandle(SELF->ob_compressorHdl));
-}
-
-static PyObject *
-clm_ReadHeader(PyObject *self, PyObject *args)
-{
-	char *header;
-	int headerSize;
-
-	CheckCompressor(SELF);
-
-	if (!PyArg_Parse(args, "s#", &header, &headerSize))
-		return NULL;
-
-	return PyInt_FromLong(clReadHeader(SELF->ob_compressorHdl,
-					   headerSize, header));
-}
-
-static PyMethodDef compressor_methods[] = {
-	{"close",		clm_CloseCompressor, METH_NOARGS}, /* alias */
-	{"CloseCompressor",	clm_CloseCompressor, METH_NOARGS},
-	{"Compress",		clm_Compress, METH_OLDARGS},
-	{"GetDefault",		clm_GetDefault, METH_OLDARGS},
-	{"GetMinMax",		clm_GetMinMax, METH_OLDARGS},
-	{"GetName",		clm_GetName, METH_OLDARGS},
-	{"GetParam",		clm_GetParam, METH_OLDARGS},
-	{"GetParamID",		clm_GetParamID, METH_OLDARGS},
-	{"GetParams",		clm_GetParams, METH_OLDARGS},
-	{"QueryParams",		clm_QueryParams, METH_NOARGS},
-	{"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
-	{"SetParam",		clm_SetParam, METH_OLDARGS},
-	{"SetParams",		clm_SetParams, METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-static PyMethodDef decompressor_methods[] = {
-	{"close",		clm_CloseDecompressor, METH_NOARGS},	/* alias */
-	{"CloseDecompressor",	clm_CloseDecompressor, METH_NOARGS},
-	{"Decompress",		clm_Decompress, METH_OLDARGS},
-	{"GetDefault",		clm_GetDefault, METH_OLDARGS},
-	{"GetMinMax",		clm_GetMinMax, METH_OLDARGS},
-	{"GetName",		clm_GetName, METH_OLDARGS},
-	{"GetParam",		clm_GetParam, METH_OLDARGS},
-	{"GetParamID",		clm_GetParamID, METH_OLDARGS},
-	{"GetParams",		clm_GetParams, METH_OLDARGS},
-	{"ReadHeader",		clm_ReadHeader, METH_OLDARGS},
-	{"QueryParams",		clm_QueryParams, METH_NOARGS},
-	{"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
-	{"SetParam",		clm_SetParam, METH_OLDARGS},
-	{"SetParams",		clm_SetParams, METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-static void
-cl_dealloc(PyObject *self)
-{
-	if (SELF->ob_compressorHdl) {
-		if (SELF->ob_isCompressor)
-			clCloseCompressor(SELF->ob_compressorHdl);
-		else
-			clCloseDecompressor(SELF->ob_compressorHdl);
-	}
-	PyObject_Del(self);
-}
-
-static PyObject *
-cl_getattr(PyObject *self, char *name)
-{
-	if (SELF->ob_isCompressor)
-		return Py_FindMethod(compressor_methods, self, name);
-	else
-		return Py_FindMethod(decompressor_methods, self, name);
-}
-
-static PyTypeObject Cltype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,			/*ob_size*/
-	"cl.cl",		/*tp_name*/
-	sizeof(clobject),	/*tp_size*/
-	0,			/*tp_itemsize*/
-	/* methods */
-	(destructor)cl_dealloc,	/*tp_dealloc*/
-	0,			/*tp_print*/
-	(getattrfunc)cl_getattr, /*tp_getattr*/
-	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
-	0,			/*tp_repr*/
-	0,			/*tp_as_number*/
-	0,			/*tp_as_sequence*/
-	0,			/*tp_as_mapping*/
-};
-
-static PyObject *
-doOpen(PyObject *self, PyObject *args, int (*open_func)(int, CL_Handle *),
-       int iscompressor)
-{
-	int scheme;
-	clobject *new;
-
-	if (!PyArg_ParseTuple(args, "i", &scheme))
-		return NULL;
-
-	new = PyObject_New(clobject, &Cltype);
-	if (new == NULL)
-		return NULL;
-
-	new->ob_compressorHdl = NULL;
-	new->ob_isCompressor = iscompressor;
-	new->ob_paramtypes = NULL;
-
-	error_handler_called = 0;
-	if ((*open_func)(scheme, &new->ob_compressorHdl) == FAILURE ||
-	    error_handler_called) {
-		Py_DECREF(new);
-		if (!error_handler_called)
-			PyErr_SetString(ClError, "Open(De)Compressor failed");
-		return NULL;
-	}
-	return (PyObject *)new;
-}
-
-static PyObject *
-cl_OpenCompressor(PyObject *self, PyObject *args)
-{
-	return doOpen(self, args, clOpenCompressor, 1);
-}
-
-static PyObject *
-cl_OpenDecompressor(PyObject *self, PyObject *args)
-{
-	return doOpen(self, args, clOpenDecompressor, 0);
-}
-
-static PyObject *
-cl_QueryScheme(PyObject *self, PyObject *args)
-{
-	char *header;
-	int headerlen;
-	int scheme;
-
-	if (!PyArg_ParseTuple(args, "s#", &header, &headerlen))
-		return NULL;
-
-	scheme = clQueryScheme(header);
-	if (scheme < 0) {
-		PyErr_SetString(ClError, "unknown compression scheme");
-		return NULL;
-	}
-
-	return PyInt_FromLong(scheme);
-}
-
-static PyObject *
-cl_QueryMaxHeaderSize(PyObject *self, PyObject *args)
-{
-	int scheme;
-
-	if (!PyArg_ParseTuple(args, "i", &scheme))
-		return NULL;
-
-	return PyInt_FromLong(clQueryMaxHeaderSize(scheme));
-}
-
-static PyObject *
-cl_QueryAlgorithms(PyObject *self, PyObject *args)
-{
-	int algorithmMediaType;
-	int bufferlength;
-	int *PVbuffer;
-	PyObject *list;
-	int i;
-
-	if (!PyArg_ParseTuple(args, "i", &algorithmMediaType))
-		return NULL;
-
-	error_handler_called = 0;
-	bufferlength = clQueryAlgorithms(algorithmMediaType, 0, 0);
-	if (error_handler_called)
-		return NULL;
-
-	PVbuffer = PyMem_NEW(int, bufferlength);
-	if (PVbuffer == NULL)
-		return PyErr_NoMemory();
-
-	bufferlength = clQueryAlgorithms(algorithmMediaType, PVbuffer,
-					 bufferlength);
-	if (error_handler_called) {
-		PyMem_DEL(PVbuffer);
-		return NULL;
-	}
-
-	list = PyList_New(bufferlength);
-	if (list == NULL) {
-		PyMem_DEL(PVbuffer);
-		return NULL;
-	}
-
-	for (i = 0; i < bufferlength; i++) {
-		if (i & 1)
-			PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
-		else if (PVbuffer[i] == 0) {
-			Py_INCREF(Py_None);
-			PyList_SetItem(list, i, Py_None);
-		} else
-			PyList_SetItem(list, i,
-				   PyString_FromString((char *) PVbuffer[i]));
-	}
-
-	PyMem_DEL(PVbuffer);
-
-	return list;
-}
-
-static PyObject *
-cl_QuerySchemeFromName(PyObject *self, PyObject *args)
-{
-	int algorithmMediaType;
-	char *name;
-	int scheme;
-
-	if (!PyArg_ParseTuple(args, "is", &algorithmMediaType, &name))
-		return NULL;
-
-	error_handler_called = 0;
-	scheme = clQuerySchemeFromName(algorithmMediaType, name);
-	if (error_handler_called) {
-		PyErr_SetString(ClError, "unknown compression scheme");
-		return NULL;
-	}
-
-	return PyInt_FromLong(scheme);
-}
-
-static PyObject *
-cl_GetAlgorithmName(PyObject *self, PyObject *args)
-{
-	int scheme;
-	char *name;
-
-	if (!PyArg_ParseTuple(args, "i", &scheme))
-		return NULL;
-
-	name = clGetAlgorithmName(scheme);
-	if (name == 0) {
-		PyErr_SetString(ClError, "unknown compression scheme");
-		return NULL;
-	}
-
-	return PyString_FromString(name);
-}
-
-static PyObject *
-do_set(PyObject *self, PyObject *args, int (*func)(int, int, int))
-{
-	int scheme, paramID, value;
-	float fvalue;
-	int is_float = 0;
-
-	if (!PyArg_ParseTuple(args, "iii", &scheme, &paramID, &value)) {
-		PyErr_Clear();
-		if (!PyArg_ParseTuple(args, "iif", &scheme, &paramID, &fvalue)) {
-			PyErr_Clear();
-			PyErr_SetString(PyExc_TypeError,
-			     "bad argument list (format '(iii)' or '(iif)')");
-			return NULL;
-		}
-		value = CL_TypeIsInt(fvalue);
-		is_float = 1;
-	} else {
-		/* check some parameters which we know to be floats */
-		switch (scheme) {
-		case CL_COMPRESSION_RATIO:
-		case CL_SPEED:
-			fvalue = value;
-			value = CL_TypeIsInt(fvalue);
-			is_float = 1;
-			break;
-		}
-	}
-
- 	error_handler_called = 0;
-	value = (*func)(scheme, paramID, value);
-	if (error_handler_called)
-		return NULL;
-
-	if (is_float)
-		return PyFloat_FromDouble(CL_TypeIsFloat(value));
-	else
-		return PyInt_FromLong(value);
-}
-
-static PyObject *
-cl_SetDefault(PyObject *self, PyObject *args)
-{
-	return do_set(self, args, clSetDefault);
-}
-
-static PyObject *
-cl_SetMin(PyObject *self, PyObject *args)
-{
-	return do_set(self, args, clSetMin);
-}
-
-static PyObject *
-cl_SetMax(PyObject *self, PyObject *args)
-{
-	return do_set(self, args, clSetMax);
-}
-
-#define func(name, handler)	\
-static PyObject *cl_##name(PyObject *self, PyObject *args) \
-{ \
-	  int x; \
-	  if (!PyArg_ParseTuple(args, "i", &x)) return NULL; \
-	  return Py##handler(CL_##name(x)); \
-}
-
-#define func2(name, handler)	\
-static PyObject *cl_##name(PyObject *self, PyObject *args) \
-{ \
-	  int a1, a2; \
-	  if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL; \
-	  return Py##handler(CL_##name(a1, a2)); \
-}
-
-func(BytesPerSample, Int_FromLong)
-func(BytesPerPixel, Int_FromLong)
-func(AudioFormatName, String_FromString)
-func(VideoFormatName, String_FromString)
-func(AlgorithmNumber, Int_FromLong)
-func(AlgorithmType, Int_FromLong)
-func2(Algorithm, Int_FromLong)
-func(ParamNumber, Int_FromLong)
-func(ParamType, Int_FromLong)
-func2(ParamID, Int_FromLong)
-
-#ifdef CLDEBUG
-	static PyObject *
-cvt_type(PyObject *self, PyObject *args)
-{
-	int number;
-	float fnumber;
-
-	if (PyArg_Parse(args, "i", &number))
-		return PyFloat_FromDouble(CL_TypeIsFloat(number));
-	else {
-		PyErr_Clear();
-		if (PyArg_Parse(args, "f", &fnumber))
-			return PyInt_FromLong(CL_TypeIsInt(fnumber));
-		return NULL;
-	}
-}
-#endif
-
-static PyMethodDef cl_methods[] = {
-	{"CompressImage",	cl_CompressImage, METH_VARARGS},
-	{"DecompressImage",	cl_DecompressImage, METH_VARARGS},
-	{"GetAlgorithmName",	cl_GetAlgorithmName, METH_VARARGS},
-	{"OpenCompressor",	cl_OpenCompressor, METH_VARARGS},
-	{"OpenDecompressor",	cl_OpenDecompressor, METH_VARARGS},
-	{"QueryAlgorithms",	cl_QueryAlgorithms, METH_VARARGS},
-	{"QueryMaxHeaderSize",	cl_QueryMaxHeaderSize, METH_VARARGS},
-	{"QueryScheme",		cl_QueryScheme, METH_VARARGS},
-	{"QuerySchemeFromName",	cl_QuerySchemeFromName, METH_VARARGS},
-	{"SetDefault",		cl_SetDefault, METH_VARARGS},
-	{"SetMax",		cl_SetMax, METH_VARARGS},
-	{"SetMin",		cl_SetMin, METH_VARARGS},
-	{"BytesPerSample",	cl_BytesPerSample, METH_VARARGS},
-	{"BytesPerPixel",	cl_BytesPerPixel, METH_VARARGS},
-	{"AudioFormatName",	cl_AudioFormatName, METH_VARARGS},
-	{"VideoFormatName",	cl_VideoFormatName, METH_VARARGS},
-	{"AlgorithmNumber",	cl_AlgorithmNumber, METH_VARARGS},
-	{"AlgorithmType",	cl_AlgorithmType, METH_VARARGS},
-	{"Algorithm",		cl_Algorithm, METH_VARARGS},
-	{"ParamNumber",		cl_ParamNumber, METH_VARARGS},
-	{"ParamType",		cl_ParamType, METH_VARARGS},
-	{"ParamID",		cl_ParamID, METH_VARARGS},
-#ifdef CLDEBUG
-	{"cvt_type",		cvt_type, METH_VARARGS},
-#endif
-	{NULL,			NULL} /* Sentinel */
-};
-
-#ifdef CL_JPEG_SOFTWARE
-#define IRIX_5_3_LIBRARY
-#endif
-
-void
-initcl(void)
-{
-	PyObject *m, *d, *x;
-
-	m = Py_InitModule("cl", cl_methods);
-	if (m == NULL)
-		return;
-	d = PyModule_GetDict(m);
-
-	ClError = PyErr_NewException("cl.error", NULL, NULL);
-	(void) PyDict_SetItemString(d, "error", ClError);
-
-#ifdef CL_ADDED_ALGORITHM_ERROR
-	x = PyInt_FromLong(CL_ADDED_ALGORITHM_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "ADDED_ALGORITHM_ERROR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ALAW
-	x = PyInt_FromLong(CL_ALAW);
-	if (x == NULL || PyDict_SetItemString(d, "ALAW", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ALGORITHM_ID
-	x = PyInt_FromLong(CL_ALGORITHM_ID);
-	if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_ID", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ALGORITHM_TABLE_FULL
-	x = PyInt_FromLong(CL_ALGORITHM_TABLE_FULL);
-	if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_TABLE_FULL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ALGORITHM_VERSION
-	x = PyInt_FromLong(CL_ALGORITHM_VERSION);
-	if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_VERSION", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ALG_AUDIO
-	x = PyInt_FromLong(CL_ALG_AUDIO);
-	if (x == NULL || PyDict_SetItemString(d, "ALG_AUDIO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ALG_VIDEO
-	x = PyInt_FromLong(CL_ALG_VIDEO);
-	if (x == NULL || PyDict_SetItemString(d, "ALG_VIDEO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AUDIO
-	x = PyInt_FromLong(CL_AUDIO);
-	if (x == NULL || PyDict_SetItemString(d, "AUDIO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_BITRATE_POLICY
-	x = PyInt_FromLong(CL_AWARE_BITRATE_POLICY);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_POLICY", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_BITRATE_TARGET
-	x = PyInt_FromLong(CL_AWARE_BITRATE_TARGET);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_TARGET", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_CHANNEL_POLICY
-	x = PyInt_FromLong(CL_AWARE_CHANNEL_POLICY);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_CHANNEL_POLICY", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_CONST_QUAL
-	x = PyInt_FromLong(CL_AWARE_CONST_QUAL);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_CONST_QUAL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_ERROR
-	x = PyInt_FromLong(CL_AWARE_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_ERROR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_FIXED_RATE
-	x = PyInt_FromLong(CL_AWARE_FIXED_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_FIXED_RATE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_INDEPENDENT
-	x = PyInt_FromLong(CL_AWARE_INDEPENDENT);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_INDEPENDENT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_JOINT_STEREO
-	x = PyInt_FromLong(CL_AWARE_JOINT_STEREO);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_JOINT_STEREO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_LAYER
-	x = PyInt_FromLong(CL_AWARE_LAYER);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_LAYER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_LOSSLESS
-	x = PyInt_FromLong(CL_AWARE_LOSSLESS);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_LOSSLESS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_MPEG_AUDIO
-	x = PyInt_FromLong(CL_AWARE_MPEG_AUDIO);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_AUDIO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_MPEG_LAYER_I
-	x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_I);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_I", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_MPEG_LAYER_II
-	x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_II);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_II", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_MULTIRATE
-	x = PyInt_FromLong(CL_AWARE_MULTIRATE);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_MULTIRATE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_NOISE_MARGIN
-	x = PyInt_FromLong(CL_AWARE_NOISE_MARGIN);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_NOISE_MARGIN", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_AWARE_STEREO
-	x = PyInt_FromLong(CL_AWARE_STEREO);
-	if (x == NULL || PyDict_SetItemString(d, "AWARE_STEREO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_ALGORITHM_NAME
-	x = PyInt_FromLong(CL_BAD_ALGORITHM_NAME);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_NAME", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_ALGORITHM_TYPE
-	x = PyInt_FromLong(CL_BAD_ALGORITHM_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_TYPE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BLOCK_SIZE
-	x = PyInt_FromLong(CL_BAD_BLOCK_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BLOCK_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BOARD
-	x = PyInt_FromLong(CL_BAD_BOARD);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BOARD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFERING
-	x = PyInt_FromLong(CL_BAD_BUFFERING);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERING", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFERLENGTH_NEG
-	x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_NEG);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFERLENGTH_ODD
-	x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_ODD);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_EXISTS
-	x = PyInt_FromLong(CL_BAD_BUFFER_EXISTS);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_EXISTS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_HANDLE
-	x = PyInt_FromLong(CL_BAD_BUFFER_HANDLE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_HANDLE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_POINTER
-	x = PyInt_FromLong(CL_BAD_BUFFER_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_QUERY_SIZE
-	x = PyInt_FromLong(CL_BAD_BUFFER_QUERY_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_QUERY_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_SIZE
-	x = PyInt_FromLong(CL_BAD_BUFFER_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_SIZE_POINTER
-	x = PyInt_FromLong(CL_BAD_BUFFER_SIZE_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_BUFFER_TYPE
-	x = PyInt_FromLong(CL_BAD_BUFFER_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_TYPE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_COMPRESSION_SCHEME
-	x = PyInt_FromLong(CL_BAD_COMPRESSION_SCHEME);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSION_SCHEME", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_COMPRESSOR_HANDLE
-	x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_COMPRESSOR_HANDLE_POINTER
-	x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_FRAME_SIZE
-	x = PyInt_FromLong(CL_BAD_FRAME_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_FRAME_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_FUNCTIONALITY
-	x = PyInt_FromLong(CL_BAD_FUNCTIONALITY);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTIONALITY", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_FUNCTION_POINTER
-	x = PyInt_FromLong(CL_BAD_FUNCTION_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTION_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_HEADER_SIZE
-	x = PyInt_FromLong(CL_BAD_HEADER_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_HEADER_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_INITIAL_VALUE
-	x = PyInt_FromLong(CL_BAD_INITIAL_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_INITIAL_VALUE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_INTERNAL_FORMAT
-	x = PyInt_FromLong(CL_BAD_INTERNAL_FORMAT);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_INTERNAL_FORMAT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_LICENSE
-	x = PyInt_FromLong(CL_BAD_LICENSE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_LICENSE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_MIN_GT_MAX
-	x = PyInt_FromLong(CL_BAD_MIN_GT_MAX);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_MIN_GT_MAX", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_NO_BUFFERSPACE
-	x = PyInt_FromLong(CL_BAD_NO_BUFFERSPACE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_NO_BUFFERSPACE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_NUMBER_OF_BLOCKS
-	x = PyInt_FromLong(CL_BAD_NUMBER_OF_BLOCKS);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_NUMBER_OF_BLOCKS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_PARAM
-	x = PyInt_FromLong(CL_BAD_PARAM);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_PARAM_ID_POINTER
-	x = PyInt_FromLong(CL_BAD_PARAM_ID_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_ID_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_PARAM_TYPE
-	x = PyInt_FromLong(CL_BAD_PARAM_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_TYPE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_POINTER
-	x = PyInt_FromLong(CL_BAD_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_PVBUFFER
-	x = PyInt_FromLong(CL_BAD_PVBUFFER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_SCHEME_POINTER
-	x = PyInt_FromLong(CL_BAD_SCHEME_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_SCHEME_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_STREAM_HEADER
-	x = PyInt_FromLong(CL_BAD_STREAM_HEADER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_STREAM_HEADER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_STRING_POINTER
-	x = PyInt_FromLong(CL_BAD_STRING_POINTER);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_STRING_POINTER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BAD_TEXT_STRING_PTR
-	x = PyInt_FromLong(CL_BAD_TEXT_STRING_PTR);
-	if (x == NULL || PyDict_SetItemString(d, "BAD_TEXT_STRING_PTR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BEST_FIT
-	x = PyInt_FromLong(CL_BEST_FIT);
-	if (x == NULL || PyDict_SetItemString(d, "BEST_FIT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BIDIRECTIONAL
-	x = PyInt_FromLong(CL_BIDIRECTIONAL);
-	if (x == NULL || PyDict_SetItemString(d, "BIDIRECTIONAL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BITRATE
-	x = PyInt_FromLong(CL_BITRATE);
-	if (x == NULL || PyDict_SetItemString(d, "BITRATE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BITRATE_POLICY
-	x = PyInt_FromLong(CL_BITRATE_POLICY);
-	if (x == NULL || PyDict_SetItemString(d, "BITRATE_POLICY", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BITRATE_TARGET
-	x = PyInt_FromLong(CL_BITRATE_TARGET);
-	if (x == NULL || PyDict_SetItemString(d, "BITRATE_TARGET", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BITS_PER_COMPONENT
-	x = PyInt_FromLong(CL_BITS_PER_COMPONENT);
-	if (x == NULL || PyDict_SetItemString(d, "BITS_PER_COMPONENT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BLENDING
-	x = PyInt_FromLong(CL_BLENDING);
-	if (x == NULL || PyDict_SetItemString(d, "BLENDING", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BLOCK_SIZE
-	x = PyInt_FromLong(CL_BLOCK_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "BLOCK_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BOTTOM_UP
-	x = PyInt_FromLong(CL_BOTTOM_UP);
-	if (x == NULL || PyDict_SetItemString(d, "BOTTOM_UP", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BUFFER_NOT_CREATED
-	x = PyInt_FromLong(CL_BUFFER_NOT_CREATED);
-	if (x == NULL || PyDict_SetItemString(d, "BUFFER_NOT_CREATED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BUF_COMPRESSED
-	x = PyInt_FromLong(CL_BUF_COMPRESSED);
-	if (x == NULL || PyDict_SetItemString(d, "BUF_COMPRESSED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BUF_DATA
-	x = PyInt_FromLong(CL_BUF_DATA);
-	if (x == NULL || PyDict_SetItemString(d, "BUF_DATA", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_BUF_FRAME
-	x = PyInt_FromLong(CL_BUF_FRAME);
-	if (x == NULL || PyDict_SetItemString(d, "BUF_FRAME", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_CHANNEL_POLICY
-	x = PyInt_FromLong(CL_CHANNEL_POLICY);
-	if (x == NULL || PyDict_SetItemString(d, "CHANNEL_POLICY", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_CHROMA_THRESHOLD
-	x = PyInt_FromLong(CL_CHROMA_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "CHROMA_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_CODEC
-	x = PyInt_FromLong(CL_CODEC);
-	if (x == NULL || PyDict_SetItemString(d, "CODEC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COMPONENTS
-	x = PyInt_FromLong(CL_COMPONENTS);
-	if (x == NULL || PyDict_SetItemString(d, "COMPONENTS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COMPRESSED_BUFFER_SIZE
-	x = PyInt_FromLong(CL_COMPRESSED_BUFFER_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "COMPRESSED_BUFFER_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COMPRESSION_RATIO
-	x = PyInt_FromLong(CL_COMPRESSION_RATIO);
-	if (x == NULL || PyDict_SetItemString(d, "COMPRESSION_RATIO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COMPRESSOR
-	x = PyInt_FromLong(CL_COMPRESSOR);
-	if (x == NULL || PyDict_SetItemString(d, "COMPRESSOR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_CONTINUOUS_BLOCK
-	x = PyInt_FromLong(CL_CONTINUOUS_BLOCK);
-	if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_BLOCK", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_CONTINUOUS_NONBLOCK
-	x = PyInt_FromLong(CL_CONTINUOUS_NONBLOCK);
-	if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_NONBLOCK", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COSMO_CODEC_CONTROL
-	x = PyInt_FromLong(CL_COSMO_CODEC_CONTROL);
-	if (x == NULL || PyDict_SetItemString(d, "COSMO_CODEC_CONTROL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COSMO_NUM_PARAMS
-	x = PyInt_FromLong(CL_COSMO_NUM_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "COSMO_NUM_PARAMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COSMO_VALUE_BASE
-	x = PyInt_FromLong(CL_COSMO_VALUE_BASE);
-	if (x == NULL || PyDict_SetItemString(d, "COSMO_VALUE_BASE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COSMO_VIDEO_MANUAL_CONTROL
-	x = PyInt_FromLong(CL_COSMO_VIDEO_MANUAL_CONTROL);
-	if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_MANUAL_CONTROL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_COSMO_VIDEO_TRANSFER_MODE
-	x = PyInt_FromLong(CL_COSMO_VIDEO_TRANSFER_MODE);
-	if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_TRANSFER_MODE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_DATA
-	x = PyInt_FromLong(CL_DATA);
-	if (x == NULL || PyDict_SetItemString(d, "DATA", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_DECOMPRESSOR
-	x = PyInt_FromLong(CL_DECOMPRESSOR);
-	if (x == NULL || PyDict_SetItemString(d, "DECOMPRESSOR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_DSO_ERROR
-	x = PyInt_FromLong(CL_DSO_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "DSO_ERROR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_EDGE_THRESHOLD
-	x = PyInt_FromLong(CL_EDGE_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "EDGE_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ENABLE_IMAGEINFO
-	x = PyInt_FromLong(CL_ENABLE_IMAGEINFO);
-	if (x == NULL || PyDict_SetItemString(d, "ENABLE_IMAGEINFO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_END_OF_SEQUENCE
-	x = PyInt_FromLong(CL_END_OF_SEQUENCE);
-	if (x == NULL || PyDict_SetItemString(d, "END_OF_SEQUENCE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ENUM_VALUE
-	x = PyInt_FromLong(CL_ENUM_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_EXACT_COMPRESSION_RATIO
-	x = PyInt_FromLong(CL_EXACT_COMPRESSION_RATIO);
-	if (x == NULL || PyDict_SetItemString(d, "EXACT_COMPRESSION_RATIO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_EXTERNAL_DEVICE
-	x = PyInt_FromLong((long) CL_EXTERNAL_DEVICE);
-	if (x == NULL || PyDict_SetItemString(d, "EXTERNAL_DEVICE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FLOATING_ENUM_VALUE
-	x = PyInt_FromLong(CL_FLOATING_ENUM_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "FLOATING_ENUM_VALUE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FLOATING_RANGE_VALUE
-	x = PyInt_FromLong(CL_FLOATING_RANGE_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "FLOATING_RANGE_VALUE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT
-	x = PyInt_FromLong(CL_FORMAT);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_ABGR
-	x = PyInt_FromLong(CL_FORMAT_ABGR);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_ABGR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_BGR
-	x = PyInt_FromLong(CL_FORMAT_BGR);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_BGR233
-	x = PyInt_FromLong(CL_FORMAT_BGR233);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR233", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_GRAYSCALE
-	x = PyInt_FromLong(CL_FORMAT_GRAYSCALE);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_GRAYSCALE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_MONO
-	x = PyInt_FromLong(CL_FORMAT_MONO);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_MONO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_RBG323
-	x = PyInt_FromLong(CL_FORMAT_RBG323);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_RBG323", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_STEREO_INTERLEAVED
-	x = PyInt_FromLong(CL_FORMAT_STEREO_INTERLEAVED);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_STEREO_INTERLEAVED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_XBGR
-	x = PyInt_FromLong(CL_FORMAT_XBGR);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_XBGR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_YCbCr
-	x = PyInt_FromLong(CL_FORMAT_YCbCr);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_YCbCr422
-	x = PyInt_FromLong(CL_FORMAT_YCbCr422);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FORMAT_YCbCr422DC
-	x = PyInt_FromLong(CL_FORMAT_YCbCr422DC);
-	if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422DC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME
-	x = PyInt_FromLong(CL_FRAME);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAMES_PER_CHUNK
-	x = PyInt_FromLong(CL_FRAMES_PER_CHUNK);
-	if (x == NULL || PyDict_SetItemString(d, "FRAMES_PER_CHUNK", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME_BUFFER_SIZE
-	x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME_BUFFER_SIZE_ZERO
-	x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE_ZERO);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE_ZERO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME_INDEX
-	x = PyInt_FromLong(CL_FRAME_INDEX);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME_INDEX", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME_RATE
-	x = PyInt_FromLong(CL_FRAME_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME_RATE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME_SIZE
-	x = PyInt_FromLong(CL_FRAME_SIZE);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME_SIZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_FRAME_TYPE
-	x = PyInt_FromLong(CL_FRAME_TYPE);
-	if (x == NULL || PyDict_SetItemString(d, "FRAME_TYPE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_G711_ALAW
-	x = PyInt_FromLong(CL_G711_ALAW);
-	if (x == NULL || PyDict_SetItemString(d, "G711_ALAW", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_G711_ALAW_SOFTWARE
-	x = PyInt_FromLong(CL_G711_ALAW_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "G711_ALAW_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_G711_ULAW
-	x = PyInt_FromLong(CL_G711_ULAW);
-	if (x == NULL || PyDict_SetItemString(d, "G711_ULAW", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_G711_ULAW_SOFTWARE
-	x = PyInt_FromLong(CL_G711_ULAW_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "G711_ULAW_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_GRAYSCALE
-	x = PyInt_FromLong(CL_GRAYSCALE);
-	if (x == NULL || PyDict_SetItemString(d, "GRAYSCALE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_HDCC
-	x = PyInt_FromLong(CL_HDCC);
-	if (x == NULL || PyDict_SetItemString(d, "HDCC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_HDCC_SAMPLES_PER_TILE
-	x = PyInt_FromLong(CL_HDCC_SAMPLES_PER_TILE);
-	if (x == NULL || PyDict_SetItemString(d, "HDCC_SAMPLES_PER_TILE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_HDCC_SOFTWARE
-	x = PyInt_FromLong(CL_HDCC_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "HDCC_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_HDCC_TILE_THRESHOLD
-	x = PyInt_FromLong(CL_HDCC_TILE_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "HDCC_TILE_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_HEADER_START_CODE
-	x = PyInt_FromLong(CL_HEADER_START_CODE);
-	if (x == NULL || PyDict_SetItemString(d, "HEADER_START_CODE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGEINFO_FIELDMASK
-	x = PyInt_FromLong(CL_IMAGEINFO_FIELDMASK);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGEINFO_FIELDMASK", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGE_CROP_BOTTOM
-	x = PyInt_FromLong(CL_IMAGE_CROP_BOTTOM);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_BOTTOM", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGE_CROP_LEFT
-	x = PyInt_FromLong(CL_IMAGE_CROP_LEFT);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_LEFT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGE_CROP_RIGHT
-	x = PyInt_FromLong(CL_IMAGE_CROP_RIGHT);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_RIGHT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGE_CROP_TOP
-	x = PyInt_FromLong(CL_IMAGE_CROP_TOP);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_TOP", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGE_HEIGHT
-	x = PyInt_FromLong(CL_IMAGE_HEIGHT);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGE_HEIGHT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMAGE_WIDTH
-	x = PyInt_FromLong(CL_IMAGE_WIDTH);
-	if (x == NULL || PyDict_SetItemString(d, "IMAGE_WIDTH", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMPACT_CODEC_CONTROL
-	x = PyInt_FromLong(CL_IMPACT_CODEC_CONTROL);
-	if (x == NULL || PyDict_SetItemString(d, "IMPACT_CODEC_CONTROL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMPACT_FRAME_INTERLEAVE
-	x = PyInt_FromLong(CL_IMPACT_FRAME_INTERLEAVE);
-	if (x == NULL || PyDict_SetItemString(d, "IMPACT_FRAME_INTERLEAVE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_IMPACT_NUM_PARAMS
-	x = PyInt_FromLong(CL_IMPACT_NUM_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "IMPACT_NUM_PARAMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_INTERNAL_FORMAT
-	x = PyInt_FromLong(CL_INTERNAL_FORMAT);
-	if (x == NULL || PyDict_SetItemString(d, "INTERNAL_FORMAT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_INTERNAL_IMAGE_HEIGHT
-	x = PyInt_FromLong(CL_INTERNAL_IMAGE_HEIGHT);
-	if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_HEIGHT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_INTERNAL_IMAGE_WIDTH
-	x = PyInt_FromLong(CL_INTERNAL_IMAGE_WIDTH);
-	if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_WIDTH", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_INTRA
-	x = PyInt_FromLong(CL_INTRA);
-	if (x == NULL || PyDict_SetItemString(d, "INTRA", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG
-	x = PyInt_FromLong(CL_JPEG);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_COSMO
-	x = PyInt_FromLong(CL_JPEG_COSMO);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_COSMO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_ERROR
-	x = PyInt_FromLong(CL_JPEG_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_ERROR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_IMPACT
-	x = PyInt_FromLong(CL_JPEG_IMPACT);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_IMPACT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_NUM_PARAMS
-	x = PyInt_FromLong(CL_JPEG_NUM_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_NUM_PARAMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_QUALITY_FACTOR
-	x = PyInt_FromLong(CL_JPEG_QUALITY_FACTOR);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_QUALITY_FACTOR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_QUANTIZATION_TABLES
-	x = PyInt_FromLong(CL_JPEG_QUANTIZATION_TABLES);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_QUANTIZATION_TABLES", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_SOFTWARE
-	x = PyInt_FromLong(CL_JPEG_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_JPEG_STREAM_HEADERS
-	x = PyInt_FromLong(CL_JPEG_STREAM_HEADERS);
-	if (x == NULL || PyDict_SetItemString(d, "JPEG_STREAM_HEADERS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_KEYFRAME
-	x = PyInt_FromLong(CL_KEYFRAME);
-	if (x == NULL || PyDict_SetItemString(d, "KEYFRAME", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_KEYFRAME_DISTANCE
-	x = PyInt_FromLong(CL_KEYFRAME_DISTANCE);
-	if (x == NULL || PyDict_SetItemString(d, "KEYFRAME_DISTANCE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_LAST_FRAME_INDEX
-	x = PyInt_FromLong(CL_LAST_FRAME_INDEX);
-	if (x == NULL || PyDict_SetItemString(d, "LAST_FRAME_INDEX", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_LAYER
-	x = PyInt_FromLong(CL_LAYER);
-	if (x == NULL || PyDict_SetItemString(d, "LAYER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_LUMA_THRESHOLD
-	x = PyInt_FromLong(CL_LUMA_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "LUMA_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS
-	x = PyInt_FromLong(CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_AUDIO_ALGORITHMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MAX_NUMBER_OF_FORMATS
-	x = PyInt_FromLong(CL_MAX_NUMBER_OF_FORMATS);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_FORMATS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MAX_NUMBER_OF_ORIGINAL_FORMATS
-	x = PyInt_FromLong(CL_MAX_NUMBER_OF_ORIGINAL_FORMATS);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_ORIGINAL_FORMATS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MAX_NUMBER_OF_PARAMS
-	x = PyInt_FromLong(CL_MAX_NUMBER_OF_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_PARAMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS
-	x = PyInt_FromLong(CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS);
-	if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_VIDEO_ALGORITHMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MONO
-	x = PyInt_FromLong(CL_MONO);
-	if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_AWARE
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_AWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_AWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_LAYER
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_LAYER_I
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_I);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_I", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_LAYER_II
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_II);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_II", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_MODE
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_MODE_DUAL
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_DUAL);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_DUAL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_MODE_JOINT
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_JOINT);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_JOINT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_MODE_SINGLE
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_SINGLE);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_SINGLE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_MODE_STEREO
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_STEREO);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_STEREO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_AUDIO_SOFTWARE
-	x = PyInt_FromLong(CL_MPEG1_AUDIO_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_END_OF_STREAM
-	x = PyInt_FromLong(CL_MPEG1_END_OF_STREAM);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_END_OF_STREAM", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_ERROR
-	x = PyInt_FromLong(CL_MPEG1_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_ERROR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_NUM_PARAMS
-	x = PyInt_FromLong(CL_MPEG1_NUM_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_NUM_PARAMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_M
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_M);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_M", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_N
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_N);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_N", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_SOFTNESS
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MAXIMUM", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_SOFTNESS_MEDIUM
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MEDIUM);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MEDIUM", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_SOFTNESS_NONE
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_NONE);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_NONE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG1_VIDEO_SOFTWARE
-	x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MPEG_VIDEO
-	x = PyInt_FromLong(CL_MPEG_VIDEO);
-	if (x == NULL || PyDict_SetItemString(d, "MPEG_VIDEO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MULTIRATE_AWARE
-	x = PyInt_FromLong(CL_MULTIRATE_AWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MULTIRATE_AWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC1
-	x = PyInt_FromLong(CL_MVC1);
-	if (x == NULL || PyDict_SetItemString(d, "MVC1", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC1_SOFTWARE
-	x = PyInt_FromLong(CL_MVC1_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MVC1_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2
-	x = PyInt_FromLong(CL_MVC2);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_BLENDING
-	x = PyInt_FromLong(CL_MVC2_BLENDING);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_BLENDING_OFF
-	x = PyInt_FromLong(CL_MVC2_BLENDING_OFF);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_OFF", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_BLENDING_ON
-	x = PyInt_FromLong(CL_MVC2_BLENDING_ON);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_ON", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_CHROMA_THRESHOLD
-	x = PyInt_FromLong(CL_MVC2_CHROMA_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_CHROMA_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_EDGE_THRESHOLD
-	x = PyInt_FromLong(CL_MVC2_EDGE_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_EDGE_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_ERROR
-	x = PyInt_FromLong(CL_MVC2_ERROR);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_ERROR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_LUMA_THRESHOLD
-	x = PyInt_FromLong(CL_MVC2_LUMA_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_LUMA_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC2_SOFTWARE
-	x = PyInt_FromLong(CL_MVC2_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MVC2_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC3_QUALITY_LEVEL
-	x = PyInt_FromLong(CL_MVC3_QUALITY_LEVEL);
-	if (x == NULL || PyDict_SetItemString(d, "MVC3_QUALITY_LEVEL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_MVC3_SOFTWARE
-	x = PyInt_FromLong(CL_MVC3_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "MVC3_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NEXT_NOT_AVAILABLE
-	x = PyInt_FromLong(CL_NEXT_NOT_AVAILABLE);
-	if (x == NULL || PyDict_SetItemString(d, "NEXT_NOT_AVAILABLE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NOISE_MARGIN
-	x = PyInt_FromLong(CL_NOISE_MARGIN);
-	if (x == NULL || PyDict_SetItemString(d, "NOISE_MARGIN", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NONE
-	x = PyInt_FromLong(CL_NONE);
-	if (x == NULL || PyDict_SetItemString(d, "NONE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NUMBER_OF_FORMATS
-	x = PyInt_FromLong(CL_NUMBER_OF_FORMATS);
-	if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FORMATS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NUMBER_OF_FRAMES
-	x = PyInt_FromLong(CL_NUMBER_OF_FRAMES);
-	if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FRAMES", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NUMBER_OF_PARAMS
-	x = PyInt_FromLong(CL_NUMBER_OF_PARAMS);
-	if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NUMBER_OF_PARAMS_FREEZE
-	x = PyInt_FromLong(CL_NUMBER_OF_PARAMS_FREEZE);
-	if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS_FREEZE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_NUMBER_OF_VIDEO_FORMATS
-	x = PyInt_FromLong(CL_NUMBER_OF_VIDEO_FORMATS);
-	if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_VIDEO_FORMATS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ORIENTATION
-	x = PyInt_FromLong(CL_ORIENTATION);
-	if (x == NULL || PyDict_SetItemString(d, "ORIENTATION", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ORIGINAL_FORMAT
-	x = PyInt_FromLong(CL_ORIGINAL_FORMAT);
-	if (x == NULL || PyDict_SetItemString(d, "ORIGINAL_FORMAT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_PARAM_OUT_OF_RANGE
-	x = PyInt_FromLong(CL_PARAM_OUT_OF_RANGE);
-	if (x == NULL || PyDict_SetItemString(d, "PARAM_OUT_OF_RANGE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_PIXEL_ASPECT
-	x = PyInt_FromLong(CL_PIXEL_ASPECT);
-	if (x == NULL || PyDict_SetItemString(d, "PIXEL_ASPECT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_PREDICTED
-	x = PyInt_FromLong(CL_PREDICTED);
-	if (x == NULL || PyDict_SetItemString(d, "PREDICTED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_PREROLL
-	x = PyInt_FromLong(CL_PREROLL);
-	if (x == NULL || PyDict_SetItemString(d, "PREROLL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_QUALITY_FACTOR
-	x = PyInt_FromLong(CL_QUALITY_FACTOR);
-	if (x == NULL || PyDict_SetItemString(d, "QUALITY_FACTOR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_QUALITY_LEVEL
-	x = PyInt_FromLong(CL_QUALITY_LEVEL);
-	if (x == NULL || PyDict_SetItemString(d, "QUALITY_LEVEL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_QUALITY_SPATIAL
-	x = PyInt_FromLong(CL_QUALITY_SPATIAL);
-	if (x == NULL || PyDict_SetItemString(d, "QUALITY_SPATIAL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_QUALITY_TEMPORAL
-	x = PyInt_FromLong(CL_QUALITY_TEMPORAL);
-	if (x == NULL || PyDict_SetItemString(d, "QUALITY_TEMPORAL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_QUANTIZATION_TABLES
-	x = PyInt_FromLong(CL_QUANTIZATION_TABLES);
-	if (x == NULL || PyDict_SetItemString(d, "QUANTIZATION_TABLES", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RANGE_VALUE
-	x = PyInt_FromLong(CL_RANGE_VALUE);
-	if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RGB
-	x = PyInt_FromLong(CL_RGB);
-	if (x == NULL || PyDict_SetItemString(d, "RGB", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RGB332
-	x = PyInt_FromLong(CL_RGB332);
-	if (x == NULL || PyDict_SetItemString(d, "RGB332", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RGB8
-	x = PyInt_FromLong(CL_RGB8);
-	if (x == NULL || PyDict_SetItemString(d, "RGB8", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RGBA
-	x = PyInt_FromLong(CL_RGBA);
-	if (x == NULL || PyDict_SetItemString(d, "RGBA", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RGBX
-	x = PyInt_FromLong(CL_RGBX);
-	if (x == NULL || PyDict_SetItemString(d, "RGBX", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RLE
-	x = PyInt_FromLong(CL_RLE);
-	if (x == NULL || PyDict_SetItemString(d, "RLE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RLE24
-	x = PyInt_FromLong(CL_RLE24);
-	if (x == NULL || PyDict_SetItemString(d, "RLE24", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RLE24_SOFTWARE
-	x = PyInt_FromLong(CL_RLE24_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "RLE24_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RLE_SOFTWARE
-	x = PyInt_FromLong(CL_RLE_SOFTWARE);
-	if (x == NULL || PyDict_SetItemString(d, "RLE_SOFTWARE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RTR
-	x = PyInt_FromLong(CL_RTR);
-	if (x == NULL || PyDict_SetItemString(d, "RTR", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RTR1
-	x = PyInt_FromLong(CL_RTR1);
-	if (x == NULL || PyDict_SetItemString(d, "RTR1", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_RTR_QUALITY_LEVEL
-	x = PyInt_FromLong(CL_RTR_QUALITY_LEVEL);
-	if (x == NULL || PyDict_SetItemString(d, "RTR_QUALITY_LEVEL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_SAMPLES_PER_TILE
-	x = PyInt_FromLong(CL_SAMPLES_PER_TILE);
-	if (x == NULL || PyDict_SetItemString(d, "SAMPLES_PER_TILE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_SCHEME_BUSY
-	x = PyInt_FromLong(CL_SCHEME_BUSY);
-	if (x == NULL || PyDict_SetItemString(d, "SCHEME_BUSY", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_SCHEME_NOT_AVAILABLE
-	x = PyInt_FromLong(CL_SCHEME_NOT_AVAILABLE);
-	if (x == NULL || PyDict_SetItemString(d, "SCHEME_NOT_AVAILABLE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_SPEED
-	x = PyInt_FromLong(CL_SPEED);
-	if (x == NULL || PyDict_SetItemString(d, "SPEED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_STEREO_INTERLEAVED
-	x = PyInt_FromLong(CL_STEREO_INTERLEAVED);
-	if (x == NULL || PyDict_SetItemString(d, "STEREO_INTERLEAVED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_STREAM_HEADERS
-	x = PyInt_FromLong(CL_STREAM_HEADERS);
-	if (x == NULL || PyDict_SetItemString(d, "STREAM_HEADERS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_TILE_THRESHOLD
-	x = PyInt_FromLong(CL_TILE_THRESHOLD);
-	if (x == NULL || PyDict_SetItemString(d, "TILE_THRESHOLD", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_TOP_DOWN
-	x = PyInt_FromLong(CL_TOP_DOWN);
-	if (x == NULL || PyDict_SetItemString(d, "TOP_DOWN", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_ULAW
-	x = PyInt_FromLong(CL_ULAW);
-	if (x == NULL || PyDict_SetItemString(d, "ULAW", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_UNCOMPRESSED
-	x = PyInt_FromLong(CL_UNCOMPRESSED);
-	if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_UNCOMPRESSED_AUDIO
-	x = PyInt_FromLong(CL_UNCOMPRESSED_AUDIO);
-	if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_AUDIO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_UNCOMPRESSED_VIDEO
-	x = PyInt_FromLong(CL_UNCOMPRESSED_VIDEO);
-	if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_VIDEO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_UNKNOWN_SCHEME
-	x = PyInt_FromLong(CL_UNKNOWN_SCHEME);
-	if (x == NULL || PyDict_SetItemString(d, "UNKNOWN_SCHEME", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_VIDEO
-	x = PyInt_FromLong(CL_VIDEO);
-	if (x == NULL || PyDict_SetItemString(d, "VIDEO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_Y
-	x = PyInt_FromLong(CL_Y);
-	if (x == NULL || PyDict_SetItemString(d, "Y", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YCbCr
-	x = PyInt_FromLong(CL_YCbCr);
-	if (x == NULL || PyDict_SetItemString(d, "YCbCr", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YCbCr422
-	x = PyInt_FromLong(CL_YCbCr422);
-	if (x == NULL || PyDict_SetItemString(d, "YCbCr422", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YCbCr422DC
-	x = PyInt_FromLong(CL_YCbCr422DC);
-	if (x == NULL || PyDict_SetItemString(d, "YCbCr422DC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YCbCr422HC
-	x = PyInt_FromLong(CL_YCbCr422HC);
-	if (x == NULL || PyDict_SetItemString(d, "YCbCr422HC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YUV
-	x = PyInt_FromLong(CL_YUV);
-	if (x == NULL || PyDict_SetItemString(d, "YUV", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YUV422
-	x = PyInt_FromLong(CL_YUV422);
-	if (x == NULL || PyDict_SetItemString(d, "YUV422", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YUV422DC
-	x = PyInt_FromLong(CL_YUV422DC);
-	if (x == NULL || PyDict_SetItemString(d, "YUV422DC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef CL_YUV422HC
-	x = PyInt_FromLong(CL_YUV422HC);
-	if (x == NULL || PyDict_SetItemString(d, "YUV422HC", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_STEREO
-	x = PyInt_FromLong(AWCMP_STEREO);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_STEREO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_JOINT_STEREO
-	x = PyInt_FromLong(AWCMP_JOINT_STEREO);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_JOINT_STEREO", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_INDEPENDENT
-	x = PyInt_FromLong(AWCMP_INDEPENDENT);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_INDEPENDENT", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_FIXED_RATE
-	x = PyInt_FromLong(AWCMP_FIXED_RATE);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_FIXED_RATE", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_CONST_QUAL
-	x = PyInt_FromLong(AWCMP_CONST_QUAL);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_CONST_QUAL", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_LOSSLESS
-	x = PyInt_FromLong(AWCMP_LOSSLESS);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_LOSSLESS", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_MPEG_LAYER_I
-	x = PyInt_FromLong(AWCMP_MPEG_LAYER_I);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_I", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-#ifdef AWCMP_MPEG_LAYER_II
-	x = PyInt_FromLong(AWCMP_MPEG_LAYER_II);
-	if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_II", x) < 0)
-		return;
-	Py_DECREF(x);
-#endif
-
-	(void) clSetErrorHandler(cl_ErrorHandler);
-}

Deleted: /python/branches/p3yk-noslice/Modules/collectionsmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/collectionsmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,1373 +0,0 @@
-#include "Python.h"
-#include "structmember.h"
-
-/* collections module implementation of a deque() datatype
-   Written and maintained by Raymond D. Hettinger <python at rcn.com>
-   Copyright (c) 2004 Python Software Foundation.
-   All rights reserved.
-*/
-
-/* The block length may be set to any number over 1.  Larger numbers
- * reduce the number of calls to the memory allocator but take more
- * memory.  Ideally, BLOCKLEN should be set with an eye to the
- * length of a cache line.
- */
-
-#define BLOCKLEN 62
-#define CENTER ((BLOCKLEN - 1) / 2)
-
-/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
- * This list is not circular (the leftmost block has leftlink==NULL,
- * and the rightmost block has rightlink==NULL).  A deque d's first
- * element is at d.leftblock[leftindex] and its last element is at
- * d.rightblock[rightindex]; note that, unlike as for Python slice
- * indices, these indices are inclusive on both ends.  By being inclusive
- * on both ends, algorithms for left and right operations become
- * symmetrical which simplifies the design.
- *
- * The list of blocks is never empty, so d.leftblock and d.rightblock
- * are never equal to NULL.
- *
- * The indices, d.leftindex and d.rightindex are always in the range
- *     0 <= index < BLOCKLEN.
- * Their exact relationship is:
- *     (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
- *
- * Empty deques have d.len == 0; d.leftblock==d.rightblock;
- * d.leftindex == CENTER+1; and d.rightindex == CENTER.
- * Checking for d.len == 0 is the intended way to see whether d is empty.
- *
- * Whenever d.leftblock == d.rightblock,
- *     d.leftindex + d.len - 1 == d.rightindex.
- *
- * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
- * become indices into distinct blocks and either may be larger than the
- * other.
- */
-
-typedef struct BLOCK {
-	struct BLOCK *leftlink;
-	struct BLOCK *rightlink;
-	PyObject *data[BLOCKLEN];
-} block;
-
-static block *
-newblock(block *leftlink, block *rightlink, int len) {
-	block *b;
-	/* To prevent len from overflowing INT_MAX on 64-bit machines, we
-	 * refuse to allocate new blocks if the current len is dangerously
-	 * close.  There is some extra margin to prevent spurious arithmetic
-	 * overflows at various places.  The following check ensures that
-	 * the blocks allocated to the deque, in the worst case, can only
-	 * have INT_MAX-2 entries in total.
-	 */
-	if (len >= INT_MAX - 2*BLOCKLEN) {
-		PyErr_SetString(PyExc_OverflowError,
-				"cannot add more blocks to the deque");
-		return NULL;
-	}
-	b = PyMem_Malloc(sizeof(block));
-	if (b == NULL) {
-		PyErr_NoMemory();
-		return NULL;
-	}
-	b->leftlink = leftlink;
-	b->rightlink = rightlink;
-	return b;
-}
-
-typedef struct {
-	PyObject_HEAD
-	block *leftblock;
-	block *rightblock;
-	int leftindex;	/* in range(BLOCKLEN) */
-	int rightindex;	/* in range(BLOCKLEN) */
-	int len;
-	long state;	/* incremented whenever the indices move */
-	PyObject *weakreflist; /* List of weak references */
-} dequeobject;
-
-static PyTypeObject deque_type;
-
-static PyObject *
-deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
-	dequeobject *deque;
-	block *b;
-
-	if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds))
-		return NULL;
-
-	/* create dequeobject structure */
-	deque = (dequeobject *)type->tp_alloc(type, 0);
-	if (deque == NULL)
-		return NULL;
-
-	b = newblock(NULL, NULL, 0);
-	if (b == NULL) {
-		Py_DECREF(deque);
-		return NULL;
-	}
-
-	assert(BLOCKLEN >= 2);
-	deque->leftblock = b;
-	deque->rightblock = b;
-	deque->leftindex = CENTER + 1;
-	deque->rightindex = CENTER;
-	deque->len = 0;
-	deque->state = 0;
-	deque->weakreflist = NULL;
-
-	return (PyObject *)deque;
-}
-
-static PyObject *
-deque_append(dequeobject *deque, PyObject *item)
-{
-	deque->state++;
-	if (deque->rightindex == BLOCKLEN-1) {
-		block *b = newblock(deque->rightblock, NULL, deque->len);
-		if (b == NULL)
-			return NULL;
-		assert(deque->rightblock->rightlink == NULL);
-		deque->rightblock->rightlink = b;
-		deque->rightblock = b;
-		deque->rightindex = -1;
-	}
-	Py_INCREF(item);
-	deque->len++;
-	deque->rightindex++;
-	deque->rightblock->data[deque->rightindex] = item;
-	Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
-
-static PyObject *
-deque_appendleft(dequeobject *deque, PyObject *item)
-{
-	deque->state++;
-	if (deque->leftindex == 0) {
-		block *b = newblock(NULL, deque->leftblock, deque->len);
-		if (b == NULL)
-			return NULL;
-		assert(deque->leftblock->leftlink == NULL);
-		deque->leftblock->leftlink = b;
-		deque->leftblock = b;
-		deque->leftindex = BLOCKLEN;
-	}
-	Py_INCREF(item);
-	deque->len++;
-	deque->leftindex--;
-	deque->leftblock->data[deque->leftindex] = item;
-	Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
-
-static PyObject *
-deque_pop(dequeobject *deque, PyObject *unused)
-{
-	PyObject *item;
-	block *prevblock;
-
-	if (deque->len == 0) {
-		PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
-		return NULL;
-	}
-	item = deque->rightblock->data[deque->rightindex];
-	deque->rightindex--;
-	deque->len--;
-	deque->state++;
-
-	if (deque->rightindex == -1) {
-		if (deque->len == 0) {
-			assert(deque->leftblock == deque->rightblock);
-			assert(deque->leftindex == deque->rightindex+1);
-			/* re-center instead of freeing a block */
-			deque->leftindex = CENTER + 1;
-			deque->rightindex = CENTER;
-		} else {
-			prevblock = deque->rightblock->leftlink;
-			assert(deque->leftblock != deque->rightblock);
-			PyMem_Free(deque->rightblock);
-			prevblock->rightlink = NULL;
-			deque->rightblock = prevblock;
-			deque->rightindex = BLOCKLEN - 1;
-		}
-	}
-	return item;
-}
-
-PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
-
-static PyObject *
-deque_popleft(dequeobject *deque, PyObject *unused)
-{
-	PyObject *item;
-	block *prevblock;
-
-	if (deque->len == 0) {
-		PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
-		return NULL;
-	}
-	assert(deque->leftblock != NULL);
-	item = deque->leftblock->data[deque->leftindex];
-	deque->leftindex++;
-	deque->len--;
-	deque->state++;
-
-	if (deque->leftindex == BLOCKLEN) {
-		if (deque->len == 0) {
-			assert(deque->leftblock == deque->rightblock);
-			assert(deque->leftindex == deque->rightindex+1);
-			/* re-center instead of freeing a block */
-			deque->leftindex = CENTER + 1;
-			deque->rightindex = CENTER;
-		} else {
-			assert(deque->leftblock != deque->rightblock);
-			prevblock = deque->leftblock->rightlink;
-			PyMem_Free(deque->leftblock);
-			assert(prevblock != NULL);
-			prevblock->leftlink = NULL;
-			deque->leftblock = prevblock;
-			deque->leftindex = 0;
-		}
-	}
-	return item;
-}
-
-PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
-
-static PyObject *
-deque_extend(dequeobject *deque, PyObject *iterable)
-{
-	PyObject *it, *item;
-
-	it = PyObject_GetIter(iterable);
-	if (it == NULL)
-		return NULL;
-
-	while ((item = PyIter_Next(it)) != NULL) {
-		deque->state++;
-		if (deque->rightindex == BLOCKLEN-1) {
-			block *b = newblock(deque->rightblock, NULL,
-					    deque->len);
-			if (b == NULL) {
-				Py_DECREF(item);
-				Py_DECREF(it);
-				return NULL;
-			}
-			assert(deque->rightblock->rightlink == NULL);
-			deque->rightblock->rightlink = b;
-			deque->rightblock = b;
-			deque->rightindex = -1;
-		}
-		deque->len++;
-		deque->rightindex++;
-		deque->rightblock->data[deque->rightindex] = item;
-	}
-	Py_DECREF(it);
-	if (PyErr_Occurred())
-		return NULL;
-	Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(extend_doc,
-"Extend the right side of the deque with elements from the iterable");
-
-static PyObject *
-deque_extendleft(dequeobject *deque, PyObject *iterable)
-{
-	PyObject *it, *item;
-
-	it = PyObject_GetIter(iterable);
-	if (it == NULL)
-		return NULL;
-
-	while ((item = PyIter_Next(it)) != NULL) {
-		deque->state++;
-		if (deque->leftindex == 0) {
-			block *b = newblock(NULL, deque->leftblock,
-					    deque->len);
-			if (b == NULL) {
-				Py_DECREF(item);
-				Py_DECREF(it);
-				return NULL;
-			}
-			assert(deque->leftblock->leftlink == NULL);
-			deque->leftblock->leftlink = b;
-			deque->leftblock = b;
-			deque->leftindex = BLOCKLEN;
-		}
-		deque->len++;
-		deque->leftindex--;
-		deque->leftblock->data[deque->leftindex] = item;
-	}
-	Py_DECREF(it);
-	if (PyErr_Occurred())
-		return NULL;
-	Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(extendleft_doc,
-"Extend the left side of the deque with elements from the iterable");
-
-static int
-_deque_rotate(dequeobject *deque, Py_ssize_t n)
-{
-	int i, len=deque->len, halflen=(len+1)>>1;
-	PyObject *item, *rv;
-
-	if (len == 0)
-		return 0;
-	if (n > halflen || n < -halflen) {
-		n %= len;
-		if (n > halflen)
-			n -= len;
-		else if (n < -halflen)
-			n += len;
-	}
-
-	for (i=0 ; i<n ; i++) {
-		item = deque_pop(deque, NULL);
-		assert (item != NULL);
-		rv = deque_appendleft(deque, item);
-		Py_DECREF(item);
-		if (rv == NULL)
-			return -1;
-		Py_DECREF(rv);
-	}
-	for (i=0 ; i>n ; i--) {
-		item = deque_popleft(deque, NULL);
-		assert (item != NULL);
-		rv = deque_append(deque, item);
-		Py_DECREF(item);
-		if (rv == NULL)
-			return -1;
-		Py_DECREF(rv);
-	}
-	return 0;
-}
-
-static PyObject *
-deque_rotate(dequeobject *deque, PyObject *args)
-{
-	int n=1;
-
-	if (!PyArg_ParseTuple(args, "|i:rotate", &n))
-		return NULL;
-	if (_deque_rotate(deque, n) == 0)
-		Py_RETURN_NONE;
-	return NULL;
-}
-
-PyDoc_STRVAR(rotate_doc,
-"Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left.");
-
-static Py_ssize_t
-deque_len(dequeobject *deque)
-{
-	return deque->len;
-}
-
-static PyObject *
-deque_remove(dequeobject *deque, PyObject *value)
-{
-	Py_ssize_t i, n=deque->len;
-
-	for (i=0 ; i<n ; i++) {
-		PyObject *item = deque->leftblock->data[deque->leftindex];
-		int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
-
-		if (deque->len != n) {
-			PyErr_SetString(PyExc_IndexError,
-				"deque mutated during remove().");
-			return NULL;
-		}
-		if (cmp > 0) {
-			PyObject *tgt = deque_popleft(deque, NULL);
-			assert (tgt != NULL);
-			Py_DECREF(tgt);
-			if (_deque_rotate(deque, i) == -1)
-				return NULL;
-			Py_RETURN_NONE;
-		}
-		else if (cmp < 0) {
-			_deque_rotate(deque, i);
-			return NULL;
-		}
-		_deque_rotate(deque, -1);
-	}
-	PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
-	return NULL;
-}
-
-PyDoc_STRVAR(remove_doc,
-"D.remove(value) -- remove first occurrence of value.");
-
-static int
-deque_clear(dequeobject *deque)
-{
-	PyObject *item;
-
-	while (deque->len) {
-		item = deque_pop(deque, NULL);
-		assert (item != NULL);
-		Py_DECREF(item);
-	}
-	assert(deque->leftblock == deque->rightblock &&
-	       deque->leftindex - 1 == deque->rightindex &&
-	       deque->len == 0);
-	return 0;
-}
-
-static PyObject *
-deque_item(dequeobject *deque, int i)
-{
-	block *b;
-	PyObject *item;
-	int n, index=i;
-
-	if (i < 0 || i >= deque->len) {
-		PyErr_SetString(PyExc_IndexError,
-				"deque index out of range");
-		return NULL;
-	}
-
-	if (i == 0) {
-		i = deque->leftindex;
-		b = deque->leftblock;
-	} else if (i == deque->len - 1) {
-		i = deque->rightindex;
-		b = deque->rightblock;
-	} else {
-		i += deque->leftindex;
-		n = i / BLOCKLEN;
-		i %= BLOCKLEN;
-		if (index < (deque->len >> 1)) {
-			b = deque->leftblock;
-			while (n--)
-				b = b->rightlink;
-		} else {
-			n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
-			b = deque->rightblock;
-			while (n--)
-				b = b->leftlink;
-		}
-	}
-	item = b->data[i];
-	Py_INCREF(item);
-	return item;
-}
-
-/* delitem() implemented in terms of rotate for simplicity and reasonable
-   performance near the end points.  If for some reason this method becomes
-   popular, it is not hard to re-implement this using direct data movement
-   (similar to code in list slice assignment) and achieve a two or threefold
-   performance boost.
-*/
-
-static int
-deque_del_item(dequeobject *deque, Py_ssize_t i)
-{
-	PyObject *item;
-
-	assert (i >= 0 && i < deque->len);
-	if (_deque_rotate(deque, -i) == -1)
-		return -1;
-
-	item = deque_popleft(deque, NULL);
-	assert (item != NULL);
-	Py_DECREF(item);
-
-	return _deque_rotate(deque, i);
-}
-
-static int
-deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
-{
-	PyObject *old_value;
-	block *b;
-	Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
-
-	if (i < 0 || i >= len) {
-		PyErr_SetString(PyExc_IndexError,
-				"deque index out of range");
-		return -1;
-	}
-	if (v == NULL)
-		return deque_del_item(deque, i);
-
-	i += deque->leftindex;
-	n = i / BLOCKLEN;
-	i %= BLOCKLEN;
-	if (index <= halflen) {
-		b = deque->leftblock;
-		while (n--)
-			b = b->rightlink;
-	} else {
-		n = (deque->leftindex + len - 1) / BLOCKLEN - n;
-		b = deque->rightblock;
-		while (n--)
-			b = b->leftlink;
-	}
-	Py_INCREF(v);
-	old_value = b->data[i];
-	b->data[i] = v;
-	Py_DECREF(old_value);
-	return 0;
-}
-
-static PyObject *
-deque_clearmethod(dequeobject *deque)
-{
-	int rv;
-
-	rv = deque_clear(deque);
-	assert (rv != -1);
-	Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
-
-static void
-deque_dealloc(dequeobject *deque)
-{
-	PyObject_GC_UnTrack(deque);
-	if (deque->weakreflist != NULL)
-		PyObject_ClearWeakRefs((PyObject *) deque);
-	if (deque->leftblock != NULL) {
-		deque_clear(deque);
-		assert(deque->leftblock != NULL);
-		PyMem_Free(deque->leftblock);
-	}
-	deque->leftblock = NULL;
-	deque->rightblock = NULL;
-	deque->ob_type->tp_free(deque);
-}
-
-static int
-deque_traverse(dequeobject *deque, visitproc visit, void *arg)
-{
-	block *b;
-	PyObject *item;
-	int index;
-	int indexlo = deque->leftindex;
-
-	for (b = deque->leftblock; b != NULL; b = b->rightlink) {
-		const int indexhi = b == deque->rightblock ?
-					 deque->rightindex :
-				    	 BLOCKLEN - 1;
-
-		for (index = indexlo; index <= indexhi; ++index) {
-			item = b->data[index];
-			Py_VISIT(item);
-		}
-		indexlo = 0;
-	}
-	return 0;
-}
-
-static long
-deque_nohash(PyObject *self)
-{
-	PyErr_SetString(PyExc_TypeError, "deque objects are unhashable");
-	return -1;
-}
-
-static PyObject *
-deque_copy(PyObject *deque)
-{
-	return PyObject_CallFunctionObjArgs((PyObject *)(deque->ob_type),
-		deque, NULL);
-}
-
-PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
-
-static PyObject *
-deque_reduce(dequeobject *deque)
-{
-	PyObject *dict, *result, *it;
-
-	dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
-	if (dict == NULL) {
-		PyErr_Clear();
-		dict = Py_None;
-		Py_INCREF(dict);
-	}
-	it = PyObject_GetIter((PyObject *)deque);
-	if (it == NULL) {
-		Py_DECREF(dict);
-		return NULL;
-	}
-	result = Py_BuildValue("O()ON", deque->ob_type, dict, it);
-	Py_DECREF(dict);
-	return result;
-}
-
-PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
-
-static PyObject *
-deque_repr(PyObject *deque)
-{
-	PyObject *aslist, *result, *fmt;
-	int i;
-
-	i = Py_ReprEnter(deque);
-	if (i != 0) {
-		if (i < 0)
-			return NULL;
-		return PyString_FromString("[...]");
-	}
-
-	aslist = PySequence_List(deque);
-	if (aslist == NULL) {
-		Py_ReprLeave(deque);
-		return NULL;
-	}
-
-	fmt = PyString_FromString("deque(%r)");
-	if (fmt == NULL) {
-		Py_DECREF(aslist);
-		Py_ReprLeave(deque);
-		return NULL;
-	}
-	result = PyString_Format(fmt, aslist);
-	Py_DECREF(fmt);
-	Py_DECREF(aslist);
-	Py_ReprLeave(deque);
-	return result;
-}
-
-static int
-deque_tp_print(PyObject *deque, FILE *fp, int flags)
-{
-	PyObject *it, *item;
-	char *emit = "";	/* No separator emitted on first pass */
-	char *separator = ", ";
-	int i;
-
-	i = Py_ReprEnter(deque);
-	if (i != 0) {
-		if (i < 0)
-			return i;
-		fputs("[...]", fp);
-		return 0;
-	}
-
-	it = PyObject_GetIter(deque);
-	if (it == NULL)
-		return -1;
-
-	fputs("deque([", fp);
-	while ((item = PyIter_Next(it)) != NULL) {
-		fputs(emit, fp);
-		emit = separator;
-		if (PyObject_Print(item, fp, 0) != 0) {
-			Py_DECREF(item);
-			Py_DECREF(it);
-			Py_ReprLeave(deque);
-			return -1;
-		}
-		Py_DECREF(item);
-	}
-	Py_ReprLeave(deque);
-	Py_DECREF(it);
-	if (PyErr_Occurred())
-		return -1;
-	fputs("])", fp);
-	return 0;
-}
-
-static PyObject *
-deque_richcompare(PyObject *v, PyObject *w, int op)
-{
-	PyObject *it1=NULL, *it2=NULL, *x, *y;
-	int b, vs, ws, cmp=-1;
-
-	if (!PyObject_TypeCheck(v, &deque_type) ||
-	    !PyObject_TypeCheck(w, &deque_type)) {
-		Py_INCREF(Py_NotImplemented);
-		return Py_NotImplemented;
-	}
-
-	/* Shortcuts */
-	vs = ((dequeobject *)v)->len;
-	ws = ((dequeobject *)w)->len;
-	if (op == Py_EQ) {
-		if (v == w)
-			Py_RETURN_TRUE;
-		if (vs != ws)
-			Py_RETURN_FALSE;
-	}
-	if (op == Py_NE) {
-		if (v == w)
-			Py_RETURN_FALSE;
-		if (vs != ws)
-			Py_RETURN_TRUE;
-	}
-
-	/* Search for the first index where items are different */
-	it1 = PyObject_GetIter(v);
-	if (it1 == NULL)
-		goto done;
-	it2 = PyObject_GetIter(w);
-	if (it2 == NULL)
-		goto done;
-	for (;;) {
-		x = PyIter_Next(it1);
-		if (x == NULL && PyErr_Occurred())
-			goto done;
-		y = PyIter_Next(it2);
-		if (x == NULL || y == NULL)
-			break;
-		b = PyObject_RichCompareBool(x, y, Py_EQ);
-		if (b == 0) {
-			cmp = PyObject_RichCompareBool(x, y, op);
-			Py_DECREF(x);
-			Py_DECREF(y);
-			goto done;
-		}
-		Py_DECREF(x);
-		Py_DECREF(y);
-		if (b == -1)
-			goto done;
-	}
-	/* We reached the end of one deque or both */
-	Py_XDECREF(x);
-	Py_XDECREF(y);
-	if (PyErr_Occurred())
-		goto done;
-	switch (op) {
-	case Py_LT: cmp = y != NULL; break;  /* if w was longer */
-	case Py_LE: cmp = x == NULL; break;  /* if v was not longer */
-	case Py_EQ: cmp = x == y;    break;  /* if we reached the end of both */
-	case Py_NE: cmp = x != y;    break;  /* if one deque continues */
-	case Py_GT: cmp = x != NULL; break;  /* if v was longer */
-	case Py_GE: cmp = y == NULL; break;  /* if w was not longer */
-	}
-
-done:
-	Py_XDECREF(it1);
-	Py_XDECREF(it2);
-	if (cmp == 1)
-		Py_RETURN_TRUE;
-	if (cmp == 0)
-		Py_RETURN_FALSE;
-	return NULL;
-}
-
-static int
-deque_init(dequeobject *deque, PyObject *args, PyObject *kwds)
-{
-	PyObject *iterable = NULL;
-
-	if (!PyArg_UnpackTuple(args, "deque", 0, 1, &iterable))
-		return -1;
-
-	if (iterable != NULL) {
-		PyObject *rv = deque_extend(deque, iterable);
-		if (rv == NULL)
-			return -1;
-		Py_DECREF(rv);
-	}
-	return 0;
-}
-
-static PySequenceMethods deque_as_sequence = {
-	(lenfunc)deque_len,		/* sq_length */
-	0,				/* sq_concat */
-	0,				/* sq_repeat */
-	(ssizeargfunc)deque_item,	/* sq_item */
-	0,				/* sq_slice */
-	(ssizeobjargproc)deque_ass_item,	/* sq_ass_item */
-};
-
-/* deque object ********************************************************/
-
-static PyObject *deque_iter(dequeobject *deque);
-static PyObject *deque_reviter(dequeobject *deque);
-PyDoc_STRVAR(reversed_doc,
-	"D.__reversed__() -- return a reverse iterator over the deque");
-
-static PyMethodDef deque_methods[] = {
-	{"append",		(PyCFunction)deque_append,
-		METH_O,		 append_doc},
-	{"appendleft",		(PyCFunction)deque_appendleft,
-		METH_O,		 appendleft_doc},
-	{"clear",		(PyCFunction)deque_clearmethod,
-		METH_NOARGS,	 clear_doc},
-	{"__copy__",		(PyCFunction)deque_copy,
-		METH_NOARGS,	 copy_doc},
-	{"extend",		(PyCFunction)deque_extend,
-		METH_O,		 extend_doc},
-	{"extendleft",		(PyCFunction)deque_extendleft,
-		METH_O,		 extendleft_doc},
-	{"pop",			(PyCFunction)deque_pop,
-		METH_NOARGS,	 pop_doc},
-	{"popleft",		(PyCFunction)deque_popleft,
-		METH_NOARGS,	 popleft_doc},
-	{"__reduce__",	(PyCFunction)deque_reduce,
-		METH_NOARGS,	 reduce_doc},
-	{"remove",		(PyCFunction)deque_remove,
-		METH_O,		 remove_doc},
-	{"__reversed__",	(PyCFunction)deque_reviter,
-		METH_NOARGS,	 reversed_doc},
-	{"rotate",		(PyCFunction)deque_rotate,
-		METH_VARARGS,	rotate_doc},
-	{NULL,		NULL}	/* sentinel */
-};
-
-PyDoc_STRVAR(deque_doc,
-"deque(iterable) --> deque object\n\
-\n\
-Build an ordered collection accessible from endpoints only.");
-
-static PyTypeObject deque_type = {
-	PyObject_HEAD_INIT(NULL)
-	0,				/* ob_size */
-	"collections.deque",		/* tp_name */
-	sizeof(dequeobject),		/* tp_basicsize */
-	0,				/* tp_itemsize */
-	/* methods */
-	(destructor)deque_dealloc,	/* tp_dealloc */
-	deque_tp_print,			/* tp_print */
-	0,				/* tp_getattr */
-	0,				/* tp_setattr */
-	0,				/* tp_compare */
-	deque_repr,			/* tp_repr */
-	0,				/* tp_as_number */
-	&deque_as_sequence,		/* tp_as_sequence */
-	0,				/* tp_as_mapping */
-	deque_nohash,			/* tp_hash */
-	0,				/* tp_call */
-	0,				/* tp_str */
-	PyObject_GenericGetAttr,	/* tp_getattro */
-	0,				/* tp_setattro */
-	0,				/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
-		 Py_TPFLAGS_HAVE_GC,	/* tp_flags */
-	deque_doc,			/* tp_doc */
-	(traverseproc)deque_traverse,	/* tp_traverse */
-	(inquiry)deque_clear,		/* tp_clear */
-	(richcmpfunc)deque_richcompare,	/* tp_richcompare */
-	offsetof(dequeobject, weakreflist),	/* tp_weaklistoffset*/
-	(getiterfunc)deque_iter,	/* tp_iter */
-	0,				/* tp_iternext */
-	deque_methods,			/* tp_methods */
-	0,				/* tp_members */
-	0,				/* tp_getset */
-	0,				/* tp_base */
-	0,				/* tp_dict */
-	0,				/* tp_descr_get */
-	0,				/* tp_descr_set */
-	0,				/* tp_dictoffset */
-	(initproc)deque_init,		/* tp_init */
-	PyType_GenericAlloc,		/* tp_alloc */
-	deque_new,			/* tp_new */
-	PyObject_GC_Del,		/* tp_free */
-};
-
-/*********************** Deque Iterator **************************/
-
-typedef struct {
-	PyObject_HEAD
-	int index;
-	block *b;
-	dequeobject *deque;
-	long state;	/* state when the iterator is created */
-	int counter;    /* number of items remaining for iteration */
-} dequeiterobject;
-
-PyTypeObject dequeiter_type;
-
-static PyObject *
-deque_iter(dequeobject *deque)
-{
-	dequeiterobject *it;
-
-	it = PyObject_New(dequeiterobject, &dequeiter_type);
-	if (it == NULL)
-		return NULL;
-	it->b = deque->leftblock;
-	it->index = deque->leftindex;
-	Py_INCREF(deque);
-	it->deque = deque;
-	it->state = deque->state;
-	it->counter = deque->len;
-	return (PyObject *)it;
-}
-
-static void
-dequeiter_dealloc(dequeiterobject *dio)
-{
-	Py_XDECREF(dio->deque);
-	dio->ob_type->tp_free(dio);
-}
-
-static PyObject *
-dequeiter_next(dequeiterobject *it)
-{
-	PyObject *item;
-
-	if (it->deque->state != it->state) {
-		it->counter = 0;
-		PyErr_SetString(PyExc_RuntimeError,
-				"deque mutated during iteration");
-		return NULL;
-	}
-	if (it->counter == 0)
-		return NULL;        
-	assert (!(it->b == it->deque->rightblock &&
-		  it->index > it->deque->rightindex));
-
-	item = it->b->data[it->index];
-	it->index++;
-	it->counter--;
-	if (it->index == BLOCKLEN && it->counter > 0) {
-		assert (it->b->rightlink != NULL);
-		it->b = it->b->rightlink;
-		it->index = 0;
-	}
-	Py_INCREF(item);
-	return item;
-}
-
-static PyObject *
-dequeiter_len(dequeiterobject *it)
-{
-	return PyInt_FromLong(it->counter);
-}
-
-PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
-
-static PyMethodDef dequeiter_methods[] = {
-	{"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
- 	{NULL,		NULL}		/* sentinel */
-};
-
-PyTypeObject dequeiter_type = {
-	PyObject_HEAD_INIT(NULL)
-	0,					/* ob_size */
-	"deque_iterator",			/* tp_name */
-	sizeof(dequeiterobject),		/* tp_basicsize */
-	0,					/* tp_itemsize */
-	/* methods */
-	(destructor)dequeiter_dealloc,		/* tp_dealloc */
-	0,					/* tp_print */
-	0,					/* tp_getattr */
-	0,					/* tp_setattr */
-	0,					/* tp_compare */
-	0,					/* tp_repr */
-	0,					/* tp_as_number */
-	0,					/* tp_as_sequence */
-	0,					/* tp_as_mapping */
-	0,					/* tp_hash */
-	0,					/* tp_call */
-	0,					/* tp_str */
-	PyObject_GenericGetAttr,		/* tp_getattro */
-	0,					/* tp_setattro */
-	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
-	0,					/* tp_doc */
-	0,					/* tp_traverse */
-	0,					/* tp_clear */
-	0,					/* tp_richcompare */
-	0,					/* tp_weaklistoffset */
-	PyObject_SelfIter,			/* tp_iter */
-	(iternextfunc)dequeiter_next,		/* tp_iternext */
-	dequeiter_methods,			/* tp_methods */
-	0,
-};
-
-/*********************** Deque Reverse Iterator **************************/
-
-PyTypeObject dequereviter_type;
-
-static PyObject *
-deque_reviter(dequeobject *deque)
-{
-	dequeiterobject *it;
-
-	it = PyObject_New(dequeiterobject, &dequereviter_type);
-	if (it == NULL)
-		return NULL;
-	it->b = deque->rightblock;
-	it->index = deque->rightindex;
-	Py_INCREF(deque);
-	it->deque = deque;
-	it->state = deque->state;
-	it->counter = deque->len;
-	return (PyObject *)it;
-}
-
-static PyObject *
-dequereviter_next(dequeiterobject *it)
-{
-	PyObject *item;
-	if (it->counter == 0)
-		return NULL;
-
-	if (it->deque->state != it->state) {
-		it->counter = 0;
-		PyErr_SetString(PyExc_RuntimeError,
-				"deque mutated during iteration");
-		return NULL;
-	}
-	assert (!(it->b == it->deque->leftblock &&
-		  it->index < it->deque->leftindex));
-
-	item = it->b->data[it->index];
-	it->index--;
-	it->counter--;
-	if (it->index == -1 && it->counter > 0) {
-		assert (it->b->leftlink != NULL);
-		it->b = it->b->leftlink;
-		it->index = BLOCKLEN - 1;
-	}
-	Py_INCREF(item);
-	return item;
-}
-
-PyTypeObject dequereviter_type = {
-	PyObject_HEAD_INIT(NULL)
-	0,					/* ob_size */
-	"deque_reverse_iterator",		/* tp_name */
-	sizeof(dequeiterobject),		/* tp_basicsize */
-	0,					/* tp_itemsize */
-	/* methods */
-	(destructor)dequeiter_dealloc,		/* tp_dealloc */
-	0,					/* tp_print */
-	0,					/* tp_getattr */
-	0,					/* tp_setattr */
-	0,					/* tp_compare */
-	0,					/* tp_repr */
-	0,					/* tp_as_number */
-	0,					/* tp_as_sequence */
-	0,					/* tp_as_mapping */
-	0,					/* tp_hash */
-	0,					/* tp_call */
-	0,					/* tp_str */
-	PyObject_GenericGetAttr,		/* tp_getattro */
-	0,					/* tp_setattro */
-	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,			/* tp_flags */
-	0,					/* tp_doc */
-	0,					/* tp_traverse */
-	0,					/* tp_clear */
-	0,					/* tp_richcompare */
-	0,					/* tp_weaklistoffset */
-	PyObject_SelfIter,			/* tp_iter */
-	(iternextfunc)dequereviter_next,	/* tp_iternext */
-	dequeiter_methods,			/* tp_methods */
-	0,
-};
-
-/* defaultdict type *********************************************************/
-
-typedef struct {
-	PyDictObject dict;
-	PyObject *default_factory;
-} defdictobject;
-
-static PyTypeObject defdict_type; /* Forward */
-
-PyDoc_STRVAR(defdict_missing_doc,
-"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
-  if self.default_factory is None: raise KeyError(key)\n\
-  self[key] = value = self.default_factory()\n\
-  return value\n\
-");
-
-static PyObject *
-defdict_missing(defdictobject *dd, PyObject *key)
-{
-	PyObject *factory = dd->default_factory;
-	PyObject *value;
-	if (factory == NULL || factory == Py_None) {
-		/* XXX Call dict.__missing__(key) */
-		PyErr_SetObject(PyExc_KeyError, key);
-		return NULL;
-	}
-	value = PyEval_CallObject(factory, NULL);
-	if (value == NULL)
-		return value;
-	if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
-		Py_DECREF(value);
-		return NULL;
-	}
-	return value;
-}
-
-PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
-
-static PyObject *
-defdict_copy(defdictobject *dd)
-{
-	/* This calls the object's class.  That only works for subclasses
-	   whose class constructor has the same signature.  Subclasses that
-	   define a different constructor signature must override copy().
-	*/
-	return PyObject_CallFunctionObjArgs((PyObject *)dd->dict.ob_type,
-					    dd->default_factory, dd, NULL);
-}
-
-static PyObject *
-defdict_reduce(defdictobject *dd)
-{
-	/* __reduce__ must return a 5-tuple as follows:
-
-	   - factory function
-	   - tuple of args for the factory function
-	   - additional state (here None)
-	   - sequence iterator (here None)
-	   - dictionary iterator (yielding successive (key, value) pairs
-
-	   This API is used by pickle.py and copy.py.
-
-	   For this to be useful with pickle.py, the default_factory
-	   must be picklable; e.g., None, a built-in, or a global
-	   function in a module or package.
-
-	   Both shallow and deep copying are supported, but for deep
-	   copying, the default_factory must be deep-copyable; e.g. None,
-	   or a built-in (functions are not copyable at this time).
-
-	   This only works for subclasses as long as their constructor
-	   signature is compatible; the first argument must be the
-	   optional default_factory, defaulting to None.
-	*/
-	PyObject *args;
-	PyObject *items;
-	PyObject *iteritems;
-	PyObject *result;
-	if (dd->default_factory == NULL || dd->default_factory == Py_None)
-		args = PyTuple_New(0);
-	else
-		args = PyTuple_Pack(1, dd->default_factory);
-	if (args == NULL)
-		return NULL;
-	items = PyObject_CallMethod((PyObject *)dd, "items", "()");
-	if (items == NULL) {
-		Py_DECREF(args);
-		return NULL;
-	}
-	iteritems = PyObject_GetIter(items);
-	Py_DECREF(items);
-	if (iteritems == NULL) {
-		Py_DECREF(args);
-		return NULL;
-	}
-	result = PyTuple_Pack(5, dd->dict.ob_type, args,
-			      Py_None, Py_None, iteritems);
-	Py_DECREF(iteritems);
-	Py_DECREF(args);
-	return result;
-}
-
-static PyMethodDef defdict_methods[] = {
-	{"__missing__", (PyCFunction)defdict_missing, METH_O,
-	 defdict_missing_doc},
-	{"copy", (PyCFunction)defdict_copy, METH_NOARGS,
-	 defdict_copy_doc},
-	{"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
-	 defdict_copy_doc},
-	{"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
-	 reduce_doc},
-	{NULL}
-};
-
-static PyMemberDef defdict_members[] = {
-	{"default_factory", T_OBJECT,
-	 offsetof(defdictobject, default_factory), 0,
-	 PyDoc_STR("Factory for default value called by __missing__().")},
-	{NULL}
-};
-
-static void
-defdict_dealloc(defdictobject *dd)
-{
-	Py_CLEAR(dd->default_factory);
-	PyDict_Type.tp_dealloc((PyObject *)dd);
-}
-
-static int
-defdict_print(defdictobject *dd, FILE *fp, int flags)
-{
-	int sts;
-	fprintf(fp, "defaultdict(");
-	if (dd->default_factory == NULL)
-		fprintf(fp, "None");
-	else {
-		PyObject_Print(dd->default_factory, fp, 0);
-	}
-	fprintf(fp, ", ");
-	sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
-	fprintf(fp, ")");
-	return sts;
-}
-
-static PyObject *
-defdict_repr(defdictobject *dd)
-{
-	PyObject *defrepr;
-	PyObject *baserepr;
-	PyObject *result;
-	baserepr = PyDict_Type.tp_repr((PyObject *)dd);
-	if (baserepr == NULL)
-		return NULL;
-	if (dd->default_factory == NULL)
-		defrepr = PyString_FromString("None");
-	else
-		defrepr = PyObject_Repr(dd->default_factory);
-	if (defrepr == NULL) {
-		Py_DECREF(baserepr);
-		return NULL;
-	}
-	result = PyString_FromFormat("defaultdict(%s, %s)",
-				     PyString_AS_STRING(defrepr),
-				     PyString_AS_STRING(baserepr));
-	Py_DECREF(defrepr);
-	Py_DECREF(baserepr);
-	return result;
-}
-
-static int
-defdict_traverse(PyObject *self, visitproc visit, void *arg)
-{
-	Py_VISIT(((defdictobject *)self)->default_factory);
-	return PyDict_Type.tp_traverse(self, visit, arg);
-}
-
-static int
-defdict_tp_clear(defdictobject *dd)
-{
-	Py_CLEAR(dd->default_factory);
-	return PyDict_Type.tp_clear((PyObject *)dd);
-}
-
-static int
-defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
-{
-	defdictobject *dd = (defdictobject *)self;
-	PyObject *olddefault = dd->default_factory;
-	PyObject *newdefault = NULL;
-	PyObject *newargs;
-	int result;
-	if (args == NULL || !PyTuple_Check(args))
-		newargs = PyTuple_New(0);
-	else {
-		Py_ssize_t n = PyTuple_GET_SIZE(args);
-		if (n > 0) {
-			newdefault = PyTuple_GET_ITEM(args, 0);
-			if (!PyCallable_Check(newdefault)) {
-				PyErr_SetString(PyExc_TypeError,
-					"first argument must be callable");                           
-				return -1;
-			}
-		}
-		newargs = PySequence_GetSlice(args, 1, n);
-	}
-	if (newargs == NULL)
-		return -1;
-	Py_XINCREF(newdefault);
-	dd->default_factory = newdefault;
-	result = PyDict_Type.tp_init(self, newargs, kwds);
-	Py_DECREF(newargs);
-	Py_XDECREF(olddefault);
-	return result;
-}
-
-PyDoc_STRVAR(defdict_doc,
-"defaultdict(default_factory) --> dict with default factory\n\
-\n\
-The default factory is called without arguments to produce\n\
-a new value when a key is not present, in __getitem__ only.\n\
-A defaultdict compares equal to a dict with the same items.\n\
-");
-
-/* See comment in xxsubtype.c */
-#define DEFERRED_ADDRESS(ADDR) 0
-
-static PyTypeObject defdict_type = {
-	PyObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type))
-	0,				/* ob_size */
-	"collections.defaultdict",	/* tp_name */
-	sizeof(defdictobject),		/* tp_basicsize */
-	0,				/* tp_itemsize */
-	/* methods */
-	(destructor)defdict_dealloc,	/* tp_dealloc */
-	(printfunc)defdict_print,	/* tp_print */
-	0,				/* tp_getattr */
-	0,				/* tp_setattr */
-	0,				/* tp_compare */
-	(reprfunc)defdict_repr,		/* tp_repr */
-	0,				/* tp_as_number */
-	0,				/* tp_as_sequence */
-	0,				/* tp_as_mapping */
-	0,	       			/* tp_hash */
-	0,				/* tp_call */
-	0,				/* tp_str */
-	PyObject_GenericGetAttr,	/* tp_getattro */
-	0,				/* tp_setattro */
-	0,				/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
-		Py_TPFLAGS_HAVE_GC,	/* tp_flags */
-	defdict_doc,			/* tp_doc */
-	defdict_traverse,		/* tp_traverse */
-	(inquiry)defdict_tp_clear,	/* tp_clear */
-	0,				/* tp_richcompare */
-	0,				/* tp_weaklistoffset*/
-	0,				/* tp_iter */
-	0,				/* tp_iternext */
-	defdict_methods,		/* tp_methods */
-	defdict_members,		/* tp_members */
-	0,				/* tp_getset */
-	DEFERRED_ADDRESS(&PyDict_Type),	/* tp_base */
-	0,				/* tp_dict */
-	0,				/* tp_descr_get */
-	0,				/* tp_descr_set */
-	0,				/* tp_dictoffset */
-	defdict_init,			/* tp_init */
-	PyType_GenericAlloc,		/* tp_alloc */
-	0,				/* tp_new */
-	PyObject_GC_Del,		/* tp_free */
-};
-
-/* module level code ********************************************************/
-
-PyDoc_STRVAR(module_doc,
-"High performance data structures.\n\
-- deque:        ordered collection accessible from endpoints only\n\
-- defaultdict:  dict subclass with a default value factory\n\
-");
-
-PyMODINIT_FUNC
-initcollections(void)
-{
-	PyObject *m;
-
-	m = Py_InitModule3("collections", NULL, module_doc);
-	if (m == NULL)
-		return;
-
-	if (PyType_Ready(&deque_type) < 0)
-		return;
-	Py_INCREF(&deque_type);
-	PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
-
-	defdict_type.tp_base = &PyDict_Type;
-	if (PyType_Ready(&defdict_type) < 0)
-		return;
-	Py_INCREF(&defdict_type);
-	PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
-
-	if (PyType_Ready(&dequeiter_type) < 0)
-		return;
-
-	if (PyType_Ready(&dequereviter_type) < 0)
-		return;
-
-	return;
-}

Modified: python/branches/p3yk-noslice/Modules/config.c.in
==============================================================================
--- python/branches/p3yk-noslice/Modules/config.c.in	(original)
+++ python/branches/p3yk-noslice/Modules/config.c.in	Wed Jul 11 15:40:56 2007
@@ -50,7 +50,6 @@
 	{"__main__", NULL},
 	{"__builtin__", NULL},
 	{"sys", NULL},
-	{"exceptions", NULL},
 
 	/* This lives in gcmodule.c */
 	{"gc", initgc},
@@ -63,4 +62,3 @@
 #ifdef __cplusplus
 }
 #endif
-

Deleted: /python/branches/p3yk-noslice/Modules/cstubs
==============================================================================
--- /python/branches/p3yk-noslice/Modules/cstubs	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,1362 +0,0 @@
-
-/*
-Input used to generate the Python module "glmodule.c".
-The stub generator is a Python script called "cgen.py".
-
-Each definition must be contained on one line:
-
-<returntype> <name> <type> <arg> <type> <arg>
-
-<returntype> can be: void, short, long (XXX maybe others?)
-
-<type> can be: char, string, short, float, long, or double
-	string indicates a null terminated string;
-	if <type> is char and <arg> begins with a *, the * is stripped
-	and <type> is changed into string
-
-<arg> has the form <mode> or <mode>[<subscript>]
-	where <mode> can be
-		s: arg is sent
-		r: arg is received		(arg is a pointer)
-	and <subscript> can be (N and I are numbers):
-		N
-		argI
-		retval
-		N*argI
-		N*I
-		N*retval
-	In the case where the subscript consists of two parts
-	separated by *, the first part is the width of the matrix, and
-	the second part is the length of the matrix.  This order is
-	opposite from the order used in C to declare a two-dimensional
-	matrix.
-*/
-
-/*
- * An attempt has been made to make this module switch threads on qread
- * calls. It is far from safe, though.
- */
-
-#include <gl.h>
-#include <device.h>
-
-#ifdef __sgi
-extern int devport();
-extern int textwritemask();
-extern int pagewritemask();
-extern int gewrite();
-extern int gettp();
-#endif
-
-#include "Python.h"
-#include "cgensupport.h"
-
-/*
-Some stubs are too complicated for the stub generator.
-We can include manually written versions of them here.
-A line starting with '%' gives the name of the function so the stub
-generator can include it in the table of functions.
-*/
-
-% qread
-
-static PyObject *
-gl_qread(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	long retval;
-	short arg1 ;
-	Py_BEGIN_ALLOW_THREADS
-	retval = qread( & arg1 );
-	Py_END_ALLOW_THREADS
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewlongobject(retval));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg1));
-	  return v;
-	}
-}
-
-
-/*
-varray -- an array of v.. calls.
-The argument is an array (maybe list or tuple) of points.
-Each point must be a tuple or list of coordinates (x, y, z).
-The points may be 2- or 3-dimensional but must all have the
-same dimension.  Float and int values may be mixed however.
-The points are always converted to 3D double precision points
-by assuming z=0.0 if necessary (as indicated in the man page),
-and for each point v3d() is called.
-*/
-
-% varray
-
-static PyObject *
-gl_varray(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	PyObject *v, *w=NULL;
-	int i, n, width;
-	double vec[3];
-	PyObject * (*getitem)(PyObject *, int);
-	
-	if (!PyArg_GetObject(args, 1, 0, &v))
-		return NULL;
-	
-	if (PyList_Check(v)) {
-		n = PyList_Size(v);
-		getitem = PyList_GetItem;
-	}
-	else if (PyTuple_Check(v)) {
-		n = PyTuple_Size(v);
-		getitem = PyTuple_GetItem;
-	}
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	
-	if (n == 0) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	if (n > 0)
-		w = (*getitem)(v, 0);
-	
-	width = 0;
-	if (w == NULL) {
-	}
-	else if (PyList_Check(w)) {
-		width = PyList_Size(w);
-	}
-	else if (PyTuple_Check(w)) {
-		width = PyTuple_Size(w);
-	}
-	
-	switch (width) {
-	case 2:
-		vec[2] = 0.0;
-		/* Fall through */
-	case 3:
-		break;
-	default:
-		PyErr_BadArgument();
-		return NULL;
-	}
-	
-	for (i = 0; i < n; i++) {
-		w = (*getitem)(v, i);
-		if (!PyArg_GetDoubleArray(w, 1, 0, width, vec))
-			return NULL;
-		v3d(vec);
-	}
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/*
-vnarray, nvarray -- an array of n3f and v3f calls.
-The argument is an array (list or tuple) of pairs of points and normals.
-Each pair is a tuple (NOT a list) of a point and a normal for that point.
-Each point or normal must be a tuple (NOT a list) of coordinates (x, y, z).
-Three coordinates must be given.  Float and int values may be mixed.
-For each pair, n3f() is called for the normal, and then v3f() is called
-for the vector.
-
-vnarray and nvarray differ only in the order of the vector and normal in
-the pair: vnarray expects (v, n) while nvarray expects (n, v).
-*/
-
-static PyObject *gen_nvarray(); /* Forward */
-
-% nvarray
-
-static PyObject *
-gl_nvarray(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	return gen_nvarray(args, 0);
-}
-
-% vnarray
-
-static PyObject *
-gl_vnarray(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	return gen_nvarray(args, 1);
-}
-
-/* Generic, internal version of {nv,nv}array: inorm indicates the
-   argument order, 0: normal first, 1: vector first. */
-
-static PyObject *
-gen_nvarray(args, inorm)
-	PyObject *args;
-	int inorm;
-{
-	PyObject *v, *w, *wnorm, *wvec;
-	int i, n;
-	float norm[3], vec[3];
-	PyObject * (*getitem)(PyObject *, int);
-	
-	if (!PyArg_GetObject(args, 1, 0, &v))
-		return NULL;
-	
-	if (PyList_Check(v)) {
-		n = PyList_Size(v);
-		getitem = PyList_GetItem;
-	}
-	else if (PyTuple_Check(v)) {
-		n = PyTuple_Size(v);
-		getitem = PyTuple_GetItem;
-	}
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	
-	for (i = 0; i < n; i++) {
-		w = (*getitem)(v, i);
-		if (!PyTuple_Check(w) || PyTuple_Size(w) != 2) {
-			PyErr_BadArgument();
-			return NULL;
-		}
-		wnorm = PyTuple_GetItem(w, inorm);
-		wvec = PyTuple_GetItem(w, 1 - inorm);
-		if (!PyArg_GetFloatArray(wnorm, 1, 0, 3, norm) ||
-			!PyArg_GetFloatArray(wvec, 1, 0, 3, vec))
-			return NULL;
-		n3f(norm);
-		v3f(vec);
-	}
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type).
-   The dimensions of ctl[] are computed as follows:
-   [len(s_knots) - s_order], [len(t_knots) - t_order]
-*/
-
-% nurbssurface
-
-static PyObject *
-gl_nurbssurface(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	long arg1 ;
-	double * arg2 ;
-	long arg3 ;
-	double * arg4 ;
-	double *arg5 ;
-	long arg6 ;
-	long arg7 ;
-	long arg8 ;
-	long ncoords;
-	long s_byte_stride, t_byte_stride;
-	long s_nctl, t_nctl;
-	long s, t;
-	PyObject *v, *w, *pt;
-	double *pnext;
-	if (!PyArg_GetLongArraySize(args, 6, 0, &arg1))
-		return NULL;
-	if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	if (!PyArg_GetDoubleArray(args, 6, 0, arg1 , arg2))
-		return NULL;
-	if (!PyArg_GetLongArraySize(args, 6, 1, &arg3))
-		return NULL;
-	if ((arg4 = PyMem_NEW(double, arg3 )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	if (!PyArg_GetDoubleArray(args, 6, 1, arg3 , arg4))
-		return NULL;
-	if (!PyArg_GetLong(args, 6, 3, &arg6))
-		return NULL;
-	if (!PyArg_GetLong(args, 6, 4, &arg7))
-		return NULL;
-	if (!PyArg_GetLong(args, 6, 5, &arg8))
-		return NULL;
-	if (arg8 == N_XYZ)
-		ncoords = 3;
-	else if (arg8 == N_XYZW)
-		ncoords = 4;
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	s_nctl = arg1 - arg6;
-	t_nctl = arg3 - arg7;
-	if (!PyArg_GetObject(args, 6, 2, &v))
-		return NULL;
-	if (!PyList_Check(v) || PyList_Size(v) != s_nctl) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	if ((arg5 = PyMem_NEW(double, s_nctl*t_nctl*ncoords )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	pnext = arg5;
-	for (s = 0; s < s_nctl; s++) {
-		w = PyList_GetItem(v, s);
-		if (w == NULL || !PyList_Check(w) ||
-					PyList_Size(w) != t_nctl) {
-			PyErr_BadArgument();
-			return NULL;
-		}
-		for (t = 0; t < t_nctl; t++) {
-			pt = PyList_GetItem(w, t);
-			if (!PyArg_GetDoubleArray(pt, 1, 0, ncoords, pnext))
-				return NULL;
-			pnext += ncoords;
-		}
-	}
-	s_byte_stride = sizeof(double) * ncoords;
-	t_byte_stride = s_byte_stride * s_nctl;
-	nurbssurface( arg1 , arg2 , arg3 , arg4 ,
-		s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg4);
-	PyMem_DEL(arg5);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* nurbscurve(knots, ctlpoints, order, type).
-   The length of ctlpoints is len(knots)-order. */
-
-%nurbscurve
-
-static PyObject *
-gl_nurbscurve(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	long arg1 ;
-	double * arg2 ;
-	long arg3 ;
-	double * arg4 ;
-	long arg5 ;
-	long arg6 ;
-	int ncoords, npoints;
-	int i;
-	PyObject *v;
-	double *pnext;
-	if (!PyArg_GetLongArraySize(args, 4, 0, &arg1))
-		return NULL;
-	if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	if (!PyArg_GetDoubleArray(args, 4, 0, arg1 , arg2))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 2, &arg5))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 3, &arg6))
-		return NULL;
-	if (arg6 == N_ST)
-		ncoords = 2;
-	else if (arg6 == N_STW)
-		ncoords = 3;
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	npoints = arg1 - arg5;
-	if (!PyArg_GetObject(args, 4, 1, &v))
-		return NULL;
-	if (!PyList_Check(v) || PyList_Size(v) != npoints) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	if ((arg4 = PyMem_NEW(double, npoints*ncoords )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	pnext = arg4;
-	for (i = 0; i < npoints; i++) {
-		if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
-			return NULL;
-		pnext += ncoords;
-	}
-	arg3 = (sizeof(double)) * ncoords;
-	nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg4);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* pwlcurve(points, type).
-   Points is a list of points. Type must be N_ST. */
-
-%pwlcurve
-
-static PyObject *
-gl_pwlcurve(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	PyObject *v;
-	long type;
-	double *data, *pnext;
-	long npoints, ncoords;
-	int i;
-	if (!PyArg_GetObject(args, 2, 0, &v))
-		return NULL;
-	if (!PyArg_GetLong(args, 2, 1, &type))
-		return NULL;
-	if (!PyList_Check(v)) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	npoints = PyList_Size(v);
-	if (type == N_ST)
-		ncoords = 2;
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	if ((data = PyMem_NEW(double, npoints*ncoords)) == NULL) {
-		return PyErr_NoMemory();
-	}
-	pnext = data;
-	for (i = 0; i < npoints; i++) {
-		if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
-			return NULL;
-		pnext += ncoords;
-	}
-	pwlcurve(npoints, data, sizeof(double)*ncoords, type);
-	PyMem_DEL(data);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-/* Picking and Selecting */
-
-static short *pickbuffer = NULL;
-static long pickbuffersize;
-
-static PyObject *
-pick_select(args, func)
-	PyObject *args;
-	void (*func)();
-{
-	if (!PyArg_GetLong(args, 1, 0, &pickbuffersize))
-		return NULL;
-	if (pickbuffer != NULL) {
-		PyErr_SetString(PyExc_RuntimeError,
-			"pick/gselect: already picking/selecting");
-		return NULL;
-	}
-	if ((pickbuffer = PyMem_NEW(short, pickbuffersize)) == NULL) {
-		return PyErr_NoMemory();
-	}
-	(*func)(pickbuffer, pickbuffersize);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-endpick_select(args, func)
-	PyObject *args;
-	long (*func)();
-{
-	PyObject *v, *w;
-	int i, nhits, n;
-	if (pickbuffer == NULL) {
-		PyErr_SetString(PyExc_RuntimeError,
-			"endpick/endselect: not in pick/select mode");
-		return NULL;
-	}
-	nhits = (*func)(pickbuffer);
-	if (nhits < 0) {
-		nhits = -nhits; /* How to report buffer overflow otherwise? */
-	}
-	/* Scan the buffer to see how many integers */
-	n = 0;
-	for (; nhits > 0; nhits--) {
-		n += 1 + pickbuffer[n];
-	}
-	v = PyList_New(n);
-	if (v == NULL)
-		return NULL;
-	/* XXX Could do it nicer and interpret the data structure here,
-	   returning a list of lists. But this can be done in Python... */
-	for (i = 0; i < n; i++) {
-		w = PyInt_FromLong((long)pickbuffer[i]);
-		if (w == NULL) {
-			Py_DECREF(v);
-			return NULL;
-		}
-		PyList_SetItem(v, i, w);
-	}
-	PyMem_DEL(pickbuffer);
-	pickbuffer = NULL;
-	return v;
-}
-
-extern void pick(), gselect();
-extern long endpick(), endselect();
-
-%pick
-static PyObject *gl_pick(self, args) PyObject *self, *args; {
-	return pick_select(args, pick);
-}
-
-%endpick
-static PyObject *gl_endpick(self, args) PyObject *self, *args; {
-	return endpick_select(args, endpick);
-}
-
-%gselect
-static PyObject *gl_gselect(self, args) PyObject *self, *args; {
-	return pick_select(args, gselect);
-}
-
-%endselect
-static PyObject *gl_endselect(self, args) PyObject *self, *args; {
-	return endpick_select(args, endselect);
-}
-
-
-/* XXX The generator botches this one.  Here's a quick hack to fix it. */
-
-/* XXX The generator botches this one.  Here's a quick hack to fix it. */
-
-% getmatrix float r[16]
-
-static PyObject *
-gl_getmatrix(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	Matrix arg1;
-	PyObject *v, *w;
-	int i, j;
-	getmatrix( arg1 );
-	v = PyList_New(16);
-	if (v == NULL) {
-		return PyErr_NoMemory();
-	}
-	for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
-		w = mknewfloatobject(arg1[i][j]);
-		if (w == NULL) {
-			Py_DECREF(v);
-			return NULL;
-		}
-		PyList_SetItem(v, i*4+j, w);
-	}
-	return v;
-}
-
-/* Here's an alternate version that returns a 4x4 matrix instead of
-   a vector.  Unfortunately it is incompatible with loadmatrix and
-   multmatrix... */
-
-% altgetmatrix float r[4][4]
-
-static PyObject *
-gl_altgetmatrix(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	Matrix arg1;
-	PyObject *v, *w;
-	int i, j;
-	getmatrix( arg1 );
-	v = PyList_New(4);
-	if (v == NULL) {
-		return NULL;
-	}
-	for (i = 0; i < 4; i++) {
-		w = PyList_New(4);
-		if (w == NULL) {
-			Py_DECREF(v);
-			return NULL;
-		}
-		PyList_SetItem(v, i, w);
-	}
-	for (i = 0; i < 4; i++) {
-		for (j = 0; j < 4; j++) {
-			w = mknewfloatobject(arg1[i][j]);
-			if (w == NULL) {
-				Py_DECREF(v);
-				return NULL;
-			}
-			PyList_SetItem(PyList_GetItem(v, i), j, w);
-		}
-	}
-	return v;
-}
-
-% lrectwrite
-
-static PyObject *
-gl_lrectwrite(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	short x1 ;
-	short y1 ;
-	short x2 ;
-	short y2 ;
-	string parray ;
-	PyObject *s;
-#if 0
-	int pixcount;
-#endif
-	if (!PyArg_GetShort(args, 5, 0, &x1))
-		return NULL;
-	if (!PyArg_GetShort(args, 5, 1, &y1))
-		return NULL;
-	if (!PyArg_GetShort(args, 5, 2, &x2))
-		return NULL;
-	if (!PyArg_GetShort(args, 5, 3, &y2))
-		return NULL;
-	if (!PyArg_GetString(args, 5, 4, &parray))
-		return NULL;
-	if (!PyArg_GetObject(args, 5, 4, &s))
-		return NULL;
-#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)) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "string arg to lrectwrite has wrong size");
-		return NULL;
-	}
-#endif
-	lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-% lrectread
-
-static PyObject *
-gl_lrectread(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	short x1 ;
-	short y1 ;
-	short x2 ;
-	short y2 ;
-	PyObject *parray;
-	int pixcount;
-	if (!PyArg_GetShort(args, 4, 0, &x1))
-		return NULL;
-	if (!PyArg_GetShort(args, 4, 1, &y1))
-		return NULL;
-	if (!PyArg_GetShort(args, 4, 2, &x2))
-		return NULL;
-	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));
-	if (parray == NULL)
-		return NULL; /* No memory */
-	lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
-	return parray;
-}
-
-% readdisplay
-
-static PyObject *
-gl_readdisplay(self, args)
-	PyObject *self;
-        PyObject *args;
-{
-        short x1, y1, x2, y2;
-	unsigned long *parray, hints;
-	long size, size_ret;
-	PyObject *rv;
-
-	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));
-	if ( rv == NULL )
-	  return NULL;
-	parray = (unsigned long *)PyString_AsString(rv);
-	size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
-	if ( size_ret != size ) {
-	    printf("gl_readdisplay: got %ld pixels, expected %ld\n",
-		   size_ret, size);
-	    PyErr_SetString(PyExc_RuntimeError, "readdisplay returned unexpected length");
-	    return NULL;
-	}
-	return rv;
-}
-
-/* Desperately needed, here are tools to compress and decompress
-   the data manipulated by lrectread/lrectwrite.
-
-   gl.packrect(width, height, packfactor, bigdata) --> smalldata
-		makes 'bigdata' 4*(packfactor**2) times smaller by:
-		- turning it into B/W (a factor 4)
-		- replacing squares of size pacfactor by one
-		  representative
-
-   gl.unpackrect(width, height, packfactor, smalldata) --> bigdata
-		is the inverse; the numeric arguments must be *the same*.
-
-   Both work best if width and height are multiples of packfactor
-   (in fact unpackrect will leave garbage bytes).
-*/
-
-% packrect
-
-static PyObject *
-gl_packrect(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	long width, height, packfactor;
-	char *s;
-	PyObject *unpacked, *packed;
-	int pixcount, packedcount, x, y, r, g, b;
-	unsigned long pixel;
-	unsigned char *p;
-	unsigned long *parray;
-	if (!PyArg_GetLong(args, 4, 0, &width))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 1, &height))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 2, &packfactor))
-		return NULL;
-	if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
-		return NULL;
-	if (!PyArg_GetObject(args, 4, 3, &unpacked))
-		return NULL;
-	if (width <= 0 || height <= 0 || packfactor <= 0) {
-		PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
-		return NULL;
-	}
-	pixcount = width*height;
-	packedcount = ((width+packfactor-1)/packfactor) *
-		((height+packfactor-1)/packfactor);
-	if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "string arg to packrect has wrong size");
-		return NULL;
-	}
-	packed = PyString_FromStringAndSize((char *)NULL, packedcount);
-	if (packed == NULL)
-		return NULL;
-	parray = (unsigned long *) PyString_AsString(unpacked);
-	p = (unsigned char *) PyString_AsString(packed);
-	for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
-		for (x = 0; x < width; x += packfactor) {
-			pixel = parray[x];
-			r = pixel & 0xff;
-			g = (pixel >> 8) & 0xff;
-			b = (pixel >> 16) & 0xff;
-			*p++ = (30*r+59*g+11*b) / 100;
-		}
-	}
-	return packed;
-}
-
-% unpackrect
-
-static unsigned long unpacktab[256];
-static int unpacktab_inited = 0;
-
-static PyObject *
-gl_unpackrect(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	long width, height, packfactor;
-	char *s;
-	PyObject *unpacked, *packed;
-	int pixcount, packedcount;
-	register unsigned char *p;
-	register unsigned long *parray;
-	if (!unpacktab_inited) {
-		register int white;
-		for (white = 256; --white >= 0; )
-			unpacktab[white] = white * 0x010101L;
-		unpacktab_inited++;
-	}
-	if (!PyArg_GetLong(args, 4, 0, &width))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 1, &height))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 2, &packfactor))
-		return NULL;
-	if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
-		return NULL;
-	if (!PyArg_GetObject(args, 4, 3, &packed))
-		return NULL;
-	if (width <= 0 || height <= 0 || packfactor <= 0) {
-		PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
-		return NULL;
-	}
-	pixcount = width*height;
-	packedcount = ((width+packfactor-1)/packfactor) *
-		((height+packfactor-1)/packfactor);
-	if (PyString_Size(packed) != packedcount) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "string arg to unpackrect has wrong size");
-		return NULL;
-	}
-	unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
-	if (unpacked == NULL)
-		return NULL;
-	parray = (unsigned long *) PyString_AsString(unpacked);
-	p = (unsigned char *) PyString_AsString(packed);
-	if (packfactor == 1 && width*height > 0) {
-		/* Just expand bytes to longs */
-		register int x = width * height;
-		do {
-			*parray++ = unpacktab[*p++];
-		} while (--x >= 0);
-	}
-	else {
-		register int y;
-		for (y = 0; y < height-packfactor+1;
-		     y += packfactor, parray += packfactor*width) {
-			register int x;
-			for (x = 0; x < width-packfactor+1; x += packfactor) {
-				register unsigned long pixel = unpacktab[*p++];
-				register int i;
-				for (i = packfactor*width; (i-=width) >= 0;) {
-					register int j;
-					for (j = packfactor; --j >= 0; )
-						parray[i+x+j] = pixel;
-				}
-			}
-		}
-	}
-	return unpacked;
-}
-
-% gversion
-static PyObject *
-gl_gversion(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	char buf[20];
-	gversion(buf);
-	return PyString_FromString(buf);
-}
-
-
-/* void clear - Manual because of clash with termcap */
-%clear
-static PyObject *
-gl_clear(self, args)
-	PyObject *self;
-	PyObject *args;
-{
-	__GLclear( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* End of manually written stubs */
-
-%%
-
-long 	getshade
-if !solaris	void 	devport 	short s long s
-void 	rdr2i 		long s long s
-void	rectfs 		short s short s short s short s
-void 	rects 		short s short s short s short s
-void 	rmv2i 		long s long s
-void	noport
-void	popviewport
-void	clearhitcode
-void	closeobj
-void	cursoff
-void	curson
-void	doublebuffer
-void 	finish
-void	gconfig
-void	ginit
-void	greset
-void	multimap
-void	onemap
-void	popattributes
-void	popmatrix
-void	pushattributes
-void	pushmatrix
-void	pushviewport
-void	qreset
-void	RGBmode
-void	singlebuffer
-void	swapbuffers
-void	gsync
-void	gflush
-void	tpon
-void	tpoff
-void	clkon
-void	clkoff
-void	ringbell
-#void	callfunc
-void	gbegin
-void	textinit
-void	initnames
-void	pclos
-void	popname
-if !solaris	void	spclos
-void	zclear
-void	screenspace
-void	reshapeviewport
-void	winpush
-void	winpop
-void	foreground
-void	endfullscrn
-if !solaris	void	endpupmode
-void	fullscrn
-if !solaris	void	pupmode
-void	winconstraints
-void	pagecolor 	short s
-void	textcolor 	short s
-void 	color 	  	short s
-void	curveit		short s
-void	font		short s
-void 	linewidth	short s
-void    setlinestyle	short s
-void	setmap		short s
-void	swapinterval	short s
-void	writemask	short s
-if !solaris	void	textwritemask	short s
-void	qdevice		short s
-void	unqdevice	short s
-void	curvebasis	short s
-void	curveprecision	short s
-void	loadname	short s
-void	passthrough	short s
-void	pushname	short s
-void	setmonitor	short s
-if !solaris	void	setshade	short s
-void	setpattern	short s
-if !solaris	void	pagewritemask	short s
-#
-void	callobj		long s
-void	delobj		long s
-void 	editobj		long s
-void	makeobj		long s
-void	maketag		long s
-void	chunksize	long s
-void	compactify	long s
-void	deltag		long s
-void	lsrepeat	long s
-void	objinsert	long s
-void 	objreplace	long s
-void	winclose	long s
-void	blanktime	long s
-void 	freepup		long s
-# This is not in the library!?
-###void	pupcolor	long s
-#
-void	backbuffer	long s
-void 	frontbuffer	long s
-if !solaris	void	lsbackup	long s
-void	resetls		long s
-void	lampon		long s
-void	lampoff		long s
-void	setbell		long s
-void	blankscreen	long s
-void 	depthcue	long s
-void	zbuffer		long s
-void	backface	long s
-#
-void 	cmov2i		long s long s
-void 	draw2i		long s long s
-void	move2i		long s long s
-void	pnt2i		long s long s
-void 	patchbasis	long s long s
-void 	patchprecision	long s long s
-void	pdr2i		long s long s
-void	pmv2i		long s long s
-void	rpdr2i		long s long s
-void	rpmv2i		long s long s
-void	xfpt2i		long s long s
-void	objdelete	long s long s
-void	patchcurves	long s long s
-void	minsize		long s long s
-void 	maxsize		long s long s
-void	keepaspect	long s long s
-void	prefsize	long s long s
-void	stepunit	long s long s
-void 	fudge		long s long s
-void 	winmove		long s long s
-#
-void 	attachcursor	short s short s
-void 	deflinestyle	short s short s
-void 	noise		short s short s
-void 	picksize	short s short s
-void 	qenter		short s short s
-void 	setdepth	short s short s
-void 	cmov2s		short s short s
-void 	draw2s		short s	short s
-void 	move2s		short s short s
-void 	pdr2s		short s short s
-void 	pmv2s		short s short s
-void 	pnt2s		short s short s
-void 	rdr2s		short s short s
-void 	rmv2s		short s short s
-void 	rpdr2s		short s short s
-void 	rpmv2s		short s short s
-void 	xfpt2s		short s short s
-#
-void cmov2		float s float s
-void draw2		float s float s
-void move2		float s float s
-void pnt2		float s float s
-void pdr2		float s float s
-void pmv2		float s float s
-void rdr2		float s float s
-void rmv2		float s float s
-void rpdr2		float s float s
-void rpmv2		float s float s
-void xfpt2		float s float s
-#
-void loadmatrix		float s[4*4]
-# Really [4][4]
-void multmatrix		float s[4*4]
-# Really [4][4]
-void crv			float s[3*4]
-# Really [4][3]
-void rcrv			float s[4*4]
-# Really [4][4]
-#
-# Methods that have strings.  
-#
-void addtopup		long s char *s long s
-void charstr		char *s
-void getport	 	char *s
-long strwidth		char *s
-long winopen		char *s
-void wintitle		char *s
-#
-# Methods that have 1 long (# of elements) and an array 
-#
-void polf		long s float s[3*arg1]
-void polf2		long s float s[2*arg1]
-void poly		long s float s[3*arg1]
-void poly2		long s float s[2*arg1]
-void crvn		long s float s[3*arg1]
-void rcrvn		long s float s[4*arg1]
-#
-void polf2i		long s long s[2*arg1]
-void polfi		long s long s[3*arg1]
-void poly2i		long s long s[2*arg1]
-void polyi		long s long s[3*arg1]
-#
-void polf2s		long s short s[2*arg1]
-void polfs		long s short s[3*arg1]
-void polys		long s short s[3*arg1]
-void poly2s		long s short s[2*arg1]
-#
-void defcursor		short s u_short s[128]
-# Is this useful?
-void writepixels	short s u_short s[arg1]
-# Should be unsigned short...
-void defbasis		long s float s[4*4]
-if !solaris	void gewrite		short s short s[arg1]
-#
-void rotate		short s char s
-# This is not in the library!?
-###void setbutton		short s char s
-void rot		float s char s
-#
-void circfi		long s long s long s
-void circi		long s long s long s
-void cmovi		long s long s long s
-void drawi		long s long s long s
-void movei		long s long s long s
-void pnti 		long s long s long s
-void newtag		long s long s long s
-void pdri  		long s long s long s
-void pmvi  		long s long s long s
-void rdri  		long s long s long s
-void rmvi  		long s long s long s
-void rpdri 		long s long s long s
-void rpmvi 		long s long s long s
-void xfpti 		long s long s long s
-#
-void circ		float s float s float s
-void circf		float s float s float s
-void cmov		float s float s float s
-void draw		float s float s float s
-void move		float s float s float s
-void pnt		float s float s float s
-void scale		float s float s float s
-void translate		float s float s float s
-void pdr		float s float s float s
-void pmv		float s float s float s
-void rdr		float s float s float s
-void rmv		float s float s float s
-void rpdr		float s float s float s
-void rpmv		float s float s float s
-void xfpt		float s float s float s
-#
-void RGBcolor		short s short s short s
-void RGBwritemask	short s short s short s
-void setcursor		short s short s short s
-void tie		short s short s short s
-void circfs		short s short s short s
-void circs		short s short s short s
-void cmovs		short s short s short s
-void draws		short s short s short s
-void moves		short s short s short s
-void pdrs		short s short s short s
-void pmvs		short s short s short s
-void pnts		short s short s short s
-void rdrs		short s short s short s
-void rmvs		short s short s short s
-void rpdrs		short s short s short s
-void rpmvs		short s short s short s
-void xfpts		short s short s short s
-void curorigin		short s short s short s
-void cyclemap		short s short s short s
-#
-void patch		float s[4*4] float s[4*4] float s[4*4]
-void splf		long s float s[3*arg1] u_short s[arg1]
-void splf2		long s float s[2*arg1] u_short s[arg1]
-void splfi		long s long s[3*arg1] u_short s[arg1]
-void splf2i		long s long s[2*arg1] u_short s[arg1]
-void splfs		long s short s[3*arg1] u_short s[arg1]
-void splf2s		long s short s[2*arg1] u_short s[arg1]
-###void defpattern		short s short s u_short s[arg2*arg2/16]
-#
-void rpatch		float s[4*4] float s[4*4] float s[4*4] float s[4*4]
-#
-# routines that send 4 floats
-#
-void ortho2		float s float s float s float s
-void rect		float s float s float s float s
-void rectf		float s float s float s float s
-void xfpt4		float s float s float s float s
-#
-void textport		short s short s short s short s
-void mapcolor		short s short s short s short s
-void scrmask		short s short s short s short s
-void setvaluator	short s short s short s short s
-void viewport		short s short s short s short s
-void shaderange		short s short s short s short s
-void xfpt4s		short s short s short s short s
-void rectfi		long s long s long s long s
-void recti		long s long s long s long s
-void xfpt4i		long s long s long s long s
-void prefposition	long s long s long s long s
-#
-void arc		float s float s float s short s short s
-void arcf		float s float s float s short s short s
-void arcfi		long s long s long s short s short s
-void arci		long s long s long s short s short s
-#
-void bbox2		short s short s float s float s float s float s
-void bbox2i		short s short s long s long s long s long s
-void bbox2s		short s short s short s short s short s short s
-void blink		short s short s short s short s short s
-void ortho		float s float s float s float s float s float s
-void window		float s float s float s float s float s float s
-void lookat		float s float s float s float s float s float s short s
-#
-void perspective	short s float s float s float s
-void polarview		float s short s short s short s
-# XXX getichararray not supported
-#void writeRGB		short s char s[arg1] char s[arg1] char s[arg1]
-#
-void arcfs		short s short s short s short s short s
-void arcs		short s short s short s short s short s
-void rectcopy		short s short s short s short s short s short s
-if !solaris	void RGBcursor		short s short s short s short s short s short s short s
-#
-long getbutton		short s
-long getcmmode
-long getlsbackup
-long getresetls
-long getdcm
-long getzbuffer
-long ismex
-long isobj		long s
-long isqueued		short s
-long istag		long s
-#
-long genobj
-long gentag
-long getbuffer
-long getcolor
-long getdisplaymode
-long getfont
-long getheight
-long gethitcode
-long getlstyle
-long getlwidth
-long getmap
-long getplanes
-long getwritemask
-long qtest
-long getlsrepeat
-long getmonitor
-long getopenobj
-long getpattern
-long winget
-long winattach
-long getothermonitor
-long newpup
-#
-long getvaluator	short s
-void winset		long s
-long dopup		long s
-void getdepth		short r short r
-void getcpos		short r short r
-void getsize		long r long r
-void getorigin		long r long r
-void getviewport	short r short r short r short r
-if !solaris	void gettp		short r short r short r short r
-void getgpos		float r float r float r float r
-void winposition	long s long s long s long s
-void gRGBcolor		short r short r short r
-void gRGBmask		short r short r short r
-void getscrmask	short r short r short r short r
-###void gRGBcursor	short r short r short r short r short r short r short r short r
-void getmcolor		short s short r short r short r
-void mapw		long s short s short s float r float r float r float r float r float r
-void mapw2		long s short s short s float r float r
-###void defrasterfont	short s short s short s Fontchar s[arg3] short s short s[4*arg5]
-###long qread		short r
-void getcursor		short r u_short r u_short r long r
-#
-#   For these we receive arrays of stuff
-#
-###void getdev 		long s short s[arg1] short r[arg1]
-#XXX not generated correctly yet
-#void getmatrix		float r[16]
-###long readpixels		short s short r[retval]
-###long readRGB		short s char r[retval] char r[retval] char r[retval]
-###long blkqread		short s short r[arg1]
-#
-#   New 4D routines
-#
-void cmode
-void concave		long s
-void curstype		long s
-void drawmode		long s
-void gammaramp		short s[256] short s[256] short s[256]
-long getbackface
-long getdescender
-long getdrawmode
-long getmmode
-long getsm
-long getvideo		long s
-void imakebackground
-void lmbind		short s short s
-void lmdef		long s long s long s float s[arg3]
-void mmode		long s
-void normal		float s[3]
-void overlay		long s
-void RGBrange		short s short s short s short s short s short s short s short s
-if !solaris	void setvideo 		long s long s
-void shademodel		long s
-void underlay		long s
-#
-# New Personal Iris/GT Routines
-#
-void bgnclosedline
-void bgnline
-void bgnpoint
-void bgnpolygon
-void bgnsurface
-void bgntmesh
-void bgntrim
-void endclosedline
-void endline
-void endpoint
-void endpolygon
-void endsurface
-void endtmesh
-void endtrim
-void blendfunction	long s long s
-void c3f		float s[3]
-void c3i		long  s[3]
-void c3s		short s[3]
-void c4f		float s[4]
-void c4i		long  s[4]
-void c4s		short s[4]
-void colorf		float s
-void cpack		long s
-void czclear		long s long s
-void dglclose		long s
-long dglopen		char *s long s
-long getgdesc		long s
-void getnurbsproperty	long s float r
-void glcompat		long s long s
-void iconsize 		long s long s
-void icontitle		char *s
-void lRGBrange		short s short s short s short s short s short s long s long s
-void linesmooth		long s
-void lmcolor		long s
-void logicop		long s
-###long lrectread	 	short s short s short s short s long r[retval]
-###void lrectwrite		short s short s short s short s long s[(arg2-arg1+1)*(arg4-arg3+1)]
-### Now manual, with string last arg
-###long rectread	 	short s short s short s short s short r[retval]
-###void rectwrite		short s short s short s short s short s[(arg2-arg1+1)*(arg4-arg3+1)]
-void lsetdepth		long s long s
-void lshaderange	short s short s long s long s
-void n3f		float s[3]
-void noborder
-void pntsmooth		long s
-void readsource		long s
-void rectzoom		float s float s
-void sbox		float s float s float s float s
-void sboxi		long s long s long s long s
-void sboxs		short s short s short s short s
-void sboxf		float s float s float s float s
-void sboxfi		long s long s long s long s
-void sboxfs		short s short s short s short s
-void setnurbsproperty	long s float s
-void setpup 		long s long s long s
-void smoothline		long s
-void subpixel		long s
-void swaptmesh
-long swinopen		long s
-void v2f		float s[2]
-void v2i		long  s[2]
-void v2s		short s[2]
-void v3f		float s[3]
-void v3i		long  s[3]
-void v3s		short s[3]
-void v4f		float s[4]
-void v4i		long  s[4]
-void v4s		short s[4]
-void videocmd		long s
-long windepth		long s
-void wmpack		long s
-void zdraw		long s
-void zfunction		long s
-void zsource		long s
-void zwritemask		long s
-#
-#   uses doubles
-#
-void v2d		double s[2]
-void v3d		double s[3]
-void v4d		double s[4]
-#
-# Why isn't this here?
-#
-void pixmode		long s long s
-#
-# New in IRIX 4.0
-#
-long qgetfd
-void dither		long s

Modified: python/branches/p3yk-noslice/Modules/datetimemodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/datetimemodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/datetimemodule.c	Wed Jul 11 15:40:56 2007
@@ -13,7 +13,9 @@
 /* Differentiate between building the core module and building extension
  * modules.
  */
+#ifndef Py_BUILD_CORE
 #define Py_BUILD_CORE
+#endif
 #include "datetime.h"
 #undef Py_BUILD_CORE
 
@@ -2603,7 +2605,7 @@
 	{"ctime",       (PyCFunction)date_ctime,        METH_NOARGS,
 	 PyDoc_STR("Return ctime() style string.")},
 
-	{"strftime",   	(PyCFunction)date_strftime,	METH_KEYWORDS,
+	{"strftime",   	(PyCFunction)date_strftime,	METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("format -> strftime() style string.")},
 
 	{"timetuple",   (PyCFunction)date_timetuple,    METH_NOARGS,
@@ -2628,7 +2630,7 @@
 	 PyDoc_STR("Return the day of the week represented by the date.\n"
 		   "Monday == 0 ... Sunday == 6")},
 
-	{"replace",     (PyCFunction)date_replace,      METH_KEYWORDS,
+	{"replace",     (PyCFunction)date_replace,      METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("Return date with new specified fields.")},
 
 	{"__reduce__", (PyCFunction)date_reduce,        METH_NOARGS,
@@ -3378,7 +3380,7 @@
 	 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
 	 	   "[+HH:MM].")},
 
-	{"strftime",   	(PyCFunction)time_strftime,	METH_KEYWORDS,
+	{"strftime",   	(PyCFunction)time_strftime,	METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("format -> strftime() style string.")},
 
 	{"utcoffset",	(PyCFunction)time_utcoffset,	METH_NOARGS,
@@ -3390,7 +3392,7 @@
 	{"dst",		(PyCFunction)time_dst,		METH_NOARGS,
 	 PyDoc_STR("Return self.tzinfo.dst(self).")},
 
-	{"replace",     (PyCFunction)time_replace,	METH_KEYWORDS,
+	{"replace",     (PyCFunction)time_replace,	METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("Return time with new specified fields.")},
 
 	{"__reduce__", (PyCFunction)time_reduce,        METH_NOARGS,
@@ -3644,6 +3646,12 @@
 		return NULL;
 	fraction = timestamp - (double)timet;
 	us = (int)round_to_long(fraction * 1e6);
+	if (us < 0) {
+		/* Truncation towards zero is not what we wanted
+		   for negative numbers (Python's mod semantics) */
+		timet -= 1;
+		us += 1000000;
+	}
 	/* If timestamp is less than one microsecond smaller than a
 	 * full second, round up. Otherwise, ValueErrors are raised
 	 * for some floats. */
@@ -4410,7 +4418,7 @@
 	/* Class methods: */
 
 	{"now",         (PyCFunction)datetime_now,
-	 METH_KEYWORDS | METH_CLASS,
+	 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
 	 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
 
 	{"utcnow",         (PyCFunction)datetime_utcnow,
@@ -4418,7 +4426,7 @@
 	 PyDoc_STR("Return a new datetime representing UTC day and time.")},
 
 	{"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
-	 METH_KEYWORDS | METH_CLASS,
+	 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
 	 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
 
 	{"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
@@ -4455,7 +4463,7 @@
 	{"utctimetuple",   (PyCFunction)datetime_utctimetuple, METH_NOARGS,
          PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
 
-	{"isoformat",   (PyCFunction)datetime_isoformat, METH_KEYWORDS,
+	{"isoformat",   (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("[sep] -> string in ISO 8601 format, "
 	 	   "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
 	 	   "sep is used to separate the year from the time, and "
@@ -4470,10 +4478,10 @@
 	{"dst",		(PyCFunction)datetime_dst, METH_NOARGS,
 	 PyDoc_STR("Return self.tzinfo.dst(self).")},
 
-	{"replace",     (PyCFunction)datetime_replace,	METH_KEYWORDS,
+	{"replace",     (PyCFunction)datetime_replace,	METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("Return datetime with new specified fields.")},
 
-	{"astimezone",  (PyCFunction)datetime_astimezone, METH_KEYWORDS,
+	{"astimezone",  (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
 	 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
 
 	{"__reduce__", (PyCFunction)datetime_reduce,     METH_NOARGS,

Deleted: /python/branches/p3yk-noslice/Modules/flmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/flmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,2139 +0,0 @@
-/* FL module -- interface to Mark Overmars' FORMS Library. */
-
-/* This code works with FORMS version 2.2 (if you defined
-   OBSOLETE_FORMS_CALLS), and 2.3.
-   FORMS can be ftp'ed from ftp.cs.ruu.nl (131.211.80.17), directory
-   /pub/SGI/FORMS. */
-
-/* A half-hearted attempt has been made to allow programs using this
- * module to exploit parallelism (through the threads module). No provisions
- * have been made for multiple threads to use this module at the same time,
- * though. So, a program with a forms thread and a non-forms thread will work
- * fine but a program with two threads using forms will probably crash (unless
- * the program takes precaution to ensure that only one thread can be in
- * this module at any time). This will have to be fixed some time.
- * (A fix will probably also have to synchronize with the gl module).
- */
-
-#include "Python.h"
-#include "forms.h"
-#include "structmember.h"
-
-/* Generic Forms Objects */
-
-typedef struct {
-	PyObject_HEAD
-	FL_OBJECT *ob_generic;
-	PyMethodDef *ob_methods;
-	PyObject *ob_callback;
-	PyObject *ob_callback_arg;
-} genericobject;
-
-static PyTypeObject GenericObjecttype;
-
-#define is_genericobject(g) ((g)->ob_type == &GenericObjecttype)
-
-/* List of all objects (XXX this should be a hash table on address...) */
-
-static PyObject *allgenerics = NULL;
-static int nfreeslots = 0;
-
-/* Add an object to the list of known objects */
-
-static void
-knowgeneric(genericobject *g)
-{
-	int i, n;
-	/* Create the list if it doesn't already exist */
-	if (allgenerics == NULL) {
-		allgenerics = PyList_New(0);
-		if (allgenerics == NULL) {
-			PyErr_Clear();
-			return; /* Too bad, live without allgenerics... */
-		}
-	}
-	if (nfreeslots > 0) {
-		/* Search the list for reusable slots (NULL items) */
-		/* XXX This can be made faster! */
-		n = PyList_Size(allgenerics);
-		for (i = 0; i < n; i++) {
-			if (PyList_GetItem(allgenerics, i) == NULL) {
-				Py_INCREF(g);
-				PyList_SetItem(allgenerics, i, (PyObject *)g);
-				nfreeslots--;
-				return;
-			}
-		}
-		/* Strange... no free slots found... */
-		nfreeslots = 0;
-	}
-	/* No free entries, append new item to the end */
-	PyList_Append(allgenerics, (PyObject *)g);
-}
-
-/* Find an object in the list of known objects */
-
-static genericobject *
-findgeneric(FL_OBJECT *generic)
-{
-	int i, n;
-	genericobject *g;
-	
-	if (allgenerics == NULL)
-		return NULL; /* No objects known yet */
-	n = PyList_Size(allgenerics);
-	for (i = 0; i < n; i++) {
-		g = (genericobject *)PyList_GetItem(allgenerics, i);
-		if (g != NULL && g->ob_generic == generic)
-			return g;
-	}
-	return NULL; /* Unknown object */
-}
-
-/* Remove an object from the list of known objects */
-
-static void
-forgetgeneric(genericobject *g)
-{
-	int i, n;
-	
-	Py_XDECREF(g->ob_callback);
-	g->ob_callback = NULL;
-	Py_XDECREF(g->ob_callback_arg);
-	g->ob_callback_arg = NULL;
-	if (allgenerics == NULL)
-		return; /* No objects known yet */
-	n = PyList_Size(allgenerics);
-	for (i = 0; i < n; i++) {
-		if (g == (genericobject *)PyList_GetItem(allgenerics, i)) {
-			PyList_SetItem(allgenerics, i, (PyObject *)NULL);
-			nfreeslots++;
-			break;
-		}
-	}
-}
-
-/* Called when a form is about to be freed --
-   remove all the objects that we know about from it. */
-
-static void
-releaseobjects(FL_FORM *form)
-{
-	int i, n;
-	genericobject *g;
-	
-	if (allgenerics == NULL)
-		return; /* No objects known yet */
-	n = PyList_Size(allgenerics);
-	for (i = 0; i < n; i++) {
-		g = (genericobject *)PyList_GetItem(allgenerics, i);
-		if (g != NULL && g->ob_generic->form == form) {
-			fl_delete_object(g->ob_generic);
-			/* The object is now unreachable for
-			   do_forms and check_forms, so
-			   delete it from the list of known objects */
-			Py_XDECREF(g->ob_callback);
-			g->ob_callback = NULL;
-			Py_XDECREF(g->ob_callback_arg);
-			g->ob_callback_arg = NULL;
-			PyList_SetItem(allgenerics, i, (PyObject *)NULL);
-			nfreeslots++;
-		}
-	}
-}
-
-
-/* Methods of generic objects */
-
-static PyObject *
-generic_set_call_back(genericobject *g, PyObject *args)
-{
-	if (PyTuple_GET_SIZE(args) == 0) {
-		Py_XDECREF(g->ob_callback);
-		Py_XDECREF(g->ob_callback_arg);
-		g->ob_callback = NULL;
-		g->ob_callback_arg = NULL;
-	}
-	else {
-        PyObject *a, *b;
-        if (!PyArg_UnpackTuple(args, "set_call_back", 2, 2, &a, &b)
-            return NULL;
-		Py_XDECREF(g->ob_callback);
-		Py_XDECREF(g->ob_callback_arg);
-		g->ob_callback = a;
-		Py_INCREF(g->ob_callback);
-		g->ob_callback_arg = b;
-		Py_INCREF(g->ob_callback_arg);
-	}
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-generic_call(genericobject *g, void (*func)(FL_OBJECT *))
-{
-	(*func)(g->ob_generic);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-generic_delete_object(genericobject *g)
-{
-	PyObject *res;
-	res = generic_call(g, fl_delete_object);
-	if (res != NULL)
-		forgetgeneric(g);
-	return res;
-}
-
-static PyObject *
-generic_show_object(genericobject *g)
-{
-	return generic_call(g, fl_show_object);
-}
-
-static PyObject *
-generic_hide_object(genericobject *g)
-{
-	return generic_call(g, fl_hide_object);
-}
-
-static PyObject *
-generic_redraw_object(genericobject *g)
-{
-	return generic_call(g, fl_redraw_object);
-}
-
-#ifdef OBSOLETE_FORMS_CALLS
- 
- /* (un)freeze_object() are obsolete in FORMS 2.2 and unsupported
-    in 2.3.  Since there's no foolproof way to tell which version we're
-    using, we omit them unconditionally. */
- 
-static PyObject *
-generic_freeze_object(genericobject *g)
-{
-	return generic_call(g, fl_freeze_object);
-}
-
-static PyObject *
-generic_unfreeze_object(genericobject *g)
-{
-	return generic_call(g, fl_unfreeze_object);
-}
-
-#endif /* OBSOLETE_FORMS_CALLS */
-
-static PyObject *
-generic_activate_object(genericobject *g)
-{
-	return generic_call(g, fl_activate_object);
-}
-
-static PyObject *
-generic_deactivate_object(genericobject *g)
-{
-	return generic_call(g, fl_deactivate_object);
-}
-
-static PyObject *
-generic_set_object_shortcut(genericobject *g, PyObject *args)
-{
-	char *str;
-	if (!PyArg_ParseTuple(args, "s:set_object_shortcut", &str))
-		return NULL;
-	fl_set_object_shortcut(g->ob_generic, str);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyMethodDef generic_methods[] = {
-	{"set_call_back",	(PyCFunction)generic_set_call_back, METH_VARARGS},
-	{"delete_object",	(PyCFunction)generic_delete_object, METH_NOARGS},
-	{"show_object",		(PyCFunction)generic_show_object, METH_NOARGS},
-	{"hide_object",		(PyCFunction)generic_hide_object, METH_NOARGS},
-	{"redraw_object",	(PyCFunction)generic_redraw_object, METH_NOARGS},
-#ifdef OBSOLETE_FORMS_CALLS
-	{"freeze_object",	(PyCFunction)generic_freeze_object, METH_NOARGS},
-	{"unfreeze_object",	(PyCFunction)generic_unfreeze_object, METH_NOARGS},
-#endif
-	{"activate_object",	(PyCFunction)generic_activate_object, METH_NOARGS},
-	{"deactivate_object",	(PyCFunction)generic_deactivate_object, METH_NOARGS},
-	{"set_object_shortcut",	(PyCFunction)generic_set_object_shortcut, METH_VARARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-static void
-generic_dealloc(genericobject *g)
-{
-	fl_free_object(g->ob_generic);
-	Py_XDECREF(g->ob_callback);
-	Py_XDECREF(g->ob_callback_arg);
-	PyObject_Del(g);
-}
-
-#define OFF(x) offsetof(FL_OBJECT, x)
-
-static struct memberlist generic_memberlist[] = {
-	{"objclass",	T_INT,		OFF(objclass),	RO},
-	{"type",	T_INT,		OFF(type),	RO},
-	{"boxtype",	T_INT,		OFF(boxtype)},
-	{"x",		T_FLOAT,	OFF(x)},
-	{"y",		T_FLOAT,	OFF(y)},
-	{"w",		T_FLOAT,	OFF(w)},
-	{"h",		T_FLOAT,	OFF(h)},
-	{"col1",	T_INT,		OFF(col1)},
-	{"col2",	T_INT,		OFF(col2)},
-	{"align",	T_INT,		OFF(align)},
-	{"lcol",	T_INT,		OFF(lcol)},
-	{"lsize",	T_FLOAT,	OFF(lsize)},
-	/* "label" is treated specially! */
-	{"lstyle",	T_INT,		OFF(lstyle)},
-	{"pushed",	T_INT,		OFF(pushed),	RO},
-	{"focus",	T_INT,		OFF(focus),	RO},
-	{"belowmouse",	T_INT,		OFF(belowmouse),RO},
-/*	{"frozen",	T_INT,		OFF(frozen),	RO},	*/
-	{"active",	T_INT,		OFF(active)},
-	{"input",	T_INT,		OFF(input)},
-	{"visible",	T_INT,		OFF(visible),	RO},
-	{"radio",	T_INT,		OFF(radio)},
-	{"automatic",	T_INT,		OFF(automatic)},
-	{NULL}	/* Sentinel */
-};
-
-#undef OFF
-
-static PyObject *
-generic_getattr(genericobject *g, char *name)
-{
-	PyObject *meth;
-
-	/* XXX Ought to special-case name "__methods__" */
-	if (g-> ob_methods) {
-		meth = Py_FindMethod(g->ob_methods, (PyObject *)g, name);
-		if (meth != NULL) return meth;
-		PyErr_Clear();
-	}
-
-	meth = Py_FindMethod(generic_methods, (PyObject *)g, name);
-	if (meth != NULL)
-		return meth;
-	PyErr_Clear();
-
-	/* "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 PyMember_Get((char *)g->ob_generic, generic_memberlist, name);
-}
-
-static int
-generic_setattr(genericobject *g, char *name, PyObject *v)
-{
-	int ret;
-
-	if (v == NULL) {
-		PyErr_SetString(PyExc_TypeError,
-				"can't delete forms object attributes");
-		return -1;
-	}
-
-	/* "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)) {
-			PyErr_SetString(PyExc_TypeError,
-					"label attr must be string");
-			return -1;
-		}
-		fl_set_object_label(g->ob_generic, PyString_AsString(v));
-		return 0;
-	}
-
-	ret = PyMember_Set((char *)g->ob_generic, generic_memberlist, name, v);
-
-	/* Rather than calling all the various set_object_* functions,
-	   we call fl_redraw_object here.  This is sometimes redundant
-	   but I doubt that's a big problem */
-	if (ret == 0)
-		fl_redraw_object(g->ob_generic);
-
-	return ret;
-}
-
-static PyObject *
-generic_repr(genericobject *g)
-{
-	char buf[100];
-	PyOS_snprintf(buf, sizeof(buf), "<FORMS_object at %p, objclass=%d>",
-		      g, g->ob_generic->objclass);
-	return PyString_FromString(buf);
-}
-
-static PyTypeObject GenericObjecttype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,				/*ob_size*/
-	"fl.FORMS_object",		/*tp_name*/
-	sizeof(genericobject),		/*tp_size*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)generic_dealloc,	/*tp_dealloc*/
-	0,				/*tp_print*/
-	(getattrfunc)generic_getattr,	/*tp_getattr*/
-	(setattrfunc)generic_setattr,	/*tp_setattr*/
-	0,				/*tp_compare*/
-	(reprfunc)generic_repr,		/*tp_repr*/
-};
-
-static PyObject *
-newgenericobject(FL_OBJECT *generic, PyMethodDef *methods)
-{
-	genericobject *g;
-	g = PyObject_New(genericobject, &GenericObjecttype);
-	if (g == NULL)
-		return NULL;
-	g-> ob_generic = generic;
-	g->ob_methods = methods;
-	g->ob_callback = NULL;
-	g->ob_callback_arg = NULL;
-	knowgeneric(g);
-	return (PyObject *)g;
-}
-
-/**********************************************************************/
-/* Some common calling sequences */
-
-/* void func (object, float) */
-static PyObject *
-call_forms_INf (void (*func)(FL_OBJECT *, float), FL_OBJECT *obj, PyObject *args)
-{
-	float parameter;
-
-	if (!PyArg_Parse(args, "f", &parameter)) return NULL;
-
-	(*func) (obj, parameter);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void func (object, float) */
-static PyObject *
-call_forms_INfINf (void (*func)(FL_OBJECT *, float, float), FL_OBJECT *obj, PyObject *args)
-{
-	float par1, par2;
-
-	if (!PyArg_Parse(args, "(ff)", &par1, &par2)) return NULL;
-
-	(*func) (obj, par1, par2);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void func (object, int) */
-static PyObject *
-call_forms_INi (void (*func)(FL_OBJECT *, int), FL_OBJECT *obj, PyObject *args)
-{
-	int parameter;
-
-	if (!PyArg_Parse(args, "i", &parameter)) return NULL;
-
-	(*func) (obj, parameter);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void func (object, char) */
-static PyObject *
-call_forms_INc (void (*func)(FL_OBJECT *, int), FL_OBJECT *obj, PyObject *args)
-{
-	char *a;
-
-	if (!PyArg_Parse(args, "s", &a)) return NULL;
-
-	(*func) (obj, a[0]);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void func (object, string) */
-static PyObject *
-call_forms_INstr (void (*func)(FL_OBJECT *, char *), FL_OBJECT *obj, PyObject *args)
-{
-	char *a;
-
-	if (!PyArg_Parse(args, "s", &a)) return NULL;
-
-	(*func) (obj, a);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-/* void func (object, int, string) */
-static PyObject *
-call_forms_INiINstr (void (*func)(FL_OBJECT *, int, char *), FL_OBJECT *obj, PyObject *args)
-{
-	char *b;
-	int a;
-	
-	if (!PyArg_Parse(args, "(is)", &a, &b)) return NULL;
-	
-	(*func) (obj, a, b);
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-#ifdef UNUSED
-/* void func (object, int, int) */
-static PyObject *
-call_forms_INiINi (void (*func)(FL_OBJECT *, int, int), FL_OBJECT *obj, PyObject *args)
-{
-	int par1, par2;
-	
-	if (!PyArg_Parse(args, "(ii)", &par1, &par2)) return NULL;
-	
-	(*func) (obj, par1, par2);
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-#endif
-
-/* int func (object) */
-static PyObject *
-call_forms_Ri (int (*func)(FL_OBJECT *), FL_OBJECT *obj)
-{
-	int retval;
-
-	retval = (*func) (obj);
-
-	return PyInt_FromLong ((long) retval);
-}
-
-/* char * func (object) */
-static PyObject *
-call_forms_Rstr (char * (*func)(FL_OBJECT *), FL_OBJECT *obj)
-{
-	char *str;
-
-	str = (*func) (obj);
-
-	if (str == NULL) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	return PyString_FromString (str);
-}
-
-/* int func (object) */
-static PyObject *
-call_forms_Rf (float (*func)(FL_OBJECT *), FL_OBJECT *obj)
-{
-	float retval;
-
-	retval = (*func) (obj);
-
-	return PyFloat_FromDouble (retval);
-}
-
-static PyObject *
-call_forms_OUTfOUTf (void (*func)(FL_OBJECT *, float *, float *), FL_OBJECT *obj)
-{
-	float f1, f2;
-
-	(*func) (obj, &f1, &f2);
-
-	return Py_BuildValue("(ff)", f1, f2);
-}
-
-#ifdef UNUSED
-static PyObject *
-call_forms_OUTf (void (*func)(FL_OBJECT *, float *), FL_OBJECT *obj)
-{
-	float f;
-
-	(*func) (obj, &f);
-
-	return PyFloat_FromDouble (f);
-}
-#endif
-
-/**********************************************************************/
-/* Class : browser */
-
-static PyObject *
-set_browser_topline(genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_browser_topline, g-> ob_generic, args);
-}
-
-static PyObject *
-clear_browser(genericobject *g)
-{
-	return generic_call (g, fl_clear_browser);
-}
-
-static PyObject *
-add_browser_line (genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_add_browser_line, g-> ob_generic, args);
-}
-
-static PyObject *
-addto_browser (genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_addto_browser, g-> ob_generic, args);
-}
-
-static PyObject *
-insert_browser_line (genericobject *g, PyObject *args)
-{
-	return call_forms_INiINstr (fl_insert_browser_line,
-				    g-> ob_generic, args);
-}
-
-static PyObject *
-delete_browser_line (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_delete_browser_line, g-> ob_generic, args);
-}
-
-static PyObject *
-replace_browser_line (genericobject *g, PyObject *args)
-{
-	return call_forms_INiINstr (fl_replace_browser_line,
-				    g-> ob_generic, args);
-}
-
-static PyObject *
-get_browser_line(genericobject *g, PyObject *args)
-{
-	int i;
-	char *str;
-
-	if (!PyArg_Parse(args, "i", &i))
-		return NULL;
-
-	str = fl_get_browser_line (g->ob_generic, i);
-
-	if (str == NULL) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	return PyString_FromString (str);
-}
-
-static PyObject *
-load_browser (genericobject *g, PyObject *args)
-{
-	/* XXX strictly speaking this is wrong since fl_load_browser
-	   XXX returns int, not void */
-	return call_forms_INstr (fl_load_browser, g-> ob_generic, args);
-}
-
-static PyObject *
-get_browser_maxline(genericobject *g)
-{
-	return call_forms_Ri (fl_get_browser_maxline, g-> ob_generic);
-}
-
-static PyObject *
-select_browser_line (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_select_browser_line, g-> ob_generic, args);
-}
-
-static PyObject *
-deselect_browser_line (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_deselect_browser_line, g-> ob_generic, args);
-}
-
-static PyObject *
-deselect_browser (genericobject *g)
-{
-	return generic_call (g, fl_deselect_browser);
-}
-
-static PyObject *
-isselected_browser_line (genericobject *g, PyObject *args)
-{
-	int i, j;
-	
-	if (!PyArg_Parse(args, "i", &i))
-		return NULL;
-	
-	j = fl_isselected_browser_line (g->ob_generic, i);
-	
-	return PyInt_FromLong (j);
-}
-
-static PyObject *
-get_browser (genericobject *g)
-{
-	return call_forms_Ri (fl_get_browser, g-> ob_generic);
-}
-
-static PyObject *
-set_browser_fontsize (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_browser_fontsize, g-> ob_generic, args);
-}
-
-static PyObject *
-set_browser_fontstyle (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_browser_fontstyle, g-> ob_generic, args);
-}
-
-static PyObject *
-set_browser_specialkey (genericobject *g, PyObject *args)
-{
-	return call_forms_INc(fl_set_browser_specialkey, g-> ob_generic, args);
-}
-
-static PyMethodDef browser_methods[] = {
-	{"set_browser_topline",		(PyCFunction)set_browser_topline,
-	 METH_OLDARGS},
-	{"clear_browser",		(PyCFunction)clear_browser,
-	 METH_NOARGS},
-	{"add_browser_line",		(PyCFunction)add_browser_line,
-	 METH_OLDARGS},
-	{"addto_browser",		(PyCFunction)addto_browser,
-	 METH_OLDARGS},
-	{"insert_browser_line",		(PyCFunction)insert_browser_line,
-	 METH_OLDARGS},
-	{"delete_browser_line",		(PyCFunction)delete_browser_line,
-	 METH_OLDARGS},
-	{"replace_browser_line",	(PyCFunction)replace_browser_line,
-	 METH_OLDARGS},
-	{"get_browser_line",		(PyCFunction)get_browser_line,
-	 METH_OLDARGS},
-	{"load_browser",		(PyCFunction)load_browser,
-	 METH_OLDARGS},
-	{"get_browser_maxline",		(PyCFunction)get_browser_maxline,
-	 METH_NOARGS,}
-	{"select_browser_line",		(PyCFunction)select_browser_line,
-	 METH_OLDARGS},
-	{"deselect_browser_line",	(PyCFunction)deselect_browser_line,
-	 METH_OLDARGS},
-	{"deselect_browser",		(PyCFunction)deselect_browser,
-	 METH_NOARGS,}
-	{"isselected_browser_line",	(PyCFunction)isselected_browser_line,
-	 METH_OLDARGS},
-	{"get_browser",			(PyCFunction)get_browser,
-	 METH_NOARGS,}
-	{"set_browser_fontsize",	(PyCFunction)set_browser_fontsize,
-	 METH_OLDARGS},
-	{"set_browser_fontstyle",	(PyCFunction)set_browser_fontstyle,
-	 METH_OLDARGS},
-	{"set_browser_specialkey",	(PyCFunction)set_browser_specialkey,
-	 METH_OLDARGS},
-	{NULL,				NULL}		/* sentinel */
-};
-
-/* Class: button */
-
-static PyObject *
-set_button(genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_button, g-> ob_generic, args);
-}
-
-static PyObject *
-get_button(genericobject *g)
-{
-	return call_forms_Ri (fl_get_button, g-> ob_generic);
-}
-
-static PyObject *
-get_button_numb(genericobject *g)
-{
-	return call_forms_Ri (fl_get_button_numb, g-> ob_generic);
-}
-
-static PyObject *
-set_button_shortcut(genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_set_button_shortcut, g-> ob_generic, args);
-}
-
-static PyMethodDef button_methods[] = {
-	{"set_button",		(PyCFunction)set_button, METH_OLDARGS},
-	{"get_button",		(PyCFunction)get_button, METH_NOARGS},
-	{"get_button_numb",	(PyCFunction)get_button_numb, METH_NOARGS},
-	{"set_button_shortcut",	(PyCFunction)set_button_shortcut, METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-/* Class: choice */
-
-static PyObject *
-set_choice(genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_choice, g-> ob_generic, args);
-}
-
-static PyObject *
-get_choice(genericobject *g)
-{
-	return call_forms_Ri (fl_get_choice, g-> ob_generic);
-}
-
-static PyObject *
-clear_choice (genericobject *g)
-{
-	return generic_call (g, fl_clear_choice);
-}
-
-static PyObject *
-addto_choice (genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_addto_choice, g-> ob_generic, args);
-}
-
-static PyObject *
-replace_choice (genericobject *g, PyObject *args)
-{
-	return call_forms_INiINstr (fl_replace_choice, g-> ob_generic, args);
-}
-
-static PyObject *
-delete_choice (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_delete_choice, g-> ob_generic, args);
-}
-
-static PyObject *
-get_choice_text (genericobject *g)
-{
-	return call_forms_Rstr (fl_get_choice_text, g-> ob_generic);
-}
-
-static PyObject *
-set_choice_fontsize (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_choice_fontsize, g-> ob_generic, args);
-}
-
-static PyObject *
-set_choice_fontstyle (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_choice_fontstyle, g-> ob_generic, args);
-}
-
-static PyMethodDef choice_methods[] = {
-	{"set_choice",		(PyCFunction)set_choice,      METH_OLDARGS},
-	{"get_choice",		(PyCFunction)get_choice,      METH_NOARGS},
-	{"clear_choice",	(PyCFunction)clear_choice,    METH_NOARGS},
-	{"addto_choice",	(PyCFunction)addto_choice,    METH_OLDARGS},
-	{"replace_choice",	(PyCFunction)replace_choice,  METH_OLDARGS},
-	{"delete_choice",	(PyCFunction)delete_choice,   METH_OLDARGS},
-	{"get_choice_text",	(PyCFunction)get_choice_text, METH_NOARGS},
-	{"set_choice_fontsize", (PyCFunction)set_choice_fontsize, METH_OLDARGS},
-	{"set_choice_fontstyle",(PyCFunction)set_choice_fontstyle, METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-/* Class : Clock */
-
-static PyObject *
-get_clock(genericobject *g)
-{
-	int i0, i1, i2;
-
-	fl_get_clock (g->ob_generic, &i0, &i1, &i2);
-
-	return Py_BuildValue("(iii)", i0, i1, i2);
-}
-
-static PyMethodDef clock_methods[] = {
-	{"get_clock",		(PyCFunction)get_clock, METH_NOARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-/* CLass : Counters */
-
-static PyObject *
-get_counter_value(genericobject *g)
-{
-	return call_forms_Rf (fl_get_counter_value, g-> ob_generic);
-}
-
-static PyObject *
-set_counter_value (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_counter_value, g-> ob_generic, args);
-}
-
-static PyObject *
-set_counter_precision (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_counter_precision, g-> ob_generic, args);
-}
-
-static PyObject *
-set_counter_bounds (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_counter_bounds, g-> ob_generic, args);
-}
-
-static PyObject *
-set_counter_step (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_counter_step, g-> ob_generic, args);
-}
-
-static PyObject *
-set_counter_return (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_counter_return, g-> ob_generic, args);
-}
-
-static PyMethodDef counter_methods[] = {
-	{"set_counter_value",		(PyCFunction)set_counter_value,
-	 METH_OLDARGS},
-	{"get_counter_value",		(PyCFunction)get_counter_value,
-	 METH_NOARGS},
-	{"set_counter_bounds",		(PyCFunction)set_counter_bounds,
-	 METH_OLDARGS},
-	{"set_counter_step",		(PyCFunction)set_counter_step,
-	 METH_OLDARGS},
-	{"set_counter_precision",	(PyCFunction)set_counter_precision,
-	 METH_OLDARGS},
-	{"set_counter_return",		(PyCFunction)set_counter_return,
-	 METH_OLDARGS},
-	{NULL,				NULL}		/* sentinel */
-};
-
-
-/* Class: Dials */
-
-static PyObject *
-get_dial_value(genericobject *g)
-{
-	return call_forms_Rf (fl_get_dial_value, g-> ob_generic);
-}
-
-static PyObject *
-set_dial_value (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_dial_value, g-> ob_generic, args);
-}
-
-static PyObject *
-set_dial_bounds (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_dial_bounds, g-> ob_generic, args);
-}
-
-static PyObject *
-get_dial_bounds (genericobject *g)
-{
-	return call_forms_OUTfOUTf (fl_get_dial_bounds, g-> ob_generic);
-}
-
-static PyObject *
-set_dial_step (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_dial_step, g-> ob_generic, args);
-}
-
-static PyMethodDef dial_methods[] = {
-	{"set_dial_value",	(PyCFunction)set_dial_value,  METH_OLDARGS},
-	{"get_dial_value",	(PyCFunction)get_dial_value,  METH_NOARGS},
-	{"set_dial_bounds",	(PyCFunction)set_dial_bounds, METH_OLDARGS},
-	{"get_dial_bounds",	(PyCFunction)get_dial_bounds, METH_NOARGS},
-	{"set_dial_step",	(PyCFunction)set_dial_step,   METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-/* Class : Input */
-
-static PyObject *
-set_input (genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_set_input, g-> ob_generic, args);
-}
-
-static PyObject *
-get_input (genericobject *g)
-{
-	return call_forms_Rstr (fl_get_input, g-> ob_generic);
-}
-
-static PyObject *
-set_input_color (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_input_color, g-> ob_generic, args);
-}
-
-static PyObject *
-set_input_return (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_input_return, g-> ob_generic, args);
-}
-
-static PyMethodDef input_methods[] = {
-	{"set_input",		(PyCFunction)set_input,        METH_OLDARGS},
-	{"get_input",		(PyCFunction)get_input,        METH_NOARGS},
-	{"set_input_color",	(PyCFunction)set_input_color,  METH_OLDARGS},
-	{"set_input_return",	(PyCFunction)set_input_return, METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-
-/* Class : Menu */
-
-static PyObject *
-set_menu (genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_set_menu, g-> ob_generic, args);
-}
-
-static PyObject *
-get_menu (genericobject *g)
-{
-	/* XXX strictly speaking this is wrong since fl_get_menu
-	   XXX returns long, not int */
-	return call_forms_Ri (fl_get_menu, g-> ob_generic);
-}
-
-static PyObject *
-get_menu_text (genericobject *g)
-{
-	return call_forms_Rstr (fl_get_menu_text, g-> ob_generic);
-}
-
-static PyObject *
-addto_menu (genericobject *g, PyObject *args)
-{
-	return call_forms_INstr (fl_addto_menu, g-> ob_generic, args);
-}
-
-static PyMethodDef menu_methods[] = {
-	{"set_menu",		(PyCFunction)set_menu,      METH_OLDARGS},
-	{"get_menu",		(PyCFunction)get_menu,      METH_NOARGS},
-	{"get_menu_text",	(PyCFunction)get_menu_text, METH_NOARGS},
-	{"addto_menu",		(PyCFunction)addto_menu,    METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-
-/* Class: Sliders */
-
-static PyObject *
-get_slider_value(genericobject *g)
-{
-	return call_forms_Rf (fl_get_slider_value, g-> ob_generic);
-}
-
-static PyObject *
-set_slider_value (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_slider_value, g-> ob_generic, args);
-}
-
-static PyObject *
-set_slider_bounds (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_slider_bounds, g-> ob_generic, args);
-}
-
-static PyObject *
-get_slider_bounds (genericobject *g)
-{
-	return call_forms_OUTfOUTf(fl_get_slider_bounds, g-> ob_generic);
-}
-
-static PyObject *
-set_slider_return (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_slider_return, g-> ob_generic, args);
-}
-
-static PyObject *
-set_slider_size (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_slider_size, g-> ob_generic, args);
-}
-
-static PyObject *
-set_slider_precision (genericobject *g, PyObject *args)
-{
-	return call_forms_INi (fl_set_slider_precision, g-> ob_generic, args);
-}
-
-static PyObject *
-set_slider_step (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_slider_step, g-> ob_generic, args);
-}
-
-
-static PyMethodDef slider_methods[] = {
-	{"set_slider_value",	(PyCFunction)set_slider_value,  METH_OLDARGS},
-	{"get_slider_value",	(PyCFunction)get_slider_value,  METH_NOARGS},
-	{"set_slider_bounds",	(PyCFunction)set_slider_bounds, METH_OLDARGS},
-	{"get_slider_bounds",	(PyCFunction)get_slider_bounds, METH_NOARGS},
-	{"set_slider_return",	(PyCFunction)set_slider_return, METH_OLDARGS},
-	{"set_slider_size",	(PyCFunction)set_slider_size,   METH_OLDARGS},
-	{"set_slider_precision",(PyCFunction)set_slider_precision, METH_OLDARGS},
-	{"set_slider_step",	(PyCFunction)set_slider_step,   METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-static PyObject *
-set_positioner_xvalue (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_positioner_xvalue, g-> ob_generic, args);
-}
-
-static PyObject *
-set_positioner_xbounds (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_positioner_xbounds,
-				  g-> ob_generic, args);
-}
-
-static PyObject *
-set_positioner_yvalue (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_positioner_yvalue, g-> ob_generic, args);
-}
-
-static PyObject *
-set_positioner_ybounds (genericobject *g, PyObject *args)
-{
-	return call_forms_INfINf (fl_set_positioner_ybounds,
-				  g-> ob_generic, args);
-}
-
-static PyObject *
-get_positioner_xvalue (genericobject *g)
-{
-	return call_forms_Rf (fl_get_positioner_xvalue, g-> ob_generic);
-}
-
-static PyObject *
-get_positioner_xbounds (genericobject *g)
-{
-	return call_forms_OUTfOUTf (fl_get_positioner_xbounds, g-> ob_generic);
-}
-
-static PyObject *
-get_positioner_yvalue (genericobject *g)
-{
-	return call_forms_Rf (fl_get_positioner_yvalue, g-> ob_generic);
-}
-
-static PyObject *
-get_positioner_ybounds (genericobject *g)
-{
-	return call_forms_OUTfOUTf (fl_get_positioner_ybounds, g-> ob_generic);
-}
-
-static PyMethodDef positioner_methods[] = {
-	{"set_positioner_xvalue",	(PyCFunction)set_positioner_xvalue,
-	 METH_OLDARGS},
-	{"set_positioner_yvalue",	(PyCFunction)set_positioner_yvalue,
-	 METH_OLDARGS},
-	{"set_positioner_xbounds",	(PyCFunction)set_positioner_xbounds,
-	 METH_OLDARGS},
-	{"set_positioner_ybounds",	(PyCFunction)set_positioner_ybounds,
-	 METH_OLDARGS},
-	{"get_positioner_xvalue",	(PyCFunction)get_positioner_xvalue,
-	 METH_NOARGS},
-	{"get_positioner_yvalue",	(PyCFunction)get_positioner_yvalue,
-	 METH_NOARGS},
-	{"get_positioner_xbounds",	(PyCFunction)get_positioner_xbounds,
-	 METH_NOARGS},
-	{"get_positioner_ybounds",	(PyCFunction)get_positioner_ybounds,
-	 METH_NOARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-/* Class timer */
-
-static PyObject *
-set_timer (genericobject *g, PyObject *args)
-{
-	return call_forms_INf (fl_set_timer, g-> ob_generic, args);
-}
-
-static PyObject *
-get_timer (genericobject *g)
-{
-	return call_forms_Rf (fl_get_timer, g-> ob_generic);
-}
-
-static PyMethodDef timer_methods[] = {
-	{"set_timer",		(PyCFunction)set_timer, METH_OLDARGS},
-	{"get_timer",		(PyCFunction)get_timer, METH_NOARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-/* Form objects */
-
-typedef struct {
-	PyObject_HEAD
-	FL_FORM *ob_form;
-} formobject;
-
-static PyTypeObject Formtype;
-
-#define is_formobject(v) ((v)->ob_type == &Formtype)
-
-static PyObject *
-form_show_form(formobject *f, PyObject *args)
-{
-	int place, border;
-	char *name;
-	if (!PyArg_Parse(args, "(iis)", &place, &border, &name))
-		return NULL;
-	fl_show_form(f->ob_form, place, border, name);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-form_call(void (*func)(FL_FORM *), FL_FORM *f)
-{
-	(*func)(f);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-form_call_INiINi(void (*func)(FL_FORM *, int, int), FL_FORM *f, PyObject *args)
-{
-	int a, b;
-
-	if (!PyArg_Parse(args, "(ii)", &a, &b)) return NULL;
-
-	(*func)(f, a, b);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-form_call_INfINf(void (*func)(FL_FORM *, float, float), FL_FORM *f, PyObject *args)
-{
-	float a, b;
-
-	if (!PyArg_Parse(args, "(ff)", &a, &b)) return NULL;
-
-	(*func)(f, a, b);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-form_hide_form(formobject *f)
-{
-	return form_call(fl_hide_form, f-> ob_form);
-}
-
-static PyObject *
-form_redraw_form(formobject *f)
-{
-	return form_call(fl_redraw_form, f-> ob_form);
-}
-
-static PyObject *
-form_set_form_position(formobject *f, PyObject *args)
-{
-	return form_call_INiINi(fl_set_form_position, f-> ob_form, args);
-}
-
-static PyObject *
-form_set_form_size(formobject *f, PyObject *args)
-{
-	return form_call_INiINi(fl_set_form_size, f-> ob_form, args);
-}
-
-static PyObject *
-form_scale_form(formobject *f, PyObject *args)
-{
-	return form_call_INfINf(fl_scale_form, f-> ob_form, args);
-}
-
-static PyObject *
-generic_add_object(formobject *f, PyObject *args, FL_OBJECT *(*func)(int, float, float, float, float, char*), PyMethodDef *internal_methods)
-{
-	int type;
-	float x, y, w, h;
-	char *name;
-	FL_OBJECT *obj;
-
-	if (!PyArg_Parse(args,"(iffffs)", &type,&x,&y,&w,&h,&name))
-		return NULL;
-
-	fl_addto_form (f-> ob_form);
-
-	obj = (*func) (type, x, y, w, h, name);
-
-	fl_end_form();
-
-	if (obj == NULL) {
-		PyErr_NoMemory();
-		return NULL;
-	}
-
-	return newgenericobject (obj, internal_methods);
-}
-
-static PyObject *
-form_add_button(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_button, button_methods);
-}
-
-static PyObject *
-form_add_lightbutton(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_lightbutton, button_methods);
-}
-
-static PyObject *
-form_add_roundbutton(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_roundbutton, button_methods);
-}
-
-static PyObject *
-form_add_menu (formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_menu, menu_methods);
-}
-
-static PyObject *
-form_add_slider(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_slider, slider_methods);
-}
-
-static PyObject *
-form_add_valslider(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_valslider, slider_methods);
-}
-
-static PyObject *
-form_add_dial(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_dial, dial_methods);
-}
-
-static PyObject *
-form_add_counter(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_counter, counter_methods);
-}
-
-static PyObject *
-form_add_clock(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_clock, clock_methods);
-}
-
-static PyObject *
-form_add_box(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_box,
-				  (PyMethodDef *)NULL);
-}
-
-static PyObject *
-form_add_choice(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_choice, choice_methods);
-}
-
-static PyObject *
-form_add_browser(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_browser, browser_methods);
-}
-
-static PyObject *
-form_add_positioner(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_positioner,
-				  positioner_methods);
-}
-
-static PyObject *
-form_add_input(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_input, input_methods);
-}
-
-static PyObject *
-form_add_text(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_text,
-				  (PyMethodDef *)NULL);
-}
-
-static PyObject *
-form_add_timer(formobject *f, PyObject *args)
-{
-	return generic_add_object(f, args, fl_add_timer, timer_methods);
-}
-
-static PyObject *
-form_freeze_form(formobject *f)
-{
-	return form_call(fl_freeze_form, f-> ob_form);
-}
-
-static PyObject *
-form_unfreeze_form(formobject *f)
-{
-	return form_call(fl_unfreeze_form, f-> ob_form);
-}
-
-static PyObject *
-form_activate_form(formobject *f)
-{
-	return form_call(fl_activate_form, f-> ob_form);
-}
-
-static PyObject *
-form_deactivate_form(formobject *f)
-{
-	return form_call(fl_deactivate_form, f-> ob_form);
-}
-
-static PyObject *
-form_bgn_group(formobject *f, PyObject *args)
-{
-	FL_OBJECT *obj;
-
-	fl_addto_form(f-> ob_form);
-	obj = fl_bgn_group();
-	fl_end_form();
-
-	if (obj == NULL) {
-		PyErr_NoMemory();
-		return NULL;
-	}
-
-	return newgenericobject (obj, (PyMethodDef *) NULL);
-}
-
-static PyObject *
-form_end_group(formobject *f, PyObject *args)
-{
-	fl_addto_form(f-> ob_form);
-	fl_end_group();
-	fl_end_form();
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_find_first_or_last(FL_OBJECT *(*func)(FL_FORM *, int, float, float), formobject *f, PyObject *args)
-{
-	int type;
-	float mx, my;
-	FL_OBJECT *generic;
-	genericobject *g;
-	
-	if (!PyArg_Parse(args, "(iff)", &type, &mx, &my)) return NULL;
-
-	generic = (*func) (f-> ob_form, type, mx, my);
-
-	if (generic == NULL)
-	{
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-
-	g = findgeneric(generic);
-	if (g == NULL) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "forms_find_{first|last} returns unknown object");
-		return NULL;
-	}
-	Py_INCREF(g);
-	return (PyObject *) g;
-}
-
-static PyObject *
-form_find_first(formobject *f, PyObject *args)
-{
-	return forms_find_first_or_last(fl_find_first, f, args);
-}
-
-static PyObject *
-form_find_last(formobject *f, PyObject *args)
-{
-	return forms_find_first_or_last(fl_find_last, f, args);
-}
-
-static PyObject *
-form_set_object_focus(formobject *f, PyObject *args)
-{
-	genericobject *g;
-	if (args == NULL || !is_genericobject(args)) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	g = (genericobject *)args;
-	fl_set_object_focus(f->ob_form, g->ob_generic);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyMethodDef form_methods[] = {
-/* adm */
-	{"show_form",		(PyCFunction)form_show_form,     METH_OLDARGS},
-	{"hide_form",		(PyCFunction)form_hide_form,     METH_NOARGS},
-	{"redraw_form",		(PyCFunction)form_redraw_form,   METH_NOARGS},
-	{"set_form_position",	(PyCFunction)form_set_form_position, METH_OLDARGS},
-	{"set_form_size",	(PyCFunction)form_set_form_size, METH_OLDARGS},
-	{"scale_form",		(PyCFunction)form_scale_form,    METH_OLDARGS},
-	{"freeze_form",		(PyCFunction)form_freeze_form,   METH_NOARGS},
-	{"unfreeze_form",	(PyCFunction)form_unfreeze_form, METH_NOARGS},
-	{"activate_form",	(PyCFunction)form_activate_form, METH_NOARGS},
-	{"deactivate_form",	(PyCFunction)form_deactivate_form, METH_NOARGS},
-	{"bgn_group",		(PyCFunction)form_bgn_group,  METH_OLDARGS},
-	{"end_group",		(PyCFunction)form_end_group,  METH_OLDARGS},
-	{"find_first",		(PyCFunction)form_find_first, METH_OLDARGS},
-	{"find_last",		(PyCFunction)form_find_last,  METH_OLDARGS},
-	{"set_object_focus",	(PyCFunction)form_set_object_focus, METH_OLDARGS},
-
-/* basic objects */
-	{"add_button",		(PyCFunction)form_add_button, METH_OLDARGS},
-/*	{"add_bitmap",		(method)form_add_bitmap, METH_OLDARGS}, */
-	{"add_lightbutton",	(PyCFunction)form_add_lightbutton, METH_OLDARGS},
-	{"add_roundbutton",	(PyCFunction)form_add_roundbutton, METH_OLDARGS},
-	{"add_menu",		(PyCFunction)form_add_menu,      METH_OLDARGS},
-	{"add_slider",		(PyCFunction)form_add_slider,    METH_OLDARGS},
-	{"add_positioner",	(PyCFunction)form_add_positioner, METH_OLDARGS},
-	{"add_valslider",	(PyCFunction)form_add_valslider, METH_OLDARGS},
-	{"add_dial",		(PyCFunction)form_add_dial,      METH_OLDARGS},
-	{"add_counter",		(PyCFunction)form_add_counter,   METH_OLDARGS},
-	{"add_box",		(PyCFunction)form_add_box,       METH_OLDARGS},
-	{"add_clock",		(PyCFunction)form_add_clock,     METH_OLDARGS},
-	{"add_choice",		(PyCFunction)form_add_choice,    METH_OLDARGS},
-	{"add_browser",		(PyCFunction)form_add_browser,   METH_OLDARGS},
-	{"add_input",		(PyCFunction)form_add_input,     METH_OLDARGS},
-	{"add_timer",		(PyCFunction)form_add_timer,     METH_OLDARGS},
-	{"add_text",		(PyCFunction)form_add_text,      METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-static void
-form_dealloc(formobject *f)
-{
-	releaseobjects(f->ob_form);
-	if (f->ob_form->visible)
-		fl_hide_form(f->ob_form);
-	fl_free_form(f->ob_form);
-	PyObject_Del(f);
-}
-
-#define OFF(x) offsetof(FL_FORM, x)
-
-static struct memberlist form_memberlist[] = {
-	{"window",	T_LONG,		OFF(window),	RO},
-	{"w",		T_FLOAT,	OFF(w)},
-	{"h",		T_FLOAT,	OFF(h)},
-	{"x",		T_FLOAT,	OFF(x),		RO},
-	{"y",		T_FLOAT,	OFF(y),		RO},
-	{"deactivated",	T_INT,		OFF(deactivated)},
-	{"visible",	T_INT,		OFF(visible),	RO},
-	{"frozen",	T_INT,		OFF(frozen),	RO},
-	{"doublebuf",	T_INT,		OFF(doublebuf)},
-	{NULL}	/* Sentinel */
-};
-
-#undef OFF
-
-static PyObject *
-form_getattr(formobject *f, char *name)
-{
-	PyObject *meth;
-
-	meth = Py_FindMethod(form_methods, (PyObject *)f, name);
-	if (meth != NULL)
-		return meth;
-	PyErr_Clear();
-	return PyMember_Get((char *)f->ob_form, form_memberlist, name);
-}
-
-static int
-form_setattr(formobject *f, char *name, PyObject *v)
-{
-	if (v == NULL) {
-		PyErr_SetString(PyExc_TypeError,
-				"can't delete form attributes");
-		return -1;
-	}
-
-	return PyMember_Set((char *)f->ob_form, form_memberlist, name, v);
-}
-
-static PyObject *
-form_repr(formobject *f)
-{
-	char buf[100];
-	PyOS_snprintf(buf, sizeof(buf), "<FORMS_form at %p, window=%ld>",
-		      f, f->ob_form->window);
-	return PyString_FromString(buf);
-}
-
-static PyTypeObject Formtype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,				/*ob_size*/
-	"fl.FORMS_form",		/*tp_name*/
-	sizeof(formobject),		/*tp_size*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)form_dealloc,	/*tp_dealloc*/
-	0,				/*tp_print*/
-	(getattrfunc)form_getattr,	/*tp_getattr*/
-	(setattrfunc)form_setattr,	/*tp_setattr*/
-	0,				/*tp_compare*/
-	(reprfunc)form_repr,		/*tp_repr*/
-};
-
-static PyObject *
-newformobject(FL_FORM *form)
-{
-	formobject *f;
-	f = PyObject_New(formobject, &Formtype);
-	if (f == NULL)
-		return NULL;
-	f->ob_form = form;
-	return (PyObject *)f;
-}
-
-
-/* The "fl" module */
-
-static PyObject *
-forms_make_form(PyObject *dummy, PyObject *args)
-{
-	int type;
-	float w, h;
-	FL_FORM *form;
-	if (!PyArg_Parse(args, "(iff)", &type, &w, &h))
-		return NULL;
-	form = fl_bgn_form(type, w, h);
-	if (form == NULL) {
-		/* XXX Actually, cannot happen! */
-		PyErr_NoMemory();
-		return NULL;
-	}
-	fl_end_form();
-	return newformobject(form);
-}
-
-static PyObject *
-forms_activate_all_forms(PyObject *f, PyObject *args)
-{
-	fl_activate_all_forms();
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_deactivate_all_forms(PyObject *f, PyObject *args)
-{
-	fl_deactivate_all_forms();
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *my_event_callback = NULL;
-
-static PyObject *
-forms_set_event_call_back(PyObject *dummy, PyObject *args)
-{
-	if (args == Py_None)
-		args = NULL;
-	my_event_callback = args;
-	Py_XINCREF(args);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_do_or_check_forms(PyObject *dummy, FL_OBJECT *(*func)(void))
-{
-	FL_OBJECT *generic;
-	genericobject *g;
-	PyObject *arg, *res;
-
-	for (;;) {
-		Py_BEGIN_ALLOW_THREADS
-		generic = (*func)();
-		Py_END_ALLOW_THREADS
-		if (generic == NULL) {
-			Py_INCREF(Py_None);
-			return Py_None;
-		}
-		if (generic == FL_EVENT) {
-			int dev;
-			short val;
-			if (my_event_callback == NULL)
-				return PyInt_FromLong(-1L);
-			dev = fl_qread(&val);
-			arg = Py_BuildValue("(ih)", dev, val);
-			if (arg == NULL)
-				return NULL;
-			res = PyEval_CallObject(my_event_callback, arg);
-			Py_XDECREF(res);
-			Py_DECREF(arg);
-			if (res == NULL)
-				return NULL; /* Callback raised exception */
-			continue;
-		}
-		g = findgeneric(generic);
-		if (g == NULL) {
-			/* Object not known to us (some dialogs cause this) */
-			continue; /* Ignore it */
-		}
-		if (g->ob_callback == NULL) {
-			Py_INCREF(g);
-			return ((PyObject *) g);
-		}
-		arg = PyTuple_Pack(2, (PyObject *)g, g->ob_callback_arg);
-		if (arg == NULL)
-			return NULL;
-		res = PyEval_CallObject(g->ob_callback, arg);
-		Py_XDECREF(res);
-		Py_DECREF(arg);
-		if (res == NULL)
-			return NULL; /* Callback raised exception */
-	}
-}
-
-static PyObject *
-forms_do_forms(PyObject *dummy)
-{
-	return forms_do_or_check_forms(dummy, fl_do_forms);
-}
-
-static PyObject *
-forms_check_forms(PyObject *dummy)
-{
-	return forms_do_or_check_forms(dummy, fl_check_forms);
-}
-
-static PyObject *
-forms_do_only_forms(PyObject *dummy)
-{
-	return forms_do_or_check_forms(dummy, fl_do_only_forms);
-}
-
-static PyObject *
-forms_check_only_forms(PyObject *dummy)
-{
-	return forms_do_or_check_forms(dummy, fl_check_only_forms);
-}
-
-#ifdef UNUSED
-static PyObject *
-fl_call(void (*func)(void))
-{
-	(*func)();
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-#endif
-
-static PyObject *
-forms_set_graphics_mode(PyObject *dummy, PyObject *args)
-{
-	int rgbmode, doublebuf;
-
-	if (!PyArg_Parse(args, "(ii)", &rgbmode, &doublebuf))
-		return NULL;
-	fl_set_graphics_mode(rgbmode,doublebuf);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_get_rgbmode(PyObject *dummy, PyObject *args)
-{
-	extern int fl_rgbmode;
-
-	if (args != NULL) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	return PyInt_FromLong((long)fl_rgbmode);
-}
-
-static PyObject *
-forms_show_errors(PyObject *dummy, PyObject *args)
-{
-	int show;
-	if (!PyArg_Parse(args, "i", &show))
-		return NULL;
-	fl_show_errors(show);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_set_font_name(PyObject *dummy, PyObject *args)
-{
-	int numb;
-	char *name;
-	if (!PyArg_Parse(args, "(is)", &numb, &name))
-		return NULL;
-	fl_set_font_name(numb, name);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-static PyObject *
-forms_qdevice(PyObject *self, PyObject *args)
-{
-	short arg1;
-	if (!PyArg_Parse(args, "h", &arg1))
-		return NULL;
-	fl_qdevice(arg1);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_unqdevice(PyObject *self, PyObject *args)
-{
-	short arg1;
-	if (!PyArg_Parse(args, "h", &arg1))
-		return NULL;
-	fl_unqdevice(arg1);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_isqueued(PyObject *self, PyObject *args)
-{
-	long retval;
-	short arg1;
-	if (!PyArg_Parse(args, "h", &arg1))
-		return NULL;
-	retval = fl_isqueued(arg1);
-
-	return PyInt_FromLong(retval);
-}
-
-static PyObject *
-forms_qtest(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = fl_qtest();
-	return PyInt_FromLong(retval);
-}
-
-
-static PyObject *
-forms_qread(PyObject *self, PyObject *args)
-{
-	int dev;
-	short val;
-	Py_BEGIN_ALLOW_THREADS
-	dev = fl_qread(&val);
-	Py_END_ALLOW_THREADS
-	return Py_BuildValue("(ih)", dev, val);
-}
-
-static PyObject *
-forms_qreset(PyObject *self)
-{
-	fl_qreset();
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_qenter(PyObject *self, PyObject *args)
-{
-	short arg1, arg2;
-	if (!PyArg_Parse(args, "(hh)", &arg1, &arg2))
-		return NULL;
-	fl_qenter(arg1, arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_color(PyObject *self, PyObject *args)
-{
-	int arg;
-
-	if (!PyArg_Parse(args, "i", &arg)) return NULL;
-
-	fl_color((short) arg);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_mapcolor(PyObject *self, PyObject *args)
-{
-	int arg0, arg1, arg2, arg3;
-
-	if (!PyArg_Parse(args, "(iiii)", &arg0, &arg1, &arg2, &arg3))
-		return NULL;
-
-	fl_mapcolor(arg0, (short) arg1, (short) arg2, (short) arg3);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_getmcolor(PyObject *self, PyObject *args)
-{
-	int arg;
-	short r, g, b;
-
-	if (!PyArg_Parse(args, "i", &arg)) return NULL;
-
-	fl_getmcolor(arg, &r, &g, &b);
-
-	return Py_BuildValue("(hhh)", r, g, b);
-}
-
-static PyObject *
-forms_get_mouse(PyObject *self)
-{
-	float x, y;
-
-	fl_get_mouse(&x, &y);
-
-	return Py_BuildValue("(ff)", x, y);
-}
-
-static PyObject *
-forms_tie(PyObject *self, PyObject *args)
-{
-	short arg1, arg2, arg3;
-	if (!PyArg_Parse(args, "(hhh)", &arg1, &arg2, &arg3))
-		return NULL;
-	fl_tie(arg1, arg2, arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_show_message(PyObject *f, PyObject *args)
-{
-	char *a, *b, *c;
-
-	if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	fl_show_message(a, b, c);
-	Py_END_ALLOW_THREADS
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-forms_show_choice(PyObject *f, PyObject *args)
-{
-	char *m1, *m2, *m3, *b1, *b2, *b3;
-	int nb;
-	char *format;
-	long rv;
-
-	if (args == NULL || !PyTuple_Check(args)) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	nb = PyTuple_Size(args) - 3;
-	if (nb <= 0) {
-		PyErr_SetString(PyExc_TypeError,
-				"need at least one button label");
-		return NULL;
-	}
-	if (PyInt_Check(PyTuple_GetItem(args, 3))) {
-		PyErr_SetString(PyExc_TypeError,
-			   "'number-of-buttons' argument not needed");
-		return NULL;
-	}
-	switch (nb) {
-	case 1: format = "(ssss)"; break;
-	case 2: format = "(sssss)"; break;
-	case 3: format = "(ssssss)"; break;
-	default:
-		PyErr_SetString(PyExc_TypeError, "too many button labels");
-		return NULL;
-	}
-
-	if (!PyArg_Parse(args, format, &m1, &m2, &m3, &b1, &b2, &b3))
-		return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	rv = fl_show_choice(m1, m2, m3, nb, b1, b2, b3);
-	Py_END_ALLOW_THREADS
-	return PyInt_FromLong(rv);
-}
-
-static PyObject *
-forms_show_question(PyObject *f, PyObject *args)
-{
-	int ret;
-	char *a, *b, *c;
-
-	if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	ret = fl_show_question(a, b, c);
-	Py_END_ALLOW_THREADS
-
-	return PyInt_FromLong((long) ret);
-}
-
-static PyObject *
-forms_show_input(PyObject *f, PyObject *args)
-{
-	char *str;
-	char *a, *b;
-
-	if (!PyArg_Parse(args, "(ss)", &a, &b)) return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	str = fl_show_input(a, b);
-	Py_END_ALLOW_THREADS
-
-	if (str == NULL) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	return PyString_FromString(str);
-}
-
-static PyObject *
-forms_file_selector(PyObject *f, PyObject *args)
-{
-	char *str;
-	char *a, *b, *c, *d;
-
-	if (!PyArg_Parse(args, "(ssss)", &a, &b, &c, &d)) return NULL;
-
-	Py_BEGIN_ALLOW_THREADS
-	str = fl_show_file_selector(a, b, c, d);
-	Py_END_ALLOW_THREADS
-
-	if (str == NULL) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	return PyString_FromString(str);
-}
-
-
-static PyObject *
-forms_file_selector_func(PyObject *args, char *(*func)(void))
-{
-	char *str;
-
-	str = (*func) ();
-
-	if (str == NULL) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	return PyString_FromString(str);
-}
-
-static PyObject *
-forms_get_directory(PyObject *f, PyObject *args)
-{
-	return forms_file_selector_func(args, fl_get_directory);
-}
-
-static PyObject *
-forms_get_pattern(PyObject *f, PyObject *args)
-{
-	return forms_file_selector_func(args, fl_get_pattern);
-}
-
-static PyObject *
-forms_get_filename(PyObject *f, PyObject *args)
-{
-	return forms_file_selector_func(args, fl_get_filename);
-}
-
-static PyMethodDef forms_methods[] = {
-/* adm */
-	{"make_form",		forms_make_form, METH_OLDARGS},
-	{"activate_all_forms",	forms_activate_all_forms, METH_OLDARGS},
-	{"deactivate_all_forms",forms_deactivate_all_forms, METH_OLDARGS},
-/* gl support wrappers */
-	{"qdevice",		forms_qdevice, METH_OLDARGS},
-	{"unqdevice",		forms_unqdevice, METH_OLDARGS},
-	{"isqueued",		forms_isqueued, METH_OLDARGS},
-	{"qtest",		forms_qtest, METH_OLDARGS},
-	{"qread",		forms_qread, METH_OLDARGS},
-/*	{"blkqread",		forms_blkqread, METH_OLDARGS}, */
-	{"qreset",		forms_qreset, METH_NOARGS},
-	{"qenter",		forms_qenter, METH_OLDARGS},
-	{"get_mouse",		forms_get_mouse, METH_NOARGS},
-	{"tie",			forms_tie, METH_OLDARGS},
-/*	{"new_events",		forms_new_events, METH_OLDARGS}, */
-	{"color",		forms_color, METH_OLDARGS},
-	{"mapcolor",		forms_mapcolor, METH_OLDARGS},
-	{"getmcolor",		forms_getmcolor, METH_OLDARGS},
-/* interaction */
-	{"do_forms",		forms_do_forms, METH_NOARGS},
-	{"do_only_forms",	forms_do_only_forms, METH_NOARGS},
-	{"check_forms",		forms_check_forms, METH_NOARGS},
-	{"check_only_forms",	forms_check_only_forms, METH_NOARGS},
-	{"set_event_call_back",	forms_set_event_call_back, METH_OLDARGS},
-/* goodies */
-	{"show_message",	forms_show_message, METH_OLDARGS},
-	{"show_question",	forms_show_question, METH_OLDARGS},
-	{"show_choice",		forms_show_choice, METH_OLDARGS},
-	{"show_input",		forms_show_input, METH_OLDARGS},
-	{"show_file_selector",	forms_file_selector, METH_OLDARGS},
-	{"file_selector",	forms_file_selector, METH_OLDARGS}, /* BW compat */
-	{"get_directory",	forms_get_directory, METH_OLDARGS},
-	{"get_pattern",		forms_get_pattern, METH_OLDARGS},
-	{"get_filename",	forms_get_filename, METH_OLDARGS},
-	{"set_graphics_mode",	forms_set_graphics_mode, METH_OLDARGS},
-	{"get_rgbmode",		forms_get_rgbmode, METH_OLDARGS},
-	{"show_errors",		forms_show_errors, METH_OLDARGS},
-	{"set_font_name",	forms_set_font_name, METH_OLDARGS},
-	{NULL,			NULL}		/* sentinel */
-};
-
-PyMODINIT_FUNC
-initfl(void)
-{
-	Py_InitModule("fl", forms_methods);
-	if (m == NULL)
-		return;
-	foreground();
-	fl_init();
-}
-
-
-

Deleted: /python/branches/p3yk-noslice/Modules/fmmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/fmmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,264 +0,0 @@
-
-/* Font Manager module */
-
-#include "Python.h"
-
-#include <gl.h>
-#include <device.h>
-#include <fmclient.h>
-
-
-/* Font Handle object implementation */
-
-typedef struct {
-	PyObject_HEAD
-	fmfonthandle fh_fh;
-} fhobject;
-
-static PyTypeObject Fhtype;
-
-#define is_fhobject(v)		((v)->ob_type == &Fhtype)
-
-static PyObject *
-newfhobject(fmfonthandle fh)
-{
-	fhobject *fhp;
-	if (fh == NULL) {
-		PyErr_SetString(PyExc_RuntimeError,
-				"error creating new font handle");
-		return NULL;
-	}
-	fhp = PyObject_New(fhobject, &Fhtype);
-	if (fhp == NULL)
-		return NULL;
-	fhp->fh_fh = fh;
-	return (PyObject *)fhp;
-}
-
-/* Font Handle methods */
-
-static PyObject *
-fh_scalefont(fhobject *self, PyObject *args)
-{
-	double size;
-	if (!PyArg_ParseTuple(args, "d", &size))
-		return NULL;
-	return newfhobject(fmscalefont(self->fh_fh, size));
-}
-
-/* XXX fmmakefont */
-
-static PyObject *
-fh_setfont(fhobject *self)
-{
-	fmsetfont(self->fh_fh);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-fh_getfontname(fhobject *self)
-{
-	char fontname[256];
-	int len;
-	len = fmgetfontname(self->fh_fh, sizeof fontname, fontname);
-	if (len < 0) {
-		PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontname");
-		return NULL;
-	}
-	return PyString_FromStringAndSize(fontname, len);
-}
-
-static PyObject *
-fh_getcomment(fhobject *self)
-{
-	char comment[256];
-	int len;
-	len = fmgetcomment(self->fh_fh, sizeof comment, comment);
-	if (len < 0) {
-		PyErr_SetString(PyExc_RuntimeError, "error in fmgetcomment");
-		return NULL;
-	}
-	return PyString_FromStringAndSize(comment, len);
-}
-
-static PyObject *
-fh_getfontinfo(fhobject *self)
-{
-	fmfontinfo info;
-	if (fmgetfontinfo(self->fh_fh, &info) < 0) {
-		PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontinfo");
-		return NULL;
-	}
-	return Py_BuildValue("(llllllll)",
-			     info.printermatched,
-			     info.fixed_width,
-			     info.xorig,
-			     info.yorig,
-			     info.xsize,
-			     info.ysize,
-			     info.height,
-			     info.nglyphs);
-}
-
-#if 0
-static PyObject *
-fh_getwholemetrics(fhobject *self, PyObject *args)
-{
-}
-#endif
-
-static PyObject *
-fh_getstrwidth(fhobject *self, PyObject *args)
-{
-	char *str;
-	if (!PyArg_ParseTuple(args, "s", &str))
-		return NULL;
-	return PyInt_FromLong(fmgetstrwidth(self->fh_fh, str));
-}
-
-static PyMethodDef fh_methods[] = {
-	{"scalefont",	(PyCFunction)fh_scalefont,   METH_VARARGS},
-	{"setfont",	(PyCFunction)fh_setfont,     METH_NOARGS},
-	{"getfontname",	(PyCFunction)fh_getfontname, METH_NOARGS},
-	{"getcomment",	(PyCFunction)fh_getcomment,  METH_NOARGS},
-	{"getfontinfo",	(PyCFunction)fh_getfontinfo, METH_NOARGS},
-#if 0
-	{"getwholemetrics",	(PyCFunction)fh_getwholemetrics, METH_VARARGS},
-#endif
-	{"getstrwidth",	(PyCFunction)fh_getstrwidth, METH_VARARGS},
-	{NULL,		NULL}		/* sentinel */
-};
-
-static PyObject *
-fh_getattr(fhobject *fhp, char *name)
-{
-	return Py_FindMethod(fh_methods, (PyObject *)fhp, name);
-}
-
-static void
-fh_dealloc(fhobject *fhp)
-{
-	fmfreefont(fhp->fh_fh);
-	PyObject_Del(fhp);
-}
-
-static PyTypeObject Fhtype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,				/*ob_size*/
-	"fm.font handle",		/*tp_name*/
-	sizeof(fhobject),		/*tp_size*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)fh_dealloc,		/*tp_dealloc*/
-	0,				/*tp_print*/
-	(getattrfunc)fh_getattr,	/*tp_getattr*/
-	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
-	0,				/*tp_repr*/
-};
-
-
-/* Font Manager functions */
-
-static PyObject *
-fm_init(PyObject *self)
-{
-	fminit();
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-fm_findfont(PyObject *self, PyObject *args)
-{
-	char *str;
-	if (!PyArg_ParseTuple(args, "s", &str))
-		return NULL;
-	return newfhobject(fmfindfont(str));
-}
-
-static PyObject *
-fm_prstr(PyObject *self, PyObject *args)
-{
-	char *str;
-	if (!PyArg_ParseTuple(args, "s", &str))
-		return NULL;
-	fmprstr(str);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* XXX This uses a global variable as temporary! Not re-entrant! */
-
-static PyObject *fontlist;
-
-static void
-clientproc(char *fontname)
-{
-	int err;
-	PyObject *v;
-	if (fontlist == NULL)
-		return;
-	v = PyString_FromString(fontname);
-	if (v == NULL)
-		err = -1;
-	else {
-		err = PyList_Append(fontlist, v);
-		Py_DECREF(v);
-	}
-	if (err != 0) {
-		Py_DECREF(fontlist);
-		fontlist = NULL;
-	}
-}
-
-static PyObject *
-fm_enumerate(PyObject *self)
-{
-	PyObject *res;
-	fontlist = PyList_New(0);
-	if (fontlist == NULL)
-		return NULL;
-	fmenumerate(clientproc);
-	res = fontlist;
-	fontlist = NULL;
-	return res;
-}
-
-static PyObject *
-fm_setpath(PyObject *self, PyObject *args)
-{
-	char *str;
-	if (!PyArg_ParseTuple(args, "s", &str))
-		return NULL;
-	fmsetpath(str);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-fm_fontpath(PyObject *self)
-{
-	return PyString_FromString(fmfontpath());
-}
-
-static PyMethodDef fm_methods[] = {
-	{"init",	fm_init,      METH_NOARGS},
-	{"findfont",	fm_findfont,  METH_VARARGS},
-	{"enumerate",	fm_enumerate, METH_NOARGS},
-	{"prstr",	fm_prstr,     METH_VARARGS},
-	{"setpath",	fm_setpath,   METH_VARARGS},
-	{"fontpath",	fm_fontpath,  METH_NOARGS},
-	{NULL,		NULL}		/* sentinel */
-};
-
-
-void
-initfm(void)
-{
-	Py_InitModule("fm", fm_methods);
-	if (m == NULL)
-		return;
-	fminit();
-}

Modified: python/branches/p3yk-noslice/Modules/getaddrinfo.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/getaddrinfo.c	(original)
+++ python/branches/p3yk-noslice/Modules/getaddrinfo.c	Wed Jul 11 15:40:56 2007
@@ -129,12 +129,12 @@
 #define IN_LOOPBACKNET	    127
 #endif
 
-static int get_name Py_PROTO((const char *, struct gai_afd *,
+static int get_name(const char *, struct gai_afd *,
 			  struct addrinfo **, char *, struct addrinfo *,
-			  int));
-static int get_addr Py_PROTO((const char *, int, struct addrinfo **,
-			struct addrinfo *, int));
-static int str_isnumber Py_PROTO((const char *));
+			  int);
+static int get_addr(const char *, int, struct addrinfo **,
+			struct addrinfo *, int);
+static int str_isnumber(const char *);
 	
 static char *ai_errlist[] = {
 	"success.",

Modified: python/branches/p3yk-noslice/Modules/getbuildinfo.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/getbuildinfo.c	(original)
+++ python/branches/p3yk-noslice/Modules/getbuildinfo.c	Wed Jul 11 15:40:56 2007
@@ -20,7 +20,11 @@
 #endif
 #endif
 
-#ifdef SUBWCREV
+/* on unix, SVNVERSION is passed on the command line.
+ * on Windows, the string is interpolated using
+ * subwcrev.exe
+ */
+#ifndef SVNVERSION
 #define SVNVERSION "$WCRANGE$$WCMODS?M:$"
 #endif
 
@@ -40,9 +44,9 @@
 const char *
 _Py_svnversion(void)
 {
-#ifdef SVNVERSION
-	return SVNVERSION;
-#else
+	/* the following string can be modified by subwcrev.exe */
+	static const char svnversion[] = SVNVERSION;
+	if (svnversion[0] != '$')
+		return svnversion; /* it was interpolated, or passed on command line */
 	return "exported";
-#endif
 }

Modified: python/branches/p3yk-noslice/Modules/getnameinfo.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/getnameinfo.c	(original)
+++ python/branches/p3yk-noslice/Modules/getnameinfo.c	Wed Jul 11 15:40:56 2007
@@ -82,8 +82,8 @@
 #define ENI_SALEN	6
 
 /* forward declaration to make gcc happy */
-int getnameinfo Py_PROTO((const struct sockaddr *, size_t, char *, size_t,
-			  char *, size_t, int));
+int getnameinfo(const struct sockaddr *, size_t, char *, size_t,
+			  char *, size_t, int);
 
 int
 getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)

Modified: python/branches/p3yk-noslice/Modules/getpath.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/getpath.c	(original)
+++ python/branches/p3yk-noslice/Modules/getpath.c	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
  * as best as is possible, but most imports will fail.
  *
  * Before any searches are done, the location of the executable is
- * determined.  If argv[0] has one or more slashs in it, it is used
+ * determined.  If argv[0] has one or more slashes in it, it is used
  * unchanged.  Otherwise, it must have been invoked from the shell's path,
  * so we search $PATH for the named executable and use that.  If the
  * executable was not found on $PATH (or there was no $PATH environment

Deleted: /python/branches/p3yk-noslice/Modules/glmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/glmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,7628 +0,0 @@
-
-/*
-Input used to generate the Python module "glmodule.c".
-The stub generator is a Python script called "cgen.py".
-
-Each definition must be contained on one line:
-
-<returntype> <name> <type> <arg> <type> <arg>
-
-<returntype> can be: void, short, long (XXX maybe others?)
-
-<type> can be: char, string, short, float, long, or double
-	string indicates a null terminated string;
-	if <type> is char and <arg> begins with a *, the * is stripped
-	and <type> is changed into string
-
-<arg> has the form <mode> or <mode>[<subscript>]
-	where <mode> can be
-		s: arg is sent
-		r: arg is received		(arg is a pointer)
-	and <subscript> can be (N and I are numbers):
-		N
-		argI
-		retval
-		N*argI
-		N*I
-		N*retval
-	In the case where the subscript consists of two parts
-	separated by *, the first part is the width of the matrix, and
-	the second part is the length of the matrix.  This order is
-	opposite from the order used in C to declare a two-dimensional
-	matrix.
-*/
-
-/*
- * An attempt has been made to make this module switch threads on qread
- * calls. It is far from safe, though.
- */
-
-#include <gl.h>
-#include <device.h>
-
-#ifdef __sgi
-extern int devport();
-extern int textwritemask();
-extern int pagewritemask();
-extern int gewrite();
-extern int gettp();
-#endif
-
-#include "Python.h"
-#include "cgensupport.h"
-
-/*
-Some stubs are too complicated for the stub generator.
-We can include manually written versions of them here.
-A line starting with '%' gives the name of the function so the stub
-generator can include it in the table of functions.
-*/
-
-
-static PyObject *
-gl_qread(PyObject *self, PyObject *args)
-{
-	long retval;
-	short arg1 ;
-	Py_BEGIN_ALLOW_THREADS
-	retval = qread( & arg1 );
-	Py_END_ALLOW_THREADS
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewlongobject(retval));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg1));
-	  return v;
-	}
-}
-
-
-/*
-varray -- an array of v.. calls.
-The argument is an array (maybe list or tuple) of points.
-Each point must be a tuple or list of coordinates (x, y, z).
-The points may be 2- or 3-dimensional but must all have the
-same dimension.  Float and int values may be mixed however.
-The points are always converted to 3D double precision points
-by assuming z=0.0 if necessary (as indicated in the man page),
-and for each point v3d() is called.
-*/
-
-
-static PyObject *
-gl_varray(PyObject *self, PyObject *args)
-{
-	PyObject *v, *w=NULL;
-	int i, n, width;
-	double vec[3];
-	PyObject * (*getitem)(PyObject *, int);
-	
-	if (!PyArg_GetObject(args, 1, 0, &v))
-		return NULL;
-	
-	if (PyList_Check(v)) {
-		n = PyList_Size(v);
-		getitem = PyList_GetItem;
-	}
-	else if (PyTuple_Check(v)) {
-		n = PyTuple_Size(v);
-		getitem = PyTuple_GetItem;
-	}
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	
-	if (n == 0) {
-		Py_INCREF(Py_None);
-		return Py_None;
-	}
-	if (n > 0)
-		w = (*getitem)(v, 0);
-	
-	width = 0;
-	if (w == NULL) {
-	}
-	else if (PyList_Check(w)) {
-		width = PyList_Size(w);
-	}
-	else if (PyTuple_Check(w)) {
-		width = PyTuple_Size(w);
-	}
-	
-	switch (width) {
-	case 2:
-		vec[2] = 0.0;
-		/* Fall through */
-	case 3:
-		break;
-	default:
-		PyErr_BadArgument();
-		return NULL;
-	}
-	
-	for (i = 0; i < n; i++) {
-		w = (*getitem)(v, i);
-		if (!PyArg_GetDoubleArray(w, 1, 0, width, vec))
-			return NULL;
-		v3d(vec);
-	}
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/*
-vnarray, nvarray -- an array of n3f and v3f calls.
-The argument is an array (list or tuple) of pairs of points and normals.
-Each pair is a tuple (NOT a list) of a point and a normal for that point.
-Each point or normal must be a tuple (NOT a list) of coordinates (x, y, z).
-Three coordinates must be given.  Float and int values may be mixed.
-For each pair, n3f() is called for the normal, and then v3f() is called
-for the vector.
-
-vnarray and nvarray differ only in the order of the vector and normal in
-the pair: vnarray expects (v, n) while nvarray expects (n, v).
-*/
-
-static PyObject *gen_nvarray(); /* Forward */
-
-
-static PyObject *
-gl_nvarray(PyObject *self, PyObject *args)
-{
-	return gen_nvarray(args, 0);
-}
-
-
-static PyObject *
-gl_vnarray(PyObject *self, PyObject *args)
-{
-	return gen_nvarray(args, 1);
-}
-
-/* Generic, internal version of {nv,nv}array: inorm indicates the
-   argument order, 0: normal first, 1: vector first. */
-
-static PyObject *
-gen_nvarray(PyObject *args, int inorm)
-{
-	PyObject *v, *w, *wnorm, *wvec;
-	int i, n;
-	float norm[3], vec[3];
-	PyObject * (*getitem)(PyObject *, int);
-	
-	if (!PyArg_GetObject(args, 1, 0, &v))
-		return NULL;
-	
-	if (PyList_Check(v)) {
-		n = PyList_Size(v);
-		getitem = PyList_GetItem;
-	}
-	else if (PyTuple_Check(v)) {
-		n = PyTuple_Size(v);
-		getitem = PyTuple_GetItem;
-	}
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	
-	for (i = 0; i < n; i++) {
-		w = (*getitem)(v, i);
-		if (!PyTuple_Check(w) || PyTuple_Size(w) != 2) {
-			PyErr_BadArgument();
-			return NULL;
-		}
-		wnorm = PyTuple_GetItem(w, inorm);
-		wvec = PyTuple_GetItem(w, 1 - inorm);
-		if (!PyArg_GetFloatArray(wnorm, 1, 0, 3, norm) ||
-			!PyArg_GetFloatArray(wvec, 1, 0, 3, vec))
-			return NULL;
-		n3f(norm);
-		v3f(vec);
-	}
-	
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type).
-   The dimensions of ctl[] are computed as follows:
-   [len(s_knots) - s_order], [len(t_knots) - t_order]
-*/
-
-
-static PyObject *
-gl_nurbssurface(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	double * arg2 ;
-	long arg3 ;
-	double * arg4 ;
-	double *arg5 ;
-	long arg6 ;
-	long arg7 ;
-	long arg8 ;
-	long ncoords;
-	long s_byte_stride, t_byte_stride;
-	long s_nctl, t_nctl;
-	long s, t;
-	PyObject *v, *w, *pt;
-	double *pnext;
-	if (!PyArg_GetLongArraySize(args, 6, 0, &arg1))
-		return NULL;
-	if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	if (!PyArg_GetDoubleArray(args, 6, 0, arg1 , arg2))
-		return NULL;
-	if (!PyArg_GetLongArraySize(args, 6, 1, &arg3))
-		return NULL;
-	if ((arg4 = PyMem_NEW(double, arg3 )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	if (!PyArg_GetDoubleArray(args, 6, 1, arg3 , arg4))
-		return NULL;
-	if (!PyArg_GetLong(args, 6, 3, &arg6))
-		return NULL;
-	if (!PyArg_GetLong(args, 6, 4, &arg7))
-		return NULL;
-	if (!PyArg_GetLong(args, 6, 5, &arg8))
-		return NULL;
-	if (arg8 == N_XYZ)
-		ncoords = 3;
-	else if (arg8 == N_XYZW)
-		ncoords = 4;
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	s_nctl = arg1 - arg6;
-	t_nctl = arg3 - arg7;
-	if (!PyArg_GetObject(args, 6, 2, &v))
-		return NULL;
-	if (!PyList_Check(v) || PyList_Size(v) != s_nctl) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	if ((arg5 = PyMem_NEW(double, s_nctl*t_nctl*ncoords )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	pnext = arg5;
-	for (s = 0; s < s_nctl; s++) {
-		w = PyList_GetItem(v, s);
-		if (w == NULL || !PyList_Check(w) ||
-					PyList_Size(w) != t_nctl) {
-			PyErr_BadArgument();
-			return NULL;
-		}
-		for (t = 0; t < t_nctl; t++) {
-			pt = PyList_GetItem(w, t);
-			if (!PyArg_GetDoubleArray(pt, 1, 0, ncoords, pnext))
-				return NULL;
-			pnext += ncoords;
-		}
-	}
-	s_byte_stride = sizeof(double) * ncoords;
-	t_byte_stride = s_byte_stride * s_nctl;
-	nurbssurface( arg1 , arg2 , arg3 , arg4 ,
-		s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg4);
-	PyMem_DEL(arg5);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* nurbscurve(knots, ctlpoints, order, type).
-   The length of ctlpoints is len(knots)-order. */
-
-
-static PyObject *
-gl_nurbscurve(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	double * arg2 ;
-	long arg3 ;
-	double * arg4 ;
-	long arg5 ;
-	long arg6 ;
-	int ncoords, npoints;
-	int i;
-	PyObject *v;
-	double *pnext;
-	if (!PyArg_GetLongArraySize(args, 4, 0, &arg1))
-		return NULL;
-	if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	if (!PyArg_GetDoubleArray(args, 4, 0, arg1 , arg2))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 2, &arg5))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 3, &arg6))
-		return NULL;
-	if (arg6 == N_ST)
-		ncoords = 2;
-	else if (arg6 == N_STW)
-		ncoords = 3;
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	npoints = arg1 - arg5;
-	if (!PyArg_GetObject(args, 4, 1, &v))
-		return NULL;
-	if (!PyList_Check(v) || PyList_Size(v) != npoints) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	if ((arg4 = PyMem_NEW(double, npoints*ncoords )) == NULL) {
-		return PyErr_NoMemory();
-	}
-	pnext = arg4;
-	for (i = 0; i < npoints; i++) {
-		if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
-			return NULL;
-		pnext += ncoords;
-	}
-	arg3 = (sizeof(double)) * ncoords;
-	nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg4);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* pwlcurve(points, type).
-   Points is a list of points. Type must be N_ST. */
-
-
-static PyObject *
-gl_pwlcurve(PyObject *self, PyObject *args)
-{
-	PyObject *v;
-	long type;
-	double *data, *pnext;
-	long npoints, ncoords;
-	int i;
-	if (!PyArg_GetObject(args, 2, 0, &v))
-		return NULL;
-	if (!PyArg_GetLong(args, 2, 1, &type))
-		return NULL;
-	if (!PyList_Check(v)) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	npoints = PyList_Size(v);
-	if (type == N_ST)
-		ncoords = 2;
-	else {
-		PyErr_BadArgument();
-		return NULL;
-	}
-	if ((data = PyMem_NEW(double, npoints*ncoords)) == NULL) {
-		return PyErr_NoMemory();
-	}
-	pnext = data;
-	for (i = 0; i < npoints; i++) {
-		if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
-			return NULL;
-		pnext += ncoords;
-	}
-	pwlcurve(npoints, data, sizeof(double)*ncoords, type);
-	PyMem_DEL(data);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-/* Picking and Selecting */
-
-static short *pickbuffer = NULL;
-static long pickbuffersize;
-
-static PyObject *
-pick_select(PyObject *args, void (*func)())
-{
-	if (!PyArg_GetLong(args, 1, 0, &pickbuffersize))
-		return NULL;
-	if (pickbuffer != NULL) {
-		PyErr_SetString(PyExc_RuntimeError,
-			"pick/gselect: already picking/selecting");
-		return NULL;
-	}
-	if ((pickbuffer = PyMem_NEW(short, pickbuffersize)) == NULL) {
-		return PyErr_NoMemory();
-	}
-	(*func)(pickbuffer, pickbuffersize);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-endpick_select(long (*func)())
-{
-	PyObject *v, *w;
-	int i, nhits, n;
-	if (pickbuffer == NULL) {
-		PyErr_SetString(PyExc_RuntimeError,
-			"endpick/endselect: not in pick/select mode");
-		return NULL;
-	}
-	nhits = (*func)(pickbuffer);
-	if (nhits < 0) {
-		nhits = -nhits; /* How to report buffer overflow otherwise? */
-	}
-	/* Scan the buffer to see how many integers */
-	n = 0;
-	for (; nhits > 0; nhits--) {
-		n += 1 + pickbuffer[n];
-	}
-	v = PyList_New(n);
-	if (v == NULL)
-		return NULL;
-	/* XXX Could do it nicer and interpret the data structure here,
-	   returning a list of lists. But this can be done in Python... */
-	for (i = 0; i < n; i++) {
-		w = PyInt_FromLong((long)pickbuffer[i]);
-		if (w == NULL) {
-			Py_DECREF(v);
-			return NULL;
-		}
-		PyList_SetItem(v, i, w);
-	}
-	PyMem_DEL(pickbuffer);
-	pickbuffer = NULL;
-	return v;
-}
-
-extern void pick(), gselect();
-extern long endpick(), endselect();
-
-static PyObject *gl_pick(PyObject *self, PyObject *args)
-{
-	return pick_select(args, pick);
-}
-
-static PyObject *gl_endpick(PyObject *self)
-{
-	return endpick_select(endpick);
-}
-
-static PyObject *gl_gselect(PyObject *self, PyObject *args)
-{
-	return pick_select(args, gselect);
-}
-
-static PyObject *gl_endselect(PyObject *self)
-{
-	return endpick_select(endselect);
-}
-
-
-/* XXX The generator botches this one.  Here's a quick hack to fix it. */
-
-/* XXX The generator botches this one.  Here's a quick hack to fix it. */
-
-
-static PyObject *
-gl_getmatrix(PyObject *self, PyObject *args)
-{
-	Matrix arg1;
-	PyObject *v, *w;
-	int i, j;
-	getmatrix( arg1 );
-	v = PyList_New(16);
-	if (v == NULL) {
-		return PyErr_NoMemory();
-	}
-	for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
-		w = mknewfloatobject(arg1[i][j]);
-		if (w == NULL) {
-			Py_DECREF(v);
-			return NULL;
-		}
-		PyList_SetItem(v, i*4+j, w);
-	}
-	return v;
-}
-
-/* Here's an alternate version that returns a 4x4 matrix instead of
-   a vector.  Unfortunately it is incompatible with loadmatrix and
-   multmatrix... */
-
-
-static PyObject *
-gl_altgetmatrix(PyObject *self, PyObject *args)
-{
-	Matrix arg1;
-	PyObject *v, *w;
-	int i, j;
-	getmatrix( arg1 );
-	v = PyList_New(4);
-	if (v == NULL) {
-		return NULL;
-	}
-	for (i = 0; i < 4; i++) {
-		w = PyList_New(4);
-		if (w == NULL) {
-			Py_DECREF(v);
-			return NULL;
-		}
-		PyList_SetItem(v, i, w);
-	}
-	for (i = 0; i < 4; i++) {
-		for (j = 0; j < 4; j++) {
-			w = mknewfloatobject(arg1[i][j]);
-			if (w == NULL) {
-				Py_DECREF(v);
-				return NULL;
-			}
-			PyList_SetItem(PyList_GetItem(v, i), j, w);
-		}
-	}
-	return v;
-}
-
-
-static PyObject *
-gl_lrectwrite(PyObject *self, PyObject *args)
-{
-	short x1 ;
-	short y1 ;
-	short x2 ;
-	short y2 ;
-	string parray ;
-	PyObject *s;
-#if 0
-	int pixcount;
-#endif
-	if (!PyArg_GetShort(args, 5, 0, &x1))
-		return NULL;
-	if (!PyArg_GetShort(args, 5, 1, &y1))
-		return NULL;
-	if (!PyArg_GetShort(args, 5, 2, &x2))
-		return NULL;
-	if (!PyArg_GetShort(args, 5, 3, &y2))
-		return NULL;
-	if (!PyArg_GetString(args, 5, 4, &parray))
-		return NULL;
-	if (!PyArg_GetObject(args, 5, 4, &s))
-		return NULL;
-#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)) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "string arg to lrectwrite has wrong size");
-		return NULL;
-	}
-#endif
-	lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-static PyObject *
-gl_lrectread(PyObject *self, PyObject *args)
-{
-	short x1 ;
-	short y1 ;
-	short x2 ;
-	short y2 ;
-	PyObject *parray;
-	int pixcount;
-	if (!PyArg_GetShort(args, 4, 0, &x1))
-		return NULL;
-	if (!PyArg_GetShort(args, 4, 1, &y1))
-		return NULL;
-	if (!PyArg_GetShort(args, 4, 2, &x2))
-		return NULL;
-	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));
-	if (parray == NULL)
-		return NULL; /* No memory */
-	lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
-	return parray;
-}
-
-
-static PyObject *
-gl_readdisplay(PyObject *self, PyObject *args)
-{
-        short x1, y1, x2, y2;
-	unsigned long *parray, hints;
-	long size, size_ret;
-	PyObject *rv;
-
-	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));
-	if ( rv == NULL )
-	  return NULL;
-	parray = (unsigned long *)PyString_AsString(rv);
-	size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
-	if ( size_ret != size ) {
-	    printf("gl_readdisplay: got %ld pixels, expected %ld\n",
-		   size_ret, size);
-	    PyErr_SetString(PyExc_RuntimeError, "readdisplay returned unexpected length");
-	    return NULL;
-	}
-	return rv;
-}
-
-/* Desperately needed, here are tools to compress and decompress
-   the data manipulated by lrectread/lrectwrite.
-
-   gl.packrect(width, height, packfactor, bigdata) --> smalldata
-		makes 'bigdata' 4*(packfactor**2) times smaller by:
-		- turning it into B/W (a factor 4)
-		- replacing squares of size pacfactor by one
-		  representative
-
-   gl.unpackrect(width, height, packfactor, smalldata) --> bigdata
-		is the inverse; the numeric arguments must be *the same*.
-
-   Both work best if width and height are multiples of packfactor
-   (in fact unpackrect will leave garbage bytes).
-*/
-
-
-static PyObject *
-gl_packrect(PyObject *self, PyObject *args)
-{
-	long width, height, packfactor;
-	char *s;
-	PyObject *unpacked, *packed;
-	int pixcount, packedcount, x, y, r, g, b;
-	unsigned long pixel;
-	unsigned char *p;
-	unsigned long *parray;
-	if (!PyArg_GetLong(args, 4, 0, &width))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 1, &height))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 2, &packfactor))
-		return NULL;
-	if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
-		return NULL;
-	if (!PyArg_GetObject(args, 4, 3, &unpacked))
-		return NULL;
-	if (width <= 0 || height <= 0 || packfactor <= 0) {
-		PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
-		return NULL;
-	}
-	pixcount = width*height;
-	packedcount = ((width+packfactor-1)/packfactor) *
-		((height+packfactor-1)/packfactor);
-	if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "string arg to packrect has wrong size");
-		return NULL;
-	}
-	packed = PyString_FromStringAndSize((char *)NULL, packedcount);
-	if (packed == NULL)
-		return NULL;
-	parray = (unsigned long *) PyString_AsString(unpacked);
-	p = (unsigned char *) PyString_AsString(packed);
-	for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
-		for (x = 0; x < width; x += packfactor) {
-			pixel = parray[x];
-			r = pixel & 0xff;
-			g = (pixel >> 8) & 0xff;
-			b = (pixel >> 16) & 0xff;
-			*p++ = (30*r+59*g+11*b) / 100;
-		}
-	}
-	return packed;
-}
-
-
-static unsigned long unpacktab[256];
-static int unpacktab_inited = 0;
-
-static PyObject *
-gl_unpackrect(PyObject *self, PyObject *args)
-{
-	long width, height, packfactor;
-	char *s;
-	PyObject *unpacked, *packed;
-	int pixcount, packedcount;
-	register unsigned char *p;
-	register unsigned long *parray;
-	if (!unpacktab_inited) {
-		register int white;
-		for (white = 256; --white >= 0; )
-			unpacktab[white] = white * 0x010101L;
-		unpacktab_inited++;
-	}
-	if (!PyArg_GetLong(args, 4, 0, &width))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 1, &height))
-		return NULL;
-	if (!PyArg_GetLong(args, 4, 2, &packfactor))
-		return NULL;
-	if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
-		return NULL;
-	if (!PyArg_GetObject(args, 4, 3, &packed))
-		return NULL;
-	if (width <= 0 || height <= 0 || packfactor <= 0) {
-		PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
-		return NULL;
-	}
-	pixcount = width*height;
-	packedcount = ((width+packfactor-1)/packfactor) *
-		((height+packfactor-1)/packfactor);
-	if (PyString_Size(packed) != packedcount) {
-		PyErr_SetString(PyExc_RuntimeError,
-			   "string arg to unpackrect has wrong size");
-		return NULL;
-	}
-	unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
-	if (unpacked == NULL)
-		return NULL;
-	parray = (unsigned long *) PyString_AsString(unpacked);
-	p = (unsigned char *) PyString_AsString(packed);
-	if (packfactor == 1 && width*height > 0) {
-		/* Just expand bytes to longs */
-		register int x = width * height;
-		do {
-			*parray++ = unpacktab[*p++];
-		} while (--x >= 0);
-	}
-	else {
-		register int y;
-		for (y = 0; y < height-packfactor+1;
-		     y += packfactor, parray += packfactor*width) {
-			register int x;
-			for (x = 0; x < width-packfactor+1; x += packfactor) {
-				register unsigned long pixel = unpacktab[*p++];
-				register int i;
-				for (i = packfactor*width; (i-=width) >= 0;) {
-					register int j;
-					for (j = packfactor; --j >= 0; )
-						parray[i+x+j] = pixel;
-				}
-			}
-		}
-	}
-	return unpacked;
-}
-
-static PyObject *
-gl_gversion(PyObject *self, PyObject *args)
-{
-	char buf[20];
-	gversion(buf);
-	return PyString_FromString(buf);
-}
-
-
-/* void clear - Manual because of clash with termcap */
-static PyObject *
-gl_clear(PyObject *self, PyObject *args)
-{
-	__GLclear( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* End of manually written stubs */
-
-
-/* long getshade */
-
-static PyObject *
-gl_getshade(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getshade( );
-	return mknewlongobject(retval);
-}
-
-/* void devport short s long s */
-
-static PyObject *
-gl_devport(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	long arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	devport( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rdr2i long s long s */
-
-static PyObject *
-gl_rdr2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	rdr2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rectfs short s short s short s short s */
-
-static PyObject *
-gl_rectfs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	rectfs( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rects short s short s short s short s */
-
-static PyObject *
-gl_rects(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	rects( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rmv2i long s long s */
-
-static PyObject *
-gl_rmv2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	rmv2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void noport */
-
-static PyObject *
-gl_noport(PyObject *self, PyObject *args)
-{
-	noport( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void popviewport */
-
-static PyObject *
-gl_popviewport(PyObject *self, PyObject *args)
-{
-	popviewport( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void clearhitcode */
-
-static PyObject *
-gl_clearhitcode(PyObject *self, PyObject *args)
-{
-	clearhitcode( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void closeobj */
-
-static PyObject *
-gl_closeobj(PyObject *self, PyObject *args)
-{
-	closeobj( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cursoff */
-
-static PyObject *
-gl_cursoff(PyObject *self, PyObject *args)
-{
-	cursoff( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void curson */
-
-static PyObject *
-gl_curson(PyObject *self, PyObject *args)
-{
-	curson( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void doublebuffer */
-
-static PyObject *
-gl_doublebuffer(PyObject *self, PyObject *args)
-{
-	doublebuffer( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void finish */
-
-static PyObject *
-gl_finish(PyObject *self, PyObject *args)
-{
-	finish( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gconfig */
-
-static PyObject *
-gl_gconfig(PyObject *self, PyObject *args)
-{
-	gconfig( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void ginit */
-
-static PyObject *
-gl_ginit(PyObject *self, PyObject *args)
-{
-	ginit( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void greset */
-
-static PyObject *
-gl_greset(PyObject *self, PyObject *args)
-{
-	greset( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void multimap */
-
-static PyObject *
-gl_multimap(PyObject *self, PyObject *args)
-{
-	multimap( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void onemap */
-
-static PyObject *
-gl_onemap(PyObject *self, PyObject *args)
-{
-	onemap( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void popattributes */
-
-static PyObject *
-gl_popattributes(PyObject *self, PyObject *args)
-{
-	popattributes( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void popmatrix */
-
-static PyObject *
-gl_popmatrix(PyObject *self, PyObject *args)
-{
-	popmatrix( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pushattributes */
-
-static PyObject *
-gl_pushattributes(PyObject *self, PyObject *args)
-{
-	pushattributes( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pushmatrix */
-
-static PyObject *
-gl_pushmatrix(PyObject *self, PyObject *args)
-{
-	pushmatrix( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pushviewport */
-
-static PyObject *
-gl_pushviewport(PyObject *self, PyObject *args)
-{
-	pushviewport( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void qreset */
-
-static PyObject *
-gl_qreset(PyObject *self, PyObject *args)
-{
-	qreset( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void RGBmode */
-
-static PyObject *
-gl_RGBmode(PyObject *self, PyObject *args)
-{
-	RGBmode( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void singlebuffer */
-
-static PyObject *
-gl_singlebuffer(PyObject *self, PyObject *args)
-{
-	singlebuffer( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void swapbuffers */
-
-static PyObject *
-gl_swapbuffers(PyObject *self, PyObject *args)
-{
-	swapbuffers( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gsync */
-
-static PyObject *
-gl_gsync(PyObject *self, PyObject *args)
-{
-	gsync( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gflush */
-
-static PyObject *
-gl_gflush(PyObject *self, PyObject *args)
-{
-	gflush( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void tpon */
-
-static PyObject *
-gl_tpon(PyObject *self, PyObject *args)
-{
-	tpon( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void tpoff */
-
-static PyObject *
-gl_tpoff(PyObject *self, PyObject *args)
-{
-	tpoff( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void clkon */
-
-static PyObject *
-gl_clkon(PyObject *self, PyObject *args)
-{
-	clkon( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void clkoff */
-
-static PyObject *
-gl_clkoff(PyObject *self, PyObject *args)
-{
-	clkoff( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void ringbell */
-
-static PyObject *
-gl_ringbell(PyObject *self, PyObject *args)
-{
-	ringbell( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gbegin */
-
-static PyObject *
-gl_gbegin(PyObject *self, PyObject *args)
-{
-	gbegin( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void textinit */
-
-static PyObject *
-gl_textinit(PyObject *self, PyObject *args)
-{
-	textinit( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void initnames */
-
-static PyObject *
-gl_initnames(PyObject *self, PyObject *args)
-{
-	initnames( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pclos */
-
-static PyObject *
-gl_pclos(PyObject *self, PyObject *args)
-{
-	pclos( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void popname */
-
-static PyObject *
-gl_popname(PyObject *self, PyObject *args)
-{
-	popname( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void spclos */
-
-static PyObject *
-gl_spclos(PyObject *self, PyObject *args)
-{
-	spclos( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void zclear */
-
-static PyObject *
-gl_zclear(PyObject *self, PyObject *args)
-{
-	zclear( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void screenspace */
-
-static PyObject *
-gl_screenspace(PyObject *self, PyObject *args)
-{
-	screenspace( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void reshapeviewport */
-
-static PyObject *
-gl_reshapeviewport(PyObject *self, PyObject *args)
-{
-	reshapeviewport( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void winpush */
-
-static PyObject *
-gl_winpush(PyObject *self, PyObject *args)
-{
-	winpush( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void winpop */
-
-static PyObject *
-gl_winpop(PyObject *self, PyObject *args)
-{
-	winpop( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void foreground */
-
-static PyObject *
-gl_foreground(PyObject *self, PyObject *args)
-{
-	foreground( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endfullscrn */
-
-static PyObject *
-gl_endfullscrn(PyObject *self, PyObject *args)
-{
-	endfullscrn( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endpupmode */
-
-static PyObject *
-gl_endpupmode(PyObject *self, PyObject *args)
-{
-	endpupmode( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void fullscrn */
-
-static PyObject *
-gl_fullscrn(PyObject *self, PyObject *args)
-{
-	fullscrn( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pupmode */
-
-static PyObject *
-gl_pupmode(PyObject *self, PyObject *args)
-{
-	pupmode( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void winconstraints */
-
-static PyObject *
-gl_winconstraints(PyObject *self, PyObject *args)
-{
-	winconstraints( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pagecolor short s */
-
-static PyObject *
-gl_pagecolor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	pagecolor( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void textcolor short s */
-
-static PyObject *
-gl_textcolor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	textcolor( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void color short s */
-
-static PyObject *
-gl_color(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	color( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void curveit short s */
-
-static PyObject *
-gl_curveit(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	curveit( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void font short s */
-
-static PyObject *
-gl_font(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	font( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void linewidth short s */
-
-static PyObject *
-gl_linewidth(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	linewidth( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setlinestyle short s */
-
-static PyObject *
-gl_setlinestyle(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	setlinestyle( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setmap short s */
-
-static PyObject *
-gl_setmap(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	setmap( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void swapinterval short s */
-
-static PyObject *
-gl_swapinterval(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	swapinterval( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void writemask short s */
-
-static PyObject *
-gl_writemask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	writemask( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void textwritemask short s */
-
-static PyObject *
-gl_textwritemask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	textwritemask( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void qdevice short s */
-
-static PyObject *
-gl_qdevice(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	qdevice( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void unqdevice short s */
-
-static PyObject *
-gl_unqdevice(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	unqdevice( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void curvebasis short s */
-
-static PyObject *
-gl_curvebasis(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	curvebasis( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void curveprecision short s */
-
-static PyObject *
-gl_curveprecision(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	curveprecision( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void loadname short s */
-
-static PyObject *
-gl_loadname(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	loadname( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void passthrough short s */
-
-static PyObject *
-gl_passthrough(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	passthrough( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pushname short s */
-
-static PyObject *
-gl_pushname(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	pushname( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setmonitor short s */
-
-static PyObject *
-gl_setmonitor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	setmonitor( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setshade short s */
-
-static PyObject *
-gl_setshade(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	setshade( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setpattern short s */
-
-static PyObject *
-gl_setpattern(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	setpattern( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pagewritemask short s */
-
-static PyObject *
-gl_pagewritemask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	pagewritemask( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void callobj long s */
-
-static PyObject *
-gl_callobj(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	callobj( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void delobj long s */
-
-static PyObject *
-gl_delobj(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	delobj( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void editobj long s */
-
-static PyObject *
-gl_editobj(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	editobj( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void makeobj long s */
-
-static PyObject *
-gl_makeobj(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	makeobj( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void maketag long s */
-
-static PyObject *
-gl_maketag(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	maketag( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void chunksize long s */
-
-static PyObject *
-gl_chunksize(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	chunksize( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void compactify long s */
-
-static PyObject *
-gl_compactify(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	compactify( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void deltag long s */
-
-static PyObject *
-gl_deltag(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	deltag( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lsrepeat long s */
-
-static PyObject *
-gl_lsrepeat(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	lsrepeat( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void objinsert long s */
-
-static PyObject *
-gl_objinsert(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	objinsert( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void objreplace long s */
-
-static PyObject *
-gl_objreplace(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	objreplace( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void winclose long s */
-
-static PyObject *
-gl_winclose(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	winclose( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void blanktime long s */
-
-static PyObject *
-gl_blanktime(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	blanktime( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void freepup long s */
-
-static PyObject *
-gl_freepup(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	freepup( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void backbuffer long s */
-
-static PyObject *
-gl_backbuffer(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	backbuffer( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void frontbuffer long s */
-
-static PyObject *
-gl_frontbuffer(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	frontbuffer( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lsbackup long s */
-
-static PyObject *
-gl_lsbackup(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	lsbackup( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void resetls long s */
-
-static PyObject *
-gl_resetls(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	resetls( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lampon long s */
-
-static PyObject *
-gl_lampon(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	lampon( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lampoff long s */
-
-static PyObject *
-gl_lampoff(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	lampoff( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setbell long s */
-
-static PyObject *
-gl_setbell(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	setbell( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void blankscreen long s */
-
-static PyObject *
-gl_blankscreen(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	blankscreen( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void depthcue long s */
-
-static PyObject *
-gl_depthcue(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	depthcue( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void zbuffer long s */
-
-static PyObject *
-gl_zbuffer(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	zbuffer( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void backface long s */
-
-static PyObject *
-gl_backface(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	backface( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cmov2i long s long s */
-
-static PyObject *
-gl_cmov2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	cmov2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void draw2i long s long s */
-
-static PyObject *
-gl_draw2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	draw2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void move2i long s long s */
-
-static PyObject *
-gl_move2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	move2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pnt2i long s long s */
-
-static PyObject *
-gl_pnt2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	pnt2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void patchbasis long s long s */
-
-static PyObject *
-gl_patchbasis(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	patchbasis( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void patchprecision long s long s */
-
-static PyObject *
-gl_patchprecision(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	patchprecision( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pdr2i long s long s */
-
-static PyObject *
-gl_pdr2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	pdr2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pmv2i long s long s */
-
-static PyObject *
-gl_pmv2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	pmv2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpdr2i long s long s */
-
-static PyObject *
-gl_rpdr2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	rpdr2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpmv2i long s long s */
-
-static PyObject *
-gl_rpmv2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	rpmv2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt2i long s long s */
-
-static PyObject *
-gl_xfpt2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	xfpt2i( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void objdelete long s long s */
-
-static PyObject *
-gl_objdelete(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	objdelete( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void patchcurves long s long s */
-
-static PyObject *
-gl_patchcurves(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	patchcurves( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void minsize long s long s */
-
-static PyObject *
-gl_minsize(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	minsize( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void maxsize long s long s */
-
-static PyObject *
-gl_maxsize(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	maxsize( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void keepaspect long s long s */
-
-static PyObject *
-gl_keepaspect(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	keepaspect( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void prefsize long s long s */
-
-static PyObject *
-gl_prefsize(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	prefsize( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void stepunit long s long s */
-
-static PyObject *
-gl_stepunit(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	stepunit( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void fudge long s long s */
-
-static PyObject *
-gl_fudge(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	fudge( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void winmove long s long s */
-
-static PyObject *
-gl_winmove(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	winmove( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void attachcursor short s short s */
-
-static PyObject *
-gl_attachcursor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	attachcursor( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void deflinestyle short s short s */
-
-static PyObject *
-gl_deflinestyle(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	deflinestyle( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void noise short s short s */
-
-static PyObject *
-gl_noise(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	noise( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void picksize short s short s */
-
-static PyObject *
-gl_picksize(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	picksize( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void qenter short s short s */
-
-static PyObject *
-gl_qenter(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	qenter( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setdepth short s short s */
-
-static PyObject *
-gl_setdepth(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	setdepth( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cmov2s short s short s */
-
-static PyObject *
-gl_cmov2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	cmov2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void draw2s short s short s */
-
-static PyObject *
-gl_draw2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	draw2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void move2s short s short s */
-
-static PyObject *
-gl_move2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	move2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pdr2s short s short s */
-
-static PyObject *
-gl_pdr2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	pdr2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pmv2s short s short s */
-
-static PyObject *
-gl_pmv2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	pmv2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pnt2s short s short s */
-
-static PyObject *
-gl_pnt2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	pnt2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rdr2s short s short s */
-
-static PyObject *
-gl_rdr2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	rdr2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rmv2s short s short s */
-
-static PyObject *
-gl_rmv2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	rmv2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpdr2s short s short s */
-
-static PyObject *
-gl_rpdr2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	rpdr2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpmv2s short s short s */
-
-static PyObject *
-gl_rpmv2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	rpmv2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt2s short s short s */
-
-static PyObject *
-gl_xfpt2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	xfpt2s( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cmov2 float s float s */
-
-static PyObject *
-gl_cmov2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	cmov2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void draw2 float s float s */
-
-static PyObject *
-gl_draw2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	draw2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void move2 float s float s */
-
-static PyObject *
-gl_move2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	move2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pnt2 float s float s */
-
-static PyObject *
-gl_pnt2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	pnt2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pdr2 float s float s */
-
-static PyObject *
-gl_pdr2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	pdr2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pmv2 float s float s */
-
-static PyObject *
-gl_pmv2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	pmv2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rdr2 float s float s */
-
-static PyObject *
-gl_rdr2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	rdr2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rmv2 float s float s */
-
-static PyObject *
-gl_rmv2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	rmv2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpdr2 float s float s */
-
-static PyObject *
-gl_rpdr2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	rpdr2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpmv2 float s float s */
-
-static PyObject *
-gl_rpmv2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	rpmv2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt2 float s float s */
-
-static PyObject *
-gl_xfpt2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	xfpt2( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void loadmatrix float s[4*4] */
-
-static PyObject *
-gl_loadmatrix(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] [ 4 ] ;
-	if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
-		return NULL;
-	loadmatrix( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void multmatrix float s[4*4] */
-
-static PyObject *
-gl_multmatrix(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] [ 4 ] ;
-	if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
-		return NULL;
-	multmatrix( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void crv float s[3*4] */
-
-static PyObject *
-gl_crv(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] [ 3 ] ;
-	if (!getifloatarray(args, 1, 0, 3 * 4 , (float *) arg1))
-		return NULL;
-	crv( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rcrv float s[4*4] */
-
-static PyObject *
-gl_rcrv(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] [ 4 ] ;
-	if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
-		return NULL;
-	rcrv( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void addtopup long s char *s long s */
-
-static PyObject *
-gl_addtopup(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	string arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getistringarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	addtopup( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void charstr char *s */
-
-static PyObject *
-gl_charstr(PyObject *self, PyObject *args)
-{
-	string arg1 ;
-	if (!getistringarg(args, 1, 0, &arg1))
-		return NULL;
-	charstr( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void getport char *s */
-
-static PyObject *
-gl_getport(PyObject *self, PyObject *args)
-{
-	string arg1 ;
-	if (!getistringarg(args, 1, 0, &arg1))
-		return NULL;
-	getport( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long strwidth char *s */
-
-static PyObject *
-gl_strwidth(PyObject *self, PyObject *args)
-{
-	long retval;
-	string arg1 ;
-	if (!getistringarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = strwidth( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* long winopen char *s */
-
-static PyObject *
-gl_winopen(PyObject *self, PyObject *args)
-{
-	long retval;
-	string arg1 ;
-	if (!getistringarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = winopen( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void wintitle char *s */
-
-static PyObject *
-gl_wintitle(PyObject *self, PyObject *args)
-{
-	string arg1 ;
-	if (!getistringarg(args, 1, 0, &arg1))
-		return NULL;
-	wintitle( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polf long s float s[3*arg1] */
-
-static PyObject *
-gl_polf(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
-		return NULL;
-	polf( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polf2 long s float s[2*arg1] */
-
-static PyObject *
-gl_polf2(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 2 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
-		return NULL;
-	polf2( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void poly long s float s[3*arg1] */
-
-static PyObject *
-gl_poly(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
-		return NULL;
-	poly( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void poly2 long s float s[2*arg1] */
-
-static PyObject *
-gl_poly2(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 2 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
-		return NULL;
-	poly2( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void crvn long s float s[3*arg1] */
-
-static PyObject *
-gl_crvn(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
-		return NULL;
-	crvn( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rcrvn long s float s[4*arg1] */
-
-static PyObject *
-gl_rcrvn(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 4 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 4;
-	if ((arg2 = (float(*)[4]) PyMem_NEW(float , 4 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 1, 0, 4 * arg1 , (float *) arg2))
-		return NULL;
-	rcrvn( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polf2i long s long s[2*arg1] */
-
-static PyObject *
-gl_polf2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long (* arg2) [ 2 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
-		return NULL;
-	polf2i( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polfi long s long s[3*arg1] */
-
-static PyObject *
-gl_polfi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
-		return NULL;
-	polfi( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void poly2i long s long s[2*arg1] */
-
-static PyObject *
-gl_poly2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long (* arg2) [ 2 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
-		return NULL;
-	poly2i( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polyi long s long s[3*arg1] */
-
-static PyObject *
-gl_polyi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
-		return NULL;
-	polyi( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polf2s long s short s[2*arg1] */
-
-static PyObject *
-gl_polf2s(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short (* arg2) [ 2 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
-		return NULL;
-	polf2s( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polfs long s short s[3*arg1] */
-
-static PyObject *
-gl_polfs(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
-		return NULL;
-	polfs( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polys long s short s[3*arg1] */
-
-static PyObject *
-gl_polys(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short (* arg2) [ 3 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
-		return NULL;
-	polys( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void poly2s long s short s[2*arg1] */
-
-static PyObject *
-gl_poly2s(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short (* arg2) [ 2 ] ;
-	if (!getilongarraysize(args, 1, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
-		return NULL;
-	poly2s( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void defcursor short s u_short s[128] */
-
-static PyObject *
-gl_defcursor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	unsigned short arg2 [ 128 ] ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarray(args, 2, 1, 128 , (short *) arg2))
-		return NULL;
-	defcursor( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void writepixels short s u_short s[arg1] */
-
-static PyObject *
-gl_writepixels(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	unsigned short * arg2 ;
-	if (!getishortarraysize(args, 1, 0, &arg1))
-		return NULL;
-	if ((arg2 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 1, 0, arg1 , (short *) arg2))
-		return NULL;
-	writepixels( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void defbasis long s float s[4*4] */
-
-static PyObject *
-gl_defbasis(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float arg2 [ 4 ] [ 4 ] ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarray(args, 2, 1, 4 * 4 , (float *) arg2))
-		return NULL;
-	defbasis( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gewrite short s short s[arg1] */
-
-static PyObject *
-gl_gewrite(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short * arg2 ;
-	if (!getishortarraysize(args, 1, 0, &arg1))
-		return NULL;
-	if ((arg2 = PyMem_NEW(short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 1, 0, arg1 , arg2))
-		return NULL;
-	gewrite( arg1 , arg2 );
-	PyMem_DEL(arg2);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rotate short s char s */
-
-static PyObject *
-gl_rotate(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	char arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getichararg(args, 2, 1, &arg2))
-		return NULL;
-	rotate( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rot float s char s */
-
-static PyObject *
-gl_rot(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	char arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getichararg(args, 2, 1, &arg2))
-		return NULL;
-	rot( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void circfi long s long s long s */
-
-static PyObject *
-gl_circfi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	circfi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void circi long s long s long s */
-
-static PyObject *
-gl_circi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	circi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cmovi long s long s long s */
-
-static PyObject *
-gl_cmovi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	cmovi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void drawi long s long s long s */
-
-static PyObject *
-gl_drawi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	drawi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void movei long s long s long s */
-
-static PyObject *
-gl_movei(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	movei( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pnti long s long s long s */
-
-static PyObject *
-gl_pnti(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	pnti( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void newtag long s long s long s */
-
-static PyObject *
-gl_newtag(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	newtag( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pdri long s long s long s */
-
-static PyObject *
-gl_pdri(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	pdri( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pmvi long s long s long s */
-
-static PyObject *
-gl_pmvi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	pmvi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rdri long s long s long s */
-
-static PyObject *
-gl_rdri(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	rdri( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rmvi long s long s long s */
-
-static PyObject *
-gl_rmvi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	rmvi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpdri long s long s long s */
-
-static PyObject *
-gl_rpdri(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	rpdri( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpmvi long s long s long s */
-
-static PyObject *
-gl_rpmvi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	rpmvi( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpti long s long s long s */
-
-static PyObject *
-gl_xfpti(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	xfpti( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void circ float s float s float s */
-
-static PyObject *
-gl_circ(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	circ( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void circf float s float s float s */
-
-static PyObject *
-gl_circf(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	circf( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cmov float s float s float s */
-
-static PyObject *
-gl_cmov(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	cmov( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void draw float s float s float s */
-
-static PyObject *
-gl_draw(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	draw( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void move float s float s float s */
-
-static PyObject *
-gl_move(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	move( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pnt float s float s float s */
-
-static PyObject *
-gl_pnt(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	pnt( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void scale float s float s float s */
-
-static PyObject *
-gl_scale(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	scale( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void translate float s float s float s */
-
-static PyObject *
-gl_translate(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	translate( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pdr float s float s float s */
-
-static PyObject *
-gl_pdr(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	pdr( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pmv float s float s float s */
-
-static PyObject *
-gl_pmv(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	pmv( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rdr float s float s float s */
-
-static PyObject *
-gl_rdr(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	rdr( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rmv float s float s float s */
-
-static PyObject *
-gl_rmv(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	rmv( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpdr float s float s float s */
-
-static PyObject *
-gl_rpdr(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	rpdr( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpmv float s float s float s */
-
-static PyObject *
-gl_rpmv(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	rpmv( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt float s float s float s */
-
-static PyObject *
-gl_xfpt(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	if (!getifloatarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 3, 2, &arg3))
-		return NULL;
-	xfpt( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void RGBcolor short s short s short s */
-
-static PyObject *
-gl_RGBcolor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	RGBcolor( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void RGBwritemask short s short s short s */
-
-static PyObject *
-gl_RGBwritemask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	RGBwritemask( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setcursor short s short s short s */
-
-static PyObject *
-gl_setcursor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	setcursor( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void tie short s short s short s */
-
-static PyObject *
-gl_tie(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	tie( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void circfs short s short s short s */
-
-static PyObject *
-gl_circfs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	circfs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void circs short s short s short s */
-
-static PyObject *
-gl_circs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	circs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cmovs short s short s short s */
-
-static PyObject *
-gl_cmovs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	cmovs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void draws short s short s short s */
-
-static PyObject *
-gl_draws(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	draws( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void moves short s short s short s */
-
-static PyObject *
-gl_moves(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	moves( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pdrs short s short s short s */
-
-static PyObject *
-gl_pdrs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	pdrs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pmvs short s short s short s */
-
-static PyObject *
-gl_pmvs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	pmvs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pnts short s short s short s */
-
-static PyObject *
-gl_pnts(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	pnts( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rdrs short s short s short s */
-
-static PyObject *
-gl_rdrs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	rdrs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rmvs short s short s short s */
-
-static PyObject *
-gl_rmvs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	rmvs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpdrs short s short s short s */
-
-static PyObject *
-gl_rpdrs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	rpdrs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpmvs short s short s short s */
-
-static PyObject *
-gl_rpmvs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	rpmvs( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpts short s short s short s */
-
-static PyObject *
-gl_xfpts(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	xfpts( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void curorigin short s short s short s */
-
-static PyObject *
-gl_curorigin(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	curorigin( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cyclemap short s short s short s */
-
-static PyObject *
-gl_cyclemap(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	if (!getishortarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	cyclemap( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void patch float s[4*4] float s[4*4] float s[4*4] */
-
-static PyObject *
-gl_patch(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] [ 4 ] ;
-	float arg2 [ 4 ] [ 4 ] ;
-	float arg3 [ 4 ] [ 4 ] ;
-	if (!getifloatarray(args, 3, 0, 4 * 4 , (float *) arg1))
-		return NULL;
-	if (!getifloatarray(args, 3, 1, 4 * 4 , (float *) arg2))
-		return NULL;
-	if (!getifloatarray(args, 3, 2, 4 * 4 , (float *) arg3))
-		return NULL;
-	patch( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void splf long s float s[3*arg1] u_short s[arg1] */
-
-static PyObject *
-gl_splf(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 3 ] ;
-	unsigned short * arg3 ;
-	if (!getilongarraysize(args, 2, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 2, 0, 3 * arg1 , (float *) arg2))
-		return NULL;
-	if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
-		return NULL;
-	splf( arg1 , arg2 , arg3 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void splf2 long s float s[2*arg1] u_short s[arg1] */
-
-static PyObject *
-gl_splf2(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float (* arg2) [ 2 ] ;
-	unsigned short * arg3 ;
-	if (!getilongarraysize(args, 2, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 2, 0, 2 * arg1 , (float *) arg2))
-		return NULL;
-	if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
-		return NULL;
-	splf2( arg1 , arg2 , arg3 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void splfi long s long s[3*arg1] u_short s[arg1] */
-
-static PyObject *
-gl_splfi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long (* arg2) [ 3 ] ;
-	unsigned short * arg3 ;
-	if (!getilongarraysize(args, 2, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getilongarray(args, 2, 0, 3 * arg1 , (long *) arg2))
-		return NULL;
-	if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
-		return NULL;
-	splfi( arg1 , arg2 , arg3 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void splf2i long s long s[2*arg1] u_short s[arg1] */
-
-static PyObject *
-gl_splf2i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long (* arg2) [ 2 ] ;
-	unsigned short * arg3 ;
-	if (!getilongarraysize(args, 2, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getilongarray(args, 2, 0, 2 * arg1 , (long *) arg2))
-		return NULL;
-	if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
-		return NULL;
-	splf2i( arg1 , arg2 , arg3 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void splfs long s short s[3*arg1] u_short s[arg1] */
-
-static PyObject *
-gl_splfs(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short (* arg2) [ 3 ] ;
-	unsigned short * arg3 ;
-	if (!getilongarraysize(args, 2, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 3;
-	if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 0, 3 * arg1 , (short *) arg2))
-		return NULL;
-	if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
-		return NULL;
-	splfs( arg1 , arg2 , arg3 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void splf2s long s short s[2*arg1] u_short s[arg1] */
-
-static PyObject *
-gl_splf2s(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short (* arg2) [ 2 ] ;
-	unsigned short * arg3 ;
-	if (!getilongarraysize(args, 2, 0, &arg1))
-		return NULL;
-	arg1 = arg1 / 2;
-	if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 0, 2 * arg1 , (short *) arg2))
-		return NULL;
-	if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
-		return NULL;
-	splf2s( arg1 , arg2 , arg3 );
-	PyMem_DEL(arg2);
-	PyMem_DEL(arg3);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rpatch float s[4*4] float s[4*4] float s[4*4] float s[4*4] */
-
-static PyObject *
-gl_rpatch(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] [ 4 ] ;
-	float arg2 [ 4 ] [ 4 ] ;
-	float arg3 [ 4 ] [ 4 ] ;
-	float arg4 [ 4 ] [ 4 ] ;
-	if (!getifloatarray(args, 4, 0, 4 * 4 , (float *) arg1))
-		return NULL;
-	if (!getifloatarray(args, 4, 1, 4 * 4 , (float *) arg2))
-		return NULL;
-	if (!getifloatarray(args, 4, 2, 4 * 4 , (float *) arg3))
-		return NULL;
-	if (!getifloatarray(args, 4, 3, 4 * 4 , (float *) arg4))
-		return NULL;
-	rpatch( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void ortho2 float s float s float s float s */
-
-static PyObject *
-gl_ortho2(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	ortho2( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rect float s float s float s float s */
-
-static PyObject *
-gl_rect(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	rect( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rectf float s float s float s float s */
-
-static PyObject *
-gl_rectf(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	rectf( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt4 float s float s float s float s */
-
-static PyObject *
-gl_xfpt4(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	xfpt4( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void textport short s short s short s short s */
-
-static PyObject *
-gl_textport(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	textport( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void mapcolor short s short s short s short s */
-
-static PyObject *
-gl_mapcolor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	mapcolor( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void scrmask short s short s short s short s */
-
-static PyObject *
-gl_scrmask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	scrmask( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setvaluator short s short s short s short s */
-
-static PyObject *
-gl_setvaluator(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	setvaluator( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void viewport short s short s short s short s */
-
-static PyObject *
-gl_viewport(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	viewport( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void shaderange short s short s short s short s */
-
-static PyObject *
-gl_shaderange(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	shaderange( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt4s short s short s short s short s */
-
-static PyObject *
-gl_xfpt4s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	xfpt4s( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rectfi long s long s long s long s */
-
-static PyObject *
-gl_rectfi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	rectfi( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void recti long s long s long s long s */
-
-static PyObject *
-gl_recti(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	recti( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void xfpt4i long s long s long s long s */
-
-static PyObject *
-gl_xfpt4i(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	xfpt4i( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void prefposition long s long s long s long s */
-
-static PyObject *
-gl_prefposition(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	prefposition( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void arc float s float s float s short s short s */
-
-static PyObject *
-gl_arc(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getifloatarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	arc( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void arcf float s float s float s short s short s */
-
-static PyObject *
-gl_arcf(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getifloatarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	arcf( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void arcfi long s long s long s short s short s */
-
-static PyObject *
-gl_arcfi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getilongarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	arcfi( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void arci long s long s long s short s short s */
-
-static PyObject *
-gl_arci(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getilongarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	arci( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bbox2 short s short s float s float s float s float s */
-
-static PyObject *
-gl_bbox2(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	float arg3 ;
-	float arg4 ;
-	float arg5 ;
-	float arg6 ;
-	if (!getishortarg(args, 6, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 6, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 6, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 6, 3, &arg4))
-		return NULL;
-	if (!getifloatarg(args, 6, 4, &arg5))
-		return NULL;
-	if (!getifloatarg(args, 6, 5, &arg6))
-		return NULL;
-	bbox2( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bbox2i short s short s long s long s long s long s */
-
-static PyObject *
-gl_bbox2i(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	long arg3 ;
-	long arg4 ;
-	long arg5 ;
-	long arg6 ;
-	if (!getishortarg(args, 6, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 6, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 6, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 6, 3, &arg4))
-		return NULL;
-	if (!getilongarg(args, 6, 4, &arg5))
-		return NULL;
-	if (!getilongarg(args, 6, 5, &arg6))
-		return NULL;
-	bbox2i( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bbox2s short s short s short s short s short s short s */
-
-static PyObject *
-gl_bbox2s(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	short arg6 ;
-	if (!getishortarg(args, 6, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 6, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 6, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 6, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 6, 4, &arg5))
-		return NULL;
-	if (!getishortarg(args, 6, 5, &arg6))
-		return NULL;
-	bbox2s( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void blink short s short s short s short s short s */
-
-static PyObject *
-gl_blink(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getishortarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	blink( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void ortho float s float s float s float s float s float s */
-
-static PyObject *
-gl_ortho(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	float arg5 ;
-	float arg6 ;
-	if (!getifloatarg(args, 6, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 6, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 6, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 6, 3, &arg4))
-		return NULL;
-	if (!getifloatarg(args, 6, 4, &arg5))
-		return NULL;
-	if (!getifloatarg(args, 6, 5, &arg6))
-		return NULL;
-	ortho( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void window float s float s float s float s float s float s */
-
-static PyObject *
-gl_window(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	float arg5 ;
-	float arg6 ;
-	if (!getifloatarg(args, 6, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 6, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 6, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 6, 3, &arg4))
-		return NULL;
-	if (!getifloatarg(args, 6, 4, &arg5))
-		return NULL;
-	if (!getifloatarg(args, 6, 5, &arg6))
-		return NULL;
-	window( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lookat float s float s float s float s float s float s short s */
-
-static PyObject *
-gl_lookat(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	float arg5 ;
-	float arg6 ;
-	short arg7 ;
-	if (!getifloatarg(args, 7, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 7, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 7, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 7, 3, &arg4))
-		return NULL;
-	if (!getifloatarg(args, 7, 4, &arg5))
-		return NULL;
-	if (!getifloatarg(args, 7, 5, &arg6))
-		return NULL;
-	if (!getishortarg(args, 7, 6, &arg7))
-		return NULL;
-	lookat( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void perspective short s float s float s float s */
-
-static PyObject *
-gl_perspective(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	perspective( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void polarview float s short s short s short s */
-
-static PyObject *
-gl_polarview(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	polarview( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void arcfs short s short s short s short s short s */
-
-static PyObject *
-gl_arcfs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getishortarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	arcfs( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void arcs short s short s short s short s short s */
-
-static PyObject *
-gl_arcs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	if (!getishortarg(args, 5, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 5, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 5, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 5, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 5, 4, &arg5))
-		return NULL;
-	arcs( arg1 , arg2 , arg3 , arg4 , arg5 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rectcopy short s short s short s short s short s short s */
-
-static PyObject *
-gl_rectcopy(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	short arg6 ;
-	if (!getishortarg(args, 6, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 6, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 6, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 6, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 6, 4, &arg5))
-		return NULL;
-	if (!getishortarg(args, 6, 5, &arg6))
-		return NULL;
-	rectcopy( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void RGBcursor short s short s short s short s short s short s short s */
-
-static PyObject *
-gl_RGBcursor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	short arg6 ;
-	short arg7 ;
-	if (!getishortarg(args, 7, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 7, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 7, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 7, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 7, 4, &arg5))
-		return NULL;
-	if (!getishortarg(args, 7, 5, &arg6))
-		return NULL;
-	if (!getishortarg(args, 7, 6, &arg7))
-		return NULL;
-	RGBcursor( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long getbutton short s */
-
-static PyObject *
-gl_getbutton(PyObject *self, PyObject *args)
-{
-	long retval;
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = getbutton( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* long getcmmode */
-
-static PyObject *
-gl_getcmmode(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getcmmode( );
-	return mknewlongobject(retval);
-}
-
-/* long getlsbackup */
-
-static PyObject *
-gl_getlsbackup(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getlsbackup( );
-	return mknewlongobject(retval);
-}
-
-/* long getresetls */
-
-static PyObject *
-gl_getresetls(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getresetls( );
-	return mknewlongobject(retval);
-}
-
-/* long getdcm */
-
-static PyObject *
-gl_getdcm(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getdcm( );
-	return mknewlongobject(retval);
-}
-
-/* long getzbuffer */
-
-static PyObject *
-gl_getzbuffer(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getzbuffer( );
-	return mknewlongobject(retval);
-}
-
-/* long ismex */
-
-static PyObject *
-gl_ismex(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = ismex( );
-	return mknewlongobject(retval);
-}
-
-/* long isobj long s */
-
-static PyObject *
-gl_isobj(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = isobj( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* long isqueued short s */
-
-static PyObject *
-gl_isqueued(PyObject *self, PyObject *args)
-{
-	long retval;
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = isqueued( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* long istag long s */
-
-static PyObject *
-gl_istag(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = istag( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* long genobj */
-
-static PyObject *
-gl_genobj(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = genobj( );
-	return mknewlongobject(retval);
-}
-
-/* long gentag */
-
-static PyObject *
-gl_gentag(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = gentag( );
-	return mknewlongobject(retval);
-}
-
-/* long getbuffer */
-
-static PyObject *
-gl_getbuffer(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getbuffer( );
-	return mknewlongobject(retval);
-}
-
-/* long getcolor */
-
-static PyObject *
-gl_getcolor(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getcolor( );
-	return mknewlongobject(retval);
-}
-
-/* long getdisplaymode */
-
-static PyObject *
-gl_getdisplaymode(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getdisplaymode( );
-	return mknewlongobject(retval);
-}
-
-/* long getfont */
-
-static PyObject *
-gl_getfont(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getfont( );
-	return mknewlongobject(retval);
-}
-
-/* long getheight */
-
-static PyObject *
-gl_getheight(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getheight( );
-	return mknewlongobject(retval);
-}
-
-/* long gethitcode */
-
-static PyObject *
-gl_gethitcode(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = gethitcode( );
-	return mknewlongobject(retval);
-}
-
-/* long getlstyle */
-
-static PyObject *
-gl_getlstyle(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getlstyle( );
-	return mknewlongobject(retval);
-}
-
-/* long getlwidth */
-
-static PyObject *
-gl_getlwidth(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getlwidth( );
-	return mknewlongobject(retval);
-}
-
-/* long getmap */
-
-static PyObject *
-gl_getmap(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getmap( );
-	return mknewlongobject(retval);
-}
-
-/* long getplanes */
-
-static PyObject *
-gl_getplanes(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getplanes( );
-	return mknewlongobject(retval);
-}
-
-/* long getwritemask */
-
-static PyObject *
-gl_getwritemask(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getwritemask( );
-	return mknewlongobject(retval);
-}
-
-/* long qtest */
-
-static PyObject *
-gl_qtest(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = qtest( );
-	return mknewlongobject(retval);
-}
-
-/* long getlsrepeat */
-
-static PyObject *
-gl_getlsrepeat(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getlsrepeat( );
-	return mknewlongobject(retval);
-}
-
-/* long getmonitor */
-
-static PyObject *
-gl_getmonitor(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getmonitor( );
-	return mknewlongobject(retval);
-}
-
-/* long getopenobj */
-
-static PyObject *
-gl_getopenobj(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getopenobj( );
-	return mknewlongobject(retval);
-}
-
-/* long getpattern */
-
-static PyObject *
-gl_getpattern(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getpattern( );
-	return mknewlongobject(retval);
-}
-
-/* long winget */
-
-static PyObject *
-gl_winget(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = winget( );
-	return mknewlongobject(retval);
-}
-
-/* long winattach */
-
-static PyObject *
-gl_winattach(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = winattach( );
-	return mknewlongobject(retval);
-}
-
-/* long getothermonitor */
-
-static PyObject *
-gl_getothermonitor(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getothermonitor( );
-	return mknewlongobject(retval);
-}
-
-/* long newpup */
-
-static PyObject *
-gl_newpup(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = newpup( );
-	return mknewlongobject(retval);
-}
-
-/* long getvaluator short s */
-
-static PyObject *
-gl_getvaluator(PyObject *self, PyObject *args)
-{
-	long retval;
-	short arg1 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = getvaluator( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void winset long s */
-
-static PyObject *
-gl_winset(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	winset( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long dopup long s */
-
-static PyObject *
-gl_dopup(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = dopup( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void getdepth short r short r */
-
-static PyObject *
-gl_getdepth(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	getdepth( & arg1 , & arg2 );
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  return v;
-	}
-}
-
-/* void getcpos short r short r */
-
-static PyObject *
-gl_getcpos(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	getcpos( & arg1 , & arg2 );
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  return v;
-	}
-}
-
-/* void getsize long r long r */
-
-static PyObject *
-gl_getsize(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	getsize( & arg1 , & arg2 );
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewlongobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewlongobject(arg2));
-	  return v;
-	}
-}
-
-/* void getorigin long r long r */
-
-static PyObject *
-gl_getorigin(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	getorigin( & arg1 , & arg2 );
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewlongobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewlongobject(arg2));
-	  return v;
-	}
-}
-
-/* void getviewport short r short r short r short r */
-
-static PyObject *
-gl_getviewport(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	getviewport( & arg1 , & arg2 , & arg3 , & arg4 );
-	{ PyObject *v = PyTuple_New( 4 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  PyTuple_SetItem(v, 2, mknewshortobject(arg3));
-	  PyTuple_SetItem(v, 3, mknewshortobject(arg4));
-	  return v;
-	}
-}
-
-/* void gettp short r short r short r short r */
-
-static PyObject *
-gl_gettp(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	gettp( & arg1 , & arg2 , & arg3 , & arg4 );
-	{ PyObject *v = PyTuple_New( 4 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  PyTuple_SetItem(v, 2, mknewshortobject(arg3));
-	  PyTuple_SetItem(v, 3, mknewshortobject(arg4));
-	  return v;
-	}
-}
-
-/* void getgpos float r float r float r float r */
-
-static PyObject *
-gl_getgpos(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	getgpos( & arg1 , & arg2 , & arg3 , & arg4 );
-	{ PyObject *v = PyTuple_New( 4 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewfloatobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewfloatobject(arg2));
-	  PyTuple_SetItem(v, 2, mknewfloatobject(arg3));
-	  PyTuple_SetItem(v, 3, mknewfloatobject(arg4));
-	  return v;
-	}
-}
-
-/* void winposition long s long s long s long s */
-
-static PyObject *
-gl_winposition(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	winposition( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gRGBcolor short r short r short r */
-
-static PyObject *
-gl_gRGBcolor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	gRGBcolor( & arg1 , & arg2 , & arg3 );
-	{ PyObject *v = PyTuple_New( 3 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  PyTuple_SetItem(v, 2, mknewshortobject(arg3));
-	  return v;
-	}
-}
-
-/* void gRGBmask short r short r short r */
-
-static PyObject *
-gl_gRGBmask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	gRGBmask( & arg1 , & arg2 , & arg3 );
-	{ PyObject *v = PyTuple_New( 3 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  PyTuple_SetItem(v, 2, mknewshortobject(arg3));
-	  return v;
-	}
-}
-
-/* void getscrmask short r short r short r short r */
-
-static PyObject *
-gl_getscrmask(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	getscrmask( & arg1 , & arg2 , & arg3 , & arg4 );
-	{ PyObject *v = PyTuple_New( 4 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg2));
-	  PyTuple_SetItem(v, 2, mknewshortobject(arg3));
-	  PyTuple_SetItem(v, 3, mknewshortobject(arg4));
-	  return v;
-	}
-}
-
-/* void getmcolor short s short r short r short r */
-
-static PyObject *
-gl_getmcolor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 1, 0, &arg1))
-		return NULL;
-	getmcolor( arg1 , & arg2 , & arg3 , & arg4 );
-	{ PyObject *v = PyTuple_New( 3 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg2));
-	  PyTuple_SetItem(v, 1, mknewshortobject(arg3));
-	  PyTuple_SetItem(v, 2, mknewshortobject(arg4));
-	  return v;
-	}
-}
-
-/* void mapw long s short s short s float r float r float r float r float r float r */
-
-static PyObject *
-gl_mapw(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short arg2 ;
-	short arg3 ;
-	float arg4 ;
-	float arg5 ;
-	float arg6 ;
-	float arg7 ;
-	float arg8 ;
-	float arg9 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	mapw( arg1 , arg2 , arg3 , & arg4 , & arg5 , & arg6 , & arg7 , & arg8 , & arg9 );
-	{ PyObject *v = PyTuple_New( 6 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
-	  PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
-	  PyTuple_SetItem(v, 2, mknewfloatobject(arg6));
-	  PyTuple_SetItem(v, 3, mknewfloatobject(arg7));
-	  PyTuple_SetItem(v, 4, mknewfloatobject(arg8));
-	  PyTuple_SetItem(v, 5, mknewfloatobject(arg9));
-	  return v;
-	}
-}
-
-/* void mapw2 long s short s short s float r float r */
-
-static PyObject *
-gl_mapw2(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	short arg2 ;
-	short arg3 ;
-	float arg4 ;
-	float arg5 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 3, 2, &arg3))
-		return NULL;
-	mapw2( arg1 , arg2 , arg3 , & arg4 , & arg5 );
-	{ PyObject *v = PyTuple_New( 2 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
-	  PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
-	  return v;
-	}
-}
-
-/* void getcursor short r u_short r u_short r long r */
-
-static PyObject *
-gl_getcursor(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	unsigned short arg2 ;
-	unsigned short arg3 ;
-	long arg4 ;
-	getcursor( & arg1 , & arg2 , & arg3 , & arg4 );
-	{ PyObject *v = PyTuple_New( 4 );
-	  if (v == NULL) return NULL;
-	  PyTuple_SetItem(v, 0, mknewshortobject(arg1));
-	  PyTuple_SetItem(v, 1, mknewshortobject((short) arg2));
-	  PyTuple_SetItem(v, 2, mknewshortobject((short) arg3));
-	  PyTuple_SetItem(v, 3, mknewlongobject(arg4));
-	  return v;
-	}
-}
-
-/* void cmode */
-
-static PyObject *
-gl_cmode(PyObject *self, PyObject *args)
-{
-	cmode( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void concave long s */
-
-static PyObject *
-gl_concave(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	concave( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void curstype long s */
-
-static PyObject *
-gl_curstype(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	curstype( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void drawmode long s */
-
-static PyObject *
-gl_drawmode(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	drawmode( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void gammaramp short s[256] short s[256] short s[256] */
-
-static PyObject *
-gl_gammaramp(PyObject *self, PyObject *args)
-{
-	short arg1 [ 256 ] ;
-	short arg2 [ 256 ] ;
-	short arg3 [ 256 ] ;
-	if (!getishortarray(args, 3, 0, 256 , arg1))
-		return NULL;
-	if (!getishortarray(args, 3, 1, 256 , arg2))
-		return NULL;
-	if (!getishortarray(args, 3, 2, 256 , arg3))
-		return NULL;
-	gammaramp( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long getbackface */
-
-static PyObject *
-gl_getbackface(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getbackface( );
-	return mknewlongobject(retval);
-}
-
-/* long getdescender */
-
-static PyObject *
-gl_getdescender(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getdescender( );
-	return mknewlongobject(retval);
-}
-
-/* long getdrawmode */
-
-static PyObject *
-gl_getdrawmode(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getdrawmode( );
-	return mknewlongobject(retval);
-}
-
-/* long getmmode */
-
-static PyObject *
-gl_getmmode(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getmmode( );
-	return mknewlongobject(retval);
-}
-
-/* long getsm */
-
-static PyObject *
-gl_getsm(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = getsm( );
-	return mknewlongobject(retval);
-}
-
-/* long getvideo long s */
-
-static PyObject *
-gl_getvideo(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = getvideo( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void imakebackground */
-
-static PyObject *
-gl_imakebackground(PyObject *self, PyObject *args)
-{
-	imakebackground( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lmbind short s short s */
-
-static PyObject *
-gl_lmbind(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	if (!getishortarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 2, 1, &arg2))
-		return NULL;
-	lmbind( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lmdef long s long s long s float s[arg3] */
-
-static PyObject *
-gl_lmdef(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	float * arg4 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarraysize(args, 3, 2, &arg3))
-		return NULL;
-	if ((arg4 = PyMem_NEW(float , arg3 )) == NULL)
-		return PyErr_NoMemory();
-	if (!getifloatarray(args, 3, 2, arg3 , arg4))
-		return NULL;
-	lmdef( arg1 , arg2 , arg3 , arg4 );
-	PyMem_DEL(arg4);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void mmode long s */
-
-static PyObject *
-gl_mmode(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	mmode( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void normal float s[3] */
-
-static PyObject *
-gl_normal(PyObject *self, PyObject *args)
-{
-	float arg1 [ 3 ] ;
-	if (!getifloatarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	normal( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void overlay long s */
-
-static PyObject *
-gl_overlay(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	overlay( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void RGBrange short s short s short s short s short s short s short s short s */
-
-static PyObject *
-gl_RGBrange(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	short arg6 ;
-	short arg7 ;
-	short arg8 ;
-	if (!getishortarg(args, 8, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 8, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 8, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 8, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 8, 4, &arg5))
-		return NULL;
-	if (!getishortarg(args, 8, 5, &arg6))
-		return NULL;
-	if (!getishortarg(args, 8, 6, &arg7))
-		return NULL;
-	if (!getishortarg(args, 8, 7, &arg8))
-		return NULL;
-	RGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setvideo long s long s */
-
-static PyObject *
-gl_setvideo(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	setvideo( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void shademodel long s */
-
-static PyObject *
-gl_shademodel(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	shademodel( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void underlay long s */
-
-static PyObject *
-gl_underlay(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	underlay( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgnclosedline */
-
-static PyObject *
-gl_bgnclosedline(PyObject *self, PyObject *args)
-{
-	bgnclosedline( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgnline */
-
-static PyObject *
-gl_bgnline(PyObject *self, PyObject *args)
-{
-	bgnline( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgnpoint */
-
-static PyObject *
-gl_bgnpoint(PyObject *self, PyObject *args)
-{
-	bgnpoint( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgnpolygon */
-
-static PyObject *
-gl_bgnpolygon(PyObject *self, PyObject *args)
-{
-	bgnpolygon( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgnsurface */
-
-static PyObject *
-gl_bgnsurface(PyObject *self, PyObject *args)
-{
-	bgnsurface( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgntmesh */
-
-static PyObject *
-gl_bgntmesh(PyObject *self, PyObject *args)
-{
-	bgntmesh( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void bgntrim */
-
-static PyObject *
-gl_bgntrim(PyObject *self, PyObject *args)
-{
-	bgntrim( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endclosedline */
-
-static PyObject *
-gl_endclosedline(PyObject *self, PyObject *args)
-{
-	endclosedline( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endline */
-
-static PyObject *
-gl_endline(PyObject *self, PyObject *args)
-{
-	endline( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endpoint */
-
-static PyObject *
-gl_endpoint(PyObject *self, PyObject *args)
-{
-	endpoint( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endpolygon */
-
-static PyObject *
-gl_endpolygon(PyObject *self, PyObject *args)
-{
-	endpolygon( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endsurface */
-
-static PyObject *
-gl_endsurface(PyObject *self, PyObject *args)
-{
-	endsurface( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endtmesh */
-
-static PyObject *
-gl_endtmesh(PyObject *self, PyObject *args)
-{
-	endtmesh( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void endtrim */
-
-static PyObject *
-gl_endtrim(PyObject *self, PyObject *args)
-{
-	endtrim( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void blendfunction long s long s */
-
-static PyObject *
-gl_blendfunction(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	blendfunction( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void c3f float s[3] */
-
-static PyObject *
-gl_c3f(PyObject *self, PyObject *args)
-{
-	float arg1 [ 3 ] ;
-	if (!getifloatarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	c3f( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void c3i long s[3] */
-
-static PyObject *
-gl_c3i(PyObject *self, PyObject *args)
-{
-	long arg1 [ 3 ] ;
-	if (!getilongarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	c3i( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void c3s short s[3] */
-
-static PyObject *
-gl_c3s(PyObject *self, PyObject *args)
-{
-	short arg1 [ 3 ] ;
-	if (!getishortarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	c3s( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void c4f float s[4] */
-
-static PyObject *
-gl_c4f(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] ;
-	if (!getifloatarray(args, 1, 0, 4 , arg1))
-		return NULL;
-	c4f( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void c4i long s[4] */
-
-static PyObject *
-gl_c4i(PyObject *self, PyObject *args)
-{
-	long arg1 [ 4 ] ;
-	if (!getilongarray(args, 1, 0, 4 , arg1))
-		return NULL;
-	c4i( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void c4s short s[4] */
-
-static PyObject *
-gl_c4s(PyObject *self, PyObject *args)
-{
-	short arg1 [ 4 ] ;
-	if (!getishortarray(args, 1, 0, 4 , arg1))
-		return NULL;
-	c4s( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void colorf float s */
-
-static PyObject *
-gl_colorf(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	if (!getifloatarg(args, 1, 0, &arg1))
-		return NULL;
-	colorf( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void cpack long s */
-
-static PyObject *
-gl_cpack(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	cpack( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void czclear long s long s */
-
-static PyObject *
-gl_czclear(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	czclear( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void dglclose long s */
-
-static PyObject *
-gl_dglclose(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	dglclose( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long dglopen char *s long s */
-
-static PyObject *
-gl_dglopen(PyObject *self, PyObject *args)
-{
-	long retval;
-	string arg1 ;
-	long arg2 ;
-	if (!getistringarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	retval = dglopen( arg1 , arg2 );
-	return mknewlongobject(retval);
-}
-
-/* long getgdesc long s */
-
-static PyObject *
-gl_getgdesc(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = getgdesc( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void getnurbsproperty long s float r */
-
-static PyObject *
-gl_getnurbsproperty(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float arg2 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	getnurbsproperty( arg1 , & arg2 );
-	return mknewfloatobject(arg2);
-}
-
-/* void glcompat long s long s */
-
-static PyObject *
-gl_glcompat(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	glcompat( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void iconsize long s long s */
-
-static PyObject *
-gl_iconsize(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	iconsize( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void icontitle char *s */
-
-static PyObject *
-gl_icontitle(PyObject *self, PyObject *args)
-{
-	string arg1 ;
-	if (!getistringarg(args, 1, 0, &arg1))
-		return NULL;
-	icontitle( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lRGBrange short s short s short s short s short s short s long s long s */
-
-static PyObject *
-gl_lRGBrange(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	short arg5 ;
-	short arg6 ;
-	long arg7 ;
-	long arg8 ;
-	if (!getishortarg(args, 8, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 8, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 8, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 8, 3, &arg4))
-		return NULL;
-	if (!getishortarg(args, 8, 4, &arg5))
-		return NULL;
-	if (!getishortarg(args, 8, 5, &arg6))
-		return NULL;
-	if (!getilongarg(args, 8, 6, &arg7))
-		return NULL;
-	if (!getilongarg(args, 8, 7, &arg8))
-		return NULL;
-	lRGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void linesmooth long s */
-
-static PyObject *
-gl_linesmooth(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	linesmooth( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lmcolor long s */
-
-static PyObject *
-gl_lmcolor(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	lmcolor( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void logicop long s */
-
-static PyObject *
-gl_logicop(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	logicop( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lsetdepth long s long s */
-
-static PyObject *
-gl_lsetdepth(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	lsetdepth( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void lshaderange short s short s long s long s */
-
-static PyObject *
-gl_lshaderange(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	lshaderange( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void n3f float s[3] */
-
-static PyObject *
-gl_n3f(PyObject *self, PyObject *args)
-{
-	float arg1 [ 3 ] ;
-	if (!getifloatarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	n3f( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void noborder */
-
-static PyObject *
-gl_noborder(PyObject *self, PyObject *args)
-{
-	noborder( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pntsmooth long s */
-
-static PyObject *
-gl_pntsmooth(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	pntsmooth( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void readsource long s */
-
-static PyObject *
-gl_readsource(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	readsource( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void rectzoom float s float s */
-
-static PyObject *
-gl_rectzoom(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	if (!getifloatarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	rectzoom( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void sbox float s float s float s float s */
-
-static PyObject *
-gl_sbox(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	sbox( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void sboxi long s long s long s long s */
-
-static PyObject *
-gl_sboxi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	sboxi( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void sboxs short s short s short s short s */
-
-static PyObject *
-gl_sboxs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	sboxs( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void sboxf float s float s float s float s */
-
-static PyObject *
-gl_sboxf(PyObject *self, PyObject *args)
-{
-	float arg1 ;
-	float arg2 ;
-	float arg3 ;
-	float arg4 ;
-	if (!getifloatarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getifloatarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getifloatarg(args, 4, 3, &arg4))
-		return NULL;
-	sboxf( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void sboxfi long s long s long s long s */
-
-static PyObject *
-gl_sboxfi(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	long arg4 ;
-	if (!getilongarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getilongarg(args, 4, 3, &arg4))
-		return NULL;
-	sboxfi( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void sboxfs short s short s short s short s */
-
-static PyObject *
-gl_sboxfs(PyObject *self, PyObject *args)
-{
-	short arg1 ;
-	short arg2 ;
-	short arg3 ;
-	short arg4 ;
-	if (!getishortarg(args, 4, 0, &arg1))
-		return NULL;
-	if (!getishortarg(args, 4, 1, &arg2))
-		return NULL;
-	if (!getishortarg(args, 4, 2, &arg3))
-		return NULL;
-	if (!getishortarg(args, 4, 3, &arg4))
-		return NULL;
-	sboxfs( arg1 , arg2 , arg3 , arg4 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setnurbsproperty long s float s */
-
-static PyObject *
-gl_setnurbsproperty(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	float arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getifloatarg(args, 2, 1, &arg2))
-		return NULL;
-	setnurbsproperty( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void setpup long s long s long s */
-
-static PyObject *
-gl_setpup(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	long arg3 ;
-	if (!getilongarg(args, 3, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 3, 1, &arg2))
-		return NULL;
-	if (!getilongarg(args, 3, 2, &arg3))
-		return NULL;
-	setpup( arg1 , arg2 , arg3 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void smoothline long s */
-
-static PyObject *
-gl_smoothline(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	smoothline( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void subpixel long s */
-
-static PyObject *
-gl_subpixel(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	subpixel( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void swaptmesh */
-
-static PyObject *
-gl_swaptmesh(PyObject *self, PyObject *args)
-{
-	swaptmesh( );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long swinopen long s */
-
-static PyObject *
-gl_swinopen(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = swinopen( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void v2f float s[2] */
-
-static PyObject *
-gl_v2f(PyObject *self, PyObject *args)
-{
-	float arg1 [ 2 ] ;
-	if (!getifloatarray(args, 1, 0, 2 , arg1))
-		return NULL;
-	v2f( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v2i long s[2] */
-
-static PyObject *
-gl_v2i(PyObject *self, PyObject *args)
-{
-	long arg1 [ 2 ] ;
-	if (!getilongarray(args, 1, 0, 2 , arg1))
-		return NULL;
-	v2i( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v2s short s[2] */
-
-static PyObject *
-gl_v2s(PyObject *self, PyObject *args)
-{
-	short arg1 [ 2 ] ;
-	if (!getishortarray(args, 1, 0, 2 , arg1))
-		return NULL;
-	v2s( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v3f float s[3] */
-
-static PyObject *
-gl_v3f(PyObject *self, PyObject *args)
-{
-	float arg1 [ 3 ] ;
-	if (!getifloatarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	v3f( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v3i long s[3] */
-
-static PyObject *
-gl_v3i(PyObject *self, PyObject *args)
-{
-	long arg1 [ 3 ] ;
-	if (!getilongarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	v3i( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v3s short s[3] */
-
-static PyObject *
-gl_v3s(PyObject *self, PyObject *args)
-{
-	short arg1 [ 3 ] ;
-	if (!getishortarray(args, 1, 0, 3 , arg1))
-		return NULL;
-	v3s( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v4f float s[4] */
-
-static PyObject *
-gl_v4f(PyObject *self, PyObject *args)
-{
-	float arg1 [ 4 ] ;
-	if (!getifloatarray(args, 1, 0, 4 , arg1))
-		return NULL;
-	v4f( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v4i long s[4] */
-
-static PyObject *
-gl_v4i(PyObject *self, PyObject *args)
-{
-	long arg1 [ 4 ] ;
-	if (!getilongarray(args, 1, 0, 4 , arg1))
-		return NULL;
-	v4i( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v4s short s[4] */
-
-static PyObject *
-gl_v4s(PyObject *self, PyObject *args)
-{
-	short arg1 [ 4 ] ;
-	if (!getishortarray(args, 1, 0, 4 , arg1))
-		return NULL;
-	v4s( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void videocmd long s */
-
-static PyObject *
-gl_videocmd(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	videocmd( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long windepth long s */
-
-static PyObject *
-gl_windepth(PyObject *self, PyObject *args)
-{
-	long retval;
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	retval = windepth( arg1 );
-	return mknewlongobject(retval);
-}
-
-/* void wmpack long s */
-
-static PyObject *
-gl_wmpack(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	wmpack( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void zdraw long s */
-
-static PyObject *
-gl_zdraw(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	zdraw( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void zfunction long s */
-
-static PyObject *
-gl_zfunction(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	zfunction( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void zsource long s */
-
-static PyObject *
-gl_zsource(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	zsource( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void zwritemask long s */
-
-static PyObject *
-gl_zwritemask(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	zwritemask( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v2d double s[2] */
-
-static PyObject *
-gl_v2d(PyObject *self, PyObject *args)
-{
-	double arg1 [ 2 ] ;
-	if (!getidoublearray(args, 1, 0, 2 , arg1))
-		return NULL;
-	v2d( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v3d double s[3] */
-
-static PyObject *
-gl_v3d(PyObject *self, PyObject *args)
-{
-	double arg1 [ 3 ] ;
-	if (!getidoublearray(args, 1, 0, 3 , arg1))
-		return NULL;
-	v3d( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void v4d double s[4] */
-
-static PyObject *
-gl_v4d(PyObject *self, PyObject *args)
-{
-	double arg1 [ 4 ] ;
-	if (!getidoublearray(args, 1, 0, 4 , arg1))
-		return NULL;
-	v4d( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* void pixmode long s long s */
-
-static PyObject *
-gl_pixmode(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	long arg2 ;
-	if (!getilongarg(args, 2, 0, &arg1))
-		return NULL;
-	if (!getilongarg(args, 2, 1, &arg2))
-		return NULL;
-	pixmode( arg1 , arg2 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-/* long qgetfd */
-
-static PyObject *
-gl_qgetfd(PyObject *self, PyObject *args)
-{
-	long retval;
-	retval = qgetfd( );
-	return mknewlongobject(retval);
-}
-
-/* void dither long s */
-
-static PyObject *
-gl_dither(PyObject *self, PyObject *args)
-{
-	long arg1 ;
-	if (!getilongarg(args, 1, 0, &arg1))
-		return NULL;
-	dither( arg1 );
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static struct PyMethodDef gl_methods[] = {
-	{"qread", gl_qread,                  METH_OLDARGS},
-	{"varray", gl_varray,                METH_OLDARGS},
-	{"nvarray", gl_nvarray,              METH_OLDARGS},
-	{"vnarray", gl_vnarray,              METH_OLDARGS},
-	{"nurbssurface", gl_nurbssurface,    METH_OLDARGS},
-	{"nurbscurve", gl_nurbscurve,        METH_OLDARGS},
-	{"pwlcurve", gl_pwlcurve,            METH_OLDARGS},
-	{"pick", gl_pick,                    METH_OLDARGS},
-	{"endpick", gl_endpick,              METH_NOARGS},
-	{"gselect", gl_gselect,              METH_OLDARGS},
-	{"endselect", gl_endselect,          METH_NOARGS},
-	{"getmatrix", gl_getmatrix,          METH_OLDARGS},
-	{"altgetmatrix", gl_altgetmatrix,    METH_OLDARGS},
-	{"lrectwrite", gl_lrectwrite,        METH_OLDARGS},
-	{"lrectread", gl_lrectread,          METH_OLDARGS},
-	{"readdisplay", gl_readdisplay,      METH_OLDARGS},
-	{"packrect", gl_packrect,            METH_OLDARGS},
-	{"unpackrect", gl_unpackrect,        METH_OLDARGS},
-	{"gversion", gl_gversion,            METH_OLDARGS},
-	{"clear", gl_clear,                  METH_OLDARGS},
-	{"getshade", gl_getshade,            METH_OLDARGS},
-	{"devport", gl_devport,              METH_OLDARGS},
-	{"rdr2i", gl_rdr2i,                  METH_OLDARGS},
-	{"rectfs", gl_rectfs,                METH_OLDARGS},
-	{"rects", gl_rects,                  METH_OLDARGS},
-	{"rmv2i", gl_rmv2i,                  METH_OLDARGS},
-	{"noport", gl_noport,                METH_OLDARGS},
-	{"popviewport", gl_popviewport,      METH_OLDARGS},
-	{"clearhitcode", gl_clearhitcode,    METH_OLDARGS},
-	{"closeobj", gl_closeobj,            METH_OLDARGS},
-	{"cursoff", gl_cursoff,              METH_OLDARGS},
-	{"curson", gl_curson,                METH_OLDARGS},
-	{"doublebuffer", gl_doublebuffer,    METH_OLDARGS},
-	{"finish", gl_finish,                METH_OLDARGS},
-	{"gconfig", gl_gconfig,              METH_OLDARGS},
-	{"ginit", gl_ginit,                  METH_OLDARGS},
-	{"greset", gl_greset,                METH_OLDARGS},
-	{"multimap", gl_multimap,            METH_OLDARGS},
-	{"onemap", gl_onemap,                METH_OLDARGS},
-	{"popattributes", gl_popattributes,  METH_OLDARGS},
-	{"popmatrix", gl_popmatrix,          METH_OLDARGS},
-	{"pushattributes", gl_pushattributes,METH_OLDARGS},
-	{"pushmatrix", gl_pushmatrix,        METH_OLDARGS},
-	{"pushviewport", gl_pushviewport,    METH_OLDARGS},
-	{"qreset", gl_qreset,                METH_OLDARGS},
-	{"RGBmode", gl_RGBmode,              METH_OLDARGS},
-	{"singlebuffer", gl_singlebuffer,    METH_OLDARGS},
-	{"swapbuffers", gl_swapbuffers,      METH_OLDARGS},
-	{"gsync", gl_gsync,                  METH_OLDARGS},
-	{"gflush", gl_gflush,                METH_OLDARGS},
-	{"tpon", gl_tpon,                    METH_OLDARGS},
-	{"tpoff", gl_tpoff,                  METH_OLDARGS},
-	{"clkon", gl_clkon,                  METH_OLDARGS},
-	{"clkoff", gl_clkoff,                METH_OLDARGS},
-	{"ringbell", gl_ringbell,            METH_OLDARGS},
-	{"gbegin", gl_gbegin,                METH_OLDARGS},
-	{"textinit", gl_textinit,            METH_OLDARGS},
-	{"initnames", gl_initnames,          METH_OLDARGS},
-	{"pclos", gl_pclos,                  METH_OLDARGS},
-	{"popname", gl_popname,              METH_OLDARGS},
-	{"spclos", gl_spclos,                METH_OLDARGS},
-	{"zclear", gl_zclear,                METH_OLDARGS},
-	{"screenspace", gl_screenspace,      METH_OLDARGS},
-	{"reshapeviewport", gl_reshapeviewport, METH_OLDARGS},
-	{"winpush", gl_winpush,              METH_OLDARGS},
-	{"winpop", gl_winpop,                METH_OLDARGS},
-	{"foreground", gl_foreground,        METH_OLDARGS},
-	{"endfullscrn", gl_endfullscrn,      METH_OLDARGS},
-	{"endpupmode", gl_endpupmode,        METH_OLDARGS},
-	{"fullscrn", gl_fullscrn,            METH_OLDARGS},
-	{"pupmode", gl_pupmode,              METH_OLDARGS},
-	{"winconstraints", gl_winconstraints, METH_OLDARGS},
-	{"pagecolor", gl_pagecolor,          METH_OLDARGS},
-	{"textcolor", gl_textcolor,          METH_OLDARGS},
-	{"color", gl_color,                  METH_OLDARGS},
-	{"curveit", gl_curveit,              METH_OLDARGS},
-	{"font", gl_font,                    METH_OLDARGS},
-	{"linewidth", gl_linewidth,          METH_OLDARGS},
-	{"setlinestyle", gl_setlinestyle,    METH_OLDARGS},
-	{"setmap", gl_setmap,                METH_OLDARGS},
-	{"swapinterval", gl_swapinterval,    METH_OLDARGS},
-	{"writemask", gl_writemask,          METH_OLDARGS},
-	{"textwritemask", gl_textwritemask,  METH_OLDARGS},
-	{"qdevice", gl_qdevice,              METH_OLDARGS},
-	{"unqdevice", gl_unqdevice,          METH_OLDARGS},
-	{"curvebasis", gl_curvebasis,        METH_OLDARGS},
-	{"curveprecision", gl_curveprecision,METH_OLDARGS},
-	{"loadname", gl_loadname,            METH_OLDARGS},
-	{"passthrough", gl_passthrough,      METH_OLDARGS},
-	{"pushname", gl_pushname,            METH_OLDARGS},
-	{"setmonitor", gl_setmonitor,        METH_OLDARGS},
-	{"setshade", gl_setshade,            METH_OLDARGS},
-	{"setpattern", gl_setpattern,        METH_OLDARGS},
-	{"pagewritemask", gl_pagewritemask,  METH_OLDARGS},
-	{"callobj", gl_callobj,              METH_OLDARGS},
-	{"delobj", gl_delobj,                METH_OLDARGS},
-	{"editobj", gl_editobj,              METH_OLDARGS},
-	{"makeobj", gl_makeobj,              METH_OLDARGS},
-	{"maketag", gl_maketag,              METH_OLDARGS},
-	{"chunksize", gl_chunksize,          METH_OLDARGS},
-	{"compactify", gl_compactify,        METH_OLDARGS},
-	{"deltag", gl_deltag,                METH_OLDARGS},
-	{"lsrepeat", gl_lsrepeat,            METH_OLDARGS},
-	{"objinsert", gl_objinsert,          METH_OLDARGS},
-	{"objreplace", gl_objreplace,        METH_OLDARGS},
-	{"winclose", gl_winclose,            METH_OLDARGS},
-	{"blanktime", gl_blanktime,          METH_OLDARGS},
-	{"freepup", gl_freepup,              METH_OLDARGS},
-	{"backbuffer", gl_backbuffer,        METH_OLDARGS},
-	{"frontbuffer", gl_frontbuffer,      METH_OLDARGS},
-	{"lsbackup", gl_lsbackup,            METH_OLDARGS},
-	{"resetls", gl_resetls,              METH_OLDARGS},
-	{"lampon", gl_lampon,                METH_OLDARGS},
-	{"lampoff", gl_lampoff,              METH_OLDARGS},
-	{"setbell", gl_setbell,              METH_OLDARGS},
-	{"blankscreen", gl_blankscreen,      METH_OLDARGS},
-	{"depthcue", gl_depthcue,            METH_OLDARGS},
-	{"zbuffer", gl_zbuffer,              METH_OLDARGS},
-	{"backface", gl_backface,            METH_OLDARGS},
-	{"cmov2i", gl_cmov2i,                METH_OLDARGS},
-	{"draw2i", gl_draw2i,                METH_OLDARGS},
-	{"move2i", gl_move2i,                METH_OLDARGS},
-	{"pnt2i", gl_pnt2i,                  METH_OLDARGS},
-	{"patchbasis", gl_patchbasis,        METH_OLDARGS},
-	{"patchprecision", gl_patchprecision, METH_OLDARGS},
-	{"pdr2i", gl_pdr2i,                  METH_OLDARGS},
-	{"pmv2i", gl_pmv2i,                  METH_OLDARGS},
-	{"rpdr2i", gl_rpdr2i,                METH_OLDARGS},
-	{"rpmv2i", gl_rpmv2i,                METH_OLDARGS},
-	{"xfpt2i", gl_xfpt2i,                METH_OLDARGS},
-	{"objdelete", gl_objdelete,          METH_OLDARGS},
-	{"patchcurves", gl_patchcurves,      METH_OLDARGS},
-	{"minsize", gl_minsize,              METH_OLDARGS},
-	{"maxsize", gl_maxsize,              METH_OLDARGS},
-	{"keepaspect", gl_keepaspect,        METH_OLDARGS},
-	{"prefsize", gl_prefsize,            METH_OLDARGS},
-	{"stepunit", gl_stepunit,            METH_OLDARGS},
-	{"fudge", gl_fudge,                  METH_OLDARGS},
-	{"winmove", gl_winmove,              METH_OLDARGS},
-	{"attachcursor", gl_attachcursor,    METH_OLDARGS},
-	{"deflinestyle", gl_deflinestyle,    METH_OLDARGS},
-	{"noise", gl_noise,                  METH_OLDARGS},
-	{"picksize", gl_picksize,            METH_OLDARGS},
-	{"qenter", gl_qenter,                METH_OLDARGS},
-	{"setdepth", gl_setdepth,            METH_OLDARGS},
-	{"cmov2s", gl_cmov2s,                METH_OLDARGS},
-	{"draw2s", gl_draw2s,                METH_OLDARGS},
-	{"move2s", gl_move2s,                METH_OLDARGS},
-	{"pdr2s", gl_pdr2s,                  METH_OLDARGS},
-	{"pmv2s", gl_pmv2s,                  METH_OLDARGS},
-	{"pnt2s", gl_pnt2s,                  METH_OLDARGS},
-	{"rdr2s", gl_rdr2s,                  METH_OLDARGS},
-	{"rmv2s", gl_rmv2s,                  METH_OLDARGS},
-	{"rpdr2s", gl_rpdr2s,                METH_OLDARGS},
-	{"rpmv2s", gl_rpmv2s,                METH_OLDARGS},
-	{"xfpt2s", gl_xfpt2s,                METH_OLDARGS},
-	{"cmov2", gl_cmov2,                  METH_OLDARGS},
-	{"draw2", gl_draw2,                  METH_OLDARGS},
-	{"move2", gl_move2,                  METH_OLDARGS},
-	{"pnt2", gl_pnt2,                    METH_OLDARGS},
-	{"pdr2", gl_pdr2,                    METH_OLDARGS},
-	{"pmv2", gl_pmv2,                    METH_OLDARGS},
-	{"rdr2", gl_rdr2,                    METH_OLDARGS},
-	{"rmv2", gl_rmv2,                    METH_OLDARGS},
-	{"rpdr2", gl_rpdr2,                  METH_OLDARGS},
-	{"rpmv2", gl_rpmv2,                  METH_OLDARGS},
-	{"xfpt2", gl_xfpt2,                  METH_OLDARGS},
-	{"loadmatrix", gl_loadmatrix,        METH_OLDARGS},
-	{"multmatrix", gl_multmatrix,        METH_OLDARGS},
-	{"crv", gl_crv,                      METH_OLDARGS},
-	{"rcrv", gl_rcrv,                    METH_OLDARGS},
-	{"addtopup", gl_addtopup,            METH_OLDARGS},
-	{"charstr", gl_charstr,              METH_OLDARGS},
-	{"getport", gl_getport,              METH_OLDARGS},
-	{"strwidth", gl_strwidth,            METH_OLDARGS},
-	{"winopen", gl_winopen,              METH_OLDARGS},
-	{"wintitle", gl_wintitle,            METH_OLDARGS},
-	{"polf", gl_polf,                    METH_OLDARGS},
-	{"polf2", gl_polf2,                  METH_OLDARGS},
-	{"poly", gl_poly,                    METH_OLDARGS},
-	{"poly2", gl_poly2,                  METH_OLDARGS},
-	{"crvn", gl_crvn,                    METH_OLDARGS},
-	{"rcrvn", gl_rcrvn,                  METH_OLDARGS},
-	{"polf2i", gl_polf2i,                METH_OLDARGS},
-	{"polfi", gl_polfi,                  METH_OLDARGS},
-	{"poly2i", gl_poly2i,                METH_OLDARGS},
-	{"polyi", gl_polyi,                  METH_OLDARGS},
-	{"polf2s", gl_polf2s,                METH_OLDARGS},
-	{"polfs", gl_polfs,                  METH_OLDARGS},
-	{"polys", gl_polys,                  METH_OLDARGS},
-	{"poly2s", gl_poly2s,                METH_OLDARGS},
-	{"defcursor", gl_defcursor,          METH_OLDARGS},
-	{"writepixels", gl_writepixels,      METH_OLDARGS},
-	{"defbasis", gl_defbasis,            METH_OLDARGS},
-	{"gewrite", gl_gewrite,              METH_OLDARGS},
-	{"rotate", gl_rotate,                METH_OLDARGS},
-	{"rot", gl_rot,                      METH_OLDARGS},
-	{"circfi", gl_circfi,                METH_OLDARGS},
-	{"circi", gl_circi,                  METH_OLDARGS},
-	{"cmovi", gl_cmovi,                  METH_OLDARGS},
-	{"drawi", gl_drawi,                  METH_OLDARGS},
-	{"movei", gl_movei,                  METH_OLDARGS},
-	{"pnti", gl_pnti,                    METH_OLDARGS},
-	{"newtag", gl_newtag,                METH_OLDARGS},
-	{"pdri", gl_pdri,                    METH_OLDARGS},
-	{"pmvi", gl_pmvi,                    METH_OLDARGS},
-	{"rdri", gl_rdri,                    METH_OLDARGS},
-	{"rmvi", gl_rmvi,                    METH_OLDARGS},
-	{"rpdri", gl_rpdri,                  METH_OLDARGS},
-	{"rpmvi", gl_rpmvi,                  METH_OLDARGS},
-	{"xfpti", gl_xfpti,                  METH_OLDARGS},
-	{"circ", gl_circ,                    METH_OLDARGS},
-	{"circf", gl_circf,                  METH_OLDARGS},
-	{"cmov", gl_cmov,                    METH_OLDARGS},
-	{"draw", gl_draw,                    METH_OLDARGS},
-	{"move", gl_move,                    METH_OLDARGS},
-	{"pnt", gl_pnt,                      METH_OLDARGS},
-	{"scale", gl_scale,                  METH_OLDARGS},
-	{"translate", gl_translate,          METH_OLDARGS},
-	{"pdr", gl_pdr,                      METH_OLDARGS},
-	{"pmv", gl_pmv,                      METH_OLDARGS},
-	{"rdr", gl_rdr,                      METH_OLDARGS},
-	{"rmv", gl_rmv,                      METH_OLDARGS},
-	{"rpdr", gl_rpdr,                    METH_OLDARGS},
-	{"rpmv", gl_rpmv,                    METH_OLDARGS},
-	{"xfpt", gl_xfpt,                    METH_OLDARGS},
-	{"RGBcolor", gl_RGBcolor,            METH_OLDARGS},
-	{"RGBwritemask", gl_RGBwritemask,    METH_OLDARGS},
-	{"setcursor", gl_setcursor,          METH_OLDARGS},
-	{"tie", gl_tie,                      METH_OLDARGS},
-	{"circfs", gl_circfs,                METH_OLDARGS},
-	{"circs", gl_circs,                  METH_OLDARGS},
-	{"cmovs", gl_cmovs,                  METH_OLDARGS},
-	{"draws", gl_draws,                  METH_OLDARGS},
-	{"moves", gl_moves,                  METH_OLDARGS},
-	{"pdrs", gl_pdrs,                    METH_OLDARGS},
-	{"pmvs", gl_pmvs,                    METH_OLDARGS},
-	{"pnts", gl_pnts,                    METH_OLDARGS},
-	{"rdrs", gl_rdrs,                    METH_OLDARGS},
-	{"rmvs", gl_rmvs,                    METH_OLDARGS},
-	{"rpdrs", gl_rpdrs,                  METH_OLDARGS},
-	{"rpmvs", gl_rpmvs,                  METH_OLDARGS},
-	{"xfpts", gl_xfpts,                  METH_OLDARGS},
-	{"curorigin", gl_curorigin,          METH_OLDARGS},
-	{"cyclemap", gl_cyclemap,            METH_OLDARGS},
-	{"patch", gl_patch,                  METH_OLDARGS},
-	{"splf", gl_splf,                    METH_OLDARGS},
-	{"splf2", gl_splf2,                  METH_OLDARGS},
-	{"splfi", gl_splfi,                  METH_OLDARGS},
-	{"splf2i", gl_splf2i,                METH_OLDARGS},
-	{"splfs", gl_splfs,                  METH_OLDARGS},
-	{"splf2s", gl_splf2s,                METH_OLDARGS},
-	{"rpatch", gl_rpatch,                METH_OLDARGS},
-	{"ortho2", gl_ortho2,                METH_OLDARGS},
-	{"rect", gl_rect,                    METH_OLDARGS},
-	{"rectf", gl_rectf,                  METH_OLDARGS},
-	{"xfpt4", gl_xfpt4,                  METH_OLDARGS},
-	{"textport", gl_textport,            METH_OLDARGS},
-	{"mapcolor", gl_mapcolor,            METH_OLDARGS},
-	{"scrmask", gl_scrmask,              METH_OLDARGS},
-	{"setvaluator", gl_setvaluator,      METH_OLDARGS},
-	{"viewport", gl_viewport,            METH_OLDARGS},
-	{"shaderange", gl_shaderange,        METH_OLDARGS},
-	{"xfpt4s", gl_xfpt4s,                METH_OLDARGS},
-	{"rectfi", gl_rectfi,                METH_OLDARGS},
-	{"recti", gl_recti,                  METH_OLDARGS},
-	{"xfpt4i", gl_xfpt4i,                METH_OLDARGS},
-	{"prefposition", gl_prefposition,    METH_OLDARGS},
-	{"arc", gl_arc,                      METH_OLDARGS},
-	{"arcf", gl_arcf,                    METH_OLDARGS},
-	{"arcfi", gl_arcfi,                  METH_OLDARGS},
-	{"arci", gl_arci,                    METH_OLDARGS},
-	{"bbox2", gl_bbox2,                  METH_OLDARGS},
-	{"bbox2i", gl_bbox2i,                METH_OLDARGS},
-	{"bbox2s", gl_bbox2s,                METH_OLDARGS},
-	{"blink", gl_blink,                  METH_OLDARGS},
-	{"ortho", gl_ortho,                  METH_OLDARGS},
-	{"window", gl_window,                METH_OLDARGS},
-	{"lookat", gl_lookat,                METH_OLDARGS},
-	{"perspective", gl_perspective,      METH_OLDARGS},
-	{"polarview", gl_polarview,          METH_OLDARGS},
-	{"arcfs", gl_arcfs,                  METH_OLDARGS},
-	{"arcs", gl_arcs,                    METH_OLDARGS},
-	{"rectcopy", gl_rectcopy,            METH_OLDARGS},
-	{"RGBcursor", gl_RGBcursor,          METH_OLDARGS},
-	{"getbutton", gl_getbutton,          METH_OLDARGS},
-	{"getcmmode", gl_getcmmode,          METH_OLDARGS},
-	{"getlsbackup", gl_getlsbackup,      METH_OLDARGS},
-	{"getresetls", gl_getresetls,        METH_OLDARGS},
-	{"getdcm", gl_getdcm,                METH_OLDARGS},
-	{"getzbuffer", gl_getzbuffer,        METH_OLDARGS},
-	{"ismex", gl_ismex,                  METH_OLDARGS},
-	{"isobj", gl_isobj,                  METH_OLDARGS},
-	{"isqueued", gl_isqueued,            METH_OLDARGS},
-	{"istag", gl_istag,                  METH_OLDARGS},
-	{"genobj", gl_genobj,                METH_OLDARGS},
-	{"gentag", gl_gentag,                METH_OLDARGS},
-	{"getbuffer", gl_getbuffer,          METH_OLDARGS},
-	{"getcolor", gl_getcolor,            METH_OLDARGS},
-	{"getdisplaymode", gl_getdisplaymode, METH_OLDARGS},
-	{"getfont", gl_getfont,              METH_OLDARGS},
-	{"getheight", gl_getheight,          METH_OLDARGS},
-	{"gethitcode", gl_gethitcode,        METH_OLDARGS},
-	{"getlstyle", gl_getlstyle,          METH_OLDARGS},
-	{"getlwidth", gl_getlwidth,          METH_OLDARGS},
-	{"getmap", gl_getmap,                METH_OLDARGS},
-	{"getplanes", gl_getplanes,          METH_OLDARGS},
-	{"getwritemask", gl_getwritemask,    METH_OLDARGS},
-	{"qtest", gl_qtest,                  METH_OLDARGS},
-	{"getlsrepeat", gl_getlsrepeat,      METH_OLDARGS},
-	{"getmonitor", gl_getmonitor,        METH_OLDARGS},
-	{"getopenobj", gl_getopenobj,        METH_OLDARGS},
-	{"getpattern", gl_getpattern,        METH_OLDARGS},
-	{"winget", gl_winget,                METH_OLDARGS},
-	{"winattach", gl_winattach,          METH_OLDARGS},
-	{"getothermonitor", gl_getothermonitor, METH_OLDARGS},
-	{"newpup", gl_newpup,                METH_OLDARGS},
-	{"getvaluator", gl_getvaluator,      METH_OLDARGS},
-	{"winset", gl_winset,                METH_OLDARGS},
-	{"dopup", gl_dopup,                  METH_OLDARGS},
-	{"getdepth", gl_getdepth,            METH_OLDARGS},
-	{"getcpos", gl_getcpos,              METH_OLDARGS},
-	{"getsize", gl_getsize,              METH_OLDARGS},
-	{"getorigin", gl_getorigin,          METH_OLDARGS},
-	{"getviewport", gl_getviewport,      METH_OLDARGS},
-	{"gettp", gl_gettp,                  METH_OLDARGS},
-	{"getgpos", gl_getgpos,              METH_OLDARGS},
-	{"winposition", gl_winposition,      METH_OLDARGS},
-	{"gRGBcolor", gl_gRGBcolor,          METH_OLDARGS},
-	{"gRGBmask", gl_gRGBmask,            METH_OLDARGS},
-	{"getscrmask", gl_getscrmask,        METH_OLDARGS},
-	{"getmcolor", gl_getmcolor,          METH_OLDARGS},
-	{"mapw", gl_mapw,                    METH_OLDARGS},
-	{"mapw2", gl_mapw2,                  METH_OLDARGS},
-	{"getcursor", gl_getcursor,          METH_OLDARGS},
-	{"cmode", gl_cmode,                  METH_OLDARGS},
-	{"concave", gl_concave,              METH_OLDARGS},
-	{"curstype", gl_curstype,            METH_OLDARGS},
-	{"drawmode", gl_drawmode,            METH_OLDARGS},
-	{"gammaramp", gl_gammaramp,          METH_OLDARGS},
-	{"getbackface", gl_getbackface,      METH_OLDARGS},
-	{"getdescender", gl_getdescender,    METH_OLDARGS},
-	{"getdrawmode", gl_getdrawmode,      METH_OLDARGS},
-	{"getmmode", gl_getmmode,            METH_OLDARGS},
-	{"getsm", gl_getsm,                  METH_OLDARGS},
-	{"getvideo", gl_getvideo,            METH_OLDARGS},
-	{"imakebackground", gl_imakebackground, METH_OLDARGS},
-	{"lmbind", gl_lmbind,                METH_OLDARGS},
-	{"lmdef", gl_lmdef,                  METH_OLDARGS},
-	{"mmode", gl_mmode,                  METH_OLDARGS},
-	{"normal", gl_normal,                METH_OLDARGS},
-	{"overlay", gl_overlay,              METH_OLDARGS},
-	{"RGBrange", gl_RGBrange,            METH_OLDARGS},
-	{"setvideo", gl_setvideo,            METH_OLDARGS},
-	{"shademodel", gl_shademodel,        METH_OLDARGS},
-	{"underlay", gl_underlay,            METH_OLDARGS},
-	{"bgnclosedline", gl_bgnclosedline,  METH_OLDARGS},
-	{"bgnline", gl_bgnline,              METH_OLDARGS},
-	{"bgnpoint", gl_bgnpoint,            METH_OLDARGS},
-	{"bgnpolygon", gl_bgnpolygon,        METH_OLDARGS},
-	{"bgnsurface", gl_bgnsurface,        METH_OLDARGS},
-	{"bgntmesh", gl_bgntmesh,            METH_OLDARGS},
-	{"bgntrim", gl_bgntrim,              METH_OLDARGS},
-	{"endclosedline", gl_endclosedline,  METH_OLDARGS},
-	{"endline", gl_endline,              METH_OLDARGS},
-	{"endpoint", gl_endpoint,            METH_OLDARGS},
-	{"endpolygon", gl_endpolygon,        METH_OLDARGS},
-	{"endsurface", gl_endsurface,        METH_OLDARGS},
-	{"endtmesh", gl_endtmesh,            METH_OLDARGS},
-	{"endtrim", gl_endtrim,              METH_OLDARGS},
-	{"blendfunction", gl_blendfunction,  METH_OLDARGS},
-	{"c3f", gl_c3f,                      METH_OLDARGS},
-	{"c3i", gl_c3i,                      METH_OLDARGS},
-	{"c3s", gl_c3s,                      METH_OLDARGS},
-	{"c4f", gl_c4f,                      METH_OLDARGS},
-	{"c4i", gl_c4i,                      METH_OLDARGS},
-	{"c4s", gl_c4s,                      METH_OLDARGS},
-	{"colorf", gl_colorf,                METH_OLDARGS},
-	{"cpack", gl_cpack,                  METH_OLDARGS},
-	{"czclear", gl_czclear,              METH_OLDARGS},
-	{"dglclose", gl_dglclose,            METH_OLDARGS},
-	{"dglopen", gl_dglopen,              METH_OLDARGS},
-	{"getgdesc", gl_getgdesc,            METH_OLDARGS},
-	{"getnurbsproperty", gl_getnurbsproperty, METH_OLDARGS},
-	{"glcompat", gl_glcompat,            METH_OLDARGS},
-	{"iconsize", gl_iconsize,            METH_OLDARGS},
-	{"icontitle", gl_icontitle,          METH_OLDARGS},
-	{"lRGBrange", gl_lRGBrange,          METH_OLDARGS},
-	{"linesmooth", gl_linesmooth,        METH_OLDARGS},
-	{"lmcolor", gl_lmcolor,              METH_OLDARGS},
-	{"logicop", gl_logicop,              METH_OLDARGS},
-	{"lsetdepth", gl_lsetdepth,          METH_OLDARGS},
-	{"lshaderange", gl_lshaderange,      METH_OLDARGS},
-	{"n3f", gl_n3f,                      METH_OLDARGS},
-	{"noborder", gl_noborder,            METH_OLDARGS},
-	{"pntsmooth", gl_pntsmooth,          METH_OLDARGS},
-	{"readsource", gl_readsource,        METH_OLDARGS},
-	{"rectzoom", gl_rectzoom,            METH_OLDARGS},
-	{"sbox", gl_sbox,                    METH_OLDARGS},
-	{"sboxi", gl_sboxi,                  METH_OLDARGS},
-	{"sboxs", gl_sboxs,                  METH_OLDARGS},
-	{"sboxf", gl_sboxf,                  METH_OLDARGS},
-	{"sboxfi", gl_sboxfi,                METH_OLDARGS},
-	{"sboxfs", gl_sboxfs,                METH_OLDARGS},
-	{"setnurbsproperty", gl_setnurbsproperty, METH_OLDARGS},
-	{"setpup", gl_setpup,                METH_OLDARGS},
-	{"smoothline", gl_smoothline,        METH_OLDARGS},
-	{"subpixel", gl_subpixel,            METH_OLDARGS},
-	{"swaptmesh", gl_swaptmesh,          METH_OLDARGS},
-	{"swinopen", gl_swinopen,            METH_OLDARGS},
-	{"v2f", gl_v2f,                      METH_OLDARGS},
-	{"v2i", gl_v2i,                      METH_OLDARGS},
-	{"v2s", gl_v2s,                      METH_OLDARGS},
-	{"v3f", gl_v3f,                      METH_OLDARGS},
-	{"v3i", gl_v3i,                      METH_OLDARGS},
-	{"v3s", gl_v3s,                      METH_OLDARGS},
-	{"v4f", gl_v4f,                      METH_OLDARGS},
-	{"v4i", gl_v4i,                      METH_OLDARGS},
-	{"v4s", gl_v4s,                      METH_OLDARGS},
-	{"videocmd", gl_videocmd,            METH_OLDARGS},
-	{"windepth", gl_windepth,            METH_OLDARGS},
-	{"wmpack", gl_wmpack,                METH_OLDARGS},
-	{"zdraw", gl_zdraw,                  METH_OLDARGS},
-	{"zfunction", gl_zfunction,          METH_OLDARGS},
-	{"zsource", gl_zsource,              METH_OLDARGS},
-	{"zwritemask", gl_zwritemask,        METH_OLDARGS},
-	{"v2d", gl_v2d,                      METH_OLDARGS},
-	{"v3d", gl_v3d,                      METH_OLDARGS},
-	{"v4d", gl_v4d,                      METH_OLDARGS},
-	{"pixmode", gl_pixmode,              METH_OLDARGS},
-	{"qgetfd", gl_qgetfd,                METH_OLDARGS},
-	{"dither", gl_dither,                METH_OLDARGS},
-	{NULL, NULL} /* Sentinel */
-};
-
-void
-initgl(void)
-{
-	(void) Py_InitModule("gl", gl_methods);
-}

Deleted: /python/branches/p3yk-noslice/Modules/imageop.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/imageop.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,785 +0,0 @@
-
-/* imageopmodule - Various operations on pictures */
-
-#ifdef sun
-#define signed
-#endif
-
-#include "Python.h"
-
-#if SIZEOF_INT == 4
-typedef int Py_Int32;
-typedef unsigned int Py_UInt32;
-#else
-#if SIZEOF_LONG == 4
-typedef long Py_Int32;
-typedef unsigned long Py_UInt32;
-#else
-#error "No 4-byte integral type"
-#endif
-#endif
-
-#define CHARP(cp, xmax, x, y) ((char *)(cp+y*xmax+x))
-#define SHORTP(cp, xmax, x, y) ((short *)(cp+2*(y*xmax+x)))
-#define LONGP(cp, xmax, x, y) ((Py_Int32 *)(cp+4*(y*xmax+x)))
-
-static PyObject *ImageopError;
-static PyObject *ImageopDict;
-
-/* If this function returns true (the default if anything goes wrong), we're
-   behaving in a backward-compatible way with respect to how multi-byte pixels
-   are stored in the strings.  The code in this module was originally written
-   for an SGI which is a big-endian system, and so the old code assumed that
-   4-byte integers hold the R, G, and B values in a particular order.
-   However, on little-endian systems the order is reversed, and so not
-   actually compatible with what gl.lrectwrite and imgfile expect.
-   (gl.lrectwrite and imgfile are also SGI-specific, however, it is
-   conceivable that the data handled here comes from or goes to an SGI or that
-   it is otherwise used in the expectation that the byte order in the strings
-   is as specified.)
-
-   The function returns the value of the module variable
-   "backward_compatible", or 1 if the variable does not exist or is not an
-   int.
- */
-
-static int
-imageop_backward_compatible(void)
-{
-	static PyObject *bcos;
-	PyObject *bco;
-	long rc;
-
-	if (ImageopDict == NULL) /* "cannot happen" */
-		return 1;
-	if (bcos == NULL) {
-		/* cache string object for future use */
-		bcos = PyString_FromString("backward_compatible");
-		if (bcos == NULL)
-			return 1;
-	}
-	bco = PyDict_GetItem(ImageopDict, bcos);
-	if (bco == NULL)
-		return 1;
-	if (!PyInt_Check(bco))
-		return 1;
-	rc = PyInt_AsLong(bco);
-	if (PyErr_Occurred()) {
-		/* not an integer, or too large, or something */
-		PyErr_Clear();
-		rc = 1;
-	}
-	return rc != 0;		/* convert to values 0, 1 */
-}
-
-static PyObject *
-imageop_crop(PyObject *self, PyObject *args)
-{
-	char *cp, *ncp;
-	short *nsp;
-	Py_Int32 *nlp;
-	int len, size, x, y, newx1, newx2, newy1, newy2;
-	int ix, iy, xstep, ystep;
-	PyObject *rv;
-
-	if ( !PyArg_ParseTuple(args, "s#iiiiiii", &cp, &len, &size, &x, &y,
-			  &newx1, &newy1, &newx2, &newy2) )
-		return 0;
-    
-	if ( size != 1 && size != 2 && size != 4 ) {
-		PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
-		return 0;
-	}
-	if ( len != size*x*y ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-	xstep = (newx1 < newx2)? 1 : -1;
-	ystep = (newy1 < newy2)? 1 : -1;
-    
-	rv = PyString_FromStringAndSize(NULL,
-			     (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size);
-	if ( rv == 0 )
-		return 0;
-	ncp = (char *)PyString_AsString(rv);
-	nsp = (short *)ncp;
-	nlp = (Py_Int32 *)ncp;
-	newy2 += ystep;
-	newx2 += xstep;
-	for( iy = newy1; iy != newy2; iy+=ystep ) {
-		for ( ix = newx1; ix != newx2; ix+=xstep ) {
-			if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) {
-				if ( size == 1 )
-					*ncp++ = 0;
-				else
-					*nlp++ = 0;
-			} else {
-				if ( size == 1 )
-					*ncp++ = *CHARP(cp, x, ix, iy);
-				else if ( size == 2 )
-					*nsp++ = *SHORTP(cp, x, ix, iy);
-				else
-					*nlp++ = *LONGP(cp, x, ix, iy);
-			}
-		}
-	}
-	return rv;
-}
- 
-static PyObject *
-imageop_scale(PyObject *self, PyObject *args)
-{
-	char *cp, *ncp;
-	short *nsp;
-	Py_Int32 *nlp;
-	int len, size, x, y, newx, newy;
-	int ix, iy;
-	int oix, oiy;
-	PyObject *rv;
-
-	if ( !PyArg_ParseTuple(args, "s#iiiii",
-			  &cp, &len, &size, &x, &y, &newx, &newy) )
-		return 0;
-    
-	if ( size != 1 && size != 2 && size != 4 ) {
-		PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
-		return 0;
-	}
-	if ( len != size*x*y ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, newx*newy*size);
-	if ( rv == 0 )
-		return 0;
-	ncp = (char *)PyString_AsString(rv);
-	nsp = (short *)ncp;
-	nlp = (Py_Int32 *)ncp;
-	for( iy = 0; iy < newy; iy++ ) {
-		for ( ix = 0; ix < newx; ix++ ) {
-			oix = ix * x / newx;
-			oiy = iy * y / newy;
-			if ( size == 1 )
-				*ncp++ = *CHARP(cp, x, oix, oiy);
-			else if ( size == 2 )
-				*nsp++ = *SHORTP(cp, x, oix, oiy);
-			else
-				*nlp++ = *LONGP(cp, x, oix, oiy);
-		}
-	}
-	return rv;
-}
-
-/* Note: this routine can use a bit of optimizing */
-
-static PyObject *
-imageop_tovideo(PyObject *self, PyObject *args)
-{
-	int maxx, maxy, x, y, len;
-	int i;
-	unsigned char *cp, *ncp;
-	int width;
-	PyObject *rv;
-   
-    
-	if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &width, &maxx, &maxy) )
-		return 0;
-
-	if ( width != 1 && width != 4 ) {
-		PyErr_SetString(ImageopError, "Size should be 1 or 4");
-		return 0;
-	}
-	if ( maxx*maxy*width != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, len);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	if ( width == 1 ) {
-		memcpy(ncp, cp, maxx);		/* Copy first line */
-		ncp += maxx;
-		for (y=1; y<maxy; y++) {	/* Interpolate other lines */
-			for(x=0; x<maxx; x++) {
-				i = y*maxx + x;
-				*ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1;
-			}
-		}
-	} else {
-		memcpy(ncp, cp, maxx*4);		/* Copy first line */
-		ncp += maxx*4;
-		for (y=1; y<maxy; y++) {	/* Interpolate other lines */
-			for(x=0; x<maxx; x++) {
-				i = (y*maxx + x)*4 + 1;
-				*ncp++ = 0;	/* Skip alfa comp */
-				*ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
-				i++;
-				*ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
-				i++;
-				*ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
-			}
-		}
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_grey2mono(PyObject *self, PyObject *args)
-{
-	int tres, x, y, len;
-	unsigned char *cp, *ncp;
-	unsigned char ovalue;
-	PyObject *rv;
-	int i, bit;
-   
-    
-	if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &x, &y, &tres) )
-		return 0;
-
-	if ( x*y != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, (len+7)/8);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	bit = 0x80;
-	ovalue = 0;
-	for ( i=0; i < len; i++ ) {
-		if ( (int)cp[i] > tres )
-			ovalue |= bit;
-		bit >>= 1;
-		if ( bit == 0 ) {
-			*ncp++ = ovalue;
-			bit = 0x80;
-			ovalue = 0;
-		}
-	}
-	if ( bit != 0x80 )
-		*ncp++ = ovalue;
-	return rv;
-}
-
-static PyObject *
-imageop_grey2grey4(PyObject *self, PyObject *args)
-{
-	int x, y, len;
-	unsigned char *cp, *ncp;
-	unsigned char ovalue;
-	PyObject *rv;
-	int i;
-	int pos;
-   
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	if ( x*y != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, (len+1)/2);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-	pos = 0;
-	ovalue = 0;
-	for ( i=0; i < len; i++ ) {
-		ovalue |= ((int)cp[i] & 0xf0) >> pos;
-		pos += 4;
-		if ( pos == 8 ) {
-			*ncp++ = ovalue;
-			ovalue = 0;
-			pos = 0;
-		}
-	}
-	if ( pos != 0 )
-		*ncp++ = ovalue;
-	return rv;
-}
-
-static PyObject *
-imageop_grey2grey2(PyObject *self, PyObject *args)
-{
-	int x, y, len;
-	unsigned char *cp, *ncp;
-	unsigned char ovalue;
-	PyObject *rv;
-	int i;
-	int pos;
-   
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	if ( x*y != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, (len+3)/4);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-	pos = 0;
-	ovalue = 0;
-	for ( i=0; i < len; i++ ) {
-		ovalue |= ((int)cp[i] & 0xc0) >> pos;
-		pos += 2;
-		if ( pos == 8 ) {
-			*ncp++ = ovalue;
-			ovalue = 0;
-			pos = 0;
-		}
-	}
-	if ( pos != 0 )
-		*ncp++ = ovalue;
-	return rv;
-}
-
-static PyObject *
-imageop_dither2mono(PyObject *self, PyObject *args)
-{
-	int sum, x, y, len;
-	unsigned char *cp, *ncp;
-	unsigned char ovalue;
-	PyObject *rv;
-	int i, bit;
-   
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	if ( x*y != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, (len+7)/8);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	bit = 0x80;
-	ovalue = 0;
-	sum = 0;
-	for ( i=0; i < len; i++ ) {
-		sum += cp[i];
-		if ( sum >= 256 ) {
-			sum -= 256;
-			ovalue |= bit;
-		}
-		bit >>= 1;
-		if ( bit == 0 ) {
-			*ncp++ = ovalue;
-			bit = 0x80;
-			ovalue = 0;
-		}
-	}
-	if ( bit != 0x80 )
-		*ncp++ = ovalue;
-	return rv;
-}
-
-static PyObject *
-imageop_dither2grey2(PyObject *self, PyObject *args)
-{
-	int x, y, len;
-	unsigned char *cp, *ncp;
-	unsigned char ovalue;
-	PyObject *rv;
-	int i;
-	int pos;
-	int sum = 0, nvalue;
-   
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	if ( x*y != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, (len+3)/4);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-	pos = 1;
-	ovalue = 0;
-	for ( i=0; i < len; i++ ) {
-		sum += cp[i];
-		nvalue = sum & 0x180;
-		sum -= nvalue;
-		ovalue |= nvalue >> pos;
-		pos += 2;
-		if ( pos == 9 ) {
-			*ncp++ = ovalue;
-			ovalue = 0;
-			pos = 1;
-		}
-	}
-	if ( pos != 0 )
-		*ncp++ = ovalue;
-	return rv;
-}
-
-static PyObject *
-imageop_mono2grey(PyObject *self, PyObject *args)
-{
-	int v0, v1, x, y, len, nlen;
-	unsigned char *cp, *ncp;
-	PyObject *rv;
-	int i, bit;
-    
-	if ( !PyArg_ParseTuple(args, "s#iiii", &cp, &len, &x, &y, &v0, &v1) )
-		return 0;
-
-	nlen = x*y;
-	if ( (nlen+7)/8 != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	bit = 0x80;
-	for ( i=0; i < nlen; i++ ) {
-		if ( *cp & bit )
-			*ncp++ = v1;
-		else
-			*ncp++ = v0;
-		bit >>= 1;
-		if ( bit == 0 ) {
-			bit = 0x80;
-			cp++;
-		}
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_grey22grey(PyObject *self, PyObject *args)
-{
-	int x, y, len, nlen;
-	unsigned char *cp, *ncp;
-	PyObject *rv;
-	int i, pos, value = 0, nvalue;
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	nlen = x*y;
-	if ( (nlen+3)/4 != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	pos = 0;
-	for ( i=0; i < nlen; i++ ) {
-		if ( pos == 0 ) {
-			value = *cp++;
-			pos = 8;
-		}
-		pos -= 2;
-		nvalue = (value >> pos) & 0x03;
-		*ncp++ = nvalue | (nvalue << 2) |
-			 (nvalue << 4) | (nvalue << 6);
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_grey42grey(PyObject *self, PyObject *args)
-{
-	int x, y, len, nlen;
-	unsigned char *cp, *ncp;
-	PyObject *rv;
-	int i, pos, value = 0, nvalue;
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	nlen = x*y;
-	if ( (nlen+1)/2 != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	pos = 0;
-	for ( i=0; i < nlen; i++ ) {
-		if ( pos == 0 ) {
-			value = *cp++;
-			pos = 8;
-		}
-		pos -= 4;
-		nvalue = (value >> pos) & 0x0f;
-		*ncp++ = nvalue | (nvalue << 4);
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_rgb2rgb8(PyObject *self, PyObject *args)
-{
-	int x, y, len, nlen;
-	unsigned char *cp;
-	unsigned char *ncp;
-	PyObject *rv;
-	int i, r, g, b;
-	int backward_compatible = imageop_backward_compatible();
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	nlen = x*y;
-	if ( nlen*4 != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	for ( i=0; i < nlen; i++ ) {
-		/* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
-		if (backward_compatible) {
-			Py_UInt32 value = * (Py_UInt32 *) cp;
-			cp += 4;
-			r = (int) ((value & 0xff) / 255. * 7. + .5);
-			g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
-			b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
-		} else {
-			cp++;		/* skip alpha channel */
-			b = (int) (*cp++ / 255. * 3. + .5);
-			g = (int) (*cp++ / 255. * 7. + .5);
-			r = (int) (*cp++ / 255. * 7. + .5);
-		}
-		*ncp++ = (unsigned char)((r<<5) | (b<<3) | g);
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_rgb82rgb(PyObject *self, PyObject *args)
-{
-	int x, y, len, nlen;
-	unsigned char *cp;
-	unsigned char *ncp;
-	PyObject *rv;
-	int i, r, g, b;
-	unsigned char value;
-	int backward_compatible = imageop_backward_compatible();
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	nlen = x*y;
-	if ( nlen != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen*4);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	for ( i=0; i < nlen; i++ ) {
-		/* Bits in source: RRRBBGGG
-		** Red and Green are multiplied by 36.5, Blue by 85
-		*/
-		value = *cp++;
-		r = (value >> 5) & 7;
-		g = (value     ) & 7;
-		b = (value >> 3) & 3;
-		r = (r<<5) | (r<<3) | (r>>1);
-		g = (g<<5) | (g<<3) | (g>>1);
-		b = (b<<6) | (b<<4) | (b<<2) | b;
-		if (backward_compatible) {
-			Py_UInt32 nvalue = r | (g<<8) | (b<<16);
-			* (Py_UInt32 *) ncp = nvalue;
-			ncp += 4;
-		} else {
-			*ncp++ = 0;
-			*ncp++ = b;
-			*ncp++ = g;
-			*ncp++ = r;
-		}
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_rgb2grey(PyObject *self, PyObject *args)
-{
-	int x, y, len, nlen;
-	unsigned char *cp;
-	unsigned char *ncp;
-	PyObject *rv;
-	int i, r, g, b;
-	int nvalue;
-	int backward_compatible = imageop_backward_compatible();
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	nlen = x*y;
-	if ( nlen*4 != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	for ( i=0; i < nlen; i++ ) {
-		if (backward_compatible) {
-			Py_UInt32 value = * (Py_UInt32 *) cp;
-			cp += 4;
-			r = (int) ((value & 0xff) / 255. * 7. + .5);
-			g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
-			b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
-		} else {
-			cp++;		/* skip alpha channel */
-			b = *cp++;
-			g = *cp++;
-			r = *cp++;
-		}
-		nvalue = (int)(0.30*r + 0.59*g + 0.11*b);
-		if ( nvalue > 255 ) nvalue = 255;
-		*ncp++ = (unsigned char)nvalue;
-	}
-	return rv;
-}
-
-static PyObject *
-imageop_grey2rgb(PyObject *self, PyObject *args)
-{
-	int x, y, len, nlen;
-	unsigned char *cp;
-	unsigned char *ncp;
-	PyObject *rv;
-	int i;
-	unsigned char value;
-	int backward_compatible = imageop_backward_compatible();
-    
-	if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
-		return 0;
-
-	nlen = x*y;
-	if ( nlen != len ) {
-		PyErr_SetString(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = PyString_FromStringAndSize(NULL, nlen*4);
-	if ( rv == 0 )
-		return 0;
-	ncp = (unsigned char *)PyString_AsString(rv);
-
-	for ( i=0; i < nlen; i++ ) {
-		value = *cp++;
-		if (backward_compatible) {
-			* (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
-			ncp += 4;
-		} else {
-			*ncp++ = 0;
-			*ncp++ = value;
-			*ncp++ = value;
-			*ncp++ = value;
-		}
-	}
-	return rv;
-}
-
-/*
-static object *
-imageop_mul(object *self, object *args)
-{
-	char *cp, *ncp;
-	int len, size, x, y;
-	object *rv;
-	int i;
-
-	if ( !getargs(args, "(s#iii)", &cp, &len, &size, &x, &y) )
-		return 0;
-    
-	if ( size != 1 && size != 4 ) {
-		err_setstr(ImageopError, "Size should be 1 or 4");
-		return 0;
-	}
-	if ( len != size*x*y ) {
-		err_setstr(ImageopError, "String has incorrect length");
-		return 0;
-	}
-    
-	rv = newsizedstringobject(NULL, XXXX);
-	if ( rv == 0 )
-		return 0;
-	ncp = (char *)getstringvalue(rv);
-    
-    
-	for ( i=0; i < len; i += size ) {
-	}
-	return rv;
-}
-*/
-
-static PyMethodDef imageop_methods[] = {
-	{ "crop",		imageop_crop, METH_VARARGS },
-	{ "scale",		imageop_scale, METH_VARARGS },
-	{ "grey2mono",	        imageop_grey2mono, METH_VARARGS },
-	{ "grey2grey2",	        imageop_grey2grey2, METH_VARARGS },
-	{ "grey2grey4",	        imageop_grey2grey4, METH_VARARGS },
-	{ "dither2mono",	imageop_dither2mono, METH_VARARGS },
-	{ "dither2grey2",	imageop_dither2grey2, METH_VARARGS },
-	{ "mono2grey",	        imageop_mono2grey, METH_VARARGS },
-	{ "grey22grey",	        imageop_grey22grey, METH_VARARGS },
-	{ "grey42grey",	        imageop_grey42grey, METH_VARARGS },
-	{ "tovideo",	        imageop_tovideo, METH_VARARGS },
-	{ "rgb2rgb8",	        imageop_rgb2rgb8, METH_VARARGS },
-	{ "rgb82rgb",	        imageop_rgb82rgb, METH_VARARGS },
-	{ "rgb2grey",	        imageop_rgb2grey, METH_VARARGS },
-	{ "grey2rgb",	        imageop_grey2rgb, METH_VARARGS },
-	{ 0,                    0 }
-};
-
-
-PyMODINIT_FUNC
-initimageop(void)
-{
-	PyObject *m;
-	m = Py_InitModule("imageop", imageop_methods);
-	if (m == NULL)
-		return;
-	ImageopDict = PyModule_GetDict(m);
-	ImageopError = PyErr_NewException("imageop.error", NULL, NULL);
-	if (ImageopError != NULL)
-		PyDict_SetItemString(ImageopDict, "error", ImageopError);
-}

Deleted: /python/branches/p3yk-noslice/Modules/imgfile.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/imgfile.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,504 +0,0 @@
-
-/* IMGFILE module - Interface to sgi libimage */
-
-/* XXX This module should be done better at some point. It should return
-** an object of image file class, and have routines to manipulate these
-** image files in a neater way (so you can get rgb images off a greyscale
-** file, for instance, or do a straight display without having to get the
-** image bits into python, etc).
-**
-** Warning: this module is very non-reentrant (esp. the readscaled stuff)
-*/
-
-#include "Python.h"
-
-#include <gl/image.h>
-
-#include "/usr/people/4Dgifts/iristools/include/izoom.h"
-
-/* Bunch of missing extern decls; keep gcc -Wall happy... */
-extern void i_seterror();
-extern void iclose();
-extern void filterzoom();
-extern void putrow();
-extern void getrow();
-
-static PyObject * ImgfileError; /* Exception we raise for various trouble */
-
-static int top_to_bottom;	/* True if we want top-to-bottom images */
-
-/* The image library does not always call the error hander :-(,
-   therefore we have a global variable indicating that it was called.
-   It is cleared by imgfile_open(). */
-
-static int error_called;
-
-
-/* The error handler */
-
-static void
-imgfile_error(char *str)
-{
-	PyErr_SetString(ImgfileError, str);
-	error_called = 1;
-	return;	/* To imglib, which will return a failure indicator */
-}
-
-
-/* Open an image file and return a pointer to it.
-   Make sure we raise an exception if we fail. */
-
-static IMAGE *
-imgfile_open(char *fname)
-{
-	IMAGE *image;
-	i_seterror(imgfile_error);
-	error_called = 0;
-	errno = 0;
-	if ( (image = iopen(fname, "r")) == NULL ) {
-		/* Error may already be set by imgfile_error */
-		if ( !error_called ) {
-			if (errno)
-				PyErr_SetFromErrno(ImgfileError);
-			else
-				PyErr_SetString(ImgfileError,
-						"Can't open image file");
-		}
-		return NULL;
-	}
-	return image;
-}
-
-static PyObject *
-imgfile_ttob(PyObject *self, PyObject *args)
-{
-	int newval;
-	PyObject *rv;
-    
-	if (!PyArg_ParseTuple(args, "i:ttob", &newval))
-		return NULL;
-	rv = PyInt_FromLong(top_to_bottom);
-	top_to_bottom = newval;
-	return rv;
-}
-
-static PyObject *
-imgfile_read(PyObject *self, PyObject *args)
-{
-	char *fname;
-	PyObject *rv;
-	int xsize, ysize, zsize;
-	char *cdatap;
-	long *idatap;
-	static short rs[8192], gs[8192], bs[8192];
-	int x, y;
-	IMAGE *image;
-	int yfirst, ylast, ystep;
-
-	if ( !PyArg_ParseTuple(args, "s:read", &fname) )
-		return NULL;
-    
-	if ( (image = imgfile_open(fname)) == NULL )
-		return NULL;
-    
-	if ( image->colormap != CM_NORMAL ) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can only handle CM_NORMAL images");
-		return NULL;
-	}
-	if ( BPP(image->type) != 1 ) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can't handle imgfiles with bpp!=1");
-		return NULL;
-	}
-	xsize = image->xsize;
-	ysize = image->ysize;
-	zsize = image->zsize;
-	if ( zsize != 1 && zsize != 3) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can only handle 1 or 3 byte pixels");
-		return NULL;
-	}
-	if ( xsize > 8192 ) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can't handle image with > 8192 columns");
-		return NULL;
-	}
-
-	if ( zsize == 3 ) zsize = 4;
-	rv = PyString_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
-	if ( rv == NULL ) {
-		iclose(image);
-		return NULL;
-	}
-	cdatap = PyString_AsString(rv);
-	idatap = (long *)cdatap;
-
-	if (top_to_bottom) {
-		yfirst = ysize-1;
-		ylast = -1;
-		ystep = -1;
-	} else {
-		yfirst = 0;
-		ylast = ysize;
-		ystep = 1;
-	}
-	for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
-		if ( zsize == 1 ) {
-			getrow(image, rs, y, 0);
-			for(x=0; x<xsize; x++ )
-				*cdatap++ = rs[x];
-		} else {
-			getrow(image, rs, y, 0);
-			getrow(image, gs, y, 1);
-			getrow(image, bs, y, 2);
-			for(x=0; x<xsize; x++ )
-				*idatap++ = (rs[x] & 0xff)  |
-					((gs[x] & 0xff)<<8) |
-					((bs[x] & 0xff)<<16);
-		}
-	}
-	iclose(image);
-	if ( error_called ) {
-		Py_DECREF(rv);
-		return NULL;
-	}
-	return rv;
-}
-
-static IMAGE *glob_image;
-static long *glob_datap;
-static int glob_width, glob_z, glob_ysize;
-
-static void
-xs_get(short *buf, int y)
-{
-	if (top_to_bottom)
-		getrow(glob_image, buf, (glob_ysize-1-y), glob_z);
-	else
-		getrow(glob_image, buf, y, glob_z);
-}
-
-static void
-xs_put_c(short *buf, int y)
-{
-	char *datap = (char *)glob_datap + y*glob_width;
-	int width = glob_width;
-
-	while ( width-- )
-		*datap++ = (*buf++) & 0xff;
-}
-
-static void
-xs_put_0(short *buf, int y)
-{
-	long *datap = glob_datap + y*glob_width;
-	int width = glob_width;
-
-	while ( width-- )
-		*datap++ = (*buf++) & 0xff;
-}
-static void
-xs_put_12(short *buf, int y)
-{
-	long *datap = glob_datap + y*glob_width;
-	int width = glob_width;
-
-	while ( width-- )
-		*datap++ |= ((*buf++) & 0xff) << (glob_z*8);
-}
-
-static void
-xscale(IMAGE *image, int xsize, int ysize, int zsize,
-       long *datap, int xnew, int ynew, int fmode, double blur)
-{
-	glob_image = image;
-	glob_datap = datap;
-	glob_width = xnew;
-	glob_ysize = ysize;
-	if ( zsize == 1 ) {
-		glob_z = 0;
-		filterzoom(xs_get, xs_put_c, xsize, ysize,
-			   xnew, ynew, fmode, blur);
-	} else {
-		glob_z = 0;
-		filterzoom(xs_get, xs_put_0, xsize, ysize,
-			   xnew, ynew, fmode, blur);
-		glob_z = 1;
-		filterzoom(xs_get, xs_put_12, xsize, ysize,
-			   xnew, ynew, fmode, blur);
-		glob_z = 2;
-		filterzoom(xs_get, xs_put_12, xsize, ysize,
-			   xnew, ynew, fmode, blur);
-	}
-}
-
-
-static PyObject *
-imgfile_readscaled(PyObject *self, PyObject *args)
-{
-	char *fname;
-	PyObject *rv;
-	int xsize, ysize, zsize;
-	char *cdatap;
-	long *idatap;
-	static short rs[8192], gs[8192], bs[8192];
-	int x, y;
-	int xwtd, ywtd, xorig, yorig;
-	float xfac, yfac;
-	IMAGE *image;
-	char *filter;
-	double blur = 1.0;
-	int extended;
-	int fmode = 0;
-	int yfirst, ylast, ystep;
-
-	/*
-	** Parse args. Funny, since arg 4 and 5 are optional
-	** (filter name and blur factor). Also, 4 or 5 arguments indicates
-	** extended scale algorithm in stead of simple-minded pixel drop/dup.
-	*/
-	extended = PyTuple_Size(args) >= 4;
-	if ( !PyArg_ParseTuple(args, "sii|sd",
-			       &fname, &xwtd, &ywtd, &filter, &blur) )
-		return NULL;
-
-	/*
-	** Check parameters, open file and check type, rows, etc.
-	*/
-	if ( extended ) {
-		if ( strcmp(filter, "impulse") == 0 )
-			fmode = IMPULSE;
-		else if ( strcmp( filter, "box") == 0 )
-			fmode = BOX;
-		else if ( strcmp( filter, "triangle") == 0 )
-			fmode = TRIANGLE;
-		else if ( strcmp( filter, "quadratic") == 0 )
-			fmode = QUADRATIC;
-		else if ( strcmp( filter, "gaussian") == 0 )
-			fmode = GAUSSIAN;
-		else {
-			PyErr_SetString(ImgfileError, "Unknown filter type");
-			return NULL;
-		}
-	}
-    
-	if ( (image = imgfile_open(fname)) == NULL )
-		return NULL;
-    
-	if ( image->colormap != CM_NORMAL ) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can only handle CM_NORMAL images");
-		return NULL;
-	}
-	if ( BPP(image->type) != 1 ) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can't handle imgfiles with bpp!=1");
-		return NULL;
-	}
-	xsize = image->xsize;
-	ysize = image->ysize;
-	zsize = image->zsize;
-	if ( zsize != 1 && zsize != 3) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can only handle 1 or 3 byte pixels");
-		return NULL;
-	}
-	if ( xsize > 8192 ) {
-		iclose(image);
-		PyErr_SetString(ImgfileError,
-				"Can't handle image with > 8192 columns");
-		return NULL;
-	}
-
-	if ( zsize == 3 ) zsize = 4;
-	rv = PyString_FromStringAndSize(NULL, xwtd*ywtd*zsize);
-	if ( rv == NULL ) {
-		iclose(image);
-		return NULL;
-	}
-	PyFPE_START_PROTECT("readscaled", return 0)
-	xfac = (float)xsize/(float)xwtd;
-	yfac = (float)ysize/(float)ywtd;
-	PyFPE_END_PROTECT(yfac)
-	cdatap = PyString_AsString(rv);
-	idatap = (long *)cdatap;
-
-	if ( extended ) {
-		xscale(image, xsize, ysize, zsize,
-		       idatap, xwtd, ywtd, fmode, blur);
-	} else {
-		if (top_to_bottom) {
-			yfirst = ywtd-1;
-			ylast = -1;
-			ystep = -1;
-		} else {
-			yfirst = 0;
-			ylast = ywtd;
-			ystep = 1;
-		}
-		for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
-			yorig = (int)(y*yfac);
-			if ( zsize == 1 ) {
-				getrow(image, rs, yorig, 0);
-				for(x=0; x<xwtd; x++ ) {
-					*cdatap++ = rs[(int)(x*xfac)];	
-				}
-			} else {
-				getrow(image, rs, yorig, 0);
-				getrow(image, gs, yorig, 1);
-				getrow(image, bs, yorig, 2);
-				for(x=0; x<xwtd; x++ ) {
-					xorig = (int)(x*xfac);
-					*idatap++ = (rs[xorig] & 0xff)  |
-						((gs[xorig] & 0xff)<<8) |
-						((bs[xorig] & 0xff)<<16);
-				}
-			}
-		}
-	}
-	iclose(image);
-	if ( error_called ) {
-		Py_DECREF(rv);
-		return NULL;
-	}
-	return rv;
-}
-
-static PyObject *
-imgfile_getsizes(PyObject *self, PyObject *args)
-{
-	char *fname;
-	PyObject *rv;
-	IMAGE *image;
-    
-	if ( !PyArg_ParseTuple(args, "s:getsizes", &fname) )
-		return NULL;
-    
-	if ( (image = imgfile_open(fname)) == NULL )
-		return NULL;
-	rv = Py_BuildValue("(iii)", image->xsize, image->ysize, image->zsize);
-	iclose(image);
-	return rv;
-}
-
-static PyObject *
-imgfile_write(PyObject *self, PyObject *args)
-{
-	IMAGE *image;
-	char *fname;
-	int xsize, ysize, zsize, len;
-	char *cdatap;
-	long *idatap;
-	short rs[8192], gs[8192], bs[8192];
-	short r, g, b;
-	long rgb;
-	int x, y;
-	int yfirst, ylast, ystep;
-
-
-	if ( !PyArg_ParseTuple(args, "ss#iii:write",
-			  &fname, &cdatap, &len, &xsize, &ysize, &zsize) )
-		return NULL;
-    
-	if ( zsize != 1 && zsize != 3 ) {
-		PyErr_SetString(ImgfileError,
-				"Can only handle 1 or 3 byte pixels");
-		return NULL;
-	}
-	if ( len != xsize * ysize * (zsize == 1 ? 1 : 4) ) {
-		PyErr_SetString(ImgfileError, "Data does not match sizes");
-		return NULL;
-	}
-	if ( xsize > 8192 ) {
-		PyErr_SetString(ImgfileError,
-				"Can't handle image with > 8192 columns");
-		return NULL;
-	}
-
-	error_called = 0;
-	errno = 0;
-	image =iopen(fname, "w", RLE(1), 3, xsize, ysize, zsize);
-	if ( image == 0 ) {
-		if ( ! error_called ) {
-			if (errno)
-				PyErr_SetFromErrno(ImgfileError);
-			else
-				PyErr_SetString(ImgfileError,
-						"Can't create image file");
-		}
-		return NULL;
-	}
-
-	idatap = (long *)cdatap;
-    
-	if (top_to_bottom) {
-		yfirst = ysize-1;
-		ylast = -1;
-		ystep = -1;
-	} else {
-		yfirst = 0;
-		ylast = ysize;
-		ystep = 1;
-	}
-	for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
-		if ( zsize == 1 ) {
-			for( x=0; x<xsize; x++ )
-				rs[x] = *cdatap++;
-			putrow(image, rs, y, 0);
-		} else {
-			for( x=0; x<xsize; x++ ) {
-				rgb = *idatap++;
-				r = rgb & 0xff;
-				g = (rgb >> 8 ) & 0xff;
-				b = (rgb >> 16 ) & 0xff;
-				rs[x] = r;
-				gs[x] = g;
-				bs[x] = b;
-			}
-			putrow(image, rs, y, 0);
-			putrow(image, gs, y, 1);
-			putrow(image, bs, y, 2);
-		}
-	}
-	iclose(image);
-	if ( error_called )
-		return NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-    
-}
-
-
-static PyMethodDef imgfile_methods[] = {
-	{ "getsizes",	imgfile_getsizes, METH_VARARGS },
-	{ "read",	imgfile_read, METH_VARARGS },
-	{ "readscaled",	imgfile_readscaled, METH_VARARGS},
-	{ "write",	imgfile_write, METH_VARARGS },
-	{ "ttob",	imgfile_ttob, METH_VARARGS },
-	{ NULL,		NULL } /* Sentinel */
-};
-
-
-void
-initimgfile(void)
-{
-	PyObject *m, *d;
-	m = Py_InitModule("imgfile", imgfile_methods);
-	if (m == NULL)
-		return;
-	d = PyModule_GetDict(m);
-	ImgfileError = PyErr_NewException("imgfile.error", NULL, NULL);
-	if (ImgfileError != NULL)
-		PyDict_SetItemString(d, "error", ImgfileError);
-}
-
-
-

Modified: python/branches/p3yk-noslice/Modules/itertoolsmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/itertoolsmodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/itertoolsmodule.c	Wed Jul 11 15:40:56 2007
@@ -1701,7 +1701,7 @@
 PyDoc_STRVAR(chain_doc,
 "chain(*iterables) --> chain object\n\
 \n\
-Return a chain object whose .next() method returns elements from the\n\
+Return a chain object whose .__next__() method returns elements from the\n\
 first iterable until it is exhausted, then elements from the next\n\
 iterable, until all of the iterables are exhausted.");
 
@@ -2073,9 +2073,9 @@
 static PyObject *
 count_next(countobject *lz)
 {
-        if (lz->cnt == LONG_MAX) {
+        if (lz->cnt == PY_SSIZE_T_MAX) {
                 PyErr_SetString(PyExc_OverflowError,
-                        "cannot count beyond LONG_MAX");                
+                        "cannot count beyond PY_SSIZE_T_MAX");                
                 return NULL;         
         }
 	return PyInt_FromSsize_t(lz->cnt++);
@@ -2090,7 +2090,7 @@
 PyDoc_STRVAR(count_doc,
 "count([firstval]) --> count object\n\
 \n\
-Return a count object whose .next() method returns consecutive\n\
+Return a count object whose .__next__() method returns consecutive\n\
 integers starting from zero or, if specified, from firstval.");
 
 static PyTypeObject count_type = {
@@ -2272,8 +2272,8 @@
 PyDoc_STRVAR(izip_doc,
 "izip(iter1 [,iter2 [...]]) --> izip object\n\
 \n\
-Return a izip object whose .next() method returns a tuple where\n\
-the i-th element comes from the i-th iterable argument.  The .next()\n\
+Return a izip object whose .__next__() method returns a tuple where\n\
+the i-th element comes from the i-th iterable argument.  The .__next__()\n\
 method continues until the shortest iterable in the argument sequence\n\
 is exhausted and then it raises StopIteration.  Works like the zip()\n\
 function but consumes less memory by returning an iterator instead of\n\
@@ -2648,8 +2648,8 @@
 PyDoc_STRVAR(izip_longest_doc,
 "izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\
 \n\
-Return an izip_longest object whose .next() method returns a tuple where\n\
-the i-th element comes from the i-th iterable argument.  The .next()\n\
+Return an izip_longest object whose .__next__() method returns a tuple where\n\
+the i-th element comes from the i-th iterable argument.  The .__next__()\n\
 method continues until the longest iterable in the argument sequence\n\
 is exhausted and then it raises StopIteration.  When the shorter iterables\n\
 are exhausted, the fillvalue is substituted in their place.  The fillvalue\n\

Modified: python/branches/p3yk-noslice/Modules/main.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/main.c	(original)
+++ python/branches/p3yk-noslice/Modules/main.c	Wed Jul 11 15:40:56 2007
@@ -214,13 +214,11 @@
 	char *module = NULL;
 	FILE *fp = stdin;
 	char *p;
-	int inspect = 0;
 	int unbuffered = 0;
 	int skipfirstline = 0;
 	int stdin_is_interactive = 0;
 	int help = 0;
 	int version = 0;
-	int saw_inspect_flag = 0;
 	int saw_unbuffered_flag = 0;
 	PyCompilerFlags cf;
 
@@ -268,8 +266,7 @@
 			break;
 
 		case 'i':
-			inspect++;
-			saw_inspect_flag = 1;
+			Py_InspectFlag++;
 			Py_InteractiveFlag++;
 			break;
 
@@ -338,9 +335,9 @@
 		return 0;
 	}
 
-	if (!saw_inspect_flag &&
+	if (!Py_InspectFlag &&
 	    (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
-		inspect = 1;
+		Py_InspectFlag = 1;
 	if (!saw_unbuffered_flag &&
 	    (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
 		unbuffered = 1;
@@ -468,7 +465,7 @@
 
 	PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
 
-	if ((inspect || (command == NULL && filename == NULL && module == NULL)) &&
+	if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
 	    isatty(fileno(stdin))) {
 		PyObject *v;
 		v = PyImport_ImportModule("readline");
@@ -487,6 +484,7 @@
 	}
 	else {
 		if (filename == NULL && stdin_is_interactive) {
+			Py_InspectFlag = 0; /* do exit on SystemExit */
 			RunStartupFile(&cf);
 		}
 		/* XXX */
@@ -499,16 +497,18 @@
 	/* Check this environment variable at the end, to give programs the
 	 * opportunity to set it from Python.
 	 */
-	if (!saw_inspect_flag &&
+	if (!Py_InspectFlag &&
 	    (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
 	{
-		inspect = 1;
+		Py_InspectFlag = 1;
 	}
 
-	if (inspect && stdin_is_interactive &&
-	    (filename != NULL || command != NULL || module != NULL))
+	if (Py_InspectFlag && stdin_is_interactive &&
+	    (filename != NULL || command != NULL || module != NULL)) {
+		Py_InspectFlag = 0;
 		/* XXX */
 		sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
+	}
 
 	WaitForThreadShutdown();
 

Deleted: /python/branches/p3yk-noslice/Modules/md5.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/md5.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,381 +0,0 @@
-/*
-  Copyright (C) 1999, 2000, 2002 Aladdin Enterprises.  All rights reserved.
-
-  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.
-
-  L. Peter Deutsch
-  ghost at aladdin.com
-
- */
-/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
-/*
-  Independent implementation of MD5 (RFC 1321).
-
-  This code implements the MD5 Algorithm defined in RFC 1321, whose
-  text is available at
-	http://www.ietf.org/rfc/rfc1321.txt
-  The code is derived from the text of the RFC, including the test suite
-  (section A.5) but excluding the rest of Appendix A.  It does not include
-  any code or documentation that is identified in the RFC as being
-  copyrighted.
-
-  The original and principal author of md5.c is L. Peter Deutsch
-  <ghost at aladdin.com>.  Other authors are noted in the change history
-  that follows (in reverse chronological order):
-
-  2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
-	either statically or dynamically; added missing #include <string.h>
-	in library.
-  2002-03-11 lpd Corrected argument list for main(), and added int return
-	type, in test program and T value program.
-  2002-02-21 lpd Added missing #include <stdio.h> in test program.
-  2000-07-03 lpd Patched to eliminate warnings about "constant is
-	unsigned in ANSI C, signed in traditional"; made test program
-	self-checking.
-  1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
-  1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
-  1999-05-03 lpd Original version.
- */
-
-#include "md5.h"
-#include <string.h>
-
-#undef BYTE_ORDER	/* 1 = big-endian, -1 = little-endian, 0 = unknown */
-#ifdef ARCH_IS_BIG_ENDIAN
-#  define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
-#else
-#  define BYTE_ORDER 0
-#endif
-
-#define T_MASK ((md5_word_t)~0)
-#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
-#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
-#define T3    0x242070db
-#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
-#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
-#define T6    0x4787c62a
-#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
-#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
-#define T9    0x698098d8
-#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
-#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
-#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
-#define T13    0x6b901122
-#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
-#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
-#define T16    0x49b40821
-#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
-#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
-#define T19    0x265e5a51
-#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
-#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
-#define T22    0x02441453
-#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
-#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
-#define T25    0x21e1cde6
-#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
-#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
-#define T28    0x455a14ed
-#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
-#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
-#define T31    0x676f02d9
-#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
-#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
-#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
-#define T35    0x6d9d6122
-#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
-#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
-#define T38    0x4bdecfa9
-#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
-#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
-#define T41    0x289b7ec6
-#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
-#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
-#define T44    0x04881d05
-#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
-#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
-#define T47    0x1fa27cf8
-#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
-#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
-#define T50    0x432aff97
-#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
-#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
-#define T53    0x655b59c3
-#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
-#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
-#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
-#define T57    0x6fa87e4f
-#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
-#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
-#define T60    0x4e0811a1
-#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
-#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
-#define T63    0x2ad7d2bb
-#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
-
-
-static void
-md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
-{
-    md5_word_t
-	a = pms->abcd[0], b = pms->abcd[1],
-	c = pms->abcd[2], d = pms->abcd[3];
-    md5_word_t t;
-#if BYTE_ORDER > 0
-    /* Define storage only for big-endian CPUs. */
-    md5_word_t X[16];
-#else
-    /* Define storage for little-endian or both types of CPUs. */
-    md5_word_t xbuf[16];
-    const md5_word_t *X;
-#endif
-
-    {
-#if BYTE_ORDER == 0
-	/*
-	 * Determine dynamically whether this is a big-endian or
-	 * little-endian machine, since we can use a more efficient
-	 * algorithm on the latter.
-	 */
-	static const int w = 1;
-
-	if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
-#endif
-#if BYTE_ORDER <= 0		/* little-endian */
-	{
-	    /*
-	     * On little-endian machines, we can process properly aligned
-	     * data without copying it.
-	     */
-	    if (!((data - (const md5_byte_t *)0) & 3)) {
-		/* data are properly aligned */
-		X = (const md5_word_t *)data;
-	    } else {
-		/* not aligned */
-		memcpy(xbuf, data, 64);
-		X = xbuf;
-	    }
-	}
-#endif
-#if BYTE_ORDER == 0
-	else			/* dynamic big-endian */
-#endif
-#if BYTE_ORDER >= 0		/* big-endian */
-	{
-	    /*
-	     * On big-endian machines, we must arrange the bytes in the
-	     * right order.
-	     */
-	    const md5_byte_t *xp = data;
-	    int i;
-
-#  if BYTE_ORDER == 0
-	    X = xbuf;		/* (dynamic only) */
-#  else
-#    define xbuf X		/* (static only) */
-#  endif
-	    for (i = 0; i < 16; ++i, xp += 4)
-		xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
-	}
-#endif
-    }
-
-#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
-
-    /* Round 1. */
-    /* Let [abcd k s i] denote the operation
-       a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
-#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + F(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-    /* Do the following 16 operations. */
-    SET(a, b, c, d,  0,  7,  T1);
-    SET(d, a, b, c,  1, 12,  T2);
-    SET(c, d, a, b,  2, 17,  T3);
-    SET(b, c, d, a,  3, 22,  T4);
-    SET(a, b, c, d,  4,  7,  T5);
-    SET(d, a, b, c,  5, 12,  T6);
-    SET(c, d, a, b,  6, 17,  T7);
-    SET(b, c, d, a,  7, 22,  T8);
-    SET(a, b, c, d,  8,  7,  T9);
-    SET(d, a, b, c,  9, 12, T10);
-    SET(c, d, a, b, 10, 17, T11);
-    SET(b, c, d, a, 11, 22, T12);
-    SET(a, b, c, d, 12,  7, T13);
-    SET(d, a, b, c, 13, 12, T14);
-    SET(c, d, a, b, 14, 17, T15);
-    SET(b, c, d, a, 15, 22, T16);
-#undef SET
-
-     /* Round 2. */
-     /* Let [abcd k s i] denote the operation
-          a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
-#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + G(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-     /* Do the following 16 operations. */
-    SET(a, b, c, d,  1,  5, T17);
-    SET(d, a, b, c,  6,  9, T18);
-    SET(c, d, a, b, 11, 14, T19);
-    SET(b, c, d, a,  0, 20, T20);
-    SET(a, b, c, d,  5,  5, T21);
-    SET(d, a, b, c, 10,  9, T22);
-    SET(c, d, a, b, 15, 14, T23);
-    SET(b, c, d, a,  4, 20, T24);
-    SET(a, b, c, d,  9,  5, T25);
-    SET(d, a, b, c, 14,  9, T26);
-    SET(c, d, a, b,  3, 14, T27);
-    SET(b, c, d, a,  8, 20, T28);
-    SET(a, b, c, d, 13,  5, T29);
-    SET(d, a, b, c,  2,  9, T30);
-    SET(c, d, a, b,  7, 14, T31);
-    SET(b, c, d, a, 12, 20, T32);
-#undef SET
-
-     /* Round 3. */
-     /* Let [abcd k s t] denote the operation
-          a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
-#define H(x, y, z) ((x) ^ (y) ^ (z))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + H(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-     /* Do the following 16 operations. */
-    SET(a, b, c, d,  5,  4, T33);
-    SET(d, a, b, c,  8, 11, T34);
-    SET(c, d, a, b, 11, 16, T35);
-    SET(b, c, d, a, 14, 23, T36);
-    SET(a, b, c, d,  1,  4, T37);
-    SET(d, a, b, c,  4, 11, T38);
-    SET(c, d, a, b,  7, 16, T39);
-    SET(b, c, d, a, 10, 23, T40);
-    SET(a, b, c, d, 13,  4, T41);
-    SET(d, a, b, c,  0, 11, T42);
-    SET(c, d, a, b,  3, 16, T43);
-    SET(b, c, d, a,  6, 23, T44);
-    SET(a, b, c, d,  9,  4, T45);
-    SET(d, a, b, c, 12, 11, T46);
-    SET(c, d, a, b, 15, 16, T47);
-    SET(b, c, d, a,  2, 23, T48);
-#undef SET
-
-     /* Round 4. */
-     /* Let [abcd k s t] denote the operation
-          a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
-#define I(x, y, z) ((y) ^ ((x) | ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + I(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-     /* Do the following 16 operations. */
-    SET(a, b, c, d,  0,  6, T49);
-    SET(d, a, b, c,  7, 10, T50);
-    SET(c, d, a, b, 14, 15, T51);
-    SET(b, c, d, a,  5, 21, T52);
-    SET(a, b, c, d, 12,  6, T53);
-    SET(d, a, b, c,  3, 10, T54);
-    SET(c, d, a, b, 10, 15, T55);
-    SET(b, c, d, a,  1, 21, T56);
-    SET(a, b, c, d,  8,  6, T57);
-    SET(d, a, b, c, 15, 10, T58);
-    SET(c, d, a, b,  6, 15, T59);
-    SET(b, c, d, a, 13, 21, T60);
-    SET(a, b, c, d,  4,  6, T61);
-    SET(d, a, b, c, 11, 10, T62);
-    SET(c, d, a, b,  2, 15, T63);
-    SET(b, c, d, a,  9, 21, T64);
-#undef SET
-
-     /* Then perform the following additions. (That is increment each
-        of the four registers by the value it had before this block
-        was started.) */
-    pms->abcd[0] += a;
-    pms->abcd[1] += b;
-    pms->abcd[2] += c;
-    pms->abcd[3] += d;
-}
-
-void
-md5_init(md5_state_t *pms)
-{
-    pms->count[0] = pms->count[1] = 0;
-    pms->abcd[0] = 0x67452301;
-    pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
-    pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
-    pms->abcd[3] = 0x10325476;
-}
-
-void
-md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
-{
-    const md5_byte_t *p = data;
-    int left = nbytes;
-    int offset = (pms->count[0] >> 3) & 63;
-    md5_word_t nbits = (md5_word_t)(nbytes << 3);
-
-    if (nbytes <= 0)
-	return;
-
-    /* Update the message length. */
-    pms->count[1] += nbytes >> 29;
-    pms->count[0] += nbits;
-    if (pms->count[0] < nbits)
-	pms->count[1]++;
-
-    /* Process an initial partial block. */
-    if (offset) {
-	int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
-	memcpy(pms->buf + offset, p, copy);
-	if (offset + copy < 64)
-	    return;
-	p += copy;
-	left -= copy;
-	md5_process(pms, pms->buf);
-    }
-
-    /* Process full blocks. */
-    for (; left >= 64; p += 64, left -= 64)
-	md5_process(pms, p);
-
-    /* Process a final partial block. */
-    if (left)
-	memcpy(pms->buf, p, left);
-}
-
-void
-md5_finish(md5_state_t *pms, md5_byte_t digest[16])
-{
-    static const md5_byte_t pad[64] = {
-	0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-    };
-    md5_byte_t data[8];
-    int i;
-
-    /* Save the length before padding. */
-    for (i = 0; i < 8; ++i)
-	data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
-    /* Pad to 56 bytes mod 64. */
-    md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
-    /* Append the length. */
-    md5_append(pms, data, 8);
-    for (i = 0; i < 16; ++i)
-	digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
-}

Deleted: /python/branches/p3yk-noslice/Modules/md5.h
==============================================================================
--- /python/branches/p3yk-noslice/Modules/md5.h	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,91 +0,0 @@
-/*
-  Copyright (C) 1999, 2002 Aladdin Enterprises.  All rights reserved.
-
-  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.
-
-  L. Peter Deutsch
-  ghost at aladdin.com
-
- */
-/* $Id$ */
-/*
-  Independent implementation of MD5 (RFC 1321).
-
-  This code implements the MD5 Algorithm defined in RFC 1321, whose
-  text is available at
-	http://www.ietf.org/rfc/rfc1321.txt
-  The code is derived from the text of the RFC, including the test suite
-  (section A.5) but excluding the rest of Appendix A.  It does not include
-  any code or documentation that is identified in the RFC as being
-  copyrighted.
-
-  The original and principal author of md5.h is L. Peter Deutsch
-  <ghost at aladdin.com>.  Other authors are noted in the change history
-  that follows (in reverse chronological order):
-
-  2002-04-13 lpd Removed support for non-ANSI compilers; removed
-	references to Ghostscript; clarified derivation from RFC 1321;
-	now handles byte order either statically or dynamically.
-  1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
-  1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
-	added conditionalization for C++ compilation from Martin
-	Purschke <purschke at bnl.gov>.
-  1999-05-03 lpd Original version.
- */
-
-#ifndef md5_INCLUDED
-#  define md5_INCLUDED
-
-/*
- * This package supports both compile-time and run-time determination of CPU
- * byte order.  If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
- * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
- * defined as non-zero, the code will be compiled to run only on big-endian
- * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
- * run on either big- or little-endian CPUs, but will run slightly less
- * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
- */
-
-typedef unsigned char md5_byte_t; /* 8-bit byte */
-typedef unsigned int md5_word_t; /* 32-bit word */
-
-/* Define the state of the MD5 Algorithm. */
-typedef struct md5_state_s {
-    md5_word_t count[2];	/* message length in bits, lsw first */
-    md5_word_t abcd[4];		/* digest buffer */
-    md5_byte_t buf[64];		/* accumulate block */
-} md5_state_t;
-
-#ifdef __cplusplus
-extern "C" 
-{
-#endif
-
-/* Initialize the algorithm. */
-void md5_init(md5_state_t *pms);
-
-/* Append a string to the message. */
-void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
-
-/* Finish the message and return the digest. */
-void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
-
-#ifdef __cplusplus
-}  /* end extern "C" */
-#endif
-
-#endif /* md5_INCLUDED */

Deleted: /python/branches/p3yk-noslice/Modules/md5module.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/md5module.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,312 +0,0 @@
-
-/* MD5 module */
-
-/* This module provides an interface to the RSA Data Security,
-   Inc. MD5 Message-Digest Algorithm, described in RFC 1321.
-   It requires the files md5c.c and md5.h (which are slightly changed
-   from the versions in the RFC to avoid the "global.h" file.) */
-
-
-/* MD5 objects */
-
-#include "Python.h"
-#include "structmember.h"
-#include "md5.h"
-
-typedef struct {
-	PyObject_HEAD
-        md5_state_t	md5;		/* the context holder */
-} md5object;
-
-static PyTypeObject MD5type;
-
-#define is_md5object(v)		((v)->ob_type == &MD5type)
-
-static md5object *
-newmd5object(void)
-{
-	md5object *md5p;
-
-	md5p = PyObject_New(md5object, &MD5type);
-	if (md5p == NULL)
-		return NULL;
-
-	md5_init(&md5p->md5);	/* actual initialisation */
-	return md5p;
-}
-
-
-/* MD5 methods */
-
-static void
-md5_dealloc(md5object *md5p)
-{
-	PyObject_Del(md5p);
-}
-
-
-/* MD5 methods-as-attributes */
-
-static PyObject *
-md5_update(md5object *self, PyObject *args)
-{
-	unsigned char *cp;
-	int len;
-
-	if (!PyArg_ParseTuple(args, "s#:update", &cp, &len))
-		return NULL;
-
-	md5_append(&self->md5, cp, len);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-PyDoc_STRVAR(update_doc,
-"update (arg)\n\
-\n\
-Update the md5 object with the string arg. Repeated calls are\n\
-equivalent to a single call with the concatenation of all the\n\
-arguments.");
-
-
-static PyObject *
-md5_digest(md5object *self)
-{
- 	md5_state_t mdContext;
-	unsigned char aDigest[16];
-
-	/* make a temporary copy, and perform the final */
-	mdContext = self->md5;
-	md5_finish(&mdContext, aDigest);
-
-	return PyString_FromStringAndSize((char *)aDigest, 16);
-}
-
-PyDoc_STRVAR(digest_doc,
-"digest() -> string\n\
-\n\
-Return the digest of the strings passed to the update() method so\n\
-far. This is a 16-byte string which may contain non-ASCII characters,\n\
-including null bytes.");
-
-
-static PyObject *
-md5_hexdigest(md5object *self)
-{
- 	md5_state_t mdContext;
-	unsigned char digest[16];
-	unsigned char hexdigest[32];
-	int i, j;
-
-	/* make a temporary copy, and perform the final */
-	mdContext = self->md5;
-	md5_finish(&mdContext, digest);
-
-	/* Make hex version of the digest */
-	for(i=j=0; i<16; i++) {
-		char c;
-		c = (digest[i] >> 4) & 0xf;
-		c = (c>9) ? c+'a'-10 : c + '0';
-		hexdigest[j++] = c;
-		c = (digest[i] & 0xf);
-		c = (c>9) ? c+'a'-10 : c + '0';
-		hexdigest[j++] = c;
-	}
-	return PyString_FromStringAndSize((char*)hexdigest, 32);
-}
-
-
-PyDoc_STRVAR(hexdigest_doc,
-"hexdigest() -> string\n\
-\n\
-Like digest(), but returns the digest as a string of hexadecimal digits.");
-
-
-static PyObject *
-md5_copy(md5object *self)
-{
-	md5object *md5p;
-
-	if ((md5p = newmd5object()) == NULL)
-		return NULL;
-
-	md5p->md5 = self->md5;
-
-	return (PyObject *)md5p;
-}
-
-PyDoc_STRVAR(copy_doc,
-"copy() -> md5 object\n\
-\n\
-Return a copy (``clone'') of the md5 object.");
-
-
-static PyMethodDef md5_methods[] = {
-	{"update",    (PyCFunction)md5_update,    METH_VARARGS, update_doc},
-	{"digest",    (PyCFunction)md5_digest,    METH_NOARGS,  digest_doc},
-	{"hexdigest", (PyCFunction)md5_hexdigest, METH_NOARGS,  hexdigest_doc},
-	{"copy",      (PyCFunction)md5_copy,      METH_NOARGS,  copy_doc},
-	{NULL, NULL}			     /* sentinel */
-};
-
-static PyObject *
-md5_get_block_size(PyObject *self, void *closure)
-{
-    return PyInt_FromLong(64);
-}
-
-static PyObject *
-md5_get_digest_size(PyObject *self, void *closure)
-{
-    return PyInt_FromLong(16);
-}
-
-static PyObject *
-md5_get_name(PyObject *self, void *closure)
-{
-    return PyString_FromStringAndSize("MD5", 3);
-}
-
-static PyGetSetDef md5_getseters[] = {
-    {"digest_size",
-     (getter)md5_get_digest_size, NULL,
-     NULL,
-     NULL},
-    {"block_size",
-     (getter)md5_get_block_size, NULL,
-     NULL,
-     NULL},
-    {"name",
-     (getter)md5_get_name, NULL,
-     NULL,
-     NULL},
-    /* the old md5 and sha modules support 'digest_size' as in PEP 247.
-     * the old sha module also supported 'digestsize'.  ugh. */
-    {"digestsize",
-     (getter)md5_get_digest_size, NULL,
-     NULL,
-     NULL},
-    {NULL}  /* Sentinel */
-};
-
-
-PyDoc_STRVAR(module_doc,
-"This module implements the interface to RSA's MD5 message digest\n\
-algorithm (see also Internet RFC 1321). Its use is quite\n\
-straightforward: use the new() to create an md5 object. You can now\n\
-feed this object with arbitrary strings using the update() method, and\n\
-at any point you can ask it for the digest (a strong kind of 128-bit\n\
-checksum, a.k.a. ``fingerprint'') of the concatenation of the strings\n\
-fed to it so far using the digest() method.\n\
-\n\
-Functions:\n\
-\n\
-new([arg]) -- return a new md5 object, initialized with arg if provided\n\
-md5([arg]) -- DEPRECATED, same as new, but for compatibility\n\
-\n\
-Special Objects:\n\
-\n\
-MD5Type -- type object for md5 objects");
-
-PyDoc_STRVAR(md5type_doc,
-"An md5 represents the object used to calculate the MD5 checksum of a\n\
-string of information.\n\
-\n\
-Methods:\n\
-\n\
-update() -- updates the current digest with an additional string\n\
-digest() -- return the current digest value\n\
-hexdigest() -- return the current digest as a string of hexadecimal digits\n\
-copy() -- return a copy of the current md5 object");
-
-static PyTypeObject MD5type = {
-	PyObject_HEAD_INIT(NULL)
-	0,			  /*ob_size*/
-	"_md5.md5",		  /*tp_name*/
-	sizeof(md5object),	  /*tp_size*/
-	0,			  /*tp_itemsize*/
-	/* methods */
-	(destructor)md5_dealloc,  /*tp_dealloc*/
-	0,			  /*tp_print*/
-	0,                        /*tp_getattr*/
-	0,			  /*tp_setattr*/
-	0,			  /*tp_compare*/
-	0,			  /*tp_repr*/
-        0,			  /*tp_as_number*/
-	0,                        /*tp_as_sequence*/
-	0,			  /*tp_as_mapping*/
-	0, 			  /*tp_hash*/
-	0,			  /*tp_call*/
-	0,			  /*tp_str*/
-	0,			  /*tp_getattro*/
-	0,			  /*tp_setattro*/
-	0,	                  /*tp_as_buffer*/
-	Py_TPFLAGS_DEFAULT,	  /*tp_flags*/
-	md5type_doc,		  /*tp_doc*/
-        0,                        /*tp_traverse*/
-        0,			  /*tp_clear*/
-        0,			  /*tp_richcompare*/
-        0,			  /*tp_weaklistoffset*/
-        0,			  /*tp_iter*/
-        0,			  /*tp_iternext*/
-        md5_methods,	          /*tp_methods*/
-        0,      	          /*tp_members*/
-        md5_getseters,            /*tp_getset*/
-};
-
-
-/* MD5 functions */
-
-static PyObject *
-MD5_new(PyObject *self, PyObject *args)
-{
-	md5object *md5p;
-	unsigned char *cp = NULL;
-	int len = 0;
-
-	if (!PyArg_ParseTuple(args, "|s#:new", &cp, &len))
-		return NULL;
-
-	if ((md5p = newmd5object()) == NULL)
-		return NULL;
-
-	if (cp)
-		md5_append(&md5p->md5, cp, len);
-
-	return (PyObject *)md5p;
-}
-
-PyDoc_STRVAR(new_doc,
-"new([arg]) -> md5 object\n\
-\n\
-Return a new md5 object. If arg is present, the method call update(arg)\n\
-is made.");
-
-
-/* List of functions exported by this module */
-
-static PyMethodDef md5_functions[] = {
-	{"new",		(PyCFunction)MD5_new, METH_VARARGS, new_doc},
-	{NULL,		NULL}	/* Sentinel */
-};
-
-
-/* Initialize this module. */
-
-PyMODINIT_FUNC
-init_md5(void)
-{
-	PyObject *m, *d;
-
-        MD5type.ob_type = &PyType_Type;
-        if (PyType_Ready(&MD5type) < 0)
-            return;
-	m = Py_InitModule3("_md5", md5_functions, module_doc);
-	if (m == NULL)
-	    return;
-	d = PyModule_GetDict(m);
-	PyDict_SetItemString(d, "MD5Type", (PyObject *)&MD5type);
-	PyModule_AddIntConstant(m, "digest_size", 16);
-	/* No need to check the error here, the caller will do that */
-}

Modified: python/branches/p3yk-noslice/Modules/operator.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/operator.c	(original)
+++ python/branches/p3yk-noslice/Modules/operator.c	Wed Jul 11 15:40:56 2007
@@ -65,7 +65,6 @@
   if(! PyArg_UnpackTuple(a,#OP,2,2,&a1,&a2)) return NULL; \
   return PyObject_RichCompare(a1,a2,A); }
 
-spami(isCallable       , PyCallable_Check)
 spami(isNumberType     , PyNumber_Check)
 spami(truth            , PyObject_IsTrue)
 spam2(op_add           , PyNumber_Add)
@@ -102,7 +101,6 @@
 spam2(op_iconcat       , PySequence_InPlaceConcat)
 spamoi(op_irepeat      , PySequence_InPlaceRepeat)
 spami2b(op_contains     , PySequence_Contains)
-spami2b(sequenceIncludes, PySequence_Contains)
 spamn2(indexOf         , PySequence_Index)
 spamn2(countOf         , PySequence_Count)
 spami(isMappingType    , PyMapping_Check)
@@ -166,43 +164,41 @@
 op_getslice(PyObject *s, PyObject *a)
 {
         PyObject *a1;
-        int a2,a3;
+        Py_ssize_t a2, a3;
 
-        if (!PyArg_ParseTuple(a,"Oii:getslice",&a1,&a2,&a3))
+        if (!PyArg_ParseTuple(a, "Onn:getslice", &a1, &a2, &a3))
                 return NULL;
-        return PySequence_GetSlice(a1,a2,a3);
+        return PySequence_GetSlice(a1, a2, a3);
 }
 
 static PyObject*
 op_setslice(PyObject *s, PyObject *a)
 {
         PyObject *a1, *a4;
-        int a2,a3;
+        Py_ssize_t a2, a3;
 
-        if (!PyArg_ParseTuple(a,"OiiO:setslice",&a1,&a2,&a3,&a4))
+        if (!PyArg_ParseTuple(a, "OnnO:setslice", &a1, &a2, &a3, &a4))
                 return NULL;
 
-        if (-1 == PySequence_SetSlice(a1,a2,a3,a4))
+        if (-1 == PySequence_SetSlice(a1, a2, a3, a4))
                 return NULL;
 
-        Py_INCREF(Py_None);
-        return Py_None;
+	Py_RETURN_NONE;
 }
 
 static PyObject*
 op_delslice(PyObject *s, PyObject *a)
 {
         PyObject *a1;
-        int a2,a3;
+        Py_ssize_t a2, a3;
 
-        if(! PyArg_ParseTuple(a,"Oii:delslice",&a1,&a2,&a3))
+        if (!PyArg_ParseTuple(a, "Onn:delslice", &a1, &a2, &a3))
                 return NULL;
 
-        if (-1 == PySequence_DelSlice(a1,a2,a3))
+        if (-1 == PySequence_DelSlice(a1, a2, a3))
                 return NULL;
 
-        Py_INCREF(Py_None);
-        return Py_None;
+	Py_RETURN_NONE;
 }
 
 #undef spam1
@@ -218,8 +214,6 @@
 
 static struct PyMethodDef operator_methods[] = {
 
-spam1o(isCallable,
- "isCallable(a) -- Same as callable(a).")
 spam1o(isNumberType,
  "isNumberType(a) -- Return True if a has a numeric type, False otherwise.")
 spam1o(isSequenceType,
@@ -228,8 +222,6 @@
  "truth(a) -- Return True if a is true, False otherwise.")
 spam2(contains,__contains__,
  "contains(a, b) -- Same as b in a (note reversed operands).")
-spam1(sequenceIncludes,
- "sequenceIncludes(a, b) -- Same as b in a (note reversed operands; deprecated).")
 spam1(indexOf,
  "indexOf(a, b) -- Return the first index of b in a.")
 spam1(countOf,

Modified: python/branches/p3yk-noslice/Modules/parsermodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/parsermodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/parsermodule.c	Wed Jul 11 15:40:56 2007
@@ -854,35 +854,34 @@
 VALIDATER(class);               VALIDATER(node);
 VALIDATER(parameters);          VALIDATER(suite);
 VALIDATER(testlist);            VALIDATER(varargslist);
-VALIDATER(vfpdef);              VALIDATER(vfplist);
+VALIDATER(vfpdef);              
 VALIDATER(stmt);                VALIDATER(simple_stmt);
 VALIDATER(expr_stmt);           VALIDATER(power);
 VALIDATER(del_stmt);
-VALIDATER(return_stmt);         VALIDATER(list_iter);
-VALIDATER(raise_stmt);          VALIDATER(import_stmt);
-VALIDATER(import_name);         VALIDATER(import_from);
-VALIDATER(global_stmt);         VALIDATER(list_if);
-VALIDATER(assert_stmt);         VALIDATER(list_for);
-VALIDATER(compound_stmt);       VALIDATER(vname);
+VALIDATER(return_stmt);         VALIDATER(raise_stmt);
+VALIDATER(import_stmt);         VALIDATER(import_stmt);
+VALIDATER(import_name);         VALIDATER(yield_stmt);
+VALIDATER(global_stmt);         VALIDATER(assert_stmt);
+VALIDATER(compound_stmt);
 VALIDATER(while);               VALIDATER(for);
 VALIDATER(try);                 VALIDATER(except_clause);
 VALIDATER(test);                VALIDATER(and_test);
 VALIDATER(not_test);            VALIDATER(comparison);
-VALIDATER(comp_op);             VALIDATER(expr);
+VALIDATER(comp_op);             
+VALIDATER(star_expr);           VALIDATER(expr);
 VALIDATER(xor_expr);            VALIDATER(and_expr);
 VALIDATER(shift_expr);          VALIDATER(arith_expr);
 VALIDATER(term);                VALIDATER(factor);
 VALIDATER(atom);                VALIDATER(lambdef);
 VALIDATER(trailer);             VALIDATER(subscript);
 VALIDATER(subscriptlist);       VALIDATER(sliceop);
-VALIDATER(exprlist);            VALIDATER(dictsetmaker);
+VALIDATER(exprlist);            VALIDATER(dictorsetmaker);
 VALIDATER(arglist);             VALIDATER(argument);
-VALIDATER(listmaker);           VALIDATER(yield_stmt);
-VALIDATER(testlist1);           VALIDATER(gen_for);
-VALIDATER(gen_iter);            VALIDATER(gen_if);
-VALIDATER(testlist_gexp);	VALIDATER(yield_expr);
-VALIDATER(yield_or_testlist);	VALIDATER(or_test);
-VALIDATER(old_test); 		VALIDATER(old_lambdef);
+VALIDATER(testlist1);           VALIDATER(comp_for);
+VALIDATER(comp_iter);           VALIDATER(comp_if);
+VALIDATER(testlist_comp);       VALIDATER(yield_expr);
+VALIDATER(yield_or_testlist);   VALIDATER(or_test);
+VALIDATER(test_nocond);         VALIDATER(lambdef_nocond);
 
 #undef VALIDATER
 
@@ -1112,26 +1111,18 @@
 }
 
 
-static int
-validate_testlist_safe(node *tree)
-{
-    return (validate_repeating_list(tree, testlist_safe,
-                                    validate_old_test, "testlist_safe"));
-}
-
-
-/* validate either vname or tname.
- * vname: NAME
- * tname: NAME [':' test]
+/* validate either vfpdef or tfpdef.
+ * vfpdef: NAME
+ * tfpdef: NAME [':' test]
  */
 static int
-validate_vname(node *tree)
+validate_vfpdef(node *tree)
 {
     int nch = NCH(tree);
-    if (TYPE(tree) == vname) {
+    if (TYPE(tree) == vfpdef) {
         return nch == 1 && validate_name(CHILD(tree, 0), NULL);
     }
-    else if (TYPE(tree) == tname) {
+    else if (TYPE(tree) == tfpdef) {
         if (nch == 1) {
             return validate_name(CHILD(tree, 0), NULL);
         }
@@ -1144,8 +1135,8 @@
     return 0;
 }
 
-/* '*' vname (',' vname ['=' test])* [',' '**' vname] | '**' vname
- * ..or tname in place of vname. vname: NAME; tname: NAME [':' test]
+/* '*' vfpdef (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef
+ * ..or tfpdef in place of vfpdef. vfpdef: NAME; tfpdef: NAME [':' test]
  */
 static int
 validate_varargslist_trailer(node *tree, int start)
@@ -1161,27 +1152,27 @@
     sym = TYPE(CHILD(tree, start));
     if (sym == STAR) {
         /*
-         * '*' vname (',' vname ['=' test])* [',' '**' vname] | '**' vname
+         * '*' vfpdef (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef
          */
         if (nch-start == 2)
-            res = validate_vname(CHILD(tree, start+1));
+            res = validate_vfpdef(CHILD(tree, start+1));
         else if (nch-start == 5 && TYPE(CHILD(tree, start+2)) == COMMA)
-            res = (validate_vname(CHILD(tree, start+1))
+            res = (validate_vfpdef(CHILD(tree, start+1))
                    && validate_comma(CHILD(tree, start+2))
                    && validate_doublestar(CHILD(tree, start+3))
-                   && validate_vname(CHILD(tree, start+4)));
+                   && validate_vfpdef(CHILD(tree, start+4)));
         else {
-            /* skip over vname (',' vname ['=' test])*  */
+            /* skip over vfpdef (',' vfpdef ['=' test])*  */
             i = start + 1;
-	    if (TYPE(CHILD(tree, i)) == vname ||
-	        TYPE(CHILD(tree, i)) == tname) { /* skip over vname or tname */
+	    if (TYPE(CHILD(tree, i)) == vfpdef ||
+	        TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */
 		i += 1;
 	    }
-            while (res && i+1 < nch) { /* validate  (',' vname ['=' test])* */
+            while (res && i+1 < nch) { /* validate  (',' vfpdef ['=' test])* */
                 res = validate_comma(CHILD(tree, i));
                 if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR) 
                     break;
-                res = res && validate_vname(CHILD(tree, i+1));
+                res = res && validate_vfpdef(CHILD(tree, i+1));
                 if (res && i+2 < nch && TYPE(CHILD(tree, i+2)) == EQUAL) {
                     res = res && (i+3 < nch) 
                           && validate_test(CHILD(tree, i+3));
@@ -1191,9 +1182,9 @@
                     i += 2;
                 }
             }
-            /* [',' '**' vname] */
+            /* [',' '**' vfpdef] */
             if (res && i+1 < nch && TYPE(CHILD(tree, i+1)) == DOUBLESTAR) {
-                res = validate_vname(CHILD(tree, i+2));
+                res = validate_vfpdef(CHILD(tree, i+2));
             }
         }
     }
@@ -1202,7 +1193,7 @@
          *  '**' NAME
          */
         if (nch-start == 2)
-            res = validate_vname(CHILD(tree, start+1));
+            res = validate_vfpdef(CHILD(tree, start+1));
     }
     if (!res)
         err_string("illegal variable argument trailer for varargslist");
@@ -1215,19 +1206,15 @@
  * Validate typedargslist or varargslist.
  *
  * typedargslist: ((tfpdef ['=' test] ',')*
- *                 ('*' [tname] (',' tname ['=' test])* [',' '**' tname] |
- *                  '**' tname)
+ *                 ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] |
+ *                  '**' tfpdef)
  *                 | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
- * tname: NAME [':' test]
- * tfpdef: tname | '(' tfplist ')'
- * tfplist: tfpdef (',' tfpdef)* [',']
+ * tfpdef: NAME [':' test]
  * varargslist: ((vfpdef ['=' test] ',')*
- *               ('*' [vname] (',' vname ['=' test])*  [',' '**' vname] |
- *                '**' vname)
+ *               ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] |
+ *                '**' vfpdef)
  *               | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
- * vname: NAME
- * vfpdef: vname | '(' vfplist ')'
- * vfplist: vfpdef (',' vfpdef)* [',']
+ * vfpdef: NAME
  *
  */
 static int
@@ -1238,162 +1225,71 @@
                TYPE(tree) == typedargslist) &&
               (nch != 0);
     int sym;
+    node *ch;
+    int i = 0;
+    
     if (!res)
         return 0;
     if (nch < 1) {
         err_string("varargslist missing child nodes");
         return 0;
     }
-    sym = TYPE(CHILD(tree, 0));
-    if (sym == STAR || sym == DOUBLESTAR)
-        /* whole thing matches:
-         *    '*' [NAME] (',' NAME ['=' test])* [',' '**' NAME] | '**' NAME
-         */
-        res = validate_varargslist_trailer(tree, 0);
-    else if (sym == vfpdef || sym == tfpdef) {
-        int i = 0;
-
-        sym = TYPE(CHILD(tree, nch-1));
-        if (sym == vname || sym == tname) {
-            /*
-             *   (vfpdef ['=' test] ',')+
-             *       ('*' vname [',' '**' vname]
-             *     | '**' vname)
-             */
-            /* skip over (vfpdef ['=' test] ',')+ */
-            while (res && (i+2 <= nch)) {
-                res = validate_vfpdef(CHILD(tree, i));
-                ++i;
-                if (res && TYPE(CHILD(tree, i)) == EQUAL && (i+2 <= nch)) {
-                    res = (validate_equal(CHILD(tree, i))
-                           && validate_test(CHILD(tree, i+1)));
-                    if (res)
-                        i += 2;
-                }
-                if (res && i < nch) {
-                    res = validate_comma(CHILD(tree, i));
-                    ++i;
-                    if (res && i < nch
-                        && (TYPE(CHILD(tree, i)) == DOUBLESTAR
-                            || TYPE(CHILD(tree, i)) == STAR))
-                        break;
-                }
-            }
-            /* .. ('*' [NAME] (',' NAME ['=' test])* [',' '**' NAME] | '**' NAME)
-             * i --^^^
-             */
-            if (res)
-                res = validate_varargslist_trailer(tree, i);
-        }
-        else {
-            /*
-             *  vfpdef ['=' test] (',' vfpdef ['=' test])* [',']
-             */
-            /* strip trailing comma node */
-            if (sym == COMMA) {
-                res = validate_comma(CHILD(tree, nch-1));
-                if (!res)
-                    return 0;
-                --nch;
-            }
-            /*
-             *  vfpdef ['=' test] (',' vfpdef ['=' test])*
-             */
-            res = validate_vfpdef(CHILD(tree, 0));
+    while (i < nch) {
+        ch = CHILD(tree, i);      
+        sym = TYPE(ch);
+        if (sym == vfpdef || sym == tfpdef) {
+            /* validate (vfpdef ['=' test] ',')+ */
+            res = validate_vfpdef(ch);
             ++i;
             if (res && (i+2 <= nch) && TYPE(CHILD(tree, i)) == EQUAL) {
                 res = (validate_equal(CHILD(tree, i))
                        && validate_test(CHILD(tree, i+1)));
-                i += 2;
+                if (res)
+                  i += 2;
             }
-            /*
-             *  ... (',' vfpdef ['=' test])*
-             *  i ---^^^
-             */
-            while (res && (nch - i) >= 2) {
-                res = (validate_comma(CHILD(tree, i))
-                       && validate_vfpdef(CHILD(tree, i+1)));
-                i += 2;
-                if (res && (nch - i) >= 2 && TYPE(CHILD(tree, i)) == EQUAL) {
-                    res = (validate_equal(CHILD(tree, i))
-                           && validate_test(CHILD(tree, i+1)));
-                    i += 2;
-                }
-            }
-            if (res && nch - i != 0) {
-                res = 0;
-                err_string("illegal formation for varargslist");
+            if (res && i < nch) {
+                res = validate_comma(CHILD(tree, i));
+                ++i;
             }
+        } else if (sym == DOUBLESTAR || sym == STAR) {
+            res = validate_varargslist_trailer(tree, i);
+            break;
+        } else {
+            res = 0;
+            err_string("illegal formation for varargslist");
         }
     }
     return res;
 }
 
 
-/*  list_iter:  list_for | list_if
- */
-static int
-validate_list_iter(node *tree)
-{
-    int res = (validate_ntype(tree, list_iter)
-               && validate_numnodes(tree, 1, "list_iter"));
-    if (res && TYPE(CHILD(tree, 0)) == list_for)
-        res = validate_list_for(CHILD(tree, 0));
-    else
-        res = validate_list_if(CHILD(tree, 0));
-
-    return res;
-}
-
-/*  gen_iter:  gen_for | gen_if
- */
-static int
-validate_gen_iter(node *tree)
-{
-    int res = (validate_ntype(tree, gen_iter)
-               && validate_numnodes(tree, 1, "gen_iter"));
-    if (res && TYPE(CHILD(tree, 0)) == gen_for)
-        res = validate_gen_for(CHILD(tree, 0));
-    else
-        res = validate_gen_if(CHILD(tree, 0));
-
-    return res;
-}
-
-/*  list_for:  'for' exprlist 'in' testlist [list_iter]
+/*  comp_iter:  comp_for | comp_if
  */
 static int
-validate_list_for(node *tree)
+validate_comp_iter(node *tree)
 {
-    int nch = NCH(tree);
-    int res;
-
-    if (nch == 5)
-        res = validate_list_iter(CHILD(tree, 4));
+    int res = (validate_ntype(tree, comp_iter)
+               && validate_numnodes(tree, 1, "comp_iter"));
+    if (res && TYPE(CHILD(tree, 0)) == comp_for)
+        res = validate_comp_for(CHILD(tree, 0));
     else
-        res = validate_numnodes(tree, 4, "list_for");
-
-    if (res)
-        res = (validate_name(CHILD(tree, 0), "for")
-               && validate_exprlist(CHILD(tree, 1))
-               && validate_name(CHILD(tree, 2), "in")
-               && validate_testlist_safe(CHILD(tree, 3)));
+        res = validate_comp_if(CHILD(tree, 0));
 
     return res;
 }
 
-/*  gen_for:  'for' exprlist 'in' test [gen_iter]
+/*  comp_for:  'for' exprlist 'in' test [comp_iter]
  */
 static int
-validate_gen_for(node *tree)
+validate_comp_for(node *tree)
 {
     int nch = NCH(tree);
     int res;
 
     if (nch == 5)
-        res = validate_gen_iter(CHILD(tree, 4));
+        res = validate_comp_iter(CHILD(tree, 4));
     else
-        res = validate_numnodes(tree, 4, "gen_for");
+        res = validate_numnodes(tree, 4, "comp_for");
 
     if (res)
         res = (validate_name(CHILD(tree, 0), "for")
@@ -1404,87 +1300,26 @@
     return res;
 }
 
-/*  list_if:  'if' old_test [list_iter]
+/*  comp_if:  'if' test_nocond [comp_iter]
  */
 static int
-validate_list_if(node *tree)
+validate_comp_if(node *tree)
 {
     int nch = NCH(tree);
     int res;
 
     if (nch == 3)
-        res = validate_list_iter(CHILD(tree, 2));
+        res = validate_comp_iter(CHILD(tree, 2));
     else
-        res = validate_numnodes(tree, 2, "list_if");
-
-    if (res)
-        res = (validate_name(CHILD(tree, 0), "if")
-               && validate_old_test(CHILD(tree, 1)));
-
-    return res;
-}
-
-/*  gen_if:  'if' old_test [gen_iter]
- */
-static int
-validate_gen_if(node *tree)
-{
-    int nch = NCH(tree);
-    int res;
+        res = validate_numnodes(tree, 2, "comp_if");
 
-    if (nch == 3)
-        res = validate_gen_iter(CHILD(tree, 2));
-    else
-        res = validate_numnodes(tree, 2, "gen_if");
-    
     if (res)
         res = (validate_name(CHILD(tree, 0), "if")
-               && validate_old_test(CHILD(tree, 1)));
+               && validate_test_nocond(CHILD(tree, 1)));
 
     return res;
 }
 
-/* validate_vfpdef()
- *
- * Validate vfpdef or tfpdef.
- *
- * vname: NAME
- * vfpdef: vname | '(' vfplist ')'
- * vfplist: vfpdef (',' vfpdef)* [',']
- *
- * tname: NAME [':' test]
- * tfpdef: tname | '(' tfplist ')'
- * tfplist: tfpdef (',' tfpdef)* [',']
- *
- */
-static int
-validate_vfpdef(node *tree)
-{
-    int nch = NCH(tree);
-    int typ = TYPE(tree);
-    int res = typ == vfpdef || typ == tfpdef;
-
-    if (res) {
-        if (nch == 1)
-            res = validate_vname(CHILD(tree, 0));
-        else if (nch == 3)
-            res = (validate_lparen(CHILD(tree, 0))
-                   && validate_vfplist(CHILD(tree, 1))
-                   && validate_rparen(CHILD(tree, 2)));
-        else
-            res = validate_numnodes(tree, 1, "fpdef");
-    }
-    return (res);
-}
-
-
-static int
-validate_vfplist(node *tree)
-{
-    return (validate_repeating_list(tree, vfplist,
-                                    validate_vfpdef, "vfplist"));
-}
-
 
 /*  simple_stmt | compound_stmt
  *
@@ -1568,7 +1403,7 @@
 
 
 /*  compound_stmt:
- *      if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
+ *      if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef | decorated
  */
 static int
 validate_compound_stmt(node *tree)
@@ -1587,7 +1422,8 @@
           || (ntype == for_stmt)
           || (ntype == try_stmt)
           || (ntype == funcdef)
-          || (ntype == classdef))
+          || (ntype == classdef)
+          || (ntype == decorated))
         res = validate_node(tree);
     else {
         res = 0;
@@ -1597,7 +1433,6 @@
     return (res);
 }
 
-
 static int
 validate_yield_or_testlist(node *tree)
 {
@@ -2089,13 +1924,13 @@
 }
 
 static int
-validate_old_test(node *tree)
+validate_test_nocond(node *tree)
 {
     int nch = NCH(tree);
-    int res = validate_ntype(tree, old_test) && (nch == 1);
+    int res = validate_ntype(tree, test_nocond) && (nch == 1);
 
-    if (res && (TYPE(CHILD(tree, 0)) == old_lambdef))
-        res = (validate_old_lambdef(CHILD(tree, 0)));
+    if (res && (TYPE(CHILD(tree, 0)) == lambdef_nocond))
+        res = (validate_lambdef_nocond(CHILD(tree, 0)));
     else if (res) {
         res = (validate_or_test(CHILD(tree, 0)));
     }
@@ -2160,11 +1995,11 @@
     int nch = NCH(tree);
     int res = (validate_ntype(tree, comparison)
                && is_odd(nch)
-               && validate_expr(CHILD(tree, 0)));
+               && validate_star_expr(CHILD(tree, 0)));
 
     for (pos = 1; res && (pos < nch); pos += 2)
         res = (validate_comp_op(CHILD(tree, pos))
-               && validate_expr(CHILD(tree, pos + 1)));
+               && validate_star_expr(CHILD(tree, pos + 1)));
 
     return (res);
 }
@@ -2222,6 +2057,20 @@
 
 
 static int
+validate_star_expr(node *tree)
+{
+    int res = validate_ntype(tree, star_expr);
+    if (!res) return res;
+    if (NCH(tree) == 2) {
+        return validate_ntype(CHILD(tree, 0), STAR) && \
+               validate_expr(CHILD(tree, 1));
+    } else {
+        return validate_expr(CHILD(tree, 0));
+    }
+}
+
+
+static int
 validate_expr(node *tree)
 {
     int j;
@@ -2393,14 +2242,14 @@
 		if (TYPE(CHILD(tree, 1))==yield_expr)
 			res = validate_yield_expr(CHILD(tree, 1));
 		else
-                	res = validate_testlist_gexp(CHILD(tree, 1));
+                	res = validate_testlist_comp(CHILD(tree, 1));
 	    }
             break;
           case LSQB:
             if (nch == 2)
                 res = validate_ntype(CHILD(tree, 1), RSQB);
             else if (nch == 3)
-                res = (validate_listmaker(CHILD(tree, 1))
+                res = (validate_testlist_comp(CHILD(tree, 1))
                        && validate_ntype(CHILD(tree, 2), RSQB));
             else {
                 res = 0;
@@ -2412,7 +2261,7 @@
                    && validate_ntype(CHILD(tree, nch - 1), RBRACE));
 
             if (res && (nch == 3))
-                res = validate_dictsetmaker(CHILD(tree, 1));
+                res = validate_dictorsetmaker(CHILD(tree, 1));
             break;
           case NAME:
           case NUMBER:
@@ -2436,63 +2285,26 @@
 }
 
 
-/*  listmaker:
- *    test ( list_for | (',' test)* [','] )
- */
-static int
-validate_listmaker(node *tree)
-{
-    int nch = NCH(tree);
-    int ok = nch;
-
-    if (nch == 0)
-        err_string("missing child nodes of listmaker");
-    else
-        ok = validate_test(CHILD(tree, 0));
-
-    /*
-     *  list_for | (',' test)* [',']
-     */
-    if (nch == 2 && TYPE(CHILD(tree, 1)) == list_for)
-        ok = validate_list_for(CHILD(tree, 1));
-    else {
-        /*  (',' test)* [',']  */
-        int i = 1;
-        while (ok && nch - i >= 2) {
-            ok = (validate_comma(CHILD(tree, i))
-                  && validate_test(CHILD(tree, i+1)));
-            i += 2;
-        }
-        if (ok && i == nch-1)
-            ok = validate_comma(CHILD(tree, i));
-        else if (i != nch) {
-            ok = 0;
-            err_string("illegal trailing nodes for listmaker");
-        }
-    }
-    return ok;
-}
-
-/*  testlist_gexp:
- *    test ( gen_for | (',' test)* [','] )
+/*  testlist_comp:
+ *    test ( comp_for | (',' test)* [','] )
  */
 static int
-validate_testlist_gexp(node *tree)
+validate_testlist_comp(node *tree)
 {
     int nch = NCH(tree);
     int ok = nch;
 
     if (nch == 0)
-        err_string("missing child nodes of testlist_gexp");
+        err_string("missing child nodes of testlist_comp");
     else {
         ok = validate_test(CHILD(tree, 0));
     }
 
     /*
-     *  gen_for | (',' test)* [',']
+     *  comp_for | (',' test)* [',']
      */
-    if (nch == 2 && TYPE(CHILD(tree, 1)) == gen_for)
-        ok = validate_gen_for(CHILD(tree, 1));
+    if (nch == 2 && TYPE(CHILD(tree, 1)) == comp_for)
+        ok = validate_comp_for(CHILD(tree, 1));
     else {
         /*  (',' test)* [',']  */
         int i = 1;
@@ -2505,7 +2317,7 @@
             ok = validate_comma(CHILD(tree, i));
         else if (i != nch) {
             ok = 0;
-            err_string("illegal trailing nodes for testlist_gexp");
+            err_string("illegal trailing nodes for testlist_comp");
         }
     }
     return ok;
@@ -2554,28 +2366,40 @@
 
 /*  funcdef:
  *      
- *            -6   -5    -4         -3  -2 -1
- *  [decorators] 'def' NAME parameters ':' suite
+ *     -5   -4         -3  -2    -1
+ *  'def' NAME parameters ':' suite
  */
 static int
 validate_funcdef(node *tree)
 {
     int nch = NCH(tree);
     int ok = (validate_ntype(tree, funcdef)
-	       && ((nch == 5) || (nch == 6))
+	       && (nch == 5)
 	       && validate_name(RCHILD(tree, -5), "def")
 	       && validate_ntype(RCHILD(tree, -4), NAME)
 	       && validate_colon(RCHILD(tree, -2))
 	       && validate_parameters(RCHILD(tree, -3))
 	       && validate_suite(RCHILD(tree, -1)));
-
-    if (ok && (nch == 6))
-	ok = validate_decorators(CHILD(tree, 0));
-
     return ok;
 }
 
 
+/* decorated
+ *   decorators (classdef | funcdef)
+ */
+static int
+validate_decorated(node *tree)
+{
+  int nch = NCH(tree);
+  int ok = (validate_ntype(tree, decorated)
+	    && (nch == 2)
+	    && validate_decorators(RCHILD(tree, -2))
+	    && (validate_funcdef(RCHILD(tree, -1))
+		|| validate_class(RCHILD(tree, -1)))
+	    );
+  return ok;
+}
+
 static int
 validate_lambdef(node *tree)
 {
@@ -2596,10 +2420,10 @@
 
 
 static int
-validate_old_lambdef(node *tree)
+validate_lambdef_nocond(node *tree)
 {
     int nch = NCH(tree);
-    int res = (validate_ntype(tree, old_lambdef)
+    int res = (validate_ntype(tree, lambdef_nocond)
                && ((nch == 3) || (nch == 4))
                && validate_name(CHILD(tree, 0), "lambda")
                && validate_colon(CHILD(tree, nch - 2))
@@ -2608,7 +2432,7 @@
     if (res && (nch == 4))
         res = validate_varargslist(CHILD(tree, 1));
     else if (!res && !PyErr_Occurred())
-        (void) validate_numnodes(tree, 3, "old_lambdef");
+        (void) validate_numnodes(tree, 3, "lambdef_nocond");
 
     return (res);
 }
@@ -2633,7 +2457,7 @@
         for (i=0; i<nch; i++) {
             if (TYPE(CHILD(tree, i)) == argument) {
                 node *ch = CHILD(tree, i);
-                if (NCH(ch) == 2 && TYPE(CHILD(ch, 1)) == gen_for) {
+                if (NCH(ch) == 2 && TYPE(CHILD(ch, 1)) == comp_for) {
                     err_string("need '(', ')' for generator expression");
                     return 0;
                 }
@@ -2700,7 +2524,7 @@
 
 /*  argument:
  *
- *  [test '='] test [gen_for]
+ *  [test '='] test [comp_for]
  */
 static int
 validate_argument(node *tree)
@@ -2711,7 +2535,7 @@
                && validate_test(CHILD(tree, 0)));
 
     if (res && (nch == 2))
-        res = validate_gen_for(CHILD(tree, 1));
+        res = validate_comp_for(CHILD(tree, 1));
     else if (res && (nch == 3))
         res = (validate_equal(CHILD(tree, 1))
                && validate_test(CHILD(tree, 2)));
@@ -2848,15 +2672,15 @@
 validate_exprlist(node *tree)
 {
     return (validate_repeating_list(tree, exprlist,
-                                    validate_expr, "exprlist"));
+                                    validate_star_expr, "exprlist"));
 }
 
 
 static int
-validate_dictsetmaker(node *tree)
+validate_dictorsetmaker(node *tree)
 {
     int nch = NCH(tree);
-    int res = (validate_ntype(tree, dictsetmaker)
+    int res = (validate_ntype(tree, dictorsetmaker)
                && (nch >= 3)
                && validate_test(CHILD(tree, 0))
                && validate_colon(CHILD(tree, 1))
@@ -2919,6 +2743,9 @@
           case classdef:
             res = validate_class(tree);
             break;
+	  case decorated:
+	    res = validate_decorated(tree);
+	    break;
             /*
              *  "Trivial" parse tree nodes.
              *  (Why did I call these trivial?)

Modified: python/branches/p3yk-noslice/Modules/posixmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/posixmodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/posixmodule.c	Wed Jul 11 15:40:56 2007
@@ -263,7 +263,6 @@
 #include <process.h>
 #endif
 #include "osdefs.h"
-#define _WIN32_WINNT 0x0400	  /* Needed for CryptoAPI on some systems */
 #include <windows.h>
 #include <shellapi.h>	/* for ShellExecute() */
 #define popen	_popen
@@ -844,14 +843,48 @@
 	*(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW");
 }
 
+static BOOL
+attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
+{
+	HANDLE hFindFile;
+	WIN32_FIND_DATAA FileData;
+	hFindFile = FindFirstFileA(pszFile, &FileData);
+	if (hFindFile == INVALID_HANDLE_VALUE)
+		return FALSE;
+	FindClose(hFindFile);
+	pfad->dwFileAttributes = FileData.dwFileAttributes;
+	pfad->ftCreationTime   = FileData.ftCreationTime;
+	pfad->ftLastAccessTime = FileData.ftLastAccessTime;
+	pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
+	pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
+	pfad->nFileSizeLow     = FileData.nFileSizeLow;
+	return TRUE;
+}
+
+static BOOL
+attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
+{
+	HANDLE hFindFile;
+	WIN32_FIND_DATAW FileData;
+	hFindFile = FindFirstFileW(pszFile, &FileData);
+	if (hFindFile == INVALID_HANDLE_VALUE)
+		return FALSE;
+	FindClose(hFindFile);
+	pfad->dwFileAttributes = FileData.dwFileAttributes;
+	pfad->ftCreationTime   = FileData.ftCreationTime;
+	pfad->ftLastAccessTime = FileData.ftLastAccessTime;
+	pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
+	pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
+	pfad->nFileSizeLow     = FileData.nFileSizeLow;
+	return TRUE;
+}
+
 static BOOL WINAPI
 Py_GetFileAttributesExA(LPCSTR pszFile, 
 		       GET_FILEEX_INFO_LEVELS level,
                        LPVOID pv)
 {
 	BOOL result;
-	HANDLE hFindFile;
-	WIN32_FIND_DATAA FileData;
 	LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
 	/* First try to use the system's implementation, if that is
 	   available and either succeeds to gives an error other than
@@ -873,17 +906,7 @@
 	   accept). */
 	if (GetFileAttributesA(pszFile) == 0xFFFFFFFF)
 		return FALSE;
-	hFindFile = FindFirstFileA(pszFile, &FileData);
-	if (hFindFile == INVALID_HANDLE_VALUE)
-		return FALSE;
-	FindClose(hFindFile);
-	pfad->dwFileAttributes = FileData.dwFileAttributes;
-	pfad->ftCreationTime   = FileData.ftCreationTime;
-	pfad->ftLastAccessTime = FileData.ftLastAccessTime;
-	pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
-	pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
-	pfad->nFileSizeLow     = FileData.nFileSizeLow;
-	return TRUE;
+	return attributes_from_dir(pszFile, pfad);
 }
 
 static BOOL WINAPI
@@ -892,8 +915,6 @@
                        LPVOID pv)
 {
 	BOOL result;
-	HANDLE hFindFile;
-	WIN32_FIND_DATAW FileData;
 	LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
 	/* First try to use the system's implementation, if that is
 	   available and either succeeds to gives an error other than
@@ -915,17 +936,7 @@
 	   accept). */
 	if (GetFileAttributesW(pszFile) == 0xFFFFFFFF)
 		return FALSE;
-	hFindFile = FindFirstFileW(pszFile, &FileData);
-	if (hFindFile == INVALID_HANDLE_VALUE)
-		return FALSE;
-	FindClose(hFindFile);
-	pfad->dwFileAttributes = FileData.dwFileAttributes;
-	pfad->ftCreationTime   = FileData.ftCreationTime;
-	pfad->ftLastAccessTime = FileData.ftLastAccessTime;
-	pfad->ftLastWriteTime  = FileData.ftLastWriteTime;
-	pfad->nFileSizeHigh    = FileData.nFileSizeHigh;
-	pfad->nFileSizeLow     = FileData.nFileSizeLow;
-	return TRUE;
+	return attributes_from_dir_w(pszFile, pfad);
 }
 
 static int 
@@ -936,10 +947,20 @@
 	char *dot;
 	/* XXX not supported on Win95 and NT 3.x */
 	if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
-		/* Protocol violation: we explicitly clear errno, instead of
-		   setting it to a POSIX error. Callers should use GetLastError. */
-		errno = 0;
-		return -1;
+		if (GetLastError() != ERROR_SHARING_VIOLATION) {
+			/* Protocol violation: we explicitly clear errno, instead of
+			   setting it to a POSIX error. Callers should use GetLastError. */
+			errno = 0;
+			return -1;
+		} else {
+			/* Could not get attributes on open file. Fall back to
+			   reading the directory. */
+			if (!attributes_from_dir(path, &info)) {
+				/* Very strange. This should not fail now */
+				errno = 0;
+				return -1;
+			}
+		}
 	}
 	code = attribute_data_to_stat(&info, result);
 	if (code != 0)
@@ -964,10 +985,20 @@
 	WIN32_FILE_ATTRIBUTE_DATA info;
 	/* XXX not supported on Win95 and NT 3.x */
 	if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
-		/* Protocol violation: we explicitly clear errno, instead of
-		   setting it to a POSIX error. Callers should use GetLastError. */
-		errno = 0;
-		return -1;
+		if (GetLastError() != ERROR_SHARING_VIOLATION) {
+			/* Protocol violation: we explicitly clear errno, instead of
+			   setting it to a POSIX error. Callers should use GetLastError. */
+			errno = 0;
+			return -1;
+		} else {
+			/* Could not get attributes on open file. Fall back to
+			   reading the directory. */
+			if (!attributes_from_dir_w(path, &info)) {
+				/* Very strange. This should not fail now */
+				errno = 0;
+				return -1;
+			}
+		}
 	}
 	code = attribute_data_to_stat(&info, result);
 	if (code < 0)
@@ -4809,18 +4840,19 @@
 			        (sizeof(modulepath)/sizeof(modulepath[0]))
 			               -strlen(modulepath));
 			if (stat(modulepath, &statinfo) != 0) {
+				size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]);
 				/* Eeek - file-not-found - possibly an embedding
 				   situation - see if we can locate it in sys.prefix
 				*/
 				strncpy(modulepath,
 				        Py_GetExecPrefix(),
-				        sizeof(modulepath)/sizeof(modulepath[0]));
+				        mplen);
+				modulepath[mplen-1] = '\0';
 				if (modulepath[strlen(modulepath)-1] != '\\')
 					strcat(modulepath, "\\");
 				strncat(modulepath,
 				        szConsoleSpawn,
-				        (sizeof(modulepath)/sizeof(modulepath[0]))
-				               -strlen(modulepath));
+				        mplen-strlen(modulepath));
 				/* No where else to look - raise an easily identifiable
 				   error, rather than leaving Windows to report
 				   "file not found" - as the user is probably blissfully
@@ -6215,16 +6247,23 @@
 posix_fdopen(PyObject *self, PyObject *args)
 {
 	int fd;
-	char *mode = "r";
+	char *orgmode = "r";
 	int bufsize = -1;
 	FILE *fp;
 	PyObject *f;
-	if (!PyArg_ParseTuple(args, "i|si", &fd, &mode, &bufsize))
+	char *mode;
+	if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize))
 		return NULL;
 
-	if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
-		PyErr_Format(PyExc_ValueError,
-			     "invalid file mode '%s'", mode);
+	/* Sanitize mode.  See fileobject.c */
+	mode = PyMem_MALLOC(strlen(orgmode)+3);
+	if (!mode) {
+		PyErr_NoMemory();
+		return NULL;
+	}
+	strcpy(mode, orgmode);
+	if (_PyFile_SanitizeMode(mode)) {
+		PyMem_FREE(mode);
 		return NULL;
 	}
 	Py_BEGIN_ALLOW_THREADS
@@ -6246,9 +6285,10 @@
 	fp = fdopen(fd, mode);
 #endif
 	Py_END_ALLOW_THREADS
+	PyMem_FREE(mode);
 	if (fp == NULL)
 		return posix_error();
-	f = PyFile_FromFile(fp, "<fdopen>", mode, fclose);
+	f = PyFile_FromFile(fp, "<fdopen>", orgmode, fclose);
 	if (f != NULL)
 		PyFile_SetBufSize(f, bufsize);
 	return f;

Deleted: /python/branches/p3yk-noslice/Modules/puremodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/puremodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,988 +0,0 @@
-/* This module exports the C API to such Pure Software Inc. (tm) (now
- * called Pure Atria Corporation) products as Purify (tm) and Quantify
- * (tm).  Other packages could be added, but I didn't have those products
- * and thus lack the API documentation.
- *
- * Currently supported: Quantify 2.x, Purify 3.x
- *
- * You need to decide which products you want to incorporate into the
- * module when you compile this file.  The way to do this is to edit
- * <Python>/Modules/Setup to pass the appropriate flags to the compiler.
- * -DWITH_PURIFY compiles in the Purify support, and -DWITH_QUANTIFY
- * compiles in the Quantify support.  -DWITH_ALL_PURE compiles in both.
- * You can also build a Purify'd or Quantify'd interpreter by passing in
- * the LINKCC variable to make.  E.g. if you want to build a Purify'd
- * interpreter and are using gcc, build Python with this command:
- *
- * make LINKCC='purify gcc'
- *
- * It would be nice (and probably easy) to provide this file as a shared
- * library, however since it doesn't appear that Pure gives us shared
- * libraries of the stubs, it doesn't really matter.  For now, you have to
- * link this file in statically.
- *
- * Major bogosity.  The purify.h header file exports purify_exit(), but
- * guess what?  It is not defined in the libpurify_stubs.a file!  I tried
- * to fake one here, hoping the Pure linker would Do The Right Thing when
- * instrumented for Purify, but it doesn't seem to, so I don't export
- * purify_exit() to the Python layer.  In Python you should raise a
- * SystemExit exception anyway.
- *
- * The actual purify.h and quantify.h files which embody the APIs are
- * copyrighted by Pure Software, Inc. and are only attainable through them.
- * This module assumes you have legally installed licenses of their
- * software.  Contact them on the Web via <http://www.pureatria.com/>
- *
- * Author: Barry Warsaw <bwarsaw at python.org>
- *                      <bwarsaw at cnri.reston.va.us>
- */
-
-#include "Python.h"
-
-#if defined(WITH_PURIFY) || defined(WITH_ALL_PURE)
-#    include <purify.h>
-#    define HAS_PURIFY_EXIT 0                /* See note at top of file */
-#    define PURE_PURIFY_VERSION 3            /* not provided by purify.h */
-#endif
-#if defined(WITH_QUANTIFY) || defined(WITH_ALL_PURE)
-#    include <quantify.h>
-#    define PURE_QUANTIFY_VERSION 2          /* not provided by quantify.h */
-#endif
-#if defined(PURIFY_H) || defined(QUANTIFY_H)
-#    define COMMON_PURE_FUNCTIONS
-#endif /* PURIFY_H || QUANTIFY_H */
-
-typedef int (*VoidArgFunc)(void);
-typedef int (*StringArgFunc)(char*);
-typedef int (*PrintfishFunc)(const char*, ...);
-typedef int (*StringIntArgFunc)(const char*, int);
-
-
-
-static PyObject*
-call_voidarg_function(VoidArgFunc func, PyObject *self, PyObject *args)
-{
-	int status;
-
-	if (!PyArg_ParseTuple(args, ""))
-		return NULL;
-
-	status = func();
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-call_stringarg_function(StringArgFunc func, PyObject *self, PyObject *args)
-{
-	int status;
-	char* stringarg;
-
-	if (!PyArg_ParseTuple(args, "s", &stringarg))
-		return NULL;
-
-	status = func(stringarg);
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-call_stringorint_function(StringArgFunc func, PyObject *self, PyObject *args)
-{
-	int status;
-	int intarg;
-	char* stringarg;
-
-        /* according to the quantify.h file, the argument to
-         * quantify_*_recording_system_call can be an integer or a string,
-	 * but the functions are prototyped as taking a single char*
-	 * argument. Yikes!
-         */
-	if (PyArg_ParseTuple(args, "i", &intarg))
-		/* func is prototyped as int(*)(char*)
-		 * better shut up the compiler
-		 */
-		status = func((char*)intarg);
-
-	else {
-		PyErr_Clear();
-		if (!PyArg_ParseTuple(args, "s", &stringarg))
-			return NULL;
-		else
-			status = func(stringarg);
-	}
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-call_printfish_function(PrintfishFunc func, PyObject *self, PyObject *args)
-{
-	/* we support the printf() style vararg functions by requiring the
-         * formatting be done in Python.  At the C level we pass just a string
-         * to the printf() style function.
-         */
-	int status;
-	char* argstring;
-
-	if (!PyArg_ParseTuple(args, "s", &argstring))
-		return NULL;
-
-	status = func("%s", argstring);
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-call_intasaddr_function(StringArgFunc func, PyObject *self, PyObject *args)
-{
-	long memrep;
-	int id;
-
-	if (!PyArg_ParseTuple(args, "l", &memrep))
-		return NULL;
-
-	id = func((char*)memrep);
-	return Py_BuildValue("i", id);
-}
-
-static PyObject*
-call_stringandint_function(StringIntArgFunc func, PyObject *self,
-			   PyObject *args)
-{
-	long srcrep;
-	int size;
-	int status;
-
-	if (!PyArg_ParseTuple(args, "li", &srcrep, &size))
-		return NULL;
-
-	status = func((char*)srcrep, size);
-	return Py_BuildValue("i", status);
-}
-
-
-
-/* functions common to all products
- *
- * N.B. These printf() style functions are a bit of a kludge.  Since the
- * API doesn't provide vprintf versions of them, we can't call them
- * directly.  They don't support all the standard printf % modifiers
- * anyway.  The way to use these is to use Python's % string operator to do
- * the formatting.  By the time these functions get the thing to print,
- * it's already a string, and they just use "%s" as the format string.
- */
-
-#ifdef COMMON_PURE_FUNCTIONS
-
-static PyObject*
-pure_pure_logfile_printf(PyObject* self, PyObject* args)
-{
-	return call_printfish_function(pure_logfile_printf, self, args);
-}
-
-static PyObject*
-pure_pure_printf(PyObject* self, PyObject* args)
-{
-	return call_printfish_function(pure_printf, self, args);
-}
-
-static PyObject*
-pure_pure_printf_with_banner(PyObject* self, PyObject* args)
-{
-	return call_printfish_function(pure_printf_with_banner, self, args);
-}
-
-
-#endif /* COMMON_PURE_FUNCTIONS */
-
-
-
-/* Purify functions
- *
- * N.B. There are some interfaces described in the purify.h file that are
- * not described in the manual.
- *
- * Unsigned longs purify_report_{address,number,type,result} are not
- * accessible from the Python layer since they seem mostly useful when
- * purify_stop_here() is called by the (C) debugger.  The same is true of
- * the purify_stop_here_internal() function so it isn't exported either.
- * And purify_stop_here() should never be called directly.
- *
- * The header file says purify_{new,all,clear_new}_reports() are obsolete
- * so they aren't exported.
- *
- * None of the custom dynamic loader functions are exported.
- *
- * purify_unsafe_memcpy() isn't exported.
- *
- * purify_{start,size}_of_block() aren't exported.
- *
- * The manual that I have says that the prototype for the second argument
- * to purify_map_pool is:
- *
- *    void (*fn)(char*)
- *
- * but the purify.h file declares it as:
- *
- *    void (*fn)(char*, int, void*)
- *
- * and does not explain what the other arguments are for.  I support the
- * latter but I don't know if I do it right or usefully.
- *
- * The header file says that purify_describe() returns a char* which is the
- * pointer passed to it.  The manual says it returns an int, but I believe
- * that is a typo.
- */
-#ifdef PURIFY_H
-
-static PyObject*
-pure_purify_all_inuse(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_all_inuse, self, args);
-}
-static PyObject*
-pure_purify_all_leaks(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_all_leaks, self, args);
-}
-static PyObject*
-pure_purify_new_inuse(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_new_inuse, self, args);
-}
-static PyObject*
-pure_purify_new_leaks(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_new_leaks, self, args);
-}
-static PyObject*
-pure_purify_clear_inuse(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_clear_inuse, self, args);
-}
-static PyObject*
-pure_purify_clear_leaks(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_clear_leaks, self, args);
-}
-static PyObject*
-pure_purify_all_fds_inuse(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_all_fds_inuse, self, args);
-}
-static PyObject*
-pure_purify_new_fds_inuse(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_new_fds_inuse, self, args);
-}
-static PyObject*
-pure_purify_printf_with_call_chain(PyObject *self, PyObject *args)
-{
-	return call_printfish_function(purify_printf_with_call_chain,
-				       self, args);
-}
-static PyObject*
-pure_purify_set_pool_id(PyObject *self, PyObject *args)
-{
-	long memrep;
-	int id;
-
-	if (!PyArg_ParseTuple(args, "li:purify_set_pool_id", &memrep, &id))
-		return NULL;
-
-	purify_set_pool_id((char*)memrep, id);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-static PyObject*
-pure_purify_get_pool_id(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_get_pool_id, self, args);
-}
-static PyObject*
-pure_purify_set_user_data(PyObject *self, PyObject *args)
-{
-	long memrep;
-	long datarep;
-
-	if (!PyArg_ParseTuple(args, "ll:purify_set_user_data", &memrep, &datarep))
-		return NULL;
-
-	purify_set_user_data((char*)memrep, (void*)datarep);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-static PyObject*
-pure_purify_get_user_data(PyObject *self, PyObject *args)
-{
-        /* can't use call_intasaddr_function() since purify_get_user_data()
-         * returns a void*
-         */
-	long memrep;
-	void* data;
-
-	if (!PyArg_ParseTuple(args, "l:purify_get_user_data", &memrep))
-		return NULL;
-
-	data = purify_get_user_data((char*)memrep);
-	return Py_BuildValue("l", (long)data);
-}
-
-
-/* this global variable is shared by both mapping functions:
- * pure_purify_map_pool() and pure_purify_map_pool_id().  Since they cache
- * this variable it should be safe in the face of recursion or cross
- * calling.
- *
- * Further note that the prototype for the callback function is wrong in
- * the Purify manual.  The manual says the function takes a single char*,
- * but the header file says it takes an additional int and void*.  I have
- * no idea what these are for!
- */
-static PyObject* MapCallable = NULL;
-
-static void
-map_pool_callback(char* mem, int user_size, void *user_aux_data)
-{
-	long memrep = (long)mem;
-	long user_aux_data_rep = (long)user_aux_data;
-	PyObject* result;
-	PyObject* memobj = Py_BuildValue("lil", memrep, user_size,
-					 user_aux_data_rep);
-
-	if (memobj == NULL)
-		return;
-
-	result = PyEval_CallObject(MapCallable, memobj);
-	Py_DECREF(result);
-	Py_DECREF(memobj);
-}
-
-static PyObject*
-pure_purify_map_pool(PyObject *self, PyObject *args)
-{
-        /* cache global variable in case of recursion */
-	PyObject* saved_callable = MapCallable;
-	PyObject* arg_callable;
-	int id;
-
-	if (!PyArg_ParseTuple(args, "iO:purify_map_pool", &id, &arg_callable))
-		return NULL;
-
-	if (!PyCallable_Check(arg_callable)) {
-		PyErr_SetString(PyExc_TypeError,
-				"Second argument must be callable");
-		return NULL;
-	}
-	MapCallable = arg_callable;
-	purify_map_pool(id, map_pool_callback);
-	MapCallable = saved_callable;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static void
-PurifyMapPoolIdCallback(int id)
-{
-	PyObject* result;
-	PyObject* intobj = Py_BuildValue("i", id);
-
-	if (intobj == NULL)
-		return;
-
-	result = PyEval_CallObject(MapCallable, intobj);
-	Py_DECREF(result);
-	Py_DECREF(intobj);
-}
-
-static PyObject*
-pure_purify_map_pool_id(PyObject *self, PyObject *args)
-{
-        /* cache global variable in case of recursion */
-	PyObject* saved_callable = MapCallable;
-	PyObject* arg_callable;
-
-	if (!PyArg_ParseTuple(args, "O:purify_map_pool_id", &arg_callable))
-		return NULL;
-
-	if (!PyCallable_Check(arg_callable)) {
-		PyErr_SetString(PyExc_TypeError, "Argument must be callable.");
-		return NULL;
-	}
-
-	MapCallable = arg_callable;
-	purify_map_pool_id(PurifyMapPoolIdCallback);
-	MapCallable = saved_callable;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-
-
-static PyObject*
-pure_purify_new_messages(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_new_messages, self, args);
-}
-static PyObject*
-pure_purify_all_messages(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_all_messages, self, args);
-}
-static PyObject*
-pure_purify_clear_messages(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_clear_messages, self, args);
-}
-static PyObject*
-pure_purify_clear_new_messages(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_clear_new_messages, self, args);
-}
-static PyObject*
-pure_purify_start_batch(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_start_batch, self, args);
-}
-static PyObject*
-pure_purify_start_batch_show_first(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_start_batch_show_first,
-				     self, args);
-}
-static PyObject*
-pure_purify_stop_batch(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_stop_batch, self, args);
-}
-static PyObject*
-pure_purify_name_thread(PyObject *self, PyObject *args)
-{
-        /* can't strictly use call_stringarg_function since
-         * purify_name_thread takes a const char*, not a char*
-         */
-	int status;
-	char* stringarg;
-
-	if (!PyArg_ParseTuple(args, "s:purify_name_thread", &stringarg))
-		return NULL;
-
-	status = purify_name_thread(stringarg);
-	return Py_BuildValue("i", status);
-}
-static PyObject*
-pure_purify_watch(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch, self, args);
-}
-static PyObject*
-pure_purify_watch_1(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_1, self, args);
-}
-static PyObject*
-pure_purify_watch_2(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_2, self, args);
-}
-static PyObject*
-pure_purify_watch_4(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_4, self, args);
-}
-static PyObject*
-pure_purify_watch_8(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_8, self, args);
-}
-static PyObject*
-pure_purify_watch_w_1(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_w_1, self, args);
-}
-static PyObject*
-pure_purify_watch_w_2(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_w_2, self, args);
-}
-static PyObject*
-pure_purify_watch_w_4(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_w_4, self, args);
-}
-static PyObject*
-pure_purify_watch_w_8(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_w_8, self, args);
-}
-static PyObject*
-pure_purify_watch_r_1(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_r_1, self, args);
-}
-static PyObject*
-pure_purify_watch_r_2(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_r_2, self, args);
-}
-static PyObject*
-pure_purify_watch_r_4(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_r_4, self, args);
-}
-static PyObject*
-pure_purify_watch_r_8(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_r_8, self, args);
-}
-static PyObject*
-pure_purify_watch_rw_1(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_rw_1, self, args);
-}
-static PyObject*
-pure_purify_watch_rw_2(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_rw_2, self, args);
-}
-static PyObject*
-pure_purify_watch_rw_4(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_rw_4, self, args);
-}
-static PyObject*
-pure_purify_watch_rw_8(PyObject *self, PyObject *args)
-{
-	return call_intasaddr_function(purify_watch_rw_8, self, args);
-}
-
-static PyObject*
-pure_purify_watch_n(PyObject *self, PyObject *args)
-{
-	long addrrep;
-	unsigned int size;
-	char* type;
-	int status;
-
-	if (!PyArg_ParseTuple(args, "lis:purify_watch_n", &addrrep, &size, &type))
-		return NULL;
-
-	status = purify_watch_n((char*)addrrep, size, type);
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-pure_purify_watch_info(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_watch_info, self, args);
-}
-
-static PyObject*
-pure_purify_watch_remove(PyObject *self, PyObject *args)
-{
-	int watchno;
-	int status;
-
-	if (!PyArg_ParseTuple(args, "i:purify_watch_remove", &watchno))
-		return NULL;
-
-	status = purify_watch_remove(watchno);
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-pure_purify_watch_remove_all(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_watch_remove_all, self, args);
-}
-static PyObject*
-pure_purify_describe(PyObject *self, PyObject *args)
-{
-	long addrrep;
-	char* rtn;
-
-	if (!PyArg_ParseTuple(args, "l:purify_describe", &addrrep))
-		return NULL;
-
-	rtn = purify_describe((char*)addrrep);
-	return Py_BuildValue("l", (long)rtn);
-}
-
-static PyObject*
-pure_purify_what_colors(PyObject *self, PyObject *args)
-{
-	long addrrep;
-	unsigned int size;
-	int status;
-    
-	if (!PyArg_ParseTuple(args, "li:purify_what_colors", &addrrep, &size))
-		return NULL;
-
-	status = purify_what_colors((char*)addrrep, size);
-	return Py_BuildValue("i", status);
-}
-
-static PyObject*
-pure_purify_is_running(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(purify_is_running, self, args);
-}
-
-static PyObject*
-pure_purify_assert_is_readable(PyObject *self, PyObject *args)
-{
-	return call_stringandint_function(purify_assert_is_readable,
-					  self, args);
-}
-static PyObject*
-pure_purify_assert_is_writable(PyObject *self, PyObject *args)
-{
-	return call_stringandint_function(purify_assert_is_writable,
-					  self, args);
-}
-
-#if HAS_PURIFY_EXIT
-
-/* I wish I could include this, but I can't.  See the notes at the top of
- * the file.
- */
-
-static PyObject*
-pure_purify_exit(PyObject *self, PyObject *args)
-{
-	int status;
-
-	if (!PyArg_ParseTuple(args, "i:purify_exit", &status))
-		return NULL;
-
-        /* purify_exit doesn't always act like exit(). See the manual */
-	purify_exit(status);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-#endif /* HAS_PURIFY_EXIT */
-
-#endif /* PURIFY_H */
-
-
-
-/* Quantify functions
- *
- * N.B. Some of these functions are only described in the quantify.h file,
- * not in the version of the hardcopy manual that I had.  If you're not
- * sure what some of these do, check the header file, it is documented
- * fairly well.
- *
- * None of the custom dynamic loader functions are exported.
- *
- */
-#ifdef QUANTIFY_H
-
-static PyObject*
-pure_quantify_is_running(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_is_running, self, args);
-}
-static PyObject*
-pure_quantify_help(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_help, self, args);
-}
-static PyObject*
-pure_quantify_print_recording_state(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_print_recording_state,
-				     self, args);
-}
-static PyObject*
-pure_quantify_start_recording_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_start_recording_data,
-				     self, args);
-}
-static PyObject*
-pure_quantify_stop_recording_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_stop_recording_data, self, args);
-}
-static PyObject*
-pure_quantify_is_recording_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_is_recording_data, self, args);
-}
-static PyObject*
-pure_quantify_start_recording_system_calls(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_start_recording_system_calls,
-				     self, args);
-}
-static PyObject*
-pure_quantify_stop_recording_system_calls(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_stop_recording_system_calls,
-				     self, args);
-}
-static PyObject*
-pure_quantify_is_recording_system_calls(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_is_recording_system_calls,
-				     self, args);
-}
-static PyObject*
-pure_quantify_start_recording_system_call(PyObject *self, PyObject *args)
-{
-	return call_stringorint_function(quantify_start_recording_system_call,
-					   self, args);
-}
-static PyObject*
-pure_quantify_stop_recording_system_call(PyObject *self, PyObject *args)
-{
-	return call_stringorint_function(quantify_stop_recording_system_call,
-					 self, args);
-}
-static PyObject*
-pure_quantify_is_recording_system_call(PyObject *self, PyObject *args)
-{
-	return call_stringorint_function(quantify_is_recording_system_call,
-					 self, args);
-}
-static PyObject*
-pure_quantify_start_recording_dynamic_library_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(
-		quantify_start_recording_dynamic_library_data,
-		self, args);
-}
-static PyObject*
-pure_quantify_stop_recording_dynamic_library_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(
-		quantify_stop_recording_dynamic_library_data,
-		self, args);
-}
-static PyObject*
-pure_quantify_is_recording_dynamic_library_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(
-		quantify_is_recording_dynamic_library_data,
-		self, args);
-}
-static PyObject*
-pure_quantify_start_recording_register_window_traps(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(
-		quantify_start_recording_register_window_traps,
-		self, args);
-}
-static PyObject*
-pure_quantify_stop_recording_register_window_traps(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(
-		quantify_stop_recording_register_window_traps,
-		self, args);
-}
-static PyObject*
-pure_quantify_is_recording_register_window_traps(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(
-		quantify_is_recording_register_window_traps,
-		self, args);
-}
-static PyObject*
-pure_quantify_disable_recording_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_disable_recording_data,
-				     self, args);
-}
-static PyObject*
-pure_quantify_clear_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_clear_data, self, args);
-}
-static PyObject*
-pure_quantify_save_data(PyObject *self, PyObject *args)
-{
-	return call_voidarg_function(quantify_save_data, self, args);
-}
-static PyObject*
-pure_quantify_save_data_to_file(PyObject *self, PyObject *args)
-{
-	return call_stringarg_function(quantify_save_data_to_file, self, args);
-}
-static PyObject*
-pure_quantify_add_annotation(PyObject *self, PyObject *args)
-{
-	return call_stringarg_function(quantify_add_annotation, self, args);
-}
-
-#endif /* QUANTIFY_H */
-
-
-
-/* external interface
- */
-static struct PyMethodDef
-pure_methods[] = {
-#ifdef COMMON_PURE_FUNCTIONS
-    {"pure_logfile_printf",            pure_pure_logfile_printf,            METH_VARARGS},
-    {"pure_printf",                    pure_pure_printf,                    METH_VARARGS},
-    {"pure_printf_with_banner",        pure_pure_printf_with_banner,        METH_VARARGS},
-#endif /* COMMON_PURE_FUNCTIONS */
-#ifdef PURIFY_H
-    {"purify_all_inuse",               pure_purify_all_inuse,               METH_VARARGS},
-    {"purify_all_leaks",               pure_purify_all_leaks,               METH_VARARGS},
-    {"purify_new_inuse",               pure_purify_new_inuse,               METH_VARARGS},
-    {"purify_new_leaks",               pure_purify_new_leaks,               METH_VARARGS},
-    {"purify_clear_inuse",             pure_purify_clear_inuse,             METH_VARARGS},
-    {"purify_clear_leaks",             pure_purify_clear_leaks,             METH_VARARGS},
-    {"purify_all_fds_inuse",           pure_purify_all_fds_inuse,           METH_VARARGS},
-    {"purify_new_fds_inuse",           pure_purify_new_fds_inuse,           METH_VARARGS},
-    /* see purify.h */
-    {"purify_logfile_printf",          pure_pure_logfile_printf,            METH_VARARGS},
-    {"purify_printf",                  pure_pure_printf,                    METH_VARARGS},
-    {"purify_printf_with_banner",      pure_pure_printf_with_banner,        METH_VARARGS},
-    /**/
-    {"purify_printf_with_call_chain",  pure_purify_printf_with_call_chain,  METH_VARARGS},
-    {"purify_set_pool_id",             pure_purify_set_pool_id,             METH_VARARGS},
-    {"purify_get_pool_id",             pure_purify_get_pool_id,             METH_VARARGS},
-    {"purify_set_user_data",           pure_purify_set_user_data,           METH_VARARGS},
-    {"purify_get_user_data",           pure_purify_get_user_data,           METH_VARARGS},
-    {"purify_map_pool",                pure_purify_map_pool,                METH_VARARGS},
-    {"purify_map_pool_id",             pure_purify_map_pool_id,             METH_VARARGS},
-    {"purify_new_messages",            pure_purify_new_messages,            METH_VARARGS},
-    {"purify_all_messages",            pure_purify_all_messages,            METH_VARARGS},
-    {"purify_clear_messages",          pure_purify_clear_messages,          METH_VARARGS},
-    {"purify_clear_new_messages",      pure_purify_clear_new_messages,      METH_VARARGS},
-    {"purify_start_batch",             pure_purify_start_batch,             METH_VARARGS},
-    {"purify_start_batch_show_first",  pure_purify_start_batch_show_first,  METH_VARARGS},
-    {"purify_stop_batch",              pure_purify_stop_batch,              METH_VARARGS},
-    {"purify_name_thread",             pure_purify_name_thread,             METH_VARARGS},
-    {"purify_watch",                   pure_purify_watch,                   METH_VARARGS},
-    {"purify_watch_1",                 pure_purify_watch_1,                 METH_VARARGS},
-    {"purify_watch_2",                 pure_purify_watch_2,                 METH_VARARGS},
-    {"purify_watch_4",                 pure_purify_watch_4,                 METH_VARARGS},
-    {"purify_watch_8",                 pure_purify_watch_8,                 METH_VARARGS},
-    {"purify_watch_w_1",               pure_purify_watch_w_1,               METH_VARARGS},
-    {"purify_watch_w_2",               pure_purify_watch_w_2,               METH_VARARGS},
-    {"purify_watch_w_4",               pure_purify_watch_w_4,               METH_VARARGS},
-    {"purify_watch_w_8",               pure_purify_watch_w_8,               METH_VARARGS},
-    {"purify_watch_r_1",               pure_purify_watch_r_1,               METH_VARARGS},
-    {"purify_watch_r_2",               pure_purify_watch_r_2,               METH_VARARGS},
-    {"purify_watch_r_4",               pure_purify_watch_r_4,               METH_VARARGS},
-    {"purify_watch_r_8",               pure_purify_watch_r_8,               METH_VARARGS},
-    {"purify_watch_rw_1",              pure_purify_watch_rw_1,              METH_VARARGS},
-    {"purify_watch_rw_2",              pure_purify_watch_rw_2,              METH_VARARGS},
-    {"purify_watch_rw_4",              pure_purify_watch_rw_4,              METH_VARARGS},
-    {"purify_watch_rw_8",              pure_purify_watch_rw_8,              METH_VARARGS},
-    {"purify_watch_n",                 pure_purify_watch_n,                 METH_VARARGS},
-    {"purify_watch_info",              pure_purify_watch_info,              METH_VARARGS},
-    {"purify_watch_remove",            pure_purify_watch_remove,            METH_VARARGS},
-    {"purify_watch_remove_all",        pure_purify_watch_remove_all,        METH_VARARGS},
-    {"purify_describe",                pure_purify_describe,                METH_VARARGS},
-    {"purify_what_colors",             pure_purify_what_colors,             METH_VARARGS},
-    {"purify_is_running",              pure_purify_is_running,              METH_VARARGS},
-    {"purify_assert_is_readable",      pure_purify_assert_is_readable,      METH_VARARGS},
-    {"purify_assert_is_writable",      pure_purify_assert_is_writable,      METH_VARARGS},
-#if HAS_PURIFY_EXIT
-    /* I wish I could include this, but I can't.  See the notes at the
-     * top of the file.
-     */
-    {"purify_exit",                    pure_purify_exit,                    METH_VARARGS},
-#endif /* HAS_PURIFY_EXIT */
-#endif /* PURIFY_H */
-#ifdef QUANTIFY_H
-    {"quantify_is_running",            pure_quantify_is_running,            METH_VARARGS},
-    {"quantify_help",                  pure_quantify_help,                  METH_VARARGS},
-    {"quantify_print_recording_state", pure_quantify_print_recording_state, METH_VARARGS},
-    {"quantify_start_recording_data",  pure_quantify_start_recording_data,  METH_VARARGS},
-    {"quantify_stop_recording_data",   pure_quantify_stop_recording_data,   METH_VARARGS},
-    {"quantify_is_recording_data",     pure_quantify_is_recording_data,  METH_VARARGS},
-    {"quantify_start_recording_system_calls",
-     pure_quantify_start_recording_system_calls, METH_VARARGS},
-    {"quantify_stop_recording_system_calls",
-     pure_quantify_stop_recording_system_calls, METH_VARARGS},
-    {"quantify_is_recording_system_calls",
-     pure_quantify_is_recording_system_calls, METH_VARARGS},
-    {"quantify_start_recording_system_call",
-     pure_quantify_start_recording_system_call, METH_VARARGS},
-    {"quantify_stop_recording_system_call",
-     pure_quantify_stop_recording_system_call, METH_VARARGS},
-    {"quantify_is_recording_system_call",
-     pure_quantify_is_recording_system_call, METH_VARARGS},
-    {"quantify_start_recording_dynamic_library_data",
-     pure_quantify_start_recording_dynamic_library_data, METH_VARARGS},
-    {"quantify_stop_recording_dynamic_library_data",
-     pure_quantify_stop_recording_dynamic_library_data, METH_VARARGS},
-    {"quantify_is_recording_dynamic_library_data",
-     pure_quantify_is_recording_dynamic_library_data, METH_VARARGS},
-    {"quantify_start_recording_register_window_traps",
-     pure_quantify_start_recording_register_window_traps, METH_VARARGS},
-    {"quantify_stop_recording_register_window_traps",
-     pure_quantify_stop_recording_register_window_traps, METH_VARARGS},
-    {"quantify_is_recording_register_window_traps",
-     pure_quantify_is_recording_register_window_traps, METH_VARARGS},
-    {"quantify_disable_recording_data",
-     pure_quantify_disable_recording_data, METH_VARARGS},
-    {"quantify_clear_data",        pure_quantify_clear_data,        METH_VARARGS},
-    {"quantify_save_data",         pure_quantify_save_data,         METH_VARARGS},
-    {"quantify_save_data_to_file", pure_quantify_save_data_to_file, METH_VARARGS},
-    {"quantify_add_annotation",    pure_quantify_add_annotation,    METH_VARARGS},
-#endif /* QUANTIFY_H */
-    {NULL,  NULL}			     /* sentinel */
-};
-
-
-
-static void
-ins(d, name, val)
-	PyObject *d;
-	char* name;
-	long val;
-{
-	PyObject *v = PyInt_FromLong(val);
-	if (v) {
-		(void)PyDict_SetItemString(d, name, v);
-		Py_DECREF(v);
-	}
-}
-
-
-void
-initpure()
-{
-	PyObject *m, *d;
-
-	m = Py_InitModule("pure", pure_methods);
-	if (m == NULL)
-    		return;
-	d = PyModule_GetDict(m);
-
-        /* this is bogus because we should be able to find this information
-         * out from the header files.  Pure's current versions don't
-         * include this information!
-         */
-#ifdef PURE_PURIFY_VERSION
-	ins(d, "PURIFY_VERSION", PURE_PURIFY_VERSION);
-#else
-	PyDict_SetItemString(d, "PURIFY_VERSION", Py_None);
-#endif
-
-        /* these aren't terribly useful because purify_exit() isn't
-         * exported correctly.  See the note at the top of the file.
-         */
-#ifdef PURIFY_EXIT_ERRORS
-	ins(d, "PURIFY_EXIT_ERRORS", PURIFY_EXIT_ERRORS);
-#endif
-#ifdef PURIFY_EXIT_LEAKS
-	ins(d, "PURIFY_EXIT_LEAKS",  PURIFY_EXIT_LEAKS);
-#endif
-#ifdef PURIFY_EXIT_PLEAKS
-	ins(d, "PURIFY_EXIT_PLEAKS", PURIFY_EXIT_PLEAKS);
-#endif
-
-
-#ifdef PURE_QUANTIFY_VERSION
-	ins(d, "QUANTIFY_VERSION", PURE_QUANTIFY_VERSION);
-#else
-	PyDict_SetItemString(d, "QUANTIFY_VERSION", Py_None);
-#endif
-}

Modified: python/branches/p3yk-noslice/Modules/readline.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/readline.c	(original)
+++ python/branches/p3yk-noslice/Modules/readline.c	Wed Jul 11 15:40:56 2007
@@ -34,6 +34,8 @@
 #ifdef HAVE_RL_COMPLETION_MATCHES
 #define completion_matches(x, y) \
 	rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
+#else
+extern char **completion_matches(char *, rl_compentry_func_t *);
 #endif
 
 
@@ -632,7 +634,7 @@
 /* C function to call the Python completer. */
 
 static char *
-on_completion(char *text, int state)
+on_completion(const char *text, int state)
 {
 	char *result = NULL;
 	if (completer != NULL) {

Deleted: /python/branches/p3yk-noslice/Modules/rgbimgmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/rgbimgmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,780 +0,0 @@
-/*
- *   	fastimg -
- *		Faster reading and writing of image files.
- *
- *      This code should work on machines with any byte order.
- *
- *	Could someone make this run real fast using multiple processors 
- *	or how about using memory mapped files to speed it up?
- *
- *				Paul Haeberli - 1991
- *
- *	Changed to return sizes.
- *				Sjoerd Mullender - 1993
- *	Changed to incorporate into Python.
- *				Sjoerd Mullender - 1993
- */
-#include "Python.h"
-
-#if SIZEOF_INT == 4
-typedef int Py_Int32;
-typedef unsigned int Py_UInt32;
-#else
-#if SIZEOF_LONG == 4
-typedef long Py_Int32;
-typedef unsigned long Py_UInt32;
-#else
-#error "No 4-byte integral type"
-#endif
-#endif
-
-#include <string.h>
-
-/*
- *	from image.h
- *
- */
-typedef struct {
-	unsigned short	imagic;		/* stuff saved on disk . . */
-	unsigned short 	type;
-	unsigned short 	dim;
-	unsigned short 	xsize;
-	unsigned short 	ysize;
-	unsigned short 	zsize;
-	Py_UInt32 	min;
-	Py_UInt32 	max;
-	Py_UInt32	wastebytes;	
-	char 		name[80];
-	Py_UInt32	colormap;
-
-	Py_Int32	file;		/* stuff used in core only */
-	unsigned short 	flags;
-	short		dorev;
-	short		x;
-	short		y;
-	short		z;
-	short		cnt;
-	unsigned short	*ptr;
-	unsigned short	*base;
-	unsigned short	*tmpbuf;
-	Py_UInt32	offset;
-	Py_UInt32	rleend;		/* for rle images */
-	Py_UInt32	*rowstart;	/* for rle images */
-	Py_Int32	*rowsize;	/* for rle images */
-} IMAGE;
-
-#define IMAGIC 	0732
-
-#define TYPEMASK		0xff00
-#define BPPMASK			0x00ff
-#define ITYPE_VERBATIM		0x0000
-#define ITYPE_RLE		0x0100
-#define ISRLE(type)		(((type) & 0xff00) == ITYPE_RLE)
-#define ISVERBATIM(type)	(((type) & 0xff00) == ITYPE_VERBATIM)
-#define BPP(type)		((type) & BPPMASK)
-#define RLE(bpp)		(ITYPE_RLE | (bpp))
-#define VERBATIM(bpp)		(ITYPE_VERBATIM | (bpp))
-/*
- *	end of image.h stuff
- *
- */
-
-#define RINTLUM (79)
-#define GINTLUM (156)
-#define BINTLUM (21)
-
-#define ILUM(r,g,b)     ((int)(RINTLUM*(r)+GINTLUM*(g)+BINTLUM*(b))>>8)
-
-#define OFFSET_R	3	/* this is byte order dependent */
-#define OFFSET_G	2
-#define OFFSET_B	1
-#define OFFSET_A	0
-
-#define CHANOFFSET(z)	(3-(z))	/* this is byte order dependent */
-
-static void expandrow(unsigned char *, unsigned char *, int);
-static void setalpha(unsigned char *, int);
-static void copybw(Py_Int32 *, int);
-static void interleaverow(unsigned char*, unsigned char*, int, int);
-static int compressrow(unsigned char *, unsigned char *, int, int);
-static void lumrow(unsigned char *, unsigned char *, int);
-
-#ifdef ADD_TAGS
-#define TAGLEN	(5)
-#else
-#define TAGLEN	(0)
-#endif
-
-static PyObject *ImgfileError;
-
-static int reverse_order;
-
-#ifdef ADD_TAGS
-/*
- *	addlongimgtag - 
- *		this is used to extract image data from core dumps.
- *
- */
-static void 
-addlongimgtag(Py_UInt32 *dptr, int xsize, int ysize)
-{
-	dptr = dptr + (xsize * ysize);
-	dptr[0] = 0x12345678;
-	dptr[1] = 0x59493333;
-	dptr[2] = 0x69434222;
-	dptr[3] = xsize;
-	dptr[4] = ysize;
-}
-#endif
-
-/*
- *	byte order independent read/write of shorts and longs.
- *
- */
-static unsigned short
-getshort(FILE *inf)
-{
-	unsigned char buf[2];
-
-	fread(buf, 2, 1, inf);
-	return (buf[0] << 8) + (buf[1] << 0);
-}
-
-static Py_UInt32
-getlong(FILE *inf)
-{
-	unsigned char buf[4];
-
-	fread(buf, 4, 1, inf);
-	return (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + (buf[3] << 0);
-}
-
-static void
-putshort(FILE *outf, unsigned short val)
-{
-	unsigned char buf[2];
-
-	buf[0] = (val >> 8);
-	buf[1] = (val >> 0);
-	fwrite(buf, 2, 1, outf);
-}
-
-static int
-putlong(FILE *outf, Py_UInt32 val)
-{
-	unsigned char buf[4];
-
-	buf[0] = (unsigned char) (val >> 24);
-	buf[1] = (unsigned char) (val >> 16);
-	buf[2] = (unsigned char) (val >> 8);
-	buf[3] = (unsigned char) (val >> 0);
-	return (int)fwrite(buf, 4, 1, outf);
-}
-
-static void
-readheader(FILE *inf, IMAGE *image)
-{
-	memset(image ,0, sizeof(IMAGE));
-	image->imagic = getshort(inf);
-	image->type   = getshort(inf);
-	image->dim    = getshort(inf);
-	image->xsize  = getshort(inf);
-	image->ysize  = getshort(inf);
-	image->zsize  = getshort(inf);
-}
-
-static int
-writeheader(FILE *outf, IMAGE *image)
-{
-	IMAGE t;
-
-	memset(&t, 0, sizeof(IMAGE));
-	fwrite(&t, sizeof(IMAGE), 1, outf);
-	fseek(outf, 0, SEEK_SET);
-	putshort(outf, image->imagic);
-	putshort(outf, image->type);
-	putshort(outf, image->dim);
-	putshort(outf, image->xsize);
-	putshort(outf, image->ysize);
-	putshort(outf, image->zsize);
-	putlong(outf, image->min);
-	putlong(outf, image->max);
-	putlong(outf, 0);
-	return (int)fwrite("no name", 8, 1, outf);
-}
-
-static int
-writetab(FILE *outf, /*unsigned*/ Py_Int32 *tab, int len)
-{
-	int r = 0;
-
-	while(len) {
-		r = putlong(outf, *tab++);
-		len--;
-	}
-	return r;
-}
-
-static void
-readtab(FILE *inf, /*unsigned*/ Py_Int32 *tab, int len)
-{
-	while(len) {
-		*tab++ = getlong(inf);
-		len--;
-	}
-}
-
-/*
- *	sizeofimage - 
- *		return the xsize and ysize of an iris image file.
- *
- */
-static PyObject *
-sizeofimage(PyObject *self, PyObject *args)
-{
-	char *name;
-	IMAGE image;
-	FILE *inf;
-
-	if (!PyArg_ParseTuple(args, "s:sizeofimage", &name))
-		return NULL;
-
-	inf = fopen(name, "rb");
-	if (!inf) {
-		PyErr_SetString(ImgfileError, "can't open image file");
-		return NULL;
-	}
-	readheader(inf, &image);
-	fclose(inf);
-	if (image.imagic != IMAGIC) {
-		PyErr_SetString(ImgfileError,
-				"bad magic number in image file");
-		return NULL;
-	}
-	return Py_BuildValue("(ii)", image.xsize, image.ysize);
-}
-
-/*
- *	longimagedata - 
- *		read in a B/W RGB or RGBA iris image file and return a 
- *	pointer to an array of longs.
- *
- */
-static PyObject *
-longimagedata(PyObject *self, PyObject *args)
-{
-	char *name;
-	unsigned char *base, *lptr;
-	unsigned char *rledat = NULL, *verdat = NULL;
-	Py_Int32 *starttab = NULL, *lengthtab = NULL;
-	FILE *inf = NULL;
-	IMAGE image;
-	int y, z, tablen;
-	int xsize, ysize, zsize;
-	int bpp, rle, cur, badorder;
-	int rlebuflen;
-	PyObject *rv = NULL;
-
-	if (!PyArg_ParseTuple(args, "s:longimagedata", &name))
-		return NULL;
-
-	inf = fopen(name,"rb");
-	if (!inf) {
-		PyErr_SetString(ImgfileError, "can't open image file");
-		return NULL;
-	}
-	readheader(inf,&image);
-	if (image.imagic != IMAGIC) {
-		PyErr_SetString(ImgfileError,
-				"bad magic number in image file");
-		goto finally;
-	}
-	rle = ISRLE(image.type);
-	bpp = BPP(image.type);
-	if (bpp != 1) {
-		PyErr_SetString(ImgfileError,
-				"image must have 1 byte per pix chan");
-		goto finally;
-	}
-	xsize = image.xsize;
-	ysize = image.ysize;
-	zsize = image.zsize;
-	if (rle) {
-		tablen = ysize * zsize * sizeof(Py_Int32);
-		starttab = (Py_Int32 *)malloc(tablen);
-		lengthtab = (Py_Int32 *)malloc(tablen);
-		rlebuflen = (int) (1.05 * xsize +10);
-		rledat = (unsigned char *)malloc(rlebuflen);
-		if (!starttab || !lengthtab || !rledat) {
-			PyErr_NoMemory();
-			goto finally;
-		}
-		
-		fseek(inf, 512, SEEK_SET);
-		readtab(inf, starttab, ysize*zsize);
-		readtab(inf, lengthtab, ysize*zsize);
-
-		/* check data order */
-		cur = 0;
-		badorder = 0;
-		for(y = 0; y < ysize; y++) {
-			for(z = 0; z < zsize; z++) {
-				if (starttab[y + z * ysize] < cur) {
-					badorder = 1;
-					break;
-				}
-				cur = starttab[y +z * ysize];
-			}
-			if (badorder)
-				break;
-		}
-
-		fseek(inf, 512 + 2 * tablen, SEEK_SET);
-		cur = 512 + 2 * tablen;
-		rv = PyString_FromStringAndSize((char *)NULL,
-				      (xsize * ysize + TAGLEN) * sizeof(Py_Int32));
-		if (rv == NULL)
-			goto finally;
-
-		base = (unsigned char *) PyString_AsString(rv);
-#ifdef ADD_TAGS
-		addlongimgtag(base,xsize,ysize);
-#endif
-		if (badorder) {
-			for (z = 0; z < zsize; z++) {
-				lptr = base;
-				if (reverse_order)
-					lptr += (ysize - 1) * xsize
-						* sizeof(Py_UInt32);
-				for (y = 0; y < ysize; y++) {
-					int idx = y + z * ysize;
-					if (cur != starttab[idx]) {
-						fseek(inf,starttab[idx],
-						      SEEK_SET);
-						cur = starttab[idx];
-					}
-					if (lengthtab[idx] > rlebuflen) {
-						PyErr_SetString(ImgfileError,
-							"rlebuf is too small");
-						Py_DECREF(rv);
-						rv = NULL;
-						goto finally;
-					}
-					fread(rledat, lengthtab[idx], 1, inf);
-					cur += lengthtab[idx];
-					expandrow(lptr, rledat, 3-z);
-					if (reverse_order)
-						lptr -= xsize
-						      * sizeof(Py_UInt32);
-					else
-						lptr += xsize
-						      * sizeof(Py_UInt32);
-				}
-			}
-		} else {
-			lptr = base;
-			if (reverse_order)
-				lptr += (ysize - 1) * xsize
-					* sizeof(Py_UInt32);
-			for (y = 0; y < ysize; y++) {
-				for(z = 0; z < zsize; z++) {
-					int idx = y + z * ysize;
-					if (cur != starttab[idx]) {
-						fseek(inf, starttab[idx],
-						      SEEK_SET);
-						cur = starttab[idx];
-					}
-					fread(rledat, lengthtab[idx], 1, inf);
-					cur += lengthtab[idx];
-					expandrow(lptr, rledat, 3-z);
-				}
-				if (reverse_order)
-					lptr -= xsize * sizeof(Py_UInt32);
-				else
-					lptr += xsize * sizeof(Py_UInt32);
-			}
-		}
-		if (zsize == 3) 
-			setalpha(base, xsize * ysize);
-		else if (zsize < 3) 
-			copybw((Py_Int32 *) base, xsize * ysize);
-	}
-	else {
-		rv = PyString_FromStringAndSize((char *) 0,
-					   (xsize*ysize+TAGLEN)*sizeof(Py_Int32));
-		if (rv == NULL)
-			goto finally;
-
-		base = (unsigned char *) PyString_AsString(rv);
-#ifdef ADD_TAGS
-		addlongimgtag(base, xsize, ysize);
-#endif
-		verdat = (unsigned char *)malloc(xsize);
-		if (!verdat) {
-			Py_CLEAR(rv);
-			goto finally;
-		}
-
-		fseek(inf, 512, SEEK_SET);
-		for (z = 0; z < zsize; z++) {
-			lptr = base;
-			if (reverse_order)
-				lptr += (ysize - 1) * xsize
-				        * sizeof(Py_UInt32);
-			for (y = 0; y < ysize; y++) {
-				fread(verdat, xsize, 1, inf);
-				interleaverow(lptr, verdat, 3-z, xsize);
-				if (reverse_order)
-					lptr -= xsize * sizeof(Py_UInt32);
-				else
-					lptr += xsize * sizeof(Py_UInt32);
-			}
-		}
-		if (zsize == 3)
-			setalpha(base, xsize * ysize);
-		else if (zsize < 3) 
-			copybw((Py_Int32 *) base, xsize * ysize);
-	}
-  finally:
-	if (starttab)
-		free(starttab);
-	if (lengthtab)
-		free(lengthtab);
-	if (rledat)
-		free(rledat);
-	if (verdat)
-		free(verdat);
-	fclose(inf);
-	return rv;
-}
-
-/* static utility functions for longimagedata */
-
-static void
-interleaverow(unsigned char *lptr, unsigned char *cptr, int z, int n)
-{
-	lptr += z;
-	while (n--) {
-		*lptr = *cptr++;
-		lptr += 4;
-	}
-}
-
-static void
-copybw(Py_Int32 *lptr, int n)
-{
-	while (n >= 8) {
-		lptr[0] = 0xff000000 + (0x010101 * (lptr[0] & 0xff));
-		lptr[1] = 0xff000000 + (0x010101 * (lptr[1] & 0xff));
-		lptr[2] = 0xff000000 + (0x010101 * (lptr[2] & 0xff));
-		lptr[3] = 0xff000000 + (0x010101 * (lptr[3] & 0xff));
-		lptr[4] = 0xff000000 + (0x010101 * (lptr[4] & 0xff));
-		lptr[5] = 0xff000000 + (0x010101 * (lptr[5] & 0xff));
-		lptr[6] = 0xff000000 + (0x010101 * (lptr[6] & 0xff));
-		lptr[7] = 0xff000000 + (0x010101 * (lptr[7] & 0xff));
-		lptr += 8;
-		n -= 8;
-	}
-	while (n--) {
-		*lptr = 0xff000000 + (0x010101 * (*lptr&0xff));
-		lptr++;
-	}
-}
-
-static void
-setalpha(unsigned char *lptr, int n)
-{
-	while (n >= 8) {
-		lptr[0 * 4] = 0xff;
-		lptr[1 * 4] = 0xff;
-		lptr[2 * 4] = 0xff;
-		lptr[3 * 4] = 0xff;
-		lptr[4 * 4] = 0xff;
-		lptr[5 * 4] = 0xff;
-		lptr[6 * 4] = 0xff;
-		lptr[7 * 4] = 0xff;
-		lptr += 4 * 8;
-		n -= 8;
-	}
-	while (n--) {
-		*lptr = 0xff;
-		lptr += 4;
-	}
-}
-
-static void
-expandrow(unsigned char *optr, unsigned char *iptr, int z)
-{
-	unsigned char pixel, count;
-
-	optr += z;
-	while (1) {
-		pixel = *iptr++;
-		if (!(count = (pixel & 0x7f)))
-			return;
-		if (pixel & 0x80) {
-			while (count >= 8) {
-				optr[0 * 4] = iptr[0];
-				optr[1 * 4] = iptr[1];
-				optr[2 * 4] = iptr[2];
-				optr[3 * 4] = iptr[3];
-				optr[4 * 4] = iptr[4];
-				optr[5 * 4] = iptr[5];
-				optr[6 * 4] = iptr[6];
-				optr[7 * 4] = iptr[7];
-				optr += 8 * 4;
-				iptr += 8;
-				count -= 8;
-			}
-			while (count--) {
-				*optr = *iptr++;
-				optr += 4;
-			}
-		}
-		else {
-			pixel = *iptr++;
-			while (count >= 8) {
-				optr[0 * 4] = pixel;
-				optr[1 * 4] = pixel;
-				optr[2 * 4] = pixel;
-				optr[3 * 4] = pixel;
-				optr[4 * 4] = pixel;
-				optr[5 * 4] = pixel;
-				optr[6 * 4] = pixel;
-				optr[7 * 4] = pixel;
-				optr += 8 * 4;
-				count -= 8;
-			}
-			while (count--) {
-				*optr = pixel;
-				optr += 4;
-			}
-		}
-	}
-}
-
-/*
- *	longstoimage -
- *		copy an array of longs to an iris image file.  Each long
- *	represents one pixel.  xsize and ysize specify the dimensions of
- *	the pixel array.  zsize specifies what kind of image file to
- *	write out.  if zsize is 1, the luminance of the pixels are
- *	calculated, and a single channel black and white image is saved.
- *	If zsize is 3, an RGB image file is saved.  If zsize is 4, an
- *	RGBA image file is saved.
- *
- */
-static PyObject *
-longstoimage(PyObject *self, PyObject *args)
-{
-	unsigned char *lptr;
-	char *name;
-	int xsize, ysize, zsize;
-	FILE *outf = NULL;
-	IMAGE image;
-	int tablen, y, z, pos, len;
-	Py_Int32 *starttab = NULL, *lengthtab = NULL;
-	unsigned char *rlebuf = NULL;
-	unsigned char *lumbuf = NULL;
-	int rlebuflen;
-	Py_ssize_t goodwrite;
-	PyObject *retval = NULL;
-
-	if (!PyArg_ParseTuple(args, "s#iiis:longstoimage", &lptr, &len,
-			      &xsize, &ysize, &zsize, &name))
-		return NULL;
-
-	goodwrite = 1;
-	outf = fopen(name, "wb");
-	if (!outf) {
-		PyErr_SetString(ImgfileError, "can't open output file");
-		return NULL;
-	}
-	tablen = ysize * zsize * sizeof(Py_Int32);
-
-	starttab = (Py_Int32 *)malloc(tablen);
-	lengthtab = (Py_Int32 *)malloc(tablen);
-	rlebuflen = (int) (1.05 * xsize + 10);
-	rlebuf = (unsigned char *)malloc(rlebuflen);
-	lumbuf = (unsigned char *)malloc(xsize * sizeof(Py_Int32));
-	if (!starttab || !lengthtab || !rlebuf || !lumbuf) {
-		PyErr_NoMemory();
-		goto finally;
-	}
-	
-	memset(&image, 0, sizeof(IMAGE));
-	image.imagic = IMAGIC; 
-	image.type = RLE(1);
-	if (zsize>1)
-		image.dim = 3;
-	else
-		image.dim = 2;
-	image.xsize = xsize;
-	image.ysize = ysize;
-	image.zsize = zsize;
-	image.min = 0;
-	image.max = 255;
-	goodwrite *= writeheader(outf, &image);
-	pos = 512 + 2 * tablen;
-	fseek(outf, pos, SEEK_SET);
-	if (reverse_order)
-		lptr += (ysize - 1) * xsize * sizeof(Py_UInt32);
-	for (y = 0; y < ysize; y++) {
-		for (z = 0; z < zsize; z++) {
-			if (zsize == 1) {
-				lumrow(lptr, lumbuf, xsize);
-				len = compressrow(lumbuf, rlebuf,
-						  CHANOFFSET(z), xsize);
-			} else {
-				len = compressrow(lptr, rlebuf,
-						  CHANOFFSET(z), xsize);
-			}
-			if(len > rlebuflen) {
-				PyErr_SetString(ImgfileError,
-						"rlebuf is too small");
-				goto finally;
-			}
-			goodwrite *= fwrite(rlebuf, len, 1, outf);
-			starttab[y + z * ysize] = pos;
-			lengthtab[y + z * ysize] = len;
-			pos += len;
-		}
-		if (reverse_order)
-			lptr -= xsize * sizeof(Py_UInt32);
-		else
-			lptr += xsize * sizeof(Py_UInt32);
-	}
-
-	fseek(outf, 512, SEEK_SET);
-	goodwrite *= writetab(outf, starttab, ysize*zsize);
-	goodwrite *= writetab(outf, lengthtab, ysize*zsize);
-	if (goodwrite) {
-		Py_INCREF(Py_None);
-		retval = Py_None;
-	} else
-		PyErr_SetString(ImgfileError, "not enough space for image");
-
-  finally:
-	fclose(outf);
-	free(starttab);
-	free(lengthtab);
-	free(rlebuf);
-	free(lumbuf);
-	return retval;
-}
-
-/* static utility functions for longstoimage */
-
-static void
-lumrow(unsigned char *rgbptr, unsigned char *lumptr, int n)
-{
-	lumptr += CHANOFFSET(0);
-	while (n--) {
-		*lumptr = ILUM(rgbptr[OFFSET_R],
-			       rgbptr[OFFSET_G],
-			       rgbptr[OFFSET_B]);
-		lumptr += 4;
-		rgbptr += 4;
-	}
-}
-
-static int
-compressrow(unsigned char *lbuf, unsigned char *rlebuf, int z, int cnt)
-{
-	unsigned char *iptr, *ibufend, *sptr, *optr;
-	short todo, cc;							
-	Py_Int32 count;
-
-	lbuf += z;
-	iptr = lbuf;
-	ibufend = iptr + cnt * 4;
-	optr = rlebuf;
-
-	while(iptr < ibufend) {
-		sptr = iptr;
-		iptr += 8;
-		while ((iptr<ibufend) &&
-		       ((iptr[-8]!=iptr[-4]) ||(iptr[-4]!=iptr[0])))
-		{
-			iptr += 4;
-		}
-		iptr -= 8;
-		count = (iptr - sptr) / 4;
-		while (count) {
-			todo = count > 126 ? 126 : (short)count;
-			count -= todo;
-			*optr++ = 0x80 | todo;
-			while (todo > 8) {
-				optr[0] = sptr[0 * 4];
-				optr[1] = sptr[1 * 4];
-				optr[2] = sptr[2 * 4];
-				optr[3] = sptr[3 * 4];
-				optr[4] = sptr[4 * 4];
-				optr[5] = sptr[5 * 4];
-				optr[6] = sptr[6 * 4];
-				optr[7] = sptr[7 * 4];
-				optr += 8;
-				sptr += 8 * 4;
-				todo -= 8;
-			}
-			while (todo--) {
-				*optr++ = *sptr;
-				sptr += 4;
-			}
-		}
-		sptr = iptr;
-		cc = *iptr;
-		iptr += 4;
-		while ((iptr < ibufend) && (*iptr == cc))
-			iptr += 4;
-		count = (iptr - sptr) / 4;
-		while (count) {
-			todo = count > 126 ? 126 : (short)count;
-			count -= todo;
-			*optr++ = (unsigned char) todo;
-			*optr++ = (unsigned char) cc;
-		}
-	}
-	*optr++ = 0;
-	return optr - (unsigned char *)rlebuf;
-}
-
-static PyObject *
-ttob(PyObject *self, PyObject *args)
-{
-	int order, oldorder;
-
-	if (!PyArg_ParseTuple(args, "i:ttob", &order))
-		return NULL;
-	oldorder = reverse_order;
-	reverse_order = order;
-	return PyInt_FromLong(oldorder);
-}
-
-static PyMethodDef
-rgbimg_methods[] = {
-	{"sizeofimage",	   sizeofimage, METH_VARARGS},
-	{"longimagedata",  longimagedata, METH_VARARGS},
-	{"longstoimage",   longstoimage, METH_VARARGS},
-	{"ttob",	   ttob, METH_VARARGS},
-	{NULL,             NULL}	     /* sentinel */
-};
-
-
-PyMODINIT_FUNC
-initrgbimg(void)
-{
-	PyObject *m, *d;
-	m = Py_InitModule("rgbimg", rgbimg_methods);
-	if (m == NULL)
-		return;
-
-	if (PyErr_Warn(PyExc_DeprecationWarning, 
-				"the rgbimg module is deprecated"))
-		return;
-	
-	d = PyModule_GetDict(m);
-	ImgfileError = PyErr_NewException("rgbimg.error", NULL, NULL);
-	if (ImgfileError != NULL)
-		PyDict_SetItemString(d, "error", ImgfileError);
-}

Deleted: /python/branches/p3yk-noslice/Modules/sgimodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/sgimodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,55 +0,0 @@
-
-/* SGI module -- random SGI-specific things */
-
-#include "Python.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-static PyObject *
-sgi_nap(PyObject *self, PyObject *args)
-{
-	long ticks;
-	if (!PyArg_ParseTuple(args, "l:nap", &ticks))
-		return NULL;
-	Py_BEGIN_ALLOW_THREADS
-	sginap(ticks);
-	Py_END_ALLOW_THREADS
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-extern char *_getpty(int *, int, mode_t, int);
-
-static PyObject *
-sgi__getpty(PyObject *self, PyObject *args)
-{
-	int oflag;
-	int mode;
-	int nofork;
-	char *name;
-	int fildes;
-	if (!PyArg_ParseTuple(args, "iii:_getpty", &oflag, &mode, &nofork))
-		return NULL;
-	errno = 0;
-	name = _getpty(&fildes, oflag, (mode_t)mode, nofork);
-	if (name == NULL) {
-		PyErr_SetFromErrno(PyExc_IOError);
-		return NULL;
-	}
-	return Py_BuildValue("(si)", name, fildes);
-}
-
-static PyMethodDef sgi_methods[] = {
-	{"nap",		sgi_nap,	METH_VARARGS},
-	{"_getpty",	sgi__getpty,	METH_VARARGS},
-	{NULL,		NULL}		/* sentinel */
-};
-
-
-void
-initsgi(void)
-{
-	Py_InitModule("sgi", sgi_methods);
-}

Deleted: /python/branches/p3yk-noslice/Modules/shamodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/shamodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,593 +0,0 @@
-/* SHA module */
-
-/* This module provides an interface to NIST's Secure Hash Algorithm */
-
-/* See below for information about the original code this module was
-   based upon. Additional work performed by:
-
-   Andrew Kuchling (amk at amk.ca)
-   Greg Stein (gstein at lyra.org)
-
-   Copyright (C) 2005   Gregory P. Smith (greg at electricrain.com)
-   Licensed to PSF under a Contributor Agreement.
-
-*/
-
-/* SHA objects */
-
-#include "Python.h"
-#include "structmember.h"
-
-
-/* Endianness testing and definitions */
-#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
-	if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
-
-#define PCT_LITTLE_ENDIAN 1
-#define PCT_BIG_ENDIAN 0
-
-/* Some useful types */
-
-typedef unsigned char SHA_BYTE;
-
-#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32;	/* 32-bit integer */
-#else
-/* not defined. compilation will die. */
-#endif
-
-/* The SHA block size and message digest sizes, in bytes */
-
-#define SHA_BLOCKSIZE    64
-#define SHA_DIGESTSIZE  20
-
-/* The structure for storing SHS info */
-
-typedef struct {
-    PyObject_HEAD
-    SHA_INT32 digest[5];		/* Message digest */
-    SHA_INT32 count_lo, count_hi;	/* 64-bit bit count */
-    SHA_BYTE data[SHA_BLOCKSIZE];	/* SHA data buffer */
-    int Endianness;
-    int local;				/* unprocessed amount in data */
-} SHAobject;
-
-/* When run on a little-endian CPU we need to perform byte reversal on an
-   array of longwords. */
-
-static void longReverse(SHA_INT32 *buffer, int byteCount, int Endianness)
-{
-    SHA_INT32 value;
-
-    if ( Endianness == PCT_BIG_ENDIAN )
-	return;
-
-    byteCount /= sizeof(*buffer);
-    while (byteCount--) {
-        value = *buffer;
-        value = ( ( value & 0xFF00FF00L ) >> 8  ) | \
-                ( ( value & 0x00FF00FFL ) << 8 );
-        *buffer++ = ( value << 16 ) | ( value >> 16 );
-    }
-}
-
-static void SHAcopy(SHAobject *src, SHAobject *dest)
-{
-    dest->Endianness = src->Endianness;
-    dest->local = src->local;
-    dest->count_lo = src->count_lo;
-    dest->count_hi = src->count_hi;
-    memcpy(dest->digest, src->digest, sizeof(src->digest));
-    memcpy(dest->data, src->data, sizeof(src->data));
-}
-
-
-/* ------------------------------------------------------------------------
- *
- * This code for the SHA algorithm was noted as public domain. The original
- * headers are pasted below.
- *
- * Several changes have been made to make it more compatible with the
- * Python environment and desired interface.
- *
- */
-
-/* NIST Secure Hash Algorithm */
-/* heavily modified by Uwe Hollerbach <uh at alumni.caltech edu> */
-/* from Peter C. Gutmann's implementation as found in */
-/* Applied Cryptography by Bruce Schneier */
-/* Further modifications to include the "UNRAVEL" stuff, below */
-
-/* This code is in the public domain */
-
-/* UNRAVEL should be fastest & biggest */
-/* UNROLL_LOOPS should be just as big, but slightly slower */
-/* both undefined should be smallest and slowest */
-
-#define UNRAVEL
-/* #define UNROLL_LOOPS */
-
-/* The SHA f()-functions.  The f1 and f3 functions can be optimized to
-   save one boolean operation each - thanks to Rich Schroeppel,
-   rcs at cs.arizona.edu for discovering this */
-
-/*#define f1(x,y,z)	((x & y) | (~x & z))		// Rounds  0-19 */
-#define f1(x,y,z)	(z ^ (x & (y ^ z)))		/* Rounds  0-19 */
-#define f2(x,y,z)	(x ^ y ^ z)			/* Rounds 20-39 */
-/*#define f3(x,y,z)	((x & y) | (x & z) | (y & z))	// Rounds 40-59 */
-#define f3(x,y,z)	((x & y) | (z & (x | y)))	/* Rounds 40-59 */
-#define f4(x,y,z)	(x ^ y ^ z)			/* Rounds 60-79 */
-
-/* SHA constants */
-
-#define CONST1		0x5a827999L			/* Rounds  0-19 */
-#define CONST2		0x6ed9eba1L			/* Rounds 20-39 */
-#define CONST3		0x8f1bbcdcL			/* Rounds 40-59 */
-#define CONST4		0xca62c1d6L			/* Rounds 60-79 */
-
-/* 32-bit rotate */
-
-#define R32(x,n)	((x << n) | (x >> (32 - n)))
-
-/* the generic case, for when the overall rotation is not unraveled */
-
-#define FG(n)	\
-    T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n;	\
-    E = D; D = C; C = R32(B,30); B = A; A = T
-
-/* specific cases, for when the overall rotation is unraveled */
-
-#define FA(n)	\
-    T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; B = R32(B,30)
-
-#define FB(n)	\
-    E = R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n; A = R32(A,30)
-
-#define FC(n)	\
-    D = R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n; T = R32(T,30)
-
-#define FD(n)	\
-    C = R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n; E = R32(E,30)
-
-#define FE(n)	\
-    B = R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n; D = R32(D,30)
-
-#define FT(n)	\
-    A = R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n; C = R32(C,30)
-
-/* do SHA transformation */
-
-static void
-sha_transform(SHAobject *sha_info)
-{
-    int i;
-    SHA_INT32 T, A, B, C, D, E, W[80], *WP;
-
-    memcpy(W, sha_info->data, sizeof(sha_info->data));
-    longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
-
-    for (i = 16; i < 80; ++i) {
-	W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
-
-	/* extra rotation fix */
-	W[i] = R32(W[i], 1);
-    }
-    A = sha_info->digest[0];
-    B = sha_info->digest[1];
-    C = sha_info->digest[2];
-    D = sha_info->digest[3];
-    E = sha_info->digest[4];
-    WP = W;
-#ifdef UNRAVEL
-    FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1);
-    FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1);
-    FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2);
-    FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2);
-    FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3);
-    FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3);
-    FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4);
-    FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4);
-    sha_info->digest[0] += E;
-    sha_info->digest[1] += T;
-    sha_info->digest[2] += A;
-    sha_info->digest[3] += B;
-    sha_info->digest[4] += C;
-#else /* !UNRAVEL */
-#ifdef UNROLL_LOOPS
-    FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1);
-    FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1);
-    FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2);
-    FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2);
-    FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3);
-    FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3);
-    FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4);
-    FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4);
-#else /* !UNROLL_LOOPS */
-    for (i =  0; i < 20; ++i) { FG(1); }
-    for (i = 20; i < 40; ++i) { FG(2); }
-    for (i = 40; i < 60; ++i) { FG(3); }
-    for (i = 60; i < 80; ++i) { FG(4); }
-#endif /* !UNROLL_LOOPS */
-    sha_info->digest[0] += A;
-    sha_info->digest[1] += B;
-    sha_info->digest[2] += C;
-    sha_info->digest[3] += D;
-    sha_info->digest[4] += E;
-#endif /* !UNRAVEL */
-}
-
-/* initialize the SHA digest */
-
-static void
-sha_init(SHAobject *sha_info)
-{
-    TestEndianness(sha_info->Endianness)
-
-    sha_info->digest[0] = 0x67452301L;
-    sha_info->digest[1] = 0xefcdab89L;
-    sha_info->digest[2] = 0x98badcfeL;
-    sha_info->digest[3] = 0x10325476L;
-    sha_info->digest[4] = 0xc3d2e1f0L;
-    sha_info->count_lo = 0L;
-    sha_info->count_hi = 0L;
-    sha_info->local = 0;
-}
-
-/* update the SHA digest */
-
-static void
-sha_update(SHAobject *sha_info, SHA_BYTE *buffer, int count)
-{
-    int i;
-    SHA_INT32 clo;
-
-    clo = sha_info->count_lo + ((SHA_INT32) count << 3);
-    if (clo < sha_info->count_lo) {
-        ++sha_info->count_hi;
-    }
-    sha_info->count_lo = clo;
-    sha_info->count_hi += (SHA_INT32) count >> 29;
-    if (sha_info->local) {
-        i = SHA_BLOCKSIZE - sha_info->local;
-        if (i > count) {
-            i = count;
-        }
-        memcpy(((SHA_BYTE *) sha_info->data) + sha_info->local, buffer, i);
-        count -= i;
-        buffer += i;
-        sha_info->local += i;
-        if (sha_info->local == SHA_BLOCKSIZE) {
-            sha_transform(sha_info);
-        }
-        else {
-            return;
-        }
-    }
-    while (count >= SHA_BLOCKSIZE) {
-        memcpy(sha_info->data, buffer, SHA_BLOCKSIZE);
-        buffer += SHA_BLOCKSIZE;
-        count -= SHA_BLOCKSIZE;
-        sha_transform(sha_info);
-    }
-    memcpy(sha_info->data, buffer, count);
-    sha_info->local = count;
-}
-
-/* finish computing the SHA digest */
-
-static void
-sha_final(unsigned char digest[20], SHAobject *sha_info)
-{
-    int count;
-    SHA_INT32 lo_bit_count, hi_bit_count;
-
-    lo_bit_count = sha_info->count_lo;
-    hi_bit_count = sha_info->count_hi;
-    count = (int) ((lo_bit_count >> 3) & 0x3f);
-    ((SHA_BYTE *) sha_info->data)[count++] = 0x80;
-    if (count > SHA_BLOCKSIZE - 8) {
-	memset(((SHA_BYTE *) sha_info->data) + count, 0,
-	       SHA_BLOCKSIZE - count);
-	sha_transform(sha_info);
-	memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
-    }
-    else {
-	memset(((SHA_BYTE *) sha_info->data) + count, 0,
-	       SHA_BLOCKSIZE - 8 - count);
-    }
-
-    /* GJS: note that we add the hi/lo in big-endian. sha_transform will
-       swap these values into host-order. */
-    sha_info->data[56] = (hi_bit_count >> 24) & 0xff;
-    sha_info->data[57] = (hi_bit_count >> 16) & 0xff;
-    sha_info->data[58] = (hi_bit_count >>  8) & 0xff;
-    sha_info->data[59] = (hi_bit_count >>  0) & 0xff;
-    sha_info->data[60] = (lo_bit_count >> 24) & 0xff;
-    sha_info->data[61] = (lo_bit_count >> 16) & 0xff;
-    sha_info->data[62] = (lo_bit_count >>  8) & 0xff;
-    sha_info->data[63] = (lo_bit_count >>  0) & 0xff;
-    sha_transform(sha_info);
-    digest[ 0] = (unsigned char) ((sha_info->digest[0] >> 24) & 0xff);
-    digest[ 1] = (unsigned char) ((sha_info->digest[0] >> 16) & 0xff);
-    digest[ 2] = (unsigned char) ((sha_info->digest[0] >>  8) & 0xff);
-    digest[ 3] = (unsigned char) ((sha_info->digest[0]      ) & 0xff);
-    digest[ 4] = (unsigned char) ((sha_info->digest[1] >> 24) & 0xff);
-    digest[ 5] = (unsigned char) ((sha_info->digest[1] >> 16) & 0xff);
-    digest[ 6] = (unsigned char) ((sha_info->digest[1] >>  8) & 0xff);
-    digest[ 7] = (unsigned char) ((sha_info->digest[1]      ) & 0xff);
-    digest[ 8] = (unsigned char) ((sha_info->digest[2] >> 24) & 0xff);
-    digest[ 9] = (unsigned char) ((sha_info->digest[2] >> 16) & 0xff);
-    digest[10] = (unsigned char) ((sha_info->digest[2] >>  8) & 0xff);
-    digest[11] = (unsigned char) ((sha_info->digest[2]      ) & 0xff);
-    digest[12] = (unsigned char) ((sha_info->digest[3] >> 24) & 0xff);
-    digest[13] = (unsigned char) ((sha_info->digest[3] >> 16) & 0xff);
-    digest[14] = (unsigned char) ((sha_info->digest[3] >>  8) & 0xff);
-    digest[15] = (unsigned char) ((sha_info->digest[3]      ) & 0xff);
-    digest[16] = (unsigned char) ((sha_info->digest[4] >> 24) & 0xff);
-    digest[17] = (unsigned char) ((sha_info->digest[4] >> 16) & 0xff);
-    digest[18] = (unsigned char) ((sha_info->digest[4] >>  8) & 0xff);
-    digest[19] = (unsigned char) ((sha_info->digest[4]      ) & 0xff);
-}
-
-/*
- * End of copied SHA code.
- *
- * ------------------------------------------------------------------------
- */
-
-static PyTypeObject SHAtype;
-
-
-static SHAobject *
-newSHAobject(void)
-{
-    return (SHAobject *)PyObject_New(SHAobject, &SHAtype);
-}
-
-/* Internal methods for a hashing object */
-
-static void
-SHA_dealloc(PyObject *ptr)
-{
-    PyObject_Del(ptr);
-}
-
-
-/* External methods for a hashing object */
-
-PyDoc_STRVAR(SHA_copy__doc__, "Return a copy of the hashing object.");
-
-static PyObject *
-SHA_copy(SHAobject *self, PyObject *unused)
-{
-    SHAobject *newobj;
-
-    if ( (newobj = newSHAobject())==NULL)
-        return NULL;
-
-    SHAcopy(self, newobj);
-    return (PyObject *)newobj;
-}
-
-PyDoc_STRVAR(SHA_digest__doc__,
-"Return the digest value as a string of binary data.");
-
-static PyObject *
-SHA_digest(SHAobject *self, PyObject *unused)
-{
-    unsigned char digest[SHA_DIGESTSIZE];
-    SHAobject temp;
-
-    SHAcopy(self, &temp);
-    sha_final(digest, &temp);
-    return PyString_FromStringAndSize((const char *)digest, sizeof(digest));
-}
-
-PyDoc_STRVAR(SHA_hexdigest__doc__,
-"Return the digest value as a string of hexadecimal digits.");
-
-static PyObject *
-SHA_hexdigest(SHAobject *self, PyObject *unused)
-{
-    unsigned char digest[SHA_DIGESTSIZE];
-    SHAobject temp;
-    PyObject *retval;
-    char *hex_digest;
-    int i, j;
-
-    /* Get the raw (binary) digest value */
-    SHAcopy(self, &temp);
-    sha_final(digest, &temp);
-
-    /* Create a new string */
-    retval = PyString_FromStringAndSize(NULL, sizeof(digest) * 2);
-    if (!retval)
-	    return NULL;
-    hex_digest = PyString_AsString(retval);
-    if (!hex_digest) {
-	    Py_DECREF(retval);
-	    return NULL;
-    }
-
-    /* Make hex version of the digest */
-    for(i=j=0; i<sizeof(digest); i++) {
-        char c;
-        c = (digest[i] >> 4) & 0xf;
-	c = (c>9) ? c+'a'-10 : c + '0';
-        hex_digest[j++] = c;
-        c = (digest[i] & 0xf);
-	c = (c>9) ? c+'a'-10 : c + '0';
-        hex_digest[j++] = c;
-    }
-    return retval;
-}
-
-PyDoc_STRVAR(SHA_update__doc__,
-"Update this hashing object's state with the provided string.");
-
-static PyObject *
-SHA_update(SHAobject *self, PyObject *args)
-{
-    unsigned char *cp;
-    int len;
-
-    if (!PyArg_ParseTuple(args, "s#:update", &cp, &len))
-        return NULL;
-
-    sha_update(self, cp, len);
-
-    Py_INCREF(Py_None);
-    return Py_None;
-}
-
-static PyMethodDef SHA_methods[] = {
-    {"copy",	  (PyCFunction)SHA_copy,      METH_NOARGS,  SHA_copy__doc__},
-    {"digest",	  (PyCFunction)SHA_digest,    METH_NOARGS,  SHA_digest__doc__},
-    {"hexdigest", (PyCFunction)SHA_hexdigest, METH_NOARGS,  SHA_hexdigest__doc__},
-    {"update",	  (PyCFunction)SHA_update,    METH_VARARGS, SHA_update__doc__},
-    {NULL,	  NULL}		/* sentinel */
-};
-
-static PyObject *
-SHA_get_block_size(PyObject *self, void *closure)
-{
-    return PyInt_FromLong(SHA_BLOCKSIZE);
-}
-
-static PyObject *
-SHA_get_digest_size(PyObject *self, void *closure)
-{
-    return PyInt_FromLong(SHA_DIGESTSIZE);
-}
-
-static PyObject *
-SHA_get_name(PyObject *self, void *closure)
-{
-    return PyString_FromStringAndSize("SHA1", 4);
-}
-
-static PyGetSetDef SHA_getseters[] = {
-    {"digest_size",
-     (getter)SHA_get_digest_size, NULL,
-     NULL,
-     NULL},
-    {"block_size",
-     (getter)SHA_get_block_size, NULL,
-     NULL,
-     NULL},
-    {"name",
-     (getter)SHA_get_name, NULL,
-     NULL,
-     NULL},
-    /* the old md5 and sha modules support 'digest_size' as in PEP 247.
-     * the old sha module also supported 'digestsize'.  ugh. */
-    {"digestsize",
-     (getter)SHA_get_digest_size, NULL,
-     NULL,
-     NULL},
-    {NULL}  /* Sentinel */
-};
-
-static PyTypeObject SHAtype = {
-    PyObject_HEAD_INIT(NULL)
-    0,			/*ob_size*/
-    "_sha.sha",		/*tp_name*/
-    sizeof(SHAobject),	/*tp_size*/
-    0,			/*tp_itemsize*/
-    /* methods */
-    SHA_dealloc,	/*tp_dealloc*/
-    0,			/*tp_print*/
-    0,                  /*tp_getattr*/
-    0,                  /*tp_setattr*/
-    0,                  /*tp_compare*/
-    0,                  /*tp_repr*/
-    0,                  /*tp_as_number*/
-    0,                  /*tp_as_sequence*/
-    0,                  /*tp_as_mapping*/
-    0,                  /*tp_hash*/
-    0,                  /*tp_call*/
-    0,                  /*tp_str*/
-    0,                  /*tp_getattro*/
-    0,                  /*tp_setattro*/
-    0,                  /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT, /*tp_flags*/
-    0,                  /*tp_doc*/
-    0,                  /*tp_traverse*/
-    0,			/*tp_clear*/
-    0,			/*tp_richcompare*/
-    0,			/*tp_weaklistoffset*/
-    0,			/*tp_iter*/
-    0,			/*tp_iternext*/
-    SHA_methods,	/* tp_methods */
-    0,                  /* tp_members */
-    SHA_getseters,      /* tp_getset */
-};
-
-
-/* The single module-level function: new() */
-
-PyDoc_STRVAR(SHA_new__doc__,
-"Return a new SHA hashing object.  An optional string argument\n\
-may be provided; if present, this string will be automatically\n\
-hashed.");
-
-static PyObject *
-SHA_new(PyObject *self, PyObject *args, PyObject *kwdict)
-{
-    static char *kwlist[] = {"string", NULL};
-    SHAobject *new;
-    unsigned char *cp = NULL;
-    int len;
-
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|s#:new", kwlist,
-                                     &cp, &len)) {
-        return NULL;
-    }
-
-    if ((new = newSHAobject()) == NULL)
-        return NULL;
-
-    sha_init(new);
-
-    if (PyErr_Occurred()) {
-        Py_DECREF(new);
-        return NULL;
-    }
-    if (cp)
-        sha_update(new, cp, len);
-
-    return (PyObject *)new;
-}
-
-
-/* List of functions exported by this module */
-
-static struct PyMethodDef SHA_functions[] = {
-    {"new", (PyCFunction)SHA_new, METH_VARARGS|METH_KEYWORDS, SHA_new__doc__},
-    {NULL,	NULL}		 /* Sentinel */
-};
-
-
-/* Initialize this module. */
-
-#define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
-
-PyMODINIT_FUNC
-init_sha(void)
-{
-    PyObject *m;
-
-    SHAtype.ob_type = &PyType_Type;
-    if (PyType_Ready(&SHAtype) < 0)
-        return;
-    m = Py_InitModule("_sha", SHA_functions);
-    if (m == NULL)
-	return;
-
-    /* Add some symbolic constants to the module */
-    insint("blocksize", 1);  /* For future use, in case some hash
-                                functions require an integral number of
-                                blocks */ 
-    insint("digestsize", 20);
-    insint("digest_size", 20);
-}

Modified: python/branches/p3yk-noslice/Modules/socketmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/socketmodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/socketmodule.c	Wed Jul 11 15:40:56 2007
@@ -363,8 +363,11 @@
 #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
 #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
 #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
+#define SOL_HCI SOL_HCI_RAW
+#define HCI_FILTER SO_HCI_RAW_FILTER
 #define sockaddr_l2 sockaddr_l2cap
 #define sockaddr_rc sockaddr_rfcomm
+#define hci_dev hci_node
 #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
 #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
 #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
@@ -2384,14 +2387,14 @@
 	int buflen;
 
 	/* Get the buffer's memory */
-	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv", kwlist,
+	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
 					 &buf, &buflen, &recvlen, &flags))
 		return NULL;
 	assert(buf != 0 && buflen > 0);
 
 	if (recvlen < 0) {
 		PyErr_SetString(PyExc_ValueError,
-				"negative buffersize in recv");
+				"negative buffersize in recv_into");
 		return NULL;
 	}
 	if (recvlen == 0) {
@@ -2507,6 +2510,12 @@
 	if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
 		return NULL;
 
+	if (recvlen < 0) {
+		PyErr_SetString(PyExc_ValueError,
+				"negative buffersize in recvfrom");
+		return NULL;
+	}
+
 	buf = PyString_FromStringAndSize((char *) 0, recvlen);
 	if (buf == NULL)
 		return NULL;
@@ -2553,14 +2562,15 @@
 
 	PyObject *addr = NULL;
 
-	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom", kwlist,
-					 &buf, &buflen, &recvlen, &flags))
+	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
+					 kwlist, &buf, &buflen,
+					 &recvlen, &flags))
 		return NULL;
 	assert(buf != 0 && buflen > 0);
 
 	if (recvlen < 0) {
 		PyErr_SetString(PyExc_ValueError,
-				"negative buffersize in recv");
+				"negative buffersize in recvfrom_into");
 		return NULL;
 	}
 	if (recvlen == 0) {
@@ -4440,10 +4450,10 @@
 	PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
 	PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
 	PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
-	PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
-	PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
 	PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
 #if !defined(__FreeBSD__)
+	PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
+	PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
 	PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
 #endif
 	PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);

Deleted: /python/branches/p3yk-noslice/Modules/stropmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/stropmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,1248 +0,0 @@
-/* strop module */
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-#include <ctype.h>
-
-PyDoc_STRVAR(strop_module__doc__,
-"Common string manipulations, optimized for speed.\n"
-"\n"
-"Always use \"import string\" rather than referencing\n"
-"this module directly.");
-
-/* XXX This file assumes that the <ctype.h> is*() functions
-   XXX are defined for all 8-bit characters! */
-
-#define WARN if (PyErr_Warn(PyExc_DeprecationWarning, \
-		       "strop functions are obsolete; use string methods")) \
-	     return NULL
-
-/* The lstrip(), rstrip() and strip() functions are implemented
-   in do_strip(), which uses an additional parameter to indicate what
-   type of strip should occur. */
-
-#define LEFTSTRIP 0
-#define RIGHTSTRIP 1
-#define BOTHSTRIP 2
-
-
-static PyObject *
-split_whitespace(char *s, Py_ssize_t len, Py_ssize_t maxsplit)
-{
-	Py_ssize_t i = 0, j;
-	int err;
-	Py_ssize_t countsplit = 0;
-	PyObject* item;
-	PyObject *list = PyList_New(0);
-
-	if (list == NULL)
-		return NULL;
-
-	while (i < len) {
-		while (i < len && isspace(Py_CHARMASK(s[i]))) {
-			i = i+1;
-		}
-		j = i;
-		while (i < len && !isspace(Py_CHARMASK(s[i]))) {
-			i = i+1;
-		}
-		if (j < i) {
-			item = PyString_FromStringAndSize(s+j, i-j);
-			if (item == NULL)
-				goto finally;
-
-			err = PyList_Append(list, item);
-			Py_DECREF(item);
-			if (err < 0)
-				goto finally;
-
-			countsplit++;
-			while (i < len && isspace(Py_CHARMASK(s[i]))) {
-				i = i+1;
-			}
-			if (maxsplit && (countsplit >= maxsplit) && i < len) {
-				item = PyString_FromStringAndSize(
-                                        s+i, len - i);
-				if (item == NULL)
-					goto finally;
-
-				err = PyList_Append(list, item);
-				Py_DECREF(item);
-				if (err < 0)
-					goto finally;
-
-				i = len;
-			}
-		}
-	}
-	return list;
-  finally:
-	Py_DECREF(list);
-	return NULL;
-}
-
-
-PyDoc_STRVAR(splitfields__doc__,
-"split(s [,sep [,maxsplit]]) -> list of strings\n"
-"splitfields(s [,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 nonzero, splits into at most\n"
-"maxsplit words.  If sep is not specified, any whitespace string\n"
-"is a separator.  Maxsplit defaults to 0.\n"
-"\n"
-"(split and splitfields are synonymous)");
-
-static PyObject *
-strop_splitfields(PyObject *self, PyObject *args)
-{
-	Py_ssize_t len, n, i, j, err;
-	Py_ssize_t splitcount, maxsplit;
-	char *s, *sub;
-	PyObject *list, *item;
-
-	WARN;
-	sub = NULL;
-	n = 0;
-	splitcount = 0;
-	maxsplit = 0;
-	if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit))
-		return NULL;
-	if (sub == NULL)
-		return split_whitespace(s, len, maxsplit);
-	if (n == 0) {
-		PyErr_SetString(PyExc_ValueError, "empty separator");
-		return NULL;
-	}
-
-	list = PyList_New(0);
-	if (list == NULL)
-		return NULL;
-
-	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);
-			if (item == NULL)
-				goto fail;
-			err = PyList_Append(list, item);
-			Py_DECREF(item);
-			if (err < 0)
-				goto fail;
-			i = j = i + n;
-			splitcount++;
-			if (maxsplit && (splitcount >= maxsplit))
-				break;
-		}
-		else
-			i++;
-	}
-	item = PyString_FromStringAndSize(s+j, len-j);
-	if (item == NULL)
-		goto fail;
-	err = PyList_Append(list, item);
-	Py_DECREF(item);
-	if (err < 0)
-		goto fail;
-
-	return list;
-
- fail:
-	Py_DECREF(list);
-	return NULL;
-}
-
-
-PyDoc_STRVAR(joinfields__doc__,
-"join(list [,sep]) -> string\n"
-"joinfields(list [,sep]) -> string\n"
-"\n"
-"Return a string composed of the words in list, with\n"
-"intervening occurrences of sep.  Sep defaults to a single\n"
-"space.\n"
-"\n"
-"(join and joinfields are synonymous)");
-
-static PyObject *
-strop_joinfields(PyObject *self, PyObject *args)
-{
-	PyObject *seq;
-	char *sep = NULL;
-	Py_ssize_t seqlen, seplen = 0;
-	Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
-	PyObject *res = NULL;
-	char* p = NULL;
-	ssizeargfunc getitemfunc;
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
-		return NULL;
-	if (sep == NULL) {
-		sep = " ";
-		seplen = 1;
-	}
-
-	seqlen = PySequence_Size(seq);
-	if (seqlen < 0 && PyErr_Occurred())
-		return NULL;
-
-	if (seqlen == 1) {
-		/* Optimization if there's only one item */
-		PyObject *item = PySequence_GetItem(seq, 0);
-		if (item && !PyString_Check(item)) {
-			PyErr_SetString(PyExc_TypeError,
-				 "first argument must be sequence of strings");
-			Py_DECREF(item);
-			return NULL;
-		}
-		return item;
-	}
-
-	if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
-		return NULL;
-	p = PyString_AsString(res);
-
-	/* optimize for lists, since it's the most common case.  all others
-	 * (tuples and arbitrary sequences) just use the sequence abstract
-	 * interface.
-	 */
-	if (PyList_Check(seq)) {
-		for (i = 0; i < seqlen; i++) {
-			PyObject *item = PyList_GET_ITEM(seq, i);
-			if (!PyString_Check(item)) {
-				PyErr_SetString(PyExc_TypeError,
-				"first argument must be sequence of strings");
-				Py_DECREF(res);
-				return NULL;
-			}
-			slen = PyString_GET_SIZE(item);
-			while (reslen + slen + seplen >= sz) {
-				if (_PyString_Resize(&res, sz * 2) < 0)
-					return NULL;
-				sz *= 2;
-				p = PyString_AsString(res) + reslen;
-			}
-			if (i > 0) {
-				memcpy(p, sep, seplen);
-				p += seplen;
-				reslen += seplen;
-			}
-			memcpy(p, PyString_AS_STRING(item), slen);
-			p += slen;
-			reslen += slen;
-		}
-		_PyString_Resize(&res, reslen);
-		return res;
-	}
-
-	if (seq->ob_type->tp_as_sequence == NULL ||
-		 (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
-	{
-		PyErr_SetString(PyExc_TypeError,
-				"first argument must be a sequence");
-		return NULL;
-	}
-	/* This is now type safe */
-	for (i = 0; i < seqlen; i++) {
-		PyObject *item = getitemfunc(seq, i);
-		if (!item || !PyString_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);
-		while (reslen + slen + seplen >= sz) {
-			if (_PyString_Resize(&res, sz * 2) < 0) {
-				Py_DECREF(item);
-				return NULL;
-			}
-			sz *= 2;
-			p = PyString_AsString(res) + reslen;
-		}
-		if (i > 0) {
-			memcpy(p, sep, seplen);
-			p += seplen;
-			reslen += seplen;
-		}
-		memcpy(p, PyString_AS_STRING(item), slen);
-		p += slen;
-		reslen += slen;
-		Py_DECREF(item);
-	}
-	_PyString_Resize(&res, reslen);
-	return res;
-}
-
-
-PyDoc_STRVAR(find__doc__,
-"find(s, sub [,start [,end]]) -> in\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 *
-strop_find(PyObject *self, PyObject *args)
-{
-	char *s, *sub;
-	Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX;
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last))
-		return NULL;
-
-	if (last > len)
-		last = len;
-	if (last < 0)
-		last += len;
-	if (last < 0)
-		last = 0;
-	if (i < 0)
-		i += len;
-	if (i < 0)
-		i = 0;
-
-	if (n == 0 && i <= last)
-		return PyInt_FromLong((long)i);
-
-	last -= n;
-	for (; i <= last; ++i)
-		if (s[i] == sub[0] &&
-		    (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
-			return PyInt_FromLong((long)i);
-
-	return PyInt_FromLong(-1L);
-}
-
-
-PyDoc_STRVAR(rfind__doc__,
-"rfind(s, 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 *
-strop_rfind(PyObject *self, PyObject *args)
-{
-	char *s, *sub;
-	Py_ssize_t len, n, j;
-	Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last))
-		return NULL;
-
-	if (last > len)
-		last = len;
-	if (last < 0)
-		last += len;
-	if (last < 0)
-		last = 0;
-	if (i < 0)
-		i += len;
-	if (i < 0)
-		i = 0;
-
-	if (n == 0 && i <= last)
-		return PyInt_FromLong((long)last);
-
-	for (j = last-n; j >= i; --j)
-		if (s[j] == sub[0] &&
-		    (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
-			return PyInt_FromLong((long)j);
-
-	return PyInt_FromLong(-1L);
-}
-
-
-static PyObject *
-do_strip(PyObject *args, int striptype)
-{
-	char *s;
-	Py_ssize_t len, i, j;
-
-
-	if (PyString_AsStringAndSize(args, &s, &len))
-		return NULL;
-
-	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) {
-		Py_INCREF(args);
-		return args;
-	}
-	else
-		return PyString_FromStringAndSize(s+i, j-i);
-}
-
-
-PyDoc_STRVAR(strip__doc__,
-"strip(s) -> string\n"
-"\n"
-"Return a copy of the string s with leading and trailing\n"
-"whitespace removed.");
-
-static PyObject *
-strop_strip(PyObject *self, PyObject *args)
-{
-	WARN;
-	return do_strip(args, BOTHSTRIP);
-}
-
-
-PyDoc_STRVAR(lstrip__doc__,
-"lstrip(s) -> string\n"
-"\n"
-"Return a copy of the string s with leading whitespace removed.");
-
-static PyObject *
-strop_lstrip(PyObject *self, PyObject *args)
-{
-	WARN;
-	return do_strip(args, LEFTSTRIP);
-}
-
-
-PyDoc_STRVAR(rstrip__doc__,
-"rstrip(s) -> string\n"
-"\n"
-"Return a copy of the string s with trailing whitespace removed.");
-
-static PyObject *
-strop_rstrip(PyObject *self, PyObject *args)
-{
-	WARN;
-	return do_strip(args, RIGHTSTRIP);
-}
-
-
-PyDoc_STRVAR(lower__doc__,
-"lower(s) -> string\n"
-"\n"
-"Return a copy of the string s converted to lowercase.");
-
-static PyObject *
-strop_lower(PyObject *self, PyObject *args)
-{
-	char *s, *s_new;
-	Py_ssize_t i, n;
-	PyObject *newstr;
-	int changed;
-
-	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
-		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
-	if (newstr == NULL)
-		return NULL;
-	s_new = PyString_AsString(newstr);
-	changed = 0;
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (isupper(c)) {
-			changed = 1;
-			*s_new = tolower(c);
-		} else
-			*s_new = c;
-		s_new++;
-	}
-	if (!changed) {
-		Py_DECREF(newstr);
-		Py_INCREF(args);
-		return args;
-	}
-	return newstr;
-}
-
-
-PyDoc_STRVAR(upper__doc__,
-"upper(s) -> string\n"
-"\n"
-"Return a copy of the string s converted to uppercase.");
-
-static PyObject *
-strop_upper(PyObject *self, PyObject *args)
-{
-	char *s, *s_new;
-	Py_ssize_t i, n;
-	PyObject *newstr;
-	int changed;
-
-	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
-		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
-	if (newstr == NULL)
-		return NULL;
-	s_new = PyString_AsString(newstr);
-	changed = 0;
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (islower(c)) {
-			changed = 1;
-			*s_new = toupper(c);
-		} else
-			*s_new = c;
-		s_new++;
-	}
-	if (!changed) {
-		Py_DECREF(newstr);
-		Py_INCREF(args);
-		return args;
-	}
-	return newstr;
-}
-
-
-PyDoc_STRVAR(capitalize__doc__,
-"capitalize(s) -> string\n"
-"\n"
-"Return a copy of the string s with only its first character\n"
-"capitalized.");
-
-static PyObject *
-strop_capitalize(PyObject *self, PyObject *args)
-{
-	char *s, *s_new;
-	Py_ssize_t i, n;
-	PyObject *newstr;
-	int changed;
-
-	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
-		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
-	if (newstr == NULL)
-		return NULL;
-	s_new = PyString_AsString(newstr);
-	changed = 0;
-	if (0 < n) {
-		int c = Py_CHARMASK(*s++);
-		if (islower(c)) {
-			changed = 1;
-			*s_new = toupper(c);
-		} else
-			*s_new = c;
-		s_new++;
-	}
-	for (i = 1; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (isupper(c)) {
-			changed = 1;
-			*s_new = tolower(c);
-		} else
-			*s_new = c;
-		s_new++;
-	}
-	if (!changed) {
-		Py_DECREF(newstr);
-		Py_INCREF(args);
-		return args;
-	}
-	return newstr;
-}
-
-
-PyDoc_STRVAR(expandtabs__doc__,
-"expandtabs(string, [tabsize]) -> string\n"
-"\n"
-"Expand tabs in a string, i.e. replace them by one or more spaces,\n"
-"depending on the current column and the given tab size (default 8).\n"
-"The column number is reset to zero after each newline occurring in the\n"
-"string.  This doesn't understand other non-printing characters.");
-
-static PyObject *
-strop_expandtabs(PyObject *self, PyObject *args)
-{
-	/* Original by Fredrik Lundh */
-	char* e;
-	char* p;
-	char* q;
-	Py_ssize_t i, j;
-	PyObject* out;
-	char* string;
-	Py_ssize_t stringlen;
-	int tabsize = 8;
-
-	WARN;
-	/* Get arguments */
-	if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
-		return NULL;
-	if (tabsize < 1) {
-		PyErr_SetString(PyExc_ValueError,
-				"tabsize must be at least 1");
-		return NULL;
-	}
-
-	/* First pass: determine size of output string */
-	i = j = 0; /* j: current column; i: total of previous lines */
-	e = string + stringlen;
-	for (p = string; p < e; p++) {
-		if (*p == '\t')
-			j += tabsize - (j%tabsize);
-		else {
-			j++;
-			if (*p == '\n') {
-				i += j;
-				j = 0;
-			}
-		}
-	}
-
-	/* Second pass: create output string and fill it */
-	out = PyString_FromStringAndSize(NULL, i+j);
-	if (out == NULL)
-		return NULL;
-
-	i = 0;
-	q = PyString_AS_STRING(out);
-
-	for (p = string; p < e; p++) {
-		if (*p == '\t') {
-			j = tabsize - (i%tabsize);
-			i += j;
-			while (j-- > 0)
-				*q++ = ' ';
-		} else {
-			*q++ = *p;
-			i++;
-			if (*p == '\n')
-				i = 0;
-		}
-	}
-
-	return out;
-}
-
-
-PyDoc_STRVAR(count__doc__,
-"count(s, sub[, start[, end]]) -> int\n"
-"\n"
-"Return the number of occurrences of substring sub in string\n"
-"s[start:end].  Optional arguments start and end are\n"
-"interpreted as in slice notation.");
-
-static PyObject *
-strop_count(PyObject *self, PyObject *args)
-{
-	char *s, *sub;
-	Py_ssize_t len, n;
-	Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
-	Py_ssize_t m, r;
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last))
-		return NULL;
-	if (last > len)
-		last = len;
-	if (last < 0)
-		last += len;
-	if (last < 0)
-		last = 0;
-	if (i < 0)
-		i += len;
-	if (i < 0)
-		i = 0;
-	m = last + 1 - n;
-	if (n == 0)
-		return PyInt_FromLong((long) (m-i));
-
-	r = 0;
-	while (i < m) {
-		if (!memcmp(s+i, sub, n)) {
-			r++;
-			i += n;
-		} else {
-			i++;
-		}
-	}
-	return PyInt_FromLong((long) r);
-}
-
-
-PyDoc_STRVAR(swapcase__doc__,
-"swapcase(s) -> string\n"
-"\n"
-"Return a copy of the string s with upper case characters\n"
-"converted to lowercase and vice versa.");
-
-static PyObject *
-strop_swapcase(PyObject *self, PyObject *args)
-{
-	char *s, *s_new;
-	Py_ssize_t i, n;
-	PyObject *newstr;
-	int changed;
-
-	WARN;
-	if (PyString_AsStringAndSize(args, &s, &n))
-		return NULL;
-	newstr = PyString_FromStringAndSize(NULL, n);
-	if (newstr == NULL)
-		return NULL;
-	s_new = PyString_AsString(newstr);
-	changed = 0;
-	for (i = 0; i < n; i++) {
-		int c = Py_CHARMASK(*s++);
-		if (islower(c)) {
-			changed = 1;
-			*s_new = toupper(c);
-		}
-		else if (isupper(c)) {
-			changed = 1;
-			*s_new = tolower(c);
-		}
-		else
-			*s_new = c;
-		s_new++;
-	}
-	if (!changed) {
-		Py_DECREF(newstr);
-		Py_INCREF(args);
-		return args;
-	}
-	return newstr;
-}
-
-
-PyDoc_STRVAR(atoi__doc__,
-"atoi(s [,base]) -> int\n"
-"\n"
-"Return the integer represented by the string s in the given\n"
-"base, which defaults to 10.  The string s must consist of one\n"
-"or more digits, possibly preceded by a sign.  If base is 0, it\n"
-"is chosen from the leading characters of s, 0 for octal, 0x or\n"
-"0X for hexadecimal.  If base is 16, a preceding 0x or 0X is\n"
-"accepted.");
-
-static PyObject *
-strop_atoi(PyObject *self, PyObject *args)
-{
-	char *s, *end;
-	int base = 10;
-	long x;
-	char buffer[256]; /* For errors */
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base))
-		return NULL;
-
-	if ((base != 0 && base < 2) || base > 36) {
-		PyErr_SetString(PyExc_ValueError, "invalid base for atoi()");
-		return NULL;
-	}
-
-	while (*s && isspace(Py_CHARMASK(*s)))
-		s++;
-	errno = 0;
-	if (base == 0 && s[0] == '0')
-		x = (long) PyOS_strtoul(s, &end, base);
-	else
-		x = PyOS_strtol(s, &end, base);
-	if (end == s || !isalnum(Py_CHARMASK(end[-1])))
-		goto bad;
-	while (*end && isspace(Py_CHARMASK(*end)))
-		end++;
-	if (*end != '\0') {
-  bad:
-		PyOS_snprintf(buffer, sizeof(buffer),
-			      "invalid literal for atoi(): %.200s", s);
-		PyErr_SetString(PyExc_ValueError, buffer);
-		return NULL;
-	}
-	else if (errno != 0) {
-		PyOS_snprintf(buffer, sizeof(buffer), 
-			      "atoi() literal too large: %.200s", s);
-		PyErr_SetString(PyExc_ValueError, buffer);
-		return NULL;
-	}
-	return PyInt_FromLong(x);
-}
-
-
-PyDoc_STRVAR(atol__doc__,
-"atol(s [,base]) -> long\n"
-"\n"
-"Return the long integer represented by the string s in the\n"
-"given base, which defaults to 10.  The string s must consist\n"
-"of one or more digits, possibly preceded by a sign.  If base\n"
-"is 0, it is chosen from the leading characters of s, 0 for\n"
-"octal, 0x or 0X for hexadecimal.  If base is 16, a preceding\n"
-"0x or 0X is accepted.  A trailing L or l is not accepted,\n"
-"unless base is 0.");
-
-static PyObject *
-strop_atol(PyObject *self, PyObject *args)
-{
-	char *s, *end;
-	int base = 10;
-	PyObject *x;
-	char buffer[256]; /* For errors */
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
-		return NULL;
-
-	if ((base != 0 && base < 2) || base > 36) {
-		PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
-		return NULL;
-	}
-
-	while (*s && isspace(Py_CHARMASK(*s)))
-		s++;
-	if (s[0] == '\0') {
-		PyErr_SetString(PyExc_ValueError, "empty string for atol()");
-		return NULL;
-	}
-	x = PyLong_FromString(s, &end, base);
-	if (x == NULL)
-		return NULL;
-	if (base == 0 && (*end == 'l' || *end == 'L'))
-		end++;
-	while (*end && isspace(Py_CHARMASK(*end)))
-		end++;
-	if (*end != '\0') {
-		PyOS_snprintf(buffer, sizeof(buffer),
-			      "invalid literal for atol(): %.200s", s);
-		PyErr_SetString(PyExc_ValueError, buffer);
-		Py_DECREF(x);
-		return NULL;
-	}
-	return x;
-}
-
-
-PyDoc_STRVAR(atof__doc__,
-"atof(s) -> float\n"
-"\n"
-"Return the floating point number represented by the string s.");
-
-static PyObject *
-strop_atof(PyObject *self, PyObject *args)
-{
-	char *s, *end;
-	double x;
-	char buffer[256]; /* For errors */
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "s:atof", &s))
-		return NULL;
-	while (*s && isspace(Py_CHARMASK(*s)))
-		s++;
-	if (s[0] == '\0') {
-		PyErr_SetString(PyExc_ValueError, "empty string for atof()");
-		return NULL;
-	}
-	errno = 0;
-	PyFPE_START_PROTECT("strop_atof", return 0)
-	x = PyOS_ascii_strtod(s, &end);
-	PyFPE_END_PROTECT(x)
-	while (*end && isspace(Py_CHARMASK(*end)))
-		end++;
-	if (*end != '\0') {
-		PyOS_snprintf(buffer, sizeof(buffer),
-			      "invalid literal for atof(): %.200s", s);
-		PyErr_SetString(PyExc_ValueError, buffer);
-		return NULL;
-	}
-	else if (errno != 0) {
-		PyOS_snprintf(buffer, sizeof(buffer), 
-			      "atof() literal too large: %.200s", s);
-		PyErr_SetString(PyExc_ValueError, buffer);
-		return NULL;
-	}
-	return PyFloat_FromDouble(x);
-}
-
-
-PyDoc_STRVAR(maketrans__doc__,
-"maketrans(frm, to) -> string\n"
-"\n"
-"Return a translation table (a string of 256 bytes long)\n"
-"suitable for use in string.translate.  The strings frm and to\n"
-"must be of the same length.");
-
-static PyObject *
-strop_maketrans(PyObject *self, PyObject *args)
-{
-	unsigned char *c, *from=NULL, *to=NULL;
-	Py_ssize_t i, fromlen=0, tolen=0;
-	PyObject *result;
-
-	if (!PyArg_ParseTuple(args, "t#t#:maketrans", &from, &fromlen, &to, &tolen))
-		return NULL;
-
-	if (fromlen != tolen) {
-		PyErr_SetString(PyExc_ValueError,
-				"maketrans arguments must have same length");
-		return NULL;
-	}
-
-	result = PyString_FromStringAndSize((char *)NULL, 256);
-	if (result == NULL)
-		return NULL;
-	c = (unsigned char *) PyString_AS_STRING((PyStringObject *)result);
-	for (i = 0; i < 256; i++)
-		c[i]=(unsigned char)i;
-	for (i = 0; i < fromlen; i++)
-		c[from[i]]=to[i];
-
-	return result;
-}
-
-
-PyDoc_STRVAR(translate__doc__,
-"translate(s,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 *
-strop_translate(PyObject *self, PyObject *args)
-{
-	register char *input, *table, *output;
-	Py_ssize_t i; 
-	int c, changed = 0;
-	PyObject *input_obj;
-	char *table1, *output_start, *del_table=NULL;
-	Py_ssize_t inlen, tablen, dellen = 0;
-	PyObject *result;
-	int trans_table[256];
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
-			      &table1, &tablen, &del_table, &dellen))
-		return NULL;
-	if (tablen != 256) {
-		PyErr_SetString(PyExc_ValueError,
-			      "translation table must be 256 characters long");
-		return NULL;
-	}
-
-	table = table1;
-	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_AsString(input_obj);
-
-	if (dellen == 0) {
-		/* 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)
-			return result;
-		Py_DECREF(result);
-		Py_INCREF(input_obj);
-		return input_obj;
-	}
-
-	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) {
-		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;
-}
-
-
-/* What follows is used for implementing replace().  Perry Stoll. */
-
-/*
-  mymemfind
-
-  strstr replacement for arbitrary blocks of memory.
-
-  Locates the first occurrence in the memory pointed to by MEM of the
-  contents of memory pointed to by PAT.  Returns the index into MEM if
-  found, or -1 if not found.  If len of PAT is greater than length of
-  MEM, the function returns -1.
-*/
-static Py_ssize_t 
-mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
-{
-	register Py_ssize_t ii;
-
-	/* pattern can not occur in the last pat_len-1 chars */
-	len -= pat_len;
-
-	for (ii = 0; ii <= len; ii++) {
-		if (mem[ii] == pat[0] &&
-		    (pat_len == 1 ||
-		     memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
-			return ii;
-		}
-	}
-	return -1;
-}
-
-/*
-  mymemcnt
-
-   Return the number of distinct times PAT is found in MEM.
-   meaning mem=1111 and pat==11 returns 2.
-           mem=11111 and pat==11 also return 2.
- */
-static Py_ssize_t 
-mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
-{
-	register Py_ssize_t offset = 0;
-	Py_ssize_t nfound = 0;
-
-	while (len >= 0) {
-		offset = mymemfind(mem, len, pat, pat_len);
-		if (offset == -1)
-			break;
-		mem += offset + pat_len;
-		len -= offset + pat_len;
-		nfound++;
-	}
-	return nfound;
-}
-
-/*
-   mymemreplace
-
-   Return a string in which all occurrences of PAT in memory STR are
-   replaced with SUB.
-
-   If length of PAT is less than length of STR or there are no occurrences
-   of PAT in STR, then the original string is returned. Otherwise, a new
-   string is allocated here and returned.
-
-   on return, out_len is:
-       the length of output string, or
-       -1 if the input string is returned, or
-       unchanged if an error occurs (no memory).
-
-   return value is:
-       the new string allocated locally, or
-       NULL if an error occurred.
-*/
-static char *
-mymemreplace(const char *str, Py_ssize_t len,		/* input string */
-             const char *pat, Py_ssize_t pat_len,	/* pattern string to find */
-             const char *sub, Py_ssize_t sub_len,	/* substitution string */
-             Py_ssize_t count,				/* number of replacements */
-	     Py_ssize_t *out_len)
-{
-	char *out_s;
-	char *new_s;
-	Py_ssize_t nfound, offset, new_len;
-
-	if (len == 0 || pat_len > len)
-		goto return_same;
-
-	/* find length of output string */
-	nfound = mymemcnt(str, len, pat, pat_len);
-	if (count < 0)
-		count = PY_SSIZE_T_MAX;
-	else if (nfound > count)
-		nfound = count;
-	if (nfound == 0)
-		goto return_same;
-
-	new_len = len + nfound*(sub_len - pat_len);
-	if (new_len == 0) {
-		/* Have to allocate something for the caller to free(). */
-		out_s = (char *)PyMem_MALLOC(1);
-		if (out_s == NULL)
-			return NULL;
-		out_s[0] = '\0';
-	}
-	else {
-		assert(new_len > 0);
-		new_s = (char *)PyMem_MALLOC(new_len);
-		if (new_s == NULL)
-			return NULL;
-		out_s = new_s;
-
-		for (; count > 0 && len > 0; --count) {
-			/* find index of next instance of pattern */
-			offset = mymemfind(str, len, pat, pat_len);
-			if (offset == -1)
-				break;
-
-			/* copy non matching part of input string */
-			memcpy(new_s, str, offset);
-			str += offset + pat_len;
-			len -= offset + pat_len;
-
-			/* copy substitute into the output string */
-			new_s += offset;
-			memcpy(new_s, sub, sub_len);
-			new_s += sub_len;
-		}
-		/* copy any remaining values into output string */
-		if (len > 0)
-			memcpy(new_s, str, len);
-	}
-	*out_len = new_len;
-	return out_s;
-
-  return_same:
-	*out_len = -1;
-	return (char *)str; /* cast away const */
-}
-
-
-PyDoc_STRVAR(replace__doc__,
-"replace (str, old, new[, maxsplit]) -> string\n"
-"\n"
-"Return a copy of string str 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.");
-
-static PyObject *
-strop_replace(PyObject *self, PyObject *args)
-{
-	char *str, *pat,*sub,*new_s;
-	Py_ssize_t len,pat_len,sub_len,out_len;
-	Py_ssize_t count = -1;
-	PyObject *newstr;
-
-	WARN;
-	if (!PyArg_ParseTuple(args, "t#t#t#|n:replace",
-			      &str, &len, &pat, &pat_len, &sub, &sub_len,
-			      &count))
-		return NULL;
-	if (pat_len <= 0) {
-		PyErr_SetString(PyExc_ValueError, "empty pattern string");
-		return NULL;
-	}
-	/* CAUTION:  strop treats a replace count of 0 as infinity, unlke
-	 * current (2.1) string.py and string methods.  Preserve this for
-	 * ... well, hard to say for what <wink>.
-	 */
-	if (count == 0)
-		count = -1;
-	new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
-	if (new_s == NULL) {
-		PyErr_NoMemory();
-		return NULL;
-	}
-	if (out_len == -1) {
-		/* we're returning another reference to the input string */
-		newstr = PyTuple_GetItem(args, 0);
-		Py_XINCREF(newstr);
-	}
-	else {
-		newstr = PyString_FromStringAndSize(new_s, out_len);
-		PyMem_FREE(new_s);
-	}
-	return newstr;
-}
-
-
-/* List of functions defined in the module */
-
-static PyMethodDef
-strop_methods[] = {
-	{"atof",	strop_atof,	   METH_VARARGS, atof__doc__},
-	{"atoi",	strop_atoi,	   METH_VARARGS, atoi__doc__},
-	{"atol",	strop_atol,	   METH_VARARGS, atol__doc__},
-	{"capitalize",	strop_capitalize,  METH_O,       capitalize__doc__},
-	{"count",	strop_count,	   METH_VARARGS, count__doc__},
-	{"expandtabs",	strop_expandtabs,  METH_VARARGS, expandtabs__doc__},
-	{"find",	strop_find,	   METH_VARARGS, find__doc__},
-	{"join",	strop_joinfields,  METH_VARARGS, joinfields__doc__},
-	{"joinfields",	strop_joinfields,  METH_VARARGS, joinfields__doc__},
-	{"lstrip",	strop_lstrip,	   METH_O,       lstrip__doc__},
-	{"lower",	strop_lower,	   METH_O,       lower__doc__},
-	{"maketrans",	strop_maketrans,   METH_VARARGS, maketrans__doc__},
-	{"replace",	strop_replace,	   METH_VARARGS, replace__doc__},
-	{"rfind",	strop_rfind,	   METH_VARARGS, rfind__doc__},
-	{"rstrip",	strop_rstrip,	   METH_O,       rstrip__doc__},
-	{"split",	strop_splitfields, METH_VARARGS, splitfields__doc__},
-	{"splitfields",	strop_splitfields, METH_VARARGS, splitfields__doc__},
-	{"strip",	strop_strip,	   METH_O,       strip__doc__},
-	{"swapcase",	strop_swapcase,    METH_O,       swapcase__doc__},
-	{"translate",	strop_translate,   METH_VARARGS, translate__doc__},
-	{"upper",	strop_upper,	   METH_O,       upper__doc__},
-	{NULL,		NULL}	/* sentinel */
-};
-
-
-PyMODINIT_FUNC
-initstrop(void)
-{
-	PyObject *m, *s;
-	char buf[256];
-	int c, n;
-	m = Py_InitModule4("strop", strop_methods, strop_module__doc__,
-			   (PyObject*)NULL, PYTHON_API_VERSION);
-	if (m == NULL)
-		return;
-
-	/* Create 'whitespace' object */
-	n = 0;
-	for (c = 0; c < 256; c++) {
-		if (isspace(c))
-			buf[n++] = c;
-	}
-	s = PyString_FromStringAndSize(buf, n);
-	if (s)
-		PyModule_AddObject(m, "whitespace", s);
-
-	/* Create 'lowercase' object */
-	n = 0;
-	for (c = 0; c < 256; c++) {
-		if (islower(c))
-			buf[n++] = c;
-	}
-	s = PyString_FromStringAndSize(buf, n);
-	if (s)
-		PyModule_AddObject(m, "lowercase", s);
-
-	/* Create 'uppercase' object */
-	n = 0;
-	for (c = 0; c < 256; c++) {
-		if (isupper(c))
-			buf[n++] = c;
-	}
-	s = PyString_FromStringAndSize(buf, n);
-	if (s)
-		PyModule_AddObject(m, "uppercase", s);
-}

Deleted: /python/branches/p3yk-noslice/Modules/svmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/svmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,966 +0,0 @@
-/* SV module -- interface to the Indigo video board */
-
-/* WARNING! This module is for hardware that we don't have any more,
-   so it hasn't been tested.  It has been converted to the new coding
-   style, and it is possible that this conversion has broken something
-   -- user beware! */
-
-#include <sys/time.h>
-#include <svideo.h>
-#include "Python.h"
-#include "compile.h"
-#include "yuv.h"		/* for YUV conversion functions */
-
-typedef struct {
-	PyObject_HEAD
-	SV_nodeP ob_svideo;
-	svCaptureInfo ob_info;
-} svobject;
-
-typedef struct {
-	PyObject_HEAD
-	void *ob_capture;
-	int ob_mustunlock;
-	svCaptureInfo ob_info;
-	svobject *ob_svideo;
-} captureobject;
-
-static PyObject *SvError;		/* exception sv.error */
-
-static PyObject *newcaptureobject(svobject *, void *, int);
-
-/* Set a SV-specific error from svideo_errno and return NULL */
-static PyObject *
-sv_error(void)
-{
-	PyErr_SetString(SvError, svStrerror(svideo_errno));
-	return NULL;
-}
-
-static PyObject *
-svc_conversion(captureobject *self, PyObject *args, void (*function)(),	float factor)
-{
-	PyObject *output;
-	int invert;
-	char* outstr;
-
-	if (!PyArg_Parse(args, "i", &invert))
-		return NULL;
-
-	if (!(output = PyString_FromStringAndSize(
-		NULL,
-		(int)(self->ob_info.width * self->ob_info.height * factor))))
-	{
-		return NULL;
-	}
-	if (!(outstr = PyString_AsString(output))) {
-		Py_DECREF(output);
-		return NULL;
-	}
-
-	(*function)((boolean)invert, self->ob_capture,
-		    outstr,
-		    self->ob_info.width, self->ob_info.height);
-
-	return output;
-}
-
-/*
- * 3 functions to convert from Starter Video YUV 4:1:1 format to
- * Compression Library 4:2:2 Duplicate Chroma format.
- */
-static PyObject *
-svc_YUVtoYUV422DC(captureobject *self, PyObject *args)
-{
-	if (self->ob_info.format != SV_YUV411_FRAMES) {
-		PyErr_SetString(SvError, "data has bad format");
-		return NULL;
-	}
-	return svc_conversion(self, args, yuv_sv411_to_cl422dc, 2.0);
-}
-
-static PyObject *
-svc_YUVtoYUV422DC_quarter(captureobject *self, PyObject *args)
-{
-	if (self->ob_info.format != SV_YUV411_FRAMES) {
-		PyErr_SetString(SvError, "data has bad format");
-		return NULL;
-	}
-	return svc_conversion(self, args,
-			      yuv_sv411_to_cl422dc_quartersize, 0.5);
-}
-
-static PyObject *
-svc_YUVtoYUV422DC_sixteenth(captureobject *self, PyObject *args)
-{
-	if (self->ob_info.format != SV_YUV411_FRAMES) {
-		PyErr_SetString(SvError, "data has bad format");
-		return NULL;
-	}
-	return svc_conversion(self, args,
-			      yuv_sv411_to_cl422dc_sixteenthsize, 0.125);
-}
-
-static PyObject *
-svc_YUVtoRGB(captureobject *self, PyObject *args)
-{
-	switch (self->ob_info.format) {
-	case SV_YUV411_FRAMES:
-	case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
-		break;
-	default:
-		PyErr_SetString(SvError, "data had bad format");
-		return NULL;
-	}
-	return svc_conversion(self, args, svYUVtoRGB, (float) sizeof(long));
-}
-
-static PyObject *
-svc_RGB8toRGB32(captureobject *self, PyObject *args)
-{
-	if (self->ob_info.format != SV_RGB8_FRAMES) {
-		PyErr_SetString(SvError, "data has bad format");
-		return NULL;
-	}
-	return svc_conversion(self, args, svRGB8toRGB32, (float) sizeof(long));
-}
-
-static PyObject *
-svc_InterleaveFields(captureobject *self, PyObject *args)
-{
-	if (self->ob_info.format != SV_RGB8_FRAMES) {
-		PyErr_SetString(SvError, "data has bad format");
-		return NULL;
-	}
-	return svc_conversion(self, args, svInterleaveFields, 1.0);
-}
-
-static PyObject *
-svc_GetFields(captureobject *self, PyObject *args)
-{
-	PyObject *f1 = NULL;
-	PyObject *f2 = NULL;
-	PyObject *ret = NULL;
-	int fieldsize;
-	char* obcapture;
-
-	if (self->ob_info.format != SV_RGB8_FRAMES) {
-		PyErr_SetString(SvError, "data has bad format");
-		return NULL;
-	}
-
-	fieldsize = self->ob_info.width * self->ob_info.height / 2;
-	obcapture = (char*)self->ob_capture;
-	
-	if (!(f1 = PyString_FromStringAndSize(obcapture, fieldsize)))
-		goto finally;
-	if (!(f2 = PyString_FromStringAndSize(obcapture + fieldsize,
-					      fieldsize)))
-		goto finally;
-	ret = PyTuple_Pack(2, f1, f2);
-
-  finally:
-	Py_XDECREF(f1);
-	Py_XDECREF(f2);
-	return ret;
-}
-	
-static PyObject *
-svc_UnlockCaptureData(captureobject *self, PyObject *args)
-{
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	if (!self->ob_mustunlock) {
-		PyErr_SetString(SvError, "buffer should not be unlocked");
-		return NULL;
-	}
-
-	if (svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture))
-		return sv_error();
-
-	self->ob_mustunlock = 0;
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-#ifdef USE_GL
-#include <gl.h>
-
-static PyObject *
-svc_lrectwrite(captureobject *self, PyObject *args)
-{
-	Screencoord x1, x2, y1, y2;
-
-	if (!PyArg_Parse(args, "(hhhh)", &x1, &x2, &y1, &y2))
-		return NULL;
-
-	lrectwrite(x1, x2, y1, y2, (unsigned long *) self->ob_capture);
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-#endif
-
-static PyObject *
-svc_writefile(captureobject *self, PyObject *args)
-{
-	PyObject *file;
-	int size;
-	FILE* fp;
-
-	if (!PyArg_Parse(args, "O", &file))
-		return NULL;
-
-	if (!PyFile_Check(file)) {
-		PyErr_SetString(SvError, "not a file object");
-		return NULL;
-	}
-
-	if (!(fp = PyFile_AsFile(file)))
-		return NULL;
-
-	size = self->ob_info.width * self->ob_info.height;
-
-	if (fwrite(self->ob_capture, sizeof(long), size, fp) != size) {
-		PyErr_SetString(SvError, "writing failed");
-		return NULL;
-	}
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-svc_FindVisibleRegion(captureobject *self, PyObject *args)
-{
-	void *visible;
-	int width;
-
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	if (svFindVisibleRegion(self->ob_svideo->ob_svideo,
-				self->ob_capture, &visible,
-				self->ob_info.width))
-		return sv_error();
-
-	if (visible == NULL) {
-		PyErr_SetString(SvError, "data in wrong format");
-		return NULL;
-	}
-
-	return newcaptureobject(self->ob_svideo, visible, 0);
-}
-
-static PyMethodDef capture_methods[] = {
-	{"YUVtoRGB",		(PyCFunction)svc_YUVtoRGB, METH_OLDARGS},
-	{"RGB8toRGB32",		(PyCFunction)svc_RGB8toRGB32, METH_OLDARGS},
-	{"InterleaveFields",	(PyCFunction)svc_InterleaveFields, METH_OLDARGS},
-	{"UnlockCaptureData",	(PyCFunction)svc_UnlockCaptureData, METH_OLDARGS},
-	{"FindVisibleRegion",	(PyCFunction)svc_FindVisibleRegion, METH_OLDARGS},
-	{"GetFields",		(PyCFunction)svc_GetFields, METH_OLDARGS},
-	{"YUVtoYUV422DC",	(PyCFunction)svc_YUVtoYUV422DC, METH_OLDARGS},
-	{"YUVtoYUV422DC_quarter",(PyCFunction)svc_YUVtoYUV422DC_quarter, METH_OLDARGS},
-	{"YUVtoYUV422DC_sixteenth",(PyCFunction)svc_YUVtoYUV422DC_sixteenth, METH_OLDARGS},
-#ifdef USE_GL
-	{"lrectwrite",		(PyCFunction)svc_lrectwrite, METH_OLDARGS},
-#endif
-	{"writefile",		(PyCFunction)svc_writefile, METH_OLDARGS},
-	{NULL,			NULL} 		/* sentinel */
-};
-
-static void
-capture_dealloc(captureobject *self)
-{
-	if (self->ob_capture != NULL) {
-		if (self->ob_mustunlock)
-			(void)svUnlockCaptureData(self->ob_svideo->ob_svideo,
-						  self->ob_capture);
-		self->ob_capture = NULL;
-		Py_DECREF(self->ob_svideo);
-		self->ob_svideo = NULL;
-	}
-	PyObject_Del(self);
-}
-
-static PyObject *
-capture_getattr(svobject *self, char *name)
-{
-	return Py_FindMethod(capture_methods, (PyObject *)self, name);
-}
-
-PyTypeObject Capturetype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,				/*ob_size*/
-	"sv.capture",			/*tp_name*/
-	sizeof(captureobject),		/*tp_size*/
-	0,				/*tp_itemsize*/
-	/* methods */
-	(destructor)capture_dealloc,	/*tp_dealloc*/
-	0,				/*tp_print*/
-	(getattrfunc)capture_getattr,	/*tp_getattr*/
-	0,				/*tp_setattr*/
-	0,				/*tp_compare*/
-	0,				/*tp_repr*/
-};
-
-static PyObject *
-newcaptureobject(svobject *self, void *ptr, int mustunlock)
-{
-	captureobject *p;
-
-	p = PyObject_New(captureobject, &Capturetype);
-	if (p == NULL)
-		return NULL;
-	p->ob_svideo = self;
-	Py_INCREF(self);
-	p->ob_capture = ptr;
-	p->ob_mustunlock = mustunlock;
-	p->ob_info = self->ob_info;
-	return (PyObject *) p;
-}
-
-static PyObject *
-sv_GetCaptureData(svobject *self, PyObject *args)
-{
-	void *ptr;
-	long fieldID;
-	PyObject *res, *c;
-
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	if (svGetCaptureData(self->ob_svideo, &ptr, &fieldID))
-		return sv_error();
-
-	if (ptr == NULL) {
-		PyErr_SetString(SvError, "no data available");
-		return NULL;
-	}
-
-	c = newcaptureobject(self, ptr, 1);
-	if (c == NULL)
-		return NULL;
-	res = Py_BuildValue("(Oi)", c, fieldID);
-	Py_DECREF(c);
-	return res;
-}
-
-static PyObject *
-sv_BindGLWindow(svobject *self, PyObject *args)
-{
-	long wid;
-	int mode;
-
-	if (!PyArg_Parse(args, "(ii)", &wid, &mode))
-		return NULL;
-
-	if (svBindGLWindow(self->ob_svideo, wid, mode))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_EndContinuousCapture(svobject *self, PyObject *args)
-{
-
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	if (svEndContinuousCapture(self->ob_svideo))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_IsVideoDisplayed(svobject *self, PyObject *args)
-{
-	int v;
-
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	v = svIsVideoDisplayed(self->ob_svideo);
-	if (v == -1)
-		return sv_error();
-
-	return PyInt_FromLong((long) v);
-}
-
-static PyObject *
-sv_OutputOffset(svobject *self, PyObject *args)
-{
-	int x_offset;
-	int y_offset;
-
-	if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
-		return NULL;
-
-	if (svOutputOffset(self->ob_svideo, x_offset, y_offset))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_PutFrame(svobject *self, PyObject *args)
-{
-	char *buffer;
-
-	if (!PyArg_Parse(args, "s", &buffer))
-		return NULL;
-
-	if (svPutFrame(self->ob_svideo, buffer))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_QuerySize(svobject *self, PyObject *args)
-{
-	int w;
-	int h;
-	int rw;
-	int rh;
-
-	if (!PyArg_Parse(args, "(ii)", &w, &h))
-		return NULL;
-
-	if (svQuerySize(self->ob_svideo, w, h, &rw, &rh))
-		return sv_error();
-
-	return Py_BuildValue("(ii)", (long) rw, (long) rh);
-}
-
-static PyObject *
-sv_SetSize(svobject *self, PyObject *args)
-{
-	int w;
-	int h;
-
-	if (!PyArg_Parse(args, "(ii)", &w, &h))
-		return NULL;
-
-	if (svSetSize(self->ob_svideo, w, h))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_SetStdDefaults(svobject *self, PyObject *args)
-{
-
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	if (svSetStdDefaults(self->ob_svideo))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_UseExclusive(svobject *self, PyObject *args)
-{
-	boolean onoff;
-	int mode;
-
-	if (!PyArg_Parse(args, "(ii)", &onoff, &mode))
-		return NULL;
-
-	if (svUseExclusive(self->ob_svideo, onoff, mode))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_WindowOffset(svobject *self, PyObject *args)
-{
-	int x_offset;
-	int y_offset;
-
-	if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
-		return NULL;
-
-	if (svWindowOffset(self->ob_svideo, x_offset, y_offset))
-		return sv_error();
-
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-sv_CaptureBurst(svobject *self, PyObject *args)
-{
-	int bytes, i;
-	svCaptureInfo info;
-	void *bitvector = NULL;
-	PyObject *videodata = NULL;
-	PyObject *bitvecobj = NULL;
-	PyObject *res = NULL;
-	static PyObject *evenitem, *odditem;
-
-	if (!PyArg_Parse(args, "(iiiii)", &info.format,
-			 &info.width, &info.height,
-			 &info.size, &info.samplingrate))
-		return NULL;
-
-	switch (info.format) {
-	case SV_RGB8_FRAMES:
-		bitvector = malloc(SV_BITVEC_SIZE(info.size));
-		break;
-	case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
-		break;
-	default:
-		PyErr_SetString(SvError, "illegal format specified");
-		return NULL;
-	}
-
-	if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) {
-		res = sv_error();
-		goto finally;
-	}
-
-	if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
-		goto finally;
-
-	/* XXX -- need to do something about the bitvector */
-	{
-		char* str = PyString_AsString(videodata);
-		if (!str)
-			goto finally;
-		
-		if (svCaptureBurst(self->ob_svideo, &info, str, bitvector)) {
-			res = sv_error();
-			goto finally;
-		}
-	}
-
-	if (bitvector) {
-		if (evenitem == NULL) {
-			if (!(evenitem = PyInt_FromLong(0)))
-				goto finally;
-		}
-		if (odditem == NULL) {
-			if (!(odditem = PyInt_FromLong(1)))
-				goto finally;
-		}
-		if (!(bitvecobj = PyTuple_New(2 * info.size)))
-			goto finally;
-
-		for (i = 0; i < 2 * info.size; i++) {
-			int sts;
-
-			if (SV_GET_FIELD(bitvector, i) == SV_EVEN_FIELD) {
-				Py_INCREF(evenitem);
-				sts = PyTuple_SetItem(bitvecobj, i, evenitem);
-			} else {
-				Py_INCREF(odditem);
-				sts = PyTuple_SetItem(bitvecobj, i, odditem);
-			}
-			if (sts < 0)
-				goto finally;
-		}
-	} else {
-		bitvecobj = Py_None;
-		Py_INCREF(Py_None);
-	}
-
-	res = Py_BuildValue("((iiiii)OO)", info.format,
-			    info.width, info.height,
-			    info.size, info.samplingrate,
-			    videodata, bitvecobj);
-
-  finally:
-	if (bitvector)
-		free(bitvector);
-
-	Py_XDECREF(videodata);
-	Py_XDECREF(bitvecobj);
-	return res;
-}
-
-static PyObject *
-sv_CaptureOneFrame(svobject *self, PyObject *args)
-{
-	svCaptureInfo info;
-	int format, width, height;
-	int bytes;
-	PyObject *videodata = NULL;
-	PyObject *res = NULL;
-	char *str;
-	
-	if (!PyArg_Parse(args, "(iii)", &format, &width, &height))
-		return NULL;
-
-	info.format = format;
-	info.width = width;
-	info.height = height;
-	info.size = 0;
-	info.samplingrate = 0;
-	if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes))
-		return sv_error();
-
-	if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
-		return NULL;
-	
-	str = PyString_AsString(videodata);
-	if (!str)
-		goto finally;
-
-	if (svCaptureOneFrame(self->ob_svideo, format, &width, &height, str)) {
-		res = sv_error();
-		goto finally;
-	}
-
-	res = Py_BuildValue("(iiO)", width, height, videodata);
-
-  finally:
-	Py_XDECREF(videodata);
-	return res;
-}
-
-static PyObject *
-sv_InitContinuousCapture(svobject *self, PyObject *args)
-{
-	svCaptureInfo info;
-
-	if (!PyArg_Parse(args, "(iiiii)", &info.format,
-			 &info.width, &info.height,
-			 &info.size, &info.samplingrate))
-		return NULL;
-
-	if (svInitContinuousCapture(self->ob_svideo, &info))
-		return sv_error();
-
-	self->ob_info = info;
-
-	return Py_BuildValue("(iiiii)", info.format, info.width, info.height,
-			     info.size, info.samplingrate);
-}
-
-static PyObject *
-sv_LoadMap(svobject *self, PyObject *args)
-{
-	PyObject *rgb;
-	PyObject *res = NULL;
-	rgb_tuple *mapp = NULL;
-	int maptype;
-	int i, j;			     /* indices */
-
-	if (!PyArg_Parse(args, "(iO)", &maptype, &rgb))
-		return NULL;
-
-	if (!PyList_Check(rgb) || PyList_Size(rgb) != 256) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-
-	if (!(mapp = PyMem_NEW(rgb_tuple, 256)))
-		return PyErr_NoMemory();
-
-	for (i = 0; i < 256; i++) {
-		PyObject* v = PyList_GetItem(rgb, i);
-		if (!v)
-			goto finally;
-
-		if (!PyTuple_Check(v) || PyTuple_Size(v) != 3) {
-			PyErr_BadArgument();
-			goto finally;
-		}
-		for (j = 0; j < 3; j++) {
-			PyObject* cell = PyTuple_GetItem(v, j);
-			if (!cell)
-				goto finally;
-
-			if (!PyInt_Check(cell)) {
-				PyErr_BadArgument();
-				goto finally;
-			}
-			switch (j) {
-			case 0: mapp[i].red = PyInt_AsLong(cell); break;
-			case 1: mapp[i].blue = PyInt_AsLong(cell); break;
-			case 2: mapp[i].green = PyInt_AsLong(cell); break;
-			}
-			if (PyErr_Occurred())
-				goto finally;
-		}
-	}
-
-	if (svLoadMap(self->ob_svideo, maptype, mapp)) {
-		res = sv_error();
-		goto finally;
-	}
-
-	Py_INCREF(Py_None);
-	res = Py_None;
-
-  finally:
-	PyMem_DEL(mapp);
-	return res;
-}
-		
-static PyObject *
-sv_CloseVideo(svobject *self, PyObject *args)
-{
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	if (svCloseVideo(self->ob_svideo))
-		return sv_error();
-
-	self->ob_svideo = NULL;
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-doParams(svobject *self, PyObject *args,
-         int (*func)(SV_nodeP, long *, int), int modified)
-{
-	PyObject *list;
-	PyObject *res = NULL;
-	long *PVbuffer = NULL;
-	long length;
-	int i;
-	
-	if (!PyArg_Parse(args, "O", &list))
-		return NULL;
-
-	if (!PyList_Check(list)) {
-		PyErr_BadArgument();
-		return NULL;
-	}
-
-	if ((length = PyList_Size(list)) < 0)
-		return NULL;
-
-	PVbuffer = PyMem_NEW(long, length);
-	if (PVbuffer == NULL)
-		return PyErr_NoMemory();
-
-	for (i = 0; i < length; i++) {
-		PyObject *v = PyList_GetItem(list, i);
-		if (!v)
-			goto finally;
-
-		if (!PyInt_Check(v)) {
-			PyErr_BadArgument();
-			goto finally;
-		}
-		PVbuffer[i] = PyInt_AsLong(v);
-		/* can't just test the return value, because what if the
-		   value was -1?!
-		*/
-		if (PVbuffer[i] == -1 && PyErr_Occurred())
-			goto finally;
-	}
-
-	if ((*func)(self->ob_svideo, PVbuffer, length)) {
-		res = sv_error();
-		goto finally;
-	}
-
-	if (modified) {
-		for (i = 0; i < length; i++) {
-			PyObject* v = PyInt_FromLong(PVbuffer[i]);
-			if (!v || PyList_SetItem(list, i, v) < 0)
-				goto finally;
-		}
-	}
-
-	Py_INCREF(Py_None);
-	res = Py_None;
-
-  finally:
-	PyMem_DEL(PVbuffer);
-	return res;
-}
-
-static PyObject *
-sv_GetParam(PyObject *self, PyObject *args)
-{
-	return doParams(self, args, svGetParam, 1);
-}
-
-static PyObject *
-sv_GetParamRange(PyObject *self, PyObject *args)
-{
-	return doParams(self, args, svGetParamRange, 1);
-}
-
-static PyObject *
-sv_SetParam(PyObject *self, PyObject *args)
-{
-	return doParams(self, args, svSetParam, 0);
-}
-
-static PyMethodDef svideo_methods[] = {
-	{"BindGLWindow",	(PyCFunction)sv_BindGLWindow, METH_OLDARGS},
-	{"EndContinuousCapture",(PyCFunction)sv_EndContinuousCapture, METH_OLDARGS},
-	{"IsVideoDisplayed",	(PyCFunction)sv_IsVideoDisplayed, METH_OLDARGS},
-	{"OutputOffset",	(PyCFunction)sv_OutputOffset, METH_OLDARGS},
-	{"PutFrame",		(PyCFunction)sv_PutFrame, METH_OLDARGS},
-	{"QuerySize",		(PyCFunction)sv_QuerySize, METH_OLDARGS},
-	{"SetSize",		(PyCFunction)sv_SetSize, METH_OLDARGS},
-	{"SetStdDefaults",	(PyCFunction)sv_SetStdDefaults, METH_OLDARGS},
-	{"UseExclusive",	(PyCFunction)sv_UseExclusive, METH_OLDARGS},
-	{"WindowOffset",	(PyCFunction)sv_WindowOffset, METH_OLDARGS},
-	{"InitContinuousCapture",(PyCFunction)sv_InitContinuousCapture, METH_OLDARGS},
-	{"CaptureBurst",	(PyCFunction)sv_CaptureBurst, METH_OLDARGS},
-	{"CaptureOneFrame",	(PyCFunction)sv_CaptureOneFrame, METH_OLDARGS},
-	{"GetCaptureData",	(PyCFunction)sv_GetCaptureData, METH_OLDARGS},
-	{"CloseVideo",		(PyCFunction)sv_CloseVideo, METH_OLDARGS},
-	{"LoadMap",		(PyCFunction)sv_LoadMap, METH_OLDARGS},
-	{"GetParam",		(PyCFunction)sv_GetParam, METH_OLDARGS},
-	{"GetParamRange",	(PyCFunction)sv_GetParamRange, METH_OLDARGS},
-	{"SetParam",		(PyCFunction)sv_SetParam, METH_OLDARGS},
-	{NULL,			NULL} 		/* sentinel */
-};
-
-static PyObject *
-sv_conversion(PyObject *self, PyObject *args, void (*function)(),
-              int inputfactor, float factor)
-{
-	int invert, width, height, inputlength;
-	char *input, *str;
-	PyObject *output;
-
-	if (!PyArg_Parse(args, "(is#ii)", &invert,
-			 &input, &inputlength, &width, &height))
-		return NULL;
-
-	if (width * height * inputfactor > inputlength) {
-		PyErr_SetString(SvError, "input buffer not long enough");
-		return NULL;
-	}
-
-	if (!(output = PyString_FromStringAndSize(NULL,
-					      (int)(width * height * factor))))
-		return NULL;
-
-	str = PyString_AsString(output);
-	if (!str) {
-		Py_DECREF(output);
-		return NULL;
-	}
-	(*function)(invert, input, str, width, height);
-
-	return output;
-}
-
-static PyObject *
-sv_InterleaveFields(PyObject *self, PyObject *args)
-{
-	return sv_conversion(self, args, svInterleaveFields, 1, 1.0);
-}
-
-static PyObject *
-sv_RGB8toRGB32(PyObject *self, PyObject *args)
-{
-	return sv_conversion(self, args, svRGB8toRGB32, 1, (float) sizeof(long));
-}
-
-static PyObject *
-sv_YUVtoRGB(PyObject *self, PyObject *args)
-{
-	return sv_conversion(self, args, svYUVtoRGB, 2, (float) sizeof(long));
-}
-
-static void
-svideo_dealloc(svobject *self)
-{
-	if (self->ob_svideo != NULL)
-		(void) svCloseVideo(self->ob_svideo);
-	PyObject_Del(self);
-}
-
-static PyObject *
-svideo_getattr(svobject *self, char *name)
-{
-	return Py_FindMethod(svideo_methods, (PyObject *)self, name);
-}
-
-PyTypeObject Svtype = {
-	PyObject_HEAD_INIT(&PyType_Type)
-	0,			/*ob_size*/
-	"sv.sv",		/*tp_name*/
-	sizeof(svobject),	/*tp_size*/
-	0,			/*tp_itemsize*/
-	/* methods */
-	(destructor)svideo_dealloc, /*tp_dealloc*/
-	0,			/*tp_print*/
-	(getattrfunc)svideo_getattr, /*tp_getattr*/
-	0,			/*tp_setattr*/
-	0,			/*tp_compare*/
-	0,			/*tp_repr*/
-};
-
-static PyObject *
-newsvobject(SV_nodeP svp)
-{
-	svobject *p;
-
-	p = PyObject_New(svobject, &Svtype);
-	if (p == NULL)
-		return NULL;
-	p->ob_svideo = svp;
-	p->ob_info.format = 0;
-	p->ob_info.size = 0;
-	p->ob_info.width = 0;
-	p->ob_info.height = 0;
-	p->ob_info.samplingrate = 0;
-	return (PyObject *) p;
-}
-
-static PyObject *
-sv_OpenVideo(PyObject *self, PyObject *args)
-{
-	SV_nodeP svp;
-
-	if (!PyArg_Parse(args, ""))
-		return NULL;
-
-	svp = svOpenVideo();
-	if (svp == NULL)
-		return sv_error();
-
-	return newsvobject(svp);
-}
-
-static PyMethodDef sv_methods[] = {
-	{"InterleaveFields",	(PyCFunction)sv_InterleaveFields, METH_OLDARGS},
-	{"RGB8toRGB32",		(PyCFunction)sv_RGB8toRGB32, METH_OLDARGS},
-	{"YUVtoRGB",		(PyCFunction)sv_YUVtoRGB, METH_OLDARGS},
-	{"OpenVideo",		(PyCFunction)sv_OpenVideo, METH_OLDARGS},
-	{NULL,			NULL}	/* Sentinel */
-};
-
-void
-initsv(void)
-{
-	PyObject *m, *d;
-
-	m = Py_InitModule("sv", sv_methods);
-	if (m == NULL)
-		return;
-	d = PyModule_GetDict(m);
-
-	SvError = PyErr_NewException("sv.error", NULL, NULL);
-	if (SvError == NULL || PyDict_SetItemString(d, "error", SvError) != 0)
-		return;
-}

Modified: python/branches/p3yk-noslice/Modules/symtablemodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/symtablemodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/symtablemodule.c	Wed Jul 11 15:40:56 2007
@@ -33,7 +33,7 @@
 	st = Py_SymtableString(str, filename, start);
 	if (st == NULL)
 		return NULL;
-	t = st->st_symbols;
+	t = st->st_blocks;
 	Py_INCREF(t);
 	PyMem_Free((void *)st->st_future);
 	PySymtable_Free(st);

Modified: python/branches/p3yk-noslice/Modules/timemodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/timemodule.c	(original)
+++ python/branches/p3yk-noslice/Modules/timemodule.c	Wed Jul 11 15:40:56 2007
@@ -175,7 +175,8 @@
 		if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
 			/* Unlikely to happen - this works on all intel
 			   machines at least!  Revert to clock() */
-			return PyFloat_FromDouble(clock());
+			return PyFloat_FromDouble(((double)clock()) /
+						  CLOCKS_PER_SEC);
 		}
 		divisor = (double)freq.QuadPart;
 	}

Deleted: /python/branches/p3yk-noslice/Modules/timing.h
==============================================================================
--- /python/branches/p3yk-noslice/Modules/timing.h	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 1993 George V. Neville-Neil
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *	This product includes software developed by George V. Neville-Neil
- * 4. The name, George Neville-Neil may not be used to endorse or promote 
- *    products derived from this software without specific prior 
- *    written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef _TIMING_H_
-#define _TIMING_H_
-
-#ifdef TIME_WITH_SYS_TIME
-#include <sys/time.h>
-#include <time.h>
-#else /* !TIME_WITH_SYS_TIME */
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else /* !HAVE_SYS_TIME_H */
-#include <time.h>
-#endif /* !HAVE_SYS_TIME_H */
-#endif /* !TIME_WITH_SYS_TIME */
-
-static struct timeval aftertp, beforetp;
-
-#define BEGINTIMING gettimeofday(&beforetp, NULL)
-
-#define ENDTIMING gettimeofday(&aftertp, NULL); \
-    if(beforetp.tv_usec > aftertp.tv_usec) \
-    {  \
-         aftertp.tv_usec += 1000000;  \
-         aftertp.tv_sec--; \
-    }
-
-#define TIMINGUS (((aftertp.tv_sec - beforetp.tv_sec) * 1000000) + \
-		  (aftertp.tv_usec - beforetp.tv_usec))
-
-#define TIMINGMS (((aftertp.tv_sec - beforetp.tv_sec) * 1000) + \
-		  ((aftertp.tv_usec - beforetp.tv_usec) / 1000))
-
-#define TIMINGS  ((aftertp.tv_sec - beforetp.tv_sec) + \
-		  (aftertp.tv_usec - beforetp.tv_usec) / 1000000)
-
-#endif /* _TIMING_H_ */

Deleted: /python/branches/p3yk-noslice/Modules/timingmodule.c
==============================================================================
--- /python/branches/p3yk-noslice/Modules/timingmodule.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,58 +0,0 @@
-/*
- * Author: George V. Neville-Neil
- */
-
-#include "Python.h"
-
-/* Our stuff... */
-#include "timing.h"
-
-static PyObject *
-start_timing(PyObject *self)
-{
-	Py_INCREF(Py_None);
-	BEGINTIMING;
-	return Py_None;
-}
-
-static PyObject *
-finish_timing(PyObject *self)
-{
-	ENDTIMING    
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-static PyObject *
-seconds(PyObject *self)
-{
-	return PyInt_FromLong(TIMINGS);
-}
-
-static PyObject *
-milli(PyObject *self)
-{
-	return PyInt_FromLong(TIMINGMS);
-}
-
-static PyObject *
-micro(PyObject *self)
-{
-	return PyInt_FromLong(TIMINGUS);
-}
-
-
-static PyMethodDef timing_methods[] = {
-	{"start",   (PyCFunction)start_timing, METH_NOARGS},
-	{"finish",  (PyCFunction)finish_timing, METH_NOARGS},
-	{"seconds", (PyCFunction)seconds, METH_NOARGS},
-	{"milli",   (PyCFunction)milli, METH_NOARGS},
-	{"micro",   (PyCFunction)micro, METH_NOARGS},
-	{NULL,      NULL}
-};
-
-
-PyMODINIT_FUNC inittiming(void)
-{
-	(void)Py_InitModule("timing", timing_methods);
-}

Modified: python/branches/p3yk-noslice/Objects/abstract.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/abstract.c	(original)
+++ python/branches/p3yk-noslice/Objects/abstract.c	Wed Jul 11 15:40:56 2007
@@ -565,14 +565,12 @@
 PyObject *
 PyNumber_FloorDivide(PyObject *v, PyObject *w)
 {
-	/* XXX tp_flags test */
 	return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
 }
 
 PyObject *
 PyNumber_TrueDivide(PyObject *v, PyObject *w)
 {
-	/* XXX tp_flags test */
 	return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
 }
 
@@ -649,7 +647,6 @@
 PyObject *
 PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
 {
-	/* XXX tp_flags test */
 	return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
 			  NB_SLOT(nb_floor_divide), "//=");
 }
@@ -657,7 +654,6 @@
 PyObject *
 PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
 {
-	/* XXX tp_flags test */
 	return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
 			  NB_SLOT(nb_true_divide), "/=");
 }
@@ -809,7 +805,7 @@
 		if (result &&
 		    !PyInt_Check(result) && !PyLong_Check(result)) {
 			PyErr_Format(PyExc_TypeError,
-				     "__index__ returned non-int " \
+				     "__index__ returned non-int "
 				     "(type %.200s)",
 				     result->ob_type->tp_name);
 			Py_DECREF(result);
@@ -819,7 +815,7 @@
 	else {
 		PyErr_Format(PyExc_TypeError,
 			     "'%.200s' object cannot be interpreted "
-			     "as an index", item->ob_type->tp_name);
+			     "as an integer", item->ob_type->tp_name);
 	}
 	return result;
 }
@@ -972,9 +968,25 @@
 		PyFloatObject *po = (PyFloatObject *)o;
 		return PyFloat_FromDouble(po->ob_fval);
 	}
-	return PyFloat_FromString(o, NULL);
+	return PyFloat_FromString(o);
 }
 
+
+PyObject *
+PyNumber_ToBase(PyObject *n, int base)
+{
+	PyObject *res;
+	PyObject *index = PyNumber_Index(n);
+
+	if (!index)
+		return NULL;
+	assert(PyLong_Check(index));
+	res = _PyLong_Format(index, base);
+	Py_DECREF(index);
+	return res;
+}
+
+
 /* Operations on sequences */
 
 int
@@ -2101,7 +2113,28 @@
 int
 PyObject_IsInstance(PyObject *inst, PyObject *cls)
 {
-    return recursive_isinstance(inst, cls, Py_GetRecursionLimit());
+	PyObject *t, *v, *tb;
+	PyObject *checker;
+	PyErr_Fetch(&t, &v, &tb);
+	checker = PyObject_GetAttrString(cls, "__instancecheck__");
+	PyErr_Restore(t, v, tb);
+	if (checker != NULL) {
+		PyObject *res;
+		int ok = -1;
+		if (Py_EnterRecursiveCall(" in __instancecheck__")) {
+			Py_DECREF(checker);
+			return ok;
+		}
+		res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
+		Py_LeaveRecursiveCall();
+		Py_DECREF(checker);
+		if (res != NULL) {
+			ok = PyObject_IsTrue(res);
+			Py_DECREF(res);
+		}
+		return ok;
+	}
+	return recursive_isinstance(inst, cls, Py_GetRecursionLimit());
 }
 
 static  int
@@ -2151,7 +2184,26 @@
 int
 PyObject_IsSubclass(PyObject *derived, PyObject *cls)
 {
-    return recursive_issubclass(derived, cls, Py_GetRecursionLimit());
+	PyObject *t, *v, *tb;
+	PyObject *checker;
+	PyErr_Fetch(&t, &v, &tb);
+	checker = PyObject_GetAttrString(cls, "__subclasscheck__");
+	PyErr_Restore(t, v, tb);
+	if (checker != NULL) {
+		PyObject *res;
+		int ok = -1;
+		if (Py_EnterRecursiveCall(" in __subclasscheck__"))
+			return ok;
+		res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
+		Py_LeaveRecursiveCall();
+		Py_DECREF(checker);
+		if (res != NULL) {
+			ok = PyObject_IsTrue(res);
+			Py_DECREF(res);
+		}
+		return ok;
+	}
+	return recursive_issubclass(derived, cls, Py_GetRecursionLimit());
 }
 
 

Modified: python/branches/p3yk-noslice/Objects/bufferobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/bufferobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/bufferobject.c	Wed Jul 11 15:40:56 2007
@@ -19,7 +19,7 @@
     READ_BUFFER,
     WRITE_BUFFER,
     CHAR_BUFFER,
-    ANY_BUFFER,
+    ANY_BUFFER
 };
 
 static int

Modified: python/branches/p3yk-noslice/Objects/bytesobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/bytesobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/bytesobject.c	Wed Jul 11 15:40:56 2007
@@ -6,6 +6,66 @@
 #include "Python.h"
 #include "structmember.h"
 
+/* The nullbytes are used by the stringlib during partition.
+ * If partition is removed from bytes, nullbytes and its helper
+ * Init/Fini should also be removed.
+ */
+static PyBytesObject *nullbytes = NULL;
+
+void
+PyBytes_Fini(void)
+{
+    Py_CLEAR(nullbytes);
+}
+
+int
+PyBytes_Init(void)
+{
+    nullbytes = PyObject_New(PyBytesObject, &PyBytes_Type);
+    if (nullbytes == NULL)
+        return 0;
+    nullbytes->ob_bytes = NULL;
+    nullbytes->ob_size = nullbytes->ob_alloc = 0;
+    return 1;
+}
+
+/* end nullbytes support */
+
+/* Helpers */
+
+static int
+_getbytevalue(PyObject* arg, int *value)
+{
+    PyObject *intarg = PyNumber_Int(arg);
+    if (! intarg)
+        return 0;
+    *value = PyInt_AsLong(intarg);
+    Py_DECREF(intarg);
+    if (*value < 0 || *value >= 256) {
+        PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
+        return 0;
+    }
+    return 1;
+}
+
+Py_ssize_t
+_getbuffer(PyObject *obj, void **ptr)
+{
+    PyBufferProcs *buffer = obj->ob_type->tp_as_buffer;
+
+    if (buffer == NULL ||
+        PyUnicode_Check(obj) ||
+        buffer->bf_getreadbuffer == NULL ||
+        buffer->bf_getsegcount == NULL ||
+        buffer->bf_getsegcount(obj, NULL) != 1)
+    {
+        *ptr = NULL;
+        return -1;
+    }
+
+    return buffer->bf_getreadbuffer(obj, 0, ptr);
+}
+
 /* Direct API functions */
 
 PyObject *
@@ -38,7 +98,7 @@
             memcpy(new->ob_bytes, bytes, size);
     }
     new->ob_size = new->ob_alloc = size;
-    
+
     return (PyObject *)new;
 }
 
@@ -101,56 +161,63 @@
     return 0;
 }
 
-/* Functions stuffed into the type object */
-
-static Py_ssize_t
-bytes_length(PyBytesObject *self)
-{
-    return self->ob_size;
-}
-
-static PyObject *
-bytes_concat(PyBytesObject *self, PyObject *other)
+PyObject *
+PyBytes_Concat(PyObject *a, PyObject *b)
 {
+    Py_ssize_t asize, bsize, size;
+    void *aptr, *bptr;
     PyBytesObject *result;
-    Py_ssize_t mysize;
-    Py_ssize_t size;
 
-    if (!PyBytes_Check(other)) {
-        PyErr_Format(PyExc_TypeError,
-                     "can't concat bytes to %.100s", other->ob_type->tp_name);
+    asize = _getbuffer(a, &aptr);
+    bsize = _getbuffer(b, &bptr);
+    if (asize < 0 || bsize < 0) {
+        PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
+                     a->ob_type->tp_name, b->ob_type->tp_name);
         return NULL;
     }
-    
-    mysize = self->ob_size;
-    size = mysize + ((PyBytesObject *)other)->ob_size;
+
+    size = asize + bsize;
     if (size < 0)
         return PyErr_NoMemory();
+
     result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, size);
     if (result != NULL) {
-        memcpy(result->ob_bytes, self->ob_bytes, self->ob_size);
-        memcpy(result->ob_bytes + self->ob_size,
-               ((PyBytesObject *)other)->ob_bytes,
-               ((PyBytesObject *)other)->ob_size);
+        memcpy(result->ob_bytes, aptr, asize);
+        memcpy(result->ob_bytes + asize, bptr, bsize);
     }
     return (PyObject *)result;
 }
 
+/* Functions stuffed into the type object */
+
+static Py_ssize_t
+bytes_length(PyBytesObject *self)
+{
+    return self->ob_size;
+}
+
+static PyObject *
+bytes_concat(PyBytesObject *self, PyObject *other)
+{
+    return PyBytes_Concat((PyObject *)self, other);
+}
+
 static PyObject *
 bytes_iconcat(PyBytesObject *self, PyObject *other)
 {
-    Py_ssize_t mysize;
+    void *optr;
     Py_ssize_t osize;
+    Py_ssize_t mysize;
     Py_ssize_t size;
 
-    if (!PyBytes_Check(other)) {
+    osize = _getbuffer(other, &optr);
+    if (osize < 0) {
         PyErr_Format(PyExc_TypeError,
                      "can't concat bytes to %.100s", other->ob_type->tp_name);
         return NULL;
     }
 
     mysize = self->ob_size;
-    osize = ((PyBytesObject *)other)->ob_size;
     size = mysize + osize;
     if (size < 0)
         return PyErr_NoMemory();
@@ -158,7 +225,7 @@
         self->ob_size = size;
     else if (PyBytes_Resize((PyObject *)self, size) < 0)
         return NULL;
-    memcpy(self->ob_bytes + mysize, ((PyBytesObject *)other)->ob_bytes, osize);
+    memcpy(self->ob_bytes + mysize, optr, osize);
     Py_INCREF(self);
     return (PyObject *)self;
 }
@@ -205,7 +272,7 @@
         self->ob_size = size;
     else if (PyBytes_Resize((PyObject *)self, size) < 0)
         return NULL;
-    
+
     if (mysize == 1)
         memset(self->ob_bytes, self->ob_bytes[0], size);
     else {
@@ -224,7 +291,7 @@
     Py_ssize_t i;
 
     if (other->ob_size == 1) {
-        return memchr(self->ob_bytes, other->ob_bytes[0], 
+        return memchr(self->ob_bytes, other->ob_bytes[0],
                       self->ob_size) != NULL;
     }
     if (other->ob_size == 0)
@@ -293,7 +360,7 @@
                                  &start, &stop, &step, &slicelength) < 0) {
             return NULL;
         }
-        
+
         if (slicelength <= 0)
             return PyBytes_FromStringAndSize("", 0);
         else if (step == 1) {
@@ -304,10 +371,10 @@
             char *source_buf = PyBytes_AS_STRING(self);
             char *result_buf = (char *)PyMem_Malloc(slicelength);
             PyObject *result;
-            
+
             if (result_buf == NULL)
                 return PyErr_NoMemory();
-            
+
             for (cur = start, i = 0; i < slicelength;
                  cur += step, i++) {
                      result_buf[i] = source_buf[cur];
@@ -322,20 +389,15 @@
         return NULL;
     }
 }
- 
+
 static int
 bytes_setslice(PyBytesObject *self, Py_ssize_t lo, Py_ssize_t hi,
                PyObject *values)
 {
-    int avail;
-    int needed;
-    char *bytes;
+    Py_ssize_t avail, needed;
+    void *bytes;
 
-    if (values == NULL) {
-        bytes = NULL;
-        needed = 0;
-    }
-    else if (values == (PyObject *)self || !PyBytes_Check(values)) {
+    if (values == (PyObject *)self) {
         /* Make a copy an call this function recursively */
         int err;
         values = PyBytes_FromObject(values);
@@ -345,10 +407,19 @@
         Py_DECREF(values);
         return err;
     }
+    if (values == NULL) {
+        /* del b[lo:hi] */
+        bytes = NULL;
+        needed = 0;
+    }
     else {
-        assert(PyBytes_Check(values));
-        bytes = ((PyBytesObject *)values)->ob_bytes;
-        needed = ((PyBytesObject *)values)->ob_size;
+        needed = _getbuffer(values, &bytes);
+        if (needed < 0) {
+            PyErr_Format(PyExc_TypeError,
+                         "can't set bytes slice from %.100s",
+                         values->ob_type->tp_name);
+            return -1;
+        }
     }
 
     if (lo < 0)
@@ -428,7 +499,7 @@
 {
     Py_ssize_t start, stop, step, slicelen, needed;
     char *bytes;
-    
+
     if (PyIndex_Check(item)) {
         Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 
@@ -442,7 +513,7 @@
             PyErr_SetString(PyExc_IndexError, "bytes index out of range");
             return -1;
         }
-        
+
         if (values == NULL) {
             /* Fall through to slice assignment */
             start = i;
@@ -534,7 +605,7 @@
         if (needed == 0) {
             /* Delete slice */
             Py_ssize_t cur, i;
-            
+
             if (step < 0) {
                 stop = start + 1;
                 start = stop + step * (slicelen - 1) - 1;
@@ -546,7 +617,7 @@
 
                 if (cur + step >= PyBytes_GET_SIZE(self))
                     lim = PyBytes_GET_SIZE(self) - cur - 1;
-                
+
                 memmove(self->ob_bytes + cur - i,
                         self->ob_bytes + cur + 1, lim);
             }
@@ -566,7 +637,7 @@
         else {
             /* Assign slice */
             Py_ssize_t cur, i;
-            
+
             if (needed != slicelen) {
                 PyErr_Format(PyExc_ValueError,
                              "attempt to assign bytes of size %zd "
@@ -733,65 +804,63 @@
     return -1;
 }
 
+/* Mostly copied from string_repr, but without the
+   "smart quote" functionality. */
 static PyObject *
 bytes_repr(PyBytesObject *self)
 {
-    PyObject *list;
-    PyObject *str;
-    PyObject *result;
-    int err;
-    int i;
-
-    if (self->ob_size == 0)
-        return PyString_FromString("bytes()");
-
-    list = PyList_New(0);
-    if (list == NULL)
+    size_t newsize = 3 + 4 * self->ob_size;
+    PyObject *v;
+    if (newsize > PY_SSIZE_T_MAX || newsize / 4 != self->ob_size) {
+        PyErr_SetString(PyExc_OverflowError,
+            "bytes object is too large to make repr");
         return NULL;
-
-    str = PyString_FromString("bytes([");
-    if (str == NULL)
-        goto error;
-
-    err = PyList_Append(list, str);
-    Py_DECREF(str);
-    if (err < 0)
-        goto error;
-
-    for (i = 0; i < self->ob_size; i++) {
-        char buffer[20];
-        sprintf(buffer, ", 0x%02x", (unsigned char) (self->ob_bytes[i]));
-        str = PyString_FromString((i == 0) ? buffer+2 : buffer);
-        if (str == NULL)
-            goto error;
-        err = PyList_Append(list, str);
-        Py_DECREF(str);
-        if (err < 0)
-            goto error;
     }
-
-    str = PyString_FromString("])");
-    if (str == NULL)
-        goto error;
-
-    err = PyList_Append(list, str);
-    Py_DECREF(str);
-    if (err < 0)
-        goto error;
-    
-    str = PyString_FromString("");
-    if (str == NULL)
-        goto error;
-
-    result = _PyString_Join(str, list);
-    Py_DECREF(str);
-    Py_DECREF(list);
-    return result;
-
- error:
-    /* Error handling when list != NULL  */
-    Py_DECREF(list);
-    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 = '\'';
+
+        p = PyString_AS_STRING(v);
+        *p++ = 'b';
+        *p++ = quote;
+        for (i = 0; i < self->ob_size; i++) {
+            /* There's at least enough room for a hex escape
+               and a closing quote. */
+            assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
+            c = self->ob_bytes[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 == 0)
+                *p++ = '\\', *p++ = '0';
+            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 *
@@ -801,33 +870,45 @@
 }
 
 static PyObject *
-bytes_richcompare(PyBytesObject *self, PyBytesObject *other, int op)
+bytes_richcompare(PyObject *self, PyObject *other, int op)
 {
+    Py_ssize_t self_size, other_size;
+    void *self_bytes, *other_bytes;
     PyObject *res;
-    int minsize;
+    Py_ssize_t minsize;
     int cmp;
 
-    if (!PyBytes_Check(self) || !PyBytes_Check(other)) {
+    /* Bytes can be compared to anything that supports the (binary) buffer
+       API.  Except Unicode. */
+
+    self_size = _getbuffer(self, &self_bytes);
+    if (self_size < 0) {
+        Py_INCREF(Py_NotImplemented);
+        return Py_NotImplemented;
+    }
+
+    other_size = _getbuffer(other, &other_bytes);
+    if (other_size < 0) {
         Py_INCREF(Py_NotImplemented);
         return Py_NotImplemented;
     }
 
-    if (self->ob_size != other->ob_size && (op == Py_EQ || op == Py_NE)) {
+    if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
         /* Shortcut: if the lengths differ, the objects differ */
         cmp = (op == Py_NE);
     }
     else {
-        minsize = self->ob_size;
-        if (other->ob_size < minsize)
-            minsize = other->ob_size;
+        minsize = self_size;
+        if (other_size < minsize)
+            minsize = other_size;
 
-        cmp = memcmp(self->ob_bytes, other->ob_bytes, minsize);
+        cmp = memcmp(self_bytes, other_bytes, minsize);
         /* In ISO C, memcmp() guarantees to use unsigned bytes! */
 
         if (cmp == 0) {
-            if (self->ob_size < other->ob_size)
+            if (self_size < other_size)
                 cmp = -1;
-            else if (self->ob_size > other->ob_size)
+            else if (self_size > other_size)
                 cmp = 1;
         }
 
@@ -860,7 +941,7 @@
 {
     if (index != 0) {
         PyErr_SetString(PyExc_SystemError,
-                        "accessing non-existent string segment");
+                        "accessing non-existent bytes segment");
         return -1;
     }
     *ptr = (void *)self->ob_bytes;
@@ -875,114 +956,1773 @@
     return 1;
 }
 
-PyDoc_STRVAR(decode_doc,
-"B.decode([encoding[,errors]]) -> unicode obect.\n\
+
+
+/* -------------------------------------------------------------------- */
+/* Methods */
+
+#define STRINGLIB_CHAR char
+#define STRINGLIB_CMP memcmp
+#define STRINGLIB_LEN PyBytes_GET_SIZE
+#define STRINGLIB_NEW PyBytes_FromStringAndSize
+#define STRINGLIB_EMPTY nullbytes
+
+#include "stringlib/fastsearch.h"
+#include "stringlib/count.h"
+#include "stringlib/find.h"
+#include "stringlib/partition.h"
+
+
+/* The following Py_LOCAL_INLINE and Py_LOCAL functions
+were copied from the old char* style string object. */
+
+Py_LOCAL_INLINE(void)
+_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)
+bytes_find_internal(PyBytesObject *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;
+
+    if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", &subobj,
+        _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+        return -2;
+    if (PyBytes_Check(subobj)) {
+        sub = PyBytes_AS_STRING(subobj);
+        sub_len = PyBytes_GET_SIZE(subobj);
+    }
+    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(
+            PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
+            sub, sub_len, start, end);
+    else
+        return stringlib_rfind_slice(
+            PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
+            sub, sub_len, start, end);
+}
+
+
+PyDoc_STRVAR(find__doc__,
+"B.find(sub [,start [,end]]) -> int\n\
 \n\
-Decodes B 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.");
+Return the lowest index in B where subsection 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 *
-bytes_decode(PyObject *self, PyObject *args)
-{ 
-    const char *encoding = NULL;
-    const char *errors = NULL;
+bytes_find(PyBytesObject *self, PyObject *args)
+{
+    Py_ssize_t result = bytes_find_internal(self, args, +1);
+    if (result == -2)
+        return NULL;
+    return PyInt_FromSsize_t(result);
+}
 
-    if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
+PyDoc_STRVAR(count__doc__,
+"B.count(sub[, start[, end]]) -> int\n\
+\n\
+Return the number of non-overlapping occurrences of subsection sub in\n\
+bytes B[start:end].  Optional arguments start and end are interpreted\n\
+as in slice notation.");
+
+static PyObject *
+bytes_count(PyBytesObject *self, PyObject *args)
+{
+    PyObject *sub_obj;
+    const char *str = PyBytes_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 (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
-    return PyCodec_Decode(self, encoding, errors);
+
+    if (PyBytes_Check(sub_obj)) {
+        sub = PyBytes_AS_STRING(sub_obj);
+        sub_len = PyBytes_GET_SIZE(sub_obj);
+    }
+    else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
+        return NULL;
+
+    _adjust_indices(&start, &end, PyString_GET_SIZE(self));
+
+    return PyInt_FromSsize_t(
+        stringlib_count(str + start, end - start, sub, sub_len)
+        );
 }
 
-PyDoc_STRVAR(alloc_doc,
-"B.__alloc__() -> int\n\
+
+PyDoc_STRVAR(index__doc__,
+"B.index(sub [,start [,end]]) -> int\n\
 \n\
-Returns the number of bytes actually allocated.");
+Like B.find() but raise ValueError when the subsection is not found.");
 
 static PyObject *
-bytes_alloc(PyBytesObject *self)
+bytes_index(PyBytesObject *self, PyObject *args)
 {
-    return PyInt_FromSsize_t(self->ob_alloc);
+    Py_ssize_t result = bytes_find_internal(self, args, +1);
+    if (result == -2)
+        return NULL;
+    if (result == -1) {
+        PyErr_SetString(PyExc_ValueError,
+                        "subsection not found");
+        return NULL;
+    }
+    return PyInt_FromSsize_t(result);
 }
 
-PyDoc_STRVAR(join_doc,
-"bytes.join(iterable_of_bytes) -> bytes\n\
+
+PyDoc_STRVAR(rfind__doc__,
+"B.rfind(sub [,start [,end]]) -> int\n\
 \n\
-Concatenates any number of bytes objects.  Example:\n\
-bytes.join([bytes('ab'), bytes('pq'), bytes('rs')]) -> bytes('abpqrs').");
+Return the highest index in B where subsection 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 *
-bytes_join(PyObject *cls, PyObject *it)
+bytes_rfind(PyBytesObject *self, PyObject *args)
 {
-    PyObject *seq;
-    Py_ssize_t i;
-    Py_ssize_t n;
-    PyObject **items;
-    Py_ssize_t totalsize = 0;
-    PyObject *result;
-    char *dest;
+    Py_ssize_t result = bytes_find_internal(self, args, -1);
+    if (result == -2)
+        return NULL;
+    return PyInt_FromSsize_t(result);
+}
 
-    seq = PySequence_Fast(it, "can only join an iterable");
-    if (seq == NULL)
-	return NULL;
-    n = PySequence_Fast_GET_SIZE(seq);
-    items = PySequence_Fast_ITEMS(seq);
 
-    /* Compute the total size, and check that they are all bytes */
-    for (i = 0; i < n; i++) {
-	PyObject *obj = items[i];
-	if (!PyBytes_Check(obj)) {
-	    PyErr_Format(PyExc_TypeError,
-			 "can only join an iterable of bytes "
-			 "(item %ld has type '%.100s')",
-                         /* XXX %ld isn't right on Win64 */
-			 (long)i, obj->ob_type->tp_name);
-	    goto error;
-	}
-	totalsize += PyBytes_GET_SIZE(obj);
-	if (totalsize < 0) {
-	    PyErr_NoMemory();
-	    goto error;
-	}
+PyDoc_STRVAR(rindex__doc__,
+"B.rindex(sub [,start [,end]]) -> int\n\
+\n\
+Like B.rfind() but raise ValueError when the subsection is not found.");
+
+static PyObject *
+bytes_rindex(PyBytesObject *self, PyObject *args)
+{
+    Py_ssize_t result = bytes_find_internal(self, args, -1);
+    if (result == -2)
+        return NULL;
+    if (result == -1) {
+        PyErr_SetString(PyExc_ValueError,
+                        "subsection not found");
+        return NULL;
     }
+    return PyInt_FromSsize_t(result);
+}
 
-    /* Allocate the result, and copy the bytes */
-    result = PyBytes_FromStringAndSize(NULL, totalsize);
-    if (result == NULL)
-	goto error;
-    dest = PyBytes_AS_STRING(result);
-    for (i = 0; i < n; i++) {
-	PyObject *obj = items[i];
-	Py_ssize_t size = PyBytes_GET_SIZE(obj);
-	memcpy(dest, PyBytes_AS_STRING(obj), size);
-	dest += size;
+
+/* 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)
+_bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start,
+                 Py_ssize_t end, int direction)
+{
+    Py_ssize_t len = PyBytes_GET_SIZE(self);
+    Py_ssize_t slen;
+    const char* sub;
+    const char* str;
+
+    if (PyBytes_Check(substr)) {
+        sub = PyBytes_AS_STRING(substr);
+        slen = PyBytes_GET_SIZE(substr);
+    }
+    else if (PyObject_AsCharBuffer(substr, &sub, &slen))
+        return -1;
+    str = PyBytes_AS_STRING(self);
+
+    _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;
+}
 
-    /* Done */
-    Py_DECREF(seq);
-    return result;
 
-    /* Error handling */
-  error:
-    Py_DECREF(seq);
-    return NULL;
+PyDoc_STRVAR(startswith__doc__,
+"B.startswith(prefix[, start[, end]]) -> bool\n\
+\n\
+Return True if B starts with the specified prefix, False otherwise.\n\
+With optional start, test B beginning at that position.\n\
+With optional end, stop comparing B at that position.\n\
+prefix can also be a tuple of strings to try.");
+
+static PyObject *
+bytes_startswith(PyBytesObject *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 = _bytes_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 = _bytes_tailmatch(self, subobj, start, end, -1);
+    if (result == -1)
+        return NULL;
+    else
+        return PyBool_FromLong(result);
+}
+
+PyDoc_STRVAR(endswith__doc__,
+"B.endswith(suffix[, start[, end]]) -> bool\n\
+\n\
+Return True if B ends with the specified suffix, False otherwise.\n\
+With optional start, test B beginning at that position.\n\
+With optional end, stop comparing B at that position.\n\
+suffix can also be a tuple of strings to try.");
+
+static PyObject *
+bytes_endswith(PyBytesObject *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 = _bytes_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 = _bytes_tailmatch(self, subobj, start, end, +1);
+    if (result == -1)
+        return NULL;
+    else
+        return PyBool_FromLong(result);
+}
+
+
+
+PyDoc_STRVAR(translate__doc__,
+"B.translate(table [,deletechars]) -> bytes\n\
+\n\
+Return a copy of the bytes B, 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 bytes of length 256.");
+
+static PyObject *
+bytes_translate(PyBytesObject *self, PyObject *args)
+{
+    register char *input, *output;
+    register const char *table;
+    register Py_ssize_t i, c, changed = 0;
+    PyObject *input_obj = (PyObject*)self;
+    const char *table1, *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 (PyBytes_Check(tableobj)) {
+        table1 = PyBytes_AS_STRING(tableobj);
+        tablen = PyBytes_GET_SIZE(tableobj);
+    }
+    else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen))
+        return NULL;
+
+    if (tablen != 256) {
+        PyErr_SetString(PyExc_ValueError,
+                        "translation table must be 256 characters long");
+        return NULL;
+    }
+
+    if (delobj != NULL) {
+        if (PyBytes_Check(delobj)) {
+            del_table = PyBytes_AS_STRING(delobj);
+            dellen = PyBytes_GET_SIZE(delobj);
+        }
+        else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
+            return NULL;
+    }
+    else {
+        del_table = NULL;
+        dellen = 0;
+    }
+
+    table = table1;
+    inlen = PyBytes_GET_SIZE(input_obj);
+    result = PyBytes_FromStringAndSize((char *)NULL, inlen);
+    if (result == NULL)
+        return NULL;
+    output_start = output = PyBytes_AsString(result);
+    input = PyBytes_AS_STRING(input_obj);
+
+    if (dellen == 0) {
+        /* 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 || !PyBytes_CheckExact(input_obj))
+            return result;
+        Py_DECREF(result);
+        Py_INCREF(input_obj);
+        return input_obj;
+    }
+
+    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 && PyBytes_CheckExact(input_obj)) {
+        Py_DECREF(result);
+        Py_INCREF(input_obj);
+        return input_obj;
+    }
+    /* Fix the size of the resulting string */
+    if (inlen > 0)
+        PyBytes_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))
+
+/* 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) )
+
+
+/* Bytes ops must return a string.  */
+/* If the object is subclass of bytes, create a copy */
+Py_LOCAL(PyBytesObject *)
+return_self(PyBytesObject *self)
+{
+    if (PyBytes_CheckExact(self)) {
+        Py_INCREF(self);
+        return (PyBytesObject *)self;
+    }
+    return (PyBytesObject *)PyBytes_FromStringAndSize(
+            PyBytes_AS_STRING(self),
+            PyBytes_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(PyBytesObject *)
+replace_interleave(PyBytesObject *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;
+    PyBytesObject *result;
+
+    self_len = PyBytes_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 = (PyBytesObject *)
+                     PyBytes_FromStringAndSize(NULL, result_len)) )
+        return NULL;
+
+    self_s = PyBytes_AS_STRING(self);
+    result_s = PyBytes_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(PyBytesObject *)
+replace_delete_single_character(PyBytesObject *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;
+    PyBytesObject *result;
+
+    self_len = PyBytes_GET_SIZE(self);
+    self_s = PyBytes_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 = (PyBytesObject *)
+                    PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
+        return NULL;
+    result_s = PyBytes_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(PyBytesObject *)
+replace_delete_substring(PyBytesObject *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;
+    PyBytesObject *result;
+
+    self_len = PyBytes_GET_SIZE(self);
+    self_s = PyBytes_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 = (PyBytesObject *)
+        PyBytes_FromStringAndSize(NULL, result_len)) == NULL )
+            return NULL;
+
+    result_s = PyBytes_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(PyBytesObject *)
+replace_single_character_in_place(PyBytesObject *self,
+                                  char from_c, char to_c,
+                                  Py_ssize_t maxcount)
+{
+        char *self_s, *result_s, *start, *end, *next;
+        Py_ssize_t self_len;
+        PyBytesObject *result;
+
+        /* The result string will be the same size */
+        self_s = PyBytes_AS_STRING(self);
+        self_len = PyBytes_GET_SIZE(self);
+
+        next = findchar(self_s, self_len, from_c);
+
+        if (next == NULL) {
+                /* No matches; return the original bytes */
+                return return_self(self);
+        }
+
+        /* Need to make a new bytes */
+        result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len);
+        if (result == NULL)
+                return NULL;
+        result_s = PyBytes_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(PyBytesObject *)
+replace_substring_in_place(PyBytesObject *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;
+    PyBytesObject *result;
+
+    /* The result bytes will be the same size */
+
+    self_s = PyBytes_AS_STRING(self);
+    self_len = PyBytes_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 bytes */
+        return return_self(self);
+    }
+
+    /* Need to make a new bytes */
+    result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len);
+    if (result == NULL)
+        return NULL;
+    result_s = PyBytes_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(PyBytesObject *)
+replace_single_character(PyBytesObject *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;
+    PyBytesObject *result;
+
+    self_s = PyBytes_AS_STRING(self);
+    self_len = PyBytes_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 bytes is too long");
+        return NULL;
+    }
+    result_len = self_len + product;
+    if (result_len < 0) {
+            PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
+            return NULL;
+    }
+
+    if ( (result = (PyBytesObject *)
+          PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
+            return NULL;
+    result_s = PyBytes_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 bytes */
+    Py_MEMCPY(result_s, start, end-start);
+
+    return result;
+}
+
+/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
+Py_LOCAL(PyBytesObject *)
+replace_substring(PyBytesObject *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;
+    PyBytesObject *result;
+
+    self_s = PyBytes_AS_STRING(self);
+    self_len = PyBytes_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 bytes is too long");
+        return NULL;
+    }
+    result_len = self_len + product;
+    if (result_len < 0) {
+        PyErr_SetString(PyExc_OverflowError, "replace bytes is too long");
+        return NULL;
+    }
+
+    if ( (result = (PyBytesObject *)
+          PyBytes_FromStringAndSize(NULL, result_len)) == NULL)
+        return NULL;
+    result_s = PyBytes_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 bytes */
+    Py_MEMCPY(result_s, start, end-start);
+
+    return result;
+}
+
+
+Py_LOCAL(PyBytesObject *)
+replace(PyBytesObject *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 || PyBytes_GET_SIZE(self) == 0) {
+        /* nothing to do; return the original bytes */
+        return return_self(self);
+    }
+
+    if (maxcount == 0 ||
+        (from_len == 0 && to_len == 0)) {
+        /* nothing to do; return the original bytes */
+        return return_self(self);
+    }
+
+    /* Handle zero-length special cases */
+
+    if (from_len == 0) {
+        /* insert the 'to' bytes 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 bytes to generate a non-empty bytes */
+    /* Special case so the remaining code always gets a non-empty bytes */
+    if (PyBytes_GET_SIZE(self) == 0) {
+        return return_self(self);
+    }
+
+    if (to_len == 0) {
+        /* delete all occurances of 'from' bytes */
+        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 bytes 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__,
+"B.replace (old, new[, count]) -> bytes\n\
+\n\
+Return a copy of bytes B with all occurrences of subsection\n\
+old replaced by new.  If the optional argument count is\n\
+given, only the first count occurrences are replaced.");
+
+static PyObject *
+bytes_replace(PyBytesObject *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 (PyBytes_Check(from)) {
+        from_s = PyBytes_AS_STRING(from);
+        from_len = PyBytes_GET_SIZE(from);
+    }
+    else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
+        return NULL;
+
+    if (PyBytes_Check(to)) {
+        to_s = PyBytes_AS_STRING(to);
+        to_len = PyBytes_GET_SIZE(to);
+    }
+    else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
+        return NULL;
+
+    return (PyObject *)replace((PyBytesObject *) self,
+                               from_s, from_len,
+                               to_s, to_len, count);
+}
+
+
+/* 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 = PyBytes_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 = PyBytes_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) ((PyListObject *)list)->ob_size = count
+
+
+Py_LOCAL_INLINE(PyObject *)
+split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
+{
+    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 <= len) {
+        SPLIT_ADD(s, i, len);
+    }
+    FIX_PREALLOC_SIZE(list);
+    return list;
+
+  onError:
+    Py_DECREF(list);
+    return NULL;
+}
+
+PyDoc_STRVAR(split__doc__,
+"B.split(sep [,maxsplit]) -> list of bytes\n\
+\n\
+Return a list of the bytes in the string B, using sep as the\n\
+delimiter.  If maxsplit is given, at most maxsplit\n\
+splits are done.");
+
+static PyObject *
+bytes_split(PyBytesObject *self, PyObject *args)
+{
+    Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j;
+    Py_ssize_t maxsplit = -1, count=0;
+    const char *s = PyBytes_AS_STRING(self), *sub;
+    PyObject *list, *str, *subobj;
+#ifdef USE_FAST
+    Py_ssize_t pos;
+#endif
+
+    if (!PyArg_ParseTuple(args, "O|n:split", &subobj, &maxsplit))
+        return NULL;
+    if (maxsplit < 0)
+        maxsplit = PY_SSIZE_T_MAX;
+    if (PyBytes_Check(subobj)) {
+        sub = PyBytes_AS_STRING(subobj);
+        n = PyBytes_GET_SIZE(subobj);
+    }
+    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(s, 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__,
+"B.partition(sep) -> (head, sep, tail)\n\
+\n\
+Searches for the separator sep in B, and returns the part before it,\n\
+the separator itself, and the part after it.  If the separator is not\n\
+found, returns B and two empty bytes.");
+
+static PyObject *
+bytes_partition(PyBytesObject *self, PyObject *sep_obj)
+{
+    PyObject *bytesep, *result;
+
+    bytesep = PyBytes_FromObject(sep_obj);
+    if (! bytesep)
+        return NULL;
+
+    result = stringlib_partition(
+            (PyObject*) self,
+            PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
+            bytesep,
+            PyBytes_AS_STRING(bytesep), PyBytes_GET_SIZE(bytesep)
+            );
+
+    Py_DECREF(bytesep);
+    return result;
+}
+
+PyDoc_STRVAR(rpartition__doc__,
+"B.rpartition(sep) -> (tail, sep, head)\n\
+\n\
+Searches for the separator sep in B, starting at the end of B, 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 bytes and B.");
+
+static PyObject *
+bytes_rpartition(PyBytesObject *self, PyObject *sep_obj)
+{
+    PyObject *bytesep, *result;
+
+    bytesep = PyBytes_FromObject(sep_obj);
+    if (! bytesep)
+        return NULL;
+
+    result = stringlib_rpartition(
+            (PyObject*) self,
+            PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self),
+            bytesep,
+            PyBytes_AS_STRING(bytesep), PyBytes_GET_SIZE(bytesep)
+            );
+
+    Py_DECREF(bytesep);
+    return result;
+}
+
+Py_LOCAL_INLINE(PyObject *)
+rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
+{
+    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 (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__,
+"B.rsplit(sep [,maxsplit]) -> list of bytes\n\
+\n\
+Return a list of the sections in the byte B, using sep as the\n\
+delimiter, starting at the end of the bytes and working\n\
+to the front.  If maxsplit is given, at most maxsplit splits are\n\
+done.");
+
+static PyObject *
+bytes_rsplit(PyBytesObject *self, PyObject *args)
+{
+    Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j;
+    Py_ssize_t maxsplit = -1, count=0;
+    const char *s = PyBytes_AS_STRING(self), *sub;
+    PyObject *list, *str, *subobj;
+
+    if (!PyArg_ParseTuple(args, "O|n:rsplit", &subobj, &maxsplit))
+        return NULL;
+    if (maxsplit < 0)
+        maxsplit = PY_SSIZE_T_MAX;
+    if (PyBytes_Check(subobj)) {
+        sub = PyBytes_AS_STRING(subobj);
+        n = PyBytes_GET_SIZE(subobj);
+    }
+    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(s, len, sub[0], maxsplit);
+
+    list = PyList_New(PREALLOC_SIZE(maxsplit));
+    if (list == NULL)
+        return NULL;
+
+    j = len;
+    i = j - n;
+
+    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(extend__doc__,
+"B.extend(iterable int) -> None\n\
+\n\
+Append all the elements from the iterator or sequence to the\n\
+end of the bytes.");
+static PyObject *
+bytes_extend(PyBytesObject *self, PyObject *arg)
+{
+    if (bytes_setslice(self, self->ob_size, self->ob_size, arg) == -1)
+        return NULL;
+    Py_RETURN_NONE;
+}
+
+
+PyDoc_STRVAR(reverse__doc__,
+"B.reverse() -> None\n\
+\n\
+Reverse the order of the values in bytes in place.");
+static PyObject *
+bytes_reverse(PyBytesObject *self, PyObject *unused)
+{
+    char swap, *head, *tail;
+    Py_ssize_t i, j, n = self->ob_size;
+
+    j = n / 2;
+    head = self->ob_bytes;
+    tail = head + n - 1;
+    for (i = 0; i < j; i++) {
+        swap = *head;
+        *head++ = *tail;
+        *tail-- = swap;
+    }
+
+    Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(insert__doc__,
+"B.insert(index, int) -> None\n\
+\n\
+Insert a single item into the bytes before the given index.");
+static PyObject *
+bytes_insert(PyBytesObject *self, PyObject *args)
+{
+    int value;
+    Py_ssize_t where, n = self->ob_size;
+
+    if (!PyArg_ParseTuple(args, "ni:insert", &where, &value))
+        return NULL;
+
+    if (n == PY_SSIZE_T_MAX) {
+        PyErr_SetString(PyExc_OverflowError,
+                        "cannot add more objects to bytes");
+        return NULL;
+    }
+    if (value < 0 || value >= 256) {
+        PyErr_SetString(PyExc_ValueError,
+                        "byte must be in range(0, 256)");
+        return NULL;
+    }
+    if (PyBytes_Resize((PyObject *)self, n + 1) < 0)
+        return NULL;
+
+    if (where < 0) {
+        where += n;
+        if (where < 0)
+            where = 0;
+    }
+    if (where > n)
+        where = n;
+    memmove(self->ob_bytes + where + 1, self->ob_bytes + where, n - where);
+    self->ob_bytes[where] = value;
+
+    Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(append__doc__,
+"B.append(int) -> None\n\
+\n\
+Append a single item to the end of the bytes.");
+static PyObject *
+bytes_append(PyBytesObject *self, PyObject *arg)
+{
+    int value;
+    Py_ssize_t n = self->ob_size;
+
+    if (! _getbytevalue(arg, &value))
+        return NULL;
+    if (n == PY_SSIZE_T_MAX) {
+        PyErr_SetString(PyExc_OverflowError,
+                        "cannot add more objects to bytes");
+        return NULL;
+    }
+    if (PyBytes_Resize((PyObject *)self, n + 1) < 0)
+        return NULL;
+
+    self->ob_bytes[n] = value;
+
+    Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(pop__doc__,
+"B.pop([index]) -> int\n\
+\n\
+Remove and return a single item from the bytes. If no index\n\
+argument is give, will pop the last value.");
+static PyObject *
+bytes_pop(PyBytesObject *self, PyObject *args)
+{
+    int value;
+    Py_ssize_t where = -1, n = self->ob_size;
+
+    if (!PyArg_ParseTuple(args, "|n:pop", &where))
+        return NULL;
+
+    if (n == 0) {
+        PyErr_SetString(PyExc_OverflowError,
+                        "cannot pop an empty bytes");
+        return NULL;
+    }
+    if (where < 0)
+        where += self->ob_size;
+    if (where < 0 || where >= self->ob_size) {
+        PyErr_SetString(PyExc_IndexError, "pop index out of range");
+        return NULL;
+    }
+
+    value = self->ob_bytes[where];
+    memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
+    if (PyBytes_Resize((PyObject *)self, n - 1) < 0)
+        return NULL;
+
+    return PyInt_FromLong(value);
+}
+
+PyDoc_STRVAR(remove__doc__,
+"B.remove(int) -> None\n\
+\n\
+Remove the first occurance of a value in bytes");
+static PyObject *
+bytes_remove(PyBytesObject *self, PyObject *arg)
+{
+    int value;
+    Py_ssize_t where, n = self->ob_size;
+
+    if (! _getbytevalue(arg, &value))
+        return NULL;
+
+    for (where = 0; where < n; where++) {
+        if (self->ob_bytes[where] == value)
+            break;
+    }
+    if (where == n) {
+        PyErr_SetString(PyExc_ValueError, "value not found in bytes");
+        return NULL;
+    }
+
+    memmove(self->ob_bytes + where, self->ob_bytes + where + 1, n - where);
+    if (PyBytes_Resize((PyObject *)self, n - 1) < 0)
+        return NULL;
+
+    Py_RETURN_NONE;
+}
+
+/* XXX These two helpers could be optimized if argsize == 1 */
+
+Py_ssize_t
+lstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
+              void *argptr, Py_ssize_t argsize)
+{
+    Py_ssize_t i = 0;
+    while (i < mysize && memchr(argptr, myptr[i], argsize))
+        i++;
+    return i;
+}
+
+Py_ssize_t
+rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
+              void *argptr, Py_ssize_t argsize)
+{
+    Py_ssize_t i = mysize - 1;
+    while (i >= 0 && memchr(argptr, myptr[i], argsize))
+        i--;
+    return i + 1;
+}
+
+PyDoc_STRVAR(strip__doc__,
+"B.strip(bytes) -> bytes\n\
+\n\
+Strip leading and trailing bytes contained in the argument.");
+static PyObject *
+bytes_strip(PyBytesObject *self, PyObject *arg)
+{
+    Py_ssize_t left, right, mysize, argsize;
+    void *myptr, *argptr;
+    if (arg == NULL || !PyBytes_Check(arg)) {
+        PyErr_SetString(PyExc_TypeError, "strip() requires a bytes argument");
+        return NULL;
+    }
+    myptr = self->ob_bytes;
+    mysize = self->ob_size;
+    argptr = ((PyBytesObject *)arg)->ob_bytes;
+    argsize = ((PyBytesObject *)arg)->ob_size;
+    left = lstrip_helper(myptr, mysize, argptr, argsize);
+    right = rstrip_helper(myptr, mysize, argptr, argsize);
+    return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left);
+}
+
+PyDoc_STRVAR(lstrip__doc__,
+"B.lstrip(bytes) -> bytes\n\
+\n\
+Strip leading bytes contained in the argument.");
+static PyObject *
+bytes_lstrip(PyBytesObject *self, PyObject *arg)
+{
+    Py_ssize_t left, right, mysize, argsize;
+    void *myptr, *argptr;
+    if (arg == NULL || !PyBytes_Check(arg)) {
+        PyErr_SetString(PyExc_TypeError, "strip() requires a bytes argument");
+        return NULL;
+    }
+    myptr = self->ob_bytes;
+    mysize = self->ob_size;
+    argptr = ((PyBytesObject *)arg)->ob_bytes;
+    argsize = ((PyBytesObject *)arg)->ob_size;
+    left = lstrip_helper(myptr, mysize, argptr, argsize);
+    right = mysize;
+    return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left);
+}
+
+PyDoc_STRVAR(rstrip__doc__,
+"B.rstrip(bytes) -> bytes\n\
+\n\
+Strip trailing bytes contained in the argument.");
+static PyObject *
+bytes_rstrip(PyBytesObject *self, PyObject *arg)
+{
+    Py_ssize_t left, right, mysize, argsize;
+    void *myptr, *argptr;
+    if (arg == NULL || !PyBytes_Check(arg)) {
+        PyErr_SetString(PyExc_TypeError, "strip() requires a bytes argument");
+        return NULL;
+    }
+    myptr = self->ob_bytes;
+    mysize = self->ob_size;
+    argptr = ((PyBytesObject *)arg)->ob_bytes;
+    argsize = ((PyBytesObject *)arg)->ob_size;
+    left = 0;
+    right = rstrip_helper(myptr, mysize, argptr, argsize);
+    return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left);
+}
+
+PyDoc_STRVAR(decode_doc,
+"B.decode([encoding[,errors]]) -> unicode obect.\n\
+\n\
+Decodes B 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 *
+bytes_decode(PyObject *self, PyObject *args)
+{
+    const char *encoding = NULL;
+    const char *errors = NULL;
+
+    if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
+        return NULL;
+    if (encoding == NULL)
+        encoding = PyUnicode_GetDefaultEncoding();
+    return PyCodec_Decode(self, encoding, errors);
+}
+
+PyDoc_STRVAR(alloc_doc,
+"B.__alloc__() -> int\n\
+\n\
+Returns the number of bytes actually allocated.");
+
+static PyObject *
+bytes_alloc(PyBytesObject *self)
+{
+    return PyInt_FromSsize_t(self->ob_alloc);
+}
+
+PyDoc_STRVAR(join_doc,
+"bytes.join(iterable_of_bytes) -> bytes\n\
+\n\
+Concatenates any number of bytes objects.  Example:\n\
+bytes.join([bytes('ab'), bytes('pq'), bytes('rs')]) -> bytes('abpqrs').");
+
+static PyObject *
+bytes_join(PyObject *cls, PyObject *it)
+{
+    PyObject *seq;
+    Py_ssize_t i;
+    Py_ssize_t n;
+    PyObject **items;
+    Py_ssize_t totalsize = 0;
+    PyObject *result;
+    char *dest;
+
+    seq = PySequence_Fast(it, "can only join an iterable");
+    if (seq == NULL)
+        return NULL;
+    n = PySequence_Fast_GET_SIZE(seq);
+    items = PySequence_Fast_ITEMS(seq);
+
+    /* Compute the total size, and check that they are all bytes */
+    for (i = 0; i < n; i++) {
+        PyObject *obj = items[i];
+        if (!PyBytes_Check(obj)) {
+            PyErr_Format(PyExc_TypeError,
+                         "can only join an iterable of bytes "
+                         "(item %ld has type '%.100s')",
+                         /* XXX %ld isn't right on Win64 */
+                         (long)i, obj->ob_type->tp_name);
+            goto error;
+        }
+        totalsize += PyBytes_GET_SIZE(obj);
+        if (totalsize < 0) {
+            PyErr_NoMemory();
+            goto error;
+        }
+    }
+
+    /* Allocate the result, and copy the bytes */
+    result = PyBytes_FromStringAndSize(NULL, totalsize);
+    if (result == NULL)
+        goto error;
+    dest = PyBytes_AS_STRING(result);
+    for (i = 0; i < n; i++) {
+        PyObject *obj = items[i];
+        Py_ssize_t size = PyBytes_GET_SIZE(obj);
+        memcpy(dest, PyBytes_AS_STRING(obj), size);
+        dest += size;
+    }
+
+    /* Done */
+    Py_DECREF(seq);
+    return result;
+
+    /* Error handling */
+  error:
+    Py_DECREF(seq);
+    return NULL;
+}
+
+PyDoc_STRVAR(fromhex_doc,
+"bytes.fromhex(string) -> bytes\n\
+\n\
+Create a bytes object from a string of hexadecimal numbers.\n\
+Spaces between two numbers are accepted. Example:\n\
+bytes.fromhex('10 2030') -> bytes([0x10, 0x20, 0x30]).");
+
+static int
+hex_digit_to_int(int c)
+{
+    if (isdigit(c))
+        return c - '0';
+    else {
+        if (isupper(c))
+            c = tolower(c);
+        if (c >= 'a' && c <= 'f')
+            return c - 'a' + 10;
+    }
+    return -1;
+}
+
+static PyObject *
+bytes_fromhex(PyObject *cls, PyObject *args)
+{
+    PyObject *newbytes;
+    char *hex, *buf;
+    Py_ssize_t len, byteslen, i, j;
+    int top, bot;
+
+    if (!PyArg_ParseTuple(args, "s#:fromhex", &hex, &len))
+        return NULL;
+
+    byteslen = len / 2; /* max length if there are no spaces */
+
+    newbytes = PyBytes_FromStringAndSize(NULL, byteslen);
+    if (!newbytes)
+        return NULL;
+    buf = PyBytes_AS_STRING(newbytes);
+
+    for (i = j = 0; ; i += 2) {
+        /* skip over spaces in the input */
+        while (Py_CHARMASK(hex[i]) == ' ')
+            i++;
+        if (i >= len)
+            break;
+        top = hex_digit_to_int(Py_CHARMASK(hex[i]));
+        bot = hex_digit_to_int(Py_CHARMASK(hex[i+1]));
+        if (top == -1 || bot == -1) {
+            PyErr_Format(PyExc_ValueError,
+                         "non-hexadecimal number string '%c%c' found in "
+                         "fromhex() arg at position %zd",
+                         hex[i], hex[i+1], i);
+            goto error;
+        }
+        buf[j++] = (top << 4) + bot;
+    }
+    if (PyBytes_Resize(newbytes, j) < 0)
+        goto error;
+    return newbytes;
+
+  error:
+    Py_DECREF(newbytes);
+    return NULL;
+}
+
+PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
+
+static PyObject *
+bytes_reduce(PyBytesObject *self)
+{
+    return Py_BuildValue("(O(s#))",
+                         self->ob_type,
+                         self->ob_bytes == NULL ? "" : self->ob_bytes,
+                         self->ob_size);
 }
 
 static PySequenceMethods bytes_as_sequence = {
-    (lenfunc)bytes_length,              /*sq_length*/
-    (binaryfunc)bytes_concat,           /*sq_concat*/
-    (ssizeargfunc)bytes_repeat,         /*sq_repeat*/
-    (ssizeargfunc)bytes_getitem,        /*sq_item*/
-    0,                                  /*sq_slice*/
-    (ssizeobjargproc)bytes_setitem,     /*sq_ass_item*/
-    0, 					/* sq_ass_slice */
+    (lenfunc)bytes_length,              /* sq_length */
+    (binaryfunc)bytes_concat,           /* sq_concat */
+    (ssizeargfunc)bytes_repeat,         /* sq_repeat */
+    (ssizeargfunc)bytes_getitem,        /* sq_item */
+    0,                                  /* sq_slice */
+    (ssizeobjargproc)bytes_setitem,     /* sq_ass_item */
+    0,                                  /* sq_ass_slice */
     (objobjproc)bytes_contains,         /* sq_contains */
-    (binaryfunc)bytes_iconcat,   /* sq_inplace_concat */
-    (ssizeargfunc)bytes_irepeat, /* sq_inplace_repeat */
+    (binaryfunc)bytes_iconcat,          /* sq_inplace_concat */
+    (ssizeargfunc)bytes_irepeat,        /* sq_inplace_repeat */
 };
 
 static PyMappingMethods bytes_as_mapping = {
@@ -1002,9 +2742,35 @@
 
 static PyMethodDef
 bytes_methods[] = {
+    {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__},
+    {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__},
+    {"index", (PyCFunction)bytes_index, METH_VARARGS, index__doc__},
+    {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__},
+    {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__},
+    {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, endswith__doc__},
+    {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS,
+                startswith__doc__},
+    {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__},
+    {"translate", (PyCFunction)bytes_translate, METH_VARARGS, translate__doc__},
+    {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__},
+    {"rpartition", (PyCFunction)bytes_rpartition, METH_O, rpartition__doc__},
+    {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__},
+    {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__},
+    {"extend", (PyCFunction)bytes_extend, METH_O, extend__doc__},
+    {"insert", (PyCFunction)bytes_insert, METH_VARARGS, insert__doc__},
+    {"append", (PyCFunction)bytes_append, METH_O, append__doc__},
+    {"reverse", (PyCFunction)bytes_reverse, METH_NOARGS, reverse__doc__},
+    {"pop", (PyCFunction)bytes_pop, METH_VARARGS, pop__doc__},
+    {"remove", (PyCFunction)bytes_remove, METH_O, remove__doc__},
+    {"strip", (PyCFunction)bytes_strip, METH_O, strip__doc__},
+    {"lstrip", (PyCFunction)bytes_lstrip, METH_O, lstrip__doc__},
+    {"rstrip", (PyCFunction)bytes_rstrip, METH_O, rstrip__doc__},
     {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc},
     {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc},
+    {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS,
+     fromhex_doc},
     {"join", (PyCFunction)bytes_join, METH_O|METH_CLASS, join_doc},
+    {"__reduce__", (PyCFunction)bytes_reduce, METH_NOARGS, reduce_doc},
     {NULL}
 };
 
@@ -1028,14 +2794,14 @@
     0,                                  /* tp_as_number */
     &bytes_as_sequence,                 /* tp_as_sequence */
     &bytes_as_mapping,                  /* tp_as_mapping */
-    0,		                       /* tp_hash */
+    0,                                  /* tp_hash */
     0,                                  /* tp_call */
     (reprfunc)bytes_str,                /* tp_str */
     PyObject_GenericGetAttr,            /* tp_getattro */
     0,                                  /* tp_setattro */
     &bytes_as_buffer,                   /* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT,			/* tp_flags */
-                                        /* bytes is 'final' or 'sealed' */
+    /* bytes is 'final' or 'sealed' */
+    Py_TPFLAGS_DEFAULT,                 /* tp_flags */
     bytes_doc,                          /* tp_doc */
     0,                                  /* tp_traverse */
     0,                                  /* tp_clear */

Modified: python/branches/p3yk-noslice/Objects/complexobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/complexobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/complexobject.c	Wed Jul 11 15:40:56 2007
@@ -252,12 +252,51 @@
 PyComplex_AsCComplex(PyObject *op)
 {
 	Py_complex cv;
+	PyObject *newop = NULL;
+	static PyObject *complex_str = NULL;
+
+	assert(op);
+	/* If op is already of type PyComplex_Type, return its value */
 	if (PyComplex_Check(op)) {
 		return ((PyComplexObject *)op)->cval;
 	}
+	/* If not, use op's __complex__  method, if it exists */
+	
+	/* return -1 on failure */
+	cv.real = -1.;
+	cv.imag = 0.;
+	
+        {
+		PyObject *complexfunc;
+		if (!complex_str) {
+			if (!(complex_str = PyString_FromString("__complex__")))
+				return cv;
+		}
+		complexfunc = _PyType_Lookup(op->ob_type, complex_str);
+		/* complexfunc is a borrowed reference */
+		if (complexfunc) {
+			newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
+			if (!newop)
+				return cv;
+		}
+	}
+
+	if (newop) {
+		if (!PyComplex_Check(newop)) {
+			PyErr_SetString(PyExc_TypeError,
+				"__complex__ should return a complex object");
+			Py_DECREF(newop);
+			return cv;
+		}
+		cv = ((PyComplexObject *)newop)->cval;
+		Py_DECREF(newop);
+		return cv;
+	}
+	/* If neither of the above works, interpret op as a float giving the
+	   real part of the result, and fill in the imaginary part as 0. */
 	else {
+		/* PyFloat_AsDouble will return -1 on failure */
 		cv.real = PyFloat_AsDouble(op);
-		cv.imag = 0.;
 		return cv;
 	}
 }
@@ -512,7 +551,7 @@
 	}
 	else if (errno == ERANGE) {
 		PyErr_SetString(PyExc_OverflowError,
-				"complex exponentiaion");
+				"complex exponentiation");
 		return NULL;
 	}
 	return PyComplex_FromCComplex(p);
@@ -652,7 +691,7 @@
 	const char *s, *start;
 	char *end;
 	double x=0.0, y=0.0, z;
-	int got_re=0, got_im=0, done=0;
+	int got_re=0, got_im=0, got_bracket=0, done=0;
 	int digit_or_dot;
 	int sw_error=0;
 	int sign;
@@ -692,10 +731,17 @@
 	start = s;
 	while (*s && isspace(Py_CHARMASK(*s)))
 		s++;
-	if (s[0] == '\0') {
+    if (s[0] == '\0') {
 		PyErr_SetString(PyExc_ValueError,
 				"complex() arg is an empty string");
 		return NULL;
+    }
+	if (s[0] == '(') {
+		/* Skip over possible bracket from repr(). */
+		got_bracket = 1;
+		s++;
+		while (*s && isspace(Py_CHARMASK(*s)))
+			s++;
 	}
 
 	z = -1.0;
@@ -714,13 +760,26 @@
 			if(!done) sw_error=1;
 			break;
 
+		case ')':
+			if (!got_bracket || !(got_re || got_im)) {
+				sw_error=1;
+				break;
+			}
+			got_bracket=0;
+			done=1;
+			s++;
+			while (*s && isspace(Py_CHARMASK(*s)))
+				s++;
+			if (*s) sw_error=1;
+			break;
+
 		case '-':
 			sign = -1;
 				/* Fallthrough */
 		case '+':
 			if (done)  sw_error=1;
 			s++;
-			if  (  *s=='\0'||*s=='+'||*s=='-'  ||
+			if  (  *s=='\0'||*s=='+'||*s=='-'||*s==')'||
 			       isspace(Py_CHARMASK(*s))  )  sw_error=1;
 			break;
 
@@ -746,7 +805,7 @@
 			if (isspace(Py_CHARMASK(*s))) {
 				while (*s && isspace(Py_CHARMASK(*s)))
 					s++;
-				if (s[0] != '\0')
+				if (*s && *s != ')')
 					sw_error=1;
 				else
 					done = 1;
@@ -792,7 +851,7 @@
 
 	} while (s - start < len && !sw_error);
 
-	if (sw_error) {
+	if (sw_error || got_bracket) {
 		PyErr_SetString(PyExc_ValueError,
 				"complex() arg is a malformed string");
 		return NULL;
@@ -817,12 +876,14 @@
 					 &r, &i))
 		return NULL;
 
-	/* Special-case for single argument that is already complex */
+	/* Special-case for a single argument when type(arg) is complex. */
 	if (PyComplex_CheckExact(r) && i == NULL &&
 	    type == &PyComplex_Type) {
 		/* Note that we can't know whether it's safe to return
 		   a complex *subclass* instance as-is, hence the restriction
-		   to exact complexes here.  */
+		   to exact complexes here.  If either the input or the
+		   output is a complex subclass, it will be handled below 
+		   as a non-orthogonal vector.  */
 		Py_INCREF(r);
 		return r;
 	}
@@ -873,6 +934,14 @@
 		}
 		return NULL;
 	}
+
+	/* If we get this far, then the "real" and "imag" parts should
+	   both be treated as numbers, and the constructor should return a
+	   complex number equal to (real + imag*1j).
+
+ 	   Note that we do NOT assume the input to already be in canonical
+	   form; the "real" and "imag" parts might themselves be complex
+	   numbers, which slightly complicates the code below. */
 	if (PyComplex_Check(r)) {
 		/* Note that if r is of a complex subtype, we're only
 		   retaining its real & imag parts here, and the return
@@ -883,8 +952,14 @@
 		}
 	}
 	else {
+		/* The "real" part really is entirely real, and contributes
+		   nothing in the imaginary direction.  
+		   Just treat it as a double. */
+		cr.imag = 0.0;  
 		tmp = PyNumber_Float(r);
 		if (own_r) {
+			/* r was a newly created complex number, rather
+			   than the original "real" argument. */
 			Py_DECREF(r);
 		}
 		if (tmp == NULL)
@@ -897,7 +972,6 @@
 		}
 		cr.real = PyFloat_AsDouble(tmp);
 		Py_DECREF(tmp);
-		cr.imag = 0.0;
 	}
 	if (i == NULL) {
 		ci.real = 0.0;
@@ -906,13 +980,19 @@
 	else if (PyComplex_Check(i))
 		ci = ((PyComplexObject*)i)->cval;
 	else {
+		/* The "imag" part really is entirely imaginary, and
+		   contributes nothing in the real direction.
+		   Just treat it as a double. */
+		ci.imag = 0.0;
 		tmp = (*nbi->nb_float)(i);
 		if (tmp == NULL)
 			return NULL;
 		ci.real = PyFloat_AsDouble(tmp);
 		Py_DECREF(tmp);
-		ci.imag = 0.;
 	}
+	/*  If the input was in canonical form, then the "real" and "imag"
+	    parts are real numbers, so that ci.real and cr.imag are zero.
+	    We need this correction in case they were not real numbers. */
 	cr.real -= ci.imag;
 	cr.imag += ci.real;
 	return complex_subtype_from_c_complex(type, cr);

Modified: python/branches/p3yk-noslice/Objects/dictobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/dictobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/dictobject.c	Wed Jul 11 15:40:56 2007
@@ -1205,6 +1205,24 @@
 	if (d == NULL)
 		return NULL;
 
+	if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {
+		dictobject *mp = (dictobject *)d;
+		Py_ssize_t pos = 0;
+		PyObject *key;
+		long hash;
+
+		if (dictresize(mp, PySet_GET_SIZE(seq)))
+			return NULL;
+
+		while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
+			Py_INCREF(key);
+			Py_INCREF(value);
+			if (insertdict(mp, key, hash, value))
+				return NULL;
+		}
+		return d;
+	}
+
 	it = PyObject_GetIter(seq);
 	if (it == NULL){
 		Py_DECREF(d);
@@ -1869,9 +1887,9 @@
 static PyObject *dictitems_new(PyObject *);
 static PyObject *dictvalues_new(PyObject *);
 
-PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys");
-PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items");
-PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values");
+PyDoc_STRVAR(keys__doc__, "D.keys() -> a set-like object for D's keys");
+PyDoc_STRVAR(items__doc__, "D.items() -> a set-like object for D's items");
+PyDoc_STRVAR(values__doc__, "D.values() -> a set-like object for D's values");
 
 static PyMethodDef mapp_methods[] = {
 	{"__contains__",(PyCFunction)dict_contains,     METH_O | METH_COEXIST,
@@ -1895,11 +1913,11 @@
 	 values__doc__},
 #endif
 	{"keys",	(PyCFunction)dictkeys_new,	METH_NOARGS,
-	KEYS__doc__},
+	keys__doc__},
 	{"items",	(PyCFunction)dictitems_new,	METH_NOARGS,
-	ITEMS__doc__},
+	items__doc__},
 	{"values",	(PyCFunction)dictvalues_new,	METH_NOARGS,
-	VALUES__doc__},
+	values__doc__},
 	{"update",	(PyCFunction)dict_update,	METH_VARARGS | METH_KEYWORDS,
 	 update__doc__},
 	{"fromkeys",	(PyCFunction)dict_fromkeys,	METH_VARARGS | METH_CLASS,
@@ -2027,7 +2045,7 @@
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
 	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-		Py_TPFLAGS_BASETYPE,		/* tp_flags */
+		Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS,	/* tp_flags */
 	dictionary_doc,				/* tp_doc */
 	dict_traverse,				/* tp_traverse */
 	dict_tp_clear,				/* tp_clear */
@@ -2389,8 +2407,6 @@
 /* View objects for keys(), items(), values(). */
 /***********************************************/
 
-/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */
-
 /* The instance lay-out is the same for all three; but the type differs. */
 
 typedef struct {
@@ -2438,6 +2454,14 @@
 	return (PyObject *)dv;
 }
 
+/* TODO(guido): The views objects are not complete:
+
+ * support more set operations
+ * support arbitrary mappings?
+   - either these should be static or exported in dictobject.h
+   - if public then they should probably be in builtins
+*/
+
 /* Forward */
 PyTypeObject PyDictKeys_Type;
 PyTypeObject PyDictItems_Type;

Modified: python/branches/p3yk-noslice/Objects/exceptions.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/exceptions.c	(original)
+++ python/branches/p3yk-noslice/Objects/exceptions.c	Wed Jul 11 15:40:56 2007
@@ -10,20 +10,11 @@
 #include "osdefs.h"
 
 #define MAKE_IT_NONE(x) (x) = Py_None; Py_INCREF(Py_None);
-#define EXC_MODULE_NAME "exceptions."
 
 /* NOTE: If the exception class hierarchy changes, don't forget to update
  * Lib/test/exception_hierarchy.txt
  */
 
-PyDoc_STRVAR(exceptions_doc, "Python's standard exception class hierarchy.\n\
-\n\
-Exceptions found here are defined both in the exceptions module and the\n\
-built-in namespace.  It is recommended that user-defined exceptions\n\
-inherit from Exception.  See the documentation for the exception\n\
-inheritance hierarchy.\n\
-");
-
 /*
  *    BaseException
  */
@@ -33,8 +24,10 @@
     PyBaseExceptionObject *self;
 
     self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
+    if (!self)
+        return NULL;
     /* the dict is created on the fly in PyObject_GenericSetAttr */
-    self->message = self->dict = NULL;
+    self->dict = NULL;
 
     self->args = PyTuple_New(0);
     if (!self->args) {
@@ -42,12 +35,6 @@
         return NULL;
     }
 
-    self->message = PyString_FromString("");
-    if (!self->message) {
-        Py_DECREF(self);
-        return NULL;
-    }
-
     return (PyObject *)self;
 }
 
@@ -61,11 +48,6 @@
     self->args = args;
     Py_INCREF(self->args);
 
-    if (PyTuple_GET_SIZE(self->args) == 1) {
-        Py_CLEAR(self->message);
-        self->message = PyTuple_GET_ITEM(self->args, 0);
-        Py_INCREF(self->message);
-    }
     return 0;
 }
 
@@ -74,7 +56,6 @@
 {
     Py_CLEAR(self->dict);
     Py_CLEAR(self->args);
-    Py_CLEAR(self->message);
     return 0;
 }
 
@@ -91,7 +72,6 @@
 {
     Py_VISIT(self->dict);
     Py_VISIT(self->args);
-    Py_VISIT(self->message);
     return 0;
 }
 
@@ -183,40 +163,6 @@
 };
 
 
-
-static PyObject *
-BaseException_getitem(PyBaseExceptionObject *self, Py_ssize_t index)
-{
-    return PySequence_GetItem(self->args, index);
-}
-
-static PyObject *
-BaseException_getslice(PyBaseExceptionObject *self,
-			Py_ssize_t start, Py_ssize_t stop)
-{
-    return PySequence_GetSlice(self->args, start, stop);
-}
-
-static PySequenceMethods BaseException_as_sequence = {
-    0,                      /* sq_length; */
-    0,                      /* sq_concat; */
-    0,                      /* sq_repeat; */
-    (ssizeargfunc)BaseException_getitem,  /* sq_item; */
-    (ssizessizeargfunc)BaseException_getslice,  /* sq_slice; */
-    0,                      /* sq_ass_item; */
-    0,                      /* sq_ass_slice; */
-    0,                      /* sq_contains; */
-    0,                      /* sq_inplace_concat; */
-    0                       /* sq_inplace_repeat; */
-};
-
-static PyMemberDef BaseException_members[] = {
-    {"message", T_OBJECT, offsetof(PyBaseExceptionObject, message), 0,
-        PyDoc_STR("exception message")},
-    {NULL}  /* Sentinel */
-};
-
-
 static PyObject *
 BaseException_get_dict(PyBaseExceptionObject *self)
 {
@@ -272,6 +218,7 @@
     return 0;
 }
 
+
 static PyGetSetDef BaseException_getset[] = {
     {"__dict__", (getter)BaseException_get_dict, (setter)BaseException_set_dict},
     {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
@@ -282,7 +229,7 @@
 static PyTypeObject _PyExc_BaseException = {
     PyObject_HEAD_INIT(NULL)
     0,                          /*ob_size*/
-    EXC_MODULE_NAME "BaseException", /*tp_name*/
+    "BaseException", /*tp_name*/
     sizeof(PyBaseExceptionObject), /*tp_basicsize*/
     0,                          /*tp_itemsize*/
     (destructor)BaseException_dealloc, /*tp_dealloc*/
@@ -292,7 +239,7 @@
     0,                          /* tp_compare; */
     (reprfunc)BaseException_repr, /*tp_repr*/
     0,                          /*tp_as_number*/
-    &BaseException_as_sequence, /*tp_as_sequence*/
+    0,                          /*tp_as_sequence*/
     0,                          /*tp_as_mapping*/
     0,                          /*tp_hash */
     0,                          /*tp_call*/
@@ -300,7 +247,8 @@
     PyObject_GenericGetAttr,    /*tp_getattro*/
     PyObject_GenericSetAttr,    /*tp_setattro*/
     0,                          /*tp_as_buffer*/
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,  /*tp_flags*/
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
+    	Py_TPFLAGS_BASE_EXC_SUBCLASS,  /*tp_flags*/
     PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
     (traverseproc)BaseException_traverse, /* tp_traverse */
     (inquiry)BaseException_clear, /* tp_clear */
@@ -309,7 +257,7 @@
     0,                          /* tp_iter */
     0,                          /* tp_iternext */
     BaseException_methods,      /* tp_methods */
-    BaseException_members,      /* tp_members */
+    0,                          /* tp_members */
     BaseException_getset,       /* tp_getset */
     0,                          /* tp_base */
     0,                          /* tp_dict */
@@ -332,7 +280,7 @@
 static PyTypeObject _PyExc_ ## EXCNAME = { \
     PyObject_HEAD_INIT(NULL) \
     0, \
-    EXC_MODULE_NAME # EXCNAME, \
+    # EXCNAME, \
     sizeof(PyBaseExceptionObject), \
     0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
     0, 0, 0, 0, 0, 0, 0, \
@@ -348,7 +296,7 @@
 static PyTypeObject _PyExc_ ## EXCNAME = { \
     PyObject_HEAD_INIT(NULL) \
     0, \
-    EXC_MODULE_NAME # EXCNAME, \
+    # EXCNAME, \
     sizeof(Py ## EXCSTORE ## Object), \
     0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
     0, 0, 0, 0, 0, \
@@ -364,7 +312,7 @@
 static PyTypeObject _PyExc_ ## EXCNAME = { \
     PyObject_HEAD_INIT(NULL) \
     0, \
-    EXC_MODULE_NAME # EXCNAME, \
+    # EXCNAME, \
     sizeof(Py ## EXCSTORE ## Object), 0, \
     (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
     (reprfunc)EXCSTR, 0, 0, 0, \
@@ -386,17 +334,9 @@
 
 
 /*
- *    StandardError extends Exception
- */
-SimpleExtendsException(PyExc_Exception, StandardError,
-    "Base class for all standard Python exceptions that do not represent\n"
-    "interpreter exiting.");
-
-
-/*
- *    TypeError extends StandardError
+ *    TypeError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, TypeError,
+SimpleExtendsException(PyExc_Exception, TypeError,
                        "Inappropriate argument type.");
 
 
@@ -404,7 +344,7 @@
  *    StopIteration extends Exception
  */
 SimpleExtendsException(PyExc_Exception, StopIteration,
-                       "Signal the end from iterator.next().");
+                       "Signal the end from iterator.__next__().");
 
 
 /*
@@ -460,8 +400,6 @@
 }
 
 static PyMemberDef SystemExit_members[] = {
-    {"message", T_OBJECT, offsetof(PySystemExitObject, message), 0,
-        PyDoc_STR("exception message")},
     {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
         PyDoc_STR("exception code")},
     {NULL}  /* Sentinel */
@@ -479,14 +417,14 @@
 
 
 /*
- *    ImportError extends StandardError
+ *    ImportError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, ImportError,
+SimpleExtendsException(PyExc_Exception, ImportError,
           "Import can't find module, or can't find name in module.");
 
 
 /*
- *    EnvironmentError extends StandardError
+ *    EnvironmentError extends Exception
  */
 
 /* Where a function has a single filename, such as open() or some
@@ -662,8 +600,6 @@
 }
 
 static PyMemberDef EnvironmentError_members[] = {
-    {"message", T_OBJECT, offsetof(PyEnvironmentErrorObject, message), 0,
-        PyDoc_STR("exception message")},
     {"errno", T_OBJECT, offsetof(PyEnvironmentErrorObject, myerrno), 0,
         PyDoc_STR("exception errno")},
     {"strerror", T_OBJECT, offsetof(PyEnvironmentErrorObject, strerror), 0,
@@ -713,7 +649,7 @@
     {NULL}
 };
 
-ComplexExtendsException(PyExc_StandardError, EnvironmentError,
+ComplexExtendsException(PyExc_Exception, EnvironmentError,
                         EnvironmentError, EnvironmentError_dealloc,
                         EnvironmentError_methods, EnvironmentError_members,
                         EnvironmentError_str,
@@ -895,8 +831,6 @@
 }
 
 static PyMemberDef WindowsError_members[] = {
-    {"message", T_OBJECT, offsetof(PyWindowsErrorObject, message), 0,
-        PyDoc_STR("exception message")},
     {"errno", T_OBJECT, offsetof(PyWindowsErrorObject, myerrno), 0,
         PyDoc_STR("POSIX exception code")},
     {"strerror", T_OBJECT, offsetof(PyWindowsErrorObject, strerror), 0,
@@ -925,16 +859,16 @@
 
 
 /*
- *    EOFError extends StandardError
+ *    EOFError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, EOFError,
+SimpleExtendsException(PyExc_Exception, EOFError,
                        "Read beyond end of file.");
 
 
 /*
- *    RuntimeError extends StandardError
+ *    RuntimeError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, RuntimeError,
+SimpleExtendsException(PyExc_Exception, RuntimeError,
                        "Unspecified run-time error.");
 
 
@@ -945,9 +879,9 @@
                        "Method or function hasn't been implemented yet.");
 
 /*
- *    NameError extends StandardError
+ *    NameError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, NameError,
+SimpleExtendsException(PyExc_Exception, NameError,
                        "Name not found globally.");
 
 /*
@@ -957,14 +891,14 @@
                        "Local name referenced but not bound to a value.");
 
 /*
- *    AttributeError extends StandardError
+ *    AttributeError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, AttributeError,
+SimpleExtendsException(PyExc_Exception, AttributeError,
                        "Attribute not found.");
 
 
 /*
- *    SyntaxError extends StandardError
+ *    SyntaxError extends Exception
  */
 
 static int
@@ -1127,8 +1061,6 @@
 }
 
 static PyMemberDef SyntaxError_members[] = {
-    {"message", T_OBJECT, offsetof(PySyntaxErrorObject, message), 0,
-        PyDoc_STR("exception message")},
     {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
         PyDoc_STR("exception msg")},
     {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
@@ -1145,7 +1077,7 @@
     {NULL}  /* Sentinel */
 };
 
-ComplexExtendsException(PyExc_StandardError, SyntaxError, SyntaxError,
+ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
                         SyntaxError_dealloc, 0, SyntaxError_members,
                         SyntaxError_str, "Invalid syntax.");
 
@@ -1165,9 +1097,9 @@
 
 
 /*
- *    LookupError extends StandardError
+ *    LookupError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, LookupError,
+SimpleExtendsException(PyExc_Exception, LookupError,
                        "Base class for lookup errors.");
 
 
@@ -1204,9 +1136,9 @@
 
 
 /*
- *    ValueError extends StandardError
+ *    ValueError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, ValueError,
+SimpleExtendsException(PyExc_Exception, ValueError,
                        "Inappropriate argument value (of correct type).");
 
 /*
@@ -1217,36 +1149,6 @@
                        "Unicode related error.");
 
 #ifdef Py_USING_UNICODE
-static int
-get_int(PyObject *attr, Py_ssize_t *value, const char *name)
-{
-    if (!attr) {
-        PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
-        return -1;
-    }
-
-    if (PyLong_Check(attr)) {
-        *value = PyLong_AsSsize_t(attr);
-        if (*value == -1 && PyErr_Occurred())
-            return -1;
-    } else {
-        PyErr_Format(PyExc_TypeError, "%.200s attribute must be int", name);
-        return -1;
-    }
-    return 0;
-}
-
-static int
-set_ssize_t(PyObject **attr, Py_ssize_t value)
-{
-    PyObject *obj = PyInt_FromSsize_t(value);
-    if (!obj)
-        return -1;
-    Py_CLEAR(*attr);
-    *attr = obj;
-    return 0;
-}
-
 static PyObject *
 get_string(PyObject *attr, const char *name)
 {
@@ -1326,40 +1228,38 @@
 int
 PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
 {
-    if (!get_int(((PyUnicodeErrorObject *)exc)->start, start, "start")) {
-        Py_ssize_t size;
-        PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
-                                    "object");
-        if (!obj) return -1;
-        size = PyUnicode_GET_SIZE(obj);
-        if (*start<0)
-            *start = 0; /*XXX check for values <0*/
-        if (*start>=size)
-            *start = size-1;
-        Py_DECREF(obj);
-        return 0;
-    }
-    return -1;
+    Py_ssize_t size;
+    PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
+                                "object");
+    if (!obj)
+        return -1;
+    *start = ((PyUnicodeErrorObject *)exc)->start;
+    size = PyUnicode_GET_SIZE(obj);
+    if (*start<0)
+        *start = 0; /*XXX check for values <0*/
+    if (*start>=size)
+        *start = size-1;
+    Py_DECREF(obj);
+    return 0;
 }
 
 
 int
 PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
 {
-    if (!get_int(((PyUnicodeErrorObject *)exc)->start, start, "start")) {
-        Py_ssize_t size;
-        PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
-                                   "object");
-        if (!obj) return -1;
-        size = PyString_GET_SIZE(obj);
-        if (*start<0)
-            *start = 0;
-        if (*start>=size)
-            *start = size-1;
-        Py_DECREF(obj);
-        return 0;
-    }
-    return -1;
+    Py_ssize_t size;
+    PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
+                               "object");
+    if (!obj)
+        return -1;
+    size = PyString_GET_SIZE(obj);
+    *start = ((PyUnicodeErrorObject *)exc)->start;
+    if (*start<0)
+        *start = 0;
+    if (*start>=size)
+        *start = size-1;
+    Py_DECREF(obj);
+    return 0;
 }
 
 
@@ -1373,61 +1273,62 @@
 int
 PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
 {
-    return set_ssize_t(&((PyUnicodeErrorObject *)exc)->start, start);
+    ((PyUnicodeErrorObject *)exc)->start = start;
+    return 0;
 }
 
 
 int
 PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
 {
-    return set_ssize_t(&((PyUnicodeErrorObject *)exc)->start, start);
+    ((PyUnicodeErrorObject *)exc)->start = start;
+    return 0;
 }
 
 
 int
 PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
 {
-    return set_ssize_t(&((PyUnicodeErrorObject *)exc)->start, start);
+    ((PyUnicodeErrorObject *)exc)->start = start;
+    return 0;
 }
 
 
 int
 PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
 {
-    if (!get_int(((PyUnicodeErrorObject *)exc)->end, end, "end")) {
-        Py_ssize_t size;
-        PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
-                                    "object");
-        if (!obj) return -1;
-        size = PyUnicode_GET_SIZE(obj);
-        if (*end<1)
-            *end = 1;
-        if (*end>size)
-            *end = size;
-        Py_DECREF(obj);
-        return 0;
-    }
-    return -1;
+    Py_ssize_t size;
+    PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
+                                "object");
+    if (!obj)
+        return -1;
+    *end = ((PyUnicodeErrorObject *)exc)->end;
+    size = PyUnicode_GET_SIZE(obj);
+    if (*end<1)
+        *end = 1;
+    if (*end>size)
+        *end = size;
+    Py_DECREF(obj);
+    return 0;
 }
 
 
 int
 PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
 {
-    if (!get_int(((PyUnicodeErrorObject *)exc)->end, end, "end")) {
-        Py_ssize_t size;
-        PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
-                                   "object");
-        if (!obj) return -1;
-        size = PyString_GET_SIZE(obj);
-        if (*end<1)
-            *end = 1;
-        if (*end>size)
-            *end = size;
-        Py_DECREF(obj);
-        return 0;
-    }
-    return -1;
+    Py_ssize_t size;
+    PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
+                               "object");
+    if (!obj)
+        return -1;
+    *end = ((PyUnicodeErrorObject *)exc)->end;
+    size = PyString_GET_SIZE(obj);
+    if (*end<1)
+        *end = 1;
+    if (*end>size)
+        *end = size;
+    Py_DECREF(obj);
+    return 0;
 }
 
 
@@ -1441,21 +1342,24 @@
 int
 PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
 {
-    return set_ssize_t(&((PyUnicodeErrorObject *)exc)->end, end);
+    ((PyUnicodeErrorObject *)exc)->end = end;
+    return 0;
 }
 
 
 int
 PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
 {
-    return set_ssize_t(&((PyUnicodeErrorObject *)exc)->end, end);
+    ((PyUnicodeErrorObject *)exc)->end = end;
+    return 0;
 }
 
 
 int
 PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
 {
-    return set_ssize_t(&((PyUnicodeErrorObject *)exc)->end, end);
+    ((PyUnicodeErrorObject *)exc)->end = end;
+    return 0;
 }
 
 PyObject *
@@ -1506,25 +1410,20 @@
 {
     Py_CLEAR(self->encoding);
     Py_CLEAR(self->object);
-    Py_CLEAR(self->start);
-    Py_CLEAR(self->end);
     Py_CLEAR(self->reason);
 
-    if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
+    if (!PyArg_ParseTuple(args, "O!O!nnO!",
         &PyString_Type, &self->encoding,
         objecttype, &self->object,
-        &PyLong_Type, &self->start,
-        &PyLong_Type, &self->end,
+        &self->start,
+        &self->end,
         &PyString_Type, &self->reason)) {
-        self->encoding = self->object = self->start = self->end =
-            self->reason = NULL;
+        self->encoding = self->object = self->reason = NULL;
         return -1;
     }
 
     Py_INCREF(self->encoding);
     Py_INCREF(self->object);
-    Py_INCREF(self->start);
-    Py_INCREF(self->end);
     Py_INCREF(self->reason);
 
     return 0;
@@ -1535,8 +1434,6 @@
 {
     Py_CLEAR(self->encoding);
     Py_CLEAR(self->object);
-    Py_CLEAR(self->start);
-    Py_CLEAR(self->end);
     Py_CLEAR(self->reason);
     return BaseException_clear((PyBaseExceptionObject *)self);
 }
@@ -1554,22 +1451,18 @@
 {
     Py_VISIT(self->encoding);
     Py_VISIT(self->object);
-    Py_VISIT(self->start);
-    Py_VISIT(self->end);
     Py_VISIT(self->reason);
     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
 }
 
 static PyMemberDef UnicodeError_members[] = {
-    {"message", T_OBJECT, offsetof(PyUnicodeErrorObject, message), 0,
-        PyDoc_STR("exception message")},
     {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
         PyDoc_STR("exception encoding")},
     {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
         PyDoc_STR("exception object")},
-    {"start", T_OBJECT, offsetof(PyUnicodeErrorObject, start), 0,
+    {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
         PyDoc_STR("exception start")},
-    {"end", T_OBJECT, offsetof(PyUnicodeErrorObject, end), 0,
+    {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
         PyDoc_STR("exception end")},
     {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
         PyDoc_STR("exception reason")},
@@ -1593,17 +1486,10 @@
 static PyObject *
 UnicodeEncodeError_str(PyObject *self)
 {
-    Py_ssize_t start;
-    Py_ssize_t end;
-
-    if (PyUnicodeEncodeError_GetStart(self, &start))
-        return NULL;
+    PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
 
-    if (PyUnicodeEncodeError_GetEnd(self, &end))
-        return NULL;
-
-    if (end==start+1) {
-        int badchar = (int)PyUnicode_AS_UNICODE(((PyUnicodeErrorObject *)self)->object)[start];
+    if (uself->end==uself->start+1) {
+        int badchar = (int)PyUnicode_AS_UNICODE(uself->object)[uself->start];
         char badchar_str[20];
         if (badchar <= 0xff)
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
@@ -1613,25 +1499,25 @@
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
         return PyString_FromFormat(
             "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
-            PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
+            PyString_AS_STRING(uself->encoding),
             badchar_str,
-            start,
-            PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
+            uself->start,
+            PyString_AS_STRING(uself->reason)
         );
     }
     return PyString_FromFormat(
         "'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
-        PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
-        start,
-        (end-1),
-        PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
+        PyString_AS_STRING(uself->encoding),
+        uself->start,
+        uself->end-1,
+        PyString_AS_STRING(uself->reason)
     );
 }
 
 static PyTypeObject _PyExc_UnicodeEncodeError = {
     PyObject_HEAD_INIT(NULL)
     0,
-    EXC_MODULE_NAME "UnicodeEncodeError",
+    "UnicodeEncodeError",
     sizeof(PyUnicodeErrorObject), 0,
     (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
@@ -1669,41 +1555,34 @@
 static PyObject *
 UnicodeDecodeError_str(PyObject *self)
 {
-    Py_ssize_t start = 0;
-    Py_ssize_t end = 0;
-
-    if (PyUnicodeDecodeError_GetStart(self, &start))
-    return NULL;
+    PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
 
-    if (PyUnicodeDecodeError_GetEnd(self, &end))
-    return NULL;
-
-    if (end==start+1) {
+    if (uself->end==uself->start+1) {
         /* FromFormat does not support %02x, so format that separately */
         char byte[4];
         PyOS_snprintf(byte, sizeof(byte), "%02x",
-                      ((int)PyString_AS_STRING(((PyUnicodeErrorObject *)self)->object)[start])&0xff);
+                      ((int)PyString_AS_STRING(uself->object)[uself->start])&0xff);
         return PyString_FromFormat(
             "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
-            PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
+            PyString_AS_STRING(uself->encoding),
             byte,
-            start,
-            PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
+            uself->start,
+            PyString_AS_STRING(uself->reason)
         );
     }
     return PyString_FromFormat(
         "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
-        PyString_AS_STRING(((PyUnicodeErrorObject *)self)->encoding),
-        start,
-        (end-1),
-        PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
+        PyString_AS_STRING(uself->encoding),
+        uself->start,
+        uself->end-1,
+        PyString_AS_STRING(uself->reason)
     );
 }
 
 static PyTypeObject _PyExc_UnicodeDecodeError = {
     PyObject_HEAD_INIT(NULL)
     0,
-    EXC_MODULE_NAME "UnicodeDecodeError",
+    "UnicodeDecodeError",
     sizeof(PyUnicodeErrorObject), 0,
     (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
@@ -1740,22 +1619,18 @@
         return -1;
 
     Py_CLEAR(self->object);
-    Py_CLEAR(self->start);
-    Py_CLEAR(self->end);
     Py_CLEAR(self->reason);
 
-    if (!PyArg_ParseTuple(args, "O!O!O!O!",
+    if (!PyArg_ParseTuple(args, "O!nnO!",
         &PyUnicode_Type, &self->object,
-        &PyLong_Type, &self->start,
-        &PyLong_Type, &self->end,
+        &self->start,
+        &self->end,
         &PyString_Type, &self->reason)) {
-        self->object = self->start = self->end = self->reason = NULL;
+        self->object = self->reason = NULL;
         return -1;
     }
 
     Py_INCREF(self->object);
-    Py_INCREF(self->start);
-    Py_INCREF(self->end);
     Py_INCREF(self->reason);
 
     return 0;
@@ -1765,17 +1640,10 @@
 static PyObject *
 UnicodeTranslateError_str(PyObject *self)
 {
-    Py_ssize_t start;
-    Py_ssize_t end;
-
-    if (PyUnicodeTranslateError_GetStart(self, &start))
-        return NULL;
+    PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
 
-    if (PyUnicodeTranslateError_GetEnd(self, &end))
-        return NULL;
-
-    if (end==start+1) {
-        int badchar = (int)PyUnicode_AS_UNICODE(((PyUnicodeErrorObject *)self)->object)[start];
+    if (uself->end==uself->start+1) {
+        int badchar = (int)PyUnicode_AS_UNICODE(uself->object)[uself->start];
         char badchar_str[20];
         if (badchar <= 0xff)
             PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
@@ -1786,22 +1654,22 @@
         return PyString_FromFormat(
             "can't translate character u'\\%s' in position %zd: %.400s",
             badchar_str,
-            start,
-            PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
+            uself->start,
+            PyString_AS_STRING(uself->reason)
         );
     }
     return PyString_FromFormat(
         "can't translate characters in position %zd-%zd: %.400s",
-        start,
-        (end-1),
-        PyString_AS_STRING(((PyUnicodeErrorObject *)self)->reason)
+        uself->start,
+        uself->end-1,
+        PyString_AS_STRING(uself->reason)
     );
 }
 
 static PyTypeObject _PyExc_UnicodeTranslateError = {
     PyObject_HEAD_INIT(NULL)
     0,
-    EXC_MODULE_NAME "UnicodeTranslateError",
+    "UnicodeTranslateError",
     sizeof(PyUnicodeErrorObject), 0,
     (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
@@ -1825,16 +1693,16 @@
 
 
 /*
- *    AssertionError extends StandardError
+ *    AssertionError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, AssertionError,
+SimpleExtendsException(PyExc_Exception, AssertionError,
                        "Assertion failed.");
 
 
 /*
- *    ArithmeticError extends StandardError
+ *    ArithmeticError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, ArithmeticError,
+SimpleExtendsException(PyExc_Exception, ArithmeticError,
                        "Base class for arithmetic errors.");
 
 
@@ -1860,9 +1728,9 @@
 
 
 /*
- *    SystemError extends StandardError
+ *    SystemError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, SystemError,
+SimpleExtendsException(PyExc_Exception, SystemError,
     "Internal error in the Python interpreter.\n"
     "\n"
     "Please report this to the Python maintainer, along with the traceback,\n"
@@ -1870,16 +1738,16 @@
 
 
 /*
- *    ReferenceError extends StandardError
+ *    ReferenceError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, ReferenceError,
+SimpleExtendsException(PyExc_Exception, ReferenceError,
                        "Weak ref proxy used after referent went away.");
 
 
 /*
- *    MemoryError extends StandardError
+ *    MemoryError extends Exception
  */
-SimpleExtendsException(PyExc_StandardError, MemoryError, "Out of memory.");
+SimpleExtendsException(PyExc_Exception, MemoryError, "Out of memory.");
 
 
 /* Warning category docstrings */
@@ -1955,17 +1823,10 @@
  */
 PyObject *PyExc_MemoryErrorInst=NULL;
 
-/* module global functions */
-static PyMethodDef functions[] = {
-    /* Sentinel */
-    {NULL, NULL}
-};
-
 #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
     Py_FatalError("exceptions bootstrapping error.");
 
 #define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \
-    PyModule_AddObject(m, # TYPE, PyExc_ ## TYPE); \
     if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
         Py_FatalError("Module dictionary insertion problem.");
 
@@ -1995,11 +1856,10 @@
 PyMODINIT_FUNC
 _PyExc_Init(void)
 {
-    PyObject *m, *bltinmod, *bdict;
+    PyObject *bltinmod, *bdict;
 
     PRE_INIT(BaseException)
     PRE_INIT(Exception)
-    PRE_INIT(StandardError)
     PRE_INIT(TypeError)
     PRE_INIT(StopIteration)
     PRE_INIT(GeneratorExit)
@@ -2052,10 +1912,6 @@
     PRE_INIT(ImportWarning)
     PRE_INIT(UnicodeWarning)
 
-    m = Py_InitModule4("exceptions", functions, exceptions_doc,
-        (PyObject *)NULL, PYTHON_API_VERSION);
-    if (m == NULL) return;
-
     bltinmod = PyImport_ImportModule("__builtin__");
     if (bltinmod == NULL)
         Py_FatalError("exceptions bootstrapping error.");
@@ -2065,7 +1921,6 @@
 
     POST_INIT(BaseException)
     POST_INIT(Exception)
-    POST_INIT(StandardError)
     POST_INIT(TypeError)
     POST_INIT(StopIteration)
     POST_INIT(GeneratorExit)

Modified: python/branches/p3yk-noslice/Objects/fileobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/fileobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/fileobject.c	Wed Jul 11 15:40:56 2007
@@ -138,17 +138,16 @@
    ignore stuff they don't understand... write or append mode with
    universal newline support is expressly forbidden by PEP 278.
    Additionally, remove the 'U' from the mode string as platforms
-   won't know what it is. */
-/* zero return is kewl - one is un-kewl */
-static int
-sanitize_the_mode(char *mode)
+   won't know what it is. Non-zero return signals an exception */
+int
+_PyFile_SanitizeMode(char *mode)
 {
 	char *upos;
 	size_t len = strlen(mode);
 
 	if (!len) {
 		PyErr_SetString(PyExc_ValueError, "empty mode string");
-		return 1;
+		return -1;
 	}
 
 	upos = strchr(mode, 'U');
@@ -159,7 +158,7 @@
 			PyErr_Format(PyExc_ValueError, "universal newline "
 			             "mode can only be used with modes "
 				     "starting with 'r'");
-			return 1;
+			return -1;
 		}
 
 		if (mode[0] != 'r') {
@@ -174,7 +173,7 @@
 	} else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
 		PyErr_Format(PyExc_ValueError, "mode string must begin with "
 	        	    "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
-		return 1;
+		return -1;
 	}
 
 	return 0;
@@ -203,20 +202,11 @@
 	}
 	strcpy(newmode, mode);
 
-	if (sanitize_the_mode(newmode)) {
+	if (_PyFile_SanitizeMode(newmode)) {
 		f = NULL;
 		goto cleanup;
 	}
 
-	/* rexec.py can't stop a user from getting the file() constructor --
-	   all they have to do is get *any* file object f, and then do
-	   type(f).  Here we prevent them from doing damage with it. */
-	if (PyEval_GetRestricted()) {
-		PyErr_SetString(PyExc_IOError,
-		"file() constructor not accessible in restricted mode");
-		f = NULL;
-		goto cleanup;
-	}
 	errno = 0;
 
 #ifdef MS_WINDOWS

Modified: python/branches/p3yk-noslice/Objects/floatobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/floatobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/floatobject.c	Wed Jul 11 15:40:56 2007
@@ -62,24 +62,8 @@
 	return (PyObject *) op;
 }
 
-/**************************************************************************
-RED_FLAG 22-Sep-2000 tim
-PyFloat_FromString's pend argument is braindead.  Prior to this RED_FLAG,
-
-1.  If v was a regular string, *pend was set to point to its terminating
-    null byte.  That's useless (the caller can find that without any
-    help from this function!).
-
-2.  If v was a Unicode string, or an object convertible to a character
-    buffer, *pend was set to point into stack trash (the auto temp
-    vector holding the character buffer).  That was downright dangerous.
-
-Since we can't change the interface of a public API function, pend is
-still supported but now *officially* useless:  if pend is not NULL,
-*pend is set to NULL.
-**************************************************************************/
 PyObject *
-PyFloat_FromString(PyObject *v, char **pend)
+PyFloat_FromString(PyObject *v)
 {
 	const char *s, *last, *end;
 	double x;
@@ -89,8 +73,6 @@
 #endif
 	Py_ssize_t len;
 
-	if (pend)
-		*pend = NULL;
 	if (PyString_Check(v)) {
 		s = PyString_AS_STRING(v);
 		len = PyString_GET_SIZE(v);
@@ -697,18 +679,7 @@
 
 	/* Sort out special cases here instead of relying on pow() */
 	if (iw == 0) { 		/* v**0 is 1, even 0**0 */
-		PyFPE_START_PROTECT("pow", return NULL)
-		if ((PyObject *)z != Py_None) {
-			double iz;
-			CONVERT_TO_DOUBLE(z, iz);
-			ix = fmod(1.0, iz);
-			if (ix != 0 && iz < 0)
-				ix += iz;
-		}
-		else
-			ix = 1.0;
-		PyFPE_END_PROTECT(ix)
-		return PyFloat_FromDouble(ix);
+		return PyFloat_FromDouble(1.0);
 	}
 	if (iv == 0.0) {  /* 0**w is error if w<0, else 1 */
 		if (iw < 0.0) {
@@ -852,7 +823,7 @@
 	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
 		return NULL;
 	if (PyString_Check(x))
-		return PyFloat_FromString(x, NULL);
+		return PyFloat_FromString(x);
 	return PyNumber_Float(x);
 }
 

Modified: python/branches/p3yk-noslice/Objects/frameobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/frameobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/frameobject.c	Wed Jul 11 15:40:56 2007
@@ -48,7 +48,7 @@
 }
 
 /* Setter for f_lineno - you can set f_lineno from within a trace function in
- * order to jump to a given line of code, subject to some restrictions.  Most
+ * order to jump to a given line of code, subject to some restrictions.	 Most
  * lines are OK to jump to because they don't make any assumptions about the
  * state of the stack (obvious because you could remove the line and the code
  * would still work without any stack errors), but there are some constructs
@@ -68,7 +68,7 @@
 	int new_lineno = 0;		/* The new value of f_lineno */
 	int new_lasti = 0;		/* The new value of f_lasti */
 	int new_iblock = 0;		/* The new value of f_iblock */
-	char *code = NULL;		/* The bytecode for the frame... */
+	unsigned char *code = NULL;	/* The bytecode for the frame... */
 	Py_ssize_t code_len = 0;	/* ...and its length */
 	char *lnotab = NULL;		/* Iterating over co_lnotab */
 	Py_ssize_t lnotab_len = 0;	/* (ditto) */
@@ -85,7 +85,7 @@
 	int blockstack[CO_MAXBLOCKS];	/* Walking the 'finally' blocks */
 	int in_finally[CO_MAXBLOCKS];	/* (ditto) */
 	int blockstack_top = 0;		/* (ditto) */
-	int setup_op = 0;               /* (ditto) */
+	unsigned char setup_op = 0;	/* (ditto) */
 
 	/* f_lineno must be an integer. */
 	if (!PyInt_CheckExact(p_new_lineno)) {
@@ -137,7 +137,7 @@
 	}
 
 	/* We're now ready to look at the bytecode. */
-	PyString_AsStringAndSize(f->f_code->co_code, &code, &code_len);
+	PyString_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);
 
@@ -159,7 +159,7 @@
 
 	/* You can't jump into or out of a 'finally' block because the 'try'
 	 * block leaves something on the stack for the END_FINALLY to clean
-	 * up.  So we walk the bytecode, maintaining a simulated blockstack.
+	 * up.	So we walk the bytecode, maintaining a simulated blockstack.
 	 * When we reach the old or new address and it's in a 'finally' block
 	 * we note the address of the corresponding SETUP_FINALLY.  The jump
 	 * is only legal if neither address is in a 'finally' block or
@@ -340,18 +340,12 @@
 	return 0;
 }
 
-static PyObject *
-frame_getrestricted(PyFrameObject *f, void *closure)
-{
-	return PyBool_FromLong(PyFrame_IsRestricted(f));
-}
 
 static PyGetSetDef frame_getsetlist[] = {
 	{"f_locals",	(getter)frame_getlocals, NULL, NULL},
 	{"f_lineno",	(getter)frame_getlineno,
 			(setter)frame_setlineno, NULL},
 	{"f_trace",	(getter)frame_gettrace, (setter)frame_settrace, NULL},
-	{"f_restricted",(getter)frame_getrestricted,NULL, NULL},
 	{0}
 };
 
@@ -383,7 +377,7 @@
 	ob_type		== &Frametype
 	f_back		next item on free list, or NULL
 	f_stacksize	size of value stack
-        ob_size         size of localsplus
+	ob_size		size of localsplus
    Note that the value and block stacks are preserved -- this can save
    another malloc() call or two (and two free() calls as well!).
    Also note that, unlike for integers, each frame object is a
@@ -408,12 +402,12 @@
 	PyObject **p, **valuestack;
 	PyCodeObject *co;
 
- 	PyObject_GC_UnTrack(f);
+	PyObject_GC_UnTrack(f);
 	Py_TRASHCAN_SAFE_BEGIN(f)
 	/* Kill all local variables */
-        valuestack = f->f_valuestack;
-        for (p = f->f_localsplus; p < valuestack; p++)
-                Py_CLEAR(*p);
+	valuestack = f->f_valuestack;
+	for (p = f->f_localsplus; p < valuestack; p++)
+		Py_CLEAR(*p);
 
 	/* Free stack */
 	if (f->f_stacktop != NULL) {
@@ -430,18 +424,18 @@
 	Py_CLEAR(f->f_exc_value);
 	Py_CLEAR(f->f_exc_traceback);
 
-        co = f->f_code;
-        if (co->co_zombieframe == NULL)
-                co->co_zombieframe = f;
+	co = f->f_code;
+	if (co->co_zombieframe == NULL)
+		co->co_zombieframe = f;
 	else if (numfree < MAXFREELIST) {
 		++numfree;
 		f->f_back = free_list;
 		free_list = f;
-        }
+	}
 	else 
 		PyObject_GC_Del(f);
 
-        Py_DECREF(co);
+	Py_DECREF(co);
 	Py_TRASHCAN_SAFE_END(f)
 }
 
@@ -482,12 +476,12 @@
 	int i, slots;
 
 	/* Before anything else, make sure that this frame is clearly marked
-         * as being defunct!  Else, e.g., a generator reachable from this
-         * frame may also point to this frame, believe itself to still be
-         * active, and try cleaning up this frame again.
-         */
+	 * as being defunct!  Else, e.g., a generator reachable from this
+	 * frame may also point to this frame, believe itself to still be
+	 * active, and try cleaning up this frame again.
+	 */
 	oldtop = f->f_stacktop;
-        f->f_stacktop = NULL;
+	f->f_stacktop = NULL;
 
 	Py_CLEAR(f->f_exc_type);
 	Py_CLEAR(f->f_exc_value);
@@ -514,10 +508,10 @@
 	"frame",
 	sizeof(PyFrameObject),
 	sizeof(PyObject *),
-	(destructor)frame_dealloc, 		/* tp_dealloc */
+	(destructor)frame_dealloc,		/* tp_dealloc */
 	0,					/* tp_print */
-	0, 					/* tp_getattr */
-	0,			 		/* tp_setattr */
+	0,					/* tp_getattr */
+	0,					/* tp_setattr */
 	0,					/* tp_compare */
 	0,					/* tp_repr */
 	0,					/* tp_as_number */
@@ -530,8 +524,8 @@
 	PyObject_GenericSetAttr,		/* tp_setattro */
 	0,					/* tp_as_buffer */
 	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
-	0,             				/* tp_doc */
- 	(traverseproc)frame_traverse,		/* tp_traverse */
+	0,					/* tp_doc */
+	(traverseproc)frame_traverse,		/* tp_traverse */
 	(inquiry)frame_clear,			/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
@@ -579,7 +573,7 @@
 				builtins = NULL;
 		}
 		if (builtins == NULL) {
-			/* No builtins!  Make up a minimal one
+			/* No builtins!	 Make up a minimal one
 			   Give them 'None', at least. */
 			builtins = PyDict_New();
 			if (builtins == NULL ||
@@ -599,39 +593,39 @@
 		Py_INCREF(builtins);
 	}
 	if (code->co_zombieframe != NULL) {
-                f = code->co_zombieframe;
-                code->co_zombieframe = NULL;
-                _Py_NewReference((PyObject *)f);
-                assert(f->f_code == code);
-	}
-        else {
-                Py_ssize_t extras, ncells, nfrees;
-                ncells = PyTuple_GET_SIZE(code->co_cellvars);
-                nfrees = PyTuple_GET_SIZE(code->co_freevars);
-                extras = code->co_stacksize + code->co_nlocals + ncells +
-                    nfrees;
-                if (free_list == NULL) {
-                    f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
-                        extras);
-                    if (f == NULL) {
-                            Py_DECREF(builtins);
-                            return NULL;
-                    }
-                }
-                else {
-                    assert(numfree > 0);
-                    --numfree;
-                    f = free_list;
-                    free_list = free_list->f_back;
-                    if (f->ob_size < extras) {
-                            f = PyObject_GC_Resize(PyFrameObject, f, extras);
-                            if (f == NULL) {
-                                    Py_DECREF(builtins);
-                                    return NULL;
-                            }
-                    }
-                    _Py_NewReference((PyObject *)f);
-                }
+		f = code->co_zombieframe;
+		code->co_zombieframe = NULL;
+		_Py_NewReference((PyObject *)f);
+		assert(f->f_code == code);
+	}
+	else {
+		Py_ssize_t extras, ncells, nfrees;
+		ncells = PyTuple_GET_SIZE(code->co_cellvars);
+		nfrees = PyTuple_GET_SIZE(code->co_freevars);
+		extras = code->co_stacksize + code->co_nlocals + ncells +
+		    nfrees;
+		if (free_list == NULL) {
+		    f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
+			extras);
+		    if (f == NULL) {
+			    Py_DECREF(builtins);
+			    return NULL;
+		    }
+		}
+		else {
+		    assert(numfree > 0);
+		    --numfree;
+		    f = free_list;
+		    free_list = free_list->f_back;
+		    if (f->ob_size < extras) {
+			    f = PyObject_GC_Resize(PyFrameObject, f, extras);
+			    if (f == NULL) {
+				    Py_DECREF(builtins);
+				    return NULL;
+			    }
+		    }
+		    _Py_NewReference((PyObject *)f);
+		}
 
 		f->f_code = code;
 		extras = code->co_nlocals + ncells + nfrees;
@@ -640,7 +634,7 @@
 			f->f_localsplus[i] = NULL;
 		f->f_locals = NULL;
 		f->f_trace = NULL;
-                f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
+		f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
 	}
 	f->f_stacktop = f->f_valuestack;
 	f->f_builtins = builtins;
@@ -659,13 +653,13 @@
 			Py_DECREF(f);
 			return NULL;
 		}
-                f->f_locals = locals;
+		f->f_locals = locals;
 	}
 	else {
 		if (locals == NULL)
 			locals = globals;
 		Py_INCREF(locals);
-                f->f_locals = locals;
+		f->f_locals = locals;
 	}
 	f->f_tstate = tstate;
 
@@ -701,18 +695,38 @@
 	return b;
 }
 
-/* Convert between "fast" version of locals and dictionary version */
+/* Convert between "fast" version of locals and dictionary version.
+   
+   map and values are input arguments.	map is a tuple of strings.
+   values is an array of PyObject*.  At index i, map[i] is the name of
+   the variable with value values[i].  The function copies the first
+   nmap variable from map/values into dict.  If values[i] is NULL,
+   the variable is deleted from dict.
+
+   If deref is true, then the values being copied are cell variables
+   and the value is extracted from the cell variable before being put
+   in dict.
+
+   Exceptions raised while modifying the dict are silently ignored,
+   because there is no good way to report them.
+ */
 
 static void
 map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
-	    Py_ssize_t deref)
+	    int deref)
 {
 	Py_ssize_t j;
+	assert(PyTuple_Check(map));
+	assert(PyDict_Check(dict));
+	assert(PyTuple_Size(map) >= nmap);
 	for (j = nmap; --j >= 0; ) {
 		PyObject *key = PyTuple_GET_ITEM(map, j);
 		PyObject *value = values[j];
-		if (deref)
+		assert(PyString_Check(key));
+		if (deref) {
+			assert(PyCell_Check(value));
 			value = PyCell_GET(value);
+		}
 		if (value == NULL) {
 			if (PyObject_DelItem(dict, key) != 0)
 				PyErr_Clear();
@@ -724,29 +738,55 @@
 	}
 }
 
+/* Copy values from the "locals" dict into the fast locals.
+
+   dict is an input argument containing string keys representing
+   variables names and arbitrary PyObject* as values.
+
+   map and values are input arguments.	map is a tuple of strings.
+   values is an array of PyObject*.  At index i, map[i] is the name of
+   the variable with value values[i].  The function copies the first
+   nmap variable from map/values into dict.  If values[i] is NULL,
+   the variable is deleted from dict.
+
+   If deref is true, then the values being copied are cell variables
+   and the value is extracted from the cell variable before being put
+   in dict.  If clear is true, then variables in map but not in dict
+   are set to NULL in map; if clear is false, variables missing in
+   dict are ignored.
+
+   Exceptions raised while modifying the dict are silently ignored,
+   because there is no good way to report them.
+*/
+
 static void
 dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
-	    Py_ssize_t deref, int clear)
+	    int deref, int clear)
 {
 	Py_ssize_t j;
+	assert(PyTuple_Check(map));
+	assert(PyDict_Check(dict));
+	assert(PyTuple_Size(map) >= nmap);
 	for (j = nmap; --j >= 0; ) {
 		PyObject *key = PyTuple_GET_ITEM(map, j);
 		PyObject *value = PyObject_GetItem(dict, key);
-		if (value == NULL)
+		assert(PyString_Check(key));
+		/* We only care about NULLs if clear is true. */
+		if (value == NULL) {
 			PyErr_Clear();
+			if (!clear)
+				continue;
+		}
 		if (deref) {
-			if (value || clear) {
-				if (PyCell_GET(values[j]) != value) {
-					if (PyCell_Set(values[j], value) < 0)
-						PyErr_Clear();
-				}
-			}
-		} else if (value != NULL || clear) {
-			if (values[j] != value) {
-				Py_XINCREF(value);
-				Py_XDECREF(values[j]);
-				values[j] = value;
+			assert(PyCell_Check(values[j]));
+			if (PyCell_GET(values[j]) != value) {
+				if (PyCell_Set(values[j], value) < 0)
+					PyErr_Clear();
 			}
+		} else if (values[j] != value) {
+			Py_XINCREF(value);
+			Py_XDECREF(values[j]);
+			values[j] = value;
 		}
 		Py_XDECREF(value);
 	}
@@ -761,7 +801,7 @@
 	PyObject *error_type, *error_value, *error_traceback;
 	PyCodeObject *co;
 	Py_ssize_t j;
-        int ncells, nfreevars;
+	int ncells, nfreevars;
 	if (f == NULL)
 		return;
 	locals = f->f_locals;
@@ -788,8 +828,18 @@
 	if (ncells || nfreevars) {
 		map_to_dict(co->co_cellvars, ncells,
 			    locals, fast + co->co_nlocals, 1);
-		map_to_dict(co->co_freevars, nfreevars,
-			    locals, fast + co->co_nlocals + ncells, 1);
+		/* If the namespace is unoptimized, then one of the 
+		   following cases applies:
+		   1. It does not contain free variables, because it
+		      uses import * or is a top-level namespace.
+		   2. It is a class namespace.
+		   We don't want to accidentally copy free variables
+		   into the locals dict used by the class.
+		*/
+		if (co->co_flags & CO_OPTIMIZED) {
+			map_to_dict(co->co_freevars, nfreevars,
+				    locals, fast + co->co_nlocals + ncells, 1);
+		}
 	}
 	PyErr_Restore(error_type, error_value, error_traceback);
 }
@@ -827,7 +877,7 @@
 			    locals, fast + co->co_nlocals, 1, clear);
 		dict_to_map(co->co_freevars, nfreevars,
 			    locals, fast + co->co_nlocals + ncells, 1, 
- 			    clear);
+			    clear);
 	}
 	PyErr_Restore(error_type, error_value, error_traceback);
 }

Modified: python/branches/p3yk-noslice/Objects/funcobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/funcobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/funcobject.c	Wed Jul 11 15:40:56 2007
@@ -225,31 +225,18 @@
 #define OFF(x) offsetof(PyFunctionObject, x)
 
 static PyMemberDef func_memberlist[] = {
-        {"func_closure",  T_OBJECT,     OFF(func_closure),
+        {"__closure__",   T_OBJECT,     OFF(func_closure),
 	 RESTRICTED|READONLY},
-        {"func_doc",      T_OBJECT,     OFF(func_doc), WRITE_RESTRICTED},
         {"__doc__",       T_OBJECT,     OFF(func_doc), WRITE_RESTRICTED},
-        {"func_globals",  T_OBJECT,     OFF(func_globals),
+        {"__globals__",   T_OBJECT,     OFF(func_globals),
 	 RESTRICTED|READONLY},
         {"__module__",    T_OBJECT,     OFF(func_module), WRITE_RESTRICTED},
         {NULL}  /* Sentinel */
 };
 
-static int
-restricted(void)
-{
-	if (!PyEval_GetRestricted())
-		return 0;
-	PyErr_SetString(PyExc_RuntimeError,
-		"function attributes not accessible in restricted mode");
-	return 1;
-}
-
 static PyObject *
 func_get_dict(PyFunctionObject *op)
 {
-	if (restricted())
-		return NULL;
 	if (op->func_dict == NULL) {
 		op->func_dict = PyDict_New();
 		if (op->func_dict == NULL)
@@ -264,8 +251,6 @@
 {
 	PyObject *tmp;
 
-	if (restricted())
-		return -1;
 	/* It is illegal to del f.func_dict */
 	if (value == NULL) {
 		PyErr_SetString(PyExc_TypeError,
@@ -288,8 +273,6 @@
 static PyObject *
 func_get_code(PyFunctionObject *op)
 {
-	if (restricted())
-		return NULL;
 	Py_INCREF(op->func_code);
 	return op->func_code;
 }
@@ -300,13 +283,11 @@
 	PyObject *tmp;
 	Py_ssize_t nfree, nclosure;
 
-	if (restricted())
-		return -1;
 	/* Not legal to del f.func_code or to set it to anything
 	 * other than a code object. */
 	if (value == NULL || !PyCode_Check(value)) {
 		PyErr_SetString(PyExc_TypeError,
-				"func_code must be set to a code object");
+				"__code__ must be set to a code object");
 		return -1;
 	}
 	nfree = PyCode_GetNumFree((PyCodeObject *)value);
@@ -339,13 +320,11 @@
 {
 	PyObject *tmp;
 
-	if (restricted())
-		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)) {
 		PyErr_SetString(PyExc_TypeError,
-				"func_name must be set to a string object");
+				"__name__ must be set to a string object");
 		return -1;
 	}
 	tmp = op->func_name;
@@ -358,8 +337,6 @@
 static PyObject *
 func_get_defaults(PyFunctionObject *op)
 {
-	if (restricted())
-		return NULL;
 	if (op->func_defaults == NULL) {
 		Py_INCREF(Py_None);
 		return Py_None;
@@ -373,15 +350,13 @@
 {
 	PyObject *tmp;
 
-	if (restricted())
-		return -1;
 	/* Legal to del f.func_defaults.
 	 * Can only set func_defaults to NULL or a tuple. */
 	if (value == Py_None)
 		value = NULL;
 	if (value != NULL && !PyTuple_Check(value)) {
 		PyErr_SetString(PyExc_TypeError,
-				"func_defaults must be set to a tuple object");
+				"__defaults__ must be set to a tuple object");
 		return -1;
 	}
 	tmp = op->func_defaults;
@@ -394,8 +369,6 @@
 static PyObject *
 func_get_kwdefaults(PyFunctionObject *op)
 {
-	if (restricted())
-		return NULL;
 	if (op->func_kwdefaults == NULL) {
 		Py_INCREF(Py_None);
 		return Py_None;
@@ -408,17 +381,14 @@
 func_set_kwdefaults(PyFunctionObject *op, PyObject *value)
 {
 	PyObject *tmp;
-    
-	if (restricted())
-		return -1;
 
 	if (value == Py_None)
 		value = NULL;
-	/* Legal to del f.func_defaults.
+	/* Legal to del f.func_kwdefaults.
 	 * Can only set func_kwdefaults to NULL or a dict. */
 	if (value != NULL && !PyDict_Check(value)) {
 		PyErr_SetString(PyExc_TypeError,
-			"func_kwdefaults must be set to a dict object");
+			"__kwdefaults__ must be set to a dict object");
 		return -1;
 	}
 	tmp = op->func_kwdefaults;
@@ -452,7 +422,7 @@
 	 * or a dict. */
 	if (value != NULL && !PyDict_Check(value)) {
 		PyErr_SetString(PyExc_TypeError,
-			"func_annotations must be set to a dict object");
+			"__annotations__ must be set to a dict object");
 		return -1;
 	}
 	tmp = op->func_annotations;
@@ -463,16 +433,14 @@
 }
 
 static PyGetSetDef func_getsetlist[] = {
-        {"func_code", (getter)func_get_code, (setter)func_set_code},
-        {"func_defaults", (getter)func_get_defaults,
+        {"__code__", (getter)func_get_code, (setter)func_set_code},
+        {"__defaults__", (getter)func_get_defaults,
 	 (setter)func_set_defaults},
-	{"func_kwdefaults", (getter)func_get_kwdefaults,
+	{"__kwdefaults__", (getter)func_get_kwdefaults,
 	 (setter)func_set_kwdefaults},
-	{"func_annotations", (getter)func_get_annotations,
+	{"__annotations__", (getter)func_get_annotations,
 	 (setter)func_set_annotations},
-	{"func_dict", (getter)func_get_dict, (setter)func_set_dict},
 	{"__dict__", (getter)func_get_dict, (setter)func_set_dict},
-	{"func_name", (getter)func_get_name, (setter)func_set_name},
 	{"__name__", (getter)func_get_name, (setter)func_set_name},
 	{NULL} /* Sentinel */
 };
@@ -590,6 +558,7 @@
 	Py_XDECREF(op->func_module);
 	Py_DECREF(op->func_name);
 	Py_XDECREF(op->func_defaults);
+	Py_XDECREF(op->func_kwdefaults);
 	Py_XDECREF(op->func_doc);
 	Py_XDECREF(op->func_dict);
 	Py_XDECREF(op->func_closure);
@@ -612,6 +581,7 @@
 	Py_VISIT(f->func_globals);
 	Py_VISIT(f->func_module);
 	Py_VISIT(f->func_defaults);
+	Py_VISIT(f->func_kwdefaults);
 	Py_VISIT(f->func_doc);
 	Py_VISIT(f->func_name);
 	Py_VISIT(f->func_dict);

Modified: python/branches/p3yk-noslice/Objects/intobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/intobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/intobject.c	Wed Jul 11 15:40:56 2007
@@ -214,11 +214,10 @@
 		return -1;
 	}
 
-	if (nb->nb_long != 0) {
+	if (nb->nb_long != 0)
 		io = (PyIntObject*) (*nb->nb_long) (op);
-	} else {
+	else
 		io = (PyIntObject*) (*nb->nb_int) (op);
-	}
 	if (io == NULL)
 		return -1;
 	if (!PyInt_Check(io)) {
@@ -395,7 +394,7 @@
 	char *buffer = (char *)PyMem_MALLOC(length+1);
 
 	if (buffer == NULL)
-		return NULL;
+		return PyErr_NoMemory();
 
 	if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
 		PyMem_FREE(buffer);
@@ -923,32 +922,6 @@
 }
 
 static PyObject *
-int_oct(PyIntObject *v)
-{
-	char buf[100];
-	long x = v -> ob_ival;
-	if (x < 0)
-		PyOS_snprintf(buf, sizeof(buf), "-0%lo", -x);
-	else if (x == 0)
-		strcpy(buf, "0");
-	else
-		PyOS_snprintf(buf, sizeof(buf), "0%lo", x);
-	return PyString_FromString(buf);
-}
-
-static PyObject *
-int_hex(PyIntObject *v)
-{
-	char buf[100];
-	long x = v -> ob_ival;
-	if (x < 0)
-		PyOS_snprintf(buf, sizeof(buf), "-0x%lx", -x);
-	else
-		PyOS_snprintf(buf, sizeof(buf), "0x%lx", x);
-	return PyString_FromString(buf);
-}
-
-static PyObject *
 int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
 
 static PyObject *
@@ -1075,8 +1048,8 @@
 	(unaryfunc)int_int,	/*nb_int*/
 	(unaryfunc)int_long,	/*nb_long*/
 	(unaryfunc)int_float,	/*nb_float*/
-	(unaryfunc)int_oct,	/*nb_oct*/
-	(unaryfunc)int_hex, 	/*nb_hex*/
+	0,			/*nb_oct*/ /* not in use */
+	0, 			/*nb_hex*/ /* not in use */
 	0,			/*nb_inplace_add*/
 	0,			/*nb_inplace_subtract*/
 	0,			/*nb_inplace_multiply*/
@@ -1115,7 +1088,8 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+		Py_TPFLAGS_INT_SUBCLASS,	/* tp_flags */
 	int_doc,				/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */

Modified: python/branches/p3yk-noslice/Objects/listobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/listobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/listobject.c	Wed Jul 11 15:40:56 2007
@@ -2692,7 +2692,7 @@
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
 	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-		Py_TPFLAGS_BASETYPE,		/* tp_flags */
+		Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS,	/* tp_flags */
  	list_doc,				/* tp_doc */
  	(traverseproc)list_traverse,		/* tp_traverse */
  	(inquiry)list_clear,			/* tp_clear */

Modified: python/branches/p3yk-noslice/Objects/longobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/longobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/longobject.c	Wed Jul 11 15:40:56 2007
@@ -24,7 +24,7 @@
 int quick_int_allocs, quick_neg_int_allocs;
 #endif
 
-static inline PyObject *
+static PyObject *
 get_small_int(int ival)
 {
 	PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
@@ -80,7 +80,6 @@
 static PyLongObject *mul1(PyLongObject *, wdigit);
 static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
 static PyLongObject *divrem1(PyLongObject *, digit, digit *);
-static PyObject *long_format(PyObject *aa, int base);
 
 #define SIGCHECK(PyTryBlock) \
 	if (--_Py_Ticker < 0) { \
@@ -298,6 +297,7 @@
 	/* This version by Tim Peters */
 	register PyLongObject *v;
 	unsigned long x, prev;
+	long res;
 	Py_ssize_t i;
 	int sign;
 	int do_decref = 0; /* if nb_int was called */
@@ -326,46 +326,55 @@
 		}
 	}
 
+	res = -1;
 	v = (PyLongObject *)vv;
 	i = v->ob_size;
+
 	switch (i) {
-	case -1: return -v->ob_digit[0];
-	case 0: return 0;
-	case 1: return v->ob_digit[0];
-	}
-	sign = 1;
-	x = 0;
-	if (i < 0) {
-		sign = -1;
-		i = -(i);
-	}
-	while (--i >= 0) {
-		prev = x;
-		x = (x << SHIFT) + v->ob_digit[i];
-		if ((x >> SHIFT) != prev)
-			goto overflow;
+	case -1:
+		res = -v->ob_digit[0];
+		break;
+	case 0:
+		res = 0;
+		break;
+	case 1:
+		res = v->ob_digit[0];
+		break;
+	default:
+		sign = 1;
+		x = 0;
+		if (i < 0) {
+			sign = -1;
+			i = -(i);
+		}
+		while (--i >= 0) {
+			prev = x;
+			x = (x << SHIFT) + v->ob_digit[i];
+			if ((x >> SHIFT) != prev) {
+				PyErr_SetString(PyExc_OverflowError,
+					"Python int too large to convert to C long");
+				goto exit;
+			}
+		}
+		/* Haven't lost any bits, but casting to long requires extra care
+		 * (see comment above).
+	         */
+		if (x <= (unsigned long)LONG_MAX) {
+			res = (long)x * sign;
+		}
+		else if (sign < 0 && x == PY_ABS_LONG_MIN) {
+			res = LONG_MIN;
+		}
+		else {
+			PyErr_SetString(PyExc_OverflowError,
+				"Python int too large to convert to C long");
+		}	
 	}
+ exit:
 	if (do_decref) {
 		Py_DECREF(vv);
 	}
-	/* Haven't lost any bits, but casting to long requires extra care
-	 * (see comment above).
-         */
-	if (x <= (unsigned long)LONG_MAX) {
-		return (long)x * sign;
-	}
-	else if (sign < 0 && x == PY_ABS_LONG_MIN) {
-		return LONG_MIN;
-	}
-	/* else overflow */
-
- overflow:
-	if (do_decref) {
-		Py_DECREF(vv);
-	}
-	PyErr_SetString(PyExc_OverflowError,
-			"Python int too large to convert to C long");
-	return -1;
+	return res;
 }
 
 int
@@ -1374,7 +1383,7 @@
 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
    in pout, and returning the remainder.  pin and pout point at the LSD.
    It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
-   long_format, but that should be done with great care since longs are
+   _PyLong_Format, but that should be done with great care since longs are
    immutable. */
 
 static digit
@@ -1414,10 +1423,10 @@
 
 /* Convert a long int object to a string, using a given conversion base.
    Return a string object.
-   If base is 8 or 16, add the proper prefix '0' or '0x'. */
+   If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
 
-static PyObject *
-long_format(PyObject *aa, int base)
+PyObject *
+_PyLong_Format(PyObject *aa, int base)
 {
 	register PyLongObject *a = (PyLongObject *)aa;
 	PyStringObject *str;
@@ -1541,14 +1550,18 @@
 		Py_DECREF(scratch);
 	}
 
-	if (base == 8) {
-		if (size_a != 0)
-			*--p = '0';
-	}
-	else if (base == 16) {
+	if (base == 16) {
 		*--p = 'x';
 		*--p = '0';
 	}
+	else if (base == 8) {
+		*--p = 'o';
+		*--p = '0';
+	}
+	else if (base == 2) {
+		*--p = 'b';
+		*--p = '0';
+	}
 	else if (base != 10) {
 		*--p = '#';
 		*--p = '0' + base%10;
@@ -1665,9 +1678,9 @@
 PyObject *
 PyLong_FromString(char *str, char **pend, int base)
 {
-	int sign = 1;
+	int sign = 1, error_if_nonzero = 0;
 	char *start, *orig_str = str;
-	PyLongObject *z;
+	PyLongObject *z = NULL;
 	PyObject *strobj, *strrepr;
 	Py_ssize_t slen;
 
@@ -1691,10 +1704,21 @@
 			base = 10;
 		else if (str[1] == 'x' || str[1] == 'X')
 			base = 16;
-		else
+		else if (str[1] == 'o' || str[1] == 'O')
 			base = 8;
+		else if (str[1] == 'b' || str[1] == 'B')
+			base = 2;
+		else {
+			/* "old" (C-style) octal literal, now invalid.
+			   it might still be zero though */
+			error_if_nonzero = 1;
+			base = 10;
+		}
 	}
-	if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
+	if (str[0] == '0' &&
+	    ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
+	     (base == 8  && (str[1] == 'o' || str[1] == 'O')) ||
+	     (base == 2  && (str[1] == 'b' || str[1] == 'B'))))
 		str += 2;
 
 	start = str;
@@ -1898,6 +1922,15 @@
 	}
 	if (z == NULL)
 		return NULL;
+	if (error_if_nonzero) {
+		/* reset the base to 0, else the exception message
+		   doesn't make too much sense */
+		base = 0;
+		if (z->ob_size != 0)
+			goto onError;
+		/* there might still be other problems, therefore base
+		   remains zero here for the same reason */
+	}
 	if (str == start)
 		goto onError;
 	if (sign < 0)
@@ -1975,6 +2008,8 @@
 	     a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
 		/* |a| < |b|. */
 		*pdiv = (PyLongObject*)PyLong_FromLong(0);
+		if (*pdiv == NULL)
+			return -1;
 		Py_INCREF(a);
 		*prem = (PyLongObject *) a;
 		return 0;
@@ -1985,6 +2020,10 @@
 		if (z == NULL)
 			return -1;
 		*prem = (PyLongObject *) PyLong_FromLong((long)rem);
+		if (*prem == NULL) {
+			Py_DECREF(z);
+			return -1;
+		}
 	}
 	else {
 		z = x_divrem(a, b, prem);
@@ -2114,7 +2153,7 @@
 static PyObject *
 long_repr(PyObject *v)
 {
-	return long_format(v, 10);
+	return _PyLong_Format(v, 10);
 }
 
 static int
@@ -3473,18 +3512,6 @@
 }
 
 static PyObject *
-long_oct(PyObject *v)
-{
-	return long_format(v, 8);
-}
-
-static PyObject *
-long_hex(PyObject *v)
-{
-	return long_format(v, 16);
-}
-
-static PyObject *
 long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
 
 static PyObject *
@@ -3504,16 +3531,23 @@
 	if (base == -909)
 		return PyNumber_Long(x);
 	else if (PyString_Check(x)) {
-		char *s = PyString_AS_STRING(x);
-		char *end;
-		PyObject *r = PyLong_FromString(s, &end, base);
-		if (r != NULL && end != s + PyString_GET_SIZE(x)) {
-			PyErr_SetString(PyExc_ValueError,
-				"null byte in argument for int()");
-			Py_DECREF(r);
-			r = NULL;
+		/* 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)) {
+			/* create a repr() of the input string,
+			 * just like PyLong_FromString does. */
+			PyObject *srepr;
+			srepr = PyObject_Repr(x);
+			if (srepr == NULL)
+				return NULL;
+			PyErr_Format(PyExc_ValueError,
+			     "invalid literal for int() with base %d: %s",
+			     base, PyString_AS_STRING(srepr));
+			Py_DECREF(srepr);
+			return NULL;
 		}
-		return r;
+		return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
 	}
 #ifdef Py_USING_UNICODE
 	else if (PyUnicode_Check(x))
@@ -3601,8 +3635,8 @@
 			long_int,	/*nb_int*/
 			long_long,	/*nb_long*/
 			long_float,	/*nb_float*/
-			long_oct,	/*nb_oct*/
-			long_hex,	/*nb_hex*/
+			0,		/*nb_oct*/ /* not used */
+			0,		/*nb_hex*/ /* not used */
 	0,				/* nb_inplace_add */
 	0,				/* nb_inplace_subtract */
 	0,				/* nb_inplace_multiply */
@@ -3643,7 +3677,8 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+		Py_TPFLAGS_LONG_SUBCLASS,	/* tp_flags */
 	long_doc,				/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */

Modified: python/branches/p3yk-noslice/Objects/methodobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/methodobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/methodobject.c	Wed Jul 11 15:40:56 2007
@@ -158,11 +158,7 @@
 meth_get__self__(PyCFunctionObject *m, void *closure)
 {
 	PyObject *self;
-	if (PyEval_GetRestricted()) {
-		PyErr_SetString(PyExc_RuntimeError,
-			"method.__self__ not accessible in restricted mode");
-		return NULL;
-	}
+
 	self = m->m_self;
 	if (self == NULL)
 		self = Py_None;

Modified: python/branches/p3yk-noslice/Objects/object.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/object.c	(original)
+++ python/branches/p3yk-noslice/Objects/object.c	Wed Jul 11 15:40:56 2007
@@ -1284,6 +1284,8 @@
 	return x->ob_type->tp_call != NULL;
 }
 
+/* ------------------------- PyObject_Dir() helpers ------------------------- */
+
 /* Helper for PyObject_Dir.
    Merge the __dict__ of aclass into dict, and recursively also all
    the __dict__s of aclass's base classes.  The order of merging isn't
@@ -1343,158 +1345,185 @@
 	return 0;
 }
 
-/* Helper for PyObject_Dir.
-   If obj has an attr named attrname that's a list, merge its string
-   elements into keys of dict.
-   Return 0 on success, -1 on error.  Errors due to not finding the attr,
-   or the attr not being a list, are suppressed.
-*/
+/* Helper for PyObject_Dir without arguments: returns the local scope. */
+static PyObject *
+_dir_locals(void)
+{
+	PyObject *names;
+	PyObject *locals = PyEval_GetLocals();
 
-static int
-merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
+	if (locals == NULL) {
+		PyErr_SetString(PyExc_SystemError, "frame does not exist");
+		return NULL;
+	}
+
+	names = PyMapping_Keys(locals);
+	if (!names)
+		return NULL;
+	if (!PyList_Check(names)) {
+		PyErr_Format(PyExc_TypeError,
+			"dir(): expected keys() of locals to be a list, "
+			"not '%.200s'", names->ob_type->tp_name);
+		Py_DECREF(names);
+		return NULL;
+	}
+	/* the locals don't need to be DECREF'd */
+	return names;
+}
+
+/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
+   We deliberately don't suck up its __class__, as methods belonging to the 
+   metaclass would probably be more confusing than helpful. 
+*/
+static PyObject * 
+_specialized_dir_type(PyObject *obj)
 {
-	PyObject *list;
-	int result = 0;
+	PyObject *result = NULL;
+	PyObject *dict = PyDict_New();
 
-	assert(PyDict_Check(dict));
-	assert(obj);
-	assert(attrname);
+	if (dict != NULL && merge_class_dict(dict, obj) == 0)
+		result = PyDict_Keys(dict);
 
-	list = PyObject_GetAttrString(obj, attrname);
-	if (list == NULL)
-		PyErr_Clear();
+	Py_XDECREF(dict);
+	return result;
+}
 
-	else if (PyList_Check(list)) {
-		int i;
-		for (i = 0; i < PyList_GET_SIZE(list); ++i) {
-			PyObject *item = PyList_GET_ITEM(list, i);
-			if (PyString_Check(item)) {
-				result = PyDict_SetItem(dict, item, Py_None);
-				if (result < 0)
-					break;
-			}
+/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
+static PyObject *
+_specialized_dir_module(PyObject *obj)
+{
+	PyObject *result = NULL;
+	PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
+
+	if (dict != NULL) {
+		if (PyDict_Check(dict))
+			result = PyDict_Keys(dict);
+		else {
+			PyErr_Format(PyExc_TypeError,
+				     "%.200s.__dict__ is not a dictionary",
+				     PyModule_GetName(obj));
 		}
 	}
 
-	Py_XDECREF(list);
+	Py_XDECREF(dict);
 	return result;
 }
 
-/* Like __builtin__.dir(arg).  See bltinmodule.c's builtin_dir for the
-   docstring, which should be kept in synch with this implementation. */
-
-PyObject *
-PyObject_Dir(PyObject *arg)
+/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
+   and recursively up the __class__.__bases__ chain.
+*/
+static PyObject *
+_generic_dir(PyObject *obj)
 {
-	/* Set exactly one of these non-NULL before the end. */
-	PyObject *result = NULL;	/* result list */
-	PyObject *masterdict = NULL;	/* result is masterdict.keys() */
-
-	/* If NULL arg, return the locals. */
-	if (arg == NULL) {
-		PyObject *locals = PyEval_GetLocals();
-		if (locals == NULL)
-			goto error;
-		result = PyMapping_Keys(locals);
-		if (result == NULL)
-			goto error;
+	PyObject *result = NULL;
+	PyObject *dict = NULL;
+	PyObject *itsclass = NULL;
+	
+	/* Get __dict__ (which may or may not be a real dict...) */
+	dict = PyObject_GetAttrString(obj, "__dict__");
+	if (dict == NULL) {
+		PyErr_Clear();
+		dict = PyDict_New();
 	}
-
-	/* Elif this is some form of module, we only want its dict. */
-	else if (PyModule_Check(arg)) {
-		masterdict = PyObject_GetAttrString(arg, "__dict__");
-		if (masterdict == NULL)
-			goto error;
-		if (!PyDict_Check(masterdict)) {
-			PyErr_SetString(PyExc_TypeError,
-					"module.__dict__ is not a dictionary");
-			goto error;
-		}
+	else if (!PyDict_Check(dict)) {
+		Py_DECREF(dict);
+		dict = PyDict_New();
 	}
-
-	/* Elif some form of type or class, grab its dict and its bases.
-	   We deliberately don't suck up its __class__, as methods belonging
-	   to the metaclass would probably be more confusing than helpful. */
-	else if (PyType_Check(arg)) {
-		masterdict = PyDict_New();
-		if (masterdict == NULL)
-			goto error;
-		if (merge_class_dict(masterdict, arg) < 0)
-			goto error;
+	else {
+		/* Copy __dict__ to avoid mutating it. */
+		PyObject *temp = PyDict_Copy(dict);
+		Py_DECREF(dict);
+		dict = temp;
 	}
 
-	/* Else look at its dict, and the attrs reachable from its class. */
+	if (dict == NULL)
+		goto error;
+
+	/* Merge in attrs reachable from its class. */
+	itsclass = PyObject_GetAttrString(obj, "__class__");
+	if (itsclass == NULL)
+		/* XXX(tomer): Perhaps fall back to obj->ob_type if no
+		               __class__ exists? */
+		PyErr_Clear();
 	else {
-		PyObject *itsclass;
-		/* Create a dict to start with.  CAUTION:  Not everything
-		   responding to __dict__ returns a dict! */
-		masterdict = PyObject_GetAttrString(arg, "__dict__");
-		if (masterdict == NULL) {
-			PyErr_Clear();
-			masterdict = PyDict_New();
-		}
-		else if (!PyDict_Check(masterdict)) {
-			Py_DECREF(masterdict);
-			masterdict = PyDict_New();
-		}
-		else {
-			/* The object may have returned a reference to its
-			   dict, so copy it to avoid mutating it. */
-			PyObject *temp = PyDict_Copy(masterdict);
-			Py_DECREF(masterdict);
-			masterdict = temp;
-		}
-		if (masterdict == NULL)
+		if (merge_class_dict(dict, itsclass) != 0)
 			goto error;
+	}
 
-		/* Merge in __members__ and __methods__ (if any).
-		   XXX Would like this to go away someday; for now, it's
-		   XXX needed to get at im_self etc of method objects. */
-		if (merge_list_attr(masterdict, arg, "__members__") < 0)
-			goto error;
-		if (merge_list_attr(masterdict, arg, "__methods__") < 0)
-			goto error;
+	result = PyDict_Keys(dict);
+	/* fall through */
+error:
+	Py_XDECREF(itsclass);
+	Py_XDECREF(dict);
+	return result;
+}
 
-		/* Merge in attrs reachable from its class.
-		   CAUTION:  Not all objects have a __class__ attr. */
-		itsclass = PyObject_GetAttrString(arg, "__class__");
-		if (itsclass == NULL)
-			PyErr_Clear();
-		else {
-			int status = merge_class_dict(masterdict, itsclass);
-			Py_DECREF(itsclass);
-			if (status < 0)
-				goto error;
-		}
-	}
+/* Helper for PyObject_Dir: object introspection.
+   This calls one of the above specialized versions if no __dir__ method
+   exists. */
+static PyObject *
+_dir_object(PyObject *obj)
+{
+	PyObject * result = NULL;
+	PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
+						    "__dir__");
 
-	assert((result == NULL) ^ (masterdict == NULL));
-	if (masterdict != NULL) {
-		/* The result comes from its keys. */
-		assert(result == NULL);
-		result = PyDict_Keys(masterdict);
-		if (result == NULL)
-			goto error;
+	assert(obj);
+	if (dirfunc == NULL) {
+		/* use default implementation */
+		PyErr_Clear();
+		if (PyModule_Check(obj))
+			result = _specialized_dir_module(obj);
+		else if (PyType_Check(obj))
+			result = _specialized_dir_type(obj);
+		else
+			result = _generic_dir(obj);
 	}
+	else {
+		/* use __dir__ */
+		result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
+		Py_DECREF(dirfunc);
+		if (result == NULL)
+			return NULL;
 
-	assert(result);
-	if (!PyList_Check(result)) {
-		PyErr_Format(PyExc_TypeError,
-			"Expected keys() to be a list, not '%.200s'",
-			result->ob_type->tp_name);
-		goto error;
+		/* result must be a list */
+		/* XXX(gbrandl): could also check if all items are strings */
+		if (!PyList_Check(result)) {
+			PyErr_Format(PyExc_TypeError,
+				     "__dir__() must return a list, not %.200s",
+				     result->ob_type->tp_name);
+			Py_DECREF(result);
+			result = NULL;
+		}
 	}
-	if (PyList_Sort(result) != 0)
-		goto error;
+
+	return result;
+}
+
+/* Implementation of dir() -- if obj is NULL, returns the names in the current
+   (local) scope.  Otherwise, performs introspection of the object: returns a
+   sorted list of attribute names (supposedly) accessible from the object
+*/
+PyObject *
+PyObject_Dir(PyObject *obj)
+{
+	PyObject * result;
+
+	if (obj == NULL)
+		/* no object -- introspect the locals */
+		result = _dir_locals();
 	else
-		goto normal_return;
+		/* object -- introspect the object */
+		result = _dir_object(obj);
 
-  error:
-	Py_XDECREF(result);
-	result = NULL;
-	/* fall through */
-  normal_return:
-  	Py_XDECREF(masterdict);
+	assert(result == NULL || PyList_Check(result));
+
+	if (result != NULL && PyList_Sort(result) != 0) {
+		/* sorting the list failed */
+		Py_DECREF(result);
+		result = NULL;
+	}
+	
 	return result;
 }
 
@@ -1863,4 +1892,3 @@
 #ifdef __cplusplus
 }
 #endif
-

Modified: python/branches/p3yk-noslice/Objects/rangeobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/rangeobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/rangeobject.c	Wed Jul 11 15:40:56 2007
@@ -2,139 +2,292 @@
 
 #include "Python.h"
 
+/* Support objects whose length is > PY_SSIZE_T_MAX.
+
+   This could be sped up for small PyLongs if they fit in an Py_ssize_t.
+   This only matters on Win64.  Though we could use PY_LONG_LONG which
+   would presumably help perf.
+*/
+
 typedef struct {
-	PyObject_HEAD
-	long	start;
-	long	step;
-	long	len;
+    PyObject_HEAD
+    PyObject *start;
+    PyObject *stop;
+    PyObject *step;
 } rangeobject;
 
-/* Return number of items in range/xrange (lo, hi, step).  step > 0
- * required.  Return a value < 0 if & only if the true value is too
- * large to fit in a signed long.
- */
-static long
-get_len_of_range(long lo, long hi, long step)
+/* Helper function for validating step.  Always returns a new reference or
+   NULL on error. 
+*/
+static PyObject *
+validate_step(PyObject *step)
 {
-	/* -------------------------------------------------------------
-	If lo >= hi, the range is empty.
-	Else if n values are in the range, the last one is
-	lo + (n-1)*step, which must be <= hi-1.  Rearranging,
-	n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
-	the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
-	the RHS is non-negative and so truncation is the same as the
-	floor.  Letting M be the largest positive long, the worst case
-	for the RHS numerator is hi=M, lo=-M-1, and then
-	hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
-	precision to compute the RHS exactly.
-	---------------------------------------------------------------*/
-	long n = 0;
-	if (lo < hi) {
-		unsigned long uhi = (unsigned long)hi;
-		unsigned long ulo = (unsigned long)lo;
-		unsigned long diff = uhi - ulo - 1;
-		n = (long)(diff / (unsigned long)step + 1);
-	}
-	return n;
+    /* No step specified, use a step of 1. */
+    if (!step)
+        return PyInt_FromLong(1);
+
+    step = PyNumber_Index(step);
+    if (step) {
+        Py_ssize_t istep = PyNumber_AsSsize_t(step, NULL);
+        if (istep == -1 && PyErr_Occurred()) {
+            /* Ignore OverflowError, we know the value isn't 0. */
+            PyErr_Clear();
+        }
+        else if (istep == 0) {
+            PyErr_SetString(PyExc_ValueError,
+                            "range() arg 3 must not be zero");
+            Py_CLEAR(step);
+        }
+    }
+
+    return step;
 }
 
+/* XXX(nnorwitz): should we error check if the user passes any empty ranges?
+   range(-10)
+   range(0, -5)
+   range(0, 5, -1)
+*/
 static PyObject *
 range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
 {
-	rangeobject *obj;
-	long ilow = 0, ihigh = 0, istep = 1;
-	long n;
-
-	if (!_PyArg_NoKeywords("xrange()", kw))
-		return NULL;
-
-	if (PyTuple_Size(args) <= 1) {
-		if (!PyArg_ParseTuple(args,
-				"l;xrange() requires 1-3 int arguments",
-				&ihigh))
-			return NULL;
-	}
-	else {
-		if (!PyArg_ParseTuple(args,
-				"ll|l;xrange() requires 1-3 int arguments",
-				&ilow, &ihigh, &istep))
-			return NULL;
-	}
-	if (istep == 0) {
-		PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
-		return NULL;
-	}
-	if (istep > 0)
-		n = get_len_of_range(ilow, ihigh, istep);
-	else
-		n = get_len_of_range(ihigh, ilow, -istep);
-	if (n < 0) {
-		PyErr_SetString(PyExc_OverflowError,
-				"xrange() result has too many items");
-		return NULL;
-	}
-
-	obj = PyObject_New(rangeobject, &PyRange_Type);
-	if (obj == NULL)
-		return NULL;
-	obj->start = ilow;
-	obj->len   = n;
-	obj->step  = istep;
-	return (PyObject *) obj;
+    rangeobject *obj = NULL;
+    PyObject *start = NULL, *stop = NULL, *step = NULL;
+
+    if (!_PyArg_NoKeywords("range()", kw))
+        return NULL;
+
+    if (PyTuple_Size(args) <= 1) {
+        if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop))
+            goto Fail;
+        stop = PyNumber_Index(stop);
+        if (!stop)
+            goto Fail;
+        start = PyInt_FromLong(0);
+        step = PyInt_FromLong(1);
+        if (!start || !step)
+            goto Fail;
+    }
+    else {
+        if (!PyArg_UnpackTuple(args, "range", 2, 3,
+                               &start, &stop, &step))
+            goto Fail;
+
+        /* Convert borrowed refs to owned refs */
+        start = PyNumber_Index(start);
+        stop = PyNumber_Index(stop);
+        step = validate_step(step);
+        if (!start || !stop || !step)
+            goto Fail;
+    }
+
+    obj = PyObject_New(rangeobject, &PyRange_Type);
+    if (obj == NULL)
+        goto Fail;
+    obj->start = start;
+    obj->stop = stop;
+    obj->step = step;
+    return (PyObject *) obj;
+
+Fail:
+    Py_XDECREF(start);
+    Py_XDECREF(stop);
+    Py_XDECREF(step);
+    return NULL;
 }
 
 PyDoc_STRVAR(range_doc,
-"xrange([start,] stop[, step]) -> xrange object\n\
+"range([start,] stop[, step]) -> range object\n\
 \n\
-Like range(), but instead of returning a list, returns an object that\n\
-generates the numbers in the range on demand.  For looping, this is \n\
-slightly faster than range() and more memory efficient.");
+Returns an iterator that generates the numbers in the range on demand.");
 
-static PyObject *
-range_item(rangeobject *r, Py_ssize_t i)
+static void
+range_dealloc(rangeobject *r)
+{
+    Py_DECREF(r->start);
+    Py_DECREF(r->stop);
+    Py_DECREF(r->step);
+}
+
+/* Return number of items in range (lo, hi, step), when arguments are
+ * PyInt or PyLong objects.  step > 0 required.  Return a value < 0 if
+ * & only if the true value is too large to fit in a signed long.
+ * Arguments MUST return 1 with either PyInt_Check() or
+ * PyLong_Check().  Return -1 when there is an error.
+ */
+static PyObject*
+range_length_obj(rangeobject *r)
 {
-	if (i < 0 || i >= r->len) {
-		PyErr_SetString(PyExc_IndexError,
-				"xrange object index out of range");
-		return NULL;
-	}
-	return PyInt_FromSsize_t(r->start + (i % r->len) * r->step);
+    /* -------------------------------------------------------------
+    Algorithm is equal to that of get_len_of_range(), but it operates
+    on PyObjects (which are assumed to be PyLong or PyInt objects).
+    ---------------------------------------------------------------*/
+    int cmp_result, cmp_call;
+    PyObject *lo, *hi;
+    PyObject *step = NULL;
+    PyObject *diff = NULL;
+    PyObject *one = NULL;
+    PyObject *tmp1 = NULL, *tmp2 = NULL, *result;
+                /* holds sub-expression evaluations */
+
+    PyObject *zero = PyLong_FromLong(0);
+    if (zero == NULL)
+        return NULL;
+    cmp_call = PyObject_Cmp(r->step, zero, &cmp_result);
+    Py_DECREF(zero);
+    if (cmp_call == -1)
+        return NULL;
+
+    assert(cmp_result != 0);
+    if (cmp_result > 0) {
+        lo = r->start;
+        hi = r->stop;
+        step = r->step;
+        Py_INCREF(step);
+    } else {
+        lo = r->stop;
+        hi = r->start;
+        step = PyNumber_Negative(r->step);
+        if (!step)
+            return NULL;
+    }
+
+    /* if (lo >= hi), return length of 0. */
+    if (PyObject_Compare(lo, hi) >= 0) {
+        Py_XDECREF(step);
+        return PyLong_FromLong(0);
+    }
+
+    if ((one = PyLong_FromLong(1L)) == NULL)
+        goto Fail;
+
+    if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
+        goto Fail;
+
+    if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
+        goto Fail;
+
+    if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
+        goto Fail;
+
+    if ((result = PyNumber_Add(tmp2, one)) == NULL)
+        goto Fail;
+
+    Py_DECREF(tmp2);
+    Py_DECREF(diff);
+    Py_DECREF(step);
+    Py_DECREF(tmp1);
+    Py_DECREF(one);
+    return result;
+
+  Fail:
+    Py_XDECREF(tmp2);
+    Py_XDECREF(diff);
+    Py_XDECREF(step);
+    Py_XDECREF(tmp1);
+    Py_XDECREF(one);
+    return NULL;
 }
 
 static Py_ssize_t
 range_length(rangeobject *r)
 {
-	return (Py_ssize_t)(r->len);
+    PyObject *len = range_length_obj(r);
+    Py_ssize_t result = -1;
+    if (len) {
+        result = PyLong_AsSsize_t(len);
+        Py_DECREF(len);
+    }
+    return result;
 }
 
+/* range(...)[x] is necessary for:  seq[:] = range(...) */
+
 static PyObject *
-range_repr(rangeobject *r)
+range_item(rangeobject *r, Py_ssize_t i)
 {
-	PyObject *rtn;
+    Py_ssize_t len = range_length(r);
+    PyObject *rem, *incr, *result;
 
-	if (r->start == 0 && r->step == 1)
-		rtn = PyString_FromFormat("xrange(%ld)",
-					  r->start + r->len * r->step);
-
-	else if (r->step == 1)
-		rtn = PyString_FromFormat("xrange(%ld, %ld)",
-					  r->start,
-					  r->start + r->len * r->step);
-
-	else
-		rtn = PyString_FromFormat("xrange(%ld, %ld, %ld)",
-					  r->start,
-					  r->start + r->len * r->step,
-					  r->step);
-	return rtn;
+    /* XXX(nnorwitz): should negative indices be supported? */
+    /* XXX(nnorwitz): should support range[x] where x > PY_SSIZE_T_MAX? */
+    if (i < 0 || i >= len) {
+        if (!PyErr_Occurred())
+            PyErr_SetString(PyExc_IndexError,
+                            "xrange object index out of range");
+            return NULL;
+        }
+
+    /* XXX(nnorwitz): optimize for short ints. */
+    rem = PyLong_FromSsize_t(i % len);
+    if (!rem)
+        return NULL;
+    incr = PyNumber_Multiply(rem, r->step);
+    Py_DECREF(rem);
+    if (!incr)
+        return NULL;
+    result = PyNumber_Add(r->start, incr);
+    Py_DECREF(incr);
+    return result;
+}
+
+static PyObject *
+range_repr(rangeobject *r)
+{
+    PyObject *start_str = NULL, *stop_str = NULL, *step_str = NULL;
+    PyObject *result = NULL;
+    Py_ssize_t istart, istep;
+
+    /* We always need the stop value. */
+    stop_str = PyObject_Str(r->stop);
+    if (!stop_str)
+        return NULL;
+
+    /* XXX(nnorwitz): should we use PyObject_Repr instead of str? */
+
+    /* Check for special case values for printing.  We don't always
+       need the start or step values.  We don't care about errors
+       (it means overflow), so clear the errors. */
+    istart = PyNumber_AsSsize_t(r->start, NULL);
+    if (istart != 0 || (istart == -1 && PyErr_Occurred())) {
+        PyErr_Clear();
+        start_str = PyObject_Str(r->start);
+    }
+
+    istep = PyNumber_AsSsize_t(r->step, NULL);
+    if (istep != 1 || (istep == -1 && PyErr_Occurred())) {
+        PyErr_Clear();
+        step_str = PyObject_Str(r->step);
+    }
+
+    if (istart == 0 && istep == 1)
+        result = PyString_FromFormat("range(%s)",
+                                     PyString_AS_STRING(stop_str));
+    else if (istep == 1) {
+        if (start_str)
+            result = PyString_FromFormat("range(%s, %s)",
+                                         PyString_AS_STRING(start_str),
+                                         PyString_AS_STRING(stop_str));
+    }
+    else if (start_str && step_str)
+        result = PyString_FromFormat("range(%s, %s, %s)",
+                                     PyString_AS_STRING(start_str),
+                                     PyString_AS_STRING(stop_str),
+                                     PyString_AS_STRING(step_str));
+    /* else result is NULL and an error should already be set. */
+
+    Py_XDECREF(start_str);
+    Py_XDECREF(stop_str);
+    Py_XDECREF(step_str);
+    return result;
 }
 
 static PySequenceMethods range_as_sequence = {
-	(lenfunc)range_length,	/* sq_length */
-	0,			/* sq_concat */
-	0,			/* sq_repeat */
-	(ssizeargfunc)range_item, /* sq_item */
-	0,			/* sq_slice */
+    (lenfunc)range_length,	/* sq_length */
+    0,			/* sq_concat */
+    0,			/* sq_repeat */
+    (ssizeargfunc)range_item, /* sq_item */
+    0,			/* sq_slice */
 };
 
 static PyObject * range_iter(PyObject *seq);
@@ -144,17 +297,18 @@
 "Returns a reverse iterator.");
 
 static PyMethodDef range_methods[] = {
-	{"__reversed__",	(PyCFunction)range_reverse, METH_NOARGS, reverse_doc},
- 	{NULL,		NULL}		/* sentinel */
+    {"__reversed__",	(PyCFunction)range_reverse, METH_NOARGS,
+	reverse_doc},
+    {NULL,		NULL}		/* sentinel */
 };
 
 PyTypeObject PyRange_Type = {
 	PyObject_HEAD_INIT(&PyType_Type)
 	0,			/* Number of items for varobject */
-	"xrange",		/* Name of this type */
+	"range",		/* Name of this type */
 	sizeof(rangeobject),	/* Basic object size */
 	0,			/* Item size for varobject */
-	(destructor)PyObject_Del, /* tp_dealloc */
+	(destructor)range_dealloc, /* tp_dealloc */
 	0,			/* tp_print */
 	0,			/* tp_getattr */
 	0,			/* tp_setattr */
@@ -192,6 +346,11 @@
 
 /*********************** Xrange Iterator **************************/
 
+/* There are 2 types of iterators, one for C longs, the other for
+   Python longs (ie, PyObjects).  This should make iteration fast
+   in the normal case, but possible for any numeric value.
+*/
+
 typedef struct {
 	PyObject_HEAD
 	long	index;
@@ -203,25 +362,43 @@
 static PyObject *
 rangeiter_next(rangeiterobject *r)
 {
-	if (r->index < r->len)
-		return PyInt_FromLong(r->start + (r->index++) * r->step);
-	return NULL;
+    if (r->index < r->len)
+        return PyInt_FromLong(r->start + (r->index++) * r->step);
+    return NULL;
 }
 
 static PyObject *
 rangeiter_len(rangeiterobject *r)
 {
-	return PyInt_FromLong(r->len - r->index);
+    return PyInt_FromLong(r->len - r->index);
 }
 
-PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
+typedef struct {
+    PyObject_HEAD
+    PyObject *index;
+    PyObject *start;
+    PyObject *step;
+    PyObject *len;
+} longrangeiterobject;
+
+static PyObject *
+longrangeiter_len(longrangeiterobject *r, PyObject *no_args)
+{
+    return PyNumber_Subtract(r->len, r->index);
+}
+
+static PyObject *rangeiter_new(PyTypeObject *, PyObject *args, PyObject *kw);
+
+PyDoc_STRVAR(length_hint_doc,
+             "Private method returning an estimate of len(list(it)).");
 
 static PyMethodDef rangeiter_methods[] = {
-	{"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, length_hint_doc},
- 	{NULL,		NULL}		/* sentinel */
+    {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS,
+	length_hint_doc},
+    {NULL,		NULL}		/* sentinel */
 };
 
-static PyTypeObject Pyrangeiter_Type = {
+PyTypeObject Pyrangeiter_Type = {
 	PyObject_HEAD_INIT(&PyType_Type)
 	0,                                      /* ob_size */
 	"rangeiterator",                        /* tp_name */
@@ -252,50 +429,283 @@
 	PyObject_SelfIter,			/* tp_iter */
 	(iternextfunc)rangeiter_next,		/* tp_iternext */
 	rangeiter_methods,			/* tp_methods */
-	0,
+	0,					/* tp_members */
+	0,					/* tp_getset */
+	0,					/* tp_base */
+	0,					/* tp_dict */
+	0,					/* tp_descr_get */
+	0,					/* tp_descr_set */
+	0,					/* tp_dictoffset */
+	0,					/* tp_init */
+	0,					/* tp_alloc */
+	rangeiter_new,				/* tp_new */
 };
 
+/* Return number of items in range/xrange (lo, hi, step).  step > 0
+ * required.  Return a value < 0 if & only if the true value is too
+ * large to fit in a signed long.
+ */
+static long
+get_len_of_range(long lo, long hi, long step)
+{
+    /* -------------------------------------------------------------
+    If lo >= hi, the range is empty.
+    Else if n values are in the range, the last one is
+    lo + (n-1)*step, which must be <= hi-1.  Rearranging,
+    n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
+    the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
+    the RHS is non-negative and so truncation is the same as the
+    floor.  Letting M be the largest positive long, the worst case
+    for the RHS numerator is hi=M, lo=-M-1, and then
+    hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
+    precision to compute the RHS exactly.
+    ---------------------------------------------------------------*/
+    long n = 0;
+    if (lo < hi) {
+        unsigned long uhi = (unsigned long)hi;
+        unsigned long ulo = (unsigned long)lo;
+        unsigned long diff = uhi - ulo - 1;
+        n = (long)(diff / (unsigned long)step + 1);
+    }
+    return n;
+}
+
 static PyObject *
-range_iter(PyObject *seq)
+int_range_iter(long start, long stop, long step)
 {
-	rangeiterobject *it;
+    rangeiterobject *it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
+    if (it == NULL)
+        return NULL;
+    it->start = start;
+    it->step = step;
+    if (step > 0)
+        it->len = get_len_of_range(start, stop, step);
+    else
+        it->len = get_len_of_range(stop, start, -step);
+    it->index = 0;
+    return (PyObject *)it;
+}
 
-	if (!PyRange_Check(seq)) {
-		PyErr_BadInternalCall();
-		return NULL;
-	}
-	it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
-	if (it == NULL)
-		return NULL;
-	it->index = 0;
-	it->start = ((rangeobject *)seq)->start;
-	it->step = ((rangeobject *)seq)->step;
-	it->len = ((rangeobject *)seq)->len;
-	return (PyObject *)it;
+static PyObject *
+rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw)
+{
+    long start, stop, step;
+
+    if (!_PyArg_NoKeywords("rangeiter()", kw))
+        return NULL;
+
+    if (!PyArg_ParseTuple(args, "lll;rangeiter() requires 3 int arguments",
+                          &start, &stop, &step))
+        return NULL;
+
+    return int_range_iter(start, stop, step);
+}
+
+static PyMethodDef longrangeiter_methods[] = {
+    {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS,
+	length_hint_doc},
+    {NULL,		NULL}		/* sentinel */
+};
+
+static void
+longrangeiter_dealloc(longrangeiterobject *r)
+{
+    Py_XDECREF(r->index);
+    Py_XDECREF(r->start);
+    Py_XDECREF(r->step);
+    Py_XDECREF(r->len);
 }
 
 static PyObject *
-range_reverse(PyObject *seq)
+longrangeiter_next(longrangeiterobject *r)
 {
-	rangeiterobject *it;
-	long start, step, len;
+    PyObject *one, *product, *new_index, *result;
+    if (PyObject_RichCompareBool(r->index, r->len, Py_LT) != 1)
+        return NULL;
+
+    one = PyLong_FromLong(1);
+    if (!one)
+        return NULL;
+
+    product = PyNumber_Multiply(r->index, r->step);
+    if (!product) {
+        Py_DECREF(one);
+        return NULL;
+    }
+
+    new_index = PyNumber_Add(r->index, one);
+    Py_DECREF(one);
+    if (!new_index) {
+        Py_DECREF(product);
+        return NULL;
+    }
+
+    result = PyNumber_Add(r->start, product);
+    Py_DECREF(product);
+    if (result) {
+        Py_DECREF(r->index);
+        r->index = new_index;
+    }
 
-	if (!PyRange_Check(seq)) {
-		PyErr_BadInternalCall();
-		return NULL;
-	}
-	it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
-	if (it == NULL)
-		return NULL;
-
-	start = ((rangeobject *)seq)->start;
-	step = ((rangeobject *)seq)->step;
-	len = ((rangeobject *)seq)->len;
-
-	it->index = 0;
-	it->start = start + (len-1) * step;
-	it->step = -step;
-	it->len = len;
+    return result;
+}
 
-	return (PyObject *)it;
+static PyTypeObject Pylongrangeiter_Type = {
+	PyObject_HEAD_INIT(&PyType_Type)
+	0,                                      /* ob_size */
+	"rangeiterator",                        /* tp_name */
+	sizeof(longrangeiterobject),            /* tp_basicsize */
+	0,                                      /* tp_itemsize */
+	/* methods */
+	(destructor)longrangeiter_dealloc,	/* tp_dealloc */
+	0,                                      /* tp_print */
+	0,                                      /* tp_getattr */
+	0,                                      /* tp_setattr */
+	0,                                      /* tp_compare */
+	0,                                      /* tp_repr */
+	0,                                      /* tp_as_number */
+	0,					/* tp_as_sequence */
+	0,                                      /* tp_as_mapping */
+	0,                                      /* tp_hash */
+	0,                                      /* tp_call */
+	0,                                      /* tp_str */
+	PyObject_GenericGetAttr,                /* tp_getattro */
+	0,                                      /* tp_setattro */
+	0,                                      /* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	0,                                      /* tp_doc */
+	0,					/* tp_traverse */
+	0,                                      /* tp_clear */
+	0,                                      /* tp_richcompare */
+	0,                                      /* tp_weaklistoffset */
+	PyObject_SelfIter,			/* tp_iter */
+	(iternextfunc)longrangeiter_next,	/* tp_iternext */
+	longrangeiter_methods,			/* tp_methods */
+	0,
+};
+
+static PyObject *
+range_iter(PyObject *seq)
+{
+    rangeobject *r = (rangeobject *)seq;
+    longrangeiterobject *it;
+    PyObject *tmp, *len;
+
+    assert(PyRange_Check(seq));
+    if (_PyLong_FitsInLong(r->start) &&
+        _PyLong_FitsInLong(r->stop) &&
+        _PyLong_FitsInLong(r->step))
+        return int_range_iter(PyLong_AsLong(r->start),
+                      PyLong_AsLong(r->stop),
+                      PyLong_AsLong(r->step));
+
+    it = PyObject_New(longrangeiterobject, &Pylongrangeiter_Type);
+    if (it == NULL)
+        return NULL;
+
+    /* Do all initialization here, so we can DECREF on failure. */
+    it->start = r->start;
+    it->step = r->step;
+    Py_INCREF(it->start);
+    Py_INCREF(it->step);
+
+    it->len = it->index = NULL;
+
+    /* Calculate length: (r->stop - r->start) / r->step */
+    tmp = PyNumber_Subtract(r->stop, r->start);
+    if (!tmp)
+        goto create_failure;
+    len = PyNumber_FloorDivide(tmp, r->step);
+    Py_DECREF(tmp);
+    if (!len)
+        goto create_failure;
+    it->len = len;
+    it->index = PyLong_FromLong(0);
+    if (!it->index)
+        goto create_failure;
+
+    return (PyObject *)it;
+
+create_failure:
+    Py_DECREF(it);
+    return NULL;
+}
+
+static PyObject *
+range_reverse(PyObject *seq)
+{
+    rangeobject *range = (rangeobject*) seq;
+    longrangeiterobject *it;
+    PyObject *one, *sum, *diff, *len = NULL, *product;
+
+    /* XXX(nnorwitz): do the calc for the new start/stop first,
+        then if they fit, call the proper iter()?
+    */
+    assert(PyRange_Check(seq));
+    if (_PyLong_FitsInLong(range->start) &&
+        _PyLong_FitsInLong(range->stop) &&
+        _PyLong_FitsInLong(range->step)) {
+        long start = PyLong_AsLong(range->start);
+        long step = PyLong_AsLong(range->step);
+        long stop = PyLong_AsLong(range->stop);
+        /* XXX(nnorwitz): need to check for overflow and simplify. */
+        long len = get_len_of_range(start, stop, step);
+        long new_start = start + (len - 1) * step;
+        long new_stop = start;
+        if (step > 0)
+            new_stop -= 1;
+        else
+            new_stop += 1;
+        return int_range_iter(new_start, new_stop, -step);
+    }
+
+    it = PyObject_New(longrangeiterobject, &Pylongrangeiter_Type);
+    if (it == NULL)
+        return NULL;
+
+    /* start + (len - 1) * step */
+    len = range_length_obj(range);
+    if (!len)
+        goto create_failure;
+
+    one = PyLong_FromLong(1);
+    if (!one)
+        goto create_failure;
+
+    diff = PyNumber_Subtract(len, one);
+    Py_DECREF(one);
+    if (!diff)
+        goto create_failure;
+
+    product = PyNumber_Multiply(len, range->step);
+    if (!product)
+        goto create_failure;
+
+    sum = PyNumber_Add(range->start, product);
+    Py_DECREF(product);
+    it->start = sum;
+    if (!it->start)
+        goto create_failure;
+    it->step = PyNumber_Negative(range->step);
+    if (!it->step) {
+        Py_DECREF(it->start);
+        PyObject_Del(it);
+        return NULL;
+    }
+
+    /* Steal reference to len. */
+    it->len = len;
+
+    it->index = PyLong_FromLong(0);
+    if (!it->index) {
+        Py_DECREF(it);
+        return NULL;
+    }
+
+    return (PyObject *)it;
+
+create_failure:
+    Py_XDECREF(len);
+    PyObject_Del(it);
+    return NULL;
 }

Modified: python/branches/p3yk-noslice/Objects/setobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/setobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/setobject.c	Wed Jul 11 15:40:56 2007
@@ -2154,7 +2154,7 @@
 }
 
 int
-_PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **entry)
+_PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key)
 {
 	setentry *entry_ptr;
 
@@ -2164,7 +2164,23 @@
 	}
 	if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
 		return 0;
-	*entry = entry_ptr->key;
+	*key = entry_ptr->key;
+	return 1;
+}
+
+int
+_PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash)
+{
+	setentry *entry;
+
+	if (!PyAnySet_Check(set)) {
+		PyErr_BadInternalCall();
+		return -1;
+	}
+	if (set_next((PySetObject *)set, pos, &entry) == 0)
+		return 0;
+	*key = entry->key;
+	*hash = entry->hash;
 	return 1;
 }
 
@@ -2206,7 +2222,7 @@
 	Py_ssize_t count;
 	char *s;
 	Py_ssize_t i;
-	PyObject *elem, *dup, *t, *f, *dup2;
+	PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
 	PyObject *ob = (PyObject *)so;
 
 	/* Verify preconditions and exercise type/size checks */
@@ -2252,8 +2268,8 @@
 
 	/* Exercise direct iteration */
 	i = 0, count = 0;
-	while (_PySet_Next((PyObject *)dup, &i, &elem)) {
-		s = PyString_AsString(elem);
+	while (_PySet_Next((PyObject *)dup, &i, &x)) {
+		s = PyString_AsString(x);
 		assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
 		count++;
 	}

Modified: python/branches/p3yk-noslice/Objects/sliceobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/sliceobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/sliceobject.c	Wed Jul 11 15:40:56 2007
@@ -274,9 +274,19 @@
 S. Out of bounds indices are clipped in a manner consistent with the\n\
 handling of normal slices.");
 
+static PyObject *
+slice_reduce(PySliceObject* self)
+{
+	return Py_BuildValue("O(OOO)", self->ob_type, self->start, self->stop, self->step);
+}
+
+PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
+
 static PyMethodDef slice_methods[] = {
 	{"indices",	(PyCFunction)slice_indices,
 	 METH_O,	slice_indices_doc},
+	{"__reduce__",	(PyCFunction)slice_reduce,
+	 METH_NOARGS,	reduce_doc},
 	{NULL, NULL}
 };
 

Modified: python/branches/p3yk-noslice/Objects/stringobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/stringobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/stringobject.c	Wed Jul 11 15:40:56 2007
@@ -948,6 +948,8 @@
 		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",
 			     bb->ob_type->tp_name);
@@ -1108,8 +1110,7 @@
 		   much time, since Py_NE is rarely used.  */
 		if (a->ob_size == b->ob_size
 		    && (a->ob_sval[0] == b->ob_sval[0]
-			&& memcmp(a->ob_sval, b->ob_sval,
-				  a->ob_size) == 0)) {
+			&& memcmp(a->ob_sval, b->ob_sval, a->ob_size) == 0)) {
 			result = Py_True;
 		} else {
 			result = Py_False;
@@ -1122,7 +1123,7 @@
 		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
+	} else
 		c = 0;
 	if (c == 0)
 		c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
@@ -2333,10 +2334,10 @@
 string_translate(PyStringObject *self, PyObject *args)
 {
 	register char *input, *output;
-	register const char *table;
+	const char *table;
 	register Py_ssize_t i, c, changed = 0;
 	PyObject *input_obj = (PyObject*)self;
-	const char *table1, *output_start, *del_table=NULL;
+	const char *output_start, *del_table=NULL;
 	Py_ssize_t inlen, tablen, dellen = 0;
 	PyObject *result;
 	int trans_table[256];
@@ -2347,9 +2348,13 @@
 		return NULL;
 
 	if (PyString_Check(tableobj)) {
-		table1 = PyString_AS_STRING(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
@@ -2363,7 +2368,7 @@
 		return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
 	}
 #endif
-	else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen))
+	else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
 		return NULL;
 
 	if (tablen != 256) {
@@ -2392,7 +2397,6 @@
 		dellen = 0;
 	}
 
-	table = table1;
 	inlen = PyString_GET_SIZE(input_obj);
 	result = PyString_FromStringAndSize((char *)NULL, inlen);
 	if (result == NULL)
@@ -2400,7 +2404,7 @@
 	output_start = output = PyString_AsString(result);
 	input = PyString_AS_STRING(input_obj);
 
-	if (dellen == 0) {
+	if (dellen == 0 && table != NULL) {
 		/* If no deletions are required, use faster code */
 		for (i = inlen; --i >= 0; ) {
 			c = Py_CHARMASK(*input++);
@@ -2414,8 +2418,13 @@
 		return input_obj;
 	}
 
-	for (i = 0; i < 256; i++)
-		trans_table[i] = Py_CHARMASK(table[i]);
+	if (table == NULL) {
+		for (i = 0; i < 256; i++)
+			trans_table[i] = Py_CHARMASK(i);
+	} else {
+		for (i = 0; i < 256; i++)
+			trans_table[i] = Py_CHARMASK(table[i]);
+	}
 
 	for (i = 0; i < dellen; i++)
 		trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
@@ -3288,7 +3297,7 @@
 {
     const char *e, *p;
     char *q;
-    Py_ssize_t i, j;
+    Py_ssize_t i, j, old_j;
     PyObject *u;
     int tabsize = 8;
 
@@ -3296,21 +3305,38 @@
 	return NULL;
 
     /* First pass: determine size of output string */
-    i = j = 0;
+    i = j = old_j = 0;
     e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
     for (p = PyString_AS_STRING(self); p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0)
+	    if (tabsize > 0) {
 		j += tabsize - (j % tabsize);
+		if (old_j > j) {
+		    PyErr_SetString(PyExc_OverflowError,
+				    "new string is too long");
+		    return NULL;
+		}
+		old_j = j;
+            }
 	}
         else {
             j++;
             if (*p == '\n' || *p == '\r') {
                 i += j;
-                j = 0;
+                old_j = j = 0;
+                if (i < 0) {
+                    PyErr_SetString(PyExc_OverflowError,
+                                    "new string is too long");
+                    return NULL;
+                }
             }
         }
 
+    if ((i + j) < 0) {
+        PyErr_SetString(PyExc_OverflowError, "new string is too long");
+        return NULL;
+    }
+
     /* Second pass: create output string and fill it */
     u = PyString_FromStringAndSize(NULL, i + j);
     if (!u)
@@ -3813,8 +3839,6 @@
 
 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__},
@@ -4006,7 +4030,8 @@
 	PyObject_GenericGetAttr,		/* tp_getattro */
 	0,					/* tp_setattro */
 	&string_as_buffer,			/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+		Py_TPFLAGS_STRING_SUBCLASS,	/* tp_flags */
 	string_doc,				/* tp_doc */
 	0,					/* tp_traverse */
 	0,					/* tp_clear */
@@ -4223,12 +4248,13 @@
 		result = val->ob_type->tp_str(val);
 		break;
 	case 'o':
-		result = val->ob_type->tp_as_number->nb_oct(val);
+		numnondigits = 2;
+		result = PyNumber_ToBase(val, 8);
 		break;
 	case 'x':
 	case 'X':
 		numnondigits = 2;
-		result = val->ob_type->tp_as_number->nb_hex(val);
+		result = PyNumber_ToBase(val, 16);
 		break;
 	default:
 		assert(!"'type' not in [duoxX]");
@@ -4263,32 +4289,16 @@
 	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] = '-';
-		}
+	if (((flags & F_ALT) == 0 &&
+	    (type == 'o' || type == 'x' || type == 'X'))) {
+		assert(buf[sign] == '0');
+		assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
+                       buf[sign+1] == 'o');
+		numnondigits -= 2;
+		buf += 2;
+		len -= 2;
+		if (sign)
+			buf[0] = '-';
 		assert(len == numnondigits + numdigits);
 		assert(numdigits > 0);
 	}
@@ -4357,9 +4367,10 @@
 		prec = 1;
 
 	if ((flags & F_ALT) &&
-	    (type == 'x' || type == 'X')) {
-		/* When converting under %#x or %#X, there are a number
+	    (type == 'x' || type == 'X' || type == 'o')) {
+		/* When converting under %#o, %#x or %#X, there are a number
 		 * of issues that cause pain:
+		 * - for %#o, we want a different base marker than C
 		 * - 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
@@ -4387,7 +4398,7 @@
 			      prec, type);
 	}
 
-	/* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
+	/* buf = '+'/'-'/'' + '0o'/'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) {
@@ -4768,10 +4779,13 @@
 				reslen += rescnt;
 				if (reslen < 0) {
 					Py_DECREF(result);
+					Py_XDECREF(temp);
 					return PyErr_NoMemory();
 				}
-				if (_PyString_Resize(&result, reslen) < 0)
+				if (_PyString_Resize(&result, reslen) < 0) {
+					Py_XDECREF(temp);
 					return NULL;
+				}
 				res = PyString_AS_STRING(result)
 					+ reslen - rescnt;
 			}
@@ -4782,7 +4796,8 @@
 				if (width > len)
 					width--;
 			}
-			if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
+			if ((flags & F_ALT) &&
+			    (c == 'x' || c == 'X' || c == 'o')) {
 				assert(pbuf[0] == '0');
 				assert(pbuf[1] == c);
 				if (fill != ' ') {
@@ -4805,7 +4820,7 @@
 				if (sign)
 					*res++ = sign;
 				if ((flags & F_ALT) &&
-				    (c == 'x' || c == 'X')) {
+				    (c == 'x' || c == 'X' || c == 'o')) {
 					assert(pbuf[0] == '0');
 					assert(pbuf[1] == c);
 					*res++ = *pbuf++;
@@ -4822,6 +4837,7 @@
                         if (dict && (argidx < arglen) && c != '%') {
                                 PyErr_SetString(PyExc_TypeError,
                                            "not all arguments converted during string formatting");
+                                Py_XDECREF(temp);
                                 goto error;
                         }
 			Py_XDECREF(temp);
@@ -4969,6 +4985,7 @@
 	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;
@@ -4983,8 +5000,9 @@
 	   give them their stolen references back, and then clear and DECREF
 	   the interned dict. */
 
-	fprintf(stderr, "releasing interned strings\n");
 	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) {
@@ -4993,15 +5011,20 @@
 			break;
 		case SSTATE_INTERNED_IMMORTAL:
 			s->ob_refcnt += 1;
+			immortal_size += s->ob_size;
 			break;
 		case SSTATE_INTERNED_MORTAL:
 			s->ob_refcnt += 2;
+			mortal_size += s->ob_size;
 			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);

Modified: python/branches/p3yk-noslice/Objects/tupleobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/tupleobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/tupleobject.c	Wed Jul 11 15:40:56 2007
@@ -675,7 +675,7 @@
 	0,					/* tp_setattro */
 	0,					/* tp_as_buffer */
 	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-		Py_TPFLAGS_BASETYPE,		/* tp_flags */
+		Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */
 	tuple_doc,				/* tp_doc */
  	(traverseproc)tupletraverse,		/* tp_traverse */
 	0,					/* tp_clear */

Modified: python/branches/p3yk-noslice/Objects/typeobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/typeobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/typeobject.c	Wed Jul 11 15:40:56 2007
@@ -1,6 +1,7 @@
 /* Type object implementation */
 
 #include "Python.h"
+#include "frameobject.h"
 #include "structmember.h"
 
 #include <ctype.h>
@@ -265,9 +266,10 @@
 			PyObject* mro;
 			PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
 					 "", 2, 2, &cls, &mro);
-			Py_DECREF(cls->tp_mro);
+			Py_INCREF(mro);
+			ob = cls->tp_mro;
 			cls->tp_mro = mro;
-			Py_INCREF(cls->tp_mro);
+			Py_DECREF(ob);
 		}
 		Py_DECREF(temp);
 		goto bail;
@@ -520,7 +522,7 @@
 
 	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
 		/* For a heaptype, the instances count as references
-		   to the type.  Traverse the type so the collector
+		   to the type.	 Traverse the type so the collector
 		   can find cycles involving this link. */
 		Py_VISIT(type);
 
@@ -640,7 +642,7 @@
 		assert(base);
 	}
 
-	/* If we added a weaklist, we clear it.  Do this *before* calling
+	/* If we added a weaklist, we clear it.	 Do this *before* calling
 	   the finalizer (__del__), clearing slots, or clearing the instance
 	   dict. */
 
@@ -711,7 +713,7 @@
 
 	   A. Read the comment titled "Trashcan mechanism" in object.h.
 	      For one, this explains why there must be a call to GC-untrack
-	      before the trashcan begin macro.  Without understanding the
+	      before the trashcan begin macro.	Without understanding the
 	      trashcan code, the answers to the following questions don't make
 	      sense.
 
@@ -719,7 +721,7 @@
 	      GC-track again afterward?
 
 	   A. In the case that the base class is GC-aware, the base class
-	      probably GC-untracks the object.  If it does that using the
+	      probably GC-untracks the object.	If it does that using the
 	      UNTRACK macro, this will crash when the object is already
 	      untracked.  Because we don't know what the base class does, the
 	      only safe thing is to make sure the object is tracked when we
@@ -727,19 +729,19 @@
 	      requires that the object is *untracked* before it is called.  So
 	      the dance becomes:
 
-	         GC untrack
+		 GC untrack
 		 trashcan begin
 		 GC track
 
-           Q. Why did the last question say "immediately GC-track again"?
-              It's nowhere near immediately.
+	   Q. Why did the last question say "immediately GC-track again"?
+	      It's nowhere near immediately.
 
-           A. Because the code *used* to re-track immediately.  Bad Idea.
-              self has a refcount of 0, and if gc ever gets its hands on it
-              (which can happen if any weakref callback gets invoked), it
-              looks like trash to gc too, and gc also tries to delete self
-              then.  But we're already deleting self.  Double dealloction is
-              a subtle disaster.
+	   A. Because the code *used* to re-track immediately.	Bad Idea.
+	      self has a refcount of 0, and if gc ever gets its hands on it
+	      (which can happen if any weakref callback gets invoked), it
+	      looks like trash to gc too, and gc also tries to delete self
+	      then.  But we're already deleting self.  Double dealloction is
+	      a subtle disaster.
 
 	   Q. Why the bizarre (net-zero) manipulation of
 	      _PyTrash_delete_nesting around the trashcan macros?
@@ -752,17 +754,17 @@
 	      - subtype_dealloc() is called
 
 	      - the trashcan limit is not yet reached, so the trashcan level
-	        is incremented and the code between trashcan begin and end is
-	        executed
+		is incremented and the code between trashcan begin and end is
+		executed
 
 	      - this destroys much of the object's contents, including its
-	        slots and __dict__
+		slots and __dict__
 
 	      - basedealloc() is called; this is really list_dealloc(), or
-	        some other type which also uses the trashcan macros
+		some other type which also uses the trashcan macros
 
 	      - the trashcan limit is now reached, so the object is put on the
-	        trashcan's to-be-deleted-later list
+		trashcan's to-be-deleted-later list
 
 	      - basedealloc() returns
 
@@ -771,13 +773,13 @@
 	      - subtype_dealloc() returns
 
 	      - later, the trashcan code starts deleting the objects from its
-	        to-be-deleted-later list
+		to-be-deleted-later list
 
 	      - subtype_dealloc() is called *AGAIN* for the same object
 
 	      - at the very least (if the destroyed slots and __dict__ don't
-	        cause problems) the object's type gets decref'ed a second
-	        time, which is *BAD*!!!
+		cause problems) the object's type gets decref'ed a second
+		time, which is *BAD*!!!
 
 	      The remedy is to make sure that if the code between trashcan
 	      begin and end in subtype_dealloc() is called, the code between
@@ -789,7 +791,7 @@
 	      But now it's possible that a chain of objects consisting solely
 	      of objects whose deallocator is subtype_dealloc() will defeat
 	      the trashcan mechanism completely: the decremented level means
-	      that the effective level never reaches the limit.  Therefore, we
+	      that the effective level never reaches the limit.	 Therefore, we
 	      *increment* the level *before* entering the trashcan block, and
 	      matchingly decrement it after leaving.  This means the trashcan
 	      code will trigger a little early, but that's no big deal.
@@ -840,7 +842,7 @@
 /* Internal routines to do a method lookup in the type
    without looking in the instance dictionary
    (so we can't use PyObject_GetAttr) but still binding
-   it to the instance.  The arguments are the object,
+   it to the instance.	The arguments are the object,
    the method name as a C string, and the address of a
    static variable used to cache the interned Python string.
 
@@ -883,7 +885,7 @@
 }
 
 /* A variation of PyObject_CallMethod that uses lookup_method()
-   instead of PyObject_GetAttrString().  This uses the same convention
+   instead of PyObject_GetAttrString().	 This uses the same convention
    as lookup_method to cache the interned name string object. */
 
 static PyObject *
@@ -1044,7 +1046,7 @@
 
    It's hard to produce a good error message.  In the absence of better
    insight into error reporting, report the classes that were candidates
-   to be put next into the MRO.  There is some conflict between the
+   to be put next into the MRO.	 There is some conflict between the
    order in which they should be put in the MRO, but it's hard to
    diagnose what constraint can't be satisfied.
 */
@@ -1116,7 +1118,7 @@
 		if (remain[i] >= PyList_GET_SIZE(cur_list)) {
 			empty_cnt++;
 			continue;
-                }
+		}
 
 		/* Choose next candidate for MRO.
 
@@ -1193,7 +1195,7 @@
 		if (parentMRO == NULL) {
 			Py_DECREF(to_merge);
 			return NULL;
-	        }
+		}
 
 		PyList_SET_ITEM(to_merge, i, parentMRO);
 	}
@@ -1359,10 +1361,12 @@
 			type->tp_itemsize != base->tp_itemsize;
 	}
 	if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
-	    type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
+	    type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
+	    type->tp_flags & Py_TPFLAGS_HEAPTYPE)
 		t_size -= sizeof(PyObject *);
 	if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
-	    type->tp_dictoffset + sizeof(PyObject *) == t_size)
+	    type->tp_dictoffset + sizeof(PyObject *) == t_size &&
+	    type->tp_flags & Py_TPFLAGS_HEAPTYPE)
 		t_size -= sizeof(PyObject *);
 
 	return t_size != b_size;
@@ -1388,12 +1392,73 @@
 static int update_slot(PyTypeObject *, PyObject *);
 static void fixup_slot_dispatchers(PyTypeObject *);
 
+/*
+ * Helpers for  __dict__ descriptor.  We don't want to expose the dicts
+ * inherited from various builtin types.  The builtin base usually provides
+ * its own __dict__ descriptor, so we use that when we can.
+ */
+static PyTypeObject *
+get_builtin_base_with_dict(PyTypeObject *type)
+{
+	while (type->tp_base != NULL) {
+		if (type->tp_dictoffset != 0 &&
+		    !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
+			return type;
+		type = type->tp_base;
+	}
+	return NULL;
+}
+
+static PyObject *
+get_dict_descriptor(PyTypeObject *type)
+{
+	static PyObject *dict_str;
+	PyObject *descr;
+
+	if (dict_str == NULL) {
+		dict_str = PyString_InternFromString("__dict__");
+		if (dict_str == NULL)
+			return NULL;
+	}
+	descr = _PyType_Lookup(type, dict_str);
+	if (descr == NULL || !PyDescr_IsData(descr))
+		return NULL;
+
+	return descr;
+}
+
+static void
+raise_dict_descr_error(PyObject *obj)
+{
+	PyErr_Format(PyExc_TypeError,
+		     "this __dict__ descriptor does not support "
+		     "'%.200s' objects", obj->ob_type->tp_name);
+}
+
 static PyObject *
 subtype_dict(PyObject *obj, void *context)
 {
-	PyObject **dictptr = _PyObject_GetDictPtr(obj);
+	PyObject **dictptr;
 	PyObject *dict;
+	PyTypeObject *base;
+
+	base = get_builtin_base_with_dict(obj->ob_type);
+	if (base != NULL) {
+		descrgetfunc func;
+		PyObject *descr = get_dict_descriptor(base);
+		if (descr == NULL) {
+			raise_dict_descr_error(obj);
+			return NULL;
+		}
+		func = descr->ob_type->tp_descr_get;
+		if (func == NULL) {
+			raise_dict_descr_error(obj);
+			return NULL;
+		}
+		return func(descr, obj, (PyObject *)(obj->ob_type));
+	}
 
+	dictptr = _PyObject_GetDictPtr(obj);
 	if (dictptr == NULL) {
 		PyErr_SetString(PyExc_AttributeError,
 				"This object has no __dict__");
@@ -1409,9 +1474,27 @@
 static int
 subtype_setdict(PyObject *obj, PyObject *value, void *context)
 {
-	PyObject **dictptr = _PyObject_GetDictPtr(obj);
+	PyObject **dictptr;
 	PyObject *dict;
+	PyTypeObject *base;
 
+	base = get_builtin_base_with_dict(obj->ob_type);
+	if (base != NULL) {
+		descrsetfunc func;
+		PyObject *descr = get_dict_descriptor(base);
+		if (descr == NULL) {
+			raise_dict_descr_error(obj);
+			return -1;
+		}
+		func = descr->ob_type->tp_descr_set;
+		if (func == NULL) {
+			raise_dict_descr_error(obj);
+			return -1;
+		}
+		return func(descr, obj, value);
+	}
+
+	dictptr = _PyObject_GetDictPtr(obj);
 	if (dictptr == NULL) {
 		PyErr_SetString(PyExc_AttributeError,
 				"This object has no __dict__");
@@ -1510,31 +1593,69 @@
 static PyObject *
 _unicode_to_string(PyObject *slots, Py_ssize_t nslots)
 {
-	PyObject *tmp = slots;
-	PyObject *o, *o1;
+	PyObject *tmp = NULL;
+	PyObject *slot_name, *new_name;
 	Py_ssize_t i;
+
 	for (i = 0; i < nslots; i++) {
-		if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
-			if (tmp == slots) {
-				tmp = PySequence_GetSlice(slots, 0, PyTuple_GET_SIZE(slots));
+		if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
+			if (tmp == NULL) {
+				tmp = PySequence_List(slots);
 				if (tmp == NULL)
 					return NULL;
 			}
-			o1 = _PyUnicode_AsDefaultEncodedString
-					(o, NULL);
-			if (o1 == NULL) {
+			new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
+								     NULL);
+			if (new_name == NULL) {
 				Py_DECREF(tmp);
-				return 0;
+				return NULL;
 			}
-			Py_INCREF(o1);
-			Py_DECREF(o);
-			PyTuple_SET_ITEM(tmp, i, o1);
+			Py_INCREF(new_name);
+			PyList_SET_ITEM(tmp, i, new_name);
+			Py_DECREF(slot_name);
 		}
 	}
-	return tmp;
+	if (tmp != NULL) {
+		slots = PyList_AsTuple(tmp);
+		Py_DECREF(tmp);
+	}
+	return slots;
 }
 #endif
 
+/* Forward */
+static int
+object_init(PyObject *self, PyObject *args, PyObject *kwds);
+
+static int
+type_init(PyObject *cls, PyObject *args, PyObject *kwds)
+{
+	int res;
+
+	assert(args != NULL && PyTuple_Check(args));
+	assert(kwds == NULL || PyDict_Check(kwds));
+
+	if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
+		PyErr_SetString(PyExc_TypeError,
+				"type.__init__() takes no keyword arguments");
+		return -1;
+	}
+
+	if (args != NULL && PyTuple_Check(args) &&
+	    (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
+		PyErr_SetString(PyExc_TypeError,
+				"type.__init__() takes 1 or 3 arguments");
+		return -1;
+	}
+
+	/* Call object.__init__(self) now. */
+	/* XXX Could call super(type, cls).__init__() but what's the point? */
+	args = PyTuple_GetSlice(args, 0, 0);
+	res = object_init(cls, args, NULL);
+	Py_DECREF(args);
+	return res;
+}
+
 static PyObject *
 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
 {
@@ -1651,7 +1772,7 @@
 		/* Have slots */
 
 		/* Make it into a tuple */
-		if (PyString_Check(slots))
+		if (PyString_Check(slots) || PyUnicode_Check(slots))
 			slots = PyTuple_Pack(1, slots);
 		else
 			slots = PySequence_Tuple(slots);
@@ -1676,12 +1797,12 @@
 
 #ifdef Py_USING_UNICODE
 		tmp = _unicode_to_string(slots, nslots);
+		if (tmp == NULL)
+			goto bad_slots;
 		if (tmp != slots) {
 			Py_DECREF(slots);
 			slots = tmp;
 		}
-		if (!tmp)
-			return NULL;
 #endif
 		/* Check for valid slot names and two special cases */
 		for (i = 0; i < nslots; i++) {
@@ -1712,8 +1833,11 @@
 			}
 		}
 
-		/* Copy slots into yet another tuple, demangling names */
-		newslots = PyTuple_New(nslots - add_dict - add_weak);
+		/* Copy slots into a list, mangle names and sort them.
+		   Sorted names are needed for __class__ assignment.
+		   Convert them back to tuple at the end.
+		*/
+		newslots = PyList_New(nslots - add_dict - add_weak);
 		if (newslots == NULL)
 			goto bad_slots;
 		for (i = j = 0; i < nslots; i++) {
@@ -1724,15 +1848,25 @@
 			    (add_weak && strcmp(s, "__weakref__") == 0))
 				continue;
 			tmp =_Py_Mangle(name, tmp);
-                        if (!tmp)
-                            goto bad_slots;
-			PyTuple_SET_ITEM(newslots, j, tmp);
+			if (!tmp)
+			    goto bad_slots;
+			PyList_SET_ITEM(newslots, j, tmp);
 			j++;
 		}
 		assert(j == nslots - add_dict - add_weak);
 		nslots = j;
 		Py_DECREF(slots);
-		slots = newslots;
+		if (PyList_Sort(newslots) == -1) {
+			Py_DECREF(bases);
+			Py_DECREF(newslots);
+			return NULL;
+		}
+		slots = PyList_AsTuple(newslots);
+		Py_DECREF(newslots);
+		if (slots == NULL) {
+			Py_DECREF(bases);
+			return NULL;
+		}
 
 		/* Secondary bases may provide weakrefs or dict */
 		if (nbases > 1 &&
@@ -1823,13 +1957,13 @@
 		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
 		if (doc != NULL && PyString_Check(doc)) {
 			const size_t n = (size_t)PyString_GET_SIZE(doc);
-                        char *tp_doc = (char *)PyObject_MALLOC(n+1);
+			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);
-                        type->tp_doc = tp_doc;
+			type->tp_doc = tp_doc;
 		}
 	}
 
@@ -1855,13 +1989,11 @@
 				PyTuple_GET_ITEM(slots, i));
 			mp->type = T_OBJECT_EX;
 			mp->offset = slotoffset;
-			if (base->tp_weaklistoffset == 0 &&
-			    strcmp(mp->name, "__weakref__") == 0) {
-				add_weak++;
-				mp->type = T_OBJECT;
-				mp->flags = READONLY;
-				type->tp_weaklistoffset = slotoffset;
-			}
+
+			/* __dict__ and __weakref__ are already filtered out */
+			assert(strcmp(mp->name, "__dict__") != 0);
+			assert(strcmp(mp->name, "__weakref__") != 0);
+
 			slotoffset += sizeof(PyObject *);
 		}
 	}
@@ -2069,9 +2201,9 @@
 	Py_XDECREF(type->tp_mro);
 	Py_XDECREF(type->tp_cache);
 	Py_XDECREF(type->tp_subclasses);
-        /* A type's tp_doc is heap allocated, unlike the tp_doc slots
-         * of most other objects.  It's okay to cast it to char *.
-         */
+	/* A type's tp_doc is heap allocated, unlike the tp_doc slots
+	 * of most other objects.  It's okay to cast it to char *.
+	 */
 	PyObject_Free((char *)type->tp_doc);
 	Py_XDECREF(et->ht_name);
 	Py_XDECREF(et->ht_slots);
@@ -2190,7 +2322,7 @@
 	sizeof(PyMemberDef),			/* tp_itemsize */
 	(destructor)type_dealloc,		/* tp_dealloc */
 	0,					/* tp_print */
-	0,			 		/* tp_getattr */
+	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */
 	(reprfunc)type_repr,			/* tp_repr */
@@ -2204,7 +2336,7 @@
 	(setattrofunc)type_setattro,		/* tp_setattro */
 	0,					/* tp_as_buffer */
 	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
-		Py_TPFLAGS_BASETYPE,		/* tp_flags */
+		Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS,	/* tp_flags */
 	type_doc,				/* tp_doc */
 	(traverseproc)type_traverse,		/* tp_traverse */
 	(inquiry)type_clear,			/* tp_clear */
@@ -2220,37 +2352,113 @@
 	0,					/* tp_descr_get */
 	0,					/* tp_descr_set */
 	offsetof(PyTypeObject, tp_dict),	/* tp_dictoffset */
-	0,					/* tp_init */
+	type_init,				/* tp_init */
 	0,					/* tp_alloc */
 	type_new,				/* tp_new */
-	PyObject_GC_Del,        		/* tp_free */
+	PyObject_GC_Del,			/* tp_free */
 	(inquiry)type_is_gc,			/* tp_is_gc */
 };
 
 
 /* The base type of all types (eventually)... except itself. */
 
+/* You may wonder why object.__new__() only complains about arguments
+   when object.__init__() is not overridden, and vice versa.
+
+   Consider the use cases:
+
+   1. When neither is overridden, we want to hear complaints about
+      excess (i.e., any) arguments, since their presence could
+      indicate there's a bug.
+
+   2. When defining an Immutable type, we are likely to override only
+      __new__(), since __init__() is called too late to initialize an
+      Immutable object.  Since __new__() defines the signature for the
+      type, it would be a pain to have to override __init__() just to
+      stop it from complaining about excess arguments.
+
+   3. When defining a Mutable type, we are likely to override only
+      __init__().  So here the converse reasoning applies: we don't
+      want to have to override __new__() just to stop it from
+      complaining.
+
+   4. When __init__() is overridden, and the subclass __init__() calls
+      object.__init__(), the latter should complain about excess
+      arguments; ditto for __new__().
+
+   Use cases 2 and 3 make it unattractive to unconditionally check for
+   excess arguments.  The best solution that addresses all four use
+   cases is as follows: __init__() complains about excess arguments
+   unless __new__() is overridden and __init__() is not overridden
+   (IOW, if __init__() is overridden or __new__() is not overridden);
+   symmetrically, __new__() complains about excess arguments unless
+   __init__() is overridden and __new__() is not overridden
+   (IOW, if __new__() is overridden or __init__() is not overridden).
+
+   However, for backwards compatibility, this breaks too much code.
+   Therefore, in 2.6, we'll *warn* about excess arguments when both
+   methods are overridden; for all other cases we'll use the above
+   rules.
+
+*/
+
+/* Forward */
+static PyObject *
+object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
+
+static int
+excess_args(PyObject *args, PyObject *kwds)
+{
+	return PyTuple_GET_SIZE(args) ||
+		(kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
+}
+
 static int
 object_init(PyObject *self, PyObject *args, PyObject *kwds)
 {
-	return 0;
+	int err = 0;
+	if (excess_args(args, kwds)) {
+		PyTypeObject *type = self->ob_type;
+		if (type->tp_init != object_init &&
+		    type->tp_new != object_new)
+		{
+			err = PyErr_WarnEx(PyExc_DeprecationWarning,
+				   "object.__init__() takes no parameters",
+				   1);
+		}
+		else if (type->tp_init != object_init ||
+			 type->tp_new == object_new)
+		{
+			PyErr_SetString(PyExc_TypeError,
+				"object.__init__() takes no parameters");
+			err = -1;
+		}
+	}
+	return err;
 }
 
-/* If we don't have a tp_new for a new-style class, new will use this one.
-   Therefore this should take no arguments/keywords.  However, this new may
-   also be inherited by objects that define a tp_init but no tp_new.  These
-   objects WILL pass argumets to tp_new, because it gets the same args as
-   tp_init.  So only allow arguments if we aren't using the default init, in
-   which case we expect init to handle argument parsing. */
 static PyObject *
 object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
-	if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
-	     (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
-		PyErr_SetString(PyExc_TypeError,
-				"default __new__ takes no parameters");
-		return NULL;
+	int err = 0;
+	if (excess_args(args, kwds)) {
+		if (type->tp_new != object_new &&
+		    type->tp_init != object_init)
+		{
+			err = PyErr_WarnEx(PyExc_DeprecationWarning,
+				   "object.__new__() takes no parameters",
+				   1);
+		}
+		else if (type->tp_new != object_new ||
+			 type->tp_init == object_init)
+		{
+			PyErr_SetString(PyExc_TypeError,
+				"object.__new__() takes no parameters");
+			err = -1;
+		}
 	}
+	if (err < 0)
+		return NULL;
 	return type->tp_alloc(type, 0);
 }
 
@@ -2310,18 +2518,34 @@
 
 	case Py_EQ:
 		res = (self == other) ? Py_True : Py_False;
+		Py_INCREF(res);
 		break;
 
 	case Py_NE:
-		res = (self != other) ? Py_True : Py_False;
+		/* By default, != returns the opposite of ==,
+		   unless the latter returns NotImplemented. */
+		res = PyObject_RichCompare(self, other, Py_EQ);
+		if (res != NULL && res != Py_NotImplemented) {
+			int ok = PyObject_IsTrue(res);
+			Py_DECREF(res);
+			if (ok < 0)
+				res = NULL;
+			else {
+				if (ok)
+					res = Py_False;
+				else
+					res = Py_True;
+				Py_INCREF(res);
+			}
+		}
 		break;
 
 	default:
 		res = Py_NotImplemented;
+		Py_INCREF(res);
 		break;
 	}
 
-	Py_INCREF(res);
 	return res;
 }
 
@@ -2351,6 +2575,7 @@
 {
 	PyTypeObject *base = a->tp_base;
 	Py_ssize_t size;
+	PyObject *slots_a, *slots_b;
 
 	if (base != b->tp_base)
 		return 0;
@@ -2361,6 +2586,15 @@
 		size += sizeof(PyObject *);
 	if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
 		size += sizeof(PyObject *);
+
+	/* Check slots compliance */
+	slots_a = ((PyHeapTypeObject *)a)->ht_slots;
+	slots_b = ((PyHeapTypeObject *)b)->ht_slots;
+	if (slots_a && slots_b) {
+		if (PyObject_Compare(slots_a, slots_b) != 0)
+			return 0;
+		size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
+	}
 	return size == a->tp_basicsize && size == b->tp_basicsize;
 }
 
@@ -2644,11 +2878,54 @@
 	return res;
 }
 
+/*
+ * There were two problems when object.__reduce__ and object.__reduce_ex__
+ * were implemented in the same function:
+ *  - trying to pickle an object with a custom __reduce__ method that
+ *    fell back to object.__reduce__ in certain circumstances led to
+ *    infinite recursion at Python level and eventual RuntimeError.
+ *  - Pickling objects that lied about their type by overwriting the
+ *    __class__ descriptor could lead to infinite recursion at C level
+ *    and eventual segfault.
+ *
+ * Because of backwards compatibility, the two methods still have to
+ * behave in the same way, even if this is not required by the pickle
+ * protocol. This common functionality was moved to the _common_reduce
+ * function.
+ */
+static PyObject *
+_common_reduce(PyObject *self, int proto)
+{
+	PyObject *copy_reg, *res;
+
+	if (proto >= 2)
+		return reduce_2(self);
+
+	copy_reg = import_copy_reg();
+	if (!copy_reg)
+		return NULL;
+
+	res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
+	Py_DECREF(copy_reg);
+
+	return res;
+}
+
+static PyObject *
+object_reduce(PyObject *self, PyObject *args)
+{
+	int proto = 0;
+
+	if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
+		return NULL;
+
+	return _common_reduce(self, proto);
+}
+
 static PyObject *
 object_reduce_ex(PyObject *self, PyObject *args)
 {
-	/* Call copy_reg._reduce_ex(self, proto) */
-	PyObject *reduce, *copy_reg, *res;
+	PyObject *reduce, *res;
 	int proto = 0;
 
 	if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
@@ -2684,23 +2961,13 @@
 			Py_DECREF(reduce);
 	}
 
-	if (proto >= 2)
-		return reduce_2(self);
-
-	copy_reg = import_copy_reg();
-	if (!copy_reg)
-		return NULL;
-
-	res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
-	Py_DECREF(copy_reg);
-
-	return res;
+	return _common_reduce(self, proto);
 }
 
 static PyMethodDef object_methods[] = {
 	{"__reduce_ex__", object_reduce_ex, METH_VARARGS,
 	 PyDoc_STR("helper for pickle")},
-	{"__reduce__", object_reduce_ex, METH_VARARGS,
+	{"__reduce__", object_reduce, METH_VARARGS,
 	 PyDoc_STR("helper for pickle")},
 	{0}
 };
@@ -2708,13 +2975,13 @@
 
 PyTypeObject PyBaseObject_Type = {
 	PyObject_HEAD_INIT(&PyType_Type)
- 	0,					/* ob_size */
+	0,					/* ob_size */
 	"object",				/* tp_name */
 	sizeof(PyObject),			/* tp_basicsize */
 	0,					/* tp_itemsize */
 	object_dealloc,				/* tp_dealloc */
 	0,					/* tp_print */
-	0,			 		/* tp_getattr */
+	0,					/* tp_getattr */
 	0,					/* tp_setattr */
 	0,					/* tp_compare */
 	object_repr,				/* tp_repr */
@@ -2746,7 +3013,7 @@
 	object_init,				/* tp_init */
 	PyType_GenericAlloc,			/* tp_alloc */
 	object_new,				/* tp_new */
-	PyObject_Del,           		/* tp_free */
+	PyObject_Del,				/* tp_free */
 };
 
 
@@ -2873,6 +3140,24 @@
 	COPYVAL(tp_itemsize);
 	COPYVAL(tp_weaklistoffset);
 	COPYVAL(tp_dictoffset);
+
+	/* Setup fast subclass flags */
+	if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
+		type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyType_Type))
+		type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyLong_Type))
+		type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyString_Type))
+		type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyUnicode_Type))
+		type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyTuple_Type))
+		type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyList_Type))
+		type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
+	else if (PyType_IsSubtype(base, &PyDict_Type))
+		type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
 }
 
 /* Map rich comparison operators to their __xx__ namesakes */
@@ -2952,8 +3237,6 @@
 		COPYNUM(nb_int);
 		COPYNUM(nb_long);
 		COPYNUM(nb_float);
-		COPYNUM(nb_oct);
-		COPYNUM(nb_hex);
 		COPYNUM(nb_inplace_add);
 		COPYNUM(nb_inplace_subtract);
 		COPYNUM(nb_inplace_multiply);
@@ -3099,9 +3382,9 @@
 		Py_INCREF(base);
 	}
 
-        /* Now the only way base can still be NULL is if type is
-         * &PyBaseObject_Type.
-         */
+	/* Now the only way base can still be NULL is if type is
+	 * &PyBaseObject_Type.
+	 */
 
 	/* Initialize the base class */
 	if (base != NULL && base->tp_dict == NULL) {
@@ -3109,13 +3392,13 @@
 			goto error;
 	}
 
-	/* Initialize ob_type if NULL.  This means extensions that want to be
+	/* Initialize ob_type if NULL.	This means extensions that want to be
 	   compilable separately on Windows can call PyType_Ready() instead of
 	   initializing the ob_type field of their type objects. */
-        /* The test for base != NULL is really unnecessary, since base is only
-           NULL when type is &PyBaseObject_Type, and we know its ob_type is
-           not NULL (it's initialized to &PyType_Type).  But coverity doesn't
-           know that. */
+	/* The test for base != NULL is really unnecessary, since base is only
+	   NULL when type is &PyBaseObject_Type, and we know its ob_type is
+	   not NULL (it's initialized to &PyType_Type).	 But coverity doesn't
+	   know that. */
 	if (type->ob_type == NULL && base != NULL)
 		type->ob_type = base->ob_type;
 
@@ -3179,9 +3462,9 @@
 	/* Sanity check for tp_free. */
 	if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
 	    (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
-	    	/* This base class needs to call tp_free, but doesn't have
-	    	 * one, or its tp_free is for non-gc'ed objects.
-	    	 */
+		/* This base class needs to call tp_free, but doesn't have
+		 * one, or its tp_free is for non-gc'ed objects.
+		 */
 		PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
 			     "gc and is a base type but has inappropriate "
 			     "tp_free slot",
@@ -3320,7 +3603,7 @@
 /* Generic wrappers for overloadable 'operators' such as __getitem__ */
 
 /* There's a wrapper *function* for each distinct function typedef used
-   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
+   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).	There's a
    wrapper *table* for each distinct operation (e.g. __len__, __add__).
    Most tables have only one entry; the tables for binary operators have two
    entries, one regular and one with reversed arguments. */
@@ -3611,8 +3894,8 @@
 	PyTypeObject *type = self->ob_type;
 	while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
 		type = type->tp_base;
-        /* If type is NULL now, this is a really weird type.
-           In the spirit of backwards compatibility (?), just shut up. */
+	/* If type is NULL now, this is a really weird type.
+	   In the spirit of backwards compatibility (?), just shut up. */
 	if (type && type->tp_setattro != func) {
 		PyErr_Format(PyExc_TypeError,
 			     "can't apply this %s to %s object",
@@ -3828,8 +4111,8 @@
 	staticbase = subtype;
 	while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
 		staticbase = staticbase->tp_base;
-        /* If staticbase is NULL now, it is a really weird type.
-           In the spirit of backwards compatibility (?), just shut up. */
+	/* If staticbase is NULL now, it is a really weird type.
+	   In the spirit of backwards compatibility (?), just shut up. */
 	if (staticbase && staticbase->tp_new != type->tp_new) {
 		PyErr_Format(PyExc_TypeError,
 			     "%s.__new__(%s) is not safe, use %s.__new__()",
@@ -3848,9 +4131,9 @@
 }
 
 static struct PyMethodDef tp_new_methoddef[] = {
-	{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
+	{"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
 	 PyDoc_STR("T.__new__(S, ...) -> "
-	 	   "a new object with type S, a subtype of T")},
+		   "a new object with type S, a subtype of T")},
 	{0}
 };
 
@@ -4206,8 +4489,6 @@
 SLOT0(slot_nb_int, "__int__")
 SLOT0(slot_nb_long, "__long__")
 SLOT0(slot_nb_float, "__float__")
-SLOT0(slot_nb_oct, "__oct__")
-SLOT0(slot_nb_hex, "__hex__")
 SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
 SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
 SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
@@ -4535,7 +4816,7 @@
 slot_tp_iternext(PyObject *self)
 {
 	static PyObject *next_str;
-	return call_method(self, "next", &next_str, "()");
+	return call_method(self, "__next__", &next_str, "()");
 }
 
 static PyObject *
@@ -4768,11 +5049,11 @@
 	   user-defined methods has unexpected side-effects, as shown by
 	   test_descr.notimplemented() */
 	SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
-          "x.__add__(y) <==> x+y"),
+	  "x.__add__(y) <==> x+y"),
 	SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
-          "x.__mul__(n) <==> x*n"),
+	  "x.__mul__(n) <==> x*n"),
 	SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
-          "x.__rmul__(n) <==> n*x"),
+	  "x.__rmul__(n) <==> n*x"),
 	SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
 	       "x.__getitem__(y) <==> x[y]"),
 	SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
@@ -4782,9 +5063,9 @@
 	SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
 	       "x.__contains__(y) <==> y in x"),
 	SQSLOT("__iadd__", sq_inplace_concat, NULL,
-          wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
+	  wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
 	SQSLOT("__imul__", sq_inplace_repeat, NULL,
-          wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
+	  wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
 
 	MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
 	       "x.__len__() <==> len(x)"),
@@ -4845,10 +5126,6 @@
 	       "long(x)"),
 	UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
 	       "float(x)"),
-	UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
-	       "oct(x)"),
-	UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
-	       "hex(x)"),
 	NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, 
 	       "x[y:z] <==> x[y.__index__():z.__index__()]"),
 	IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
@@ -4917,8 +5194,8 @@
 	       "x.__ge__(y) <==> x>=y"),
 	TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
 	       "x.__iter__() <==> iter(x)"),
-	TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
-	       "x.next() -> the next value, or raise StopIteration"),
+	TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
+	       "x.__next__() <==> next(x)"),
 	TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
 	       "descr.__get__(obj[, type]) -> value"),
 	TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
@@ -4935,7 +5212,7 @@
 };
 
 /* Given a type pointer and an offset gotten from a slotdef entry, return a
-   pointer to the actual slot.  This is not quite the same as simply adding
+   pointer to the actual slot.	This is not quite the same as simply adding
    the offset to the type pointer, since it takes care to indirect through the
    proper indirection pointer (as_buffer, etc.); it returns NULL if the
    indirection pointer is NULL. */
@@ -4999,7 +5276,7 @@
 	}
 
 	/* Look in all matching slots of the type; if exactly one of these has
-	   a filled-in slot, return its value.  Otherwise return NULL. */
+	   a filled-in slot, return its value.	Otherwise return NULL. */
 	res = NULL;
 	for (pp = ptrs; *pp; pp++) {
 		ptr = slotptr(type, (*pp)->offset);
@@ -5238,13 +5515,13 @@
    dictionary with method descriptors for function slots.  For each
    function slot (like tp_repr) that's defined in the type, one or more
    corresponding descriptors are added in the type's tp_dict dictionary
-   under the appropriate name (like __repr__).  Some function slots
+   under the appropriate name (like __repr__).	Some function slots
    cause more than one descriptor to be added (for example, the nb_add
    slot adds both __add__ and __radd__ descriptors) and some function
    slots compete for the same descriptor (for example both sq_item and
    mp_subscript generate a __getitem__ descriptor).
 
-   In the latter case, the first slotdef entry encoutered wins.  Since
+   In the latter case, the first slotdef entry encoutered wins.	 Since
    slotdef entries are sorted by the offset of the slot in the
    PyHeapTypeObject, this gives us some control over disambiguating
    between competing slots: the members of PyHeapTypeObject are listed
@@ -5416,7 +5693,7 @@
 
 	   obj can be a new-style class, or an instance of one:
 
-	   - If it is a class, it must be a subclass of 'type'.  This case is
+	   - If it is a class, it must be a subclass of 'type'.	 This case is
 	     used for class methods; the return value is obj.
 
 	   - If it is an instance, it must be an instance of 'type'.  This is
@@ -5467,7 +5744,7 @@
 			Py_DECREF(class_attr);
 	}
 
-  	PyErr_SetString(PyExc_TypeError,
+	PyErr_SetString(PyExc_TypeError,
 			"super(type, obj): "
 			"obj must be an instance or subtype of type");
 	return NULL;
@@ -5488,7 +5765,7 @@
 		/* If su is an instance of a (strict) subclass of super,
 		   call its type */
 		return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
-					            su->type, obj, NULL);
+						    su->type, obj, NULL);
 	else {
 		/* Inline the common case */
 		PyTypeObject *obj_type = supercheck(su->type, obj);
@@ -5511,14 +5788,76 @@
 super_init(PyObject *self, PyObject *args, PyObject *kwds)
 {
 	superobject *su = (superobject *)self;
-	PyTypeObject *type;
+	PyTypeObject *type = NULL;
 	PyObject *obj = NULL;
 	PyTypeObject *obj_type = NULL;
 
 	if (!_PyArg_NoKeywords("super", kwds))
 		return -1;
-	if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
+	if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
 		return -1;
+
+        if (type == NULL) {
+		/* Call super(), without args -- fill in from __class__
+		   and first local variable on the stack. */
+		PyFrameObject *f = PyThreadState_GET()->frame;
+		PyCodeObject *co = f->f_code;
+		int i, n;
+		if (co == NULL) {
+			PyErr_SetString(PyExc_SystemError,
+					"super(): no code object");
+			return -1;
+		}
+		if (co->co_argcount == 0) {
+			PyErr_SetString(PyExc_SystemError,
+					"super(): no arguments");
+			return -1;
+		}
+		obj = f->f_localsplus[0];
+		if (obj == NULL) {
+			PyErr_SetString(PyExc_SystemError,
+					"super(): arg[0] deleted");
+			return -1;
+		}
+		if (co->co_freevars == NULL)
+			n = 0;
+		else {
+			assert(PyTuple_Check(co->co_freevars));
+			n = PyTuple_GET_SIZE(co->co_freevars);
+		}
+		for (i = 0; i < n; i++) {
+			PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
+			assert(PyString_Check(name)); /* XXX PyUnicode? */
+			if (!strcmp(PyString_AS_STRING(name), "__class__")) {
+				PyObject *cell =
+					f->f_localsplus[co->co_nlocals + i];
+				if (cell == NULL || !PyCell_Check(cell)) {
+					PyErr_SetString(PyExc_SystemError,
+					  "super(): bad __class__ cell");
+					return -1;
+				}
+				type = (PyTypeObject *) PyCell_GET(cell);
+				if (type == NULL) {
+					PyErr_SetString(PyExc_SystemError,
+					  "super(): empty __class__ cell");
+					return -1;
+				}
+				if (!PyType_Check(type)) {
+				    PyErr_Format(PyExc_SystemError,
+				      "super(): __class__ is not a type (%s)",
+				      type->ob_type->tp_name);
+				    return -1;
+				}
+				break;
+			}
+		}
+		if (type == NULL) {
+			PyErr_SetString(PyExc_SystemError,
+					"super(): __class__ cell not found");
+			return -1;
+		}
+        }
+
 	if (obj == Py_None)
 		obj = NULL;
 	if (obj != NULL) {
@@ -5535,13 +5874,19 @@
 }
 
 PyDoc_STRVAR(super_doc,
+"super() -> same as super(__class__, <first argument>)\n"
 "super(type) -> unbound super object\n"
 "super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
 "super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
 "Typical use to call a cooperative superclass method:\n"
 "class C(B):\n"
 "    def meth(self, arg):\n"
-"        super(C, self).meth(arg)");
+"	 super().meth(arg)\n"
+"This works for class methods too:\n"
+"class C(B):\n"
+"    @classmethod\n"
+"    def cmeth(cls, arg):\n"
+"	 super().cmeth(arg)\n");
 
 static int
 super_traverse(PyObject *self, visitproc visit, void *arg)
@@ -5562,7 +5907,7 @@
 	sizeof(superobject),			/* tp_basicsize */
 	0,					/* tp_itemsize */
 	/* methods */
-	super_dealloc,		 		/* tp_dealloc */
+	super_dealloc,				/* tp_dealloc */
 	0,					/* tp_print */
 	0,					/* tp_getattr */
 	0,					/* tp_setattr */
@@ -5570,7 +5915,7 @@
 	super_repr,				/* tp_repr */
 	0,					/* tp_as_number */
 	0,					/* tp_as_sequence */
-	0,		       			/* tp_as_mapping */
+	0,					/* tp_as_mapping */
 	0,					/* tp_hash */
 	0,					/* tp_call */
 	0,					/* tp_str */
@@ -5579,9 +5924,9 @@
 	0,					/* tp_as_buffer */
 	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
 		Py_TPFLAGS_BASETYPE,		/* tp_flags */
- 	super_doc,				/* tp_doc */
- 	super_traverse,				/* tp_traverse */
- 	0,					/* tp_clear */
+	super_doc,				/* tp_doc */
+	super_traverse,				/* tp_traverse */
+	0,					/* tp_clear */
 	0,					/* tp_richcompare */
 	0,					/* tp_weaklistoffset */
 	0,					/* tp_iter */
@@ -5597,5 +5942,5 @@
 	super_init,				/* tp_init */
 	PyType_GenericAlloc,			/* tp_alloc */
 	PyType_GenericNew,			/* tp_new */
-	PyObject_GC_Del,        		/* tp_free */
+	PyObject_GC_Del,			/* tp_free */
 };

Modified: python/branches/p3yk-noslice/Objects/unicodeobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/unicodeobject.c	(original)
+++ python/branches/p3yk-noslice/Objects/unicodeobject.c	Wed Jul 11 15:40:56 2007
@@ -5535,6 +5535,9 @@
 {
     PyUnicodeObject *u = NULL, *v = NULL, *w;
 
+    if (PyBytes_Check(left) || PyBytes_Check(right))
+        return PyBytes_Concat(left, right);
+
     /* Coerce the two arguments */
     u = (PyUnicodeObject *)PyUnicode_FromObject(left);
     if (u == NULL)
@@ -5690,7 +5693,7 @@
     Py_UNICODE *e;
     Py_UNICODE *p;
     Py_UNICODE *q;
-    Py_ssize_t i, j;
+    Py_ssize_t i, j, old_j;
     PyUnicodeObject *u;
     int tabsize = 8;
 
@@ -5698,21 +5701,38 @@
 	return NULL;
 
     /* First pass: determine size of output string */
-    i = j = 0;
+    i = j = old_j = 0;
     e = self->str + self->length;
     for (p = self->str; p < e; p++)
         if (*p == '\t') {
-	    if (tabsize > 0)
+	    if (tabsize > 0) {
 		j += tabsize - (j % tabsize);
+		if (old_j > j) {
+		    PyErr_SetString(PyExc_OverflowError,
+				    "new string is too long");
+		    return NULL;
+		}
+		old_j = j;
+	    }
 	}
         else {
             j++;
             if (*p == '\n' || *p == '\r') {
                 i += j;
-                j = 0;
+                old_j = j = 0;
+                if (i < 0) {
+                    PyErr_SetString(PyExc_OverflowError,
+                                    "new string is too long");
+                    return NULL;
+                }
             }
         }
 
+    if ((i + j) < 0) {
+        PyErr_SetString(PyExc_OverflowError, "new string is too long");
+        return NULL;
+    }
+
     /* Second pass: create output string and fill it */
     u = _PyUnicode_New(i + j);
     if (!u)
@@ -7335,9 +7355,10 @@
     }
 
     if ((flags & F_ALT) &&
-        (type == 'x' || type == 'X')) {
-        /* When converting under %#x or %#X, there are a number
+        (type == 'x' || type == 'X' || type == 'o')) {
+        /* When converting under %#o, %#x or %#X, there are a number
          * of issues that cause pain:
+	 * - for %#o, we want a different base marker than C
          * - 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
@@ -7795,7 +7816,7 @@
 		if (width > len)
 		    width--;
 	    }
-	    if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
+	    if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
 		assert(pbuf[0] == '0');
 		assert(pbuf[1] == c);
 		if (fill != ' ') {
@@ -7817,7 +7838,7 @@
 	    if (fill == ' ') {
 		if (sign)
 		    *res++ = sign;
-		if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
+		if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
 		    assert(pbuf[0] == '0');
 		    assert(pbuf[1] == c);
 		    *res++ = *pbuf++;
@@ -7955,7 +7976,8 @@
     PyObject_GenericGetAttr, 		/* tp_getattro */
     0,			 		/* tp_setattro */
     &unicode_as_buffer,			/* tp_as_buffer */
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | 
+        Py_TPFLAGS_UNICODE_SUBCLASS,	/* tp_flags */
     unicode_doc,			/* tp_doc */
     0,					/* tp_traverse */
     0,					/* tp_clear */

Modified: python/branches/p3yk-noslice/PC/VC6/pcbuild.dsw
==============================================================================
--- python/branches/p3yk-noslice/PC/VC6/pcbuild.dsw	(original)
+++ python/branches/p3yk-noslice/PC/VC6/pcbuild.dsw	Wed Jul 11 15:40:56 2007
@@ -26,6 +26,9 @@
 
 Package=<4>
 {{{
+    Begin Project Dependency
+    Project_Dep_Name pythoncore
+    End Project Dependency
 }}}
 
 ###############################################################################

Modified: python/branches/p3yk-noslice/PC/VC6/pythoncore.dsp
==============================================================================
--- python/branches/p3yk-noslice/PC/VC6/pythoncore.dsp	(original)
+++ python/branches/p3yk-noslice/PC/VC6/pythoncore.dsp	Wed Jul 11 15:40:56 2007
@@ -619,10 +619,6 @@
 # End Source File
 # Begin Source File
 
-SOURCE=..\..\Modules\stropmodule.c
-# End Source File
-# Begin Source File
-
 SOURCE=..\..\Python\structmember.c
 # End Source File
 # Begin Source File

Modified: python/branches/p3yk-noslice/PC/WinMain.c
==============================================================================
--- python/branches/p3yk-noslice/PC/WinMain.c	(original)
+++ python/branches/p3yk-noslice/PC/WinMain.c	Wed Jul 11 15:40:56 2007
@@ -1,10 +1,10 @@
 /* Minimal main program -- everything is loaded from the library. */
 
+#include "Python.h"
+
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
 
-#include "Python.h"
-
 int WINAPI WinMain(
     HINSTANCE hInstance,      /* handle to current instance */
     HINSTANCE hPrevInstance,  /* handle to previous instance */

Modified: python/branches/p3yk-noslice/PC/_winreg.c
==============================================================================
--- python/branches/p3yk-noslice/PC/_winreg.c	(original)
+++ python/branches/p3yk-noslice/PC/_winreg.c	Wed Jul 11 15:40:56 2007
@@ -12,10 +12,10 @@
 
 */
 
-#include "windows.h"
 #include "Python.h"
 #include "structmember.h"
 #include "malloc.h" /* for alloca */
+#include "windows.h"
 
 static BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pRes, BOOL bNoneOK);
 static PyObject *PyHKEY_FromHKEY(HKEY h);
@@ -693,11 +693,12 @@
 Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
 {
 	int i,j;
+	DWORD d;
 	switch (typ) {
 		case REG_DWORD:
-			if (value != Py_None && !PyInt_Check(value))
+			if (value != Py_None && !PyLong_Check(value))
 				return FALSE;
-			*retDataBuf = (BYTE *)PyMem_NEW(DWORD, sizeof(DWORD));
+			*retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
 			if (*retDataBuf==NULL){
 				PyErr_NoMemory();
 				return FALSE;
@@ -707,10 +708,10 @@
 				DWORD zero = 0;
 				memcpy(*retDataBuf, &zero, sizeof(DWORD));
 			}
-			else
-				memcpy(*retDataBuf,
-				       &PyInt_AS_LONG((PyIntObject *)value),
-				       sizeof(DWORD));
+			else {
+				d = PyLong_AsLong(value);
+				memcpy(*retDataBuf, &d, sizeof(DWORD));
+			}
 			break;
 		case REG_SZ:
 		case REG_EXPAND_SZ:

Modified: python/branches/p3yk-noslice/PC/config.c
==============================================================================
--- python/branches/p3yk-noslice/PC/config.c	(original)
+++ python/branches/p3yk-noslice/PC/config.c	Wed Jul 11 15:40:56 2007
@@ -6,28 +6,19 @@
 #include "Python.h"
 
 extern void initarray(void);
-#ifndef MS_WIN64
+#ifndef MS_WINI64
 extern void initaudioop(void);
 #endif
 extern void initbinascii(void);
 extern void initcmath(void);
 extern void initerrno(void);
 extern void initgc(void);
-#ifndef MS_WIN64
-extern void initimageop(void);
-#endif
 extern void initmath(void);
-extern void init_md5(void);
 extern void initnt(void);
 extern void initoperator(void);
-#ifndef MS_WIN64
-extern void initrgbimg(void);
-#endif
 extern void initsignal(void);
-extern void init_sha(void);
 extern void init_sha256(void);
 extern void init_sha512(void);
-extern void initstrop(void);
 extern void inittime(void);
 extern void initthread(void);
 extern void initcStringIO(void);
@@ -43,7 +34,7 @@
 extern void initzipimport(void);
 extern void init_random(void);
 extern void inititertools(void);
-extern void initcollections(void);
+extern void init_collections(void);
 extern void init_heapq(void);
 extern void init_bisect(void);
 extern void init_symtable(void);
@@ -80,7 +71,7 @@
         {"array", initarray},
 	{"_ast", init_ast},
 #ifdef MS_WINDOWS
-#ifndef MS_WIN64
+#ifndef MS_WINI64
         {"audioop", initaudioop},
 #endif
 #endif
@@ -88,21 +79,12 @@
         {"cmath", initcmath},
         {"errno", initerrno},
         {"gc", initgc},
-#ifndef MS_WIN64
-        {"imageop", initimageop},
-#endif
         {"math", initmath},
-        {"_md5", init_md5},
         {"nt", initnt}, /* Use the NT os functions, not posix */
         {"operator", initoperator},
-#ifndef MS_WIN64
-        {"rgbimg", initrgbimg},
-#endif
         {"signal", initsignal},
-        {"_sha", init_sha},
         {"_sha256", init_sha256},
         {"_sha512", init_sha512},
-        {"strop", initstrop},
         {"time", inittime},
 #ifdef WITH_THREAD
         {"thread", initthread},
@@ -124,7 +106,7 @@
         {"_heapq", init_heapq},
 	{"_lsprof", init_lsprof},
 	{"itertools", inititertools},
-        {"collections", initcollections},
+        {"_collections", init_collections},
 	{"_symtable", init_symtable},
 	{"mmap", initmmap},
 	{"_csv", init_csv},
@@ -161,7 +143,6 @@
         {"__main__", NULL},
         {"__builtin__", NULL},
         {"sys", NULL},
-	{"exceptions", NULL},
         
         {"_types", init_types},
 

Modified: python/branches/p3yk-noslice/PC/dl_nt.c
==============================================================================
--- python/branches/p3yk-noslice/PC/dl_nt.c	(original)
+++ python/branches/p3yk-noslice/PC/dl_nt.c	Wed Jul 11 15:40:56 2007
@@ -7,11 +7,9 @@
 forgotten) from the programmer.
 
 */
-#include "windows.h"
 
-/* NT and Python share these */
-#include "pyconfig.h"
 #include "Python.h"
+#include "windows.h"
 
 char dllVersionBuffer[16] = ""; // a private buffer
 

Modified: python/branches/p3yk-noslice/PC/getpathp.c
==============================================================================
--- python/branches/p3yk-noslice/PC/getpathp.c	(original)
+++ python/branches/p3yk-noslice/PC/getpathp.c	Wed Jul 11 15:40:56 2007
@@ -650,7 +650,7 @@
 			   start of the path in question - even if this
 			   is one character before the start of the buffer
 			*/
-			while (*look != DELIM && look >= module_search_path)
+			while (look >= module_search_path && *look != DELIM)
 				look--;
 			nchars = lookEnd-look;
 			strncpy(lookBuf, look+1, nchars);

Modified: python/branches/p3yk-noslice/PC/make_versioninfo.c
==============================================================================
--- python/branches/p3yk-noslice/PC/make_versioninfo.c	(original)
+++ python/branches/p3yk-noslice/PC/make_versioninfo.c	Wed Jul 11 15:40:56 2007
@@ -27,7 +27,12 @@
 		PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL);
 	printf("#define MS_DLL_ID \"%d.%d\"\n",
 	       PY_MAJOR_VERSION, PY_MINOR_VERSION);
+	printf("#ifndef _DEBUG\n");
 	printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n",
 	       PY_MAJOR_VERSION, PY_MINOR_VERSION);
+	printf("#else\n");
+	printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n",
+	       PY_MAJOR_VERSION, PY_MINOR_VERSION);
+	printf("#endif\n");
 	return 0;
 }

Modified: python/branches/p3yk-noslice/PC/os2emx/Makefile
==============================================================================
--- python/branches/p3yk-noslice/PC/os2emx/Makefile	(original)
+++ python/branches/p3yk-noslice/PC/os2emx/Makefile	Wed Jul 11 15:40:56 2007
@@ -268,7 +268,6 @@
 DESCRIPTION.crypt$(MODULE.EXT)=		Python Extension DLL implementing the crypt$(BRO)$(BRC) function
 DESCRIPTION._tkinter$(MODULE.EXT)=	Python Extension DLL for access to Tcl/Tk Environment
 DESCRIPTION.readline$(MODULE.EXT)=	Python Extension DLL for access to GNU ReadLine library
-DESCRIPTION.bsddb185$(MODULE.EXT)=	Python Extension DLL for access to BSD DB (v1.85) library
 DESCRIPTION._curses$(MODLIB.EXT)=	Python Extension DLL for access to ncurses library
 DESCRIPTION.pyexpat$(MODULE.EXT)=	Python Extension DLL for access to expat library
 DESCRIPTION.bz2$(MODULE.EXT)=		Python Extension DLL for accessing the bz2 compression library
@@ -301,21 +300,15 @@
 		Modules/itertoolsmodule.c \
 		Modules/_localemodule.c \
 		Modules/mathmodule.c \
-		Modules/md5.c \
-		Modules/md5module.c \
 		Modules/operator.c \
 		Modules/_randommodule.c \
-		Modules/rgbimgmodule.c \
-		Modules/shamodule.c \
 		Modules/sha256module.c \
 		Modules/sha512module.c \
 		Modules/_sre.c \
-		Modules/stropmodule.c \
 		Modules/_struct.c \
 		Modules/symtablemodule.c \
 		Modules/termios.c \
 		Modules/timemodule.c \
-		Modules/timingmodule.c \
 		Modules/_weakref.c \
 		Modules/xxsubtype.c \
 		Modules/zipimport.c)
@@ -471,9 +464,6 @@
 ifeq ($(HAVE_GREADLINE),yes)
   HARDEXTMODULES+=	readline
 endif
-ifeq ($(HAVE_BSDDB),yes)
-  HARDEXTMODULES+=	bsddb185
-endif
 ifeq ($(HAVE_NCURSES),yes)
   LIBEXTMODULES+=	_curses
   HARDEXTMODULES+=	_curses_
@@ -600,10 +590,6 @@
 unicoded$(MODULE.EXT): unicodedata$(MODULE.EXT)
 	cp $^ $@
 
-# - optional modules (requiring other software to be installed)
-bsddb185$(MODULE.EXT): $(OUT)bsddbmodule$O $(OUT)bsddb185_m.def $(PYTHON.IMPLIB)
-	$(LD) $(LDFLAGS.DLL) -o $@ $(^^) $(L^) -ldb $(LIBS)
-
 crypt$(MODULE.EXT): $(OUT)cryptmodule$O $(OUT)crypt_m.def $(PYTHON.IMPLIB)
 	$(LD) $(LDFLAGS.DLL) -o $@ $(^^) $(L^) -lufc $(LIBS)
 

Modified: python/branches/p3yk-noslice/PC/os2emx/config.c
==============================================================================
--- python/branches/p3yk-noslice/PC/os2emx/config.c	(original)
+++ python/branches/p3yk-noslice/PC/os2emx/config.c	Wed Jul 11 15:40:56 2007
@@ -65,15 +65,12 @@
 extern void initmath();
 extern void init_md5();
 extern void initoperator();
-extern void initrgbimg();
 extern void init_sha();
 extern void init_sha256();
 extern void init_sha512();
-extern void initstrop();
 extern void init_struct();
 extern void inittermios();
 extern void inittime();
-extern void inittiming();
 extern void initxxsubtype();
 extern void initzipimport();
 #if !HAVE_DYNAMIC_LOADING
@@ -81,7 +78,6 @@
 extern void init_curses_panel();
 extern void init_hotshot();
 extern void init_testcapi();
-extern void initbsddb185();
 extern void initbz2();
 extern void initfpectl();
 extern void initfpetest();
@@ -129,17 +125,12 @@
 	{"imageop", initimageop},
 	{"itertools", inititertools},
 	{"math", initmath},
-	{"_md5", init_md5},
 	{"operator", initoperator},
-	{"rgbimg", initrgbimg},
-	{"_sha", init_sha},
 	{"_sha256", init_sha256},
 	{"_sha512", init_sha512},
-	{"strop", initstrop},
 	{"_struct", init_struct},
 	{"termios", inittermios},
 	{"time", inittime},
-	{"timing", inittiming},
 	{"xxsubtype", initxxsubtype},
 	{"zipimport", initzipimport},
 #if !HAVE_DYNAMIC_LOADING
@@ -147,7 +138,6 @@
 	{"_curses_panel", init_curses_panel},
 	{"_hotshot", init_hotshot},
 	{"_testcapi", init_testcapi},
-	{"bsddb185", initbsddb185},
 	{"bz2", initbz2},
 	{"fpectl", initfpectl},
 	{"fpetest", initfpetest},
@@ -172,7 +162,6 @@
 	{"__main__", NULL},
 	{"__builtin__", NULL},
 	{"sys", NULL},
-	{"exceptions", NULL},
 
 	/* This lives in gcmodule.c */
 	{"gc", initgc},

Modified: python/branches/p3yk-noslice/PC/os2emx/python25.def
==============================================================================
--- python/branches/p3yk-noslice/PC/os2emx/python25.def	(original)
+++ python/branches/p3yk-noslice/PC/os2emx/python25.def	Wed Jul 11 15:40:56 2007
@@ -767,7 +767,6 @@
   "_PyExc_Fini"
   "PyExc_BaseException"
   "PyExc_Exception"
-  "PyExc_StandardError"
   "PyExc_TypeError"
   "PyExc_StopIteration"
   "PyExc_GeneratorExit"
@@ -1255,26 +1254,12 @@
 ; From python25_s.lib(mathmodule)
 ;  "initmath"
 
-; From python25_s.lib(md5)
-  "md5_finish"
-  "md5_init"
-  "md5_append"
-
-; From python25_s.lib(md5module)
-;  "init_md5"
-
 ; From python25_s.lib(operator)
 ;  "initoperator"
 
 ; From python25_s.lib(_randommodule)
 ;  "init_random"
 
-; From python25_s.lib(rgbimgmodule)
-;  "initrgbimg"
-
-; From python25_s.lib(shamodule)
-;  "init_sha"
-
 ; From python25_s.lib(sha256module)
 ;  "init_sha256"
 
@@ -1284,9 +1269,6 @@
 ; From python25_s.lib(_sre)
 ;  "init_sre"
 
-; From python25_s.lib(stropmodule)
-;  "initstrop"
-
 ; From python25_s.lib(_struct)
 ;  "init_struct"
 
@@ -1301,9 +1283,6 @@
   "_PyTime_DoubleToTimet"
 ;  "inittimezone"
 
-; From python25_s.lib(timingmodule)
-;  "inittiming"
-
 ; From python25_s.lib(_weakref)
 ;  "init_weakref"
 

Modified: python/branches/p3yk-noslice/PC/os2vacpp/config.c
==============================================================================
--- python/branches/p3yk-noslice/PC/os2vacpp/config.c	(original)
+++ python/branches/p3yk-noslice/PC/os2vacpp/config.c	Wed Jul 11 15:40:56 2007
@@ -31,7 +31,6 @@
 extern void initsignal(void);
 extern void initselect(void);
 extern void init_socket(void);
-extern void initstrop(void);
 extern void initstruct(void);
 extern void inittime(void);
 extern void initthread(void);
@@ -75,7 +74,6 @@
         {"_socket", init_socket},
         {"select", initselect},
 #endif
-        {"strop", initstrop},
         {"struct", initstruct},
         {"time", inittime},
 #ifdef WITH_THREAD

Modified: python/branches/p3yk-noslice/PC/os2vacpp/makefile
==============================================================================
--- python/branches/p3yk-noslice/PC/os2vacpp/makefile	(original)
+++ python/branches/p3yk-noslice/PC/os2vacpp/makefile	Wed Jul 11 15:40:56 2007
@@ -371,19 +371,6 @@
 	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
 	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
 
-almodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 arraymodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -439,46 +426,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-cdmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
-cgensupport.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
-	 $(PY_MODULES)\cgensupport.h $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h \
-	 $(PY_INCLUDE)\complexobject.h pyconfig.h $(PY_INCLUDE)\dictobject.h \
-	 $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h \
-	 $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h \
-	 $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
-clmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 cmathmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -616,33 +563,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-flmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\structmember.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
-	 $(PY_INCLUDE)\tupleobject.h
-
-fmmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 fpectlmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -700,20 +620,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-glmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_MODULES)\cgensupport.h \
-	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
-	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
-	 $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h \
-	 $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h \
-	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
-	 $(PY_INCLUDE)\tupleobject.h
-
 grpmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
 	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
 	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
@@ -741,19 +647,6 @@
 	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
 	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
 
-imgfile.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 main.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
 	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
 	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
@@ -781,21 +674,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-md5c.obj: pyconfig.h $(PY_MODULES)\md5.h
-
-md5module.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_MODULES)\md5.h $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 mpzmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -852,20 +730,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\token.h \
 	 $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
 
-pcremodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_MODULES)\pcre-internal.h \
-	 $(PY_MODULES)\pcre.h $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h \
-	 $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h \
-	 $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
-	 $(PY_INCLUDE)\tupleobject.h
-
 posix.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
 	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
 	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
@@ -894,19 +758,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-puremodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 pwdmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
 	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
 	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
@@ -921,20 +772,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-pypcre.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\graminit.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_MODULES)\pcre-internal.h $(PY_MODULES)\pcre.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 readline.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
 	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
 	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
@@ -962,20 +799,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-rgbimgmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
-	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
-	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
-	 $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h \
-	 $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h \
-	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
-	 $(PY_INCLUDE)\tupleobject.h
-
 selectmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -990,19 +813,6 @@
 	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
 	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
 
-sgimodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 signalmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -1032,47 +842,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-soundex.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
-	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
-	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \
-	 $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h \
-	 $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
-stdwinmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
-	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
-	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
-	 $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h \
-	 $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h \
-	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
-	 $(PY_INCLUDE)\tupleobject.h
-
-stropmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
-	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
-	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
-	 $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h \
-	 $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h \
-	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
-	 $(PY_INCLUDE)\tupleobject.h
-
 structmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -1101,21 +870,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\structmember.h \
 	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
 
-svmodule.obj: $(PY_INCLUDE)\abstract.h $(OS2TCPIP)\Include\sys\time.h $(PY_INCLUDE)\ceval.h \
-	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\compile.h \
-	 $(PY_INCLUDE)\complexobject.h pyconfig.h $(PY_INCLUDE)\dictobject.h \
-	 $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h \
-	 $(PY_INCLUDE)\import.h $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h \
-	 $(PY_INCLUDE)\listobject.h $(PY_INCLUDE)\longobject.h \
-	 $(PY_INCLUDE)\methodobject.h $(PY_INCLUDE)\modsupport.h \
-	 $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h $(PY_INCLUDE)\myproto.h \
-	 $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h $(PY_INCLUDE)\pydebug.h \
-	 $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h $(PY_INCLUDE)\pystate.h \
-	 $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h $(PY_INCLUDE)\rangeobject.h \
-	 $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
-	 $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h \
-	 $(PY_MODULES)\yuv.h
-
 syslogmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
 	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
 	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
@@ -1171,20 +925,6 @@
 	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h \
 	 $(PY_INCLUDE)\tupleobject.h
 
-timingmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
-	 $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
-	 pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
-	 $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
-	 $(PY_INCLUDE)\intobject.h $(PY_INCLUDE)\intrcheck.h $(PY_INCLUDE)\listobject.h \
-	 $(PY_INCLUDE)\longobject.h $(PY_INCLUDE)\methodobject.h \
-	 $(PY_INCLUDE)\modsupport.h $(PY_INCLUDE)\moduleobject.h $(PY_INCLUDE)\mymalloc.h \
-	 $(PY_INCLUDE)\myproto.h $(PY_INCLUDE)\object.h $(PY_INCLUDE)\objimpl.h \
-	 $(PY_INCLUDE)\pydebug.h $(PY_INCLUDE)\pyerrors.h $(PY_INCLUDE)\pyfpe.h \
-	 $(PY_INCLUDE)\pystate.h $(PY_INCLUDE)\python.h $(PY_INCLUDE)\pythonrun.h \
-	 $(PY_INCLUDE)\rangeobject.h $(PY_INCLUDE)\sliceobject.h \
-	 $(PY_INCLUDE)\stringobject.h $(PY_INCLUDE)\sysmodule.h $(PY_MODULES)\timing.h \
-	 $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
-
 xxmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classobject.h \
 	 $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h pyconfig.h \
 	 $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h $(PY_INCLUDE)\floatobject.h \

Modified: python/branches/p3yk-noslice/PC/os2vacpp/makefile.omk
==============================================================================
--- python/branches/p3yk-noslice/PC/os2vacpp/makefile.omk	(original)
+++ python/branches/p3yk-noslice/PC/os2vacpp/makefile.omk	Wed Jul 11 15:40:56 2007
@@ -170,45 +170,30 @@
 # Omitted Modules (and Description/Reason):
   #
   # Multimedia:
-  # almodule.c      -- Non-OS/2 Audio Channel Facility (?)
-  # cdmodule.c      -- Wrapper of Non-OS/2 CD Audio Functions
   # audioop.c       -- Various Compute Operations on Audio Samples
   # imageop.c       -- Various Compute Operations on Video Samples
-  # imgfile.c       -- Wrapper of SGI ImageLib API
-  # rgbimgmodule.c  -- Non-OS/2 Image Read/Write Capability (Primitive)
   # sunaudiodev.c   -- Wrapper of Sun Audio Device API
-  # clmodule.c      -- Wrapper of SGI Image/Audio Compression API
 
   # Database:
   # dbmmodule.c     -- Wrapper of DBM Database API (Generic Flavor)
-  # bsddbmodule.c   -- Wrapper of DBM Database API (BSD Flavor)
   # gdbmmodule.c    -- Wrapper of DBM Database API (GNU Flavor)
 
   # Cryptography:
   # cryptmodule.c   -- Simple Wrapper for crypt() Function
-  # rotormodule.c   -- Implementation of Enigma Crypto Based on Rotors
 
-#                  cgensupport.obj   \
 #                  fcntlmodule.obj   \
-#                  fmmodule.obj      \
 #                  fpectlmodule.obj  \
 #                  fpetestmodule.obj \
 # Unix-Specific    getpath.obj       \
-#                  glmodule.obj      \
 #                  grpmodule.obj     \
 #                  mpzmodule.obj     \
 #                  nismodule.obj     \
 #                  parsermodule.obj  \
-#                  pcremodule.obj    \
 #                  pwdmodule.obj     \
-#                  pypcre.obj        \
 #                  readline.obj      \
 #                  resource.obj      \
-#                  sgimodule.obj     \
-#                  svmodule.obj      \
 #                  syslogmodule.obj  \
 #                  termios.obj       \
-#                  timingmodule.obj  \
 
   # User Interface:
 #                  _tkinter.obj      \     
@@ -358,14 +343,6 @@
 	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
 	 traceback.h tupleobject.h
 
-almodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 arraymodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -398,30 +375,6 @@
 	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
 	 traceback.h tupleobject.h
 
-cdmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
-cgensupport.obj: abstract.h ceval.h cgensupport.h classobject.h cobject.h \
-	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
-	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
-	 longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
-	 myproto.h object.h objimpl.h pydebug.h pyerrors.h pyfpe.h \
-	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h traceback.h tupleobject.h
-
-clmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 cmathmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -502,22 +455,6 @@
 	 pyerrors.h pyfpe.h pystate.h python.h pythonrun.h rangeobject.h \
 	 sliceobject.h stringobject.h sysmodule.h traceback.h tupleobject.h
 
-flmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h \
-	 structmember.h sysmodule.h traceback.h tupleobject.h
-
-fmmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 fpectlmodule.obj: abstract.h ceval.h classobject.h cobject.h \
 	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
 	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
@@ -552,14 +489,6 @@
 	 python.h pythonrun.h rangeobject.h sliceobject.h stringobject.h \
 	 sysmodule.h traceback.h tupleobject.h
 
-glmodule.obj: abstract.h ceval.h cgensupport.h classobject.h cobject.h \
-	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
-	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
-	 longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
-	 myproto.h object.h objimpl.h pydebug.h pyerrors.h pyfpe.h \
-	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h traceback.h tupleobject.h
-
 grpmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 grp.h import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -576,14 +505,6 @@
 	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
 	 traceback.h tupleobject.h
 
-imgfile.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 main.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -600,16 +521,6 @@
 	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
 	 stringobject.h sysmodule.h traceback.h tupleobject.h
 
-md5c.obj: pyconfig.h md5.h
-
-md5module.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h md5.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 mpzmodule.obj: abstract.h ceval.h classobject.h cobject.h \
 	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
 	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
@@ -643,14 +554,6 @@
 	 rangeobject.h sliceobject.h stringobject.h sysmodule.h token.h \
 	 traceback.h tupleobject.h
 
-pcremodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pcre-internal.h pcre.h pydebug.h pyerrors.h \
-	 pyfpe.h pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h traceback.h tupleobject.h
-
 posix.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -667,14 +570,6 @@
 	 python.h pythonrun.h rangeobject.h sliceobject.h stringobject.h \
 	 sysmodule.h traceback.h tupleobject.h
 
-puremodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 pwdmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -683,14 +578,6 @@
 	 python.h pythonrun.h rangeobject.h sliceobject.h stringobject.h \
 	 sysmodule.h traceback.h tupleobject.h
 
-pypcre.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 graminit.h import.h intobject.h intrcheck.h listobject.h \
-	 longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
-	 myproto.h object.h objimpl.h pcre-internal.h pcre.h pydebug.h \
-	 pyerrors.h pyfpe.h pystate.h python.h pythonrun.h rangeobject.h \
-	 sliceobject.h stringobject.h sysmodule.h traceback.h tupleobject.h
-
 readline.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \
@@ -707,22 +594,6 @@
 	 pyerrors.h pyfpe.h pystate.h python.h pythonrun.h rangeobject.h \
 	 sliceobject.h stringobject.h sysmodule.h traceback.h tupleobject.h
 
-rgbimgmodule.obj: abstract.h ceval.h classobject.h cobject.h \
-	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
-	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
-	 longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
-	 myproto.h object.h objimpl.h pydebug.h pyerrors.h pyfpe.h \
-	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h traceback.h tupleobject.h
-
-rotormodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h mymath.h \
-	 myproto.h object.h objimpl.h pydebug.h pyerrors.h pyfpe.h \
-	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h traceback.h tupleobject.h
-
 selectmodule.obj: abstract.h ceval.h classobject.h cobject.h \
 	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
 	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
@@ -731,14 +602,6 @@
 	 pyerrors.h pyfpe.h pystate.h python.h pythonrun.h rangeobject.h \
 	 sliceobject.h stringobject.h sysmodule.h traceback.h tupleobject.h
 
-sgimodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 signalmodule.obj: abstract.h ceval.h classobject.h cobject.h \
 	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
 	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
@@ -756,30 +619,6 @@
 	 pyfpe.h pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
 	 stringobject.h sysmodule.h traceback.h tupleobject.h
 
-soundex.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
-stdwinmodule.obj: abstract.h ceval.h classobject.h cobject.h \
-	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
-	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
-	 longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
-	 myproto.h object.h objimpl.h pydebug.h pyerrors.h pyfpe.h \
-	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h traceback.h tupleobject.h
-
-stropmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
-	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
-	 import.h intobject.h intrcheck.h listobject.h longobject.h \
-	 methodobject.h modsupport.h moduleobject.h mymalloc.h myproto.h \
-	 object.h objimpl.h pydebug.h pyerrors.h pyfpe.h pystate.h python.h \
-	 pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
-	 traceback.h tupleobject.h
-
 structmodule.obj: abstract.h ceval.h classobject.h cobject.h \
 	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
 	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
@@ -797,15 +636,6 @@
 	 sliceobject.h stringobject.h structmember.h sysmodule.h \
 	 traceback.h tupleobject.h
 
-svmodule.obj: abstract.h c:\mptn\include\sys\time.h ceval.h classobject.h \
-	 cobject.h compile.h complexobject.h pyconfig.h dictobject.h \
-	 fileobject.h floatobject.h funcobject.h import.h intobject.h \
-	 intrcheck.h listobject.h longobject.h methodobject.h modsupport.h \
-	 moduleobject.h mymalloc.h myproto.h object.h objimpl.h pydebug.h \
-	 pyerrors.h pyfpe.h pystate.h python.h pythonrun.h rangeobject.h \
-	 sliceobject.h stringobject.h sysmodule.h traceback.h tupleobject.h \
-	 yuv.h
-
 syslogmodule.obj: abstract.h ceval.h classobject.h cobject.h \
 	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
 	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
@@ -838,14 +668,6 @@
 	 python.h pythonrun.h rangeobject.h sliceobject.h stringobject.h \
 	 sysmodule.h traceback.h tupleobject.h
 
-timingmodule.obj: abstract.h ceval.h classobject.h cobject.h \
-	 complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
-	 funcobject.h import.h intobject.h intrcheck.h listobject.h \
-	 longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
-	 myproto.h object.h objimpl.h pydebug.h pyerrors.h pyfpe.h \
-	 pystate.h python.h pythonrun.h rangeobject.h sliceobject.h \
-	 stringobject.h sysmodule.h timing.h traceback.h tupleobject.h
-
 xxmodule.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
 	 pyconfig.h dictobject.h fileobject.h floatobject.h funcobject.h \
 	 import.h intobject.h intrcheck.h listobject.h longobject.h \

Modified: python/branches/p3yk-noslice/PC/os2vacpp/python.def
==============================================================================
--- python/branches/p3yk-noslice/PC/os2vacpp/python.def	(original)
+++ python/branches/p3yk-noslice/PC/os2vacpp/python.def	Wed Jul 11 15:40:56 2007
@@ -30,7 +30,6 @@
                PyExc_OSError
                PyExc_OverflowError
                PyExc_RuntimeError
-               PyExc_StandardError
                PyExc_SyntaxError
                PyExc_SystemError
                PyExc_SystemExit

Modified: python/branches/p3yk-noslice/PC/pyconfig.h
==============================================================================
--- python/branches/p3yk-noslice/PC/pyconfig.h	(original)
+++ python/branches/p3yk-noslice/PC/pyconfig.h	Wed Jul 11 15:40:56 2007
@@ -128,6 +128,8 @@
    defined on Win32 *and* Win64. Win32 only code must therefore be
    guarded as follows:
    	#if defined(MS_WIN32) && !defined(MS_WIN64)
+   Some modules are disabled on Itanium processors, therefore we
+   have MS_WINI64 set for those targets, otherwise MS_WINX64
 */
 #ifdef _WIN64
 #define MS_WIN64
@@ -135,17 +137,28 @@
 
 /* set the COMPILER */
 #ifdef MS_WIN64
-#ifdef _M_IX86
-#define COMPILER _Py_PASTE_VERSION("64 bit (Intel)")
-#elif defined(_M_IA64)
+#if defined(_M_IA64)
 #define COMPILER _Py_PASTE_VERSION("64 bit (Itanium)")
-#elif defined(_M_AMD64)
+#define MS_WINI64
+#elif defined(_M_X64)
 #define COMPILER _Py_PASTE_VERSION("64 bit (AMD64)")
+#define MS_WINX64
 #else
 #define COMPILER _Py_PASTE_VERSION("64 bit (Unknown)")
 #endif
 #endif /* MS_WIN64 */
 
+/* set the version macros for the windows headers */
+#ifdef MS_WINX64
+/* 64 bit only runs on XP or greater */
+#define _WIN32_WINNT 0x0501
+#define WINVER 0x0501
+#else
+/* NT 4.0 or greater required otherwise */
+#define _WIN32_WINNT 0x0400
+#define WINVER 0x0400
+#endif
+
 /* _W64 is not defined for VC6 or eVC4 */
 #ifndef _W64
 #define _W64
@@ -234,6 +247,9 @@
 #define COMPILER "[gcc]"
 #define hypot _hypot
 #define PY_LONG_LONG long long
+#define PY_LLONG_MIN LLONG_MIN
+#define PY_LLONG_MAX LLONG_MAX
+#define PY_ULLONG_MAX ULLONG_MAX
 #endif /* GNUC */
 
 /* ------------------------------------------------------------------------*/
@@ -259,6 +275,9 @@
 #define HAVE_LONG_LONG 1
 #ifndef PY_LONG_LONG
 #	define PY_LONG_LONG __int64
+#	define PY_LLONG_MAX _I64_MAX
+#	define PY_LLONG_MIN _I64_MIN
+#	define PY_ULLONG_MAX _UI64_MAX
 #endif
 
 /* For Windows the Python core is in a DLL by default.  Test
@@ -284,9 +303,9 @@
 			their Makefile (other compilers are generally
 			taken care of by distutils.) */
 #			ifdef _DEBUG
-#				pragma comment(lib,"python26_d.lib")
+#				pragma comment(lib,"python30_d.lib")
 #			else
-#				pragma comment(lib,"python26.lib")
+#				pragma comment(lib,"python30.lib")
 #			endif /* _DEBUG */
 #		endif /* _MSC_VER */
 #	endif /* Py_BUILD_CORE */
@@ -478,22 +497,13 @@
 /* Define if you want to have a Unicode type. */
 #define Py_USING_UNICODE
 
-/* Define as the integral type used for Unicode representation. */
-#define PY_UNICODE_TYPE unsigned short
-
 /* Define as the size of the unicode type. */
-#define Py_UNICODE_SIZE SIZEOF_SHORT
-
-/* Define if you have a useable wchar_t type defined in wchar.h; useable
-   means wchar_t must be 16-bit unsigned type. (see
-   Include/unicodeobject.h). */
-#if Py_UNICODE_SIZE == 2
-#define HAVE_USABLE_WCHAR_T
+/* This is enough for unicodeobject.h to do the "right thing" on Windows. */
+#define Py_UNICODE_SIZE 2
 
 /* Define to indicate that the Python Unicode representation can be passed
    as-is to Win32 Wide API.  */
 #define Py_WIN_WIDE_FILENAMES
-#endif
 
 /* Use Python's own small-block memory-allocator. */
 #define WITH_PYMALLOC 1

Modified: python/branches/p3yk-noslice/PC/winsound.c
==============================================================================
--- python/branches/p3yk-noslice/PC/winsound.c	(original)
+++ python/branches/p3yk-noslice/PC/winsound.c	Wed Jul 11 15:40:56 2007
@@ -35,9 +35,9 @@
    winsound.PlaySound(None, 0)
 */
 
+#include <Python.h>
 #include <windows.h>
 #include <mmsystem.h>
-#include <Python.h>
 #ifdef HAVE_CONIO_H
 #include <conio.h>	/* port functions on Win9x */
 #endif

Modified: python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj	(original)
+++ python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj	Wed Jul 11 15:40:56 2007
@@ -213,7 +213,7 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\db-4.4.20\build_win32\Release_AMD64\libdb44s.lib"
+				AdditionalDependencies="..\..\db-4.4.20\build_win32\Release_AMD64\libdb44s.lib bufferoverflowU.lib"
 				OutputFile="./_bsddb.pyd"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"

Modified: python/branches/p3yk-noslice/PCbuild/_ssl.mak
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_ssl.mak	(original)
+++ python/branches/p3yk-noslice/PCbuild/_ssl.mak	Wed Jul 11 15:40:56 2007
@@ -1,3 +1,4 @@
+EXTRA_LIBS=
 
 !IFDEF DEBUG
 SUFFIX=_d.pyd
@@ -26,12 +27,12 @@
 	@if not exist "$(TEMP)/_ssl/." mkdir "$(TEMP)/_ssl"
 	cl /nologo /c $(SSL_SOURCE) $(CFLAGS) /Fo$(TEMP)\_ssl\$*.obj $(INCLUDES)
 	link /nologo @<<
-             /dll /out:_ssl$(SUFFIX) $(TEMP)\_ssl\$*.obj $(SSL_LIBS)
+             /dll /out:_ssl$(SUFFIX) $(TEMP)\_ssl\$*.obj $(SSL_LIBS) $(EXTRA_LIBS)
 <<
 
 _hashlib$(SUFFIX): $(HASH_SOURCE) $(SSL_LIB_DIR)/libeay32.lib ../PC/*.h ../Include/*.h
     @if not exist "$(TEMP)/_hashlib/." mkdir "$(TEMP)/_hashlib"
     cl /nologo /c $(HASH_SOURCE) $(CFLAGS) $(EXTRA_CFLAGS) /Fo$(TEMP)\_hashlib\$*.obj $(INCLUDES) 
     link /nologo @<<
-	/dll /out:_hashlib$(SUFFIX) $(HASH_LIBS) $(TEMP)\_hashlib\$*.obj
+	/dll /out:_hashlib$(SUFFIX) $(HASH_LIBS) $(EXTRA_LIBS) $(TEMP)\_hashlib\$*.obj
 <<

Modified: python/branches/p3yk-noslice/PCbuild/build_ssl.bat
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/build_ssl.bat	(original)
+++ python/branches/p3yk-noslice/PCbuild/build_ssl.bat	Wed Jul 11 15:40:56 2007
@@ -1,3 +1,5 @@
+if "%1" == "ReleaseAMD64" call "%MSSdk%\SetEnv" /XP64 /RETAIL
+
 @echo off
 if not defined HOST_PYTHON (
   if %1 EQU Debug (

Modified: python/branches/p3yk-noslice/PCbuild/build_ssl.py
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/build_ssl.py	(original)
+++ python/branches/p3yk-noslice/PCbuild/build_ssl.py	Wed Jul 11 15:40:56 2007
@@ -170,7 +170,7 @@
     if debug:
         defs = defs + " " + "DEBUG=1"
     if arch in ('amd64', 'ia64'):
-        defs = defs + " EXTRA_CFLAGS=/GS-"
+        defs = defs + " EXTRA_CFLAGS=/GS- EXTRA_LIBS=bufferoverflowU.lib"
     makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags
     print "Executing:", makeCommand
     sys.stdout.flush()

Modified: python/branches/p3yk-noslice/PCbuild/pcbuild.sln
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/pcbuild.sln	(original)
+++ python/branches/p3yk-noslice/PCbuild/pcbuild.sln	Wed Jul 11 15:40:56 2007
@@ -259,12 +259,14 @@
 		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Release.ActiveCfg = Release|Win32
 		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Release.Build.0 = Release|Win32
 		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.ReleaseAMD64.ActiveCfg = ReleaseAMD64|Win32
+		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.ReleaseAMD64.Build.0 = ReleaseAMD64|Win32
 		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.ReleaseItanium.ActiveCfg = ReleaseItanium|Win32
 		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Debug.ActiveCfg = Debug|Win32
 		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Debug.Build.0 = Debug|Win32
 		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Release.ActiveCfg = Release|Win32
 		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Release.Build.0 = Release|Win32
 		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.ReleaseAMD64.ActiveCfg = ReleaseAMD64|Win32
+		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.ReleaseAMD64.Build.0 = ReleaseAMD64|Win32
 		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.ReleaseItanium.ActiveCfg = ReleaseItanium|Win32
 		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Debug.ActiveCfg = Debug|Win32
 		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Debug.Build.0 = Debug|Win32

Modified: python/branches/p3yk-noslice/PCbuild/python.iss
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/python.iss	(original)
+++ python/branches/p3yk-noslice/PCbuild/python.iss	Wed Jul 11 15:40:56 2007
@@ -171,7 +171,6 @@
 
 
 Source: Lib\*.py; DestDir: {app}\Lib; CopyMode: alwaysoverwrite; Components: main
-Source: Lib\compiler\*.*; DestDir: {app}\Lib\compiler; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
 Source: Lib\distutils\*.*; DestDir: {app}\Lib\distutils; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
 Source: Lib\email\*.*; DestDir: {app}\Lib\email; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
 Source: Lib\encodings\*.*; DestDir: {app}\Lib\encodings; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
@@ -270,9 +269,6 @@
 
 
 [UninstallDelete]
-Name: {app}\Lib\compiler\*.pyc; Type: files
-Name: {app}\Lib\compiler\*.pyo; Type: files
-Name: {app}\Lib\compiler; Type: dirifempty
 Name: {app}\Lib\distutils\command\*.pyc; Type: files
 Name: {app}\Lib\distutils\command\*.pyo; Type: files
 Name: {app}\Lib\distutils\command; Type: dirifempty

Modified: python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj	Wed Jul 11 15:40:56 2007
@@ -39,15 +39,15 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26.dll"
+				OutputFile="./python30.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26.pdb"
+				ProgramDatabaseFile=".\./python30.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26.lib"
+				ImportLibrary=".\./python30.lib"
 				TargetMachine="1"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -99,15 +99,15 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26_d.dll"
+				OutputFile="./python30_d.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26_d.pdb"
+				ProgramDatabaseFile=".\./python30_d.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26_d.lib"
+				ImportLibrary=".\./python30_d.lib"
 				TargetMachine="1"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -166,15 +166,15 @@
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26.dll"
+				OutputFile="./python30.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="FALSE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26.pdb"
+				ProgramDatabaseFile=".\./python30.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26.lib"
+				ImportLibrary=".\./python30.lib"
 				TargetMachine="0"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -233,15 +233,15 @@
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python26.dll"
+				OutputFile="./python30.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python26.pdb"
+				ProgramDatabaseFile=".\./python30.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python26.lib"
+				ImportLibrary=".\./python30.lib"
 				TargetMachine="0"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -365,6 +365,9 @@
 			RelativePath="..\Modules\_codecsmodule.c">
 		</File>
 		<File
+			RelativePath="..\Modules\_collectionsmodule.c">
+		</File>
+		<File
 			RelativePath="..\Modules\_csv.c">
 		</File>
 		<File
@@ -461,9 +464,6 @@
 			RelativePath="..\Objects\codeobject.c">
 		</File>
 		<File
-			RelativePath="..\Modules\collectionsmodule.c">
-		</File>
-		<File
 			RelativePath="..\Python\compile.c">
 		</File>
 		<File
@@ -566,9 +566,6 @@
 			RelativePath="..\Parser\grammar1.c">
 		</File>
 		<File
-			RelativePath="..\Modules\imageop.c">
-		</File>
-		<File
 			RelativePath="..\Python\import.c">
 		</File>
 		<File
@@ -629,12 +626,6 @@
 			RelativePath="..\Modules\mathmodule.c">
 		</File>
 		<File
-			RelativePath="..\Modules\md5.c">
-		</File>
-		<File
-			RelativePath="..\Modules\md5module.c">
-		</File>
-		<File
 			RelativePath="..\Parser\metagrammar.c">
 		</File>
 		<File
@@ -716,9 +707,6 @@
 			RelativePath="..\Objects\rangeobject.c">
 		</File>
 		<File
-			RelativePath="..\Modules\rgbimgmodule.c">
-		</File>
-		<File
 			RelativePath="..\Modules\rotatingtree.c">
 		</File>
 		<File
@@ -731,9 +719,6 @@
 			RelativePath="..\Modules\sha512module.c">
 		</File>
 		<File
-			RelativePath="..\Modules\shamodule.c">
-		</File>
-		<File
 			RelativePath="..\Modules\signalmodule.c">
 		</File>
 		<File
@@ -743,9 +728,6 @@
 			RelativePath="..\Objects\stringobject.c">
 		</File>
 		<File
-			RelativePath="..\Modules\stropmodule.c">
-		</File>
-		<File
 			RelativePath="..\Python\structmember.c">
 		</File>
 		<File

Deleted: /python/branches/p3yk-noslice/PCbuild8/Uninstal.wse
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/Uninstal.wse	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,514 +0,0 @@
-Document Type: WSE
-item: Global
-  Version=8.14
-  Flags=00000100
-  Split=1420
-  Languages=65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-  Copy Default=1
-  Japanese Font Name=MS Gothic
-  Japanese Font Size=10
-  Start Gradient=0 0 255
-  End Gradient=0 0 0
-  Windows Flags=00000000000000000000101000001000
-  Message Font=MS Sans Serif
-  Font Size=8
-  Disk Label=GLBS
-  Disk Filename=INSTALL
-  Patch Flags=0000000000000001
-  Patch Threshold=200
-  Patch Memory=4096
-  Per-User Version ID=1
-  Crystal Format=10111100101100000010001001001001
-  Step View=&Properties
-end
-item: Remark
-  Text=Note from Tim:  This is a verbatim copy of Wise's Uninstal.wse, altered at the end to write
-end
-item: Remark
-  Text=uninstall info under HKCU instead of HKLM if our DOADMIN var is false.
-end
-item: Remark
-end
-item: Remark
-  Text=     Install Support for uninstalling the application.
-end
-item: Remark
-end
-item: Set Variable
-  Variable=UNINSTALL_PATH
-  Value=%_LOGFILE_PATH_%
-  Flags=00000010
-end
-item: Set Variable
-  Variable=UNINSTALL_PATH
-  Value=%UNINSTALL_PATH%\UNWISE.EXE
-end
-item: Compiler Variable If
-  Variable=_EXE_OS_TYPE_
-  Value=WIN32
-end
-item: Install File
-  Source=%_WISE_%\UNWISE32.EXE
-  Destination=%UNINSTALL_PATH%
-  Flags=0000000000000010
-end
-item: Compiler Variable Else
-end
-item: Install File
-  Source=%_WISE_%\UNWISE.EXE
-  Destination=%UNINSTALL_PATH%
-  Flags=0000000000000010
-end
-item: Compiler Variable End
-end
-item: Remark
-end
-item: Remark
-  Text=     Install Support for multiple languages
-end
-item: Remark
-end
-item: Set Variable
-  Variable=UNINSTALL_LANG
-  Value=%UNINSTALL_PATH%
-  Flags=00000010
-end
-item: Set Variable
-  Variable=UNINSTALL_LANG
-  Value=%UNINSTALL_LANG%\UNWISE.INI
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=C
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.FRA
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_C_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.FRA
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=D
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.FRA
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_D_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.FRA
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=E
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.DEU
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_E_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.DEU
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=F
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.PTG
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_F_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.PTG
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=G
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.ESP
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_G_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.ESP
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=H
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.ESP
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_H_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.ESP
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=I
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.ITA
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_I_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.ITA
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=J
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.DAN
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_J_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.DAN
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=K
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.FIN
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_K_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.FIN
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=L
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.ISL
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_L_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.ISL
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=M
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.NLD
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_M_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.NLD
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=N
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.NOR
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_N_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.NOR
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=O
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.SVE
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_O_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.SVE
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Compiler Variable If
-  Variable=_LANG_LIST_
-  Value=P
-  Flags=00000010
-end
-item: Compiler Variable If
-  Value=%_WISE_%\LANGUAGE\UNWISE.JPN
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=LANG
-  Value=%_LANG_P_NAME_%
-end
-item: Install File
-  Source=%_WISE_%\LANGUAGE\UNWISE.JPN
-  Destination=%UNINSTALL_LANG%
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Compiler Variable End
-end
-item: Compiler Variable End
-end
-item: Remark
-end
-item: Remark
-  Text=     Install the add/remove or uninstall icon
-end
-item: Remark
-end
-item: Set Variable
-  Variable=UNINSTALL_PATH
-  Value=%UNINSTALL_PATH%
-  Flags=00010100
-end
-item: Set Variable
-  Variable=INST_LOG_PATH
-  Value=%_LOGFILE_PATH_%
-  Flags=00010100
-end
-item: Check Configuration
-  Flags=10111011
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=1
-end
-item: Remark
-  Text=Write uninstall info under HKLM.  This if/else/end block added by Tim.
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%APPTITLE%
-  Value Name=DisplayName
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%UNINSTALL_PATH% %INST_LOG_PATH%
-  New Value=
-  Value Name=UninstallString
-  Root=2
-end
-item: Else Statement
-end
-item: Remark
-  Text=The same, but write under HKCU instead.
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%APPTITLE%
-  Value Name=DisplayName
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%UNINSTALL_PATH% %INST_LOG_PATH%
-  New Value=
-  Value Name=UninstallString
-  Root=1
-end
-item: End Block
-end
-item: Else Statement
-end
-item: Add ProgMan Icon
-  Group=%GROUP%
-  Icon Name=Uninstall %APPTITLE%
-  Command Line=%UNINSTALL_PATH% %INST_LOG_PATH%
-end
-item: End Block
-end
-item: Check Configuration
-  Flags=11110010
-end
-item: If/While Statement
-  Variable=DOBRAND
-  Value=1
-end
-item: Edit Registry
-  Total Keys=2
-  item: Key
-    Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-    New Value=%COMPANY%
-    Value Name=RegCompany
-    Root=2
-  end
-  item: Key
-    Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-    New Value=%NAME%
-    Value Name=RegOwner
-    Root=2
-  end
-end
-item: End Block
-end
-item: End Block
-end

Deleted: /python/branches/p3yk-noslice/PCbuild8/_bsddb.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_bsddb.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,385 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="_bsddb"
-	ProjectGUID="{E1DBB220-D64B-423D-A545-539A55AA7FE2}"
-	SccProjectName="_bsddb"
-	SccLocalPath=".."
-	SccProvider="MSSCCI:Perforce SCM"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\_bsddb"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include;..\PC;&quot;..\..\db-4.4.20\build_win32&quot;"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\db-4.4.20\build_win32\Debug\libdb44sd.lib"
-				OutputFile="./_bsddb_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_bsddb_d.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=".\./_bsddb_d.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\_bsddb"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include;..\PC;&quot;..\..\db-4.4.20\build_win32&quot;"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\db-4.4.20\build_win32\Release\libdb44s.lib"
-				OutputFile="./_bsddb.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_bsddb.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=".\./_bsddb.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\_bsddb"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_ITANIUM"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include;..\PC;&quot;..\..\db-4.4.20\build_win32&quot;"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\db-4.4.20\build_win32\Release_IA64\libdb44s.lib"
-				OutputFile="./_bsddb.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_bsddb.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=".\./_bsddb.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\_bsddb"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_OPTERON /GS-"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include;..\PC;&quot;..\..\db-4.4.20\build_win32&quot;"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\db-4.4.20\build_win32\Release_AMD64\libdb44s.lib"
-				OutputFile="./_bsddb.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_bsddb.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=".\./_bsddb.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_bsddb.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_ctypes.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_ctypes.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,410 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="_ctypes"
-	ProjectGUID="{F22F40F4-D318-40DC-96B3-88DC81CE0894}"
-	RootNamespace="_ctypes"
-	Keyword="Win32Proj"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\_ctypes\libffi_msvc"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				MinimalRebuild="false"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="false"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions="/EXPORT:DllGetClassObject,PRIVATE /EXPORT:DllCanUnloadNow,PRIVATE"
-				OutputFile="$(OutDir)\_ctypes_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				BaseAddress="0x1D1A0000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\_ctypes\libffi_msvc"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				MinimalRebuild="false"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="false"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions="/EXPORT:DllGetClassObject,PRIVATE /EXPORT:DllCanUnloadNow,PRIVATE"
-				OutputFile="$(OutDir)\_ctypes_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				BaseAddress="0x1D1A0000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\_ctypes\libffi_msvc"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="false"
-				DebugInformationFormat="0"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions="/EXPORT:DllGetClassObject,PRIVATE /EXPORT:DllCanUnloadNow,PRIVATE"
-				OutputFile="$(OutDir)\_ctypes.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				OptimizeReferences="0"
-				EnableCOMDATFolding="0"
-				BaseAddress="0x1D1A0000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\_ctypes\libffi_msvc"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="false"
-				DebugInformationFormat="0"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions="/EXPORT:DllGetClassObject,PRIVATE /EXPORT:DllCanUnloadNow,PRIVATE"
-				OutputFile="$(OutDir)\_ctypes.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				OptimizeReferences="0"
-				EnableCOMDATFolding="0"
-				BaseAddress="0x1D1A0000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_ctypes\_ctypes.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\callbacks.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\callproc.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\cfield.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\libffi_msvc\ffi.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\malloc_closure.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\libffi_msvc\prep_cif.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\stgdict.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_ctypes\libffi_msvc\win32.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_ctypes_test.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_ctypes_test.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,370 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="_ctypes_test"
-	ProjectGUID="{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}"
-	RootNamespace="_ctypes_test"
-	Keyword="Win32Proj"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes_test"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				MinimalRebuild="false"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\_ctypes_test_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes_test"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				MinimalRebuild="false"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)/_ctypes_test_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes_test"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="0"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\_ctypes_test.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				OptimizeReferences="0"
-				EnableCOMDATFolding="0"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_ctypes_test"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="0"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\_ctypes_test.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="0"
-				OptimizeReferences="0"
-				EnableCOMDATFolding="0"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_ctypes\_ctypes_test.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_elementtree.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_elementtree.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,388 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="_elementtree"
-	ProjectGUID="{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}"
-	RootNamespace="_elementtree"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_elementtree"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="_DEBUG;HAVE_EXPAT_H;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\_elementtree_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_elementtree"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="_DEBUG;HAVE_EXPAT_H;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\_elementtree_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_elementtree"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\_elementtree.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_elementtree"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\_elementtree.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_elementtree.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\expat\xmlparse.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\expat\xmlrole.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\expat\xmltok.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_msi.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_msi.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,375 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="_msi"
-	ProjectGUID="{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}"
-	RootNamespace="_msi"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_msi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="fci.lib msi.lib rpcrt4.lib"
-				OutputFile="$(OutDir)\_msi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_msi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="fci.lib msi.lib rpcrt4.lib"
-				OutputFile="$(OutDir)\_msi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_msi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="fci.lib msi.lib rpcrt4.lib"
-				OutputFile="$(OutDir)\_msi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_msi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="fci.lib msi.lib rpcrt4.lib"
-				OutputFile="$(OutDir)\_msi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\PC\_msi.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_socket.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_socket.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,381 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="_socket"
-	ProjectGUID="{324F66C2-44D0-4D50-B979-F9DAE7FD36DB}"
-	SccProjectName="_socket"
-	SccLocalPath=".."
-	SccProvider="MSSCCI:Perforce SCM"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\_socket"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="ws2_32.lib"
-				OutputFile="./_socket_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_socket_d.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e1D0000"
-				ImportLibrary=".\./_socket_d.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\_socket"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="ws2_32.lib"
-				OutputFile="./_socket.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_socket.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e1D0000"
-				ImportLibrary=".\./_socket.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\_socket"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_ITANIUM"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
-				AdditionalDependencies="ws2_32.lib"
-				OutputFile="./_socket.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_socket.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e1D0000"
-				ImportLibrary=".\./_socket.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\_socket"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_OPTERON /GS-"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				AdditionalDependencies="ws2_32.lib"
-				OutputFile="./_socket.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_socket.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e1D0000"
-				ImportLibrary=".\./_socket.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\socketmodule.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_sqlite3.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_sqlite3.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,411 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="_sqlite3"
-	ProjectGUID="{2FF0A312-22F9-4C34-B070-842916DE27A9}"
-	RootNamespace="_sqlite3"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_sqlite3"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include;..\PC;..\..\sqlite-source-3.3.4"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;MODULE_NAME=\&quot;sqlite3\&quot;"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\sqlite-source-3.3.4\sqlite3.lib"
-				OutputFile="$(OutDir)\_sqlite3_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_sqlite"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include;..\PC;..\..\sqlite-source-3.3.4"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;MODULE_NAME=\&quot;sqlite3\&quot;"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\sqlite-source-3.3.4\sqlite3.lib"
-				OutputFile="$(OutDir)\_sqlite3_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_sqlite3"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include;..\PC;..\..\sqlite-source-3.3.4"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;MODULE_NAME=\&quot;sqlite3\&quot;"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\sqlite-source-3.3.4\sqlite3.lib"
-				OutputFile="$(OutDir)\_sqlite3.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\_sqlite3"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include;..\PC;..\..\sqlite-source-3.3.4"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;MODULE_NAME=\&quot;sqlite3\&quot;"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\sqlite-source-3.3.4\sqlite3.lib"
-				OutputFile="$(OutDir)\_sqlite3.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1e180000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_sqlite\cache.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\connection.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\cursor.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\microprotocols.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\module.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\prepare_protocol.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\row.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\statement.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sqlite\util.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_ssl.mak
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_ssl.mak	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,21 +0,0 @@
-
-!IFDEF DEBUG
-MODULE=_ssl_d.pyd
-TEMP_DIR=x86-temp-debug/_ssl
-CFLAGS=/Od /Zi /MDd /LDd /DDEBUG /D_DEBUG /DWIN32
-SSL_LIB_DIR=$(SSL_DIR)/out32.dbg
-!ELSE
-MODULE=_ssl.pyd
-TEMP_DIR=x86-temp-release/_ssl
-CFLAGS=/Ox /MD /LD /DWIN32
-SSL_LIB_DIR=$(SSL_DIR)/out32
-!ENDIF
-
-INCLUDES=-I ../Include -I ../PC -I $(SSL_DIR)/inc32
-LIBS=gdi32.lib wsock32.lib user32.lib advapi32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib
-
-SOURCE=../Modules/_ssl.c $(SSL_LIB_DIR)/libeay32.lib $(SSL_LIB_DIR)/ssleay32.lib
-
-$(MODULE): $(SOURCE) ../PC/*.h ../Include/*.h
-    @if not exist "$(TEMP_DIR)/." mkdir "$(TEMP_DIR)"
-    cl /nologo $(SOURCE) $(CFLAGS) /Fo$(TEMP_DIR)\$*.obj $(INCLUDES) /link /out:$(MODULE) $(LIBS)

Deleted: /python/branches/p3yk-noslice/PCbuild8/_ssl.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_ssl.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,121 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="_ssl"
-	ProjectGUID="{8E85BA54-8A47-4C8B-B72E-8E17579CC6D7}"
-	RootNamespace="_ssl"
-	Keyword="MakeFileProj"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\_ssl"
-			ConfigurationType="0"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCNMakeTool"
-				BuildCommandLine="python build_ssl.py"
-				ReBuildCommandLine="python build_ssl.py -a"
-				CleanCommandLine="echo Nothing to do"
-				Output="_ssl.pyd"
-				PreprocessorDefinitions=""
-				IncludeSearchPath=""
-				ForcedIncludes=""
-				AssemblySearchPath=""
-				ForcedUsingAssemblies=""
-				CompileAsManaged=""
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\_ssl"
-			ConfigurationType="0"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCNMakeTool"
-				BuildCommandLine="python_d -u build_ssl.py -d"
-				ReBuildCommandLine="python_d -u build_ssl.py -d -a"
-				CleanCommandLine="echo Nothing to do"
-				Output="_ssl_d.pyd"
-				PreprocessorDefinitions=""
-				IncludeSearchPath=""
-				ForcedIncludes=""
-				AssemblySearchPath=""
-				ForcedUsingAssemblies=""
-				CompileAsManaged=""
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\_ssl"
-			ConfigurationType="0"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCNMakeTool"
-				BuildCommandLine="python build_ssl.py"
-				ReBuildCommandLine="python build_ssl.py -a"
-				CleanCommandLine=""
-				Output="_ssl.pyd"
-				PreprocessorDefinitions=""
-				IncludeSearchPath=""
-				ForcedIncludes=""
-				AssemblySearchPath=""
-				ForcedUsingAssemblies=""
-				CompileAsManaged=""
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\_ssl"
-			ConfigurationType="0"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCNMakeTool"
-				BuildCommandLine="python build_ssl.py"
-				ReBuildCommandLine="python build_ssl.py -a"
-				CleanCommandLine=""
-				Output="_ssl.pyd"
-				PreprocessorDefinitions=""
-				IncludeSearchPath=""
-				ForcedIncludes=""
-				AssemblySearchPath=""
-				ForcedUsingAssemblies=""
-				CompileAsManaged=""
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_ssl.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_testcapi.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_testcapi.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,374 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="_testcapi"
-	ProjectGUID="{59CBF474-9E06-4C50-9142-C44A118BB447}"
-	SccProjectName="_testcapi"
-	SccLocalPath=".."
-	SccProvider="MSSCCI:Perforce SCM"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\_testcapi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="./_testcapi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				ProgramDatabaseFile=".\./_testcapi.pdb"
-				BaseAddress="0x1e1F0000"
-				ImportLibrary=".\./_testcapi.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\_testcapi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="./_testcapi_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_testcapi_d.pdb"
-				BaseAddress="0x1e1F0000"
-				ImportLibrary=".\./_testcapi_d.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\_testcapi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_ITANIUM"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
-				OutputFile="./_testcapi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				ProgramDatabaseFile=".\./_testcapi.pdb"
-				BaseAddress="0x1e1F0000"
-				ImportLibrary=".\./_testcapi.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\_testcapi"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_OPTERON /GS-"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				OutputFile="./_testcapi.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				ProgramDatabaseFile=".\./_testcapi.pdb"
-				BaseAddress="0x1e1F0000"
-				ImportLibrary=".\./_testcapi.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_testcapimodule.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/_tkinter.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/_tkinter.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,389 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="_tkinter"
-	ProjectGUID="{5B51DFF7-5DC0-41F8-8791-A4AB7114A151}"
-	SccProjectName="_tkinter"
-	SccLocalPath="..\.."
-	SccProvider="MSSCCI:Perforce SCM"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\_tkinter"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\..\tcltk\include,..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;WITH_APPINIT"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\tcltk\lib\tk84.lib ..\..\tcltk\lib\tcl84.lib odbccp32.lib"
-				OutputFile="./_tkinter.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_tkinter.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e190000"
-				ImportLibrary=".\./_tkinter.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\_tkinter"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\..\tcltk\include,..\Include,..\PC"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;WITH_APPINIT"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\tcltk\lib\tk84.lib ..\..\tcltk\lib\tcl84.lib odbccp32.lib"
-				OutputFile="./_tkinter_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_tkinter_d.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e190000"
-				ImportLibrary=".\./_tkinter_d.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\_tkinter"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_ITANIUM"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\..\tcltk\include,..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;WITH_APPINIT"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\tcltk\lib\tk84.lib ..\..\tcltk\lib\tcl84.lib odbccp32.lib"
-				OutputFile="./_tkinter.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_tkinter.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e190000"
-				ImportLibrary=".\./_tkinter.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\_tkinter"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_OPTERON /GS-"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\..\tcltk\include,..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;WITH_APPINIT"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\tcltk\lib\tk84.lib ..\..\tcltk\lib\tcl84.lib odbccp32.lib"
-				OutputFile="./_tkinter.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories=""
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./_tkinter.pdb"
-				SubSystem="2"
-				BaseAddress="0x1e190000"
-				ImportLibrary=".\./_tkinter.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\_tkinter.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\tkappinit.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/build_ssl.py
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/build_ssl.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,163 +0,0 @@
-# Script for building the _ssl module for Windows.
-# Uses Perl to setup the OpenSSL environment correctly
-# and build OpenSSL, then invokes a simple nmake session
-# for _ssl.pyd itself.
-
-# THEORETICALLY, you can:
-# * Unpack the latest SSL release one level above your main Python source
-#   directory.  It is likely you will already find the zlib library and
-#   any other external packages there.
-# * Install ActivePerl and ensure it is somewhere on your path.
-# * Run this script from the PCBuild directory.
-#
-# it should configure and build SSL, then build the ssl Python extension
-# without intervention.
-
-import os, sys, re
-
-# Find all "foo.exe" files on the PATH.
-def find_all_on_path(filename, extras = None):
-    entries = os.environ["PATH"].split(os.pathsep)
-    ret = []
-    for p in entries:
-        fname = os.path.abspath(os.path.join(p, filename))
-        if os.path.isfile(fname) and fname not in ret:
-            ret.append(fname)
-    if extras:
-        for p in extras:
-            fname = os.path.abspath(os.path.join(p, filename))
-            if os.path.isfile(fname) and fname not in ret:
-                ret.append(fname)
-    return ret
-
-# Find a suitable Perl installation for OpenSSL.
-# cygwin perl does *not* work.  ActivePerl does.
-# Being a Perl dummy, the simplest way I can check is if the "Win32" package
-# is available.
-def find_working_perl(perls):
-    for perl in perls:
-        fh = os.popen(perl + ' -e "use Win32;"')
-        fh.read()
-        rc = fh.close()
-        if rc:
-            continue
-        return perl
-    print "Can not find a suitable PERL:"
-    if perls:
-        print " the following perl interpreters were found:"
-        for p in perls:
-            print " ", p
-        print " None of these versions appear suitable for building OpenSSL"
-    else:
-        print " NO perl interpreters were found on this machine at all!"
-    print " Please install ActivePerl and ensure it appears on your path"
-    print "The Python SSL module was not built"
-    return None
-
-# Locate the best SSL directory given a few roots to look into.
-def find_best_ssl_dir(sources):
-    candidates = []
-    for s in sources:
-        try:
-            s = os.path.abspath(s)
-            fnames = os.listdir(s)
-        except os.error:
-            fnames = []
-        for fname in fnames:
-            fqn = os.path.join(s, fname)
-            if os.path.isdir(fqn) and fname.startswith("openssl-"):
-                candidates.append(fqn)
-    # Now we have all the candidates, locate the best.
-    best_parts = []
-    best_name = None
-    for c in candidates:
-        parts = re.split("[.-]", os.path.basename(c))[1:]
-        # eg - openssl-0.9.7-beta1 - ignore all "beta" or any other qualifiers
-        if len(parts) >= 4:
-            continue
-        if parts > best_parts:
-            best_parts = parts
-            best_name = c
-    if best_name is not None:
-        print "Found an SSL directory at '%s'" % (best_name,)
-    else:
-        print "Could not find an SSL directory in '%s'" % (sources,)
-    return best_name
-
-def main():
-    debug = "-d" in sys.argv
-    build_all = "-a" in sys.argv
-    make_flags = ""
-    if build_all:
-        make_flags = "-a"
-    # perl should be on the path, but we also look in "\perl" and "c:\\perl"
-    # as "well known" locations
-    perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"])
-    perl = find_working_perl(perls)
-    if perl is None:
-        sys.exit(1)
-
-    print "Found a working perl at '%s'" % (perl,)
-    # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live.
-    ssl_dir = find_best_ssl_dir(("../..",))
-    if ssl_dir is None:
-        sys.exit(1)
-
-    old_cd = os.getcwd()
-    try:
-        os.chdir(ssl_dir)
-        # If the ssl makefiles do not exist, we invoke Perl to generate them.
-        if not os.path.isfile(os.path.join(ssl_dir, "32.mak")) or \
-           not os.path.isfile(os.path.join(ssl_dir, "d32.mak")):
-            print "Creating the makefiles..."
-            # Put our working Perl at the front of our path
-            os.environ["PATH"] = os.path.split(perl)[0] + \
-                                          os.pathsep + \
-                                          os.environ["PATH"]
-            # ms\32all.bat will reconfigure OpenSSL and then try to build
-            # all outputs (debug/nondebug/dll/lib).  So we filter the file
-            # to exclude any "nmake" commands and then execute.
-            tempname = "ms\\32all_py.bat"
-
-            in_bat  = open("ms\\32all.bat")
-            temp_bat = open(tempname,"w")
-            while 1:
-                cmd = in_bat.readline()
-                print 'cmd', repr(cmd)
-                if not cmd: break
-                if cmd.strip()[:5].lower() == "nmake":
-                    continue
-                temp_bat.write(cmd)
-            in_bat.close()
-            temp_bat.close()
-            os.system(tempname)
-            try:
-                os.remove(tempname)
-            except:
-                pass
-
-        # Now run make.
-        print "Executing nmake over the ssl makefiles..."
-        if debug:
-            rc = os.system("nmake /nologo -f d32.mak")
-            if rc:
-                print "Executing d32.mak failed"
-                print rc
-                sys.exit(rc)
-        else:
-            rc = os.system("nmake /nologo -f 32.mak")
-            if rc:
-                print "Executing 32.mak failed"
-                print rc
-                sys.exit(rc)
-    finally:
-        os.chdir(old_cd)
-    # And finally, we can build the _ssl module itself for Python.
-    defs = "SSL_DIR=%s" % (ssl_dir,)
-    if debug:
-        defs = defs + " " + "DEBUG=1"
-    rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags)
-    sys.exit(rc)
-
-if __name__=='__main__':
-    main()

Deleted: /python/branches/p3yk-noslice/PCbuild8/bz2.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/bz2.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,390 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="bz2"
-	ProjectGUID="{AC557788-6354-43F7-BE05-C9C8C59A344A}"
-	RootNamespace="bz2"
-	SccProjectName="bz2"
-	SccLocalPath=".."
-	SccProvider="MSSCCI:Perforce SCM"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\bz2"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\..\bzip2-1.0.3"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine="cd ..\..\bzip2-1.0.3&#x0D;&#x0A;nmake /nologo /f makefile.msc&#x0D;&#x0A;"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\bzip2-1.0.3\libbz2.lib"
-				OutputFile="./bz2_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="msvcrt,libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./bz2_d.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D170000"
-				ImportLibrary=".\./bz2_d.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\bz2"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\..\bzip2-1.0.3"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine="cd ..\..\bzip2-1.0.3&#x0D;&#x0A;nmake /nologo /f makefile.msc lib&#x0D;&#x0A;"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="..\..\bzip2-1.0.3\libbz2.lib"
-				OutputFile="./bz2.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./bz2.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D170000"
-				ImportLibrary=".\./bz2.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\bz2"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_ITANIUM"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\..\bzip2-1.0.3"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine="cd ..\..\bzip2-1.0.3&#x0D;&#x0A;nmake /nologo /f makefile.msc lib&#x0D;&#x0A;"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\bzip2-1.0.3\libbz2.lib"
-				OutputFile="./bz2.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./bz2.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D170000"
-				ImportLibrary=".\./bz2.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\bz2"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_OPTERON /GS-"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\..\bzip2-1.0.3"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine="cd ..\..\bzip2-1.0.3&#x0D;&#x0A;nmake /nologo /f makefile.msc lib&#x0D;&#x0A;"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				AdditionalDependencies="..\..\bzip2-1.0.3\libbz2.lib"
-				OutputFile="./bz2.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./bz2.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D170000"
-				ImportLibrary=".\./bz2.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\bz2module.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/db.build
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/db.build	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,10 +0,0 @@
-<?xml version="1.0"?>
-<project>
- <target name="all" description="Build all targets.">
-   <solution configuration="release">
-     <projects>
-       <include name="db_static.vcproj" />
-     </projects>
-   </solution>
- </target>
-</project>

Deleted: /python/branches/p3yk-noslice/PCbuild8/field3.py
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/field3.py	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,35 +0,0 @@
-# An absurd workaround for the lack of arithmetic in MS's resource compiler.
-# After building Python, run this, then paste the output into the appropriate
-# part of PC\python_nt.rc.
-# Example output:
-#
-# * For 2.3a0,
-# * PY_MICRO_VERSION = 0
-# * PY_RELEASE_LEVEL = 'alpha' = 0xA
-# * PY_RELEASE_SERIAL = 1
-# *
-# * and 0*1000 + 10*10 + 1 = 101.
-# */
-# #define FIELD3 101
-
-import sys
-
-major, minor, micro, level, serial = sys.version_info
-levelnum = {'alpha': 0xA,
-            'beta': 0xB,
-            'candidate': 0xC,
-            'final': 0xF,
-           }[level]
-string = sys.version.split()[0] # like '2.3a0'
-
-print " * For %s," % string
-print " * PY_MICRO_VERSION = %d" % micro
-print " * PY_RELEASE_LEVEL = %r = %s" % (level, hex(levelnum))
-print " * PY_RELEASE_SERIAL = %d" % serial
-print " *"
-
-field3 = micro * 1000 + levelnum * 10 + serial
-
-print " * and %d*1000 + %d*10 + %d = %d" % (micro, levelnum, serial, field3)
-print " */"
-print "#define FIELD3", field3

Deleted: /python/branches/p3yk-noslice/PCbuild8/make_buildinfo.c
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/make_buildinfo.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,81 +0,0 @@
-#include <windows.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdio.h>
-
-/* This file creates the getbuildinfo2.c file, by
-   invoking subwcrev.exe (if found).
-   If this isn't a subversion checkout, or subwcrev isn't
-   found, it copies ..\\Modules\\getbuildinfo.c instead.
-
-   A file, getbuildinfo2.h is then updated to define
-   SUBWCREV if it was a subversion checkout.
-
-   getbuildinfo2.c is part of the pythoncore project with
-   getbuildinfo2.h as a forced include.  This helps
-   VisualStudio refrain from unnecessary compiles much of the
-   time.
-
-   Currently, subwcrev.exe is found from the registry entries
-   of TortoiseSVN.
-
-   make_buildinfo.exe is called as a pre-build step for pythoncore.
-
-*/
-
-int make_buildinfo2()
-{
-	struct _stat st;
-	HKEY hTortoise;
-	char command[500];
-	DWORD type, size;
-	if (_stat(".svn", &st) < 0)
-		return 0;
-	/* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
-	if (_stat("no_subwcrev", &st) == 0)
-		return 0;
-	if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
-	    RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
-		/* Tortoise not installed */
-		return 0;
-	command[0] = '"';  /* quote the path to the executable */
-	size = sizeof(command) - 1;
-	if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
-	    type != REG_SZ)
-		/* Registry corrupted */
-		return 0;
-	strcat_s(command, sizeof(command), "bin\\subwcrev.exe");
-	if (_stat(command+1, &st) < 0)
-		/* subwcrev.exe not part of the release */
-		return 0;
-	strcat_s(command, sizeof(command), "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c");
-	puts(command); fflush(stdout);
-	if (system(command) < 0)
-		return 0;
-	return 1;
-}
-
-int main(int argc, char*argv[])
-{
-	char command[500] = "";
-	int svn;
-	FILE *f;
-
-	if (fopen_s(&f, "getbuildinfo2.h", "w"))
-		return EXIT_FAILURE;
-	/* Get getbuildinfo.c from svn as getbuildinfo2.c */
-	svn = make_buildinfo2();
-	if (svn) {
-		puts("got getbuildinfo2.c from svn.  Updating getbuildinfo2.h");
-		/* yes.  make sure SUBWCREV is defined */
-		fprintf(f, "#define SUBWCREV\n");
-	} else {
-		puts("didn't get getbuildinfo2.c from svn.  Copying from Modules and clearing getbuildinfo2.h");
-		strcat_s(command, sizeof(command), "copy ..\\Modules\\getbuildinfo.c getbuildinfo2.c");
-		puts(command); fflush(stdout);
-		if (system(command) < 0)
-			return EXIT_FAILURE;
-	}
-	fclose(f);
-	return 0;
-}
\ No newline at end of file

Deleted: /python/branches/p3yk-noslice/PCbuild8/make_buildinfo.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/make_buildinfo.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,115 +0,0 @@
-<?xml version="1.0" encoding="windows-1250"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="make_buildinfo"
-	ProjectGUID="{C73F0EC1-358B-4177-940F-0846AC8B04CD}"
-	RootNamespace="make_buildinfo"
-	Keyword="Win32Proj"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="."
-			IntermediateDirectory=".\x86-temp-release\make_buildinfo"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_DEPRECATE"
-				MinimalRebuild="true"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="1"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="4"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)/make_buildinfo.exe"
-				LinkIncremental="2"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile="$(OutDir)/make_buildinfo.pdb"
-				SubSystem="1"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-				Description="Making getbuildinfo2.c"
-				CommandLine="$(TargetPath)"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<Filter
-			Name="Source Files"
-			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
-			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
-			>
-			<File
-				RelativePath=".\make_buildinfo.c"
-				>
-			</File>
-		</Filter>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/make_versioninfo.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/make_versioninfo.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,204 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="make_versioninfo"
-	ProjectGUID="{F0E0541E-F17D-430B-97C4-93ADF0DD284E}"
-	RootNamespace="make_versioninfo"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\make_versioninfo"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-				CommandLine=".\make_versioninfo.exe &gt;..\PC\pythonnt_rc.h&#x0D;&#x0A;"
-				Outputs="..\PC\pythonnt_rc.h"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile=".\./make_versioninfo.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./make_versioninfo.pdb"
-				SubSystem="1"
-				BaseAddress="0x1d000000"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-				CommandLine="$(TargetFileName) &gt; ..\PC\python_nt.h"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\make_versioninfo"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-				CommandLine=".\make_versioninfo_d.exe &gt;..\PC\pythonnt_rc_d.h&#x0D;&#x0A;"
-				Outputs="..\PC\pythonnt_rc_d.h"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				BrowseInformation="1"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="./make_versioninfo_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./make_versioninfo_d.pdb"
-				SubSystem="1"
-				BaseAddress="0x1d000000"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-				CommandLine="$(TargetFileName) &gt; ..\PC\python_nt_d.h"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\PC\make_versioninfo.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Modified: python/branches/p3yk-noslice/PCbuild8/pcbuild.sln
==============================================================================
--- python/branches/p3yk-noslice/PCbuild8/pcbuild.sln	(original)
+++ python/branches/p3yk-noslice/PCbuild8/pcbuild.sln	Wed Jul 11 15:40:56 2007
@@ -1,304 +1,410 @@
 Microsoft Visual Studio Solution File, Format Version 9.00
 # Visual Studio 2005
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythoncore", "pythoncore.vcproj", "{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythoncore", "pythoncore\pythoncore.vcproj", "{987306EC-6BAD-4440-B4FB-A699A1EE6A28}"
 	ProjectSection(ProjectDependencies) = postProject
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E} = {F0E0541E-F17D-430B-97C4-93ADF0DD284E}
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD} = {C73F0EC1-358B-4177-940F-0846AC8B04CD}
+		{87AB87DB-B665-4621-A67B-878C15B93FF0} = {87AB87DB-B665-4621-A67B-878C15B93FF0}
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED} = {2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythonw", "pythonw.vcproj", "{F4229CC3-873C-49AE-9729-DD308ED4CD4A}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_versioninfo", "make_versioninfo\make_versioninfo.vcproj", "{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_buildinfo", "make_buildinfo\make_buildinfo.vcproj", "{87AB87DB-B665-4621-A67B-878C15B93FF0}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_ctypes", "_ctypes\_ctypes.vcproj", "{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "select", "select.vcproj", "{97239A56-DBC0-41D2-BC14-C87D9B97D63B}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_ctypes_test", "_ctypes_test\_ctypes_test.vcproj", "{F548A318-960A-4B37-9CD6-86B1B0E33CC8}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "unicodedata", "unicodedata.vcproj", "{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_elementtree", "_elementtree\_elementtree.vcproj", "{CB025148-F0A1-4B32-A669-19EE0534136D}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "w9xpopen", "w9xpopen.vcproj", "{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_msi", "_msi\_msi.vcproj", "{A25ADCC5-8DE1-4F88-B842-C287923280B1}"
+	ProjectSection(ProjectDependencies) = postProject
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
+	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "winsound", "winsound.vcproj", "{51F35FAE-FB92-4B2C-9187-1542C065AD77}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_sqlite3", "_sqlite3\_sqlite3.vcproj", "{D50E5319-41CC-429A-8E81-B1CD391C3A7B}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_elementtree", "_elementtree.vcproj", "{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "python", "python\python.vcproj", "{AE617428-B823-4B87-BC6D-DC7C12C746D3}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_buildinfo", "make_buildinfo.vcproj", "{C73F0EC1-358B-4177-940F-0846AC8B04CD}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythonw", "pythonw\pythonw.vcproj", "{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}"
+	ProjectSection(ProjectDependencies) = postProject
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
+	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_msi", "_msi.vcproj", "{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "select", "select\select.vcproj", "{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_ctypes", "_ctypes.vcproj", "{F22F40F4-D318-40DC-96B3-88DC81CE0894}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "unicodedata", "unicodedata\unicodedata.vcproj", "{D04B2089-7DA9-4D92-B23F-07453BC46652}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_ctypes_test", "_ctypes_test.vcproj", "{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "winsound", "winsound\winsound.vcproj", "{1015E3B4-FD3B-4402-AA6E-7806514156D6}"
 	ProjectSection(ProjectDependencies) = postProject
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894} = {F22F40F4-D318-40DC-96B3-88DC81CE0894}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_sqlite3", "_sqlite3.vcproj", "{2FF0A312-22F9-4C34-B070-842916DE27A9}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_socket", "_socket\_socket.vcproj", "{AE31A248-5367-4EB2-A511-8722BC351CB4}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8B172265-1F31-4880-A29C-11A4B7A80172}"
-	ProjectSection(SolutionItems) = preProject
-		..\Modules\getbuildinfo.c = ..\Modules\getbuildinfo.c
-		readme.txt = readme.txt
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_bsddb", "_bsddb\_bsddb.vcproj", "{E644B843-F7CA-4888-AA6D-653C77592856}"
+	ProjectSection(ProjectDependencies) = postProject
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "python", "python.vcproj", "{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_testcapi", "_testcapi\_testcapi.vcproj", "{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}"
 	ProjectSection(ProjectDependencies) = postProject
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
 	EndProjectSection
 EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "make_versioninfo", "make_versioninfo.vcproj", "{F0E0541E-F17D-430B-97C4-93ADF0DD284E}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_tkinter", "_tkinter\_tkinter.vcproj", "{3A1515AF-3694-4222-91F2-9837BDF60F9A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bz2", "bz2\bz2.vcproj", "{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}"
+	ProjectSection(ProjectDependencies) = postProject
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pyexpat", "pyexpat\pyexpat.vcproj", "{80EBF51A-6018-4589-9A53-5AAF2872E230}"
+	ProjectSection(ProjectDependencies) = postProject
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28} = {987306EC-6BAD-4440-B4FB-A699A1EE6A28}
+	EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{310B6D98-CFE1-4215-97C1-E52989488A50}"
+	ProjectSection(SolutionItems) = preProject
+		readme.txt = readme.txt
+	EndProjectSection
 EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
 		Debug|x64 = Debug|x64
-		PGIRelease|Win32 = PGIRelease|Win32
-		PGIRelease|x64 = PGIRelease|x64
-		PGORelease|Win32 = PGORelease|Win32
-		PGORelease|x64 = PGORelease|x64
+		PGInstrument|Win32 = PGInstrument|Win32
+		PGInstrument|x64 = PGInstrument|x64
+		PGUpdate|Win32 = PGUpdate|Win32
+		PGUpdate|x64 = PGUpdate|x64
 		Release|Win32 = Release|Win32
 		Release|x64 = Release|x64
 	EndGlobalSection
 	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Debug|Win32.ActiveCfg = Debug|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Debug|Win32.Build.0 = Debug|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Debug|x64.ActiveCfg = Debug|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Debug|x64.Build.0 = Debug|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGIRelease|Win32.ActiveCfg = PGIRelease|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGIRelease|Win32.Build.0 = PGIRelease|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGIRelease|x64.ActiveCfg = PGIRelease|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGIRelease|x64.Build.0 = PGIRelease|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGORelease|Win32.ActiveCfg = PGORelease|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGORelease|Win32.Build.0 = PGORelease|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGORelease|x64.ActiveCfg = PGORelease|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.PGORelease|x64.Build.0 = PGORelease|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Release|Win32.ActiveCfg = Release|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Release|Win32.Build.0 = Release|Win32
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Release|x64.ActiveCfg = Release|x64
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}.Release|x64.Build.0 = Release|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Debug|Win32.ActiveCfg = Debug|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Debug|Win32.Build.0 = Debug|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Debug|x64.ActiveCfg = Debug|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Debug|x64.Build.0 = Debug|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGIRelease|Win32.Build.0 = Release|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGIRelease|x64.ActiveCfg = Release|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGIRelease|x64.Build.0 = Release|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGORelease|Win32.Build.0 = Release|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGORelease|x64.ActiveCfg = Release|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.PGORelease|x64.Build.0 = Release|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Release|Win32.ActiveCfg = Release|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Release|Win32.Build.0 = Release|Win32
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Release|x64.ActiveCfg = Release|x64
-		{F4229CC3-873C-49AE-9729-DD308ED4CD4A}.Release|x64.Build.0 = Release|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Debug|Win32.ActiveCfg = Debug|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Debug|Win32.Build.0 = Debug|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Debug|x64.ActiveCfg = Debug|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Debug|x64.Build.0 = Debug|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGIRelease|Win32.Build.0 = Release|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGIRelease|x64.ActiveCfg = Release|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGIRelease|x64.Build.0 = Release|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGORelease|Win32.Build.0 = Release|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGORelease|x64.ActiveCfg = Release|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.PGORelease|x64.Build.0 = Release|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Release|Win32.ActiveCfg = Release|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Release|Win32.Build.0 = Release|Win32
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Release|x64.ActiveCfg = Release|x64
-		{97239A56-DBC0-41D2-BC14-C87D9B97D63B}.Release|x64.Build.0 = Release|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Debug|Win32.ActiveCfg = Debug|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Debug|Win32.Build.0 = Debug|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Debug|x64.ActiveCfg = Debug|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Debug|x64.Build.0 = Debug|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGIRelease|Win32.Build.0 = Release|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGIRelease|x64.ActiveCfg = Release|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGIRelease|x64.Build.0 = Release|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGORelease|Win32.Build.0 = Release|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGORelease|x64.ActiveCfg = Release|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.PGORelease|x64.Build.0 = Release|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Release|Win32.ActiveCfg = Release|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Release|Win32.Build.0 = Release|Win32
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Release|x64.ActiveCfg = Release|x64
-		{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}.Release|x64.Build.0 = Release|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Debug|Win32.ActiveCfg = Debug|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Debug|Win32.Build.0 = Debug|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Debug|x64.ActiveCfg = Debug|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Debug|x64.Build.0 = Debug|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGIRelease|Win32.Build.0 = Release|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGIRelease|x64.ActiveCfg = Release|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGIRelease|x64.Build.0 = Release|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGORelease|Win32.Build.0 = Release|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGORelease|x64.ActiveCfg = Release|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.PGORelease|x64.Build.0 = Release|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Release|Win32.ActiveCfg = Release|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Release|Win32.Build.0 = Release|Win32
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Release|x64.ActiveCfg = Release|x64
-		{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}.Release|x64.Build.0 = Release|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Debug|Win32.ActiveCfg = Debug|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Debug|Win32.Build.0 = Debug|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Debug|x64.ActiveCfg = Debug|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Debug|x64.Build.0 = Debug|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGIRelease|Win32.Build.0 = Release|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGIRelease|x64.ActiveCfg = Release|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGIRelease|x64.Build.0 = Release|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGORelease|Win32.Build.0 = Release|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGORelease|x64.ActiveCfg = Release|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.PGORelease|x64.Build.0 = Release|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Release|Win32.ActiveCfg = Release|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Release|Win32.Build.0 = Release|Win32
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Release|x64.ActiveCfg = Release|x64
-		{51F35FAE-FB92-4B2C-9187-1542C065AD77}.Release|x64.Build.0 = Release|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Debug|Win32.Build.0 = Debug|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Debug|x64.ActiveCfg = Debug|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Debug|x64.Build.0 = Debug|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGIRelease|Win32.Build.0 = Release|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGIRelease|x64.ActiveCfg = Release|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGIRelease|x64.Build.0 = Release|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGORelease|Win32.Build.0 = Release|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGORelease|x64.ActiveCfg = Release|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.PGORelease|x64.Build.0 = Release|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Release|Win32.ActiveCfg = Release|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Release|Win32.Build.0 = Release|Win32
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Release|x64.ActiveCfg = Release|x64
-		{1966DDE2-4AB7-4E4E-ACC9-C121E4D37F8E}.Release|x64.Build.0 = Release|x64
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Debug|Win32.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Debug|Win32.Build.0 = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Debug|x64.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Debug|x64.Build.0 = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.PGIRelease|Win32.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.PGIRelease|Win32.Build.0 = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.PGIRelease|x64.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.PGORelease|Win32.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.PGORelease|Win32.Build.0 = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.PGORelease|x64.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Release|Win32.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Release|Win32.Build.0 = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Release|x64.ActiveCfg = Debug|Win32
-		{C73F0EC1-358B-4177-940F-0846AC8B04CD}.Release|x64.Build.0 = Debug|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Debug|Win32.ActiveCfg = Debug|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Debug|Win32.Build.0 = Debug|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Debug|x64.ActiveCfg = Debug|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Debug|x64.Build.0 = Debug|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGIRelease|Win32.Build.0 = Release|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGIRelease|x64.ActiveCfg = Release|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGIRelease|x64.Build.0 = Release|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGORelease|Win32.Build.0 = Release|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGORelease|x64.ActiveCfg = Release|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.PGORelease|x64.Build.0 = Release|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Release|Win32.ActiveCfg = Release|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Release|Win32.Build.0 = Release|Win32
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Release|x64.ActiveCfg = Release|x64
-		{2C0BEFB9-70E2-4F80-AC5B-4AB8EE023574}.Release|x64.Build.0 = Release|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Debug|Win32.ActiveCfg = Debug|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Debug|Win32.Build.0 = Debug|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Debug|x64.ActiveCfg = Debug|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Debug|x64.Build.0 = Debug|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGIRelease|Win32.Build.0 = Release|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGIRelease|x64.ActiveCfg = Release|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGIRelease|x64.Build.0 = Release|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGORelease|Win32.Build.0 = Release|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGORelease|x64.ActiveCfg = Release|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.PGORelease|x64.Build.0 = Release|x64
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Release|Win32.ActiveCfg = Release|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Release|Win32.Build.0 = Release|Win32
-		{F22F40F4-D318-40DC-96B3-88DC81CE0894}.Release|x64.ActiveCfg = Release|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Debug|Win32.ActiveCfg = Debug|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Debug|Win32.Build.0 = Debug|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Debug|x64.ActiveCfg = Debug|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Debug|x64.Build.0 = Debug|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGIRelease|Win32.Build.0 = Release|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGIRelease|x64.ActiveCfg = Release|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGIRelease|x64.Build.0 = Release|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGORelease|Win32.Build.0 = Release|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGORelease|x64.ActiveCfg = Release|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.PGORelease|x64.Build.0 = Release|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Release|Win32.ActiveCfg = Release|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Release|Win32.Build.0 = Release|Win32
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Release|x64.ActiveCfg = Release|x64
-		{8CF334D9-4F82-42EB-97AF-83592C5AFD2F}.Release|x64.Build.0 = Release|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Debug|Win32.ActiveCfg = Debug|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Debug|Win32.Build.0 = Debug|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Debug|x64.ActiveCfg = Debug|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Debug|x64.Build.0 = Debug|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGIRelease|Win32.Build.0 = Release|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGIRelease|x64.ActiveCfg = Release|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGIRelease|x64.Build.0 = Release|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGORelease|Win32.Build.0 = Release|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGORelease|x64.ActiveCfg = Release|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.PGORelease|x64.Build.0 = Release|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Release|Win32.ActiveCfg = Release|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Release|Win32.Build.0 = Release|Win32
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Release|x64.ActiveCfg = Release|x64
-		{2FF0A312-22F9-4C34-B070-842916DE27A9}.Release|x64.Build.0 = Release|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Debug|Win32.ActiveCfg = Debug|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Debug|Win32.Build.0 = Debug|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Debug|x64.ActiveCfg = Debug|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Debug|x64.Build.0 = Debug|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGIRelease|Win32.Build.0 = Release|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGIRelease|x64.ActiveCfg = Release|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGIRelease|x64.Build.0 = Release|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGORelease|Win32.Build.0 = Release|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGORelease|x64.ActiveCfg = Release|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.PGORelease|x64.Build.0 = Release|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Release|Win32.ActiveCfg = Release|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Release|Win32.Build.0 = Release|Win32
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Release|x64.ActiveCfg = Release|x64
-		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}.Release|x64.Build.0 = Release|x64
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Debug|Win32.Build.0 = Debug|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Debug|x64.ActiveCfg = Debug|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Debug|x64.Build.0 = Debug|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.PGIRelease|Win32.ActiveCfg = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.PGIRelease|Win32.Build.0 = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.PGIRelease|x64.ActiveCfg = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.PGORelease|Win32.ActiveCfg = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.PGORelease|Win32.Build.0 = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.PGORelease|x64.ActiveCfg = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Release|Win32.ActiveCfg = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Release|Win32.Build.0 = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Release|x64.ActiveCfg = Release|Win32
-		{F0E0541E-F17D-430B-97C4-93ADF0DD284E}.Release|x64.Build.0 = Release|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Debug|Win32.ActiveCfg = Debug|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Debug|Win32.Build.0 = Debug|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Debug|x64.ActiveCfg = Debug|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Debug|x64.Build.0 = Debug|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Release|Win32.ActiveCfg = Release|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Release|Win32.Build.0 = Release|Win32
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Release|x64.ActiveCfg = Release|x64
+		{987306EC-6BAD-4440-B4FB-A699A1EE6A28}.Release|x64.Build.0 = Release|x64
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Debug|Win32.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Debug|Win32.Build.0 = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Debug|x64.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Debug|x64.Build.0 = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.PGInstrument|Win32.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.PGInstrument|Win32.Build.0 = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.PGInstrument|x64.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.PGUpdate|Win32.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.PGUpdate|Win32.Build.0 = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.PGUpdate|x64.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Release|Win32.ActiveCfg = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Release|Win32.Build.0 = Debug|Win32
+		{2AB2AC43-1B73-40B1-8964-95B3FC3F15ED}.Release|x64.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Debug|Win32.Build.0 = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Debug|x64.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Debug|x64.Build.0 = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.PGInstrument|Win32.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.PGInstrument|Win32.Build.0 = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.PGInstrument|x64.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.PGUpdate|Win32.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.PGUpdate|Win32.Build.0 = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.PGUpdate|x64.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Release|Win32.ActiveCfg = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Release|Win32.Build.0 = Debug|Win32
+		{87AB87DB-B665-4621-A67B-878C15B93FF0}.Release|x64.ActiveCfg = Debug|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Debug|Win32.Build.0 = Debug|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Debug|x64.ActiveCfg = Debug|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Debug|x64.Build.0 = Debug|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Release|Win32.ActiveCfg = Release|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Release|Win32.Build.0 = Release|Win32
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Release|x64.ActiveCfg = Release|x64
+		{8D80F68B-F6EC-4E69-9B04-73F632A8A8ED}.Release|x64.Build.0 = Release|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Debug|Win32.Build.0 = Debug|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Debug|x64.ActiveCfg = Debug|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Debug|x64.Build.0 = Debug|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Release|Win32.ActiveCfg = Release|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Release|Win32.Build.0 = Release|Win32
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Release|x64.ActiveCfg = Release|x64
+		{F548A318-960A-4B37-9CD6-86B1B0E33CC8}.Release|x64.Build.0 = Release|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Debug|Win32.Build.0 = Debug|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Debug|x64.ActiveCfg = Debug|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Debug|x64.Build.0 = Debug|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Release|Win32.ActiveCfg = Release|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Release|Win32.Build.0 = Release|Win32
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Release|x64.ActiveCfg = Release|x64
+		{CB025148-F0A1-4B32-A669-19EE0534136D}.Release|x64.Build.0 = Release|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Debug|Win32.Build.0 = Debug|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Debug|x64.ActiveCfg = Debug|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Debug|x64.Build.0 = Debug|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Release|Win32.ActiveCfg = Release|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Release|Win32.Build.0 = Release|Win32
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Release|x64.ActiveCfg = Release|x64
+		{A25ADCC5-8DE1-4F88-B842-C287923280B1}.Release|x64.Build.0 = Release|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Debug|Win32.Build.0 = Debug|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Debug|x64.ActiveCfg = Debug|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Debug|x64.Build.0 = Debug|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Release|Win32.ActiveCfg = Release|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Release|Win32.Build.0 = Release|Win32
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Release|x64.ActiveCfg = Release|x64
+		{D50E5319-41CC-429A-8E81-B1CD391C3A7B}.Release|x64.Build.0 = Release|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Debug|Win32.ActiveCfg = Debug|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Debug|Win32.Build.0 = Debug|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Debug|x64.ActiveCfg = Debug|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Debug|x64.Build.0 = Debug|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Release|Win32.ActiveCfg = Release|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Release|Win32.Build.0 = Release|Win32
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Release|x64.ActiveCfg = Release|x64
+		{AE617428-B823-4B87-BC6D-DC7C12C746D3}.Release|x64.Build.0 = Release|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Debug|Win32.ActiveCfg = Debug|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Debug|Win32.Build.0 = Debug|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Debug|x64.ActiveCfg = Debug|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Debug|x64.Build.0 = Debug|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Release|Win32.ActiveCfg = Release|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Release|Win32.Build.0 = Release|Win32
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Release|x64.ActiveCfg = Release|x64
+		{98C3DB47-DD1F-4A4B-9D3C-1DBB32AC6667}.Release|x64.Build.0 = Release|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Debug|Win32.Build.0 = Debug|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Debug|x64.ActiveCfg = Debug|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Debug|x64.Build.0 = Debug|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Release|Win32.ActiveCfg = Release|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Release|Win32.Build.0 = Release|Win32
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Release|x64.ActiveCfg = Release|x64
+		{0BAFC4A4-8DB5-4CC6-9DDB-A1D32C682B2F}.Release|x64.Build.0 = Release|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Debug|Win32.Build.0 = Debug|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Debug|x64.ActiveCfg = Debug|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Debug|x64.Build.0 = Debug|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Release|Win32.ActiveCfg = Release|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Release|Win32.Build.0 = Release|Win32
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Release|x64.ActiveCfg = Release|x64
+		{D04B2089-7DA9-4D92-B23F-07453BC46652}.Release|x64.Build.0 = Release|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Debug|Win32.Build.0 = Debug|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Debug|x64.ActiveCfg = Debug|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Debug|x64.Build.0 = Debug|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Release|Win32.ActiveCfg = Release|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Release|Win32.Build.0 = Release|Win32
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Release|x64.ActiveCfg = Release|x64
+		{1015E3B4-FD3B-4402-AA6E-7806514156D6}.Release|x64.Build.0 = Release|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Debug|Win32.ActiveCfg = Debug|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Debug|Win32.Build.0 = Debug|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Debug|x64.ActiveCfg = Debug|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Debug|x64.Build.0 = Debug|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Release|Win32.ActiveCfg = Release|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Release|Win32.Build.0 = Release|Win32
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Release|x64.ActiveCfg = Release|x64
+		{AE31A248-5367-4EB2-A511-8722BC351CB4}.Release|x64.Build.0 = Release|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Debug|Win32.ActiveCfg = Debug|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Debug|Win32.Build.0 = Debug|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Debug|x64.ActiveCfg = Debug|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Debug|x64.Build.0 = Debug|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Release|Win32.ActiveCfg = PGInstrument|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Release|Win32.Build.0 = PGInstrument|Win32
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Release|x64.ActiveCfg = Release|x64
+		{E644B843-F7CA-4888-AA6D-653C77592856}.Release|x64.Build.0 = Release|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Debug|Win32.ActiveCfg = Debug|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Debug|Win32.Build.0 = Debug|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Debug|x64.ActiveCfg = Debug|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Debug|x64.Build.0 = Debug|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Release|Win32.ActiveCfg = Release|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Release|Win32.Build.0 = Release|Win32
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Release|x64.ActiveCfg = Release|x64
+		{1E8DCFC4-1EF8-4076-8CA2-B08D3C979749}.Release|x64.Build.0 = Release|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Debug|Win32.Build.0 = Debug|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Debug|x64.ActiveCfg = Debug|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Debug|x64.Build.0 = Debug|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Release|Win32.ActiveCfg = Release|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Release|Win32.Build.0 = Release|Win32
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Release|x64.ActiveCfg = Release|x64
+		{3A1515AF-3694-4222-91F2-9837BDF60F9A}.Release|x64.Build.0 = Release|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Debug|Win32.Build.0 = Debug|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Debug|x64.ActiveCfg = Debug|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Debug|x64.Build.0 = Debug|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Release|Win32.ActiveCfg = Release|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Release|Win32.Build.0 = Release|Win32
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Release|x64.ActiveCfg = Release|x64
+		{18C518FB-33CB-4C16-AA05-8DEA8DE66DF0}.Release|x64.Build.0 = Release|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Debug|Win32.ActiveCfg = Debug|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Debug|Win32.Build.0 = Debug|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Debug|x64.ActiveCfg = Debug|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Debug|x64.Build.0 = Debug|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGInstrument|x64.ActiveCfg = PGInstrument|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGInstrument|x64.Build.0 = PGInstrument|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGUpdate|x64.ActiveCfg = PGUpdate|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.PGUpdate|x64.Build.0 = PGUpdate|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Release|Win32.ActiveCfg = Release|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Release|Win32.Build.0 = Release|Win32
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Release|x64.ActiveCfg = Release|x64
+		{80EBF51A-6018-4589-9A53-5AAF2872E230}.Release|x64.Build.0 = Release|x64
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

Deleted: /python/branches/p3yk-noslice/PCbuild8/pyexpat.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/pyexpat.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,393 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="pyexpat"
-	ProjectGUID="{7E551393-3C43-47F8-9F3F-5BC368A6C487}"
-	SccProjectName="pyexpat"
-	SccLocalPath=".."
-	SccProvider="MSSCCI:Perforce SCM"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-debug\pyexpat"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="_DEBUG;HAVE_EXPAT_H;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;XML_STATIC;HAVE_MEMMOVE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="./pyexpat_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./pyexpat_d.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=".\./pyexpat_d.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\."
-			IntermediateDirectory=".\x86-temp-release\pyexpat"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;XML_STATIC;HAVE_MEMMOVE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="./pyexpat.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./pyexpat.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=".\./pyexpat.lib"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseItanium|Win32"
-			OutputDirectory="./."
-			IntermediateDirectory=".\ia64-temp-release\pyexpat"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_ITANIUM"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;XML_STATIC;HAVE_MEMMOVE"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="./pyexpat.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./pyexpat.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=".\./pyexpat.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="ReleaseAMD64|Win32"
-			OutputDirectory="."
-			IntermediateDirectory="amd64-temp-release\pyexpat"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions=" /USECL:MS_OPTERON"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;XML_STATIC;HAVE_MEMMOVE"
-				StringPooling="true"
-				BasicRuntimeChecks="0"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="./pyexpat.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=".\./pyexpat.pdb"
-				SubSystem="2"
-				BaseAddress="0x1D100000"
-				ImportLibrary=".\./pyexpat.lib"
-				TargetMachine="0"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\pyexpat.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\expat\xmlparse.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\expat\xmlrole.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\expat\xmltok.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/python.build
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/python.build	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,21 +0,0 @@
-<?xml version="1.0"?>
-<project>
- <target name="all" description="Build all targets.">
-   <solution configuration="release">
-     <projects>
-       <include name="make_versioninfo.vcproj" />
-     </projects>
-   </solution>
-   <exec program="make_versioninfo" output="pythonnt_rc.h" />
-
-   <solution configuration="release" solutionfile="pcbuild.sln">
-     <excludeprojects>
-       <include name="_tkinter.vcproj" />
-       <include name="bz2.vcproj" />
-       <include name="_bsddb.vcproj" />
-       <include name="_sqlite3.vcproj" />
-       <include name="_ssl.vcproj" />
-     </excludeprojects>
-   </solution>
- </target>
-</project>

Deleted: /python/branches/p3yk-noslice/PCbuild8/python.iss
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/python.iss	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,346 +0,0 @@
-; Script generated by the Inno Setup Script Wizard.
-; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
-
-; This is the whole ball of wax for an Inno installer for Python.
-; To use, download Inno Setup from http://www.jrsoftware.org/isdl.htm/,
-; install it, and double-click on this file.  That launches the Inno
-; script compiler.  The GUI is extemely simple, and has only one button
-; you may not recognize instantly:  click it.  You're done.  It builds
-; the installer into PCBuild/Python-2.2a1.exe.  Size and speed of the
-; installer are competitive with the Wise installer; Inno uninstall
-; seems much quicker than Wise (but also feebler, and the uninstall
-; log is in some un(human)readable binary format).
-;
-; What's Done
-; -----------
-; All the usual Windows Python files are installed by this now.
-; All the usual Windows Python Start menu entries are created and
-; work fine.
-; .py, .pyw, .pyc and .pyo extensions are registered.
-;     PROBLEM:  Inno uninstall does not restore their previous registry
-;               associations (if any).  Wise did.  This will make life
-;               difficult for alpha (etc) testers.
-; The Python install is fully functional for "typical" uses.
-;
-; What's Not Done
-; ---------------
-; None of "Mark Hammond's" registry entries are written.
-; No installation of files is done into the system dir:
-;     The MS DLLs aren't handled at all by this yet.
-;     Python22.dll is unpacked into the main Python dir.
-;
-; Inno can't do different things on NT/2000 depending on whether the user
-; has Admin privileges, so I don't know how to "solve" either of those,
-; short of building two installers (one *requiring* Admin privs, the
-; other not doing anything that needs Admin privs).
-;
-; Inno has no concept of variables, so lots of lines in this file need
-; to be fiddled by hand across releases.  Simplest way out:  stick this
-; file in a giant triple-quoted r-string (note that backslashes are
-; required all over the place here -- forward slashes DON'T WORK in
-; Inno), and use %(yadda)s string interpolation to do substitutions; i.e.,
-; write a very simple Python program to *produce* this script.
-
-[Setup]
-AppName=Python and combined Win32 Extensions
-AppVerName=Python 2.2.2 and combined Win32 Extensions 150
-AppId=Python 2.2.2.150
-AppVersion=2.2.2.150
-AppCopyright=Python is Copyright © 2001 Python Software Foundation. Win32 Extensions are Copyright © 1996-2001 Greg Stein and Mark Hammond.
-
-; Default install dir; value of {app} later (unless user overrides).
-; {sd} = system root drive, probably "C:".
-DefaultDirName={sd}\Python22
-;DefaultDirName={pf}\Python
-
-; Start menu folder name; value of {group} later (unless user overrides).
-DefaultGroupName=Python 2.2
-
-; Point SourceDir to one above PCBuild = src.
-; means this script can run unchanged from anyone's CVS tree, no matter
-; what they called the top-level directories.
-SourceDir=.
-OutputDir=..
-OutputBaseFilename=Python-2.2.2-Win32-150-Setup
-
-AppPublisher=PythonLabs at Digital Creations
-AppPublisherURL=http://www.python.org
-AppSupportURL=http://www.python.org
-AppUpdatesURL=http://www.python.org
-
-AlwaysCreateUninstallIcon=true
-ChangesAssociations=true
-UninstallLogMode=new
-AllowNoIcons=true
-AdminPrivilegesRequired=true
-UninstallDisplayIcon={app}\pyc.ico
-WizardDebug=false
-
-; The fewer screens the better; leave these commented.
-
-Compression=bzip
-InfoBeforeFile=LICENSE.txt
-;InfoBeforeFile=Misc\NEWS
-
-; uncomment the following line if you want your installation to run on NT 3.51 too.
-; MinVersion=4,3.51
-
-[Types]
-Name: normal; Description: Select desired components; Flags: iscustom
-
-[Components]
-Name: main; Description: Python and Win32 Extensions; Types: normal
-Name: docs; Description: Python documentation (HTML); Types: normal
-Name: tk; Description: TCL/TK, tkinter, and Idle; Types: normal
-Name: tools; Description: Python utility scripts (Tools\); Types: normal
-Name: test; Description: Python test suite (Lib\test\); Types: normal
-
-[Tasks]
-Name: extensions; Description: Register file associations (.py, .pyw, .pyc, .pyo); Components: main; Check: IsAdminLoggedOn
-
-[Files]
-; Caution:  Using forward slashes instead screws up in amazing ways.
-; Unknown:  By the time Components (and other attrs) are added to these lines, they're
-; going to get awfully long.  But don't see a way to continue logical lines across
-; physical lines.
-
-Source: LICENSE.txt; DestDir: {app}; CopyMode: alwaysoverwrite
-Source: README.txt; DestDir: {app}; CopyMode: alwaysoverwrite
-Source: News.txt; DestDir: {app}; CopyMode: alwaysoverwrite
-Source: *.ico; DestDir: {app}; CopyMode: alwaysoverwrite; Components: main
-
-Source: python.exe; DestDir: {app}; CopyMode: alwaysoverwrite; Components: main
-Source: pythonw.exe; DestDir: {app}; CopyMode: alwaysoverwrite; Components: main
-Source: w9xpopen.exe; DestDir: {app}; CopyMode: alwaysoverwrite; Components: main
-
-
-Source: DLLs\tcl83.dll; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: tk
-Source: DLLs\tk83.dll; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: tk
-Source: tcl\*.*; DestDir: {app}\tcl; CopyMode: alwaysoverwrite; Components: tk; Flags: recursesubdirs
-
-Source: sysdir\python22.dll; DestDir: {sys}; CopyMode: alwaysskipifsameorolder; Components: main; Flags: sharedfile restartreplace
-Source: sysdir\PyWinTypes22.dll; DestDir: {sys}; CopyMode: alwaysskipifsameorolder; Components: main; Flags: restartreplace sharedfile
-Source: sysdir\pythoncom22.dll; DestDir: {sys}; CopyMode: alwaysskipifsameorolder; Components: main; Flags: restartreplace sharedfile
-
-Source: DLLs\_socket.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\_socket.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\_sre.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\_sre.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\_symtable.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\_symtable.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\_testcapi.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\_testcapi.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\_tkinter.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: tk
-Source: libs\_tkinter.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: tk
-
-Source: DLLs\bsddb.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\bsddb.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\mmap.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\mmap.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\parser.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\parser.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\pyexpat.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\pyexpat.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\select.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\select.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\unicodedata.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\unicodedata.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\_winreg.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\_winreg.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\winsound.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\winsound.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\zlib.pyd; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-Source: libs\zlib.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: libs\python22.lib; DestDir: {app}\libs; CopyMode: alwaysoverwrite; Components: main
-
-Source: DLLs\expat.dll; DestDir: {app}\DLLs; CopyMode: alwaysoverwrite; Components: main
-
-
-
-Source: Lib\*.py; DestDir: {app}\Lib; CopyMode: alwaysoverwrite; Components: main
-Source: Lib\compiler\*.*; DestDir: {app}\Lib\compiler; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\distutils\*.*; DestDir: {app}\Lib\distutils; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\email\*.*; DestDir: {app}\Lib\email; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\encodings\*.*; DestDir: {app}\Lib\encodings; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\hotshot\*.*; DestDir: {app}\Lib\hotshot; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\lib-old\*.*; DestDir: {app}\Lib\lib-old; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\xml\*.*; DestDir: {app}\Lib\xml; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\hotshot\*.*; DestDir: {app}\Lib\hotshot; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\test\*.*; DestDir: {app}\Lib\test; CopyMode: alwaysoverwrite; Components: test; Flags: recursesubdirs
-
-Source: Lib\site-packages\README.txt; DestDir: {app}\Lib\site-packages; CopyMode: alwaysoverwrite; Components: main
-
-Source: Lib\site-packages\PyWin32.chm; DestDir: {app}\Lib\site-packages; CopyMode: alwaysoverwrite; Components: docs
-Source: Lib\site-packages\win32\*.*; DestDir: {app}\Lib\site-packages\win32; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\site-packages\win32com\*.*; DestDir: {app}\Lib\site-packages\win32com; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-Source: Lib\site-packages\win32comext\*.*; DestDir: {app}\Lib\site-packages\win32comext; CopyMode: alwaysoverwrite; Components: main; Flags: recursesubdirs
-
-Source: Lib\lib-tk\*.py; DestDir: {app}\Lib\lib-tk; CopyMode: alwaysoverwrite; Components: tk; Flags: recursesubdirs
-
-Source: include\*.h; DestDir: {app}\include; CopyMode: alwaysoverwrite; Components: main
-
-Source: Tools\idle\*.*; DestDir: {app}\Tools\idle; CopyMode: alwaysoverwrite; Components: tk; Flags: recursesubdirs
-
-Source: Tools\pynche\*.*; DestDir: {app}\Tools\pynche; CopyMode: alwaysoverwrite; Components: tools; Flags: recursesubdirs
-Source: Tools\scripts\*.*; DestDir: {app}\Tools\Scripts; CopyMode: alwaysoverwrite; Components: tools; Flags: recursesubdirs
-Source: Tools\webchecker\*.*; DestDir: {app}\Tools\webchecker; CopyMode: alwaysoverwrite; Components: tools; Flags: recursesubdirs
-Source: Tools\versioncheck\*.*; DestDir: {app}\Tools\versioncheck; CopyMode: alwaysoverwrite; Components: tools; Flags: recursesubdirs
-
-Source: Doc\*.*; DestDir: {app}\Doc; CopyMode: alwaysoverwrite; Flags: recursesubdirs; Components: docs
-
-
-[Icons]
-Name: {group}\Python (command line); Filename: {app}\python.exe; WorkingDir: {app}; Components: main
-Name: {group}\Python Manuals; Filename: {app}\Doc\index.html; WorkingDir: {app}; Components: docs
-Name: {group}\Win32 Extensions Help; Filename: {app}\Lib\site-packages\PyWin32.chm; WorkingDir: {app}\Lib\site-packages; Components: docs
-Name: {group}\Module Docs; Filename: {app}\pythonw.exe; WorkingDir: {app}; Parameters: """{app}\Tools\Scripts\pydoc.pyw"""; Components: tools
-Name: {group}\IDLE (Python GUI); Filename: {app}\pythonw.exe; WorkingDir: {app}; Parameters: """{app}\Tools\idle\idle.pyw"""; Components: tools
-
-[Registry]
-; Register .py
-Tasks: extensions; Root: HKCR; Subkey: .py; ValueType: string; ValueName: ; ValueData: Python File; Flags: uninsdeletevalue
-Tasks: extensions; Root: HKCR; Subkey: .py; ValueType: string; ValueName: Content Type; ValueData: text/plain; Flags: uninsdeletevalue
-Tasks: extensions; Root: HKCR; Subkey: Python File; ValueType: string; ValueName: ; ValueData: Python File; Flags: uninsdeletekey
-Tasks: extensions; Root: HKCR; Subkey: Python File\DefaultIcon; ValueType: string; ValueName: ; ValueData: {app}\Py.ico
-Tasks: extensions; Root: HKCR; Subkey: Python File\shell\open\command; ValueType: string; ValueName: ; ValueData: """{app}\python.exe"" ""%1"" %*"
-
-; Register .pyc
-Tasks: extensions; Root: HKCR; Subkey: .pyc; ValueType: string; ValueName: ; ValueData: Python CompiledFile; Flags: uninsdeletevalue
-Tasks: extensions; Root: HKCR; Subkey: Python CompiledFile; ValueType: string; ValueName: ; ValueData: Compiled Python File; Flags: uninsdeletekey
-Tasks: extensions; Root: HKCR; Subkey: Python CompiledFile\DefaultIcon; ValueType: string; ValueName: ; ValueData: {app}\pyc.ico
-Tasks: extensions; Root: HKCR; Subkey: Python CompiledFile\shell\open\command; ValueType: string; ValueName: ; ValueData: """{app}\python.exe"" ""%1"" %*"
-
-; Register .pyo
-Tasks: extensions; Root: HKCR; Subkey: .pyo; ValueType: string; ValueName: ; ValueData: Python CompiledFile; Flags: uninsdeletevalue
-
-; Register .pyw
-Tasks: extensions; Root: HKCR; Subkey: .pyw; ValueType: string; ValueName: ; ValueData: Python NoConFile; Flags: uninsdeletevalue
-Tasks: extensions; Root: HKCR; Subkey: .pyw; ValueType: string; ValueName: Content Type; ValueData: text/plain; Flags: uninsdeletevalue
-Tasks: extensions; Root: HKCR; Subkey: Python NoConFile; ValueType: string; ValueName: ; ValueData: Python File (no console); Flags: uninsdeletekey
-Tasks: extensions; Root: HKCR; Subkey: Python NoConFile\DefaultIcon; ValueType: string; ValueName: ; ValueData: {app}\Py.ico
-Tasks: extensions; Root: HKCR; Subkey: Python NoConFile\shell\open\command; ValueType: string; ValueName: ; ValueData: """{app}\pythonw.exe"" ""%1"" %*"
-
-
-; Python Registry Keys
-Root: HKLM; Subkey: SOFTWARE\Python; Flags: uninsdeletekeyifempty; Check: IsAdminLoggedOn
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore; Flags: uninsdeletekeyifempty
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2; Flags: uninsdeletekeyifempty
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\PythonPath; ValueData: "{app}\Lib;{app}\DLLs"; Flags: uninsdeletekeyifempty
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\PythonPath\tk; ValueData: {app}\Lib\lib-tk; Flags: uninsdeletekey; Components: tk
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\PythonPath\win32; ValueData: "{app}\lib\site-packages\win32;{app}\lib\site-packages\win32\lib"; Flags: uninsdeletekey
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\PythonPath\win32com; ValueData: C:\Python\lib\site-packages; Flags: uninsdeletekey
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\Modules; Flags: uninsdeletekeyifempty
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\Modules\pythoncom; ValueData: {sys}\pythoncom22.dll; Flags: uninsdeletekey
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\Modules\pywintypes; ValueData: {sys}\PyWinTypes22.dll; Flags: uninsdeletekey
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\InstallPath; ValueData: {app}; Flags: uninsdeletekeyifempty; ValueType: string
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\InstallPath\InstallGroup; ValueData: {group}; Flags: uninsdeletekey
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\Help; Flags: uninsdeletekeyifempty
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\Help\Main Python Documentation; ValueType: string; ValueData: {app}\Doc\index.html; Flags: uninsdeletekey; Components: docs
-Root: HKLM; Subkey: SOFTWARE\Python\PythonCore\2.2\Help\Python Win32 Documentation; ValueType: string; ValueData: {app}\lib\site-packages\PyWin32.chm; Flags: uninsdeletekey; Components: docs
-
-[_ISTool]
-EnableISX=true
-
-
-[Code]
-Program Setup;
-
-Function IsAdminNotLoggedOn(): Boolean;
-begin
-  Result := Not IsAdminLoggedOn();
-end;
-
-begin
-end.
-
-
-
-
-[UninstallDelete]
-Name: {app}\Lib\compiler\*.pyc; Type: files
-Name: {app}\Lib\compiler\*.pyo; Type: files
-Name: {app}\Lib\compiler; Type: dirifempty
-Name: {app}\Lib\distutils\command\*.pyc; Type: files
-Name: {app}\Lib\distutils\command\*.pyo; Type: files
-Name: {app}\Lib\distutils\command; Type: dirifempty
-Name: {app}\Lib\distutils\*.pyc; Type: files
-Name: {app}\Lib\distutils\*.pyo; Type: files
-Name: {app}\Lib\distutils; Type: dirifempty
-Name: {app}\Lib\email\test\*.pyc; Type: files
-Name: {app}\Lib\email\test\*.pyo; Type: files
-Name: {app}\Lib\email\test; Type: dirifempty
-Name: {app}\Lib\email\*.pyc; Type: files
-Name: {app}\Lib\email\*.pyo; Type: files
-Name: {app}\Lib\email; Type: dirifempty
-Name: {app}\Lib\encodings\*.pyc; Type: files
-Name: {app}\Lib\encodings\*.pyo; Type: files
-Name: {app}\Lib\encodings; Type: dirifempty
-Name: {app}\Lib\hotshot\*.pyc; Type: files
-Name: {app}\Lib\hotshot\*.pyo; Type: files
-Name: {app}\Lib\hotshot; Type: dirifempty
-Name: {app}\Lib\lib-old\*.pyc; Type: files
-Name: {app}\Lib\lib-old\*.pyo; Type: files
-Name: {app}\Lib\lib-old; Type: dirifempty
-Name: {app}\Lib\lib-tk\*.pyc; Type: files
-Name: {app}\Lib\lib-tk\*.pyo; Type: files
-Name: {app}\Lib\lib-tk; Type: dirifempty
-Name: {app}\Lib\test\*.pyc; Type: files
-Name: {app}\Lib\test\*.pyo; Type: files
-Name: {app}\Lib\test; Type: dirifempty
-Name: {app}\Lib\xml\dom\*.pyc; Type: files
-Name: {app}\Lib\xml\dom\*.pyo; Type: files
-Name: {app}\Lib\xml\dom; Type: dirifempty
-Name: {app}\Lib\xml\parsers\*.pyc; Type: files
-Name: {app}\Lib\xml\parsers\*.pyo; Type: files
-Name: {app}\Lib\xml\parsers; Type: dirifempty
-Name: {app}\Lib\xml\sax\*.pyc; Type: files
-Name: {app}\Lib\xml\sax\*.pyo; Type: files
-Name: {app}\Lib\xml\sax; Type: dirifempty
-Name: {app}\Lib\xml\*.pyc; Type: files
-Name: {app}\Lib\xml\*.pyo; Type: files
-Name: {app}\Lib\xml; Type: dirifempty
-
-Name: {app}\Lib\site-packages\win32; Type: filesandordirs
-Name: {app}\Lib\site-packages\win32com; Type: filesandordirs
-Name: {app}\Lib\site-packages\win32comext; Type: filesandordirs
-Name: {app}\Lib\site-packages\pythoncom.py*; Type: files
-Name: {app}\Lib\site-packages; Type: dirifempty
-
-Name: {app}\Lib\*.pyc; Type: files
-Name: {app}\Lib; Type: dirifempty
-
-Name: {app}\Tools\pynche\*.pyc; Type: files
-Name: {app}\Tools\pynche\*.pyo; Type: files
-Name: {app}\Tools\pynche; Type: dirifempty
-
-Name: {app}\Tools\idle\*.pyc; Type: files
-Name: {app}\Tools\idle\*.pyo; Type: files
-Name: {app}\Tools\idle; Type: dirifempty
-
-Name: {app}\Tools\scripts\*.pyc; Type: files
-Name: {app}\Tools\scripts\*.pyo; Type: files
-Name: {app}\Tools\scripts; Type: dirifempty
-
-Name: {app}\Tools\versioncheck\*.pyc; Type: files
-Name: {app}\Tools\versioncheck\*.pyo; Type: files
-Name: {app}\Tools\versioncheck; Type: dirifempty
-
-Name: {app}\Tools\webchecker\*.pyc; Type: files
-Name: {app}\Tools\webchecker\*.pyo; Type: files
-Name: {app}\Tools\webchecker; Type: dirifempty
-
-Name: {app}\Tools; Type: dirifempty
-

Deleted: /python/branches/p3yk-noslice/PCbuild8/python.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/python.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,399 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="python"
-	ProjectGUID="{B11D750F-CD1F-4A96-85CE-E69A5C5259F9}"
-	RootNamespace="python"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\python"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\python.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="1"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\python"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\python.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="1"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\python"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				BrowseInformation="1"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="_DEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib"
-				OutputFile="$(OutDir)\python_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="1"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\python"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				BrowseInformation="1"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="_DEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="odbccp32.lib python26_d.lib"
-				OutputFile="$(OutDir)\python_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="1"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\PC\pycon.ico"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\python.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\python_exe.rc"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/python20.wse
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/python20.wse	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,3135 +0,0 @@
-Document Type: WSE
-item: Global
-  Version=9.0
-  Title=Python 2.4a1
-  Flags=00010100
-  Languages=65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-  Japanese Font Name=MS Gothic
-  Japanese Font Size=10
-  Start Gradient=0 255 0
-  End Gradient=0 128 0
-  Windows Flags=00000100000011010010010100001010
-  Log Pathname=%MAINDIR%\INSTALL.LOG
-  Message Font=MS Sans Serif
-  Font Size=8
-  Pages Modified=00010000011101000000000100000111
-  Extra Pages=00000000000000000000000010110010
-  Disk Filename=SETUP
-  Patch Flags=0000000000001001
-  Patch Threshold=85
-  Patch Memory=4000
-  MIF PDF Version=1.0
-  MIF SMS Version=2.0
-  EXE Filename=Python-2.4a1.exe
-  Dialogs Version=8
-  Version File=2.4a1
-  Version Description=Python Programming Language
-  Version Copyright=©2001-2007 Python Software Foundation
-  Version Company=Python Software Foundation
-  Crystal Format=10111100101100000010001001001001
-  Step View=&All
-  Variable Name1=_WISE_
-  Variable Description1=WISE root directory
-  Variable Default1=C:\Programme\Wise Installation System
-  Variable Flags1=00001000
-  Variable Name2=_TCLDIR_
-  Variable Description2=The directory in which the Tcl/Tk installation
-  Variable Description2=lives.  This must be a sibling of the Python
-  Variable Description2=directory.
-  Variable Default2=tcl84
-  Variable Flags2=00001000
-  Variable Name3=_DOC_
-  Variable Description3=The unpacked HTML doc directory.
-  Variable Default3=..\html
-  Variable Flags3=00001001
-  Variable Name4=_SYS_
-  Variable Description4=System directory (where to find MSVCRT.DLL)
-  Variable Default4=C:\Windows\System
-  Variable Values4=C:\Windows\System
-  Variable Values4=C:\WINNT\System32
-  Variable Values4=C:\Code\MSDLLs
-  Variable Values4=C:\Windows\System32
-  Variable Flags4=00000010
-  Variable Name5=_PYMAJOR_
-  Variable Description5=Python major version number; the 2 in 2.3.
-  Variable Default5=2
-  Variable Flags5=00001000
-  Variable Name6=_PYMINOR_
-  Variable Description6=Python minor version number; the 3 in 2.3
-  Variable Default6=3
-  Variable Flags6=00001000
-  Variable Name7=_DOADMIN_
-  Variable Description7=The initial value for %DOADMIN%.
-  Variable Description7=When 0, we never try to write under HKLM,
-  Variable Description7=and install the Python + MS runtime DLLs in
-  Variable Description7=the Python directory instead of the system dir.
-  Variable Default7=1
-  Variable Values7=1
-  Variable Values7=0
-  Variable Flags7=00001010
-  Variable Name8=_ALIASNAME_
-  Variable Flags8=00001000
-  Variable Name9=_ALIASPATH_
-  Variable Flags9=00001000
-  Variable Name10=_ALIASTYPE_
-  Variable Flags10=00001000
-end
-item: Set Variable
-  Variable=PYVER_STRING
-  Value=2.3
-end
-item: Remark
-end
-item: Remark
-  Text=When the version number changes, set the compiler
-end
-item: Remark
-  Text=vrbls _PYMAJOR_ and  _PYMINOR_.
-end
-item: Remark
-  Text=Nothing in the script below should need fiddling then.
-end
-item: Remark
-  Text=Other things that need fiddling:
-end
-item: Remark
-  Text=    PYVER_STRING above.
-end
-item: Remark
-  Text=    The "Title:" in the upper left corner of the GUI.
-end
-item: Remark
-  Text=    Build Settings and Version Resource on step 6 (Finish) of the Installation Expert
-end
-item: Remark
-  Text=        Be sure to select Steps->All or you may not see these!
-end
-item: Remark
-end
-item: Remark
-  Text=When the version of Tcl/Tk changes, the compiler vrbl
-end
-item: Remark
-  Text=_TCLDIR_ may also need to be changed.
-end
-item: Remark
-end
-item: Set Variable
-  Variable=APPTITLE
-  Value=Python %PYVER_STRING%
-end
-item: Remark
-  Text=PY_VERSION should be major.minor only; used to create the registry key; must match MS_DLL_ID in python_nt.rc
-end
-item: Set Variable
-  Variable=PY_VERSION
-  Value=%_PYMAJOR_%.%_PYMINOR_%
-end
-item: Remark
-  Text=GROUP is the Start menu group name; user can override.
-end
-item: Set Variable
-  Variable=GROUP
-  Value=Python %PY_VERSION%
-  Flags=10000000
-end
-item: Remark
-  Text=MAINDIR is the app directory; user can override.
-end
-item: Set Variable
-  Variable=MAINDIR
-  Value=Python%_PYMAJOR_%%_PYMINOR_%
-end
-item: Remark
-end
-item: Set Variable
-  Variable=DOADMIN
-  Value=%_DOADMIN_%
-end
-item: Remark
-  Text=Give non-admin users a chance to abort.
-end
-item: Check Configuration
-  Flags=10011111
-end
-item: Set Variable
-  Variable=DOADMIN
-  Value=0
-end
-item: Display Message
-  Title=Doing non-admin install
-  Text=The current login does not have Administrator Privileges on this machine.  Python will install its registry information into the per-user area only for the current login, instead of into the per-machine area for every account on this machine.  Some advanced uses of Python may not work as a result (for example, running a Python script as a service).
-  Text=
-  Text=If this is not what you want, please click Cancel to abort this installation, log on as an Administrator, and start the installation again.
-  Flags=00001000
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=BEGIN WIZARD STUFF -----------------------------------------------------------------------------------------------------------------------------
-end
-item: Remark
-  Text=Note from Tim: the "stop" on the next line is actually "pause".
-end
-item: Open/Close INSTALL.LOG
-  Flags=00000001
-end
-item: Remark
-  Text=If the destination system does not have a writable Windows\System directory, system files will be written to the Windows\ directory
-end
-item: Check if File/Dir Exists
-  Pathname=%SYS%
-  Flags=10000100
-end
-item: Set Variable
-  Variable=SYS
-  Value=%WIN%
-end
-item: End Block
-end
-item: Check Configuration
-  Flags=10111011
-end
-item: Get Registry Key Value
-  Variable=COMMON
-  Key=SOFTWARE\Microsoft\Windows\CurrentVersion
-  Default=C:\Program Files\Common Files
-  Value Name=CommonFilesDir
-  Flags=00000100
-end
-item: Get Registry Key Value
-  Variable=PROGRAM_FILES
-  Key=SOFTWARE\Microsoft\Windows\CurrentVersion
-  Default=C:\Program Files
-  Value Name=ProgramFilesDir
-  Flags=00000100
-end
-item: Set Variable
-  Variable=EXPLORER
-  Value=1
-end
-item: End Block
-end
-item: Remark
-  Text=Note from Tim:  The Wizard hardcod "C:" at the start of the replacement text for MAINDIR.
-end
-item: Remark
-  Text=That's not appropriate if the system drive doesn't happen to be C:.
-end
-item: Remark
-  Text=I removed the "C:", and that did the right thing for two people who tested it on non-C: machines,
-end
-item: Remark
-  Text=but it's unclear whether it will always do the right thing.
-end
-item: Set Variable
-  Variable=MAINDIR
-  Value=\%MAINDIR%
-  Flags=00001100
-end
-item: Remark
-  Text=BACKUP is the variable that holds the path that all backup files will be copied to when overwritten
-end
-item: Set Variable
-  Variable=BACKUP
-  Value=%MAINDIR%\BACKUP
-  Flags=10000000
-end
-item: Remark
-  Text=DOBACKUP determines if a backup will be performed.  The possible values are A (do backup) or B (do not do backup)
-end
-item: Set Variable
-  Variable=DOBACKUP
-  Value=A
-end
-item: Remark
-  Text=BRANDING determines if the installation will be branded with a name and company.  By default, this is written to the INST directory (installation media).
-end
-item: Set Variable
-  Variable=BRANDING
-  Value=0
-end
-item: If/While Statement
-  Variable=BRANDING
-  Value=1
-end
-item: Read INI Value
-  Variable=NAME
-  Pathname=%INST%\CUSTDATA.INI
-  Section=Registration
-  Item=Name
-end
-item: Read INI Value
-  Variable=COMPANY
-  Pathname=%INST%\CUSTDATA.INI
-  Section=Registration
-  Item=Company
-end
-item: If/While Statement
-  Variable=NAME
-end
-item: Set Variable
-  Variable=DOBRAND
-  Value=1
-end
-item: Get System Information
-  Variable=NAME
-  Flags=00000110
-end
-item: Get System Information
-  Variable=COMPANY
-  Flags=00000111
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-  Text=END WIZARD STUFF -----------------------------------------------------------------------------------------------------------------------------
-end
-item: Remark
-end
-item: Remark
-  Text=Set vrbls for the "Advanced Options" subdialog of Components.
-end
-item: Set Variable
-  Variable=SELECT_ADMIN
-  Value=A
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=0
-end
-item: Set Variable
-  Variable=SELECT_ADMIN
-  Value=B
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=TASKS values:
-end
-item: Remark
-  Text=A: Register file extensions
-end
-item: Remark
-  Text=B: Create Start Menu shortcuts
-end
-item: Set Variable
-  Variable=TASKS
-  Value=AB
-end
-item: Remark
-end
-item: Remark
-  Text=COMPONENTS values:
-end
-item: Remark
-  Text=A: interpreter and libraries
-end
-item: Remark
-  Text=B: Tcl/Tk
-end
-item: Remark
-  Text=C: docs
-end
-item: Remark
-  Text=D: tools
-end
-item: Remark
-  Text=E: test suite
-end
-item: Set Variable
-  Variable=COMPONENTS
-  Value=ABCDE
-end
-item: Remark
-end
-item: Remark
-  Text=March thru the user GUI.
-end
-item: Wizard Block
-  Direction Variable=DIRECTION
-  Display Variable=DISPLAY
-  Bitmap Pathname=.\installer.bmp
-  X Position=9
-  Y Position=10
-  Filler Color=11173759
-  Dialog=Select Destination Directory
-  Dialog=Backup Replaced Files
-  Dialog=Select Components
-  Dialog=Select Program Manager Group
-  Variable=
-  Variable=
-  Variable=
-  Variable=TASKS
-  Value=
-  Value=
-  Value=
-  Value=B
-  Compare=0
-  Compare=0
-  Compare=0
-  Compare=3
-  Flags=00000011
-end
-item: If/While Statement
-  Variable=DISPLAY
-  Value=Start Installation
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=Install directory:  %MAINDIR%%CRLF%
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=SELECT_ADMIN
-  Value=A
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Doing admin install.%CRLF%
-  Flags=00000001
-end
-item: Else Statement
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Doing non-admin install.%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=DOBACKUP
-  Value=A
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Make backups, into %BACKUP%%CRLF%
-  Flags=00000001
-end
-item: Else Statement
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Don't make backups.%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: Remark
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Components:%CRLF%
-  Flags=00000001
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=A
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=    Python interpreter and libraries%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=B
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=    Tcl/Tk (Tkinter, IDLE, pydoc)%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=C
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=    Python documentation%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=D
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=    Tool and utility scripts%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=E
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=    Python test suite%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=TASKS
-  Value=A
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Register file extensions.%CRLF%
-  Flags=00000001
-end
-item: Else Statement
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Don't register file extensions.%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=TASKS
-  Value=B
-  Flags=00000010
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%Start Menu group:  %GROUP%%CRLF%
-  Flags=00000001
-end
-item: Else Statement
-end
-item: Set Variable
-  Variable=SUMMARY
-  Value=%CRLF%No Start Menu shortcuts.%CRLF%
-  Flags=00000001
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-end
-item: Custom Dialog Set
-  Name=Select Destination Directory
-  Display Variable=DISPLAY
-  item: Dialog
-    Title=%APPTITLE% Installation
-    Title French=Installation de %APPTITLE%
-    Title German=Installation von %APPTITLE%
-    Title Spanish=Instalación de %APPTITLE%
-    Title Italian=Installazione di %APPTITLE%
-    Width=339
-    Height=280
-    Font Name=Helv
-    Font Size=8
-    item: Push Button
-      Rectangle=188 234 244 253
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=&Next >
-      Text French=&Suite >
-      Text German=&Weiter >
-      Text Spanish=&Siguiente >
-      Text Italian=&Avanti >
-    end
-    item: Push Button
-      Rectangle=264 234 320 253
-      Action=3
-      Create Flags=01010000000000010000000000000000
-      Text=&Cancel
-      Text French=&Annuler
-      Text German=&Abbrechen
-      Text Spanish=&Cancelar
-      Text Italian=&Annulla
-    end
-    item: Static
-      Rectangle=10 225 320 226
-      Action=3
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Rectangle=108 11 323 33
-      Create Flags=01010000000000000000000000000000
-      Flags=0000000000000001
-      Name=Times New Roman
-      Font Style=-24 0 0 0 700 255 0 0 0 3 2 1 18
-      Text=Select Destination Directory
-      Text French=Sélectionner le répertoire de destination
-      Text German=Zielverzeichnis wählen
-      Text Spanish=Seleccione el directorio de destino
-      Text Italian=Selezionare Directory di destinazione
-    end
-    item: Listbox
-      Rectangle=108 58 321 219
-      Variable=MAINDIR
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000100000010000000101000001
-      Flags=0000110000001010
-      Text=%MAINDIR%
-      Text=
-    end
-    item: Static
-      Rectangle=108 40 313 58
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000000000
-      Text=Please select a directory for the %APPTITLE% files.
-    end
-  end
-  item: Dialog
-    Title=Select Destination Directory
-    Title French=Sélectionner le répertoire de destination
-    Title German=Zielverzeichnis wählen
-    Title Spanish=Seleccione el directorio de destino
-    Title Italian=Selezionare Directory di destinazione
-    Width=276
-    Height=216
-    Font Name=Helv
-    Font Size=8
-    item: Listbox
-      Rectangle=6 6 204 186
-      Variable=MAINDIR
-      Create Flags=01010000100000010000000101000000
-      Flags=0000110000100010
-      Text=%MAINDIR%
-      Text French=%MAINDIR%
-      Text German=%MAINDIR%
-      Text Spanish=%MAINDIR%
-      Text Italian=%MAINDIR%
-    end
-    item: Push Button
-      Rectangle=209 8 265 26
-      Create Flags=01010000000000010000000000000001
-      Text=OK
-      Text French=OK
-      Text German=OK
-      Text Spanish=Aceptar
-      Text Italian=OK
-    end
-    item: Push Button
-      Rectangle=209 31 265 50
-      Variable=MAINDIR
-      Value=%MAINDIR_SAVE%
-      Create Flags=01010000000000010000000000000000
-      Flags=0000000000000001
-      Text=Cancel
-      Text French=Annuler
-      Text German=Abbrechen
-      Text Spanish=Cancelar
-      Text Italian=Annulla
-    end
-  end
-end
-item: Custom Dialog Set
-  Name=Backup Replaced Files
-  Display Variable=DISPLAY
-  item: Dialog
-    Title=%APPTITLE% Installation
-    Title French=Fichiers de Sauvegarde Remplacés
-    Title German=Sicherungskopie von ersetzten Dateien erstellen
-    Title Portuguese=Ficheiros substituídos de segurança
-    Title Spanish=Copias de seguridad de los archivos reemplazados
-    Title Italian=Backup file sostituiti
-    Title Danish=Sikkerhedskopiering af erstattede filer
-    Title Dutch=Vervangen bestanden kopiëren
-    Title Norwegian=Sikkerhetskopiere erstattede filer
-    Title Swedish=Säkerhetskopiera utbytta filer
-    Width=350
-    Height=280
-    Font Name=Helv
-    Font Size=8
-    item: Push Button
-      Rectangle=188 234 244 251
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=&Next >
-      Text French=&Suivant>
-      Text German=&Weiter>
-      Text Portuguese=&Próximo>
-      Text Spanish=&Siguiente >
-      Text Italian=&Avanti >
-      Text Danish=&Næste>
-      Text Dutch=&Volgende>
-      Text Norwegian=&Neste>
-      Text Swedish=&Nästa >
-    end
-    item: Push Button
-      Rectangle=131 234 188 251
-      Variable=DIRECTION
-      Value=B
-      Create Flags=01010000000000010000000000000000
-      Text=< &Back
-      Text French=<&Retour
-      Text German=<&Zurück
-      Text Portuguese=<&Retornar
-      Text Spanish=<&Retroceder
-      Text Italian=< &Indietro
-      Text Danish=<&Tilbage
-      Text Dutch=<&Terug
-      Text Norwegian=<&Tilbake
-      Text Swedish=< &Tillbaka
-    end
-    item: Push Button
-      Rectangle=278 234 330 251
-      Action=3
-      Create Flags=01010000000000010000000000000000
-      Text=Cancel
-      Text French=Annuler
-      Text German=Abbrechen
-      Text Portuguese=Cancelar
-      Text Spanish=Cancelar
-      Text Italian=Annulla
-      Text Danish=Annuller
-      Text Dutch=Annuleren
-      Text Norwegian=Avbryt
-      Text Swedish=Avbryt
-    end
-    item: Static
-      Rectangle=11 221 329 223
-      Action=3
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Rectangle=108 46 320 98
-      Create Flags=01010000000000000000000000000000
-      Text=This installation program can create backup copies of all files replaced during the installation. These files will be used when the software is uninstalled and a rollback is requested.  If backup copies are not created, you will only be able to uninstall the software and not roll the system back to a previous state.
-      Text=
-      Text=Do you want to create backups of replaced files?
-      Text French=Le programme d'installation peut créer des copies de sauvegarde de tous les fichiers remplacés pendant l'installation. Ces fichiers sont utilisés au cas où le logiciel est désinstallé et que l'on procède à la reprise du système. Si les copies de sauvegarde ne sont pas créées, on ne pourra que désinstaller le logiciel sans reprendre le système à un état précédent. Voulez-vous créer une sauvegarde des fichiers remplacés ?
-      Text German=Dieses Installationsprogramm kann Sicherungskopien von allen während der Installation ersetzten Dateien erstellen. Diese Dateien werden zur Rückgängigmachung der Installation und bei Anforderung eines Rollbacks verwendet. Ohne Sicherungskopien ist nur eine Rückgängigmachung der Installation möglich, nicht aber ein Rollback des Systems. Sicherungskopien der ersetzten Dateien erstellen?
-      Text Portuguese=Este programa de instalação pode criar cópias de segurança de todos os ficheiros substituídos durante a instalação. Estes ficheiros serão utilizados quando o programa for desinstalado  e for requisitada uma retomada. Se as cópias de segurança não forem criadas, só poderá desinstalar o programa e não pode retomar  um estado anterior do sistema. Deseja criar cópias de segurança dos ficheiros substituídos?
-      Text Spanish=Este programa de instalación puede crear copias de seguridad de todos los archivos reemplazados durante la instalación. Estos archivos se utilizarán cuando se desinstale el software y se solicite volver al estado anterior. Si no se crean copias de seguridad, únicamente podrá desinstalar el software y no podrá devolver el sistema al estado anterior. ¿Desea crear archivos de seguridad de los archivos reemplazados?
-      Text Italian=Questo programma di installazione può creare copie di backup di tutti i file sostituiti durante l’installazione. Questi file saranno usati quando il software sarà disinstallato e sarà richiesto un ritorno allo stato precedente. Se non crei le copie di backup, potrai solo disinstallare il software, ma non potrai riportare il sistema allo stato precedente. Vuoi creare i file di backup dei file sostituiti?
-      Text Danish=Dette installationsprogram kan oprette sikkerhedskopier af alle filer, som erstattes under installationen. Disse filer benyttes, når softwaren fjernes, og den tidligere systemkonfiguration genetableres. Hvis der ikke oprettes sikkerhedskopier, kan du kun fjerne den installerede software og ikke genetablere den tidligere systemkonfiguration. Vil du oprette sikkerhedskopier af filer, som erstattes?
-      Text Dutch=Dit installatieprogramma kan kopieën maken van alle bestanden die tijdens de installatie worden vervangen. Deze worden dan gebruikt als de software-installatie ongedaan wordt gemaakt en u het systeem wilt laten terugkeren naar de oorspronkelijke staat. Als er geen back-up kopieën worden gemaakt, kunt u de software enkel verwijderen maar het systeem niet in de oorspronkelijke staat terugbrengen. Wilt u een back-up maken van de vervangen bestanden?
-      Text Norwegian=Dette installasjonsprogrammet kan lage sikkerhetskopier av alle filer som blir erstattet under installasjonen. Disse filene vil tas i bruk når programvaren er avinstallert og det er behov for tilbakestilling. Hvis det ikke er laget sikkerhetskopier, kan du kun avinstallere programvaren og ikke stille systemet tilbake til tidligere status. Ønsker du å lage sikkerhetskopier av de filene som blir erstattet nå?
-      Text Swedish=Installationsprogrammet kan skapa säkerhetskopior av alla filer som byts ut under installationen. Dessa filer kan sedan användas när programvaran avinstalleras och du begär rollback. Om du då inte har några säkerhetskopior kan du bara avinstallera programvaran, inte återskapa systemet i dess tidigare skick. Vill du göra säkerhetskopior av de ersatta filerna?
-    end
-    item: Radio Button
-      Rectangle=141 106 265 136
-      Variable=DOBACKUP
-      Create Flags=01010000000000010000000000001001
-      Text=&Yes, make backups
-      Text=N&o, do not make backups
-      Text=
-      Text French=&Oui
-      Text French=N&on
-      Text French=
-      Text German=&Ja
-      Text German=N&ein
-      Text German=
-      Text Portuguese=&Sim
-      Text Portuguese=Nã&o
-      Text Portuguese=
-      Text Spanish=&Sí
-      Text Spanish=N&o
-      Text Spanish=
-      Text Italian=&Sì
-      Text Italian=N&o
-      Text Italian=
-      Text Danish=&Ja
-      Text Danish=&Nej
-      Text Danish=
-      Text Dutch=&Ja
-      Text Dutch=N&ee
-      Text Dutch=
-      Text Norwegian=&Ja
-      Text Norwegian=&Nei
-      Text Norwegian=
-      Text Swedish=&Ja
-      Text Swedish=N&ej
-      Text Swedish=
-    end
-    item: Static
-      Control Name=BACK2
-      Rectangle=108 173 320 208
-      Action=1
-      Create Flags=01010000000000000000000000000111
-      Text=Backup File Destination Directory
-      Text French=Répertoire de destination des fichiers de sauvegarde
-      Text German=Zielverzeichnis für die Sicherungsdatei
-      Text Portuguese=Directório de destino de ficheiro de segurança
-      Text Spanish=Directorio de Destino de los Archivos de Seguridad
-      Text Italian=Directory di destinazione dei file di backup
-      Text Danish=Destinationsbibliotek til sikkerhedskopier
-      Text Dutch=Doeldirectory backup-bestand
-      Text Norwegian=Målkatalog for sikkerhetskopier
-      Text Swedish=Katalog för säkerhetskopierade filer
-    end
-    item: Push Button
-      Control Name=BACK3
-      Rectangle=265 185 318 203
-      Variable=BACKUP_SAVE
-      Value=%BACKUP%
-      Destination Dialog=1
-      Action=2
-      Create Flags=01010000000000010000000000000000
-      Text=B&rowse...
-      Text French=P&arcourir
-      Text German=B&lättern...
-      Text Portuguese=P&rocurar
-      Text Spanish=V&isualizar...
-      Text Italian=Sfoglia...
-      Text Danish=&Gennemse...
-      Text Dutch=B&laderen...
-      Text Norwegian=Bla igjennom
-      Text Swedish=&Bläddra
-    end
-    item: Static
-      Control Name=BACK4
-      Rectangle=129 188 254 200
-      Destination Dialog=2
-      Create Flags=01010000000000000000000000000000
-      Text=%BACKUP%
-      Text French=%BACKUP%
-      Text German=%BACKUP%
-      Text Portuguese=%BACKUP%
-      Text Spanish=%BACKUP%
-      Text Italian=%BACKUP%
-      Text Danish=%BACKUP%
-      Text Dutch=%BACKUP%
-      Text Norwegian=%BACKUP%
-      Text Swedish=%BACKUP%
-    end
-    item: Static
-      Rectangle=108 11 323 36
-      Create Flags=01010000000000000000000000000000
-      Flags=0000000000000001
-      Name=Times New Roman
-      Font Style=-24 0 0 0 700 255 0 0 0 3 2 1 18
-      Text=Backup Replaced Files
-      Text French=Sélectionner les composants
-      Text German=Komponenten auswählen
-      Text Spanish=Seleccione componentes
-      Text Italian=Selezionare i componenti
-    end
-    item: If/While Statement
-      Variable=DOBACKUP
-      Value=B
-    end
-    item: Set Control Attribute
-      Control Name=BACK3
-      Operation=1
-    end
-    item: Set Control Attribute
-      Control Name=BACK4
-      Operation=1
-    end
-    item: Else Statement
-    end
-    item: Set Control Attribute
-      Control Name=BACK3
-    end
-    item: Set Control Attribute
-      Control Name=BACK4
-    end
-    item: End Block
-    end
-  end
-  item: Dialog
-    Title=Select Destination Directory
-    Title French=Choisissez le répertoire de destination
-    Title German=Zielverzeichnis wählen
-    Title Portuguese=Seleccionar Directório de Destino
-    Title Spanish=Seleccione el Directorio de Destino
-    Title Italian=Seleziona Directory di destinazione
-    Title Danish=Vælg Destinationsbibliotek
-    Title Dutch=Kies Doeldirectory
-    Title Norwegian=Velg målkatalog
-    Title Swedish=Välj destinationskalatog
-    Width=276
-    Height=216
-    Font Name=Helv
-    Font Size=8
-    item: Listbox
-      Rectangle=6 3 200 186
-      Variable=BACKUP
-      Create Flags=01010000100000010000000101000000
-      Flags=0000110000100010
-      Text=%BACKUP%
-      Text=
-      Text French=%BACKUP%
-      Text French=
-      Text German=%BACKUP%
-      Text German=
-      Text Portuguese=%BACKUP%
-      Text Portuguese=
-      Text Spanish=%BACKUP%
-      Text Spanish=
-      Text Italian=%BACKUP%
-      Text Italian=
-      Text Danish=%BACKUP%
-      Text Danish=
-      Text Dutch=%BACKUP%
-      Text Dutch=
-      Text Norwegian=%BACKUP%
-      Text Norwegian=
-      Text Swedish=%BACKUP%
-      Text Swedish=
-    end
-    item: Push Button
-      Rectangle=209 8 265 26
-      Create Flags=01010000000000010000000000000001
-      Text=OK
-      Text French=OK
-      Text German=OK
-      Text Portuguese=OK
-      Text Spanish=ACEPTAR
-      Text Italian=OK
-      Text Danish=OK
-      Text Dutch=OK
-      Text Norwegian=OK
-      Text Swedish=OK
-    end
-    item: Push Button
-      Rectangle=209 31 265 50
-      Variable=BACKUP
-      Value=%BACKUP_SAVE%
-      Create Flags=01010000000000010000000000000000
-      Flags=0000000000000001
-      Text=Cancel
-      Text French=Annuler
-      Text German=Abbrechen
-      Text Portuguese=Cancelar
-      Text Spanish=Cancelar
-      Text Italian=Annulla
-      Text Danish=Slet
-      Text Dutch=Annuleren
-      Text Norwegian=Avbryt
-      Text Swedish=Avbryt
-    end
-  end
-end
-item: Custom Dialog Set
-  Name=Select Components
-  Display Variable=DISPLAY
-  item: Dialog
-    Title=%APPTITLE% Installation
-    Title French=Installation de %APPTITLE%
-    Title German=Installation von %APPTITLE%
-    Title Spanish=Instalación de %APPTITLE%
-    Title Italian=Installazione di %APPTITLE%
-    Width=339
-    Height=280
-    Font Name=Helv
-    Font Size=8
-    item: Push Button
-      Rectangle=188 234 244 253
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=&Next >
-      Text French=&Suite >
-      Text German=&Weiter >
-      Text Spanish=&Siguiente >
-      Text Italian=&Avanti >
-    end
-    item: Push Button
-      Rectangle=131 234 188 253
-      Variable=DIRECTION
-      Value=B
-      Create Flags=01010000000000010000000000000000
-      Text=< &Back
-      Text French=< &Retour
-      Text German=< &Zurück
-      Text Spanish=< &Atrás
-      Text Italian=< &Indietro
-    end
-    item: Push Button
-      Rectangle=264 234 320 253
-      Action=3
-      Create Flags=01010000000000010000000000000000
-      Text=&Cancel
-      Text French=&Annuler
-      Text German=&Abbrechen
-      Text Spanish=&Cancelar
-      Text Italian=&Annulla
-    end
-    item: Checkbox
-      Rectangle=108 66 313 156
-      Variable=COMPONENTS
-      Create Flags=01010000000000010000000000000011
-      Flags=0000000000000110
-      Text=Python interpreter and libraries
-      Text=Tcl/Tk (Tkinter, IDLE, pydoc)
-      Text=Python HTML docs
-      Text=Python utility scripts (Tools/)
-      Text=Python test suite (Lib/test/)
-      Text=
-      Text French=Python interpreter, library and IDLE
-      Text French=Python HTML docs
-      Text French=Python utility scripts (Tools/)
-      Text French=Python test suite (Lib/test/)
-      Text French=
-      Text German=Python interpreter, library and IDLE
-      Text German=Python HTML docs
-      Text German=Python utility scripts (Tools/)
-      Text German=Python test suite (Lib/test/)
-      Text German=
-      Text Spanish=Python interpreter, library and IDLE
-      Text Spanish=Python HTML docs
-      Text Spanish=Python utility scripts (Tools/)
-      Text Spanish=Python test suite (Lib/test/)
-      Text Spanish=
-      Text Italian=Python interpreter, library and IDLE
-      Text Italian=Python HTML docs
-      Text Italian=Python utility scripts (Tools/)
-      Text Italian=Python test suite (Lib/test/)
-      Text Italian=
-    end
-    item: Static
-      Rectangle=108 45 320 63
-      Create Flags=01010000000000000000000000000000
-      Text=Choose which components to install by checking the boxes below.
-      Text French=Choisissez les composants que vous voulez installer en cochant les cases ci-dessous.
-      Text German=Wählen Sie die zu installierenden Komponenten, indem Sie in die entsprechenden Kästchen klicken.
-      Text Spanish=Elija los componentes que desee instalar marcando los cuadros de abajo.
-      Text Italian=Scegliere quali componenti installare selezionando le caselle sottostanti.
-    end
-    item: Push Button
-      Rectangle=188 203 269 220
-      Destination Dialog=1
-      Action=2
-      Enabled Color=00000000000000000000000011111111
-      Create Flags=01010000000000010000000000000000
-      Text=Advanced Options ...
-    end
-    item: Static
-      Rectangle=10 225 320 226
-      Action=3
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Rectangle=108 10 323 43
-      Create Flags=01010000000000000000000000000000
-      Flags=0000000000000001
-      Name=Times New Roman
-      Font Style=-24 0 0 0 700 255 0 0 0 3 2 1 18
-      Text=Select Components
-      Text French=Sélectionner les composants
-      Text German=Komponenten auswählen
-      Text Spanish=Seleccione componentes
-      Text Italian=Selezionare i componenti
-    end
-    item: Static
-      Rectangle=251 180 311 193
-      Variable=COMPONENTS
-      Value=MAINDIR
-      Create Flags=01010000000000000000000000000010
-    end
-    item: Static
-      Rectangle=251 168 311 179
-      Variable=COMPONENTS
-      Create Flags=01010000000000000000000000000010
-    end
-    item: Static
-      Rectangle=123 168 234 181
-      Create Flags=01010000000000000000000000000000
-      Text=Disk Space Required:
-      Text French=Espace disque requis :
-      Text German=Notwendiger Speicherplatz:
-      Text Spanish=Espacio requerido en el disco:
-      Text Italian=Spazio su disco necessario:
-    end
-    item: Static
-      Rectangle=123 180 234 193
-      Create Flags=01010000000000000000000000000000
-      Text=Disk Space Remaining:
-      Text French=Espace disque disponible :
-      Text German=Verbleibender Speicherplatz:
-      Text Spanish=Espacio en disco disponible:
-      Text Italian=Spazio su disco disponibile:
-    end
-    item: Static
-      Rectangle=108 158 320 196
-      Action=1
-      Create Flags=01010000000000000000000000000111
-    end
-    item: If/While Statement
-      Variable=DLG_EVENT_TYPE
-      Value=VERIFY
-    end
-    item: Remark
-      Text=If they're installing Tcl/Tk, Tools, or the test suite, doesn't make much sense unless they're installing Python too.
-    end
-    item: If/While Statement
-      Variable=COMPONENTS
-      Value=BDE
-      Flags=00001010
-    end
-    item: If/While Statement
-      Variable=COMPONENTS
-      Value=A
-      Flags=00000011
-    end
-    item: Display Message
-      Title=Are you sure?
-      Text=Installing Tcl/Tk, Tools or the test suite doesn't make much sense unless you install the Python interpreter and libraries too.
-      Text=
-      Text=Click Yes if that's really what you want.
-      Flags=00101101
-    end
-    item: Remark
-      Text=Nothing -- just proceed to the next dialog.
-    end
-    item: Else Statement
-    end
-    item: Remark
-      Text=Return to the dialog.
-    end
-    item: Set Variable
-      Variable=DLG_EVENT_TYPE
-    end
-    item: End Block
-    end
-    item: End Block
-    end
-    item: End Block
-    end
-    item: End Block
-    end
-  end
-  item: Dialog
-    Title=Advanced Options
-    Width=339
-    Height=213
-    Font Name=Helv
-    Font Size=8
-    item: Radio Button
-      Control Name=ADMIN2
-      Rectangle=11 46 90 76
-      Variable=SELECT_ADMIN
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000010000000000001001
-      Text=Admin install
-      Text=Non-Admin installl
-      Text=
-    end
-    item: Push Button
-      Rectangle=188 170 244 189
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=OK
-      Text French=&Suite >
-      Text German=&Weiter >
-      Text Spanish=&Siguiente >
-      Text Italian=&Avanti >
-    end
-    item: Static
-      Rectangle=5 3 326 83
-      Action=1
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Control Name=ADMIN1
-      Rectangle=11 11 321 45
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000000000
-      Text=By default, the install records settings in the per-machine area of the registry (HKLM), and installs the Python and C runtime DLLs to %SYS32%.  Choose "Non-Admin install" if you would prefer settings made in the per-user registry (HKCU), and DLLs installed in %MAINDIR%.
-    end
-    item: Static
-      Rectangle=5 90 326 157
-      Action=1
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Checkbox
-      Rectangle=11 121 243 151
-      Variable=TASKS
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000010000000000000011
-      Text=Register file extensions (.py, .pyw, .pyc, .pyo)
-      Text=Create Start Menu shortcuts
-      Text=
-    end
-    item: Static
-      Rectangle=11 103 320 121
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000000000
-      Text=Choose tasks to perform by checking the boxes below.
-    end
-    item: If/While Statement
-      Variable=DLG_EVENT_TYPE
-      Value=INIT
-    end
-    item: If/While Statement
-      Variable=DOADMIN
-      Value=1
-    end
-    item: Set Control Attribute
-      Control Name=ADMIN2
-    end
-    item: Else Statement
-    end
-    item: Set Control Text
-      Control Name=ADMIN1
-      Control Text=This section is available only if logged in to an account with Administrator privileges.
-    end
-    item: Set Control Attribute
-      Control Name=ADMIN2
-      Operation=1
-    end
-    item: End Block
-    end
-    item: End Block
-    end
-  end
-end
-item: Custom Dialog Set
-  Name=Select Program Manager Group
-  Display Variable=DISPLAY
-  item: Dialog
-    Title=%APPTITLE% Installation
-    Title French=Installation de %APPTITLE%
-    Title German=Installation von %APPTITLE%
-    Title Spanish=Instalación de %APPTITLE%
-    Title Italian=Installazione di %APPTITLE%
-    Width=339
-    Height=280
-    Font Name=Helv
-    Font Size=8
-    item: Push Button
-      Rectangle=188 234 244 253
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=&Next >
-      Text French=&Suite >
-      Text German=&Weiter >
-      Text Spanish=&Siguiente >
-      Text Italian=&Avanti >
-    end
-    item: Push Button
-      Rectangle=131 234 188 253
-      Variable=DIRECTION
-      Value=B
-      Create Flags=01010000000000010000000000000000
-      Flags=0000000000000001
-      Text=< &Back
-      Text French=< &Retour
-      Text German=< &Zurück
-      Text Spanish=< &Atrás
-      Text Italian=< &Indietro
-    end
-    item: Push Button
-      Rectangle=264 234 320 253
-      Action=3
-      Create Flags=01010000000000010000000000000000
-      Text=&Cancel
-      Text French=&Annuler
-      Text German=&Abbrechen
-      Text Spanish=&Cancelar
-      Text Italian=&Annulla
-    end
-    item: Static
-      Rectangle=10 225 320 226
-      Action=3
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Rectangle=108 10 323 53
-      Create Flags=01010000000000000000000000000000
-      Flags=0000000000000001
-      Name=Times New Roman
-      Font Style=-24 0 0 0 700 255 0 0 0 3 2 1 18
-      Text=Select Start Menu Group
-      Text French=Sélectionner le groupe du Gestionnaire de programme
-      Text German=Bestimmung der Programm-Managergruppe
-      Text Spanish=Seleccione grupo del Administrador de programas
-      Text Italian=Selezionare il gruppo ProgMan
-    end
-    item: Static
-      Rectangle=108 35 320 65
-      Create Flags=01010000000000000000000000000000
-      Text=Enter the name of the Start Menu program group to which to add the %APPTITLE% icons:
-      Text French=Entrez le nom du groupe du Gestionnaire de programme dans lequel vous souhaitez ajouter les icônes de %APPTITLE% :
-      Text German=Geben Sie den Namen der Programmgruppe ein, der das Symbol %APPTITLE% hinzugefügt werden soll:
-      Text Spanish=Escriba el nombre del grupo del Administrador de programas en el que desea agregar los iconos de %APPTITLE%:
-      Text Italian=Inserire il nome del gruppo Program Manager per aggiungere le icone %APPTITLE% a:
-    end
-    item: Combobox
-      Rectangle=108 56 320 219
-      Variable=GROUP
-      Create Flags=01010000001000010000001100000001
-      Flags=0000000000000001
-      Text=%GROUP%
-      Text=
-      Text French=%GROUP%
-      Text German=%GROUP%
-      Text Spanish=%GROUP%
-      Text Italian=%GROUP%
-    end
-  end
-end
-item: Custom Dialog Set
-  Name=Start Installation
-  Display Variable=DISPLAY
-  item: Dialog
-    Title=%APPTITLE% Installation
-    Title French=Installation de %APPTITLE%
-    Title German=Installation von %APPTITLE%
-    Title Spanish=Instalación de %APPTITLE%
-    Title Italian=Installazione di %APPTITLE%
-    Width=339
-    Height=280
-    Font Name=Helv
-    Font Size=8
-    item: Push Button
-      Rectangle=188 234 244 253
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=&Next >
-      Text French=&Suite >
-      Text German=&Weiter >
-      Text Spanish=&Siguiente >
-      Text Italian=&Avanti >
-    end
-    item: Push Button
-      Rectangle=131 234 188 253
-      Variable=DIRECTION
-      Value=B
-      Create Flags=01010000000000010000000000000000
-      Text=< &Back
-      Text French=< &Retour
-      Text German=< &Zurück
-      Text Spanish=< &Atrás
-      Text Italian=< &Indietro
-    end
-    item: Push Button
-      Rectangle=264 234 320 253
-      Action=3
-      Create Flags=01010000000000010000000000000000
-      Text=&Cancel
-      Text French=&Annuler
-      Text German=&Abbrechen
-      Text Spanish=&Cancelar
-      Text Italian=&Annulla
-    end
-    item: Static
-      Rectangle=10 225 320 226
-      Action=3
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Rectangle=108 10 323 53
-      Create Flags=01010000000000000000000000000000
-      Flags=0000000000000001
-      Name=Times New Roman
-      Font Style=-24 0 0 0 700 255 0 0 0 3 2 1 18
-      Text=Ready to Install!
-      Text French=Prêt à installer !
-      Text German=Installationsbereit!
-      Text Spanish=¡Preparado para la instalación!
-      Text Italian=Pronto per l'installazione!
-    end
-    item: Static
-      Rectangle=108 40 320 62
-      Create Flags=01010000000000000000000000000000
-      Text=Click the Next button to install %APPTITLE%, or the Back button to change choices:
-      Text French=Vous êtes maintenant prêt à installer les fichiers %APPTITLE%.
-      Text French=
-      Text French=Cliquez sur le bouton Suite pour commencer l'installation ou sur le bouton Retour pour entrer les informations d'installation à nouveau.
-      Text German=Sie können %APPTITLE% nun installieren.
-      Text German=
-      Text German=Klicken Sie auf "Weiter", um mit der Installation zu beginnen. Klicken Sie auf "Zurück", um die Installationsinformationen neu einzugeben.
-      Text Spanish=Ya está listo para instalar %APPTITLE%.
-      Text Spanish=
-      Text Spanish=Presione el botón Siguiente para comenzar la instalación o presione Atrás para volver a ingresar la información para la instalación.
-      Text Italian=Ora è possibile installare %APPTITLE%.
-      Text Italian=
-      Text Italian=Premere il pulsante Avanti per avviare l'installazione o il pulsante Indietro per reinserire le informazioni di installazione.
-    end
-    item: Editbox
-      Rectangle=108 66 324 219
-      Help Context=16711681
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000100000000001100011000100
-      Text=%SUMMARY%
-    end
-  end
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=DISPLAY
-  Value=Select Destination Directory
-end
-item: Remark
-  Text=User may have changed MAINDIR, so reset BACKUP to match.
-end
-item: Set Variable
-  Variable=BACKUP
-  Value=%MAINDIR%\BACKUP
-end
-item: End Block
-end
-item: Remark
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=BEGIN WIZARD STUFF -----------------------------------------------------------------------------------------------------------------------------
-end
-item: Remark
-  Text=When the BACKUP feature is enabled, the BACKUPDIR is initialized
-end
-item: If/While Statement
-  Variable=DOBACKUP
-  Value=A
-end
-item: Set Variable
-  Variable=BACKUPDIR
-  Value=%BACKUP%
-end
-item: End Block
-end
-item: Remark
-  Text=The BRANDING information is written to the INI file on the installation media.
-end
-item: If/While Statement
-  Variable=BRANDING
-  Value=1
-end
-item: If/While Statement
-  Variable=DOBRAND
-  Value=1
-end
-item: Edit INI File
-  Pathname=%INST%\CUSTDATA.INI
-  Settings=[Registration]
-  Settings=NAME=%NAME%
-  Settings=COMPANY=%COMPANY%
-  Settings=
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-  Text=Begin writing to the INSTALL.LOG
-end
-item: Open/Close INSTALL.LOG
-end
-item: Remark
-  Text=Check free disk space calculates free disk space as well as component sizes.
-end
-item: Remark
-  Text=It should be located before all Install File actions.
-end
-item: Check Disk Space
-  Component=COMPONENTS
-end
-item: Remark
-  Text=This include script allows uninstall support
-end
-item: Remark
-  Text=Note from Tim:  this is our own Uninstal.wse, a copy of Wise's except
-end
-item: Remark
-  Text=it writes to HKCU (instead of HKLM) if the user doesn't have admin privs.
-end
-item: Include Script
-  Pathname=.\Uninstal.wse
-end
-item: Remark
-  Text=Note from Tim: these seeming no-ops actually convert to short filenames.
-end
-item: Set Variable
-  Variable=COMMON
-  Value=%COMMON%
-  Flags=00010100
-end
-item: Set Variable
-  Variable=MAINDIR
-  Value=%MAINDIR%
-  Flags=00010100
-end
-item: Remark
-  Text=This IF/THEN/ELSE reads the correct registry entries for shortcut/icon placement
-end
-item: Check Configuration
-  Flags=10111011
-end
-item: Get Registry Key Value
-  Variable=STARTUPDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%WIN%\Start Menu\Programs\StartUp
-  Value Name=StartUp
-  Flags=00000010
-end
-item: Get Registry Key Value
-  Variable=DESKTOPDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%WIN%\Desktop
-  Value Name=Desktop
-  Flags=00000010
-end
-item: Get Registry Key Value
-  Variable=STARTMENUDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%WIN%\Start Menu
-  Value Name=Start Menu
-  Flags=00000010
-end
-item: Get Registry Key Value
-  Variable=GROUPDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%WIN%\Start Menu\Programs
-  Value Name=Programs
-  Flags=00000010
-end
-item: Get Registry Key Value
-  Variable=CSTARTUPDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%STARTUPDIR%
-  Value Name=Common Startup
-  Flags=00000100
-end
-item: Get Registry Key Value
-  Variable=CDESKTOPDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%DESKTOPDIR%
-  Value Name=Common Desktop
-  Flags=00000100
-end
-item: Get Registry Key Value
-  Variable=CSTARTMENUDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%STARTMENUDIR%
-  Value Name=Common Start Menu
-  Flags=00000100
-end
-item: Get Registry Key Value
-  Variable=CGROUPDIR
-  Key=Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
-  Default=%GROUPDIR%
-  Value Name=Common Programs
-  Flags=00000100
-end
-item: Else Statement
-end
-item: Remark
-  Text=Note from Tim:  the Wizard left this block empty!
-end
-item: Remark
-  Text=Perhaps it's only relevant on Windows 3.1.
-end
-item: End Block
-end
-item: Remark
-  Text=END WIZARD STUFF -----------------------------------------------------------------------------------------------------------------------------
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=SELECT_ADMIN
-  Value=B
-end
-item: Remark
-  Text=The user chose a non-admin install in "Advanced Options".
-end
-item: Remark
-  Text=This should come after the include of Uninstal.wse above, because
-end
-item: Remark
-  Text=writing uninstall info to HKCU is ineffective except under Win2K.
-end
-item: Set Variable
-  Variable=DOADMIN
-  Value=0
-end
-item: End Block
-end
-item: Remark
-end
-item: Set Variable
-  Variable=CGROUP_SAVE
-  Value=%GROUP%
-end
-item: If/While Statement
-  Variable=TASKS
-  Value=B
-  Flags=00000010
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=1
-end
-item: Set Variable
-  Variable=GROUP
-  Value=%CGROUPDIR%\%GROUP%
-end
-item: Else Statement
-end
-item: Set Variable
-  Variable=GROUP
-  Value=%GROUPDIR%\%GROUP%
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=Long section to install files.
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=1
-end
-item: Set Variable
-  Variable=DLLDEST
-  Value=%SYS32%
-end
-item: Else Statement
-end
-item: Set Variable
-  Variable=DLLDEST
-  Value=%MAINDIR%
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=Install the license even if they deselect everything <wink>.
-end
-item: Install File
-  Source=..\license
-  Destination=%MAINDIR%\LICENSE.txt
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\readme
-  Destination=%MAINDIR%\README.txt
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\misc\news
-  Destination=%MAINDIR%\NEWS.txt
-  Flags=0000000000000010
-end
-item: Remark
-  Text=Icons -- always install so that the uninstaller can use them for its own display.
-end
-item: Install File
-  Source=..\pc\pycon.ico
-  Destination=%MAINDIR%\pycon.ico
-  Flags=0000000010000010
-end
-item: Install File
-  Source=..\pc\pyc.ico
-  Destination=%MAINDIR%\pyc.ico
-  Flags=0000000010000010
-end
-item: Install File
-  Source=..\pc\py.ico
-  Destination=%MAINDIR%\py.ico
-  Flags=0000000010000010
-end
-item: Remark
-end
-item: Remark
-  Text=These arrange to (recursively!) delete all .pyc and .pyo files at uninstall time.
-end
-item: Remark
-  Text=This "does the right thing":  any directories left empty at the end are removed.
-end
-item: Add Text to INSTALL.LOG
-  Text=File Tree: %MAINDIR%\*.pyc
-end
-item: Add Text to INSTALL.LOG
-  Text=File Tree: %MAINDIR%\*.pyo
-end
-item: Remark
-end
-item: Remark
-  Text=A: interpreter and libraries
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=A
-  Flags=00000010
-end
-item: Remark
-  Text=Executables
-end
-item: Install File
-  Source=.\python.exe
-  Destination=%MAINDIR%\python.exe
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\pythonw.exe
-  Destination=%MAINDIR%\pythonw.exe
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\w9xpopen.exe
-  Destination=%MAINDIR%\w9xpopen.exe
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=Extension module DLLs (.pyd); keep in synch with libs directory next
-end
-item: Install File
-  Source=.\_winreg.pyd
-  Destination=%MAINDIR%\DLLs\_winreg.pyd
-  Description=Extension modules
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_csv.pyd
-  Destination=%MAINDIR%\DLLs\_csv.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_sre.pyd
-  Destination=%MAINDIR%\DLLs\_sre.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_ssl.pyd
-  Destination=%MAINDIR%\DLLs\_ssl.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_symtable.pyd
-  Destination=%MAINDIR%\DLLs\_symtable.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_testcapi.pyd
-  Destination=%MAINDIR%\DLLs\_testcapi.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_tkinter.pyd
-  Destination=%MAINDIR%\DLLs\_tkinter.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_socket.pyd
-  Destination=%MAINDIR%\DLLs\_socket.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_bsddb.pyd
-  Destination=%MAINDIR%\DLLs\_bsddb.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\bz2.pyd
-  Destination=%MAINDIR%\DLLs\bz2.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\datetime.pyd
-  Destination=%MAINDIR%\DLLs\datetime.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\mmap.pyd
-  Destination=%MAINDIR%\DLLs\mmap.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\parser.pyd
-  Destination=%MAINDIR%\DLLs\parser.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\pyexpat.pyd
-  Destination=%MAINDIR%\DLLs\pyexpat.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\select.pyd
-  Destination=%MAINDIR%\DLLs\select.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\unicodedata.pyd
-  Destination=%MAINDIR%\DLLs\unicodedata.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\winsound.pyd
-  Destination=%MAINDIR%\DLLs\winsound.pyd
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\zlib.pyd
-  Destination=%MAINDIR%\DLLs\zlib.pyd
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=Link libraries (.lib); keep in synch with DLLs above, except that the Python lib lives here.
-end
-item: Install File
-  Source=.\_winreg.lib
-  Destination=%MAINDIR%\libs\_winreg.lib
-  Description=Link library files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_csv.lib
-  Destination=%MAINDIR%\libs\_csv.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_sre.lib
-  Destination=%MAINDIR%\libs\_sre.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_ssl.lib
-  Destination=%MAINDIR%\libs\_ssl.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_symtable.lib
-  Destination=%MAINDIR%\libs\_symtable.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_testcapi.lib
-  Destination=%MAINDIR%\libs\_testcapi.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_tkinter.lib
-  Destination=%MAINDIR%\libs\_tkinter.lib
-  Description=Extension modules
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_socket.lib
-  Destination=%MAINDIR%\libs\_socket.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\_bsddb.lib
-  Destination=%MAINDIR%\libs\_bsddb.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\bz2.lib
-  Destination=%MAINDIR%\libs\bz2.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\datetime.lib
-  Destination=%MAINDIR%\libs\datetime.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\mmap.lib
-  Destination=%MAINDIR%\libs\mmap.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\parser.lib
-  Destination=%MAINDIR%\libs\parser.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\pyexpat.lib
-  Destination=%MAINDIR%\libs\pyexpat.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\select.lib
-  Destination=%MAINDIR%\libs\select.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\unicodedata.lib
-  Destination=%MAINDIR%\libs\unicodedata.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\winsound.lib
-  Destination=%MAINDIR%\libs\winsound.lib
-  Flags=0000000000000010
-end
-item: Install File
-  Source=.\zlib.lib
-  Destination=%MAINDIR%\libs\zlib.lib
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=.\python%_pymajor_%%_pyminor_%.lib
-  Destination=%MAINDIR%\libs\python%_PYMAJOR_%%_PYMINOR_%.lib
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=Main Python DLL
-end
-item: Remark
-  Text=Tell Wise it's OK to delete the Python DLL at uninstall time,
-end
-item: Remark
-  Text=despite that we (may) write it into a system directory.
-end
-item: Add Text to INSTALL.LOG
-  Text=Non-System File:
-end
-item: Install File
-  Source=.\python%_pymajor_%%_pyminor_%.dll
-  Destination=%DLLDEST%\python%_PYMAJOR_%%_PYMINOR_%.dll
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=Libraries (Lib/)
-end
-item: Install File
-  Source=..\lib\*.py
-  Destination=%MAINDIR%\Lib
-  Description=Library Modules
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\bsddb\*.py
-  Destination=%MAINDIR%\Lib\bsddb
-  Description=Berkeley database package
-  Flags=0000000100000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\compiler\*.py
-  Destination=%MAINDIR%\Lib\compiler
-  Description=Python compiler written in Python
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\distutils\*.py
-  Destination=%MAINDIR%\Lib\distutils
-  Description=Distribution utility modules
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\distutils\readme
-  Destination=%MAINDIR%\Lib\distutils\README.txt
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\distutils\command\*.py
-  Destination=%MAINDIR%\Lib\distutils\command
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\distutils\command\wininst.exe
-  Destination=%MAINDIR%\Lib\distutils\command\wininst.exe
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\distutils\command\command_template
-  Destination=%MAINDIR%\Lib\distutils\command\command_template
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\email\*.py
-  Destination=%MAINDIR%\Lib\email
-  Description=Library email package
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\email\test\*.py
-  Destination=%MAINDIR%\Lib\email\test
-  Description=email tests
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\email\test\data\*.txt
-  Destination=%MAINDIR%\Lib\email\test\data
-  Description=email test data
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\email\test\data\*.gif
-  Destination=%MAINDIR%\Lib\email\test\data
-  Description=email test data
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\email\test\data\*.au
-  Destination=%MAINDIR%\Lib\email\test\data
-  Description=email test data
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\encodings\*.py
-  Destination=%MAINDIR%\Lib\encodings
-  Description=Unicode encoding tables
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\hotshot\*.py
-  Destination=%MAINDIR%\Lib\hotshot
-  Description=Fast Python profiler
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\lib-old\*.py
-  Destination=%MAINDIR%\Lib\lib-old
-  Description=Obsolete modules
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\lib-tk\*.py
-  Destination=%MAINDIR%\Lib\lib-tk
-  Description=Tkinter related library modules
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\logging\*.py
-  Destination=%MAINDIR%\Lib\logging
-  Description=Logging package
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\site-packages\readme
-  Destination=%MAINDIR%\Lib\site-packages\README.txt
-  Description=Site packages
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\xml\*.py
-  Destination=%MAINDIR%\Lib\xml
-  Description=XML support packages
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\xml\dom\*.py
-  Destination=%MAINDIR%\Lib\xml\dom
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\xml\parsers\*.py
-  Destination=%MAINDIR%\Lib\xml\parsers
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\xml\sax\*.py
-  Destination=%MAINDIR%\Lib\xml\sax
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=C Include files
-end
-item: Install File
-  Source=..\include\*.h
-  Destination=%MAINDIR%\include
-  Description=Header files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\pc\pyconfig.h
-  Destination=%MAINDIR%\include\pyconfig.h
-  Description=Header files (pyconfig.h)
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=Microsoft C runtime libraries
-end
-item: Install File
-  Source=%_SYS_%\MSVCIRT.DLL
-  Destination=%DLLDEST%\MSVCIRT.DLL
-  Description=Visual C++ Runtime DLLs
-  Flags=0000011000010011
-end
-item: Install File
-  Source=%_SYS_%\MSVCRT.DLL
-  Destination=%DLLDEST%\MSVCRT.DLL
-  Description=Visual C++ Runtime DLLs
-  Flags=0000011000010011
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=B: Tcl/Tk (Tkinter, IDLE, pydoc)
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=B
-  Flags=00000010
-end
-item: Remark
-  Text=Tcl/Tk
-end
-item: Install File
-  Source=..\..\%_tcldir_%\bin\*.dll
-  Destination=%MAINDIR%\DLLs
-  Description=Tcl/Tk binaries and libraries
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\..\%_tcldir_%\lib\*.*
-  Destination=%MAINDIR%\tcl
-  Description=Tcl/Tk binaries and libraries
-  Flags=0000000100000010
-end
-item: Remark
-end
-item: Remark
-  Text=IDLE
-end
-item: Install File
-  Source=..\Lib\idlelib\*.py
-  Destination=%MAINDIR%\Lib\idlelib
-  Description=Integrated DeveLopment Environment for Python
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\Lib\idlelib\*.txt
-  Destination=%MAINDIR%\Lib\idlelib
-  Description=Integrated DeveLopment Environment for Python
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\Lib\idlelib\*.def
-  Destination=%MAINDIR%\Lib\idlelib
-  Description=Integrated DeveLopment Environment for Python
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\Lib\idlelib\Icons\*
-  Destination=%MAINDIR%\Lib\idlelib\Icons
-  Description=Integrated DeveLopment Environment for Python
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\Tools\scripts\idle
-  Destination=%MAINDIR%\Lib\idlelib\idle.pyw
-  Description=IDLE bootstrap script
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Remark
-  Text=Windows pydoc driver
-end
-item: Install File
-  Source=..\tools\scripts\*.pyw
-  Destination=%MAINDIR%\Tools\Scripts
-  Description=Windows pydoc driver
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=C: docs
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=C
-  Flags=00000010
-end
-item: Install File
-  Source=%_DOC_%\*.*
-  Destination=%MAINDIR%\Doc
-  Description=Python Documentation (HTML)
-  Flags=0000000100000010
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=D: tools
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=D
-  Flags=00000010
-end
-item: Install File
-  Source=..\tools\scripts\*.py
-  Destination=%MAINDIR%\Tools\Scripts
-  Description=Utility Scripts
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\scripts\*.doc
-  Destination=%MAINDIR%\Tools\Scripts
-  Description=Utility Scripts
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\scripts\readme
-  Destination=%MAINDIR%\Tools\Scripts\README.txt
-  Description=Utility Scripts
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\tools\webchecker\*.py
-  Destination=%MAINDIR%\Tools\webchecker
-  Description=Web checker tool
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\webchecker\readme
-  Destination=%MAINDIR%\Tools\webchecker\README.txt
-  Description=Web checker tool
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\tools\versioncheck\*.py
-  Destination=%MAINDIR%\Tools\versioncheck
-  Description=Version checker tool
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\versioncheck\readme
-  Destination=%MAINDIR%\Tools\versioncheck\README.txt
-  Description=Version checker tool
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\tools\pynche\*.py
-  Destination=%MAINDIR%\Tools\pynche
-  Description=pynche color editor
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\pynche\*.txt
-  Destination=%MAINDIR%\Tools\pynche
-  Description=pynche color editor
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\pynche\x\*.txt
-  Destination=%MAINDIR%\Tools\pynche\X
-  Description=pynche color editor - X files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\tools\pynche\readme
-  Destination=%MAINDIR%\Tools\pynche\README.txt
-  Description=pynche color editor - README
-  Flags=0000000100000010
-end
-item: Install File
-  Source=..\tools\pynche\pynche
-  Destination=%MAINDIR%\Tools\pynche\pynche.py
-  Description=pynche color editor - main
-  Flags=0000000100000010
-end
-item: Install File
-  Source=..\tools\pynche\pynche.pyw
-  Destination=%MAINDIR%\Tools\pynche\pynche.pyw
-  Description=pynche color editor - noconsole main
-  Flags=0000000100000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\tools\i18n\*.py
-  Destination=%MAINDIR%\Tools\i18n
-  Description=Internationalization helpers
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=E: test suite
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=E
-  Flags=00000010
-end
-item: Install File
-  Source=..\lib\test\audiotest.au
-  Destination=%MAINDIR%\Lib\test\audiotest.au
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.uue
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.py
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.xml
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.out
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.bz2
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.tar
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.gz
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Install File
-  Source=..\lib\test\*.txt
-  Destination=%MAINDIR%\Lib\test
-  Description=Python Test files
-  Flags=0000000000000010
-end
-item: Remark
-end
-item: Install File
-  Source=..\lib\test\output\*.*
-  Destination=%MAINDIR%\Lib\test\output
-  Description=Python Test output files
-  Flags=0000000000000010
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=DONE with file copying.
-end
-item: Remark
-  Text=The rest is registry and Start Menu fiddling.
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=A
-  Flags=00000010
-end
-item: If/While Statement
-  Variable=TASKS
-  Value=A
-  Flags=00000010
-end
-item: Remark
-  Text=Register file extensions.  As usual, Admin privs get in the way, but with a twist:
-end
-item: Remark
-  Text=You don't need admin privs to write to HKEY_CLASSES_ROOT *except* under Win2K.
-end
-item: Remark
-  Text=On Win2K, a user without Admin privs has to register extensions under HKCU\Software\CLASSES instead.
-end
-item: Remark
-  Text=But while you can *do* that under other flavors of Windows too, it has no useful effect except in Win2K.
-end
-item: Set Variable
-  Variable=USE_HKCR
-  Value=1
-end
-item: Check Configuration
-  Flags=11110010
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=0
-end
-item: Set Variable
-  Variable=USE_HKCR
-  Value=0
-end
-item: End Block
-end
-item: End Block
-end
-item: If/While Statement
-  Variable=USE_HKCR
-  Value=1
-end
-item: Remark
-  Text=File types.
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.File
-  New Value=Python File
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.File\shell\open\command
-  New Value=%MAINDIR%\python.exe "%%1" %%*
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.File\DefaultIcon
-  New Value=%MAINDIR%\Py.ico
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.NoConFile
-  New Value=Python File (no console)
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.NoConFile\shell\open\command
-  New Value=%MAINDIR%\pythonw.exe "%%1" %%*
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.NoConFile\DefaultIcon
-  New Value=%MAINDIR%\Py.ico
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.CompiledFile
-  New Value=Compiled Python File
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.CompiledFile\shell\open\command
-  New Value=%MAINDIR%\python.exe "%%1" %%*
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.CompiledFile\DefaultIcon
-  New Value=%MAINDIR%\pyc.ico
-end
-item: Remark
-end
-item: Remark
-  Text=File extensions.
-end
-item: Edit Registry
-  Total Keys=1
-  Key=.py
-  New Value=Python.File
-end
-item: Edit Registry
-  Total Keys=1
-  Key=.py
-  New Value=text/plain
-  Value Name=Content Type
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=.pyw
-  New Value=Python.NoConFile
-end
-item: Edit Registry
-  Total Keys=1
-  Key=.pyw
-  New Value=text/plain
-  Value Name=Content Type
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=.pyc
-  New Value=Python.CompiledFile
-end
-item: Edit Registry
-  Total Keys=1
-  Key=.pyo
-  New Value=Python.CompiledFile
-end
-item: Else Statement
-end
-item: Remark
-  Text=File types.
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.File
-  New Value=Python File
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.File\shell\open\command
-  New Value=%MAINDIR%\python.exe "%%1" %%*
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.File\DefaultIcon
-  New Value=%MAINDIR%\Py.ico
-  Root=1
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.NoConFile
-  New Value=Python File (no console)
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.NoConFile\shell\open\command
-  New Value=%MAINDIR%\pythonw.exe "%%1" %%*
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.NoConFile\DefaultIcon
-  New Value=%MAINDIR%\Py.ico
-  Root=1
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.CompiledFile
-  New Value=Compiled Python File
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.CompiledFile\shell\open\command
-  New Value=%MAINDIR%\python.exe "%%1" %%*
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.CompiledFile\DefaultIcon
-  New Value=%MAINDIR%\pyc.ico
-  Root=1
-end
-item: Remark
-end
-item: Remark
-  Text=File extensions.
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\.py
-  New Value=Python.File
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\.py
-  New Value=text/plain
-  Value Name=Content Type
-  Root=1
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\.pyw
-  New Value=Python.NoConFile
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\.pyw
-  New Value=text/plain
-  Value Name=Content Type
-  Root=1
-end
-item: Remark
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\.pyc
-  New Value=Python.CompiledFile
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\.pyo
-  New Value=Python.CompiledFile
-  Root=1
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=If we're installing IDLE, also set an Edit context menu action to use IDLE, for .py and .pyw files.
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=B
-  Flags=00000010
-end
-item: If/While Statement
-  Variable=USE_HKCR
-  Value=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.NoConFile\shell\Edit with IDLE\command
-  New Value=%MAINDIR%\pythonw.exe %MAINDIR%\Lib\idlelib\idle.pyw -n -e "%%1"
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Python.File\shell\Edit with IDLE\command
-  New Value=%MAINDIR%\pythonw.exe %MAINDIR%\Lib\idlelib\idle.pyw -n -e "%%1"
-end
-item: Else Statement
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.NoConFile\shell\Edit with IDLE\command
-  New Value=%MAINDIR%\pythonw.exe %MAINDIR%\Lib\idlelib\idle.pyw -n -e "%%1"
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\CLASSES\Python.File\shell\Edit with IDLE\command
-  New Value=%MAINDIR%\pythonw.exe %MAINDIR%\Lib\idlelib\idle.pyw -n -e "%%1"
-  Root=1
-end
-item: End Block
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=Register Python paths.
-end
-item: Remark
-  Text=Write to HKLM for admin, else HKCU.  Keep these blocks otherwise identical!
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\CurrentVersion
-  Root=130
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\InstallPath
-  New Value=%MAINDIR%
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\InstallPath\InstallGroup
-  New Value=%CGROUP_SAVE%
-  New Value=
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\PythonPath
-  New Value=%MAINDIR%\Lib;%MAINDIR%\DLLs;%MAINDIR%\Lib\lib-tk
-  New Value=
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\Modules
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
-  New Value=%MAINDIR%\Python.exe
-  Root=2
-end
-item: Else Statement
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\CurrentVersion
-  Root=129
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\InstallPath
-  New Value=%MAINDIR%
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\InstallPath\InstallGroup
-  New Value=%CGROUP_SAVE%
-  New Value=
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\PythonPath
-  New Value=%MAINDIR%\Lib;%MAINDIR%\DLLs;%MAINDIR%\Lib\lib-tk
-  New Value=
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\Modules
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
-  New Value=%MAINDIR%\Python.exe
-  Root=1
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=Registry fiddling for docs.
-end
-item: Remark
-  Text=Write to HKLM for admin, else HKCU.  Keep these blocks otherwise identical!
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=C
-  Flags=00000010
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\Help\Main Python Documentation
-  New Value=%MAINDIR%\Doc\index.html
-  Root=2
-end
-item: Else Statement
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Python\PythonCore\%PY_VERSION%\Help\Main Python Documentation
-  New Value=%MAINDIR%\Doc\index.html
-  Root=1
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=Set the app publisher and URL entries for Win2K add/remove.
-end
-item: Remark
-  Text=It doesn't hurt on other systems.
-end
-item: Remark
-  Text=As usual, write to HKLM or HKCU depending on Admin privs.
-end
-item: Remark
-  Text=CAUTION:  If you set this info on the "Windows 2000" page (step 6) of the
-end
-item: Remark
-  Text=Installation Expert, it only shows up in the "If" block below.  Keep in synch!
-end
-item: If/While Statement
-  Variable=DOADMIN
-  Value=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=http://www.python.org/
-  Value Name=HelpLink
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=PythonLabs at Zope Corporation
-  Value Name=Publisher
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=http://www.python.org/
-  Value Name=URLInfoAbout
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%PYVER_STRING%
-  Value Name=DisplayVersion
-  Root=2
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%MAINDIR%\py.ico,-0
-  Value Name=DisplayIcon
-  Root=2
-end
-item: Else Statement
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=http://www.python.org/
-  Value Name=HelpLink
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=PythonLabs at Zope Corporation
-  Value Name=Publisher
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=http://www.python.org/
-  Value Name=URLInfoAbout
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%PYVER_STRING%
-  Value Name=DisplayVersion
-  Root=1
-end
-item: Edit Registry
-  Total Keys=1
-  Key=Software\Microsoft\Windows\CurrentVersion\Uninstall\%APPTITLE%
-  New Value=%MAINDIR%\py.ico,-0
-  Value Name=DisplayIcon
-  Root=1
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=Populate Start Menu group
-end
-item: If/While Statement
-  Variable=TASKS
-  Value=B
-  Flags=00000010
-end
-item: Remark
-  Text=Shortcut to installer no matter what.
-end
-item: Create Shortcut
-  Source=%MAINDIR%\unwise.exe
-  Destination=%GROUP%\Uninstall Python.lnk
-  Working Directory=%MAINDIR%
-  Key Type=1536
-  Flags=00000001
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=A
-  Flags=00000010
-end
-item: Create Shortcut
-  Source=%MAINDIR%\python.exe
-  Destination=%GROUP%\Python (command line).lnk
-  Working Directory=%MAINDIR%
-  Icon Pathname=%MAINDIR%\pycon.ico
-  Key Type=1536
-  Flags=00000001
-end
-item: End Block
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=B
-  Flags=00000010
-end
-item: Create Shortcut
-  Source=%MAINDIR%\pythonw.exe
-  Destination=%GROUP%\IDLE (Python GUI).lnk
-  Command Options="%MAINDIR%\Lib\idlelib\idle.pyw"
-  Working Directory=%MAINDIR%
-  Key Type=1536
-  Flags=00000001
-end
-item: Create Shortcut
-  Source=%MAINDIR%\pythonw.exe
-  Destination=%GROUP%\Module Docs.lnk
-  Command Options="%MAINDIR%\Tools\Scripts\pydocgui.pyw"
-  Working Directory=%MAINDIR%
-  Key Type=1536
-  Flags=00000001
-end
-item: End Block
-end
-item: Remark
-end
-item: If/While Statement
-  Variable=COMPONENTS
-  Value=C
-  Flags=00000010
-end
-item: Create Shortcut
-  Source=%MAINDIR%\Doc\index.html
-  Destination=%GROUP%\Python Manuals.lnk
-  Working Directory=%MAINDIR%
-  Key Type=1536
-  Flags=00000001
-end
-item: End Block
-end
-item: End Block
-end
-item: Remark
-end
-item: Remark
-  Text=I don't think we need this, but have always done it.
-end
-item: Self-Register OCXs/DLLs
-  Description=Updating System Configuration, Please Wait...
-end
-item: Remark
-end
-remarked item: Remark
-  Text=Don't enable "Delete in-use files".  Here's what happens:
-end
-remarked item: Remark
-  Text=Install Python; uninstall Python; install Python again.  Reboot the machine.
-end
-remarked item: Remark
-  Text=Now UNWISE.EXE is missing.  I think this is a Wise bug, but so it goes.
-end
-remarked item: Add Text to INSTALL.LOG
-  Text=Delete in-use files: On
-end
-item: Remark
-end
-item: Wizard Block
-  Direction Variable=DIRECTION
-  Display Variable=DISPLAY
-  Bitmap Pathname=.\installer.bmp
-  X Position=9
-  Y Position=10
-  Filler Color=11173759
-  Flags=00000011
-end
-item: Custom Dialog Set
-  Name=Finished
-  Display Variable=DISPLAY
-  item: Dialog
-    Title=%APPTITLE% Installation
-    Title French=Installation de %APPTITLE%
-    Title German=Installation von %APPTITLE%
-    Title Spanish=Instalación de %APPTITLE%
-    Title Italian=Installazione di %APPTITLE%
-    Width=339
-    Height=280
-    Font Name=Helv
-    Font Size=8
-    item: Push Button
-      Rectangle=188 234 244 253
-      Variable=DIRECTION
-      Value=N
-      Create Flags=01010000000000010000000000000001
-      Text=&Finish
-      Text French=&Fin
-      Text German=&Weiter
-      Text Spanish=&Terminar
-      Text Italian=&Fine
-    end
-    item: Push Button
-      Rectangle=264 234 320 253
-      Variable=DISABLED
-      Value=!
-      Action=3
-      Create Flags=01010000000000010000000000000000
-      Text=&Cancel
-      Text French=&Annuler
-      Text German=&Abbrechen
-      Text Spanish=&Cancelar
-      Text Italian=&Annulla
-    end
-    item: Static
-      Rectangle=108 10 323 48
-      Create Flags=01010000000000000000000000000000
-      Flags=0000000000000001
-      Name=Times New Roman
-      Font Style=-24 0 0 0 700 255 0 0 0 3 2 1 18
-      Text=Installation Completed!
-      Text French=Installation terminée !
-      Text German=Die Installation ist abgeschlossen!
-      Text Spanish=¡Instalación terminada!
-      Text Italian=Installazione completata!
-    end
-    item: Static
-      Rectangle=108 44 320 82
-      Create Flags=01010000000000000000000000000000
-      Text=%APPTITLE% has been successfully installed.
-      Text=
-      Text=Press the Finish button to exit this installation.
-      Text French=%APPTITLE% est maintenant installé.
-      Text French=
-      Text French=Cliquez sur le bouton Fin pour quitter l'installation.
-      Text German=%APPTITLE% wurde erfolgreich installiert.
-      Text German=
-      Text German=Klicken Sie auf "Weiter", um die Installation zu beenden.
-      Text Spanish=%APPTITLE% se ha instalado con éxito.
-      Text Spanish=
-      Text Spanish=Presione el botón Terminar para salir de esta instalación.
-      Text Italian=L'installazione %APPTITLE% è stata portata a termine con successo.
-      Text Italian=
-      Text Italian=Premere il pulsante Fine per uscire dall'installazione.
-    end
-    item: Static
-      Rectangle=10 225 320 226
-      Action=3
-      Create Flags=01010000000000000000000000000111
-    end
-    item: Static
-      Rectangle=106 105 312 210
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000000000
-      Text=Special Windows thanks to:
-      Text=
-      Text=Wise Solutions, for the use of InstallMaster 8.1.
-      Text=    http://www.wisesolutions.com/
-      Text=
-      Text=
-      Text=LettError, Erik van Blokland, for the Python for Windows graphic.
-      Text=    http://www.letterror.com/
-      Text=
-      Text=
-      Text=Mark Hammond, without whose years of freely shared Windows expertise, Python for Windows would still be Python for DOS.
-    end
-    item: Static
-      Rectangle=106 95 312 96
-      Action=3
-      Enabled Color=00000000000000001111111111111111
-      Create Flags=01010000000000000000000000001001
-    end
-  end
-end
-item: End Block
-end
-item: New Event
-  Name=Cancel
-end
-item: Remark
-  Text=This include script supports a rollback to preinstallation state if the user chooses to cancel before the installation is complete.
-end
-item: Include Script
-  Pathname=%_WISE_%\INCLUDE\rollback.wse
-end

Deleted: /python/branches/p3yk-noslice/PCbuild8/pythoncore.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/pythoncore.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,1946 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="pythoncore"
-	ProjectGUID="{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}"
-	RootNamespace="pythoncore"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				WholeProgramOptimization="false"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;USE_DL_EXPORT;_CRT_SECURE_NO_DEPRECATE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\python26.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				LinkTimeCodeGeneration="0"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				WholeProgramOptimization="false"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;USE_DL_EXPORT;_CRT_SECURE_NO_DEPRECATE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				BufferSecurityCheck="false"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				Detect64BitPortabilityProblems="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\python26.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				LinkTimeCodeGeneration="0"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="_DEBUG;USE_DL_EXPORT;WIN32;_WINDOWS;_CRT_SECURE_NO_DEPRECATE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="_DEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				Description="generate buildinfo"
-				CommandLine="make_buildinfo.exe $(ConfigurationName)"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\python26_d.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="_DEBUG;USE_DL_EXPORT;WIN32;_WINDOWS;_CRT_SECURE_NO_DEPRECATE"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="_DEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\python26_d.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="PGIRelease|Win32"
-			OutputDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-				Description="Get getbuildinfo2.c"
-				CommandLine="make_buildinfo.exe"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				WholeProgramOptimization="true"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;USE_DL_EXPORT;_CRT_SECURE_NO_DEPRECATE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)/python26.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				LinkTimeCodeGeneration="2"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-				CommandLine=""
-			/>
-		</Configuration>
-		<Configuration
-			Name="PGIRelease|x64"
-			OutputDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-				Description="Get getbuildinfo2.c"
-				CommandLine="make_buildinfo.exe"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				WholeProgramOptimization="true"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;USE_DL_EXPORT;_CRT_SECURE_NO_DEPRECATE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine=""
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)/python26.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				LinkTimeCodeGeneration="2"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-				CommandLine=""
-			/>
-		</Configuration>
-		<Configuration
-			Name="PGORelease|Win32"
-			OutputDirectory="$(PlatformName)\$(ConfigurationName)"
-			IntermediateDirectory="$(PlatformName)\PGIRelease\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			BuildLogFile="$(OutDir)\BuildLog.htm"
-			ExcludeBuckets="7"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				WholeProgramOptimization="true"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;USE_DL_EXPORT;_CRT_SECURE_NO_DEPRECATE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine="copy $(PlatformName)\python.exe $(IntDir)&#x0D;&#x0A;$(IntDir)\python.exe ../Tools/pybench/pybench.py -n 1&#x0D;&#x0A;"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\python26.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				LinkTimeCodeGeneration="3"
-				ProfileGuidedDatabase="$(IntDir)\$(TargetName).pgd"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="PGORelease|x64"
-			OutputDirectory="$(PlatformName)\$(ConfigurationName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythoncore"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			BuildLogFile="$(OutDir)\BuildLog.htm"
-			ExcludeBuckets="7"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				AdditionalOptions="/Zm200 "
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				WholeProgramOptimization="true"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS;USE_DL_EXPORT;_CRT_SECURE_NO_DEPRECATE"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-				AdditionalIncludeDirectories="..\Include"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-				CommandLine="copy $(PlatformName)\python.exe $(IntDir)&#x0D;&#x0A;$(IntDir)\python.exe ../Tools/pybench/pybench.py -n 1&#x0D;&#x0A;"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\python26.dll"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				LinkTimeCodeGeneration="3"
-				ProfileGuidedDatabase="$(IntDir)\$(TargetName).pgd"
-				BaseAddress="0x1e000000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<Filter
-			Name="zlib"
-			>
-			<File
-				RelativePath="..\Modules\zlib\adler32.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\compress.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\crc32.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\deflate.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\gzio.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\infback.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\inffast.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\inflate.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\inftrees.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\trees.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\uncompr.c"
-				>
-			</File>
-			<File
-				RelativePath="..\Modules\zlibmodule.c"
-				>
-				<FileConfiguration
-					Name="Release|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Release|x64"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="Debug|x64"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="PGIRelease|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="PGIRelease|x64"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="PGORelease|Win32"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-				<FileConfiguration
-					Name="PGORelease|x64"
-					>
-					<Tool
-						Name="VCCLCompilerTool"
-						AdditionalIncludeDirectories="..\Modules\zlib"
-					/>
-				</FileConfiguration>
-			</File>
-			<File
-				RelativePath="..\Modules\zlib\zutil.c"
-				>
-			</File>
-		</Filter>
-		<Filter
-			Name="include files"
-			>
-			<File
-				RelativePath="..\Include\abstract.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\asdl.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\ast.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\bitset.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\boolobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\bufferobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\cellobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\ceval.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\classobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\cobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\code.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\codecs.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\compile.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\complexobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\cStringIO.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\datetime.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\descrobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\dictobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\enumobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\errcode.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\eval.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\fileobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\floatobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\frameobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\funcobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\genobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\graminit.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\grammar.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\import.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\intobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\intrcheck.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\iterobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\listobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\longintrepr.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\longobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\marshal.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\metagrammar.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\methodobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\modsupport.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\moduleobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\node.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\object.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\objimpl.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\opcode.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\osdefs.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\parsetok.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\patchlevel.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pgen.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pgenheaders.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\py_curses.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pyarena.h"
-				>
-			</File>
-			<File
-				RelativePath="..\PC\pyconfig.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pydebug.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pyerrors.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pyexpat.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pyfpe.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pygetopt.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pymactoolbox.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pymem.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pyport.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pystate.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pystrtod.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\Python-ast.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\Python.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pythonrun.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\pythread.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\rangeobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\setobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\sliceobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\stringobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\structmember.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\structseq.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\symtable.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\sysmodule.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\timefuncs.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\token.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\traceback.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\tupleobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\ucnhash.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\unicodeobject.h"
-				>
-			</File>
-			<File
-				RelativePath="..\Include\weakrefobject.h"
-				>
-			</File>
-		</Filter>
-		<File
-			RelativePath="..\Modules\_bisectmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\_codecs_cn.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\_codecs_hk.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\_codecs_iso2022.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\_codecs_jp.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\_codecs_kr.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\_codecs_tw.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_codecsmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_csv.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_functoolsmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_heapqmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_hotshot.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_localemodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_lsprof.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_randommodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_sre.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_struct.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Pc\_subprocess.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_typesmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\_weakref.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Pc\_winreg.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\abstract.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\acceler.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\arraymodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\asdl.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\ast.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\audioop.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\binascii.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\bitset.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\bltinmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\boolobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\bufferobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\cellobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\ceval.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\classobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cmathmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\cobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\codecs.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\codeobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\collectionsmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\compile.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\complexobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\config.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cPickle.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cStringIO.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\datetimemodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\descrobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\dictobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\dl_nt.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\dynload_win.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\enumobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\errnomodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\errors.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\exceptions.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\fileobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\firstsets.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\floatobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\frameobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\frozen.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\funcobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\future.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\gcmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\genobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\getargs.c"
-			>
-		</File>
-		<File
-			RelativePath=".\getbuildinfo2.c"
-			>
-			<FileConfiguration
-				Name="Release|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="Release|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="Debug|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="Debug|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGIRelease|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGIRelease|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGORelease|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGORelease|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					ForcedIncludeFiles="getbuildinfo2.h"
-				/>
-			</FileConfiguration>
-		</File>
-		<File
-			RelativePath="..\Python\getcompiler.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\getcopyright.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\getmtime.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\getopt.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\getpathp.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\getplatform.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\getversion.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\graminit.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\grammar.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\grammar1.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\imageop.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\import.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\import_nt.c"
-			>
-			<FileConfiguration
-				Name="Release|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="Release|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="Debug|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="Debug|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGIRelease|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGIRelease|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGORelease|Win32"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-			<FileConfiguration
-				Name="PGORelease|x64"
-				>
-				<Tool
-					Name="VCCLCompilerTool"
-					AdditionalIncludeDirectories="..\Python"
-				/>
-			</FileConfiguration>
-		</File>
-		<File
-			RelativePath="..\Python\importdl.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\intobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\iterobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\itertoolsmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\listnode.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\listobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\longobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\main.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\marshal.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\mathmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\md5.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\md5module.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\metagrammar.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\methodobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\mmapmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\modsupport.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\moduleobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\msvcrtmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\cjkcodecs\multibytecodec.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\myreadline.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\mysnprintf.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\mystrtoul.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\node.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\object.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\obmalloc.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\operator.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\parser.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\parsermodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\parsetok.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\peephole.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\posixmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\pyarena.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\pyfpe.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\pystate.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\pystrtod.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\Python-ast.c"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\python_nt.rc"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\pythonrun.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\rangeobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\rgbimgmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\rotatingtree.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\setobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\sha256module.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\sha512module.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\sha512module.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\shamodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\signalmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\signalmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\sliceobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\stringobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\stropmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\structmember.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\structseq.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\symtable.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\symtablemodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\sysmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\thread.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\threadmodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\timemodule.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Parser\tokenizer.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Python\traceback.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\tupleobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\typeobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\unicodectype.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\unicodeobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Objects\weakrefobject.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\xxsubtype.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\yuvconvert.c"
-			>
-		</File>
-		<File
-			RelativePath="..\Modules\zipimport.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/pythonw.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/pythonw.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,383 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="pythonw"
-	ProjectGUID="{F4229CC3-873C-49AE-9729-DD308ED4CD4A}"
-	RootNamespace="pythonw"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythonw"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="_DEBUG"
-				Culture="1033"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\pythonw_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythonw"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="_DEBUG"
-				Culture="1033"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\pythonw_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythonw"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\pythonw.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\pythonw"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-				PreprocessorDefinitions="NDEBUG"
-				Culture="1033"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\pythonw.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				StackReserveSize="2000000"
-				BaseAddress="0x1d000000"
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\PC\python_exe.rc"
-			>
-		</File>
-		<File
-			RelativePath="..\PC\WinMain.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Modified: python/branches/p3yk-noslice/PCbuild8/readme.txt
==============================================================================
--- python/branches/p3yk-noslice/PCbuild8/readme.txt	(original)
+++ python/branches/p3yk-noslice/PCbuild8/readme.txt	Wed Jul 11 15:40:56 2007
@@ -2,44 +2,66 @@
 -------------------------------------
 This directory is used to build Python for Win32 platforms, e.g. Windows
 95, 98 and NT.  It requires Microsoft Visual C++ 8.0
-(a.k.a. Visual Studio 2005).
+(a.k.a. Visual Studio 2005).  There are two Platforms defined, Win32
+and x64.
 (For other Windows platforms and compilers, see ../PC/readme.txt.)
 
 All you need to do is open the workspace "pcbuild.sln" in MSVC++, select
 the Debug or Release setting (using "Solution Configuration" from
-the "Standard" toolbar"), and build the projects.
+the "Standard" toolbar"), and build the solution.
 
-The proper order to build subprojects:
+A .bat file, build.bat, is provided to simplify command line builds.
 
-1) pythoncore (this builds the main Python DLL and library files,
-               python26.{dll, lib} in Release mode)
-              NOTE:  in previous releases, this subproject was
-              named after the release number, e.g. python20.
-
-2) python (this builds the main Python executable,
-           python.exe in Release mode)
-
-3) the other subprojects, as desired or needed (note:  you probably don't
-   want to build most of the other subprojects, unless you're building an
-   entire Python distribution from scratch, or specifically making changes
-   to the subsystems they implement, or are running a Python core buildbot
-   test slave; see SUBPROJECTS below)
+Some of the subprojects rely on external libraries and won't build
+unless you have them installed.
 
-Binary files go into PCBuild8\Win32 or \x64 directories and don't
-interfere with each other.
+Binary files go into PCBuild8\$(PlatformName)($ConfigurationName),
+which will be something like Win32Debug, Win32Release, x64Release, etc.
 
 When using the Debug setting, the output files have a _d added to
 their name:  python26_d.dll, python_d.exe, parser_d.pyd, and so on.
 
-There are two special configurations for the pythoncore project and
-the solution.  These are PGIRelease and PGORelease.  They are for
-createing profile-guided optimized versions of python.dll.
-The former creates the instrumented binaries, and the latter
-runs python.exe with the instrumented python.dll on the performance
-testsuite, and creates a new, optimized, python.dll in
-PCBuild8\Win32\PGORelease, or in the x64 folder.  Note that although
-we can cross-compile x64 binaries on a 32 bit machine, we cannot
-create the PGO binaries, since they require actually running the code.
+PROFILER GUIDED OPTIMIZATION
+----------------------------
+There are two special solution configurations for Profiler Guided
+Optimization.  Careful use of this has been shown to yield more than
+10% extra speed.
+1) Build the PGInstrument solution configuration.  This will yield
+binaries in the win32PGO or x64PGO folders.  (You may want do start
+by erasing any .pgc files there, present from earlier runs.)
+2) Instrument the binaries.  Do this by for example running the test
+suite:  win32PGO\python.exe ..\lib\test\regrtest.py.  This will excercise
+python thoroughly.
+3) Build the PGUpdate solution configuration (You may need to ask it
+to rebuild.)  This will incorporate the information gathered in step 2
+and produce new binaries in the same win32PGO or x64pPGO folders.
+4) (optional) You can continue to build the PGUpdate configuration as
+you work on python.  It will continue to use the data from step 2, even
+if you add or modify files as part of your work.  Thus, it makes sense to 
+run steps 1 and 2 maybe once a week, and then use step 3) for all regular
+work.
+
+A .bat file, build_pgo.bat is included to automate this process
+
+You can convince yourself of the benefits of the PGO by comparing the
+results of the python testsuite with the regular Release build.
+
+
+C RUNTIME
+---------
+Visual Studio 2005 uses version 8 of the C runtime.  The executables are
+linked to a CRT "side by side" assembly which must be present on the target
+machine.  This is avalible under the VC/Redist folder of your visual studio
+distribution.  Note that ServicePack1 of Visual Studio 2005 has a different
+version than the original.  On XP and later operating systems that support
+side-by-side assemblies it is not enough to have the msvcrt80.dll present,
+it has to be there as a whole assembly, that is, a folder with the .dll
+and a .manifest.  Also, a check is made for the correct version.
+Therefore, one should distribute this assembly with the dlls, and keep
+it in the same directory.  For compatibility with older systems, one should
+also set the PATH to this directory so that the dll can be found.
+For more info, see the Readme in the VC/Redist folder.
+
 
 SUBPROJECTS
 -----------
@@ -267,164 +289,22 @@
     build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do
     this by hand.
 
-Building for Itanium
---------------------
-
-The project files support a ReleaseItanium configuration which creates
-Win64/Itanium binaries. For this to work, you need to install the Platform
-SDK, in particular the 64-bit support. This includes an Itanium compiler
-(future releases of the SDK likely include an AMD64 compiler as well).
-In addition, you need the Visual Studio plugin for external C compilers,
-from http://sf.net/projects/vsextcomp. The plugin will wrap cl.exe, to
-locate the proper target compiler, and convert compiler options
-accordingly. The project files require atleast version 0.8.
 
 Building for AMD64
 ------------------
 
-The build process for the ReleaseAMD64 configuration is very similar
-to the Itanium configuration; make sure you use the latest version of
-vsextcomp.
-
-Building Python Using the free MS Toolkit Compiler
---------------------------------------------------
-
-The build process for Visual C++ can be used almost unchanged with the free MS
-Toolkit Compiler. This provides a way of building Python using freely
-available software.
-
-Requirements
-
-    To build Python, the following tools are required:
-
-    * The Visual C++ Toolkit Compiler
-        from http://msdn.microsoft.com/visualc/vctoolkit2003/
-    * A recent Platform SDK
-        from http://www.microsoft.com/downloads/details.aspx?FamilyID=484269e2-3b89-47e3-8eb7-1f2be6d7123a
-    * The .NET 1.1 SDK
-        from http://www.microsoft.com/downloads/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d
-
-    [Does anyone have better URLs for the last 2 of these?]
-
-    The toolkit compiler is needed as it is an optimising compiler (the
-    compiler supplied with the .NET SDK is a non-optimising version). The
-    platform SDK is needed to provide the Windows header files and libraries
-    (the Windows 2003 Server SP1 edition, typical install, is known to work -
-    other configurations or versions are probably fine as well). The .NET 1.1
-    SDK is needed because it contains a version of msvcrt.dll which links to
-    the msvcr71.dll CRT. Note that the .NET 2.0 SDK is NOT acceptable, as it
-    references msvcr80.dll.
-
-    All of the above items should be installed as normal.
-
-    If you intend to build the openssl (needed for the _ssl extension) you
-    will need the C runtime sources installed as part of the platform SDK.
-
-    In addition, you will need Nant, available from
-    http://nant.sourceforge.net. The 0.85 release candidate 3 version is known
-    to work. This is the latest released version at the time of writing. Later
-    "nightly build" versions are known NOT to work - it is not clear at
-    present whether future released versions will work.
-
-Setting up the environment
-
-    Start a platform SDK "build environment window" from the start menu. The
-    "Windows XP 32-bit retail" version is known to work.
-
-    Add the following directories to your PATH:
-        * The toolkit compiler directory
-        * The SDK "Win64" binaries directory
-	* The Nant directory
-    Add to your INCLUDE environment variable:
-        * The toolkit compiler INCLUDE directory
-    Add to your LIB environment variable:
-        * The toolkit compiler LIB directory
-	* The .NET SDK Visual Studio 2003 VC7\lib directory
-
-    The following commands should set things up as you need them:
-
-        rem Set these values according to where you installed the software
-        set TOOLKIT=C:\Program Files\Microsoft Visual C++ Toolkit 2003
-        set SDK=C:\Program Files\Microsoft Platform SDK
-        set NET=C:\Program Files\Microsoft Visual Studio .NET 2003
-        set NANT=C:\Utils\Nant
-
-        set PATH=%TOOLKIT%\bin;%PATH%;%SDK%\Bin\win64;%NANT%\bin
-        set INCLUDE=%TOOLKIT%\include;%INCLUDE%
-        set LIB=%TOOLKIT%\lib;%NET%\VC7\lib;%LIB%
-
-    The "win64" directory from the SDK is added to supply executables such as
-    "cvtres" and "lib", which are not available elsewhere. The versions in the
-    "win64" directory are 32-bit programs, so they are fine to use here.
-
-    That's it. To build Python (the core only, no binary extensions which
-    depend on external libraries) you just need to issue the command
-
-        nant -buildfile:python.build all
-
-    from within the PCBuild directory.
-
-Extension modules
-
-    To build those extension modules which require external libraries
-    (_tkinter, bz2, _bsddb, _sqlite3, _ssl) you can follow the instructions
-    for the Visual Studio build above, with a few minor modifications. These
-    instructions have only been tested using the sources in the Python
-    subversion repository - building from original sources should work, but
-    has not been tested.
-
-    For each extension module you wish to build, you should remove the
-    associated include line from the excludeprojects section of pc.build.
-
-    The changes required are:
-
-    _tkinter
-        The tix makefile (tix-8.4.0\win\makefile.vc) must be modified to
-	remove references to TOOLS32. The relevant lines should be changed to
-	read:
-            cc32 = cl.exe
-            link32 = link.exe
-            include32 = 
-	The remainder of the build instructions will work as given.
-
-    bz2
-        No changes are needed
-
-    _bsddb
-        The file db.build should be copied from the Python PCBuild directory
-	to the directory db-4.4.20\build_win32.
-
-	The file db_static.vcproj in db-4.4.20\build_win32 should be edited to
-	remove the string "$(SolutionDir)" - this occurs in 2 places, only
-	relevant for 64-bit builds. (The edit is required as otherwise, nant
-	wants to read the solution file, which is not in a suitable form).
-
-	The bsddb library can then be build with the command
-	    nant -buildfile:db.build all
-	run from the db-4.4.20\build_win32 directory.
-
-    _sqlite3
-        No changes are needed. However, in order for the tests to succeed, a
-	copy of sqlite3.dll must be downloaded, and placed alongside
-	python.exe.
-
-    _ssl
-        The documented build process works as written. However, it needs a
-	copy of the file setargv.obj, which is not supplied in the platform
-	SDK. However, the sources are available (in the crt source code). To
-	build setargv.obj, proceed as follows:
-
-        Copy setargv.c, cruntime.h and internal.h from %SDK%\src\crt to a
-	temporary directory.
-	Compile using "cl /c /I. /MD /D_CRTBLD setargv.c"
-	Copy the resulting setargv.obj to somewhere on your LIB environment
-	(%SDK%\lib is a reasonable place).
+Select x64 as the destination platform.
 
-	With setargv.obj in place, the standard build process should work
-	fine.
 
 YOUR OWN EXTENSION DLLs
 -----------------------
 If you want to create your own extension module DLL, there's an example
 with easy-to-follow instructions in ../PC/example/; read the file
 readme.txt there first.
+Also, you can simply use Visual Studio to "Add new project to solution".
+Elect to create a win32 project, .dll, empty project.
+This will create a subdirectory with a .vcproj file in it.  Now, You can
+simply copy most of another .vcproj, like _test_capi/_test_capi.vcproj over
+(you can't just copy and rename it, since the target will have a unique GUID.)
+At some point we want to be able to provide a template for creating a
+project.

Modified: python/branches/p3yk-noslice/PCbuild8/rmpyc.py
==============================================================================
--- python/branches/p3yk-noslice/PCbuild8/rmpyc.py	(original)
+++ python/branches/p3yk-noslice/PCbuild8/rmpyc.py	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,5 @@
 # Remove all the .pyc and .pyo files under ../Lib.
+import sys
 
 
 def deltree(root):
@@ -21,5 +22,9 @@
 
     return npyc, npyo
 
-npyc, npyo = deltree("../Lib")
+path = "../Lib"
+if len(sys.argv) > 1:
+    path = sys.argv[1]
+
+npyc, npyo = deltree(path)
 print npyc, ".pyc deleted,", npyo, ".pyo deleted"

Modified: python/branches/p3yk-noslice/PCbuild8/rt.bat
==============================================================================
--- python/branches/p3yk-noslice/PCbuild8/rt.bat	(original)
+++ python/branches/p3yk-noslice/PCbuild8/rt.bat	Wed Jul 11 15:40:56 2007
@@ -2,6 +2,8 @@
 rem Run Tests.  Run the regression test suite.
 rem Usage:  rt [-d] [-O] [-q] regrtest_args
 rem -d   Run Debug build (python_d.exe).  Else release build.
+rem -pgo Run PGO build, e.g. for instrumentation
+rem -x64 Run the x64 version, otherwise win32
 rem -O   Run python.exe or python_d.exe (see -d) with -O.
 rem -q   "quick" -- normally the tests are run twice, the first time
 rem      after deleting all the .py[co] files reachable from Lib/.
@@ -24,16 +26,21 @@
 
 setlocal
 
-set exe=python
+set platf=win32
+set exe=python.exe
 set qmode=
 set dashO=
+set conf=Release
 PATH %PATH%;..\..\tcltk\bin
 
 :CheckOpts
 if "%1"=="-O" (set dashO=-O)     & shift & goto CheckOpts
 if "%1"=="-q" (set qmode=yes)    & shift & goto CheckOpts
-if "%1"=="-d" (set exe=python_d) & shift & goto CheckOpts
+if "%1"=="-d" (set exe=python_d.exe) & (set conf=Debug) & shift & goto CheckOpts
+if "%1"=="-x64" (set platf=x64) & shift & goto CheckOpts
+if "%1"=="-pgo" (set conf=PGO) & shift & goto CheckOpts
 
+set exe=%platf%%conf%\%exe%
 set cmd=%exe% %dashO% -E -tt ../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9
 if defined qmode goto Qmode
 

Deleted: /python/branches/p3yk-noslice/PCbuild8/select.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/select.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,379 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="select"
-	ProjectGUID="{97239A56-DBC0-41D2-BC14-C87D9B97D63B}"
-	RootNamespace="select"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\select"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="wsock32.lib"
-				OutputFile="$(OutDir)\select.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D110000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\select"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="NDEBUG;WIN32;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="wsock32.lib"
-				OutputFile="$(OutDir)\select.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames="libc"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D110000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\select"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="wsock32.lib"
-				OutputFile="$(OutDir)\select_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames="libc,msvcrt"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D110000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\select"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="wsock32.lib"
-				OutputFile="$(OutDir)\select_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				IgnoreDefaultLibraryNames="libc,msvcrt"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				SubSystem="2"
-				BaseAddress="0x1D110000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\selectmodule.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/unicodedata.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/unicodedata.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,371 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="unicodedata"
-	ProjectGUID="{FA5FC7EB-C72F-415F-AE42-91DD605ABDDA}"
-	RootNamespace="unicodedata"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\unicodedata"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\unicodedata.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D120000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\unicodedata"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\unicodedata.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D120000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\unicodedata"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\unicodedata_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D120000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\unicodedata"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;MMAP_EXPORTS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\unicodedata_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D120000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\Modules\unicodedata.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/w9xpopen.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/w9xpopen.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,353 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="w9xpopen"
-	ProjectGUID="{E9E0A1F6-0009-4E8C-B8F8-1B8F5D49A058}"
-	RootNamespace="w9xpopen"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\w9xpopen"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\w9xpopen_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\w9xpopen"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\w9xpopen_d.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\w9xpopen"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\w9xpopen.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\w9xpopen"
-			ConfigurationType="1"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				OutputFile="$(OutDir)\w9xpopen.exe"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\PC\w9xpopen.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Deleted: /python/branches/p3yk-noslice/PCbuild8/winsound.vcproj
==============================================================================
--- /python/branches/p3yk-noslice/PCbuild8/winsound.vcproj	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,375 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="8,00"
-	Name="winsound"
-	ProjectGUID="{51F35FAE-FB92-4B2C-9187-1542C065AD77}"
-	RootNamespace="winsound"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-		<Platform
-			Name="x64"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\winsound"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WINSOUND_EXPORTS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="winmm.lib"
-				OutputFile="$(OutDir)\winsound_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Debug|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\winsound"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;WINSOUND_EXPORTS"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				DebugInformationFormat="3"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="winmm.lib"
-				OutputFile="$(OutDir)\winsound_d.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\winsound"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;WINSOUND_EXPORTS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="winmm.lib"
-				OutputFile="$(OutDir)\winsound.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|x64"
-			OutputDirectory="$(PlatformName)"
-			IntermediateDirectory="$(PlatformName)\$(ConfigurationName)\winsound"
-			ConfigurationType="2"
-			InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
-			UseOfMFC="0"
-			ATLMinimizesCRunTimeLibraryUsage="false"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-				TargetEnvironment="3"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				InlineFunctionExpansion="1"
-				AdditionalIncludeDirectories="..\Include,..\PC"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;WINSOUND_EXPORTS"
-				StringPooling="true"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				SuppressStartupBanner="true"
-				CompileAs="0"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="winmm.lib"
-				OutputFile="$(OutDir)\winsound.pyd"
-				LinkIncremental="1"
-				SuppressStartupBanner="true"
-				AdditionalLibraryDirectories="$(OutDir)"
-				GenerateDebugInformation="true"
-				ProgramDatabaseFile=""
-				BaseAddress="0x1D160000"
-				ImportLibrary=""
-				TargetMachine="17"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<File
-			RelativePath="..\PC\winsound.c"
-			>
-		</File>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>

Modified: python/branches/p3yk-noslice/Parser/Python.asdl
==============================================================================
--- python/branches/p3yk-noslice/Parser/Python.asdl	(original)
+++ python/branches/p3yk-noslice/Parser/Python.asdl	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
--- ASDL's five builtin types are identifier, int, string, object, bool
+-- ASDL's five builtin types are identifier, int, string, object
 
 module Python version "$Revision$"
 {
@@ -10,8 +10,14 @@
 	    | Suite(stmt* body)
 
 	stmt = FunctionDef(identifier name, arguments args, 
-                           stmt* body, expr* decorators, expr? returns)
-	      | ClassDef(identifier name, expr* bases, stmt* body)
+                           stmt* body, expr* decorator_list, expr? returns)
+	      | ClassDef(identifier name, 
+			 expr* bases,
+			 keyword* keywords,
+			 expr? starargs,
+			 expr? kwargs,
+			 stmt* body,
+			 expr *decorator_list)
 	      | Return(expr? value)
 
 	      | Delete(expr* targets)
@@ -34,6 +40,7 @@
 	      | ImportFrom(identifier module, alias* names, int? level)
 
 	      | Global(identifier* names)
+	      | Nonlocal(identifier* names)
 	      | Expr(expr value)
 	      | Pass | Break | Continue
 
@@ -50,6 +57,8 @@
 	     | Dict(expr* keys, expr* values)
 	     | Set(expr* elts)
 	     | ListComp(expr elt, comprehension* generators)
+	     | SetComp(expr elt, comprehension* generators)
+	     | DictComp(expr key, expr value, comprehension* generators)
 	     | GeneratorExp(expr elt, comprehension* generators)
 	     -- the grammar constrains where yield expressions can occur
 	     | Yield(expr? value)
@@ -60,12 +69,14 @@
 			 expr? starargs, expr? kwargs)
 	     | Num(object n) -- a number as a PyObject.
 	     | Str(string s) -- need to specify raw, unicode, etc?
+	     | Bytes(string s)
 	     | Ellipsis
 	     -- other literals? bools?
 
 	     -- the following expression can appear in assignment context
 	     | Attribute(expr value, identifier attr, expr_context ctx)
 	     | Subscript(expr value, slice slice, expr_context ctx)
+	     | Starred(expr value, expr_context ctx)
 	     | Name(identifier id, expr_context ctx)
 	     | List(expr* elts, expr_context ctx) 
 	     | Tuple(expr* elts, expr_context ctx)
@@ -101,8 +112,7 @@
                      arg* kwonlyargs, identifier? kwarg,
                      expr? kwargannotation, expr* defaults,
                      expr* kw_defaults)
-	arg = SimpleArg(identifier arg, expr? annotation)
-            | NestedArgs(arg* args)
+	arg = (identifier arg, expr? annotation)
 
         -- keyword arguments supplied to call
         keyword = (identifier arg, expr value)
@@ -110,3 +120,4 @@
         -- import name with optional 'as' alias.
         alias = (identifier name, identifier? asname)
 }
+

Modified: python/branches/p3yk-noslice/Parser/asdl.py
==============================================================================
--- python/branches/p3yk-noslice/Parser/asdl.py	(original)
+++ python/branches/p3yk-noslice/Parser/asdl.py	Wed Jul 11 15:40:56 2007
@@ -13,10 +13,15 @@
 #__metaclass__ = type
 
 import os
+import sys
 import traceback
 
 import spark
 
+def output(string):
+    sys.stdout.write(string + "\n")
+
+
 class Token:
     # spark seems to dispatch in the parser based on a token's
     # type attribute
@@ -45,7 +50,7 @@
         self.value = value
         self.lineno = lineno
 
-class ASDLSyntaxError:
+class ASDLSyntaxError(Exception):
 
     def __init__(self, lineno, token=None, msg=None):
         self.lineno = lineno
@@ -110,49 +115,54 @@
     def error(self, tok):
         raise ASDLSyntaxError(tok.lineno, tok)
 
-    def p_module_0(self, (module, name, version, _0, _1)):
+    def p_module_0(self, info):
         " module ::= Id Id version { } "
+        module, name, version, _0, _1 = info
         if module.value != "module":
             raise ASDLSyntaxError(module.lineno,
                                   msg="expected 'module', found %s" % module)
         return Module(name, None, version)
 
-    def p_module(self, (module, name, version, _0, definitions, _1)):
+    def p_module(self, info):
         " module ::= Id Id version { definitions } "
+        module, name, version, _0, definitions, _1 = info
         if module.value != "module":
             raise ASDLSyntaxError(module.lineno,
                                   msg="expected 'module', found %s" % module)
         return Module(name, definitions, version)
 
-    def p_version(self, (version, V)):
+    def p_version(self, info):
         "version ::= Id String"
+        version, V = info
         if version.value != "version":
             raise ASDLSyntaxError(version.lineno,
-                                msg="expected 'version', found %" % version)
+                                  msg="expected 'version', found %" % version)
         return V
 
-    def p_definition_0(self, (definition,)):
+    def p_definition_0(self, definition):
         " definitions ::= definition "
-        return definition
+        return definition[0]
 
-    def p_definition_1(self, (definitions, definition)):
+    def p_definition_1(self, definitions):
         " definitions ::= definition definitions "
-        return definitions + definition
+        return definitions[0] + definitions[1]
 
-    def p_definition(self, (id, _, type)):
+    def p_definition(self, info):
         " definition ::= Id = type "
+        id, _, type = info
         return [Type(id, type)]
 
-    def p_type_0(self, (product,)):
+    def p_type_0(self, product):
         " type ::= product "
-        return product
+        return product[0]
 
-    def p_type_1(self, (sum,)):
+    def p_type_1(self, sum):
         " type ::= sum "
-        return Sum(sum)
+        return Sum(sum[0])
 
-    def p_type_2(self, (sum, id, _0, attributes, _1)):
+    def p_type_2(self, info):
         " type ::= sum Id ( fields ) "
+        sum, id, _0, attributes, _1 = info
         if id.value != "attributes":
             raise ASDLSyntaxError(id.lineno,
                                   msg="expected attributes, found %s" % id)
@@ -160,65 +170,73 @@
             attributes.reverse()
         return Sum(sum, attributes)
 
-    def p_product(self, (_0, fields, _1)):
+    def p_product(self, info):
         " product ::= ( fields ) "
+        _0, fields, _1 = info
         # XXX can't I just construct things in the right order?
         fields.reverse()
         return Product(fields)
 
-    def p_sum_0(self, (constructor,)):
+    def p_sum_0(self, constructor):
         " sum ::= constructor """
-        return [constructor]
+        return [constructor[0]]
 
-    def p_sum_1(self, (constructor, _, sum)):
+    def p_sum_1(self, ):
         " sum ::= constructor | sum "
+        constructor, _, sum = info
         return [constructor] + sum
 
-    def p_sum_2(self, (constructor, _, sum)):
+    def p_sum_2(self, info):
         " sum ::= constructor | sum "
+        constructor, _, sum = info
         return [constructor] + sum
 
-    def p_constructor_0(self, (id,)):
+    def p_constructor_0(self, id):
         " constructor ::= Id "
-        return Constructor(id)
+        return Constructor(id[0])
 
-    def p_constructor_1(self, (id, _0, fields, _1)):
+    def p_constructor_1(self, info):
         " constructor ::= Id ( fields ) "
+        id, _0, fields, _1 = info
         # XXX can't I just construct things in the right order?
         fields.reverse()
         return Constructor(id, fields)
 
-    def p_fields_0(self, (field,)):
+    def p_fields_0(self, field):
         " fields ::= field "
-        return [field]
+        return [field[0]]
 
-    def p_fields_1(self, (field, _, fields)):
+    def p_fields_1(self, info):
         " fields ::= field , fields "
+        field, _, fields = info
         return fields + [field]
 
-    def p_field_0(self, (type,)):
+    def p_field_0(self, type_):
         " field ::= Id "
-        return Field(type)
+        return Field(type_[0])
 
-    def p_field_1(self, (type, name)):
+    def p_field_1(self, info):
         " field ::= Id Id "
+        type, name = info
         return Field(type, name)
 
-    def p_field_2(self, (type, _, name)):
+    def p_field_2(self, info):
         " field ::= Id * Id "
+        type, _, name = info
         return Field(type, name, seq=1)
 
-    def p_field_3(self, (type, _, name)):
+    def p_field_3(self, info):
         " field ::= Id ? Id "
+        type, _, name = info
         return Field(type, name, opt=1)
 
-    def p_field_4(self, (type, _)):
+    def p_field_4(self, type_):
         " field ::= Id * "
-        return Field(type, seq=1)
+        return Field(type_[0], seq=1)
 
-    def p_field_5(self, (type, _)):
+    def p_field_5(self, type_):
         " field ::= Id ? "
-        return Field(type, opt=1)
+        return Field(type[0], opt=1)
 
 builtin_types = ("identifier", "string", "int", "bool", "object")
 
@@ -306,9 +324,9 @@
             return
         try:
             meth(object, *args)
-        except Exception, err:
-            print "Error visiting", repr(object)
-            print err
+        except Exception:
+            output("Error visiting", repr(object))
+            output(sys.exc_info()[1])
             traceback.print_exc()
             # XXX hack
             if hasattr(self, 'file'):
@@ -353,8 +371,8 @@
         if conflict is None:
             self.cons[key] = name
         else:
-            print "Redefinition of constructor %s" % key
-            print "Defined in %s and %s" % (conflict, name)
+            output("Redefinition of constructor %s" % key)
+            output("Defined in %s and %s" % (conflict, name))
             self.errors += 1
         for f in cons.fields:
             self.visit(f, key)
@@ -376,7 +394,7 @@
         if t not in mod.types and not t in builtin_types:
             v.errors += 1
             uses = ", ".join(v.types[t])
-            print "Undefined type %s, used in %s" % (t, uses)
+            output("Undefined type %s, used in %s" % (t, uses))
 
     return not v.errors
 
@@ -388,10 +406,10 @@
     tokens = scanner.tokenize(buf)
     try:
         return parser.parse(tokens)
-    except ASDLSyntaxError, err:
-        print err
+    except ASDLSyntaxError:
+        output(sys.exc_info()[1])
         lines = buf.split("\n")
-        print lines[err.lineno - 1] # lines starts at 0, files at 1
+        output(lines[err.lineno - 1]) # lines starts at 0, files at 1
 
 if __name__ == "__main__":
     import glob
@@ -404,12 +422,12 @@
         files = glob.glob(testdir + "/*.asdl")
 
     for file in files:
-        print file
+        output(file)
         mod = parse(file)
-        print "module", mod.name
-        print len(mod.dfns), "definitions"
+        output("module", mod.name)
+        output(len(mod.dfns), "definitions")
         if not check(mod):
-            print "Check failed"
+            output("Check failed")
         else:
             for dfn in mod.dfns:
-                print dfn.type
+                output(dfn.type)

Modified: python/branches/p3yk-noslice/Parser/asdl_c.py
==============================================================================
--- python/branches/p3yk-noslice/Parser/asdl_c.py	(original)
+++ python/branches/p3yk-noslice/Parser/asdl_c.py	Wed Jul 11 15:40:56 2007
@@ -15,7 +15,7 @@
     """Return a string for the C name of the type.
 
     This function special cases the default types provided by asdl:
-    identifier, string, int, bool.
+    identifier, string, int.
     """
     # XXX ack!  need to figure out where Id is useful and where string
     if isinstance(name, asdl.Id):
@@ -288,8 +288,7 @@
         emit("{")
         emit("%s p;" % ctype, 1)
         for argtype, argname, opt in args:
-            # XXX hack alert: false is allowed for a bool
-            if not opt and not (argtype == "bool" or argtype == "int"):
+            if not opt and argtype != "int":
                 emit("if (!%s) {" % argname, 1)
                 emit("PyErr_SetString(PyExc_ValueError,", 2)
                 msg = "field %s is required for %s" % (argname, name)
@@ -299,10 +298,8 @@
                 emit('}', 1)
 
         emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1);
-        emit("if (!p) {", 1)
-        emit("PyErr_NoMemory();", 2)
+        emit("if (!p)", 1)
         emit("return NULL;", 2)
-        emit("}", 1)
         if union:
             self.emit_body_union(name, args, attrs)
         else:
@@ -469,12 +466,8 @@
 }
 #define ast2obj_identifier ast2obj_object
 #define ast2obj_string ast2obj_object
-static PyObject* ast2obj_bool(bool b)
-{
-    return PyBool_FromLong(b);
-}
 
-static PyObject* ast2obj_int(bool b)
+static PyObject* ast2obj_int(long b)
 {
     return PyInt_FromLong(b);
 }
@@ -725,7 +718,7 @@
             v.visit(object)
             v.emit("", 0)
 
-common_msg = "/* File automatically generated by %s. */\n"
+common_msg = "/* File automatically generated by %s. */\n\n"
 
 c_file_msg = """
 /*
@@ -735,6 +728,7 @@
    The __version__ number is set to the revision number of the commit
    containing the grammar change.
 */
+
 """
 
 def main(srcfile):
@@ -748,25 +742,25 @@
     if INC_DIR:
         p = "%s/%s-ast.h" % (INC_DIR, mod.name)
         f = open(p, "wb")
-        print >> f, auto_gen_msg
-        print >> f, '#include "asdl.h"\n'
+        f.write(auto_gen_msg)
+        f.write('#include "asdl.h"\n\n')
         c = ChainOfVisitors(TypeDefVisitor(f),
                             StructVisitor(f),
                             PrototypeVisitor(f),
                             )
         c.visit(mod)
-        print >>f, "PyObject* PyAST_mod2obj(mod_ty t);"
+        f.write("PyObject* PyAST_mod2obj(mod_ty t);\n")
         f.close()
 
     if SRC_DIR:
         p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
         f = open(p, "wb")
-        print >> f, auto_gen_msg
-        print >> f, c_file_msg % parse_version(mod)
-        print >> f, '#include "Python.h"'
-        print >> f, '#include "%s-ast.h"' % mod.name
-        print >> f
-        print >>f, "static PyTypeObject* AST_type;"
+        f.write(auto_gen_msg)
+        f.write(c_file_msg % parse_version(mod))
+        f.write('#include "Python.h"\n')
+        f.write('#include "%s-ast.h"\n' % mod.name)
+        f.write('\n')
+        f.write("static PyTypeObject* AST_type;\n")
         v = ChainOfVisitors(
             PyTypesDeclareVisitor(f),
             PyTypesVisitor(f),
@@ -786,7 +780,7 @@
     SRC_DIR = ''
     opts, args = getopt.getopt(sys.argv[1:], "h:c:")
     if len(opts) != 1:
-        print "Must specify exactly one output file"
+        sys.stdout.write("Must specify exactly one output file\n")
         sys.exit(1)
     for o, v in opts:
         if o == '-h':
@@ -794,6 +788,6 @@
         if o == '-c':
             SRC_DIR = v
     if len(args) != 1:
-        print "Must specify single input file"
+        sys.stdout.write("Must specify single input file\n")
         sys.exit(1)
     main(args[0])

Modified: python/branches/p3yk-noslice/Parser/spark.py
==============================================================================
--- python/branches/p3yk-noslice/Parser/spark.py	(original)
+++ python/branches/p3yk-noslice/Parser/spark.py	Wed Jul 11 15:40:56 2007
@@ -23,7 +23,18 @@
 
 import re
 import sys
-import string
+
+# Compatability with older pythons.
+def output(string='', end='\n'):
+    sys.stdout.write(string + end)
+
+try:
+    sorted
+except NameError:
+    def sorted(seq):
+        seq2 = seq[:]
+        seq2.sort()
+        return seq2
 
 def _namelist(instance):
     namelist, namedict, classlist = [], {}, [instance.__class__]
@@ -57,10 +68,10 @@
                 rv.append(self.makeRE(name))
 
         rv.append(self.makeRE('t_default'))
-        return string.join(rv, '|')
+        return '|'.join(rv)
 
     def error(self, s, pos):
-        print "Lexical error at position %s" % pos
+        output("Lexical error at position %s" % pos)
         raise SystemExit
 
     def tokenize(self, s):
@@ -79,7 +90,7 @@
 
     def t_default(self, s):
         r'( . | \n )+'
-        print "Specification error: unmatched input"
+        output("Specification error: unmatched input")
         raise SystemExit
 
 #
@@ -172,7 +183,7 @@
 
     def addRule(self, doc, func, _preprocess=1):
         fn = func
-        rules = string.split(doc)
+        rules = doc.split()
 
         index = []
         for i in range(len(rules)):
@@ -296,7 +307,7 @@
         return None
 
     def error(self, token):
-        print "Syntax error at or near `%s' token" % token
+        output("Syntax error at or near `%s' token" % token)
         raise SystemExit
 
     def parse(self, tokens):
@@ -313,7 +324,7 @@
             self.states = { 0: self.makeState0() }
             self.makeState(0, self._BOF)
 
-        for i in xrange(len(tokens)):
+        for i in range(len(tokens)):
             sets.append([])
 
             if sets[i] == []:
@@ -342,10 +353,10 @@
         #
         return self._NULLABLE == sym[0:len(self._NULLABLE)]
 
-    def skip(self, (lhs, rhs), pos=0):
-        n = len(rhs)
+    def skip(self, hs, pos=0):
+        n = len(hs[1])
         while pos < n:
-            if not self.isnullable(rhs[pos]):
+            if not self.isnullable(hs[1][pos]):
                 break
             pos = pos + 1
         return pos
@@ -419,8 +430,7 @@
         #  need to know the entire set of predicted nonterminals
         #  to do this without accidentally duplicating states.
         #
-        core = predicted.keys()
-        core.sort()
+        core = sorted(predicted.keys())
         tcore = tuple(core)
         if tcore in self.cores:
             self.edges[(k, None)] = self.cores[tcore]
@@ -605,7 +615,7 @@
             rule = self.ambiguity(self.newrules[nt])
         else:
             rule = self.newrules[nt][0]
-        #print rule
+        #output(rule)
 
         rhs = rule[1]
         attr = [None] * len(rhs)
@@ -624,7 +634,7 @@
         rule = choices[0]
         if len(choices) > 1:
             rule = self.ambiguity(choices)
-        #print rule
+        #output(rule)
 
         rhs = rule[1]
         attr = [None] * len(rhs)
@@ -661,7 +671,7 @@
             sortlist.append((len(rhs), name))
             name2index[name] = i
         sortlist.sort()
-        list = map(lambda (a,b): b, sortlist)
+        list = [b for a, b in sortlist]
         return rules[name2index[self.resolve(list)]]
 
     def resolve(self, list):
@@ -826,15 +836,15 @@
 
 def _dump(tokens, sets, states):
     for i in range(len(sets)):
-        print 'set', i
+        output('set %d' % i)
         for item in sets[i]:
-            print '\t', item
+            output('\t', item)
             for (lhs, rhs), pos in states[item[0]].items:
-                print '\t\t', lhs, '::=',
-                print string.join(rhs[:pos]),
-                print '.',
-                print string.join(rhs[pos:])
+                output('\t\t', lhs, '::=', end='')
+                output(' '.join(rhs[:pos]), end='')
+                output('.', end='')
+                output(' '.join(rhs[pos:]))
         if i < len(tokens):
-            print
-            print 'token', str(tokens[i])
-            print
+            output()
+            output('token %s' % str(tokens[i]))
+            output()

Modified: python/branches/p3yk-noslice/Parser/tokenizer.c
==============================================================================
--- python/branches/p3yk-noslice/Parser/tokenizer.c	(original)
+++ python/branches/p3yk-noslice/Parser/tokenizer.c	Wed Jul 11 15:40:56 2007
@@ -93,6 +93,7 @@
 	"DOUBLESLASHEQUAL",
 	"AT",
 	"RARROW",
+	"ELLIPSIS",
 	/* This table must match the #defines in token.h! */
 	"OP",
 	"<ERRORTOKEN>",
@@ -1082,6 +1083,16 @@
 			break;
 		}
 		break;
+        case '.':
+	        switch (c2) {
+		case '.':
+			switch (c3) {
+			case '.':
+				return ELLIPSIS;
+			}
+			break;
+		}
+		break;
 	}
 	return OP;
 }
@@ -1244,6 +1255,14 @@
 			if (c == '"' || c == '\'')
 				goto letter_quote;
 			break;
+		case 'b':
+		case 'B':
+			c = tok_nextc(tok);
+			if (c == 'r' || c == 'R')
+				c = tok_nextc(tok);
+			if (c == '"' || c == '\'')
+				goto letter_quote;
+			break;
 		}
 		while (isalnum(c) || c == '_') {
 			c = tok_nextc(tok);
@@ -1270,19 +1289,28 @@
 		c = tok_nextc(tok);
 		if (isdigit(c)) {
 			goto fraction;
-		}
-		else {
+		} else if (c == '.') {
+			c = tok_nextc(tok);
+			if (c == '.') {
+				*p_start = tok->start;
+				*p_end = tok->cur; 
+				return ELLIPSIS;
+			} else {
+				tok_backup(tok, c);
+			}
+			tok_backup(tok, '.');
+		} else {
 			tok_backup(tok, c);
-			*p_start = tok->start;
-			*p_end = tok->cur;
-			return DOT;
 		}
+		*p_start = tok->start;
+		*p_end = tok->cur;
+		return DOT;
 	}
 
 	/* Number */
 	if (isdigit(c)) {
 		if (c == '0') {
-			/* Hex or octal -- maybe. */
+			/* Hex, octal or binary -- maybe. */
 			c = tok_nextc(tok);
 			if (c == '.')
 				goto fraction;
@@ -1296,18 +1324,27 @@
 					c = tok_nextc(tok);
 				} while (isxdigit(c));
 			}
+                        else if (c == 'o' || c == 'O') {
+				/* Octal */
+				do {
+					c = tok_nextc(tok);
+				} while ('0' <= c && c < '8');
+			}
+			else if (c == 'b' || c == 'B') {
+				/* Binary */
+				do {
+					c = tok_nextc(tok);
+				} while (c == '0' || c == '1');
+			}
 			else {
-				int found_decimal = 0;
-				/* Octal; c is first char of it */
-				/* There's no 'isoctdigit' macro, sigh */
-				while ('0' <= c && c < '8') {
+				int nonzero = 0;
+				/* maybe old-style octal; c is first char of it */
+				/* in any case, allow '0' as a literal */
+				while (c == '0')
+					c = tok_nextc(tok);
+				while (isdigit(c)) {
+					nonzero = 1;
 					c = tok_nextc(tok);
-				}
-				if (isdigit(c)) {
-					found_decimal = 1;
-					do {
-						c = tok_nextc(tok);
-					} while (isdigit(c));
 				}
 				if (c == '.')
 					goto fraction;
@@ -1317,7 +1354,7 @@
 				else if (c == 'j' || c == 'J')
 					goto imaginary;
 #endif
-				else if (found_decimal) {
+				else if (nonzero) {
 					tok->done = E_TOKEN;
 					tok_backup(tok, c);
 					return ERRORTOKEN;

Modified: python/branches/p3yk-noslice/Python/Python-ast.c
==============================================================================
--- python/branches/p3yk-noslice/Python/Python-ast.c	(original)
+++ python/branches/p3yk-noslice/Python/Python-ast.c	Wed Jul 11 15:40:56 2007
@@ -2,7 +2,7 @@
 
 
 /*
-   __version__ 53731.
+   __version__ 53867.
 
    This module must be committed separately after each AST grammar change;
    The __version__ number is set to the revision number of the commit
@@ -42,14 +42,18 @@
         "name",
         "args",
         "body",
-        "decorators",
+        "decorator_list",
         "returns",
 };
 static PyTypeObject *ClassDef_type;
 static char *ClassDef_fields[]={
         "name",
         "bases",
+        "keywords",
+        "starargs",
+        "kwargs",
         "body",
+        "decorator_list",
 };
 static PyTypeObject *Return_type;
 static char *Return_fields[]={
@@ -131,6 +135,10 @@
 static char *Global_fields[]={
         "names",
 };
+static PyTypeObject *Nonlocal_type;
+static char *Nonlocal_fields[]={
+        "names",
+};
 static PyTypeObject *Expr_type;
 static char *Expr_fields[]={
         "value",
@@ -185,6 +193,11 @@
         "elt",
         "generators",
 };
+static PyTypeObject *SetComp_type;
+static char *SetComp_fields[]={
+        "elt",
+        "generators",
+};
 static PyTypeObject *GeneratorExp_type;
 static char *GeneratorExp_fields[]={
         "elt",
@@ -216,6 +229,10 @@
 static char *Str_fields[]={
         "s",
 };
+static PyTypeObject *Bytes_type;
+static char *Bytes_fields[]={
+        "s",
+};
 static PyTypeObject *Ellipsis_type;
 static PyTypeObject *Attribute_type;
 static char *Attribute_fields[]={
@@ -229,6 +246,11 @@
         "slice",
         "ctx",
 };
+static PyTypeObject *Starred_type;
+static char *Starred_fields[]={
+        "value",
+        "ctx",
+};
 static PyTypeObject *Name_type;
 static char *Name_fields[]={
         "id",
@@ -346,15 +368,10 @@
 };
 static PyTypeObject *arg_type;
 static PyObject* ast2obj_arg(void*);
-static PyTypeObject *SimpleArg_type;
-static char *SimpleArg_fields[]={
+static char *arg_fields[]={
         "arg",
         "annotation",
 };
-static PyTypeObject *NestedArgs_type;
-static char *NestedArgs_fields[]={
-        "args",
-};
 static PyTypeObject *keyword_type;
 static PyObject* ast2obj_keyword(void*);
 static char *keyword_fields[]={
@@ -439,12 +456,8 @@
 }
 #define ast2obj_identifier ast2obj_object
 #define ast2obj_string ast2obj_object
-static PyObject* ast2obj_bool(bool b)
-{
-    return PyBool_FromLong(b);
-}
 
-static PyObject* ast2obj_int(bool b)
+static PyObject* ast2obj_int(long b)
 {
     return PyInt_FromLong(b);
 }
@@ -473,7 +486,7 @@
         FunctionDef_type = make_type("FunctionDef", stmt_type,
                                      FunctionDef_fields, 5);
         if (!FunctionDef_type) return 0;
-        ClassDef_type = make_type("ClassDef", stmt_type, ClassDef_fields, 3);
+        ClassDef_type = make_type("ClassDef", stmt_type, ClassDef_fields, 7);
         if (!ClassDef_type) return 0;
         Return_type = make_type("Return", stmt_type, Return_fields, 1);
         if (!Return_type) return 0;
@@ -507,6 +520,8 @@
         if (!ImportFrom_type) return 0;
         Global_type = make_type("Global", stmt_type, Global_fields, 1);
         if (!Global_type) return 0;
+        Nonlocal_type = make_type("Nonlocal", stmt_type, Nonlocal_fields, 1);
+        if (!Nonlocal_type) return 0;
         Expr_type = make_type("Expr", stmt_type, Expr_fields, 1);
         if (!Expr_type) return 0;
         Pass_type = make_type("Pass", stmt_type, NULL, 0);
@@ -534,6 +549,8 @@
         if (!Set_type) return 0;
         ListComp_type = make_type("ListComp", expr_type, ListComp_fields, 2);
         if (!ListComp_type) return 0;
+        SetComp_type = make_type("SetComp", expr_type, SetComp_fields, 2);
+        if (!SetComp_type) return 0;
         GeneratorExp_type = make_type("GeneratorExp", expr_type,
                                       GeneratorExp_fields, 2);
         if (!GeneratorExp_type) return 0;
@@ -547,12 +564,16 @@
         if (!Num_type) return 0;
         Str_type = make_type("Str", expr_type, Str_fields, 1);
         if (!Str_type) return 0;
+        Bytes_type = make_type("Bytes", expr_type, Bytes_fields, 1);
+        if (!Bytes_type) return 0;
         Ellipsis_type = make_type("Ellipsis", expr_type, NULL, 0);
         if (!Ellipsis_type) return 0;
         Attribute_type = make_type("Attribute", expr_type, Attribute_fields, 3);
         if (!Attribute_type) return 0;
         Subscript_type = make_type("Subscript", expr_type, Subscript_fields, 3);
         if (!Subscript_type) return 0;
+        Starred_type = make_type("Starred", expr_type, Starred_fields, 2);
+        if (!Starred_type) return 0;
         Name_type = make_type("Name", expr_type, Name_fields, 2);
         if (!Name_type) return 0;
         List_type = make_type("List", expr_type, List_fields, 2);
@@ -727,14 +748,8 @@
         if (!excepthandler_type) return 0;
         arguments_type = make_type("arguments", AST_type, arguments_fields, 8);
         if (!arguments_type) return 0;
-        arg_type = make_type("arg", AST_type, NULL, 0);
+        arg_type = make_type("arg", AST_type, arg_fields, 2);
         if (!arg_type) return 0;
-        if (!add_attributes(arg_type, NULL, 0)) return 0;
-        SimpleArg_type = make_type("SimpleArg", arg_type, SimpleArg_fields, 2);
-        if (!SimpleArg_type) return 0;
-        NestedArgs_type = make_type("NestedArgs", arg_type, NestedArgs_fields,
-                                    1);
-        if (!NestedArgs_type) return 0;
         keyword_type = make_type("keyword", AST_type, keyword_fields, 2);
         if (!keyword_type) return 0;
         alias_type = make_type("alias", AST_type, alias_fields, 2);
@@ -748,10 +763,8 @@
 {
         mod_ty p;
         p = (mod_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Module_kind;
         p->v.Module.body = body;
         return p;
@@ -762,10 +775,8 @@
 {
         mod_ty p;
         p = (mod_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Interactive_kind;
         p->v.Interactive.body = body;
         return p;
@@ -781,10 +792,8 @@
                 return NULL;
         }
         p = (mod_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Expression_kind;
         p->v.Expression.body = body;
         return p;
@@ -795,10 +804,8 @@
 {
         mod_ty p;
         p = (mod_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Suite_kind;
         p->v.Suite.body = body;
         return p;
@@ -806,8 +813,8 @@
 
 stmt_ty
 FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq *
-            decorators, expr_ty returns, int lineno, int col_offset, PyArena
-            *arena)
+            decorator_list, expr_ty returns, int lineno, int col_offset,
+            PyArena *arena)
 {
         stmt_ty p;
         if (!name) {
@@ -821,15 +828,13 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = FunctionDef_kind;
         p->v.FunctionDef.name = name;
         p->v.FunctionDef.args = args;
         p->v.FunctionDef.body = body;
-        p->v.FunctionDef.decorators = decorators;
+        p->v.FunctionDef.decorator_list = decorator_list;
         p->v.FunctionDef.returns = returns;
         p->lineno = lineno;
         p->col_offset = col_offset;
@@ -837,8 +842,9 @@
 }
 
 stmt_ty
-ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int lineno, int
-         col_offset, PyArena *arena)
+ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords, expr_ty
+         starargs, expr_ty kwargs, asdl_seq * body, asdl_seq * decorator_list,
+         int lineno, int col_offset, PyArena *arena)
 {
         stmt_ty p;
         if (!name) {
@@ -847,14 +853,16 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = ClassDef_kind;
         p->v.ClassDef.name = name;
         p->v.ClassDef.bases = bases;
+        p->v.ClassDef.keywords = keywords;
+        p->v.ClassDef.starargs = starargs;
+        p->v.ClassDef.kwargs = kwargs;
         p->v.ClassDef.body = body;
+        p->v.ClassDef.decorator_list = decorator_list;
         p->lineno = lineno;
         p->col_offset = col_offset;
         return p;
@@ -865,10 +873,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Return_kind;
         p->v.Return.value = value;
         p->lineno = lineno;
@@ -881,10 +887,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Delete_kind;
         p->v.Delete.targets = targets;
         p->lineno = lineno;
@@ -903,10 +907,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Assign_kind;
         p->v.Assign.targets = targets;
         p->v.Assign.value = value;
@@ -936,10 +938,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = AugAssign_kind;
         p->v.AugAssign.target = target;
         p->v.AugAssign.op = op;
@@ -965,10 +965,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = For_kind;
         p->v.For.target = target;
         p->v.For.iter = iter;
@@ -990,10 +988,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = While_kind;
         p->v.While.test = test;
         p->v.While.body = body;
@@ -1014,10 +1010,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = If_kind;
         p->v.If.test = test;
         p->v.If.body = body;
@@ -1038,10 +1032,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = With_kind;
         p->v.With.context_expr = context_expr;
         p->v.With.optional_vars = optional_vars;
@@ -1057,10 +1049,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Raise_kind;
         p->v.Raise.type = type;
         p->v.Raise.inst = inst;
@@ -1076,10 +1066,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = TryExcept_kind;
         p->v.TryExcept.body = body;
         p->v.TryExcept.handlers = handlers;
@@ -1095,10 +1083,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = TryFinally_kind;
         p->v.TryFinally.body = body;
         p->v.TryFinally.finalbody = finalbody;
@@ -1117,10 +1103,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Assert_kind;
         p->v.Assert.test = test;
         p->v.Assert.msg = msg;
@@ -1134,10 +1118,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Import_kind;
         p->v.Import.names = names;
         p->lineno = lineno;
@@ -1156,10 +1138,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = ImportFrom_kind;
         p->v.ImportFrom.module = module;
         p->v.ImportFrom.names = names;
@@ -1174,10 +1154,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Global_kind;
         p->v.Global.names = names;
         p->lineno = lineno;
@@ -1186,6 +1164,20 @@
 }
 
 stmt_ty
+Nonlocal(asdl_seq * names, int lineno, int col_offset, PyArena *arena)
+{
+        stmt_ty p;
+        p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
+        if (!p)
+                return NULL;
+        p->kind = Nonlocal_kind;
+        p->v.Nonlocal.names = names;
+        p->lineno = lineno;
+        p->col_offset = col_offset;
+        return p;
+}
+
+stmt_ty
 Expr(expr_ty value, int lineno, int col_offset, PyArena *arena)
 {
         stmt_ty p;
@@ -1195,10 +1187,8 @@
                 return NULL;
         }
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Expr_kind;
         p->v.Expr.value = value;
         p->lineno = lineno;
@@ -1211,10 +1201,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Pass_kind;
         p->lineno = lineno;
         p->col_offset = col_offset;
@@ -1226,10 +1214,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Break_kind;
         p->lineno = lineno;
         p->col_offset = col_offset;
@@ -1241,10 +1227,8 @@
 {
         stmt_ty p;
         p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Continue_kind;
         p->lineno = lineno;
         p->col_offset = col_offset;
@@ -1262,10 +1246,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = BoolOp_kind;
         p->v.BoolOp.op = op;
         p->v.BoolOp.values = values;
@@ -1295,10 +1277,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = BinOp_kind;
         p->v.BinOp.left = left;
         p->v.BinOp.op = op;
@@ -1324,10 +1304,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = UnaryOp_kind;
         p->v.UnaryOp.op = op;
         p->v.UnaryOp.operand = operand;
@@ -1352,10 +1330,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Lambda_kind;
         p->v.Lambda.args = args;
         p->v.Lambda.body = body;
@@ -1385,10 +1361,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = IfExp_kind;
         p->v.IfExp.test = test;
         p->v.IfExp.body = body;
@@ -1404,10 +1378,8 @@
 {
         expr_ty p;
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Dict_kind;
         p->v.Dict.keys = keys;
         p->v.Dict.values = values;
@@ -1421,10 +1393,8 @@
 {
         expr_ty p;
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Set_kind;
         p->v.Set.elts = elts;
         p->lineno = lineno;
@@ -1443,10 +1413,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = ListComp_kind;
         p->v.ListComp.elt = elt;
         p->v.ListComp.generators = generators;
@@ -1456,6 +1424,27 @@
 }
 
 expr_ty
+SetComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena
+        *arena)
+{
+        expr_ty p;
+        if (!elt) {
+                PyErr_SetString(PyExc_ValueError,
+                                "field elt is required for SetComp");
+                return NULL;
+        }
+        p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
+        if (!p)
+                return NULL;
+        p->kind = SetComp_kind;
+        p->v.SetComp.elt = elt;
+        p->v.SetComp.generators = generators;
+        p->lineno = lineno;
+        p->col_offset = col_offset;
+        return p;
+}
+
+expr_ty
 GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset,
              PyArena *arena)
 {
@@ -1466,10 +1455,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = GeneratorExp_kind;
         p->v.GeneratorExp.elt = elt;
         p->v.GeneratorExp.generators = generators;
@@ -1483,10 +1470,8 @@
 {
         expr_ty p;
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Yield_kind;
         p->v.Yield.value = value;
         p->lineno = lineno;
@@ -1505,10 +1490,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Compare_kind;
         p->v.Compare.left = left;
         p->v.Compare.ops = ops;
@@ -1529,10 +1512,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Call_kind;
         p->v.Call.func = func;
         p->v.Call.args = args;
@@ -1554,10 +1535,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Num_kind;
         p->v.Num.n = n;
         p->lineno = lineno;
@@ -1575,10 +1554,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Str_kind;
         p->v.Str.s = s;
         p->lineno = lineno;
@@ -1587,14 +1564,31 @@
 }
 
 expr_ty
+Bytes(string s, int lineno, int col_offset, PyArena *arena)
+{
+        expr_ty p;
+        if (!s) {
+                PyErr_SetString(PyExc_ValueError,
+                                "field s is required for Bytes");
+                return NULL;
+        }
+        p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
+        if (!p)
+                return NULL;
+        p->kind = Bytes_kind;
+        p->v.Bytes.s = s;
+        p->lineno = lineno;
+        p->col_offset = col_offset;
+        return p;
+}
+
+expr_ty
 Ellipsis(int lineno, int col_offset, PyArena *arena)
 {
         expr_ty p;
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Ellipsis_kind;
         p->lineno = lineno;
         p->col_offset = col_offset;
@@ -1622,10 +1616,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Attribute_kind;
         p->v.Attribute.value = value;
         p->v.Attribute.attr = attr;
@@ -1656,10 +1648,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Subscript_kind;
         p->v.Subscript.value = value;
         p->v.Subscript.slice = slice;
@@ -1670,6 +1660,32 @@
 }
 
 expr_ty
+Starred(expr_ty value, expr_context_ty ctx, int lineno, int col_offset, PyArena
+        *arena)
+{
+        expr_ty p;
+        if (!value) {
+                PyErr_SetString(PyExc_ValueError,
+                                "field value is required for Starred");
+                return NULL;
+        }
+        if (!ctx) {
+                PyErr_SetString(PyExc_ValueError,
+                                "field ctx is required for Starred");
+                return NULL;
+        }
+        p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
+        if (!p)
+                return NULL;
+        p->kind = Starred_kind;
+        p->v.Starred.value = value;
+        p->v.Starred.ctx = ctx;
+        p->lineno = lineno;
+        p->col_offset = col_offset;
+        return p;
+}
+
+expr_ty
 Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, PyArena
      *arena)
 {
@@ -1685,10 +1701,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Name_kind;
         p->v.Name.id = id;
         p->v.Name.ctx = ctx;
@@ -1708,10 +1722,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = List_kind;
         p->v.List.elts = elts;
         p->v.List.ctx = ctx;
@@ -1731,10 +1743,8 @@
                 return NULL;
         }
         p = (expr_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Tuple_kind;
         p->v.Tuple.elts = elts;
         p->v.Tuple.ctx = ctx;
@@ -1748,10 +1758,8 @@
 {
         slice_ty p;
         p = (slice_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Slice_kind;
         p->v.Slice.lower = lower;
         p->v.Slice.upper = upper;
@@ -1764,10 +1772,8 @@
 {
         slice_ty p;
         p = (slice_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = ExtSlice_kind;
         p->v.ExtSlice.dims = dims;
         return p;
@@ -1783,10 +1789,8 @@
                 return NULL;
         }
         p = (slice_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->kind = Index_kind;
         p->v.Index.value = value;
         return p;
@@ -1807,10 +1811,8 @@
                 return NULL;
         }
         p = (comprehension_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->target = target;
         p->iter = iter;
         p->ifs = ifs;
@@ -1823,10 +1825,8 @@
 {
         excepthandler_ty p;
         p = (excepthandler_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->type = type;
         p->name = name;
         p->body = body;
@@ -1842,10 +1842,8 @@
 {
         arguments_ty p;
         p = (arguments_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->args = args;
         p->vararg = vararg;
         p->varargannotation = varargannotation;
@@ -1858,36 +1856,19 @@
 }
 
 arg_ty
-SimpleArg(identifier arg, expr_ty annotation, PyArena *arena)
+arg(identifier arg, expr_ty annotation, PyArena *arena)
 {
         arg_ty p;
         if (!arg) {
                 PyErr_SetString(PyExc_ValueError,
-                                "field arg is required for SimpleArg");
+                                "field arg is required for arg");
                 return NULL;
         }
         p = (arg_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
-                return NULL;
-        }
-        p->kind = SimpleArg_kind;
-        p->v.SimpleArg.arg = arg;
-        p->v.SimpleArg.annotation = annotation;
-        return p;
-}
-
-arg_ty
-NestedArgs(asdl_seq * args, PyArena *arena)
-{
-        arg_ty p;
-        p = (arg_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
-        p->kind = NestedArgs_kind;
-        p->v.NestedArgs.args = args;
+        p->arg = arg;
+        p->annotation = annotation;
         return p;
 }
 
@@ -1906,10 +1887,8 @@
                 return NULL;
         }
         p = (keyword_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->arg = arg;
         p->value = value;
         return p;
@@ -1925,10 +1904,8 @@
                 return NULL;
         }
         p = (alias_ty)PyArena_Malloc(arena, sizeof(*p));
-        if (!p) {
-                PyErr_NoMemory();
+        if (!p)
                 return NULL;
-        }
         p->name = name;
         p->asname = asname;
         return p;
@@ -2019,9 +1996,11 @@
                 if (PyObject_SetAttrString(result, "body", value) == -1)
                         goto failed;
                 Py_DECREF(value);
-                value = ast2obj_list(o->v.FunctionDef.decorators, ast2obj_expr);
+                value = ast2obj_list(o->v.FunctionDef.decorator_list,
+                                     ast2obj_expr);
                 if (!value) goto failed;
-                if (PyObject_SetAttrString(result, "decorators", value) == -1)
+                if (PyObject_SetAttrString(result, "decorator_list", value) ==
+                    -1)
                         goto failed;
                 Py_DECREF(value);
                 value = ast2obj_expr(o->v.FunctionDef.returns);
@@ -2043,11 +2022,33 @@
                 if (PyObject_SetAttrString(result, "bases", value) == -1)
                         goto failed;
                 Py_DECREF(value);
+                value = ast2obj_list(o->v.ClassDef.keywords, ast2obj_keyword);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "keywords", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                value = ast2obj_expr(o->v.ClassDef.starargs);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "starargs", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                value = ast2obj_expr(o->v.ClassDef.kwargs);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "kwargs", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
                 value = ast2obj_list(o->v.ClassDef.body, ast2obj_stmt);
                 if (!value) goto failed;
                 if (PyObject_SetAttrString(result, "body", value) == -1)
                         goto failed;
                 Py_DECREF(value);
+                value = ast2obj_list(o->v.ClassDef.decorator_list,
+                                     ast2obj_expr);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "decorator_list", value) ==
+                    -1)
+                        goto failed;
+                Py_DECREF(value);
                 break;
         case Return_kind:
                 result = PyType_GenericNew(Return_type, NULL, NULL);
@@ -2286,6 +2287,15 @@
                         goto failed;
                 Py_DECREF(value);
                 break;
+        case Nonlocal_kind:
+                result = PyType_GenericNew(Nonlocal_type, NULL, NULL);
+                if (!result) goto failed;
+                value = ast2obj_list(o->v.Nonlocal.names, ast2obj_identifier);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "names", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                break;
         case Expr_kind:
                 result = PyType_GenericNew(Expr_type, NULL, NULL);
                 if (!result) goto failed;
@@ -2454,6 +2464,21 @@
                         goto failed;
                 Py_DECREF(value);
                 break;
+        case SetComp_kind:
+                result = PyType_GenericNew(SetComp_type, NULL, NULL);
+                if (!result) goto failed;
+                value = ast2obj_expr(o->v.SetComp.elt);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "elt", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                value = ast2obj_list(o->v.SetComp.generators,
+                                     ast2obj_comprehension);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "generators", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                break;
         case GeneratorExp_kind:
                 result = PyType_GenericNew(GeneratorExp_type, NULL, NULL);
                 if (!result) goto failed;
@@ -2550,6 +2575,15 @@
                         goto failed;
                 Py_DECREF(value);
                 break;
+        case Bytes_kind:
+                result = PyType_GenericNew(Bytes_type, NULL, NULL);
+                if (!result) goto failed;
+                value = ast2obj_string(o->v.Bytes.s);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "s", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                break;
         case Ellipsis_kind:
                 result = PyType_GenericNew(Ellipsis_type, NULL, NULL);
                 if (!result) goto failed;
@@ -2592,6 +2626,20 @@
                         goto failed;
                 Py_DECREF(value);
                 break;
+        case Starred_kind:
+                result = PyType_GenericNew(Starred_type, NULL, NULL);
+                if (!result) goto failed;
+                value = ast2obj_expr(o->v.Starred.value);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "value", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                value = ast2obj_expr_context(o->v.Starred.ctx);
+                if (!value) goto failed;
+                if (PyObject_SetAttrString(result, "ctx", value) == -1)
+                        goto failed;
+                Py_DECREF(value);
+                break;
         case Name_kind:
                 result = PyType_GenericNew(Name_type, NULL, NULL);
                 if (!result) goto failed;
@@ -2987,31 +3035,18 @@
                 return Py_None;
         }
 
-        switch (o->kind) {
-        case SimpleArg_kind:
-                result = PyType_GenericNew(SimpleArg_type, NULL, NULL);
-                if (!result) goto failed;
-                value = ast2obj_identifier(o->v.SimpleArg.arg);
-                if (!value) goto failed;
-                if (PyObject_SetAttrString(result, "arg", value) == -1)
-                        goto failed;
-                Py_DECREF(value);
-                value = ast2obj_expr(o->v.SimpleArg.annotation);
-                if (!value) goto failed;
-                if (PyObject_SetAttrString(result, "annotation", value) == -1)
-                        goto failed;
-                Py_DECREF(value);
-                break;
-        case NestedArgs_kind:
-                result = PyType_GenericNew(NestedArgs_type, NULL, NULL);
-                if (!result) goto failed;
-                value = ast2obj_list(o->v.NestedArgs.args, ast2obj_arg);
-                if (!value) goto failed;
-                if (PyObject_SetAttrString(result, "args", value) == -1)
-                        goto failed;
-                Py_DECREF(value);
-                break;
-        }
+        result = PyType_GenericNew(arg_type, NULL, NULL);
+        if (!result) return NULL;
+        value = ast2obj_identifier(o->arg);
+        if (!value) goto failed;
+        if (PyObject_SetAttrString(result, "arg", value) == -1)
+                goto failed;
+        Py_DECREF(value);
+        value = ast2obj_expr(o->annotation);
+        if (!value) goto failed;
+        if (PyObject_SetAttrString(result, "annotation", value) == -1)
+                goto failed;
+        Py_DECREF(value);
         return result;
 failed:
         Py_XDECREF(value);
@@ -3089,7 +3124,7 @@
         if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return;
         if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)
                 return;
-        if (PyModule_AddStringConstant(m, "__version__", "53731") < 0)
+        if (PyModule_AddStringConstant(m, "__version__", "53867") < 0)
                 return;
         if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return;
         if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0)
@@ -3129,6 +3164,8 @@
             0) return;
         if (PyDict_SetItemString(d, "Global", (PyObject*)Global_type) < 0)
             return;
+        if (PyDict_SetItemString(d, "Nonlocal", (PyObject*)Nonlocal_type) < 0)
+            return;
         if (PyDict_SetItemString(d, "Expr", (PyObject*)Expr_type) < 0) return;
         if (PyDict_SetItemString(d, "Pass", (PyObject*)Pass_type) < 0) return;
         if (PyDict_SetItemString(d, "Break", (PyObject*)Break_type) < 0) return;
@@ -3147,6 +3184,8 @@
         if (PyDict_SetItemString(d, "Set", (PyObject*)Set_type) < 0) return;
         if (PyDict_SetItemString(d, "ListComp", (PyObject*)ListComp_type) < 0)
             return;
+        if (PyDict_SetItemString(d, "SetComp", (PyObject*)SetComp_type) < 0)
+            return;
         if (PyDict_SetItemString(d, "GeneratorExp",
             (PyObject*)GeneratorExp_type) < 0) return;
         if (PyDict_SetItemString(d, "Yield", (PyObject*)Yield_type) < 0) return;
@@ -3155,12 +3194,15 @@
         if (PyDict_SetItemString(d, "Call", (PyObject*)Call_type) < 0) return;
         if (PyDict_SetItemString(d, "Num", (PyObject*)Num_type) < 0) return;
         if (PyDict_SetItemString(d, "Str", (PyObject*)Str_type) < 0) return;
+        if (PyDict_SetItemString(d, "Bytes", (PyObject*)Bytes_type) < 0) return;
         if (PyDict_SetItemString(d, "Ellipsis", (PyObject*)Ellipsis_type) < 0)
             return;
         if (PyDict_SetItemString(d, "Attribute", (PyObject*)Attribute_type) <
             0) return;
         if (PyDict_SetItemString(d, "Subscript", (PyObject*)Subscript_type) <
             0) return;
+        if (PyDict_SetItemString(d, "Starred", (PyObject*)Starred_type) < 0)
+            return;
         if (PyDict_SetItemString(d, "Name", (PyObject*)Name_type) < 0) return;
         if (PyDict_SetItemString(d, "List", (PyObject*)List_type) < 0) return;
         if (PyDict_SetItemString(d, "Tuple", (PyObject*)Tuple_type) < 0) return;
@@ -3227,10 +3269,6 @@
         if (PyDict_SetItemString(d, "arguments", (PyObject*)arguments_type) <
             0) return;
         if (PyDict_SetItemString(d, "arg", (PyObject*)arg_type) < 0) return;
-        if (PyDict_SetItemString(d, "SimpleArg", (PyObject*)SimpleArg_type) <
-            0) return;
-        if (PyDict_SetItemString(d, "NestedArgs", (PyObject*)NestedArgs_type) <
-            0) return;
         if (PyDict_SetItemString(d, "keyword", (PyObject*)keyword_type) < 0)
             return;
         if (PyDict_SetItemString(d, "alias", (PyObject*)alias_type) < 0) return;

Modified: python/branches/p3yk-noslice/Python/ast.c
==============================================================================
--- python/branches/p3yk-noslice/Python/ast.c	(original)
+++ python/branches/p3yk-noslice/Python/ast.c	Wed Jul 11 15:40:56 2007
@@ -25,21 +25,27 @@
 static expr_ty ast_for_expr(struct compiling *, const node *);
 static stmt_ty ast_for_stmt(struct compiling *, const node *);
 static asdl_seq *ast_for_suite(struct compiling *, const node *);
-static asdl_seq *ast_for_exprlist(struct compiling *, const node *, expr_context_ty);
+static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
+                                  expr_context_ty);
 static expr_ty ast_for_testlist(struct compiling *, const node *);
-static expr_ty ast_for_testlist_gexp(struct compiling *, const node *);
+static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
 
 /* Note different signature for ast_for_call */
 static expr_ty ast_for_call(struct compiling *, const node *, expr_ty);
 
 static PyObject *parsenumber(const char *);
-static PyObject *parsestr(const char *s, const char *encoding);
-static PyObject *parsestrplus(struct compiling *, const node *n);
+static PyObject *parsestr(const node *n, const char *encoding, int *bytesmode);
+static PyObject *parsestrplus(struct compiling *, const node *n,
+                              int *bytesmode);
 
 #ifndef LINENO
 #define LINENO(n)       ((n)->n_lineno)
 #endif
 
+#define COMP_GENEXP   0
+#define COMP_LISTCOMP 1
+#define COMP_SETCOMP  2
+
 static identifier
 new_identifier(const char* n, PyArena *arena) {
     PyObject* id = PyString_InternFromString(n);
@@ -186,8 +192,8 @@
     if (flags && flags->cf_flags & PyCF_SOURCE_IS_UTF8) {
         c.c_encoding = "utf-8";
         if (TYPE(n) == encoding_decl) {
-                ast_error(n, "encoding declaration in Unicode string");
-                goto error;
+            ast_error(n, "encoding declaration in Unicode string");
+            goto error;
         }
     } else if (TYPE(n) == encoding_decl) {
         c.c_encoding = STR(n);
@@ -202,7 +208,7 @@
         case file_input:
             stmts = asdl_seq_new(num_stmts(n), arena);
             if (!stmts)
-                    return NULL;
+                return NULL;
             for (i = 0; i < NCH(n) - 1; i++) {
                 ch = CHILD(n, i);
                 if (TYPE(ch) == NEWLINE)
@@ -230,7 +236,7 @@
         case eval_input: {
             expr_ty testlist_ast;
 
-            /* XXX Why not gen_for here? */
+            /* XXX Why not comp_for here? */
             testlist_ast = ast_for_testlist(&c, CHILD(n, 0));
             if (!testlist_ast)
                 goto error;
@@ -243,6 +249,8 @@
                     goto error;
                 asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
                                             arena));
+                if (!asdl_seq_GET(stmts, 0))
+                    goto error;
                 return Interactive(stmts, arena);
             }
             else {
@@ -273,6 +281,8 @@
                 return Interactive(stmts, arena);
             }
         default:
+            PyErr_Format(PyExc_SystemError,
+                         "invalid node %d for PyAST_FromNode", TYPE(n));
             goto error;
     }
  error:
@@ -314,6 +324,29 @@
     }
 }
 
+static const char* FORBIDDEN[] = {
+    "None",
+    "True",
+    "False",
+    NULL,
+};
+
+static int
+forbidden_name(expr_ty e, const node *n)
+{
+    const char *id;
+    const char **p;
+    assert(PyString_Check(e->v.Name.id));
+    id = PyString_AS_STRING(e->v.Name.id);
+    for (p = FORBIDDEN; *p; p++) {
+        if (strcmp(*p, id) == 0) {
+            ast_error(n, "assignment to keyword");
+            return 1;
+        }
+    }
+    return 0;
+}
+
 /* Set the context ctx for expr_ty e, recursively traversing e.
 
    Only sets context for expr kinds that "can appear in assignment context"
@@ -342,18 +375,23 @@
     switch (e->kind) {
         case Attribute_kind:
             if (ctx == Store &&
-                    !strcmp(PyString_AS_STRING(e->v.Attribute.attr), "None")) {
-                    return ast_error(n, "assignment to None");
+                !strcmp(PyString_AS_STRING(e->v.Attribute.attr), "None")) {
+                return ast_error(n, "assignment to None");
             }
             e->v.Attribute.ctx = ctx;
             break;
         case Subscript_kind:
             e->v.Subscript.ctx = ctx;
             break;
+        case Starred_kind:
+            e->v.Starred.ctx = ctx;
+            if (!set_context(e->v.Starred.value, ctx, n))
+                return 0;
+            break;
         case Name_kind:
-            if (ctx == Store &&
-                !strcmp(PyString_AS_STRING(e->v.Name.id), "None")) {
-                    return ast_error(n, "assignment to None");
+            if (ctx == Store) {
+                if (forbidden_name(e, n))
+                    return 0; /* forbidden_name() calls ast_error() */
             }
             e->v.Name.ctx = ctx;
             break;
@@ -387,6 +425,9 @@
         case ListComp_kind:
             expr_name = "list comprehension";
             break;
+        case SetComp_kind:
+            expr_name = "set comprehension";
+            break;
         case Dict_kind:
         case Set_kind:
         case Num_kind:
@@ -529,19 +570,14 @@
     asdl_seq *seq;
     expr_ty expression;
     int i;
-    assert(TYPE(n) == testlist
-           || TYPE(n) == listmaker
-           || TYPE(n) == testlist_gexp
-           || TYPE(n) == testlist_safe
-           || TYPE(n) == testlist1
-           );
+    assert(TYPE(n) == testlist || TYPE(n) == testlist_comp);
 
     seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
     if (!seq)
         return NULL;
 
     for (i = 0; i < NCH(n); i += 2) {
-        assert(TYPE(CHILD(n, i)) == test || TYPE(CHILD(n, i)) == old_test);
+        assert(TYPE(CHILD(n, i)) == test || TYPE(CHILD(n, i)) == test_nocond);
 
         expression = ast_for_expr(c, CHILD(n, i));
         if (!expression)
@@ -554,13 +590,13 @@
 }
 
 static arg_ty
-compiler_simple_arg(struct compiling *c, const node *n)
+compiler_arg(struct compiling *c, const node *n)
 {
     identifier name;
     expr_ty annotation = NULL;
     node *ch;
 
-    assert(TYPE(n) == tname || TYPE(n) == vname);
+    assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef);
     ch = CHILD(n, 0);
     if (!strcmp(STR(ch), "None")) {
         ast_error(ch, "assignment to None");
@@ -576,51 +612,12 @@
             return NULL;
     }
 
-    return SimpleArg(name, annotation, c->c_arena);
-}
-
-static arg_ty
-compiler_complex_args(struct compiling *c, const node *n)
-{
-    int i, len = (NCH(n) + 1) / 2;
-    arg_ty arg;
-    asdl_seq *args = asdl_seq_new(len, c->c_arena);
-    if (!args)
-        return NULL;
-
-    assert(TYPE(n) == tfplist || TYPE(n) == vfplist);
-    for (i = 0; i < len; i++) {
-        const node *child = CHILD(n, 2*i);
-        /* def foo(((x), y)): -- x is not nested complex, special case. */
-        while (NCH(child) == 3 && NCH(CHILD(child, 1)) == 1)
-            child = CHILD(CHILD(child, 1), 0);
-
-        /* child either holds a tname or '(', a tfplist, ')' */
-        switch (TYPE(CHILD(child, 0))) {
-        case tname:
-        case vname:
-            arg = compiler_simple_arg(c, CHILD(child, 0));
-            break;
-        case LPAR:
-            arg = compiler_complex_args(c, CHILD(child, 1));
-            break;
-        default:
-            PyErr_Format(PyExc_SystemError,
-                             "unexpected node in args: %d @ %d",
-                             TYPE(CHILD(child, 0)), i);
-            arg = NULL;
-        }
-        if (!arg)
-            return NULL;
-        asdl_seq_SET(args, i, arg);
-    }
-
-    return NestedArgs(args, c->c_arena);
+    return arg(name, annotation, c->c_arena);
 }
 
 /* returns -1 if failed to handle keyword only arguments
    returns new position to keep processing if successful
-               (',' tname ['=' test])*
+               (',' tfpdef ['=' test])*
                      ^^^
    start pointing here
  */
@@ -638,8 +635,8 @@
     while (i < NCH(n)) {
         ch = CHILD(n, i);
         switch (TYPE(ch)) {
-            case vname:
-            case tname:
+            case vfpdef:
+            case tfpdef:
                 if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
                     expression = ast_for_expr(c, CHILD(n, i + 2));
                     if (!expression) {
@@ -668,7 +665,7 @@
                     ast_error(ch, "assignment to None");
                     goto error;
                 }
-                arg = SimpleArg(NEW_IDENTIFIER(ch), annotation, c->c_arena);
+                arg = arg(NEW_IDENTIFIER(ch), annotation, c->c_arena);
                 if (!arg) {
                     ast_error(ch, "expecting name");
                     goto error;
@@ -698,13 +695,15 @@
 
        parameters: '(' [typedargslist] ')'
        typedargslist: ((tfpdef ['=' test] ',')*
-           ('*' [tname] (',' tname ['=' test])* [',' '**' tname]
-           | '**' tname)
+           ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] 
+           | '**' tfpdef)
            | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
+       tfpdef: NAME [':' test]
        varargslist: ((vfpdef ['=' test] ',')*
-           ('*' [vname] (',' vname ['=' test])*  [',' '**' vname]
-           | '**' vname)
+           ('*' [vfpdef] (',' vfpdef ['=' test])*  [',' '**' vfpdef] 
+           | '**' vfpdef)
            | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
+       vfpdef: NAME
     */
     int i, j, k, nposargs = 0, nkwonlyargs = 0;
     int nposdefaults = 0, found_default = 0;
@@ -726,17 +725,13 @@
     for (i = 0; i < NCH(n); i++) {
         ch = CHILD(n, i);
         if (TYPE(ch) == STAR) {
-            if (TYPE(CHILD(n, i+1)) == tname
-                || TYPE(CHILD(n, i+1)) == vname) {
-            /* skip NAME of vararg */
-            /* so that following can count only keyword only args */
-                i += 2;
-            }
-            else {
-                i++;
-            }
+            /* skip star and possible argument */
+            i++;
+            i += (TYPE(CHILD(n, i)) == tfpdef
+                  || TYPE(CHILD(n, i)) == vfpdef);
             break; 
         }
+        if (TYPE(ch) == DOUBLESTAR) break;
         if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++;
         if (TYPE(ch) == EQUAL) nposdefaults++;
     }
@@ -745,9 +740,8 @@
     for ( ; i < NCH(n); ++i) {
         ch = CHILD(n, i);
         if (TYPE(ch) == DOUBLESTAR) break;
-        if (TYPE(ch) == tname || TYPE(ch) == vname) nkwonlyargs++;
+        if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++;
     }
-
     posargs = (nposargs ? asdl_seq_new(nposargs, c->c_arena) : NULL);
     if (!posargs && nposargs)
         goto error;
@@ -772,12 +766,8 @@
         return NULL;
     }
 
-    /* tname: NAME [':' test]
-       tfpdef: tname | '(' tfplist ')'
-       tfplist: tfpdef (',' tfpdef)* [',']
-       vname: NAME
-       vfpdef: NAME | '(' vfplist ')'
-       vfplist: vfpdef (',' vfpdef)* [',']
+    /* tfpdef: NAME [':' test]
+       vfpdef: NAME
     */
     i = 0;
     j = 0;  /* index for defaults */
@@ -804,14 +794,7 @@
                              "non-default argument follows default argument");
                     goto error;
                 }
-                /* def foo((x)): is not complex, special case. */
-                while (NCH(ch) == 3 && NCH(CHILD(ch, 1)) == 1)
-                    ch = CHILD(CHILD(ch, 1), 0);
-
-                if (NCH(ch) != 1)
-                    arg = compiler_complex_args(c, CHILD(ch, 1));
-                else
-                    arg = compiler_simple_arg(c, CHILD(ch, 0));
+                arg = compiler_arg(c, ch);
                 if (!arg)
                     goto error;
                 asdl_seq_SET(posargs, k++, arg);
@@ -823,7 +806,7 @@
                     ast_error(CHILD(n, i), "no name for vararg");
                     goto error;
                 }
-                ch = CHILD(n, i+1);  /* tname or COMMA */
+                ch = CHILD(n, i+1);  /* tfpdef or COMMA */
                 if (TYPE(ch) == COMMA) {
                     int res = 0;
                     i += 2; /* now follows keyword only arguments */
@@ -839,12 +822,12 @@
                 else {
                     vararg = NEW_IDENTIFIER(CHILD(ch, 0));
                     if (NCH(ch) > 1) {
-                            /* there is an annotation on the vararg */
-                            varargannotation = ast_for_expr(c, CHILD(ch, 2));
+                        /* there is an annotation on the vararg */
+                        varargannotation = ast_for_expr(c, CHILD(ch, 2));
                     }
                     i += 3;
-                    if (i < NCH(n) && (TYPE(CHILD(n, i)) == tname
-                                    || TYPE(CHILD(n, i)) == vname)) {
+                    if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef
+                                    || TYPE(CHILD(n, i)) == vfpdef)) {
                         int res = 0;
                         res = handle_keywordonly_args(c, n, i,
                                                       kwonlyargs, kwdefaults);
@@ -854,8 +837,8 @@
                 }
                 break;
             case DOUBLESTAR:
-                ch = CHILD(n, i+1);  /* tname */
-                assert(TYPE(ch) == tname || TYPE(ch) == vname);
+                ch = CHILD(n, i+1);  /* tfpdef */
+                assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef);
                 if (!strcmp(STR(CHILD(ch, 0)), "None")) {
                         ast_error(CHILD(ch, 0), "assignment to None");
                         goto error;
@@ -972,28 +955,17 @@
 }
 
 static stmt_ty
-ast_for_funcdef(struct compiling *c, const node *n)
+ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
 {
-    /* funcdef: 'def' [decorators] NAME parameters ['->' test] ':' suite */
+    /* funcdef: 'def' NAME parameters ['->' test] ':' suite */
     identifier name;
     arguments_ty args;
     asdl_seq *body;
-    asdl_seq *decorator_seq = NULL;
     expr_ty returns = NULL;
-    int name_i;
+    int name_i = 1;
 
     REQ(n, funcdef);
 
-    if (NCH(n) == 6) { /* decorators are present */
-        decorator_seq = ast_for_decorators(c, CHILD(n, 0));
-        if (!decorator_seq)
-            return NULL;
-        name_i = 2;
-    }
-    else {
-        name_i = 1;
-    }
-
     name = NEW_IDENTIFIER(CHILD(n, name_i));
     if (!name)
         return NULL;
@@ -1018,10 +990,35 @@
                        n->n_col_offset, c->c_arena);
 }
 
+static stmt_ty
+ast_for_decorated(struct compiling *c, const node *n)
+{
+    /* decorated: decorators (classdef | funcdef) */
+    stmt_ty thing = NULL;
+    asdl_seq *decorator_seq = NULL;
+
+    REQ(n, decorated);
+
+    decorator_seq = ast_for_decorators(c, CHILD(n, 0));
+    if (!decorator_seq)
+      return NULL;
+
+    assert(TYPE(CHILD(n, 1)) == funcdef ||
+	   TYPE(CHILD(n, 1)) == classdef);
+
+    if (TYPE(CHILD(n, 1)) == funcdef) {
+      thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
+    } else if (TYPE(CHILD(n, 1)) == classdef) {
+      thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
+    }
+    return thing;
+}
+
 static expr_ty
 ast_for_lambdef(struct compiling *c, const node *n)
 {
-    /* lambdef: 'lambda' [varargslist] ':' test */
+    /* lambdef: 'lambda' [varargslist] ':' test
+       lambdef_nocond: 'lambda' [varargslist] ':' test_nocond */
     arguments_ty args;
     expr_ty expression;
 
@@ -1066,323 +1063,242 @@
                  c->c_arena);
 }
 
-/* XXX(nnorwitz): the listcomp and genexpr code should be refactored
-   so there is only a single version.  Possibly for loops can also re-use
-   the code.
-*/
-
-/* Count the number of 'for' loop in a list comprehension.
+/*
+   Count the number of 'for' loops in a comprehension.
 
-   Helper for ast_for_listcomp().
+   Helper for ast_for_comprehension().
 */
 
 static int
-count_list_fors(const node *n)
+count_comp_fors(const node *n)
 {
     int n_fors = 0;
-    node *ch = CHILD(n, 1);
 
- count_list_for:
+  count_comp_for:
     n_fors++;
-    REQ(ch, list_for);
-    if (NCH(ch) == 5)
-        ch = CHILD(ch, 4);
+    REQ(n, comp_for);
+    if (NCH(n) == 5)
+        n = CHILD(n, 4);
     else
         return n_fors;
- count_list_iter:
-    REQ(ch, list_iter);
-    ch = CHILD(ch, 0);
-    if (TYPE(ch) == list_for)
-        goto count_list_for;
-    else if (TYPE(ch) == list_if) {
-        if (NCH(ch) == 3) {
-            ch = CHILD(ch, 2);
-            goto count_list_iter;
+  count_comp_iter:
+    REQ(n, comp_iter);
+    n = CHILD(n, 0);
+    if (TYPE(n) == comp_for)
+        goto count_comp_for;
+    else if (TYPE(n) == comp_if) {
+        if (NCH(n) == 3) {
+            n = CHILD(n, 2);
+            goto count_comp_iter;
         }
         else
             return n_fors;
     }
 
     /* Should never be reached */
-    PyErr_SetString(PyExc_SystemError, "logic error in count_list_fors");
+    PyErr_SetString(PyExc_SystemError,
+                    "logic error in count_comp_fors");
     return -1;
 }
 
-/* Count the number of 'if' statements in a list comprehension.
+/* Count the number of 'if' statements in a comprehension.
 
-   Helper for ast_for_listcomp().
+   Helper for ast_for_comprehension().
 */
 
 static int
-count_list_ifs(const node *n)
+count_comp_ifs(const node *n)
 {
     int n_ifs = 0;
 
- count_list_iter:
-    REQ(n, list_iter);
-    if (TYPE(CHILD(n, 0)) == list_for)
-        return n_ifs;
-    n = CHILD(n, 0);
-    REQ(n, list_if);
-    n_ifs++;
-    if (NCH(n) == 2)
-        return n_ifs;
-    n = CHILD(n, 2);
-    goto count_list_iter;
+    while (1) {
+        REQ(n, comp_iter);
+        if (TYPE(CHILD(n, 0)) == comp_for)
+            return n_ifs;
+        n = CHILD(n, 0);
+        REQ(n, comp_if);
+        n_ifs++;
+        if (NCH(n) == 2)
+            return n_ifs;
+        n = CHILD(n, 2);
+    }
 }
 
+
 static expr_ty
-ast_for_listcomp(struct compiling *c, const node *n)
+ast_for_seqcomp(struct compiling *c, const node *n, int type)
 {
-    /* listmaker: test ( list_for | (',' test)* [','] )
-       list_for: 'for' exprlist 'in' testlist_safe [list_iter]
-       list_iter: list_for | list_if
-       list_if: 'if' test [list_iter]
-       testlist_safe: test [(',' test)+ [',']]
-    */
+    /* testlist_comp: test ( comp_for | (',' test)* [','] )
+       argument: [test '='] test [comp_for]       # Really [keyword '='] test */
     expr_ty elt;
-    asdl_seq *listcomps;
+    asdl_seq *comps;
     int i, n_fors;
     node *ch;
-
-    REQ(n, listmaker);
+    
     assert(NCH(n) > 1);
-
+    
     elt = ast_for_expr(c, CHILD(n, 0));
     if (!elt)
         return NULL;
-
-    n_fors = count_list_fors(n);
+    
+    n_fors = count_comp_fors(CHILD(n, 1));
     if (n_fors == -1)
         return NULL;
 
-    listcomps = asdl_seq_new(n_fors, c->c_arena);
-    if (!listcomps)
+    comps = asdl_seq_new(n_fors, c->c_arena);
+    if (!comps)
         return NULL;
 
-    ch = CHILD(n, 1);
+    if (ast_for_comprehension(c, CHILD(n, 1), n_fors, comps) < 0)
+        return NULL;
+
+    if (type == COMP_GENEXP)
+        return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
+    else if (type == COMP_LISTCOMP)
+        return ListComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
+    else if (type == COMP_SETCOMP)
+        return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
+    else
+        /* Should never happen */
+        return NULL;
+}
+
+static int
+ast_for_comprehension(struct compiling *c, const node *ch, int n_fors, asdl_seq *comps)
+{
+    int i;
+
     for (i = 0; i < n_fors; i++) {
-        comprehension_ty lc;
+        comprehension_ty comp;
         asdl_seq *t;
         expr_ty expression;
         node *for_ch;
-
-        REQ(ch, list_for);
-
+        
+        REQ(ch, comp_for);
+        
         for_ch = CHILD(ch, 1);
         t = ast_for_exprlist(c, for_ch, Store);
         if (!t)
-            return NULL;
-        expression = ast_for_testlist(c, CHILD(ch, 3));
+            return -1;
+        expression = ast_for_expr(c, CHILD(ch, 3));
         if (!expression)
-            return NULL;
+            return -1;
 
         /* Check the # of children rather than the length of t, since
-           [x for x, in ... ] has 1 element in t, but still requires a Tuple. */
+           (x for x, in ...) has 1 element in t, but still requires a Tuple. */
         if (NCH(for_ch) == 1)
-            lc = comprehension((expr_ty)asdl_seq_GET(t, 0), expression, NULL,
-                               c->c_arena);
+            comp = comprehension((expr_ty)asdl_seq_GET(t, 0), expression,
+                                 NULL, c->c_arena);
         else
-            lc = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset,
-                                     c->c_arena),
-                               expression, NULL, c->c_arena);
-        if (!lc)
-            return NULL;
+            comp = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset,
+                                       c->c_arena),
+                                 expression, NULL, c->c_arena);
+
+        if (!comp)
+            return -1;
 
         if (NCH(ch) == 5) {
             int j, n_ifs;
             asdl_seq *ifs;
-
+            
             ch = CHILD(ch, 4);
-            n_ifs = count_list_ifs(ch);
+            n_ifs = count_comp_ifs(ch);
             if (n_ifs == -1)
-                return NULL;
+                return -1;
 
             ifs = asdl_seq_new(n_ifs, c->c_arena);
             if (!ifs)
-                return NULL;
+                return -1;
 
             for (j = 0; j < n_ifs; j++) {
-            REQ(ch, list_iter);
-                    ch = CHILD(ch, 0);
-                    REQ(ch, list_if);
-
-                asdl_seq_SET(ifs, j, ast_for_expr(c, CHILD(ch, 1)));
+                REQ(ch, comp_iter);
+                ch = CHILD(ch, 0);
+                REQ(ch, comp_if);
+                
+                expression = ast_for_expr(c, CHILD(ch, 1));
+                if (!expression)
+                    return -1;
+                asdl_seq_SET(ifs, j, expression);
                 if (NCH(ch) == 3)
                     ch = CHILD(ch, 2);
-                }
-                /* on exit, must guarantee that ch is a list_for */
-                if (TYPE(ch) == list_iter)
-                        ch = CHILD(ch, 0);
-            lc->ifs = ifs;
             }
-            asdl_seq_SET(listcomps, i, lc);
+            /* on exit, must guarantee that ch is a comp_for */
+            if (TYPE(ch) == comp_iter)
+                ch = CHILD(ch, 0);
+            comp->ifs = ifs;
+        }
+        asdl_seq_SET(comps, i, comp);
     }
-
-    return ListComp(elt, listcomps, LINENO(n), n->n_col_offset, c->c_arena);
+    return 0;
 }
 
-/*
-   Count the number of 'for' loops in a generator expression.
-
-   Helper for ast_for_genexp().
-*/
-
-static int
-count_gen_fors(const node *n)
+static expr_ty
+ast_for_genexp(struct compiling *c, const node *n)
 {
-        int n_fors = 0;
-        node *ch = CHILD(n, 1);
-
- count_gen_for:
-        n_fors++;
-        REQ(ch, gen_for);
-        if (NCH(ch) == 5)
-                ch = CHILD(ch, 4);
-        else
-                return n_fors;
- count_gen_iter:
-        REQ(ch, gen_iter);
-        ch = CHILD(ch, 0);
-        if (TYPE(ch) == gen_for)
-                goto count_gen_for;
-        else if (TYPE(ch) == gen_if) {
-                if (NCH(ch) == 3) {
-                        ch = CHILD(ch, 2);
-                        goto count_gen_iter;
-                }
-                else
-                    return n_fors;
-        }
-
-        /* Should never be reached */
-        PyErr_SetString(PyExc_SystemError,
-                        "logic error in count_gen_fors");
-        return -1;
+    assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument));
+    return ast_for_comprehension(c, n, COMP_GENEXP);
 }
 
-/* Count the number of 'if' statements in a generator expression.
-
-   Helper for ast_for_genexp().
-*/
-
-static int
-count_gen_ifs(const node *n)
+static expr_ty
+ast_for_listcomp(struct compiling *c, const node *n)
 {
-        int n_ifs = 0;
+    assert(TYPE(n) == (testlist_comp));
+    return ast_for_comprehension(c, n, COMP_LISTCOMP);
+}
 
-        while (1) {
-                REQ(n, gen_iter);
-                if (TYPE(CHILD(n, 0)) == gen_for)
-                        return n_ifs;
-                n = CHILD(n, 0);
-                REQ(n, gen_if);
-                n_ifs++;
-                if (NCH(n) == 2)
-                        return n_ifs;
-                n = CHILD(n, 2);
-        }
+static expr_ty
+ast_for_setcomp(struct compiling *c, const node *n)
+{
+    assert(TYPE(n) == (dictorsetmaker));
+    return ast_for_comprehension(c, n, COMP_SETCOMP);
 }
 
-/* TODO(jhylton): Combine with list comprehension code? */
 static expr_ty
-ast_for_genexp(struct compiling *c, const node *n)
+ast_for_dictcomp(struct compiling *c, const node *n)
 {
-    /* testlist_gexp: test ( gen_for | (',' test)* [','] )
-       argument: [test '='] test [gen_for]       # Really [keyword '='] test */
-    expr_ty elt;
-    asdl_seq *genexps;
+    /* dict(orset)maker: test ':' test ( comp_for | (',' test ':' test)* [','] )
+       comp_iter: comp_for | comp_if
+       comp_for: 'for' exprlist 'in' or_test [comp_iter]
+       comp_if: 'if' test_nocond [comp_iter]
+     */
+    expr_ty key, value;
+    asdl_seq *comps;
     int i, n_fors;
     node *ch;
     
-    assert(TYPE(n) == (testlist_gexp) || TYPE(n) == (argument));
-    assert(NCH(n) > 1);
+    assert(NCH(n) > 3);
+    REQ(CHILD(n, 1), COLON);
     
-    elt = ast_for_expr(c, CHILD(n, 0));
-    if (!elt)
+    key = ast_for_expr(c, CHILD(n, 0));
+    if (!key)
+        return NULL;
+    value = ast_for_expr(c, CHILD(n, 2));
+    if (!value)
         return NULL;
     
-    n_fors = count_gen_fors(n);
+    n_fors = count_comp_fors(CHILD(n, 3));
     if (n_fors == -1)
         return NULL;
 
-    genexps = asdl_seq_new(n_fors, c->c_arena);
-    if (!genexps)
+    comps = asdl_seq_new(n_fors, c->c_arena);
+    if (!comps)
         return NULL;
 
-    ch = CHILD(n, 1);
-    for (i = 0; i < n_fors; i++) {
-        comprehension_ty ge;
-        asdl_seq *t;
-        expr_ty expression;
-        node *for_ch;
-        
-        REQ(ch, gen_for);
-        
-        for_ch = CHILD(ch, 1);
-        t = ast_for_exprlist(c, for_ch, Store);
-        if (!t)
-            return NULL;
-        expression = ast_for_expr(c, CHILD(ch, 3));
-        if (!expression)
-            return NULL;
-
-        /* Check the # of children rather than the length of t, since
-           (x for x, in ...) has 1 element in t, but still requires a Tuple. */
-        if (NCH(for_ch) == 1)
-            ge = comprehension((expr_ty)asdl_seq_GET(t, 0), expression,
-                               NULL, c->c_arena);
-        else
-            ge = comprehension(Tuple(t, Store, LINENO(ch), ch->n_col_offset,
-                                     c->c_arena),
-                               expression, NULL, c->c_arena);
-
-        if (!ge)
-            return NULL;
-
-        if (NCH(ch) == 5) {
-            int j, n_ifs;
-            asdl_seq *ifs;
-            
-            ch = CHILD(ch, 4);
-            n_ifs = count_gen_ifs(ch);
-            if (n_ifs == -1)
-                return NULL;
-
-            ifs = asdl_seq_new(n_ifs, c->c_arena);
-            if (!ifs)
-                return NULL;
+    if (ast_for_comprehension(c, CHILD(n, 3), n_fors, comps) < 0)
+        return NULL;
 
-            for (j = 0; j < n_ifs; j++) {
-                REQ(ch, gen_iter);
-                ch = CHILD(ch, 0);
-                REQ(ch, gen_if);
-                
-                expression = ast_for_expr(c, CHILD(ch, 1));
-                if (!expression)
-                    return NULL;
-                asdl_seq_SET(ifs, j, expression);
-                if (NCH(ch) == 3)
-                    ch = CHILD(ch, 2);
-            }
-            /* on exit, must guarantee that ch is a gen_for */
-            if (TYPE(ch) == gen_iter)
-                ch = CHILD(ch, 0);
-            ge->ifs = ifs;
-        }
-        asdl_seq_SET(genexps, i, ge);
-    }
-    
-    return GeneratorExp(elt, genexps, LINENO(n), n->n_col_offset, c->c_arena);
+    return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena);
 }
 
 static expr_ty
 ast_for_atom(struct compiling *c, const node *n)
 {
-    /* atom: '(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']'
-       | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING+
+    /* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']'
+       | '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+
+       | '...' | 'None' | 'True' | 'False'
     */
     node *ch = CHILD(n, 0);
+    int bytesmode = 0;
     
     switch (TYPE(ch)) {
     case NAME:
@@ -1390,12 +1306,15 @@
            changed. */
         return Name(NEW_IDENTIFIER(ch), Load, LINENO(n), n->n_col_offset, c->c_arena);
     case STRING: {
-        PyObject *str = parsestrplus(c, n);
+        PyObject *str = parsestrplus(c, n, &bytesmode);
         if (!str)
             return NULL;
 
         PyArena_AddPyObject(c->c_arena, str);
-        return Str(str, LINENO(n), n->n_col_offset, c->c_arena);
+        if (bytesmode)
+            return Bytes(str, LINENO(n), n->n_col_offset, c->c_arena);
+        else
+            return Str(str, LINENO(n), n->n_col_offset, c->c_arena);
     }
     case NUMBER: {
         PyObject *pynum = parsenumber(STR(ch));
@@ -1405,7 +1324,7 @@
         PyArena_AddPyObject(c->c_arena, pynum);
         return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
     }
-    case DOT: /* Ellipsis */
+    case ELLIPSIS: /* Ellipsis */
         return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena);
     case LPAR: /* some parenthesized expressions */
         ch = CHILD(n, 1);
@@ -1415,18 +1334,19 @@
         
         if (TYPE(ch) == yield_expr)
             return ast_for_expr(c, ch);
-        
-        if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == gen_for))
+
+        /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ 
+        if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for))
             return ast_for_genexp(c, ch);
         
-        return ast_for_testlist_gexp(c, ch);
+        return ast_for_testlist(c, ch);
     case LSQB: /* list (or list comprehension) */
         ch = CHILD(n, 1);
         
         if (TYPE(ch) == RSQB)
             return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
         
-        REQ(ch, listmaker);
+        REQ(ch, testlist_comp);
         if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
             asdl_seq *elts = seq_for_testlist(c, ch);
             if (!elts)
@@ -1437,27 +1357,37 @@
         else
             return ast_for_listcomp(c, ch);
     case LBRACE: {
-        /* dictsetmaker: test ':' test (',' test ':' test)* [','] |
-         *               test (',' test)* [',']  */
+        /* dictorsetmaker: test ':' test (',' test ':' test)* [','] |
+         *                 test (gen_for | (',' test)* [','])  */
         int i, size;
         asdl_seq *keys, *values;
 
         ch = CHILD(n, 1);
-        if (NCH(ch) == 1 || (NCH(ch) > 0 && STR(CHILD(ch, 1))[0] == ',')) {
-            /* it's a set */
+        if (TYPE(ch) == RBRACE) {
+            /* it's an empty dict */
+            return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
+        } else if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
+            /* it's a simple set */
+            asdl_seq *elts;
             size = (NCH(ch) + 1) / 2; /* +1 in case no trailing comma */
-            keys = asdl_seq_new(size, c->c_arena);
-            if (!keys)
+            elts = asdl_seq_new(size, c->c_arena);
+            if (!elts)
                 return NULL;
-
             for (i = 0; i < NCH(ch); i += 2) {
                 expr_ty expression;
                 expression = ast_for_expr(c, CHILD(ch, i));
                 if (!expression)
                     return NULL;
-                asdl_seq_SET(keys, i / 2, expression);
+                asdl_seq_SET(elts, i / 2, expression);
             }
-            return Set(keys, LINENO(n), n->n_col_offset, c->c_arena);
+            return Set(elts, LINENO(n), n->n_col_offset, c->c_arena);
+        } else if (TYPE(CHILD(ch, 1)) == comp_for) {
+            /* it's a set comprehension */
+            return ast_for_setcomp(c, ch);
+        } else if (NCH(ch) > 3 && TYPE(CHILD(ch, 3)) == comp_for) {
+            /* it's a dict comprehension */
+            return ast_for_dictcomp(c, ch);
+        }
         } else {
             /* it's a dict */
             size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */
@@ -1568,53 +1498,53 @@
 static expr_ty
 ast_for_binop(struct compiling *c, const node *n)
 {
-        /* Must account for a sequence of expressions.
-           How should A op B op C by represented?  
-           BinOp(BinOp(A, op, B), op, C).
-        */
+    /* Must account for a sequence of expressions.
+       How should A op B op C by represented?  
+       BinOp(BinOp(A, op, B), op, C).
+    */
 
-        int i, nops;
-        expr_ty expr1, expr2, result;
-        operator_ty newoperator;
+    int i, nops;
+    expr_ty expr1, expr2, result;
+    operator_ty newoperator;
 
-        expr1 = ast_for_expr(c, CHILD(n, 0));
-        if (!expr1)
-            return NULL;
+    expr1 = ast_for_expr(c, CHILD(n, 0));
+    if (!expr1)
+        return NULL;
 
-        expr2 = ast_for_expr(c, CHILD(n, 2));
-        if (!expr2)
-            return NULL;
+    expr2 = ast_for_expr(c, CHILD(n, 2));
+    if (!expr2)
+        return NULL;
 
-        newoperator = get_operator(CHILD(n, 1));
-        if (!newoperator)
-            return NULL;
+    newoperator = get_operator(CHILD(n, 1));
+    if (!newoperator)
+        return NULL;
 
-        result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
-                       c->c_arena);
-        if (!result)
-            return NULL;
+    result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
+                   c->c_arena);
+    if (!result)
+        return NULL;
 
-        nops = (NCH(n) - 1) / 2;
-        for (i = 1; i < nops; i++) {
-                expr_ty tmp_result, tmp;
-                const node* next_oper = CHILD(n, i * 2 + 1);
+    nops = (NCH(n) - 1) / 2;
+    for (i = 1; i < nops; i++) {
+        expr_ty tmp_result, tmp;
+        const node* next_oper = CHILD(n, i * 2 + 1);
 
-                newoperator = get_operator(next_oper);
-                if (!newoperator)
-                    return NULL;
+        newoperator = get_operator(next_oper);
+        if (!newoperator)
+            return NULL;
 
-                tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
-                if (!tmp)
-                    return NULL;
+        tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
+        if (!tmp)
+            return NULL;
 
-                tmp_result = BinOp(result, newoperator, tmp, 
-                                   LINENO(next_oper), next_oper->n_col_offset,
-                                   c->c_arena);
-                if (!tmp) 
-                        return NULL;
-                result = tmp_result;
-        }
-        return result;
+        tmp_result = BinOp(result, newoperator, tmp, 
+                           LINENO(next_oper), next_oper->n_col_offset,
+                           c->c_arena);
+        if (!tmp) 
+            return NULL;
+        result = tmp_result;
+    }
+    return result;
 }
 
 static expr_ty
@@ -1655,7 +1585,7 @@
             int j;
             slice_ty slc;
             expr_ty e;
-            bool simple = true;
+            int simple = 1;
             asdl_seq *slices, *elts;
             slices = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
             if (!slices)
@@ -1665,7 +1595,7 @@
                 if (!slc)
                     return NULL;
                 if (slc->kind != Index_kind)
-                    simple = false;
+                    simple = 0;
                 asdl_seq_SET(slices, j / 2, slc);
             }
             if (!simple) {
@@ -1777,6 +1707,21 @@
     return e;
 }
 
+static expr_ty
+ast_for_starred(struct compiling *c, const node *n)
+{
+    expr_ty tmp;
+    REQ(n, star_expr);
+
+    tmp = ast_for_expr(c, CHILD(n, 1));
+    if (!tmp)
+        return NULL;
+
+    /* The Load context is changed later. */
+    return Starred(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
+}
+
+
 /* Do not name a variable 'expr'!  Will cause a compile error.
 */
 
@@ -1785,6 +1730,7 @@
 {
     /* handle the full range of simple expressions
        test: or_test ['if' or_test 'else' test] | lambdef
+       test_nocond: or_test | lambdef_nocond
        or_test: and_test ('or' and_test)* 
        and_test: not_test ('and' not_test)*
        not_test: 'not' not_test | comparison
@@ -1797,15 +1743,6 @@
        term: factor (('*'|'/'|'%'|'//') factor)*
        factor: ('+'|'-'|'~') factor | power
        power: atom trailer* ('**' factor)*
-
-       As well as modified versions that exist for backward compatibility,
-       to explicitly allow:
-       [ x for x in lambda: 0, lambda: 1 ]
-       (which would be ambiguous without these extra rules)
-       
-       old_test: or_test | old_lambdef
-       old_lambdef: 'lambda' [vararglist] ':' old_test
-
     */
 
     asdl_seq *seq;
@@ -1814,9 +1751,9 @@
  loop:
     switch (TYPE(n)) {
         case test:
-        case old_test:
+        case test_nocond:
             if (TYPE(CHILD(n, 0)) == lambdef ||
-                TYPE(CHILD(n, 0)) == old_lambdef)
+                TYPE(CHILD(n, 0)) == lambdef_nocond)
                 return ast_for_lambdef(c, CHILD(n, 0));
             else if (NCH(n) > 1)
                 return ast_for_ifexpr(c, n);
@@ -1896,6 +1833,11 @@
             }
             break;
 
+        case star_expr:
+            if (TYPE(CHILD(n, 0)) == STAR) {
+                return ast_for_starred(c, n);
+            }
+            /* Fallthrough */
         /* The next five cases all handle BinOps.  The main body of code
            is the same in each case, but the switch turned inside out to
            reuse the code for each type of operator.
@@ -1942,7 +1884,7 @@
     /*
       arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
                | '**' test)
-      argument: [test '='] test [gen_for]        # Really [keyword '='] test
+      argument: [test '='] test [comp_for]        # Really [keyword '='] test
     */
 
     int i, nargs, nkeywords, ngens;
@@ -1960,7 +1902,7 @@
         if (TYPE(ch) == argument) {
             if (NCH(ch) == 1)
                 nargs++;
-            else if (TYPE(CHILD(ch, 1)) == gen_for)
+            else if (TYPE(CHILD(ch, 1)) == comp_for)
                 ngens++;
             else
                 nkeywords++;
@@ -2000,7 +1942,7 @@
                     return NULL;
                 asdl_seq_SET(args, nargs++, e);
             }  
-            else if (TYPE(CHILD(ch, 1)) == gen_for) {
+            else if (TYPE(CHILD(ch, 1)) == comp_for) {
                 e = ast_for_genexp(c, ch);
                 if (!e)
                     return NULL;
@@ -2025,8 +1967,14 @@
                 } else if (e->kind != Name_kind) {
                   ast_error(CHILD(ch, 0), "keyword can't be an expression");
                   return NULL;
-                }
+                } else if (forbidden_name(e, ch)) {
+		  return NULL;
+		}
                 key = e->v.Name.id;
+                if (!strcmp(PyString_AS_STRING(key), "None")) {
+                    ast_error(CHILD(ch, 0), "assignment to None");
+                    return NULL;
+                }
                 e = ast_for_expr(c, CHILD(ch, 2));
                 if (!e)
                     return NULL;
@@ -2052,18 +2000,16 @@
 static expr_ty
 ast_for_testlist(struct compiling *c, const node* n)
 {
-    /* testlist_gexp: test (',' test)* [','] */
+    /* testlist_comp: test (comp_for | (',' test)* [',']) */
     /* testlist: test (',' test)* [','] */
-    /* testlist_safe: test (',' test)+ [','] */
     /* testlist1: test (',' test)* */
     assert(NCH(n) > 0);
-    if (TYPE(n) == testlist_gexp) {
+    if (TYPE(n) == testlist_comp) {
         if (NCH(n) > 1)
-            assert(TYPE(CHILD(n, 1)) != gen_for);
+            assert(TYPE(CHILD(n, 1)) != comp_for);
     }
     else {
         assert(TYPE(n) == testlist ||
-               TYPE(n) == testlist_safe ||
                TYPE(n) == testlist1);
     }
     if (NCH(n) == 1)
@@ -2076,39 +2022,6 @@
     }
 }
 
-static expr_ty
-ast_for_testlist_gexp(struct compiling *c, const node* n)
-{
-    /* testlist_gexp: test ( gen_for | (',' test)* [','] ) */
-    /* argument: test [ gen_for ] */
-    assert(TYPE(n) == testlist_gexp || TYPE(n) == argument);
-    if (NCH(n) > 1 && TYPE(CHILD(n, 1)) == gen_for)
-        return ast_for_genexp(c, n);
-    return ast_for_testlist(c, n);
-}
-
-/* like ast_for_testlist() but returns a sequence */
-static asdl_seq*
-ast_for_class_bases(struct compiling *c, const node* n)
-{
-    /* testlist: test (',' test)* [','] */
-    assert(NCH(n) > 0);
-    REQ(n, testlist);
-    if (NCH(n) == 1) {
-        expr_ty base;
-        asdl_seq *bases = asdl_seq_new(1, c->c_arena);
-        if (!bases)
-            return NULL;
-        base = ast_for_expr(c, CHILD(n, 0));
-        if (!base)
-            return NULL;
-        asdl_seq_SET(bases, 0, base);
-        return bases;
-    }
-
-    return seq_for_testlist(c, n);
-}
-
 static stmt_ty
 ast_for_expr_stmt(struct compiling *c, const node *n)
 {
@@ -2147,11 +2060,8 @@
                           "expression not possible");
                 return NULL;
             case Name_kind: {
-                const char *var_name = PyString_AS_STRING(expr1->v.Name.id);
-                if (var_name[0] == 'N' && !strcmp(var_name, "None")) {
-                    ast_error(ch, "assignment to None");
+                if (forbidden_name(expr1, ch))
                     return NULL;
-                }
                 break;
             }
             case Attribute_kind:
@@ -2423,8 +2333,8 @@
     /*
       import_stmt: import_name | import_from
       import_name: 'import' dotted_as_names
-      import_from: 'from' ('.'* dotted_name | '.') 'import'
-                          ('*' | '(' import_as_names ')' | import_as_names)
+      import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+)
+                   'import' ('*' | '(' import_as_names ')' | import_as_names)
     */
     int lineno;
     int col_offset;
@@ -2462,6 +2372,10 @@
                 mod = alias_for_import_name(c, CHILD(n, idx));
                 idx++;
                 break;
+            } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) {
+                /* three consecutive dots are tokenized as one ELLIPSIS */ 
+                ndots += 3;
+                continue;
             } else if (TYPE(CHILD(n, idx)) != DOT) {
                 break;
             }
@@ -2552,6 +2466,27 @@
 }
 
 static stmt_ty
+ast_for_nonlocal_stmt(struct compiling *c, const node *n)
+{
+    /* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */
+    identifier name;
+    asdl_seq *s;
+    int i;
+
+    REQ(n, nonlocal_stmt);
+    s = asdl_seq_new(NCH(n) / 2, c->c_arena);
+    if (!s)
+        return NULL;
+    for (i = 1; i < NCH(n); i += 2) {
+        name = NEW_IDENTIFIER(CHILD(n, i));
+        if (!name)
+            return NULL;
+        asdl_seq_SET(s, i / 2, name);
+    }
+    return Nonlocal(s, LINENO(n), n->n_col_offset, c->c_arena);
+}
+
+static stmt_ty
 ast_for_assert_stmt(struct compiling *c, const node *n)
 {
     /* assert_stmt: 'assert' test [',' test] */
@@ -2667,7 +2602,8 @@
         if (!suite_seq)
             return NULL;
             
-        return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena);
+        return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
+                  c->c_arena);
     }
 
     s = STR(CHILD(n, 4));
@@ -2689,10 +2625,13 @@
         if (!seq2)
             return NULL;
 
-        return If(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena);
+        return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
+                  c->c_arena);
     }
     else if (s[2] == 'i') {
         int i, n_elif, has_else = 0;
+        expr_ty expression;
+        asdl_seq *suite_seq;
         asdl_seq *orelse = NULL;
         n_elif = NCH(n) - 4;
         /* must reference the child n_elif+1 since 'else' token is third,
@@ -2705,8 +2644,7 @@
         n_elif /= 4;
 
         if (has_else) {
-            expr_ty expression;
-            asdl_seq *seq1, *seq2;
+            asdl_seq *suite_seq2;
 
             orelse = asdl_seq_new(1, c->c_arena);
             if (!orelse)
@@ -2714,24 +2652,24 @@
             expression = ast_for_expr(c, CHILD(n, NCH(n) - 6));
             if (!expression)
                 return NULL;
-            seq1 = ast_for_suite(c, CHILD(n, NCH(n) - 4));
-            if (!seq1)
+            suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4));
+            if (!suite_seq)
                 return NULL;
-            seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
-            if (!seq2)
+            suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
+            if (!suite_seq2)
                 return NULL;
 
-            asdl_seq_SET(orelse, 0, If(expression, seq1, seq2, 
-                                       LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset,
-                                       c->c_arena));
+            asdl_seq_SET(orelse, 0, 
+                         If(expression, suite_seq, suite_seq2, 
+                            LINENO(CHILD(n, NCH(n) - 6)),
+                            CHILD(n, NCH(n) - 6)->n_col_offset,
+                            c->c_arena));
             /* the just-created orelse handled the last elif */
             n_elif--;
         }
 
         for (i = 0; i < n_elif; i++) {
             int off = 5 + (n_elif - i - 1) * 4;
-            expr_ty expression;
-            asdl_seq *suite_seq;
             asdl_seq *newobj = asdl_seq_new(1, c->c_arena);
             if (!newobj)
                 return NULL;
@@ -2744,12 +2682,18 @@
 
             asdl_seq_SET(newobj, 0,
                          If(expression, suite_seq, orelse, 
-                            LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena));
+                            LINENO(CHILD(n, off)),
+                            CHILD(n, off)->n_col_offset, c->c_arena));
             orelse = newobj;
         }
-        return If(ast_for_expr(c, CHILD(n, 1)),
-                  ast_for_suite(c, CHILD(n, 3)),
-                  orelse, LINENO(n), n->n_col_offset, c->c_arena);
+        expression = ast_for_expr(c, CHILD(n, 1));
+        if (!expression)
+            return NULL;
+        suite_seq = ast_for_suite(c, CHILD(n, 3));
+        if (!suite_seq)
+            return NULL;
+        return If(expression, suite_seq, orelse,
+                  LINENO(n), n->n_col_offset, c->c_arena);
     }
 
     PyErr_Format(PyExc_SystemError,
@@ -2839,7 +2783,7 @@
 static excepthandler_ty
 ast_for_except_clause(struct compiling *c, const node *exc, node *body)
 {
-    /* except_clause: 'except' [test [',' test]] */
+    /* except_clause: 'except' [test ['as' test]] */
     REQ(exc, except_clause);
     REQ(body, suite);
 
@@ -3004,11 +2948,12 @@
 }
 
 static stmt_ty
-ast_for_classdef(struct compiling *c, const node *n)
+ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
 {
-    /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
-    asdl_seq *bases, *s;
-    
+    /* classdef: 'class' NAME ['(' arglist ')'] ':' suite */
+    asdl_seq *s;
+    expr_ty call, dummy;
+
     REQ(n, classdef);
 
     if (!strcmp(STR(CHILD(n, 1)), "None")) {
@@ -3016,32 +2961,36 @@
             return NULL;
     }
 
-    if (NCH(n) == 4) {
+    if (NCH(n) == 4) { /* class NAME ':' suite */
         s = ast_for_suite(c, CHILD(n, 3));
         if (!s)
             return NULL;
-        return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, s, LINENO(n),
-                        n->n_col_offset, c->c_arena);
+        return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, NULL, NULL, NULL, s,
+                        decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
     }
-    /* check for empty base list */
-    if (TYPE(CHILD(n,3)) == RPAR) {
+
+    if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */
         s = ast_for_suite(c, CHILD(n,5));
         if (!s)
                 return NULL;
-        return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, s, LINENO(n),
-                        n->n_col_offset, c->c_arena);
+        return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, NULL, NULL, NULL, s,
+                        decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
     }
 
-    /* else handle the base class list */
-    bases = ast_for_class_bases(c, CHILD(n, 3));
-    if (!bases)
+    /* class NAME '(' arglist ')' ':' suite */
+    /* build up a fake Call node so we can extract its pieces */
+    dummy = Name(NEW_IDENTIFIER(CHILD(n, 1)), Load, LINENO(n), n->n_col_offset, c->c_arena);
+    call = ast_for_call(c, CHILD(n, 3), dummy);
+    if (!call)
         return NULL;
-
     s = ast_for_suite(c, CHILD(n, 6));
     if (!s)
         return NULL;
-    return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), bases, s, LINENO(n),
-                    n->n_col_offset, c->c_arena);
+
+    return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)),
+                    call->v.Call.args, call->v.Call.keywords,
+                    call->v.Call.starargs, call->v.Call.kwargs, s,
+                    decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
 }
 
 static stmt_ty
@@ -3058,8 +3007,8 @@
     if (TYPE(n) == small_stmt) {
         REQ(n, small_stmt);
         n = CHILD(n, 0);
-        /* small_stmt: expr_stmt | del_stmt | pass_stmt
-                     | flow_stmt | import_stmt | global_stmt | assert_stmt
+        /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt
+                  | import_stmt | global_stmt | nonlocal_stmt | assert_stmt
         */
         switch (TYPE(n)) {
             case expr_stmt:
@@ -3074,6 +3023,8 @@
                 return ast_for_import_stmt(c, n);
             case global_stmt:
                 return ast_for_global_stmt(c, n);
+            case nonlocal_stmt:
+                return ast_for_nonlocal_stmt(c, n);
             case assert_stmt:
                 return ast_for_assert_stmt(c, n);
             default:
@@ -3085,7 +3036,7 @@
     }
     else {
         /* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
-                        | funcdef | classdef
+                        | funcdef | classdef | decorated
         */
         node *ch = CHILD(n, 0);
         REQ(n, compound_stmt);
@@ -3101,9 +3052,11 @@
             case with_stmt:
                 return ast_for_with_stmt(c, ch);
             case funcdef:
-                return ast_for_funcdef(c, ch);
+                return ast_for_funcdef(c, ch, NULL);
             case classdef:
-                return ast_for_classdef(c, ch);
+                return ast_for_classdef(c, ch, NULL);
+	    case decorated:
+	        return ast_for_decorated(c, ch);
             default:
                 PyErr_Format(PyExc_SystemError,
                              "unhandled small_stmt: TYPE=%d NCH=%d\n",
@@ -3116,137 +3069,135 @@
 static PyObject *
 parsenumber(const char *s)
 {
-        const char *end;
-        long x;
-        double dx;
+    const char *end;
+    long x;
+    double dx;
 #ifndef WITHOUT_COMPLEX
-        Py_complex c;
-        int imflag;
+    Py_complex c;
+    int imflag;
 #endif
 
-        errno = 0;
-        end = s + strlen(s) - 1;
+    errno = 0;
+    end = s + strlen(s) - 1;
 #ifndef WITHOUT_COMPLEX
-        imflag = *end == 'j' || *end == 'J';
+    imflag = *end == 'j' || *end == 'J';
 #endif
-        if (*end == 'l' || *end == 'L')
-                return PyLong_FromString((char *)s, (char **)0, 0);
-        if (s[0] == '0') {
-                x = (long) PyOS_strtoul((char *)s, (char **)&end, 0);
-                if (x < 0 && errno == 0) {
-                                return PyLong_FromString((char *)s,
-                                                         (char **)0,
-                                                         0);
-                }
-        }
-        else
-                x = PyOS_strtol((char *)s, (char **)&end, 0);
-        if (*end == '\0') {
-                if (errno != 0)
-                        return PyLong_FromString((char *)s, (char **)0, 0);
-                return PyInt_FromLong(x);
+    if (s[0] == '0') {
+        x = (long) PyOS_strtoul((char *)s, (char **)&end, 0);
+        if (x < 0 && errno == 0) {
+            return PyLong_FromString((char *)s,
+                                     (char **)0,
+                                     0);
         }
-        /* XXX Huge floats may silently fail */
+    }
+    else
+        x = PyOS_strtol((char *)s, (char **)&end, 0);
+    if (*end == '\0') {
+        if (errno != 0)
+            return PyLong_FromString((char *)s, (char **)0, 0);
+        return PyInt_FromLong(x);
+    }
+    /* XXX Huge floats may silently fail */
 #ifndef WITHOUT_COMPLEX
-        if (imflag) {
-                c.real = 0.;
-                PyFPE_START_PROTECT("atof", return 0)
-                c.imag = PyOS_ascii_atof(s);
-                PyFPE_END_PROTECT(c)
-                return PyComplex_FromCComplex(c);
-        }
-        else
+    if (imflag) {
+        c.real = 0.;
+        PyFPE_START_PROTECT("atof", return 0)
+            c.imag = PyOS_ascii_atof(s);
+        PyFPE_END_PROTECT(c)
+            return PyComplex_FromCComplex(c);
+    }
+    else
 #endif
-        {
-                PyFPE_START_PROTECT("atof", return 0)
-                dx = PyOS_ascii_atof(s);
-                PyFPE_END_PROTECT(dx)
-                return PyFloat_FromDouble(dx);
-        }
+    {
+        PyFPE_START_PROTECT("atof", return 0)
+            dx = PyOS_ascii_atof(s);
+        PyFPE_END_PROTECT(dx)
+            return PyFloat_FromDouble(dx);
+    }
 }
 
 static PyObject *
 decode_utf8(const char **sPtr, const char *end, char* encoding)
 {
 #ifndef Py_USING_UNICODE
-        Py_FatalError("decode_utf8 should not be called in this build.");
-        return NULL;
+    Py_FatalError("decode_utf8 should not be called in this build.");
+    return NULL;
 #else
-        PyObject *u, *v;
-        char *s, *t;
-        t = s = (char *)*sPtr;
-        /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
-        while (s < end && (*s & 0x80)) s++;
-        *sPtr = s;
-        u = PyUnicode_DecodeUTF8(t, s - t, NULL);
-        if (u == NULL)
-                return NULL;
-        v = PyUnicode_AsEncodedString(u, encoding, NULL);
-        Py_DECREF(u);
-        return v;
+    PyObject *u, *v;
+    char *s, *t;
+    t = s = (char *)*sPtr;
+    /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
+    while (s < end && (*s & 0x80)) s++;
+    *sPtr = s;
+    u = PyUnicode_DecodeUTF8(t, s - t, NULL);
+    if (u == NULL)
+        return NULL;
+    v = PyUnicode_AsEncodedString(u, encoding, NULL);
+    Py_DECREF(u);
+    return v;
 #endif
 }
 
 static PyObject *
 decode_unicode(const char *s, size_t len, int rawmode, const char *encoding)
 {
-        PyObject *v, *u;
-        char *buf;
-        char *p;
-        const char *end;
-        if (encoding == NULL) {
-                buf = (char *)s;
-                u = NULL;
-        } else if (strcmp(encoding, "iso-8859-1") == 0) {
-                buf = (char *)s;
-                u = NULL;
-        } else {
-                /* "\XX" may become "\u005c\uHHLL" (12 bytes) */
-                u = PyString_FromStringAndSize((char *)NULL, len * 4);
-                if (u == NULL)
-                        return NULL;
-                p = buf = PyString_AsString(u);
-                end = s + len;
-                while (s < end) {
-                        if (*s == '\\') {
-                                *p++ = *s++;
-                                if (*s & 0x80) {
-                                        strcpy(p, "u005c");
-                                        p += 5;
-                                }
-                        }
-                        if (*s & 0x80) { /* XXX inefficient */
-                                PyObject *w;
-                                char *r;
-                                Py_ssize_t rn, i;
-                                w = decode_utf8(&s, end, "utf-16-be");
-                                if (w == NULL) {
-                                        Py_DECREF(u);
-                                        return NULL;
-                                }
-                                r = PyString_AsString(w);
-                                rn = PyString_Size(w);
-                                assert(rn % 2 == 0);
-                                for (i = 0; i < rn; i += 2) {
-                                        sprintf(p, "\\u%02x%02x",
-                                                r[i + 0] & 0xFF,
-                                                r[i + 1] & 0xFF);
-                                        p += 6;
-                                }
-                                Py_DECREF(w);
-                        } else {
-                                *p++ = *s++;
-                        }
-                }
-                len = p - buf;
-                s = buf;
+    PyObject *v, *u;
+    char *buf;
+    char *p;
+    const char *end;
+    if (encoding == NULL) {
+        buf = (char *)s;
+        u = NULL;
+    } else if (strcmp(encoding, "iso-8859-1") == 0) {
+        buf = (char *)s;
+        u = NULL;
+    } else {
+        /* "\XX" may become "\u005c\uHHLL" (12 bytes) */
+        u = PyString_FromStringAndSize((char *)NULL, len * 4);
+        if (u == NULL)
+            return NULL;
+        p = buf = PyString_AsString(u);
+        end = s + len;
+        while (s < end) {
+            if (*s == '\\') {
+                *p++ = *s++;
+                if (*s & 0x80) {
+                    strcpy(p, "u005c");
+                    p += 5;
+                }
+            }
+            if (*s & 0x80) { /* XXX inefficient */
+                PyObject *w;
+                char *r;
+                Py_ssize_t rn, i;
+                w = decode_utf8(&s, end, "utf-16-be");
+                if (w == NULL) {
+                    Py_DECREF(u);
+                    return NULL;
+                }
+                r = PyString_AsString(w);
+                rn = PyString_Size(w);
+                assert(rn % 2 == 0);
+                for (i = 0; i < rn; i += 2) {
+                    sprintf(p, "\\u%02x%02x",
+                            r[i + 0] & 0xFF,
+                            r[i + 1] & 0xFF);
+                    p += 6;
+                }
+                Py_DECREF(w);
+            } else {
+                *p++ = *s++;
+            }
         }
-        if (rawmode)
-                v = PyUnicode_DecodeRawUnicodeEscape(s, len, NULL);
-        else
-                v = PyUnicode_DecodeUnicodeEscape(s, len, NULL);
-        Py_XDECREF(u);
-        return v;
+        len = p - buf;
+        s = buf;
+    }
+    if (rawmode)
+        v = PyUnicode_DecodeRawUnicodeEscape(s, len, NULL);
+    else
+        v = PyUnicode_DecodeUnicodeEscape(s, len, NULL);
+    Py_XDECREF(u);
+    return v;
 }
 
 /* s is a Python string literal, including the bracketing quote characters,
@@ -3254,77 +3205,97 @@
  * parsestr parses it, and returns the decoded Python string object.
  */
 static PyObject *
-parsestr(const char *s, const char *encoding)
+parsestr(const node *n, const char *encoding, int *bytesmode)
 {
-        size_t len;
-        int quote = Py_CHARMASK(*s);
-        int rawmode = 0;
-        int need_encoding;
-        int unicode = 0;
+    size_t len;
+    const char *s = STR(n);
+    int quote = Py_CHARMASK(*s);
+    int rawmode = 0;
+    int need_encoding;
+    int unicode = 0;
 
-        if (isalpha(quote) || quote == '_') {
-                if (quote == 'u' || quote == 'U') {
-                        quote = *++s;
-                        unicode = 1;
-                }
-                if (quote == 'r' || quote == 'R') {
-                        quote = *++s;
-                        rawmode = 1;
-                }
-        }
-        if (quote != '\'' && quote != '\"') {
-                PyErr_BadInternalCall();
-                return NULL;
+    if (isalpha(quote) || quote == '_') {
+        if (quote == 'u' || quote == 'U') {
+            quote = *++s;
+            unicode = 1;
         }
-        s++;
-        len = strlen(s);
-        if (len > INT_MAX) {
-                PyErr_SetString(PyExc_OverflowError, 
-                                "string to parse is too long");
-                return NULL;
+        if (quote == 'b' || quote == 'B') {
+            quote = *++s;
+            *bytesmode = 1;
+        }             
+        if (quote == 'r' || quote == 'R') {
+            quote = *++s;
+            rawmode = 1;
         }
-        if (s[--len] != quote) {
-                PyErr_BadInternalCall();
-                return NULL;
-        }
-        if (len >= 4 && s[0] == quote && s[1] == quote) {
-                s += 2;
-                len -= 2;
-                if (s[--len] != quote || s[--len] != quote) {
-                        PyErr_BadInternalCall();
-                        return NULL;
-                }
+    }
+    if (quote != '\'' && quote != '\"') {
+        PyErr_BadInternalCall();
+        return NULL;
+    }
+    if (unicode && *bytesmode) {
+        ast_error(n, "string cannot be both bytes and unicode");
+        return NULL;
+    }
+    s++;
+    len = strlen(s);
+    if (len > INT_MAX) {
+        PyErr_SetString(PyExc_OverflowError, 
+                        "string to parse is too long");
+        return NULL;
+    }
+    if (s[--len] != quote) {
+        PyErr_BadInternalCall();
+        return NULL;
+    }
+    if (len >= 4 && s[0] == quote && s[1] == quote) {
+        s += 2;
+        len -= 2;
+        if (s[--len] != quote || s[--len] != quote) {
+            PyErr_BadInternalCall();
+            return NULL;
         }
+    }
 #ifdef Py_USING_UNICODE
-        if (unicode || Py_UnicodeFlag) {
-                return decode_unicode(s, len, rawmode, encoding);
-        }
+    if (unicode || Py_UnicodeFlag) {
+        return decode_unicode(s, len, rawmode, encoding);
+    }
 #endif
-        need_encoding = (encoding != NULL &&
-                         strcmp(encoding, "utf-8") != 0 &&
-                         strcmp(encoding, "iso-8859-1") != 0);
-        if (rawmode || strchr(s, '\\') == NULL) {
-                if (need_encoding) {
+    if (*bytesmode) {
+        /* Disallow non-ascii characters (but not escapes) */
+        const char *c;
+        for (c = s; *c; c++) {
+            if (Py_CHARMASK(*c) >= 0x80) {
+                ast_error(n, "bytes can only contain ASCII "
+                          "literal characters.");
+                return NULL;
+            }
+        }
+    }
+    need_encoding = (!*bytesmode && encoding != NULL &&
+                     strcmp(encoding, "utf-8") != 0 &&
+                     strcmp(encoding, "iso-8859-1") != 0);
+    if (rawmode || strchr(s, '\\') == NULL) {
+        if (need_encoding) {
 #ifndef Py_USING_UNICODE
-                        /* This should not happen - we never see any other
-                           encoding. */
-                        Py_FatalError(
-                            "cannot deal with encodings in this build.");
+            /* This should not happen - we never see any other
+               encoding. */
+            Py_FatalError(
+                "cannot deal with encodings in this build.");
 #else
-                        PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL);
-                        if (u == NULL)
-                                return NULL;
-                        v = PyUnicode_AsEncodedString(u, encoding, NULL);
-                        Py_DECREF(u);
-                        return v;
+            PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL);
+            if (u == NULL)
+                return NULL;
+            v = PyUnicode_AsEncodedString(u, encoding, NULL);
+            Py_DECREF(u);
+            return v;
 #endif
-                } else {
-                        return PyString_FromStringAndSize(s, len);
-                }
+        } else {
+            return PyString_FromStringAndSize(s, len);
         }
+    }
 
-        return PyString_DecodeEscape(s, len, NULL, unicode,
-                                     need_encoding ? encoding : NULL);
+    return PyString_DecodeEscape(s, len, NULL, unicode,
+                                 need_encoding ? encoding : NULL);
 }
 
 /* Build a Python string object out of a STRING atom.  This takes care of
@@ -3332,38 +3303,45 @@
  * pasting the intermediate results together.
  */
 static PyObject *
-parsestrplus(struct compiling *c, const node *n)
+parsestrplus(struct compiling *c, const node *n, int *bytesmode)
 {
-        PyObject *v;
-        int i;
-        REQ(CHILD(n, 0), STRING);
-        if ((v = parsestr(STR(CHILD(n, 0)), c->c_encoding)) != NULL) {
-                /* String literal concatenation */
-                for (i = 1; i < NCH(n); i++) {
-                        PyObject *s;
-                        s = parsestr(STR(CHILD(n, i)), c->c_encoding);
-                        if (s == NULL)
-                                goto onError;
-                        if (PyString_Check(v) && PyString_Check(s)) {
-                                PyString_ConcatAndDel(&v, s);
-                                if (v == NULL)
-                                    goto onError;
-                        }
+    PyObject *v;
+    int i;
+    REQ(CHILD(n, 0), STRING);
+    v = parsestr(CHILD(n, 0), c->c_encoding, bytesmode);
+    if (v != NULL) {
+        /* String literal concatenation */
+        for (i = 1; i < NCH(n); i++) {
+            PyObject *s;
+            int subbm = 0;
+            s = parsestr(CHILD(n, i), c->c_encoding, &subbm);
+            if (s == NULL)
+                goto onError;
+            if (*bytesmode != subbm) {
+                ast_error(n, "cannot mix bytes and nonbytes"
+                          "literals");
+                goto onError;
+            }
+            if (PyString_Check(v) && PyString_Check(s)) {
+                PyString_ConcatAndDel(&v, s);
+                if (v == NULL)
+                    goto onError;
+            }
 #ifdef Py_USING_UNICODE
-                        else {
-                                PyObject *temp = PyUnicode_Concat(v, s);
-                                Py_DECREF(s);
-                                Py_DECREF(v);
-                                v = temp;
-                                if (v == NULL)
-                                    goto onError;
-                        }
+            else {
+                PyObject *temp = PyUnicode_Concat(v, s);
+                Py_DECREF(s);
+                Py_DECREF(v);
+                v = temp;
+                if (v == NULL)
+                    goto onError;
+            }
 #endif
-                }
         }
-        return v;
+    }
+    return v;
 
- onError:
-        Py_XDECREF(v);
-        return NULL;
+  onError:
+    Py_XDECREF(v);
+    return NULL;
 }

Modified: python/branches/p3yk-noslice/Python/bltinmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Python/bltinmodule.c	(original)
+++ python/branches/p3yk-noslice/Python/bltinmodule.c	Wed Jul 11 15:40:56 2007
@@ -23,12 +23,116 @@
 const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
 #endif
 
-/* Forward */
-static PyObject *filterstring(PyObject *, PyObject *);
-#ifdef Py_USING_UNICODE
-static PyObject *filterunicode(PyObject *, PyObject *);
-#endif
-static PyObject *filtertuple (PyObject *, PyObject *);
+static PyObject *
+builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds)
+{
+	PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
+	PyObject *cls = NULL;
+	Py_ssize_t nargs, nbases;
+
+	assert(args != NULL);
+	if (!PyTuple_Check(args)) {
+		PyErr_SetString(PyExc_TypeError,
+				"__build_class__: args is not a tuple");
+		return NULL;
+	}
+	nargs = PyTuple_GET_SIZE(args);
+	if (nargs < 2) {
+		PyErr_SetString(PyExc_TypeError,
+				"__build_class__: not enough arguments");
+		return NULL;
+	}
+	func = PyTuple_GET_ITEM(args, 0); /* Better be callable */
+	name = PyTuple_GET_ITEM(args, 1);
+	if (!PyString_Check(name)) {
+		PyErr_SetString(PyExc_TypeError,
+				"__build_class__: name is not a string");
+		return NULL;
+	}
+	bases = PyTuple_GetSlice(args, 2, nargs);
+	if (bases == NULL)
+		return NULL;
+	nbases = nargs - 2;
+
+	if (kwds == NULL) {
+		meta = NULL;
+                mkw = NULL;
+        }
+	else {
+		mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */
+		if (mkw == NULL) {
+			Py_DECREF(bases);
+			return NULL;
+		}
+		meta = PyDict_GetItemString(mkw, "metaclass");
+		if (meta != NULL) {
+			Py_INCREF(meta);
+			if (PyDict_DelItemString(mkw, "metaclass") < 0) {
+				Py_DECREF(meta);
+				Py_DECREF(mkw);
+				Py_DECREF(bases);
+				return NULL;
+			}
+		}
+	}
+	if (meta == NULL) {
+		if (PyTuple_GET_SIZE(bases) == 0)
+			meta = (PyObject *) (&PyType_Type);
+		else {
+			PyObject *base0 = PyTuple_GET_ITEM(bases, 0);
+			meta = (PyObject *) (base0->ob_type);
+		}
+		Py_INCREF(meta);
+	}
+	prep = PyObject_GetAttrString(meta, "__prepare__");
+	if (prep == NULL) {
+		PyErr_Clear();
+		ns = PyDict_New();
+	}
+	else {
+		PyObject *pargs = Py_BuildValue("OO", name, bases);
+		if (pargs == NULL) {
+			Py_DECREF(prep);
+			Py_DECREF(meta);
+			Py_XDECREF(mkw);
+			Py_DECREF(bases);
+			return NULL;
+		}
+		ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
+		Py_DECREF(pargs);
+		Py_DECREF(prep);
+		if (ns == NULL) {
+			Py_DECREF(meta);
+			Py_XDECREF(mkw);
+			Py_DECREF(bases);
+			return NULL;
+		}
+	}
+	cell = PyObject_CallFunctionObjArgs(func, ns, NULL);
+	if (cell != NULL) {
+		PyObject *margs;
+		margs = Py_BuildValue("OOO", name, bases, ns);
+		if (margs != NULL) {
+			cls = PyEval_CallObjectWithKeywords(meta, margs, mkw);
+			Py_DECREF(margs);
+		}
+		if (cls != NULL && PyCell_Check(cell)) {
+			Py_INCREF(cls);
+			PyCell_SET(cell, cls);
+		}
+		Py_DECREF(cell);
+	}
+	Py_DECREF(ns);
+	Py_DECREF(meta);
+	Py_XDECREF(mkw);
+	Py_DECREF(bases);
+	return cls;
+}
+
+PyDoc_STRVAR(build_class_doc,
+"__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\
+\n\
+Internal helper function used by the class statement.");
 
 static PyObject *
 builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
@@ -140,138 +244,40 @@
 
 
 static PyObject *
-builtin_callable(PyObject *self, PyObject *v)
+builtin_bin(PyObject *self, PyObject *v)
 {
-	return PyBool_FromLong((long)PyCallable_Check(v));
+	return PyNumber_ToBase(v, 2);
 }
 
-PyDoc_STRVAR(callable_doc,
-"callable(object) -> bool\n\
+PyDoc_STRVAR(bin_doc,
+"bin(number) -> string\n\
 \n\
-Return whether the object is callable (i.e., some kind of function).\n\
-Note that classes are callable, as are instances with a __call__() method.");
+Return the binary representation of an integer or long integer.");
 
 
 static PyObject *
 builtin_filter(PyObject *self, PyObject *args)
 {
-	PyObject *func, *seq, *result, *it, *arg;
-	Py_ssize_t len;   /* guess for result list size */
-	register Py_ssize_t j;
-
-	if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
-		return NULL;
-
-	/* Strings and tuples return a result of the same type. */
-	if (PyString_Check(seq))
-		return filterstring(func, seq);
-#ifdef Py_USING_UNICODE
-	if (PyUnicode_Check(seq))
-		return filterunicode(func, seq);
-#endif
-	if (PyTuple_Check(seq))
-		return filtertuple(func, seq);
-
-	/* Pre-allocate argument list tuple. */
-	arg = PyTuple_New(1);
-	if (arg == NULL)
+	PyObject *itertools, *ifilter, *result;
+	itertools = PyImport_ImportModule("itertools");
+	if (itertools == NULL)
+		return NULL;
+	ifilter = PyObject_GetAttrString(itertools, "ifilter");
+	Py_DECREF(itertools);
+	if (ifilter == NULL)
 		return NULL;
-
-	/* Get iterator. */
-	it = PyObject_GetIter(seq);
-	if (it == NULL)
-		goto Fail_arg;
-
-	/* Guess a result list size. */
-	len = _PyObject_LengthHint(seq);
-	if (len < 0) {
-		if (!PyErr_ExceptionMatches(PyExc_TypeError)  &&
-		    !PyErr_ExceptionMatches(PyExc_AttributeError)) {
-			goto Fail_it;
-		}
-		PyErr_Clear();
-		len = 8;	/* arbitrary */
-	}
-
-	/* Get a result list. */
-	if (PyList_Check(seq) && seq->ob_refcnt == 1) {
-		/* Eww - can modify the list in-place. */
-		Py_INCREF(seq);
-		result = seq;
-	}
-	else {
-		result = PyList_New(len);
-		if (result == NULL)
-			goto Fail_it;
-	}
-
-	/* Build the result list. */
-	j = 0;
-	for (;;) {
-		PyObject *item;
-		int ok;
-
-		item = PyIter_Next(it);
-		if (item == NULL) {
-			if (PyErr_Occurred())
-				goto Fail_result_it;
-			break;
-		}
-
-		if (func == (PyObject *)&PyBool_Type || func == Py_None) {
-			ok = PyObject_IsTrue(item);
-		}
-		else {
-			PyObject *good;
-			PyTuple_SET_ITEM(arg, 0, item);
-			good = PyObject_Call(func, arg, NULL);
-			PyTuple_SET_ITEM(arg, 0, NULL);
-			if (good == NULL) {
-				Py_DECREF(item);
-				goto Fail_result_it;
-			}
-			ok = PyObject_IsTrue(good);
-			Py_DECREF(good);
-		}
-		if (ok) {
-			if (j < len)
-				PyList_SET_ITEM(result, j, item);
-			else {
-				int status = PyList_Append(result, item);
-				Py_DECREF(item);
-				if (status < 0)
-					goto Fail_result_it;
-			}
-			++j;
-		}
-		else
-			Py_DECREF(item);
-	}
-
-
-	/* Cut back result list if len is too big. */
-	if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
-		goto Fail_result_it;
-
-	Py_DECREF(it);
-	Py_DECREF(arg);
+	result = PyObject_Call(ifilter, args, NULL);
+	Py_DECREF(ifilter);
 	return result;
-
-Fail_result_it:
-	Py_DECREF(result);
-Fail_it:
-	Py_DECREF(it);
-Fail_arg:
-	Py_DECREF(arg);
-	return NULL;
 }
 
 PyDoc_STRVAR(filter_doc,
-"filter(function or None, sequence) -> list, tuple, or string\n"
-"\n"
-"Return those items of sequence for which function(item) is true.  If\n"
-"function is None, return the items that are true.  If sequence is a tuple\n"
-"or string, return the same type, else return a list.");
+"filter(predicate, iterable) -> iterator\n\
+\n\
+Return an iterator yielding only those elements of the input iterable\n\
+for which the predicate (a Boolean function) returns true.\n\
+If the predicate is None, 'lambda x: bool(x)' is assumed.\n\
+(This is identical to itertools.ifilter().)");
 
 static PyObject *
 builtin_chr(PyObject *self, PyObject *args)
@@ -334,7 +340,7 @@
 Return negative if x<y, zero if x==y, positive if x>y.");
 
 static PyObject *
-builtin_compile(PyObject *self, PyObject *args)
+builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
 {
 	char *str;
 	char *filename;
@@ -345,9 +351,12 @@
 	PyCompilerFlags cf;
 	PyObject *result = NULL, *cmd, *tmp = NULL;
 	Py_ssize_t length;
+	static char *kwlist[] = {"source", "filename", "mode", "flags",
+				 "dont_inherit", NULL};
 
-	if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename,
-			      &startstr, &supplied_flags, &dont_inherit))
+	if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
+					 kwlist, &cmd, &filename, &startstr,
+					 &supplied_flags, &dont_inherit))
 		return NULL;
 
 	cf.cf_flags = supplied_flags;
@@ -427,15 +436,16 @@
 PyDoc_STRVAR(dir_doc,
 "dir([object]) -> list of strings\n"
 "\n"
-"Return an alphabetized list of names comprising (some of) the attributes\n"
-"of the given object, and of attributes reachable from it:\n"
-"\n"
-"No argument:  the names in the current scope.\n"
-"Module object:  the module attributes.\n"
-"Type or class object:  its attributes, and recursively the attributes of\n"
-"    its bases.\n"
-"Otherwise:  its attributes, its class's attributes, and recursively the\n"
-"    attributes of its class's base classes.");
+"If called without an argument, return the names in the current scope.\n"
+"Else, return an alphabetized list of names comprising (some of) the attributes\n"
+"of the given object, and of attributes reachable from it.\n"
+"If the object supplies a method named __dir__, it will be used; otherwise\n"
+"the default dir() logic is used and returns:\n"
+"  for a module object: the module's attributes.\n"
+"  for a class object:  its attributes, and recursively the attributes\n"
+"    of its bases.\n"
+"  for any other object: its attributes, its class's attributes, and\n"
+"    recursively the attributes of its class's base classes.");
 
 static PyObject *
 builtin_divmod(PyObject *self, PyObject *args)
@@ -864,168 +874,68 @@
 static PyObject *
 builtin_map(PyObject *self, PyObject *args)
 {
-	typedef struct {
-		PyObject *it;	/* the iterator object */
-		int saw_StopIteration;  /* bool:  did the iterator end? */
-	} sequence;
-
-	PyObject *func, *result;
-	sequence *seqs = NULL, *sqp;
-	Py_ssize_t n, len;
-	register int i, j;
-
-	n = PyTuple_Size(args);
-	if (n < 2) {
-		PyErr_SetString(PyExc_TypeError,
-				"map() requires at least two args");
+	PyObject *itertools, *imap, *result;
+	itertools = PyImport_ImportModule("itertools");
+	if (itertools == NULL)
+		return NULL;
+	imap = PyObject_GetAttrString(itertools, "imap");
+	Py_DECREF(itertools);
+	if (imap == NULL)
 		return NULL;
-	}
+	result = PyObject_Call(imap, args, NULL);
+	Py_DECREF(imap);
+	return result;
+}
 
-	func = PyTuple_GetItem(args, 0);
-	n--;
+PyDoc_STRVAR(map_doc,
+"map(function, iterable[, iterable, ...]) -> iterator\n\
+\n\
+Return an iterator yielding the results of applying the function to the\n\
+items of the argument iterables(s).  If more than one iterable is given,\n\
+the function is called with an argument list consisting of the\n\
+corresponding item of each iterable, until an iterable is exhausted.\n\
+If the function is None, 'lambda *a: a' is assumed.\n\
+(This is identical to itertools.imap().)");
 
-	if (func == Py_None && n == 1) {
-		/* map(None, S) is the same as list(S). */
-		return PySequence_List(PyTuple_GetItem(args, 1));
-	}
 
-	/* Get space for sequence descriptors.  Must NULL out the iterator
-	 * pointers so that jumping to Fail_2 later doesn't see trash.
-	 */
-	if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
-		PyErr_NoMemory();
+static PyObject *
+builtin_next(PyObject *self, PyObject *args)
+{
+	PyObject *it, *res;
+	PyObject *def = NULL;
+
+	if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
+		return NULL;
+	if (!PyIter_Check(it)) {
+		PyErr_Format(PyExc_TypeError,
+			"%.200s object is not an iterator", it->ob_type->tp_name);
 		return NULL;
 	}
-	for (i = 0; i < n; ++i) {
-		seqs[i].it = (PyObject*)NULL;
-		seqs[i].saw_StopIteration = 0;
-	}
-
-	/* Do a first pass to obtain iterators for the arguments, and set len
-	 * to the largest of their lengths.
-	 */
-	len = 0;
-	for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
-		PyObject *curseq;
-		Py_ssize_t curlen;
-
-		/* Get iterator. */
-		curseq = PyTuple_GetItem(args, i+1);
-		sqp->it = PyObject_GetIter(curseq);
-		if (sqp->it == NULL) {
-			static char errmsg[] =
-			    "argument %d to map() must support iteration";
-			char errbuf[sizeof(errmsg) + 25];
-			PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
-			PyErr_SetString(PyExc_TypeError, errbuf);
-			goto Fail_2;
-		}
-
-		/* Update len. */
-		curlen = _PyObject_LengthHint(curseq);
-		if (curlen < 0) {
-			if (!PyErr_ExceptionMatches(PyExc_TypeError)  &&
-			    !PyErr_ExceptionMatches(PyExc_AttributeError)) {
-				goto Fail_2;
-			}
+	
+	res = (*it->ob_type->tp_iternext)(it);
+	if (res == NULL) {
+		if (def) {
+			if (PyErr_Occurred() &&
+			    !PyErr_ExceptionMatches(PyExc_StopIteration))
+				return NULL;
 			PyErr_Clear();
-			curlen = 8;  /* arbitrary */
+			Py_INCREF(def);
+			return def;
+		} else if (PyErr_Occurred()) {
+			return NULL;
+		} else {
+			PyErr_SetNone(PyExc_StopIteration);
+			return NULL;
 		}
-		if (curlen > len)
-			len = curlen;
 	}
-
-	/* Get space for the result list. */
-	if ((result = (PyObject *) PyList_New(len)) == NULL)
-		goto Fail_2;
-
-	/* Iterate over the sequences until all have stopped. */
-	for (i = 0; ; ++i) {
-		PyObject *alist, *item=NULL, *value;
-		int numactive = 0;
-
-		if (func == Py_None && n == 1)
-			alist = NULL;
-		else if ((alist = PyTuple_New(n)) == NULL)
-			goto Fail_1;
-
-		for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
-			if (sqp->saw_StopIteration) {
-				Py_INCREF(Py_None);
-				item = Py_None;
-			}
-			else {
-				item = PyIter_Next(sqp->it);
-				if (item)
-					++numactive;
-				else {
-					if (PyErr_Occurred()) {
-						Py_XDECREF(alist);
-						goto Fail_1;
-					}
-					Py_INCREF(Py_None);
-					item = Py_None;
-					sqp->saw_StopIteration = 1;
-				}
-			}
-			if (alist)
-				PyTuple_SET_ITEM(alist, j, item);
-			else
-				break;
-		}
-
-		if (!alist)
-			alist = item;
-
-		if (numactive == 0) {
-			Py_DECREF(alist);
-			break;
-		}
-
-		if (func == Py_None)
-			value = alist;
-		else {
-			value = PyEval_CallObject(func, alist);
-			Py_DECREF(alist);
-			if (value == NULL)
-				goto Fail_1;
-		}
-		if (i >= len) {
-			int status = PyList_Append(result, value);
-			Py_DECREF(value);
-			if (status < 0)
-				goto Fail_1;
-		}
-		else if (PyList_SetItem(result, i, value) < 0)
-		 	goto Fail_1;
-	}
-
-	if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
-		goto Fail_1;
-
-	goto Succeed;
-
-Fail_1:
-	Py_DECREF(result);
-Fail_2:
-	result = NULL;
-Succeed:
-	assert(seqs);
-	for (i = 0; i < n; ++i)
-		Py_XDECREF(seqs[i].it);
-	PyMem_DEL(seqs);
-	return result;
+	return res;
 }
 
-PyDoc_STRVAR(map_doc,
-"map(function, sequence[, sequence, ...]) -> list\n\
+PyDoc_STRVAR(next_doc,
+"next(iterator[, default])\n\
 \n\
-Return a list of the results of applying the function to the items of\n\
-the argument sequence(s).  If more than one sequence is given, the\n\
-function is called with an argument list consisting of the corresponding\n\
-item of each sequence, substituting None for missing values when not all\n\
-sequences have the same length.  If the function is None, return a list of\n\
-the items of the sequence (or a list of tuples if more than one sequence).");
+Return the next item from the iterator. If default is given and the iterator\n\
+is exhausted, it is returned instead of raising StopIteration.");
 
 
 static PyObject *
@@ -1092,24 +1002,7 @@
 static PyObject *
 builtin_hex(PyObject *self, PyObject *v)
 {
-	PyNumberMethods *nb;
-	PyObject *res;
-
-	if ((nb = v->ob_type->tp_as_number) == NULL ||
-	    nb->nb_hex == NULL) {
-		PyErr_SetString(PyExc_TypeError,
-			   "hex() argument can't be converted to hex");
-		return NULL;
-	}
-	res = (*nb->nb_hex)(v);
-	if (res && !PyString_Check(res)) {
-		PyErr_Format(PyExc_TypeError,
-			     "__hex__ returned non-string (type %.200s)",
-			     res->ob_type->tp_name);
-		Py_DECREF(res);
-		return NULL;
-	}
-	return res;
+	return PyNumber_ToBase(v, 16);
 }
 
 PyDoc_STRVAR(hex_doc,
@@ -1292,24 +1185,7 @@
 static PyObject *
 builtin_oct(PyObject *self, PyObject *v)
 {
-	PyNumberMethods *nb;
-	PyObject *res;
-
-	if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
-	    nb->nb_oct == NULL) {
-		PyErr_SetString(PyExc_TypeError,
-			   "oct() argument can't be converted to oct");
-		return NULL;
-	}
-	res = (*nb->nb_oct)(v);
-	if (res && !PyString_Check(res)) {
-		PyErr_Format(PyExc_TypeError,
-			     "__oct__ returned non-string (type %.200s)",
-			     res->ob_type->tp_name);
-		Py_DECREF(res);
-		return NULL;
-	}
-	return res;
+	return PyNumber_ToBase(v, 8);
 }
 
 PyDoc_STRVAR(oct_doc,
@@ -1343,14 +1219,24 @@
 			return PyInt_FromLong(ord);
 		}
 #ifdef Py_USING_UNICODE
-	} else if (PyUnicode_Check(obj)) {
+	}
+	else if (PyUnicode_Check(obj)) {
 		size = PyUnicode_GET_SIZE(obj);
 		if (size == 1) {
 			ord = (long)*PyUnicode_AS_UNICODE(obj);
 			return PyInt_FromLong(ord);
 		}
 #endif
-	} else {
+	} 
+	else if (PyBytes_Check(obj)) {
+		/* XXX Hopefully this is temporary */
+		size = PyBytes_GET_SIZE(obj);
+		if (size == 1) {
+			ord = (long)*PyBytes_AS_STRING(obj);
+			return PyInt_FromLong(ord);
+		}
+	}
+	else {
 		PyErr_Format(PyExc_TypeError,
 			     "ord() expected string of length 1, but " \
 			     "%.200s found", obj->ob_type->tp_name);
@@ -1392,12 +1278,14 @@
 builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
 {
 	static char *kwlist[] = {"sep", "end", "file", 0};
-	PyObject *dummy_args = PyTuple_New(0);
+	static PyObject *dummy_args;
 	PyObject *sep = NULL, *end = NULL, *file = NULL;
 	int i, err;
 
-	if (dummy_args == NULL)
-		return NULL;
+	if (dummy_args == NULL) {
+		if (!(dummy_args = PyTuple_New(0)))
+			return NULL;
+	}
 	if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
 					 kwlist, &sep, &end, &file))
                 return NULL;
@@ -1455,313 +1343,83 @@
 end:  string appended after the last value, default a newline.");
 
 
-/* Return number of items in range (lo, hi, step), when arguments are
- * PyInt or PyLong objects.  step > 0 required.  Return a value < 0 if
- * & only if the true value is too large to fit in a signed long.
- * Arguments MUST return 1 with either PyInt_Check() or
- * PyLong_Check().  Return -1 when there is an error.
- */
-static long
-get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
-{
-	/* -------------------------------------------------------------
-	Algorithm is equal to that of get_len_of_range(), but it operates
-	on PyObjects (which are assumed to be PyLong or PyInt objects).
-	---------------------------------------------------------------*/
-	long n;
-	PyObject *diff = NULL;
-	PyObject *one = NULL;
-	PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
-		/* holds sub-expression evaluations */
-
-	/* If (lo >= hi), return length of 0 (or error). */
-	n = PyObject_RichCompareBool(lo, hi, Py_LT);
-	if (n <= 0)
-		return n;
-
-	if ((one = PyLong_FromLong(1L)) == NULL)
-		goto Fail;
-
-	if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
-		goto Fail;
-
-	if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
-		goto Fail;
-
-	if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
-		goto Fail;
-
-	if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
-		goto Fail;
-
-	n = PyLong_AsLong(tmp3);
-	if (PyErr_Occurred()) {  /* Check for Overflow */
-		PyErr_Clear();
-		goto Fail;
-	}
-
-	Py_DECREF(tmp3);
-	Py_DECREF(tmp2);
-	Py_DECREF(diff);
-	Py_DECREF(tmp1);
-	Py_DECREF(one);
-	return n;
-
-  Fail:
-	Py_XDECREF(tmp3);
-	Py_XDECREF(tmp2);
-	Py_XDECREF(diff);
-	Py_XDECREF(tmp1);
-	Py_XDECREF(one);
-	return -1;
-}
-
-/* An extension of builtin_range() that handles the case when PyLong
- * arguments are given. */
 static PyObject *
-handle_range_longs(PyObject *self, PyObject *args)
+builtin_input(PyObject *self, PyObject *args)
 {
-	PyObject *ilow;
-	PyObject *ihigh = NULL;
-	PyObject *istep = NULL;
-
-	PyObject *curnum = NULL;
 	PyObject *v = NULL;
-	long bign;
-	int i, n;
-	int step_pos;
-
-	PyObject *zero = PyLong_FromLong(0);
+	PyObject *fin = PySys_GetObject("stdin");
+	PyObject *fout = PySys_GetObject("stdout");
 
-	if (zero == NULL)
+	if (!PyArg_UnpackTuple(args, "input", 0, 1, &v))
 		return NULL;
 
-	if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
-		Py_DECREF(zero);
+	if (fin == NULL) {
+		PyErr_SetString(PyExc_RuntimeError, "input: lost sys.stdin");
 		return NULL;
 	}
-
-	/* Figure out which way we were called, supply defaults, and be
-	 * sure to incref everything so that the decrefs at the end
-	 * are correct.
-	 */
-	assert(ilow != NULL);
-	if (ihigh == NULL) {
-		/* only 1 arg -- it's the upper limit */
-		ihigh = ilow;
-		ilow = NULL;
-	}
-	assert(ihigh != NULL);
-	Py_INCREF(ihigh);
-
-	/* ihigh correct now; do ilow */
-	if (ilow == NULL)
-		ilow = zero;
-	Py_INCREF(ilow);
-
-	/* ilow and ihigh correct now; do istep */
-	if (istep == NULL) {
-		istep = PyLong_FromLong(1L);
-		if (istep == NULL)
-			goto Fail;
-	}
-	else {
-		Py_INCREF(istep);
-	}
-
-	if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
-		PyErr_Format(PyExc_TypeError,
-			     "range() integer start argument expected, got %s.",
-			     ilow->ob_type->tp_name);
-		goto Fail;
-	}
-
-	if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
-		PyErr_Format(PyExc_TypeError,
-			     "range() integer end argument expected, got %s.",
-			     ihigh->ob_type->tp_name);
-		goto Fail;
-	}
-
-	if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
-		PyErr_Format(PyExc_TypeError,
-			     "range() integer step argument expected, got %s.",
-			     istep->ob_type->tp_name);
-		goto Fail;
-	}
-
-	step_pos = PyObject_RichCompareBool(istep, zero, Py_GT);
-	if (step_pos < 0)
-		goto Fail;
-	if (step_pos)
-		bign = get_len_of_range_longs(ilow, ihigh, istep);
-	else {
-		int step_zero = PyObject_RichCompareBool(istep, zero, Py_EQ);
-		PyObject *neg_istep;
-		if (step_zero < 0)
-			goto Fail;
-		if (step_zero) {
-			PyErr_SetString(PyExc_ValueError,
-				"range() step argument must not be zero");
-			goto Fail;
-		}
-		neg_istep = PyNumber_Negative(istep);
-		if (neg_istep == NULL)
-			goto Fail;
-		bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
-		Py_DECREF(neg_istep);
-	}
-
-	n = (int)bign;
-	if (bign < 0 || (long)n != bign) {
-		PyErr_SetString(PyExc_OverflowError,
-				"range() result has too many items");
-		goto Fail;
+	if (fout == NULL) {
+		PyErr_SetString(PyExc_RuntimeError, "input: lost sys.stdout");
+		return NULL;
 	}
-
-	v = PyList_New(n);
-	if (v == NULL)
-		goto Fail;
-
-	curnum = ilow;
-	Py_INCREF(curnum);
-
-	for (i = 0; i < n; i++) {
-		PyObject *w = PyNumber_Long(curnum);
-		PyObject *tmp_num;
-		if (w == NULL)
-			goto Fail;
-
-		PyList_SET_ITEM(v, i, w);
-
-		tmp_num = PyNumber_Add(curnum, istep);
-		if (tmp_num == NULL)
-			goto Fail;
-
-		Py_DECREF(curnum);
-		curnum = tmp_num;
-	}
-	Py_DECREF(ilow);
-	Py_DECREF(ihigh);
-	Py_DECREF(istep);
-	Py_DECREF(zero);
-	Py_DECREF(curnum);
-	return v;
-
-  Fail:
-	Py_DECREF(ilow);
-	Py_DECREF(ihigh);
-	Py_XDECREF(istep);
-	Py_DECREF(zero);
-	Py_XDECREF(curnum);
-	Py_XDECREF(v);
-	return NULL;
-}
-
-/* Return number of items in range/xrange (lo, hi, step).  step > 0
- * required.  Return a value < 0 if & only if the true value is too
- * large to fit in a signed long.
- */
-static long
-get_len_of_range(long lo, long hi, long step)
-{
-	/* -------------------------------------------------------------
-	If lo >= hi, the range is empty.
-	Else if n values are in the range, the last one is
-	lo + (n-1)*step, which must be <= hi-1.  Rearranging,
-	n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
-	the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
-	the RHS is non-negative and so truncation is the same as the
-	floor.  Letting M be the largest positive long, the worst case
-	for the RHS numerator is hi=M, lo=-M-1, and then
-	hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
-	precision to compute the RHS exactly.
-	---------------------------------------------------------------*/
-	long n = 0;
-	if (lo < hi) {
-		unsigned long uhi = (unsigned long)hi;
-		unsigned long ulo = (unsigned long)lo;
-		unsigned long diff = uhi - ulo - 1;
-		n = (long)(diff / (unsigned long)step + 1);
-	}
-	return n;
-}
-
-static PyObject *
-builtin_range(PyObject *self, PyObject *args)
-{
-	long ilow = 0, ihigh = 0, istep = 1;
-	long bign;
-	int i, n;
-
-	PyObject *v;
-
-	if (PyTuple_Size(args) <= 1) {
-		if (!PyArg_ParseTuple(args,
-				"l;range() requires 1-3 int arguments",
-				&ihigh)) {
-			PyErr_Clear();
-			return handle_range_longs(self, args);
+	if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
+            && isatty(fileno(PyFile_AsFile(fin)))
+            && isatty(fileno(PyFile_AsFile(fout)))) {
+		PyObject *po;
+		char *prompt;
+		char *s;
+		PyObject *result;
+		if (v != NULL) {
+			po = PyObject_Str(v);
+			if (po == NULL)
+				return NULL;
+			prompt = PyString_AsString(po);
+			if (prompt == NULL)
+				return NULL;
 		}
-	}
-	else {
-		if (!PyArg_ParseTuple(args,
-				"ll|l;range() requires 1-3 int arguments",
-				&ilow, &ihigh, &istep)) {
-			PyErr_Clear();
-			return handle_range_longs(self, args);
+		else {
+			po = NULL;
+			prompt = "";
 		}
-	}
-	if (istep == 0) {
-		PyErr_SetString(PyExc_ValueError,
-				"range() step argument must not be zero");
-		return NULL;
-	}
-	if (istep > 0)
-		bign = get_len_of_range(ilow, ihigh, istep);
-	else
-		bign = get_len_of_range(ihigh, ilow, -istep);
-	n = (int)bign;
-	if (bign < 0 || (long)n != bign) {
-		PyErr_SetString(PyExc_OverflowError,
-				"range() result has too many items");
-		return NULL;
-	}
-	v = PyList_New(n);
-	if (v == NULL)
-		return NULL;
-	for (i = 0; i < n; i++) {
-		PyObject *w = PyInt_FromLong(ilow);
-		if (w == NULL) {
-			Py_DECREF(v);
+		s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
+                                  prompt);
+		Py_XDECREF(po);
+		if (s == NULL) {
+			if (!PyErr_Occurred())
+				PyErr_SetNone(PyExc_KeyboardInterrupt);
 			return NULL;
 		}
-		PyList_SET_ITEM(v, i, w);
-		ilow += istep;
+		if (*s == '\0') {
+			PyErr_SetNone(PyExc_EOFError);
+			result = NULL;
+		}
+		else { /* strip trailing '\n' */
+			size_t len = strlen(s);
+			if (len > PY_SSIZE_T_MAX) {
+				PyErr_SetString(PyExc_OverflowError,
+						"input: input too long");
+				result = NULL;
+			}
+			else {
+				result = PyString_FromStringAndSize(s, len-1);
+			}
+		}
+		PyMem_FREE(s);
+		return result;
 	}
-	return v;
-}
-
-PyDoc_STRVAR(range_doc,
-"range([start,] stop[, step]) -> list of integers\n\
-\n\
-Return a list containing an arithmetic progression of integers.\n\
-range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
-When step is given, it specifies the increment (or decrement).\n\
-For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\n\
-These are exactly the valid indices for a list of 4 elements.");
-
-
-static PyObject *
-builtin_reload(PyObject *self, PyObject *v)
-{
-	return PyImport_ReloadModule(v);
+	if (v != NULL) {
+		if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
+			return NULL;
+	}
+	return PyFile_GetLine(fin, -1);
 }
 
-PyDoc_STRVAR(reload_doc,
-"reload(module) -> module\n\
+PyDoc_STRVAR(input_doc,
+"input([prompt]) -> string\n\
 \n\
-Reload the module.  The module must have been successfully imported before.");
+Read a string from standard input.  The trailing newline is stripped.\n\
+If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
+On Unix, GNU readline is used if enabled.  The prompt string, if given,\n\
+is printed without a trailing newline before reading.");
 
 
 static PyObject *
@@ -2019,18 +1677,20 @@
 Return an iterator yielding tuples, where each tuple contains the\n\
 corresponding element from each of the argument iterables.\n\
 The returned iterator ends when the shortest argument iterable is exhausted.\n\
-NOTE: This is implemented using itertools.izip().");
+(This is identical to itertools.izip().)");
 
 
 static PyMethodDef builtin_methods[] = {
+ 	{"__build_class__", (PyCFunction)builtin___build_class__,
+         METH_VARARGS | METH_KEYWORDS, build_class_doc},
  	{"__import__",	(PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
  	{"abs",		builtin_abs,        METH_O, abs_doc},
  	{"all",		builtin_all,        METH_O, all_doc},
  	{"any",		builtin_any,        METH_O, any_doc},
- 	{"callable",	builtin_callable,   METH_O, callable_doc},
+	{"bin",		builtin_bin,	    METH_O, bin_doc},
  	{"chr",		builtin_chr,        METH_VARARGS, chr_doc},
  	{"cmp",		builtin_cmp,        METH_VARARGS, cmp_doc},
- 	{"compile",	builtin_compile,    METH_VARARGS, compile_doc},
+ 	{"compile",	(PyCFunction)builtin_compile,    METH_VARARGS | METH_KEYWORDS, compile_doc},
  	{"delattr",	builtin_delattr,    METH_VARARGS, delattr_doc},
  	{"dir",		builtin_dir,        METH_VARARGS, dir_doc},
  	{"divmod",	builtin_divmod,     METH_VARARGS, divmod_doc},
@@ -2044,6 +1704,7 @@
  	{"hash",	builtin_hash,       METH_O, hash_doc},
  	{"hex",		builtin_hex,        METH_O, hex_doc},
  	{"id",		builtin_id,         METH_O, id_doc},
+ 	{"input",	builtin_input,      METH_VARARGS, input_doc},
  	{"isinstance",  builtin_isinstance, METH_VARARGS, isinstance_doc},
  	{"issubclass",  builtin_issubclass, METH_VARARGS, issubclass_doc},
  	{"iter",	builtin_iter,       METH_VARARGS, iter_doc},
@@ -2052,13 +1713,12 @@
  	{"map",		builtin_map,        METH_VARARGS, map_doc},
  	{"max",		(PyCFunction)builtin_max,        METH_VARARGS | METH_KEYWORDS, max_doc},
  	{"min",		(PyCFunction)builtin_min,        METH_VARARGS | METH_KEYWORDS, min_doc},
+	{"next",	(PyCFunction)builtin_next,       METH_VARARGS, next_doc},
  	{"oct",		builtin_oct,        METH_O, oct_doc},
  	{"open",	(PyCFunction)builtin_open,       METH_VARARGS | METH_KEYWORDS, open_doc},
  	{"ord",		builtin_ord,        METH_O, ord_doc},
  	{"pow",		builtin_pow,        METH_VARARGS, pow_doc},
  	{"print",	(PyCFunction)builtin_print,      METH_VARARGS | METH_KEYWORDS, print_doc},
- 	{"range",	builtin_range,      METH_VARARGS, range_doc},
- 	{"reload",	builtin_reload,     METH_O, reload_doc},
  	{"repr",	builtin_repr,       METH_O, repr_doc},
  	{"round",	(PyCFunction)builtin_round,      METH_VARARGS | METH_KEYWORDS, round_doc},
  	{"setattr",	builtin_setattr,    METH_VARARGS, setattr_doc},
@@ -2127,6 +1787,7 @@
 	SETBUILTIN("int",		&PyLong_Type);
 	SETBUILTIN("list",		&PyList_Type);
 	SETBUILTIN("object",		&PyBaseObject_Type);
+	SETBUILTIN("range",		&PyRange_Type);
 	SETBUILTIN("reversed",		&PyReversed_Type);
 	SETBUILTIN("set",		&PySet_Type);
 	SETBUILTIN("slice",		&PySlice_Type);
@@ -2135,7 +1796,6 @@
 	SETBUILTIN("super",		&PySuper_Type);
 	SETBUILTIN("tuple",		&PyTuple_Type);
 	SETBUILTIN("type",		&PyType_Type);
-	SETBUILTIN("xrange",		&PyRange_Type);
 #ifdef Py_USING_UNICODE
 	SETBUILTIN("unicode",		&PyUnicode_Type);
 #endif
@@ -2150,264 +1810,3 @@
 #undef ADD_TO_ALL
 #undef SETBUILTIN
 }
-
-/* Helper for filter(): filter a tuple through a function */
-
-static PyObject *
-filtertuple(PyObject *func, PyObject *tuple)
-{
-	PyObject *result;
-	Py_ssize_t i, j;
-	Py_ssize_t len = PyTuple_Size(tuple);
-
-	if (len == 0) {
-		if (PyTuple_CheckExact(tuple))
-			Py_INCREF(tuple);
-		else
-			tuple = PyTuple_New(0);
-		return tuple;
-	}
-
-	if ((result = PyTuple_New(len)) == NULL)
-		return NULL;
-
-	for (i = j = 0; i < len; ++i) {
-		PyObject *item, *good;
-		int ok;
-
-		if (tuple->ob_type->tp_as_sequence &&
-		    tuple->ob_type->tp_as_sequence->sq_item) {
-			item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
-			if (item == NULL)
-				goto Fail_1;
-		} else {
-			PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
-			goto Fail_1;
-		}
-		if (func == Py_None) {
-			Py_INCREF(item);
-			good = item;
-		}
-		else {
-			PyObject *arg = PyTuple_Pack(1, item);
-			if (arg == NULL) {
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-			good = PyEval_CallObject(func, arg);
-			Py_DECREF(arg);
-			if (good == NULL) {
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-		}
-		ok = PyObject_IsTrue(good);
-		Py_DECREF(good);
-		if (ok) {
-			if (PyTuple_SetItem(result, j++, item) < 0)
-				goto Fail_1;
-		}
-		else
-			Py_DECREF(item);
-	}
-
-	if (_PyTuple_Resize(&result, j) < 0)
-		return NULL;
-
-	return result;
-
-Fail_1:
-	Py_DECREF(result);
-	return NULL;
-}
-
-
-/* Helper for filter(): filter a string through a function */
-
-static PyObject *
-filterstring(PyObject *func, PyObject *strobj)
-{
-	PyObject *result;
-	Py_ssize_t i, j;
-	Py_ssize_t len = PyString_Size(strobj);
-	Py_ssize_t outlen = len;
-
-	if (func == Py_None) {
-		/* If it's a real string we can return the original,
-		 * 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)) {
-			Py_INCREF(strobj);
-			return strobj;
-		}
-	}
-	if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
-		return NULL;
-
-	for (i = j = 0; i < len; ++i) {
-		PyObject *item;
-		int ok;
-
-		item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
-		if (item == NULL)
-			goto Fail_1;
-		if (func==Py_None) {
-			ok = 1;
-		} else {
-			PyObject *arg, *good;
-			arg = PyTuple_Pack(1, item);
-			if (arg == NULL) {
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-			good = PyEval_CallObject(func, arg);
-			Py_DECREF(arg);
-			if (good == NULL) {
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-			ok = PyObject_IsTrue(good);
-			Py_DECREF(good);
-		}
-		if (ok) {
-			Py_ssize_t reslen;
-			if (!PyString_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);
-			if (reslen == 1) {
-				PyString_AS_STRING(result)[j++] =
-					PyString_AS_STRING(item)[0];
-			} else {
-				/* do we need more space? */
-				Py_ssize_t need = j + reslen + len-i-1;
-				if (need > outlen) {
-					/* overallocate, to avoid reallocations */
-					if (need<2*outlen)
-						need = 2*outlen;
-					if (_PyString_Resize(&result, need)) {
-						Py_DECREF(item);
-						return NULL;
-					}
-					outlen = need;
-				}
-				memcpy(
-					PyString_AS_STRING(result) + j,
-					PyString_AS_STRING(item),
-					reslen
-				);
-				j += reslen;
-			}
-		}
-		Py_DECREF(item);
-	}
-
-	if (j < outlen)
-		_PyString_Resize(&result, j);
-
-	return result;
-
-Fail_1:
-	Py_DECREF(result);
-	return NULL;
-}
-
-#ifdef Py_USING_UNICODE
-/* Helper for filter(): filter a Unicode object through a function */
-
-static PyObject *
-filterunicode(PyObject *func, PyObject *strobj)
-{
-	PyObject *result;
-	register Py_ssize_t i, j;
-	Py_ssize_t len = PyUnicode_GetSize(strobj);
-	Py_ssize_t outlen = len;
-
-	if (func == Py_None) {
-		/* If it's a real string we can return the original,
-		 * 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 (PyUnicode_CheckExact(strobj)) {
-			Py_INCREF(strobj);
-			return strobj;
-		}
-	}
-	if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
-		return NULL;
-
-	for (i = j = 0; i < len; ++i) {
-		PyObject *item, *arg, *good;
-		int ok;
-
-		item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
-		if (item == NULL)
-			goto Fail_1;
-		if (func == Py_None) {
-			ok = 1;
-		} else {
-			arg = PyTuple_Pack(1, item);
-			if (arg == NULL) {
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-			good = PyEval_CallObject(func, arg);
-			Py_DECREF(arg);
-			if (good == NULL) {
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-			ok = PyObject_IsTrue(good);
-			Py_DECREF(good);
-		}
-		if (ok) {
-			Py_ssize_t reslen;
-			if (!PyUnicode_Check(item)) {
-				PyErr_SetString(PyExc_TypeError,
-				"can't filter unicode to unicode:"
-				" __getitem__ returned different type");
-				Py_DECREF(item);
-				goto Fail_1;
-			}
-			reslen = PyUnicode_GET_SIZE(item);
-			if (reslen == 1)
-				PyUnicode_AS_UNICODE(result)[j++] =
-					PyUnicode_AS_UNICODE(item)[0];
-			else {
-				/* do we need more space? */
-				Py_ssize_t need = j + reslen + len - i - 1;
-				if (need > outlen) {
-					/* overallocate,
-					   to avoid reallocations */
-					if (need < 2 * outlen)
-						need = 2 * outlen;
-					if (PyUnicode_Resize(
-						&result, need) < 0) {
-						Py_DECREF(item);
-						goto Fail_1;
-					}
-					outlen = need;
-				}
-				memcpy(PyUnicode_AS_UNICODE(result) + j,
-				       PyUnicode_AS_UNICODE(item),
-				       reslen*sizeof(Py_UNICODE));
-				j += reslen;
-			}
-		}
-		Py_DECREF(item);
-	}
-
-	if (j < outlen)
-		PyUnicode_Resize(&result, j);
-
-	return result;
-
-Fail_1:
-	Py_DECREF(result);
-	return NULL;
-}
-#endif

Modified: python/branches/p3yk-noslice/Python/ceval.c
==============================================================================
--- python/branches/p3yk-noslice/Python/ceval.c	(original)
+++ python/branches/p3yk-noslice/Python/ceval.c	Wed Jul 11 15:40:56 2007
@@ -114,7 +114,6 @@
 static PyObject * cmp_outcome(int, PyObject *, PyObject *);
 static PyObject * import_from(PyObject *, PyObject *);
 static int import_all_from(PyObject *, PyObject *);
-static PyObject * build_class(PyObject *, PyObject *, PyObject *);
 static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
 static void reset_exc_info(PyThreadState *);
 static void format_exc_check_arg(PyObject *, char *, PyObject *);
@@ -475,7 +474,7 @@
 };
 
 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
-static int unpack_iterable(PyObject *, int, PyObject **);
+static int unpack_iterable(PyObject *, int, int, PyObject **);
 
 /* for manipulating the thread switch and periodic "stuff" - used to be
    per thread, now just a pair o' globals */
@@ -485,7 +484,6 @@
 PyObject *
 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
 {
-	/* XXX raise SystemError if globals is NULL */
 	return PyEval_EvalCodeEx(co,
 			  globals, locals,
 			  (PyObject **)NULL, 0,
@@ -654,7 +652,7 @@
 #define STACKADJ(n)	{ (void)(BASIC_STACKADJ(n), \
                                lltrace && prtrace(TOP(), "stackadj")); \
                                assert(STACK_LEVEL() <= co->co_stacksize); }
-#define EXT_POP(STACK_POINTER) (lltrace && prtrace(*(STACK_POINTER), "ext_pop"), *--(STACK_POINTER))
+#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], "ext_pop"), *--(STACK_POINTER))
 #else
 #define PUSH(v)		BASIC_PUSH(v)
 #define POP()		BASIC_POP()
@@ -1238,6 +1236,18 @@
 			}
 			break;
 
+		case SET_ADD:
+			w = POP();
+			v = POP();
+			err = PySet_Add(v, w);
+			Py_DECREF(v);
+			Py_DECREF(w);
+			if (err == 0) {
+				PREDICT(JUMP_ABSOLUTE);
+				continue;
+			}
+			break;
+
 		case INPLACE_POWER:
 			w = POP();
 			v = TOP();
@@ -1464,14 +1474,12 @@
 			}
 			break;
 
-		case LOAD_LOCALS:
-			if ((x = f->f_locals) != NULL) {
-				Py_INCREF(x);
-				PUSH(x);
-				continue;
-			}
-			PyErr_SetString(PyExc_SystemError, "no locals");
-			break;
+		case STORE_LOCALS:
+			x = POP();
+			v = f->f_locals;
+			Py_XDECREF(v);
+			f->f_locals = x;
+			continue;
 
 		case RETURN_VALUE:
 			retval = POP();
@@ -1503,7 +1511,7 @@
 				    why == WHY_CONTINUE)
 					retval = POP();
 			}
-			else if (PyExceptionClass_Check(v) || PyString_Check(v)) {
+			else if (PyExceptionClass_Check(v)) {
 				w = POP();
 				u = POP();
 				PyErr_Restore(v, w, u);
@@ -1518,16 +1526,16 @@
 			Py_DECREF(v);
 			break;
 
-		case BUILD_CLASS:
-			u = TOP();
-			v = SECOND();
-			w = THIRD();
-			STACKADJ(-2);
-			x = build_class(u, v, w);
-			SET_TOP(x);
-			Py_DECREF(u);
-			Py_DECREF(v);
-			Py_DECREF(w);
+		case LOAD_BUILD_CLASS:
+			x = PyDict_GetItemString(f->f_builtins,
+						 "__build_class__");
+			if (x == NULL) {
+				PyErr_SetString(PyExc_ImportError,
+						"__build_class__ not found");
+				break;
+			}
+			Py_INCREF(x);
+			PUSH(x);
 			break;
 
 		case STORE_NAME:
@@ -1579,17 +1587,30 @@
 					Py_INCREF(w);
 					PUSH(w);
 				}
-			} else if (unpack_iterable(v, oparg,
-						 stack_pointer + oparg))
+			} else if (unpack_iterable(v, oparg, -1,
+						 stack_pointer + oparg)) {
 				stack_pointer += oparg;
-			else {
-				if (PyErr_ExceptionMatches(PyExc_TypeError))
-					PyErr_SetString(PyExc_TypeError,
-						"unpack non-sequence");
+			} else {
+				/* unpack_iterable() raised an exception */
+				why = WHY_EXCEPTION;
+			}
+			Py_DECREF(v);
+			break;
+
+		case UNPACK_EX:
+		{
+			int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8);
+			v = POP();
+			
+			if (unpack_iterable(v, oparg & 0xFF, oparg >> 8,
+					    stack_pointer + totalargs)) {
+				stack_pointer += totalargs;
+			} else {
 				why = WHY_EXCEPTION;
 			}
 			Py_DECREF(v);
 			break;
+		}
 
 		case STORE_ATTR:
 			w = GETITEM(names, oparg);
@@ -1817,6 +1838,19 @@
 			PUSH(x);
 			if (x != NULL) continue;
 			break;
+		
+		case MAKE_BYTES:
+			w = POP();
+			if (PyString_Check(w))
+				x = PyBytes_FromStringAndSize(
+					PyString_AS_STRING(w),
+					PyString_GET_SIZE(w));
+			else
+				x = NULL;
+			Py_DECREF(w);
+			PUSH(x);
+			if (x != NULL) continue;
+			break;
 
 		case LOAD_ATTR:
 			w = GETITEM(names, oparg);
@@ -2155,6 +2189,7 @@
 		    break;
 		}
 
+		case MAKE_CLOSURE:		
 		case MAKE_FUNCTION:
 		{
 		    int posdefaults = oparg & 0xff;
@@ -2165,6 +2200,12 @@
 			v = POP(); /* code object */
 			x = PyFunction_New(v, f->f_globals);
 			Py_DECREF(v);
+			
+			if (x != NULL && opcode == MAKE_CLOSURE) {
+				v = POP();
+				err = PyFunction_SetClosure(x, v);
+				Py_DECREF(v);
+			}
 
 			if (x != NULL && num_annotations > 0) {
 				Py_ssize_t name_ix;
@@ -2218,6 +2259,8 @@
 					u = POP(); /* kw only arg name */
 					/* XXX(nnorwitz): check for errors */
 					PyDict_SetItem(v, u, w);
+					Py_DECREF(w);
+					Py_DECREF(u);
 				}
 				err = PyFunction_SetKwDefaults(x, v);
 				Py_DECREF(v);
@@ -2226,34 +2269,6 @@
 			break;
 		}
 
-		case MAKE_CLOSURE:
-		{
-			v = POP(); /* code object */
-			x = PyFunction_New(v, f->f_globals);
-			Py_DECREF(v);
-			if (x != NULL) {
-				v = POP();
-				err = PyFunction_SetClosure(x, v);
-				Py_DECREF(v);
-			}
-			if (x != NULL && oparg > 0) {
-				v = PyTuple_New(oparg);
-				if (v == NULL) {
-					Py_DECREF(x);
-					x = NULL;
-					break;
-				}
-				while (--oparg >= 0) {
-					w = POP();
-					PyTuple_SET_ITEM(v, oparg, w);
-				}
-				err = PyFunction_SetDefaults(x, v);
-				Py_DECREF(v);
-			}
-			PUSH(x);
-			break;
-		}
-
 		case BUILD_SLICE:
 			if (oparg == 3)
 				w = POP();
@@ -2859,10 +2874,6 @@
 	Py_XDECREF(tmp_type);
 	Py_XDECREF(tmp_value);
 	Py_XDECREF(tmp_tb);
-	/* For b/w compatibility */
-	PySys_SetObject("exc_type", type);
-	PySys_SetObject("exc_value", value);
-	PySys_SetObject("exc_traceback", tb);
 }
 
 static void
@@ -2893,11 +2904,6 @@
 	Py_XDECREF(tmp_value);
 	Py_XDECREF(tmp_tb);
 
-	/* For b/w compatibility */
-	PySys_SetObject("exc_type", frame->f_exc_type);
-	PySys_SetObject("exc_value", frame->f_exc_value);
-	PySys_SetObject("exc_traceback", frame->f_exc_traceback);
-
 	/* Clear the frame's exception info. */
 	tmp_type = frame->f_exc_type;
 	tmp_value = frame->f_exc_value;
@@ -3009,14 +3015,20 @@
 }
 
 /* Iterate v argcnt times and store the results on the stack (via decreasing
-   sp).  Return 1 for success, 0 if error. */
+   sp).  Return 1 for success, 0 if error.
+   
+   If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
+   with a variable target.
+*/
 
 static int
-unpack_iterable(PyObject *v, int argcnt, PyObject **sp)
+unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
 {
-	int i = 0;
+	int i = 0, j = 0;
+	Py_ssize_t ll = 0;
 	PyObject *it;  /* iter(v) */
 	PyObject *w;
+	PyObject *l = NULL; /* variable list */
 
 	assert(v != NULL);
 
@@ -3038,17 +3050,42 @@
 		*--sp = w;
 	}
 
-	/* We better have exhausted the iterator now. */
-	w = PyIter_Next(it);
-	if (w == NULL) {
-		if (PyErr_Occurred())
-			goto Error;
-		Py_DECREF(it);
-		return 1;
+	if (argcntafter == -1) {
+		/* We better have exhausted the iterator now. */
+		w = PyIter_Next(it);
+		if (w == NULL) {
+			if (PyErr_Occurred())
+				goto Error;
+			Py_DECREF(it);
+			return 1;
+		}
+		Py_DECREF(w);
+		PyErr_SetString(PyExc_ValueError, "too many values to unpack");
+		goto Error;
 	}
-	Py_DECREF(w);
-	PyErr_SetString(PyExc_ValueError, "too many values to unpack");
-	/* fall through */
+
+	l = PySequence_List(it);
+	if (l == NULL)
+		goto Error;
+	*--sp = l;
+	i++;
+
+	ll = PyList_GET_SIZE(l);
+	if (ll < argcntafter) {
+		PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack",
+			     argcnt + ll);
+		goto Error;
+	}
+
+	/* Pop the "after-variable" args off the list. */
+	for (j = argcntafter; j > 0; j--, i++) {
+		*--sp = PyList_GET_ITEM(l, ll - j);
+	}
+	/* Resize the list. */
+	((PyListObject *)l)->ob_size = ll - argcntafter;
+	Py_DECREF(it);
+	return 1;
+
 Error:
 	for (; i > 0; i--, sp++)
 		Py_DECREF(*sp);
@@ -3253,13 +3290,6 @@
 }
 
 int
-PyEval_GetRestricted(void)
-{
-	PyFrameObject *current_frame = PyEval_GetFrame();
-	return current_frame == NULL ? 0 : PyFrame_IsRestricted(current_frame);
-}
-
-int
 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
 {
 	PyFrameObject *current_frame = PyEval_GetFrame();
@@ -3673,13 +3703,31 @@
 
 	if (flags & CALL_FLAG_KW) {
 		kwdict = EXT_POP(*pp_stack);
-		if (!(kwdict && PyDict_Check(kwdict))) {
-			PyErr_Format(PyExc_TypeError,
-				     "%s%s argument after ** "
-				     "must be a dictionary",
-				     PyEval_GetFuncName(func),
-				     PyEval_GetFuncDesc(func));
-			goto ext_call_fail;
+		if (!PyDict_Check(kwdict)) {
+			PyObject *d;
+			d = PyDict_New();
+			if (d == NULL)
+				goto ext_call_fail;
+			if (PyDict_Update(d, kwdict) != 0) {
+				Py_DECREF(d);
+				/* PyDict_Update raises attribute
+				 * error (percolated from an attempt
+				 * to get 'keys' attribute) instead of
+				 * a type error if its second argument
+				 * is not a mapping.
+				 */
+				if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
+					PyErr_Format(PyExc_TypeError,
+						     "%.200s%.200s argument after ** "
+						     "must be a mapping, not %.200s",
+						     PyEval_GetFuncName(func),
+						     PyEval_GetFuncDesc(func),
+						     kwdict->ob_type->tp_name);
+				}
+				goto ext_call_fail;
+			}
+			Py_DECREF(kwdict);
+			kwdict = d;
 		}
 	}
 	if (flags & CALL_FLAG_VAR) {
@@ -3690,10 +3738,11 @@
 			if (t == NULL) {
 				if (PyErr_ExceptionMatches(PyExc_TypeError)) {
 					PyErr_Format(PyExc_TypeError,
-						     "%s%s argument after * "
-						     "must be a sequence",
+						     "%.200s%.200s argument after * "
+						     "must be a sequence, not %200s",
 						     PyEval_GetFuncName(func),
-						     PyEval_GetFuncDesc(func));
+						     PyEval_GetFuncDesc(func),
+						     stararg->ob_type->tp_name);
 				}
 				goto ext_call_fail;
 			}
@@ -3770,6 +3819,9 @@
 	return 1;
 }
 
+#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
+			 "BaseException is not allowed"
+
 static PyObject *
 cmp_outcome(int op, register PyObject *v, register PyObject *w)
 {
@@ -3798,28 +3850,18 @@
 			length = PyTuple_Size(w);
 			for (i = 0; i < length; i += 1) {
 				PyObject *exc = PyTuple_GET_ITEM(w, i);
-				if (PyString_Check(exc)) {
-					int ret_val;
-					ret_val = PyErr_WarnEx(
-							PyExc_DeprecationWarning,
-							"catching of string "
-							"exceptions is "
-							"deprecated", 1);
-					if (ret_val == -1)
-						return NULL;
+				if (!PyExceptionClass_Check(exc)) {
+					PyErr_SetString(PyExc_TypeError,
+							CANNOT_CATCH_MSG);
+					return NULL;
 				}
 			}
 		}
 		else {
-			if (PyString_Check(w)) {
-				int ret_val;
-				ret_val = PyErr_WarnEx(
-						PyExc_DeprecationWarning,
-						"catching of string "
-						"exceptions is deprecated",
-						1);
-				if (ret_val == -1)
-					return NULL;
+			if (!PyExceptionClass_Check(w)) {
+				PyErr_SetString(PyExc_TypeError,
+						CANNOT_CATCH_MSG);
+				return NULL;
 			}
 		}
 		res = PyErr_GivenExceptionMatches(v, w);
@@ -3905,58 +3947,6 @@
 	return err;
 }
 
-static PyObject *
-build_class(PyObject *methods, PyObject *bases, PyObject *name)
-{
-	PyObject *metaclass = NULL, *result, *base;
-
-	if (PyDict_Check(methods))
-		metaclass = PyDict_GetItemString(methods, "__metaclass__");
-	if (metaclass != NULL)
-		Py_INCREF(metaclass);
-	else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
-		base = PyTuple_GET_ITEM(bases, 0);
-		metaclass = PyObject_GetAttrString(base, "__class__");
-		if (metaclass == NULL) {
-			PyErr_Clear();
-			metaclass = (PyObject *)base->ob_type;
-			Py_INCREF(metaclass);
-		}
-	}
-	else {
-		PyObject *g = PyEval_GetGlobals();
-		if (g != NULL && PyDict_Check(g))
-			metaclass = PyDict_GetItemString(g, "__metaclass__");
-		if (metaclass == NULL)
-			metaclass = (PyObject *) &PyType_Type;
-		Py_INCREF(metaclass);
-	}
-	result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, NULL);
-	Py_DECREF(metaclass);
-	if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
-		/* A type error here likely means that the user passed
-		   in a base that was not a class (such the random module
-		   instead of the random.random type).  Help them out with
-		   by augmenting the error message with more information.*/
-
-		PyObject *ptype, *pvalue, *ptraceback;
-
-		PyErr_Fetch(&ptype, &pvalue, &ptraceback);
-		if (PyString_Check(pvalue)) {
-			PyObject *newmsg;
-			newmsg = PyString_FromFormat(
-				"Error when calling the metaclass bases\n    %s",
-				PyString_AS_STRING(pvalue));
-			if (newmsg != NULL) {
-				Py_DECREF(pvalue);
-				pvalue = newmsg;
-			}
-		}
-		PyErr_Restore(ptype, pvalue, ptraceback);
-	}
-	return result;
-}
-
 static void
 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
 {

Modified: python/branches/p3yk-noslice/Python/compile.c
==============================================================================
--- python/branches/p3yk-noslice/Python/compile.c	(original)
+++ python/branches/p3yk-noslice/Python/compile.c	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
  *   2. Builds a symbol table.	See symtable.c.
  *   3. Generate code for basic blocks.  See compiler_mod() in this file.
  *   4. Assemble the basic blocks into final code.  See assemble() in
- *      this file.	 
+ *	this file.	 
  *   5. Optimize the byte code (peephole optimizations).  See peephole.c
  *
  * Note that compiler_mod() suggests module, but the module ast type
@@ -39,6 +39,10 @@
 #define DEFAULT_CODE_SIZE 128
 #define DEFAULT_LNOTAB_SIZE 16
 
+#define COMP_GENEXP   0
+#define COMP_LISTCOMP 1
+#define COMP_SETCOMP  2
+
 struct instr {
 	unsigned i_jabs : 1;
 	unsigned i_jrel : 1;
@@ -119,7 +123,7 @@
 
 	int u_firstlineno; /* the first lineno of the block */
 	int u_lineno;	   /* the lineno for the current stmt */
-	bool u_lineno_set; /* boolean to indicate whether instr
+	int u_lineno_set;  /* boolean to indicate whether instr
 			      has been generated with current lineno */
 };
 
@@ -176,6 +180,11 @@
 static int expr_constant(expr_ty e);
 
 static int compiler_with(struct compiler *, stmt_ty);
+static int compiler_call_helper(struct compiler *c, int n,
+				asdl_seq *args,
+				asdl_seq *keywords,
+				expr_ty starargs,
+				expr_ty kwargs);
 
 static PyCodeObject *assemble(struct compiler *, int addNone);
 static PyObject *__doc__;
@@ -195,7 +204,17 @@
 	}
 	p = PyString_AsString(privateobj);
 	nlen = strlen(name);
-	if (name[nlen-1] == '_' && name[nlen-2] == '_') {
+	/* Don't mangle __id__ or names with dots.
+
+	   The only time a name with a dot can occur is when
+	   we are compiling an import statement that has a 
+	   package name.
+
+	   TODO(jhylton): Decide whether we want to support
+	   mangling of the module name, e.g. __M.X.
+	*/
+	if ((name[nlen-1] == '_' && name[nlen-2] == '_') 
+	    || strchr(name, '.')) {
 		Py_INCREF(ident);
 		return ident; /* Don't mangle __whatever__ */
 	}
@@ -354,10 +373,12 @@
 
 	while (PyDict_Next(src, &pos, &k, &v)) {
 		/* XXX this should probably be a macro in symtable.h */
+		long vi;
 		assert(PyInt_Check(v));
-		scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
+		vi = PyInt_AS_LONG(v);
+		scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
 
-		if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
+		if (scope == scope_type || vi & flag) {
 			PyObject *tuple, *item = PyInt_FromLong(i);
 			if (item == NULL) {
 				Py_DECREF(dest);
@@ -430,7 +451,7 @@
 	struct compiler_unit *u;
 
 	u = (struct compiler_unit *)PyObject_Malloc(sizeof(
-                                                struct compiler_unit));
+						struct compiler_unit));
 	if (!u) {
 		PyErr_NoMemory();
 		return 0;
@@ -464,7 +485,7 @@
 	u->u_nfblocks = 0;
 	u->u_firstlineno = lineno;
 	u->u_lineno = 0;
-	u->u_lineno_set = false;
+	u->u_lineno_set = 0;
 	u->u_consts = PyDict_New();
 	if (!u->u_consts) {
 		compiler_unit_free(u);
@@ -599,7 +620,7 @@
 	assert(b != NULL);
 	if (b->b_instr == NULL) {
 		b->b_instr = (struct instr *)PyObject_Malloc(
-                                 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
+				 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
 		if (b->b_instr == NULL) {
 			PyErr_NoMemory();
 			return -1;
@@ -619,7 +640,7 @@
 		}
 		b->b_ialloc <<= 1;
 		tmp = (struct instr *)PyObject_Realloc(
-                                                (void *)b->b_instr, newsize);
+						(void *)b->b_instr, newsize);
 		if (tmp == NULL) {
 			PyErr_NoMemory();
 			return -1;
@@ -643,7 +664,7 @@
 	basicblock *b;
 	if (c->u->u_lineno_set)
 		return;
-	c->u->u_lineno_set = true;
+	c->u->u_lineno_set = 1;
 	b = c->u->u_curblock;
 	b->b_instr[off].i_lineno = c->u->u_lineno;
 }
@@ -668,6 +689,7 @@
 		case UNARY_INVERT:
 			return 0;
 
+		case SET_ADD:
 		case LIST_APPEND:
 			return -2;
 
@@ -707,6 +729,8 @@
 
 		case PRINT_EXPR:
 			return -1;
+		case LOAD_BUILD_CLASS:
+			return 1;
 		case INPLACE_LSHIFT:
 		case INPLACE_RSHIFT:
 		case INPLACE_AND:
@@ -717,8 +741,8 @@
 			return 0;
 		case WITH_CLEANUP:
 			return -1; /* XXX Sometimes more */
-		case LOAD_LOCALS:
-			return 1;
+		case STORE_LOCALS:
+			return -1;
 		case RETURN_VALUE:
 			return -1;
 		case IMPORT_STAR:
@@ -730,8 +754,6 @@
 			return 0;
 		case END_FINALLY:
 			return -1; /* or -2 or -3 if exception occurred */
-		case BUILD_CLASS:
-			return -2;
 
 		case STORE_NAME:
 			return -1;
@@ -739,6 +761,8 @@
 			return 0;
 		case UNPACK_SEQUENCE:
 			return oparg-1;
+		case UNPACK_EX:
+			return (oparg&0xFF) + (oparg>>8);
 		case FOR_ITER:
 			return 1;
 
@@ -762,6 +786,8 @@
 			return 1-oparg;
 		case BUILD_MAP:
 			return 1;
+		case MAKE_BYTES:
+			return 0;
 		case LOAD_ATTR:
 			return 0;
 		case COMPARE_OP:
@@ -807,6 +833,8 @@
 			return -NARGS(oparg)-2;
 		case MAKE_FUNCTION:
 			return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
+		case MAKE_CLOSURE:
+			return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
 #undef NARGS
 		case BUILD_SLICE:
 			if (oparg == 3)
@@ -814,8 +842,6 @@
 			else
 				return -1;
 
-		case MAKE_CLOSURE:
-			return -oparg;
 		case LOAD_CLOSURE:
 			return 1;
 		case LOAD_DEREF:
@@ -1074,7 +1100,8 @@
 	if (!asdl_seq_LEN(stmts))
 		return 1;
 	st = (stmt_ty)asdl_seq_GET(stmts, 0);
-	if (compiler_isdocstring(st)) {
+	if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
+		/* don't generate docstrings if -OO */
 		i = 1;
 		VISIT(c, expr, st->v.Expr.value);
 		if (!compiler_nameop(c, __doc__, Store))
@@ -1109,7 +1136,7 @@
 	case Interactive_kind:
 		c->c_interactive = 1;
 		VISIT_SEQ_IN_SCOPE(c, stmt, 
-                                        mod->v.Interactive.body);
+					mod->v.Interactive.body);
 		break;
 	case Expression_kind:
 		VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
@@ -1200,7 +1227,8 @@
 		else /* (reftype == FREE) */
 			arg = compiler_lookup_arg(c->u->u_freevars, name);
 		if (arg == -1) {
-			printf("lookup %s in %s %d %d\n"
+			fprintf(stderr,
+				"lookup %s in %s %d %d\n"
 				"freevars of %s: %s\n",
 				PyObject_REPR(name), 
 				PyString_AS_STRING(c->u->u_name), 
@@ -1232,54 +1260,6 @@
 }
 
 static int
-compiler_unpack_nested(struct compiler *c, asdl_seq *args) {
-	int i, len;
-	len = asdl_seq_LEN(args);
-	ADDOP_I(c, UNPACK_SEQUENCE, len);
-	for (i = 0; i < len; i++) {
-		arg_ty elt = (arg_ty)asdl_seq_GET(args, i);
-		switch (elt->kind) {
-		case SimpleArg_kind:
-			if (!compiler_nameop(c, elt->v.SimpleArg.arg, Store))
-				return 0;
-			break;
-		case NestedArgs_kind:
-			if (!compiler_unpack_nested(c, elt->v.NestedArgs.args))
-				return 0;
-			break;
-		default:
-			return 0;
-		}
-    }
-    return 1;
-}
-
-static int
-compiler_arguments(struct compiler *c, arguments_ty args)
-{
-	int i;
-	int n = asdl_seq_LEN(args->args);
-
-	for (i = 0; i < n; i++) {
-		arg_ty arg = (arg_ty)asdl_seq_GET(args->args, i);
-		if (arg->kind == NestedArgs_kind) {
-			PyObject *id = PyString_FromFormat(".%d", i);
-			if (id == NULL) {
-				return 0;
-			}
-			if (!compiler_nameop(c, id, Load)) {
-				Py_DECREF(id);
-				return 0;
-			}
-			Py_DECREF(id);
-			if (!compiler_unpack_nested(c, arg->v.NestedArgs.args))
-				return 0;
-		}
-	}
-	return 1;
-}
-
-static int
 compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
 	                      asdl_seq *kw_defaults)
 {
@@ -1288,7 +1268,7 @@
 		arg_ty arg = asdl_seq_GET(kwonlyargs, i);
 		expr_ty default_ = asdl_seq_GET(kw_defaults, i);
 		if (default_) {
-			ADDOP_O(c, LOAD_CONST, arg->v.SimpleArg.arg, consts);
+			ADDOP_O(c, LOAD_CONST, arg->arg, consts);
 			if (!compiler_visit_expr(c, default_)) {
 			    return -1;
 			}
@@ -1317,17 +1297,11 @@
 	int i, error;
 	for (i = 0; i < asdl_seq_LEN(args); i++) {
 		arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
-		if (arg->kind == NestedArgs_kind)
-			error = compiler_visit_argannotations(
-			           c,
-			           arg->v.NestedArgs.args,
-			           names);
-		else
-			error = compiler_visit_argannotation(
-			           c,
-			           arg->v.SimpleArg.arg,
-			           arg->v.SimpleArg.annotation,
-			           names);
+		error = compiler_visit_argannotation(
+				c,
+			        arg->arg,
+			        arg->annotation,
+			        names);
 		if (error)
 			return error;
 	}
@@ -1338,8 +1312,12 @@
 compiler_visit_annotations(struct compiler *c, arguments_ty args,
                            expr_ty returns)
 {
-	/* push arg annotations and a list of the argument names. return the #
-	   of items pushed. this is out-of-order wrt the source code. */
+	/* Push arg annotations and a list of the argument names. Return the #
+	   of items pushed. The expressions are evaluated out-of-order wrt the 
+	   source code. 
+	   
+	   More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
+	   */
 	static identifier return_str;
 	PyObject *names;
 	int len;
@@ -1370,6 +1348,12 @@
 	}
 
 	len = PyList_GET_SIZE(names);
+	if (len > 65534) {
+		/* len must fit in 16 bits, and len is incremented below */
+		PyErr_SetString(PyExc_SyntaxError,
+				"too many annotations");
+		goto error;
+	}	
 	if (len) {
 		/* convert names to a tuple and place on stack */
 		PyObject *elt;
@@ -1401,7 +1385,7 @@
 	PyObject *first_const = Py_None;
 	arguments_ty args = s->v.FunctionDef.args;
 	expr_ty returns = s->v.FunctionDef.returns;
-	asdl_seq* decos = s->v.FunctionDef.decorators;
+	asdl_seq* decos = s->v.FunctionDef.decorator_list;
 	stmt_ty st;
 	int i, n, docstring, kw_default_count = 0, arglength;
 	int num_annotations;
@@ -1420,6 +1404,9 @@
 	if (args->defaults)
 		VISIT_SEQ(c, expr, args->defaults);
 	num_annotations = compiler_visit_annotations(c, args, returns);
+	if (num_annotations < 0)
+		return 0;
+	assert((num_annotations & 0xFFFF) == num_annotations);
 
 	if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
 				  s->lineno))
@@ -1434,9 +1421,6 @@
 	    return 0;
 	}
 
-	/* unpack nested arguments */
-	compiler_arguments(c, args);
-
 	c->u->u_argcount = asdl_seq_LEN(args->args);
 	c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
 	n = asdl_seq_LEN(s->v.FunctionDef.body);
@@ -1467,54 +1451,131 @@
 static int
 compiler_class(struct compiler *c, stmt_ty s)
 {
-	int n;
+	static PyObject *locals = NULL;
 	PyCodeObject *co;
 	PyObject *str;
-	/* push class name on stack, needed by BUILD_CLASS */
-	ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
-	/* push the tuple of base classes on the stack */
-	n = asdl_seq_LEN(s->v.ClassDef.bases);
-	if (n > 0)
-		VISIT_SEQ(c, expr, s->v.ClassDef.bases);
-	ADDOP_I(c, BUILD_TUPLE, n);
-	if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
-				  s->lineno))
-		return 0;
-	c->u->u_private = s->v.ClassDef.name;
-	Py_INCREF(c->u->u_private);
-	str = PyString_InternFromString("__name__");
-	if (!str || !compiler_nameop(c, str, Load)) {
-		Py_XDECREF(str);
-		compiler_exit_scope(c);
-		return 0;
-	}
-	
-	Py_DECREF(str);
-	str = PyString_InternFromString("__module__");
-	if (!str || !compiler_nameop(c, str, Store)) {
-		Py_XDECREF(str);
-		compiler_exit_scope(c);
-		return 0;
-	}
-	Py_DECREF(str);
+	PySTEntryObject *ste;
+	int err, i;
+	asdl_seq* decos = s->v.ClassDef.decorator_list;
 
-	if (!compiler_body(c, s->v.ClassDef.body)) {
-		compiler_exit_scope(c);
-		return 0;
+        if (!compiler_decorators(c, decos))
+                return 0;
+
+	/* initialize statics */
+	if (locals == NULL) {
+		locals = PyString_FromString("__locals__");
+		if (locals == NULL)
+			return 0;
 	}
 
-	ADDOP_IN_SCOPE(c, LOAD_LOCALS);
-	ADDOP_IN_SCOPE(c, RETURN_VALUE);
-	co = assemble(c, 1);
+	/* ultimately generate code for:
+	     <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
+	   where:
+	     <func> is a function/closure created from the class body;
+                    it has a single argument (__locals__) where the dict
+		    (or MutableSequence) representing the locals is passed
+	     <name> is the class name
+             <bases> is the positional arguments and *varargs argument
+	     <keywords> is the keyword arguments and **kwds argument
+	   This borrows from compiler_call.
+	*/
+
+	/* 0. Create a fake argument named __locals__ */
+	ste = PySymtable_Lookup(c->c_st, s);
+	if (ste == NULL)
+		return 0;
+	assert(PyList_Check(ste->ste_varnames));
+	err = PyList_Append(ste->ste_varnames, locals);
+	Py_DECREF(ste);
+	if (err < 0)
+		return 0;
+
+	/* 1. compile the class body into a code object */
+	if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
+		return 0;
+	/* this block represents what we do in the new scope */
+	{
+		/* use the class name for name mangling */
+		Py_INCREF(s->v.ClassDef.name);
+		c->u->u_private = s->v.ClassDef.name;
+		/* force it to have one mandatory argument */
+		c->u->u_argcount = 1;
+		/* load the first argument (__locals__) ... */
+		ADDOP_I(c, LOAD_FAST, 0);
+		/* ... and store it into f_locals */
+		ADDOP_IN_SCOPE(c, STORE_LOCALS);
+		/* load (global) __name__ ... */
+		str = PyString_InternFromString("__name__");
+		if (!str || !compiler_nameop(c, str, Load)) {
+			Py_XDECREF(str);
+			compiler_exit_scope(c);
+			return 0;
+		}
+		Py_DECREF(str);
+		/* ... and store it as __module__ */
+		str = PyString_InternFromString("__module__");
+		if (!str || !compiler_nameop(c, str, Store)) {
+			Py_XDECREF(str);
+			compiler_exit_scope(c);
+			return 0;
+		}
+		Py_DECREF(str);
+		/* compile the body proper */
+		if (!compiler_body(c, s->v.ClassDef.body)) {
+			compiler_exit_scope(c);
+			return 0;
+		}
+		/* return the (empty) __class__ cell */
+		str = PyString_InternFromString("__class__");
+		if (str == NULL) {
+			compiler_exit_scope(c);
+			return 0;
+		}
+		i = compiler_lookup_arg(c->u->u_cellvars, str);
+		Py_DECREF(str);
+		if (i == -1) {
+			/* This happens when nobody references the cell */
+			PyErr_Clear();
+			/* Return None */
+			ADDOP_O(c, LOAD_CONST, Py_None, consts);
+                }
+		else {
+			/* Return the cell where to store __class__ */
+			ADDOP_I(c, LOAD_CLOSURE, i);
+		}
+		ADDOP_IN_SCOPE(c, RETURN_VALUE);
+		/* create the code object */
+		co = assemble(c, 1);
+	}
+	/* leave the new scope */
 	compiler_exit_scope(c);
 	if (co == NULL)
 		return 0;
 
+	/* 2. load the 'build_class' function */
+	ADDOP(c, LOAD_BUILD_CLASS);
+
+	/* 3. load a function (or closure) made from the code object */
 	compiler_make_closure(c, co, 0);
 	Py_DECREF(co);
 
-	ADDOP_I(c, CALL_FUNCTION, 0);
-	ADDOP(c, BUILD_CLASS);
+	/* 4. load class name */
+	ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
+
+	/* 5. generate the rest of the code for the call */
+	if (!compiler_call_helper(c, 2,
+				  s->v.ClassDef.bases,
+				  s->v.ClassDef.keywords,
+				  s->v.ClassDef.starargs,
+				  s->v.ClassDef.kwargs))
+		return 0;
+
+	/* 6. apply decorators */
+        for (i = 0; i < asdl_seq_LEN(decos); i++) {
+                ADDOP_I(c, CALL_FUNCTION, 1);
+        }
+
+	/* 7. store into <name> */
 	if (!compiler_nameop(c, s->v.ClassDef.name, Store))
 		return 0;
 	return 1;
@@ -1570,9 +1631,6 @@
 	if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
 		return 0;
 
-	/* unpack nested arguments */
-	compiler_arguments(c, args);
-	
 	c->u->u_argcount = asdl_seq_LEN(args->args);
 	c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
 	VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
@@ -1621,7 +1679,7 @@
 		compiler_use_next_block(c, next);
 		ADDOP(c, POP_TOP);
 		if (s->v.If.orelse)
-	    		VISIT_SEQ(c, stmt, s->v.If.orelse);
+			VISIT_SEQ(c, stmt, s->v.If.orelse);
 	}
 	compiler_use_next_block(c, end);
 	return 1;
@@ -1646,7 +1704,7 @@
 	/* XXX(nnorwitz): is there a better way to handle this?
 	   for loops are special, we want to be able to trace them
 	   each time around, so we need to set an extra line number. */
-	c->u->u_lineno_set = false;
+	c->u->u_lineno_set = 0;
 	ADDOP_JREL(c, FOR_ITER, cleanup);
 	VISIT(c, expr, s->v.For.target);
 	VISIT_SEQ(c, stmt, s->v.For.body);
@@ -1869,8 +1927,8 @@
 						s->v.TryExcept.handlers, i);
 		if (!handler->type && i < n-1)
 		    return compiler_error(c, "default 'except:' must be last");
-        c->u->u_lineno_set = false;
-        c->u->u_lineno = handler->lineno;
+	c->u->u_lineno_set = 0;
+	c->u->u_lineno = handler->lineno;
 		except = compiler_new_block(c);
 		if (except == NULL)
 			return 0;
@@ -2132,7 +2190,7 @@
 
 	/* Always assign a lineno to the next instruction for a stmt. */
 	c->u->u_lineno = s->lineno;
-	c->u->u_lineno_set = false;
+	c->u->u_lineno_set = 0;
 
 	switch (s->kind) {
 	case FunctionDef_kind:
@@ -2197,6 +2255,7 @@
 	case ImportFrom_kind:
 		return compiler_from_import(c, s);
 	case Global_kind:
+	case Nonlocal_kind:
 		break;
 	case Expr_kind:
 		if (c->c_interactive && c->c_nestlevel <= 1) {
@@ -2212,7 +2271,7 @@
 	case Pass_kind:
 		break;
 	case Break_kind:
-                if (!compiler_in_loop(c))
+		if (!compiler_in_loop(c))
 			return compiler_error(c, "'break' outside loop");
 		ADDOP(c, BREAK_LOOP);
 		break;
@@ -2498,7 +2557,21 @@
 {
 	int n = asdl_seq_LEN(e->v.List.elts);
 	if (e->v.List.ctx == Store) {
-		ADDOP_I(c, UNPACK_SEQUENCE, n);
+		int i, seen_star = 0;
+		for (i = 0; i < n; i++) {
+			expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
+			if (elt->kind == Starred_kind && !seen_star) {
+				ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
+				seen_star = 1;
+				asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
+			} else if (elt->kind == Starred_kind) {
+				return compiler_error(c,
+					"two starred expressions in assignment");
+			}
+		}
+		if (!seen_star) {
+			ADDOP_I(c, UNPACK_SEQUENCE, n);
+		}
 	}
 	VISIT_SEQ(c, expr, e->v.List.elts);
 	if (e->v.List.ctx == Load) {
@@ -2512,7 +2585,21 @@
 {
 	int n = asdl_seq_LEN(e->v.Tuple.elts);
 	if (e->v.Tuple.ctx == Store) {
-		ADDOP_I(c, UNPACK_SEQUENCE, n);
+		int i, seen_star = 0;
+		for (i = 0; i < n; i++) {
+			expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
+			if (elt->kind == Starred_kind && !seen_star) {
+				ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
+				seen_star = 1;
+				asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
+			} else if (elt->kind == Starred_kind) {
+				return compiler_error(c,
+					"two starred expressions in assignment");
+			}
+		}
+		if (!seen_star) {
+			ADDOP_I(c, UNPACK_SEQUENCE, n);
+		}
 	}
 	VISIT_SEQ(c, expr, e->v.Tuple.elts);
 	if (e->v.Tuple.ctx == Load) {
@@ -2536,20 +2623,20 @@
 		if (cleanup == NULL)
 		    return 0;
 		VISIT(c, expr, 
-                        (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
+			(expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
 	}
 	for (i = 1; i < n; i++) {
 		ADDOP(c, DUP_TOP);
 		ADDOP(c, ROT_THREE);
 		ADDOP_I(c, COMPARE_OP,
 			cmpop((cmpop_ty)(asdl_seq_GET(
-                                                  e->v.Compare.ops, i - 1))));
+						  e->v.Compare.ops, i - 1))));
 		ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
 		NEXT_BLOCK(c);
 		ADDOP(c, POP_TOP);
 		if (i < (n - 1))
 		    VISIT(c, expr, 
-                            (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
+			    (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
 	}
 	VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
 	ADDOP_I(c, COMPARE_OP,
@@ -2570,21 +2657,37 @@
 static int
 compiler_call(struct compiler *c, expr_ty e)
 {
-	int n, code = 0;
-
 	VISIT(c, expr, e->v.Call.func);
-	n = asdl_seq_LEN(e->v.Call.args);
-	VISIT_SEQ(c, expr, e->v.Call.args);
-	if (e->v.Call.keywords) {
-		VISIT_SEQ(c, keyword, e->v.Call.keywords);
-		n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
+	return compiler_call_helper(c, 0,
+				    e->v.Call.args,
+				    e->v.Call.keywords,
+				    e->v.Call.starargs,
+				    e->v.Call.kwargs);
+}
+
+/* shared code between compiler_call and compiler_class */
+static int
+compiler_call_helper(struct compiler *c,
+		     int n, /* Args already pushed */
+		     asdl_seq *args,
+		     asdl_seq *keywords,
+		     expr_ty starargs,
+		     expr_ty kwargs)
+{
+	int code = 0;
+
+	n += asdl_seq_LEN(args);
+	VISIT_SEQ(c, expr, args);
+	if (keywords) {
+		VISIT_SEQ(c, keyword, keywords);
+		n |= asdl_seq_LEN(keywords) << 8;
 	}
-	if (e->v.Call.starargs) {
-		VISIT(c, expr, e->v.Call.starargs);
+	if (starargs) {
+		VISIT(c, expr, starargs);
 		code |= 1;
 	}
-	if (e->v.Call.kwargs) {
-		VISIT(c, expr, e->v.Call.kwargs);
+	if (kwargs) {
+		VISIT(c, expr, kwargs);
 		code |= 2;
 	}
 	switch (code) {
@@ -2604,122 +2707,45 @@
 	return 1;
 }
 
-static int
-compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
-			    asdl_seq *generators, int gen_index, 
-			    expr_ty elt)
-{
-	/* generate code for the iterator, then each of the ifs,
-	   and then write to the element */
-
-	comprehension_ty l;
-	basicblock *start, *anchor, *skip, *if_cleanup;
-	int i, n;
-
-	start = compiler_new_block(c);
-	skip = compiler_new_block(c);
-	if_cleanup = compiler_new_block(c);
-	anchor = compiler_new_block(c);
-
-	if (start == NULL || skip == NULL || if_cleanup == NULL ||
-		anchor == NULL)
-	    return 0;
-
-	l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
-	VISIT(c, expr, l->iter);
-	ADDOP(c, GET_ITER);
-	compiler_use_next_block(c, start);
-	ADDOP_JREL(c, FOR_ITER, anchor);
-	NEXT_BLOCK(c);
-	VISIT(c, expr, l->target);
-
-	/* XXX this needs to be cleaned up...a lot! */
-	n = asdl_seq_LEN(l->ifs);
-	for (i = 0; i < n; i++) {
-		expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
-		VISIT(c, expr, e);
-		ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
-		NEXT_BLOCK(c);
-		ADDOP(c, POP_TOP);
-	} 
 
-	if (++gen_index < asdl_seq_LEN(generators))
-	    if (!compiler_listcomp_generator(c, tmpname, 
-					     generators, gen_index, elt))
-		return 0;
+/* List and set comprehensions and generator expressions work by creating a
+  nested function to perform the actual iteration. This means that the
+  iteration variables don't leak into the current scope.
+  The defined function is called immediately following its definition, with the
+  result of that call being the result of the expression.
+  The LC/SC version returns the populated container, while the GE version is
+  flagged in symtable.c as a generator, so it returns the generator object
+  when the function is called.
+  This code *knows* that the loop cannot contain break, continue, or return,
+  so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
 
-	/* only append after the last for generator */
-	if (gen_index >= asdl_seq_LEN(generators)) {
-	    if (!compiler_nameop(c, tmpname, Load))
-		return 0;
-	    VISIT(c, expr, elt);
-	    ADDOP(c, LIST_APPEND);
-
-	    compiler_use_next_block(c, skip);
-	}
-	for (i = 0; i < n; i++) {
-		ADDOP_I(c, JUMP_FORWARD, 1);
-		if (i == 0)
-		    compiler_use_next_block(c, if_cleanup);
-		ADDOP(c, POP_TOP);
-	} 
-	ADDOP_JABS(c, JUMP_ABSOLUTE, start);
-	compiler_use_next_block(c, anchor);
-	/* delete the temporary list name added to locals */
-	if (gen_index == 1)
-	    if (!compiler_nameop(c, tmpname, Del))
-		return 0;
-	
-	return 1;
-}
-
-static int
-compiler_listcomp(struct compiler *c, expr_ty e)
-{
-	identifier tmp;
-	int rc = 0;
-	asdl_seq *generators = e->v.ListComp.generators;
-
-	assert(e->kind == ListComp_kind);
-	tmp = compiler_new_tmpname(c);
-	if (!tmp)
-		return 0;
-	ADDOP_I(c, BUILD_LIST, 0);
-	ADDOP(c, DUP_TOP);
-	if (compiler_nameop(c, tmp, Store))
-	    rc = compiler_listcomp_generator(c, tmp, generators, 0, 
-					     e->v.ListComp.elt);
-	Py_DECREF(tmp);
-	return rc;
-}
+  Possible cleanups:
+    - iterate over the generator sequence instead of using recursion
+*/
 
 static int
-compiler_genexp_generator(struct compiler *c,
-			  asdl_seq *generators, int gen_index, 
-			  expr_ty elt)
+compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
+				 asdl_seq *generators, int gen_index, 
+				 expr_ty elt, int type)
 {
 	/* generate code for the iterator, then each of the ifs,
 	   and then write to the element */
 
-	comprehension_ty ge;
-	basicblock *start, *anchor, *skip, *if_cleanup, *end;
+	comprehension_ty gen;
+	basicblock *start, *anchor, *skip, *if_cleanup;
 	int i, n;
 
 	start = compiler_new_block(c);
 	skip = compiler_new_block(c);
 	if_cleanup = compiler_new_block(c);
 	anchor = compiler_new_block(c);
-	end = compiler_new_block(c);
 
 	if (start == NULL || skip == NULL || if_cleanup == NULL ||
-	    anchor == NULL || end == NULL)
-		return 0;
-
-	ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
-	ADDOP_JREL(c, SETUP_LOOP, end);
-	if (!compiler_push_fblock(c, LOOP, start))
+	    anchor == NULL)
 		return 0;
 
+	gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
+	
 	if (gen_index == 0) {
 		/* Receive outermost iter as an implicit argument */
 		c->u->u_argcount = 1;
@@ -2727,18 +2753,18 @@
 	}
 	else {
 		/* Sub-iter - calculate on the fly */
-		VISIT(c, expr, ge->iter);
+		VISIT(c, expr, gen->iter);
 		ADDOP(c, GET_ITER);
 	}
 	compiler_use_next_block(c, start);
 	ADDOP_JREL(c, FOR_ITER, anchor);
 	NEXT_BLOCK(c);
-	VISIT(c, expr, ge->target);
+	VISIT(c, expr, gen->target);
 
 	/* XXX this needs to be cleaned up...a lot! */
-	n = asdl_seq_LEN(ge->ifs);
+	n = asdl_seq_LEN(gen->ifs);
 	for (i = 0; i < n; i++) {
-		expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
+		expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
 		VISIT(c, expr, e);
 		ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
 		NEXT_BLOCK(c);
@@ -2746,14 +2772,35 @@
 	} 
 
 	if (++gen_index < asdl_seq_LEN(generators))
-		if (!compiler_genexp_generator(c, generators, gen_index, elt))
-			return 0;
+		if (!compiler_comprehension_generator(c, tmpname, 
+						      generators, gen_index,
+						      elt, type))
+		return 0;
 
-	/* only append after the last 'for' generator */
+	/* only append after the last for generator */
 	if (gen_index >= asdl_seq_LEN(generators)) {
-		VISIT(c, expr, elt);
-		ADDOP(c, YIELD_VALUE);
-		ADDOP(c, POP_TOP);
+		/* comprehension specific code */
+		switch (type) {
+		case COMP_GENEXP:
+			VISIT(c, expr, elt);
+			ADDOP(c, YIELD_VALUE);
+			ADDOP(c, POP_TOP);
+			break;
+		case COMP_LISTCOMP:
+			if (!compiler_nameop(c, tmpname, Load))
+				return 0;
+			VISIT(c, expr, elt);
+			ADDOP(c, LIST_APPEND);
+			break;
+		case COMP_SETCOMP:
+			if (!compiler_nameop(c, tmpname, Load))
+				return 0;
+			VISIT(c, expr, elt);
+			ADDOP(c, SET_ADD);
+			break;
+		default:
+			return 0;
+		}
 
 		compiler_use_next_block(c, skip);
 	}
@@ -2761,53 +2808,117 @@
 		ADDOP_I(c, JUMP_FORWARD, 1);
 		if (i == 0)
 			compiler_use_next_block(c, if_cleanup);
-
+		
 		ADDOP(c, POP_TOP);
 	} 
 	ADDOP_JABS(c, JUMP_ABSOLUTE, start);
 	compiler_use_next_block(c, anchor);
-	ADDOP(c, POP_BLOCK);
-	compiler_pop_fblock(c, LOOP, start);
-	compiler_use_next_block(c, end);
 
 	return 1;
 }
 
 static int
-compiler_genexp(struct compiler *c, expr_ty e)
+compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
+		       asdl_seq *generators, expr_ty elt)
 {
-	static identifier name;
-	PyCodeObject *co;
-	expr_ty outermost_iter = ((comprehension_ty)
-				 (asdl_seq_GET(e->v.GeneratorExp.generators,
-					       0)))->iter;
+	PyCodeObject *co = NULL;
+	identifier tmp = NULL;
+	expr_ty outermost_iter;
 
-	if (!name) {
-		name = PyString_FromString("<genexpr>");
-		if (!name)
-			return 0;
-	}
+	outermost_iter = ((comprehension_ty)
+			  asdl_seq_GET(generators, 0))->iter;
 
 	if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
-		return 0;
-	compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
-				  e->v.GeneratorExp.elt);
+		goto error;
+	
+	if (type != COMP_GENEXP) {
+		tmp = compiler_new_tmpname(c);
+		if (!tmp)
+			goto error_in_scope;
+
+		ADDOP_I(c, (type == COMP_LISTCOMP ?
+			    BUILD_LIST : BUILD_SET), 0);
+		ADDOP(c, DUP_TOP);
+		if (!compiler_nameop(c, tmp, Store))
+			goto error_in_scope;
+	}
+	
+	if (!compiler_comprehension_generator(c, tmp, generators, 0, elt, type))
+		goto error_in_scope;
+	
+	if (type != COMP_GENEXP) {
+		ADDOP(c, RETURN_VALUE);
+	}
+
 	co = assemble(c, 1);
 	compiler_exit_scope(c);
 	if (co == NULL)
-		return 0;
+		goto error;
 
-	compiler_make_closure(c, co, 0);
+	if (!compiler_make_closure(c, co, 0))
+		goto error;
 	Py_DECREF(co);
+	Py_XDECREF(tmp);
 
 	VISIT(c, expr, outermost_iter);
 	ADDOP(c, GET_ITER);
 	ADDOP_I(c, CALL_FUNCTION, 1);
-
 	return 1;
+error_in_scope:
+	compiler_exit_scope(c);
+error:
+	Py_XDECREF(co);
+	Py_XDECREF(tmp);
+	return 0;
+}
+
+static int
+compiler_genexp(struct compiler *c, expr_ty e)
+{
+	static identifier name;
+	if (!name) {
+		name = PyString_FromString("<genexp>");
+		if (!name)
+			return 0;
+	}
+	assert(e->kind == GeneratorExp_kind);
+	return compiler_comprehension(c, e, COMP_GENEXP, name,
+				      e->v.GeneratorExp.generators,
+				      e->v.GeneratorExp.elt);
 }
 
 static int
+compiler_listcomp(struct compiler *c, expr_ty e)
+{
+	static identifier name;
+	if (!name) {
+		name = PyString_FromString("<listcomp>");
+		if (!name)
+			return 0;
+	}
+	assert(e->kind == ListComp_kind);
+	return compiler_comprehension(c, e, COMP_LISTCOMP, name,
+				      e->v.ListComp.generators,
+				      e->v.ListComp.elt);
+}
+
+static int
+compiler_setcomp(struct compiler *c, expr_ty e)
+{
+	static identifier name;
+	if (!name) {
+		name = PyString_FromString("<setcomp>");
+		if (!name)
+			return 0;
+	}
+	assert(e->kind == SetComp_kind);
+	return compiler_comprehension(c, e, COMP_SETCOMP, name,
+				      e->v.SetComp.generators,
+				      e->v.SetComp.elt);
+}
+
+
+static int
 compiler_visit_keyword(struct compiler *c, keyword_ty k)
 {
 	ADDOP_O(c, LOAD_CONST, k->arg, consts);
@@ -2824,6 +2935,7 @@
 static int
 expr_constant(expr_ty e)
 {
+	char *id;
 	switch (e->kind) {
 	case Ellipsis_kind:
 		return 1;
@@ -2832,11 +2944,13 @@
 	case Str_kind:
 		return PyObject_IsTrue(e->v.Str.s);
 	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),
-		           "__debug__") == 0)
-			   return ! Py_OptimizeFlag;
+		/* optimize away names that can't be reassigned */
+		id = PyString_AS_STRING(e->v.Name.id);
+		if (strcmp(id, "True") == 0) return 1;
+		if (strcmp(id, "False") == 0) return 0;
+		if (strcmp(id, "None") == 0) return 0;
+		if (strcmp(id, "__debug__") == 0)
+			return ! Py_OptimizeFlag;
 		/* fall through */
 	default:
 		return -1;
@@ -2982,11 +3096,11 @@
 	int i, n;
 
 	/* If expr e has a different line number than the last expr/stmt,
-           set a new line number for the next instruction.
-        */
+	   set a new line number for the next instruction.
+	*/
 	if (e->lineno > c->u->u_lineno) {
 		c->u->u_lineno = e->lineno;
-		c->u->u_lineno_set = false;
+		c->u->u_lineno_set = 0;
 	}
 	switch (e->kind) {
 	case BoolOp_kind:
@@ -3013,10 +3127,10 @@
 		for (i = 0; i < n; i++) {
 			ADDOP(c, DUP_TOP);
 			VISIT(c, expr, 
-                                (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
+				(expr_ty)asdl_seq_GET(e->v.Dict.values, i));
 			ADDOP(c, ROT_TWO);
 			VISIT(c, expr, 
-                                (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
+				(expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
 			ADDOP(c, STORE_SUBSCR);
 		}
 		break;
@@ -3025,10 +3139,12 @@
 		VISIT_SEQ(c, expr, e->v.Set.elts);
 		ADDOP_I(c, BUILD_SET, n);
 		break;
-	case ListComp_kind:
-		return compiler_listcomp(c, e);
 	case GeneratorExp_kind:
 		return compiler_genexp(c, e);
+	case ListComp_kind:
+		return compiler_listcomp(c, e);
+	case SetComp_kind:
+		return compiler_setcomp(c, e);
 	case Yield_kind:
 		if (c->u->u_ste->ste_type != FunctionBlock)
 			return compiler_error(c, "'yield' outside function");
@@ -3050,6 +3166,10 @@
 	case Str_kind:
 		ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
 		break;
+	case Bytes_kind:
+		ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
+		ADDOP(c, MAKE_BYTES);
+		break;
 	case Ellipsis_kind:
 		ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
 		break;
@@ -3108,6 +3228,18 @@
 			return 0;
 		}
 		break;
+	case Starred_kind:
+		switch (e->v.Starred.ctx) {
+		case Store:
+			/* In all legitimate cases, the Starred node was already replaced
+			 * by compiler_list/compiler_tuple. XXX: is that okay? */
+			return compiler_error(c,
+				"starred assignment target must be in a list or tuple");
+		default:
+			return compiler_error(c, 
+				"can use starred expression only as assignment target");
+		}
+		break;
 	case Name_kind:
 		return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
 	/* child nodes of List and Tuple will have expr_context set */
@@ -3192,13 +3324,13 @@
 
 static int
 compiler_in_loop(struct compiler *c) {
-        int i;
-        struct compiler_unit *u = c->u;
-        for (i = 0; i < u->u_nfblocks; ++i) {
-                if (u->u_fblock[i].fb_type == LOOP)
-                        return 1;
-        }
-        return 0;
+	int i;
+	struct compiler_unit *u = c->u;
+	for (i = 0; i < u->u_nfblocks; ++i) {
+		if (u->u_fblock[i].fb_type == LOOP)
+			return 1;
+	}
+	return 0;
 }
 /* Raises a SyntaxError and returns 0.
    If something goes wrong, a different exception may be raised.
@@ -3331,7 +3463,7 @@
 			int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
 			for (i = 0; i < n; i++) {
 				slice_ty sub = (slice_ty)asdl_seq_GET(
-                                        s->v.ExtSlice.dims, i);
+					s->v.ExtSlice.dims, i);
 				if (!compiler_visit_nested_slice(c, sub, ctx))
 					return 0;
 			}
@@ -3346,7 +3478,6 @@
 	return compiler_handle_subscr(c, kindname, ctx);
 }
 
-
 /* End of the compiler section, beginning of the assembler section */
 
 /* do depth-first search of basic block graph, starting with block.
@@ -3529,7 +3660,7 @@
 increment is < 256.  So, in the example above, assemble_lnotab (it used
 to be called com_set_lineno) should not (as was actually done until 2.2)
 expand 300, 300 to 255, 255, 45, 45, 
-            but to 255,   0, 45, 255, 0, 45.
+	    but to 255,	  0, 45, 255, 0, 45.
 */
 
 static int

Modified: python/branches/p3yk-noslice/Python/dynload_win.c
==============================================================================
--- python/branches/p3yk-noslice/Python/dynload_win.c	(original)
+++ python/branches/p3yk-noslice/Python/dynload_win.c	Wed Jul 11 15:40:56 2007
@@ -1,7 +1,6 @@
 
 /* Support for dynamic loading of extension modules */
 
-#include <windows.h>
 #ifdef HAVE_DIRECT_H
 #include <direct.h>
 #endif
@@ -9,20 +8,13 @@
 
 #include "Python.h"
 #include "importdl.h"
+#include <windows.h>
 
 const struct filedescr _PyImport_DynLoadFiletab[] = {
 #ifdef _DEBUG
 	{"_d.pyd", "rb", C_EXTENSION},
-	/* Temporarily disable .dll, to avoid conflicts between sqlite3.dll
-	   and the sqlite3 package. If this needs to be reverted for 2.5,
-	   some other solution for the naming conflict must be found.
-	{"_d.dll", "rb", C_EXTENSION},
-	*/
 #else
 	{".pyd", "rb", C_EXTENSION},
-	/* Likewise
-	{".dll", "rb", C_EXTENSION},
-	*/
 #endif
 	{0, 0}
 };

Modified: python/branches/p3yk-noslice/Python/errors.c
==============================================================================
--- python/branches/p3yk-noslice/Python/errors.c	(original)
+++ python/branches/p3yk-noslice/Python/errors.c	Wed Jul 11 15:40:56 2007
@@ -599,8 +599,9 @@
 		PyFile_WriteString("Exception ", f);
 		if (t) {
 			PyObject* moduleName;
-			char* className = PyExceptionClass_Name(t);
-
+			char* className;
+			assert(PyExceptionClass_Check(t));
+			className = PyExceptionClass_Name(t);
 			if (className != NULL) {
 				char *dot = strrchr(className, '.');
 				if (dot != NULL)
@@ -612,7 +613,8 @@
 				PyFile_WriteString("<unknown>", f);
 			else {
 				char* modstr = PyString_AsString(moduleName);
-				if (modstr)
+				if (modstr &&
+				    strcmp(modstr, "__builtin__") != 0)
 				{
 					PyFile_WriteString(modstr, f);
 					PyFile_WriteString(".", f);
@@ -824,4 +826,3 @@
 #ifdef __cplusplus
 }
 #endif
-

Deleted: /python/branches/p3yk-noslice/Python/fmod.c
==============================================================================
--- /python/branches/p3yk-noslice/Python/fmod.c	Wed Jul 11 15:40:56 2007
+++ (empty file)
@@ -1,27 +0,0 @@
-
-/* Portable fmod(x, y) implementation for systems that don't have it */
-
-#include "pyconfig.h"
-
-#include "pyport.h"
-#include <errno.h>
-
-double
-fmod(double x, double y)
-{
-	double i, f;
-	
-	if (y == 0.0) {
-		errno = EDOM;
-		return 0.0;
-	}
-	
-	/* return f such that x = i*y + f for some integer i
-	   such that |f| < |y| and f has the same sign as x */
-	
-	i = floor(x/y);
-	f = x - i*y;
-	if ((x < 0.0) != (y < 0.0))
-		f = f-y;
-	return f;
-}

Modified: python/branches/p3yk-noslice/Python/graminit.c
==============================================================================
--- python/branches/p3yk-noslice/Python/graminit.c	(original)
+++ python/branches/p3yk-noslice/Python/graminit.c	Wed Jul 11 15:40:56 2007
@@ -86,371 +86,313 @@
 	{1, arcs_4_0},
 	{2, arcs_4_1},
 };
-static arc arcs_5_0[2] = {
+static arc arcs_5_0[1] = {
 	{16, 1},
-	{18, 2},
 };
-static arc arcs_5_1[1] = {
+static arc arcs_5_1[2] = {
 	{18, 2},
+	{19, 2},
 };
 static arc arcs_5_2[1] = {
-	{19, 3},
+	{0, 2},
 };
-static arc arcs_5_3[1] = {
-	{20, 4},
+static state states_5[3] = {
+	{1, arcs_5_0},
+	{2, arcs_5_1},
+	{1, arcs_5_2},
 };
-static arc arcs_5_4[2] = {
-	{21, 5},
-	{23, 6},
+static arc arcs_6_0[1] = {
+	{20, 1},
 };
-static arc arcs_5_5[1] = {
-	{22, 7},
+static arc arcs_6_1[1] = {
+	{21, 2},
 };
-static arc arcs_5_6[1] = {
-	{24, 8},
+static arc arcs_6_2[1] = {
+	{22, 3},
 };
-static arc arcs_5_7[1] = {
-	{23, 6},
+static arc arcs_6_3[2] = {
+	{23, 4},
+	{25, 5},
 };
-static arc arcs_5_8[1] = {
-	{0, 8},
+static arc arcs_6_4[1] = {
+	{24, 6},
 };
-static state states_5[9] = {
-	{2, arcs_5_0},
-	{1, arcs_5_1},
-	{1, arcs_5_2},
-	{1, arcs_5_3},
-	{2, arcs_5_4},
-	{1, arcs_5_5},
-	{1, arcs_5_6},
-	{1, arcs_5_7},
-	{1, arcs_5_8},
+static arc arcs_6_5[1] = {
+	{26, 7},
 };
-static arc arcs_6_0[1] = {
+static arc arcs_6_6[1] = {
+	{25, 5},
+};
+static arc arcs_6_7[1] = {
+	{0, 7},
+};
+static state states_6[8] = {
+	{1, arcs_6_0},
+	{1, arcs_6_1},
+	{1, arcs_6_2},
+	{2, arcs_6_3},
+	{1, arcs_6_4},
+	{1, arcs_6_5},
+	{1, arcs_6_6},
+	{1, arcs_6_7},
+};
+static arc arcs_7_0[1] = {
 	{13, 1},
 };
-static arc arcs_6_1[2] = {
-	{25, 2},
+static arc arcs_7_1[2] = {
+	{27, 2},
 	{15, 3},
 };
-static arc arcs_6_2[1] = {
+static arc arcs_7_2[1] = {
 	{15, 3},
 };
-static arc arcs_6_3[1] = {
+static arc arcs_7_3[1] = {
 	{0, 3},
 };
-static state states_6[4] = {
-	{1, arcs_6_0},
-	{2, arcs_6_1},
-	{1, arcs_6_2},
-	{1, arcs_6_3},
+static state states_7[4] = {
+	{1, arcs_7_0},
+	{2, arcs_7_1},
+	{1, arcs_7_2},
+	{1, arcs_7_3},
 };
-static arc arcs_7_0[3] = {
-	{26, 1},
-	{29, 2},
-	{31, 3},
+static arc arcs_8_0[3] = {
+	{28, 1},
+	{31, 2},
+	{32, 3},
 };
-static arc arcs_7_1[3] = {
-	{27, 4},
-	{28, 5},
+static arc arcs_8_1[3] = {
+	{29, 4},
+	{30, 5},
 	{0, 1},
 };
-static arc arcs_7_2[3] = {
-	{30, 6},
-	{28, 7},
+static arc arcs_8_2[3] = {
+	{28, 6},
+	{30, 7},
 	{0, 2},
 };
-static arc arcs_7_3[1] = {
-	{30, 8},
+static arc arcs_8_3[1] = {
+	{28, 8},
 };
-static arc arcs_7_4[1] = {
-	{22, 9},
+static arc arcs_8_4[1] = {
+	{24, 9},
 };
-static arc arcs_7_5[4] = {
-	{26, 1},
-	{29, 2},
-	{31, 3},
+static arc arcs_8_5[4] = {
+	{28, 1},
+	{31, 2},
+	{32, 3},
 	{0, 5},
 };
-static arc arcs_7_6[2] = {
-	{28, 7},
+static arc arcs_8_6[2] = {
+	{30, 7},
 	{0, 6},
 };
-static arc arcs_7_7[2] = {
-	{30, 10},
-	{31, 3},
+static arc arcs_8_7[2] = {
+	{28, 10},
+	{32, 3},
 };
-static arc arcs_7_8[1] = {
+static arc arcs_8_8[1] = {
 	{0, 8},
 };
-static arc arcs_7_9[2] = {
-	{28, 5},
+static arc arcs_8_9[2] = {
+	{30, 5},
 	{0, 9},
 };
-static arc arcs_7_10[3] = {
-	{28, 7},
-	{27, 11},
+static arc arcs_8_10[3] = {
+	{30, 7},
+	{29, 11},
 	{0, 10},
 };
-static arc arcs_7_11[1] = {
-	{22, 6},
-};
-static state states_7[12] = {
-	{3, arcs_7_0},
-	{3, arcs_7_1},
-	{3, arcs_7_2},
-	{1, arcs_7_3},
-	{1, arcs_7_4},
-	{4, arcs_7_5},
-	{2, arcs_7_6},
-	{2, arcs_7_7},
-	{1, arcs_7_8},
-	{2, arcs_7_9},
-	{3, arcs_7_10},
-	{1, arcs_7_11},
-};
-static arc arcs_8_0[1] = {
-	{19, 1},
-};
-static arc arcs_8_1[2] = {
-	{23, 2},
-	{0, 1},
-};
-static arc arcs_8_2[1] = {
-	{22, 3},
-};
-static arc arcs_8_3[1] = {
-	{0, 3},
+static arc arcs_8_11[1] = {
+	{24, 6},
 };
-static state states_8[4] = {
-	{1, arcs_8_0},
-	{2, arcs_8_1},
-	{1, arcs_8_2},
+static state states_8[12] = {
+	{3, arcs_8_0},
+	{3, arcs_8_1},
+	{3, arcs_8_2},
 	{1, arcs_8_3},
+	{1, arcs_8_4},
+	{4, arcs_8_5},
+	{2, arcs_8_6},
+	{2, arcs_8_7},
+	{1, arcs_8_8},
+	{2, arcs_8_9},
+	{3, arcs_8_10},
+	{1, arcs_8_11},
 };
-static arc arcs_9_0[2] = {
-	{30, 1},
-	{13, 2},
+static arc arcs_9_0[1] = {
+	{21, 1},
 };
-static arc arcs_9_1[1] = {
+static arc arcs_9_1[2] = {
+	{25, 2},
 	{0, 1},
 };
 static arc arcs_9_2[1] = {
-	{32, 3},
+	{24, 3},
 };
 static arc arcs_9_3[1] = {
-	{15, 1},
+	{0, 3},
 };
 static state states_9[4] = {
-	{2, arcs_9_0},
-	{1, arcs_9_1},
+	{1, arcs_9_0},
+	{2, arcs_9_1},
 	{1, arcs_9_2},
 	{1, arcs_9_3},
 };
-static arc arcs_10_0[1] = {
-	{26, 1},
-};
-static arc arcs_10_1[2] = {
-	{28, 2},
-	{0, 1},
-};
-static arc arcs_10_2[2] = {
-	{26, 1},
-	{0, 2},
-};
-static state states_10[3] = {
-	{1, arcs_10_0},
-	{2, arcs_10_1},
-	{2, arcs_10_2},
-};
-static arc arcs_11_0[3] = {
+static arc arcs_10_0[3] = {
 	{34, 1},
-	{29, 2},
-	{31, 3},
+	{31, 2},
+	{32, 3},
 };
-static arc arcs_11_1[3] = {
-	{27, 4},
-	{28, 5},
+static arc arcs_10_1[3] = {
+	{29, 4},
+	{30, 5},
 	{0, 1},
 };
-static arc arcs_11_2[3] = {
-	{35, 6},
-	{28, 7},
+static arc arcs_10_2[3] = {
+	{34, 6},
+	{30, 7},
 	{0, 2},
 };
-static arc arcs_11_3[1] = {
-	{35, 8},
+static arc arcs_10_3[1] = {
+	{34, 8},
 };
-static arc arcs_11_4[1] = {
-	{22, 9},
+static arc arcs_10_4[1] = {
+	{24, 9},
 };
-static arc arcs_11_5[4] = {
+static arc arcs_10_5[4] = {
 	{34, 1},
-	{29, 2},
-	{31, 3},
+	{31, 2},
+	{32, 3},
 	{0, 5},
 };
-static arc arcs_11_6[2] = {
-	{28, 7},
+static arc arcs_10_6[2] = {
+	{30, 7},
 	{0, 6},
 };
-static arc arcs_11_7[2] = {
-	{35, 10},
-	{31, 3},
+static arc arcs_10_7[2] = {
+	{34, 10},
+	{32, 3},
 };
-static arc arcs_11_8[1] = {
+static arc arcs_10_8[1] = {
 	{0, 8},
 };
-static arc arcs_11_9[2] = {
-	{28, 5},
+static arc arcs_10_9[2] = {
+	{30, 5},
 	{0, 9},
 };
-static arc arcs_11_10[3] = {
-	{28, 7},
-	{27, 11},
+static arc arcs_10_10[3] = {
+	{30, 7},
+	{29, 11},
 	{0, 10},
 };
-static arc arcs_11_11[1] = {
-	{22, 6},
+static arc arcs_10_11[1] = {
+	{24, 6},
 };
-static state states_11[12] = {
-	{3, arcs_11_0},
-	{3, arcs_11_1},
-	{3, arcs_11_2},
-	{1, arcs_11_3},
-	{1, arcs_11_4},
-	{4, arcs_11_5},
-	{2, arcs_11_6},
-	{2, arcs_11_7},
-	{1, arcs_11_8},
-	{2, arcs_11_9},
-	{3, arcs_11_10},
-	{1, arcs_11_11},
+static state states_10[12] = {
+	{3, arcs_10_0},
+	{3, arcs_10_1},
+	{3, arcs_10_2},
+	{1, arcs_10_3},
+	{1, arcs_10_4},
+	{4, arcs_10_5},
+	{2, arcs_10_6},
+	{2, arcs_10_7},
+	{1, arcs_10_8},
+	{2, arcs_10_9},
+	{3, arcs_10_10},
+	{1, arcs_10_11},
+};
+static arc arcs_11_0[1] = {
+	{21, 1},
+};
+static arc arcs_11_1[1] = {
+	{0, 1},
+};
+static state states_11[2] = {
+	{1, arcs_11_0},
+	{1, arcs_11_1},
 };
-static arc arcs_12_0[1] = {
-	{19, 1},
+static arc arcs_12_0[2] = {
+	{3, 1},
+	{4, 1},
 };
 static arc arcs_12_1[1] = {
 	{0, 1},
 };
 static state states_12[2] = {
-	{1, arcs_12_0},
+	{2, arcs_12_0},
 	{1, arcs_12_1},
 };
-static arc arcs_13_0[2] = {
+static arc arcs_13_0[1] = {
 	{35, 1},
-	{13, 2},
 };
-static arc arcs_13_1[1] = {
-	{0, 1},
+static arc arcs_13_1[2] = {
+	{36, 2},
+	{2, 3},
 };
-static arc arcs_13_2[1] = {
-	{36, 3},
+static arc arcs_13_2[2] = {
+	{35, 1},
+	{2, 3},
 };
 static arc arcs_13_3[1] = {
-	{15, 1},
+	{0, 3},
 };
 static state states_13[4] = {
-	{2, arcs_13_0},
-	{1, arcs_13_1},
-	{1, arcs_13_2},
+	{1, arcs_13_0},
+	{2, arcs_13_1},
+	{2, arcs_13_2},
 	{1, arcs_13_3},
 };
-static arc arcs_14_0[1] = {
-	{34, 1},
-};
-static arc arcs_14_1[2] = {
-	{28, 2},
-	{0, 1},
-};
-static arc arcs_14_2[2] = {
-	{34, 1},
-	{0, 2},
-};
-static state states_14[3] = {
-	{1, arcs_14_0},
-	{2, arcs_14_1},
-	{2, arcs_14_2},
-};
-static arc arcs_15_0[2] = {
-	{3, 1},
-	{4, 1},
-};
-static arc arcs_15_1[1] = {
-	{0, 1},
-};
-static state states_15[2] = {
-	{2, arcs_15_0},
-	{1, arcs_15_1},
-};
-static arc arcs_16_0[1] = {
-	{37, 1},
-};
-static arc arcs_16_1[2] = {
-	{38, 2},
-	{2, 3},
-};
-static arc arcs_16_2[2] = {
+static arc arcs_14_0[8] = {
 	{37, 1},
-	{2, 3},
-};
-static arc arcs_16_3[1] = {
-	{0, 3},
-};
-static state states_16[4] = {
-	{1, arcs_16_0},
-	{2, arcs_16_1},
-	{2, arcs_16_2},
-	{1, arcs_16_3},
-};
-static arc arcs_17_0[7] = {
+	{38, 1},
 	{39, 1},
 	{40, 1},
 	{41, 1},
 	{42, 1},
 	{43, 1},
 	{44, 1},
-	{45, 1},
 };
-static arc arcs_17_1[1] = {
+static arc arcs_14_1[1] = {
 	{0, 1},
 };
-static state states_17[2] = {
-	{7, arcs_17_0},
-	{1, arcs_17_1},
+static state states_14[2] = {
+	{8, arcs_14_0},
+	{1, arcs_14_1},
 };
-static arc arcs_18_0[1] = {
+static arc arcs_15_0[1] = {
 	{9, 1},
 };
-static arc arcs_18_1[3] = {
-	{46, 2},
-	{27, 3},
+static arc arcs_15_1[3] = {
+	{45, 2},
+	{29, 3},
 	{0, 1},
 };
-static arc arcs_18_2[2] = {
-	{47, 4},
+static arc arcs_15_2[2] = {
+	{46, 4},
 	{9, 4},
 };
-static arc arcs_18_3[2] = {
-	{47, 5},
+static arc arcs_15_3[2] = {
+	{46, 5},
 	{9, 5},
 };
-static arc arcs_18_4[1] = {
+static arc arcs_15_4[1] = {
 	{0, 4},
 };
-static arc arcs_18_5[2] = {
-	{27, 3},
+static arc arcs_15_5[2] = {
+	{29, 3},
 	{0, 5},
 };
-static state states_18[6] = {
-	{1, arcs_18_0},
-	{3, arcs_18_1},
-	{2, arcs_18_2},
-	{2, arcs_18_3},
-	{1, arcs_18_4},
-	{2, arcs_18_5},
+static state states_15[6] = {
+	{1, arcs_15_0},
+	{3, arcs_15_1},
+	{2, arcs_15_2},
+	{2, arcs_15_3},
+	{1, arcs_15_4},
+	{2, arcs_15_5},
 };
-static arc arcs_19_0[12] = {
+static arc arcs_16_0[12] = {
+	{47, 1},
 	{48, 1},
 	{49, 1},
 	{50, 1},
@@ -462,31 +404,64 @@
 	{56, 1},
 	{57, 1},
 	{58, 1},
+};
+static arc arcs_16_1[1] = {
+	{0, 1},
+};
+static state states_16[2] = {
+	{12, arcs_16_0},
+	{1, arcs_16_1},
+};
+static arc arcs_17_0[1] = {
 	{59, 1},
 };
+static arc arcs_17_1[1] = {
+	{60, 2},
+};
+static arc arcs_17_2[1] = {
+	{0, 2},
+};
+static state states_17[3] = {
+	{1, arcs_17_0},
+	{1, arcs_17_1},
+	{1, arcs_17_2},
+};
+static arc arcs_18_0[1] = {
+	{61, 1},
+};
+static arc arcs_18_1[1] = {
+	{0, 1},
+};
+static state states_18[2] = {
+	{1, arcs_18_0},
+	{1, arcs_18_1},
+};
+static arc arcs_19_0[5] = {
+	{62, 1},
+	{63, 1},
+	{64, 1},
+	{65, 1},
+	{66, 1},
+};
 static arc arcs_19_1[1] = {
 	{0, 1},
 };
 static state states_19[2] = {
-	{12, arcs_19_0},
+	{5, arcs_19_0},
 	{1, arcs_19_1},
 };
 static arc arcs_20_0[1] = {
-	{60, 1},
+	{67, 1},
 };
 static arc arcs_20_1[1] = {
-	{61, 2},
-};
-static arc arcs_20_2[1] = {
-	{0, 2},
+	{0, 1},
 };
-static state states_20[3] = {
+static state states_20[2] = {
 	{1, arcs_20_0},
 	{1, arcs_20_1},
-	{1, arcs_20_2},
 };
 static arc arcs_21_0[1] = {
-	{62, 1},
+	{68, 1},
 };
 static arc arcs_21_1[1] = {
 	{0, 1},
@@ -495,22 +470,23 @@
 	{1, arcs_21_0},
 	{1, arcs_21_1},
 };
-static arc arcs_22_0[5] = {
-	{63, 1},
-	{64, 1},
-	{65, 1},
-	{66, 1},
-	{67, 1},
+static arc arcs_22_0[1] = {
+	{69, 1},
 };
-static arc arcs_22_1[1] = {
+static arc arcs_22_1[2] = {
+	{9, 2},
 	{0, 1},
 };
-static state states_22[2] = {
-	{5, arcs_22_0},
-	{1, arcs_22_1},
+static arc arcs_22_2[1] = {
+	{0, 2},
+};
+static state states_22[3] = {
+	{1, arcs_22_0},
+	{2, arcs_22_1},
+	{1, arcs_22_2},
 };
 static arc arcs_23_0[1] = {
-	{68, 1},
+	{46, 1},
 };
 static arc arcs_23_1[1] = {
 	{0, 1},
@@ -520,665 +496,646 @@
 	{1, arcs_23_1},
 };
 static arc arcs_24_0[1] = {
-	{69, 1},
+	{70, 1},
 };
-static arc arcs_24_1[1] = {
+static arc arcs_24_1[2] = {
+	{24, 2},
 	{0, 1},
 };
-static state states_24[2] = {
+static arc arcs_24_2[2] = {
+	{30, 3},
+	{0, 2},
+};
+static arc arcs_24_3[1] = {
+	{24, 4},
+};
+static arc arcs_24_4[2] = {
+	{30, 5},
+	{0, 4},
+};
+static arc arcs_24_5[1] = {
+	{24, 6},
+};
+static arc arcs_24_6[1] = {
+	{0, 6},
+};
+static state states_24[7] = {
 	{1, arcs_24_0},
-	{1, arcs_24_1},
+	{2, arcs_24_1},
+	{2, arcs_24_2},
+	{1, arcs_24_3},
+	{2, arcs_24_4},
+	{1, arcs_24_5},
+	{1, arcs_24_6},
 };
-static arc arcs_25_0[1] = {
-	{70, 1},
+static arc arcs_25_0[2] = {
+	{71, 1},
+	{72, 1},
 };
-static arc arcs_25_1[2] = {
-	{9, 2},
+static arc arcs_25_1[1] = {
 	{0, 1},
 };
-static arc arcs_25_2[1] = {
-	{0, 2},
-};
-static state states_25[3] = {
-	{1, arcs_25_0},
-	{2, arcs_25_1},
-	{1, arcs_25_2},
+static state states_25[2] = {
+	{2, arcs_25_0},
+	{1, arcs_25_1},
 };
 static arc arcs_26_0[1] = {
-	{47, 1},
+	{73, 1},
 };
 static arc arcs_26_1[1] = {
-	{0, 1},
+	{74, 2},
+};
+static arc arcs_26_2[1] = {
+	{0, 2},
 };
-static state states_26[2] = {
+static state states_26[3] = {
 	{1, arcs_26_0},
 	{1, arcs_26_1},
+	{1, arcs_26_2},
 };
 static arc arcs_27_0[1] = {
-	{71, 1},
+	{75, 1},
 };
-static arc arcs_27_1[2] = {
-	{22, 2},
-	{0, 1},
+static arc arcs_27_1[3] = {
+	{76, 2},
+	{77, 2},
+	{12, 3},
 };
-static arc arcs_27_2[2] = {
-	{28, 3},
-	{0, 2},
+static arc arcs_27_2[4] = {
+	{76, 2},
+	{77, 2},
+	{12, 3},
+	{73, 4},
 };
 static arc arcs_27_3[1] = {
-	{22, 4},
+	{73, 4},
 };
-static arc arcs_27_4[2] = {
-	{28, 5},
-	{0, 4},
+static arc arcs_27_4[3] = {
+	{31, 5},
+	{13, 6},
+	{78, 5},
 };
 static arc arcs_27_5[1] = {
-	{22, 6},
+	{0, 5},
 };
 static arc arcs_27_6[1] = {
-	{0, 6},
+	{78, 7},
+};
+static arc arcs_27_7[1] = {
+	{15, 5},
 };
-static state states_27[7] = {
+static state states_27[8] = {
 	{1, arcs_27_0},
-	{2, arcs_27_1},
-	{2, arcs_27_2},
+	{3, arcs_27_1},
+	{4, arcs_27_2},
 	{1, arcs_27_3},
-	{2, arcs_27_4},
+	{3, arcs_27_4},
 	{1, arcs_27_5},
 	{1, arcs_27_6},
+	{1, arcs_27_7},
 };
-static arc arcs_28_0[2] = {
-	{72, 1},
-	{73, 1},
+static arc arcs_28_0[1] = {
+	{21, 1},
 };
-static arc arcs_28_1[1] = {
+static arc arcs_28_1[2] = {
+	{80, 2},
 	{0, 1},
 };
-static state states_28[2] = {
-	{2, arcs_28_0},
-	{1, arcs_28_1},
+static arc arcs_28_2[1] = {
+	{21, 3},
+};
+static arc arcs_28_3[1] = {
+	{0, 3},
+};
+static state states_28[4] = {
+	{1, arcs_28_0},
+	{2, arcs_28_1},
+	{1, arcs_28_2},
+	{1, arcs_28_3},
 };
 static arc arcs_29_0[1] = {
-	{74, 1},
+	{12, 1},
 };
-static arc arcs_29_1[1] = {
-	{75, 2},
+static arc arcs_29_1[2] = {
+	{80, 2},
+	{0, 1},
 };
 static arc arcs_29_2[1] = {
-	{0, 2},
+	{21, 3},
+};
+static arc arcs_29_3[1] = {
+	{0, 3},
 };
-static state states_29[3] = {
+static state states_29[4] = {
 	{1, arcs_29_0},
-	{1, arcs_29_1},
+	{2, arcs_29_1},
 	{1, arcs_29_2},
+	{1, arcs_29_3},
 };
 static arc arcs_30_0[1] = {
-	{76, 1},
+	{79, 1},
 };
 static arc arcs_30_1[2] = {
-	{77, 2},
-	{12, 3},
-};
-static arc arcs_30_2[3] = {
-	{77, 2},
-	{12, 3},
-	{74, 4},
-};
-static arc arcs_30_3[1] = {
-	{74, 4},
-};
-static arc arcs_30_4[3] = {
-	{29, 5},
-	{13, 6},
-	{78, 5},
-};
-static arc arcs_30_5[1] = {
-	{0, 5},
-};
-static arc arcs_30_6[1] = {
-	{78, 7},
+	{30, 2},
+	{0, 1},
 };
-static arc arcs_30_7[1] = {
-	{15, 5},
+static arc arcs_30_2[2] = {
+	{79, 1},
+	{0, 2},
 };
-static state states_30[8] = {
+static state states_30[3] = {
 	{1, arcs_30_0},
 	{2, arcs_30_1},
-	{3, arcs_30_2},
-	{1, arcs_30_3},
-	{3, arcs_30_4},
-	{1, arcs_30_5},
-	{1, arcs_30_6},
-	{1, arcs_30_7},
+	{2, arcs_30_2},
 };
 static arc arcs_31_0[1] = {
-	{19, 1},
+	{81, 1},
 };
 static arc arcs_31_1[2] = {
-	{80, 2},
+	{30, 0},
 	{0, 1},
 };
-static arc arcs_31_2[1] = {
-	{19, 3},
-};
-static arc arcs_31_3[1] = {
-	{0, 3},
-};
-static state states_31[4] = {
+static state states_31[2] = {
 	{1, arcs_31_0},
 	{2, arcs_31_1},
-	{1, arcs_31_2},
-	{1, arcs_31_3},
 };
 static arc arcs_32_0[1] = {
-	{12, 1},
+	{21, 1},
 };
 static arc arcs_32_1[2] = {
-	{80, 2},
+	{76, 0},
 	{0, 1},
 };
-static arc arcs_32_2[1] = {
-	{19, 3},
-};
-static arc arcs_32_3[1] = {
-	{0, 3},
-};
-static state states_32[4] = {
+static state states_32[2] = {
 	{1, arcs_32_0},
 	{2, arcs_32_1},
-	{1, arcs_32_2},
-	{1, arcs_32_3},
 };
 static arc arcs_33_0[1] = {
-	{79, 1},
+	{82, 1},
 };
-static arc arcs_33_1[2] = {
-	{28, 2},
-	{0, 1},
+static arc arcs_33_1[1] = {
+	{21, 2},
 };
 static arc arcs_33_2[2] = {
-	{79, 1},
+	{30, 1},
 	{0, 2},
 };
 static state states_33[3] = {
 	{1, arcs_33_0},
-	{2, arcs_33_1},
+	{1, arcs_33_1},
 	{2, arcs_33_2},
 };
 static arc arcs_34_0[1] = {
-	{81, 1},
+	{83, 1},
 };
-static arc arcs_34_1[2] = {
-	{28, 0},
-	{0, 1},
+static arc arcs_34_1[1] = {
+	{21, 2},
+};
+static arc arcs_34_2[2] = {
+	{30, 1},
+	{0, 2},
 };
-static state states_34[2] = {
+static state states_34[3] = {
 	{1, arcs_34_0},
-	{2, arcs_34_1},
+	{1, arcs_34_1},
+	{2, arcs_34_2},
 };
 static arc arcs_35_0[1] = {
-	{19, 1},
+	{84, 1},
 };
-static arc arcs_35_1[2] = {
-	{77, 0},
-	{0, 1},
+static arc arcs_35_1[1] = {
+	{24, 2},
+};
+static arc arcs_35_2[2] = {
+	{30, 3},
+	{0, 2},
+};
+static arc arcs_35_3[1] = {
+	{24, 4},
 };
-static state states_35[2] = {
+static arc arcs_35_4[1] = {
+	{0, 4},
+};
+static state states_35[5] = {
 	{1, arcs_35_0},
-	{2, arcs_35_1},
+	{1, arcs_35_1},
+	{2, arcs_35_2},
+	{1, arcs_35_3},
+	{1, arcs_35_4},
 };
-static arc arcs_36_0[1] = {
-	{82, 1},
+static arc arcs_36_0[8] = {
+	{85, 1},
+	{86, 1},
+	{87, 1},
+	{88, 1},
+	{89, 1},
+	{19, 1},
+	{18, 1},
+	{17, 1},
 };
 static arc arcs_36_1[1] = {
-	{19, 2},
-};
-static arc arcs_36_2[2] = {
-	{28, 1},
-	{0, 2},
+	{0, 1},
 };
-static state states_36[3] = {
-	{1, arcs_36_0},
+static state states_36[2] = {
+	{8, arcs_36_0},
 	{1, arcs_36_1},
-	{2, arcs_36_2},
 };
 static arc arcs_37_0[1] = {
-	{83, 1},
+	{90, 1},
 };
 static arc arcs_37_1[1] = {
-	{22, 2},
+	{24, 2},
 };
-static arc arcs_37_2[2] = {
-	{28, 3},
-	{0, 2},
+static arc arcs_37_2[1] = {
+	{25, 3},
 };
 static arc arcs_37_3[1] = {
-	{22, 4},
+	{26, 4},
 };
-static arc arcs_37_4[1] = {
+static arc arcs_37_4[3] = {
+	{91, 1},
+	{92, 5},
 	{0, 4},
 };
-static state states_37[5] = {
+static arc arcs_37_5[1] = {
+	{25, 6},
+};
+static arc arcs_37_6[1] = {
+	{26, 7},
+};
+static arc arcs_37_7[1] = {
+	{0, 7},
+};
+static state states_37[8] = {
 	{1, arcs_37_0},
 	{1, arcs_37_1},
-	{2, arcs_37_2},
+	{1, arcs_37_2},
 	{1, arcs_37_3},
-	{1, arcs_37_4},
+	{3, arcs_37_4},
+	{1, arcs_37_5},
+	{1, arcs_37_6},
+	{1, arcs_37_7},
 };
-static arc arcs_38_0[7] = {
-	{84, 1},
-	{85, 1},
-	{86, 1},
-	{87, 1},
-	{88, 1},
-	{17, 1},
-	{89, 1},
+static arc arcs_38_0[1] = {
+	{93, 1},
 };
 static arc arcs_38_1[1] = {
-	{0, 1},
+	{24, 2},
+};
+static arc arcs_38_2[1] = {
+	{25, 3},
+};
+static arc arcs_38_3[1] = {
+	{26, 4},
+};
+static arc arcs_38_4[2] = {
+	{92, 5},
+	{0, 4},
+};
+static arc arcs_38_5[1] = {
+	{25, 6},
+};
+static arc arcs_38_6[1] = {
+	{26, 7},
 };
-static state states_38[2] = {
-	{7, arcs_38_0},
+static arc arcs_38_7[1] = {
+	{0, 7},
+};
+static state states_38[8] = {
+	{1, arcs_38_0},
 	{1, arcs_38_1},
+	{1, arcs_38_2},
+	{1, arcs_38_3},
+	{2, arcs_38_4},
+	{1, arcs_38_5},
+	{1, arcs_38_6},
+	{1, arcs_38_7},
 };
 static arc arcs_39_0[1] = {
-	{90, 1},
+	{94, 1},
 };
 static arc arcs_39_1[1] = {
-	{22, 2},
+	{60, 2},
 };
 static arc arcs_39_2[1] = {
-	{23, 3},
+	{95, 3},
 };
 static arc arcs_39_3[1] = {
-	{24, 4},
+	{9, 4},
 };
-static arc arcs_39_4[3] = {
-	{91, 1},
-	{92, 5},
-	{0, 4},
+static arc arcs_39_4[1] = {
+	{25, 5},
 };
 static arc arcs_39_5[1] = {
-	{23, 6},
+	{26, 6},
 };
-static arc arcs_39_6[1] = {
-	{24, 7},
+static arc arcs_39_6[2] = {
+	{92, 7},
+	{0, 6},
 };
 static arc arcs_39_7[1] = {
-	{0, 7},
+	{25, 8},
+};
+static arc arcs_39_8[1] = {
+	{26, 9},
+};
+static arc arcs_39_9[1] = {
+	{0, 9},
 };
-static state states_39[8] = {
+static state states_39[10] = {
 	{1, arcs_39_0},
 	{1, arcs_39_1},
 	{1, arcs_39_2},
 	{1, arcs_39_3},
-	{3, arcs_39_4},
+	{1, arcs_39_4},
 	{1, arcs_39_5},
-	{1, arcs_39_6},
+	{2, arcs_39_6},
 	{1, arcs_39_7},
+	{1, arcs_39_8},
+	{1, arcs_39_9},
 };
 static arc arcs_40_0[1] = {
-	{93, 1},
+	{96, 1},
 };
 static arc arcs_40_1[1] = {
-	{22, 2},
+	{25, 2},
 };
 static arc arcs_40_2[1] = {
-	{23, 3},
+	{26, 3},
 };
-static arc arcs_40_3[1] = {
-	{24, 4},
+static arc arcs_40_3[2] = {
+	{97, 4},
+	{98, 5},
 };
-static arc arcs_40_4[2] = {
-	{92, 5},
-	{0, 4},
+static arc arcs_40_4[1] = {
+	{25, 6},
 };
 static arc arcs_40_5[1] = {
-	{23, 6},
+	{25, 7},
 };
 static arc arcs_40_6[1] = {
-	{24, 7},
+	{26, 8},
 };
 static arc arcs_40_7[1] = {
-	{0, 7},
+	{26, 9},
+};
+static arc arcs_40_8[4] = {
+	{97, 4},
+	{92, 10},
+	{98, 5},
+	{0, 8},
+};
+static arc arcs_40_9[1] = {
+	{0, 9},
 };
-static state states_40[8] = {
+static arc arcs_40_10[1] = {
+	{25, 11},
+};
+static arc arcs_40_11[1] = {
+	{26, 12},
+};
+static arc arcs_40_12[2] = {
+	{98, 5},
+	{0, 12},
+};
+static state states_40[13] = {
 	{1, arcs_40_0},
 	{1, arcs_40_1},
 	{1, arcs_40_2},
-	{1, arcs_40_3},
-	{2, arcs_40_4},
+	{2, arcs_40_3},
+	{1, arcs_40_4},
 	{1, arcs_40_5},
 	{1, arcs_40_6},
 	{1, arcs_40_7},
+	{4, arcs_40_8},
+	{1, arcs_40_9},
+	{1, arcs_40_10},
+	{1, arcs_40_11},
+	{2, arcs_40_12},
 };
 static arc arcs_41_0[1] = {
-	{94, 1},
+	{99, 1},
 };
 static arc arcs_41_1[1] = {
-	{61, 2},
+	{24, 2},
 };
-static arc arcs_41_2[1] = {
-	{95, 3},
+static arc arcs_41_2[2] = {
+	{100, 3},
+	{25, 4},
 };
 static arc arcs_41_3[1] = {
-	{9, 4},
+	{25, 4},
 };
 static arc arcs_41_4[1] = {
-	{23, 5},
+	{26, 5},
 };
 static arc arcs_41_5[1] = {
-	{24, 6},
-};
-static arc arcs_41_6[2] = {
-	{92, 7},
-	{0, 6},
-};
-static arc arcs_41_7[1] = {
-	{23, 8},
-};
-static arc arcs_41_8[1] = {
-	{24, 9},
-};
-static arc arcs_41_9[1] = {
-	{0, 9},
+	{0, 5},
 };
-static state states_41[10] = {
+static state states_41[6] = {
 	{1, arcs_41_0},
 	{1, arcs_41_1},
-	{1, arcs_41_2},
+	{2, arcs_41_2},
 	{1, arcs_41_3},
 	{1, arcs_41_4},
 	{1, arcs_41_5},
-	{2, arcs_41_6},
-	{1, arcs_41_7},
-	{1, arcs_41_8},
-	{1, arcs_41_9},
 };
 static arc arcs_42_0[1] = {
-	{96, 1},
+	{80, 1},
 };
 static arc arcs_42_1[1] = {
-	{23, 2},
+	{101, 2},
 };
 static arc arcs_42_2[1] = {
-	{24, 3},
-};
-static arc arcs_42_3[2] = {
-	{97, 4},
-	{98, 5},
-};
-static arc arcs_42_4[1] = {
-	{23, 6},
-};
-static arc arcs_42_5[1] = {
-	{23, 7},
-};
-static arc arcs_42_6[1] = {
-	{24, 8},
-};
-static arc arcs_42_7[1] = {
-	{24, 9},
-};
-static arc arcs_42_8[4] = {
-	{97, 4},
-	{92, 10},
-	{98, 5},
-	{0, 8},
-};
-static arc arcs_42_9[1] = {
-	{0, 9},
-};
-static arc arcs_42_10[1] = {
-	{23, 11},
-};
-static arc arcs_42_11[1] = {
-	{24, 12},
-};
-static arc arcs_42_12[2] = {
-	{98, 5},
-	{0, 12},
+	{0, 2},
 };
-static state states_42[13] = {
+static state states_42[3] = {
 	{1, arcs_42_0},
 	{1, arcs_42_1},
 	{1, arcs_42_2},
-	{2, arcs_42_3},
-	{1, arcs_42_4},
-	{1, arcs_42_5},
-	{1, arcs_42_6},
-	{1, arcs_42_7},
-	{4, arcs_42_8},
-	{1, arcs_42_9},
-	{1, arcs_42_10},
-	{1, arcs_42_11},
-	{2, arcs_42_12},
 };
 static arc arcs_43_0[1] = {
-	{99, 1},
+	{102, 1},
 };
-static arc arcs_43_1[1] = {
-	{22, 2},
+static arc arcs_43_1[2] = {
+	{24, 2},
+	{0, 1},
 };
 static arc arcs_43_2[2] = {
-	{100, 3},
-	{23, 4},
+	{80, 3},
+	{0, 2},
 };
 static arc arcs_43_3[1] = {
-	{23, 4},
+	{21, 4},
 };
 static arc arcs_43_4[1] = {
-	{24, 5},
-};
-static arc arcs_43_5[1] = {
-	{0, 5},
+	{0, 4},
 };
-static state states_43[6] = {
+static state states_43[5] = {
 	{1, arcs_43_0},
-	{1, arcs_43_1},
+	{2, arcs_43_1},
 	{2, arcs_43_2},
 	{1, arcs_43_3},
 	{1, arcs_43_4},
-	{1, arcs_43_5},
 };
-static arc arcs_44_0[1] = {
-	{80, 1},
+static arc arcs_44_0[2] = {
+	{3, 1},
+	{2, 2},
 };
 static arc arcs_44_1[1] = {
-	{101, 2},
+	{0, 1},
 };
 static arc arcs_44_2[1] = {
-	{0, 2},
+	{103, 3},
+};
+static arc arcs_44_3[1] = {
+	{6, 4},
+};
+static arc arcs_44_4[2] = {
+	{6, 4},
+	{104, 1},
 };
-static state states_44[3] = {
-	{1, arcs_44_0},
+static state states_44[5] = {
+	{2, arcs_44_0},
 	{1, arcs_44_1},
 	{1, arcs_44_2},
+	{1, arcs_44_3},
+	{2, arcs_44_4},
 };
-static arc arcs_45_0[1] = {
-	{102, 1},
+static arc arcs_45_0[2] = {
+	{105, 1},
+	{106, 2},
 };
 static arc arcs_45_1[2] = {
-	{22, 2},
+	{90, 3},
 	{0, 1},
 };
-static arc arcs_45_2[2] = {
-	{80, 3},
+static arc arcs_45_2[1] = {
 	{0, 2},
 };
 static arc arcs_45_3[1] = {
-	{19, 4},
+	{105, 4},
 };
 static arc arcs_45_4[1] = {
-	{0, 4},
+	{92, 5},
+};
+static arc arcs_45_5[1] = {
+	{24, 2},
 };
-static state states_45[5] = {
-	{1, arcs_45_0},
+static state states_45[6] = {
+	{2, arcs_45_0},
 	{2, arcs_45_1},
-	{2, arcs_45_2},
+	{1, arcs_45_2},
 	{1, arcs_45_3},
 	{1, arcs_45_4},
+	{1, arcs_45_5},
 };
 static arc arcs_46_0[2] = {
-	{3, 1},
-	{2, 2},
+	{105, 1},
+	{108, 1},
 };
 static arc arcs_46_1[1] = {
 	{0, 1},
 };
-static arc arcs_46_2[1] = {
-	{103, 3},
-};
-static arc arcs_46_3[1] = {
-	{6, 4},
-};
-static arc arcs_46_4[2] = {
-	{6, 4},
-	{104, 1},
-};
-static state states_46[5] = {
+static state states_46[2] = {
 	{2, arcs_46_0},
 	{1, arcs_46_1},
-	{1, arcs_46_2},
-	{1, arcs_46_3},
-	{2, arcs_46_4},
 };
 static arc arcs_47_0[1] = {
-	{106, 1},
+	{109, 1},
 };
 static arc arcs_47_1[2] = {
-	{28, 2},
-	{0, 1},
+	{33, 2},
+	{25, 3},
 };
 static arc arcs_47_2[1] = {
-	{106, 3},
+	{25, 3},
 };
-static arc arcs_47_3[2] = {
-	{28, 4},
-	{0, 3},
+static arc arcs_47_3[1] = {
+	{24, 4},
 };
-static arc arcs_47_4[2] = {
-	{106, 3},
+static arc arcs_47_4[1] = {
 	{0, 4},
 };
 static state states_47[5] = {
 	{1, arcs_47_0},
 	{2, arcs_47_1},
 	{1, arcs_47_2},
-	{2, arcs_47_3},
-	{2, arcs_47_4},
-};
-static arc arcs_48_0[2] = {
-	{107, 1},
-	{108, 1},
-};
-static arc arcs_48_1[1] = {
-	{0, 1},
-};
-static state states_48[2] = {
-	{2, arcs_48_0},
-	{1, arcs_48_1},
+	{1, arcs_47_3},
+	{1, arcs_47_4},
 };
-static arc arcs_49_0[1] = {
+static arc arcs_48_0[1] = {
 	{109, 1},
 };
-static arc arcs_49_1[2] = {
+static arc arcs_48_1[2] = {
 	{33, 2},
-	{23, 3},
+	{25, 3},
 };
-static arc arcs_49_2[1] = {
-	{23, 3},
+static arc arcs_48_2[1] = {
+	{25, 3},
 };
-static arc arcs_49_3[1] = {
-	{106, 4},
+static arc arcs_48_3[1] = {
+	{107, 4},
 };
-static arc arcs_49_4[1] = {
+static arc arcs_48_4[1] = {
 	{0, 4},
 };
-static state states_49[5] = {
-	{1, arcs_49_0},
-	{2, arcs_49_1},
-	{1, arcs_49_2},
-	{1, arcs_49_3},
-	{1, arcs_49_4},
-};
-static arc arcs_50_0[2] = {
-	{107, 1},
-	{110, 2},
+static state states_48[5] = {
+	{1, arcs_48_0},
+	{2, arcs_48_1},
+	{1, arcs_48_2},
+	{1, arcs_48_3},
+	{1, arcs_48_4},
 };
-static arc arcs_50_1[2] = {
-	{90, 3},
-	{0, 1},
+static arc arcs_49_0[1] = {
+	{110, 1},
 };
-static arc arcs_50_2[1] = {
-	{0, 2},
+static arc arcs_49_1[2] = {
+	{111, 0},
+	{0, 1},
 };
-static arc arcs_50_3[1] = {
-	{107, 4},
+static state states_49[2] = {
+	{1, arcs_49_0},
+	{2, arcs_49_1},
 };
-static arc arcs_50_4[1] = {
-	{92, 5},
+static arc arcs_50_0[1] = {
+	{112, 1},
 };
-static arc arcs_50_5[1] = {
-	{22, 2},
+static arc arcs_50_1[2] = {
+	{113, 0},
+	{0, 1},
 };
-static state states_50[6] = {
-	{2, arcs_50_0},
+static state states_50[2] = {
+	{1, arcs_50_0},
 	{2, arcs_50_1},
-	{1, arcs_50_2},
-	{1, arcs_50_3},
-	{1, arcs_50_4},
-	{1, arcs_50_5},
 };
-static arc arcs_51_0[1] = {
-	{111, 1},
+static arc arcs_51_0[2] = {
+	{114, 1},
+	{115, 2},
 };
-static arc arcs_51_1[2] = {
-	{112, 0},
-	{0, 1},
+static arc arcs_51_1[1] = {
+	{112, 2},
+};
+static arc arcs_51_2[1] = {
+	{0, 2},
 };
-static state states_51[2] = {
-	{1, arcs_51_0},
-	{2, arcs_51_1},
+static state states_51[3] = {
+	{2, arcs_51_0},
+	{1, arcs_51_1},
+	{1, arcs_51_2},
 };
 static arc arcs_52_0[1] = {
-	{113, 1},
+	{116, 1},
 };
 static arc arcs_52_1[2] = {
-	{114, 0},
+	{117, 0},
 	{0, 1},
 };
 static state states_52[2] = {
 	{1, arcs_52_0},
 	{2, arcs_52_1},
 };
-static arc arcs_53_0[2] = {
-	{115, 1},
-	{116, 2},
-};
-static arc arcs_53_1[1] = {
-	{113, 2},
-};
-static arc arcs_53_2[1] = {
-	{0, 2},
-};
-static state states_53[3] = {
-	{2, arcs_53_0},
-	{1, arcs_53_1},
-	{1, arcs_53_2},
-};
-static arc arcs_54_0[1] = {
-	{101, 1},
-};
-static arc arcs_54_1[2] = {
-	{117, 0},
-	{0, 1},
-};
-static state states_54[2] = {
-	{1, arcs_54_0},
-	{2, arcs_54_1},
-};
-static arc arcs_55_0[9] = {
+static arc arcs_53_0[9] = {
 	{118, 1},
 	{119, 1},
 	{120, 1},
@@ -1186,41 +1143,67 @@
 	{122, 1},
 	{123, 1},
 	{95, 1},
-	{115, 2},
+	{114, 2},
 	{124, 3},
 };
-static arc arcs_55_1[1] = {
+static arc arcs_53_1[1] = {
 	{0, 1},
 };
-static arc arcs_55_2[1] = {
+static arc arcs_53_2[1] = {
 	{95, 1},
 };
-static arc arcs_55_3[2] = {
-	{115, 1},
+static arc arcs_53_3[2] = {
+	{114, 1},
 	{0, 3},
 };
-static state states_55[4] = {
-	{9, arcs_55_0},
-	{1, arcs_55_1},
-	{1, arcs_55_2},
-	{2, arcs_55_3},
+static state states_53[4] = {
+	{9, arcs_53_0},
+	{1, arcs_53_1},
+	{1, arcs_53_2},
+	{2, arcs_53_3},
+};
+static arc arcs_54_0[2] = {
+	{31, 1},
+	{101, 2},
 };
-static arc arcs_56_0[1] = {
+static arc arcs_54_1[1] = {
+	{101, 2},
+};
+static arc arcs_54_2[1] = {
+	{0, 2},
+};
+static state states_54[3] = {
+	{2, arcs_54_0},
+	{1, arcs_54_1},
+	{1, arcs_54_2},
+};
+static arc arcs_55_0[1] = {
 	{125, 1},
 };
-static arc arcs_56_1[2] = {
+static arc arcs_55_1[2] = {
 	{126, 0},
 	{0, 1},
 };
+static state states_55[2] = {
+	{1, arcs_55_0},
+	{2, arcs_55_1},
+};
+static arc arcs_56_0[1] = {
+	{127, 1},
+};
+static arc arcs_56_1[2] = {
+	{128, 0},
+	{0, 1},
+};
 static state states_56[2] = {
 	{1, arcs_56_0},
 	{2, arcs_56_1},
 };
 static arc arcs_57_0[1] = {
-	{127, 1},
+	{129, 1},
 };
 static arc arcs_57_1[2] = {
-	{128, 0},
+	{130, 0},
 	{0, 1},
 };
 static state states_57[2] = {
@@ -1228,22 +1211,23 @@
 	{2, arcs_57_1},
 };
 static arc arcs_58_0[1] = {
-	{129, 1},
+	{131, 1},
 };
-static arc arcs_58_1[2] = {
-	{130, 0},
+static arc arcs_58_1[3] = {
+	{132, 0},
+	{133, 0},
 	{0, 1},
 };
 static state states_58[2] = {
 	{1, arcs_58_0},
-	{2, arcs_58_1},
+	{3, arcs_58_1},
 };
 static arc arcs_59_0[1] = {
-	{131, 1},
+	{134, 1},
 };
 static arc arcs_59_1[3] = {
-	{132, 0},
-	{133, 0},
+	{135, 0},
+	{136, 0},
 	{0, 1},
 };
 static state states_59[2] = {
@@ -1251,242 +1235,234 @@
 	{3, arcs_59_1},
 };
 static arc arcs_60_0[1] = {
-	{134, 1},
-};
-static arc arcs_60_1[3] = {
-	{135, 0},
-	{136, 0},
-	{0, 1},
-};
-static state states_60[2] = {
-	{1, arcs_60_0},
-	{3, arcs_60_1},
-};
-static arc arcs_61_0[1] = {
 	{137, 1},
 };
-static arc arcs_61_1[5] = {
-	{29, 0},
+static arc arcs_60_1[5] = {
+	{31, 0},
 	{138, 0},
 	{139, 0},
 	{140, 0},
 	{0, 1},
 };
-static state states_61[2] = {
-	{1, arcs_61_0},
-	{5, arcs_61_1},
+static state states_60[2] = {
+	{1, arcs_60_0},
+	{5, arcs_60_1},
 };
-static arc arcs_62_0[4] = {
+static arc arcs_61_0[4] = {
 	{135, 1},
 	{136, 1},
 	{141, 1},
 	{142, 2},
 };
-static arc arcs_62_1[1] = {
+static arc arcs_61_1[1] = {
 	{137, 2},
 };
-static arc arcs_62_2[1] = {
+static arc arcs_61_2[1] = {
 	{0, 2},
 };
-static state states_62[3] = {
-	{4, arcs_62_0},
-	{1, arcs_62_1},
-	{1, arcs_62_2},
+static state states_61[3] = {
+	{4, arcs_61_0},
+	{1, arcs_61_1},
+	{1, arcs_61_2},
 };
-static arc arcs_63_0[1] = {
+static arc arcs_62_0[1] = {
 	{143, 1},
 };
-static arc arcs_63_1[3] = {
+static arc arcs_62_1[3] = {
 	{144, 1},
-	{31, 2},
+	{32, 2},
 	{0, 1},
 };
-static arc arcs_63_2[1] = {
+static arc arcs_62_2[1] = {
 	{137, 3},
 };
-static arc arcs_63_3[1] = {
+static arc arcs_62_3[1] = {
 	{0, 3},
 };
-static state states_63[4] = {
-	{1, arcs_63_0},
-	{3, arcs_63_1},
-	{1, arcs_63_2},
-	{1, arcs_63_3},
+static state states_62[4] = {
+	{1, arcs_62_0},
+	{3, arcs_62_1},
+	{1, arcs_62_2},
+	{1, arcs_62_3},
 };
-static arc arcs_64_0[7] = {
+static arc arcs_63_0[10] = {
 	{13, 1},
 	{146, 2},
-	{149, 3},
-	{19, 4},
-	{152, 4},
-	{153, 5},
-	{77, 6},
+	{148, 3},
+	{21, 4},
+	{151, 4},
+	{152, 5},
+	{77, 4},
+	{153, 4},
+	{154, 4},
+	{155, 4},
 };
-static arc arcs_64_1[3] = {
-	{47, 7},
-	{145, 7},
+static arc arcs_63_1[3] = {
+	{46, 6},
+	{145, 6},
 	{15, 4},
 };
-static arc arcs_64_2[2] = {
-	{147, 8},
-	{148, 4},
+static arc arcs_63_2[2] = {
+	{145, 7},
+	{147, 4},
 };
-static arc arcs_64_3[2] = {
-	{150, 9},
-	{151, 4},
+static arc arcs_63_3[2] = {
+	{149, 8},
+	{150, 4},
 };
-static arc arcs_64_4[1] = {
+static arc arcs_63_4[1] = {
 	{0, 4},
 };
-static arc arcs_64_5[2] = {
-	{153, 5},
+static arc arcs_63_5[2] = {
+	{152, 5},
 	{0, 5},
 };
-static arc arcs_64_6[1] = {
-	{77, 10},
-};
-static arc arcs_64_7[1] = {
+static arc arcs_63_6[1] = {
 	{15, 4},
 };
-static arc arcs_64_8[1] = {
-	{148, 4},
+static arc arcs_63_7[1] = {
+	{147, 4},
 };
-static arc arcs_64_9[1] = {
-	{151, 4},
+static arc arcs_63_8[1] = {
+	{150, 4},
 };
-static arc arcs_64_10[1] = {
-	{77, 4},
+static state states_63[9] = {
+	{10, arcs_63_0},
+	{3, arcs_63_1},
+	{2, arcs_63_2},
+	{2, arcs_63_3},
+	{1, arcs_63_4},
+	{2, arcs_63_5},
+	{1, arcs_63_6},
+	{1, arcs_63_7},
+	{1, arcs_63_8},
 };
-static state states_64[11] = {
-	{7, arcs_64_0},
-	{3, arcs_64_1},
-	{2, arcs_64_2},
-	{2, arcs_64_3},
-	{1, arcs_64_4},
-	{2, arcs_64_5},
-	{1, arcs_64_6},
-	{1, arcs_64_7},
-	{1, arcs_64_8},
-	{1, arcs_64_9},
-	{1, arcs_64_10},
-};
-static arc arcs_65_0[1] = {
-	{22, 1},
-};
-static arc arcs_65_1[3] = {
-	{154, 2},
-	{28, 3},
+static arc arcs_64_0[1] = {
+	{24, 1},
+};
+static arc arcs_64_1[3] = {
+	{156, 2},
+	{30, 3},
 	{0, 1},
 };
-static arc arcs_65_2[1] = {
+static arc arcs_64_2[1] = {
 	{0, 2},
 };
-static arc arcs_65_3[2] = {
-	{22, 4},
+static arc arcs_64_3[2] = {
+	{24, 4},
 	{0, 3},
 };
-static arc arcs_65_4[2] = {
-	{28, 3},
+static arc arcs_64_4[2] = {
+	{30, 3},
 	{0, 4},
 };
-static state states_65[5] = {
-	{1, arcs_65_0},
-	{3, arcs_65_1},
+static state states_64[5] = {
+	{1, arcs_64_0},
+	{3, arcs_64_1},
+	{1, arcs_64_2},
+	{2, arcs_64_3},
+	{2, arcs_64_4},
+};
+static arc arcs_65_0[3] = {
+	{13, 1},
+	{146, 2},
+	{76, 3},
+};
+static arc arcs_65_1[2] = {
+	{14, 4},
+	{15, 5},
+};
+static arc arcs_65_2[1] = {
+	{157, 6},
+};
+static arc arcs_65_3[1] = {
+	{21, 5},
+};
+static arc arcs_65_4[1] = {
+	{15, 5},
+};
+static arc arcs_65_5[1] = {
+	{0, 5},
+};
+static arc arcs_65_6[1] = {
+	{147, 5},
+};
+static state states_65[7] = {
+	{3, arcs_65_0},
+	{2, arcs_65_1},
 	{1, arcs_65_2},
-	{2, arcs_65_3},
-	{2, arcs_65_4},
+	{1, arcs_65_3},
+	{1, arcs_65_4},
+	{1, arcs_65_5},
+	{1, arcs_65_6},
 };
 static arc arcs_66_0[1] = {
-	{22, 1},
+	{158, 1},
 };
-static arc arcs_66_1[3] = {
-	{155, 2},
-	{28, 3},
+static arc arcs_66_1[2] = {
+	{30, 2},
 	{0, 1},
 };
-static arc arcs_66_2[1] = {
+static arc arcs_66_2[2] = {
+	{158, 1},
 	{0, 2},
 };
-static arc arcs_66_3[2] = {
-	{22, 4},
-	{0, 3},
-};
-static arc arcs_66_4[2] = {
-	{28, 3},
-	{0, 4},
-};
-static state states_66[5] = {
+static state states_66[3] = {
 	{1, arcs_66_0},
-	{3, arcs_66_1},
-	{1, arcs_66_2},
-	{2, arcs_66_3},
-	{2, arcs_66_4},
+	{2, arcs_66_1},
+	{2, arcs_66_2},
 };
-static arc arcs_67_0[1] = {
-	{109, 1},
+static arc arcs_67_0[2] = {
+	{24, 1},
+	{25, 2},
 };
 static arc arcs_67_1[2] = {
-	{33, 2},
-	{23, 3},
+	{25, 2},
+	{0, 1},
 };
-static arc arcs_67_2[1] = {
-	{23, 3},
+static arc arcs_67_2[3] = {
+	{24, 3},
+	{159, 4},
+	{0, 2},
 };
-static arc arcs_67_3[1] = {
-	{22, 4},
+static arc arcs_67_3[2] = {
+	{159, 4},
+	{0, 3},
 };
 static arc arcs_67_4[1] = {
 	{0, 4},
 };
 static state states_67[5] = {
-	{1, arcs_67_0},
+	{2, arcs_67_0},
 	{2, arcs_67_1},
-	{1, arcs_67_2},
-	{1, arcs_67_3},
+	{3, arcs_67_2},
+	{2, arcs_67_3},
 	{1, arcs_67_4},
 };
-static arc arcs_68_0[3] = {
-	{13, 1},
-	{146, 2},
-	{77, 3},
+static arc arcs_68_0[1] = {
+	{25, 1},
 };
 static arc arcs_68_1[2] = {
-	{14, 4},
-	{15, 5},
+	{24, 2},
+	{0, 1},
 };
 static arc arcs_68_2[1] = {
-	{156, 6},
-};
-static arc arcs_68_3[1] = {
-	{19, 5},
-};
-static arc arcs_68_4[1] = {
-	{15, 5},
-};
-static arc arcs_68_5[1] = {
-	{0, 5},
-};
-static arc arcs_68_6[1] = {
-	{148, 5},
+	{0, 2},
 };
-static state states_68[7] = {
-	{3, arcs_68_0},
+static state states_68[3] = {
+	{1, arcs_68_0},
 	{2, arcs_68_1},
 	{1, arcs_68_2},
-	{1, arcs_68_3},
-	{1, arcs_68_4},
-	{1, arcs_68_5},
-	{1, arcs_68_6},
 };
 static arc arcs_69_0[1] = {
-	{157, 1},
+	{116, 1},
 };
 static arc arcs_69_1[2] = {
-	{28, 2},
+	{30, 2},
 	{0, 1},
 };
 static arc arcs_69_2[2] = {
-	{157, 1},
+	{116, 1},
 	{0, 2},
 };
 static state states_69[3] = {
@@ -1494,592 +1470,469 @@
 	{2, arcs_69_1},
 	{2, arcs_69_2},
 };
-static arc arcs_70_0[2] = {
-	{22, 1},
-	{23, 2},
+static arc arcs_70_0[1] = {
+	{24, 1},
 };
 static arc arcs_70_1[2] = {
-	{23, 2},
+	{30, 2},
 	{0, 1},
 };
-static arc arcs_70_2[3] = {
-	{22, 3},
-	{158, 4},
+static arc arcs_70_2[2] = {
+	{24, 1},
 	{0, 2},
 };
-static arc arcs_70_3[2] = {
-	{158, 4},
-	{0, 3},
-};
-static arc arcs_70_4[1] = {
-	{0, 4},
-};
-static state states_70[5] = {
-	{2, arcs_70_0},
+static state states_70[3] = {
+	{1, arcs_70_0},
 	{2, arcs_70_1},
-	{3, arcs_70_2},
-	{2, arcs_70_3},
-	{1, arcs_70_4},
+	{2, arcs_70_2},
 };
 static arc arcs_71_0[1] = {
-	{23, 1},
+	{24, 1},
 };
-static arc arcs_71_1[2] = {
-	{22, 2},
+static arc arcs_71_1[4] = {
+	{25, 2},
+	{156, 3},
+	{30, 4},
 	{0, 1},
 };
 static arc arcs_71_2[1] = {
-	{0, 2},
-};
-static state states_71[3] = {
-	{1, arcs_71_0},
-	{2, arcs_71_1},
-	{1, arcs_71_2},
-};
-static arc arcs_72_0[1] = {
-	{101, 1},
-};
-static arc arcs_72_1[2] = {
-	{28, 2},
-	{0, 1},
-};
-static arc arcs_72_2[2] = {
-	{101, 1},
-	{0, 2},
-};
-static state states_72[3] = {
-	{1, arcs_72_0},
-	{2, arcs_72_1},
-	{2, arcs_72_2},
-};
-static arc arcs_73_0[1] = {
-	{22, 1},
-};
-static arc arcs_73_1[2] = {
-	{28, 2},
-	{0, 1},
-};
-static arc arcs_73_2[2] = {
-	{22, 1},
-	{0, 2},
-};
-static state states_73[3] = {
-	{1, arcs_73_0},
-	{2, arcs_73_1},
-	{2, arcs_73_2},
-};
-static arc arcs_74_0[1] = {
-	{22, 1},
-};
-static arc arcs_74_1[3] = {
-	{23, 2},
-	{28, 3},
-	{0, 1},
-};
-static arc arcs_74_2[1] = {
-	{22, 4},
+	{24, 5},
 };
-static arc arcs_74_3[2] = {
-	{22, 5},
+static arc arcs_71_3[1] = {
 	{0, 3},
 };
-static arc arcs_74_4[2] = {
-	{28, 6},
+static arc arcs_71_4[2] = {
+	{24, 6},
 	{0, 4},
 };
-static arc arcs_74_5[2] = {
-	{28, 3},
+static arc arcs_71_5[2] = {
+	{30, 7},
 	{0, 5},
 };
-static arc arcs_74_6[2] = {
-	{22, 7},
+static arc arcs_71_6[2] = {
+	{30, 4},
 	{0, 6},
 };
-static arc arcs_74_7[1] = {
-	{23, 2},
+static arc arcs_71_7[2] = {
+	{24, 8},
+	{0, 7},
 };
-static state states_74[8] = {
-	{1, arcs_74_0},
-	{3, arcs_74_1},
-	{1, arcs_74_2},
-	{2, arcs_74_3},
-	{2, arcs_74_4},
-	{2, arcs_74_5},
-	{2, arcs_74_6},
-	{1, arcs_74_7},
+static arc arcs_71_8[1] = {
+	{25, 2},
 };
-static arc arcs_75_0[1] = {
-	{159, 1},
+static state states_71[9] = {
+	{1, arcs_71_0},
+	{4, arcs_71_1},
+	{1, arcs_71_2},
+	{1, arcs_71_3},
+	{2, arcs_71_4},
+	{2, arcs_71_5},
+	{2, arcs_71_6},
+	{2, arcs_71_7},
+	{1, arcs_71_8},
 };
-static arc arcs_75_1[1] = {
-	{19, 2},
+static arc arcs_72_0[1] = {
+	{160, 1},
 };
-static arc arcs_75_2[2] = {
+static arc arcs_72_1[1] = {
+	{21, 2},
+};
+static arc arcs_72_2[2] = {
 	{13, 3},
-	{23, 4},
+	{25, 4},
 };
-static arc arcs_75_3[2] = {
-	{9, 5},
+static arc arcs_72_3[2] = {
+	{14, 5},
 	{15, 6},
 };
-static arc arcs_75_4[1] = {
-	{24, 7},
+static arc arcs_72_4[1] = {
+	{26, 7},
 };
-static arc arcs_75_5[1] = {
+static arc arcs_72_5[1] = {
 	{15, 6},
 };
-static arc arcs_75_6[1] = {
-	{23, 4},
+static arc arcs_72_6[1] = {
+	{25, 4},
 };
-static arc arcs_75_7[1] = {
+static arc arcs_72_7[1] = {
 	{0, 7},
 };
-static state states_75[8] = {
-	{1, arcs_75_0},
-	{1, arcs_75_1},
-	{2, arcs_75_2},
-	{2, arcs_75_3},
-	{1, arcs_75_4},
-	{1, arcs_75_5},
-	{1, arcs_75_6},
-	{1, arcs_75_7},
+static state states_72[8] = {
+	{1, arcs_72_0},
+	{1, arcs_72_1},
+	{2, arcs_72_2},
+	{2, arcs_72_3},
+	{1, arcs_72_4},
+	{1, arcs_72_5},
+	{1, arcs_72_6},
+	{1, arcs_72_7},
 };
-static arc arcs_76_0[3] = {
-	{160, 1},
-	{29, 2},
-	{31, 3},
+static arc arcs_73_0[3] = {
+	{161, 1},
+	{31, 2},
+	{32, 3},
 };
-static arc arcs_76_1[2] = {
-	{28, 4},
+static arc arcs_73_1[2] = {
+	{30, 4},
 	{0, 1},
 };
-static arc arcs_76_2[1] = {
-	{22, 5},
+static arc arcs_73_2[1] = {
+	{24, 5},
 };
-static arc arcs_76_3[1] = {
-	{22, 6},
+static arc arcs_73_3[1] = {
+	{24, 6},
 };
-static arc arcs_76_4[4] = {
-	{160, 1},
-	{29, 2},
-	{31, 3},
+static arc arcs_73_4[4] = {
+	{161, 1},
+	{31, 2},
+	{32, 3},
 	{0, 4},
 };
-static arc arcs_76_5[2] = {
-	{28, 7},
+static arc arcs_73_5[2] = {
+	{30, 7},
 	{0, 5},
 };
-static arc arcs_76_6[1] = {
+static arc arcs_73_6[1] = {
 	{0, 6},
 };
-static arc arcs_76_7[1] = {
-	{31, 3},
+static arc arcs_73_7[1] = {
+	{32, 3},
 };
-static state states_76[8] = {
-	{3, arcs_76_0},
-	{2, arcs_76_1},
-	{1, arcs_76_2},
-	{1, arcs_76_3},
-	{4, arcs_76_4},
-	{2, arcs_76_5},
-	{1, arcs_76_6},
-	{1, arcs_76_7},
+static state states_73[8] = {
+	{3, arcs_73_0},
+	{2, arcs_73_1},
+	{1, arcs_73_2},
+	{1, arcs_73_3},
+	{4, arcs_73_4},
+	{2, arcs_73_5},
+	{1, arcs_73_6},
+	{1, arcs_73_7},
 };
-static arc arcs_77_0[1] = {
-	{22, 1},
+static arc arcs_74_0[1] = {
+	{24, 1},
 };
-static arc arcs_77_1[3] = {
-	{155, 2},
-	{27, 3},
+static arc arcs_74_1[3] = {
+	{156, 2},
+	{29, 3},
 	{0, 1},
 };
-static arc arcs_77_2[1] = {
+static arc arcs_74_2[1] = {
 	{0, 2},
 };
-static arc arcs_77_3[1] = {
-	{22, 2},
+static arc arcs_74_3[1] = {
+	{24, 2},
 };
-static state states_77[4] = {
-	{1, arcs_77_0},
-	{3, arcs_77_1},
-	{1, arcs_77_2},
-	{1, arcs_77_3},
+static state states_74[4] = {
+	{1, arcs_74_0},
+	{3, arcs_74_1},
+	{1, arcs_74_2},
+	{1, arcs_74_3},
 };
-static arc arcs_78_0[2] = {
-	{154, 1},
-	{162, 1},
+static arc arcs_75_0[2] = {
+	{156, 1},
+	{163, 1},
 };
-static arc arcs_78_1[1] = {
+static arc arcs_75_1[1] = {
 	{0, 1},
 };
-static state states_78[2] = {
-	{2, arcs_78_0},
-	{1, arcs_78_1},
+static state states_75[2] = {
+	{2, arcs_75_0},
+	{1, arcs_75_1},
 };
-static arc arcs_79_0[1] = {
+static arc arcs_76_0[1] = {
 	{94, 1},
 };
-static arc arcs_79_1[1] = {
-	{61, 2},
+static arc arcs_76_1[1] = {
+	{60, 2},
 };
-static arc arcs_79_2[1] = {
+static arc arcs_76_2[1] = {
 	{95, 3},
 };
-static arc arcs_79_3[1] = {
+static arc arcs_76_3[1] = {
 	{105, 4},
 };
-static arc arcs_79_4[2] = {
-	{161, 5},
+static arc arcs_76_4[2] = {
+	{162, 5},
 	{0, 4},
 };
-static arc arcs_79_5[1] = {
+static arc arcs_76_5[1] = {
 	{0, 5},
 };
-static state states_79[6] = {
-	{1, arcs_79_0},
-	{1, arcs_79_1},
-	{1, arcs_79_2},
-	{1, arcs_79_3},
-	{2, arcs_79_4},
-	{1, arcs_79_5},
-};
-static arc arcs_80_0[1] = {
-	{90, 1},
-};
-static arc arcs_80_1[1] = {
-	{106, 2},
-};
-static arc arcs_80_2[2] = {
-	{161, 3},
-	{0, 2},
-};
-static arc arcs_80_3[1] = {
-	{0, 3},
-};
-static state states_80[4] = {
-	{1, arcs_80_0},
-	{1, arcs_80_1},
-	{2, arcs_80_2},
-	{1, arcs_80_3},
-};
-static arc arcs_81_0[2] = {
-	{155, 1},
-	{164, 1},
-};
-static arc arcs_81_1[1] = {
-	{0, 1},
-};
-static state states_81[2] = {
-	{2, arcs_81_0},
-	{1, arcs_81_1},
-};
-static arc arcs_82_0[1] = {
-	{94, 1},
-};
-static arc arcs_82_1[1] = {
-	{61, 2},
-};
-static arc arcs_82_2[1] = {
-	{95, 3},
-};
-static arc arcs_82_3[1] = {
-	{107, 4},
-};
-static arc arcs_82_4[2] = {
-	{163, 5},
-	{0, 4},
-};
-static arc arcs_82_5[1] = {
-	{0, 5},
-};
-static state states_82[6] = {
-	{1, arcs_82_0},
-	{1, arcs_82_1},
-	{1, arcs_82_2},
-	{1, arcs_82_3},
-	{2, arcs_82_4},
-	{1, arcs_82_5},
+static state states_76[6] = {
+	{1, arcs_76_0},
+	{1, arcs_76_1},
+	{1, arcs_76_2},
+	{1, arcs_76_3},
+	{2, arcs_76_4},
+	{1, arcs_76_5},
 };
-static arc arcs_83_0[1] = {
+static arc arcs_77_0[1] = {
 	{90, 1},
 };
-static arc arcs_83_1[1] = {
-	{106, 2},
+static arc arcs_77_1[1] = {
+	{107, 2},
 };
-static arc arcs_83_2[2] = {
-	{163, 3},
+static arc arcs_77_2[2] = {
+	{162, 3},
 	{0, 2},
 };
-static arc arcs_83_3[1] = {
+static arc arcs_77_3[1] = {
 	{0, 3},
 };
-static state states_83[4] = {
-	{1, arcs_83_0},
-	{1, arcs_83_1},
-	{2, arcs_83_2},
-	{1, arcs_83_3},
+static state states_77[4] = {
+	{1, arcs_77_0},
+	{1, arcs_77_1},
+	{2, arcs_77_2},
+	{1, arcs_77_3},
 };
-static arc arcs_84_0[1] = {
-	{22, 1},
+static arc arcs_78_0[1] = {
+	{24, 1},
 };
-static arc arcs_84_1[2] = {
-	{28, 0},
+static arc arcs_78_1[2] = {
+	{30, 0},
 	{0, 1},
 };
-static state states_84[2] = {
-	{1, arcs_84_0},
-	{2, arcs_84_1},
+static state states_78[2] = {
+	{1, arcs_78_0},
+	{2, arcs_78_1},
 };
-static arc arcs_85_0[1] = {
-	{19, 1},
+static arc arcs_79_0[1] = {
+	{21, 1},
 };
-static arc arcs_85_1[1] = {
+static arc arcs_79_1[1] = {
 	{0, 1},
 };
-static state states_85[2] = {
-	{1, arcs_85_0},
-	{1, arcs_85_1},
+static state states_79[2] = {
+	{1, arcs_79_0},
+	{1, arcs_79_1},
 };
-static arc arcs_86_0[1] = {
-	{167, 1},
+static arc arcs_80_0[1] = {
+	{166, 1},
 };
-static arc arcs_86_1[2] = {
+static arc arcs_80_1[2] = {
 	{9, 2},
 	{0, 1},
 };
-static arc arcs_86_2[1] = {
+static arc arcs_80_2[1] = {
 	{0, 2},
 };
-static state states_86[3] = {
-	{1, arcs_86_0},
-	{2, arcs_86_1},
-	{1, arcs_86_2},
+static state states_80[3] = {
+	{1, arcs_80_0},
+	{2, arcs_80_1},
+	{1, arcs_80_2},
 };
-static dfa dfas[87] = {
+static dfa dfas[81] = {
 	{256, "single_input", 0, 3, states_0,
-	 "\004\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"},
+	 "\004\050\060\200\000\000\000\050\170\052\034\144\011\040\004\000\200\041\224\017\101"},
 	{257, "file_input", 0, 2, states_1,
-	 "\204\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"},
+	 "\204\050\060\200\000\000\000\050\170\052\034\144\011\040\004\000\200\041\224\017\101"},
 	{258, "eval_input", 0, 3, states_2,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
 	{259, "decorator", 0, 7, states_3,
 	 "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
 	{260, "decorators", 0, 2, states_4,
 	 "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{261, "funcdef", 0, 9, states_5,
-	 "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{262, "parameters", 0, 4, states_6,
+	{261, "decorated", 0, 3, states_5,
+	 "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{262, "funcdef", 0, 8, states_6,
+	 "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{263, "parameters", 0, 4, states_7,
 	 "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{263, "typedargslist", 0, 12, states_7,
-	 "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{264, "tname", 0, 4, states_8,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{264, "typedargslist", 0, 12, states_8,
+	 "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
 	{265, "tfpdef", 0, 4, states_9,
-	 "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{266, "tfplist", 0, 3, states_10,
-	 "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{267, "varargslist", 0, 12, states_11,
-	 "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{268, "vname", 0, 2, states_12,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{269, "vfpdef", 0, 4, states_13,
-	 "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{270, "vfplist", 0, 3, states_14,
-	 "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{271, "stmt", 0, 2, states_15,
-	 "\000\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"},
-	{272, "simple_stmt", 0, 4, states_16,
-	 "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"},
-	{273, "small_stmt", 0, 2, states_17,
-	 "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"},
-	{274, "expr_stmt", 0, 6, states_18,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{275, "augassign", 0, 2, states_19,
-	 "\000\000\000\000\000\000\377\017\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{276, "del_stmt", 0, 3, states_20,
-	 "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{277, "pass_stmt", 0, 2, states_21,
-	 "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{278, "flow_stmt", 0, 2, states_22,
-	 "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\200"},
-	{279, "break_stmt", 0, 2, states_23,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{266, "varargslist", 0, 12, states_10,
+	 "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{267, "vfpdef", 0, 2, states_11,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{268, "stmt", 0, 2, states_12,
+	 "\000\050\060\200\000\000\000\050\170\052\034\144\011\040\004\000\200\041\224\017\101"},
+	{269, "simple_stmt", 0, 4, states_13,
+	 "\000\040\040\200\000\000\000\050\170\052\034\000\000\040\004\000\200\041\224\017\100"},
+	{270, "small_stmt", 0, 2, states_14,
+	 "\000\040\040\200\000\000\000\050\170\052\034\000\000\040\004\000\200\041\224\017\100"},
+	{271, "expr_stmt", 0, 6, states_15,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{272, "augassign", 0, 2, states_16,
+	 "\000\000\000\000\000\200\377\007\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{273, "del_stmt", 0, 3, states_17,
+	 "\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{274, "pass_stmt", 0, 2, states_18,
+	 "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{275, "flow_stmt", 0, 2, states_19,
+	 "\000\000\000\000\000\000\000\000\170\000\000\000\000\000\000\000\000\000\000\000\100"},
+	{276, "break_stmt", 0, 2, states_20,
+	 "\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{277, "continue_stmt", 0, 2, states_21,
 	 "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{280, "continue_stmt", 0, 2, states_24,
+	{278, "return_stmt", 0, 3, states_22,
 	 "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{281, "return_stmt", 0, 3, states_25,
+	{279, "yield_stmt", 0, 2, states_23,
+	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"},
+	{280, "raise_stmt", 0, 7, states_24,
 	 "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{282, "yield_stmt", 0, 2, states_26,
-	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"},
-	{283, "raise_stmt", 0, 7, states_27,
-	 "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{284, "import_stmt", 0, 2, states_28,
-	 "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000"},
-	{285, "import_name", 0, 3, states_29,
-	 "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"},
-	{286, "import_from", 0, 8, states_30,
-	 "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"},
-	{287, "import_as_name", 0, 4, states_31,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{288, "dotted_as_name", 0, 4, states_32,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{289, "import_as_names", 0, 3, states_33,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{290, "dotted_as_names", 0, 2, states_34,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{291, "dotted_name", 0, 2, states_35,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{292, "global_stmt", 0, 3, states_36,
+	{281, "import_stmt", 0, 2, states_25,
+	 "\000\000\000\000\000\000\000\000\000\012\000\000\000\000\000\000\000\000\000\000\000"},
+	{282, "import_name", 0, 3, states_26,
+	 "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"},
+	{283, "import_from", 0, 8, states_27,
+	 "\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"},
+	{284, "import_as_name", 0, 4, states_28,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{285, "dotted_as_name", 0, 4, states_29,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{286, "import_as_names", 0, 3, states_30,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{287, "dotted_as_names", 0, 2, states_31,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{288, "dotted_name", 0, 2, states_32,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{289, "global_stmt", 0, 3, states_33,
 	 "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"},
-	{293, "assert_stmt", 0, 5, states_37,
+	{290, "nonlocal_stmt", 0, 3, states_34,
 	 "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"},
-	{294, "compound_stmt", 0, 2, states_38,
-	 "\000\010\004\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\200\000"},
-	{295, "if_stmt", 0, 8, states_39,
+	{291, "assert_stmt", 0, 5, states_35,
+	 "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"},
+	{292, "compound_stmt", 0, 2, states_36,
+	 "\000\010\020\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\000\001"},
+	{293, "if_stmt", 0, 8, states_37,
 	 "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"},
-	{296, "while_stmt", 0, 8, states_40,
+	{294, "while_stmt", 0, 8, states_38,
 	 "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"},
-	{297, "for_stmt", 0, 10, states_41,
+	{295, "for_stmt", 0, 10, states_39,
 	 "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
-	{298, "try_stmt", 0, 13, states_42,
+	{296, "try_stmt", 0, 13, states_40,
 	 "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"},
-	{299, "with_stmt", 0, 6, states_43,
+	{297, "with_stmt", 0, 6, states_41,
 	 "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"},
-	{300, "with_var", 0, 3, states_44,
+	{298, "with_var", 0, 3, states_42,
 	 "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"},
-	{301, "except_clause", 0, 5, states_45,
+	{299, "except_clause", 0, 5, states_43,
 	 "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"},
-	{302, "suite", 0, 5, states_46,
-	 "\004\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"},
-	{303, "testlist_safe", 0, 5, states_47,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{304, "old_test", 0, 2, states_48,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{305, "old_lambdef", 0, 5, states_49,
+	{300, "suite", 0, 5, states_44,
+	 "\004\040\040\200\000\000\000\050\170\052\034\000\000\040\004\000\200\041\224\017\100"},
+	{301, "test", 0, 6, states_45,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{302, "test_nocond", 0, 2, states_46,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{303, "lambdef", 0, 5, states_47,
 	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"},
-	{306, "test", 0, 6, states_50,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{307, "or_test", 0, 2, states_51,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"},
-	{308, "and_test", 0, 2, states_52,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"},
-	{309, "not_test", 0, 3, states_53,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"},
-	{310, "comparison", 0, 2, states_54,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{311, "comp_op", 0, 4, states_55,
-	 "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\310\037\000\000\000\000\000"},
-	{312, "expr", 0, 2, states_56,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{313, "xor_expr", 0, 2, states_57,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{314, "and_expr", 0, 2, states_58,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{315, "shift_expr", 0, 2, states_59,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{316, "arith_expr", 0, 2, states_60,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{317, "term", 0, 2, states_61,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{318, "factor", 0, 3, states_62,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{319, "power", 0, 4, states_63,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"},
-	{320, "atom", 0, 11, states_64,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"},
-	{321, "listmaker", 0, 5, states_65,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{322, "testlist_gexp", 0, 5, states_66,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{323, "lambdef", 0, 5, states_67,
+	{304, "lambdef_nocond", 0, 5, states_48,
 	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"},
-	{324, "trailer", 0, 7, states_68,
-	 "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000"},
-	{325, "subscriptlist", 0, 3, states_69,
-	 "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{326, "subscript", 0, 5, states_70,
-	 "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{327, "sliceop", 0, 3, states_71,
-	 "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{328, "exprlist", 0, 3, states_72,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
-	{329, "testlist", 0, 3, states_73,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{330, "dictsetmaker", 0, 8, states_74,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{331, "classdef", 0, 8, states_75,
-	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"},
-	{332, "arglist", 0, 8, states_76,
-	 "\000\040\010\240\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{333, "argument", 0, 4, states_77,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{334, "list_iter", 0, 2, states_78,
-	 "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"},
-	{335, "list_for", 0, 6, states_79,
-	 "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
-	{336, "list_if", 0, 4, states_80,
-	 "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"},
-	{337, "gen_iter", 0, 2, states_81,
+	{305, "or_test", 0, 2, states_49,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\200\041\224\017\000"},
+	{306, "and_test", 0, 2, states_50,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\200\041\224\017\000"},
+	{307, "not_test", 0, 3, states_51,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\200\041\224\017\000"},
+	{308, "comparison", 0, 2, states_52,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{309, "comp_op", 0, 4, states_53,
+	 "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\304\037\000\000\000\000\000"},
+	{310, "star_expr", 0, 3, states_54,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{311, "expr", 0, 2, states_55,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{312, "xor_expr", 0, 2, states_56,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{313, "and_expr", 0, 2, states_57,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{314, "shift_expr", 0, 2, states_58,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{315, "arith_expr", 0, 2, states_59,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{316, "term", 0, 2, states_60,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{317, "factor", 0, 3, states_61,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{318, "power", 0, 4, states_62,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\224\017\000"},
+	{319, "atom", 0, 9, states_63,
+	 "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\224\017\000"},
+	{320, "testlist_comp", 0, 5, states_64,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{321, "trailer", 0, 7, states_65,
+	 "\000\040\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\004\000\000"},
+	{322, "subscriptlist", 0, 3, states_66,
+	 "\000\040\040\202\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{323, "subscript", 0, 5, states_67,
+	 "\000\040\040\202\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{324, "sliceop", 0, 3, states_68,
+	 "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{325, "exprlist", 0, 3, states_69,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\200\041\224\017\000"},
+	{326, "testlist", 0, 3, states_70,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{327, "dictorsetmaker", 0, 9, states_71,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{328, "classdef", 0, 8, states_72,
+	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"},
+	{329, "arglist", 0, 8, states_73,
+	 "\000\040\040\200\001\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{330, "argument", 0, 4, states_74,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{331, "comp_iter", 0, 2, states_75,
 	 "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"},
-	{338, "gen_for", 0, 6, states_82,
+	{332, "comp_for", 0, 6, states_76,
 	 "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
-	{339, "gen_if", 0, 4, states_83,
+	{333, "comp_if", 0, 4, states_77,
 	 "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"},
-	{340, "testlist1", 0, 2, states_84,
-	 "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
-	{341, "encoding_decl", 0, 2, states_85,
-	 "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
-	{342, "yield_expr", 0, 3, states_86,
-	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"},
+	{334, "testlist1", 0, 2, states_78,
+	 "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\200\041\224\017\000"},
+	{335, "encoding_decl", 0, 2, states_79,
+	 "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+	{336, "yield_expr", 0, 3, states_80,
+	 "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"},
 };
-static label labels[168] = {
+static label labels[167] = {
 	{0, "EMPTY"},
 	{256, 0},
 	{4, 0},
-	{272, 0},
-	{294, 0},
+	{269, 0},
+	{292, 0},
 	{257, 0},
-	{271, 0},
+	{268, 0},
 	{0, 0},
 	{258, 0},
-	{329, 0},
+	{326, 0},
 	{259, 0},
 	{50, 0},
-	{291, 0},
+	{288, 0},
 	{7, 0},
-	{332, 0},
+	{329, 0},
 	{8, 0},
 	{260, 0},
 	{261, 0},
+	{328, 0},
+	{262, 0},
 	{1, "def"},
 	{1, 0},
-	{262, 0},
+	{263, 0},
 	{51, 0},
-	{306, 0},
+	{301, 0},
 	{11, 0},
-	{302, 0},
-	{263, 0},
+	{300, 0},
+	{264, 0},
 	{265, 0},
 	{22, 0},
 	{12, 0},
 	{16, 0},
-	{264, 0},
 	{36, 0},
 	{266, 0},
 	{267, 0},
-	{269, 0},
-	{268, 0},
 	{270, 0},
-	{273, 0},
 	{13, 0},
+	{271, 0},
+	{273, 0},
 	{274, 0},
-	{276, 0},
-	{277, 0},
-	{278, 0},
-	{284, 0},
-	{292, 0},
-	{293, 0},
 	{275, 0},
-	{342, 0},
+	{281, 0},
+	{289, 0},
+	{290, 0},
+	{291, 0},
+	{272, 0},
+	{336, 0},
 	{37, 0},
 	{38, 0},
 	{39, 0},
@@ -2093,35 +1946,36 @@
 	{47, 0},
 	{49, 0},
 	{1, "del"},
-	{328, 0},
+	{325, 0},
 	{1, "pass"},
-	{279, 0},
+	{276, 0},
+	{277, 0},
+	{278, 0},
 	{280, 0},
-	{281, 0},
-	{283, 0},
-	{282, 0},
+	{279, 0},
 	{1, "break"},
 	{1, "continue"},
 	{1, "return"},
 	{1, "raise"},
-	{285, 0},
-	{286, 0},
+	{282, 0},
+	{283, 0},
 	{1, "import"},
-	{290, 0},
+	{287, 0},
 	{1, "from"},
 	{23, 0},
-	{289, 0},
-	{287, 0},
+	{52, 0},
+	{286, 0},
+	{284, 0},
 	{1, "as"},
-	{288, 0},
+	{285, 0},
 	{1, "global"},
+	{1, "nonlocal"},
 	{1, "assert"},
+	{293, 0},
+	{294, 0},
 	{295, 0},
 	{296, 0},
 	{297, 0},
-	{298, 0},
-	{299, 0},
-	{331, 0},
 	{1, "if"},
 	{1, "elif"},
 	{1, "else"},
@@ -2129,27 +1983,27 @@
 	{1, "for"},
 	{1, "in"},
 	{1, "try"},
-	{301, 0},
+	{299, 0},
 	{1, "finally"},
 	{1, "with"},
-	{300, 0},
-	{312, 0},
+	{298, 0},
+	{311, 0},
 	{1, "except"},
 	{5, 0},
 	{6, 0},
+	{305, 0},
 	{303, 0},
+	{302, 0},
 	{304, 0},
-	{307, 0},
-	{305, 0},
 	{1, "lambda"},
-	{323, 0},
-	{308, 0},
+	{306, 0},
 	{1, "or"},
-	{309, 0},
+	{307, 0},
 	{1, "and"},
 	{1, "not"},
+	{308, 0},
 	{310, 0},
-	{311, 0},
+	{309, 0},
 	{20, 0},
 	{21, 0},
 	{28, 0},
@@ -2157,53 +2011,52 @@
 	{30, 0},
 	{29, 0},
 	{1, "is"},
-	{313, 0},
+	{312, 0},
 	{18, 0},
-	{314, 0},
+	{313, 0},
 	{33, 0},
-	{315, 0},
+	{314, 0},
 	{19, 0},
-	{316, 0},
+	{315, 0},
 	{34, 0},
 	{35, 0},
-	{317, 0},
+	{316, 0},
 	{14, 0},
 	{15, 0},
-	{318, 0},
+	{317, 0},
 	{17, 0},
 	{24, 0},
 	{48, 0},
 	{32, 0},
+	{318, 0},
 	{319, 0},
+	{321, 0},
 	{320, 0},
-	{324, 0},
-	{322, 0},
 	{9, 0},
-	{321, 0},
 	{10, 0},
 	{26, 0},
-	{330, 0},
+	{327, 0},
 	{27, 0},
 	{2, 0},
 	{3, 0},
-	{335, 0},
-	{338, 0},
-	{325, 0},
-	{326, 0},
-	{327, 0},
+	{1, "None"},
+	{1, "True"},
+	{1, "False"},
+	{332, 0},
+	{322, 0},
+	{323, 0},
+	{324, 0},
 	{1, "class"},
+	{330, 0},
+	{331, 0},
 	{333, 0},
 	{334, 0},
-	{336, 0},
-	{337, 0},
-	{339, 0},
-	{340, 0},
-	{341, 0},
+	{335, 0},
 	{1, "yield"},
 };
 grammar _PyParser_Grammar = {
-	87,
+	81,
 	dfas,
-	{168, labels},
+	{167, labels},
 	256
 };

Modified: python/branches/p3yk-noslice/Python/import.c
==============================================================================
--- python/branches/p3yk-noslice/Python/import.c	(original)
+++ python/branches/p3yk-noslice/Python/import.c	Wed Jul 11 15:40:56 2007
@@ -4,6 +4,7 @@
 #include "Python.h"
 
 #include "Python-ast.h"
+#undef Yield /* undefine macro conflicting with winbase.h */
 #include "pyarena.h"
 #include "pythonrun.h"
 #include "errcode.h"
@@ -72,9 +73,10 @@
 		      3030 (added keyword-only parameters)
 		      3040 (added signature annotations)
 		      3050 (print becomes a function)
+		      3060 (PEP 3115 metaclass syntax)
 .
 */
-#define MAGIC (3050 | ((long)'\r'<<16) | ((long)'\n'<<24))
+#define MAGIC (3060 | ((long)'\r'<<16) | ((long)'\n'<<24))
 
 /* Magic word as global; note that _PyImport_Init() can change the
    value of this global to accommodate for alterations of how the
@@ -346,6 +348,14 @@
 	return Py_None;
 }
 
+static void
+imp_modules_reloading_clear(void)
+{
+	PyInterpreterState *interp = PyThreadState_Get()->interp;
+	if (interp->modules_reloading != NULL)
+		PyDict_Clear(interp->modules_reloading);
+}
+
 /* Helper for sys */
 
 PyObject *
@@ -360,8 +370,7 @@
 
 /* List of names to clear in sys */
 static char* sys_deletes[] = {
-	"path", "argv", "ps1", "ps2", "exitfunc",
-	"exc_type", "exc_value", "exc_traceback",
+	"path", "argv", "ps1", "ps2",
 	"last_type", "last_value", "last_traceback",
 	"path_hooks", "path_importer_cache", "meta_path",
 	NULL
@@ -505,6 +514,7 @@
 	PyDict_Clear(modules);
 	interp->modules = NULL;
 	Py_DECREF(modules);
+	Py_CLEAR(interp->modules_reloading);
 }
 
 
@@ -2407,13 +2417,21 @@
 PyObject *
 PyImport_ReloadModule(PyObject *m)
 {
+	PyInterpreterState *interp = PyThreadState_Get()->interp;
+	PyObject *modules_reloading = interp->modules_reloading;
 	PyObject *modules = PyImport_GetModuleDict();
-	PyObject *path = NULL, *loader = NULL;
+	PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
 	char *name, *subname;
 	char buf[MAXPATHLEN+1];
 	struct filedescr *fdp;
 	FILE *fp = NULL;
 	PyObject *newm;
+    
+	if (modules_reloading == NULL) {
+		Py_FatalError("PyImport_ReloadModule: "
+			      "no modules_reloading dictionary!");
+		return NULL;
+	}
 
 	if (m == NULL || !PyModule_Check(m)) {
 		PyErr_SetString(PyExc_TypeError,
@@ -2429,20 +2447,33 @@
 			     name);
 		return NULL;
 	}
+	existing_m = PyDict_GetItemString(modules_reloading, name);
+	if (existing_m != NULL) {
+		/* Due to a recursive reload, this module is already
+		   being reloaded. */
+		Py_INCREF(existing_m);
+		return existing_m;
+ 	}
+ 	if (PyDict_SetItemString(modules_reloading, name, m) < 0)
+		return NULL;
+
 	subname = strrchr(name, '.');
 	if (subname == NULL)
 		subname = name;
 	else {
 		PyObject *parentname, *parent;
 		parentname = PyString_FromStringAndSize(name, (subname-name));
-		if (parentname == NULL)
+		if (parentname == NULL) {
+			imp_modules_reloading_clear();
 			return NULL;
+        	}
 		parent = PyDict_GetItem(modules, parentname);
 		if (parent == NULL) {
 			PyErr_Format(PyExc_ImportError,
 			    "reload(): parent %.200s not in sys.modules",
 			    PyString_AS_STRING(parentname));
 			Py_DECREF(parentname);
+			imp_modules_reloading_clear();
 			return NULL;
 		}
 		Py_DECREF(parentname);
@@ -2457,6 +2488,7 @@
 
 	if (fdp == NULL) {
 		Py_XDECREF(loader);
+		imp_modules_reloading_clear();
 		return NULL;
 	}
 
@@ -2473,6 +2505,7 @@
 		 */
 		PyDict_SetItemString(modules, name, m);
 	}
+	imp_modules_reloading_clear();
 	return newm;
 }
 
@@ -2542,7 +2575,7 @@
 	if (import == NULL)
 		goto err;
 
-	/* Call the _import__ function with the proper argument list */
+	/* Call the __import__ function with the proper argument list */
 	r = PyObject_CallFunctionObjArgs(import, module_name, globals,
 					 globals, silly_list, NULL);
 

Modified: python/branches/p3yk-noslice/Python/marshal.c
==============================================================================
--- python/branches/p3yk-noslice/Python/marshal.c	(original)
+++ python/branches/p3yk-noslice/Python/marshal.c	Wed Jul 11 15:40:56 2007
@@ -15,7 +15,7 @@
  * and risks coring the interpreter.  When the object stack gets this deep,
  * raise an exception instead of continuing.
  */
-#define MAX_MARSHAL_STACK_DEPTH 5000
+#define MAX_MARSHAL_STACK_DEPTH 2000
 
 #define TYPE_NULL		'0'
 #define TYPE_NONE		'N'
@@ -235,9 +235,16 @@
 				goto exit;
 			}
 			else {
+				int ok;
 				o = PyInt_FromSsize_t(PyDict_Size(p->strings));
-				PyDict_SetItem(p->strings, v, o);
-				Py_DECREF(o);
+				ok = o &&
+				     PyDict_SetItem(p->strings, v, o) >= 0;
+				Py_XDECREF(o);
+				if (!ok) {
+					p->depth--;
+					p->error = 1;
+					return;
+				}
 				w_byte(TYPE_INTERNED, p);
 			}
 		}
@@ -403,7 +410,7 @@
 
 typedef WFILE RFILE; /* Same struct with different invariants */
 
-#define rs_byte(p) (((p)->ptr != (p)->end) ? (unsigned char)*(p)->ptr++ : EOF)
+#define rs_byte(p) (((p)->ptr < (p)->end) ? (unsigned char)*(p)->ptr++ : EOF)
 
 #define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p))
 
@@ -494,42 +501,60 @@
 	PyObject *v, *v2, *v3;
 	long i, n;
 	int type = r_byte(p);
+	PyObject *retval;
+
+	p->depth++;
+
+	if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
+		p->depth--;
+		PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
+		return NULL;
+	}
 
 	switch (type) {
 
 	case EOF:
 		PyErr_SetString(PyExc_EOFError,
 				"EOF read where object expected");
-		return NULL;
+		retval = NULL;
+		break;
 
 	case TYPE_NULL:
-		return NULL;
+		retval = NULL;
+		break;
 
 	case TYPE_NONE:
 		Py_INCREF(Py_None);
-		return Py_None;
+		retval = Py_None;
+		break;
 
 	case TYPE_STOPITER:
 		Py_INCREF(PyExc_StopIteration);
-		return PyExc_StopIteration;
+		retval = PyExc_StopIteration;
+		break;
 
 	case TYPE_ELLIPSIS:
 		Py_INCREF(Py_Ellipsis);
-		return Py_Ellipsis;
+		retval = Py_Ellipsis;
+		break;
 
 	case TYPE_FALSE:
 		Py_INCREF(Py_False);
-		return Py_False;
+		retval = Py_False;
+		break;
 
 	case TYPE_TRUE:
 		Py_INCREF(Py_True);
-		return Py_True;
+		retval = Py_True;
+		break;
 
 	case TYPE_INT:
-		return PyInt_FromLong(r_long(p));
+		retval = PyInt_FromLong(r_long(p));
+		break;
 
 	case TYPE_INT64:
-		return r_long64(p);
+		retval = r_long64(p);
+		break;
 
 	case TYPE_LONG:
 		{
@@ -539,12 +564,15 @@
 			if (n < -INT_MAX || n > INT_MAX) {
 				PyErr_SetString(PyExc_ValueError,
 						"bad marshal data");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			size = n<0 ? -n : n;
 			ob = _PyLong_New(size);
-			if (ob == NULL)
-				return NULL;
+			if (ob == NULL) {
+				retval = NULL;
+				break;
+			}
 			ob->ob_size = n;
 			for (i = 0; i < size; i++) {
 				int digit = r_short(p);
@@ -552,11 +580,14 @@
 					Py_DECREF(ob);
 					PyErr_SetString(PyExc_ValueError,
 							"bad marshal data");
-					return NULL;
+					ob = NULL;
+					break;
 				}
-				ob->ob_digit[i] = digit;
+				if (ob != NULL)
+					ob->ob_digit[i] = digit;
 			}
-			return (PyObject *)ob;
+			retval = (PyObject *)ob;
+			break;
 		}
 
 	case TYPE_FLOAT:
@@ -567,13 +598,16 @@
 			if (n == EOF || r_string(buf, (int)n, p) != n) {
 				PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			buf[n] = '\0';
-			PyFPE_START_PROTECT("atof", return 0)
+			retval = NULL;
+			PyFPE_START_PROTECT("atof", break)
 			dx = PyOS_ascii_atof(buf);
 			PyFPE_END_PROTECT(dx)
-			return PyFloat_FromDouble(dx);
+			retval = PyFloat_FromDouble(dx);
+			break;
 		}
 
 	case TYPE_BINARY_FLOAT:
@@ -583,13 +617,16 @@
 			if (r_string((char*)buf, 8, p) != 8) {
 				PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			x = _PyFloat_Unpack8(buf, 1);
 			if (x == -1.0 && PyErr_Occurred()) {
-				return NULL;
+				retval = NULL;
+				break;
 			}
-			return PyFloat_FromDouble(x);
+			retval = PyFloat_FromDouble(x);
+			break;
 		}
 
 #ifndef WITHOUT_COMPLEX
@@ -601,23 +638,27 @@
 			if (n == EOF || r_string(buf, (int)n, p) != n) {
 				PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			buf[n] = '\0';
-			PyFPE_START_PROTECT("atof", return 0)
+			retval = NULL;
+			PyFPE_START_PROTECT("atof", break;)
 			c.real = PyOS_ascii_atof(buf);
 			PyFPE_END_PROTECT(c)
 			n = r_byte(p);
 			if (n == EOF || r_string(buf, (int)n, p) != n) {
 				PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			buf[n] = '\0';
-			PyFPE_START_PROTECT("atof", return 0)
+			PyFPE_START_PROTECT("atof", break)
 			c.imag = PyOS_ascii_atof(buf);
 			PyFPE_END_PROTECT(c)
-			return PyComplex_FromCComplex(c);
+			retval = PyComplex_FromCComplex(c);
+			break;
 		}
 
 	case TYPE_BINARY_COMPLEX:
@@ -627,22 +668,27 @@
 			if (r_string((char*)buf, 8, p) != 8) {
 				PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			c.real = _PyFloat_Unpack8(buf, 1);
 			if (c.real == -1.0 && PyErr_Occurred()) {
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			if (r_string((char*)buf, 8, p) != 8) {
 				PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-				return NULL;
+				retval = NULL;
+				break;
 			}
 			c.imag = _PyFloat_Unpack8(buf, 1);
 			if (c.imag == -1.0 && PyErr_Occurred()) {
-				return NULL;
+				retval = NULL;
+				break;
 			}
-			return PyComplex_FromCComplex(c);
+			retval = PyComplex_FromCComplex(c);
+			break;
 		}
 #endif
 
@@ -651,32 +697,42 @@
 		n = r_long(p);
 		if (n < 0 || n > INT_MAX) {
 			PyErr_SetString(PyExc_ValueError, "bad marshal data");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		v = PyString_FromStringAndSize((char *)NULL, n);
-		if (v == NULL)
-			return v;
+		if (v == NULL) {
+			retval = NULL;
+			break;
+		}
 		if (r_string(PyString_AS_STRING(v), (int)n, p) != n) {
 			Py_DECREF(v);
 			PyErr_SetString(PyExc_EOFError,
 					"EOF read where object expected");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		if (type == TYPE_INTERNED) {
 			PyString_InternInPlace(&v);
-			PyList_Append(p->strings, v);
+			if (PyList_Append(p->strings, v) < 0) {
+				retval = NULL;
+				break;
+			}
 		}
-		return v;
+		retval = v;
+		break;
 
 	case TYPE_STRINGREF:
 		n = r_long(p);
 		if (n < 0 || n >= PyList_GET_SIZE(p->strings)) {
 			PyErr_SetString(PyExc_ValueError, "bad marshal data");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		v = PyList_GET_ITEM(p->strings, n);
 		Py_INCREF(v);
-		return v;
+		retval = v;
+		break;
 
 #ifdef Py_USING_UNICODE
 	case TYPE_UNICODE:
@@ -686,20 +742,25 @@
 		n = r_long(p);
 		if (n < 0 || n > INT_MAX) {
 			PyErr_SetString(PyExc_ValueError, "bad marshal data");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		buffer = PyMem_NEW(char, n);
-		if (buffer == NULL)
-			return PyErr_NoMemory();
+		if (buffer == NULL) {
+			retval = PyErr_NoMemory();
+			break;
+		}
 		if (r_string(buffer, (int)n, p) != n) {
 			PyMem_DEL(buffer);
 			PyErr_SetString(PyExc_EOFError,
 				"EOF read where object expected");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		v = PyUnicode_DecodeUTF8(buffer, n, NULL);
 		PyMem_DEL(buffer);
-		return v;
+		retval = v;
+		break;
 	    }
 #endif
 
@@ -707,11 +768,14 @@
 		n = r_long(p);
 		if (n < 0 || n > INT_MAX) {
 			PyErr_SetString(PyExc_ValueError, "bad marshal data");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		v = PyTuple_New((int)n);
-		if (v == NULL)
-			return v;
+		if (v == NULL) {
+			retval = NULL;
+			break;
+		}
 		for (i = 0; i < n; i++) {
 			v2 = r_object(p);
 			if ( v2 == NULL ) {
@@ -724,17 +788,21 @@
 			}
 			PyTuple_SET_ITEM(v, (int)i, v2);
 		}
-		return v;
+		retval = v;
+		break;
 
 	case TYPE_LIST:
 		n = r_long(p);
 		if (n < 0 || n > INT_MAX) {
 			PyErr_SetString(PyExc_ValueError, "bad marshal data");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		v = PyList_New((int)n);
-		if (v == NULL)
-			return v;
+		if (v == NULL) {
+			retval = NULL;
+			break;
+		}
 		for (i = 0; i < n; i++) {
 			v2 = r_object(p);
 			if ( v2 == NULL ) {
@@ -745,14 +813,17 @@
 				v = NULL;
 				break;
 			}
-			PyList_SetItem(v, (int)i, v2);
+			PyList_SET_ITEM(v, (int)i, v2);
 		}
-		return v;
+		retval = v;
+		break;
 
 	case TYPE_DICT:
 		v = PyDict_New();
-		if (v == NULL)
-			return NULL;
+		if (v == NULL) {
+			retval = NULL;
+			break;
+		}
 		for (;;) {
 			PyObject *key, *val;
 			key = r_object(p);
@@ -768,18 +839,22 @@
 			Py_DECREF(v);
 			v = NULL;
 		}
-		return v;
+		retval = v;
+		break;
 
 	case TYPE_SET:
 	case TYPE_FROZENSET:
 		n = r_long(p);
-		if (n < 0) {
+		if (n < 0 || n > INT_MAX) {
 			PyErr_SetString(PyExc_ValueError, "bad marshal data");
-			return NULL;
+			retval = NULL;
+			break;
 		}
 		v = PyTuple_New((int)n);
-		if (v == NULL)
-			return v;
+		if (v == NULL) {
+			retval = NULL;
+			break;
+		}
 		for (i = 0; i < n; i++) {
 			v2 = r_object(p);
 			if ( v2 == NULL ) {
@@ -792,23 +867,20 @@
 			}
 			PyTuple_SET_ITEM(v, (int)i, v2);
 		}
-		if (v == NULL)
-			return v;
+		if (v == NULL) {
+			retval = NULL;
+			break;
+		}
 		if (type == TYPE_SET)
 			v3 = PySet_New(v);
 		else
 			v3 = PyFrozenSet_New(v);
 		Py_DECREF(v);
-		return v3;
+		retval = v3;
+		break;
 
 	case TYPE_CODE:
-		if (PyEval_GetRestricted()) {
-			PyErr_SetString(PyExc_RuntimeError,
-				"cannot unmarshal code objects in "
-				"restricted execution mode");
-			return NULL;
-		}
-		else {
+		{
 			int argcount;
 			int kwonlyargcount;
 			int nlocals;
@@ -827,7 +899,7 @@
 			
 			v = NULL;
 
-                        /* XXX ignore long->int overflows for now */
+			/* XXX ignore long->int overflows for now */
 			argcount = (int)r_long(p);
 			kwonlyargcount = (int)r_long(p);
 			nlocals = (int)r_long(p);
@@ -880,16 +952,21 @@
 			Py_XDECREF(name);
 			Py_XDECREF(lnotab);
 
+			return v;
 		}
-		return v;
+		retval = v;
+		break;
 
 	default:
 		/* Bogus data got written, which isn't ideal.
 		   This will let you keep working and recover. */
 		PyErr_SetString(PyExc_ValueError, "bad marshal data");
-		return NULL;
+		retval = NULL;
+		break;
 
 	}
+	p->depth--;
+	return retval;
 }
 
 static PyObject *
@@ -995,6 +1072,7 @@
 	PyObject *result;
 	rf.fp = fp;
 	rf.strings = PyList_New(0);
+	rf.depth = 0;
 	result = r_object(&rf);
 	Py_DECREF(rf.strings);
 	return result;
@@ -1009,6 +1087,7 @@
 	rf.ptr = str;
 	rf.end = str + len;
 	rf.strings = PyList_New(0);
+	rf.depth = 0;
 	result = r_object(&rf);
 	Py_DECREF(rf.strings);
 	return result;
@@ -1062,9 +1141,14 @@
 	if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version))
 		return NULL;
 	if (!PyFile_Check(f)) {
-		PyErr_SetString(PyExc_TypeError,
-				"marshal.dump() 2nd arg must be file");
-		return NULL;
+		/* XXX Quick hack -- need to do this differently */
+		PyObject *s = PyMarshal_WriteObjectToString(x, version);
+		PyObject *res = NULL;
+		if (s != NULL) {
+			res = PyObject_CallMethod(f, "write", "O", s);
+			Py_DECREF(s);
+		}
+		return res;
 	}
 	wf.fp = PyFile_AsFile(f);
 	wf.str = NULL;
@@ -1097,6 +1181,7 @@
 	}
 	rf.fp = PyFile_AsFile(f);
 	rf.strings = PyList_New(0);
+	rf.depth = 0;
 	result = read_object(&rf);
 	Py_DECREF(rf.strings);
 	return result;
@@ -1125,6 +1210,7 @@
 	rf.ptr = s;
 	rf.end = s + n;
 	rf.strings = PyList_New(0);
+	rf.depth = 0;
 	result = read_object(&rf);
 	Py_DECREF(rf.strings);
 	return result;

Modified: python/branches/p3yk-noslice/Python/mystrtoul.c
==============================================================================
--- python/branches/p3yk-noslice/Python/mystrtoul.c	(original)
+++ python/branches/p3yk-noslice/Python/mystrtoul.c	Wed Jul 11 15:40:56 2007
@@ -91,7 +91,7 @@
 **		This is a general purpose routine for converting
 **		an ascii string to an integer in an arbitrary base.
 **		Leading white space is ignored.  If 'base' is zero
-**		it looks for a leading 0, 0x or 0X to tell which
+**		it looks for a leading 0b, 0o or 0x to tell which
 **		base.  If these are absent it defaults to 10.
 **		Base must be 0 or between 2 and 36 (inclusive).
 **		If 'ptr' is non-NULL it will contain a pointer to
@@ -110,29 +110,57 @@
 	while (*str && isspace(Py_CHARMASK(*str)))
 		++str;
 
-	/* check for leading 0 or 0x for auto-base or base 16 */
+	/* check for leading 0b, 0o or 0x for auto-base or base 16 */
 	switch (base) {
-		case 0:		/* look for leading 0, 0x or 0X */
-			if (*str == '0') {
+	case 0:		/* look for leading 0b, 0o or 0x */
+		if (*str == '0') {
+			++str;
+			if (*str == 'x' || *str == 'X') {
 				++str;
-				if (*str == 'x' || *str == 'X') {
-					++str;
-					base = 16;
-				}
-				else
-					base = 8;
-			}
-			else
-				base = 10;
-			break;
-
-		case 16:	/* skip leading 0x or 0X */
-			if (*str == '0') {
+				base = 16;
+			} else if (*str == 'o' || *str == 'O') {
 				++str;
-				if (*str == 'x' || *str == 'X')
+				base = 8;
+			} else if (*str == 'b' || *str == 'B') {
+				++str;
+				base = 2;
+			} else {
+				/* skip all zeroes... */
+				while (*str == '0')
+					++str;
+				while (isspace(Py_CHARMASK(*str)))
 					++str;
+				if (ptr)
+					*ptr = str;
+				return 0;
 			}
-			break;
+		}
+		else
+			base = 10;
+		break;
+
+	/* even with explicit base, skip leading 0? prefix */
+	case 16:
+		if (*str == '0') {
+			++str;
+			if (*str == 'x' || *str == 'X')
+				++str;
+		}
+		break;
+	case 8:
+		if (*str == '0') {
+			++str;
+			if (*str == 'o' || *str == 'O')
+				++str;
+		}
+		break;
+	case 2:
+		if(*str == '0') {
+			++str;
+			if (*str == 'b' || *str == 'B')
+				++str;
+		}
+		break;
 	}
 
 	/* catch silly bases */

Modified: python/branches/p3yk-noslice/Python/peephole.c
==============================================================================
--- python/branches/p3yk-noslice/Python/peephole.c	(original)
+++ python/branches/p3yk-noslice/Python/peephole.c	Wed Jul 11 15:40:56 2007
@@ -1,4 +1,4 @@
-/* Peehole optimizations for bytecode compiler. */
+/* Peephole optimizations for bytecode compiler. */
 
 #include "Python.h"
 
@@ -257,14 +257,47 @@
 	return blocks;
 }
 
+/* Helper to replace LOAD_NAME None/True/False with LOAD_CONST
+   Returns: 0 if no change, 1 if change, -1 if error */
+static int
+load_global(unsigned char *codestr, Py_ssize_t i, char *name, PyObject *consts)
+{
+	Py_ssize_t j;
+	PyObject *obj;
+	if (name == NULL)
+		return 0;
+	if (strcmp(name, "None") == 0)
+		obj = Py_None;
+	else if (strcmp(name, "True") == 0)
+		obj = Py_True;
+	else if (strcmp(name, "False") == 0)
+		obj = Py_False;
+	else
+		return 0;
+	for (j = 0; j < PyList_GET_SIZE(consts); j++) {
+		if (PyList_GET_ITEM(consts, j) == obj)
+			break;
+	}
+	if (j == PyList_GET_SIZE(consts)) {
+		if (PyList_Append(consts, obj) < 0)
+			return -1;
+	}
+	assert(PyList_GET_ITEM(consts, j) == obj);
+	codestr[i] = LOAD_CONST;
+	SETARG(codestr, i, j);
+	return 1;
+}
+
 /* Perform basic peephole optimizations to components of a code object.
    The consts object should still be in list form to allow new constants 
    to be appended.
 
-   To keep the optimizer simple, it bails out (does nothing) for code
-   containing extended arguments or that has a length over 32,700.  That 
-   allows us to avoid overflow and sign issues.	 Likewise, it bails when
-   the lineno table has complex encoding for gaps >= 255.
+   To keep the optimizer simple, it bails out (does nothing) for code that
+   has a length over 32,700, and does not calculate extended arguments. 
+   That allows us to avoid overflow and sign issues. Likewise, it bails when
+   the lineno table has complex encoding for gaps >= 255. EXTENDED_ARG can
+   appear before MAKE_FUNCTION; in this case both opcodes are skipped.
+   EXTENDED_ARG preceding any other opcode causes the optimizer to bail.
 
    Optimizations are restricted to simple transformations occuring within a
    single basic block.	All transformations keep the code size the same or 
@@ -300,7 +333,7 @@
 
 	/* Avoid situations where jump retargeting could overflow */
 	assert(PyString_Check(code));
-	codelen = PyString_Size(code);
+	codelen = PyString_GET_SIZE(code);
 	if (codelen > 32700)
 		goto exitUnchanged;
 
@@ -369,22 +402,18 @@
 				codestr[i+3] = NOP;
 				break;
 
-				/* Replace LOAD_GLOBAL/LOAD_NAME None
-                                   with LOAD_CONST None */
+				/* Replace LOAD_GLOBAL/LOAD_NAME None/True/False
+                                   with LOAD_CONST None/True/False */
 			case LOAD_NAME:
 			case LOAD_GLOBAL:
 				j = GETARG(codestr, i);
 				name = PyString_AsString(PyTuple_GET_ITEM(names, j));
-				if (name == NULL  ||  strcmp(name, "None") != 0)
+				h = load_global(codestr, i, name, consts);
+				if (h < 0)
+					goto exitUnchanged;
+				else if (h == 0)
 					continue;
-				for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
-					if (PyList_GET_ITEM(consts, j) == Py_None) {
-						codestr[i] = LOAD_CONST;
-						SETARG(codestr, i, j);
-						cumlc = lastlc + 1;
-						break;
-					}
-				}
+				cumlc = lastlc + 1;
 				break;
 
 				/* Skip over LOAD_CONST trueconst
@@ -535,7 +564,11 @@
 				break;
 
 			case EXTENDED_ARG:
-				goto exitUnchanged;
+				if (codestr[i+3] != MAKE_FUNCTION)
+					goto exitUnchanged;
+				/* don't visit MAKE_FUNCTION as GETARG will be wrong */
+				i += 3;
+				break;
 
 				/* Replace RETURN LOAD_CONST None RETURN with just RETURN */
 				/* Remove unreachable JUMPs after RETURN */

Modified: python/branches/p3yk-noslice/Python/pystate.c
==============================================================================
--- python/branches/p3yk-noslice/Python/pystate.c	(original)
+++ python/branches/p3yk-noslice/Python/pystate.c	Wed Jul 11 15:40:56 2007
@@ -68,6 +68,7 @@
 			Py_FatalError("Can't initialize threads for interpreter");
 #endif
 		interp->modules = NULL;
+		interp->modules_reloading = NULL;
 		interp->sysdict = NULL;
 		interp->builtins = NULL;
 		interp->tstate_head = NULL;
@@ -107,6 +108,7 @@
 	Py_CLEAR(interp->codec_search_cache);
 	Py_CLEAR(interp->codec_error_registry);
 	Py_CLEAR(interp->modules);
+	Py_CLEAR(interp->modules_reloading);
 	Py_CLEAR(interp->sysdict);
 	Py_CLEAR(interp->builtins);
 }

Modified: python/branches/p3yk-noslice/Python/pythonrun.c
==============================================================================
--- python/branches/p3yk-noslice/Python/pythonrun.c	(original)
+++ python/branches/p3yk-noslice/Python/pythonrun.c	Wed Jul 11 15:40:56 2007
@@ -4,6 +4,7 @@
 #include "Python.h"
 
 #include "Python-ast.h"
+#undef Yield /* undefine macro conflicting with winbase.h */
 #include "grammar.h"
 #include "node.h"
 #include "token.h"
@@ -56,7 +57,7 @@
 			      PyCompilerFlags *);
 static void err_input(perrdetail *);
 static void initsigs(void);
-static void call_sys_exitfunc(void);
+static void call_py_exitfuncs(void);
 static void call_ll_exitfuncs(void);
 extern void _PyUnicode_Init(void);
 extern void _PyUnicode_Fini(void);
@@ -71,6 +72,7 @@
 int Py_DebugFlag; /* Needed by parser.c */
 int Py_VerboseFlag; /* Needed by import.c */
 int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
+int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
 int Py_NoSiteFlag; /* Suppress 'import site' */
 int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
 int Py_FrozenFlag; /* Needed by getpath.c */
@@ -186,11 +188,17 @@
 	if (!_PyLong_Init())
 		Py_FatalError("Py_Initialize: can't init longs");
 
+	if (!PyBytes_Init())
+		Py_FatalError("Py_Initialize: can't init bytes");
+
 	_PyFloat_Init();
 
 	interp->modules = PyDict_New();
 	if (interp->modules == NULL)
 		Py_FatalError("Py_Initialize: can't make modules dictionary");
+	interp->modules_reloading = PyDict_New();
+	if (interp->modules_reloading == NULL)
+		Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
 
 #ifdef Py_USING_UNICODE
 	/* Init Unicode implementation; relies on the codec registry */
@@ -221,7 +229,6 @@
 
 	/* initialize builtin exceptions */
 	_PyExc_Init();
-	_PyImport_FixupExtension("exceptions", "exceptions");
 
 	/* phase 2 of builtins */
 	_PyImport_FixupExtension("__builtin__", "__builtin__");
@@ -353,7 +360,7 @@
 	 * threads created thru it, so this also protects pending imports in
 	 * the threads created via Threading.
 	 */
-	call_sys_exitfunc();
+	call_py_exitfuncs();
 	initialized = 0;
 
 	/* Get current thread state and interpreter pointer */
@@ -458,6 +465,7 @@
 	PyList_Fini();
 	PySet_Fini();
 	PyString_Fini();
+	PyBytes_Fini();
 	PyLong_Fini();
 	PyFloat_Fini();
 
@@ -528,6 +536,7 @@
 	/* XXX The following is lax in error checking */
 
 	interp->modules = PyDict_New();
+	interp->modules_reloading = PyDict_New();
 
 	bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
 	if (bimod != NULL) {
@@ -844,6 +853,7 @@
 {
 	PyObject *m, *d, *v;
 	const char *ext;
+	int set_file_name = 0, ret;
 
 	m = PyImport_AddModule("__main__");
 	if (m == NULL)
@@ -857,6 +867,7 @@
 			Py_DECREF(f);
 			return -1;
 		}
+		set_file_name = 1;
 		Py_DECREF(f);
 	}
 	ext = filename + strlen(filename) - 4;
@@ -866,7 +877,8 @@
 			fclose(fp);
 		if ((fp = fopen(filename, "rb")) == NULL) {
 			fprintf(stderr, "python: Can't reopen .pyc file\n");
-			return -1;
+			ret = -1;
+			goto done;
 		}
 		/* Turn on optimization if a .pyo file is given */
 		if (strcmp(ext, ".pyo") == 0)
@@ -878,10 +890,15 @@
 	}
 	if (v == NULL) {
 		PyErr_Print();
-		return -1;
+		ret = -1;
+		goto done;
 	}
 	Py_DECREF(v);
-	return 0;
+	ret = 0;
+  done:
+	if (set_file_name && PyDict_DelItemString(d, "__file__"))
+		PyErr_Clear();
+	return ret;
 }
 
 int
@@ -1011,6 +1028,11 @@
 	PyObject *exception, *value, *tb;
 	int exitcode = 0;
 
+	if (Py_InspectFlag)
+		/* Don't exit if -i flag was given. This flag is set to 0
+		 * when entering interactive mode for inspecting. */
+		return;
+
 	PyErr_Fetch(&exception, &value, &tb);
 	fflush(stdout);
 	if (value == NULL || value == Py_None)
@@ -1168,7 +1190,7 @@
 				err = PyFile_WriteString("<unknown>", f);
 			else {
 				char* modstr = PyString_AsString(moduleName);
-				if (modstr && strcmp(modstr, "exceptions"))
+				if (modstr && strcmp(modstr, "__builtin__"))
 				{
 					err = PyFile_WriteString(modstr, f);
 					err += PyFile_WriteString(".", f);
@@ -1198,8 +1220,8 @@
 			  err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
 			Py_XDECREF(s);
 		}
-		if (err == 0)
-			err = PyFile_WriteString("\n", f);
+		/* try to write a newline in any case */
+		err += PyFile_WriteString("\n", f);
 	}
 	Py_DECREF(value);
 	/* If an error happened here, don't show it.
@@ -1237,12 +1259,12 @@
 	
 	mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
 				   flags, NULL, arena);
+	if (closeit)
+		fclose(fp);
 	if (mod == NULL) {
 		PyArena_Free(arena);
 		return NULL;
 	}
-	if (closeit)
-		fclose(fp);
 	ret = run_mod(mod, filename, globals, locals, flags, arena);
 	PyArena_Free(arena);
 	return ret;
@@ -1554,6 +1576,23 @@
 #include "pythread.h"
 #endif
 
+static void (*pyexitfunc)(void) = NULL;
+/* For the atexit module. */
+void _Py_PyAtExit(void (*func)(void))
+{
+	pyexitfunc = func;
+}
+
+static void
+call_py_exitfuncs(void)
+{
+	if (pyexitfunc == NULL) 
+		return;
+
+	(*pyexitfunc)();
+	PyErr_Clear();
+}
+
 #define NEXITFUNCS 32
 static void (*exitfuncs[NEXITFUNCS])(void);
 static int nexitfuncs = 0;
@@ -1567,27 +1606,6 @@
 }
 
 static void
-call_sys_exitfunc(void)
-{
-	PyObject *exitfunc = PySys_GetObject("exitfunc");
-
-	if (exitfunc) {
-		PyObject *res;
-		Py_INCREF(exitfunc);
-		PySys_SetObject("exitfunc", (PyObject *)NULL);
-		res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
-		if (res == NULL) {
-			if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
-				PySys_WriteStderr("Error in sys.exitfunc:\n");
-			}
-			PyErr_Print();
-		}
-		Py_DECREF(exitfunc);
-	}
-
-}
-
-static void
 call_ll_exitfuncs(void)
 {
 	while (nexitfuncs > 0)

Modified: python/branches/p3yk-noslice/Python/structmember.c
==============================================================================
--- python/branches/p3yk-noslice/Python/structmember.c	(original)
+++ python/branches/p3yk-noslice/Python/structmember.c	Wed Jul 11 15:40:56 2007
@@ -54,11 +54,7 @@
 PyMember_GetOne(const char *addr, PyMemberDef *l)
 {
 	PyObject *v;
-	if ((l->flags & READ_RESTRICTED) &&
-	    PyEval_GetRestricted()) {
-		PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
-		return NULL;
-	}
+
 	addr += l->offset;
 	switch (l->type) {
 	case T_BYTE:
@@ -85,6 +81,9 @@
 	case T_ULONG:
 		v = PyLong_FromUnsignedLong(*(unsigned long*)addr);
 		break;
+	case T_PYSSIZET:
+		v = PyInt_FromSsize_t(*(Py_ssize_t*)addr);
+		break;
 	case T_FLOAT:
 		v = PyFloat_FromDouble((double)*(float*)addr);
 		break;
@@ -164,11 +163,7 @@
 
 	if ((l->flags & READONLY) || l->type == T_STRING)
 	{
-		PyErr_SetString(PyExc_TypeError, "readonly attribute");
-		return -1;
-	}
-	if ((l->flags & WRITE_RESTRICTED) && PyEval_GetRestricted()) {
-		PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
+		PyErr_SetString(PyExc_AttributeError, "readonly attribute");
 		return -1;
 	}
 	if (v == NULL && l->type != T_OBJECT_EX && l->type != T_OBJECT) {
@@ -267,6 +262,13 @@
 		}
 		break;
 		}
+	case T_PYSSIZET:{
+		*(Py_ssize_t*)addr = PyInt_AsSsize_t(v);
+		if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1)
+		    && PyErr_Occurred())
+				return -1;
+		break;
+		}
 	case T_FLOAT:{
 		double double_val;
 		double_val = PyFloat_AsDouble(v);
@@ -297,31 +299,25 @@
 		}
 		break;
 #ifdef HAVE_LONG_LONG
-	case T_LONGLONG:
-		if (!PyLong_Check(v)) {
-			PyErr_BadArgument();
+	case T_LONGLONG:{
+		PY_LONG_LONG value;
+		*(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v);
+		if ((value == -1) && PyErr_Occurred())
 			return -1;
-		} else {
-                        PY_LONG_LONG value;
-                        *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v);
-                        if ((value == -1) && PyErr_Occurred()) {
-                                return -1;
-                        }
-                }
-                break;
-	case T_ULONGLONG:
-                if (!PyLong_Check(v)) {
-                        PyErr_BadArgument();
-                        return -1;
-                } else {
-                        unsigned PY_LONG_LONG value;
-                        *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v);
-                        if ((value == (unsigned PY_LONG_LONG)-1) &&
-			    PyErr_Occurred()) {
-                                return -1;
-                        }
-                }
-                break;
+		break;
+		}
+	case T_ULONGLONG:{
+		unsigned PY_LONG_LONG value;
+		/* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong
+			doesn't ??? */
+		if (PyLong_Check(v))
+			*(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v);
+		else
+			*(unsigned PY_LONG_LONG*)addr = value = PyInt_AsLong(v);
+		if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred())
+			return -1;
+		break;
+		}
 #endif /* HAVE_LONG_LONG */
 	default:
 		PyErr_Format(PyExc_SystemError,

Modified: python/branches/p3yk-noslice/Python/symtable.c
==============================================================================
--- python/branches/p3yk-noslice/Python/symtable.c	(original)
+++ python/branches/p3yk-noslice/Python/symtable.c	Wed Jul 11 15:40:56 2007
@@ -8,9 +8,15 @@
 #define GLOBAL_AFTER_ASSIGN \
 "name '%.400s' is assigned to before global declaration"
 
+#define NONLOCAL_AFTER_ASSIGN \
+"name '%.400s' is assigned to before nonlocal declaration"
+
 #define GLOBAL_AFTER_USE \
 "name '%.400s' is used prior to global declaration"
 
+#define NONLOCAL_AFTER_USE \
+"name '%.400s' is used prior to nonlocal declaration"
+
 #define IMPORT_STAR_WARNING "import * only allowed at module level"
 
 #define RETURN_VAL_IN_GENERATOR \
@@ -70,7 +76,7 @@
 	ste->ste_generator = 0;
 	ste->ste_returns_value = 0;
 
-	if (PyDict_SetItem(st->st_symbols, ste->ste_id, (PyObject *)ste) < 0)
+	if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
 	    goto fail;
 	
 	return ste;
@@ -166,21 +172,22 @@
 static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
 static int symtable_visit_expr(struct symtable *st, expr_ty s);
 static int symtable_visit_genexp(struct symtable *st, expr_ty s);
+static int symtable_visit_listcomp(struct symtable *st, expr_ty s);
+static int symtable_visit_setcomp(struct symtable *st, expr_ty s);
 static int symtable_visit_arguments(struct symtable *st, arguments_ty);
 static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
 static int symtable_visit_alias(struct symtable *st, alias_ty);
 static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
 static int symtable_visit_keyword(struct symtable *st, keyword_ty);
 static int symtable_visit_slice(struct symtable *st, slice_ty);
-static int symtable_visit_params(struct symtable *st, asdl_seq *args, int top,
-                                 int annotations);
-static int symtable_visit_params_nested(struct symtable *st, asdl_seq *args,
-                                        int annotations);
+static int symtable_visit_params(struct symtable *st, asdl_seq *args);
+static int symtable_visit_argannotations(struct symtable *st, asdl_seq *args);
 static int symtable_implicit_arg(struct symtable *st, int pos);
 static int symtable_visit_annotations(struct symtable *st, stmt_ty s);
 
 
-static identifier top = NULL, lambda = NULL, genexpr = NULL;
+static identifier top = NULL, lambda = NULL, genexpr = NULL,
+    listcomp = NULL, setcomp = NULL, __class__ = NULL;
 
 #define GET_IDENTIFIER(VAR) \
 	((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
@@ -198,14 +205,13 @@
 		return NULL;
 
 	st->st_filename = NULL;
-	st->st_symbols = NULL;
+	st->st_blocks = NULL;
 
 	if ((st->st_stack = PyList_New(0)) == NULL)
 		goto fail;
-	if ((st->st_symbols = PyDict_New()) == NULL)
+	if ((st->st_blocks = PyDict_New()) == NULL)
 		goto fail; 
 	st->st_cur = NULL;
-	st->st_tmpname = 0;
 	st->st_private = NULL;
 	return st;
  fail:
@@ -224,6 +230,7 @@
 		return st;
 	st->st_filename = filename;
 	st->st_future = future;
+	/* Make the initial symbol information gathering pass */
 	if (!GET_IDENTIFIER(top) ||
 	    !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) {
 		PySymtable_Free(st);
@@ -232,7 +239,6 @@
 
 	st->st_top = st->st_cur;
 	st->st_cur->ste_unoptimized = OPT_TOPLEVEL;
-	/* Any other top-level initialization? */
 	switch (mod->kind) {
 	case Module_kind:
 		seq = mod->v.Module.body;
@@ -261,6 +267,7 @@
 		PySymtable_Free(st);
 		return NULL;
 	}
+	/* Make the second symbol analysis pass */
 	if (symtable_analyze(st))
 		return st;
 	PySymtable_Free(st);
@@ -274,7 +281,7 @@
 void
 PySymtable_Free(struct symtable *st)
 {
-	Py_XDECREF(st->st_symbols);
+	Py_XDECREF(st->st_blocks);
 	Py_XDECREF(st->st_stack);
 	PyMem_Free((void *)st);
 }
@@ -287,7 +294,7 @@
 	k = PyLong_FromVoidPtr(key);
 	if (k == NULL)
 		return NULL;
-	v = PyDict_GetItem(st->st_symbols, k);
+	v = PyDict_GetItem(st->st_blocks, k);
 	if (v) {
 		assert(PySTEntry_Check(v));
 		Py_INCREF(v);
@@ -308,18 +315,18 @@
 	if (!v)
 		return 0;
 	assert(PyInt_Check(v));
-	return (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
+	return (PyInt_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK;
 }
 
 
 /* Analyze raw symbol information to determine scope of each name.
 
-   The next several functions are helpers for PySymtable_Analyze(),
+   The next several functions are helpers for symtable_analyze(),
    which determines whether a name is local, global, or free.  In addition, 
    it determines which local variables are cell variables; they provide
    bindings that are used for free variables in enclosed blocks.  
 
-   There are also two kinds of free variables, implicit and explicit.  An 
+   There are also two kinds of global variables, implicit and explicit.  An 
    explicit global is declared with the global statement.  An implicit
    global is a free variable for which the compiler has found no binding
    in an enclosing function scope.  The implicit global is either a global
@@ -329,24 +336,32 @@
    is treated as a local.
 
    The symbol table requires two passes to determine the scope of each name.
-   The first pass collects raw facts from the AST: the name is a parameter 
-   here, the name is used by not defined here, etc.  The second pass analyzes
-   these facts during a pass over the PySTEntryObjects created during pass 1.
+   The first pass collects raw facts from the AST via the symtable_visit_*
+   functions: the name is a parameter here, the name is used but not defined
+   here, etc.  The second pass analyzes these facts during a pass over the
+   PySTEntryObjects created during pass 1.
 
    When a function is entered during the second pass, the parent passes
    the set of all name bindings visible to its children.  These bindings 
-   are used to determine if the variable is free or an implicit global.
-   After doing the local analysis, it analyzes each of its child blocks
-   using an updated set of name bindings.  
-
-   The children update the free variable set.  If a local variable is free 
-   in a child, the variable is marked as a cell.  The current function must 
-   provide runtime storage for the variable that may outlive the function's 
-   frame.  Cell variables are removed from the free set before the analyze
-   function returns to its parent.
-   
-   The sets of bound and free variables are implemented as dictionaries
-   mapping strings to None.
+   are used to determine if non-local variables are free or implicit globals.
+   Names which are explicitly declared nonlocal must exist in this set of
+   visible names - if they do not, a syntax error is raised. After doing
+   the local analysis, it analyzes each of its child blocks using an
+   updated set of name bindings.
+
+   The children update the free variable set.  If a local variable is added to
+   the free variable set by the child, the variable is marked as a cell.  The
+   function object being defined must provide runtime storage for the variable
+   that may outlive the function's frame.  Cell variables are removed from the
+   free set before the analyze function returns to its parent.
+
+   During analysis, the names are:
+      symbols: dict mapping from symbol names to flag values (including offset scope values)
+      scopes: dict mapping from symbol names to scope values (no offset)
+      local: set of all symbol names local to the current scope
+      bound: set of all symbol names local to a containing function scope
+      free: set of all symbol names referenced but not bound in child scopes
+      global: set of all symbol names explicitly declared as global
 */
 
 #define SET_SCOPE(DICT, NAME, I) { \
@@ -367,34 +382,59 @@
 */
 
 static int 
-analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, long flags,
+analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags,
 	     PyObject *bound, PyObject *local, PyObject *free, 
 	     PyObject *global)
 {
 	if (flags & DEF_GLOBAL) {
 		if (flags & DEF_PARAM) {
 			PyErr_Format(PyExc_SyntaxError,
-				     "name '%s' is local and global",
+				     "name '%s' is parameter and global",
 				     PyString_AS_STRING(name));
 			return 0;
 		}
-		SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
-		if (PyDict_SetItem(global, name, Py_None) < 0)
+                if (flags & DEF_NONLOCAL) {
+			PyErr_Format(PyExc_SyntaxError,
+				     "name '%s' is nonlocal and global",
+				     PyString_AS_STRING(name));
+			return 0;
+                }
+		SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
+		if (PySet_Add(global, name) < 0)
+			return 0;
+		if (bound && (PySet_Discard(bound, name) < 0))
 			return 0;
-		if (bound && PyDict_GetItem(bound, name)) {
-			if (PyDict_DelItem(bound, name) < 0)
-				return 0;
-		}
 		return 1;
 	}
-	if (flags & DEF_BOUND) {
-		SET_SCOPE(dict, name, LOCAL);
-		if (PyDict_SetItem(local, name, Py_None) < 0)
+        if (flags & DEF_NONLOCAL) {
+		if (flags & DEF_PARAM) {
+			PyErr_Format(PyExc_SyntaxError,
+				     "name '%s' is parameter and nonlocal",
+				     PyString_AS_STRING(name));
 			return 0;
-		if (PyDict_GetItem(global, name)) {
-			if (PyDict_DelItem(global, name) < 0)
-				return 0;
 		}
+		if (!bound) {
+			PyErr_Format(PyExc_SyntaxError,
+				     "nonlocal declaration not allowed at module level");
+                        return 0;
+		}
+                if (!PySet_Contains(bound, name)) {
+                        PyErr_Format(PyExc_SyntaxError,
+                                     "no binding for nonlocal '%s' found",
+				     PyString_AS_STRING(name));
+                                     
+                        return 0;
+                }
+                SET_SCOPE(scopes, name, FREE);
+                ste->ste_free = 1;
+                return PySet_Add(free, name) >= 0;
+        }
+	if (flags & DEF_BOUND) {
+		SET_SCOPE(scopes, name, LOCAL);
+		if (PySet_Add(local, name) < 0)
+			return 0;
+		if (PySet_Discard(global, name) < 0)
+			return 0;
 		return 1;
 	}
 	/* If an enclosing block has a binding for this name, it
@@ -402,27 +442,22 @@
 	   Note that having a non-NULL bound implies that the block
 	   is nested.
 	*/
-	if (bound && PyDict_GetItem(bound, name)) {
-		SET_SCOPE(dict, name, FREE);
+	if (bound && PySet_Contains(bound, name)) {
+		SET_SCOPE(scopes, name, FREE);
 		ste->ste_free = 1;
-		if (PyDict_SetItem(free, name, Py_None) < 0)
-			return 0;
-		return 1;
+		return PySet_Add(free, name) >= 0;
 	}
 	/* If a parent has a global statement, then call it global
 	   explicit?  It could also be global implicit.
 	 */
-	else if (global && PyDict_GetItem(global, name)) {
-		SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
-		return 1;
-	}
-	else {
-		if (ste->ste_nested)
-			ste->ste_free = 1;
-		SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
+	if (global && PySet_Contains(global, name)) {
+		SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
 		return 1;
 	}
-	return 0; /* Can't get here */
+	if (ste->ste_nested)
+		ste->ste_free = 1;
+	SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
+	return 1;
 }
 
 #undef SET_SCOPE
@@ -433,38 +468,44 @@
 
    Note that the current block's free variables are included in free.
    That's safe because no name can be free and local in the same scope.
+
+   The 'restrict' argument may be set to a string to restrict the analysis
+   to the one variable whose name equals that string (e.g. "__class__").
 */
 
 static int
-analyze_cells(PyObject *scope, PyObject *free)
+analyze_cells(PyObject *scopes, PyObject *free, const char *restrict)
 {
-        PyObject *name, *v, *w;
+        PyObject *name, *v, *v_cell;
 	int success = 0;
 	Py_ssize_t pos = 0;
 
-	w = PyInt_FromLong(CELL);
-	if (!w)
+	v_cell = PyInt_FromLong(CELL);
+	if (!v_cell)
 		return 0;
-	while (PyDict_Next(scope, &pos, &name, &v)) {
-		long flags;
+	while (PyDict_Next(scopes, &pos, &name, &v)) {
+		long scope;
 		assert(PyInt_Check(v));
-		flags = PyInt_AS_LONG(v);
-		if (flags != LOCAL)
+		scope = PyInt_AS_LONG(v);
+		if (scope != LOCAL)
+			continue;
+		if (!PySet_Contains(free, name))
 			continue;
-		if (!PyDict_GetItem(free, name))
+		if (restrict != NULL &&
+		    strcmp(PyString_AS_STRING(name), restrict))
 			continue;
 		/* Replace LOCAL with CELL for this name, and remove
 		   from free. It is safe to replace the value of name 
 		   in the dict, because it will not cause a resize.
 		 */
-		if (PyDict_SetItem(scope, name, w) < 0)
+		if (PyDict_SetItem(scopes, name, v_cell) < 0)
 			goto error;
-		if (!PyDict_DelItem(free, name) < 0)
+		if (PySet_Discard(free, name) < 0)
 			goto error;
 	}
 	success = 1;
  error:
-	Py_DECREF(w);
+	Py_DECREF(v_cell);
 	return success;
 }
 
@@ -499,77 +540,91 @@
 	return 0;
 }
 
-/* Enter the final scope information into the st_symbols dict. 
+/* Enter the final scope information into the ste_symbols dict. 
  * 
  * All arguments are dicts.  Modifies symbols, others are read-only.
 */
 static int
-update_symbols(PyObject *symbols, PyObject *scope, 
+update_symbols(PyObject *symbols, PyObject *scopes, 
                PyObject *bound, PyObject *free, int classflag)
 {
-	PyObject *name, *v, *u, *w, *free_value = NULL;
+	PyObject *name = NULL, *itr = NULL;
+	PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
 	Py_ssize_t pos = 0;
 
+	/* Update scope information for all symbols in this scope */
 	while (PyDict_Next(symbols, &pos, &name, &v)) {
-		long i, flags;
+		long scope, flags;
 		assert(PyInt_Check(v));
 		flags = PyInt_AS_LONG(v);
-		w = PyDict_GetItem(scope, name);
-		assert(w && PyInt_Check(w));
-		i = PyInt_AS_LONG(w);
-		flags |= (i << SCOPE_OFF);
-		u = PyInt_FromLong(flags);
-		if (!u)
+		v_scope = PyDict_GetItem(scopes, name);
+		assert(v_scope && PyInt_Check(v_scope));
+		scope = PyInt_AS_LONG(v_scope);
+		flags |= (scope << SCOPE_OFFSET);
+		v_new = PyInt_FromLong(flags);
+		if (!v_new)
 			return 0;
-		if (PyDict_SetItem(symbols, name, u) < 0) {
-			Py_DECREF(u);
+		if (PyDict_SetItem(symbols, name, v_new) < 0) {
+			Py_DECREF(v_new);
 			return 0;
 		}
-		Py_DECREF(u);
+		Py_DECREF(v_new);
 	}
 
-        free_value = PyInt_FromLong(FREE << SCOPE_OFF);
-        if (!free_value)
+	/* Record not yet resolved free variables from children (if any) */
+        v_free = PyInt_FromLong(FREE << SCOPE_OFFSET);
+        if (!v_free)
 		return 0;
 
-        /* add a free variable when it's only use is for creating a closure */
-        pos = 0;
-	while (PyDict_Next(free, &pos, &name, &v)) {
-		PyObject *o = PyDict_GetItem(symbols, name);
+	itr = PyObject_GetIter(free);
+	if (!itr)
+		goto error;
+
+	while ((name = PyIter_Next(itr))) {
+		v = PyDict_GetItem(symbols, name);
 
-		if (o) {
-			/* It could be a free variable in a method of
+		/* Handle symbol that already exists in this scope */
+		if (v) {
+			/* Handle a free variable in a method of
 			   the class that has the same name as a local
 			   or global in the class scope.
 			*/
 			if  (classflag && 
-			     PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
-				long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
-				o = PyInt_FromLong(i);
-				if (!o) {
-					Py_DECREF(free_value);
-					return 0;
+			     PyInt_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) {
+				long flags = PyInt_AS_LONG(v) | DEF_FREE_CLASS;
+				v_new = PyInt_FromLong(flags);
+				if (!v_new) {
+					goto error;
 				}
-				if (PyDict_SetItem(symbols, name, o) < 0) {
-					Py_DECREF(o);
-					Py_DECREF(free_value);
-					return 0;
+				if (PyDict_SetItem(symbols, name, v_new) < 0) {
+					Py_DECREF(v_new);
+					goto error;
 				}
-				Py_DECREF(o);
+				Py_DECREF(v_new);
 			}
-			/* else it's not free, probably a cell */
+			/* It's a cell, or already free in this scope */
+			Py_DECREF(name);
 			continue;
 		}
-		if (!PyDict_GetItem(bound, name))
+		/* Handle global symbol */
+		if (!PySet_Contains(bound, name)) {
+			Py_DECREF(name);
 			continue;       /* it's a global */
-
-		if (PyDict_SetItem(symbols, name, free_value) < 0) {
-			Py_DECREF(free_value);
-			return 0;
 		}
+		/* Propagate new free symbol up the lexical stack */
+		if (PyDict_SetItem(symbols, name, v_free) < 0) {
+			goto error;
+		}
+		Py_DECREF(name);
         }
-        Py_DECREF(free_value);
+	Py_DECREF(itr);
+        Py_DECREF(v_free);
 	return 1;
+error:
+	Py_XDECREF(v_free);
+	Py_XDECREF(itr);
+	Py_XDECREF(name);
+	return 0;
 }   
 
 /* Make final symbol table decisions for block of ste.
@@ -584,58 +639,80 @@
 analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, 
 	      PyObject *global)
 {
-	PyObject *name, *v, *local = NULL, *scope = NULL, *newbound = NULL;
+	PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
 	PyObject *newglobal = NULL, *newfree = NULL;
 	int i, success = 0;
 	Py_ssize_t pos = 0;
 
-	local = PyDict_New();
-	if (!local)
+	scopes = PyDict_New();
+	if (!scopes)
 		goto error;
-	scope = PyDict_New();
-	if (!scope)
+	local = PySet_New(NULL);
+	if (!local)
 		goto error;
-	newglobal = PyDict_New();
+	newglobal = PySet_New(NULL);
 	if (!newglobal)
 		goto error;
-	newfree = PyDict_New();
+	newfree = PySet_New(NULL);
 	if (!newfree)
 		goto error;
-	newbound = PyDict_New();
+	newbound = PySet_New(NULL);
 	if (!newbound)
 		goto error;
 
+	/* Class namespace has no effect on names visible in
+	   nested functions, so populate the global and bound
+	   sets to be passed to child blocks before analyzing
+	   this one.
+	 */
 	if (ste->ste_type == ClassBlock) {
-		/* make a copy of globals before calling analyze_name(),
-		   because global statements in the class have no effect
-		   on nested functions.
-		*/
-		if (PyDict_Update(newglobal, global) < 0)
-			goto error;
-		if (bound)
-			if (PyDict_Update(newbound, bound) < 0)
+		/* Pass down previously bound symbols */
+		if (bound) {
+			if (!PyNumber_InPlaceOr(newbound, bound))
 				goto error;
+			Py_DECREF(newbound);
+		}
+		/* Pass down known globals */
+		if (!PyNumber_InPlaceOr(newglobal, global))
+			goto error;
+		Py_DECREF(newglobal);
 	}
 
+	/* Analyze symbols in current scope */
 	assert(PySTEntry_Check(ste));
 	assert(PyDict_Check(ste->ste_symbols));
 	while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
 		long flags = PyInt_AS_LONG(v);
-		if (!analyze_name(ste, scope, name, flags, bound, local, free,
+		if (!analyze_name(ste, scopes, name, flags, bound, local, free,
 				  global))
 			goto error;
 	}
 
+	/* Populate global and bound sets to be passed to children. */
 	if (ste->ste_type != ClassBlock) {
+		/* Add function locals to bound set */
 		if (ste->ste_type == FunctionBlock) {
-			if (PyDict_Update(newbound, local) < 0)
+			if (!PyNumber_InPlaceOr(newbound, local))
 				goto error;
+			Py_DECREF(newbound);
 		}
+		/* Pass down previously bound symbols */
 		if (bound) {
-			if (PyDict_Update(newbound, bound) < 0)
+			if (!PyNumber_InPlaceOr(newbound, bound))
 				goto error;
+			Py_DECREF(newbound);
 		}
-		if (PyDict_Update(newglobal, global) < 0)
+		/* Pass down known globals */
+		if (!PyNumber_InPlaceOr(newglobal, global))
+			goto error;
+		Py_DECREF(newglobal);
+	}
+	else {
+		/* Special-case __class__ */
+		if (!GET_IDENTIFIER(__class__))
+			goto error;
+		assert(PySet_Contains(local, __class__) == 1);
+		if (PySet_Add(newbound, __class__) < 0)
 			goto error;
 	}
 
@@ -647,24 +724,32 @@
 		entry = (PySTEntryObject*)c;
 		if (!analyze_block(entry, newbound, newfree, newglobal))
 			goto error;
+		/* Check if any children have free variables */
 		if (entry->ste_free || entry->ste_child_free)
 			ste->ste_child_free = 1;
 	}
 
-	if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
+	/* Check if any local variables must be converted to cell variables */
+	if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree,
+							     NULL))
+		goto error;
+        else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree,
+							       "__class__"))
 		goto error;
-	if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
+	/* Records the results of the analysis in the symbol table entry */
+	if (!update_symbols(ste->ste_symbols, scopes, bound, newfree,
 			    ste->ste_type == ClassBlock))
 		goto error;
 	if (!check_unoptimized(ste))
 		goto error;
 
-	if (PyDict_Update(free, newfree) < 0)
+	if (!PyNumber_InPlaceOr(free, newfree))
 		goto error;
+	Py_DECREF(free);
 	success = 1;
  error:
+	Py_XDECREF(scopes);
 	Py_XDECREF(local);
-	Py_XDECREF(scope);
 	Py_XDECREF(newbound);
 	Py_XDECREF(newglobal);
 	Py_XDECREF(newfree);
@@ -679,10 +764,10 @@
 	PyObject *free, *global;
 	int r;
 
-	free = PyDict_New();
+	free = PySet_New(NULL);
 	if (!free)
 	    return 0;
-	global = PyDict_New();
+	global = PySet_New(NULL);
 	if (!global) {
 	    Py_DECREF(free);
 	    return 0;
@@ -782,6 +867,7 @@
 	long val;
 	PyObject *mangled = _Py_Mangle(st->st_private, name);
 
+
 	if (!mangled)
 		return 0;
 	dict = st->st_cur->ste_symbols;
@@ -940,8 +1026,8 @@
 					   s->v.FunctionDef.args->kw_defaults);
 		if (!symtable_visit_annotations(st, s))
 			return 0;
-		if (s->v.FunctionDef.decorators)
-			VISIT_SEQ(st, expr, s->v.FunctionDef.decorators);
+		if (s->v.FunctionDef.decorator_list)
+			VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
 		if (!symtable_enter_block(st, s->v.FunctionDef.name, 
 					  FunctionBlock, (void *)s, s->lineno))
 			return 0;
@@ -955,9 +1041,21 @@
 		if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL))
 			return 0;
 		VISIT_SEQ(st, expr, s->v.ClassDef.bases);
+		VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
+		if (s->v.ClassDef.starargs)
+			VISIT(st, expr, s->v.ClassDef.starargs);
+		if (s->v.ClassDef.kwargs)
+			VISIT(st, expr, s->v.ClassDef.kwargs);
+		if (s->v.ClassDef.decorator_list)
+			VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
 		if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, 
 					  (void *)s, s->lineno))
 			return 0;
+		if (!GET_IDENTIFIER(__class__) ||
+		    !symtable_add_def(st, __class__, DEF_LOCAL)) {
+			symtable_exit_block(st, s);
+			return 0;
+		}
 		tmp = st->st_private;
 		st->st_private = s->v.ClassDef.name;
 		VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s);
@@ -1075,6 +1173,33 @@
 		}
 		break;
 	}
+        case Nonlocal_kind: {
+		int i;
+		asdl_seq *seq = s->v.Nonlocal.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);
+			long cur = symtable_lookup(st, name);
+			if (cur < 0)
+				return 0;
+			if (cur & (DEF_LOCAL | USE)) {
+				char buf[256];
+				if (cur & DEF_LOCAL) 
+					PyOS_snprintf(buf, sizeof(buf),
+						      NONLOCAL_AFTER_ASSIGN,
+						      c_name);
+				else
+					PyOS_snprintf(buf, sizeof(buf),
+						      NONLOCAL_AFTER_USE,
+						      c_name);
+				if (!symtable_warn(st, buf, s->lineno))
+                                    return 0;
+			}
+			if (!symtable_add_def(st, name, DEF_NONLOCAL))
+				return 0;
+		}
+		break;
+	}
         case Expr_kind:
 		VISIT(st, expr, s->v.Expr.value);
 		break;
@@ -1140,14 +1265,16 @@
 	case Set_kind:
 		VISIT_SEQ(st, expr, e->v.Set.elts);
 		break;
+        case GeneratorExp_kind:
+		if (!symtable_visit_genexp(st, e))
+			return 0;
+		break;
         case ListComp_kind:
-		if (!symtable_new_tmpname(st))
+		if (!symtable_visit_listcomp(st, e))
 			return 0;
-		VISIT(st, expr, e->v.ListComp.elt);
-		VISIT_SEQ(st, comprehension, e->v.ListComp.generators);
 		break;
-        case GeneratorExp_kind:
-		if (!symtable_visit_genexp(st, e))
+	case SetComp_kind:
+		if (!symtable_visit_setcomp(st, e))
 			return 0;
 		break;
         case Yield_kind:
@@ -1177,7 +1304,8 @@
 		break;
         case Num_kind:
         case Str_kind:
-	case Ellipsis_kind:
+        case Bytes_kind:
+        case Ellipsis_kind:
 		/* Nothing to do here. */
 		break;
 	/* The following exprs can be assignment targets. */
@@ -1188,10 +1316,21 @@
 		VISIT(st, expr, e->v.Subscript.value);
 		VISIT(st, slice, e->v.Subscript.slice);
 		break;
+        case Starred_kind:
+		VISIT(st, expr, e->v.Starred.value);
+		break;
         case Name_kind:
 		if (!symtable_add_def(st, e->v.Name.id, 
 				      e->v.Name.ctx == Load ? USE : DEF_LOCAL))
 			return 0;
+		/* Special-case super: it counts as a use of __class__ */
+                if (e->v.Name.ctx == Load &&
+		    st->st_cur->ste_type == FunctionBlock &&
+		    !strcmp(PyString_AS_STRING(e->v.Name.id), "super")) {
+			if (!GET_IDENTIFIER(__class__) ||
+			    !symtable_add_def(st, __class__, USE))
+				return 0;
+                }
 		break;
 	/* child nodes of List and Tuple will have expr_context set */
         case List_kind:
@@ -1219,79 +1358,51 @@
 }
 
 static int 
-symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel,
-                      int annotations)
+symtable_visit_params(struct symtable *st, asdl_seq *args)
 {
 	int i;
 
 	if (!args)
 		return -1;
 	
-        /* go through all the toplevel arguments first */
 	for (i = 0; i < asdl_seq_LEN(args); i++) {
 		arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
-		if (arg->kind == SimpleArg_kind) {
-			if (!annotations) {
-				if (!symtable_add_def(st,
-				                      arg->v.SimpleArg.arg,
-				                      DEF_PARAM))
-					return 0;
-			}
-			else if (arg->v.SimpleArg.annotation)
-				VISIT(st, expr, arg->v.SimpleArg.annotation);
-		}
-		else if (arg->kind == NestedArgs_kind) {
-			if (toplevel && !annotations) {
-				if (!symtable_implicit_arg(st, i))
-					return 0;
-			}
-		}
-		else {
-		        PyErr_SetString(PyExc_SyntaxError,
-					"invalid expression in parameter list");
-		        PyErr_SyntaxLocation(st->st_filename,
-				             st->st_cur->ste_lineno);
-			return 0;
-		}
-	}
-
-	if (!toplevel) {
-		if (!symtable_visit_params_nested(st, args, annotations))
+		if (!symtable_add_def(st, arg->arg, DEF_PARAM))
 			return 0;
 	}
 
 	return 1;
 }
 
-static int
-symtable_visit_params_nested(struct symtable *st, asdl_seq *args,
-                             int annotations)
+static int 
+symtable_visit_argannotations(struct symtable *st, asdl_seq *args)
 {
 	int i;
+
+	if (!args)
+		return -1;
+	
 	for (i = 0; i < asdl_seq_LEN(args); i++) {
 		arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
-		if (arg->kind == NestedArgs_kind &&
-		    !symtable_visit_params(st, arg->v.NestedArgs.args, 0,
-		                           annotations))
-			return 0;
+		if (arg->annotation)
+			VISIT(st, expr, arg->annotation);
 	}
 
 	return 1;
 }
 
-
 static int
 symtable_visit_annotations(struct symtable *st, stmt_ty s)
 {
 	arguments_ty a = s->v.FunctionDef.args;
 	
-	if (a->args && !symtable_visit_params(st, a->args, 1, 1))
+	if (a->args && !symtable_visit_argannotations(st, a->args))
 		return 0;
 	if (a->varargannotation)
 		VISIT(st, expr, a->varargannotation);
 	if (a->kwargannotation)
 		VISIT(st, expr, a->kwargannotation);
-	if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs, 1, 1))
+	if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
 		return 0;
 	if (s->v.FunctionDef.returns)
 		VISIT(st, expr, s->v.FunctionDef.returns);
@@ -1304,9 +1415,9 @@
 	/* skip default arguments inside function block
 	   XXX should ast be different?
 	*/
-	if (a->args && !symtable_visit_params(st, a->args, 1, 0))
+	if (a->args && !symtable_visit_params(st, a->args))
 		return 0;
-	if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs, 1, 0))
+	if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
 		return 0;
 	if (a->vararg) {
 		if (!symtable_add_def(st, a->vararg, DEF_PARAM))
@@ -1318,8 +1429,6 @@
 			return 0;
 		st->st_cur->ste_varkeywords = 1;
 	}
-	if (a->args && !symtable_visit_params_nested(st, a->args, 0))
-		return 0;
 	return 1;
 }
 
@@ -1418,27 +1527,60 @@
 }
 
 static int 
-symtable_visit_genexp(struct symtable *st, expr_ty e)
+symtable_handle_comprehension(struct symtable *st, expr_ty e,
+                              identifier scope_name,
+                              asdl_seq *generators, expr_ty elt)
 {
+	int is_generator = (e->kind == GeneratorExp_kind);
+	int needs_tmp = !is_generator;
 	comprehension_ty outermost = ((comprehension_ty)
-			 (asdl_seq_GET(e->v.GeneratorExp.generators, 0)));
+                                        asdl_seq_GET(generators, 0));
 	/* Outermost iterator is evaluated in current scope */
 	VISIT(st, expr, outermost->iter);
-	/* Create generator scope for the rest */
-	if (!GET_IDENTIFIER(genexpr) ||
-	    !symtable_enter_block(st, genexpr, FunctionBlock, (void *)e, 0)) {
+	/* Create comprehension scope for the rest */
+	if (!scope_name ||
+	    !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, 0)) {
 		return 0;
 	}
-	st->st_cur->ste_generator = 1;
+	st->st_cur->ste_generator = is_generator;
 	/* Outermost iter is received as an argument */
 	if (!symtable_implicit_arg(st, 0)) {
 		symtable_exit_block(st, (void *)e);
 		return 0;
 	}
+	/* Allocate temporary name if needed */
+	if (needs_tmp && !symtable_new_tmpname(st)) {
+		symtable_exit_block(st, (void *)e);
+		return 0;
+	}
 	VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e);
 	VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e);
 	VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension,
-				e->v.GeneratorExp.generators, 1, (void*)e);
-	VISIT_IN_BLOCK(st, expr, e->v.GeneratorExp.elt, (void*)e);
+				generators, 1, (void*)e);
+	VISIT_IN_BLOCK(st, expr, elt, (void*)e);
 	return symtable_exit_block(st, (void *)e);
 }
+
+static int 
+symtable_visit_genexp(struct symtable *st, expr_ty e)
+{
+	return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr),
+                                             e->v.GeneratorExp.generators,
+                                             e->v.GeneratorExp.elt);
+}
+
+static int 
+symtable_visit_listcomp(struct symtable *st, expr_ty e)
+{
+	return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp),
+                                             e->v.ListComp.generators,
+                                             e->v.ListComp.elt);
+}
+
+static int
+symtable_visit_setcomp(struct symtable *st, expr_ty e)
+{
+	return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp),
+					     e->v.SetComp.generators,
+					     e->v.SetComp.elt);
+}

Modified: python/branches/p3yk-noslice/Python/sysmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Python/sysmodule.c	(original)
+++ python/branches/p3yk-noslice/Python/sysmodule.c	Wed Jul 11 15:40:56 2007
@@ -163,33 +163,6 @@
 );
 
 static PyObject *
-sys_exc_clear(PyObject *self, PyObject *noargs)
-{
-	PyThreadState *tstate = PyThreadState_GET();
-	PyObject *tmp_type, *tmp_value, *tmp_tb;
-	tmp_type = tstate->exc_type;
-	tmp_value = tstate->exc_value;
-	tmp_tb = tstate->exc_traceback;
-	tstate->exc_type = NULL;
-	tstate->exc_value = NULL;
-	tstate->exc_traceback = NULL;
-	Py_XDECREF(tmp_type);
-	Py_XDECREF(tmp_value);
-	Py_XDECREF(tmp_tb);
-	Py_INCREF(Py_None);
-	return Py_None;
-}
-
-PyDoc_STRVAR(exc_clear_doc,
-"exc_clear() -> None\n\
-\n\
-Clear global information on the current exception.  Subsequent calls to\n\
-exc_info() will return (None,None,None) until another exception is raised\n\
-in the current thread or the execution stack returns to a frame where\n\
-another exception is being handled."
-);
-
-static PyObject *
 sys_exit(PyObject *self, PyObject *args)
 {
 	PyObject *exit_code = 0;
@@ -760,7 +733,6 @@
 	 current_frames_doc},
 	{"displayhook",	sys_displayhook, METH_O, displayhook_doc},
 	{"exc_info",	sys_exc_info, METH_NOARGS, exc_info_doc},
-	{"exc_clear",	sys_exc_clear, METH_NOARGS, exc_clear_doc},
 	{"excepthook",	sys_excepthook, METH_VARARGS, excepthook_doc},
 	{"exit",	sys_exit, METH_VARARGS, exit_doc},
 #ifdef Py_USING_UNICODE
@@ -897,9 +869,6 @@
   To customize printing in an interactive session or to install a custom\n\
   top-level exception handler, assign other functions to replace these.\n\
 \n\
-exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
-  Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
-\n\
 stdin -- standard input file object; used by raw_input() and input()\n\
 stdout -- standard output file object; used by print()\n\
 stderr -- standard error object; used for error messages\n\
@@ -911,12 +880,6 @@
 last_traceback -- traceback of last uncaught exception\n\
   These three are only available in an interactive session after a\n\
   traceback has been printed.\n\
-\n\
-exc_type -- type of exception currently being handled\n\
-exc_value -- value of exception currently being handled\n\
-exc_traceback -- traceback of exception currently being handled\n\
-  The function exc_info() should be used instead of these three,\n\
-  because it is thread-safe.\n\
 "
 )
 /* concatenating string here */
@@ -957,7 +920,6 @@
 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
 excepthook() -- print an exception and its traceback to sys.stderr\n\
 exc_info() -- return thread-safe information about the current exception\n\
-exc_clear() -- clear the exception state for the current thread\n\
 exit() -- exit the interpreter by raising SystemExit\n\
 getdlopenflags() -- returns flags to be used for dlopen() calls\n\
 getrefcount() -- return the reference count for an object (plus one :-)\n\
@@ -1017,8 +979,6 @@
 	}
 	else if (istag || strncmp(br_start, "branches", 8) == 0) {
 		len = br_end2 - br_start;
-		assert(len >= 13);
-		assert(len < (sizeof(patchlevel_revision) - 13));
 		strncpy(branch, br_start, len);
 		branch[len] = '\0';
 
@@ -1037,6 +997,8 @@
 		svn_revision = svnversion;
 	else if (istag) {
 		len = strlen(_patchlevel_revision);
+		assert(len >= 13);
+		assert(len < (sizeof(patchlevel_revision) + 13));
 		strncpy(patchlevel_revision, _patchlevel_revision + 11,
 			len - 13);
 		patchlevel_revision[len - 13] = '\0';

Modified: python/branches/p3yk-noslice/Python/thread_nt.h
==============================================================================
--- python/branches/p3yk-noslice/Python/thread_nt.h	(original)
+++ python/branches/p3yk-noslice/Python/thread_nt.h	Wed Jul 11 15:40:56 2007
@@ -15,72 +15,16 @@
 	HANDLE hevent ;
 } NRMUTEX, *PNRMUTEX ;
 
-typedef PVOID WINAPI interlocked_cmp_xchg_t(PVOID *dest, PVOID exc, PVOID comperand) ;
-
-/* Sorry mate, but we haven't got InterlockedCompareExchange in Win95! */
-static PVOID WINAPI
-interlocked_cmp_xchg(PVOID *dest, PVOID exc, PVOID comperand)
-{
-	static LONG spinlock = 0 ;
-	PVOID result ;
-	DWORD dwSleep = 0;
-
-	/* Acqire spinlock (yielding control to other threads if cant aquire for the moment) */
-	while(InterlockedExchange(&spinlock, 1))
-	{
-		// Using Sleep(0) can cause a priority inversion.
-		// Sleep(0) only yields the processor if there's
-		// another thread of the same priority that's
-		// ready to run.  If a high-priority thread is
-		// trying to acquire the lock, which is held by
-		// a low-priority thread, then the low-priority
-		// thread may never get scheduled and hence never
-		// free the lock.  NT attempts to avoid priority
-		// inversions by temporarily boosting the priority
-		// of low-priority runnable threads, but the problem
-		// can still occur if there's a medium-priority
-		// thread that's always runnable.  If Sleep(1) is used,
-		// then the thread unconditionally yields the CPU.  We
-		// only do this for the second and subsequent even
-		// iterations, since a millisecond is a long time to wait
-		// if the thread can be scheduled in again sooner
-		// (~100,000 instructions).
-		// Avoid priority inversion: 0, 1, 0, 1,...
-		Sleep(dwSleep);
-		dwSleep = !dwSleep;
-	}
-	result = *dest ;
-	if (result == comperand)
-		*dest = exc ;
-	/* Release spinlock */
-	spinlock = 0 ;
-	return result ;
-} ;
-
-static interlocked_cmp_xchg_t *ixchg;
 
 BOOL
 InitializeNonRecursiveMutex(PNRMUTEX mutex)
 {
-	if (!ixchg)
-	{
-		/* Sorely, Win95 has no InterlockedCompareExchange API (Win98 has), so we have to use emulation */
-		HANDLE kernel = GetModuleHandle("kernel32.dll") ;
-		if (!kernel || (ixchg = (interlocked_cmp_xchg_t *)GetProcAddress(kernel, "InterlockedCompareExchange")) == NULL)
-			ixchg = interlocked_cmp_xchg ;
-	}
-
 	mutex->owned = -1 ;  /* No threads have entered NonRecursiveMutex */
 	mutex->thread_id = 0 ;
 	mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ;
 	return mutex->hevent != NULL ;	/* TRUE if the mutex is created */
 }
 
-#ifdef InterlockedCompareExchange
-#undef InterlockedCompareExchange
-#endif
-#define InterlockedCompareExchange(dest,exchange,comperand) (ixchg((dest), (exchange), (comperand)))
-
 VOID
 DeleteNonRecursiveMutex(PNRMUTEX mutex)
 {
@@ -98,7 +42,7 @@
 	/* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */
 	if (!wait)
 	{
-		if (InterlockedCompareExchange((PVOID *)&mutex->owned, (PVOID)0, (PVOID)-1) != (PVOID)-1)
+		if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1)
 			return WAIT_TIMEOUT ;
 		ret = WAIT_OBJECT_0 ;
 	}
@@ -196,18 +140,21 @@
 	if (obj.done == NULL)
 		return -1;
 
-	rv = _beginthread(bootstrap, _pythread_stacksize, &obj);
+	rv = _beginthread(bootstrap,
+			  Py_SAFE_DOWNCAST(_pythread_stacksize,
+					   Py_ssize_t, int),
+			  &obj);
 	if (rv == (Py_uintptr_t)-1) {
 		/* I've seen errno == EAGAIN here, which means "there are
 		 * too many threads".
 		 */
 		dprintf(("%ld: PyThread_start_new_thread failed: %p errno %d\n",
-		         PyThread_get_thread_ident(), rv, errno));
+		         PyThread_get_thread_ident(), (void*)rv, errno));
 		obj.id = -1;
 	}
 	else {
 		dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n",
-		         PyThread_get_thread_ident(), rv));
+		         PyThread_get_thread_ident(), (void*)rv));
 		/* wait for thread to initialize, so we can get its id */
 		WaitForSingleObject(obj.done, INFINITE);
 		assert(obj.id != -1);
@@ -333,7 +280,7 @@
 	dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
 
 	if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock)))
-		dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError()));
+		dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError()));
 }
 
 /* minimum/maximum thread stack sizes supported */

Modified: python/branches/p3yk-noslice/README
==============================================================================
--- python/branches/p3yk-noslice/README	(original)
+++ python/branches/p3yk-noslice/README	Wed Jul 11 15:40:56 2007
@@ -290,19 +290,9 @@
 submit a documentation bug report to SourceForge (see Bug Reports
 above) so we can remove them!)
 
-Unix platforms: If your vendor still ships (and you still use) Berkeley DB
-        1.85 you will need to edit Modules/Setup to build the bsddb185
-        module and add a line to sitecustomize.py which makes it the
-        default.  In Modules/Setup a line like
-
-            bsddb185 bsddbmodule.c
-
-        should work.  (You may need to add -I, -L or -l flags to direct the
-        compiler and linker to your include files and libraries.)
-
 XXX I think this next bit is out of date:
 
-64-bit platforms: The modules audioop, imageop and rgbimg don't work.
+64-bit platforms: The audioop module doesn't work.
         The setup.py script disables them on 64-bit installations.
         Don't try to enable them in the Modules/Setup file.  They
         contain code that is quite wordsize sensitive.  (If you have a
@@ -472,11 +462,11 @@
            your system... tested here at QNX with the following modules:
 
                 array, audioop, binascii, cPickle, cStringIO, cmath,
-                crypt, curses, errno, fcntl, gdbm, grp, imageop,
-                _locale, math, md5, new, operator, parser, pcre,
-                posix, pwd, readline, regex, reop, rgbimg, rotor,
-                select, signal, socket, soundex, strop, struct,
-                syslog, termios, time, timing, zlib, audioop, imageop, rgbimg
+                crypt, curses, errno, fcntl, gdbm, grp,
+                _locale, math, new, operator, parser,
+                posix, pwd, readline, regex,
+                select, signal, socket, struct,
+                syslog, termios, time, zlib, audioop
 
         3) make SHELL=/usr/local/bin/bash
 
@@ -530,9 +520,8 @@
 
 	     _codecs, _locale, _socket, _symtable, _testcapi, _weakref
 	     array, binascii, cmath, cPickle, crypt, cStringIO, dbm
-	     errno, fcntl, grp, math, md5, operator, parser, pwd
-	     rotor, select, struct, strop, syslog, termios,
-	     time, timing
+	     errno, fcntl, grp, math, operator, parser, pwd
+	     rotor, select, struct, syslog, termios, time
 
         4) Once the python executable and library have been built, make
            will execute setup.py, which will attempt to build remaining
@@ -578,9 +567,9 @@
 MacOSX: The tests will crash on both 10.1 and 10.2 with SEGV in
         test_re and test_sre due to the small default stack size.  If
         you set the stack size to 2048 before doing a "make test" the
-        failure can be avoided.  If you're using the tcsh (the default
-        on OSX), or csh shells use "limit stacksize 2048" and for the
-        bash shell, use "ulimit -s 2048".
+        failure can be avoided.  If you're using the tcsh or csh shells,
+        use "limit stacksize 2048" and for the bash shell (the default
+        as of OSX 10.3), use "ulimit -s 2048".
 
         On naked Darwin you may want to add the configure option
         "--disable-toolbox-glue" to disable the glue code for the Carbon
@@ -677,7 +666,11 @@
         News regarding these platforms with more recent Cygwin
         versions would be appreciated!
 
-AtheOS: From Octavian Cerna <tavy at ylabs.com>:
+AtheOS: Official support has been stopped as of Python 2.6.  All code will be
+        removed in Python 2.7 unless a maintainer steps forward for this
+        platform.
+
+        From Octavian Cerna <tavy at ylabs.com>:
 
         Before building:
 
@@ -752,9 +745,7 @@
 exposing a set of package-level functions which provide
 backwards-compatible behavior.  Only versions 3.3 through 4.4 of
 Sleepycat's libraries provide the necessary API, so older versions
-aren't supported through this interface.  The old bsddb module has
-been retained as bsddb185, though it is not built by default.  Users
-wishing to use it will have to tweak Modules/Setup to build it.  The
+aren't supported through this interface.  The
 dbm module will still be built against the Sleepycat libraries if
 other preferred alternatives (ndbm, gdbm) are not found.
 
@@ -872,10 +863,6 @@
 errors, disable it -- you're either missing support or need to adjust
 the compilation and linking parameters for that module.
 
-On SGI IRIX, there are modules that interface to many SGI specific
-system libraries, e.g. the GL library and the audio hardware.  These
-modules will not be built by the setup.py script.
-
 In addition to the file Setup, you can also edit the file Setup.local.
 (the makesetup script processes both).  You may find it more
 convenient to edit Setup.local and leave Setup alone.  Then, when
@@ -1245,7 +1232,6 @@
 Most subdirectories have their own README files.  Most files have
 comments.
 
-BeOS/           Files specific to the BeOS port
 Demo/           Demonstration scripts, modules and programs
 Doc/            Documentation sources (LaTeX)
 Grammar/        Input for the parser generator
@@ -1262,6 +1248,7 @@
 Parser/         The parser and tokenizer and their input handling
 Python/         The byte-compiler and interpreter
 README          The file you're reading now
+RISCOS/         Files specific to RISC OS port
 Tools/          Some useful programs written in Python
 pyconfig.h.in   Source from which pyconfig.h is created (GNU autoheader output)
 configure       Configuration shell script (GNU autoconf output)
@@ -1282,6 +1269,7 @@
 getbuildinfo.o  Object file from Modules/getbuildinfo.c
 libpython<version>.a    The library archive
 python          The executable interpreter
+reflog.txt      Output from running the regression suite with the -R flag 
 tags, TAGS      Tags files for vi and Emacs
 
 

Modified: python/branches/p3yk-noslice/RISCOS/Makefile
==============================================================================
--- python/branches/p3yk-noslice/RISCOS/Makefile	(original)
+++ python/branches/p3yk-noslice/RISCOS/Makefile	Wed Jul 11 15:40:56 2007
@@ -292,9 +292,6 @@
 @.^.Lib.signal/pyd: @.^.Modules.o.signalmodule s.linktab
 	$(MAKEDLK) -d @.^.Lib.signal/pyd -s s.linktab -o @.^.Modules.o.signalmodule -e initsignal
 
- at .^.Lib.strop/pyd: @.^.Modules.o.stropmodule s.linktab
-	$(MAKEDLK) -d @.^.Lib.strop/pyd -s s.linktab -o @.^.Modules.o.stropmodule -e initstrop
-
 @.^.Lib.struct/pyd: @.^.Modules.o.structmodule s.linktab
 	$(MAKEDLK) -d @.^.Lib.struct/pyd -s s.linktab -o @.^.Modules.o.structmodule -e initstruct
 

Modified: python/branches/p3yk-noslice/RISCOS/Modules/config.c
==============================================================================
--- python/branches/p3yk-noslice/RISCOS/Modules/config.c	(original)
+++ python/branches/p3yk-noslice/RISCOS/Modules/config.c	Wed Jul 11 15:40:56 2007
@@ -63,7 +63,6 @@
 	{"__main__", NULL},
 	{"__builtin__", NULL},
 	{"sys", NULL},
-	{"exceptions", NULL},
 
 	/* This lives in gcmodule.c */
 	{"gc", initgc},

Modified: python/branches/p3yk-noslice/Tools/i18n/msgfmt.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/i18n/msgfmt.py	(original)
+++ python/branches/p3yk-noslice/Tools/i18n/msgfmt.py	Wed Jul 11 15:40:56 2007
@@ -83,7 +83,7 @@
         voffsets += [l2, o2+valuestart]
     offsets = koffsets + voffsets
     output = struct.pack("Iiiiiii",
-                         0x950412deL,       # Magic
+                         0x950412de,       # Magic
                          0,                 # Version
                          len(keys),         # # of entries
                          7*4,               # start of key index

Modified: python/branches/p3yk-noslice/Tools/msi/msilib.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/msi/msilib.py	(original)
+++ python/branches/p3yk-noslice/Tools/msi/msilib.py	Wed Jul 11 15:40:56 2007
@@ -5,7 +5,7 @@
 import win32com.client
 import pythoncom, pywintypes
 from win32com.client import constants
-import re, string, os, sets, glob, popen2, sys, _winreg, struct
+import re, string, os, sets, glob, subprocess, sys, _winreg, struct
 
 try:
     basestring
@@ -388,8 +388,10 @@
         else:
             print "WARNING: cabarc.exe not found in registry"
             cabarc = "cabarc.exe"
-        f = popen2.popen4(r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name))[0]
-        for line in f:
+        cmd = r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name)
+        p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)[0]
+        for line in (p.stdout, p.stdin):
             if line.startswith("  -- adding "):
                 sys.stdout.write(".")
             else:

Modified: python/branches/p3yk-noslice/Tools/pybench/Arithmetic.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Arithmetic.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Arithmetic.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2
             b = 3
@@ -152,7 +152,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleFloatArithmetic(Test):
@@ -163,7 +163,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2.1
             b = 3.3332
@@ -307,7 +307,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleIntFloatArithmetic(Test):
@@ -318,7 +318,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2
             b = 3
@@ -462,7 +462,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -474,11 +474,11 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
-            a = 2220001L
-            b = 100001L
-            c = 30005L
+            a = 2220001
+            b = 100001
+            c = 30005
 
             c = a + b
             c = b + c
@@ -504,9 +504,9 @@
             c = b / a
             c = c / b
 
-            a = 2220001L
-            b = 100001L
-            c = 30005L
+            a = 2220001
+            b = 100001
+            c = 30005
 
             c = a + b
             c = b + c
@@ -532,9 +532,9 @@
             c = b / a
             c = c / b
 
-            a = 2220001L
-            b = 100001L
-            c = 30005L
+            a = 2220001
+            b = 100001
+            c = 30005
 
             c = a + b
             c = b + c
@@ -560,9 +560,9 @@
             c = b / a
             c = c / b
 
-            a = 2220001L
-            b = 100001L
-            c = 30005L
+            a = 2220001
+            b = 100001
+            c = 30005
 
             c = a + b
             c = b + c
@@ -588,9 +588,9 @@
             c = b / a
             c = c / b
 
-            a = 2220001L
-            b = 100001L
-            c = 30005L
+            a = 2220001
+            b = 100001
+            c = 30005
 
             c = a + b
             c = b + c
@@ -618,7 +618,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleComplexArithmetic(Test):
@@ -629,7 +629,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             a = 2 + 3j
             b = 2.5 + 4.5j
@@ -773,5 +773,5 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Calls.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Calls.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Calls.py	Wed Jul 11 15:40:56 2007
@@ -24,7 +24,7 @@
             return d,e,f
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             f()
             f1(i)
@@ -104,7 +104,7 @@
             return d,e,f
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ###
@@ -124,7 +124,7 @@
         f3 = range
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             f0()
             f0()
@@ -225,7 +225,7 @@
         f3 = range
 
         # do calls
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ###
@@ -261,7 +261,7 @@
 
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             o.f()
             o.f()
@@ -367,7 +367,7 @@
 
         o = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ###
@@ -388,7 +388,7 @@
                 return f(x-1)
             return 1
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             f(10)
             f(10)
             f(10)
@@ -405,7 +405,7 @@
                 return f(x-1)
             return 1
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 

Modified: python/branches/p3yk-noslice/Tools/pybench/CommandLine.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/CommandLine.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/CommandLine.py	Wed Jul 11 15:40:56 2007
@@ -20,7 +20,7 @@
 
 __version__ = '1.2'
 
-import sys, getopt, string, glob, os, re, exceptions, traceback
+import sys, getopt, glob, os, re, traceback
 
 ### Helpers
 
@@ -44,7 +44,7 @@
                 l.append(o.name+'=')
             else:
                 l.append(o.name)
-    return string.join(s,''),l
+    return ''.join(s), l
 
 def invisible_input(prompt='>>> '):
 
@@ -82,7 +82,7 @@
         else:
             f = open(name, mode)
         if 'w' in mode:
-            os.chmod(name, 0600)
+            os.chmod(name, 0o600)
         return f
 
 def option_dict(options):
@@ -102,7 +102,7 @@
 
 def srange(s,
 
-           split=string.split,integer=_integerRE,
+           integer=_integerRE,
            integerRange=_integerRangeRE):
 
     """ Converts a textual representation of integer numbers and ranges
@@ -116,7 +116,7 @@
     """
     l = []
     append = l.append
-    for entry in split(s,','):
+    for entry in s.split(','):
         m = integer.match(entry)
         if m:
             append(int(m.groups()[0]))
@@ -293,7 +293,7 @@
     verbose = 0
 
     # Internal errors to catch
-    InternalError = exceptions.Exception
+    InternalError = BaseException
 
     # Instance variables:
     values = None       # Dictionary of passed options (or default values)
@@ -353,20 +353,20 @@
             pass
 
         except KeyboardInterrupt:
-            print
-            print '* User Break'
-            print
+            print()
+            print('* User Break')
+            print()
             rc = 1
 
         except self.InternalError:
-            print
-            print '* Internal Error (use --debug to display the traceback)'
+            print()
+            print('* Internal Error (use --debug to display the traceback)')
             if self.debug:
-                print
+                print()
                 traceback.print_exc(20, sys.stdout)
             elif self.verbose:
-                print '  %s: %s' % sys.exc_info()[:2]
-            print
+                print('  %s: %s' % sys.exc_info()[:2])
+            print()
             rc = 1
 
         raise SystemExit(rc)
@@ -449,13 +449,13 @@
 
             # Try to convert value to integer
             try:
-                value = string.atoi(value)
+                value = int(value)
             except ValueError:
                 pass
 
             # Find handler and call it (or count the number of option
             # instances on the command line)
-            handlername = 'handle' + string.replace(optionname, '-', '_')
+            handlername = 'handle' + optionname.replace('-', '_')
             try:
                 handler = getattr(self, handlername)
             except AttributeError:
@@ -494,54 +494,55 @@
 
         self.print_header()
         if self.synopsis:
-            print 'Synopsis:'
+            print('Synopsis:')
             # To remain backward compatible:
             try:
                 synopsis = self.synopsis % self.name
             except (NameError, KeyError, TypeError):
                 synopsis = self.synopsis % self.__dict__
-            print ' ' + synopsis
-        print
+            print(' ' + synopsis)
+        print()
         self.print_options()
         if self.version:
-            print 'Version:'
-            print ' %s' % self.version
-            print
+            print('Version:')
+            print(' %s' % self.version)
+            print()
         if self.about:
-            print string.strip(self.about % self.__dict__)
-            print
+            about = self.about % self.__dict__
+            print(about.strip())
+            print()
         if note:
-            print '-'*72
-            print 'Note:',note
-            print
+            print('-'*72)
+            print('Note:',note)
+            print()
 
     def notice(self,note):
 
-        print '-'*72
-        print 'Note:',note
-        print '-'*72
-        print
+        print('-'*72)
+        print('Note:',note)
+        print('-'*72)
+        print()
 
     def print_header(self):
 
-        print '-'*72
-        print self.header % self.__dict__
-        print '-'*72
-        print
+        print('-'*72)
+        print(self.header % self.__dict__)
+        print('-'*72)
+        print()
 
     def print_options(self):
 
         options = self.options
-        print 'Options and default settings:'
+        print('Options and default settings:')
         if not options:
-            print '  None'
+            print('  None')
             return
         long = filter(lambda x: x.prefix == '--', options)
         short = filter(lambda x: x.prefix == '-', options)
         items = short + long
         for o in options:
-            print ' ',o
-        print
+            print(' ',o)
+        print()
 
     #
     # Example handlers:
@@ -579,26 +580,29 @@
 
         self.debug = 1
         # We don't want to catch internal errors:
-        self.InternalError = None
+        class NoErrorToCatch(Exception): pass
+        self.InternalError = NoErrorToCatch
 
     def handle__copyright(self,arg):
 
         self.print_header()
-        print string.strip(self.copyright % self.__dict__)
-        print
+        copyright = self.copyright % self.__dict__
+        print(copyright.strip())
+        print()
         return 0
 
     def handle__examples(self,arg):
 
         self.print_header()
         if self.examples:
-            print 'Examples:'
-            print
-            print string.strip(self.examples % self.__dict__)
-            print
+            print('Examples:')
+            print()
+            examples = self.examples % self.__dict__
+            print(examples.strip())
+            print()
         else:
-            print 'No examples available.'
-            print
+            print('No examples available.')
+            print()
         return 0
 
     def main(self):
@@ -624,13 +628,13 @@
         options = [Option('-v','verbose')]
 
         def handle_v(self,arg):
-            print 'VERBOSE, Yeah !'
+            print('VERBOSE, Yeah !')
 
     cmd = MyApplication()
     if not cmd.values['-h']:
         cmd.help()
-    print 'files:',cmd.files
-    print 'Bye...'
+    print('files:',cmd.files)
+    print('Bye...')
 
 if __name__ == '__main__':
     _test()

Modified: python/branches/p3yk-noslice/Tools/pybench/Constructs.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Constructs.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Constructs.py	Wed Jul 11 15:40:56 2007
@@ -9,7 +9,7 @@
     def test(self):
 
         a,b,c = 1,2,3
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             if a == 1:
                 if b == 2:
@@ -464,7 +464,7 @@
     def calibrate(self):
 
         a,b,c = 1,2,3
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class NestedForLoops(Test):
@@ -478,7 +478,7 @@
         l1 = range(1000)
         l2 = range(10)
         l3 = range(5)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for i in l1:
                 for j in l2:
                     for k in l3:
@@ -489,7 +489,7 @@
         l1 = range(1000)
         l2 = range(10)
         l3 = range(5)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class ForLoops(Test):
@@ -501,7 +501,7 @@
     def test(self):
 
         l1 = range(100)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for i in l1:
                 pass
             for i in l1:
@@ -560,5 +560,5 @@
     def calibrate(self):
 
         l1 = range(1000)
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Dict.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Dict.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Dict.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d1 = {}
             d2 = {}
@@ -72,7 +72,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class DictWithStringKeys(Test):
@@ -85,7 +85,7 @@
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d['abc'] = 1
             d['def'] = 2
@@ -161,7 +161,7 @@
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class DictWithFloatKeys(Test):
@@ -174,7 +174,7 @@
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d[1.234] = 1
             d[2.345] = 2
@@ -250,7 +250,7 @@
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class DictWithIntegerKeys(Test):
@@ -263,7 +263,7 @@
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d[1] = 1
             d[2] = 2
@@ -339,7 +339,7 @@
 
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SimpleDictManipulation(Test):
@@ -353,7 +353,7 @@
         d = {}
         has_key = lambda key: key in d
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             d[0] = 3
             d[1] = 4
@@ -500,5 +500,5 @@
         d = {}
         has_key = lambda key: key in d
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Exceptions.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Exceptions.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Exceptions.py	Wed Jul 11 15:40:56 2007
@@ -10,7 +10,7 @@
 
         error = ValueError
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             try:
                 raise error
             except:
@@ -48,7 +48,7 @@
 
         error = ValueError
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -60,7 +60,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             try:
                 pass
             except:
@@ -687,7 +687,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ### Test to make Fredrik happy...

Modified: python/branches/p3yk-noslice/Tools/pybench/Imports.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Imports.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Imports.py	Wed Jul 11 15:40:56 2007
@@ -12,7 +12,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             import os
             import os
             import os
@@ -45,7 +45,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -57,7 +57,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             import package
             import package
             import package
@@ -90,7 +90,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SecondSubmoduleImport(Test):
@@ -101,7 +101,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             import package.submodule
             import package.submodule
             import package.submodule
@@ -134,5 +134,5 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Instances.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Instances.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Instances.py	Wed Jul 11 15:40:56 2007
@@ -26,7 +26,7 @@
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             o = c()
             o1 = c()
             o2 = c()
@@ -62,5 +62,5 @@
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Lists.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Lists.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Lists.py	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,7 @@
         l = []
         append = l.append
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             append(2)
             append(3)
@@ -127,7 +127,7 @@
         l = []
         append = l.append
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class ListSlicing(Test):
@@ -138,10 +138,10 @@
 
     def test(self):
 
-        n = range(100)
-        r = range(25)
+        n = list(range(100))
+        r = list(range(25))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             l = n[:]
 
@@ -160,7 +160,7 @@
         n = range(100)
         r = range(25)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for j in r:
                 pass
 
@@ -172,7 +172,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             l = []
 
@@ -291,5 +291,5 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Lookups.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Lookups.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Lookups.py	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,7 @@
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             c.__a = 2
             c.__b = 3
@@ -178,7 +178,7 @@
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class NormalClassAttribute(Test):
@@ -192,7 +192,7 @@
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             c.a = 2
             c.b = 3
@@ -364,7 +364,7 @@
         class c:
             pass
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class SpecialInstanceAttribute(Test):
@@ -379,7 +379,7 @@
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             o.__a__ = 2
             o.__b__ = 3
@@ -552,7 +552,7 @@
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class NormalInstanceAttribute(Test):
@@ -567,7 +567,7 @@
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             o.a = 2
             o.b = 3
@@ -740,7 +740,7 @@
             pass
         o = c()
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class BuiltinMethodLookup(Test):
@@ -754,7 +754,7 @@
         l = []
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             l.append
             l.append
@@ -941,5 +941,5 @@
         l = []
         d = {}
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/NewInstances.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/NewInstances.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/NewInstances.py	Wed Jul 11 15:40:56 2007
@@ -35,7 +35,7 @@
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             o = c()
             o1 = c()
             o2 = c()
@@ -71,5 +71,5 @@
                 self.e = b
                 self.f = c
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Numbers.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Numbers.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Numbers.py	Wed Jul 11 15:40:56 2007
@@ -8,7 +8,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             2 < 3
             2 > 3
@@ -192,7 +192,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -204,7 +204,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             2.1 < 3.31
             2.1 > 3.31
@@ -388,7 +388,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -400,7 +400,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             2.1 < 4
             2.1 > 4
@@ -584,7 +584,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -596,189 +596,189 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
-
-            1234567890L < 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L == 3456789012345L
-            1234567890L > 3456789012345L
-            1234567890L < 3456789012345L
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
+
+            1234567890 < 3456789012345
+            1234567890 > 3456789012345
+            1234567890 == 3456789012345
+            1234567890 > 3456789012345
+            1234567890 < 3456789012345
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Strings.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Strings.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Strings.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,4 @@
 from pybench import Test
-from string import join
 import sys
 
 class ConcatStrings(Test):
@@ -11,10 +10,10 @@
     def test(self):
 
         # Make sure the strings are *not* interned
-        s = join(map(str,range(100)))
-        t = join(map(str,range(1,101)))
+        s = ''.join(map(str,range(100)))
+        t = ''.join(map(str,range(1,101)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t + s
             t + s
             t + s
@@ -77,10 +76,10 @@
 
     def calibrate(self):
 
-        s = join(map(str,range(100)))
-        t = join(map(str,range(1,101)))
+        s = ''.join(map(str,range(100)))
+        t = ''.join(map(str,range(1,101)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -93,10 +92,10 @@
     def test(self):
 
         # Make sure the strings are *not* interned
-        s = join(map(str,range(10)))
-        t = join(map(str,range(10))) + "abc"
+        s = ''.join(map(str,range(10)))
+        t = ''.join(map(str,range(10))) + "abc"
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t < s
             t > s
             t == s
@@ -159,10 +158,10 @@
 
     def calibrate(self):
 
-        s = join(map(str,range(10)))
-        t = join(map(str,range(10))) + "abc"
+        s = ''.join(map(str,range(10)))
+        t = ''.join(map(str,range(10))) + "abc"
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -175,10 +174,10 @@
     def test(self):
 
         # Make sure the strings *are* interned
-        s = sys.intern(join(map(str,range(10))))
+        s = sys.intern(''.join(map(str,range(10))))
         t = s
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t == s
             t == s
             t >= s
@@ -241,10 +240,10 @@
 
     def calibrate(self):
 
-        s = sys.intern(join(map(str,range(10))))
+        s = sys.intern(''.join(map(str,range(10))))
         t = s
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -256,7 +255,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = 'om'
             s = s + 'xbx'
             s = s + 'xcx'
@@ -319,7 +318,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -331,9 +330,9 @@
 
     def test(self):
 
-        s = join(map(str,range(100)))
+        s = ''.join(map(str,range(100)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             s[50:]
             s[:25]
@@ -377,9 +376,9 @@
 
     def calibrate(self):
 
-        s = join(map(str,range(100)))
+        s = ''.join(map(str,range(100)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ### String methods
@@ -394,12 +393,12 @@
 
         def test(self):
 
-            s = join(map(chr,range(20)),'')
-            t = join(map(chr,range(50)),'')
-            u = join(map(chr,range(100)),'')
-            v = join(map(chr,range(256)),'')
+            s = ''.join(map(chr,range(20)))
+            t = ''.join(map(chr,range(50)))
+            u = ''.join(map(chr,range(100)))
+            v = ''.join(map(chr,range(256)))
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
 
                 s.lower()
                 s.lower()
@@ -451,12 +450,12 @@
 
         def calibrate(self):
 
-            s = join(map(chr,range(20)),'')
-            t = join(map(chr,range(50)),'')
-            u = join(map(chr,range(100)),'')
-            v = join(map(chr,range(256)),'')
+            s = ''.join(map(chr,range(20)))
+            t = ''.join(map(chr,range(50)))
+            u = ''.join(map(chr,range(100)))
+            v = ''.join(map(chr,range(256)))
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
                 pass
 
     class StringPredicates(Test):
@@ -470,7 +469,7 @@
             data = ('abc', '123', '   ', '\xe4\xf6\xfc', '\xdf'*10)
             len_data = len(data)
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
                 s = data[i % len_data]
 
                 s.isalnum()
@@ -559,5 +558,5 @@
             data = ('abc', '123', '   ', '\xe4\xf6\xfc', '\xdf'*10)
             len_data = len(data)
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
                 s = data[i % len_data]

Modified: python/branches/p3yk-noslice/Tools/pybench/Tuples.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Tuples.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Tuples.py	Wed Jul 11 15:40:56 2007
@@ -11,7 +11,7 @@
         r = range(25)
         t = tuple(range(100))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             for j in r:
 
@@ -260,7 +260,7 @@
         r = range(25)
         t = tuple(range(100))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             for j in r:
                 pass
 
@@ -272,7 +272,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             t = (1,2,3,4,5,6)
 
@@ -356,5 +356,5 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass

Modified: python/branches/p3yk-noslice/Tools/pybench/Unicode.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Unicode.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/Unicode.py	Wed Jul 11 15:40:56 2007
@@ -4,7 +4,6 @@
     raise ImportError
 
 from pybench import Test
-from string import join
 
 class ConcatUnicode(Test):
 
@@ -15,10 +14,10 @@
     def test(self):
 
         # Make sure the strings are *not* interned
-        s = unicode(join(map(str,range(100))))
-        t = unicode(join(map(str,range(1,101))))
+        s = unicode(u''.join(map(str,range(100))))
+        t = unicode(u''.join(map(str,range(1,101))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t + s
             t + s
             t + s
@@ -81,10 +80,10 @@
 
     def calibrate(self):
 
-        s = unicode(join(map(str,range(100))))
-        t = unicode(join(map(str,range(1,101))))
+        s = unicode(u''.join(map(str,range(100))))
+        t = unicode(u''.join(map(str,range(1,101))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -97,10 +96,10 @@
     def test(self):
 
         # Make sure the strings are *not* interned
-        s = unicode(join(map(str,range(10))))
-        t = unicode(join(map(str,range(10))) + "abc")
+        s = unicode(u''.join(map(str,range(10))))
+        t = unicode(u''.join(map(str,range(10))) + "abc")
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             t < s
             t > s
             t == s
@@ -163,10 +162,10 @@
 
     def calibrate(self):
 
-        s = unicode(join(map(str,range(10))))
-        t = unicode(join(map(str,range(10))) + "abc")
+        s = unicode(u''.join(map(str,range(10))))
+        t = unicode(u''.join(map(str,range(10))) + "abc")
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -178,7 +177,7 @@
 
     def test(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = u'om'
             s = s + u'xbx'
             s = s + u'xcx'
@@ -241,7 +240,7 @@
 
     def calibrate(self):
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 
@@ -253,9 +252,9 @@
 
     def test(self):
 
-        s = unicode(join(map(str,range(100))))
+        s = unicode(u''.join(map(str,range(100))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             s[50:]
             s[:25]
@@ -299,9 +298,9 @@
 
     def calibrate(self):
 
-        s = unicode(join(map(str,range(100))))
+        s = unicode(u''.join(map(str,range(100))))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 ### String methods
@@ -314,12 +313,12 @@
 
     def test(self):
 
-        s = join(map(unichr,range(20)),'')
-        t = join(map(unichr,range(100)),'')
-        u = join(map(unichr,range(500)),'')
-        v = join(map(unichr,range(1000)),'')
+        s = u''.join(map(unichr,range(20)))
+        t = u''.join(map(unichr,range(100)))
+        u = u''.join(map(unichr,range(500)))
+        v = u''.join(map(unichr,range(1000)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
 
             s.lower()
             s.lower()
@@ -371,12 +370,12 @@
 
     def calibrate(self):
 
-        s = join(map(unichr,range(20)),'')
-        t = join(map(unichr,range(100)),'')
-        u = join(map(unichr,range(500)),'')
-        v = join(map(unichr,range(1000)),'')
+        s = u''.join(map(unichr,range(20)))
+        t = u''.join(map(unichr,range(100)))
+        u = u''.join(map(unichr,range(500)))
+        v = u''.join(map(unichr,range(1000)))
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             pass
 
 class UnicodePredicates(Test):
@@ -390,7 +389,7 @@
         data = (u'abc', u'123', u'   ', u'\u1234\u2345\u3456', u'\uFFFF'*10)
         len_data = len(data)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = data[i % len_data]
 
             s.isalnum()
@@ -448,7 +447,7 @@
         data = (u'abc', u'123', u'   ', u'\u1234\u2345\u3456', u'\uFFFF'*10)
         len_data = len(data)
 
-        for i in xrange(self.rounds):
+        for i in range(self.rounds):
             s = data[i % len_data]
 
 try:
@@ -475,7 +474,7 @@
             mirrored = unicodedata.mirrored
             combining = unicodedata.combining
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
 
                 c = data[i % len_data]
 
@@ -537,6 +536,6 @@
             mirrored = unicodedata.mirrored
             combining = unicodedata.combining
 
-            for i in xrange(self.rounds):
+            for i in range(self.rounds):
 
                 c = data[i % len_data]

Modified: python/branches/p3yk-noslice/Tools/pybench/clockres.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/clockres.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/clockres.py	Wed Jul 11 15:40:56 2007
@@ -33,11 +33,11 @@
     return min_diff
 
 if __name__ == '__main__':
-    print 'Clock resolution of various timer implementations:'
-    print 'time.clock:           %10.3fus' % (clockres(time.clock) * 1e6)
-    print 'time.time:            %10.3fus' % (clockres(time.time) * 1e6)
+    print('Clock resolution of various timer implementations:')
+    print('time.clock:           %10.3fus' % (clockres(time.clock) * 1e6))
+    print('time.time:            %10.3fus' % (clockres(time.time) * 1e6))
     try:
         import systimes
-        print 'systimes.processtime: %10.3fus' % (clockres(systimes.processtime) * 1e6)
+        print('systimes.processtime: %10.3fus' % (clockres(systimes.processtime) * 1e6))
     except ImportError:
         pass

Modified: python/branches/p3yk-noslice/Tools/pybench/pybench.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/pybench.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/pybench.py	Wed Jul 11 15:40:56 2007
@@ -34,7 +34,7 @@
 WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
 """
 
-import sys, time, operator, string, platform
+import sys, time, operator, platform
 from CommandLine import *
 
 try:
@@ -103,7 +103,7 @@
 def get_machine_details():
 
     if _debug:
-        print 'Getting machine details...'
+        print('Getting machine details...')
     buildno, builddate = platform.python_build()
     python = platform.python_version()
     try:
@@ -146,7 +146,8 @@
                                           d.get('buildno', 'n/a')),
          '   Unicode:        %s' % d.get('unicode', 'n/a'),
          ]
-    print indent + string.join(l, '\n' + indent) + '\n'
+    joiner = '\n' + indent
+    print(indent + joiner.join(l) + '\n')
 
 ### Test baseclass
 
@@ -167,7 +168,7 @@
         call of .run().
 
         If you change a test in some way, don't forget to increase
-        it's version number.
+        its version number.
 
     """
 
@@ -280,9 +281,9 @@
             prep_times.append(t)
         min_prep_time = min(prep_times)
         if _debug:
-            print
-            print 'Calib. prep time     = %.6fms' % (
-                min_prep_time * MILLI_SECONDS)
+            print()
+            print('Calib. prep time     = %.6fms' % (
+                min_prep_time * MILLI_SECONDS))
 
         # Time the calibration runs (doing CALIBRATION_LOOPS loops of
         # .calibrate() method calls each)
@@ -298,8 +299,8 @@
         min_overhead = min(self.overhead_times)
         max_overhead = max(self.overhead_times)
         if _debug:
-            print 'Calib. overhead time = %.6fms' % (
-                min_overhead * MILLI_SECONDS)
+            print('Calib. overhead time = %.6fms' % (
+                min_overhead * MILLI_SECONDS))
         if min_overhead < 0.0:
             raise ValueError('calibration setup did not work')
         if max_overhead - min_overhead > 0.1:
@@ -436,7 +437,7 @@
         # Init vars
         self.tests = {}
         if _debug:
-            print 'Getting machine details...'
+            print('Getting machine details...')
         self.machine_details = get_machine_details()
 
         # Make .version an instance attribute to have it saved in the
@@ -473,8 +474,8 @@
 
         # Add tests
         if self.verbose:
-            print 'Searching for tests ...'
-            print '--------------------------------------'
+            print('Searching for tests ...')
+            print('--------------------------------------')
         for testclass in setupmod.__dict__.values():
             if not hasattr(testclass, 'is_a_test'):
                 continue
@@ -488,77 +489,74 @@
                 warp=self.warp,
                 calibration_runs=self.calibration_runs,
                 timer=self.timer)
-        l = self.tests.keys()
-        l.sort()
+        l = sorted(self.tests)
         if self.verbose:
             for name in l:
-                print '  %s' % name
-            print '--------------------------------------'
-            print '  %i tests found' % len(l)
-            print
+                print('  %s' % name)
+            print('--------------------------------------')
+            print('  %i tests found' % len(l))
+            print()
 
     def calibrate(self):
 
-        print 'Calibrating tests. Please wait...',
+        print('Calibrating tests. Please wait...', end=' ')
         if self.verbose:
-            print
-            print
-            print 'Test                              min      max'
-            print '-' * LINE
-        tests = self.tests.items()
-        tests.sort()
+            print()
+            print()
+            print('Test                              min      max')
+            print('-' * LINE)
+        tests = sorted(self.tests.items())
         for i in range(len(tests)):
             name, test = tests[i]
             test.calibrate_test()
             if self.verbose:
-                print '%30s:  %6.3fms  %6.3fms' % \
+                print('%30s:  %6.3fms  %6.3fms' % \
                       (name,
                        min(test.overhead_times) * MILLI_SECONDS,
-                       max(test.overhead_times) * MILLI_SECONDS)
+                       max(test.overhead_times) * MILLI_SECONDS))
         if self.verbose:
-            print
-            print 'Done with the calibration.'
+            print()
+            print('Done with the calibration.')
         else:
-            print 'done.'
-        print
+            print('done.')
+        print()
 
     def run(self):
 
-        tests = self.tests.items()
-        tests.sort()
+        tests = sorted(self.tests.items())
         timer = self.get_timer()
-        print 'Running %i round(s) of the suite at warp factor %i:' % \
-              (self.rounds, self.warp)
-        print
+        print('Running %i round(s) of the suite at warp factor %i:' % \
+              (self.rounds, self.warp))
+        print()
         self.roundtimes = []
         for i in range(self.rounds):
             if self.verbose:
-                print ' Round %-25i  effective   absolute  overhead' % (i+1)
+                print(' Round %-25i  effective   absolute  overhead' % (i+1))
             total_eff_time = 0.0
             for j in range(len(tests)):
                 name, test = tests[j]
                 if self.verbose:
-                    print '%30s:' % name,
+                    print('%30s:' % name, end=' ')
                 test.run()
                 (eff_time, abs_time, min_overhead) = test.last_timing
                 total_eff_time = total_eff_time + eff_time
                 if self.verbose:
-                    print '    %5.0fms    %5.0fms %7.3fms' % \
+                    print('    %5.0fms    %5.0fms %7.3fms' % \
                           (eff_time * MILLI_SECONDS,
                            abs_time * MILLI_SECONDS,
-                           min_overhead * MILLI_SECONDS)
+                           min_overhead * MILLI_SECONDS))
             self.roundtimes.append(total_eff_time)
             if self.verbose:
-                print ('                   '
-                       '               ------------------------------')
-                print ('                   '
+                print(('                   '
+                       '               ------------------------------'))
+                print(('                   '
                        '     Totals:    %6.0fms' %
-                       (total_eff_time * MILLI_SECONDS))
-                print
+                       (total_eff_time * MILLI_SECONDS)))
+                print()
             else:
-                print '* Round %i done in %.3f seconds.' % (i+1,
-                                                            total_eff_time)
-        print
+                print('* Round %i done in %.3f seconds.' % (i+1,
+                                                            total_eff_time))
+        print()
 
     def stat(self):
 
@@ -583,25 +581,24 @@
 
     def print_header(self, title='Benchmark'):
 
-        print '-' * LINE
-        print '%s: %s' % (title, self.name)
-        print '-' * LINE
-        print
-        print '    Rounds: %s' % self.rounds
-        print '    Warp:   %s' % self.warp
-        print '    Timer:  %s' % self.timer
-        print
+        print('-' * LINE)
+        print('%s: %s' % (title, self.name))
+        print('-' * LINE)
+        print()
+        print('    Rounds: %s' % self.rounds)
+        print('    Warp:   %s' % self.warp)
+        print('    Timer:  %s' % self.timer)
+        print()
         if self.machine_details:
             print_machine_details(self.machine_details, indent='    ')
-            print
+            print()
 
     def print_benchmark(self, hidenoise=0, limitnames=None):
 
-        print ('Test                          '
-               '   minimum  average  operation  overhead')
-        print '-' * LINE
-        tests = self.tests.items()
-        tests.sort()
+        print(('Test                          '
+               '   minimum  average  operation  overhead'))
+        print('-' * LINE)
+        tests = sorted(self.tests.items())
         total_min_time = 0.0
         total_avg_time = 0.0
         for name, test in tests:
@@ -615,43 +612,42 @@
              min_overhead) = test.stat()
             total_min_time = total_min_time + min_time
             total_avg_time = total_avg_time + avg_time
-            print '%30s:  %5.0fms  %5.0fms  %6.2fus  %7.3fms' % \
+            print('%30s:  %5.0fms  %5.0fms  %6.2fus  %7.3fms' % \
                   (name,
                    min_time * MILLI_SECONDS,
                    avg_time * MILLI_SECONDS,
                    op_avg * MICRO_SECONDS,
-                   min_overhead *MILLI_SECONDS)
-        print '-' * LINE
-        print ('Totals:                        '
+                   min_overhead *MILLI_SECONDS))
+        print('-' * LINE)
+        print(('Totals:                        '
                ' %6.0fms %6.0fms' %
                (total_min_time * MILLI_SECONDS,
                 total_avg_time * MILLI_SECONDS,
-                ))
-        print
+                )))
+        print()
 
     def print_comparison(self, compare_to, hidenoise=0, limitnames=None):
 
         # Check benchmark versions
         if compare_to.version != self.version:
-            print ('* Benchmark versions differ: '
+            print(('* Benchmark versions differ: '
                    'cannot compare this benchmark to "%s" !' %
-                   compare_to.name)
-            print
+                   compare_to.name))
+            print()
             self.print_benchmark(hidenoise=hidenoise,
                                  limitnames=limitnames)
             return
 
         # Print header
         compare_to.print_header('Comparing with')
-        print ('Test                          '
-               '   minimum run-time        average  run-time')
-        print ('                              '
-               '   this    other   diff    this    other   diff')
-        print '-' * LINE
+        print(('Test                          '
+               '   minimum run-time        average  run-time'))
+        print(('                              '
+               '   this    other   diff    this    other   diff'))
+        print('-' * LINE)
 
         # Print test comparisons
-        tests = self.tests.items()
-        tests.sort()
+        tests = sorted(self.tests.items())
         total_min_time = other_total_min_time = 0.0
         total_avg_time = other_total_avg_time = 0.0
         benchmarks_compatible = self.compatible(compare_to)
@@ -704,15 +700,15 @@
                     # Benchmark or tests are not comparible
                     min_diff, avg_diff = 'n/a', 'n/a'
                     tests_compatible = 0
-            print '%30s: %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' % \
+            print('%30s: %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' % \
                   (name,
                    min_time * MILLI_SECONDS,
                    other_min_time * MILLI_SECONDS * compare_to.warp / self.warp,
                    min_diff,
                    avg_time * MILLI_SECONDS,
                    other_avg_time * MILLI_SECONDS * compare_to.warp / self.warp,
-                   avg_diff)
-        print '-' * LINE
+                   avg_diff))
+        print('-' * LINE)
 
         # Summarise test results
         if not benchmarks_compatible or not tests_compatible:
@@ -730,7 +726,7 @@
                      (other_total_avg_time * compare_to.warp) - 1.0) * PERCENT)
             else:
                 avg_diff = 'n/a'
-        print ('Totals:                       '
+        print(('Totals:                       '
                '  %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' %
                (total_min_time * MILLI_SECONDS,
                 (other_total_min_time * compare_to.warp/self.warp
@@ -740,11 +736,11 @@
                 (other_total_avg_time * compare_to.warp/self.warp
                  * MILLI_SECONDS),
                 avg_diff
-               ))
-        print
-        print '(this=%s, other=%s)' % (self.name,
-                                       compare_to.name)
-        print
+               )))
+        print()
+        print('(this=%s, other=%s)' % (self.name,
+                                       compare_to.name))
+        print()
 
 class PyBenchCmdline(Application):
 
@@ -823,8 +819,8 @@
         limitnames = self.values['-t']
         if limitnames:
             if _debug:
-                print '* limiting test names to one with substring "%s"' % \
-                      limitnames
+                print('* limiting test names to one with substring "%s"' % \
+                      limitnames)
             limitnames = re.compile(limitnames, re.I)
         else:
             limitnames = None
@@ -833,26 +829,26 @@
         calibration_runs = self.values['-C']
         timer = self.values['--timer']
 
-        print '-' * LINE
-        print 'PYBENCH %s' % __version__
-        print '-' * LINE
-        print '* using %s %s' % (
+        print('-' * LINE)
+        print('PYBENCH %s' % __version__)
+        print('-' * LINE)
+        print('* using %s %s' % (
             platform.python_implementation(),
-            string.join(string.split(sys.version), ' '))
+            ' '.join(sys.version.split())))
 
         # Switch off garbage collection
         if not withgc:
             try:
                 import gc
             except ImportError:
-                print '* Python version doesn\'t support garbage collection'
+                print('* Python version doesn\'t support garbage collection')
             else:
                 try:
                     gc.disable()
                 except NotImplementedError:
-                    print '* Python version doesn\'t support gc.disable'
+                    print('* Python version doesn\'t support gc.disable')
                 else:
-                    print '* disabled garbage collection'
+                    print('* disabled garbage collection')
 
         # "Disable" sys check interval
         if not withsyscheck:
@@ -861,18 +857,18 @@
             try:
                 sys.setcheckinterval(value)
             except (AttributeError, NotImplementedError):
-                print '* Python version doesn\'t support sys.setcheckinterval'
+                print('* Python version doesn\'t support sys.setcheckinterval')
             else:
-                print '* system check interval set to maximum: %s' % value
+                print('* system check interval set to maximum: %s' % value)
 
         if timer == TIMER_SYSTIMES_PROCESSTIME:
             import systimes
-            print '* using timer: systimes.processtime (%s)' % \
-                  systimes.SYSTIMES_IMPLEMENTATION
+            print('* using timer: systimes.processtime (%s)' % \
+                  systimes.SYSTIMES_IMPLEMENTATION)
         else:
-            print '* using timer: %s' % timer
+            print('* using timer: %s' % timer)
 
-        print
+        print()
 
         if compare_to:
             try:
@@ -882,9 +878,9 @@
                 f.close()
                 compare_to = bench
             except IOError as reason:
-                print '* Error opening/reading file %s: %s' % (
+                print('* Error opening/reading file %s: %s' % (
                     repr(compare_to),
-                    reason)
+                    reason))
                 compare_to = None
 
         if show_bench:
@@ -902,16 +898,16 @@
                     bench.print_benchmark(hidenoise=hidenoise,
                                           limitnames=limitnames)
             except IOError as reason:
-                print '* Error opening/reading file %s: %s' % (
+                print('* Error opening/reading file %s: %s' % (
                     repr(show_bench),
-                    reason)
-                print
+                    reason))
+                print()
             return
 
         if reportfile:
-            print 'Creating benchmark: %s (rounds=%i, warp=%i)' % \
-                  (reportfile, rounds, warp)
-            print
+            print('Creating benchmark: %s (rounds=%i, warp=%i)' % \
+                  (reportfile, rounds, warp))
+            print()
 
         # Create benchmark object
         bench = Benchmark(reportfile,
@@ -925,9 +921,9 @@
             bench.calibrate()
             bench.run()
         except KeyboardInterrupt:
-            print
-            print '*** KeyboardInterrupt -- Aborting'
-            print
+            print()
+            print('*** KeyboardInterrupt -- Aborting')
+            print()
             return
         bench.print_header()
         if compare_to:
@@ -948,12 +944,12 @@
                 pickle.dump(bench,f)
                 f.close()
             except IOError as reason:
-                print '* Error opening/writing reportfile'
+                print('* Error opening/writing reportfile')
             except IOError as reason:
-                print '* Error opening/writing reportfile %s: %s' % (
+                print('* Error opening/writing reportfile %s: %s' % (
                     reportfile,
-                    reason)
-                print
+                    reason))
+                print()
 
 if __name__ == '__main__':
     PyBenchCmdline()

Modified: python/branches/p3yk-noslice/Tools/pybench/systimes.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/systimes.py	(original)
+++ python/branches/p3yk-noslice/Tools/pybench/systimes.py	Wed Jul 11 15:40:56 2007
@@ -180,32 +180,32 @@
 ### Testing
 
 def some_workload():
-    x = 0L
-    for i in xrange(10000000L):
-        x = x + 1L
+    x = 0
+    for i in range(10000000):
+        x = x + 1
 
 def test_workload():
-    print 'Testing systimes() under load conditions'
+    print('Testing systimes() under load conditions')
     t0 = systimes()
     some_workload()
     t1 = systimes()
-    print 'before:', t0
-    print 'after:', t1
-    print 'differences:', (t1[0] - t0[0], t1[1] - t0[1])
-    print
+    print('before:', t0)
+    print('after:', t1)
+    print('differences:', (t1[0] - t0[0], t1[1] - t0[1]))
+    print()
 
 def test_idle():
-    print 'Testing systimes() under idle conditions'
+    print('Testing systimes() under idle conditions')
     t0 = systimes()
     time.sleep(1)
     t1 = systimes()
-    print 'before:', t0
-    print 'after:', t1
-    print 'differences:', (t1[0] - t0[0], t1[1] - t0[1])
-    print
+    print('before:', t0)
+    print('after:', t1)
+    print('differences:', (t1[0] - t0[0], t1[1] - t0[1]))
+    print()
 
 if __name__ == '__main__':
-    print 'Using %s as timer' % SYSTIMES_IMPLEMENTATION
-    print
+    print('Using %s as timer' % SYSTIMES_IMPLEMENTATION)
+    print()
     test_workload()
     test_idle()

Modified: python/branches/p3yk-noslice/Tools/scripts/classfix.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/classfix.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/classfix.py	Wed Jul 11 15:40:56 2007
@@ -129,7 +129,7 @@
     # First copy the file's mode to the temp file
     try:
         statbuf = os.stat(filename)
-        os.chmod(tempname, statbuf[ST_MODE] & 07777)
+        os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
     except os.error as msg:
         err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
     # Then make a backup of the original file as filename~

Modified: python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/cleanfuture.py	Wed Jul 11 15:40:56 2007
@@ -162,7 +162,7 @@
         OP = tokenize.OP
 
         changed = self.changed
-        get = tokenize.generate_tokens(self.getline).next
+        get = tokenize.generate_tokens(self.getline).__next__
         type, token, (srow, scol), (erow, ecol), line = get()
 
         # Chew up initial comments and blank lines (if any).

Modified: python/branches/p3yk-noslice/Tools/scripts/fixcid.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/fixcid.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/fixcid.py	Wed Jul 11 15:40:56 2007
@@ -174,7 +174,7 @@
     # First copy the file's mode to the temp file
     try:
         statbuf = os.stat(filename)
-        os.chmod(tempname, statbuf[ST_MODE] & 07777)
+        os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
     except os.error as msg:
         err(tempname + ': warning: chmod failed (' + str(msg) + ')\n')
     # Then make a backup of the original file as filename~

Modified: python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/ftpmirror.py	Wed Jul 11 15:40:56 2007
@@ -375,7 +375,7 @@
         return
     dirname = os.path.dirname(pathname)
     if dirname: makedir(dirname)
-    os.mkdir(pathname, 0777)
+    os.mkdir(pathname, 0o777)
 
 # Write a dictionary to a file in a way that can be read back using
 # rval() but is still somewhat readable (i.e. not a single long line).

Modified: python/branches/p3yk-noslice/Tools/scripts/linktree.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/linktree.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/linktree.py	Wed Jul 11 15:40:56 2007
@@ -31,7 +31,7 @@
         print oldtree + ': not a directory'
         return 1
     try:
-        os.mkdir(newtree, 0777)
+        os.mkdir(newtree, 0o777)
     except os.error as msg:
         print newtree + ': cannot mkdir:', msg
         return 1
@@ -63,7 +63,7 @@
             if os.path.isdir(oldname) and \
                not os.path.islink(oldname):
                 try:
-                    os.mkdir(newname, 0777)
+                    os.mkdir(newname, 0o777)
                     ok = 1
                 except:
                     print newname + \

Modified: python/branches/p3yk-noslice/Tools/scripts/methfix.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/methfix.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/methfix.py	Wed Jul 11 15:40:56 2007
@@ -140,7 +140,7 @@
     # First copy the file's mode to the temp file
     try:
         statbuf = os.stat(filename)
-        os.chmod(tempname, statbuf[ST_MODE] & 07777)
+        os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
     except os.error as msg:
         err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
     # Then make a backup of the original file as filename~

Modified: python/branches/p3yk-noslice/Tools/scripts/pathfix.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/pathfix.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/pathfix.py	Wed Jul 11 15:40:56 2007
@@ -121,7 +121,7 @@
     # First copy the file's mode to the temp file
     try:
         statbuf = os.stat(filename)
-        os.chmod(tempname, statbuf[ST_MODE] & 07777)
+        os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
     except os.error as msg:
         err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
     # Then make a backup of the original file as filename~

Modified: python/branches/p3yk-noslice/Tools/scripts/reindent.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/reindent.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/reindent.py	Wed Jul 11 15:40:56 2007
@@ -45,8 +45,8 @@
 
 def usage(msg=None):
     if msg is not None:
-        print >> sys.stderr, msg
-    print >> sys.stderr, __doc__
+        print(msg, file=sys.stderr)
+    print(__doc__, file=sys.stderr)
 
 def errprint(*args):
     sep = ""
@@ -85,7 +85,7 @@
 def check(file):
     if os.path.isdir(file) and not os.path.islink(file):
         if verbose:
-            print "listing directory", file
+            print("listing directory", file)
         names = os.listdir(file)
         for name in names:
             fullname = os.path.join(file, name)
@@ -96,7 +96,7 @@
         return
 
     if verbose:
-        print "checking", file, "...",
+        print("checking", file, "...", end=' ')
     try:
         f = open(file)
     except IOError as msg:
@@ -107,24 +107,24 @@
     f.close()
     if r.run():
         if verbose:
-            print "changed."
+            print("changed.")
             if dryrun:
-                print "But this is a dry run, so leaving it alone."
+                print("But this is a dry run, so leaving it alone.")
         if not dryrun:
             bak = file + ".bak"
             if os.path.exists(bak):
                 os.remove(bak)
             os.rename(file, bak)
             if verbose:
-                print "renamed", file, "to", bak
+                print("renamed", file, "to", bak)
             f = open(file, "w")
             r.write(f)
             f.close()
             if verbose:
-                print "wrote new", file
+                print("wrote new", file)
     else:
         if verbose:
-            print "unchanged."
+            print("unchanged.")
 
 def _rstrip(line, JUNK='\n \t'):
     """Return line stripped of trailing spaces, tabs, newlines.
@@ -193,7 +193,7 @@
                     want = have2want.get(have, -1)
                     if want < 0:
                         # Then it probably belongs to the next real stmt.
-                        for j in xrange(i+1, len(stats)-1):
+                        for j in range(i+1, len(stats)-1):
                             jline, jlevel = stats[j]
                             if jlevel >= 0:
                                 if have == getlspace(lines[jline]):
@@ -203,7 +203,7 @@
                                            # comment like this one,
                         # in which case we should shift it like its base
                         # line got shifted.
-                        for j in xrange(i-1, -1, -1):
+                        for j in range(i-1, -1, -1):
                             jline, jlevel = stats[j]
                             if jlevel >= 0:
                                 want = have + getlspace(after[jline-1]) - \
@@ -244,7 +244,7 @@
         return line
 
     # Line-eater for tokenize.
-    def tokeneater(self, type, token, (sline, scol), end, line,
+    def tokeneater(self, type, token, slinecol, end, line,
                    INDENT=tokenize.INDENT,
                    DEDENT=tokenize.DEDENT,
                    NEWLINE=tokenize.NEWLINE,
@@ -267,7 +267,7 @@
 
         elif type == COMMENT:
             if self.find_stmt:
-                self.stats.append((sline, -1))
+                self.stats.append((slinecol[0], -1))
                 # but we're still looking for a new stmt, so leave
                 # find_stmt alone
 
@@ -280,7 +280,7 @@
             # ENDMARKER.
             self.find_stmt = 0
             if line:   # not endmarker
-                self.stats.append((sline, self.level))
+                self.stats.append((slinecol[0], self.level))
 
 # Count number of leading blanks.
 def getlspace(line):

Modified: python/branches/p3yk-noslice/Tools/scripts/which.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/scripts/which.py	(original)
+++ python/branches/p3yk-noslice/Tools/scripts/which.py	Wed Jul 11 15:40:56 2007
@@ -35,7 +35,7 @@
                 msg(filename + ': not a disk file')
             else:
                 mode = S_IMODE(st[ST_MODE])
-                if mode & 0111:
+                if mode & 0o111:
                     if not ident:
                         print filename
                         ident = st[:3]

Modified: python/branches/p3yk-noslice/Tools/unicode/makeunicodedata.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/unicode/makeunicodedata.py	(original)
+++ python/branches/p3yk-noslice/Tools/unicode/makeunicodedata.py	Wed Jul 11 15:40:56 2007
@@ -757,7 +757,7 @@
     h = 0
     for c in map(ord, s.upper()):
         h = (h * magic) + c
-        ix = h & 0xff000000L
+        ix = h & 0xff000000
         if ix:
             h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff
     return h
@@ -935,7 +935,7 @@
     if __debug__:
         # exhaustively verify that the decomposition is correct
         mask = ~((~0) << shift) # i.e., low-bit mask of shift bits
-        for i in xrange(len(t)):
+        for i in range(len(t)):
             assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)]
     return best
 

Modified: python/branches/p3yk-noslice/Tools/unicode/mkstringprep.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/unicode/mkstringprep.py	(original)
+++ python/branches/p3yk-noslice/Tools/unicode/mkstringprep.py	Wed Jul 11 15:40:56 2007
@@ -37,7 +37,7 @@
         tuple.append((prev,prev+span+1))
     else:
         single.append(prev)
-    tuple = " + ".join(["range(%d,%d)" % t for t in tuple])
+    tuple = " + ".join(["list(range(%d,%d))" % t for t in tuple])
     if not single:
         return "set(%s)" % tuple
     if not tuple:

Modified: python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py	(original)
+++ python/branches/p3yk-noslice/Tools/versioncheck/pyversioncheck.py	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,4 @@
 """pyversioncheck - Module to help with checking versions"""
-import types
 import rfc822
 import urllib
 import sys
@@ -35,7 +34,7 @@
 def checkonly(package, url, version, verbose=0):
     if verbose >= VERBOSE_EACHFILE:
         print '%s:'%package
-    if type(url) == types.StringType:
+    if isinstance(url, str):
         ok, newversion, fp = _check1version(package, url, version, verbose)
     else:
         for u in url:

Modified: python/branches/p3yk-noslice/Tools/webchecker/websucker.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/webchecker/websucker.py	(original)
+++ python/branches/p3yk-noslice/Tools/webchecker/websucker.py	Wed Jul 11 15:40:56 2007
@@ -119,7 +119,7 @@
         print "Huh?  Don't know how to make dir", dir
         return
     makedirs(head)
-    os.mkdir(dir, 0777)
+    os.mkdir(dir, 0o777)
 
 if __name__ == '__main__':
     sys.exit(main() or 0)

Modified: python/branches/p3yk-noslice/configure
==============================================================================
--- python/branches/p3yk-noslice/configure	(original)
+++ python/branches/p3yk-noslice/configure	Wed Jul 11 15:40:56 2007
@@ -1,5 +1,5 @@
 #! /bin/sh
-# From configure.in Revision: 53610 .
+# From configure.in Revision: 54283 .
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.61 for python 3.0.
 #
@@ -3753,7 +3753,7 @@
 
 # Check for unsupported systems
 case $ac_sys_system/$ac_sys_release in
-Linux*/1*)
+atheos*|Linux*/1*)
    echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported.
    echo See README for details.
    exit 1;;

Modified: python/branches/p3yk-noslice/configure.in
==============================================================================
--- python/branches/p3yk-noslice/configure.in	(original)
+++ python/branches/p3yk-noslice/configure.in	Wed Jul 11 15:40:56 2007
@@ -450,7 +450,7 @@
 
 # Check for unsupported systems
 case $ac_sys_system/$ac_sys_release in
-Linux*/1*)
+atheos*|Linux*/1*)
    echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported.
    echo See README for details.
    exit 1;;
@@ -1571,9 +1571,11 @@
 then
 	case $ac_sys_system/$ac_sys_release in
 	SunOS*) if test "$GCC" = yes;
-	        then CCSHARED="-fPIC";
-		else CCSHARED="-xcode=pic32";
-	        fi;;
+		then CCSHARED="-fPIC";
+		elif test `uname -p` = sparc;
+		then CCSHARED="-xcode=pic32";
+		else CCSHARED="-Kpic";
+		fi;;
 	hp*|HP*) if test "$GCC" = yes;
 		 then CCSHARED="-fPIC";
 		 else CCSHARED="+z";

Modified: python/branches/p3yk-noslice/setup.py
==============================================================================
--- python/branches/p3yk-noslice/setup.py	(original)
+++ python/branches/p3yk-noslice/setup.py	Wed Jul 11 15:40:56 2007
@@ -91,10 +91,14 @@
 
 class PyBuildExt(build_ext):
 
+    def __init__(self, dist):
+        build_ext.__init__(self, dist)
+        self.failed = []
+
     def build_extensions(self):
 
         # Detect which modules should be compiled
-        self.detect_modules()
+        missing = self.detect_modules()
 
         # Remove modules that are present on the disabled list
         self.extensions = [ext for ext in self.extensions
@@ -178,6 +182,31 @@
 
         build_ext.build_extensions(self)
 
+        longest = max([len(e.name) for e in self.extensions])
+        if self.failed:
+            longest = max(longest, max([len(name) for name in self.failed]))
+
+        def print_three_column(lst):
+            lst.sort(key=str.lower)
+            # guarantee zip() doesn't drop anything
+            while len(lst) % 3:
+                lst.append("")
+            for e, f, g in zip(lst[::3], lst[1::3], lst[2::3]):
+                print("%-*s   %-*s   %-*s" % (longest, e, longest, f,
+                                              longest, g))
+            print()
+
+        if missing:
+            print()
+            print("Failed to find the necessary bits to build these modules:")
+            print_three_column(missing)
+
+        if self.failed:
+            failed = self.failed[:]
+            print()
+            print("Failed to build these modules:")
+            print_three_column(failed)
+
     def build_extension(self, ext):
 
         if ext.name == '_ctypes':
@@ -189,6 +218,7 @@
         except (CCompilerError, DistutilsError) as why:
             self.announce('WARNING: building of extension "%s" failed: %s' %
                           (ext.name, sys.exc_info()[1]))
+            self.failed.append(ext.name)
             return
         # Workaround for Mac OS X: The Carbon-based modules cannot be
         # reliably imported into a command-line Python
@@ -209,6 +239,7 @@
         try:
             imp.load_dynamic(ext.name, ext_filename)
         except ImportError as why:
+            self.failed.append(ext.name)
             self.announce('*** WARNING: renaming "%s" since importing it'
                           ' failed: %s' % (ext.name, why), level=3)
             assert not self.inplace
@@ -234,6 +265,7 @@
             self.announce('*** WARNING: importing extension "%s" '
                           'failed with %s: %s' % (ext.name, exc_type, why),
                           level=3)
+            self.failed.append(ext.name)
 
     def get_platform(self):
         # Get value of sys.platform
@@ -299,6 +331,7 @@
             ]
         inc_dirs = self.compiler.include_dirs + ['/usr/include']
         exts = []
+        missing = []
 
         config_h = sysconfig.get_config_h_filename()
         config_h_vars = sysconfig.parse_config_h(open(config_h))
@@ -358,8 +391,6 @@
         # math library functions, e.g. sin()
         exts.append( Extension('math',  ['mathmodule.c'],
                                libraries=math_libs) )
-        # fast string operations implemented in C
-        exts.append( Extension('strop', ['stropmodule.c']) )
         # time operations and variables
         exts.append( Extension('time', ['timemodule.c'],
                                libraries=math_libs) )
@@ -370,7 +401,7 @@
         # fast iterator tools implemented in C
         exts.append( Extension("itertools", ["itertoolsmodule.c"]) )
         # high-performance collections
-        exts.append( Extension("collections", ["collectionsmodule.c"]) )
+        exts.append( Extension("_collections", ["_collectionsmodule.c"]) )
         # bisect
         exts.append( Extension("_bisect", ["_bisectmodule.c"]) )
         # heapq
@@ -379,6 +410,8 @@
         exts.append( Extension('operator', ['operator.c']) )
         # _functools
         exts.append( Extension("_functools", ["_functoolsmodule.c"]) )
+        # atexit
+        exts.append( Extension("atexit", ["atexitmodule.c"]) )
         # Python C API test module
         exts.append( Extension('_testcapi', ['_testcapimodule.c']) )
         # profilers (_lsprof is for cProfile.py)
@@ -387,6 +420,8 @@
         # static Unicode character database
         if have_unicode:
             exts.append( Extension('unicodedata', ['unicodedata.c']) )
+        else:
+            missing.append('unicodedata')
         # access to ISO C locale support
         data = open('pyconfig.h').read()
         m = re.search(r"#s*define\s+WITH_LIBINTL\s+1\s*", data)
@@ -419,6 +454,11 @@
             if (config_h_vars.get('HAVE_GETSPNAM', False) or
                     config_h_vars.get('HAVE_GETSPENT', False)):
                 exts.append( Extension('spwd', ['spwdmodule.c']) )
+            else:
+                missing.append('spwd')
+        else:
+            missing.extend(['pwd', 'grp', 'spwd'])
+
         # select(2); not on ancient System V
         exts.append( Extension('select', ['selectmodule.c']) )
 
@@ -435,16 +475,15 @@
         # Memory-mapped files (also works on Win32).
         if platform not in ['atheos', 'mac']:
             exts.append( Extension('mmap', ['mmapmodule.c']) )
+        else:
+            missing.append('mmap')
 
         # Lance Ellinghaus's syslog module
         if platform not in ['mac']:
             # syslog daemon interface
             exts.append( Extension('syslog', ['syslogmodule.c']) )
-
-        # George Neville-Neil's timing module:
-        # Deprecated in PEP 4 http://www.python.org/peps/pep-0004.html
-        # http://mail.python.org/pipermail/python-dev/2006-January/060023.html
-        #exts.append( Extension('timing', ['timingmodule.c']) )
+        else:
+            missing.append('syslog')
 
         #
         # Here ends the simple stuff.  From here on, modules need certain
@@ -460,13 +499,6 @@
         # 64-bit platforms.
         exts.append( Extension('audioop', ['audioop.c']) )
 
-        # Disabled on 64-bit platforms
-        if sys.maxint != 9223372036854775807:
-            # Operations on images
-            exts.append( Extension('imageop', ['imageop.c']) )
-            # Read SGI RGB image files (but coded portably)
-            exts.append( Extension('rgbimg', ['rgbimgmodule.c']) )
-
         # readline
         do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
         if platform == 'darwin':
@@ -503,6 +535,9 @@
                                    library_dirs=['/usr/lib/termcap'],
                                    extra_link_args=readline_extra_link_args,
                                    libraries=readline_libs) )
+        else:
+            missing.append('readline')
+
         if platform not in ['mac']:
             # crypt module.
 
@@ -511,6 +546,8 @@
             else:
                 libs = []
             exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
+        else:
+            missing.append('crypt')
 
         # CSV files
         exts.append( Extension('_csv', ['_csv.c']) )
@@ -543,6 +580,8 @@
                                    library_dirs = ssl_libs,
                                    libraries = ['ssl', 'crypto'],
                                    depends = ['socketmodule.h']), )
+        else:
+            missing.append('_ssl')
 
         # find out which version of OpenSSL we have
         openssl_ver = 0
@@ -577,20 +616,14 @@
                                    library_dirs = ssl_libs,
                                    libraries = ['ssl', 'crypto']) )
         else:
-            # The _sha module implements the SHA1 hash algorithm.
-            exts.append( Extension('_sha', ['shamodule.c']) )
-            # The _md5 module implements the RSA Data Security, Inc. MD5
-            # Message-Digest Algorithm, described in RFC 1321.  The
-            # necessary files md5.c and md5.h are included here.
-            exts.append( Extension('_md5',
-                            sources = ['md5module.c', 'md5.c'],
-                            depends = ['md5.h']) )
+            missing.append('_hashlib')
 
         if (openssl_ver < 0x00908000):
             # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
             exts.append( Extension('_sha256', ['sha256module.c']) )
             exts.append( Extension('_sha512', ['sha512module.c']) )
-
+        else:
+            missing.extend(['_sha256', '_sha512'])
 
         # Modules that provide persistent dictionary-like semantics.  You will
         # probably want to arrange for at least one of them to be available on
@@ -616,10 +649,11 @@
             '/usr/include/db4',
             '/usr/local/include/db4',
             '/opt/sfw/include/db4',
-            '/sw/include/db4',
             '/usr/include/db3',
             '/usr/local/include/db3',
             '/opt/sfw/include/db3',
+            # Fink defaults (http://fink.sourceforge.net/)
+            '/sw/include/db4',
             '/sw/include/db3',
         ]
         # 4.x minor number specific paths
@@ -630,6 +664,8 @@
             db_inc_paths.append('/usr/local/include/db4%d' % x)
             db_inc_paths.append('/pkg/db-4.%d/include' % x)
             db_inc_paths.append('/opt/db-4.%d/include' % x)
+            # 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,):
             db_inc_paths.append('/usr/include/db3%d' % x)
@@ -654,7 +690,7 @@
                 std_variants.append(os.path.join(dn, "db3.%d"%x))
 
         db_inc_paths = std_variants + db_inc_paths
-
+        db_inc_paths = [p for p in db_inc_paths if os.path.exists(p)]
 
         db_ver_inc_map = {}
 
@@ -677,7 +713,7 @@
                         if ( (db_ver not in db_ver_inc_map) and
                            (db_ver <= max_db_ver and db_ver >= min_db_ver) ):
                             # save the include directory with the db.h version
-                            # (first occurrance only)
+                            # (first occurrence only)
                             db_ver_inc_map[db_ver] = d
                             if db_setup_debug:
                                 print("db.h: found", db_ver, "in", d)
@@ -686,7 +722,8 @@
                             if db_setup_debug: print("db.h: ignoring", d)
                     else:
                         # ignore this header, it didn't contain a version number
-                        if db_setup_debug: print("db.h: unsupported version", db_ver, "in", d)
+                        if db_setup_debug:
+                            print("db.h: no version number version in", d)
 
             db_found_vers = sorted(db_ver_inc_map.keys())
 
@@ -696,12 +733,10 @@
 
                 # check lib directories parallel to the location of the header
                 db_dirs_to_check = [
-                    os.path.join(db_incdir, '..', 'lib64'),
-                    os.path.join(db_incdir, '..', 'lib'),
-                    os.path.join(db_incdir, '..', '..', 'lib64'),
-                    os.path.join(db_incdir, '..', '..', 'lib'),
+                    db_incdir.replace("include", 'lib64'),
+                    db_incdir.replace("include", 'lib'),
                 ]
-                db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
+                db_dirs_to_check = [x for x in db_dirs_to_check if os.path.isdir(x)]
 
                 # Look for a version specific db-X.Y before an ambiguoius dbX
                 # XXX should we -ever- look for a dbX name?  Do any
@@ -740,6 +775,7 @@
             db_incs = None
             dblibs = []
             dblib_dir = None
+            missing.append('_bsddb')
 
         # The sqlite interface
         sqlite_setup_debug = False   # verbose debug prints from this script?
@@ -832,28 +868,8 @@
                                   runtime_library_dirs=sqlite_libdir,
                                   extra_link_args=sqlite_extra_link_args,
                                   libraries=["sqlite3",]))
-
-        # Look for Berkeley db 1.85.   Note that it is built as a different
-        # module name so it can be included even when later versions are
-        # available.  A very restrictive search is performed to avoid
-        # accidentally building this module with a later version of the
-        # underlying db library.  May BSD-ish Unixes incorporate db 1.85
-        # symbols into libc and place the include file in /usr/include.
-        f = "/usr/include/db.h"
-        if os.path.exists(f):
-            data = open(f).read()
-            m = re.search(r"#s*define\s+HASHVERSION\s+2\s*", data)
-            if m is not None:
-                # bingo - old version used hash file format version 2
-                ### XXX this should be fixed to not be platform-dependent
-                ### but I don't have direct access to an osf1 platform and
-                ### seemed to be muffing the search somehow
-                libraries = platform == "osf1" and ['db'] or None
-                if libraries is not None:
-                    exts.append(Extension('bsddb185', ['bsddbmodule.c'],
-                                          libraries=libraries))
-                else:
-                    exts.append(Extension('bsddb185', ['bsddbmodule.c']))
+        else:
+            missing.append('_sqlite3')
 
         # The standard Unix dbm module:
         if platform not in ['cygwin']:
@@ -879,11 +895,15 @@
                                        define_macros=[('HAVE_BERKDB_H',None),
                                                       ('DB_DBM_HSEARCH',None)],
                                        libraries=dblibs))
+            else:
+                missing.append('dbm')
 
         # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
         if (self.compiler.find_library_file(lib_dirs, 'gdbm')):
             exts.append( Extension('gdbm', ['gdbmmodule.c'],
                                    libraries = ['gdbm'] ) )
+        else:
+            missing.append('gdbm')
 
         # Unix-only modules
         if platform not in ['mac', 'win32']:
@@ -892,6 +912,8 @@
             # Jeremy Hylton's rlimit interface
             if platform not in ['atheos']:
                 exts.append( Extension('resource', ['resource.c']) )
+            else:
+                missing.append('resource')
 
             # Sun yellow pages. Some systems have the functions in libc.
             if platform not in ['cygwin', 'atheos']:
@@ -901,6 +923,10 @@
                     libs = []
                 exts.append( Extension('nis', ['nismodule.c'],
                                        libraries = libs) )
+            else:
+                missing.append('nis')
+        else:
+            missing.extend(['nis', 'resource', 'termios'])
 
         # Curses support, requiring the System V version of curses, often
         # provided by the ncurses library.
@@ -929,13 +955,16 @@
 
             exts.append( Extension('_curses', ['_cursesmodule.c'],
                                    libraries = curses_libs) )
+        else:
+            missing.append('_curses')
 
         # If the curses module is enabled, check for the panel module
         if (module_enabled(exts, '_curses') and
             self.compiler.find_library_file(lib_dirs, panel_library)):
             exts.append( Extension('_curses_panel', ['_curses_panel.c'],
                                    libraries = [panel_library] + curses_libs) )
-
+        else:
+            missing.append('_curses_panel')
 
         # Andrew Kuchling's zlib module.  Note that some versions of zlib
         # 1.1.3 have security problems.  See CERT Advisory CA-2002-07:
@@ -971,6 +1000,12 @@
                     exts.append( Extension('zlib', ['zlibmodule.c'],
                                            libraries = ['z'],
                                            extra_link_args = zlib_extra_link_args))
+                else:
+                    missing.append('zlib')
+            else:
+                missing.append('zlib')
+        else:
+            missing.append('zlib')
 
         # Gustavo Niemeyer's bz2 module.
         if (self.compiler.find_library_file(lib_dirs, 'bz2')):
@@ -981,6 +1016,8 @@
             exts.append( Extension('bz2', ['bz2module.c'],
                                    libraries = ['bz2'],
                                    extra_link_args = bz2_extra_link_args) )
+        else:
+            missing.append('bz2')
 
         # Interface to the Expat XML parser
         #
@@ -1018,14 +1055,20 @@
                                   include_dirs = [expatinc],
                                   sources = ['_elementtree.c'],
                                   ))
+        else:
+            missing.append('_elementtree')
 
         # Hye-Shik Chang's CJKCodecs modules.
         if have_unicode:
             exts.append(Extension('_multibytecodec',
                                   ['cjkcodecs/multibytecodec.c']))
             for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
-                exts.append(Extension('_codecs_' + loc,
+                exts.append(Extension('_codecs_%s' % loc,
                                       ['cjkcodecs/_codecs_%s.c' % loc]))
+        else:
+            missing.append('_multibytecodec')
+            for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
+                missing.append('_codecs_%s' % loc)
 
         # Dynamic loading module
         if sys.maxint == 0x7fffffff:
@@ -1033,22 +1076,35 @@
             dl_inc = find_file('dlfcn.h', [], inc_dirs)
             if (dl_inc is not None) and (platform not in ['atheos']):
                 exts.append( Extension('dl', ['dlmodule.c']) )
+            else:
+                missing.append('dl')
+        else:
+            missing.append('dl')
 
         # Thomas Heller's _ctypes module
         self.detect_ctypes(inc_dirs, lib_dirs)
 
+        # _fileio -- supposedly cross platform
+        exts.append(Extension('_fileio', ['_fileio.c']))
+
         # Platform-specific libraries
         if platform == 'linux2':
             # Linux-specific modules
             exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
+        else:
+            missing.append('linuxaudiodev')
 
         if platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
                         'freebsd7'):
             exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
+        else:
+            missing.append('ossaudiodev')
 
         if platform == 'sunos5':
             # SunOS specific modules
             exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
+        else:
+            missing.append('sunaudiodev')
 
         if platform == 'darwin' and ("--disable-toolbox-glue" not in
                 sysconfig.get_config_var("CONFIG_ARGS")):
@@ -1137,6 +1193,11 @@
         # Call the method for detecting whether _tkinter can be compiled
         self.detect_tkinter(inc_dirs, lib_dirs)
 
+        if '_tkinter' not in [e.name for e in self.extensions]:
+            missing.append('_tkinter')
+
+        return missing
+
     def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
         # The _tkinter module, using frameworks. Since frameworks are quite
         # different the UNIX search logic is not sharable.
@@ -1170,8 +1231,8 @@
         #
         include_dirs = [
             join(F, fw + '.framework', H)
-            for fw in 'Tcl', 'Tk'
-            for H in 'Headers', 'Versions/Current/PrivateHeaders'
+            for fw in ('Tcl', 'Tk')
+            for H in ('Headers', 'Versions/Current/PrivateHeaders')
         ]
 
         # For 8.4a2, the X11 headers are not included. Rather than include a
@@ -1438,8 +1499,8 @@
 
     def install(self):
         outfiles = install_lib.install(self)
-        self.set_file_modes(outfiles, 0644, 0755)
-        self.set_dir_modes(self.install_dir, 0755)
+        self.set_file_modes(outfiles, 0o644, 0o755)
+        self.set_dir_modes(self.install_dir, 0o755)
         return outfiles
 
     def set_file_modes(self, files, defaultMode, sharedLibMode):
@@ -1507,7 +1568,7 @@
           description = "A high-level object-oriented programming language",
           long_description = SUMMARY.strip(),
           license = "PSF license",
-          classifiers = filter(None, CLASSIFIERS.split("\n")),
+          classifiers = [x for x in CLASSIFIERS.split("\n") if x],
           platforms = ["Many"],
 
           # Build info


More information about the Python-3000-checkins mailing list